@Override public void enterPattern_matcher(SQLParser.Pattern_matcherContext ctx) { super.enterPattern_matcher(ctx); for (int i = 0; i < ctx.getChildCount(); i++) { ParseTree child = ctx.getChild(i); if (child instanceof TerminalNodeImpl) { if (isNot(child.getText())) { currentPredicate.negate(); } break; } } if (currentPredicate.isNegated()) { currentPredicate.setOperator("not like"); } else { currentPredicate.setOperator("like"); } skipNextTerminal = true; }
/** * Cloning expression to create new same expression. */ public static ExprContext cloneExprContext(final ExprContext expr) { final ExprContext clone = createContextType(expr); clone.copyFrom(expr); for (final ParseTree child : expr.children) { if (child instanceof TerminalNode) { clone.addChild(new TerminalNodeImpl(((TerminalNode) child).getSymbol())); } else if (child instanceof ExprContext) { final ExprContext cloneChild = cloneExprContext((ExprContext) child); clone.addChild(cloneChild); setLeftRight(clone, cloneChild); } else if (child instanceof Token) { clone.addChild(new CommonToken((Token) child)); } } return clone; }
/** * Creating conjunction expression. */ public static ConjunctionContext createConjunctionContext(final ExprContext leftContext, final ExprContext rightContext) { final ConjunctionContext conjunctionContext = new ConjunctionContext(new ExprContext()); final TerminalNodeImpl andNode = new TerminalNodeImpl(new CommonToken(10, "and")); // Setting context parents. leftContext.parent = conjunctionContext; andNode.parent = conjunctionContext; rightContext.parent = conjunctionContext; conjunctionContext.left = leftContext; conjunctionContext.right = rightContext; // Adding conjunction expression's children. conjunctionContext.addChild(leftContext); conjunctionContext.addChild(andNode); conjunctionContext.addChild(rightContext); return conjunctionContext; }
/** * Creating disjunction expression. */ public static DisjunctionContext createDisjunctionContext(final ExprContext leftContext, final ExprContext rightContext) { final DisjunctionContext disjunctionContext = new DisjunctionContext(new ExprContext()); final TerminalNodeImpl orNode = new TerminalNodeImpl(new CommonToken(12, "or")); // Setting context parents. leftContext.parent = disjunctionContext; rightContext.parent = disjunctionContext; orNode.parent = disjunctionContext; disjunctionContext.left = leftContext; disjunctionContext.right = rightContext; // Adding disjunction expression's children. disjunctionContext.addChild(leftContext); disjunctionContext.addChild(orNode); disjunctionContext.addChild(rightContext); return disjunctionContext; }
/** * Creating negation expression. */ public static NegationContext createNegationContext(final ExprContext expr) { final NegationContext negationContext = new NegationContext(new ExprContext()); final TerminalNodeImpl notNode = new TerminalNodeImpl(new CommonToken(FOLParser.NOT, "not")); // Setting context parents. notNode.parent = negationContext; expr.parent = negationContext; // Adding negation expression's children. negationContext.addChild(notNode); negationContext.addChild(expr); return negationContext; }
/** * Creating parentheses expression. */ public static ParenthesesContext createParenthesesContext(final ExprContext expr) { final ParenthesesContext parenthesesContext = new ParenthesesContext(new ExprContext()); final TerminalNodeImpl leftParenthes = new TerminalNodeImpl(new CommonToken(FOLParser.LP, "(")); final TerminalNodeImpl rightParenthes = new TerminalNodeImpl(new CommonToken(FOLParser.RP, ")")); // Setting context parents. leftParenthes.parent = parenthesesContext; rightParenthes.parent = parenthesesContext; expr.parent = parenthesesContext; // Adding parentheses expression's children. parenthesesContext.addChild(leftParenthes); parenthesesContext.addChild(expr); parenthesesContext.addChild(rightParenthes); return parenthesesContext; }
/** * Searches the children of the given context for a context of the given clazz * type and returns its Text Value. If there are multiple relevant child nodes, * we will return the text value for one of them at random. */ public String getChildContextText(RuleContext ctx) { if (ctx == null) { return ""; } if (ctx instanceof TypeNameContext) { return ctx.getText(); } String s = ""; for (int i = 0; i < ctx.getChildCount(); i++) { if (!(ctx.getChild(i) instanceof TerminalNodeImpl)) { try { String t = getChildContextText((RuleContext) ctx.getChild(i)); if (!t.isEmpty()) { s += t + ","; } } catch (Exception e) { // do nothing } } } return s.replaceAll(",$", ""); }
@Test public void testCheckEndingWIthSemicolon2() { Rule r = new Rule(); RuleImplementation rImpl = new RuleImplementation(); rImpl.getNames().getTextItem().add(Select_statementContext.class.getSimpleName()); rImpl.setRuleMatchType(RuleMatchType.CLASS_ONLY); r.setRuleImplementation(rImpl); RuleImplementation child = new RuleImplementation(); child.setDistance(1); child.setIndex(-1); child.setDistanceCheckType(RuleDistanceIndexMatchType.EQUALS); child.setIndexCheckType(RuleDistanceIndexMatchType.EQUALS); child.getTextToFind().getTextItem().add(";"); child.setTextCheckType(TextCheckType.STRICT); child.setRuleMatchType(RuleMatchType.CLASS_ONLY); child.setRuleResultType(RuleResultType.FAIL_IF_NOT_FOUND); child.getNames().getTextItem().add(TerminalNodeImpl.class.getSimpleName()); rImpl.getChildrenRules().getRuleImplementation().add(child); String s = "SELECT * from dbo.test where name like '%test%'"; TsqlIssue[] issues = Antlr4Utils.verify2(r, s); Assert.assertEquals(1, issues.length); }
public static TypeRef fromAntlrNode(Java8Parser.UnannArrayTypeContext antlrNode) { if (antlrNode.unannPrimitiveType() != null){ long nDims = antlrNode.dims().children.stream().filter((c)->c instanceof TerminalNodeImpl).map((c) -> (TerminalNodeImpl)c) .filter((c)->c.getText().equals("[")).count(); // TODO consider annotations // TODO consider multiple dimensions if (antlrNode.dims().annotation() != null && !antlrNode.dims().annotation().isEmpty()){ throw new UnsupportedOperationException(); } return fromAntlrNode(PrimitiveTypeRef.fromAntlrNode(antlrNode.unannPrimitiveType()), nDims); } else { throw new UnsupportedOperationException(); } }
public static TypeRef fromAntlrNode(Java8Parser.ArrayTypeContext antlrNode) { if (antlrNode.primitiveType() != null){ long nDims = antlrNode.dims().children.stream().filter((c)->c instanceof TerminalNodeImpl).map((c) -> (TerminalNodeImpl)c) .filter((c)->c.getText().equals("[")).count(); // TODO consider annotations // TODO consider multiple dimensions if (antlrNode.dims().annotation() != null && !antlrNode.dims().annotation().isEmpty()){ throw new UnsupportedOperationException(); } return fromAntlrNode(PrimitiveTypeRef.fromAntlrNode(antlrNode.primitiveType()), nDims); } else { throw new UnsupportedOperationException(); } }
private void verifyInitializerBraceStyle(SwiftParser.InitializerDeclarationContext ctx) { // Check if there is an element between the parameter clause and open brace (i.e. 'throws' or 'rethrows') // (Issue #405) ParseTree leftSibling = ParseTreeUtil.getLeftSibling(ctx.initializerBody()); if (leftSibling instanceof TerminalNodeImpl) { verifyCodeBlockOpenBraceStyle( ctx.initializerBody().codeBlock(), ((TerminalNodeImpl) leftSibling).getSymbol(), Messages.INITIALIZER_BODY); } else { verifyCodeBlockOpenBraceStyle(ctx.initializerBody().codeBlock(), ctx.parameterClause().getStop(), Messages.INITIALIZER_BODY); } verifyBodyCloseBraceStyle(ctx.initializerBody().codeBlock(), Messages.INITIALIZER_BODY); }
private void verifyEnumBraceStyle(ParserRuleContext ctx) { for (ParseTree child : ctx.children) { if (child instanceof TerminalNodeImpl && child.getText().equals("{")) { Token openBrace = ((TerminalNodeImpl) child).getSymbol(); Location openBraceLocation = ListenerUtil.getTokenLocation(openBrace); ParserRuleContext leftSibling = (ParserRuleContext) ParseTreeUtil.getLeftSibling(child); Location leftSiblingLocation = ListenerUtil.getContextStopLocation(leftSibling); if (openBraceLocation.line != leftSiblingLocation.line) { printer.warn(Rules.BRACE_STYLE, Messages.ENUM + Messages.OPEN_BRACE_STYLE, openBraceLocation); } else if (checkLeftSpaces(leftSibling.getStop(), openBrace, 1)) { printer.error(Rules.BRACE_STYLE, Messages.OPEN_BRACE + Messages.SPACE_BEFORE, openBraceLocation); } break; } } ParseTree lastChild = ParseTreeUtil.getLastChild(ctx); verifyCloseBraceStyle(lastChild, ParseTreeUtil.getLeftSibling(lastChild), Messages.ENUM); }
private void verifyCloseBraceStyle(ParseTree closeBrace, ParseTree closeBraceLeftSibling, String constructName) { Token closeBraceToken = ((TerminalNodeImpl)closeBrace).getSymbol(); Location closeBraceLocation = ListenerUtil.getTokenLocation(closeBraceToken); if (commentLeftOfCloseBrace(closeBraceToken)) { this.printer.warn(Rules.BRACE_STYLE, constructName + Messages.CLOSE_BRACE_STYLE, closeBraceLocation); return; } Location closeBraceLeftSiblingLocation = ListenerUtil.getParseTreeStopLocation(closeBraceLeftSibling); if (closeBraceLocation.line == closeBraceLeftSiblingLocation.line) { if (!closeBraceLeftSibling.getText().equals("{")) { this.printer.warn(Rules.BRACE_STYLE, constructName + Messages.CLOSE_BRACE_STYLE, closeBraceLocation); } else if (closeBraceLocation.column - closeBraceLeftSiblingLocation.column != 1) { this.printer.warn(Rules.BRACE_STYLE, Messages.EMPTY_BODY, closeBraceLeftSiblingLocation); } } }
private void verifyClosureCloseBraceStyle(SwiftParser.ClosureExpressionContext ctx) { ParseTree closeBrace = ParseTreeUtil.getLastChild(ctx); Token closeBraceToken = ((TerminalNodeImpl) closeBrace).getSymbol(); Location closeBraceLocation = ListenerUtil.getTokenLocation(closeBraceToken); Location openBraceLocation = ListenerUtil.getLocationOfChildToken(ctx, 0); if (openBraceLocation.line != closeBraceLocation.line && commentLeftOfCloseBrace(closeBraceToken)) { this.printer.warn(Rules.BRACE_STYLE, Messages.CLOSURE + Messages.CLOSE_BRACE_STYLE, closeBraceLocation); return; } Location leftSiblingLocation = ListenerUtil.getParseTreeStopLocation(ParseTreeUtil.getLeftSibling(closeBrace)); if (leftSiblingLocation.line == closeBraceLocation.line && openBraceLocation.line != closeBraceLocation.line) { this.printer.warn(Rules.BRACE_STYLE, Messages.CLOSURE + Messages.CLOSE_BRACE_STYLE, closeBraceLocation); } }
/** * Remove the separator (,) between arguments. * * @param file Source file to edit. * @param context ExpressionList context. * @param index Parameter index of the argument ("a", "b") "a" = 0, "b" = 1 */ private void removeCallSeparator(SourceFile file, ExpressionListContext context, int index) { ParseTree item = null; // Remove separator after argument. if (index == 0 && context.getChildCount() >= index + 1) { item = context.getChild(index + 1); } else if (context.getChildCount() >= index - 1) { item = context.getChild(index - 1); } if (item instanceof TerminalNodeImpl && item.getText().equals(",")) { file.getRewriter().delete(((TerminalNodeImpl)item).getPayload()); } }
@Override public void enterIn_predicate(SQLParser.In_predicateContext ctx) { super.enterIn_predicate(ctx); enterInClause(); for (int i = 0; i < ctx.getChildCount(); i++) { ParseTree child = ctx.getChild(i); if (child instanceof TerminalNodeImpl) { if (isNot(child.getText())) { currentPredicate.negate(); } break; } } currentPredicate.inOperator(); }
@Override public void enterNull_predicate(SQLParser.Null_predicateContext ctx) { super.enterNull_predicate(ctx); enterNullClause(); for (int i = 0; i < ctx.getChildCount(); i++) { ParseTree child = ctx.getChild(i); if (child instanceof TerminalNodeImpl) { if (isNot(child.getText())) { currentPredicate.negate(); } } } currentPredicate.nullOperator(); }
private boolean checkWhereStatement(@NotNull QueryParser.WhereStatementContext ctx) { if ( ctx != null && ctx.getChildCount() > 1) { //visit predicate Result result = visit(ctx.predicate()); //check if not in front predicate if ( ctx.getChild(1) instanceof TerminalNodeImpl ) return ! (Boolean) result.getValue() ; else return (Boolean) result.getValue() ; } else return true; }
private static RuleContext createColumnName_(Expr_functionContext rule, OutputField field) { Column_name_Context column_name_ = new Column_name_Context(rule.getParent(), rule.invokingState); Column_nameContext column_name = new Column_nameContext(column_name_.getParent(), rule.invokingState); IdentifierContext identifier = new IdentifierContext(column_name, rule.invokingState); CommonToken token = CommonTokenFactory.DEFAULT.create( MysqlParser.BACKTICK_QUOTED_IDENTIFIER, '`' + field.name + '`' ); TerminalNode term = new TerminalNodeImpl(token); identifier.addChild(term); column_name.addChild(identifier); column_name_.addChild(column_name); return column_name_; }
@Test public void testCheckEndingWithSemicolon() { Rule r = new Rule(); r.setKey("Example1"); r.setInternalKey("Example1"); r.setDescription("Select statement should end with semicolon"); r.setName("Select statement should end with semicolon"); RuleImplementation rImpl = new RuleImplementation(); rImpl.getNames().getTextItem().add(Select_statementContext.class.getSimpleName()); rImpl.setRuleMatchType(RuleMatchType.CLASS_ONLY); r.setRuleImplementation(rImpl); RuleImplementation child = new RuleImplementation(); child.setDistance(1); child.setIndex(-1); child.setDistanceCheckType(RuleDistanceIndexMatchType.EQUALS); child.setIndexCheckType(RuleDistanceIndexMatchType.EQUALS); child.getTextToFind().getTextItem().add(";"); child.setTextCheckType(TextCheckType.STRICT); child.setRuleMatchType(RuleMatchType.TEXT_AND_CLASS); child.setRuleResultType(RuleResultType.FAIL_IF_NOT_FOUND); child.getNames().getTextItem().add(TerminalNodeImpl.class.getSimpleName()); rImpl.getChildrenRules().getRuleImplementation().add(child); rImpl.getCompliantRulesCodeExamples().getRuleCodeExample().add("SELECT * from dbo.test where name like '%test%';"); rImpl.getViolatingRulesCodeExamples().getRuleCodeExample().add("SELECT * from dbo.test where name like '%test%'"); String s = "SELECT * from dbo.test where name like '%test%';"; //System.out.println(Antlr4Utils.ruleImplToString(r)); TsqlIssue[] issues = Antlr4Utils.verify2(r, s); //TsqlIssue[] issues = Antlr4Utils.verifyWithPrinting(r, s); Assert.assertEquals(0, issues.length); // Antlr4Utils.print(Antlr4Utils.get("SELECT * from dbo.test;"), 0); }
public static void fixParenthesized(ExprContext ctx){ PredicateContext pred = new PredicateContext(ctx, 0); PrednameContext functor = new PrednameContext(pred, 0); ParenthesizedContext paren = (ParenthesizedContext)ctx.getChild(0); functor.children = new ArrayList<ParseTree>(); pred.children = new ArrayList<ParseTree>(); functor.children.add(new TerminalNodeImpl(new CommonToken(0,""))); // Nameless functor pred.children.add(functor); pred.children.add(paren); ctx.children.set(0, pred); }
/** * Returns the starting token of the construct represented by node. * * @param node A node * @return Start token */ public static Token getStartTokenForNode(ParseTree node) { if (node instanceof TerminalNodeImpl) { return ((TerminalNodeImpl) node).getSymbol(); } else { return ((ParserRuleContext) node).getStart(); } }
/** * Returns the last token of the construct represented by node. * * @param node A node * @return Stop token */ public static Token getStopTokenForNode(ParseTree node) { if (node instanceof TerminalNodeImpl) { return ((TerminalNodeImpl) node).getSymbol(); } else { return ((ParserRuleContext) node).getStop(); } }
@Override public void enterTypeInheritanceClause(SwiftParser.TypeInheritanceClauseContext ctx) { if (ctx.classRequirement() != null && ctx.typeInheritanceList() != null) { Token left = ParseTreeUtil.getStopTokenForNode(ctx.classRequirement()); Token right = ParseTreeUtil.getStartTokenForNode(ctx.typeInheritanceList()); Token comma = ((TerminalNodeImpl) ctx.getChild(2)).getSymbol(); verifyCommaLeftAssociation(left, right, comma); } if (ctx.typeInheritanceList() != null) { checkWhitespaceAroundCommaSeparatedList(ctx.typeInheritanceList()); } }
@Override public void enterDictionaryLiteralItem(SwiftParser.DictionaryLiteralItemContext ctx) { Token left = ctx.expression(0).getStop(); Token right = ctx.expression(1).getStart(); Token colon = ((TerminalNodeImpl) ctx.getChild(1)).getSymbol(); verifyColonLeftAssociation(left, right, colon); }
@Override public void enterTypeAnnotation(SwiftParser.TypeAnnotationContext ctx) { TerminalNodeImpl colon = (TerminalNodeImpl) ctx.getChild(0); ParseTree parentLeftSibling = ParseTreeUtil.getLeftSibling(colon.getParent()); ParseTree rightSibling = ctx.getChild(1); Token left = ParseTreeUtil.getStopTokenForNode(parentLeftSibling); Token right = ParseTreeUtil.getStartTokenForNode(rightSibling); Token colonToken = colon.getSymbol(); verifyColonLeftAssociation(left, right, colonToken); }
@Override public void enterDictionaryType(SwiftParser.DictionaryTypeContext ctx) { Token left = ctx.sType(0).getStop(); Token right = ctx.sType(1).getStart(); Token colon = ((TerminalNodeImpl) ctx.getChild(2)).getSymbol(); verifyColonLeftAssociation(left, right, colon); }
@Override public void enterTypeInheritanceClause(SwiftParser.TypeInheritanceClauseContext ctx) { Token colon = ((TerminalNodeImpl) ctx.getChild(0)).getSymbol(); Token right = ((ParserRuleContext) ctx.getChild(1)).getStart(); Token left = ((ParserRuleContext) ParseTreeUtil.getLeftSibling(ctx)).getStop(); verifyColonLeftAssociation(left, right, colon); }
@Override public void enterConditionalOperator(SwiftParser.ConditionalOperatorContext ctx) { Token colon = ((TerminalNodeImpl) ctx.getChild(ctx.getChildCount() - 1)).getSymbol(); Token left = ctx.expression().getStop(); Token right = ((ParserRuleContext) ParseTreeUtil.getRightSibling(ctx)).getStart(); verifyColonIsSpaceDelimited(left, right, colon); }
@Override public void enterTupleElement(SwiftParser.TupleElementContext ctx) { if (ctx.identifier() != null) { Token colon = ((TerminalNodeImpl) ctx.getChild(1)).getSymbol(); Token left = ctx.identifier().getStop(); if (ctx.expression() != null) { Token right = ctx.expression().getStart(); verifyColonLeftAssociation(left, right, colon); } else { verifier.verifyPunctuationLeftAssociation(left, colon, Messages.COLON); } } }
@Override public void enterFunctionCallArgument(SwiftParser.FunctionCallArgumentContext ctx) { if (ctx.functionCallIdentifier() != null) { Token colon = ((TerminalNodeImpl) ctx.getChild(1)).getSymbol(); Token left = ctx.functionCallIdentifier().getStop(); if (ctx.expression() == null && ctx.operator() == null) { verifier.verifyPunctuationLeftAssociation(left, colon, Messages.COLON); return; } ParserRuleContext rightCtx = ctx.expression() == null ? ctx.operator() : ctx.expression(); Token right = rightCtx.getStart(); verifyColonLeftAssociation(left, right, colon); } }
@Override public void enterGenericParameter(SwiftParser.GenericParameterContext ctx) { if (ctx.getChildCount() == 3) { Token colon = ((TerminalNodeImpl) ctx.getChild(1)).getSymbol(); Token left = ctx.typeName().getStop(); Token right = ((ParserRuleContext) ctx.getChild(2)).getStart(); verifyColonLeftAssociation(left, right, colon); } }
@Override public void enterArgumentName(SwiftParser.ArgumentNameContext ctx) { Token colon = ((TerminalNodeImpl) ctx.getChild(1)).getSymbol(); Token left = ctx.identifier() == null ? ((TerminalNodeImpl) ctx.getChild(0)).getSymbol() : ctx.identifier().getStop(); verifier.verifyPunctuationLeftAssociation(left, colon, Messages.COLON); }
@Override public void enterFunctionType(SwiftParser.FunctionTypeContext ctx) { Optional<ParseTree> arrowOptional = ctx.children.stream() .filter(node -> node.getText().equals("->")) .findFirst(); if (!arrowOptional.isPresent()) { return; } ParseTree arrow = arrowOptional.get(); Token left = ParseTreeUtil.getStopTokenForNode(ParseTreeUtil.getLeftSibling(arrow)); Token right = ParseTreeUtil.getStartTokenForNode(ParseTreeUtil.getRightSibling(arrow)); verifyArrowIsSpaceDelimited(left, right, ((TerminalNodeImpl) arrow).getSymbol()); }
private void checkWhitespaceAroundReturnArrow(ParserRuleContext ctx) { Token arrow = ((TerminalNodeImpl) ctx.getChild(0)).getSymbol(); Token left = ParseTreeUtil.getStopTokenForNode(ParseTreeUtil.getLeftSibling(ctx)); Token right = ParseTreeUtil.getStartTokenForNode(ctx.getChild(1)); verifyArrowIsSpaceDelimited(left, right, arrow); }