Search in sources :

Example 21 with IntegerList

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

the class TestATNInterpreter method checkMatchedAlt.

public void checkMatchedAlt(LexerGrammar lg, final Grammar g, String inputString, int expected) {
    ATN lexatn = createATN(lg, true);
    LexerATNSimulator lexInterp = new LexerATNSimulator(lexatn, new DFA[] { new DFA(lexatn.modeToStartState.get(Lexer.DEFAULT_MODE)) }, null);
    IntegerList types = getTokenTypesViaATN(inputString, lexInterp);
    // System.out.println(types);
    g.importVocab(lg);
    ParserATNFactory f = new ParserATNFactory(g);
    ATN atn = f.createATN();
    TokenStream input = new MockIntTokenStream(types);
    // System.out.println("input="+input.types);
    ParserInterpreterForTesting interp = new ParserInterpreterForTesting(g, input);
    ATNState startState = atn.ruleToStartState[g.getRule("a").index];
    if (startState.transition(0).target instanceof BlockStartState) {
        startState = startState.transition(0).target;
    }
    DOTGenerator dot = new DOTGenerator(g);
    // System.out.println(dot.getDOT(atn.ruleToStartState[g.getRule("a").index]));
    Rule r = g.getRule("e");
    // if ( r!=null ) System.out.println(dot.getDOT(atn.ruleToStartState[r.index]));
    int result = interp.matchATN(input, startState);
    assertEquals(expected, result);
}
Also used : MockIntTokenStream(org.antlr.v4.test.runtime.MockIntTokenStream) TokenStream(org.antlr.v4.runtime.TokenStream) DOTGenerator(org.antlr.v4.tool.DOTGenerator) ATNState(org.antlr.v4.runtime.atn.ATNState) ParserATNFactory(org.antlr.v4.automata.ParserATNFactory) LexerATNSimulator(org.antlr.v4.runtime.atn.LexerATNSimulator) IntegerList(org.antlr.v4.runtime.misc.IntegerList) MockIntTokenStream(org.antlr.v4.test.runtime.MockIntTokenStream) RuntimeTestUtils.getTokenTypesViaATN(org.antlr.v4.test.runtime.RuntimeTestUtils.getTokenTypesViaATN) ATN(org.antlr.v4.runtime.atn.ATN) Rule(org.antlr.v4.tool.Rule) BlockStartState(org.antlr.v4.runtime.atn.BlockStartState) DFA(org.antlr.v4.runtime.dfa.DFA)

Example 22 with IntegerList

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

the class SwiftTarget method serializeTojson.

// added by janyou -->
public String serializeTojson(ATN atn) {
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add("version", ATNDeserializer.SERIALIZED_VERSION);
    builder.add("uuid", ATNDeserializer.SERIALIZED_UUID.toString());
    // convert grammar type to ATN const to avoid dependence on ANTLRParser
    builder.add("grammarType", atn.grammarType.ordinal());
    builder.add("maxTokenType", atn.maxTokenType);
    // states
    int nedges = 0;
    Map<IntervalSet, Integer> setIndices = new HashMap<IntervalSet, Integer>();
    List<IntervalSet> sets = new ArrayList<IntervalSet>();
    JsonArrayBuilder statesBuilder = Json.createArrayBuilder();
    IntegerList nonGreedyStates = new IntegerList();
    IntegerList precedenceStates = new IntegerList();
    for (ATNState s : atn.states) {
        JsonObjectBuilder stateBuilder = Json.createObjectBuilder();
        if (s == null) {
            // might be optimized away
            statesBuilder.addNull();
            continue;
        }
        int stateType = s.getStateType();
        stateBuilder.add("stateType", stateType);
        // stateBuilder.add("stateNumber",s.stateNumber);
        stateBuilder.add("ruleIndex", s.ruleIndex);
        if (s instanceof DecisionState && ((DecisionState) s).nonGreedy) {
            nonGreedyStates.add(s.stateNumber);
        }
        if (s instanceof RuleStartState && ((RuleStartState) s).isLeftRecursiveRule) {
            precedenceStates.add(s.stateNumber);
        }
        if (s.getStateType() == ATNState.LOOP_END) {
            stateBuilder.add("detailStateNumber", ((LoopEndState) s).loopBackState.stateNumber);
        } else if (s instanceof BlockStartState) {
            stateBuilder.add("detailStateNumber", ((BlockStartState) s).endState.stateNumber);
        }
        if (s.getStateType() != ATNState.RULE_STOP) {
            // the deserializer can trivially derive these edges, so there's no need to serialize them
            nedges += s.getNumberOfTransitions();
        }
        for (int i = 0; i < s.getNumberOfTransitions(); i++) {
            Transition t = s.transition(i);
            int edgeType = Transition.serializationTypes.get(t.getClass());
            if (edgeType == Transition.SET || edgeType == Transition.NOT_SET) {
                SetTransition st = (SetTransition) t;
                if (!setIndices.containsKey(st.set)) {
                    sets.add(st.set);
                    setIndices.put(st.set, sets.size() - 1);
                }
            }
        }
        statesBuilder.add(stateBuilder);
    }
    builder.add("states", statesBuilder);
    // non-greedy states
    JsonArrayBuilder nonGreedyStatesBuilder = Json.createArrayBuilder();
    for (int i = 0; i < nonGreedyStates.size(); i++) {
        nonGreedyStatesBuilder.add(nonGreedyStates.get(i));
    }
    builder.add("nonGreedyStates", nonGreedyStatesBuilder);
    // precedence states
    JsonArrayBuilder precedenceStatesBuilder = Json.createArrayBuilder();
    for (int i = 0; i < precedenceStates.size(); i++) {
        precedenceStatesBuilder.add(precedenceStates.get(i));
    }
    builder.add("precedenceStates", precedenceStatesBuilder);
    JsonArrayBuilder ruleToStartStateBuilder = Json.createArrayBuilder();
    int nrules = atn.ruleToStartState.length;
    for (int r = 0; r < nrules; r++) {
        JsonObjectBuilder stateBuilder = Json.createObjectBuilder();
        ATNState ruleStartState = atn.ruleToStartState[r];
        stateBuilder.add("stateNumber", ruleStartState.stateNumber);
        if (atn.grammarType == ATNType.LEXER) {
            // if (atn.ruleToTokenType[r] == Token.EOF) {
            // //data.add(Character.MAX_VALUE);
            // stateBuilder.add("ruleToTokenType",-1);
            // }
            // else {
            // //data.add(atn.ruleToTokenType[r]);
            stateBuilder.add("ruleToTokenType", atn.ruleToTokenType[r]);
        // }
        }
        ruleToStartStateBuilder.add(stateBuilder);
    }
    builder.add("ruleToStartState", ruleToStartStateBuilder);
    JsonArrayBuilder modeToStartStateBuilder = Json.createArrayBuilder();
    int nmodes = atn.modeToStartState.size();
    if (nmodes > 0) {
        for (ATNState modeStartState : atn.modeToStartState) {
            modeToStartStateBuilder.add(modeStartState.stateNumber);
        }
    }
    builder.add("modeToStartState", modeToStartStateBuilder);
    JsonArrayBuilder nsetsBuilder = Json.createArrayBuilder();
    int nsets = sets.size();
    // data.add(nsets);
    builder.add("nsets", nsets);
    for (IntervalSet set : sets) {
        JsonObjectBuilder setBuilder = Json.createObjectBuilder();
        boolean containsEof = set.contains(Token.EOF);
        if (containsEof && set.getIntervals().get(0).b == Token.EOF) {
            // data.add(set.getIntervals().size() - 1);
            setBuilder.add("size", set.getIntervals().size() - 1);
        } else {
            // data.add(set.getIntervals().size());
            setBuilder.add("size", set.getIntervals().size());
        }
        setBuilder.add("containsEof", containsEof ? 1 : 0);
        JsonArrayBuilder IntervalsBuilder = Json.createArrayBuilder();
        for (Interval I : set.getIntervals()) {
            JsonObjectBuilder IntervalBuilder = Json.createObjectBuilder();
            if (I.a == Token.EOF) {
                if (I.b == Token.EOF) {
                    continue;
                } else {
                    IntervalBuilder.add("a", 0);
                // data.add(0);
                }
            } else {
                IntervalBuilder.add("a", I.a);
            // data.add(I.a);
            }
            IntervalBuilder.add("b", I.b);
            IntervalsBuilder.add(IntervalBuilder);
        }
        setBuilder.add("Intervals", IntervalsBuilder);
        nsetsBuilder.add(setBuilder);
    }
    builder.add("IntervalSet", nsetsBuilder);
    // builder.add("nedges",nedges);
    JsonArrayBuilder allTransitionsBuilder = Json.createArrayBuilder();
    for (ATNState s : atn.states) {
        if (s == null) {
            // might be optimized away
            continue;
        }
        if (s.getStateType() == ATNState.RULE_STOP) {
            continue;
        }
        JsonArrayBuilder transitionsBuilder = Json.createArrayBuilder();
        for (int i = 0; i < s.getNumberOfTransitions(); i++) {
            JsonObjectBuilder transitionBuilder = Json.createObjectBuilder();
            Transition t = s.transition(i);
            if (atn.states.get(t.target.stateNumber) == null) {
                throw new IllegalStateException("Cannot serialize a transition to a removed state.");
            }
            int src = s.stateNumber;
            int trg = t.target.stateNumber;
            int edgeType = Transition.serializationTypes.get(t.getClass());
            int arg1 = 0;
            int arg2 = 0;
            int arg3 = 0;
            switch(edgeType) {
                case Transition.RULE:
                    trg = ((RuleTransition) t).followState.stateNumber;
                    arg1 = ((RuleTransition) t).target.stateNumber;
                    arg2 = ((RuleTransition) t).ruleIndex;
                    arg3 = ((RuleTransition) t).precedence;
                    break;
                case Transition.PRECEDENCE:
                    PrecedencePredicateTransition ppt = (PrecedencePredicateTransition) t;
                    arg1 = ppt.precedence;
                    break;
                case Transition.PREDICATE:
                    PredicateTransition pt = (PredicateTransition) t;
                    arg1 = pt.ruleIndex;
                    arg2 = pt.predIndex;
                    arg3 = pt.isCtxDependent ? 1 : 0;
                    break;
                case Transition.RANGE:
                    arg1 = ((RangeTransition) t).from;
                    arg2 = ((RangeTransition) t).to;
                    if (arg1 == Token.EOF) {
                        arg1 = 0;
                        arg3 = 1;
                    }
                    break;
                case Transition.ATOM:
                    arg1 = ((AtomTransition) t).label;
                    if (arg1 == Token.EOF) {
                        arg1 = 0;
                        arg3 = 1;
                    }
                    break;
                case Transition.ACTION:
                    ActionTransition at = (ActionTransition) t;
                    arg1 = at.ruleIndex;
                    arg2 = at.actionIndex;
                    // if (arg2 == -1) {
                    // arg2 = 0xFFFF;
                    // }
                    arg3 = at.isCtxDependent ? 1 : 0;
                    break;
                case Transition.SET:
                    arg1 = setIndices.get(((SetTransition) t).set);
                    break;
                case Transition.NOT_SET:
                    arg1 = setIndices.get(((SetTransition) t).set);
                    break;
                case Transition.WILDCARD:
                    break;
            }
            transitionBuilder.add("src", src);
            transitionBuilder.add("trg", trg);
            transitionBuilder.add("edgeType", edgeType);
            transitionBuilder.add("arg1", arg1);
            transitionBuilder.add("arg2", arg2);
            transitionBuilder.add("arg3", arg3);
            transitionsBuilder.add(transitionBuilder);
        }
        allTransitionsBuilder.add(transitionsBuilder);
    }
    builder.add("allTransitionsBuilder", allTransitionsBuilder);
    int ndecisions = atn.decisionToState.size();
    // data.add(ndecisions);
    JsonArrayBuilder decisionToStateBuilder = Json.createArrayBuilder();
    for (DecisionState decStartState : atn.decisionToState) {
        // data.add(decStartState.stateNumber);
        decisionToStateBuilder.add(decStartState.stateNumber);
    }
    builder.add("decisionToState", decisionToStateBuilder);
    // 
    // LEXER ACTIONS
    // 
    JsonArrayBuilder lexerActionsBuilder = Json.createArrayBuilder();
    if (atn.grammarType == ATNType.LEXER) {
        // data.add(atn.lexerActions.length);
        for (LexerAction action : atn.lexerActions) {
            JsonObjectBuilder lexerActionBuilder = Json.createObjectBuilder();
            lexerActionBuilder.add("actionType", action.getActionType().ordinal());
            // data.add(action.getActionType().ordinal());
            switch(action.getActionType()) {
                case CHANNEL:
                    int channel = ((LexerChannelAction) action).getChannel();
                    lexerActionBuilder.add("a", channel);
                    lexerActionBuilder.add("b", 0);
                    break;
                case CUSTOM:
                    int ruleIndex = ((LexerCustomAction) action).getRuleIndex();
                    int actionIndex = ((LexerCustomAction) action).getActionIndex();
                    lexerActionBuilder.add("a", ruleIndex);
                    lexerActionBuilder.add("b", actionIndex);
                    break;
                case MODE:
                    int mode = ((LexerModeAction) action).getMode();
                    lexerActionBuilder.add("a", mode);
                    lexerActionBuilder.add("b", 0);
                    break;
                case MORE:
                    lexerActionBuilder.add("a", 0);
                    lexerActionBuilder.add("b", 0);
                    break;
                case POP_MODE:
                    lexerActionBuilder.add("a", 0);
                    lexerActionBuilder.add("b", 0);
                    break;
                case PUSH_MODE:
                    mode = ((LexerPushModeAction) action).getMode();
                    lexerActionBuilder.add("a", mode);
                    lexerActionBuilder.add("b", 0);
                    break;
                case SKIP:
                    lexerActionBuilder.add("a", 0);
                    lexerActionBuilder.add("b", 0);
                    break;
                case TYPE:
                    int type = ((LexerTypeAction) action).getType();
                    lexerActionBuilder.add("a", type);
                    lexerActionBuilder.add("b", 0);
                    break;
                default:
                    String message = String.format(Locale.getDefault(), "The specified lexer action type %s is not valid.", action.getActionType());
                    throw new IllegalArgumentException(message);
            }
            lexerActionsBuilder.add(lexerActionBuilder);
        }
    }
    builder.add("lexerActions", lexerActionsBuilder);
    // don't adjust the first value since that's the version number
    // for (int i = 1; i < data.size(); i++) {
    // if (data.get(i) < Character.MIN_VALUE || data.get(i) > Character.MAX_VALUE) {
    // throw new UnsupportedOperationException("Serialized ATN data element out of range.");
    // }
    // 
    // int value = (data.get(i) + 2) & 0xFFFF;
    // data.set(i, value);
    // }
    JsonObject data = builder.build();
    // System.out.print(data.toString());
    return data.toString();
}
Also used : HashMap(java.util.HashMap) LexerTypeAction(org.antlr.v4.runtime.atn.LexerTypeAction) ArrayList(java.util.ArrayList) SetTransition(org.antlr.v4.runtime.atn.SetTransition) PrecedencePredicateTransition(org.antlr.v4.runtime.atn.PrecedencePredicateTransition) JsonObject(javax.json.JsonObject) ATNState(org.antlr.v4.runtime.atn.ATNState) IntegerList(org.antlr.v4.runtime.misc.IntegerList) LexerModeAction(org.antlr.v4.runtime.atn.LexerModeAction) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) LoopEndState(org.antlr.v4.runtime.atn.LoopEndState) LexerChannelAction(org.antlr.v4.runtime.atn.LexerChannelAction) LexerAction(org.antlr.v4.runtime.atn.LexerAction) PrecedencePredicateTransition(org.antlr.v4.runtime.atn.PrecedencePredicateTransition) PredicateTransition(org.antlr.v4.runtime.atn.PredicateTransition) DecisionState(org.antlr.v4.runtime.atn.DecisionState) ActionTransition(org.antlr.v4.runtime.atn.ActionTransition) RuleStartState(org.antlr.v4.runtime.atn.RuleStartState) IntervalSet(org.antlr.v4.runtime.misc.IntervalSet) RuleTransition(org.antlr.v4.runtime.atn.RuleTransition) RuleTransition(org.antlr.v4.runtime.atn.RuleTransition) PrecedencePredicateTransition(org.antlr.v4.runtime.atn.PrecedencePredicateTransition) PredicateTransition(org.antlr.v4.runtime.atn.PredicateTransition) ActionTransition(org.antlr.v4.runtime.atn.ActionTransition) Transition(org.antlr.v4.runtime.atn.Transition) AtomTransition(org.antlr.v4.runtime.atn.AtomTransition) SetTransition(org.antlr.v4.runtime.atn.SetTransition) RangeTransition(org.antlr.v4.runtime.atn.RangeTransition) BlockStartState(org.antlr.v4.runtime.atn.BlockStartState) LexerCustomAction(org.antlr.v4.runtime.atn.LexerCustomAction) Interval(org.antlr.v4.runtime.misc.Interval)

Example 23 with IntegerList

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

the class DOTGenerator method getStateLabel.

protected String getStateLabel(DFAState s) {
    if (s == null)
        return "null";
    StringBuilder buf = new StringBuilder(250);
    buf.append('s');
    buf.append(s.stateNumber);
    if (s.isAcceptState) {
        buf.append("=>").append(s.prediction);
    }
    if (s.requiresFullContext) {
        buf.append("^");
    }
    if (grammar != null) {
        Set<Integer> alts = s.getAltSet();
        if (alts != null) {
            buf.append("\\n");
            // separate alts
            IntegerList altList = new IntegerList();
            altList.addAll(alts);
            altList.sort();
            Set<ATNConfig> configurations = s.configs;
            for (int altIndex = 0; altIndex < altList.size(); altIndex++) {
                int alt = altList.get(altIndex);
                if (altIndex > 0) {
                    buf.append("\\n");
                }
                buf.append("alt");
                buf.append(alt);
                buf.append(':');
                // get a list of configs for just this alt
                // it will help us print better later
                List<ATNConfig> configsInAlt = new ArrayList<ATNConfig>();
                for (ATNConfig c : configurations) {
                    if (c.alt != alt)
                        continue;
                    configsInAlt.add(c);
                }
                int n = 0;
                for (int cIndex = 0; cIndex < configsInAlt.size(); cIndex++) {
                    ATNConfig c = configsInAlt.get(cIndex);
                    n++;
                    buf.append(c.toString(null, false));
                    if ((cIndex + 1) < configsInAlt.size()) {
                        buf.append(", ");
                    }
                    if (n % 5 == 0 && (configsInAlt.size() - cIndex) > 3) {
                        buf.append("\\n");
                    }
                }
            }
        }
    }
    String stateLabel = buf.toString();
    return stateLabel;
}
Also used : ATNConfig(org.antlr.v4.runtime.atn.ATNConfig) IntegerList(org.antlr.v4.runtime.misc.IntegerList) ArrayList(java.util.ArrayList)

Example 24 with IntegerList

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

the class BasePythonTest method getTokenTypesViaATN.

public IntegerList getTokenTypesViaATN(String input, LexerATNSimulator lexerATN) {
    ANTLRInputStream in = new ANTLRInputStream(input);
    IntegerList tokenTypes = new IntegerList();
    int ttype;
    do {
        ttype = lexerATN.match(in, Lexer.DEFAULT_MODE);
        tokenTypes.add(ttype);
    } while (ttype != Token.EOF);
    return tokenTypes;
}
Also used : IntegerList(org.antlr.v4.runtime.misc.IntegerList) ANTLRInputStream(org.antlr.v4.runtime.ANTLRInputStream)

Example 25 with IntegerList

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

the class BasePythonTest method getTypesFromString.

//	public void minimizeDFA(DFA dfa) {
//		DFAMinimizer dmin = new DFAMinimizer(dfa);
//		dfa.minimized = dmin.minimize();
//	}
IntegerList getTypesFromString(Grammar g, String expecting) {
    IntegerList expectingTokenTypes = new IntegerList();
    if (expecting != null && !expecting.trim().isEmpty()) {
        for (String tname : expecting.replace(" ", "").split(",")) {
            int ttype = g.getTokenType(tname);
            expectingTokenTypes.add(ttype);
        }
    }
    return expectingTokenTypes;
}
Also used : IntegerList(org.antlr.v4.runtime.misc.IntegerList) STGroupString(org.stringtemplate.v4.STGroupString) BaseRuntimeTest.antlrOnString(org.antlr.v4.test.runtime.BaseRuntimeTest.antlrOnString)

Aggregations

IntegerList (org.antlr.v4.runtime.misc.IntegerList)42 Test (org.junit.Test)12 STGroupString (org.stringtemplate.v4.STGroupString)7 ANTLRInputStream (org.antlr.v4.runtime.ANTLRInputStream)6 ATN (org.antlr.v4.runtime.atn.ATN)6 LexerATNSimulator (org.antlr.v4.runtime.atn.LexerATNSimulator)6 ArrayList (java.util.ArrayList)5 TokenStream (org.antlr.v4.runtime.TokenStream)5 DFA (org.antlr.v4.runtime.dfa.DFA)5 IntervalSet (org.antlr.v4.runtime.misc.IntervalSet)5 BaseRuntimeTest.antlrOnString (org.antlr.v4.test.runtime.BaseRuntimeTest.antlrOnString)5 ParserATNFactory (org.antlr.v4.automata.ParserATNFactory)4 DOTGenerator (org.antlr.v4.tool.DOTGenerator)4 Rule (org.antlr.v4.tool.Rule)4 HashMap (java.util.HashMap)3 ATNState (org.antlr.v4.runtime.atn.ATNState)3 BlockStartState (org.antlr.v4.runtime.atn.BlockStartState)3 MockIntTokenStream (org.antlr.v4.test.runtime.MockIntTokenStream)3 RuntimeTestUtils.getTokenTypesViaATN (org.antlr.v4.test.runtime.RuntimeTestUtils.getTokenTypesViaATN)3 BufferedWriter (java.io.BufferedWriter)2