Java Examples for org.antlr.v4.runtime.ParserRuleContext

The following java examples will help you to understand the usage of org.antlr.v4.runtime.ParserRuleContext. These source code samples are taken from different open source projects.

Example 1
Project: antlr4-master  File: ParserATNSimulator.java View source code
public int adaptivePredict(TokenStream input, int decision, ParserRuleContext outerContext) {
    if (debug || debug_list_atn_decisions) {
        System.out.println("adaptivePredict decision " + decision + " exec LA(1)==" + getLookaheadName(input) + " line " + input.LT(1).getLine() + ":" + input.LT(1).getCharPositionInLine());
    }
    _input = input;
    _startIndex = input.index();
    _outerContext = outerContext;
    DFA dfa = decisionToDFA[decision];
    _dfa = dfa;
    int m = input.mark();
    int index = _startIndex;
    // But, do we still need an initial state?
    try {
        DFAState s0;
        if (dfa.isPrecedenceDfa()) {
            // the start state for a precedence DFA depends on the current
            // parser precedence, and is provided by a DFA method.
            s0 = dfa.getPrecedenceStartState(parser.getPrecedence());
        } else {
            // the start state for a "regular" DFA is just s0
            s0 = dfa.s0;
        }
        if (s0 == null) {
            if (outerContext == null)
                outerContext = ParserRuleContext.EMPTY;
            if (debug || debug_list_atn_decisions) {
                System.out.println("predictATN decision " + dfa.decision + " exec LA(1)==" + getLookaheadName(input) + ", outerContext=" + outerContext.toString(parser));
            }
            boolean fullCtx = false;
            ATNConfigSet s0_closure = computeStartState(dfa.atnStartState, ParserRuleContext.EMPTY, fullCtx);
            if (dfa.isPrecedenceDfa()) {
                /* If this is a precedence DFA, we use applyPrecedenceFilter
					 * to convert the computed start state to a precedence start
					 * state. We then use DFA.setPrecedenceStartState to set the
					 * appropriate start state for the precedence level rather
					 * than simply setting DFA.s0.
					 */
                // not used for prediction but useful to know start configs anyway
                dfa.s0.configs = s0_closure;
                s0_closure = applyPrecedenceFilter(s0_closure);
                s0 = addDFAState(dfa, new DFAState(s0_closure));
                dfa.setPrecedenceStartState(parser.getPrecedence(), s0);
            } else {
                s0 = addDFAState(dfa, new DFAState(s0_closure));
                dfa.s0 = s0;
            }
        }
        int alt = execATN(dfa, s0, input, index, outerContext);
        if (debug)
            System.out.println("DFA after predictATN: " + dfa.toString(parser.getVocabulary()));
        return alt;
    } finally {
        // wack cache after each prediction
        mergeCache = null;
        _dfa = null;
        input.seek(index);
        input.release(m);
    }
}
Example 2
Project: joern-master  File: ModuleParser.java View source code
private Postfix_expressionContext postfix_expression(int _p) throws RecognitionException {
    ParserRuleContext _parentctx = _ctx;
    int _parentState = getState();
    Postfix_expressionContext _localctx = new Postfix_expressionContext(_ctx, _parentState);
    Postfix_expressionContext _prevctx = _localctx;
    int _startState = 50;
    enterRecursionRule(_localctx, 50, RULE_postfix_expression, _p);
    int _la;
    try {
        int _alt;
        enterOuterAlt(_localctx, 1);
        {
            {
                _localctx = new PrimaryOnlyContext(_localctx);
                _ctx = _localctx;
                _prevctx = _localctx;
                setState(341);
                primary_expression();
            }
            _ctx.stop = _input.LT(-1);
            setState(369);
            _errHandler.sync(this);
            _alt = getInterpreter().adaptivePredict(_input, 28, _ctx);
            while (_alt != 2 && _alt != -1) {
                if (_alt == 1) {
                    if (_parseListeners != null)
                        triggerExitRuleEvent();
                    _prevctx = _localctx;
                    {
                        setState(367);
                        switch(getInterpreter().adaptivePredict(_input, 27, _ctx)) {
                            case 1:
                                {
                                    _localctx = new ArrayIndexingContext(new Postfix_expressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_postfix_expression);
                                    setState(343);
                                    if (!(precpred(_ctx, 6)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 6)");
                                    setState(344);
                                    match(3);
                                    setState(345);
                                    expr();
                                    setState(346);
                                    match(22);
                                }
                                break;
                            case 2:
                                {
                                    _localctx = new FuncCallContext(new Postfix_expressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_postfix_expression);
                                    setState(348);
                                    if (!(precpred(_ctx, 5)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 5)");
                                    setState(349);
                                    match(30);
                                    setState(350);
                                    function_argument_list();
                                    setState(351);
                                    match(12);
                                }
                                break;
                            case 3:
                                {
                                    _localctx = new MemberAccessContext(new Postfix_expressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_postfix_expression);
                                    setState(353);
                                    if (!(precpred(_ctx, 4)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 4)");
                                    setState(354);
                                    match(44);
                                    setState(356);
                                    _la = _input.LA(1);
                                    if (_la == TEMPLATE) {
                                        {
                                            setState(355);
                                            match(TEMPLATE);
                                        }
                                    }
                                    {
                                        setState(358);
                                        identifier();
                                    }
                                }
                                break;
                            case 4:
                                {
                                    _localctx = new PtrMemberAccessContext(new Postfix_expressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_postfix_expression);
                                    setState(359);
                                    if (!(precpred(_ctx, 3)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 3)");
                                    setState(360);
                                    match(9);
                                    setState(362);
                                    _la = _input.LA(1);
                                    if (_la == TEMPLATE) {
                                        {
                                            setState(361);
                                            match(TEMPLATE);
                                        }
                                    }
                                    {
                                        setState(364);
                                        identifier();
                                    }
                                }
                                break;
                            case 5:
                                {
                                    _localctx = new IncDecOpContext(new Postfix_expressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_postfix_expression);
                                    setState(365);
                                    if (!(precpred(_ctx, 2)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 2)");
                                    setState(366);
                                    inc_dec();
                                }
                                break;
                        }
                    }
                }
                setState(371);
                _errHandler.sync(this);
                _alt = getInterpreter().adaptivePredict(_input, 28, _ctx);
            }
        }
    } catch (RecognitionException re) {
        _localctx.exception = re;
        _errHandler.reportError(this, re);
        _errHandler.recover(this, re);
    } finally {
        unrollRecursionContexts(_parentctx);
    }
    return _localctx;
}
Example 3
Project: poly-ql-master  File: QuestionnaireParser.java View source code
private ExprContext expr(int _p) throws RecognitionException {
    ParserRuleContext _parentctx = _ctx;
    int _parentState = getState();
    ExprContext _localctx = new ExprContext(_ctx, _parentState);
    ExprContext _prevctx = _localctx;
    int _startState = 8;
    enterRecursionRule(_localctx, 8, RULE_expr, _p);
    int _la;
    try {
        int _alt;
        enterOuterAlt(_localctx, 1);
        {
            setState(76);
            switch(_input.LA(1)) {
                case NOT:
                    {
                        _localctx = new NotContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(66);
                        match(NOT);
                        setState(67);
                        expr(8);
                    }
                    break;
                case 5:
                    {
                        _localctx = new ParenthesisContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(68);
                        match(5);
                        setState(69);
                        expr(0);
                        setState(70);
                        match(3);
                    }
                    break;
                case BOOLEAN:
                    {
                        _localctx = new BooleanContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(72);
                        match(BOOLEAN);
                    }
                    break;
                case INT:
                    {
                        _localctx = new IntegerContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(73);
                        match(INT);
                    }
                    break;
                case STRING:
                    {
                        _localctx = new StringContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(74);
                        match(STRING);
                    }
                    break;
                case ID:
                    {
                        _localctx = new IdContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(75);
                        match(ID);
                    }
                    break;
                default:
                    throw new NoViableAltException(this);
            }
            _ctx.stop = _input.LT(-1);
            setState(95);
            _errHandler.sync(this);
            _alt = getInterpreter().adaptivePredict(_input, 8, _ctx);
            while (_alt != 2 && _alt != -1) {
                if (_alt == 1) {
                    if (_parseListeners != null) {
                        triggerExitRuleEvent();
                    }
                    _prevctx = _localctx;
                    {
                        setState(93);
                        switch(getInterpreter().adaptivePredict(_input, 7, _ctx)) {
                            case 1:
                                {
                                    _localctx = new MulDivContext(new ExprContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_expr);
                                    setState(78);
                                    if (!(precpred(_ctx, 11))) {
                                        throw new FailedPredicateException(this, "precpred(_ctx, 11)");
                                    }
                                    setState(79);
                                    _la = _input.LA(1);
                                    if (!(_la == MUL || _la == DIV)) {
                                        _errHandler.recoverInline(this);
                                    }
                                    consume();
                                    setState(80);
                                    expr(12);
                                }
                                break;
                            case 2:
                                {
                                    _localctx = new AddSubContext(new ExprContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_expr);
                                    setState(81);
                                    if (!(precpred(_ctx, 10))) {
                                        throw new FailedPredicateException(this, "precpred(_ctx, 10)");
                                    }
                                    setState(82);
                                    _la = _input.LA(1);
                                    if (!(_la == ADD || _la == SUB)) {
                                        _errHandler.recoverInline(this);
                                    }
                                    consume();
                                    setState(83);
                                    expr(11);
                                }
                                break;
                            case 3:
                                {
                                    _localctx = new CompareContext(new ExprContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_expr);
                                    setState(84);
                                    if (!(precpred(_ctx, 9))) {
                                        throw new FailedPredicateException(this, "precpred(_ctx, 9)");
                                    }
                                    setState(85);
                                    _la = _input.LA(1);
                                    if (!((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << LT) | (1L << LEq) | (1L << GT) | (1L << GEq) | (1L << Eq) | (1L << NEq))) != 0))) {
                                        _errHandler.recoverInline(this);
                                    }
                                    consume();
                                    setState(86);
                                    expr(10);
                                }
                                break;
                            case 4:
                                {
                                    _localctx = new AndContext(new ExprContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_expr);
                                    setState(87);
                                    if (!(precpred(_ctx, 7))) {
                                        throw new FailedPredicateException(this, "precpred(_ctx, 7)");
                                    }
                                    {
                                        setState(88);
                                        match(AND);
                                    }
                                    setState(89);
                                    expr(8);
                                }
                                break;
                            case 5:
                                {
                                    _localctx = new OrContext(new ExprContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_expr);
                                    setState(90);
                                    if (!(precpred(_ctx, 6))) {
                                        throw new FailedPredicateException(this, "precpred(_ctx, 6)");
                                    }
                                    {
                                        setState(91);
                                        match(OR);
                                    }
                                    setState(92);
                                    expr(7);
                                }
                                break;
                        }
                    }
                }
                setState(97);
                _errHandler.sync(this);
                _alt = getInterpreter().adaptivePredict(_input, 8, _ctx);
            }
        }
    } catch (RecognitionException re) {
        _localctx.exception = re;
        _errHandler.reportError(this, re);
        _errHandler.recover(this, re);
    } finally {
        unrollRecursionContexts(_parentctx);
    }
    return _localctx;
}
Example 4
Project: Scratch-ApuC-master  File: ParserATNSimulator.java View source code
public int adaptivePredict(@NotNull TokenStream input, int decision, @Nullable ParserRuleContext outerContext) {
    if (debug || debug_list_atn_decisions) {
        System.out.println("adaptivePredict decision " + decision + " exec LA(1)==" + getLookaheadName(input) + " line " + input.LT(1).getLine() + ":" + input.LT(1).getCharPositionInLine());
    }
    _input = input;
    _startIndex = input.index();
    _outerContext = outerContext;
    DFA dfa = decisionToDFA[decision];
    int m = input.mark();
    int index = _startIndex;
    // But, do we still need an initial state?
    try {
        DFAState s0;
        if (dfa.isPrecedenceDfa()) {
            // the start state for a precedence DFA depends on the current
            // parser precedence, and is provided by a DFA method.
            s0 = dfa.getPrecedenceStartState(parser.getPrecedence());
        } else {
            // the start state for a "regular" DFA is just s0
            s0 = dfa.s0;
        }
        if (s0 == null) {
            if (outerContext == null)
                outerContext = ParserRuleContext.EMPTY;
            if (debug || debug_list_atn_decisions) {
                System.out.println("predictATN decision " + dfa.decision + " exec LA(1)==" + getLookaheadName(input) + ", outerContext=" + outerContext.toString(parser));
            }
            /* If this is not a precedence DFA, we check the ATN start state
				 * to determine if this ATN start state is the decision for the
				 * closure block that determines whether a precedence rule
				 * should continue or complete.
				 */
            if (!dfa.isPrecedenceDfa() && dfa.atnStartState instanceof StarLoopEntryState) {
                if (((StarLoopEntryState) dfa.atnStartState).precedenceRuleDecision) {
                    dfa.setPrecedenceDfa(true);
                }
            }
            boolean fullCtx = false;
            ATNConfigSet s0_closure = computeStartState(dfa.atnStartState, ParserRuleContext.EMPTY, fullCtx);
            if (dfa.isPrecedenceDfa()) {
                /* If this is a precedence DFA, we use applyPrecedenceFilter
					 * to convert the computed start state to a precedence start
					 * state. We then use DFA.setPrecedenceStartState to set the
					 * appropriate start state for the precedence level rather
					 * than simply setting DFA.s0.
					 */
                s0_closure = applyPrecedenceFilter(s0_closure);
                s0 = addDFAState(dfa, new DFAState(s0_closure));
                dfa.setPrecedenceStartState(parser.getPrecedence(), s0);
            } else {
                s0 = addDFAState(dfa, new DFAState(s0_closure));
                dfa.s0 = s0;
            }
        }
        int alt = execATN(dfa, s0, input, index, outerContext);
        if (debug)
            System.out.println("DFA after predictATN: " + dfa.toString(parser.getTokenNames()));
        return alt;
    } finally {
        // wack cache after each prediction
        mergeCache = null;
        input.seek(index);
        input.release(m);
    }
}
Example 5
Project: udidb-master  File: ExpressionSimplificationVisitor.java View source code
@Override
public Void visitAdditiveExpression(@NotNull CParser.AdditiveExpressionContext ctx) {
    NodeState nodeState = getNodeState(ctx);
    ParserRuleContext multExpr = ctx.multiplicativeExpression();
    multExpr.accept(this);
    if (ctx.additiveExpression() == null) {
        nodeState.setExpressionValue(getNodeState(multExpr).getExpressionValue());
        return null;
    }
    ParserRuleContext addExpr = ctx.additiveExpression();
    addExpr.accept(this);
    if (getNodeState(addExpr).getExpressionValue() == null || getNodeState(multExpr).getExpressionValue() == null) {
        // The computation cannot be performed yet
        return null;
    }
    String operation = ctx.getChild(1).getText();
    Number left = getNodeState(addExpr).getExpressionValue().getNumberValue();
    Number right = getNodeState(multExpr).getExpressionValue().getNumberValue();
    DebugType effectiveType = nodeState.getEffectiveType();
    Number computedValue;
    switch(operation) {
        case "+":
            if (effectiveType == Types.getType(Types.FLOAT_NAME)) {
                computedValue = left.floatValue() + right.floatValue();
            } else if (effectiveType == Types.getType(Types.DOUBLE_NAME)) {
                computedValue = left.doubleValue() + right.doubleValue();
            } else {
                // TODO handle other cases
                computedValue = 0;
            }
            break;
        case "-":
            // TODO implement
            computedValue = 0;
            break;
        default:
            throw new ParseCancellationException(INVALID_TREE_MSG);
    }
    nodeState.setExpressionValue(new NumberValue(computedValue));
    return null;
}
Example 6
Project: viskell-master  File: TypeBuilder.java View source code
/**
     * Parse a Haskell type declaration into a TypeT instance.
     *
     * @param hs The Haskell type declaration
     * @return Type
     */
public Type build(final String hs) {
    TypeLexer lexer = new TypeLexer(new ANTLRInputStream(hs));
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    TypeParser parser = new TypeParser(tokens);
    ParserRuleContext tree = parser.type();
    ParseTreeWalker walker = new ParseTreeWalker();
    TypeBuilderListener extractor;
    extractor = new TypeBuilderListener(this.typeClasses);
    walker.walk(extractor, tree);
    return extractor.result();
}
Example 7
Project: antlrworks2-master  File: GrammarIndentTask.java View source code
@RuleDependencies({ @RuleDependency(recognizer = GrammarParser.class, rule = GrammarParser.RULE_ruleAltList, version = 0, dependents = Dependents.PARENTS), @RuleDependency(recognizer = GrammarParser.class, rule = GrammarParser.RULE_lexerAltList, version = 1, dependents = Dependents.PARENTS), @RuleDependency(recognizer = GrammarParser.class, rule = GrammarParser.RULE_altList, version = 0, dependents = Dependents.PARENTS), @RuleDependency(recognizer = GrammarParser.class, rule = GrammarParser.RULE_blockSet, version = 0, dependents = Dependents.PARENTS), @RuleDependency(recognizer = GrammarParser.class, rule = GrammarParser.RULE_lexerBlock, version = 1, dependents = Dependents.PARENTS), @RuleDependency(recognizer = GrammarParser.class, rule = GrammarParser.RULE_block, version = 0, dependents = Dependents.PARENTS) })
private Tuple2<? extends ParseTree, Integer> visitGenericBlock(ParserRuleContext container) {
    if (targetElement == ParseTrees.getStartNode(container)) {
        return null;
    }
    if (ParseTrees.getTerminalNodeType(targetElement) == GrammarParser.RPAREN) {
        return Tuple.create(container, 0);
    }
    // OR lines up with previous OR
    boolean orNode = ParseTrees.getTerminalNodeType(targetElement) == GrammarParser.OR;
    if (orNode) {
        for (int i = priorSiblings.size() - 2; i >= 0; i--) {
            ParseTree sibling = priorSiblings.get(i);
            if (!(sibling instanceof TerminalNode)) {
                continue;
            }
            if (i == 0 || ParseTrees.elementStartsLine(sibling)) {
                return Tuple.create(sibling, 0);
            }
        }
        if (ParseTrees.getTerminalNodeType(ParseTrees.getStartNode(container)) != GrammarParser.LPAREN) {
            // handle at the parent so it aligns at the (
            return null;
        }
        return Tuple.create(container, 0);
    }
    // the non-terminals under these rules are straightforward
    int firstRuleIndex = -1;
    for (int i = 0; i < priorSiblings.size(); i++) {
        ParseTree sibling = priorSiblings.get(i);
        if (sibling instanceof RuleNode) {
            firstRuleIndex = i;
            break;
        }
    }
    for (int i = priorSiblings.size() - 2; i >= 0; i--) {
        ParseTree sibling = priorSiblings.get(i);
        if (!(sibling instanceof RuleNode)) {
            continue;
        }
        if (i == firstRuleIndex || ParseTrees.elementStartsLine(sibling)) {
            return Tuple.create(sibling, 0);
        }
    }
    // handle at the parent
    return null;
}
Example 8
Project: batfish-master  File: Batfish.java View source code
public static String flatten(String input, BatfishLogger logger, Settings settings, ConfigurationFormat format, String header) {
    switch(format) {
        case JUNIPER:
            {
                JuniperCombinedParser parser = new JuniperCombinedParser(input, settings);
                ParserRuleContext tree = parse(parser, logger, settings);
                JuniperFlattener flattener = new JuniperFlattener(header);
                ParseTreeWalker walker = new ParseTreeWalker();
                walker.walk(flattener, tree);
                return flattener.getFlattenedConfigurationText();
            }
        case VYOS:
            {
                VyosCombinedParser parser = new VyosCombinedParser(input, settings);
                ParserRuleContext tree = parse(parser, logger, settings);
                VyosFlattener flattener = new VyosFlattener(header);
                ParseTreeWalker walker = new ParseTreeWalker();
                walker.walk(flattener, tree);
                return flattener.getFlattenedConfigurationText();
            }
        // $CASES-OMITTED$
        default:
            throw new BatfishException("Invalid format for flattening");
    }
}
Example 9
Project: goworks-master  File: SemanticAnalyzerListener.java View source code
@RuleDependency(recognizer = GoParser.class, rule = GoParser.RULE_packageName, version = 0)
private boolean resolveQualifiedIdentifier(TerminalNode node, PackageModel currentPackage, Map<String, Collection<PackageModel>> resolvedPackages) {
    Token token = node.getSymbol();
    if (treeDecorator.getProperty(node, GoAnnotations.NODE_TYPE) != NodeType.UNDEFINED) {
        // already resolved
        return false;
    }
    ParserRuleContext qualifier = treeDecorator.getProperty(node, GoAnnotations.QUALIFIER);
    if (qualifier == null) {
        // don't have the information necessary to resolve
        return false;
    }
    Collection<? extends CodeElementModel> resolvedQualifier = treeDecorator.getProperty(qualifier, GoAnnotations.MODELS);
    if (resolvedQualifier == null) {
        CodeElementReference qualifierCodeClass = treeDecorator.getProperty(qualifier, GoAnnotations.CODE_CLASS);
        assert qualifierCodeClass != null;
        if (qualifierCodeClass != CodeElementReference.MISSING) {
            resolvedQualifier = qualifierCodeClass.resolve(annotatedParseTree, currentPackage, resolvedPackages);
        }
    }
    if (resolvedQualifier == null) {
        CodeElementReference qualifierExprType = treeDecorator.getProperty(qualifier, GoAnnotations.EXPR_TYPE);
        assert qualifierExprType != null;
        if (qualifierExprType != CodeElementReference.MISSING) {
            resolvedQualifier = qualifierExprType.resolve(annotatedParseTree, currentPackage, resolvedPackages);
        }
    }
    if (resolvedQualifier == null) {
        NodeType qualifierNodeType = treeDecorator.getProperty(qualifier, GoAnnotations.NODE_TYPE);
        if (qualifierNodeType == NodeType.UNDEFINED) {
            if (treeDecorator.getProperty(qualifier, GoAnnotations.QUALIFIED_EXPR)) {
                // haven't resolved the qualifier, which is itself a qualified expression
                return false;
            }
            TerminalNode unqualifiedLink = treeDecorator.getProperty(qualifier, GoAnnotations.UNQUALIFIED_LINK);
            if (unqualifiedLink != null) {
                Map<? extends ObjectProperty<?>, ?> properties = treeDecorator.getProperties(unqualifiedLink);
                treeDecorator.putProperties(qualifier, properties);
                qualifierNodeType = treeDecorator.getProperty(qualifier, GoAnnotations.NODE_TYPE);
                if (qualifierNodeType == NodeType.UNDEFINED) {
                    treeDecorator.putProperty(qualifier, GoAnnotations.NODE_TYPE, NodeType.UNKNOWN);
                    qualifierNodeType = NodeType.UNKNOWN;
                }
            } else {
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.log(Level.WARNING, "Unable to resolve unqualified link from qualifier: {0}", qualifier.toString(Arrays.asList(GoParser.ruleNames)));
                }
                qualifierNodeType = NodeType.UNKNOWN;
            }
        }
        assert qualifierNodeType != NodeType.UNDEFINED;
        if (qualifierNodeType == NodeType.UNKNOWN) {
            // can't resolve a dereference if the qualifier couldn't be resolved
            treeDecorator.putProperty(node, GoAnnotations.NODE_TYPE, NodeType.UNKNOWN);
            return true;
        }
        if (qualifierNodeType == NodeType.TYPE_LITERAL) {
            return resolveQualifierType(qualifier, currentPackage, resolvedPackages);
        } else if (qualifierNodeType == NodeType.PACKAGE_REF) {
            assert qualifier instanceof PackageNameContext;
            String packageName = ((PackageNameContext) qualifier).IDENTIFIER().getSymbol().getText();
            resolvedQualifier = resolvedPackages.get(packageName);
            if (resolvedQualifier == null) {
                resolvedQualifier = Collections.emptyList();
            }
        } else if (qualifierNodeType == NodeType.VAR_REF) {
            // must be referring to something within the current file since it's resolved internally
            TerminalNode target = treeDecorator.getProperty(qualifier, GoAnnotations.LOCAL_TARGET);
            assert target != null && treeDecorator.getProperty(target, GoAnnotations.NODE_TYPE) == NodeType.VAR_DECL;
            ParserRuleContext explicitType = treeDecorator.getProperty(qualifier, GoAnnotations.EXPLICIT_TYPE);
            if (explicitType == null && target != null) {
                explicitType = treeDecorator.getProperty(target, GoAnnotations.EXPLICIT_TYPE);
            }
            if (explicitType != null) {
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.log(Level.WARNING, "Unable to resolve explicit type for qualifier: {0}", qualifier.toString(Arrays.asList(GoParser.ruleNames)));
                }
                resolvedQualifier = Collections.emptyList();
            } else {
                ParserRuleContext implicitType = target != null ? treeDecorator.getProperty(target, GoAnnotations.IMPLICIT_TYPE) : null;
                int implicitIndex = target != null ? treeDecorator.getProperty(target, GoAnnotations.IMPLICIT_INDEX) : -1;
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.log(Level.WARNING, "Unable to resolve implicit type for qualifier: {0}", qualifier.toString(Arrays.asList(GoParser.ruleNames)));
                }
                resolvedQualifier = Collections.emptyList();
            }
        } else {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.log(Level.WARNING, "Unable to resolve qualifier: {0}", qualifier.toString(Arrays.asList(GoParser.ruleNames)));
            }
            resolvedQualifier = Collections.emptyList();
        }
    }
    assert resolvedQualifier != null;
    if (resolvedQualifier == null) {
        LOGGER.log(Level.WARNING, "Should not have a null resolved qualifier at this point.");
        resolvedQualifier = Collections.emptyList();
    }
    String nameText = token.getText();
    List<CodeElementModel> qualifiedModels = new ArrayList<>();
    for (CodeElementModel model : resolvedQualifier) {
        qualifiedModels.addAll(SemanticAnalyzer.getSelectableMembers(model, nameText));
    }
    if (qualifiedModels.isEmpty()) {
        treeDecorator.putProperty(node, GoAnnotations.NODE_TYPE, NodeType.UNKNOWN);
        return true;
    }
    setNodeType(node, qualifiedModels.get(0));
    treeDecorator.putProperty(node, GoAnnotations.RESOLVED, true);
    treeDecorator.putProperty(node, GoAnnotations.MODELS, qualifiedModels);
    return true;
}
Example 10
Project: hibernate-semantic-query-master  File: HqlParseTreePrinter.java View source code
@Override
public void exitEveryRule(ParserRuleContext ctx) {
    super.exitEveryRule(ctx);
    final String ruleName = parser.getRuleNames()[ctx.getRuleIndex()];
    if (!ruleName.endsWith("Keyword")) {
        HQL_LOGGER.debugf("%s %s (%s) [`%s`]", exitRulePadding(), ctx.getClass().getSimpleName(), parser.getRuleNames()[ctx.getRuleIndex()], ctx.getText());
    }
}
Example 11
Project: jvmBASIC-master  File: Dispatcher.java View source code
/**
    * dispatch
    */
public static boolean dispatch(GenerationContext generationContext) throws Exception {
    try {
        if (null != generationContext.getParseTree()) {
            final Object o = generationContext.getParseTree().getPayload();
            if (o.getClass() == CommonToken.class) {
                final CommonToken commonToken = (CommonToken) o;
                final Function function = FunctionRegistry.getInstance().getTokenFunction(commonToken.getType());
                logger.info("Dispatching to '" + function.getClass().getSimpleName() + "' for token '" + jvmBasicParser.VOCABULARY.getDisplayName(commonToken.getType()) + "'");
                return function.execute(generationContext);
            } else {
                final ParserRuleContext parserRuleContext = (ParserRuleContext) o;
                final Function function = FunctionRegistry.getInstance().getRuleFunction(parserRuleContext.getRuleIndex());
                logger.info("Dispatching to '" + function.getClass().getSimpleName() + "' for rule '" + jvmBasicParser.ruleNames[parserRuleContext.getRuleIndex()] + "'");
                return function.execute(generationContext);
            }
        }
        return true;
    } catch (final Exception e) {
        throw new Exception("Exception in dispatch at line " + generationContext.getLineNumber(), e);
    }
}
Example 12
Project: many-ql-master  File: QLGrammarParser.java View source code
private ExprContext expr(int _p) throws RecognitionException {
    ParserRuleContext _parentctx = _ctx;
    int _parentState = getState();
    ExprContext _localctx = new ExprContext(_ctx, _parentState);
    ExprContext _prevctx = _localctx;
    int _startState = 10;
    enterRecursionRule(_localctx, 10, RULE_expr, _p);
    int _la;
    try {
        int _alt;
        enterOuterAlt(_localctx, 1);
        {
            setState(61);
            switch(_input.LA(1)) {
                case SUB:
                    {
                        _localctx = new UnaryMinusContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(56);
                        match(SUB);
                        setState(57);
                        expr(9);
                    }
                    break;
                case T__10:
                    {
                        _localctx = new NotContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(58);
                        match(T__10);
                        setState(59);
                        expr(8);
                    }
                    break;
                case T__8:
                case BOOLEAN:
                case ID:
                case NUMBER:
                case STRING:
                    {
                        _localctx = new AtomiumContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(60);
                        atom();
                    }
                    break;
                default:
                    throw new NoViableAltException(this);
            }
            _ctx.stop = _input.LT(-1);
            setState(83);
            _errHandler.sync(this);
            _alt = getInterpreter().adaptivePredict(_input, 7, _ctx);
            while (_alt != 2 && _alt != org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER) {
                if (_alt == 1) {
                    if (_parseListeners != null)
                        triggerExitRuleEvent();
                    _prevctx = _localctx;
                    {
                        setState(81);
                        switch(getInterpreter().adaptivePredict(_input, 6, _ctx)) {
                            case 1:
                                {
                                    _localctx = new MultiplicationContext(new ExprContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_expr);
                                    setState(63);
                                    if (!(precpred(_ctx, 7)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 7)");
                                    setState(64);
                                    ((MultiplicationContext) _localctx).op = _input.LT(1);
                                    _la = _input.LA(1);
                                    if (!((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << MULT) | (1L << DIV) | (1L << MOD))) != 0))) {
                                        ((MultiplicationContext) _localctx).op = (Token) _errHandler.recoverInline(this);
                                    } else {
                                        consume();
                                    }
                                    setState(65);
                                    expr(8);
                                }
                                break;
                            case 2:
                                {
                                    _localctx = new AdditiveContext(new ExprContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_expr);
                                    setState(66);
                                    if (!(precpred(_ctx, 6)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 6)");
                                    setState(67);
                                    ((AdditiveContext) _localctx).op = _input.LT(1);
                                    _la = _input.LA(1);
                                    if (!(_la == ADD || _la == SUB)) {
                                        ((AdditiveContext) _localctx).op = (Token) _errHandler.recoverInline(this);
                                    } else {
                                        consume();
                                    }
                                    setState(68);
                                    expr(7);
                                }
                                break;
                            case 3:
                                {
                                    _localctx = new RelationalContext(new ExprContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_expr);
                                    setState(69);
                                    if (!(precpred(_ctx, 5)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 5)");
                                    setState(70);
                                    ((RelationalContext) _localctx).op = _input.LT(1);
                                    _la = _input.LA(1);
                                    if (!((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << LTE) | (1L << GTE) | (1L << LT) | (1L << GT))) != 0))) {
                                        ((RelationalContext) _localctx).op = (Token) _errHandler.recoverInline(this);
                                    } else {
                                        consume();
                                    }
                                    setState(71);
                                    expr(6);
                                }
                                break;
                            case 4:
                                {
                                    _localctx = new EqualityContext(new ExprContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_expr);
                                    setState(72);
                                    if (!(precpred(_ctx, 4)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 4)");
                                    setState(73);
                                    ((EqualityContext) _localctx).op = _input.LT(1);
                                    _la = _input.LA(1);
                                    if (!(_la == EQ || _la == NEQ)) {
                                        ((EqualityContext) _localctx).op = (Token) _errHandler.recoverInline(this);
                                    } else {
                                        consume();
                                    }
                                    setState(74);
                                    expr(5);
                                }
                                break;
                            case 5:
                                {
                                    _localctx = new AndContext(new ExprContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_expr);
                                    setState(75);
                                    if (!(precpred(_ctx, 3)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 3)");
                                    setState(76);
                                    match(T__11);
                                    setState(77);
                                    expr(4);
                                }
                                break;
                            case 6:
                                {
                                    _localctx = new OrContext(new ExprContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_expr);
                                    setState(78);
                                    if (!(precpred(_ctx, 2)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 2)");
                                    setState(79);
                                    match(T__12);
                                    setState(80);
                                    expr(3);
                                }
                                break;
                        }
                    }
                }
                setState(85);
                _errHandler.sync(this);
                _alt = getInterpreter().adaptivePredict(_input, 7, _ctx);
            }
        }
    } catch (RecognitionException re) {
        _localctx.exception = re;
        _errHandler.reportError(this, re);
        _errHandler.recover(this, re);
    } finally {
        unrollRecursionContexts(_parentctx);
    }
    return _localctx;
}
Example 13
Project: tailor-master  File: BraceStyleListener.java View source code
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);
}
Example 14
Project: JAME-master  File: TestCF3Parser.java View source code
@Test
public void parse() {
    try {
        ANTLRInputStream is = new ANTLRInputStream(new FileReader("cfdg/test1.cfdg"));
        CFDGLexer lexer = new CFDGLexer(is);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        CFDGParser parser = new CFDGParser(tokens);
        ParseTree choose = parser.choose();
        if (choose != null) {
            ParseTreeWalker walker = new ParseTreeWalker();
            walker.walk(new ParseTreeListener() {

                @Override
                public void visitTerminal(TerminalNode node) {
                    System.out.println(node.getText() + " " + node.getSymbol());
                }

                @Override
                public void visitErrorNode(ErrorNode node) {
                //						System.out.println(node.getText() + " " + node.getSymbol());
                }

                @Override
                public void exitEveryRule(ParserRuleContext ctx) {
                //						System.out.println(ctx.getText());
                }

                @Override
                public void enterEveryRule(ParserRuleContext ctx) {
                //						System.out.println(ctx.getText());
                }
            }, choose);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 15
Project: MaritimeCloud-master  File: AnnotationContainer.java View source code
@SuppressWarnings({ "rawtypes", "unchecked" })
AnnotationContainer parse(ParserRuleContext c) {
    for (ParseTree pt : c.children) {
        if (pt instanceof AnnotationContext) {
            AnnotationContext ac = (AnnotationContext) pt;
            String name = ac.annotationName().qualifiedName().getText();
            // System.out.println(name);
            ElementValueContext ev = ac.elementValue();
            final Anno anno;
            if (ev != null) {
                // System.out.println("Y");
                List<String> list = new ArrayList<>();
                if (ev.StringLiteral() != null) {
                    String text = ev.StringLiteral().getText();
                    text = text.replace("\"", "");
                    list.add(text);
                } else /* if (ev.elementValueArrayInitializer() != null) */
                {
                    ElementValueArrayInitializerContext ec = ev.elementValueArrayInitializer();
                    for (int i = 0; i < ec.children.size(); i++) {
                        ElementValueContext evc = ec.elementValue(i);
                        if (evc != null) {
                            // System.out.println(ev.getChildCount());
                            String text = evc.StringLiteral().getText();
                            text = text.replace("\"", "");
                            list.add(text);
                        }
                    }
                }
                // System.out.println(list);
                anno = new Anno(name, new Map.Entry[] { new AbstractMap.SimpleImmutableEntry("value", list.toArray(new String[0])) });
            } else {
                anno = new Anno(name, new Map.Entry[0]);
            }
            annotations.put(name, anno);
        }
    }
    return this;
}
Example 16
Project: monticore-master  File: ParseTrees.java View source code
/** Find smallest subtree of t enclosing range start..stop
   *  inclusively using postorder traversal.  Recursive depth-first-search.
   *
   *  @since 4.5.1
   */
public static ParserRuleContext getRootOfSubtreeEnclosingRegion(ParseTree t, // inclusive
int start, // inclusive
int stop) {
    int n = t.getChildCount();
    for (int i = 0; i < n; i++) {
        ParseTree child = t.getChild(i);
        ParserRuleContext r = getRootOfSubtreeEnclosingRegion(child, start, stop);
        if (r != null)
            return r;
    }
    if (t instanceof ParserRuleContext) {
        ParserRuleContext r = (ParserRuleContext) t;
        if (// is range fully contained in t?
        start >= r.getStart().getStartIndex() && (r.getStop() == null || stop <= r.getStop().getStopIndex())) {
            // note: r.getStop()==null likely implies that we bailed out of parser and there's nothing to the right
            return r;
        }
    }
    return null;
}
Example 17
Project: StreamCQL-master  File: SelectClauseParser.java View source code
/**
     * {@inheritDoc}
     */
@Override
public ParseContext parse(String cql) throws ParseException {
    CQLErrorListener errorListener = new CQLErrorListener();
    CQLLexer lexer = new CQLLexer(new ANTLRIgnoreCaseStringStream(cql));
    lexer.removeErrorListeners();
    lexer.addErrorListener(errorListener);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    CQLParser parser = new CQLParser(tokens);
    CQLErrorStrategy errorHandler = new CQLErrorStrategy();
    parser.setErrorHandler(errorHandler);
    parser.removeErrorListeners();
    parser.addErrorListener(errorListener);
    ParserRuleContext tree = parser.subSelectClause();
    if (errorListener.getRecException() != null) {
        errorListener.getRecException().setCql(cql);
        throw errorListener.getRecException();
    }
    LOG.info("Parse Completed, cql : {}", cql.replace("\n", " "));
    SelectClauseVisitor visitor = new SelectClauseVisitor();
    return visitor.visit(tree);
}
Example 18
Project: zen-project-master  File: SimpleJixParser.java View source code
private void parseInternal() throws UncheckedIOException {
    try {
        ANTLRInputStream src = new ANTLRInputStream(in);
        SimpleJsonLexer lexer = new SimpleJsonLexer(src);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        SimpleJsonParser parser = new SimpleJsonParser(tokens);
        ParserRuleContext tree = new ParserRuleContext();
        parser.setContext(tree);
        parser.setErrorHandler(new BailErrorStrategy());
        SimpleJsonListener listener = this;
        /*ProgramContext*/
        ParseTree parseTree = parser.program();
        DEFAULT.walk(listener, parseTree);
    } catch (IOException e) {
        throw EX.uncheckedIO(e);
    } finally {
        try {
            in.close();
        } catch (IOException e) {
        }
    }
}
Example 19
Project: android-sdk-sources-for-api-level-23-master  File: LayoutFileParser.java View source code
private void parseExpressions(String newTag, final XMLParser.ElementContext rootView, final boolean isMerge, ResourceBundle.LayoutFileBundle bundle) {
    final List<XMLParser.ElementContext> bindingElements = new ArrayList<>();
    final List<XMLParser.ElementContext> otherElementsWithIds = new ArrayList<>();
    rootView.accept(new XMLParserBaseVisitor<Void>() {

        @Override
        public Void visitElement(@NotNull XMLParser.ElementContext ctx) {
            if (filter(ctx)) {
                bindingElements.add(ctx);
            } else {
                String name = ctx.elmName.getText();
                if (!"include".equals(name) && !"fragment".equals(name) && attributeMap(ctx).containsKey("android:id")) {
                    otherElementsWithIds.add(ctx);
                }
            }
            visitChildren(ctx);
            return null;
        }

        private boolean filter(XMLParser.ElementContext ctx) {
            if (isMerge) {
                // account for XMLParser.ContentContext
                if (ctx.getParent().getParent() == rootView) {
                    return true;
                }
            } else if (ctx == rootView) {
                return true;
            }
            if (hasIncludeChild(ctx)) {
                return true;
            }
            if (XmlEditor.hasExpressionAttributes(ctx)) {
                return true;
            }
            return false;
        }

        private boolean hasIncludeChild(XMLParser.ElementContext ctx) {
            for (XMLParser.ElementContext child : XmlEditor.elements(ctx)) {
                if ("include".equals(child.elmName.getText())) {
                    return true;
                }
            }
            return false;
        }
    });
    final HashMap<XMLParser.ElementContext, String> nodeTagMap = new HashMap<XMLParser.ElementContext, String>();
    L.d("number of binding nodes %d", bindingElements.size());
    int tagNumber = 0;
    for (XMLParser.ElementContext parent : bindingElements) {
        final Map<String, String> attributes = attributeMap(parent);
        String nodeName = parent.elmName.getText();
        String viewName = null;
        String includedLayoutName = null;
        final String id = attributes.get("android:id");
        final String tag;
        final String originalTag = attributes.get("android:tag");
        if ("include".equals(nodeName)) {
            // get the layout attribute
            final String includeValue = attributes.get("layout");
            if (StringUtils.isEmpty(includeValue)) {
                L.e("%s must include a layout", parent);
            }
            if (!includeValue.startsWith(LAYOUT_PREFIX)) {
                L.e("included value (%s) must start with %s.", includeValue, LAYOUT_PREFIX);
            }
            // if user is binding something there, there MUST be a layout file to be
            // generated.
            String layoutName = includeValue.substring(LAYOUT_PREFIX.length());
            includedLayoutName = layoutName;
            final ParserRuleContext myParentContent = parent.getParent();
            Preconditions.check(myParentContent instanceof XMLParser.ContentContext, "parent of an include tag must be a content context but it is %s", myParentContent.getClass().getCanonicalName());
            final ParserRuleContext grandParent = myParentContent.getParent();
            Preconditions.check(grandParent instanceof XMLParser.ElementContext, "grandparent of an include tag must be an element context but it is %s", grandParent.getClass().getCanonicalName());
            //noinspection SuspiciousMethodCalls
            tag = nodeTagMap.get(grandParent);
        } else if ("fragment".equals(nodeName)) {
            L.e("fragments do not support data binding expressions.");
            continue;
        } else {
            viewName = getViewName(parent);
            // account for XMLParser.ContentContext
            if (rootView == parent || (isMerge && parent.getParent().getParent() == rootView)) {
                tag = newTag + "_" + tagNumber;
            } else {
                tag = "binding_" + tagNumber;
            }
            tagNumber++;
        }
        final ResourceBundle.BindingTargetBundle bindingTargetBundle = bundle.createBindingTarget(id, viewName, true, tag, originalTag, new Location(parent));
        nodeTagMap.put(parent, tag);
        bindingTargetBundle.setIncludedLayout(includedLayoutName);
        for (XMLParser.AttributeContext attr : XmlEditor.expressionAttributes(parent)) {
            String value = escapeQuotes(attr.attrValue.getText(), true);
            if (value.charAt(0) == '@' && value.charAt(1) == '{' && value.charAt(value.length() - 1) == '}') {
                final String strippedValue = value.substring(2, value.length() - 1);
                Location attrLocation = new Location(attr);
                Location valueLocation = new Location();
                // offset to 0 based
                valueLocation.startLine = attr.attrValue.getLine() - 1;
                valueLocation.startOffset = attr.attrValue.getCharPositionInLine() + attr.attrValue.getText().indexOf(strippedValue);
                valueLocation.endLine = attrLocation.endLine;
                // account for: "}
                valueLocation.endOffset = attrLocation.endOffset - 2;
                bindingTargetBundle.addBinding(escapeQuotes(attr.attrName.getText(), false), strippedValue, attrLocation, valueLocation);
            }
        }
    }
    for (XMLParser.ElementContext elm : otherElementsWithIds) {
        final String id = attributeMap(elm).get("android:id");
        final String className = getViewName(elm);
        bundle.createBindingTarget(id, className, true, null, null, new Location(elm));
    }
}
Example 20
Project: diqube-master  File: GroupByVisitor.java View source code
@Override
public Pair<GroupRequest, ComparisonRequest> visitGroupByClause(GroupByClauseContext groupByCtx) {
    GroupRequest groupRequestRes = new GroupRequest();
    int anyValueCnt = 0;
    AnyValueContext anyValueCtx;
    while ((anyValueCtx = groupByCtx.getChild(AnyValueContext.class, anyValueCnt++)) != null) {
        ColumnOrValue groupBy = anyValueCtx.accept(new AnyValueVisitor(env, repeatedColNames, functionBasedColumnNameBuilderFactory)).getLeft();
        if (!groupBy.getType().equals(ColumnOrValue.Type.COLUMN))
            throw new ParseException("Can only group on columns.");
        groupRequestRes.getGroupColumns().add(groupBy.getColumnName());
    }
    ComparisonRequest havingRequestRes = groupByCtx.accept(new ComparisonVisitor(env, repeatedColNames, functionBasedColumnNameBuilderFactory, new ArrayList<Class<? extends ParserRuleContext>>()));
    return new Pair<GroupRequest, ComparisonRequest>(groupRequestRes, havingRequestRes);
}
Example 21
Project: groovy-master  File: GroovydocManager.java View source code
private String findDocCommentByNode(ParserRuleContext node) {
    if (!asBoolean(node)) {
        return null;
    }
    if (node instanceof GroovyParser.ClassBodyContext) {
        return null;
    }
    ParserRuleContext parentContext = node.getParent();
    if (!asBoolean(parentContext)) {
        return null;
    }
    String docCommentNodeText = null;
    boolean sameTypeNodeBefore = false;
    for (ParseTree child : parentContext.children) {
        if (node == child) {
            // try to find doc comment node of its parent
            if (!asBoolean((Object) docCommentNodeText) && !sameTypeNodeBefore) {
                return findDocCommentByNode(parentContext);
            }
            return docCommentNodeText;
        }
        if (node.getClass() == child.getClass()) {
            // e.g. ClassBodyDeclarationContext == ClassBodyDeclarationContext
            docCommentNodeText = null;
            sameTypeNodeBefore = true;
            continue;
        }
        if (!(child instanceof GroovyParser.NlsContext || child instanceof GroovyParser.SepContext)) {
            continue;
        }
        // doc comments are treated as NL
        List<? extends TerminalNode> nlList = child instanceof GroovyParser.NlsContext ? ((GroovyParser.NlsContext) child).NL() : ((GroovyParser.SepContext) child).NL();
        int nlListSize = nlList.size();
        if (0 == nlListSize) {
            continue;
        }
        for (int i = nlListSize - 1; i >= 0; i--) {
            String text = nlList.get(i).getText();
            if (text.matches("\\s+")) {
                continue;
            }
            if (text.startsWith(DOC_COMMENT_PREFIX)) {
                docCommentNodeText = text;
            } else {
                docCommentNodeText = null;
            }
            break;
        }
    }
    // The exception should never be thrown!
    throw new GroovyBugError("node can not be found: " + node.getText());
}
Example 22
Project: protostuff-compiler-master  File: AbstractProtoParserListener.java View source code
protected void attachComments(ParserRuleContext ctx, AbstractElement element, boolean addTrailingComment) {
    List<String> comments = new ArrayList<>();
    Token stop = ctx.getStop();
    Token start = ctx.getStart();
    List<Token> tokensBefore = tokens.getHiddenTokensToLeft(start.getTokenIndex(), HIDDEN);
    if (tokensBefore != null) {
        for (Token token : tokensBefore) {
            if (usedComments.get(token.getLine())) {
                continue;
            }
            if (token.getType() == LINE_COMMENT) {
                addCommentToList(token, comments);
            }
        }
    }
    if (addTrailingComment) {
        List<Token> tokensAfter = tokens.getHiddenTokensToRight(stop.getTokenIndex(), HIDDEN);
        findTrailingComment(tokensAfter).ifPresent( token -> addCommentToList(token, comments));
    }
    List<String> trimComments = trim(comments);
    for (String comment : trimComments) {
        element.addComment(comment);
    }
}
Example 23
Project: querqy-master  File: QueryTransformerVisitor.java View source code
Occur getOccur(ParserRuleContext ctx) {
    List<BooleanPrefixContext> contexts = ctx.getRuleContexts(BooleanPrefixContext.class);
    if (contexts == null || contexts.isEmpty()) {
        return Occur.SHOULD;
    }
    String prf = contexts.get(0).getText();
    if (prf.length() == 1) {
        switch(prf.charAt(0)) {
            case '+':
                return Occur.MUST;
            case '-':
                return Occur.MUST_NOT;
        }
    }
    return Occur.SHOULD;
}
Example 24
Project: rpgleparser-master  File: LoggingListener.java View source code
@Override
public void enterEveryRule(ParserRuleContext ctx) {
    if (logger.isDebugEnabled()) {
        //$NON-NLS-1$
        logger.debug("enterEveryRule(ParserRuleContext) - start");
    }
    super.enterEveryRule(ctx);
    if (logger.isDebugEnabled()) {
        //$NON-NLS-1$
        logger.debug("enterEveryRule(ParserRuleContext) - end");
    }
}
Example 25
Project: titan.EclipsePlug-ins-master  File: GeneralOptionsSubPage.java View source code
private PluginSpecificParam createPluginSpecificParamNode(final String param, final String value) {
    StringBuilder name = new StringBuilder();
    loggingPage.getSelectedTreeElement().writeNamePrefix(name);
    name.append(param);
    name.append(" := ");
    final ParseTree keyAST = new AddedParseTree(name.toString());
    final ParseTree valueAST = new AddedParseTree(value);
    final ParseTree root = new ParserRuleContext();
    ConfigTreeNodeUtilities.addChild(loggingSectionHandler.getLastSectionRoot(), root);
    ConfigTreeNodeUtilities.addChild(root, new AddedParseTree("\n"));
    ConfigTreeNodeUtilities.addChild(root, keyAST);
    ConfigTreeNodeUtilities.addChild(root, valueAST);
    PluginSpecificParam psp = new PluginSpecificParam(root, keyAST, valueAST, param);
    selectedLogEntry.getPluginSpecificParam().add(psp);
    return psp;
}
Example 26
Project: yangtools-master  File: ASTSchemaSource.java View source code
private static ASTSchemaSource create(@Nonnull final SourceIdentifier identifier, @Nullable final String symbolicName, @Nonnull final ParserRuleContext tree) throws YangSyntaxErrorException {
    final YangModelDependencyInfo depInfo = YangModelDependencyInfo.fromAST(identifier.getName(), tree);
    final SourceIdentifier id = getSourceId(depInfo);
    final SemVerSourceIdentifier semVerId;
    if (identifier instanceof SemVerSourceIdentifier && !depInfo.getSemanticVersion().isPresent()) {
        semVerId = (SemVerSourceIdentifier) identifier;
    } else {
        semVerId = getSemVerSourceId(depInfo);
    }
    return new ASTSchemaSource(id, semVerId, tree, depInfo, symbolicName);
}
Example 27
Project: beakerx-master  File: GroovyAutocomplete.java View source code
public AutocompleteResult doAutocomplete(String txt, int cur, ClassLoader l) {
    ClassUtils cu = createClassUtils(l);
    setup(cu, registry);
    registry.clearForType(GroovyCompletionTypes.CUSTOM_TYPE);
    registry.clearForType(GroovyCompletionTypes.FIELD);
    registry.clearForType(GroovyCompletionTypes.NAME);
    addDefaultImports(cu);
    moreSetup(cu);
    moreSetup(registry);
    Lexer lexer = new GroovyLexer(new ANTLRInputStream(txt));
    lexer.removeErrorListeners();
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    // Create a parser that reads from the scanner
    GroovyParser parser = new GroovyParser(tokens);
    parser.removeErrorListeners();
    // start parsing at the compilationUnit rule
    ParserRuleContext t = parser.compilationUnit();
    ParseTreeWalker walker = new ParseTreeWalker();
    List<AutocompleteCandidate> q = new ArrayList<AutocompleteCandidate>();
    GroovyImportDeclarationCompletion extractor = new GroovyImportDeclarationCompletion(txt, cur, registry, cps, cu);
    GroovyNameBuilder extractor2 = new GroovyNameBuilder(registry, cu);
    GroovyNodeCompletion extractor3 = new GroovyNodeCompletion(txt, cur, registry, cu);
    walker.walk(extractor, t);
    if (extractor.getQuery() != null)
        q.addAll(extractor.getQuery());
    walker.walk(extractor2, t);
    walker.walk(extractor3, t);
    if (extractor3.getQuery() != null)
        q.addAll(extractor3.getQuery());
    List<String> ret = registry.searchCandidates(q);
    if (ret.isEmpty()) {
        q.clear();
        for (int i = cur - 1; i >= 0; i--) {
            if (i < txt.length() && Character.isWhitespace(txt.charAt(i))) {
                String tx = txt.substring(i + 1, cur).trim();
                if (!txt.isEmpty()) {
                    if (tx.contains(".")) {
                        q.add(cu.expandExpression(tx, registry, cu.DO_ALL));
                    } else {
                        q.add(new AutocompleteCandidate(GroovyCompletionTypes.NAME, tx));
                    }
                    ret = registry.searchCandidates(q);
                }
                break;
            }
        }
    }
    if (txt.charAt(cur - 1) == '.') {
        for (int i = 0; i < ret.size(); i++) {
            String s = ret.get(i);
            if (s.startsWith("."))
                ret.set(i, s.substring(1));
        }
    }
    // this shows the GUI
    if (GroovyCompletionTypes.debug)
        t.inspect(parser);
    return new AutocompleteResult(ret, getStartIndex(extractor, extractor2, extractor3));
}
Example 28
Project: ceylon.tool.converter.java2ceylon-master  File: JavaToCeylonConverter.java View source code
private boolean isInIfCondition(ConditionalExpressionContext ctx) {
    if (parent(ctx, 1) instanceof AssignmentExpressionContext && parent(ctx, 2) instanceof ExpressionContext) {
        ParserRuleContext candidate = parent(ctx, 3);
        return candidate instanceof IfThenElseStatementContext || candidate instanceof IfThenStatementContext || candidate instanceof IfThenElseStatementNoShortIfContext;
    }
    return false;
}
Example 29
Project: datacollector-master  File: OracleCDCSource.java View source code
private void generateRecords(int batchSize, PreparedStatement selectChanges, BatchMaker batchMaker, boolean forceNewResultSet) throws SQLException, StageException, ParseException {
    String operation;
    StringBuilder query = new StringBuilder();
    ResultSet resultSet;
    if (!currentResultSet.isPresent()) {
        resultSet = selectChanges.executeQuery();
        currentStatement = Optional.of(selectChanges);
        currentResultSet = Optional.of(resultSet);
    } else {
        resultSet = currentResultSet.get();
    }
    int count = 0;
    boolean incompleteRedoStatement;
    try {
        while (resultSet.next()) {
            count++;
            query.append(resultSet.getString(5));
            // CSF being 0 means query is complete, generate the record
            if (resultSet.getInt(9) == 0) {
                incompleteRedoStatement = false;
                BigDecimal scnDecimal = resultSet.getBigDecimal(1);
                String scn = scnDecimal.toPlainString();
                String username = resultSet.getString(2);
                short op = resultSet.getShort(3);
                String timestamp = resultSet.getString(4);
                String table = resultSet.getString(6).trim();
                BigDecimal commitSCN = resultSet.getBigDecimal(7);
                String queryString = query.toString();
                long seq = resultSet.getLong(8);
                String scnSeq;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Commit SCN = " + commitSCN + ", SCN = " + scn + ", Redo SQL = " + queryString);
                }
                sqlListener.reset();
                plsqlLexer lexer = new plsqlLexer(new ANTLRInputStream(queryString));
                CommonTokenStream tokenStream = new CommonTokenStream(lexer);
                plsqlParser parser = new plsqlParser(tokenStream);
                ParserRuleContext ruleContext = null;
                int operationCode = -1;
                switch(op) {
                    case OracleCDCOperationCode.UPDATE_CODE:
                    case OracleCDCOperationCode.SELECT_FOR_UPDATE_CODE:
                        ruleContext = parser.update_statement();
                        operationCode = OperationType.UPDATE_CODE;
                        break;
                    case OracleCDCOperationCode.INSERT_CODE:
                        ruleContext = parser.insert_statement();
                        operationCode = OperationType.INSERT_CODE;
                        break;
                    case OracleCDCOperationCode.DELETE_CODE:
                        ruleContext = parser.delete_statement();
                        operationCode = OperationType.DELETE_CODE;
                        break;
                    case OracleCDCOperationCode.DDL_CODE:
                        break;
                    default:
                        errorRecordHandler.onError(JDBC_43, queryString);
                        continue;
                }
                if (op != OracleCDCOperationCode.DDL_CODE) {
                    operation = OperationType.getLabelFromIntCode(operationCode);
                    scnSeq = commitSCN + OFFSET_DELIM + seq;
                    // Walk it and attach our sqlListener
                    parseTreeWalker.walk(sqlListener, ruleContext);
                    Map<String, String> columns = sqlListener.getColumns();
                    Map<String, Field> fields = new HashMap<>();
                    Record record = getContext().createRecord(scnSeq);
                    Record.Header recordHeader = record.getHeader();
                    for (Map.Entry<String, String> column : columns.entrySet()) {
                        String columnName = column.getKey();
                        fields.put(columnName, objectToField(table, columnName, column.getValue()));
                        if (decimalColumns.containsKey(table) && decimalColumns.get(table).containsKey(columnName)) {
                            int precision = decimalColumns.get(table).get(columnName).precision;
                            int scale = decimalColumns.get(table).get(columnName).scale;
                            recordHeader.setAttribute("jdbc." + columnName + ".precision", String.valueOf(precision));
                            recordHeader.setAttribute("jdbc." + columnName + ".scale", String.valueOf(scale));
                        }
                    }
                    recordHeader.setAttribute(SCN, scn);
                    recordHeader.setAttribute(USER, username);
                    recordHeader.setAttribute(OracleCDCOperationCode.OPERATION, operation);
                    recordHeader.setAttribute(TIMESTAMP_HEADER, timestamp);
                    recordHeader.setAttribute(TABLE, table);
                    recordHeader.setAttribute(OperationType.SDC_OPERATION_TYPE, String.valueOf(operationCode));
                    record.set(Field.create(fields));
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(Utils.format("Adding {} to batchmaker: {}", record, batchMaker.toString()));
                    }
                    batchMaker.addRecord(record);
                } else {
                    scnSeq = scn + OFFSET_DELIM + ZERO;
                    boolean sendSchema = false;
                    // Event is sent on every DDL, but schema is not always sent.
                    // Schema sending logic:
                    // CREATE/ALTER: Schema is sent if the schema after the ALTER is newer than the cached schema
                    // (which we would have sent as an event earlier, at the last alter)
                    // DROP/TRUNCATE: Schema is not sent, since they don't change schema.
                    DDL_EVENT type = getDdlType(queryString);
                    if (type == DDL_EVENT.ALTER || type == DDL_EVENT.CREATE) {
                        sendSchema = refreshSchema(scnDecimal, table);
                    }
                    getContext().toEvent(createEventRecord(type, queryString, table, scnSeq, sendSchema));
                }
                this.nextOffsetReference.set(scnSeq);
                query.setLength(0);
            } else {
                incompleteRedoStatement = true;
            }
            if (!incompleteRedoStatement && count >= batchSize) {
                break;
            }
        }
    } catch (SQLException ex) {
        if (ex.getErrorCode() == MISSING_LOG_FILE) {
            isCachedSCNValid = false;
        } else if (ex.getErrorCode() != RESULTSET_CLOSED_AS_LOGMINER_SESSION_CLOSED) {
            LOG.warn("SQL Exception while retrieving records", ex);
        }
        if (!resultSet.isClosed()) {
            resultSet.close();
        }
        currentResultSet = Optional.empty();
    } finally {
        if (forceNewResultSet || count < batchSize) {
            resultSet.close();
            currentResultSet = Optional.empty();
        }
    }
}
Example 30
Project: esper-master  File: EPLTreeWalkerListener.java View source code
private void handleChainedFunction(ParserRuleContext parentCtx, EsperEPL2GrammarParser.ChainedFunctionContext chainedCtx, ExprNode childExpression) {
    List<ExprChainedSpec> chainSpec = ASTLibFunctionHelper.getLibFuncChain(chainedCtx.libFunctionNoClass(), astExprNodeMap);
    ExprDotNode dotNode = new ExprDotNodeImpl(chainSpec, configurationInformation.getEngineDefaults().getExpression().isDuckTyping(), configurationInformation.getEngineDefaults().getExpression().isUdfCache());
    if (childExpression != null) {
        dotNode.addChildNode(childExpression);
    }
    ASTExprHelper.exprCollectAddSubNodesAddParentNode(dotNode, parentCtx, astExprNodeMap);
}
Example 31
Project: gramtest-master  File: MainTest.java View source code
/**
   * Test with arithmetic expressions grammar
   * @throws java.io.IOException
   */
@Test
public void testArithExpGram() throws IOException {
    Lexer lexer = new bnfLexer(new ANTLRInputStream(getClass().getResourceAsStream("/arithexp.bnf")));
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    bnfParser grammarparser = new bnfParser(tokens);
    ParserRuleContext tree = grammarparser.rulelist();
    GeneratorVisitor extractor = new GeneratorVisitor();
    extractor.visit(tree);
    List<String> generatedTests = extractor.getTests();
    Assert.assertEquals(100, generatedTests.size());
}
Example 32
Project: heroic-master  File: CoreQueryParser.java View source code
private QueryListener parse(Function<HeroicQueryParser, ParserRuleContext> op, String input) {
    final HeroicQueryLexer lexer = new HeroicQueryLexer(new ANTLRInputStream(input));
    final CommonTokenStream tokens = new CommonTokenStream(lexer);
    final HeroicQueryParser parser = new HeroicQueryParser(tokens);
    parser.removeErrorListeners();
    parser.setErrorHandler(new BailErrorStrategy());
    final ParserRuleContext context;
    try {
        context = op.apply(parser);
    } catch (final ParseCancellationException e) {
        if (!(e.getCause() instanceof RecognitionException)) {
            throw e;
        }
        throw toParseException((RecognitionException) e.getCause());
    }
    final QueryListener listener = new QueryListener();
    ParseTreeWalker.DEFAULT.walk(listener, context);
    final Token last = lexer.getToken();
    if (last.getType() != Token.EOF) {
        throw new ParseException(String.format("garbage at end of string: '%s'", last.getText()), null, last.getLine(), last.getCharPositionInLine());
    }
    return listener;
}
Example 33
Project: Koral-master  File: AnnisQueryProcessor.java View source code
private ParserRuleContext parseAnnisQuery(String query) {
    Lexer lexer = new AqlLexer((CharStream) null);
    ParserRuleContext tree = null;
    Antlr4DescriptiveErrorListener errorListener = new Antlr4DescriptiveErrorListener(query);
    // Like p. 111
    try {
        // Tokenize input data
        ANTLRInputStream input = new ANTLRInputStream(query);
        lexer.setInputStream(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        parser = new AqlParser(tokens);
        // Don't throw out erroneous stuff
        parser.setErrorHandler(new BailErrorStrategy());
        lexer.removeErrorListeners();
        lexer.addErrorListener(errorListener);
        parser.removeErrorListeners();
        parser.addErrorListener(errorListener);
        // Get starting rule from parser
        Method startRule = AqlParser.class.getMethod("start");
        tree = (ParserRuleContext) startRule.invoke(parser, (Object[]) null);
    }// Some things went wrong ...
     catch (Exception e) {
        log.error("Could not parse query. " + "Please make sure it is well-formed.");
        log.error(errorListener.generateFullErrorMsg().toString());
        addError(errorListener.generateFullErrorMsg());
    }
    return tree;
}
Example 34
Project: Painless-master  File: Writer.java View source code
void writeConstant(final ParserRuleContext source, final Object constant) {
    if (constant instanceof Number) {
        writeNumeric(source, constant);
    } else if (constant instanceof Character) {
        writeNumeric(source, (int) (char) constant);
    } else if (constant instanceof String) {
        writeString(source, constant);
    } else if (constant instanceof Boolean) {
        writeBoolean(source, constant);
    } else if (constant != null) {
        throw new IllegalStateException(error(source) + "Unexpected writer state.");
    }
}
Example 35
Project: presto-master  File: AstBuilder.java View source code
@Override
public Node visitNormalize(SqlBaseParser.NormalizeContext context) {
    Expression str = (Expression) visit(context.valueExpression());
    String normalForm = Optional.ofNullable(context.normalForm()).map(ParserRuleContext::getText).orElse("NFC");
    return new FunctionCall(getLocation(context), QualifiedName.of("normalize"), ImmutableList.of(str, new StringLiteral(getLocation(context), normalForm)));
}
Example 36
Project: pretty-formula-master  File: FormulaParser.java View source code
/**
    * Parses a mathematical formula String like "(a+b)/c" to valid math LaTeX.
    * 
    * @param formula A raw formula input String.
    * @return The formula parsed to a small subset of LaTeX.
    * @throws DetailedParseCancellationException When the parsing fails.
    */
public static String parseToLatex(String formula) throws DetailedParseCancellationException {
    VanesaFormulaLexer lexer = new VanesaFormulaLexer(new ANTLRInputStream(formula));
    lexer.removeErrorListeners();
    lexer.addErrorListener(ThrowingErrorListener.INSTANCE);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    VanesaFormulaParser parser = new VanesaFormulaParser(tokens);
    parser.removeErrorListeners();
    parser.addErrorListener(ThrowingErrorListener.INSTANCE);
    ParserRuleContext tree = parser.expr();
    return FormulaParser.EXTRACTOR.visit(tree);
}
Example 37
Project: yang-ide-master  File: YangParserModelListener.java View source code
private void updateNodePosition(ASTNode astNode, ParseTree treeNode) {
    if (astNode != null && treeNode instanceof ParserRuleContext) {
        astNode.setStartPosition(((ParserRuleContext) treeNode).start.getStartIndex());
        astNode.setLineNumber(((ParserRuleContext) treeNode).start.getLine());
        astNode.setLength(((ParserRuleContext) treeNode).stop.getStopIndex() - astNode.getStartPosition());
        Token bodyToken = null;
        for (int i = 0; i < treeNode.getChildCount(); ++i) {
            if (treeNode.getChild(i) instanceof TerminalNode) {
                final TerminalNode term = (TerminalNode) treeNode.getChild(i);
                if (term != null && term.getSymbol() != null && term.getSymbol().getType() == YangLexer.LEFT_BRACE) {
                    bodyToken = term.getSymbol();
                }
            }
        }
        if (bodyToken != null) {
            astNode.setBodyStartPosition(bodyToken.getStartIndex());
        }
        setNodeDescription(astNode, treeNode);
    }
}
Example 38
Project: ANNIS-master  File: JoinListener.java View source code
/**
   * Automatically create a join from a node and a join class.
   *
   * This will automatically get the left and right hand refs
   * and will construct a new join specified by the type using reflection.
   * 
   * It will also add an parsed location to the join.
   *
   * @node
   * @type00
   */
private void join(ParserRuleContext ctx, Class<? extends Join> type) {
    QueryNode left = relationChain.get(relationIdx);
    QueryNode right = relationChain.get(relationIdx + 1);
    try {
        Constructor<? extends Join> c = type.getConstructor(QueryNode.class);
        Join newJoin = c.newInstance(right);
        left.addOutgoingJoin(addParsedLocation(ctx, newJoin));
    } catch (NoSuchMethodException ex) {
        log.error(null, ex);
    } catch (InstantiationException ex) {
        log.error(null, ex);
    } catch (IllegalAccessException ex) {
        log.error(null, ex);
    } catch (InvocationTargetException ex) {
        log.error(null, ex);
    }
}
Example 39
Project: blaze-persistence-master  File: AbstractExpressionFactory.java View source code
private Expression createExpression(RuleInvoker ruleInvoker, String expression, boolean allowCaseWhen, boolean allowQuantifiedPredicates, boolean allowTreatJoinExtension, MacroConfiguration macroConfiguration) {
    if (expression == null) {
        throw new NullPointerException("expression");
    }
    if (expression.isEmpty()) {
        throw new IllegalArgumentException("expression");
    }
    JPQLSelectExpressionLexer l = new JPQLSelectExpressionLexer(new ANTLRInputStream(expression));
    configureLexer(l);
    CommonTokenStream tokens = new CommonTokenStream(l);
    JPQLSelectExpressionParser p = new JPQLSelectExpressionParser(tokens, allowCaseWhen, allowQuantifiedPredicates, allowTreatJoinExtension);
    configureParser(p);
    ParserRuleContext ctx;
    try {
        ctx = ruleInvoker.invokeRule(p);
    } catch (SyntaxErrorException ex) {
        throw new SyntaxErrorException("Could not parse expression '" + expression + "', " + ex.getMessage(), ex);
    }
    if (LOG.isLoggable(Level.FINEST)) {
        LOG.finest(ctx.toStringTree());
    }
    JPQLSelectExpressionVisitorImpl visitor = new JPQLSelectExpressionVisitorImpl(tokens, aggregateFunctions, enumTypes, entityTypes, macroConfiguration == null ? Collections.EMPTY_MAP : macroConfiguration.macros);
    Expression parsedExpression = visitor.visit(ctx);
    if (optimize) {
        parsedExpression = parsedExpression.accept(optimizer);
    }
    return parsedExpression;
}
Example 40
Project: ceylon-ide-eclipse-master  File: PasteAsCeylonHandler.java View source code
private static String transformJavaToCeylon(String javaCode, CeylonIdeConfig ideConfig) throws IOException {
    ANTLRInputStream input = new ANTLRInputStream(javaCode);
    Java8Lexer lexer = new Java8Lexer(input);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    Java8Parser parser = new Java8Parser(tokens);
    ParserRuleContext tree = parser.compilationUnit();
    StringWriter out = new StringWriter();
    JavaToCeylonConverterConfig config = ideConfig.getConverterConfig();
    ScopeTree scopeTree = new ScopeTree();
    tree.accept(scopeTree);
    JavaToCeylonConverter converter = new JavaToCeylonConverter(out, config.getTransformGetters(), config.getUseValues(), scopeTree);
    ideConfig.save();
    tree.accept(converter);
    String ceylonCode = out.toString();
    if (ceylonCode.equals("")) {
        return javaCode;
    } else {
        return ceylonCode;
    }
}
Example 41
Project: etp-master  File: ETPWalker.java View source code
public ETPTerm processHiddenChannels(ParserRuleContext ctx) {
    Object o = getValue(ctx);
    if (o != null) {
        ETPTerm erlTerm = (ETPTerm) o;
        List<Token> whiteLeft = tokens.getHiddenTokensToLeft(ctx.getStart().getTokenIndex(), ETPLexer.WHITESPACE);
        List<Token> whiteRight = tokens.getHiddenTokensToRight(ctx.getStop().getTokenIndex(), ETPLexer.WHITESPACE);
        List<Token> commentsLeft = tokens.getHiddenTokensToLeft(ctx.getStart().getTokenIndex(), ETPLexer.COMMENTS);
        List<Token> commentsRight = tokens.getHiddenTokensToRight(ctx.getStop().getTokenIndex(), ETPLexer.COMMENTS);
        if (whiteLeft != null) {
            StringBuilder b = new StringBuilder();
            for (Token t : whiteLeft) {
                b.append(t.getText());
            }
        //System.out.println("[[" + b.toString() + "[[");
        }
        if (whiteRight != null) {
            StringBuilder b = new StringBuilder();
            for (Token t : whiteRight) {
                b.append(t.getText());
            }
        //System.out.println("]]" + b.toString() + "]]");
        }
        if (commentsLeft != null) {
            StringBuilder b = new StringBuilder();
            for (Token t : commentsLeft) {
                b.append(t.getText());
            }
        //System.out.println("cc" + b.toString() + "cc");
        }
        if (commentsRight != null) {
            StringBuilder b = new StringBuilder();
            for (Token t : commentsRight) {
                b.append(t.getText());
            }
        //System.out.println("CC" + b.toString() + "CC");
        }
        return erlTerm;
    } else {
        return null;
    }
}
Example 42
Project: geotoolkit-master  File: FXCQLEditor.java View source code
private void syntaxHighLight(ParseTree tree) {
    if (tree instanceof ParserRuleContext) {
        final ParserRuleContext prc = (ParserRuleContext) tree;
        if (prc.exception != null) {
            //error nodes
            final Token tokenStart = prc.getStart();
            Token tokenEnd = prc.getStop();
            if (tokenEnd == null)
                tokenEnd = tokenStart;
            final int offset = tokenStart.getStartIndex();
            final int end = tokenEnd.getStopIndex() + 1;
            if (end > offset) {
                codeArea.setStyle(offset, end, STYLE_ERROR);
            }
            return;
        }
        //special case for functions
        if (prc instanceof CQLParser.ExpressionTermContext) {
            final CQLParser.ExpressionTermContext ctx = (CQLParser.ExpressionTermContext) prc;
            if (ctx.NAME() != null && ctx.LPAREN() != null) {
                final int nbChild = tree.getChildCount();
                for (int i = 0; i < nbChild; i++) {
                    final ParseTree pt = tree.getChild(i);
                    if (pt instanceof TerminalNode && ((TerminalNode) pt).getSymbol().getType() == CQLLexer.NAME) {
                        final TerminalNode tn = (TerminalNode) pt;
                        // if index<0 = missing token
                        final Token token = tn.getSymbol();
                        final int offset = token.getStartIndex();
                        final int end = token.getStopIndex() + 1;
                        if (end > offset) {
                            codeArea.setStyle(offset, end, STYLE_FUNCTION);
                        }
                    } else {
                        syntaxHighLight(pt);
                    }
                }
                return;
            }
        }
    }
    if (tree instanceof TerminalNode) {
        final TerminalNode tn = (TerminalNode) tree;
        // if index<0 = missing token
        final Token token = tn.getSymbol();
        final int offset = token.getStartIndex();
        final int end = token.getStopIndex() + 1;
        switch(token.getType()) {
            case CQLLexer.COMMA:
            case CQLLexer.UNARY:
            case CQLLexer.MULT:
                codeArea.setStyle(offset, end, STYLE_DEFAULT);
                break;
            // EXpressions -------------------------------------------------
            case CQLLexer.TEXT:
            case CQLLexer.INT:
            case CQLLexer.FLOAT:
            case CQLLexer.DATE:
            case CQLLexer.DURATION_P:
            case CQLLexer.DURATION_T:
            case CQLLexer.POINT:
            case CQLLexer.LINESTRING:
            case CQLLexer.POLYGON:
            case CQLLexer.MPOINT:
            case CQLLexer.MLINESTRING:
            case CQLLexer.MPOLYGON:
                codeArea.setStyle(offset, end, STYLE_LITERAL);
                break;
            case CQLLexer.PROPERTY_NAME:
                codeArea.setStyle(offset, end, STYLE_PROPERTY);
                break;
            case CQLLexer.NAME:
                if (tree.getChildCount() == 0) {
                    //property name
                    codeArea.setStyle(offset, end, STYLE_PROPERTY);
                } else {
                    //function name
                    codeArea.setStyle(offset, end, STYLE_FUNCTION);
                }
                break;
            case CQLLexer.RPAREN:
            case CQLLexer.LPAREN:
                codeArea.setStyle(offset, end, STYLE_PARENTHESE);
                break;
            case CQLLexer.COMPARE:
            case CQLLexer.LIKE:
            case CQLLexer.IS:
            case CQLLexer.BETWEEN:
            case CQLLexer.IN:
                codeArea.setStyle(offset, end, STYLE_OPERATOR);
                break;
            case CQLLexer.AND:
            case CQLLexer.OR:
            case CQLLexer.NOT:
                codeArea.setStyle(offset, end, STYLE_BINARY);
                break;
            case CQLLexer.BBOX:
            case CQLLexer.BEYOND:
            case CQLLexer.CONTAINS:
            case CQLLexer.CROSSES:
            case CQLLexer.DISJOINT:
            case CQLLexer.DWITHIN:
            case CQLLexer.EQUALS:
            case CQLLexer.INTERSECTS:
            case CQLLexer.OVERLAPS:
            case CQLLexer.TOUCHES:
            case CQLLexer.WITHIN:
                codeArea.setStyle(offset, end, STYLE_BINARY);
                break;
            default:
                codeArea.setStyle(offset, end, STYLE_ERROR);
                break;
        }
    }
    final int nbChild = tree.getChildCount();
    for (int i = 0; i < nbChild; i++) {
        syntaxHighLight(tree.getChild(i));
    }
}
Example 43
Project: hive-master  File: Exec.java View source code
public void execHost(ParserRuleContext ctx, String cmd) {
    try {
        if (trace) {
            trace(ctx, "HOST Command: " + cmd);
        }
        Process p = Runtime.getRuntime().exec(cmd);
        new StreamGobbler(p.getInputStream()).start();
        new StreamGobbler(p.getErrorStream()).start();
        int rc = p.waitFor();
        if (trace) {
            trace(ctx, "HOST Process exit code: " + rc);
        }
        setHostCode(rc);
    } catch (Exception e) {
        setHostCode(1);
        signal(Signal.Type.SQLEXCEPTION);
    }
}
Example 44
Project: iee-master  File: TexTranslator.java View source code
public static String translate(String expression) {
    String result = "";
    ANTLRInputStream input = new ANTLRInputStream(expression);
    MathLexer lexer = new MathLexer(input);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    MathParser parser = new MathParser(tokens);
    parser.setBuildParseTree(true);
    ParserRuleContext tree = parser.statement();
    TexMathVisitor mathVisitor = new TexMathVisitor();
    result = mathVisitor.visit(tree);
    return result;
}
Example 45
Project: monasca-common-master  File: AlarmSubExpression.java View source code
/**
   * Returns an AlarmSubExpression for the {@code expression} string.
   * 
   * @throws IllegalArgumentException if the {@code expression} is invalid
   */
@JsonCreator
public static AlarmSubExpression of(String expression) {
    AlarmExpressionParser parser = new AlarmExpressionParser(new CommonTokenStream(new AlarmExpressionLexer(new ANTLRInputStream(expression))));
    parser.removeErrorListeners();
    parser.addErrorListener(new AlarmExpressionErrorListener());
    parser.setBuildParseTree(true);
    ParserRuleContext tree = parser.start();
    AlarmSubExpressionListener listener = new AlarmSubExpressionListener(true);
    ParseTreeWalker walker = new ParseTreeWalker();
    walker.walk(listener, tree);
    return (AlarmSubExpression) listener.getElements().get(0);
}
Example 46
Project: spaghetti-master  File: TypeParsers.java View source code
private static <T extends ParametrizedReferableTypeNode, R extends AbstractParametrizedTypeNodeReference<T>> R parseParametrizedTypeNodeReference(Locator locator, R reference, TypeResolver resolver, ParserRuleContext typeCtx, ModuleParser.TypeArgumentsContext argsCtx, T type) {
    List<TypeReferenceInternal> arguments = Lists.newArrayList();
    if (argsCtx != null) {
        List<ModuleParser.ReturnTypeContext> returnTypeCtx = argsCtx.returnType();
        if (returnTypeCtx != null) {
            for (ModuleParser.ReturnTypeContext argCtx : returnTypeCtx) {
                arguments.add(parseReturnType(locator, resolver, argCtx));
            }
        }
    }
    if (arguments.size() != type.getTypeParameters().size()) {
        throw new InternalAstParserException(typeCtx, "Type argument count doesn't match number of type parameters");
    }
    reference.getArgumentsInternal().addAll(arguments);
    return reference;
}
Example 47
Project: drools-master  File: ASTBuilderVisitor.java View source code
private BaseNode buildNotCall(ParserRuleContext ctx, BaseNode name, ListNode params) {
    // and the unary tests operator
    if (params.getElements().size() == 1) {
        // if it is a single parameter, we need to check if the type is boolean
        BaseNode param = params.getElements().get(0);
        if (param instanceof UnaryTestNode) {
            return ASTBuilderFactory.newUnaryTestNode(ctx, "not", params);
        } else if (param instanceof BooleanNode) {
            return ASTBuilderFactory.newFunctionInvocationNode(ctx, name, params);
        } else if (param instanceof NameRefNode) {
            return ASTBuilderFactory.newFunctionInvocationNode(ctx, name, params);
        } else if (param instanceof QuantifiedExpressionNode) {
            return ASTBuilderFactory.newFunctionInvocationNode(ctx, name, params);
        } else if (param instanceof InstanceOfNode) {
            return ASTBuilderFactory.newFunctionInvocationNode(ctx, name, params);
        } else if (param instanceof BetweenNode) {
            return ASTBuilderFactory.newFunctionInvocationNode(ctx, name, params);
        } else if (param instanceof InNode) {
            return ASTBuilderFactory.newFunctionInvocationNode(ctx, name, params);
        } else if (param instanceof InfixOpNode && ((InfixOpNode) param).isBoolean()) {
            return ASTBuilderFactory.newFunctionInvocationNode(ctx, name, params);
        } else if (param instanceof RangeNode) {
            return ASTBuilderFactory.newUnaryTestNode(ctx, "not", params);
        } else if (param instanceof DashNode) {
            return ASTBuilderFactory.newUnaryTestNode(ctx, "not", params);
        } else {
            return ASTBuilderFactory.newUnaryTestNode(ctx, "not", params);
        }
    } else {
        return ASTBuilderFactory.newUnaryTestNode(ctx, "not", params);
    }
}
Example 48
Project: ebean-master  File: EqlAdapter.java View source code
private void addExpression(ParserRuleContext ctx) {
    int childCount = ctx.getChildCount();
    if (childCount < 3) {
        throw new IllegalStateException("expecting 3 children for comparison? " + ctx);
    }
    String operator = child(ctx, 1);
    EqlOperator op = operatorMapping.get(operator);
    if (op == null) {
        throw new IllegalStateException("No operator found for " + operator);
    }
    String path = getLeftHandSidePath(ctx);
    String rhs = child(ctx, 2);
    if (path.equals(rhs)) {
        // the 'value operator path' form
        // invert the operator and use LHS as RHS
        op = invert(op);
        rhs = child(ctx, 0);
    }
    // RHS is Path, Literal or Named input parameter
    helper.addExpression(path, op, rhs);
}
Example 49
Project: antlr-java-parser-master  File: AdapterUtil.java View source code
/**
     *
     * @param adapter
     * @param contextList
     * @param operator
     * @param <C> Context Type
     * @return Expression
     */
public static <C> Expression handleExpression(Adapter<Expression, C> adapter, List<C> contextList, BinaryExpr.Operator operator, AdapterParameters adapterParameters) {
    Expression expression = adapter.adapt(contextList.get(0), adapterParameters);
    AdapterUtil.setComments(expression, (ParserRuleContext) contextList.get(0), adapterParameters);
    // This expression represents more than one consecutive OR expression
    if (contextList.size() > 1) {
        BinaryExpr root = new BinaryExpr();
        root.setLeft(expression);
        root.setOperator(operator);
        BinaryExpr currentExpression = root;
        for (int i = 1; i < contextList.size(); i++) {
            Expression rightExpression = adapter.adapt(contextList.get(i), adapterParameters);
            AdapterUtil.setComments(rightExpression, (ParserRuleContext) contextList.get(i), adapterParameters);
            currentExpression.setRight(rightExpression);
            // On the last one, do not create a tail.
            if (i < contextList.size() - 1) {
                BinaryExpr binaryExpr = new BinaryExpr();
                binaryExpr.setLeft(currentExpression);
                binaryExpr.setOperator(operator);
                currentExpression = binaryExpr;
            }
        }
        return currentExpression;
    }
    return expression;
}
Example 50
Project: Illarion-Java-master  File: Utils.java View source code
@Nonnull
private static <T extends Enum<T>> T getEnumValue(@Nullable ParserRuleContext node, @Nonnull Class<T> enumClass, @Nonnull T defaultValue) {
    if (node == null) {
        LOGGER.warn("Expected node for enumerator {} not found.", enumClass.getSimpleName());
        return defaultValue;
    }
    String string = removeQuotes(node.getText());
    try {
        return Enum.valueOf(enumClass, string);
    } catch (IllegalArgumentException e) {
        node.addErrorNode(node.getStart());
        LOGGER.warn("Failed to resolve {} to enumerator {}", string, enumClass.getSimpleName());
        return defaultValue;
    }
}
Example 51
Project: MazeSolver-master  File: SituationActionParser.java View source code
private SituationContext situation(int _p) throws RecognitionException {
    ParserRuleContext _parentctx = _ctx;
    int _parentState = getState();
    SituationContext _localctx = new SituationContext(_ctx, _parentState);
    SituationContext _prevctx = _localctx;
    int _startState = 4;
    enterRecursionRule(_localctx, 4, RULE_situation, _p);
    int _la;
    try {
        int _alt;
        enterOuterAlt(_localctx, 1);
        {
            setState(33);
            switch(_input.LA(1)) {
                case LEFTPAR:
                case NOT:
                    {
                        _localctx = new ParensContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(26);
                        _la = _input.LA(1);
                        if (_la == NOT) {
                            {
                                setState(25);
                                match(NOT);
                            }
                        }
                        setState(28);
                        match(LEFTPAR);
                        setState(29);
                        situation(0);
                        setState(30);
                        match(RIGHTPAR);
                    }
                    break;
                case UP:
                case DOWN:
                case LEFT:
                case RIGHT:
                    {
                        _localctx = new SingleTermContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(32);
                        term();
                    }
                    break;
                default:
                    throw new NoViableAltException(this);
            }
            _ctx.stop = _input.LT(-1);
            setState(43);
            _errHandler.sync(this);
            _alt = getInterpreter().adaptivePredict(_input, 4, _ctx);
            while (_alt != 2 && _alt != org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER) {
                if (_alt == 1) {
                    if (_parseListeners != null)
                        triggerExitRuleEvent();
                    _prevctx = _localctx;
                    {
                        setState(41);
                        switch(getInterpreter().adaptivePredict(_input, 3, _ctx)) {
                            case 1:
                                {
                                    _localctx = new AndContext(new SituationContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_situation);
                                    setState(35);
                                    if (!(precpred(_ctx, 4)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 4)");
                                    setState(36);
                                    match(AND);
                                    setState(37);
                                    situation(5);
                                }
                                break;
                            case 2:
                                {
                                    _localctx = new OrContext(new SituationContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_situation);
                                    setState(38);
                                    if (!(precpred(_ctx, 3)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 3)");
                                    setState(39);
                                    match(OR);
                                    setState(40);
                                    situation(4);
                                }
                                break;
                        }
                    }
                }
                setState(45);
                _errHandler.sync(this);
                _alt = getInterpreter().adaptivePredict(_input, 4, _ctx);
            }
        }
    } catch (RecognitionException re) {
        _localctx.exception = re;
        _errHandler.reportError(this, re);
        _errHandler.recover(this, re);
    } finally {
        unrollRecursionContexts(_parentctx);
    }
    return _localctx;
}
Example 52
Project: protobuf-el-master  File: ProtoFileParser.java View source code
@Override
public void exitBytesFieldOption(final BytesFieldOptionContext ctx) {
    if (ctx.getChildCount() == 3) {
        verifyOptionNameUnique("default", ctx.getStart());
        final FieldDescriptorProto.Builder fieldBuilder = FieldDescriptorProto.Builder.class.cast(scopes.getProtoBuilder());
        final String input = ctx.getChild(2).getText();
        try {
            final String result = protoEscapeBytes(unescapeBytes(input.substring(1, input.length() - 1)));
            fieldBuilder.setDefaultValue(result);
        } catch (final InvalidEscapeSequenceException e) {
            contextLookup.reportInvalidDefaultValue((ParserRuleContext) ctx.getChild(2), e);
        }
    }
}
Example 53
Project: checkstyle-master  File: JavadocDetailNodeParser.java View source code
/**
     * Gets column number from ParseTree node.
     * @param tree
     *        ParseTree node
     * @return column number
     */
private static int getColumn(ParseTree tree) {
    final int column;
    if (tree instanceof TerminalNode) {
        column = ((TerminalNode) tree).getSymbol().getCharPositionInLine();
    } else {
        final ParserRuleContext rule = (ParserRuleContext) tree;
        column = rule.start.getCharPositionInLine();
    }
    return column;
}
Example 54
Project: graphql-java-master  File: GraphqlAntlrToLanguage.java View source code
private List<Comment> getComments(ParserRuleContext ctx) {
    Token start = ctx.getStart();
    if (start != null) {
        int tokPos = start.getTokenIndex();
        List<Token> refChannel = tokens.getHiddenTokensToLeft(tokPos, 2);
        if (refChannel != null) {
            return getCommentOnChannel(refChannel);
        }
    }
    return Collections.emptyList();
}
Example 55
Project: octopus-master  File: OctopusSql.java View source code
public static List<OctopusSqlCommand> parse(String query) {
    ANTLRInputStream input = new ANTLRInputStream(query);
    OctopusSqlLexer lexer = new OctopusSqlLexer(input);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    OctopusSqlParser parser = new OctopusSqlParser(tokens);
    ParserRuleContext tree = parser.ddl();
    ParseTreeWalker walker = new ParseTreeWalker();
    Listener lsnr = new Listener();
    walker.walk(lsnr, tree);
    return lsnr.getSqlCommands();
}
Example 56
Project: incubator-systemml-master  File: PydmlSyntacticValidator.java View source code
@Override
public void enterEveryRule(ParserRuleContext arg0) {
    if (arg0 instanceof StatementContext) {
        if (((StatementContext) arg0).info == null) {
            ((StatementContext) arg0).info = new StatementInfo();
        }
    }
    if (arg0 instanceof FunctionStatementContext) {
        if (((FunctionStatementContext) arg0).info == null) {
            ((FunctionStatementContext) arg0).info = new StatementInfo();
        }
    }
    if (arg0 instanceof ExpressionContext) {
        if (((ExpressionContext) arg0).info == null) {
            ((ExpressionContext) arg0).info = new ExpressionInfo();
        }
    }
    if (arg0 instanceof DataIdentifierContext) {
        if (((DataIdentifierContext) arg0).dataInfo == null) {
            ((DataIdentifierContext) arg0).dataInfo = new ExpressionInfo();
        }
    }
}
Example 57
Project: jetbrick-template-2x-master  File: AstCodeVisitor.java View source code
private void validateInsideOfDirectiveFor(ParserRuleContext ctx, String name) {
    ParserRuleContext p = ctx.getParent();
    while (p != null) {
        if (p instanceof Directive_forContext) {
            return;
        }
        if (p instanceof Directive_elseContext) {
            p = p.getParent();
        }
        p = p.getParent();
    }
    throw new SyntaxException(Errors.DIRECTIVE_OUTSIDE_OF_FOR, name).set(pos(ctx));
}
Example 58
Project: rest.li-master  File: PdlSchemaParser.java View source code
/**
   * Adds additional properties to an existing properties map at the location identified by
   * the given path.
   *
   * This allows for properties defined with paths such as:
   *
   * {@literal @}a.b = "x"
   * {@literal @}a.c = "y"
   *
   * to be merged together into a property map like:
   *
   * { "a": { "b": "x", "c": "y" }}
   *
   * Examples:
   *
   * <pre>
   * existing properties        | path  | value         | result
   * ---------------------------|-------|---------------|----------------------------------------
   * {}                         | a.b.c | true          | { "a": { "b": { "c": true } } }
   * { "a": {} }                | a.b   | true          | { "a": { "b": true } }
   * { "a": {} }                | a.b   | { "z": "x" }  | { "a": { "b": { "z": "x" } } }
   * { "a": { "c": "x"}} }      | a.b   | true          | { "a": { "b": true, "c": "x"} } }
   * { "a": { "b": "x"}} }      | a.b   | "y"           | ParseError "Conflicting property: a.b"
   * </pre>
   *
   * The existing properties are traversed using the given path, adding DataMaps as needed to
   * complete the traversal. If any of data elements in the existing properties along the path are
   * not DataMaps, a ParseError is thrown to report the conflict.
   *
   * @param context provides the parsing context for error reporting purposes.
   * @param existingProperties provides the properties to add to.
   * @param path provides the path of the property to insert.
   * @param value provides the value of the property to insert.
   * @throws ParseException if the path of the properties to add conflicts with data already
   * in the properties map or if a property is already exists at the path.
   */
private void addPropertiesAtPath(ParserRuleContext context, Map<String, Object> existingProperties, Iterable<String> path, Object value) throws ParseException {
    Map<String, Object> current = existingProperties;
    Iterator<String> iter = path.iterator();
    while (iter.hasNext()) {
        String pathPart = iter.next();
        if (iter.hasNext()) {
            if (existingProperties.containsKey(pathPart)) {
                Object val = existingProperties.get(pathPart);
                if (!(val instanceof DataMap)) {
                    throw new ParseException(new ParseError(new ParseErrorLocation(context), "Conflicting property: " + path.toString()));
                }
                current = (DataMap) val;
            } else {
                DataMap next = new DataMap();
                current.put(pathPart, next);
                current = next;
            }
        } else {
            if (current.containsKey(pathPart)) {
                throw new ParseException(new ParseError(new ParseErrorLocation(context), "Property already defined: " + path.toString()));
            } else {
                current.put(pathPart, value);
            }
        }
    }
}
Example 59
Project: Stencil-master  File: StencilInterpreter.java View source code
@Override
Object ref(String name, ParserRuleContext errCtx) {
    //Look for the variable in the local objects
    for (Object object : objects) {
        try {
            return PropertyUtils.getProperty(object, name);
        } catch (IllegalAccessExceptionInvocationTargetException |  e) {
            throw new ExecutionException(e, interpreter.getLocation(errCtx));
        } catch (NoSuchMethodException e) {
        }
    }
    return super.ref(name, errCtx);
}
Example 60
Project: turin-programming-language-master  File: ParseTreeToAst.java View source code
private Expression toAst(TurinParser.PlaceholderUsageContext ctx) {
    ParserRuleContext parent = ctx.getParent();
    String fieldName = null;
    while (parent != null && fieldName == null) {
        if (parent instanceof TurinParser.InTypePropertyDeclarationContext) {
            fieldName = idText(((TurinParser.InTypePropertyDeclarationContext) parent).name);
        } else {
            parent = parent.getParent();
        }
    }
    if (fieldName == null) {
        return new SemanticError("A placeholder should be used only inside in-type property declarations", getPosition(ctx));
    } else {
        Placeholder placeholder = new Placeholder();
        getPositionFrom(placeholder, ctx);
        return placeholder;
    }
}
Example 61
Project: AisLib-master  File: ExpressionFilterParserBase.java View source code
/**
     * Create a filter predicate with will compare the left-hand side to the right-hand side both assumed to be present
     * in the supplied ANTLR context.
     *
     * @param filterPredicateFactoryClass
     * @param filterPredicateFactory
     * @param ctx
     * @param <T>
     * @return
     */
protected static <T> Predicate<T> createFilterPredicateForComparison(Class<? extends FilterPredicateFactory> filterPredicateFactoryClass, FilterPredicateFactory filterPredicateFactory, ParserRuleContext ctx) {
    Predicate<T> filter = null;
    String fieldName = ctx.getStart().getText();
    if (hasCompareTo(ctx)) {
        String operator = invokeCompareTo(ctx).getText();
        if (hasINT(ctx)) {
            Integer rhs = Integer.valueOf(invokeINT(ctx).getText());
            filter = createFilterPredicateForComparison(filterPredicateFactoryClass, filterPredicateFactory, fieldName, operator, rhs);
        } else if (hasNumber(ctx)) {
            Float rhs = Float.valueOf(invokeNumber(ctx).getText());
            filter = createFilterPredicateForComparison(filterPredicateFactoryClass, filterPredicateFactory, fieldName, operator, rhs);
        } else if (hasString(ctx)) {
            /* if (isNamedValue(fieldName)) {
                        filter = createFilterPredicateForComparisonOfNamedValue(filterPredicateFactoryClass, filterPredicateFactory, ctx);
                    } else { */
            ExpressionFilterParser.StringContext stringCtx = invokeString(ctx);
            if (stringCtx.number() != null) {
                Integer rhs = Integer.valueOf(extractString(stringCtx));
                filter = createFilterPredicateForComparison(filterPredicateFactoryClass, filterPredicateFactory, fieldName, operator, rhs);
            } else if (stringCtx.STRING() != null) {
                String rhs = stringCtx.getText();
                filter = createFilterPredicateForComparison(filterPredicateFactoryClass, filterPredicateFactory, fieldName, operator, rhs);
            }
        // }
        } else {
            throw new IllegalArgumentException();
        }
    }
    return filter;
}
Example 62
Project: scotch-lang-master  File: SyntaxTransformer.java View source code
private <N, B extends SyntaxBuilder<N>> N node(ParserRuleContext context, B builder, Consumer<B> consumer) {
    consumer.accept(builder);
    if (context == null) {
        builder.withSourceLocation(NULL_SOURCE);
    } else {
        builder.withSourceLocation(source(context.getStart().getTokenSource().getSourceName(), point(context.getStart().getStartIndex(), context.getStart().getLine(), context.getStart().getCharPositionInLine() + 1), point(context.getStop().getStopIndex() + 1, context.getStop().getLine(), context.getStop().getCharPositionInLine() + 2)));
    }
    return builder.build();
}
Example 63
Project: abstools-master  File: CreateJastAddASTListener.java View source code
private ASTNode<?> setASTNodePosition(ParserRuleContext node, ASTNode<?> value) {
    assert node != null;
    int startline = node.start.getLine();
    int startcol = node.start.getCharPositionInLine();
    // for a completely empty file, CompilationUnit.stop will be null
    int endline = (node.stop == null ? node.start : node.stop).getLine();
    int endcol = (node.stop == null ? node.start : node.stop).getCharPositionInLine();
    value.setPosition(startline, startcol, endline, endcol);
    value.setFileName(this.filename);
    return value;
}
Example 64
Project: systemml-master  File: PydmlSyntacticValidator.java View source code
@Override
public void enterEveryRule(ParserRuleContext arg0) {
    if (arg0 instanceof StatementContext) {
        if (((StatementContext) arg0).info == null) {
            ((StatementContext) arg0).info = new StatementInfo();
        }
    }
    if (arg0 instanceof FunctionStatementContext) {
        if (((FunctionStatementContext) arg0).info == null) {
            ((FunctionStatementContext) arg0).info = new StatementInfo();
        }
    }
    if (arg0 instanceof ExpressionContext) {
        if (((ExpressionContext) arg0).info == null) {
            ((ExpressionContext) arg0).info = new ExpressionInfo();
        }
    }
    if (arg0 instanceof DataIdentifierContext) {
        if (((DataIdentifierContext) arg0).dataInfo == null) {
            ((DataIdentifierContext) arg0).dataInfo = new ExpressionInfo();
        }
    }
}
Example 65
Project: jetbrick-template-1x-master  File: JetTemplateCodeVisitor.java View source code
@Override
public Code visitBlock(BlockContext ctx) {
    int size = ctx.getChildCount();
    BlockCode code = scopeCode.createBlockCode(size);
    if (size == 0)
        return code;
    for (int i = 0; i < size; i++) {
        ParseTree node = ctx.children.get(i);
        Code c = node.accept(this);
        if (node instanceof TextContext) {
            // 文本节点
            TextCode textCode = (TextCode) c;
            if (trimDirectiveLine || trimDirectiveComments) {
                ParseTree prev = (i > 0) ? ctx.children.get(i - 1) : null;
                ParseTree next = (i < size - 1) ? ctx.children.get(i + 1) : null;
                boolean trimLeft;
                boolean keepLeftNewLine = false;
                if (prev == null) {
                    trimLeft = !(ctx.getParent() instanceof TemplateContext);
                } else {
                    trimLeft = prev instanceof DirectiveContext;
                    if (trimLeft) {
                        // inline directive, 对于一个内�的 #if, #for 指令,��有�求�留一个 NewLine
                        // @see https://github.com/subchen/jetbrick-template/issues/25
                        ParserRuleContext directive = (ParserRuleContext) ((DirectiveContext) prev).getChild(0);
                        if (directive instanceof If_directiveContext || directive instanceof For_directiveContext) {
                            if (directive.getStart().getLine() == directive.getStop().getLine()) {
                                // �留一个 NewLine
                                keepLeftNewLine = true;
                            }
                        }
                    }
                }
                boolean trimRight;
                if (next == null) {
                    trimRight = !(ctx.getParent() instanceof TemplateContext);
                } else {
                    trimRight = (next instanceof DirectiveContext);
                }
                // trim 指令两边的注释
                if (trimDirectiveComments) {
                    textCode.trimComments(trimLeft, trimRight, commentsPrefix, commentsSuffix);
                }
                // trim 指令两边的空白内容
                if (trimDirectiveLine) {
                    textCode.trimEmptyLine(trimLeft, trimRight, keepLeftNewLine);
                }
                // trim 掉 #tag 和 #macro 指令最�一个多余的 '\n'
                if (next == null) {
                    if (ctx.getParent() instanceof Tag_directiveContext || ctx.getParent() instanceof Macro_directiveContext) {
                        textCode.trimLastNewLine();
                    }
                }
            }
            if (!textCode.isEmpty()) {
                // 如果有相�内容的Text,则从缓存中读�
                TextCode old = textCache.get(textCode.getText());
                if (old == null) {
                    old = textCode;
                    textCache.put(textCode.getText(), textCode);
                    // add text into field
                    tcc.addField(textCode.getId(), textCode.getText());
                }
                code.addLine(old.toString());
            }
        } else {
            code.addChild(c);
        }
    }
    return code;
}
Example 66
Project: org.pshdl-master  File: PSHDLLangParser.java View source code
private PsExpressionContext psExpression(int _p) throws RecognitionException {
    final ParserRuleContext _parentctx = _ctx;
    final int _parentState = getState();
    PsExpressionContext _localctx = new PsExpressionContext(_ctx, _parentState);
    PsExpressionContext _prevctx = _localctx;
    final int _startState = 26;
    enterRecursionRule(_localctx, 26, RULE_psExpression, _p);
    int _la;
    try {
        int _alt;
        enterOuterAlt(_localctx, 1);
        {
            setState(348);
            switch(getInterpreter().adaptivePredict(_input, 37, _ctx)) {
                case 1:
                    {
                        _localctx = new PsManipContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(339);
                        switch(_input.LA(1)) {
                            case 6:
                                {
                                    setState(335);
                                    psCast();
                                }
                                break;
                            case LOGIC_NEG:
                                {
                                    setState(336);
                                    ((PsManipContext) _localctx).type = match(LOGIC_NEG);
                                }
                                break;
                            case BIT_NEG:
                                {
                                    setState(337);
                                    ((PsManipContext) _localctx).type = match(BIT_NEG);
                                }
                                break;
                            case ARITH_NEG:
                                {
                                    setState(338);
                                    ((PsManipContext) _localctx).type = match(ARITH_NEG);
                                }
                                break;
                            default:
                                throw new NoViableAltException(this);
                        }
                        setState(341);
                        psExpression(16);
                    }
                    break;
                case 2:
                    {
                        _localctx = new PsValueExpContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(342);
                        psValue();
                    }
                    break;
                case 3:
                    {
                        _localctx = new PsArrayInitExpContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(343);
                        psArrayInitSubParens();
                    }
                    break;
                case 4:
                    {
                        _localctx = new PsParensContext(_localctx);
                        _ctx = _localctx;
                        _prevctx = _localctx;
                        setState(344);
                        match(6);
                        setState(345);
                        psExpression(0);
                        setState(346);
                        match(40);
                    }
                    break;
            }
            _ctx.stop = _input.LT(-1);
            setState(391);
            _errHandler.sync(this);
            _alt = getInterpreter().adaptivePredict(_input, 39, _ctx);
            while ((_alt != 2) && (_alt != ATN.INVALID_ALT_NUMBER)) {
                if (_alt == 1) {
                    if (_parseListeners != null) {
                        triggerExitRuleEvent();
                    }
                    _prevctx = _localctx;
                    {
                        setState(389);
                        switch(getInterpreter().adaptivePredict(_input, 38, _ctx)) {
                            case 1:
                                {
                                    _localctx = new PsMulContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(350);
                                    if (!(precpred(_ctx, 15)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 15)");
                                    setState(351);
                                    ((PsMulContext) _localctx).op = _input.LT(1);
                                    _la = _input.LA(1);
                                    if (!(((((_la) & ~0x3f) == 0) && (((1L << _la) & ((1L << MUL) | (1L << DIV) | (1L << MOD) | (1L << POW))) != 0)))) {
                                        ((PsMulContext) _localctx).op = _errHandler.recoverInline(this);
                                    }
                                    consume();
                                    setState(352);
                                    psExpression(16);
                                }
                                break;
                            case 2:
                                {
                                    _localctx = new PsAddContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(353);
                                    if (!(precpred(_ctx, 14)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 14)");
                                    setState(354);
                                    ((PsAddContext) _localctx).op = _input.LT(1);
                                    _la = _input.LA(1);
                                    if (!((_la == PLUS) || (_la == ARITH_NEG))) {
                                        ((PsAddContext) _localctx).op = _errHandler.recoverInline(this);
                                    }
                                    consume();
                                    setState(355);
                                    psExpression(15);
                                }
                                break;
                            case 3:
                                {
                                    _localctx = new PsShiftContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(356);
                                    if (!(precpred(_ctx, 13)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 13)");
                                    setState(357);
                                    ((PsShiftContext) _localctx).op = _input.LT(1);
                                    _la = _input.LA(1);
                                    if (!(((((_la) & ~0x3f) == 0) && (((1L << _la) & ((1L << SLL) | (1L << SRA) | (1L << SRL))) != 0)))) {
                                        ((PsShiftContext) _localctx).op = _errHandler.recoverInline(this);
                                    }
                                    consume();
                                    setState(358);
                                    psExpression(14);
                                }
                                break;
                            case 4:
                                {
                                    _localctx = new PsEqualityCompContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(359);
                                    if (!(precpred(_ctx, 12)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 12)");
                                    setState(360);
                                    ((PsEqualityCompContext) _localctx).op = _input.LT(1);
                                    _la = _input.LA(1);
                                    if (!(((((_la) & ~0x3f) == 0) && (((1L << _la) & ((1L << LESS) | (1L << LESS_EQ) | (1L << GREATER) | (1L << GREATER_EQ))) != 0)))) {
                                        ((PsEqualityCompContext) _localctx).op = _errHandler.recoverInline(this);
                                    }
                                    consume();
                                    setState(361);
                                    psExpression(13);
                                }
                                break;
                            case 5:
                                {
                                    _localctx = new PsEqualityContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(362);
                                    if (!(precpred(_ctx, 11)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 11)");
                                    setState(363);
                                    ((PsEqualityContext) _localctx).op = _input.LT(1);
                                    _la = _input.LA(1);
                                    if (!((_la == EQ) || (_la == NOT_EQ))) {
                                        ((PsEqualityContext) _localctx).op = _errHandler.recoverInline(this);
                                    }
                                    consume();
                                    setState(364);
                                    psExpression(12);
                                }
                                break;
                            case 6:
                                {
                                    _localctx = new PsBitAndContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(365);
                                    if (!(precpred(_ctx, 10)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 10)");
                                    setState(366);
                                    match(AND);
                                    setState(367);
                                    psExpression(11);
                                }
                                break;
                            case 7:
                                {
                                    _localctx = new PsBitXorContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(368);
                                    if (!(precpred(_ctx, 9)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 9)");
                                    setState(369);
                                    match(XOR);
                                    setState(370);
                                    psExpression(9);
                                }
                                break;
                            case 8:
                                {
                                    _localctx = new PsBitOrContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(371);
                                    if (!(precpred(_ctx, 8)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 8)");
                                    setState(372);
                                    match(OR);
                                    setState(373);
                                    psExpression(9);
                                }
                                break;
                            case 9:
                                {
                                    _localctx = new PsConcatContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(374);
                                    if (!(precpred(_ctx, 7)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 7)");
                                    setState(375);
                                    match(12);
                                    setState(376);
                                    psExpression(8);
                                }
                                break;
                            case 10:
                                {
                                    _localctx = new PsBitLogAndContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(377);
                                    if (!(precpred(_ctx, 6)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 6)");
                                    setState(378);
                                    match(LOGI_AND);
                                    setState(379);
                                    psExpression(7);
                                }
                                break;
                            case 11:
                                {
                                    _localctx = new PsBitLogOrContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(380);
                                    if (!(precpred(_ctx, 5)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 5)");
                                    setState(381);
                                    match(LOGI_OR);
                                    setState(382);
                                    psExpression(6);
                                }
                                break;
                            case 12:
                                {
                                    _localctx = new PsTernaryContext(new PsExpressionContext(_parentctx, _parentState));
                                    pushNewRecursionContext(_localctx, _startState, RULE_psExpression);
                                    setState(383);
                                    if (!(precpred(_ctx, 4)))
                                        throw new FailedPredicateException(this, "precpred(_ctx, 4)");
                                    setState(384);
                                    match(24);
                                    setState(385);
                                    psExpression(0);
                                    setState(386);
                                    match(35);
                                    setState(387);
                                    psExpression(5);
                                }
                                break;
                        }
                    }
                }
                setState(393);
                _errHandler.sync(this);
                _alt = getInterpreter().adaptivePredict(_input, 39, _ctx);
            }
        }
    } catch (final RecognitionException re) {
        _localctx.exception = re;
        _errHandler.reportError(this, re);
        _errHandler.recover(this, re);
    } finally {
        unrollRecursionContexts(_parentctx);
    }
    return _localctx;
}
Example 67
Project: JsInteropGenerator-master  File: ParserUtils.java View source code
public static String getType(ParserRuleContext ctx, HashMap<String, String> typeDef) {
    IdlTypeListener listener = new IdlTypeListener(typeDef);
    ParseTreeWalker walker = new ParseTreeWalker();
    walker.walk(listener, ctx);
    return listener.getTypeValue();
}
Example 68
Project: LALU-Assembler-master  File: PostProcessError.java View source code
public ParserRuleContext getCtx() {
    return ctx;
}
Example 69
Project: smooth-build-master  File: LocationHelpers.java View source code
public static CodeLocation locationOf(ParserRuleContext parserRuleContext) {
    return locationOf(parserRuleContext.getStart());
}
Example 70
Project: ameba-master  File: QueryExprListener.java View source code
/**
     * <p>getParentSourceElement.</p>
     *
     * @param node a {@link org.antlr.v4.runtime.ParserRuleContext} object.
     * @return a {@link org.antlr.v4.runtime.ParserRuleContext} object.
     */
protected ParserRuleContext getParentSourceElement(ParserRuleContext node) {
    if (node == null)
        return null;
    ParserRuleContext parent = node.getParent();
    if (parent instanceof QueryParser.SourceElementContext) {
        return parent;
    }
    return getParentSourceElement(parent);
}
Example 71
Project: opensearchserver-master  File: BooleanQueryBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>
	 * The default implementation does nothing.
	 * </p>
	 */
@Override
public void enterEveryRule(ParserRuleContext ctx) {
}
Example 72
Project: damp.ekeko.snippets-master  File: SnippetBaseListener.java View source code
/**
	 * {@inheritDoc}
	 * <p/>
	 * The default implementation does nothing.
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 73
Project: analytics_util-master  File: DateBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 74
Project: beast2-master  File: NewickParserBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(ParserRuleContext ctx) {
}
Example 75
Project: javersion-master  File: PropertyPathBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(ParserRuleContext ctx) {
}
Example 76
Project: mumbler-master  File: Reader.java View source code
private SourceSection createSourceSection(ParserRuleContext ctx) {
    return source.createSection(MumblerParser.VOCABULARY.getDisplayName(ctx.getRuleIndex()), ctx.start.getLine(), ctx.start.getCharPositionInLine(), ctx.stop.getStopIndex() - ctx.start.getStartIndex());
}
Example 77
Project: parseq-master  File: RequestConfigKeyBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(ParserRuleContext ctx) {
}
Example 78
Project: rapidminer-studio-master  File: ExpressionParsingException.java View source code
/**
	 * @return the error context, can be {@code null}
	 */
public ParserRuleContext getErrorContext() {
    return ctx;
}
Example 79
Project: hawkular-alerts-master  File: TagQueryBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(ParserRuleContext ctx) {
}
Example 80
Project: hawkular-metrics-master  File: TagQueryBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(ParserRuleContext ctx) {
}
Example 81
Project: Hydrograph-master  File: ExpressionEditorBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(ParserRuleContext ctx) {
}
Example 82
Project: liferay-portal-master  File: DDMFormValuesQueryBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>
	 * The default implementation does nothing.
	 * </p>
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 83
Project: oql2json-master  File: ItnmDumpJSONWriter.java View source code
@Override
public void enterEveryRule(ParserRuleContext arg0) {
}
Example 84
Project: parkandrideAPI-master  File: WKTBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 85
Project: psl-master  File: PSLBaseListener.java View source code
/**
	 * {@inheritDoc}
	 * <p/>
	 * The default implementation does nothing.
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 86
Project: adl2-core-master  File: AdlTreeParserUtils.java View source code
static Token tokenOf(ParseTree tree) {
    if (tree instanceof TerminalNode) {
        return ((TerminalNode) tree).getSymbol();
    } else if (tree instanceof ParserRuleContext) {
        return ((ParserRuleContext) tree).getStart();
    } else {
        return null;
    }
}
Example 87
Project: CatrobatLanguage-master  File: CatrobatScriptBaseListener.java View source code
@Override
public void enterEveryRule(ParserRuleContext ctx) {
}
Example 88
Project: horizondb-master  File: InsertMsgBuilder.java View source code
/**
     * Extracts a list of values from the specified context. 
     * 
     * @param ctx the context from which the list must be extracted
     * @return a list of values
     */
private static List<String> toList(ParserRuleContext ctx) {
    if (ctx == null) {
        return Collections.emptyList();
    }
    List<String> list = new ArrayList<>();
    for (int i = 0, m = ctx.getChildCount(); i < m; i += 2) {
        list.add(ctx.getChild(i).getText());
    }
    return list;
}
Example 89
Project: MuteGrammar-master  File: MuteBaseListener.java View source code
/**
	 * {@inheritDoc}
	 * <p/>
	 * The default implementation does nothing.
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 90
Project: queryj-master  File: PerCommentLoggingListener.java View source code
/**
     * {@inheritDoc}
     */
@Override
public void enterEveryRule(@NotNull final ParserRuleContext ctx) {
    LogFactory.getLog(PerCommentLoggingListener.class).debug("Entering everyRule: " + ctx.getText());
}
Example 91
Project: QuickProject-master  File: CreateTableBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 92
Project: in-memory-transform-language-master  File: ITLBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 93
Project: paxquery-master  File: XPathBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 94
Project: hppc-master  File: SignatureReplacementVisitor.java View source code
private String getSourceText(ParserRuleContext c) {
    return this.processor.tokenStream.getText(c.getSourceInterval());
}
Example 95
Project: aic-praise-master  File: HOGModelVisitor.java View source code
//
// PROTECTED
//
protected StatementInfo newStatementInfo(Expression statement, ParserRuleContext ctx) {
    StatementInfo result = new StatementInfo(statement, ctx.getText(), ctx.getStart().getLine(), ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex());
    return result;
}
Example 96
Project: aql-java-master  File: AQLBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 97
Project: hawkular-inventory-master  File: Traverser.java View source code
@Override
public void exitEveryRule(ParserRuleContext ctx) {
    super.exitEveryRule(ctx);
    first = false;
}
Example 98
Project: jplag-master  File: JplagPython3Listener.java View source code
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 99
Project: L42-master  File: L42BaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}
Example 100
Project: thrift-master  File: ThriftListener.java View source code
private Location locationOf(ParserRuleContext ctx) {
    return locationOf(ctx.getStart());
}
Example 101
Project: GdxStudio-master  File: JavaBaseListener.java View source code
/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
@Override
public void enterEveryRule(@NotNull ParserRuleContext ctx) {
}