01: package fri.patterns.interpreter.parsergenerator.syntax;
02:
03: import java.util.*;
04: import java.io.Serializable;
05:
06: /**
07: A rule is a list of String symbols on the right side
08: and a nonterminal on the left side: "a ::= b c d;"
09: A nonterminal is represented as a String with no quotes,
10: every terminal must appear quoted by " or ' or ` (backquote).
11:
12: @author (c) 2004 Fritz Ritzberger
13: */
14:
15: public class Rule implements Serializable {
16: private List symbols;
17:
18: /** Source generator constructor. */
19: public Rule(String nonterminal, int rightSize) {
20: this (new ArrayList(rightSize + 1));
21: symbols.add(nonterminal);
22: }
23:
24: /** Constructing a rule from a String array, first element is interpreted as nonterminal. */
25: public Rule(String[] symbols) {
26: this (SyntaxUtil.ruleToList(symbols));
27: }
28:
29: /** Constructing a rule from a String List, first element is interpreted as nonterminal. */
30: public Rule(List symbols) {
31: if (symbols == null)
32: throw new IllegalArgumentException(
33: "Can not construct rule without nonterminal: "
34: + symbols);
35: this .symbols = symbols;
36: }
37:
38: /** Serializable constructor, do not use. */
39: protected Rule() {
40: }
41:
42: public String getNonterminal() {
43: return (String) symbols.get(0);
44: }
45:
46: public int rightSize() {
47: return symbols.size() - 1;
48: }
49:
50: public String getRightSymbol(int i) {
51: return (String) symbols.get(i + 1);
52: }
53:
54: public void setRightSymbol(String symbol, int i) {
55: symbols.set(i + 1, symbol);
56: }
57:
58: public void addRightSymbol(String symbol) {
59: symbols.add(symbol);
60: }
61:
62: public int indexOnRightSide(String symbol) {
63: for (int i = 0; i < rightSize(); i++)
64: if (getRightSymbol(i).equals(symbol))
65: return i;
66: return -1;
67: }
68:
69: /** Returns true if symbol lists are equal. */
70: public boolean equals(Object o) {
71: return ((Rule) o).symbols.equals(symbols);
72: }
73:
74: /** Returns symbol lists hashcode. */
75: public int hashCode() {
76: return symbols.hashCode();
77: }
78:
79: /** Returns the syntax as a multiline string. */
80: public String toString() {
81: StringBuffer sb = new StringBuffer(getNonterminal() + " ::= ");
82: for (int i = 0; i < rightSize(); i++) {
83: sb.append(getRightSymbol(i));
84: sb.append(" ");
85: }
86: sb.append(";");
87: return sb.toString();
88: }
89:
90: }
|