Yes it is possible. How to do this will depend on the desired implementation. Here's a sample that might work for you:
First define node:
class ParseTreeNode { private final String name; private final List<ParseTreeNode> children = ; public ParseTreeNode(String name) { this.name = name; } public void addChild(ParseTreeNode child) { children.add(child); }
Then you will need to integrate this into your recursive descent functions:
class RDParser { ParseTreeNode parse(Input input) { ParseTreeNode root = createParseTreeNodeNamed("Root") switch (input.nextToken()) { case OPT1: root.addChild(createParseTreeNodeNamed("Opt1")); break; case OPT2: while () { root.addChild(createParseTreeNodeNamed("Opt2-sibling" + )); } case SUBTREE: ParseTreeNode subtree = createParseTreeNodeNamed("Subtree"); root.addChild(subtree); parseSubtree(subtree, input); break; default: error("Input %s was not in the expected first/follow sets", input.nextToken()); } } void parseSubtree(ParseTreeNode node, Input input) { node.addChild(createParseTreeNodeNamed("subtree-child")); } ParseTreeNode createParseTreeNodeNamed(String name) { return new ParseTreeNode(name); } }
As you descend the parsing tree, you will probably want to send any new βrootβ node so that children can be added to it. Alternatively, parseSubtree can create and return a node, which will then be added to the root directory of the node.
You can create either a parsing tree or just an abstract tree using the process described above. Since the parse function returns the root directory of the node, which will refer to any and all child nodes, you will get full access to the parsing tree after parsing.
If you are using a heterogeneous or homogeneous parse tree, you will need a way to store enough information to make it useful.
Kaleb pederson
source share