KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > polyglot > visit > ConstantFolder


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 /** Visitor which performs constant folding. */
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     // Don't fold String +. Strings are often broken up for better
39
// formatting.
40
if (e instanceof Binary) {
41         Binary b = (Binary) e;
42         
43         if (b.operator() == Binary.ADD &&
44         b.left().constantValue() instanceof String JavaDoc &&
45         b.right().constantValue() instanceof String JavaDoc) {
46         
47         return b;
48         }
49     }
50     
51     Object JavaDoc 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 JavaDoc) {
58         return nf.StringLit(pos,
59                 (String JavaDoc) v).type(ts.String());
60     }
61     if (v instanceof Boolean JavaDoc) {
62         return nf.BooleanLit(pos,
63                  ((Boolean JavaDoc) v).booleanValue()).type(ts.Boolean());
64     }
65     if (v instanceof Double JavaDoc) {
66         return nf.FloatLit(pos, FloatLit.DOUBLE,
67                    ((Double JavaDoc) v).doubleValue()).type(ts.Double());
68     }
69     if (v instanceof Float JavaDoc) {
70         return nf.FloatLit(pos, FloatLit.FLOAT,
71                    ((Float JavaDoc) v).floatValue()).type(ts.Float());
72     }
73     if (v instanceof Long JavaDoc) {
74         return nf.IntLit(pos, IntLit.LONG,
75                  ((Long JavaDoc) v).longValue()).type(ts.Long());
76     }
77     if (v instanceof Integer JavaDoc) {
78         return nf.IntLit(pos, IntLit.INT,
79                  ((Integer JavaDoc) v).intValue()).type(ts.Int());
80     }
81     if (v instanceof Character JavaDoc) {
82         return nf.CharLit(pos,
83                   ((Character JavaDoc) v).charValue()).type(ts.Char());
84     }
85     
86     return e;
87     }
88 }
89
Popular Tags