Search in sources :

Example 1 with NoViableAltException

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

the class ParserATNSimulator method execATN.

/** Performs ATN simulation to compute a predicted alternative based
	 *  upon the remaining input, but also updates the DFA cache to avoid
	 *  having to traverse the ATN again for the same input sequence.

	 There are some key conditions we're looking for after computing a new
	 set of ATN configs (proposed DFA state):
	       * if the set is empty, there is no viable alternative for current symbol
	       * does the state uniquely predict an alternative?
	       * does the state have a conflict that would prevent us from
	         putting it on the work list?

	 We also have some key operations to do:
	       * add an edge from previous DFA state to potentially new DFA state, D,
	         upon current symbol but only if adding to work list, which means in all
	         cases except no viable alternative (and possibly non-greedy decisions?)
	       * collecting predicates and adding semantic context to DFA accept states
	       * adding rule context to context-sensitive DFA accept states
	       * consuming an input symbol
	       * reporting a conflict
	       * reporting an ambiguity
	       * reporting a context sensitivity
	       * reporting insufficient predicates

	 cover these cases:
	    dead end
	    single alt
	    single alt + preds
	    conflict
	    conflict + preds
	 */
protected int execATN(DFA dfa, DFAState s0, TokenStream input, int startIndex, ParserRuleContext outerContext) {
    if (debug || debug_list_atn_decisions) {
        System.out.println("execATN decision " + dfa.decision + " exec LA(1)==" + getLookaheadName(input) + " line " + input.LT(1).getLine() + ":" + input.LT(1).getCharPositionInLine());
    }
    DFAState previousD = s0;
    if (debug)
        System.out.println("s0 = " + s0);
    int t = input.LA(1);
    while (true) {
        // while more work
        DFAState D = getExistingTargetState(previousD, t);
        if (D == null) {
            D = computeTargetState(dfa, previousD, t);
        }
        if (D == ERROR) {
            // if any configs in previous dipped into outer context, that
            // means that input up to t actually finished entry rule
            // at least for SLL decision. Full LL doesn't dip into outer
            // so don't need special case.
            // We will get an error no matter what so delay until after
            // decision; better error message. Also, no reachable target
            // ATN states in SLL implies LL will also get nowhere.
            // If conflict in states that dip out, choose min since we
            // will get error no matter what.
            NoViableAltException e = noViableAlt(input, outerContext, previousD.configs, startIndex);
            input.seek(startIndex);
            int alt = getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext);
            if (alt != ATN.INVALID_ALT_NUMBER) {
                return alt;
            }
            throw e;
        }
        if (D.requiresFullContext && mode != PredictionMode.SLL) {
            // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)
            BitSet conflictingAlts = D.configs.conflictingAlts;
            if (D.predicates != null) {
                if (debug)
                    System.out.println("DFA state has preds in DFA sim LL failover");
                int conflictIndex = input.index();
                if (conflictIndex != startIndex) {
                    input.seek(startIndex);
                }
                conflictingAlts = evalSemanticContext(D.predicates, outerContext, true);
                if (conflictingAlts.cardinality() == 1) {
                    if (debug)
                        System.out.println("Full LL avoided");
                    return conflictingAlts.nextSetBit(0);
                }
                if (conflictIndex != startIndex) {
                    // restore the index so reporting the fallback to full
                    // context occurs with the index at the correct spot
                    input.seek(conflictIndex);
                }
            }
            if (dfa_debug)
                System.out.println("ctx sensitive state " + outerContext + " in " + D);
            boolean fullCtx = true;
            ATNConfigSet s0_closure = computeStartState(dfa.atnStartState, outerContext, fullCtx);
            reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index());
            int alt = execATNWithFullContext(dfa, D, s0_closure, input, startIndex, outerContext);
            return alt;
        }
        if (D.isAcceptState) {
            if (D.predicates == null) {
                return D.prediction;
            }
            int stopIndex = input.index();
            input.seek(startIndex);
            BitSet alts = evalSemanticContext(D.predicates, outerContext, true);
            switch(alts.cardinality()) {
                case 0:
                    throw noViableAlt(input, outerContext, D.configs, startIndex);
                case 1:
                    return alts.nextSetBit(0);
                default:
                    // report ambiguity after predicate evaluation to make sure the correct
                    // set of ambig alts is reported.
                    reportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs);
                    return alts.nextSetBit(0);
            }
        }
        previousD = D;
        if (t != IntStream.EOF) {
            input.consume();
            t = input.LA(1);
        }
    }
}
Also used : DFAState(org.antlr.v4.runtime.dfa.DFAState) NoViableAltException(org.antlr.v4.runtime.NoViableAltException) BitSet(java.util.BitSet)

Example 2 with NoViableAltException

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

the class TestParseTreeMatcher method testPatternMatchesStartRule2.

@Test
public void testPatternMatchesStartRule2() throws Exception {
    String grammar = "grammar X2;\n" + "s : ID '=' expr ';' | expr ';' ;\n" + "expr : ID | INT ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n";
    boolean ok = rawGenerateAndBuildRecognizer("X2.g4", grammar, "X2Parser", "X2Lexer", false);
    assertTrue(ok);
    ParseTreePatternMatcher m = getPatternMatcher("X2");
    boolean failed = false;
    try {
        m.compile("<ID> <ID> ;", m.getParser().getRuleIndex("s"));
    } catch (NoViableAltException e) {
        failed = true;
    }
    assertTrue(failed);
}
Also used : ParseTreePatternMatcher(org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher) NoViableAltException(org.antlr.v4.runtime.NoViableAltException) Test(org.junit.Test)

Example 3 with NoViableAltException

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

the class TestATNInterpreter method testMustTrackPreviousGoodAlt3WithEOF.

@Test(expected = NoViableAltException.class)
public void testMustTrackPreviousGoodAlt3WithEOF() throws Exception {
    LexerGrammar lg = new LexerGrammar("lexer grammar L;\n" + "A : 'a' ;\n" + "B : 'b' ;\n" + "C : 'c' ;\n" + "D : 'd' ;\n");
    Grammar g = new Grammar("parser grammar T;\n" + "a : (A B | A | A B C) EOF;");
    checkMatchedAlt(lg, g, "a", 2);
    checkMatchedAlt(lg, g, "ab", 1);
    checkMatchedAlt(lg, g, "abc", 3);
    try {
        checkMatchedAlt(lg, g, "abd", 1);
    } catch (NoViableAltException re) {
        assertEquals(2, re.getOffendingToken().getTokenIndex());
        assertEquals(4, re.getOffendingToken().getType());
        throw re;
    }
}
Also used : NoViableAltException(org.antlr.v4.runtime.NoViableAltException) Grammar(org.antlr.v4.tool.Grammar) LexerGrammar(org.antlr.v4.tool.LexerGrammar) LexerGrammar(org.antlr.v4.tool.LexerGrammar) Test(org.junit.Test)

Example 4 with NoViableAltException

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

the class TestATNInterpreter method testAmbigAltChooseFirst2WithEOF.

@Test(expected = NoViableAltException.class)
public void testAmbigAltChooseFirst2WithEOF() throws Exception {
    LexerGrammar lg = new LexerGrammar("lexer grammar L;\n" + "A : 'a' ;\n" + "B : 'b' ;\n" + "C : 'c' ;\n" + "D : 'd' ;\n");
    Grammar g = new Grammar("parser grammar T;\n" + "a : (A B | A B | A B C) EOF;");
    checkMatchedAlt(lg, g, "ab", 1);
    checkMatchedAlt(lg, g, "abc", 3);
    try {
        checkMatchedAlt(lg, g, "abd", 1);
    } catch (NoViableAltException re) {
        assertEquals(2, re.getOffendingToken().getTokenIndex());
        assertEquals(4, re.getOffendingToken().getType());
        throw re;
    }
}
Also used : NoViableAltException(org.antlr.v4.runtime.NoViableAltException) Grammar(org.antlr.v4.tool.Grammar) LexerGrammar(org.antlr.v4.tool.LexerGrammar) LexerGrammar(org.antlr.v4.tool.LexerGrammar) Test(org.junit.Test)

Example 5 with NoViableAltException

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

the class TestATNInterpreter method testMustTrackPreviousGoodAlt2WithEOF.

@Test(expected = NoViableAltException.class)
public void testMustTrackPreviousGoodAlt2WithEOF() throws Exception {
    LexerGrammar lg = new LexerGrammar("lexer grammar L;\n" + "A : 'a' ;\n" + "B : 'b' ;\n" + "C : 'c' ;\n" + "D : 'd' ;\n");
    Grammar g = new Grammar("parser grammar T;\n" + "a : (A | A B | A B C) EOF;");
    checkMatchedAlt(lg, g, "a", 1);
    checkMatchedAlt(lg, g, "ab", 2);
    checkMatchedAlt(lg, g, "abc", 3);
    try {
        checkMatchedAlt(lg, g, "abd", 1);
    } catch (NoViableAltException re) {
        assertEquals(2, re.getOffendingToken().getTokenIndex());
        assertEquals(4, re.getOffendingToken().getType());
        throw re;
    }
}
Also used : NoViableAltException(org.antlr.v4.runtime.NoViableAltException) Grammar(org.antlr.v4.tool.Grammar) LexerGrammar(org.antlr.v4.tool.LexerGrammar) LexerGrammar(org.antlr.v4.tool.LexerGrammar) Test(org.junit.Test)

Aggregations

NoViableAltException (org.antlr.v4.runtime.NoViableAltException)12 Test (org.junit.Test)5 Grammar (org.antlr.v4.tool.Grammar)4 LexerGrammar (org.antlr.v4.tool.LexerGrammar)4 BitSet (java.util.BitSet)2 InputMismatchException (org.antlr.v4.runtime.InputMismatchException)2 RecognitionException (org.antlr.v4.runtime.RecognitionException)2 Token (org.antlr.v4.runtime.Token)2 ClawLexer (cx2x.translator.language.parser.ClawLexer)1 ClawParser (cx2x.translator.language.parser.ClawParser)1 IllegalDirectiveException (cx2x.xcodeml.exception.IllegalDirectiveException)1 ParseException (java.text.ParseException)1 FailedPredicateException (org.antlr.v4.runtime.FailedPredicateException)1 ParserRuleContext (org.antlr.v4.runtime.ParserRuleContext)1 TokenStream (org.antlr.v4.runtime.TokenStream)1 ATN (org.antlr.v4.runtime.atn.ATN)1 LexerATNSimulator (org.antlr.v4.runtime.atn.LexerATNSimulator)1 PredictionContextCache (org.antlr.v4.runtime.atn.PredictionContextCache)1 DFA (org.antlr.v4.runtime.dfa.DFA)1 DFAState (org.antlr.v4.runtime.dfa.DFAState)1