Package org.antlr.v4.tool.ast

Examples of org.antlr.v4.tool.ast.GrammarRootAST


    this.g = g;
    this.tool = tool;
  }

  public void process() {
    GrammarRootAST root = g.ast;
    if ( root==null ) return;
        tool.log("grammar", "before: "+root.toStringTree());

        integrateImportedGrammars(g);
    reduceBlocksToSets(root);
        expandParameterizedLoops(root);

        tool.log("grammar", "after: "+root.toStringTree());
  }
View Full Code Here


   *  Side-effects: it removes children from GRAMMAR & RULES nodes
   *                in combined AST.  Anything cut out is dup'd before
   *                adding to lexer to avoid "who's ur daddy" issues
   */
  public GrammarRootAST extractImplicitLexer(Grammar combinedGrammar) {
    GrammarRootAST combinedAST = combinedGrammar.ast;
    //tool.log("grammar", "before="+combinedAST.toStringTree());
    GrammarASTAdaptor adaptor = new GrammarASTAdaptor(combinedAST.token.getInputStream());
    GrammarAST[] elements = combinedAST.getChildren().toArray(new GrammarAST[0]);

    // MAKE A GRAMMAR ROOT and ID
    String lexerName = combinedAST.getChild(0).getText()+"Lexer";
    GrammarRootAST lexerAST =
        new GrammarRootAST(new CommonToken(ANTLRParser.GRAMMAR, "LEXER_GRAMMAR"), combinedGrammar.ast.tokenStream);
    lexerAST.grammarType = ANTLRParser.LEXER;
    lexerAST.token.setInputStream(combinedAST.token.getInputStream());
    lexerAST.addChild((GrammarAST)adaptor.create(ANTLRParser.ID, lexerName));

    // COPY OPTIONS
    GrammarAST optionsRoot =
      (GrammarAST)combinedAST.getFirstChildWithType(ANTLRParser.OPTIONS);
    if ( optionsRoot!=null && optionsRoot.getChildCount()!=0 ) {
      GrammarAST lexerOptionsRoot = (GrammarAST)adaptor.dupNode(optionsRoot);
      lexerAST.addChild(lexerOptionsRoot);
      GrammarAST[] options = optionsRoot.getChildren().toArray(new GrammarAST[0]);
      for (GrammarAST o : options) {
        String optionName = o.getChild(0).getText();
        if ( Grammar.lexerOptions.contains(optionName) &&
           !Grammar.doNotCopyOptionsToLexer.contains(optionName) )
        {
          GrammarAST optionTree = (GrammarAST)adaptor.dupTree(o);
          lexerOptionsRoot.addChild(optionTree);
          lexerAST.setOption(optionName, (GrammarAST)optionTree.getChild(1));
        }
      }
    }

    // COPY all named actions, but only move those with lexer:: scope
    List<GrammarAST> actionsWeMoved = new ArrayList<GrammarAST>();
    for (GrammarAST e : elements) {
      if ( e.getType()==ANTLRParser.AT ) {
        lexerAST.addChild((Tree)adaptor.dupTree(e));
        if ( e.getChild(0).getText().equals("lexer") ) {
          actionsWeMoved.add(e);
        }
      }
    }

    for (GrammarAST r : actionsWeMoved) {
      combinedAST.deleteChild( r );
    }

    GrammarAST combinedRulesRoot =
      (GrammarAST)combinedAST.getFirstChildWithType(ANTLRParser.RULES);
    if ( combinedRulesRoot==null ) return lexerAST;

    // MOVE lexer rules

    GrammarAST lexerRulesRoot =
      (GrammarAST)adaptor.create(ANTLRParser.RULES, "RULES");
    lexerAST.addChild(lexerRulesRoot);
    List<GrammarAST> rulesWeMoved = new ArrayList<GrammarAST>();
    GrammarASTWithOptions[] rules;
    if (combinedRulesRoot.getChildCount() > 0) {
      rules = combinedRulesRoot.getChildren().toArray(new GrammarASTWithOptions[0]);
    }
    else {
      rules = new GrammarASTWithOptions[0];
    }

    for (GrammarASTWithOptions r : rules) {
      String ruleName = r.getChild(0).getText();
      if (Grammar.isTokenName(ruleName)) {
        lexerRulesRoot.addChild((Tree)adaptor.dupTree(r));
        rulesWeMoved.add(r);
      }
    }
    for (GrammarAST r : rulesWeMoved) {
      combinedRulesRoot.deleteChild( r );
    }

    // Will track 'if' from IF : 'if' ; rules to avoid defining new token for 'if'
    List<Pair<GrammarAST,GrammarAST>> litAliases =
      Grammar.getStringLiteralAliasesFromLexerRules(lexerAST);

    Set<String> stringLiterals = combinedGrammar.getStringLiterals();
    // add strings from combined grammar (and imported grammars) into lexer
    // put them first as they are keywords; must resolve ambigs to these rules
//    tool.log("grammar", "strings from parser: "+stringLiterals);
    int insertIndex = 0;
    nextLit:
    for (String lit : stringLiterals) {
      // if lexer already has a rule for literal, continue
      if ( litAliases!=null ) {
        for (Pair<GrammarAST,GrammarAST> pair : litAliases) {
          GrammarAST litAST = pair.b;
          if ( lit.equals(litAST.getText()) ) continue nextLit;
        }
      }
      // create for each literal: (RULE <uniquename> (BLOCK (ALT <lit>))
      String rname = combinedGrammar.getStringLiteralLexerRuleName(lit);
      // can't use wizard; need special node types
      GrammarAST litRule = new RuleAST(ANTLRParser.RULE);
      BlockAST blk = new BlockAST(ANTLRParser.BLOCK);
      AltAST alt = new AltAST(ANTLRParser.ALT);
      TerminalAST slit = new TerminalAST(new CommonToken(ANTLRParser.STRING_LITERAL, lit));
      alt.addChild(slit);
      blk.addChild(alt);
      CommonToken idToken = new CommonToken(ANTLRParser.TOKEN_REF, rname);
      litRule.addChild(new TerminalAST(idToken));
      litRule.addChild(blk);
      lexerRulesRoot.insertChild(insertIndex, litRule);
//      lexerRulesRoot.getChildren().add(0, litRule);
      lexerRulesRoot.freshenParentAndChildIndexes(); // reset indexes and set litRule parent

      // next literal will be added after the one just added
      insertIndex++;
    }

    // TODO: take out after stable if slow
    lexerAST.sanityCheckParentAndChildIndexes();
    combinedAST.sanityCheckParentAndChildIndexes();
//    tool.log("grammar", combinedAST.toTokenString());

        combinedGrammar.tool.log("grammar", "after extract implicit lexer ="+combinedAST.toStringTree());
        combinedGrammar.tool.log("grammar", "lexer ="+lexerAST.toStringTree());

    if ( lexerRulesRoot.getChildCount()==0 return null;
    return lexerAST;
  }
View Full Code Here

      Tool tool = new Tool();
      tool.removeListeners();
      tool.addListener(errorQueue);
      assertEquals(0, errorQueue.size());
      GrammarRootAST grammarRootAST = tool.parseGrammarFromString(gstr);
      assertEquals(0, errorQueue.size());
      Grammar g = tool.createGrammar(grammarRootAST);
      assertEquals(0, errorQueue.size());
      g.fileName = "<string>";
      tool.process(g, false);
View Full Code Here

    GrammarTransformPipeline transform = new GrammarTransformPipeline(g, this);
    transform.process();

    LexerGrammar lexerg;
    GrammarRootAST lexerAST;
    if ( g.ast!=null && g.ast.grammarType== ANTLRParser.COMBINED &&
       !g.ast.hasErrors )
    {
      lexerAST = transform.extractImplicitLexer(g); // alters g.ast
      if ( lexerAST!=null ) {
View Full Code Here

    List<GrammarRootAST> roots = new ArrayList<GrammarRootAST>();
    for (String fileName : fileNames) {
      GrammarAST t = parseGrammar(fileName);
      if ( t==null || t instanceof GrammarASTErrorNode) continue; // came back as error node
      if ( ((GrammarRootAST)t).hasErrors ) continue;
      GrammarRootAST root = (GrammarRootAST)t;
      roots.add(root);
      root.fileName = fileName;
      String grammarName = root.getChild(0).getText();

      GrammarAST tokenVocabNode = findOptionValueAST(root, "tokenVocab");
      // Make grammars depend on any tokenVocab options
      if ( tokenVocabNode!=null ) {
        String vocabName = tokenVocabNode.getText();
        g.addEdge(grammarName, vocabName);
      }
      // add cycle to graph so we always process a grammar if no error
      // even if no dependency
      g.addEdge(grammarName, grammarName);
    }

    List<String> sortedGrammarNames = g.sort();
//    System.out.println("sortedGrammarNames="+sortedGrammarNames);

    List<GrammarRootAST> sortedRoots = new ArrayList<GrammarRootAST>();
    for (String grammarName : sortedGrammarNames) {
      for (GrammarRootAST root : roots) {
        if ( root.getGrammarName().equals(grammarName) ) {
          sortedRoots.add(root);
          break;
        }
      }
    }
View Full Code Here

      if (!file.isAbsolute()) {
        file = new File(inputDirectory, fileName);
      }

      ANTLRFileStream in = new ANTLRFileStream(file.getAbsolutePath(), grammarEncoding);
      GrammarRootAST t = parse(fileName, in);
      return t;
    }
    catch (IOException ioe) {
      errMgr.toolError(ErrorType.CANNOT_OPEN_FILE, ioe, fileName);
    }
View Full Code Here

   *  when creating interpreters.  If you need to access to the lexer
   *  grammar created while processing a combined grammar, use
   *  getImplicitLexer() on returned grammar.
   */
  public Grammar loadGrammar(String fileName) {
    GrammarRootAST grammarRootAST = parseGrammar(fileName);
    final Grammar g = createGrammar(grammarRootAST);
    g.fileName = fileName;
    process(g, false);
    return g;
  }
View Full Code Here

        return null;
      }

      String absolutePath = importedFile.getAbsolutePath();
      ANTLRFileStream in = new ANTLRFileStream(absolutePath, grammarEncoding);
      GrammarRootAST root = parse(g.fileName, in);
      if (root == null) {
        return null;
      }

      imported = createGrammar(root);
      imported.fileName = absolutePath;
      importedGrammars.put(root.getGrammarName(), imported);
    }

    return imported;
  }
View Full Code Here

  }

  /** Same as loadGrammar(fileName) except import vocab from existing lexer */
  private Grammar loadGrammar(final Tool tool, final String fileName,
      final LexerGrammar lexerGrammar) {
    GrammarRootAST grammarRootAST = tool.parseGrammar(fileName);
    final Grammar g = tool.createGrammar(grammarRootAST);
    g.fileName = fileName;
    g.importVocab(lexerGrammar);
    tool.process(g, false);
    return g;
View Full Code Here

  public AltAST addPrecedenceArgToRules(AltAST t, int prec) {
    if ( t==null ) return null;
    // get all top-level rule refs from ALT
    List<GrammarAST> outerAltRuleRefs = t.getNodesWithTypePreorderDFS(IntervalSet.of(RULE_REF));
    for (GrammarAST x : outerAltRuleRefs) {
      RuleRefAST rref = (RuleRefAST)x;
      boolean recursive = rref.getText().equals(ruleName);
      boolean rightmost = rref == outerAltRuleRefs.get(outerAltRuleRefs.size()-1);
      if ( recursive && rightmost ) {
        GrammarAST dummyValueNode = new GrammarAST(new CommonToken(ANTLRParser.INT, ""+prec));
        rref.setOption(LeftRecursiveRuleTransformer.PRECEDENCE_OPTION_NAME, dummyValueNode);
      }
    }
    return t;
  }
View Full Code Here

TOP

Related Classes of org.antlr.v4.tool.ast.GrammarRootAST

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.