1 package polyglot.visit; 2 3 import polyglot.ast.*; 4 import polyglot.types.TypeSystem; 5 import polyglot.frontend.Job; 6 import polyglot.util.Position; 7 8 9 public class ConstantFolder extends NodeVisitor 10 { 11 TypeSystem ts; 12 NodeFactory nf; 13 14 public ConstantFolder(TypeSystem ts, NodeFactory nf) { 15 this.ts = ts; 16 this.nf = nf; 17 } 18 19 public TypeSystem typeSystem() { 20 return ts; 21 } 22 23 public NodeFactory nodeFactory() { 24 return nf; 25 } 26 27 public Node leave(Node old, Node n, NodeVisitor v_) { 28 if (! (n instanceof Expr)) { 29 return n; 30 } 31 32 Expr e = (Expr) n; 33 34 if (! e.isConstant()) { 35 return e; 36 } 37 38 if (e instanceof Binary) { 41 Binary b = (Binary) e; 42 43 if (b.operator() == Binary.ADD && 44 b.left().constantValue() instanceof String && 45 b.right().constantValue() instanceof String ) { 46 47 return b; 48 } 49 } 50 51 Object v = e.constantValue(); 52 Position pos = e.position(); 53 54 if (v == null) { 55 return nf.NullLit(pos).type(ts.Null()); 56 } 57 if (v instanceof String ) { 58 return nf.StringLit(pos, 59 (String ) v).type(ts.String()); 60 } 61 if (v instanceof Boolean ) { 62 return nf.BooleanLit(pos, 63 ((Boolean ) v).booleanValue()).type(ts.Boolean()); 64 } 65 if (v instanceof Double ) { 66 return nf.FloatLit(pos, FloatLit.DOUBLE, 67 ((Double ) v).doubleValue()).type(ts.Double()); 68 } 69 if (v instanceof Float ) { 70 return nf.FloatLit(pos, FloatLit.FLOAT, 71 ((Float ) v).floatValue()).type(ts.Float()); 72 } 73 if (v instanceof Long ) { 74 return nf.IntLit(pos, IntLit.LONG, 75 ((Long ) v).longValue()).type(ts.Long()); 76 } 77 if (v instanceof Integer ) { 78 return nf.IntLit(pos, IntLit.INT, 79 ((Integer ) v).intValue()).type(ts.Int()); 80 } 81 if (v instanceof Character ) { 82 return nf.CharLit(pos, 83 ((Character ) v).charValue()).type(ts.Char()); 84 } 85 86 return e; 87 } 88 } 89 | Popular Tags |