Package org.stringtemplate.v4

Examples of org.stringtemplate.v4.ST$AttributeList


      "error(" + ErrorType.LOCAL_CONFLICTS_WITH_RETVAL.code + "): T.g4:3:12: local expr conflicts with return value with same name\n" +
      "error(" + ErrorType.LABEL_CONFLICTS_WITH_RULE.code + "): T.g4:4:4: label expr conflicts with rule with same name\n" +
      "error(" + ErrorType.LABEL_CONFLICTS_WITH_ARG.code + "): T.g4:4:4: label expr conflicts with parameter with same name\n" +
      "error(" + ErrorType.LABEL_CONFLICTS_WITH_RETVAL.code + "): T.g4:4:4: label expr conflicts with return value with same name\n" +
      "error(" + ErrorType.LABEL_CONFLICTS_WITH_LOCAL.code + "): T.g4:4:4: label expr conflicts with local with same name\n";
    ST grammarST = new ST(grammarTemplate);
    grammarST.add("args", "int expr");
    grammarST.add("retvals", "int expr");
    grammarST.add("locals", "int expr");
    grammarST.add("body", "expr=expr");
    testErrors(new String[] { grammarST.render(), expected }, false);
  }
View Full Code Here


      DFAState s,
      int k)
  {
    //System.out.println("walk "+s.stateNumber+" in dfa for decision "+dfa.decisionNumber);
    if ( s.isAcceptState() ) {
      ST dfaST = templates.getInstanceOf("dfaAcceptState");
      dfaST.add("alt", Utils.integer(s.getUniquelyPredictedAlt()));
      return dfaST;
    }

    // the default templates for generating a state and its edges
    // can be an if-then-else structure or a switch
    String dfaStateName = "dfaState";
    String dfaLoopbackStateName = "dfaLoopbackState";
    String dfaOptionalBlockStateName = "dfaOptionalBlockState";
    String dfaEdgeName = "dfaEdge";
    if ( parentGenerator.canGenerateSwitch(s) ) {
      dfaStateName = "dfaStateSwitch";
      dfaLoopbackStateName = "dfaLoopbackStateSwitch";
      dfaOptionalBlockStateName = "dfaOptionalBlockStateSwitch";
      dfaEdgeName = "dfaEdgeSwitch";
    }

    ST dfaST = templates.getInstanceOf(dfaStateName);
    if ( dfa.getNFADecisionStartState().decisionStateType==NFAState.LOOPBACK ) {
      dfaST = templates.getInstanceOf(dfaLoopbackStateName);
    }
    else if ( dfa.getNFADecisionStartState().decisionStateType==NFAState.OPTIONAL_BLOCK_START ) {
      dfaST = templates.getInstanceOf(dfaOptionalBlockStateName);
    }
    dfaST.add("k", Utils.integer(k));
    dfaST.add("stateNumber", Utils.integer(s.stateNumber));
    dfaST.add("semPredState", s.isResolvedWithPredicates());
    /*
    String description = dfa.getNFADecisionStartState().getDescription();
    description = parentGenerator.target.getTargetStringLiteralFromString(description);
    //System.out.println("DFA: "+description+" associated with AST "+dfa.getNFADecisionStartState());
    if ( description!=null ) {
      dfaST.add("description", description);
    }
    */
    int EOTPredicts = NFA.INVALID_ALT_NUMBER;
    DFAState EOTTarget = null;
    //System.out.println("DFA state "+s.stateNumber);
    for (int i = 0; i < s.getNumberOfTransitions(); i++) {
      Transition edge = s.transition(i);
      //System.out.println("edge "+s.stateNumber+"-"+edge.label.toString()+"->"+edge.target.stateNumber);
      if ( edge.label.getAtom()==Label.EOT ) {
        // don't generate a real edge for EOT; track alt EOT predicts
        // generate that prediction in the else clause as default case
        EOTTarget = (DFAState)edge.target;
        EOTPredicts = EOTTarget.getUniquelyPredictedAlt();
        /*
        System.out.println("DFA s"+s.stateNumber+" EOT goes to s"+
                   edge.target.stateNumber+" predicates alt "+
                   EOTPredicts);
        */
        continue;
      }
      ST edgeST = templates.getInstanceOf(dfaEdgeName);
      // If the template wants all the label values delineated, do that
      if ( edgeST.impl.formalArguments.get("labels")!=null ) {
        List<Integer> labels = edge.label.getSet().toList();
        List<String> targetLabels = new ArrayList<String>(labels.size());
        for (int j = 0; j < labels.size(); j++) {
          Integer vI = labels.get(j);
          String label =
            parentGenerator.getTokenTypeAsTargetLabel(vI);
          targetLabels.add(label); // rewrite List element to be name
        }
        edgeST.add("labels", targetLabels);
      }
      else { // else create an expression to evaluate (the general case)
        edgeST.add("labelExpr",
                  parentGenerator.genLabelExpr(templates,edge,k));
      }

      // stick in any gated predicates for any edge if not already a pred
      if ( !edge.label.isSemanticPredicate() ) {
        DFAState target = (DFAState)edge.target;
        SemanticContext preds =
          target.getGatedPredicatesInNFAConfigurations();
        if ( preds!=null ) {
          //System.out.println("preds="+target.getGatedPredicatesInNFAConfigurations());
          ST predST = preds.genExpr(parentGenerator,
                              parentGenerator.getTemplates(),
                              dfa);
          edgeST.add("predicates", predST);
        }
      }

      ST targetST =
        walkFixedDFAGeneratingStateMachine(templates,
                           dfa,
                           (DFAState)edge.target,
                           k+1);
      edgeST.add("targetState", targetST);
      dfaST.add("edges", edgeST);
      /*
      System.out.println("back to DFA "+
                 dfa.decisionNumber+"."+s.stateNumber);
                 */
    }

    // HANDLE EOT EDGE
    if ( EOTPredicts!=NFA.INVALID_ALT_NUMBER ) {
      // EOT unique predicts an alt
      dfaST.add("eotPredictsAlt", Utils.integer(EOTPredicts));
    }
    else if ( EOTTarget!=null && EOTTarget.getNumberOfTransitions()>0 ) {
      // EOT state has transitions so must split on predicates.
      // Generate predicate else-if clauses and then generate
      // NoViableAlt exception as else clause.
      // Note: these predicates emanate from the EOT target state
      // rather than the current DFAState s so the error message
      // might be slightly misleading if you are looking at the
      // state number.  Predicates emanating from EOT targets are
      // hoisted up to the state that has the EOT edge.
      for (int i = 0; i < EOTTarget.getNumberOfTransitions(); i++) {
        Transition predEdge = EOTTarget.transition(i);
        ST edgeST = templates.getInstanceOf(dfaEdgeName);
        edgeST.add("labelExpr",
                  parentGenerator.genSemanticPredicateExpr(templates,predEdge));
        // the target must be an accept state
        //System.out.println("EOT edge");
        ST targetST =
          walkFixedDFAGeneratingStateMachine(templates,
                             dfa,
                             (DFAState)predEdge.target,
                             k+1);
        edgeST.add("targetState", targetST);
View Full Code Here

        // add output vocab file; e.g., T.tokens. This is always generated to
        // the base output directory, which will be just . if there is no -o option
        //
    files.add(getOutputFile(generator.getVocabFileName()));
        // are we generating a .h file?
        ST headerExtST = null;
        ST extST = generator.getTemplates().getInstanceOf("codeFileExtension");
        if (generator.getTemplates().isDefined("headerFile")) {
            headerExtST = generator.getTemplates().getInstanceOf("headerFileExtension");
            String suffix = Grammar.getGrammarTypeToFileNameSuffix(g.getType());
            String fileName = g.name + suffix + headerExtST.render();
            files.add(getOutputFile(fileName));
        }
        if ( g.isCombined() ) {
            // add autogenerated lexer; e.g., TLexer.java TLexer.h TLexer.tokens

            String suffix = Grammar.getGrammarTypeToFileNameSuffix(ANTLRParser.LEXER);
            String lexer = g.name + suffix + extST.render();
            files.add(getOutputFile(lexer));
            String lexerTokens = g.name + suffix + CodeGenerator.VOCAB_FILE_EXTENSION;
            files.add(getOutputFile(lexerTokens));

            // TLexer.h
View Full Code Here

        return files;
    }

    public ST getDependencies() {
        loadDependencyTemplates();
        ST dependenciesST = templates.getInstanceOf("dependencies");
        dependenciesST.add("in", getDependenciesFileList());
        dependenciesST.add("out", getGeneratedFileList());
        dependenciesST.add("grammarFileName", g.fileName);
        return dependenciesST;
    }
View Full Code Here

     * </p>
     * @param message The message to send to Maven.
     */
    @Override
    public void error(ANTLRMessage message) {
        ST msgST = tool.errMgr.getMessageTemplate(message);
        String outputMsg = msgST.render();
        if (tool.errMgr.formatWantsSingleLineMessage()) {
            outputMsg = outputMsg.replace('\n', ' ');
        }

        log.error(outputMsg);
View Full Code Here

     * </p>
     * @param message
     */
    @Override
    public void warning(ANTLRMessage message) {
        ST msgST = tool.errMgr.getMessageTemplate(message);
        String outputMsg = msgST.render();
        if (tool.errMgr.formatWantsSingleLineMessage()) {
            outputMsg = outputMsg.replace('\n', ' ');
        }

        log.warn(outputMsg);
View Full Code Here

    // Insert code in front of each primary alt to create specialized ctx if there was a label
    for (int i = 0; i < primaryAltsCode.size(); i++) {
      LeftRecursiveRuleAltInfo altInfo = r.recPrimaryAlts.get(i);
      if ( altInfo.altLabel==null ) continue;
      ST altActionST = codegenTemplates.getInstanceOf("recRuleReplaceContext");
      altActionST.add("ctxName", Utils.capitalize(altInfo.altLabel));
      Action altAction =
        new Action(delegate, function.altLabelCtxs.get(altInfo.altLabel), altActionST);
      CodeBlockForAlt alt = primaryAltsCode.get(i);
      alt.insertOp(0, altAction);
    }

    // Insert code to set ctx.stop after primary block and before op * loop
    ST setStopTokenAST = codegenTemplates.getInstanceOf("recRuleSetStopToken");
    Action setStopTokenAction = new Action(delegate, function.ruleCtx, setStopTokenAST);
    outerAlt.insertOp(1, setStopTokenAction);

    // Insert code to set _prevctx at start of * loop
    ST setPrevCtx = codegenTemplates.getInstanceOf("recRuleSetPrevCtx");
    Action setPrevCtxAction = new Action(delegate, function.ruleCtx, setPrevCtx);
    opAltStarBlock.addIterationOp(setPrevCtxAction);

    // Insert code in front of each op alt to create specialized ctx if there was an alt label
    for (int i = 0; i < opAltsCode.size(); i++) {
      ST altActionST;
      LeftRecursiveRuleAltInfo altInfo = r.recOpAlts.getElement(i);
      String templateName;
      if ( altInfo.altLabel!=null ) {
        templateName = "recRuleLabeledAltStartAction";
        altActionST = codegenTemplates.getInstanceOf(templateName);
        altActionST.add("currentAltLabel", altInfo.altLabel);
      }
      else {
        templateName = "recRuleAltStartAction";
        altActionST = codegenTemplates.getInstanceOf(templateName);
        altActionST.add("ctxName", Utils.capitalize(r.name));
      }
      altActionST.add("ruleName", r.name);
      // add label of any lr ref we deleted
      altActionST.add("label", altInfo.leftRecursiveRuleRefLabel);
      if (altActionST.impl.formalArguments.containsKey("isListLabel")) {
        altActionST.add("isListLabel", altInfo.isListLabel);
      }
      else if (altInfo.isListLabel) {
        delegate.getGenerator().tool.errMgr.toolError(ErrorType.CODE_TEMPLATE_ARG_ISSUE, templateName, "isListLabel");
      }
      Action altAction =
View Full Code Here

    // CREATE TEMPLATE FOR THIS OUTPUT OBJECT
    Class<? extends OutputModelObject> cl = omo.getClass();
    String templateName = cl.getSimpleName();
    if ( templateName == null ) {
      tool.errMgr.toolError(ErrorType.NO_MODEL_TO_TEMPLATE_MAPPING, cl.getSimpleName());
      return new ST("["+templateName+" invalid]");
    }
    ST st = templates.getInstanceOf(templateName);
    if ( st == null ) {
      tool.errMgr.toolError(ErrorType.CODE_GEN_TEMPLATES_INCOMPLETE, templateName);
      return new ST("["+templateName+" invalid]");
    }
    if ( st.impl.formalArguments == null ) {
      tool.errMgr.toolError(ErrorType.CODE_TEMPLATE_ARG_ISSUE, templateName, "<none>");
      return st;
    }

    Map<String,FormalArgument> formalArgs = st.impl.formalArguments;

    // PASS IN OUTPUT MODEL OBJECT TO TEMPLATE AS FIRST ARG
    Set<String> argNames = formalArgs.keySet();
    Iterator<String> arg_it = argNames.iterator();
    String modelArgName = arg_it.next(); // ordered so this is first arg
    st.add(modelArgName, omo);

    // COMPUTE STs FOR EACH NESTED MODEL OBJECT MARKED WITH @ModelElement AND MAKE ST ATTRIBUTE
    Set<String> usedFieldNames = new HashSet<String>();
    Field fields[] = cl.getFields();
    for (Field fi : fields) {
      ModelElement annotation = fi.getAnnotation(ModelElement.class);
      if (annotation == null) {
        continue;
      }

      String fieldName = fi.getName();

      if (!usedFieldNames.add(fieldName)) {
        tool.errMgr.toolError(ErrorType.INTERNAL_ERROR, "Model object " + omo.getClass().getSimpleName() + " has multiple fields named '" + fieldName + "'");
        continue;
      }

      // Just don't set @ModelElement fields w/o formal arg in target ST
      if ( formalArgs.get(fieldName)==null ) continue;

      try {
        Object o = fi.get(omo);
        if ( o instanceof OutputModelObject ) {  // SINGLE MODEL OBJECT?
          OutputModelObject nestedOmo = (OutputModelObject)o;
          ST nestedST = walk(nestedOmo);
//          System.out.println("set ModelElement "+fieldName+"="+nestedST+" in "+templateName);
          st.add(fieldName, nestedST);
        }
        else if ( o instanceof Collection || o instanceof OutputModelObject[] ) {
          // LIST OF MODEL OBJECTS?
          if ( o instanceof OutputModelObject[] ) {
            o = Arrays.asList((OutputModelObject[])o);
          }
          Collection<?> nestedOmos = (Collection<?>)o;
          for (Object nestedOmo : nestedOmos) {
            if ( nestedOmo==null ) continue;
            ST nestedST = walk((OutputModelObject)nestedOmo);
//            System.out.println("set ModelElement "+fieldName+"="+nestedST+" in "+templateName);
            st.add(fieldName, nestedST);
          }
        }
        else if ( o instanceof Map ) {
          Map<?, ?> nestedOmoMap = (Map<?, ?>)o;
          Map<Object, ST> m = new LinkedHashMap<Object, ST>();
          for (Map.Entry<?, ?> entry : nestedOmoMap.entrySet()) {
            ST nestedST = walk((OutputModelObject)entry.getValue());
//            System.out.println("set ModelElement "+fieldName+"="+nestedST+" in "+templateName);
            m.put(entry.getKey(), nestedST);
          }
          st.add(fieldName, m);
        }
View Full Code Here

  }

  public String getDOT(DFA dfa, boolean isLexer) {
    if ( dfa.s0==null return null;

    ST dot = stlib.getInstanceOf("dfa");
    dot.add("name", "DFA"+dfa.decision);
    dot.add("startState", dfa.s0.stateNumber);
//    dot.add("useBox", Tool.internalOption_ShowATNConfigsInDFA);
    dot.add("rankdir", rankdir);

    // define stop states first; seems to be a bug in DOT where doublecircle
    for (DFAState d : dfa.states.keySet()) {
      if ( !d.isAcceptState ) continue;
      ST st = stlib.getInstanceOf("stopstate");
      st.add("name", "s"+d.stateNumber);
      st.add("label", getStateLabel(d));
      dot.add("states", st);
    }

    for (DFAState d : dfa.states.keySet()) {
      if ( d.isAcceptState ) continue;
      if ( d.stateNumber == Integer.MAX_VALUE ) continue;
      ST st = stlib.getInstanceOf("state");
      st.add("name", "s"+d.stateNumber);
      st.add("label", getStateLabel(d));
      dot.add("states", st);
    }

    for (DFAState d : dfa.states.keySet()) {
      if ( d.edges!=null ) {
        for (int i = 0; i < d.edges.length; i++) {
          DFAState target = d.edges[i];
          if ( target==null) continue;
          if ( target.stateNumber == Integer.MAX_VALUE ) continue;
          int ttype = i-1; // we shift up for EOF as -1 for parser
          String label = String.valueOf(ttype);
          if ( isLexer ) label = "'"+getEdgeLabel(String.valueOf((char) i))+"'";
          else if ( grammar!=null ) label = grammar.getTokenDisplayName(ttype);
          ST st = stlib.getInstanceOf("edge");
          st.add("label", label);
          st.add("src", "s"+d.stateNumber);
          st.add("target", "s"+target.stateNumber);
          st.add("arrowhead", arrowhead);
          dot.add("edges", st);
        }
      }
    }
View Full Code Here

  public String getLoopCounter(GrammarAST ast) {
    return "cnt"+ ast.token.getTokenIndex();
  }

  public String getListLabel(String label) {
    ST st = getTemplates().getInstanceOf("ListLabelName");
    st.add("label", label);
    return st.render();
  }
View Full Code Here

TOP

Related Classes of org.stringtemplate.v4.ST$AttributeList

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.