Search in sources :

Example 21 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project elasticsearch by elastic.

the class ParserErrorStrategy method recoverInline.

@Override
public Token recoverInline(final Parser recognizer) throws RecognitionException {
    final Token token = recognizer.getCurrentToken();
    final String message = "unexpected token [" + getTokenErrorDisplay(token) + "]" + " was expecting one of [" + recognizer.getExpectedTokens().toString(recognizer.getVocabulary()) + "].";
    Location location = new Location(sourceName, token.getStartIndex());
    throw location.createError(new IllegalArgumentException(message));
}
Also used : Token(org.antlr.v4.runtime.Token) Location(org.elasticsearch.painless.Location)

Example 22 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project elasticsearch by elastic.

the class Walker method setupPicky.

private void setupPicky(PainlessParser parser) {
    // Diagnostic listener invokes syntaxError on other listeners for ambiguity issues,
    parser.addErrorListener(new DiagnosticErrorListener(true));
    // a second listener to fail the test when the above happens.
    parser.addErrorListener(new BaseErrorListener() {

        @Override
        public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line, final int charPositionInLine, final String msg, final RecognitionException e) {
            throw new AssertionError("line: " + line + ", offset: " + charPositionInLine + ", symbol:" + offendingSymbol + " " + msg);
        }
    });
    // Enable exact ambiguity detection (costly). we enable exact since its the default for
    // DiagnosticErrorListener, life is too short to think about what 'inexact ambiguity' might mean.
    parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);
}
Also used : DiagnosticErrorListener(org.antlr.v4.runtime.DiagnosticErrorListener) BaseErrorListener(org.antlr.v4.runtime.BaseErrorListener) EString(org.elasticsearch.painless.node.EString) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Example 23 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project antlr4 by antlr.

the class ParserInterpreter method parse.

/** Begin parsing at startRuleIndex */
public ParserRuleContext parse(int startRuleIndex) {
    RuleStartState startRuleStartState = atn.ruleToStartState[startRuleIndex];
    rootContext = createInterpreterRuleContext(null, ATNState.INVALID_STATE_NUMBER, startRuleIndex);
    if (startRuleStartState.isLeftRecursiveRule) {
        enterRecursionRule(rootContext, startRuleStartState.stateNumber, startRuleIndex, 0);
    } else {
        enterRule(rootContext, startRuleStartState.stateNumber, startRuleIndex);
    }
    while (true) {
        ATNState p = getATNState();
        switch(p.getStateType()) {
            case ATNState.RULE_STOP:
                // pop; return from rule
                if (_ctx.isEmpty()) {
                    if (startRuleStartState.isLeftRecursiveRule) {
                        ParserRuleContext result = _ctx;
                        Pair<ParserRuleContext, Integer> parentContext = _parentContextStack.pop();
                        unrollRecursionContexts(parentContext.a);
                        return result;
                    } else {
                        exitRule();
                        return rootContext;
                    }
                }
                visitRuleStopState(p);
                break;
            default:
                try {
                    visitState(p);
                } catch (RecognitionException e) {
                    setState(atn.ruleToStopState[p.ruleIndex].stateNumber);
                    getContext().exception = e;
                    getErrorHandler().reportError(this, e);
                    recover(e);
                }
                break;
        }
    }
}
Also used : RuleStartState(org.antlr.v4.runtime.atn.RuleStartState) ATNState(org.antlr.v4.runtime.atn.ATNState)

Example 24 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project antlr4 by antlr.

the class LeftRecursiveRuleTransformer method translateLeftRecursiveRule.

/** Return true if successful */
public boolean translateLeftRecursiveRule(GrammarRootAST ast, LeftRecursiveRule r, String language) {
    //tool.log("grammar", ruleAST.toStringTree());
    GrammarAST prevRuleAST = r.ast;
    String ruleName = prevRuleAST.getChild(0).getText();
    LeftRecursiveRuleAnalyzer leftRecursiveRuleWalker = new LeftRecursiveRuleAnalyzer(prevRuleAST, tool, ruleName, language);
    boolean isLeftRec;
    try {
        //			System.out.println("TESTING ---------------\n"+
        //							   leftRecursiveRuleWalker.text(ruleAST));
        isLeftRec = leftRecursiveRuleWalker.rec_rule();
    } catch (RecognitionException re) {
        // didn't match; oh well
        isLeftRec = false;
    }
    if (!isLeftRec)
        return false;
    // replace old rule's AST; first create text of altered rule
    GrammarAST RULES = (GrammarAST) ast.getFirstChildWithType(ANTLRParser.RULES);
    String newRuleText = leftRecursiveRuleWalker.getArtificialOpPrecRule();
    //		System.out.println("created: "+newRuleText);
    // now parse within the context of the grammar that originally created
    // the AST we are transforming. This could be an imported grammar so
    // we cannot just reference this.g because the role might come from
    // the imported grammar and not the root grammar (this.g)
    RuleAST t = parseArtificialRule(prevRuleAST.g, newRuleText);
    // reuse the name token from the original AST since it refers to the proper source location in the original grammar
    ((GrammarAST) t.getChild(0)).token = ((GrammarAST) prevRuleAST.getChild(0)).getToken();
    // update grammar AST and set rule's AST.
    RULES.setChild(prevRuleAST.getChildIndex(), t);
    r.ast = t;
    // Reduce sets in newly created rule tree
    GrammarTransformPipeline transform = new GrammarTransformPipeline(g, g.tool);
    transform.reduceBlocksToSets(r.ast);
    transform.expandParameterizedLoops(r.ast);
    // Rerun semantic checks on the new rule
    RuleCollector ruleCollector = new RuleCollector(g);
    ruleCollector.visit(t, "rule");
    BasicSemanticChecks basics = new BasicSemanticChecks(g, ruleCollector);
    // disable the assoc element option checks because they are already
    // handled for the pre-transformed rule.
    basics.checkAssocElementOption = false;
    basics.visit(t, "rule");
    // track recursive alt info for codegen
    r.recPrimaryAlts = new ArrayList<LeftRecursiveRuleAltInfo>();
    r.recPrimaryAlts.addAll(leftRecursiveRuleWalker.prefixAndOtherAlts);
    if (r.recPrimaryAlts.isEmpty()) {
        tool.errMgr.grammarError(ErrorType.NO_NON_LR_ALTS, g.fileName, ((GrammarAST) r.ast.getChild(0)).getToken(), r.name);
    }
    r.recOpAlts = new OrderedHashMap<Integer, LeftRecursiveRuleAltInfo>();
    r.recOpAlts.putAll(leftRecursiveRuleWalker.binaryAlts);
    r.recOpAlts.putAll(leftRecursiveRuleWalker.ternaryAlts);
    r.recOpAlts.putAll(leftRecursiveRuleWalker.suffixAlts);
    // walk alt info records and set their altAST to point to appropriate ALT subtree
    // from freshly created AST
    setAltASTPointers(r, t);
    // update Rule to just one alt and add prec alt
    ActionAST arg = (ActionAST) r.ast.getFirstChildWithType(ANTLRParser.ARG_ACTION);
    if (arg != null) {
        r.args = ScopeParser.parseTypedArgList(arg, arg.getText(), g);
        r.args.type = AttributeDict.DictType.ARG;
        r.args.ast = arg;
        // todo: isn't this Rule or something?
        arg.resolver = r.alt[1];
    }
    // these are so $label in action translation works
    for (Pair<GrammarAST, String> pair : leftRecursiveRuleWalker.leftRecursiveRuleRefLabels) {
        GrammarAST labelNode = pair.a;
        GrammarAST labelOpNode = (GrammarAST) labelNode.getParent();
        GrammarAST elementNode = (GrammarAST) labelOpNode.getChild(1);
        LabelElementPair lp = new LabelElementPair(g, labelNode, elementNode, labelOpNode.getType());
        r.alt[1].labelDefs.map(labelNode.getText(), lp);
    }
    // copy to rule from walker
    r.leftRecursiveRuleRefLabels = leftRecursiveRuleWalker.leftRecursiveRuleRefLabels;
    tool.log("grammar", "added: " + t.toStringTree());
    return true;
}
Also used : RuleAST(org.antlr.v4.tool.ast.RuleAST) RuleCollector(org.antlr.v4.semantics.RuleCollector) GrammarAST(org.antlr.v4.tool.ast.GrammarAST) LabelElementPair(org.antlr.v4.tool.LabelElementPair) ActionAST(org.antlr.v4.tool.ast.ActionAST) GrammarTransformPipeline(org.antlr.v4.tool.GrammarTransformPipeline) BasicSemanticChecks(org.antlr.v4.semantics.BasicSemanticChecks) RecognitionException(org.antlr.runtime.RecognitionException)

Example 25 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project L42 by ElvisResearchGroup.

the class Parser method getParser.

public static antlrGenerated.L42Parser getParser(String s) {
    ANTLRInputStream in = new ANTLRInputStream(s);
    antlrGenerated.L42Lexer l = new antlrGenerated.L42Lexer(in);
    /*{
      @Override public void recover(LexerNoViableAltException e) {
        throw new IllegalArgumentException(e); // Bail out
      }
    @Override public void recover(RecognitionException re) {
        throw new IllegalArgumentException(re); // Bail out
      }};*/
    CommonTokenStream t = new CommonTokenStream(l);
    antlrGenerated.L42Parser p = new antlrGenerated.L42Parser(t);
    //    p.setErrorHandler(new BailErrorStrategy());
    return p;
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) L42Lexer(antlrGenerated.L42Lexer) L42Lexer(antlrGenerated.L42Lexer) L42Parser(antlrGenerated.L42Parser) ANTLRInputStream(org.antlr.v4.runtime.ANTLRInputStream) L42Parser(antlrGenerated.L42Parser)

Aggregations

RecognitionException (org.antlr.v4.runtime.RecognitionException)13 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)10 ArrayList (java.util.ArrayList)8 BaseErrorListener (org.antlr.v4.runtime.BaseErrorListener)6 Token (org.antlr.v4.runtime.Token)6 ParseCancellationException (org.antlr.v4.runtime.misc.ParseCancellationException)6 ANTLRInputStream (org.antlr.v4.runtime.ANTLRInputStream)5 RecognitionException (org.antlr.runtime.RecognitionException)4 ParseTree (org.antlr.v4.runtime.tree.ParseTree)4 BoaLexer (boa.parser.BoaLexer)3 BoaParser (boa.parser.BoaParser)3 Expression (com.sri.ai.expresso.api.Expression)3 IOException (java.io.IOException)3 GrammarASTAdaptor (org.antlr.v4.parse.GrammarASTAdaptor)3 NoViableAltException (org.antlr.v4.runtime.NoViableAltException)3 ASPCore2Lexer (at.ac.tuwien.kr.alpha.antlr.ASPCore2Lexer)2 ASPCore2Parser (at.ac.tuwien.kr.alpha.antlr.ASPCore2Parser)2 ParsedProgram (at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram)2 ParsedTreeVisitor (at.ac.tuwien.kr.alpha.grounder.parser.ParsedTreeVisitor)2 Start (boa.compiler.ast.Start)2