01: package fri.patterns.interpreter.parsergenerator.semantics;
02:
03: import java.util.List;
04: import fri.patterns.interpreter.parsergenerator.Semantic;
05: import fri.patterns.interpreter.parsergenerator.syntax.Rule;
06:
07: /**
08: A semantic that builds a syntax tree model from a parser run.
09: Every node of the result tree contains the rule and the parsed token list.
10: The result of the parser run can be retrieved by
11: <i>(TreeBuilderSemantic.Node) parser.getResult()</i>.
12:
13: @author (c) 2002, Fritz Ritzberger
14: */
15:
16: public class TreeBuilderSemantic implements Semantic {
17: /**
18: Implements Semantic to store every node of the syntax tree with rule and values.
19: */
20: public Object doSemantic(Rule rule, List inputTokens, List ranges) {
21: return new Node(rule, inputTokens, ranges);
22: }
23:
24: /**
25: Node class that representy a syntax tree node. All sub-nodes are contained as children.
26: */
27: public static class Node {
28: private Rule rule;
29: private List inputTokens, ranges;
30:
31: public Node(Rule rule, List inputTokens, List ranges) {
32: this .rule = rule;
33: this .inputTokens = inputTokens;
34: this .ranges = ranges;
35: }
36:
37: /** Returns the rule of this syntax tree node. */
38: public Rule getRule() {
39: return rule;
40: }
41:
42: /** Returns the instance token list. */
43: public List getInputTokens() {
44: return inputTokens;
45: }
46:
47: /** Returns the instance token line range list. */
48: public List getRanges() {
49: return ranges;
50: }
51:
52: /** Returns "nonterminal@hashcode" as String representation of this node. */
53: public String toString() {
54: return getRule().getNonterminal() + "@" + hashCode();
55: }
56:
57: /**
58: Returns the human readable representation of this node and all sub-nodes.
59: @param indent spaces to indent on sub-nodes.
60: */
61: public String toString(int indent) {
62: StringBuffer sb = new StringBuffer();
63: for (int i = 0; i < indent; i++)
64: sb.append(" ");
65:
66: sb.append(toString());
67: sb.append(" ::= ");
68:
69: if (getRule().rightSize() <= 0)
70: sb.append("/*nothing*/");
71: else
72: for (int i = 0; i < getRule().rightSize(); i++)
73: sb.append(getRule().getRightSymbol(i) + " ");
74:
75: sb.append("\t=>\t");
76: sb.append(getInputTokens());
77: sb.append("\n");
78:
79: for (int i = 0; i < getInputTokens().size(); i++) {
80: Object o = getInputTokens().get(i);
81:
82: if (o instanceof Node) {
83: sb.append(((Node) o).toString(indent + 1));
84: }
85: }
86:
87: return sb.toString();
88: }
89: }
90:
91: }
|