1 31 32 package org.antlr.works.visualization.graphics.primitive; 33 34 import java.util.Map ; 35 36 41 42 public class GLiteral { 43 44 public static final String OP_SUB = "-"; 45 public static final String OP_MAX = "#"; 46 public static final String OP_LPAREN = "("; 47 public static final String OP_RPAREN = ")"; 48 public static final String OP_COMA = ","; 49 50 public static String substract(String a, String b) { 51 return a+OP_SUB+OP_LPAREN+b+OP_RPAREN; 52 } 53 54 public static String add(String a, String b) { 55 return a+b; 56 } 57 58 public static String max(String a, String b) { 59 boolean anull = a == null || a.length() == 0; 60 boolean bnull = b == null || b.length() == 0; 61 if(anull && bnull) 62 return ""; 63 else if(anull) 64 return b; 65 else if(bnull) 66 return a; 67 else 68 return OP_MAX+OP_LPAREN+a+OP_COMA+b+OP_RPAREN; 69 } 70 71 public static float evaluate(String s, Map <String ,Float > values) { 72 if(s == null) 73 return 0; 74 75 return new Evaluator(s, values).evaluate(); 76 } 77 78 private static class Evaluator { 79 80 public String s; 81 public Map <String ,Float > values; 82 public int position; 83 84 public Evaluator(String s, Map <String ,Float > values) { 85 this.s = s; 86 this.values = values; 87 } 88 89 public float evaluate() { 90 position = 0; 91 return eval(); 92 } 93 94 private float eval() { 95 float _value = 0; 96 97 do { 98 Float v = values.get(c()); 99 if(v != null) { 100 _value += v.floatValue(); 101 } else { 102 if(c().equals(OP_SUB)) 103 _value -= evaluate_sub(); 104 else if(c().equals(OP_MAX)) 105 _value += evaluate_max(); 106 else if(c().equals(OP_RPAREN)) 107 break; 108 else if(c().equals(OP_COMA)) 109 break; 110 else 111 System.err.println("** Evaluator: unexpected token \""+c()+"\""); 112 } 113 } while(nextChar()); 114 115 return _value; 116 } 117 118 private float evaluate_sub() { 119 match(OP_SUB); 120 match(OP_LPAREN); 121 return eval(); 122 } 123 124 private float evaluate_max() { 125 match(OP_MAX); 126 match(OP_LPAREN); 127 float a = eval(); 128 match(OP_COMA); 129 float b = eval(); 130 return Math.max(a,b); 131 } 132 133 private boolean nextChar() { 134 position++; 135 return position<s.length(); 136 } 137 138 private void match(String token) { 139 if(c().equals(token)) 140 nextChar(); 141 else 142 System.err.println("** Evaluator: unexpected token \""+c()+"\""); 143 } 144 145 private String c() { 146 return s.substring(position, position+1); 147 } 148 } 149 } 150 | Popular Tags |