use of org.antlr.v4.runtime.atn.ATN in project antlr4 by antlr.
the class TestExpectedTokens method testFollowIncluded.
@Test
public void testFollowIncluded() throws Exception {
String gtext = "parser grammar T;\n" + "a : b A ;\n" + "b : B | ;";
Grammar g = new Grammar(gtext);
String atnText = "RuleStart_a_0->s4\n" + "s4-b->RuleStart_b_2\n" + "s5-A->s6\n" + "s6->RuleStop_a_1\n" + "RuleStop_a_1-EOF->s11\n";
checkRuleATN(g, "a", atnText);
atnText = "RuleStart_b_2->BlockStart_9\n" + "BlockStart_9->s7\n" + "BlockStart_9->s8\n" + "s7-B->BlockEnd_10\n" + "s8->BlockEnd_10\n" + "BlockEnd_10->RuleStop_b_3\n" + "RuleStop_b_3->s5\n";
checkRuleATN(g, "b", atnText);
ATN atn = g.getATN();
// From the start of 'b' with empty stack, can only see B and EOF
int blkStartStateNumber = 9;
IntervalSet tokens = atn.getExpectedTokens(blkStartStateNumber, RuleContext.EMPTY);
assertEquals("{<EOF>, B}", tokens.toString(g.getTokenNames()));
// Now call from 'a'
tokens = atn.getExpectedTokens(blkStartStateNumber, new ParserRuleContext(ParserRuleContext.EMPTY, 4));
assertEquals("{A, B}", tokens.toString(g.getTokenNames()));
}
use of org.antlr.v4.runtime.atn.ATN in project antlr4 by antlr.
the class ParserATNFactory method createATN.
@Override
public ATN createATN() {
_createATN(g.rules.values());
assert atn.maxTokenType == g.getMaxTokenType();
addRuleFollowLinks();
addEOFTransitionToStartRules();
ATNOptimizer.optimize(g, atn);
for (Triple<Rule, ATNState, ATNState> pair : preventEpsilonClosureBlocks) {
LL1Analyzer analyzer = new LL1Analyzer(atn);
ATNState blkStart = pair.b;
ATNState blkStop = pair.c;
IntervalSet lookahead = analyzer.LOOK(blkStart, blkStop, null);
if (lookahead.contains(org.antlr.v4.runtime.Token.EPSILON)) {
ErrorType errorType = pair.a instanceof LeftRecursiveRule ? ErrorType.EPSILON_LR_FOLLOW : ErrorType.EPSILON_CLOSURE;
g.tool.errMgr.grammarError(errorType, g.fileName, ((GrammarAST) pair.a.ast.getChild(0)).getToken(), pair.a.name);
}
}
optionalCheck: for (Triple<Rule, ATNState, ATNState> pair : preventEpsilonOptionalBlocks) {
int bypassCount = 0;
for (int i = 0; i < pair.b.getNumberOfTransitions(); i++) {
ATNState startState = pair.b.transition(i).target;
if (startState == pair.c) {
bypassCount++;
continue;
}
LL1Analyzer analyzer = new LL1Analyzer(atn);
if (analyzer.LOOK(startState, pair.c, null).contains(org.antlr.v4.runtime.Token.EPSILON)) {
g.tool.errMgr.grammarError(ErrorType.EPSILON_OPTIONAL, g.fileName, ((GrammarAST) pair.a.ast.getChild(0)).getToken(), pair.a.name);
continue optionalCheck;
}
}
if (bypassCount != 1) {
throw new UnsupportedOperationException("Expected optional block with exactly 1 bypass alternative.");
}
}
return atn;
}
use of org.antlr.v4.runtime.atn.ATN in project antlr4 by antlr.
the class Tool method processNonCombinedGrammar.
public void processNonCombinedGrammar(Grammar g, boolean gencode) {
if (g.ast == null || g.ast.hasErrors)
return;
if (internalOption_PrintGrammarTree)
System.out.println(g.ast.toStringTree());
boolean ruleFail = checkForRuleIssues(g);
if (ruleFail)
return;
int prevErrors = errMgr.getNumErrors();
// MAKE SURE GRAMMAR IS SEMANTICALLY CORRECT (FILL IN GRAMMAR OBJECT)
SemanticPipeline sem = new SemanticPipeline(g);
sem.process();
String language = g.getOptionString("language");
if (!CodeGenerator.targetExists(language)) {
errMgr.toolError(ErrorType.CANNOT_CREATE_TARGET_GENERATOR, language);
return;
}
if (errMgr.getNumErrors() > prevErrors)
return;
// BUILD ATN FROM AST
ATNFactory factory;
if (g.isLexer())
factory = new LexerATNFactory((LexerGrammar) g);
else
factory = new ParserATNFactory(g);
g.atn = factory.createATN();
if (generate_ATN_dot)
generateATNs(g);
// PERFORM GRAMMAR ANALYSIS ON ATN: BUILD DECISION DFAs
AnalysisPipeline anal = new AnalysisPipeline(g);
anal.process();
if (g.tool.getNumErrors() > prevErrors)
return;
// GENERATE CODE
if (gencode) {
CodeGenPipeline gen = new CodeGenPipeline(g);
gen.process();
}
}
use of org.antlr.v4.runtime.atn.ATN in project antlr4 by antlr.
the class ATNOptimizer method optimizeSets.
private static void optimizeSets(Grammar g, ATN atn) {
if (g.isParser()) {
// parser codegen doesn't currently support SetTransition
return;
}
int removedStates = 0;
List<DecisionState> decisions = atn.decisionToState;
for (DecisionState decision : decisions) {
if (decision.ruleIndex >= 0) {
Rule rule = g.getRule(decision.ruleIndex);
if (Character.isLowerCase(rule.name.charAt(0))) {
// parser codegen doesn't currently support SetTransition
continue;
}
}
IntervalSet setTransitions = new IntervalSet();
for (int i = 0; i < decision.getNumberOfTransitions(); i++) {
Transition epsTransition = decision.transition(i);
if (!(epsTransition instanceof EpsilonTransition)) {
continue;
}
if (epsTransition.target.getNumberOfTransitions() != 1) {
continue;
}
Transition transition = epsTransition.target.transition(0);
if (!(transition.target instanceof BlockEndState)) {
continue;
}
if (transition instanceof NotSetTransition) {
// TODO: not yet implemented
continue;
}
if (transition instanceof AtomTransition || transition instanceof RangeTransition || transition instanceof SetTransition) {
setTransitions.add(i);
}
}
// due to min alt resolution policies, can only collapse sequential alts
for (int i = setTransitions.getIntervals().size() - 1; i >= 0; i--) {
Interval interval = setTransitions.getIntervals().get(i);
if (interval.length() <= 1) {
continue;
}
ATNState blockEndState = decision.transition(interval.a).target.transition(0).target;
IntervalSet matchSet = new IntervalSet();
for (int j = interval.a; j <= interval.b; j++) {
Transition matchTransition = decision.transition(j).target.transition(0);
if (matchTransition instanceof NotSetTransition) {
throw new UnsupportedOperationException("Not yet implemented.");
}
IntervalSet set = matchTransition.label();
List<Interval> intervals = set.getIntervals();
int n = intervals.size();
for (int k = 0; k < n; k++) {
Interval setInterval = intervals.get(k);
int a = setInterval.a;
int b = setInterval.b;
if (a != -1 && b != -1) {
for (int v = a; v <= b; v++) {
if (matchSet.contains(v)) {
// TODO: Token is missing (i.e. position in source will not be displayed).
g.tool.errMgr.grammarError(ErrorType.CHARACTERS_COLLISION_IN_SET, g.fileName, null, CharSupport.getANTLRCharLiteralForChar(v), CharSupport.getIntervalSetEscapedString(matchSet));
break;
}
}
}
}
matchSet.addAll(set);
}
Transition newTransition;
if (matchSet.getIntervals().size() == 1) {
if (matchSet.size() == 1) {
newTransition = CodePointTransitions.createWithCodePoint(blockEndState, matchSet.getMinElement());
} else {
Interval matchInterval = matchSet.getIntervals().get(0);
newTransition = CodePointTransitions.createWithCodePointRange(blockEndState, matchInterval.a, matchInterval.b);
}
} else {
newTransition = new SetTransition(blockEndState, matchSet);
}
decision.transition(interval.a).target.setTransition(0, newTransition);
for (int j = interval.a + 1; j <= interval.b; j++) {
Transition removed = decision.removeTransition(interval.a + 1);
atn.removeState(removed.target);
removedStates++;
}
}
}
// System.out.println("ATN optimizer removed " + removedStates + " states by collapsing sets.");
}
use of org.antlr.v4.runtime.atn.ATN in project antlr4 by antlr.
the class ATNOptimizer method optimizeStates.
private static void optimizeStates(ATN atn) {
// System.out.println(atn.states);
List<ATNState> compressed = new ArrayList<ATNState>();
// new state number
int i = 0;
for (ATNState s : atn.states) {
if (s != null) {
compressed.add(s);
// reset state number as we shift to new position
s.stateNumber = i;
i++;
}
}
// System.out.println(compressed);
// System.out.println("ATN optimizer removed " + (atn.states.size() - compressed.size()) + " null states.");
atn.states.clear();
atn.states.addAll(compressed);
}
Aggregations