summaryrefslogtreecommitdiff
path: root/sources/scala/tools/scalai/Evaluator.java
blob: 30c27053a662e2eb786df890096920624a9f35d1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*     ____ ____  ____ ____  ______                                     *\
**    / __// __ \/ __// __ \/ ____/    SOcos COmpiles Scala             **
**  __\_ \/ /_/ / /__/ /_/ /\_ \       (c) 2002, LAMP/EPFL              **
** /_____/\____/\___/\____/____/                                        **
\*                                                                      */

// $OldId: Evaluator.java,v 1.40 2002/10/04 15:37:10 paltherr Exp $
// $Id$

package scala.tools.scalai;

import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import ch.epfl.lamp.util.SourceFile;

import scala.runtime.RunTime;

import scalac.symtab.Symbol;
import scalac.util.Debug;

public class Evaluator {

    //########################################################################
    // Private Classes

    // !!! remove ?
    // !!! is it correct to extend EvaluatorException?
    private static class LabelException extends EvaluatorException {

        public final Symbol symbol;
        public final Object[] args;

        public LabelException(Symbol symbol, Object[] args) {
            this.symbol = symbol;
            this.args = args;
        }
    }

    public static class EvaluationStack {

        public final EvaluationStack stack;
        public final SourceFile source;
        public final Symbol symbol;
        public final Object self;
        public final Object[] args;
        public final Object[] vars;

        public int pos;

        public EvaluationStack(EvaluationStack stack, CodeContainer code,
            Object self, Object[] args)
        {
            this.stack = stack;
            this.source = code.source;
            this.symbol = code.symbol;
            this.self = self;
            this.args = args;
            this.vars = new Object[code.stacksize];
        }

    }

    //########################################################################
    // Private Fields

    private final EvaluatorException trace;
    private EvaluationStack stack;

    //########################################################################
    // Public Constructors

    public Evaluator() {
        this.trace = new EvaluatorException();
        this.stack = null;
    }

    //########################################################################
    // Public Methods

    public Object toString(Object object) {
        try {
            return String.valueOf(object);
        } catch (Throwable exception) {
            return throw_(exception);
        }
    }

    public Object evaluate(Variable module) {
        return load(null, module);
    }

    public Object evaluate(Variable module, Function method, Object[] args) {
        return invoke(load(null, module), method, args);
    }

    public Object evaluate(CodeContainer code) {
        return evaluate(code, null, new Object[0]);
    }

    public Object evaluate(CodePromise code, Object object, Object[] args) {
        return evaluate(code.force(), object, args);
    }

    public Object evaluate(CodeContainer code, Object object, Object[] args) {
        return trace(code, object, args);
    }

    //########################################################################
    // Private Methods - trace

    private Object trace(CodeContainer code, Object object, Object[] args) {
        try {
            try {
                stack = new EvaluationStack(stack, code, object, args);
                return evaluate(code.code);
            } catch (EvaluatorException exception) {
                throw exception;
            } catch (Throwable exception) {
                return throw_(exception, "trace");
            }
        } catch (EvaluatorException exception) {
            exception.addScalaCall(stack.symbol, stack.source, stack.pos);
            throw exception;
        } finally {
            stack = stack.stack;
        }
    }

    //########################################################################
    // Private Methods - evaluate

    private Object evaluate(Code code) {
        switch (code) {

        case Block(Code[] stats, Code value):
            for (int i = 0; i < stats.length; i++) evaluate(stats[i]);
            return evaluate(value);

        case Label(Symbol symbol, Variable[] variables, Code expression):
            while (true)
                try {
                    return evaluate(expression);
                } catch (LabelException exception) {
                    if (exception.symbol != symbol) throw exception;
                    for (int i = 0; i < variables.length; i++) {
                        // !!! null
                        store(null, variables[i], exception.args[i]);
                    }
                }

        case If(Code cond, Code thenp, Code elsep):
            Object value = evaluate(cond);
            assert value instanceof Boolean : value.getClass();
            return evaluate(((Boolean)value).booleanValue() ? thenp : elsep);

        case Switch(Code test, int[] tags, Code[] bodies, Code otherwise):
            Object value = evaluate(test);
            assert value instanceof Integer : value.getClass();
            int tag = ((Integer)value).intValue();
            for (int i = 0; i < tags.length; i++)
                if (tags[i] == tag) return evaluate(bodies[i]);
            return evaluate(otherwise);

        case Literal(Object value):
            return value;

        case Load(Code target, Variable variable):
            return load(evaluate(target), variable);

        case Store(Code target, Variable variable, Code expression):
            store(evaluate(target), variable, evaluate(expression));
            return RunTime.box_uvalue();

        case Invoke(Code target, Function function, Code[] arguments, int pos):
            Object object = evaluate(target);
            Object[] args = new Object[arguments.length];
            for (int i = 0; i < args.length; i++)
                args[i] = evaluate(arguments[i]);
            stack.pos = pos;
            return invoke(object, function, args);

        case Create(ScalaTemplate template):
            return invoke(null, template.getConstructor(),
                new Object[] {template.getHandler()});

        case IsScala(Code target, Symbol symbol):
            Object object = evaluate(target);
            if (object == null || !isScalaObject(object)) return Boolean.FALSE;
            Symbol actual = getScalaObject(object).template.getSymbol();
            return new Boolean(actual.isSubClass(symbol));

        case IsJava(Code target, Class clasz):
            Object object = evaluate(target);
            return new Boolean(clasz.isInstance(object));

        case Or(Code lf, Code rg):
            Object object = evaluate(lf);
            assert object instanceof scala.Boolean : object.getClass();
            boolean value = ((scala.Boolean)object).value;
            if (value) return new Boolean(value);
            return evaluate(rg);

        case And(Code lf, Code rg):
            Object object = evaluate(lf);
            assert object instanceof scala.Boolean : object.getClass();
            boolean value = ((scala.Boolean)object).value;
            if (!value) return new Boolean(value);
            return evaluate(rg);

        case Null:
            return null;

        case Self:
            return stack.self;

        default:
            throw Debug.abort("illegal code", code);
        }
    }

    //########################################################################
    // Private Methods - invoke

    private Object invoke(Object object, Function function, Object[] args) {
        switch (function) {

        case Global(CodePromise code):
            return evaluate(code, object, args);

        case Member(Symbol symbol):
            return getScalaObject(object).invoke(object, symbol, args);

        case Label(Symbol symbol):
            throw new LabelException(symbol, args);

        case JavaConstructor(Constructor constructor):
            return invoke(object, constructor, args);

        case JavaMethod(Method method):
            return invoke(object, method, args);

        case Pos:
            if (object instanceof scala.Int) {
                int value = ((scala.Int)object).value;
                return new Integer(value);
            } else if (object instanceof scala.Long) {
                long value = ((scala.Long)object).value;
                return new Long(value);
            } else if (object instanceof scala.Float) {
                float value = ((scala.Float)object).value;
                return new Float(value);
            } else {
                double value = ((scala.Double)object).value;
                return new Double(value);
            }

        case Neg:
            if (object instanceof scala.Int) {
                int value = ((scala.Int)object).value;
                return new Integer(-value);
            } else if (object instanceof scala.Long) {
                long value = ((scala.Long)object).value;
                return new Long(-value);
            } else if (object instanceof scala.Float) {
                float value = ((scala.Float)object).value;
                return new Float(-value);
            } else {
                double value = ((scala.Double)object).value;
                return new Double(-value);
            }

        case Throw:
            assert args.length == 0 : Debug.show(args);
            assert object instanceof Throwable : object.getClass();
            return throw_((Throwable)object);

        case StringPlus:
            assert args.length == 1 : Debug.show(args);
            //assert object instanceof String : object.getClass().getName();
            return (String.valueOf(object)).concat(String.valueOf(args[0]));

        case EqEq:
            assert args.length == 1 : Debug.show(args);
            return object == null ? new Boolean(args[0] == null) : new Boolean(object.equals(args[0])); // !!!

        case BangEq:
            assert args.length == 1 : Debug.show(args);
            return object == null ? new Boolean(args[0] != null) : new Boolean(!object.equals(args[0])); // !!!

        case HashCode:
            assert args.length == 0 : Debug.show(args);
            return new Integer(getHandlerObject(object).hashCode());

        case ToString:
            assert args.length == 0 : Debug.show(args);
            return getHandlerObject(object).toString();

        default:
            throw Debug.abort("illegal function", function);
        }
    }

    private Object invoke(Object object, Constructor constructor,Object[]args){
        try {
            return constructor.newInstance(args);
        } catch (StackOverflowError exception) {
            return throw_(exception);
        } catch (ExceptionInInitializerError exception) {
            return throw_(exception);
        } catch (InvocationTargetException exception) {
            return throw_(exception);
        } catch (InstantiationException exception) {
            String msg1 = "\n  object = " + Debug.show(object);
            String msg2 = "\n  constr = " + Debug.show(constructor);
            String msg3 = "\n  args   = " + Debug.show(args);
            throw Debug.abort(msg1 + msg2 + msg3, exception);
        } catch (IllegalAccessException exception) {
            String msg1 = "\n  object = " + Debug.show(object);
            String msg2 = "\n  constr = " + Debug.show(constructor);
            String msg3 = "\n  args   = " + Debug.show(args);
            throw Debug.abort(msg1 + msg2 + msg3, exception);
        } catch (IllegalArgumentException exception) {
            String msg1 = "\n  object = " + Debug.show(object);
            String msg2 = "\n  constr = " + Debug.show(constructor);
            String msg3 = "\n  args   = " + Debug.show(args);
            throw Debug.abort(msg1 + msg2 + msg3, exception);
        }
    }

    private Object invoke(Object object, Method method, Object[] args) {
        try {
            return method.invoke(object, args);
        } catch (StackOverflowError exception) {
            return throw_(exception);
        } catch (NullPointerException exception) {
            return throw_(exception);
        } catch (ExceptionInInitializerError exception) {
            return throw_(exception);
        } catch (InvocationTargetException exception) {
            return throw_(exception);
        } catch (IllegalAccessException exception) {
            String msg1 = "\n  object = " + Debug.show(object);
            String msg2 = "\n  method = " + Debug.show(method);
            String msg3 = "\n  args   = " + Debug.show(args);
            throw Debug.abort(msg1 + msg2 + msg3, exception);
        } catch (IllegalArgumentException exception) {
            String msg1 = "\n  object = " + Debug.show(object);
            String msg2 = "\n  method = " + Debug.show(method);
            String msg3 = "\n  args   = " + Debug.show(args);
            throw Debug.abort(msg1 + msg2 + msg3, exception);
        }
    }

    //########################################################################
    // Private Methods - store

    private Object store(Object object, Variable variable, Object value) {
        switch (variable) {

        case Global(_):
            return ((Variable.Global)variable).value = value;

        case Module(_, _):
            return ((Variable.Module)variable).value = value;

        case Member(int index):
            return getScalaObject(object).variables[index] = value;

        case Argument(int index):
            return stack.args[index] = value;

        case Local(int index):
            return stack.vars[index] = value;

        case JavaField(Field field):
            return store(object, field, value);

        default:
            throw Debug.abort("illegal variable", variable);
        }
    }

    private Object store(Object object, Field field, Object value) {
        try {
            field.set(object, value);
            return value;
        } catch (NullPointerException exception) {
            return throw_(exception);
        } catch (ExceptionInInitializerError exception) {
            return throw_(exception);
        } catch (IllegalAccessException exception) {
            String msg1 = "\n  object = " + Debug.show(object);
            String msg2 = "\n  field  = " + Debug.show(field);
            String msg3 = "\n  value  = " + Debug.show(value);
            throw Debug.abort(msg1 + msg2 + msg3, exception);
        } catch (IllegalArgumentException exception) {
            String msg1 = "\n  object = " + Debug.show(object);
            String msg2 = "\n  field  = " + Debug.show(field);
            String msg3 = "\n  value  = " + Debug.show(value);
            throw Debug.abort(msg1 + msg2 + msg3, exception);
        }
    }

    //########################################################################
    // Private Methods - load

    private Object load(Object object, Variable variable) {
        switch (variable) {

        case Global(Object value):
            return value;

        case Module(CodePromise body, Object value):
            if (value != null) return value;
            ((Variable.Module)variable).body = null;
            evaluate(body, null, new Object[0]);
            return load(object, variable);

        case Member(int index):
            return getScalaObject(object).variables[index];

        case Argument(int index):
            return stack.args[index];

        case Local(int index):
            return stack.vars[index];

        case JavaField(Field field):
            return load(object, field);

        default:
            throw Debug.abort("illegal variable", variable);
        }
    }

    private Object load(Object object, Field field) {
        try {
            return field.get(object);
        } catch (NullPointerException exception) {
            return throw_(exception);
        } catch (ExceptionInInitializerError exception) {
            return throw_(exception);
        } catch (IllegalAccessException exception) {
            String msg1 = "\n  object = " + Debug.show(object);
            String msg2 = "\n  field  = " + Debug.show(field);
            throw Debug.abort(msg1 + msg2, exception);
        } catch (IllegalArgumentException exception) {
            String msg1 = "\n  object = " + Debug.show(object);
            String msg2 = "\n  field  = " + Debug.show(field);
            throw Debug.abort(msg1 + msg2, exception);
        }
    }

    //########################################################################
    // Private Methods - throw

    private Object throw_(Throwable exception) {
        return throw_(exception, null);
    }

    private Object throw_(Throwable exception, String method) {
        if (exception.getCause() != null && (
                exception instanceof ExceptionInInitializerError ||
                exception instanceof InvocationTargetException))
            exception = exception.getCause();
        if (trace.getCause() != exception) trace.reset(exception);
        trace.addScalaLeavePoint(getClass().getName(), method);
        throw trace;
    }

    //########################################################################
    // Private Methods - !!!

    private boolean isScalaObject(Object object) {
        return Proxy.isProxyClass(object.getClass()); // !!! add more checks ?
    }

    private ScalaObject getScalaObject(Object object) {
        Object handler = getHandlerObject(object);
        assert handler instanceof ScalaObject : handler.getClass();
        return (ScalaObject)handler;
    }

    private Object getHandlerObject(Object object) {
        if (object == null) return throw_(new NullPointerException());
        assert object instanceof Proxy : object.getClass();
        return Proxy.getInvocationHandler(object);
    }

    //########################################################################
}