01: package ro.infoiasi.donald.compiler.lexer;
02:
03: import java.util.*;
04:
05: /** An operator in a regular expression */
06: public class Operator implements Comparable {
07: private char symbol;
08: private OpType type;
09: private int precedence;
10: private static int prec = 0;
11:
12: /** The type of operator */
13: private static class OpType {
14: private OpType() { /* nothing*/
15: }
16:
17: public static final OpType UNARY_LEFT = new OpType();
18: public static final OpType UNARY_RIGHT = new OpType();
19: public static final OpType BINARY = new OpType();
20: }
21:
22: private static HashMap ops = new HashMap();
23:
24: private Operator(char symbol, OpType type) {
25: this .symbol = symbol;
26: this .type = type;
27: this .precedence = prec--;
28: ops.put(new Character(symbol), this );
29: }
30:
31: // operators appear in precedence order (unary should always be on top)
32: public static final Operator ITARAT = new Operator('*',
33: OpType.UNARY_LEFT);
34: public static final Operator CONCAT = new Operator('.',
35: OpType.BINARY);
36: public static final Operator UNION = new Operator('|',
37: OpType.BINARY);
38:
39: /** Returns the operator corresponding to the given symbol.
40: If no such operator exists then null is returned. */
41: public static Operator get(char symbol) {
42: return (Operator) ops.get(new Character(symbol));
43: }
44:
45: /** Returns the symbol representing the operator */
46: public char getSymbol() {
47: return symbol;
48: }
49:
50: public static Iterator iterator() {
51: return ops.values().iterator();
52: }
53:
54: public int compareTo(Object obj) {
55: if (obj == null) {
56: throw new NullPointerException();
57: }
58: Operator op = (Operator) obj;
59: return (precedence - op.precedence);
60: }
61:
62: /** Returns true is the operator is unary and binds to the expression to its left */
63: public boolean isUnaryLeft() {
64: return type == OpType.UNARY_LEFT;
65: }
66:
67: /** Returns true is the operator is unary and binds to the expression to its right */
68: public boolean isUnaryRight() {
69: return type == OpType.UNARY_RIGHT;
70: }
71:
72: /** Returns true is the operator is binary */
73: public boolean isBinary() {
74: return type == OpType.BINARY;
75: }
76:
77: public static void main(String args[]) throws Exception {
78: System.out.println("Precedence: ");
79: Iterator it = Operator.iterator();
80: Operator op1;
81: Operator op2 = (Operator) it.next();
82: while (it.hasNext()) {
83: op1 = op2;
84: op2 = (Operator) it.next();
85: System.out.print("[" + op1.getSymbol() + "]");
86: if (op1.compareTo(op2) < 0) {
87: System.out.print("<");
88: } else if (op1.compareTo(op2) > 0) {
89: System.out.print(">");
90: } else {
91: System.out.println("==");
92: }
93: System.out.println("[" + op2.getSymbol() + "]");
94: }
95: }
96: }
|