1 22 package org.jboss.aspects.dbc.condition.parser; 23 24 29 public class BeanshellGenerator implements ExpressionVisitor 30 { 31 Expression expr; 32 StringBuffer code; 33 int indent; 34 36 public BeanshellGenerator(Expression expr) 37 { 38 this.expr = expr; 39 } 40 41 public String createBeanshellCode() 42 { 43 code = new StringBuffer (); 44 expr.accept(this); 46 return code.toString(); 47 } 48 49 public void visit(Expression expr) 50 { 51 expr.accept(this); 52 } 53 54 public void visit(BooleanExpression expr) 55 { 56 if (expr.isTopLevel()) 57 { 58 code.append("return (" + expr.getExpression() + ");\n"); 59 } 60 else 61 { 62 code.append(expr.getExpression()); 63 } 64 } 65 66 public void visit(ForAllExpression expr) 67 { 68 createLoopCode(expr, false); 69 } 70 71 public void visit(ExistsExpression expr) 72 { 73 createLoopCode(expr, true); 74 } 75 76 public void visit(ImpliesExpression expr) 77 { 78 indent(); 79 code.append("if ("); 80 expr.getLhs().accept(this); 81 code.append("){\n"); 82 indent++; 83 indent(); 84 code.append("if(!("); 85 expr.getRhs().accept(this); 86 code.append(")){\n"); 87 indent++; 88 indent(); 89 code.append("return false;\n"); 90 indent--; 91 indent(); 92 code.append("}\n"); 93 94 indent--; 95 indent(); 96 code.append("}\n"); 97 98 if (expr.isTopLevel()) 99 { 100 code.append("return true;\n"); 101 } 102 } 103 104 public void visit(JavaExpression expr) 105 { 106 code.append(expr.getJava()); 107 code.append("\nreturn true;\n"); 108 } 109 110 private void indent() 111 { 112 for (int i = 0 ; i < indent * 2 ; i++) 113 { 114 code.append(" "); 115 } 116 } 117 118 private void createLoopCode(LoopExpression expr, boolean breakType) 119 { 120 String declaration = expr.getDeclaration(); 121 String collection = expr.getCollection(); 122 Expression body = expr.getBody(); 123 124 indent(); 125 code.append("for (" + declaration + " : " + collection + "){\n"); 126 indent++; 127 128 if (body instanceof BooleanExpression) 129 { 130 indent(); 131 code.append("if ("); 132 133 if (!breakType) 134 { 135 code.append("!"); 136 } 137 138 code.append("("); 139 body.accept(this); 140 code.append(")){\n"); 141 142 indent++; 143 indent(); 144 code.append("return "+ breakType + ";\n"); 145 146 indent--; 147 indent(); 148 code.append("}\n"); 149 } 150 else if (body instanceof ImpliesExpression) 151 { 152 body.accept(this); 153 } 154 else 155 { 156 body.accept(this); 157 } 158 indent--; 159 indent(); 160 code.append("}\n"); 161 if (expr.isTopLevel()) 162 { 163 indent(); 164 code.append("return "+ !breakType + ";\n"); 165 } 166 } 167 } 168 | Popular Tags |