| 1 package ro.infoiasi.donald.compiler.lexer; 2 3 import java.util.*; 4 5 6 public class Operator implements Comparable { 7 private char symbol; 8 private OpType type; 9 private int precedence; 10 private static int prec = 0; 11 12 13 private static class OpType { 14 private OpType() { } 15 public static final OpType UNARY_LEFT = new OpType(); 16 public static final OpType UNARY_RIGHT = new OpType(); 17 public static final OpType BINARY = new OpType(); 18 } 19 20 private static HashMap ops = new HashMap(); 21 22 private Operator(char symbol, OpType type) { 23 this.symbol = symbol; 24 this.type = type; 25 this.precedence = prec--; 26 ops.put(new Character (symbol), this); 27 } 28 29 public static final Operator ITARAT = new Operator('*', OpType.UNARY_LEFT); 31 public static final Operator CONCAT = new Operator('.', OpType.BINARY); 32 public static final Operator UNION = new Operator('|', OpType.BINARY); 33 34 36 public static Operator get(char symbol) { 37 return (Operator)ops.get(new Character (symbol)); 38 } 39 40 41 public char getSymbol() { 42 return symbol; 43 } 44 45 public static Iterator iterator() { 46 return ops.values().iterator(); 47 } 48 49 public int compareTo(Object obj) { 50 if (obj == null) { 51 throw new NullPointerException (); 52 } 53 Operator op = (Operator)obj; 54 return (precedence-op.precedence); 55 } 56 57 58 public boolean isUnaryLeft() { 59 return type==OpType.UNARY_LEFT; 60 } 61 62 63 public boolean isUnaryRight() { 64 return type==OpType.UNARY_RIGHT; 65 } 66 67 68 public boolean isBinary() { 69 return type==OpType.BINARY; 70 } 71 72 public static void main(String args[]) throws Exception { 73 System.out.println("Precedence: "); 74 Iterator it = Operator.iterator(); 75 Operator op1; 76 Operator op2 = (Operator)it.next(); 77 while (it.hasNext()) { 78 op1 = op2; 79 op2 = (Operator)it.next(); 80 System.out.print("["+op1.getSymbol()+"]"); 81 if (op1.compareTo(op2)<0) { 82 System.out.print("<"); 83 } else if (op1.compareTo(op2)>0) { 84 System.out.print(">"); 85 } else { 86 System.out.println("=="); 87 } 88 System.out.println("["+op2.getSymbol()+"]"); 89 } 90 } 91 } 92 | Popular Tags |