Source

lang-js / js / opcodes.py

  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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
from js.jsobj import W_IntNumber, W_FloatNumber, W_String,\
     W_Array, W_PrimitiveObject, ActivationObject,\
     create_object, W_Object, w_Undefined, newbool,\
     w_True, w_False, W_List, w_Null, W_Iterator, W_Root
import js.jsobj as jsobj
from js.execution import JsTypeError, ReturnException, ThrowException
from js.baseop import plus, sub, compare, AbstractEC, StrictEC,\
     compare_e, increment, decrement, commonnew, mult, division, uminus, mod
from pypy.rlib.rarithmetic import intmask

class Opcode(object):
    def __init__(self):
        pass

    def eval(self, ctx, stack):
        """ Execute in context ctx
        """
        raise NotImplementedError

    def __repr__(self):
        return self.__class__.__name__

class BaseBinaryComparison(Opcode):
    def eval(self, ctx, stack):
        s4 = stack.pop()
        s2 = stack.pop()
        stack.append(self.decision(ctx, s2, s4))

    def decision(self, ctx, op1, op2):
        raise NotImplementedError

class BaseBinaryBitwiseOp(Opcode):
    def eval(self, ctx, stack):
        s5 = stack.pop().ToInt32(ctx)
        s6 = stack.pop().ToInt32(ctx)
        stack.append(self.operation(ctx, s5, s6))

    def operation(self, ctx, op1, op2):
        raise NotImplementedError

class BaseBinaryOperation(Opcode):
    def eval(self, ctx, stack):
        right = stack.pop()
        left = stack.pop()
        stack.append(self.operation(ctx, left, right))

class BaseUnaryOperation(Opcode):
    pass

class Undefined(Opcode):
    def eval(self, ctx, stack):
        stack.append(w_Undefined)

class LOAD_INTCONSTANT(Opcode):
    _immutable_fields_ = ['w_intvalue']
    def __init__(self, value):
        self.w_intvalue = W_IntNumber(int(value))

    def eval(self, ctx, stack):
        stack.append(self.w_intvalue)

    def __repr__(self):
        return 'LOAD_INTCONSTANT %s' % (self.w_intvalue.intval,)

class LOAD_BOOLCONSTANT(Opcode):
    def __init__(self, value):
        self.boolval = value

    def eval(self, ctx, stack):
        stack.append(newbool(self.boolval))

class LOAD_FLOATCONSTANT(Opcode):
    def __init__(self, value):
        self.w_floatvalue = W_FloatNumber(float(value))

    def eval(self, ctx, stack):
        stack.append(self.w_floatvalue)

    def __repr__(self):
        return 'LOAD_FLOATCONSTANT %s' % (self.w_floatvalue.floatval,)

class LOAD_STRINGCONSTANT(Opcode):
    _immutable_fields_ = ['w_stringvalue']
    def __init__(self, value):
        self.w_stringvalue = W_String(value)

    def eval(self, ctx, stack):
        stack.append(self.w_stringvalue)

    #def get_literal(self, ctx):
    #    return W_String(self.strval).ToString(ctx)

    def __repr__(self):
        return 'LOAD_STRINGCONSTANT "%s"' % (self.w_stringvalue.strval,)

class LOAD_UNDEFINED(Opcode):
    def eval(self, ctx, stack):
        stack.append(w_Undefined)

class LOAD_NULL(Opcode):
    def eval(self, ctx, stack):
        stack.append(w_Null)

class LOAD_VARIABLE(Opcode):
    _immutable_fields_ = ['identifier']
    def __init__(self, identifier):
        self.identifier = identifier

    def eval(self, ctx, stack):
        stack.append(ctx.resolve_identifier(ctx, self.identifier))

    def __repr__(self):
        return 'LOAD_VARIABLE "%s"' % (self.identifier,)

class LOAD_REALVAR(Opcode):
    def __init__(self, depth, identifier):
        self.depth = depth
        self.identifier = identifier

    def eval(self, ctx, stack):
        raise NotImplementedError()
        # XXX
        # scope = ctx.scope[self.depth]
        # stack.append(scope.Get(ctx, self.identifier))
        #stack.append(W_Reference(self.identifier, scope))

    def __repr__(self):
        return 'LOAD_VARIABLE "%s"' % (self.identifier,)

class LOAD_ARRAY(Opcode):
    def __init__(self, counter):
        self.counter = counter

    def eval(self, ctx, stack):
        proto = ctx.get_global().Get(ctx, 'Array').Get(ctx, 'prototype')
        array = W_Array(ctx, Prototype=proto, Class = proto.Class)
        for i in range(self.counter):
            array.Put(ctx, str(self.counter - i - 1), stack.pop())
        stack.append(array)

    def __repr__(self):
        return 'LOAD_ARRAY %d' % (self.counter,)

class LOAD_LIST(Opcode):
    _immutable_fields_ = ['counter']
    def __init__(self, counter):
        self.counter = counter

    def eval(self, ctx, stack):
        list_w = stack.pop_n(self.counter)[:] # pop_n returns a non-resizable list
        stack.append(W_List(list_w))

    def __repr__(self):
        return 'LOAD_LIST %d' % (self.counter,)

class LOAD_FUNCTION(Opcode):
    def __init__(self, funcobj):
        self.funcobj = funcobj

    def eval(self, ctx, stack):
        proto = ctx.get_global().Get(ctx, 'Function').Get(ctx, 'prototype')
        w_func = W_Object(ctx=ctx, Prototype=proto, Class='Function',
                          callfunc=self.funcobj)
        w_func.Put(ctx, 'length', W_IntNumber(len(self.funcobj.params)))
        w_obj = create_object(ctx, 'Object')
        w_obj.Put(ctx, 'constructor', w_func, flags = jsobj.DE)
        w_func.Put(ctx, 'prototype', w_obj)
        stack.append(w_func)

    def __repr__(self):
        return 'LOAD_FUNCTION' # XXX

# class STORE_VAR(Opcode):
#     def __init__(self, depth, name):
#         self.name = name
#         self.depth = depth

#     def eval(self, ctx, stack):
#         value = stack[-1]
#         ctx.scope[self.depth].Put(ctx, self.name, value)

#     def __repr__(self):
#         return 'STORE_VAR "%s"' % self.name

class LOAD_OBJECT(Opcode):
    def __init__(self, counter):
        self.counter = counter

    def eval(self, ctx, stack):
        w_obj = create_object(ctx, 'Object')
        for _ in range(self.counter):
            name = stack.pop().ToString(ctx)
            w_elem = stack.pop()
            w_obj.Put(ctx, name, w_elem)
        stack.append(w_obj)

    def __repr__(self):
        return 'LOAD_OBJECT %d' % (self.counter,)

class LOAD_MEMBER(Opcode):
    def eval(self, ctx, stack):
        w_obj = stack.pop().ToObject(ctx)
        name = stack.pop().ToString(ctx)
        stack.append(w_obj.Get(ctx, name))

class COMMA(BaseUnaryOperation):
    def eval(self, ctx, stack):
        one = stack.pop()
        stack.pop()
        stack.append(one)
        # XXX

class SUB(BaseBinaryOperation):
    def operation(self, ctx, left, right):
        return sub(ctx, left, right)

class IN(BaseBinaryOperation):
    def operation(self, ctx, left, right):
        if not isinstance(right, W_Object):
            raise ThrowException(W_String("TypeError"))
        name = left.ToString(ctx)
        return newbool(right.HasProperty(name))

class TYPEOF(BaseUnaryOperation):
    def eval(self, ctx, stack):
        one = stack.pop()
        stack.append(W_String(one.type()))

class TYPEOF_VARIABLE(Opcode):
    def __init__(self, name):
        self.name = name

    def eval(self, ctx, stack):
        try:
            var = ctx.resolve_identifier(ctx, self.name)
            stack.append(W_String(var.type()))
        except ThrowException:
            stack.append(W_String('undefined'))

#class Typeof(UnaryOp):
#    def eval(self, ctx):
#        val = self.expr.eval(ctx)
#        if isinstance(val, W_Reference) and val.GetBase() is None:
#            return W_String("undefined")
#        return W_String(val.GetValue().type())

class ADD(BaseBinaryOperation):
    def operation(self, ctx, left, right):
        return plus(ctx, left, right)

class BITAND(BaseBinaryBitwiseOp):
    def operation(self, ctx, op1, op2):
        return W_IntNumber(op1&op2)

class BITXOR(BaseBinaryBitwiseOp):
    def operation(self, ctx, op1, op2):
        return W_IntNumber(op1^op2)

class BITOR(BaseBinaryBitwiseOp):
    def operation(self, ctx, op1, op2):
        return W_IntNumber(op1|op2)

class BITNOT(BaseUnaryOperation):
    def eval(self, ctx, stack):
        op = stack.pop().ToInt32(ctx)
        stack.append(W_IntNumber(~op))

class URSH(BaseBinaryBitwiseOp):
    def eval(self, ctx, stack):
        op2 = stack.pop().ToUInt32(ctx)
        op1 = stack.pop().ToUInt32(ctx)
        # XXX check if it could fit into int
        stack.append(W_FloatNumber(op1 >> (op2 & 0x1F)))

class RSH(BaseBinaryBitwiseOp):
    def eval(self, ctx, stack):
        op2 = stack.pop().ToUInt32(ctx)
        op1 = stack.pop().ToInt32(ctx)
        stack.append(W_IntNumber(op1 >> intmask(op2 & 0x1F)))

class LSH(BaseBinaryBitwiseOp):
    def eval(self, ctx, stack):
        op2 = stack.pop().ToUInt32(ctx)
        op1 = stack.pop().ToInt32(ctx)
        stack.append(W_IntNumber(op1 << intmask(op2 & 0x1F)))

class MUL(BaseBinaryOperation):
    def operation(self, ctx, op1, op2):
        return mult(ctx, op1, op2)

class DIV(BaseBinaryOperation):
    def operation(self, ctx, op1, op2):
        return division(ctx, op1, op2)

class MOD(BaseBinaryOperation):
    def operation(self, ctx, op1, op2):
        return mod(ctx, op1, op2)

class UPLUS(BaseUnaryOperation):
    def eval(self, ctx, stack):
        if isinstance(stack.top(), W_IntNumber):
            return
        if isinstance(stack.top(), W_FloatNumber):
            return
        stack.append(W_FloatNumber(stack.pop().ToNumber(ctx)))

class UMINUS(BaseUnaryOperation):
    def eval(self, ctx, stack):
        stack.append(uminus(stack.pop(), ctx))

class NOT(BaseUnaryOperation):
    def eval(self, ctx, stack):
        stack.append(newbool(not stack.pop().ToBoolean()))

class INCR(BaseUnaryOperation):
    def eval(self, ctx, stack):
        value = stack.pop()
        newvalue = increment(ctx, value)
        stack.append(newvalue)

class DECR(BaseUnaryOperation):
    def eval(self, ctx, stack):
        value = stack.pop()
        newvalue = decrement(ctx, value)
        stack.append(newvalue)

class GT(BaseBinaryComparison):
    def decision(self, ctx, op1, op2):
        return newbool(compare(ctx, op1, op2))

class GE(BaseBinaryComparison):
    def decision(self, ctx, op1, op2):
        return newbool(compare_e(ctx, op1, op2))

class LT(BaseBinaryComparison):
    def decision(self, ctx, op1, op2):
        return newbool(compare(ctx, op2, op1))

class LE(BaseBinaryComparison):
    def decision(self, ctx, op1, op2):
        return newbool(compare_e(ctx, op2, op1))

class EQ(BaseBinaryComparison):
    def decision(self, ctx, op1, op2):
        return newbool(AbstractEC(ctx, op1, op2))

class NE(BaseBinaryComparison):
    def decision(self, ctx, op1, op2):
        return newbool(not AbstractEC(ctx, op1, op2))

class IS(BaseBinaryComparison):
    def decision(self, ctx, op1, op2):
        return newbool(StrictEC(ctx, op1, op2))

class ISNOT(BaseBinaryComparison):
    def decision(self, ctx, op1, op2):
        return newbool(not StrictEC(ctx, op1, op2))

class STORE_MEMBER(Opcode):
    def eval(self, ctx, stack):
        left = stack.pop()
        member = stack.pop()
        value = stack.pop()
        name = member.ToString(ctx)
        left.ToObject(ctx).Put(ctx, name, value)
        stack.append(value)

class STORE(Opcode):
    _immutable_fields_ = ['name']
    def __init__(self, name):
        self.name = name

    def eval(self, ctx, stack):
        value = stack.top()
        ctx.assign(self.name, value)

    def __repr__(self):
        return '%s "%s"' % (self.__class__.__name__, self.name)

class LABEL(Opcode):
    def __init__(self, num):
        self.num = num

    def __repr__(self):
        return 'LABEL %d' % (self.num,)

class BaseJump(Opcode):
    _immutable_fields_ = ['where']
    def __init__(self, where):
        self.where = where
        self.decision = False

    def do_jump(self, stack, pos):
        return 0

    def __repr__(self):
        return '%s %d' % (self.__class__.__name__, self.where)

class JUMP(BaseJump):
    def eval(self, ctx, stack):
        pass

    def do_jump(self, stack, pos):
        return self.where

class BaseIfJump(BaseJump):
    def eval(self, ctx, stack):
        value = stack.pop()
        self.decision = value.ToBoolean()

class BaseIfNopopJump(BaseJump):
    def eval(self, ctx, stack):
        value = stack.top()
        self.decision = value.ToBoolean()

class JUMP_IF_FALSE(BaseIfJump):
    def do_jump(self, stack, pos):
        if self.decision:
            return pos + 1
        return self.where

class JUMP_IF_FALSE_NOPOP(BaseIfNopopJump):
    def do_jump(self, stack, pos):
        if self.decision:
            stack.pop()
            return pos + 1
        return self.where

class JUMP_IF_TRUE(BaseIfJump):
    def do_jump(self, stack, pos):
        if self.decision:
            return self.where
        return pos + 1

class JUMP_IF_TRUE_NOPOP(BaseIfNopopJump):
    def do_jump(self, stack, pos):
        if self.decision:
            return self.where
        stack.pop()
        return pos + 1

class DECLARE_FUNCTION(Opcode):
    def __init__(self, funcobj):
        self.funcobj = funcobj

    def eval(self, ctx, stack):
        # function declaration actyally don't run anything
        proto = ctx.get_global().Get(ctx, 'Function').Get(ctx, 'prototype')
        w_func = W_Object(ctx=ctx, Prototype=proto, Class='Function', callfunc=self.funcobj)
        w_func.Put(ctx, 'length', W_IntNumber(len(self.funcobj.params)))
        w_obj = create_object(ctx, 'Object')
        w_obj.Put(ctx, 'constructor', w_func, flags = jsobj.DE)
        w_func.Put(ctx, 'prototype', w_obj)
        if self.funcobj.name is not None:
            ctx.scope[-1].Put(ctx, self.funcobj.name, w_func)

    def __repr__(self):
        funcobj = self.funcobj
        if funcobj.name is None:
            name = ""
        else:
            name = funcobj.name + " "
        codestr = '\n'.join(['  %r' % (op,) for op in funcobj.opcodes])
        return 'DECLARE_FUNCTION %s%r [\n%s\n]' % (name, funcobj.params, codestr)

class DECLARE_VAR(Opcode):
    def __init__(self, name):
        self.name = name

    def eval(self, ctx, stack):
        ctx.declare_variable(self.name)

    def __repr__(self):
        return 'DECLARE_VAR "%s"' % (self.name,)

class RETURN(Opcode):
    def eval(self, ctx, stack):
        raise ReturnException(stack.pop())

class POP(Opcode):
    def eval(self, ctx, stack):
        stack.pop()

def common_call(ctx, r1, args, this, name):
    if not isinstance(r1, W_PrimitiveObject):
        raise ThrowException(W_String("%s is not a callable (%s)"%(r1.ToString(ctx), name)))
    try:
        res = r1.Call(ctx=ctx, args=args.tolist(), this=this)
    except JsTypeError:
        raise ThrowException(W_String("%s is not a function (%s)"%(r1.ToString(ctx), name)))
    return res

class CALL(Opcode):
    def eval(self, ctx, stack):
        r1 = stack.pop()
        args = stack.pop()
        name = r1.ToString(ctx)
        #XXX hack, this should be comming from context
        stack.append(common_call(ctx, r1, args, ctx.scope[-1], name))

class CALL_METHOD(Opcode):
    def eval(self, ctx, stack):
        method = stack.pop()
        what = stack.pop().ToObject(ctx)
        args = stack.pop()
        name = method.ToString(ctx)
        r1 = what.Get(ctx, name)
        stack.append(common_call(ctx, r1, args, what, name))

#class CALL_BASEOP(Opcode):
    #def __init__(self, baseop):
        #self.baseop = baseop

    #def eval(self, ctx, stack):
        #from js.baseop import get_baseop_func
        #func = get_baseop_func(self.baseop)
        #args = stack.pop_n(func.argcount)
        #kwargs = {'ctx':ctx}
        #val = func(*args, **kwargs)
        #stack.append(val)

    #def __repr__(self):
        #from js.baseop import get_baseop_name, get_baseop_func
        #return "CALL_BASEOP %s (%d)" % (get_baseop_name(self.baseop), self.baseop)

class DUP(Opcode):
    def eval(self, ctx, stack):
        stack.append(stack.top())

class THROW(Opcode):
    def eval(self, ctx, stack):
        val = stack.pop()
        raise ThrowException(val)

class TRYCATCHBLOCK(Opcode):
    def __init__(self, tryfunc, catchparam, catchfunc, finallyfunc):
        self.tryfunc     = tryfunc
        self.catchfunc   = catchfunc
        self.catchparam  = catchparam
        self.finallyfunc = finallyfunc

    def eval(self, ctx, stack):
        try:
            try:
                self.tryfunc.run(ctx)
            except ThrowException, e:
                if self.catchfunc is not None:
                    # XXX just copied, I don't know if it's right
                    obj = W_Object()
                    obj.Put(ctx, self.catchparam, e.exception)
                    ctx.push_object(obj)
                    try:
                        self.catchfunc.run(ctx)
                    finally:
                        ctx.pop_object()
                if self.finallyfunc is not None:
                    self.finallyfunc.run(ctx)
                if not self.catchfunc:
                    raise
        except ReturnException:
            # we run finally block here and re-raise the exception
            if self.finallyfunc is not None:
                self.finallyfunc.run(ctx)
            raise

    def __repr__(self):
        return "TRYCATCHBLOCK" # XXX shall we add stuff here???

class NEW(Opcode):
    def eval(self, ctx, stack):
        y = stack.pop()
        x = stack.pop()
        assert isinstance(y, W_List)
        args = y.get_args()
        stack.append(commonnew(ctx, x, args))

class NEW_NO_ARGS(Opcode):
    def eval(self, ctx, stack):
        x = stack.pop()
        stack.append(commonnew(ctx, x, []))

# ------------ iterator support ----------------

class LOAD_ITERATOR(Opcode):
    def eval(self, ctx, stack):
        obj = stack.pop().ToObject(ctx)
        props = [prop.value for prop in obj.propdict.values() if not prop.flags & jsobj.DE]
        stack.append(W_Iterator(props))

class JUMP_IF_ITERATOR_EMPTY(BaseJump):
    def eval(self, ctx, stack):
        pass

    def do_jump(self, stack, pos):
        iterator = stack.top()
        assert isinstance(iterator, W_Iterator)
        if iterator.empty():
            return self.where
        return pos + 1

class NEXT_ITERATOR(Opcode):
    def __init__(self, name):
        self.name = name

    def eval(self, ctx, stack):
        iterator = stack.top()
        assert isinstance(iterator, W_Iterator)
        ctx.assign(self.name, iterator.next())

# ---------------- with support ---------------------

class WITH_START(Opcode):
    def eval(self, ctx, stack):
        obj = stack.pop().ToObject(ctx)
        ctx.push_object(obj)

class WITH_END(Opcode):
    def eval(self, ctx, stack):
        ctx.pop_object()

# ------------------ delete -------------------------

class DELETE(Opcode):
    def __init__(self, name):
        self.name = name

    def eval(self, ctx, stack):
        stack.append(newbool(ctx.delete_identifier(self.name)))

class DELETE_MEMBER(Opcode):
    def eval(self, ctx, stack):
        what = stack.pop().ToString(ctx)
        obj = stack.pop().ToObject(ctx)
        stack.append(newbool(obj.Delete(what)))

class LOAD_LOCAL(Opcode):
    _immutable_fields_ = ['local']
    def __init__(self, local):
        self.local = local

    def eval(self, ctx, stack):
        stack.append(ctx.get_local_value(self.local))

    def __repr__(self):
        return 'LOAD_LOCAL %d' % (self.local,)

class STORE_LOCAL(Opcode):
    _immutable_fields_ = ['local']
    def __init__(self, local):
        self.local = local

    def eval(self, ctx, stack):
        value = stack.top()
        ctx.assign_local(self.local, value)

    def __repr__(self):
        return 'STORE_LOCAL %d' % (self.local,)

# different opcode mappings, to make annotator happy

OpcodeMap = {}

for name, value in locals().items():
    if name.upper() == name and type(value) == type(Opcode) and issubclass(value, Opcode):
        OpcodeMap[name] = value

class Opcodes:
    pass

opcodes = Opcodes()
for name, value in OpcodeMap.items():
    setattr(opcodes, name, value)