01: /**************************************************************************/
02: /* N I C E */
03: /* A simple imperative object-oriented research language */
04: /* (c) Daniel Bonniot 1999 */
05: /* */
06: /* This program is free software; you can redistribute it and/or modify */
07: /* it under the terms of the GNU General Public License as published by */
08: /* the Free Software Foundation; either version 2 of the License, or */
09: /* (at your option) any later version. */
10: /* */
11: /**************************************************************************/package nice.tools.code;
12:
13: import gnu.expr.*;
14: import gnu.bytecode.*;
15:
16: import nice.lang.inline.OptionOr;
17:
18: /**
19: Ensures that the expression has the given bytecode type.
20:
21: That is, add a cast in the bytecode if necessary.
22:
23: @author Daniel Bonniot
24: */
25:
26: public class EnsureTypeProc extends gnu.mapping.Procedure1 implements
27: Inlineable {
28: public static Expression ensure(Expression exp, Type expectedType) {
29: Type type = exp.getType();
30:
31: if (!type.isAssignableTo(expectedType))
32: return Inline.inline(new EnsureTypeProc(expectedType), exp);
33: else
34: return exp;
35: }
36:
37: private EnsureTypeProc(Type type) {
38: this .type = type;
39: }
40:
41: private Type type;
42:
43: public void compile(ApplyExp exp, Compilation comp, Target target) {
44: CodeAttr code = comp.getCode();
45:
46: Target oldTarget = null;
47: if (target instanceof StackTarget) {
48: oldTarget = target;
49: target = StackTarget.getInstance(type);
50: }
51:
52: exp.getArgs()[0].compile(comp, target);
53:
54: /*
55: If we changed the target, we also have to use the old one.
56: It can happen that both produce code. For instance with
57: int[][] a;
58: a[1][2] = 3; // i.e. set(get(a,1), 2, 3)
59: */
60: if (oldTarget != null)
61: oldTarget.compileFromStack(comp, type);
62: }
63:
64: public gnu.bytecode.Type getReturnType(Expression[] args) {
65: return type;
66: }
67:
68: public Object apply1(Object arg1) {
69: throw new RuntimeException("not implemented");
70: }
71: }
|