in reference/src/main/java/ConvertJava.java [211:308]
private JSONArray getSerializedTree(RuleContext t, CommonTokenStream tokens) {
stackDepth++;
int n = t.getChildCount();
boolean hasLeaf = false;
if (n == 0 || stackDepth > MAX_DEPTH) {
childHasLeaf = false;
stackDepth--;
return null;
}
String thisRuleName = getRuleName(t);
String oldClassName = null;
String oldMethodName = null;
int oldBeginLine = 0;
if (thisRuleName.equals("classDeclaration")) {
oldClassName = thisClassName;
}
if (thisRuleName.equals("methodDeclaration")) {
oldMethodName = thisMethodName;
thisMethodName = ((TerminalNodeImpl) t.getChild(1)).getText();
oldBeginLine = beginLine;
beginLine = ((TerminalNodeImpl) t.getChild(1)).getSymbol().getLine();
}
JSONArray simpleTree = new JSONArray();
simpleTree.put("");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
ParseTree tree = t.getChild(i);
if (tree instanceof TerminalNodeImpl) {
String s = tree.getText();
if (!s.equals("<EOF>")) {
Token thisToken = ((TerminalNodeImpl) tree).getSymbol();
String ruleName = vocab.getDisplayName(thisToken.getType());
String ws1 = getLeadingOrTrailing(tree, tokens, true);
String ws2 = getLeadingOrTrailing(tree, tokens, false);
JSONObject tok = new JSONObject();
tok.put("token", s);
tok.put("leading", ws1);
tok.put("trailing", ws2);
boolean isLeaf;
if (identifiersRuleNames.contains(ruleName)) {
if (localVarContexts.contains(thisRuleName)) {
tok.put("var", true);
// System.out.println(s);
}
isLeaf = true;
sb.append("#");
hasLeaf = true;
setClassName(thisRuleName, t, i);
} else {
isLeaf = false;
sb.append(s);
}
if (isLeaf) tok.put("leaf", isLeaf);
tok.put("line", thisToken.getLine());
endLine = thisToken.getLine();
simpleTree.put(tok);
}
} else {
JSONArray child = getSerializedTree((RuleContext) tree, tokens);
if (child != null && child.length() > 0) {
if (child.length() == 2) {
simpleTree.put(child.get(1));
sb.append(child.get(0));
hasLeaf = hasLeaf || childHasLeaf;
} else if (!childHasLeaf
&& !child.get(0).equals("{}")) { // see the while(m.find()){} query
sb.append(child.get(0));
for (int j = 1; j < child.length(); j++) {
simpleTree.put(child.get(j));
}
} else {
sb.append("#");
hasLeaf = true;
simpleTree.put(child);
}
}
}
}
simpleTree.put(0, sb.toString());
childHasLeaf = hasLeaf;
dumpMethodAst(thisRuleName, simpleTree);
if (thisRuleName.equals("classDeclaration")) {
thisClassName = oldClassName;
}
if (thisRuleName.equals("methodDeclaration")) {
thisMethodName = oldMethodName;
beginLine = oldBeginLine;
}
stackDepth--;
return simpleTree;
}