Search in sources :

Example 11 with Pair

use of org.antlr.v4.runtime.misc.Pair in project antlr4 by antlr.

the class SemanticPipeline method assignLexerTokenTypes.

void assignLexerTokenTypes(Grammar g, List<GrammarAST> tokensDefs) {
    // put in root, even if imported
    Grammar G = g.getOutermostGrammar();
    for (GrammarAST def : tokensDefs) {
        // tokens { id (',' id)* } so must check IDs not TOKEN_REF
        if (Grammar.isTokenName(def.getText())) {
            G.defineTokenName(def.getText());
        }
    }
    /* Define token types for nonfragment rules which do not include a 'type(...)'
		 * or 'more' lexer command.
		 */
    for (Rule r : g.rules.values()) {
        if (!r.isFragment() && !hasTypeOrMoreCommand(r)) {
            G.defineTokenName(r.name);
        }
    }
    // FOR ALL X : 'xxx'; RULES, DEFINE 'xxx' AS TYPE X
    List<Pair<GrammarAST, GrammarAST>> litAliases = Grammar.getStringLiteralAliasesFromLexerRules(g.ast);
    Set<String> conflictingLiterals = new HashSet<String>();
    if (litAliases != null) {
        for (Pair<GrammarAST, GrammarAST> pair : litAliases) {
            GrammarAST nameAST = pair.a;
            GrammarAST litAST = pair.b;
            if (!G.stringLiteralToTypeMap.containsKey(litAST.getText())) {
                G.defineTokenAlias(nameAST.getText(), litAST.getText());
            } else {
                // oops two literal defs in two rules (within or across modes).
                conflictingLiterals.add(litAST.getText());
            }
        }
        for (String lit : conflictingLiterals) {
            // Remove literal if repeated across rules so it's not
            // found by parser grammar.
            Integer value = G.stringLiteralToTypeMap.remove(lit);
            if (value != null && value > 0 && value < G.typeToStringLiteralList.size() && lit.equals(G.typeToStringLiteralList.get(value))) {
                G.typeToStringLiteralList.set(value, null);
            }
        }
    }
}
Also used : GrammarAST(org.antlr.v4.tool.ast.GrammarAST) Grammar(org.antlr.v4.tool.Grammar) LexerGrammar(org.antlr.v4.tool.LexerGrammar) Rule(org.antlr.v4.tool.Rule) Pair(org.antlr.v4.runtime.misc.Pair) HashSet(java.util.HashSet)

Example 12 with Pair

use of org.antlr.v4.runtime.misc.Pair in project antlr4 by antlr.

the class TestXPath method testError.

protected void testError(String input, String path, String expected, String startRuleName, String parserName, String lexerName) throws Exception {
    Pair<Parser, Lexer> pl = getParserAndLexer(input, parserName, lexerName);
    Parser parser = pl.a;
    ParseTree tree = execStartRule(startRuleName, parser);
    IllegalArgumentException e = null;
    try {
        XPath.findAll(tree, path, parser);
    } catch (IllegalArgumentException iae) {
        e = iae;
    }
    assertNotNull(e);
    assertEquals(expected, e.getMessage());
}
Also used : Lexer(org.antlr.v4.runtime.Lexer) ParseTree(org.antlr.v4.runtime.tree.ParseTree) Parser(org.antlr.v4.runtime.Parser)

Example 13 with Pair

use of org.antlr.v4.runtime.misc.Pair 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;
}
Also used : LeftRecursiveRule(org.antlr.v4.tool.LeftRecursiveRule) Triple(org.antlr.v4.runtime.misc.Triple) LL1Analyzer(org.antlr.v4.runtime.atn.LL1Analyzer) ErrorType(org.antlr.v4.tool.ErrorType) IntervalSet(org.antlr.v4.runtime.misc.IntervalSet) GrammarAST(org.antlr.v4.tool.ast.GrammarAST) Rule(org.antlr.v4.tool.Rule) LeftRecursiveRule(org.antlr.v4.tool.LeftRecursiveRule) ATNState(org.antlr.v4.runtime.atn.ATNState)

Example 14 with Pair

use of org.antlr.v4.runtime.misc.Pair in project antlr4 by antlr.

the class BaseRuntimeTest method testParser.

public void testParser(RuntimeTestDescriptor descriptor) throws Exception {
    mkdir(delegate.getTmpDir());
    Pair<String, String> pair = descriptor.getGrammar();
    ClassLoader cloader = getClass().getClassLoader();
    URL templates = cloader.getResource("org/antlr/v4/test/runtime/templates/" + descriptor.getTarget() + ".test.stg");
    STGroupFile targetTemplates = new STGroupFile(templates, "UTF-8", '<', '>');
    targetTemplates.registerRenderer(String.class, new StringRenderer());
    // write out any slave grammars
    List<Pair<String, String>> slaveGrammars = descriptor.getSlaveGrammars();
    if (slaveGrammars != null) {
        for (Pair<String, String> spair : slaveGrammars) {
            STGroup g = new STGroup('<', '>');
            g.registerRenderer(String.class, new StringRenderer());
            g.importTemplates(targetTemplates);
            ST grammarST = new ST(g, spair.b);
            writeFile(delegate.getTmpDir(), spair.a + ".g4", grammarST.render());
        }
    }
    String grammarName = pair.a;
    String grammar = pair.b;
    STGroup g = new STGroup('<', '>');
    g.importTemplates(targetTemplates);
    g.registerRenderer(String.class, new StringRenderer());
    ST grammarST = new ST(g, grammar);
    grammar = grammarST.render();
    String found = delegate.execParser(grammarName + ".g4", grammar, grammarName + "Parser", grammarName + "Lexer", grammarName + "Listener", grammarName + "Visitor", descriptor.getStartRule(), descriptor.getInput(), descriptor.showDiagnosticErrors());
    if (delegate instanceof SpecialRuntimeTestAssert) {
        ((SpecialRuntimeTestAssert) delegate).assertEqualStrings(descriptor.getErrors(), delegate.getParseErrors());
        ((SpecialRuntimeTestAssert) delegate).assertEqualStrings(descriptor.getOutput(), found);
    } else {
        assertEquals(descriptor.getErrors(), delegate.getParseErrors());
        assertEquals(descriptor.getOutput(), found);
    }
}
Also used : ST(org.stringtemplate.v4.ST) STGroup(org.stringtemplate.v4.STGroup) StringRenderer(org.stringtemplate.v4.StringRenderer) STGroupFile(org.stringtemplate.v4.STGroupFile) URL(java.net.URL) Pair(org.antlr.v4.runtime.misc.Pair)

Example 15 with Pair

use of org.antlr.v4.runtime.misc.Pair in project antlr4 by antlr.

the class BaseRuntimeTest method testLexer.

public void testLexer(RuntimeTestDescriptor descriptor) throws Exception {
    mkdir(delegate.getTmpDir());
    Pair<String, String> pair = descriptor.getGrammar();
    ClassLoader cloader = getClass().getClassLoader();
    URL templates = cloader.getResource("org/antlr/v4/test/runtime/templates/" + descriptor.getTarget() + ".test.stg");
    STGroupFile targetTemplates = new STGroupFile(templates, "UTF-8", '<', '>');
    targetTemplates.registerRenderer(String.class, new StringRenderer());
    // write out any slave grammars
    List<Pair<String, String>> slaveGrammars = descriptor.getSlaveGrammars();
    if (slaveGrammars != null) {
        for (Pair<String, String> spair : slaveGrammars) {
            STGroup g = new STGroup('<', '>');
            g.registerRenderer(String.class, new StringRenderer());
            g.importTemplates(targetTemplates);
            ST grammarST = new ST(g, spair.b);
            writeFile(delegate.getTmpDir(), spair.a + ".g4", grammarST.render());
        }
    }
    String grammarName = pair.a;
    String grammar = pair.b;
    STGroup g = new STGroup('<', '>');
    g.registerRenderer(String.class, new StringRenderer());
    g.importTemplates(targetTemplates);
    ST grammarST = new ST(g, grammar);
    grammar = grammarST.render();
    String found = delegate.execLexer(grammarName + ".g4", grammar, grammarName, descriptor.getInput(), descriptor.showDFA());
    if (delegate instanceof SpecialRuntimeTestAssert) {
        ((SpecialRuntimeTestAssert) delegate).assertEqualStrings(descriptor.getOutput(), found);
        ((SpecialRuntimeTestAssert) delegate).assertEqualStrings(descriptor.getANTLRToolErrors(), delegate.getANTLRToolErrors());
        ((SpecialRuntimeTestAssert) delegate).assertEqualStrings(descriptor.getErrors(), delegate.getParseErrors());
    } else {
        assertEquals(descriptor.getOutput(), found);
        assertEquals(descriptor.getANTLRToolErrors(), delegate.getANTLRToolErrors());
        assertEquals(descriptor.getErrors(), delegate.getParseErrors());
    }
}
Also used : ST(org.stringtemplate.v4.ST) STGroup(org.stringtemplate.v4.STGroup) StringRenderer(org.stringtemplate.v4.StringRenderer) STGroupFile(org.stringtemplate.v4.STGroupFile) URL(java.net.URL) Pair(org.antlr.v4.runtime.misc.Pair)

Aggregations

Pair (org.antlr.v4.runtime.misc.Pair)15 GrammarAST (org.antlr.v4.tool.ast.GrammarAST)10 ArrayList (java.util.ArrayList)8 AltAST (org.antlr.v4.tool.ast.AltAST)7 Lexer (org.antlr.v4.runtime.Lexer)4 Parser (org.antlr.v4.runtime.Parser)4 IntervalSet (org.antlr.v4.runtime.misc.IntervalSet)4 HashMap (java.util.HashMap)3 List (java.util.List)3 GrammarASTAdaptor (org.antlr.v4.parse.GrammarASTAdaptor)3 URL (java.net.URL)2 HashSet (java.util.HashSet)2 LinkedHashMap (java.util.LinkedHashMap)2 CommonToken (org.antlr.runtime.CommonToken)2 RecognitionException (org.antlr.runtime.RecognitionException)2 AltLabelStructDecl (org.antlr.v4.codegen.model.decl.AltLabelStructDecl)2 AttributeDecl (org.antlr.v4.codegen.model.decl.AttributeDecl)2 ContextRuleGetterDecl (org.antlr.v4.codegen.model.decl.ContextRuleGetterDecl)2 ContextRuleListGetterDecl (org.antlr.v4.codegen.model.decl.ContextRuleListGetterDecl)2 ContextRuleListIndexedGetterDecl (org.antlr.v4.codegen.model.decl.ContextRuleListIndexedGetterDecl)2