-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathbase.py
More file actions
2780 lines (2445 loc) · 107 KB
/
base.py
File metadata and controls
2780 lines (2445 loc) · 107 KB
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''Most important file in Js2Py implementation: PyJs class - father of all PyJs objects'''
from copy import copy
import re
from .translators.friendly_nodes import REGEXP_CONVERTER
from .utils.injector import fix_js_args
from types import FunctionType, ModuleType, GeneratorType, BuiltinFunctionType, MethodType, BuiltinMethodType
import traceback
try:
import numpy
NUMPY_AVAILABLE = True
except:
NUMPY_AVAILABLE = False
# python 3 support
import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
def str_repr(s):
if six.PY2:
return s.encode('utf-8')
else:
return s
def MakeError(name, message):
"""Returns PyJsException with PyJsError inside"""
return JsToPyException(ERRORS[name](Js(message)))
def to_python(val):
if not isinstance(val, PyJs):
return val
if isinstance(val, PyJsUndefined) or isinstance(val, PyJsNull):
return None
elif isinstance(val, PyJsNumber):
# this can be either float or long/int better to assume its int/long when a whole number...
v = val.value
try:
i = int(v) if v==v else v # nan...
return v if i!=v else i
except:
return v
elif isinstance(val, (PyJsString, PyJsBoolean)):
return val.value
elif isinstance(val, PyObjectWrapper):
return val.__dict__['obj']
return JsObjectWrapper(val)
def to_dict(js_obj, known=None): # fixed recursion error in self referencing objects
res = {}
if known is None:
known = {}
if js_obj in known:
return known[js_obj]
known[js_obj] = res
for k in js_obj:
name = k.value
input = js_obj.get(name)
output = to_python(input)
if isinstance(output, JsObjectWrapper):
if output._obj.Class=='Object':
output = to_dict(output._obj, known)
known[input] = output
elif output._obj.Class in ['Array','Int8Array','Uint8Array','Uint8ClampedArray','Int16Array','Uint16Array','Int32Array','Uint32Array','Float32Array','Float64Array']:
output = to_list(output._obj)
known[input] = output
res[name] = output
return res
def to_list(js_obj, known=None):
res = len(js_obj)*[None]
if known is None:
known = {}
if js_obj in known:
return known[js_obj]
known[js_obj] = res
for k in js_obj:
try:
name = int(k.value)
except:
continue
input = js_obj.get(str(name))
output = to_python(input)
if isinstance(output, JsObjectWrapper):
if output._obj.Class in ['Array', 'Int8Array','Uint8Array','Uint8ClampedArray','Int16Array','Uint16Array','Int32Array','Uint32Array','Float32Array','Float64Array', 'Arguments']:
output = to_list(output._obj, known)
known[input] = output
elif output._obj.Class in ['Object']:
output = to_dict(output._obj)
known[input] = output
res[name] = output
return res
def HJs(val):
if hasattr(val, '__call__'): #
@Js
def PyWrapper(this, arguments, var=None):
args = tuple(to_python(e) for e in arguments.to_list())
try:
py_res = val.__call__(*args)
except Exception as e:
message = 'your Python function failed! '
try:
message += e.message
except:
pass
raise MakeError('Error', message)
return py_wrap(py_res)
try:
PyWrapper.func_name = val.__name__
except:
pass
return PyWrapper
if isinstance(val, tuple):
val = list(val)
return Js(val)
def Js(val, Clamped=False):
'''Converts Py type to PyJs type'''
if isinstance(val, PyJs):
return val
elif val is None:
return undefined
elif isinstance(val, basestring):
return PyJsString(val, StringPrototype)
elif isinstance(val, bool):
return true if val else false
elif isinstance(val, float) or isinstance(val, int) or isinstance(val, long) or (NUMPY_AVAILABLE and isinstance(val, (numpy.int8,numpy.uint8,
numpy.int16,numpy.uint16,
numpy.int32,numpy.uint32,
numpy.float32,numpy.float64))):
# This is supposed to speed things up. may not be the case
if val in NUM_BANK:
return NUM_BANK[val]
return PyJsNumber(float(val), NumberPrototype)
elif isinstance(val, FunctionType):
return PyJsFunction(val, FunctionPrototype)
#elif isinstance(val, ModuleType):
# mod = {}
# for name in dir(val):
# value = getattr(val, name)
# if isinstance(value, ModuleType):
# continue # prevent recursive module conversion
# try:
# jsval = HJs(value)
# except RuntimeError:
# print 'Could not convert %s to PyJs object!' % name
# continue
# mod[name] = jsval
# return Js(mod)
#elif isintance(val, ClassType):
elif isinstance(val, dict): # convert to object
temp = PyJsObject({}, ObjectPrototype)
for k, v in six.iteritems(val):
temp.put(Js(k), Js(v))
return temp
elif isinstance(val, (list, tuple)): #Convert to array
return PyJsArray(val, ArrayPrototype)
# convert to typedarray
elif isinstance(val, JsObjectWrapper):
return val.__dict__['_obj']
elif NUMPY_AVAILABLE and isinstance(val, numpy.ndarray):
if val.dtype == numpy.int8:
return PyJsInt8Array(val, Int8ArrayPrototype)
elif val.dtype == numpy.uint8 and not Clamped:
return PyJsUint8Array(val, Uint8ArrayPrototype)
elif val.dtype == numpy.uint8 and Clamped:
return PyJsUint8ClampedArray(val, Uint8ClampedArrayPrototype)
elif val.dtype == numpy.int16:
return PyJsInt16Array(val, Int16ArrayPrototype)
elif val.dtype == numpy.uint16:
return PyJsUint16Array(val, Uint16ArrayPrototype)
elif val.dtype == numpy.int32:
return PyJsInt32Array(val, Int32ArrayPrototype)
elif val.dtype == numpy.uint32:
return PyJsUint16Array(val, Uint32ArrayPrototype)
elif val.dtype == numpy.float32:
return PyJsFloat32Array(val, Float32ArrayPrototype)
elif val.dtype == numpy.float64:
return PyJsFloat64Array(val, Float64ArrayPrototype)
else: # try to convert to js object
return py_wrap(val)
#raise RuntimeError('Cant convert python type to js (%s)' % repr(val))
#try:
# obj = {}
# for name in dir(val):
# if name.startswith('_'): #dont wrap attrs that start with _
# continue
# value = getattr(val, name)
# import types
# if not isinstance(value, (FunctionType, BuiltinFunctionType, MethodType, BuiltinMethodType,
# dict, int, basestring, bool, float, long, list, tuple)):
# continue
# obj[name] = HJs(value)
# return Js(obj)
#except:
# raise RuntimeError('Cant convert python type to js (%s)' % repr(val))
def Type(val):
try:
return val.TYPE
except:
raise RuntimeError('Invalid type: '+str(val))
def is_data_descriptor(desc):
return desc and ('value' in desc or 'writable' in desc)
def is_accessor_descriptor(desc):
return desc and ('get' in desc or 'set' in desc)
def is_generic_descriptor(desc):
return desc and not (is_data_descriptor(desc) or is_accessor_descriptor(desc))
##############################################################################
class PyJs(object):
PRIMITIVES = frozenset(['String', 'Number', 'Boolean', 'Undefined', 'Null'])
TYPE = 'Object'
Class = None
extensible = True
prototype = None
own = {}
GlobalObject = None
IS_CHILD_SCOPE = False
value = None
buff = None
def __init__(self, value=None, prototype=None, extensible=False):
'''Constructor for Number String and Boolean'''
# I dont think this is needed anymore
# if self.Class=='String' and not isinstance(value, basestring):
# raise TypeError
# if self.Class=='Number':
# if not isinstance(value, float):
# if not (isinstance(value, int) or isinstance(value, long)):
# raise TypeError
# value = float(value)
# if self.Class=='Boolean' and not isinstance(value, bool):
# raise TypeError
self.value = value
self.extensible = extensible
self.prototype = prototype
self.own = {}
self.buff = None
def is_undefined(self):
return self.Class=='Undefined'
def is_null(self):
return self.Class=='Null'
def is_primitive(self):
return self.TYPE in self.PRIMITIVES
def is_object(self):
return not self.is_primitive()
def _type(self):
return Type(self)
def is_callable(self):
return hasattr(self, 'call')
def get_own_property(self, prop):
return self.own.get(prop)
def get_property(self, prop):
cand = self.get_own_property(prop)
if cand:
return cand
if self.prototype is not None:
return self.prototype.get_property(prop)
def update_array(self):
for i in range(self.get('length').to_uint32()):
self.put(str(i),Js(self.buff[i]))
def get(self, prop): #external use!
#prop = prop.value
if self.Class=='Undefined' or self.Class=='Null':
raise MakeError('TypeError', 'Undefined and null dont have properties!')
if not isinstance(prop, basestring):
prop = prop.to_string().value
if not isinstance(prop, basestring): raise RuntimeError('Bug')
if NUMPY_AVAILABLE and prop.isdigit():
if isinstance(self.buff,numpy.ndarray):
self.update_array()
cand = self.get_property(prop)
if cand is None:
return Js(None)
if is_data_descriptor(cand):
return cand['value']
if cand['get'].is_undefined():
return cand['get']
return cand['get'].call(self)
def can_put(self, prop): #to check
desc = self.get_own_property(prop)
if desc: #if we have this property
if is_accessor_descriptor(desc):
return desc['set'].is_callable() # Check if setter method is defined
else: #data desc
return desc['writable']
if self.prototype is not None:
return self.extensible
inherited = self.get_property(prop)
if inherited is None:
return self.extensible
if is_accessor_descriptor(inherited):
return not inherited['set'].is_undefined()
elif self.extensible:
return inherited['writable']
return False
def put(self, prop, val, op=None): #external use!
'''Just like in js: self.prop op= val
for example when op is '+' it will be self.prop+=val
op can be either None for simple assignment or one of:
* / % + - << >> & ^ |'''
if self.Class=='Undefined' or self.Class=='Null':
raise MakeError('TypeError', 'Undefined and null dont have properties!')
if not isinstance(prop, basestring):
prop = prop.to_string().value
if NUMPY_AVAILABLE and prop.isdigit():
if self.Class == 'Int8Array':
val = Js(numpy.int8(val.to_number().value))
elif self.Class == 'Uint8Array':
val = Js(numpy.uint8(val.to_number().value))
elif self.Class == 'Uint8ClampedArray':
if val < Js(numpy.uint8(0)):
val = Js(numpy.uint8(0))
elif val > Js(numpy.uint8(255)):
val = Js(numpy.uint8(255))
else:
val = Js(numpy.uint8(val.to_number().value))
elif self.Class == 'Int16Array':
val = Js(numpy.int16(val.to_number().value))
elif self.Class == 'Uint16Array':
val = Js(numpy.uint16(val.to_number().value))
elif self.Class == 'Int32Array':
val = Js(numpy.int32(val.to_number().value))
elif self.Class == 'Uint32Array':
val = Js(numpy.uint32(val.to_number().value))
elif self.Class == 'Float32Array':
val = Js(numpy.float32(val.to_number().value))
elif self.Class == 'Float64Array':
val = Js(numpy.float64(val.to_number().value))
if isinstance(self.buff,numpy.ndarray):
self.buff[int(prop)] = int(val.to_number().value)
#we need to set the value to the incremented one
if op is not None:
val = getattr(self.get(prop), OP_METHODS[op])(val)
if not self.can_put(prop):
return val
own_desc = self.get_own_property(prop)
if is_data_descriptor(own_desc):
if self.Class in ['Array','Int8Array','Uint8Array','Uint8ClampedArray','Int16Array','Uint16Array','Int32Array','Uint32Array','Float32Array','Float64Array']:
self.define_own_property(prop, {'value':val})
else:
self.own[prop]['value'] = val
return val
desc = self.get_property(prop)
if is_accessor_descriptor(desc):
desc['set'].call(self, (val,))
else:
new = {'value' : val,
'writable' : True,
'configurable' : True,
'enumerable' : True}
if self.Class in ['Array','Int8Array','Uint8Array','Uint8ClampedArray','Int16Array','Uint16Array','Int32Array','Uint32Array','Float32Array','Float64Array']:
self.define_own_property(prop, new)
else:
self.own[prop] = new
return val
def has_property(self, prop):
return self.get_property(prop) is not None
def delete(self, prop):
if not isinstance(prop, basestring):
prop = prop.to_string().value
desc = self.get_own_property(prop)
if desc is None:
return Js(True)
if desc['configurable']:
del self.own[prop]
return Js(True)
return Js(False)
def default_value(self, hint=None): # made a mistake at the very early stage and made it to prefer string... caused lots! of problems
order = ('valueOf', 'toString')
if hint=='String' or (hint is None and self.Class=='Date'):
order = ('toString', 'valueOf')
for meth_name in order:
method = self.get(meth_name)
if method is not None and method.is_callable():
cand = method.call(self)
if cand.is_primitive():
return cand
raise MakeError('TypeError', 'Cannot convert object to primitive value')
def define_own_property(self, prop, desc): #Internal use only. External through Object
# prop must be a Py string. Desc is either a descriptor or accessor.
#Messy method - raw translation from Ecma spec to prevent any bugs. # todo check this
current = self.get_own_property(prop)
extensible = self.extensible
if not current: #We are creating a new property
if not extensible:
return False
if is_data_descriptor(desc) or is_generic_descriptor(desc):
DEFAULT_DATA_DESC = {'value': undefined, #undefined
'writable': False,
'enumerable': False,
'configurable': False}
DEFAULT_DATA_DESC.update(desc)
self.own[prop] = DEFAULT_DATA_DESC
else:
DEFAULT_ACCESSOR_DESC = {'get': undefined, #undefined
'set': undefined, #undefined
'enumerable': False,
'configurable': False}
DEFAULT_ACCESSOR_DESC.update(desc)
self.own[prop] = DEFAULT_ACCESSOR_DESC
return True
if not desc or desc==current: #We dont need to change anything.
return True
configurable = current['configurable']
if not configurable: #Prevent changing configurable or enumerable
if desc.get('configurable'):
return False
if 'enumerable' in desc and desc['enumerable']!=current['enumerable']:
return False
if is_generic_descriptor(desc):
pass
elif is_data_descriptor(current)!=is_data_descriptor(desc):
if not configurable:
return False
if is_data_descriptor(current):
del current['value']
del current['writable']
current['set'] = undefined #undefined
current['get'] = undefined #undefined
else:
del current['set']
del current['get']
current['value'] = undefined #undefined
current['writable'] = False
elif is_data_descriptor(current) and is_data_descriptor(desc):
if not configurable:
if not current['writable'] and desc.get('writable'):
return False
if not current['writable'] and 'value' in desc and current['value']!=desc['value']:
return False
elif is_accessor_descriptor(current) and is_accessor_descriptor(desc):
if not configurable:
if 'set' in desc and desc['set'] is not current['set']:
return False
if 'get' in desc and desc['get'] is not current['get']:
return False
current.update(desc)
return True
#these methods will work only for Number class
def is_infinity(self):
assert self.Class=='Number'
return self.value==float('inf') or self.value==-float('inf')
def is_nan(self):
assert self.Class=='Number'
return self.value!=self.value #nan!=nan evaluates to true
def is_finite(self):
return not (self.is_nan() or self.is_infinity())
#Type Conversions. to_type. All must return pyjs subclass instance
def to_primitive(self, hint=None):
if self.is_primitive():
return self
if hint is None and (self.Class=='Number' or self.Class=='Boolean'): # favour number for Class== Number or Boolean default = String
hint = 'Number'
return self.default_value(hint)
def to_boolean(self):
typ = Type(self)
if typ=='Boolean': #no need to convert
return self
elif typ=='Null' or typ=='Undefined': #they are both always false
return false
elif typ=='Number' or typ=='String': #false only for 0, '' and NaN
return Js(bool(self.value and self.value==self.value)) # test for nan (nan -> flase)
else: #object - always true
return true
def to_number(self):
typ = Type(self)
if typ=='Null': #null is 0
return Js(0)
elif typ=='Undefined': # undefined is NaN
return NaN
elif typ=='Boolean': # 1 for true 0 for false
return Js(int(self.value))
elif typ=='Number':# or self.Class=='Number': # no need to convert
return self
elif typ=='String':
s = self.value.strip() #Strip white space
if not s: # '' is simply 0
return Js(0)
if 'x' in s or 'X' in s[:3]: #hex (positive only)
try: # try to convert
num = int(s, 16)
except ValueError: # could not convert > NaN
return NaN
return Js(num)
sign = 1 #get sign
if s[0] in '+-':
if s[0]=='-':
sign = -1
s = s[1:]
if s=='Infinity': #Check for infinity keyword. 'NaN' will be NaN anyway.
return Js(sign*float('inf'))
try: #decimal try
num = sign*float(s) # Converted
except ValueError:
return NaN # could not convert to decimal > return NaN
return Js(num)
else: #object - most likely it will be NaN.
return self.to_primitive('Number').to_number()
def to_string(self):
typ = Type(self)
if typ=='Null':
return Js('null')
elif typ=='Undefined':
return Js('undefined')
elif typ=='Boolean':
return Js('true') if self.value else Js('false')
elif typ=='Number': #or self.Class=='Number':
if self.is_nan():
return Js('NaN')
elif self.is_infinity():
sign = '-' if self.value<0 else ''
return Js(sign+'Infinity')
elif isinstance(self.value, long) or self.value.is_integer(): # dont print .0
return Js(unicode(int(self.value)))
return Js(unicode(self.value)) # accurate enough
elif typ=='String':
return self
else: #object
return self.to_primitive('String').to_string()
def to_object(self):
typ = self.TYPE
if typ=='Null' or typ=='Undefined':
raise MakeError('TypeError', 'undefined or null can\'t be converted to object')
elif typ=='Boolean': # Unsure here... todo repair here
return Boolean.create(self)
elif typ=='Number': #?
return Number.create(self)
elif typ=='String': #?
return String.create(self)
else: #object
return self
def to_int32(self):
num = self.to_number()
if num.is_nan() or num.is_infinity():
return 0
int32 = int(num.value) % 2**32
return int(int32 - 2**32 if int32 >= 2**31 else int32)
def strict_equality_comparison(self, other):
return PyJsStrictEq(self, other)
def cok(self):
"""Check object coercible"""
if self.Class in ('Undefined', 'Null'):
raise MakeError('TypeError', 'undefined or null can\'t be converted to object')
def to_int(self):
num = self.to_number()
if num.is_nan():
return 0
elif num.is_infinity():
return 10**20 if num.value>0 else -10**20
return int(num.value)
def to_uint32(self):
num = self.to_number()
if num.is_nan() or num.is_infinity():
return 0
return int(num.value) % 2**32
def to_uint16(self):
num = self.to_number()
if num.is_nan() or num.is_infinity():
return 0
return int(num.value) % 2**16
def to_int16(self):
num = self.to_number()
if num.is_nan() or num.is_infinity():
return 0
int16 = int(num.value) % 2**16
return int(int16 - 2**16 if int16 >= 2**15 else int16)
def same_as(self, other):
typ = Type(self)
if typ!=other.Class:
return False
if typ=='Undefined' or typ=='Null':
return True
if typ=='Boolean' or typ=='Number' or typ=='String':
return self.value==other.value
else: #object
return self is other #Id compare.
#Not to be used by translation (only internal use)
def __getitem__(self, item):
return self.get(str(item) if not isinstance(item, PyJs) else item.to_string().value)
def __setitem__(self, item, value):
self.put(str(item) if not isinstance(item, PyJs) else item.to_string().value, Js(value))
def __len__(self):
try:
return self.get('length').to_uint32()
except:
raise TypeError('This object (%s) does not have length property'%self.Class)
#Oprators-------------
#Unary, other will be implemented as functions. Increments and decrements
# will be methods of Number class
def __neg__(self): #-u
return Js(-self.to_number().value)
def __pos__(self): #+u
return self.to_number()
def __invert__(self): #~u
return Js(Js(~self.to_int32()).to_int32())
def neg(self): # !u cant do 'not u' :(
return Js(not self.to_boolean().value)
def __nonzero__(self):
return self.to_boolean().value
def __bool__(self):
return self.to_boolean().value
def typeof(self):
if self.is_callable():
return Js('function')
typ = Type(self).lower()
if typ=='null':
typ = 'object'
return Js(typ)
#Bitwise operators
# <<, >>, &, ^, |
# <<
def __lshift__(self, other):
lnum = self.to_int32()
rnum = other.to_uint32()
shiftCount = rnum & 0x1F
return Js(Js(lnum << shiftCount).to_int32())
# >>
def __rshift__(self, other):
lnum = self.to_int32()
rnum = other.to_uint32()
shiftCount = rnum & 0x1F
return Js(Js(lnum >> shiftCount).to_int32())
# >>>
def pyjs_bshift(self, other):
lnum = self.to_uint32()
rnum = other.to_uint32()
shiftCount = rnum & 0x1F
return Js(Js(lnum >> shiftCount).to_uint32())
# &
def __and__(self, other):
lnum = self.to_int32()
rnum = other.to_int32()
return Js(Js(lnum & rnum).to_int32())
# ^
def __xor__(self, other):
lnum = self.to_int32()
rnum = other.to_int32()
return Js(Js(lnum ^ rnum).to_int32())
# |
def __or__(self, other):
lnum = self.to_int32()
rnum = other.to_int32()
return Js(Js(lnum | rnum).to_int32())
# Additive operators
# + and - are implemented here
# +
def __add__(self, other):
a = self.to_primitive()
b = other.to_primitive()
if a.TYPE=='String' or b.TYPE=='String':
return Js(a.to_string().value+b.to_string().value)
a = a.to_number()
b = b.to_number()
return Js(a.value+b.value)
# -
def __sub__(self, other):
return Js(self.to_number().value-other.to_number().value)
#Multiplicative operators
# *, / and % are implemented here
# *
def __mul__(self, other):
return Js(self.to_number().value*other.to_number().value)
# /
def __div__(self, other):
a = self.to_number().value
b = other.to_number().value
if b:
return Js(a/b)
if not a or a!=a:
return NaN
return Infinity if a>0 else -Infinity
# %
def __mod__(self, other):
a = self.to_number().value
b = other.to_number().value
if abs(a)==float('inf') or not b:
return NaN
if abs(b)==float('inf'):
return Js(a)
pyres = Js(a%b) #different signs in python and javascript
#python has the same sign as b and js has the same
#sign as a.
if a<0 and pyres.value>0:
pyres.value -= abs(b)
elif a>0 and pyres.value<0:
pyres.value += abs(b)
return Js(pyres)
#Comparisons (I dont implement === and !== here, these
# will be implemented as external functions later)
# <, <=, !=, ==, >=, > are implemented here.
def abstract_relational_comparison(self, other, self_first=True):
''' self<other if self_first else other<self.
Returns the result of the question: is self smaller than other?
in case self_first is false it returns the answer of:
is other smaller than self.
result is PyJs type: bool or undefined'''
px = self.to_primitive('Number')
py = other.to_primitive('Number')
if not self_first: #reverse order
px, py = py, px
if not (px.Class=='String' and py.Class=='String'):
px, py = px.to_number(), py.to_number()
if px.is_nan() or py.is_nan():
return undefined
return Js(px.value<py.value) # same cmp algorithm
else:
# I am pretty sure that python has the same
# string cmp algorithm but I have to confirm it
return Js(px.value<py.value)
#<
def __lt__(self, other):
res = self.abstract_relational_comparison(other, True)
if res.is_undefined():
return false
return res
#<=
def __le__(self, other):
res = self.abstract_relational_comparison(other, False)
if res.is_undefined():
return false
return res.neg()
#>=
def __ge__(self, other):
res = self.abstract_relational_comparison(other, True)
if res.is_undefined():
return false
return res.neg()
#>
def __gt__(self, other):
res = self.abstract_relational_comparison(other, False)
if res.is_undefined():
return false
return res
def abstract_equality_comparison(self, other):
''' returns the result of JS == compare.
result is PyJs type: bool'''
tx, ty = self.TYPE, other.TYPE
if tx==ty:
if tx=='Undefined' or tx=='Null':
return true
if tx=='Number' or tx=='String' or tx=='Boolean':
return Js(self.value==other.value)
return Js(self is other) # Object
elif (tx=='Undefined' and ty=='Null') or (ty=='Undefined' and tx=='Null'):
return true
elif tx=='Number' and ty=='String':
return self.abstract_equality_comparison(other.to_number())
elif tx=='String' and ty=='Number':
return self.to_number().abstract_equality_comparison(other)
elif tx=='Boolean':
return self.to_number().abstract_equality_comparison(other)
elif ty=='Boolean':
return self.abstract_equality_comparison(other.to_number())
elif (tx=='String' or tx=='Number') and other.is_object():
return self.abstract_equality_comparison(other.to_primitive())
elif (ty=='String' or ty=='Number') and self.is_object():
return self.to_primitive().abstract_equality_comparison(other)
else:
return false
#==
def __eq__(self, other):
return self.abstract_equality_comparison(other)
#!=
def __ne__(self, other):
return self.abstract_equality_comparison(other).neg()
#Other methods (instanceof)
def instanceof(self, other):
'''checks if self is instance of other'''
if not hasattr(other, 'has_instance'):
return false
return other.has_instance(self)
#iteration
def __iter__(self):
#Returns a generator of all own enumerable properties
# since the size od self.own can change we need to use different method of iteration.
# SLOW! New items will NOT show up.
returned = {}
if not self.IS_CHILD_SCOPE:
cands = sorted(name for name in self.own if self.own[name]['enumerable'])
else:
cands = sorted(name for name in self.own)
for cand in cands:
check = self.own.get(cand)
if check and check['enumerable']:
yield Js(cand)
def contains(self, other):
if not self.is_object():
raise MakeError('TypeError',"You can\'t use 'in' operator to search in non-objects")
return Js(self.has_property(other.to_string().value))
#Other Special methods
def __call__(self, *args):
'''Call a property prop as a function (this will be global object).
NOTE: dont pass this and arguments here, these will be added
automatically!'''
if not self.is_callable():
raise MakeError('TypeError', '%s is not a function'%self.typeof())
return self.call(self.GlobalObject, args)
def create(self, *args):
'''Generally not a constructor, raise an error'''
raise MakeError('TypeError', '%s is not a constructor'%self.Class)
def __unicode__(self):
return self.to_string().value
def __repr__(self):
if self.Class=='String':
return str_repr(self.value)
elif self.Class in ['Array','Int8Array','Uint8Array','Uint8ClampedArray','Int16Array','Uint16Array','Int32Array','Uint32Array','Float32Array','Float64Array']:
res = []
for e in self:
res.append(repr(self.get(e)))
return '[%s]'%', '.join(res)
else:
val = str_repr(self.to_string().value)
return val
def _fuck_python3(self): # hack to make object hashable in python 3 (__eq__ causes problems)
return object.__hash__(self)
def callprop(self, prop, *args):
'''Call a property prop as a method (this will be self).
NOTE: dont pass this and arguments here, these will be added
automatically!'''
if not isinstance(prop, basestring):
prop = prop.to_string().value
cand = self.get(prop)
if not cand.is_callable():
raise MakeError('TypeError','%s is not a function'%cand.typeof())
return cand.call(self, args)
def to_python(self):
"""returns equivalent python object.
for example if this object is javascript array then this method will return equivalent python array"""
return to_python(self)
def to_py(self):
"""returns equivalent python object.
for example if this object is javascript array then this method will return equivalent python array"""
return self.to_python()
if six.PY3:
PyJs.__hash__ = PyJs._fuck_python3
PyJs.__truediv__ = PyJs.__div__
#Define some more classes representing operators:
def PyJsStrictEq(a, b):
'''a===b'''
tx, ty = Type(a), Type(b)
if tx!=ty:
return false
if tx=='Undefined' or tx=='Null':
return true
if a.is_primitive(): #string bool and number case
return Js(a.value==b.value)
if a.Class == b.Class == 'PyObjectWrapper':
return Js(a.obj == b.obj)
return Js(a is b) # object comparison
def PyJsStrictNeq(a, b):
''' a!==b'''
return PyJsStrictEq(a, b).neg()
def PyJsBshift(a, b):
"""a>>>b"""
return a.pyjs_bshift(b)
def PyJsComma(a, b):
return b
from .internals.simplex import JsException as PyJsException
import pyjsparser
pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError('SyntaxError', msg)
class PyJsSwitchException(Exception): pass
PyJs.MakeError = staticmethod(MakeError)
def JsToPyException(js):
temp = PyJsException()
temp.mes = js
return temp
def PyExceptionToJs(py):
return py.mes
#Scope class it will hold all the variables accessible to user
class Scope(PyJs):
Class = 'global'
extensible = True