KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > polyglot > ext > pao > visit > PaoBoxer


1 package polyglot.ext.pao.visit;
2
3 import polyglot.ast.Expr;
4 import polyglot.ast.Node;
5 import polyglot.ast.NodeFactory;
6 import polyglot.ext.pao.extension.PaoExt;
7 import polyglot.ext.pao.types.PaoTypeSystem;
8 import polyglot.frontend.Job;
9 import polyglot.types.SemanticException;
10 import polyglot.types.Type;
11 import polyglot.types.TypeSystem;
12 import polyglot.util.Position;
13 import polyglot.visit.AscriptionVisitor;
14 import polyglot.visit.NodeVisitor;
15
16 /**
17  * Visitor that inserts boxing and unboxing code into the AST.
18  * <code>PaoBoxer</code> accomplishes this task by first inserting explicit
19  * casts into the AST, where primitive values need to be treated as objects,
20  * and then uses the {@link PaoExt#rewrite(PaoTypeSystem, NodeFactory) PaoExt.rewrite(PaoTypeSystem, NodeFactory)}
21  * method to rewrite these explicit casts into appropriate boxing and
22  * unboxing code.
23  */

24 public class PaoBoxer extends AscriptionVisitor
25 {
26     public PaoBoxer(Job job, TypeSystem ts, NodeFactory nf) {
27         super(job, ts, nf);
28     }
29
30     /**
31      * Inserts an explicit cast if the type of expressions <code>e</code> is
32      * a primitive type, and the type <code>toType</code> is a reference type.
33      * For example, <code>Integer i = 42</code> will be modified to
34      * <code>Integer i = (Object)42</code>. The <code>leaveCall</code> method
35      * will ensure that these explicit casts are rewritten to the correct
36      * boxing and unboxing code.
37      */

38     public Expr ascribe(Expr e, Type toType) {
39         Type fromType = e.type();
40
41         if (toType == null) {
42             return e;
43         }
44
45         Position p = e.position();
46
47         // Insert a cast. Translation of the cast will insert the
48
// correct boxing/unboxing code.
49
if (toType.isReference() && fromType.isPrimitive()) {
50             return nf.Cast(p, nf.CanonicalTypeNode(p, ts.Object()), e);
51         }
52
53         return e;
54     }
55
56     /**
57      * Calls the
58      * {@link PaoExt#rewrite(PaoTypeSystem, NodeFactory) PaoExt.rewrite(PaoTypeSystem, NodeFactory)}
59      * method to rewrite the explicit casts inserted by the
60      * <code>ascribe</code> method into correct boxing and unboxing code.
61      */

62     public Node leaveCall(Node old, Node n, NodeVisitor v) throws SemanticException {
63         n = super.leaveCall(old, n, v);
64
65         if (n.ext() instanceof PaoExt) {
66             return ((PaoExt) n.ext()).rewrite((PaoTypeSystem) typeSystem(),
67                                               nodeFactory());
68         }
69
70         return n;
71     }
72 }
73
Popular Tags