forked from tunnelvisionlabs/antlrworks2
-
Notifications
You must be signed in to change notification settings - Fork 2
/
AbstractForestParser.java
170 lines (149 loc) · 7.28 KB
/
AbstractForestParser.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/*
* Copyright (c) 2012 Sam Harwell, Tunnel Vision Laboratories LLC
* All rights reserved.
*
* The source code of this document is proprietary work, and is not licensed for
* distribution. For information about licensing, contact Sam Harwell at:
* sam@tunnelvisionlabs.com
*/
package org.antlr.works.editor.antlr4.completion;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.antlr.v4.runtime.FailedPredicateException;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.RuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.atn.ATNConfig;
import org.antlr.v4.runtime.atn.ATNState;
import org.antlr.v4.runtime.atn.DecisionState;
import org.antlr.v4.runtime.atn.PlusBlockStartState;
import org.antlr.v4.runtime.atn.PlusLoopbackState;
import org.antlr.v4.runtime.atn.StarLoopEntryState;
import org.antlr.v4.runtime.atn.StarLoopbackState;
import org.antlr.v4.runtime.misc.IntegerList;
import org.antlr.v4.runtime.misc.IntervalSet;
/**
*
* @author Sam Harwell
* @param <TParser>
*/
public abstract class AbstractForestParser<TParser extends CodeCompletionParser> implements ForestParser<TParser> {
// -J-Dorg.antlr.works.editor.antlr4.completion.AbstractForestParser.level=FINE
protected static final Logger LOGGER = Logger.getLogger(AbstractForestParser.class.getName());
@Override
public Map<RuleContext, CaretReachedException> getParseTrees(TParser parser) {
List<MultipleDecisionData> potentialAlternatives = new ArrayList<>();
IntegerList currentPath = new IntegerList();
Map<RuleContext, CaretReachedException> results = new IdentityHashMap<>();
// make sure the token stream is initialized before getting the index
parser.getInputStream().LA(1);
int initialToken = parser.getInputStream().index();
while (true) {
parser.getInputStream().seek(initialToken);
tryParse(parser, potentialAlternatives, currentPath, results);
if (!incrementCurrentPath(potentialAlternatives, currentPath)) {
break;
}
}
LOGGER.log(Level.FINE, "Forest parser constructed {0} parse trees.", results.size());
if (LOGGER.isLoggable(Level.FINEST)) {
for (Map.Entry<RuleContext, CaretReachedException> entry : results.entrySet()) {
LOGGER.log(Level.FINEST, entry.getKey().toStringTree(parser instanceof Parser ? (Parser)parser : null));
}
}
return results;
}
protected boolean incrementCurrentPath(List<MultipleDecisionData> potentialAlternatives, IntegerList currentPath) {
for (int i = currentPath.size() - 1; i >= 0; i--) {
if (currentPath.get(i) < potentialAlternatives.get(i).alternatives.length - 1) {
currentPath.set(i, currentPath.get(i) + 1);
return true;
}
potentialAlternatives.remove(i);
currentPath.removeAt(i);
}
return false;
}
protected void tryParse(TParser parser, List<MultipleDecisionData> potentialAlternatives, IntegerList currentPath, Map<RuleContext, CaretReachedException> results) {
RuleContext parseTree;
try {
parser.getInterpreter().setFixedDecisions(potentialAlternatives, currentPath);
parseTree = parseImpl(parser);
results.put(parseTree, null);
} catch (CaretReachedException ex) {
if (ex.getTransitions() == null) {
return;
}
for (parseTree = ex.getFinalContext(); parseTree.getParent() != null; parseTree = parseTree.getParent()) {
// intentionally blank
}
if (ex.getCause() instanceof FailedPredicateException) {
return;
}
if (ex.getCause() != null) {
IntervalSet alts = new IntervalSet();
IntervalSet semanticAlts = new IntervalSet();
for (ATNConfig c : ex.getTransitions().keySet()) {
if (semanticAlts.contains(c.getAlt())) {
continue;
}
alts.add(c.getAlt());
@SuppressWarnings("unchecked")
Recognizer<Token, ?> recognizer = parser instanceof Recognizer ? (Recognizer<Token, ?>)parser : null;
if (recognizer == null || c.getSemanticContext().eval(recognizer, ex.getFinalContext())) {
semanticAlts.add(c.getAlt());
}
}
if (alts.size() != semanticAlts.size()) {
LOGGER.log(Level.FINER, "Forest decision {0} reduced to {1} by predicate evaluation.", new Object[] { alts, semanticAlts });
}
MultipleDecisionData decisionData = new MultipleDecisionData();
decisionData.inputIndex = parser.getInputStream().index();
decisionData.decision = 0;
if (ex.getCause() != null) {
int stateNumber = ex.getCause().getOffendingState();
ATNState state = parser.getATN().states.get(stateNumber);
if (state instanceof StarLoopbackState) {
assert state.getNumberOfTransitions() == 1 && state.onlyHasEpsilonTransitions();
assert state.transition(0).target instanceof StarLoopEntryState;
state = state.transition(0).target;
} else if (state instanceof PlusBlockStartState && ((PlusBlockStartState)state).decision == -1) {
state = ((PlusBlockStartState)state).loopBackState;
assert state instanceof PlusLoopbackState;
}
if (state instanceof DecisionState) {
decisionData.decision = ((DecisionState)state).decision;
if (decisionData.decision < 0) {
LOGGER.log(Level.WARNING, "No decision number found for state {0}.", state.stateNumber);
}
} else {
if (state != null) {
LOGGER.log(Level.WARNING, "No decision number found for state {0}.", state.stateNumber);
} else {
LOGGER.log(Level.WARNING, "No decision number found for state <null>.");
}
// continuing is likely to never terminate
return;
}
}
assert semanticAlts.getMinElement() >= 1;
assert semanticAlts.getMaxElement() <= parser.getATN().decisionToState.get(decisionData.decision).getNumberOfTransitions();
decisionData.alternatives = semanticAlts.toArray();
potentialAlternatives.add(decisionData);
currentPath.add(-1);
}
else {
results.put(parseTree, ex);
}
} catch (RecognitionException ex) {
// not a viable path
}
}
protected abstract RuleContext parseImpl(TParser parser);
}