/
ParseTreeUtil.java
259 lines (244 loc) · 9.7 KB
/
ParseTreeUtil.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/*
* Copyright 2023 Philipp Salvisberg <philipp.salvisberg@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.islandsql.grammar.util;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Parse tree utilities.
*/
public class ParseTreeUtil {
/**
* Gets all nodes that are instances of the list of desired classes.
* Start node can be any node in the parse tree.
*
* @param parseTree Start node.
* @param desiredTypes Desired classes (must be descendants of ParseTree).
* @return List of nodes that are instances of the of desired class.
*/
public static List<? extends ParseTree> getAllContentsOfTypes(ParseTree parseTree, List<Class<? extends ParseTree>> desiredTypes) {
FindRuleListener listener = new FindRuleListener(desiredTypes);
ParseTreeWalker walker = new ParseTreeWalker();
int childCount = parseTree.getChildCount();
for (int i = 0; i < childCount; i++) {
walker.walk(listener, parseTree.getChild(i));
}
return listener.getResult();
}
/**
* Gets all nodes that are instances of the desired class.
* Start node can be any node in the parse tree.
*
* @param parseTree Start node.
* @param desiredType Desired class (must be a descendant of ParseTree).
* @param <T> The return type of the result.
* @return List of nodes that are instances of the of desired class.
*/
@SuppressWarnings("unchecked")
public static <T extends ParseTree> List<T> getAllContentsOfType(ParseTree parseTree, Class<T> desiredType) {
List<Class<? extends ParseTree>> desiredTypes = Collections.singletonList(desiredType);
return (List<T>) getAllContentsOfTypes(parseTree, desiredTypes);
}
/**
* Gets the parent node of the desired class.
* Start node can be any node in the parse tree.
*
* @param parseTree Start node (child).
* @param desiredType Desired class (must be a descendant of ParseTree).
* @param <T> The return type of the result.
* @return An instance of the desired class.
*/
@SuppressWarnings("unchecked")
public static <T extends ParseTree> T getContainerOfType(ParseTree parseTree, Class<T> desiredType) {
ParseTree parent = parseTree.getParent();
while (parent != null) {
if (desiredType.isInstance(parent)) {
return (T) parent;
}
parent = parent.getParent();
}
return null;
}
/**
* Determines if a node is abstract.
* A node is abstract if it contains the same token as its only child.
*
* @param parseTree Node to be checked.
* @return Returns true if the node is abstract, otherwise false.
*/
public static boolean isAbstract(ParseTree parseTree) {
if (parseTree instanceof ParserRuleContext) {
if (parseTree.getChildCount() == 1) {
ParseTree child = parseTree.getChild(0);
return child instanceof ParserRuleContext
&& ((ParserRuleContext) child).getStart() == ((ParserRuleContext) parseTree).getStart()
&& ((ParserRuleContext) child).getStop() == ((ParserRuleContext) parseTree).getStop();
}
}
return false;
}
/**
* Gets the most abstract parent node.
* This is a parent node with the same tokens as the start node.
*
* @param parseTree Start node.
* @return Returns a parent node or the start node.
*/
public static ParseTree getMostAbstract(ParseTree parseTree) {
ParserRuleContext result;
if (parseTree instanceof ParserRuleContext) {
result = (ParserRuleContext) parseTree;
while (isAbstract(result.getParent())) {
result = result.getParent();
}
return result;
}
return parseTree;
}
/**
* Get the most concrete child node.
* This is a child with the same tokens as the start node.
*
* @param parseTree Start node.
* @return Returns a child node or the start node.
*/
public static ParseTree getMostConcrete(ParseTree parseTree) {
ParserRuleContext result;
if (parseTree instanceof ParserRuleContext) {
result = (ParserRuleContext) parseTree;
while (isAbstract(result)) {
result = (ParserRuleContext) result.getChild(0);
}
return result;
}
return parseTree;
}
/**
* Get the previous sibling of the start node.
* Abstract nodes are treated as non-existent.
*
* @param parseTree Start node.
* @return Returns the most concrete node of the previous sibling. Returns null if the start node is the first child or the start node has no parent.
*/
public static ParseTree getPreviousSibling(ParseTree parseTree) {
ParseTree abstractParseTree = getMostAbstract(parseTree);
ParseTree parent = abstractParseTree.getParent();
ParseTree previous = null;
if (parent != null) {
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
ParseTree current = parent.getChild(i);
if (current == abstractParseTree) {
return getMostConcrete(previous);
}
previous = current;
}
}
return null;
}
/**
* Get the next sibling of the start node.
* Abstract nodes are treated as non-existent.
*
* @param parseTree Start node.
* @return Returns the most concrete node of the next sibling. Returns null if the start node is the first child or the start node has no parent.
*/
public static ParseTree getNextSibling(ParseTree parseTree) {
ParseTree abstractParseTree = getMostAbstract(parseTree);
ParseTree parent = abstractParseTree.getParent();
ParseTree next = null;
if (parent != null) {
for (int i = parent.getChildCount() - 1; i >= 0; i--) {
ParseTree current = parent.getChild(i);
if (current == abstractParseTree) {
return getMostConcrete(next);
}
next = current;
}
}
return null;
}
/**
* Get all nodes that are an instance of the desired class and a sibling of the start node.
* Abstract nodes are treated as non-existent.
*
* @param parseTree Start node.
* @param desiredType Desired class.
* @param <T> The return type of the result.
* @return Returns a list of instances of the desired class that are siblings of the start node.
*/
@SuppressWarnings("unchecked")
public static <T extends ParseTree> List<T> getSiblingsOfType(ParseTree parseTree, Class<T> desiredType) {
List<T> result = new ArrayList<>();
ParseTree abstractCtx = getMostAbstract(parseTree);
ParseTree parent = abstractCtx.getParent();
if (parent != null) {
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
ParseTree child = getMostConcrete(parent.getChild(i));
if (desiredType.isInstance(child)) {
result.add((T) child);
}
}
}
return result;
}
/**
* Gets the label name of an alternative.
* If an alternative is labeld with "#someLabel" in the grammar, then
* a subclass named "IslandSqlParser$SomeLabelContext" of another
* rule class (not ParserRuleContext) is created.
*
* @param ctx ParserRuleContext to get the alternative label name from.
* @return Returns the label name or null, if no label is defined.
*/
public static String getLabelName(ParserRuleContext ctx) {
if (ctx.getClass().getSuperclass().getSimpleName().equals("ParserRuleContext")) {
return null;
} else {
String className = ctx.getClass().getName();
String labelName = className.substring(className.indexOf("$") + 1, className.lastIndexOf("Context"));
return Character.toLowerCase(labelName.charAt(0)) + labelName.substring(1);
}
}
/**
* Produces a hierarchical parse tree as string.
*
* @param root The start node.
* @return Returns a hierarchical parse tree as string.
*/
public static String printParseTree(ParseTree root) {
PrintRuleListener listener = new PrintRuleListener();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(listener, root);
return listener.getResult();
}
/**
* Produces a parse tree as string in DOT format.
*
* @param root The start node.
* @return Returns a parse tree as string in DOT format.
*/
public static String dotParseTree(ParseTree root) {
DotRuleListener listener = new DotRuleListener();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(listener, root);
return listener.getResult();
}
}