KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > polyglot > ext > pao > extension > PaoCastExt_c


1 package polyglot.ext.pao.extension;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.Collections JavaDoc;
5 import java.util.List JavaDoc;
6
7 import polyglot.ast.*;
8 import polyglot.ext.pao.types.PaoTypeSystem;
9 import polyglot.types.ConstructorInstance;
10 import polyglot.types.MethodInstance;
11 import polyglot.types.Type;
12
13 /**
14  * The <code>PaoExt</code> implementation for the
15  * <code>Cast</code> AST node.
16  */

17 public class PaoCastExt_c extends PaoExt_c {
18     /**
19      * Insert boxing and unboxing code for the casts inserted by the
20      * <code>PaoBoxer</code>.
21      * @see PaoExt_c#rewrite(PaoTypeSystem, NodeFactory)
22      * @see polyglot.ext.pao.visit.PaoBoxer
23      */

24     public Node rewrite(PaoTypeSystem ts, NodeFactory nf) {
25
26         Cast c = (Cast) node();
27         Type rtype = c.expr().type();
28         Type ltype = c.castType().type();
29
30         if (ltype.isPrimitive() && rtype.isReference()) {
31             // We have an expression with reference type being cast to
32
// a primitive type, added by the PaoBoxer visitor.
33
// We need to unbox.
34

35             // e.g., "(int)e", where e is of type Integer gets rewritten to
36
// "((polyglot.ext.pao.runtime.Integer)e).getInt()"
37

38             MethodInstance mi = ts.getter(ltype.toPrimitive());
39
40             Cast x = nf.Cast(c.position(),
41                              nf.CanonicalTypeNode(c.position(), mi.container()),
42                              c.expr());
43             x = (Cast) x.type(mi.container());
44
45             Call y = nf.Call(c.position(), x, mi.name(),
46                              Collections.EMPTY_LIST);
47             y = (Call) y.type(mi.returnType());
48
49             return y.methodInstance(mi);
50         }
51         else if (ltype.isReference() && rtype.isPrimitive()) {
52             // We have an expression with primitive type being cast to
53
// a reference type, added by the PaoBoxer visitor.
54
// We need to box.
55

56             // e.g., "(Integer)e", where e is of type int gets rewritten to
57
// "new polyglot.ext.pao.runtime.Integer(e)"
58

59             ConstructorInstance ci = ts.wrapper(rtype.toPrimitive());
60
61             List JavaDoc args = new ArrayList JavaDoc(1);
62             args.add(c.expr());
63
64             New x = nf.New(c.position(),
65                            nf.CanonicalTypeNode(c.position(), ci.container()),
66                            args);
67             x = (New) x.type(ci.container());
68             return x.constructorInstance(ci);
69         }
70
71         // Don't need to either box or unbox.
72
return super.rewrite(ts, nf);
73     }
74 }
75
Popular Tags