Search in sources :

Example 1 with Attribute

use of org.antlr.v4.tool.Attribute in project antlr4 by antlr.

the class ActionTranslator method attr.

@Override
public void attr(String expr, Token x) {
    gen.g.tool.log("action-translator", "attr " + x);
    Attribute a = node.resolver.resolveToAttribute(x.getText(), node);
    if (a != null) {
        switch(a.dict.type) {
            case ARG:
                chunks.add(new ArgRef(nodeContext, x.getText()));
                break;
            case RET:
                chunks.add(new RetValueRef(rf.ruleCtx, x.getText()));
                break;
            case LOCAL:
                chunks.add(new LocalRef(nodeContext, x.getText()));
                break;
            case PREDEFINED_RULE:
                chunks.add(getRulePropertyRef(x));
                break;
        }
    }
    if (node.resolver.resolvesToToken(x.getText(), node)) {
        // $label
        chunks.add(new TokenRef(nodeContext, getTokenLabel(x.getText())));
        return;
    }
    if (node.resolver.resolvesToLabel(x.getText(), node)) {
        // $x for x=ID etc...
        chunks.add(new LabelRef(nodeContext, getTokenLabel(x.getText())));
        return;
    }
    if (node.resolver.resolvesToListLabel(x.getText(), node)) {
        // $ids for ids+=ID etc...
        chunks.add(new ListLabelRef(nodeContext, x.getText()));
        return;
    }
    Rule r = factory.getGrammar().getRule(x.getText());
    if (r != null) {
        // $r for r rule ref
        chunks.add(new LabelRef(nodeContext, getRuleLabel(x.getText())));
    }
}
Also used : ListLabelRef(org.antlr.v4.codegen.model.chunk.ListLabelRef) Attribute(org.antlr.v4.tool.Attribute) TokenRef(org.antlr.v4.codegen.model.chunk.TokenRef) QRetValueRef(org.antlr.v4.codegen.model.chunk.QRetValueRef) RetValueRef(org.antlr.v4.codegen.model.chunk.RetValueRef) Rule(org.antlr.v4.tool.Rule) ArgRef(org.antlr.v4.codegen.model.chunk.ArgRef) LabelRef(org.antlr.v4.codegen.model.chunk.LabelRef) ListLabelRef(org.antlr.v4.codegen.model.chunk.ListLabelRef) LocalRef(org.antlr.v4.codegen.model.chunk.LocalRef)

Example 2 with Attribute

use of org.antlr.v4.tool.Attribute in project antlr4 by antlr.

the class TestScopeParsing method testArgs.

@Test
public void testArgs() throws Exception {
    Grammar dummy = new Grammar("grammar T; a:'a';");
    LinkedHashMap<String, Attribute> attributes = ScopeParser.parseTypedArgList(null, input, dummy).attributes;
    List<String> out = new ArrayList<>();
    for (String arg : attributes.keySet()) {
        Attribute attr = attributes.get(arg);
        out.add(attr.toString());
    }
    String actual = Utils.join(out.toArray(), ", ");
    assertEquals(output, actual);
}
Also used : Attribute(org.antlr.v4.tool.Attribute) ArrayList(java.util.ArrayList) Grammar(org.antlr.v4.tool.Grammar) Test(org.junit.Test)

Example 3 with Attribute

use of org.antlr.v4.tool.Attribute in project antlr4 by antlr.

the class SemanticPipeline method process.

public void process() {
    if (g.ast == null)
        return;
    // COLLECT RULE OBJECTS
    RuleCollector ruleCollector = new RuleCollector(g);
    ruleCollector.process(g.ast);
    // DO BASIC / EASY SEMANTIC CHECKS
    int prevErrors = g.tool.errMgr.getNumErrors();
    BasicSemanticChecks basics = new BasicSemanticChecks(g, ruleCollector);
    basics.process();
    if (g.tool.errMgr.getNumErrors() > prevErrors)
        return;
    // TRANSFORM LEFT-RECURSIVE RULES
    prevErrors = g.tool.errMgr.getNumErrors();
    LeftRecursiveRuleTransformer lrtrans = new LeftRecursiveRuleTransformer(g.ast, ruleCollector.rules.values(), g);
    lrtrans.translateLeftRecursiveRules();
    // don't continue if we got errors during left-recursion elimination
    if (g.tool.errMgr.getNumErrors() > prevErrors)
        return;
    // STORE RULES IN GRAMMAR
    for (Rule r : ruleCollector.rules.values()) {
        g.defineRule(r);
    }
    // COLLECT SYMBOLS: RULES, ACTIONS, TERMINALS, ...
    SymbolCollector collector = new SymbolCollector(g);
    collector.process(g.ast);
    // CHECK FOR SYMBOL COLLISIONS
    SymbolChecks symcheck = new SymbolChecks(g, collector);
    // side-effect: strip away redef'd rules.
    symcheck.process();
    for (GrammarAST a : collector.namedActions) {
        g.defineAction(a);
    }
    // LINK (outermost) ALT NODES WITH Alternatives
    for (Rule r : g.rules.values()) {
        for (int i = 1; i <= r.numberOfAlts; i++) {
            r.alt[i].ast.alt = r.alt[i];
        }
    }
    // ASSIGN TOKEN TYPES
    g.importTokensFromTokensFile();
    if (g.isLexer()) {
        assignLexerTokenTypes(g, collector.tokensDefs);
    } else {
        assignTokenTypes(g, collector.tokensDefs, collector.tokenIDRefs, collector.terminals);
    }
    symcheck.checkForModeConflicts(g);
    assignChannelTypes(g, collector.channelDefs);
    // CHECK RULE REFS NOW (that we've defined rules in grammar)
    symcheck.checkRuleArgs(g, collector.rulerefs);
    identifyStartRules(collector);
    symcheck.checkForQualifiedRuleIssues(g, collector.qualifiedRulerefs);
    // don't continue if we got symbol errors
    if (g.tool.getNumErrors() > 0)
        return;
    // CHECK ATTRIBUTE EXPRESSIONS FOR SEMANTIC VALIDITY
    AttributeChecks.checkAllAttributeExpressions(g);
    UseDefAnalyzer.trackTokenRuleRefsInActions(g);
}
Also used : GrammarAST(org.antlr.v4.tool.ast.GrammarAST) LeftRecursiveRuleTransformer(org.antlr.v4.analysis.LeftRecursiveRuleTransformer) Rule(org.antlr.v4.tool.Rule)

Example 4 with Attribute

use of org.antlr.v4.tool.Attribute in project antlr4 by antlr.

the class OutputModelWalker method walk.

public ST walk(OutputModelObject omo, boolean header) {
    // 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]");
    }
    if (header)
        templateName += "Header";
    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();
    // ordered so this is first arg
    String modelArgName = arg_it.next();
    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, header);
                //					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, header);
                    //						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(), header);
                    //						System.out.println("set ModelElement "+fieldName+"="+nestedST+" in "+templateName);
                    m.put(entry.getKey(), nestedST);
                }
                st.add(fieldName, m);
            } else if (o != null) {
                tool.errMgr.toolError(ErrorType.INTERNAL_ERROR, "not recognized nested model element: " + fieldName);
            }
        } catch (IllegalAccessException iae) {
            tool.errMgr.toolError(ErrorType.CODE_TEMPLATE_ARG_ISSUE, templateName, fieldName);
        }
    }
    //st.impl.dump();
    return st;
}
Also used : ST(org.stringtemplate.v4.ST) OutputModelObject(org.antlr.v4.codegen.model.OutputModelObject) LinkedHashMap(java.util.LinkedHashMap) FormalArgument(org.stringtemplate.v4.compiler.FormalArgument) Field(java.lang.reflect.Field) ModelElement(org.antlr.v4.codegen.model.ModelElement) Collection(java.util.Collection) OutputModelObject(org.antlr.v4.codegen.model.OutputModelObject) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 5 with Attribute

use of org.antlr.v4.tool.Attribute in project antlr4 by antlr.

the class ScopeParser method parse.

public static AttributeDict parse(ActionAST action, String s, char separator, Grammar g) {
    AttributeDict dict = new AttributeDict();
    List<Pair<String, Integer>> decls = splitDecls(s, separator);
    for (Pair<String, Integer> decl : decls) {
        if (decl.a.trim().length() > 0) {
            Attribute a = parseAttributeDef(action, decl, g);
            dict.add(a);
        }
    }
    return dict;
}
Also used : Attribute(org.antlr.v4.tool.Attribute) AttributeDict(org.antlr.v4.tool.AttributeDict) Pair(org.antlr.v4.runtime.misc.Pair)

Aggregations

Attribute (org.antlr.v4.tool.Attribute)5 ArgRef (org.antlr.v4.codegen.model.chunk.ArgRef)2 QRetValueRef (org.antlr.v4.codegen.model.chunk.QRetValueRef)2 Rule (org.antlr.v4.tool.Rule)2 Field (java.lang.reflect.Field)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 CommonToken (org.antlr.runtime.CommonToken)1 LeftRecursiveRuleTransformer (org.antlr.v4.analysis.LeftRecursiveRuleTransformer)1 ModelElement (org.antlr.v4.codegen.model.ModelElement)1 OutputModelObject (org.antlr.v4.codegen.model.OutputModelObject)1 ActionText (org.antlr.v4.codegen.model.chunk.ActionText)1 LabelRef (org.antlr.v4.codegen.model.chunk.LabelRef)1 ListLabelRef (org.antlr.v4.codegen.model.chunk.ListLabelRef)1 LocalRef (org.antlr.v4.codegen.model.chunk.LocalRef)1 RetValueRef (org.antlr.v4.codegen.model.chunk.RetValueRef)1 TokenRef (org.antlr.v4.codegen.model.chunk.TokenRef)1