-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfer.py
executable file
·4481 lines (3755 loc) · 142 KB
/
infer.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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import copy
from optparse import OptionParser
def LOG(*args):
if not LOG.enabled: return
print('// ' + str(args))
# S = '//'
# for a in args: S += ' ' + str(a)
# print(S)
EOF = chr(255)
# Enumeration for allowing octals and ignoring junk when converting
# strings to numbers.
#enum ConversionFlags {
NO_FLAGS = 0
ALLOW_HEX = 1
ALLOW_OCTALS = 2
ALLOW_TRAILING_JUNK = 4
def IsInRange(c, lower_limit, higher_limit):
assert(ord(c) != -1)
return ord(lower_limit) <= ord(c) and ord(c) <= ord(higher_limit)
def IsDecimalDigit(c):
# ECMA-262, 3rd, 7.8.3 (p 16)
return IsInRange(c, '0', '9')
def IsLetter(c):
return IsInRange(c, 'a', 'z') or IsInRange(c, 'A', 'Z')
def IsIdentifierStart(c):
if c == '$' or c == '_' or c == '\\':
return True
return IsLetter(c)
def IsLineTerminator(c):
return c == '\n'
def IsIdentifierPart(c):
return IsIdentifierStart(c) or IsDecimalDigit(c) or c == '_';
def DoubleToInt32(c):
return int(c)
class Token:
tokens_ = [
# End of source indicator.
("EOS", "EOS", 0),
# Punctuators (ECMA-262, section 7.7, page 15).
("LPAREN", "(", 0),
("RPAREN", ")", 0),
("LBRACK", "[", 0),
("RBRACK", "]", 0),
("LBRACE", "{", 0),
("RBRACE", "}", 0),
("COLON", ":", 0) ,
("SEMICOLON", ";", 0),
("PERIOD", ".", 0),
("CONDITIONAL", "?", 3),
("INC", "++", 0),
("DEC", "--", 0),
# Assignment operators.
# IsAssignmentOp() relies on this block of enum values
# being contiguous and sorted in the same order!
# ("INIT_VAR", "=init_var", 2), # AST-use only.
("INIT_VAR", "=", 2), # AST-use only.
("INIT_CONST", "=init_const", 2), # AST-use only.
("ASSIGN", "=", 2),
("ASSIGN_BIT_OR", "|=", 2),
("ASSIGN_BIT_XOR", "^=", 2),
("ASSIGN_BIT_AND", "&=", 2),
("ASSIGN_SHL", "<<=", 2),
("ASSIGN_SAR", ">>=", 2),
("ASSIGN_SHR", ">>>=", 2),
("ASSIGN_ADD", "+=", 2),
("ASSIGN_SUB", "-=", 2),
("ASSIGN_MUL", "*=", 2),
("ASSIGN_DIV", "/=", 2),
("ASSIGN_MOD", "%=", 2),
# Binary operators sorted by precedence.
# IsBinaryOp() relies on this block of enum values
# being contiguous and sorted in the same order!
("COMMA", ",", 1),
("OR", "||", 4),
("AND", "&&", 5),
("BIT_OR", "|", 6),
("BIT_XOR", "^", 7),
("BIT_AND", "&", 8),
("SHL", "<<", 11),
("SAR", ">>", 11),
("SHR", ">>>", 11),
("ADD", "+", 12),
("SUB", "-", 12),
("MUL", "*", 13),
("DIV", "/", 13),
("MOD", "%", 13),
# Compare operators sorted by precedence.
# IsCompareOp() relies on this block of enum values
# being contiguous and sorted in the same order!
("EQ", "==", 9),
("NE", "!=", 9),
("EQ_STRICT", "===", 9),
("NE_STRICT", "!==", 9),
("LT", "<", 10),
("GT", ">", 10),
("LTE", "<=", 10),
("GTE", ">=", 10),
("INSTANCEOF", "instanceof", 10),
("IN", "in", 10),
# Unary operators.
# IsUnaryOp() relies on this block of enum values
# being contiguous and sorted in the same order!
("NOT", "!", 0),
("BIT_NOT", "~", 0),
("DELETE", "delete", 0),
("TYPEOF", "typeof", 0),
("VOID", "void", 0),
# Keywords (ECMA-262, section 7.5.2, page 13).
("BREAK", "break", 0),
("CASE", "case", 0),
("CATCH", "catch", 0),
("CONTINUE", "continue", 0),
("DEBUGGER", "debugger", 0),
("DEFAULT", "default", 0),
# DELETE
("DO", "do", 0),
("ELSE", "else", 0),
("FINALLY", "finally", 0),
("FOR", "for", 0),
("FUNCTION", "function", 0),
("IF", "if", 0),
# IN
# INSTANCEOF
("NEW", "new", 0),
("RETURN", "return", 0),
("SWITCH", "switch", 0),
("THIS", "this", 0),
("THROW", "throw", 0),
("TRY", "try", 0),
# TYPEOF
("VAR", "var", 0),
# VOID
("WHILE", "while", 0),
("WITH", "with", 0),
# Future reserved words (ECMA-262, section 7.5.3, page 14).
("ABSTRACT", "abstract", 0),
("BOOLEAN", "boolean", 0),
("BYTE", "byte", 0),
("CHAR", "char", 0),
("CLASS", "class", 0),
("CONST", "const", 0),
("DOUBLE", "double", 0),
("ENUM", "enum", 0),
("EXPORT", "export", 0),
("EXTENDS", "extends", 0),
("FINAL", "final", 0),
("FLOAT", "float", 0),
("GOTO", "goto", 0),
("IMPLEMENTS", "implements", 0),
("IMPORT", "import", 0),
("INT", "int", 0),
("INTERFACE", "interface", 0),
("LONG", "long", 0),
("NATIVE", "native", 0),
("PACKAGE", "package", 0),
("PRIVATE", "private", 0),
("PROTECTED", "protected", 0),
("PUBLIC", "public", 0),
("SHORT", "short", 0),
("STATIC", "static", 0),
("SUPER", "super", 0),
("SYNCHRONIZED", "synchronized", 0),
("THROWS", "throws", 0),
("TRANSIENT", "transient", 0),
("VOLATILE", "volatile", 0),
# Literals (ECMA-262, section 7.8, page 16).
("NULL_LITERAL", "null", 0),
("TRUE_LITERAL", "true", 0),
("FALSE_LITERAL", "false", 0),
("NUMBER", None, 0),
("STRING", None, 0),
# Identifiers (not keywords or future reserved words).
("IDENTIFIER", None, 0),
# Illegal token - not able to scan.
("ILLEGAL", "ILLEGAL", 0),
# Scanner-internal use only.
("WHITESPACE", None, 0)
]
@staticmethod
def Init():
Token.names_ = [token[0] for token in Token.tokens_]
Token.strings_ = [token[1] for token in Token.tokens_]
Token.precedences_ = [token[2] for token in Token.tokens_]
Token.name2int_ = dict()
for i in range(0, len(Token.tokens_)):
Token.name2int_[Token.tokens_[i][1]] = i
vars(Token)[Token.tokens_[i][0]] = i
@staticmethod
def Name(type):
return Token.names_[type]
@staticmethod
def String(tok):
return Token.strings_[tok]
@staticmethod
def Precedence(tok):
return Token.precedences_[tok]
@staticmethod
def IsAssignmentOp(op):
return Token.INIT_VAR <= op and op <= Token.ASSIGN_MOD
@staticmethod
def IsUnaryOp(op):
return (Token.NOT <= op and op <= Token.VOID or
op == Token.ADD or op == Token.SUB)
@staticmethod
def IsCountOp(op):
return op == Token.INC or op == Token.DEC
@staticmethod
def IsCompareOp(op):
return Token.EQ <= op and op <= Token.IN
@staticmethod
def IsBinaryOp(op):
return Token.COMMA<= op and op <= Token.MOD
Token.Init()
class KeywordMatcher:
def __init__(self):
self.buffer = ""
def AddChar(self, c):
self.buffer += c
def token(self):
if self.buffer in Token.name2int_:
return Token.name2int_[self.buffer]
return Token.IDENTIFIER
class Scanner:
class Location:
def __init__(self, b = 0, e = 0):
self.beg_pos = b
self.end_pos = e
class TokenDesc:
def __init__(self):
self.token = Token.ILLEGAL
self.location = Scanner.Location()
self.literal_buffer = ""
def __init__(self, source, position = 0):
self.source_ = source
self.position_ = position
# Set c0_ (one character ahead)
self.Advance()
self.current_ = Scanner.TokenDesc()
self.next_ = Scanner.TokenDesc()
# Skip initial whitespace allowing HTML comment ends just like
# after a newline and scan first token.
self.has_line_terminator_before_next_ = True
self.SkipWhiteSpace()
self.Scan()
def peek(self):
return self.next_.token
def Next(self):
self.current_ = copy.copy(self.next_)
self.Scan()
return self.current_.token
def literal_string(self):
return self.current_.literal_string
def source_pos(self):
return self.position_
def location(self):
return self.current_.location
def has_line_terminator_before_next(self):
return self.has_line_terminator_before_next_
def Select(self, *args):
def Select1(tok):
self.Advance()
return tok
def Select3(next, then, else_):
self.Advance()
if self.c0_ == next:
self.Advance()
return then
else:
return else_
return (Select1 if len(args) == 1 else Select3)(*args)
def Scan(self):
self.next_.literal_buffer = ""
token = Token.WHITESPACE
self.has_line_terminator_before_next_ = False
while token == Token.WHITESPACE:
# Remember the position of the next token
self.next_.location.beg_pos = self.source_pos()
# Continue scanning for tokens as long as we're just skipping
# whitespace.
if self.c0_ == ' ' or self.c0_ == '\t':
self.Advance()
token = Token.WHITESPACE
elif self.c0_ == '\n':
self.Advance()
self.has_line_terminator_before_next_ = True
token = Token.WHITESPACE
elif self.c0_ == '"' or self.c0_ == '\'':
token = self.ScanString()
elif self.c0_ == '<':
# < <= << <<= <!--
self.Advance()
if self.c0_ == '=':
token = self.Select(Token.LTE)
elif self.c0_ == '<':
token = self.Select("=", Token.ASSIGN_SHL, Token.SHL)
# } else if (c0_ == '!') {
# token = ScanHtmlComment();
else:
token = Token.LT
elif self.c0_ == '>':
# > >= >> >>= >>> >>>=
self.Advance()
if self.c0_ == '=':
token = self.Select(Token.GTE)
elif self.c0_ == '>':
# >> >>= >>> >>>=
self.Advance()
if self.c0_ == '=':
token = self.Select(Token.ASSIGN_SAR)
elif self.c0_ == '>':
token = self.Select('=', Token.ASSIGN_SHR, Token.SHR)
else:
token = Token.SAR;
else:
token = Token.GT
elif self.c0_ == '=':
self.Advance()
if self.c0_ == '=':
token = self.Select('=', Token.EQ_STRICT, Token.EQ)
else:
token = Token.ASSIGN
elif self.c0_ == '!':
self.Advance()
if self.c0_ == '=':
token = self.Select('=', Token.NE_STRICT, Token.NE)
else:
token = Token.NOT
elif self.c0_ == '+':
# + ++ +=
self.Advance()
if self.c0_ == '+':
token = self.Select(Token.INC)
elif self.c0_ == '=':
token = self.Select(Token.ASSIGN_ADD)
else:
token = Token.ADD
elif self.c0_ == '-':
# - -- --> -=
self.Advance()
if self.c0_ == '-':
token = self.Select(Token.DEC)
elif self.c0_ == '=':
token = self.Select(Token.ASSIGN_SUB)
else:
token = Token.SUB
elif self.c0_ == '*':
# * *=
token = self.Select('=', Token.ASSIGN_MUL, Token.MUL)
elif self.c0_ == '%':
# % %=
token = self.Select('=', Token.ASSIGN_MOD, Token.MOD)
elif self.c0_ == '/':
# / // /* /=
self.Advance();
if self.c0_ == '/':
token = self.SkipSingleLineComment()
elif self.c0_ == '*':
token = self.SkipMultiLineComment()
elif self.c0_ == '=':
token = self.Select(Token.ASSIGN_DIV)
else:
token = Token.DIV
elif self.c0_ == '&':
# & && &=
self.Advance()
if self.c0_ == '&':
token = self.Select(Token.AND)
elif self.c0_ == '=':
token = self.Select(Token.ASSIGN_BIT_AND)
else:
token = Token.BIT_AND
elif self.c0_ == '|':
# | || |=
self.Advance()
if self.c0_ == '|':
token = self.Select(Token.OR)
elif self.c0_ == '=':
token = self.Select(Token.ASSIGN_BIT_OR)
else:
token = Token.BIT_OR
elif self.c0_ == '^':
# ^ ^=
token = self.Select('=', Token.ASSIGN_BIT_XOR, Token.BIT_XOR)
elif self.c0_ == '.':
# . Number
self.Advance();
if IsDecimalDigit(self.c0_):
token = self.ScanNumber(True)
else:
token = Token.PERIOD
elif self.c0_ == ':':
token = self.Select(Token.COLON)
elif self.c0_ == ';':
token = self.Select(Token.SEMICOLON)
elif self.c0_ == ',':
token = self.Select(Token.COMMA)
elif self.c0_ == '(':
token = self.Select(Token.LPAREN)
elif self.c0_ == ')':
token = self.Select(Token.RPAREN)
elif self.c0_ == '[':
token = self.Select(Token.LBRACK)
elif self.c0_ == ']':
token = self.Select(Token.RBRACK)
elif self.c0_ == '{':
token = self.Select(Token.LBRACE)
elif self.c0_ == '}':
token = self.Select(Token.RBRACE)
elif self.c0_ == '?':
token = self.Select(Token.CONDITIONAL)
elif self.c0_ == '~':
token = self.Select(Token.BIT_NOT)
else:
if IsIdentifierStart(self.c0_):
token = self.ScanIdentifier()
elif IsDecimalDigit(self.c0_):
token = self.ScanNumber(False)
elif self.SkipWhiteSpace():
token = Token.WHITESPACE
elif self.c0_ == EOF:
token = Token.EOS
else:
token = self.Select(Token.ILLEGAL)
self.next_.location.end_pos = self.source_pos()
self.next_.token = token
def ScanDecimalDigits(self):
while IsDecimalDigit(self.c0_):
self.AddCharAdvance()
def ScanNumber(self, seen_period):
assert(IsDecimalDigit(self.c0_))
DECIMAL = 0
HEX = 1
OCTAL = 2
kind = DECIMAL
self.StartLiteral()
if seen_period:
# we have already seen a decimal point of the float
self.AddChar('.')
self.ScanDecimalDigits() # we know we have at least one digit
else:
# if the first character is '0' we must check for octals and hex
if self.c0_ == '0':
self.AddCharAdvance()
# either 0, 0exxx, 0Exxx, 0.xxx, an octal number, or a hex number
if self.c0_ == 'x' or self.c0_ == 'X':
kind = HEX
self.AddCharAdvance()
if not IsHexDigit(self.c0_):
return Token.ILLEGAL
while IsHexDigit(self.c0_):
self.AddCharAdvance()
elif ord('0') <= ord(self.c0_) and ord(self.c0_) <= ord('7'):
# (possible) octal number
kind = OCTAL
while True:
if self.c0_ == '8' or self.c0_ == '9':
kind = DECIMAL
break
if ord(self.c0_) < ord('0') or ord('7') < ord(self.c0_):
break
self.AddCharAdvance()
# Parse decimal digits and allow trailing fractional part.
if kind == DECIMAL:
self.ScanDecimalDigits() # optional
if self.c0_ == '.':
self.AddCharAdvance()
self.ScanDecimalDigits() # optional
# scan exponent, if any
if self.c0_ == 'e' or self.c0_ == 'E':
assert(kind != HEX) # 'e'/'E' must be scanned as part of the hex number
if kind == OCTAL:
return Token.ILLEGAL # no exponent for octals allowed
# scan exponent
self.AddCharAdvance()
if self.c0_ == '+' or self.c0_ == '-':
self.AddCharAdvance()
if not IsDecimalDigit(self.c0_):
# we must have at least one decimal digit after 'e'/'E'
return Token.ILLEGAL
self.ScanDecimalDigits()
# The source character immediately following a numeric literal must
# not be an identifier start or a decimal digit; see ECMA-262
# section 7.8.3, page 17 (note that we read only one decimal digit
# if the value is 0).
if IsDecimalDigit(self.c0_) or IsIdentifierStart(self.c0_):
return Token.ILLEGAL
return Token.NUMBER
def ScanString(self):
quote = self.c0_
self.Advance()
self.StartLiteral()
while self.c0_ != quote and self.c0_ != EOF and not IsLineTerminator(self.c0_):
c = self.c0_
self.Advance()
if c == '\\':
if self.c0_ == EOF:
return Token.ILLEGAL
ScanEscape()
else:
self.AddChar(c)
if self.c0_ != quote:
return Token.ILLEGAL
self.Advance() # consume quote
return Token.STRING
def Advance(self):
if self.position_ == len(self.source_):
self.c0_ = EOF
else:
self.c0_ = self.source_[self.position_]
self.position_ += 1
def SkipWhiteSpace(self):
start_position = self.source_pos()
while True:
while self.c0_.isspace():
# IsWhiteSpace() includes line terminators!
if IsLineTerminator(self.c0_):
# Ignore line terminators, but remember them. This is necessary
# for automatic semicolon insertion.
self.has_line_terminator_before_next_ = True
self.Advance()
# Return whether or not we skipped any characters.
return self.source_pos() != start_position
def SkipSingleLineComment(self):
self.Advance()
# The line terminator at the end of the line is not considered
# to be part of the single-line comment; it is recognized
# separately by the lexical grammar and becomes part of the
# stream of input elements for the syntactic grammar (see
# ECMA-262, section 7.4, page 12).
while self.c0_ != EOF and not IsLineTerminator(self.c0_):
self.Advance()
return Token.WHITESPACE
def SkipMultiLineComment(self):
assert(self.c0_ == '*')
self.Advance()
while self.c0_ != EOF:
ch = self.c0_
self.Advance()
# If we have reached the end of the multi-line comment, we
# consume the '/' and insert a whitespace. This way all
# multi-line comments are treated as whitespace - even the ones
# containing line terminators. This contradicts ECMA-262, section
# 7.4, page 12, that says that multi-line comments containing
# line terminators should be treated as a line terminator, but it
# matches the behaviour of SpiderMonkey and KJS.
if ch == '*' and self.c0_ == '/':
self.c0_ = ' '
return Token.WHITESPACE
# Unterminated multi-line comment.
return Token.ILLEGAL
def StartLiteral(self):
self.next_.literal_string = ""
def AddChar(self, c):
self.next_.literal_string += c
def AddCharAdvance(self):
self.AddChar(self.c0_)
self.Advance()
def ScanIdentifier(self):
assert(IsIdentifierStart(self.c0_))
self.StartLiteral()
keyword_match = KeywordMatcher()
if self.c0_ == '\\':
assert(False)
else:
self.AddChar(self.c0_)
keyword_match.AddChar(self.c0_)
self.Advance()
# Scan the rest of the identifier characters.
while IsIdentifierPart(self.c0_):
if self.c0_ == '\\':
assert(False)
else:
self.AddChar(self.c0_)
keyword_match.AddChar(self.c0_)
self.Advance()
return keyword_match.token()
##############
class JSObject:
def __init__(self, kind, value):
self.kind = kind
self.value = value
def IsString(self):
return self.kind == "string"
def IsNumber(self):
return self.kind == "number"
def Number(self):
return self.value
JSNULL = JSObject("null", "null")
JSTRUE = JSObject("true", "true")
JSFALSE = JSObject("false", "false")
JSUNDEFINED = JSObject("undefined", "undefined")
JSBUILTINS = [JSNULL, JSTRUE, JSFALSE, JSUNDEFINED]
##############
class SmiAnalysis:
#enum Kind {
UNKNOWN = 0
LIKELY_SMI = 1
def __init__(self):
self.kind = SmiAnalysis.UNKNOWN
def Is(self, kind):
return self.kind == kind
def IsKnown(self):
return not self.Is(SmiAnalysis.UNKNOWN)
def IsUnknown(self):
return self.Is(SmiAnalysis.UNKNOWN)
def IsLikelySmi(self):
return self.Is(SmiAnalysis.LIKELY_SMI)
def CopyFrom(self, other):
self.kind = other.kind
@staticmethod
def Type2String(type):
if type == SmiAnalysis.UNKNOWN:
return "UNKNOWN"
elif type == SmiAnalysis.LIKELY_SMI:
return "LIKELY_SMI"
assert(False)
def SetAsLikelySmi(self):
self.kind = self.LIKELY_SMI
def SetAsLikelySmiIfUnknown(self):
if self.IsUnknown():
self.SetAsLikelySmi()
class UseCount:
def __init__(self):
self.nreads_ = 0
self.nwrites_ = 0
def RecordRead(self, weight):
assert(weight > 0)
self.nreads_ += weight
# We must have a positive nreads_ here. Handle
# any kind of overflow by setting nreads_ to
# some large-ish value.
if self.nreads_ <= 0: self.nreads_ = 1000000
assert(self.is_read() and self.is_used())
def RecordWrite(self, weight):
assert(weight > 0)
self.nwrites_ += weight
# We must have a positive nwrites_ here. Handle
# any kind of overflow by setting nwrites_ to
# some large-ish value.
if self.nwrites_ <= 0: self.nwrites_ = 1000000
assert(self.is_written() and self.is_used())
def RecordAccess(self, weight):
self.RecordRead(weight)
self.RecordWrite(weight)
def RecordUses(self, uses):
if uses.nreads() > 0: self.RecordRead(uses.nreads())
if uses.nwrites() > 0: self.RecordWrite(uses.nwrites())
def nreads(self): return self.nreads_
def nwrites(self): return self.nwrites_
def nuses(self): return self.nreads_ + self.nwrites_
def is_read(self): return self.nreads() > 0
def is_written(self): return self.nwrites() > 0
def is_used(self): return self.nuses() > 0
# The AST refers to variables via VariableProxies - placeholders for the actual
# variables. Variables themselves are never directly referred to from the AST,
# they are maintained by scopes, and referred to from VariableProxies and Slots
# after binding and variable allocation.
class Variable:
#enum Mode {
# User declared variables:
VAR = 0 # declared via 'var', and 'function' declarations
CONST = 1 # declared via 'const' declarations
# Variables introduced by the compiler:
DYNAMIC = 2 # always require dynamic lookup (we don't know
# the declaration)
DYNAMIC_GLOBAL = 3 # requires dynamic lookup, but we know that the
# variable is global unless it has been shadowed
# by an eval-introduced variable
DYNAMIC_LOCAL = 4 # requires dynamic lookup, but we know that the
# variable is local and where it is unless it
# has been shadowed by an eval-introduced
# variable
INTERNAL = 5 # like VAR, but not user-visible (may or may not
# be in a context)
TEMPORARY = 6 # temporary variables (not user-visible), never
# in a context
#enum Kind {
NORMAL = 0
THIS = 1
ARGUMENTS = 2
def __init__(self, scope, name, mode, is_valid_lhs, kind):
self.scope_ = scope
self.name_ = name
self.mode_ = mode
self.is_valid_LHS_ = is_valid_lhs
self.kind_ = kind
self.local_if_not_shadowed_ = None
self.is_accessed_from_inner_scope_ = False
self.rewrite_ = None
self.var_uses_ = UseCount()
#ASSERT(name->IsSymbol());
self.fun_ = None # added by keisuke
@staticmethod
def Mode2String(mode):
for t in ((Variable.VAR, "VAR"),
(Variable.CONST,"CONST"),
(Variable.DYNAMIC,"DYNAMIC"),
(Variable.DYNAMIC_GLOBAL,"DYNAMIC_GLOBAL"),
(Variable.DYNAMIC_LOCAL,"DYNAMIC_LOCAL"),
(Variable.INTERNAL,"INTERNAL"),
(Variable.TEMPORARY,"TEMPORARY")):
if mode == t[0]:
return t[1]
assert(0)
def AsProperty(self):
return None if self.rewrite == None else self.rewrite.AsProperty()
def AsVariable(self):
if self.rewrite_ == None or self.rewrite_.AsSlot() != None:
return self
else:
return None
# The source code for an eval() call may refer to a variable that is
# in an outer scope about which we don't know anything (it may not
# be the global scope). scope() is NULL in that case. Currently the
# scope is only used to follow the context chain length.
def scope(self): return self.scope_
def name(self): return self.name_
def mode(self): return self.mode_
def is_accessed_from_inner_scope(self):
return self.is_accessed_from_inner_scope_
def var_uses(self): return self.var_uses_
def obj_uses(self): return self.obj_uses_
def IsVariable(self, n):
return not self.is_this() and self.name_.value == n.value
def is_dynamic(self):
return (self.mode_ == self.DYNAMIC or
self.mode_ == self.DYNAMIC_GLOBAL or
self.mode_ == self.DYNAMIC_LOCAL)
def is_global(self):
# Temporaries are never global, they must always be allocated in the
# activation frame.
return (self.mode_ != self.TEMPORARY and self.scope_ != None and
self.scope_.is_global_scope())
def is_this(self): return self.kind_ == self.THIS
def is_possibly_eval(self):
return (self.IsVariable("eval") and
(self.mode_ == self.DYNAMIC or self.mode_ == self.DYNAMIC_GLOBAL))
def local_if_not_shadowed(self):
assert(self.mode_ == self.DYNAMIC_LOCAL and self.local_if_not_shadowed_ != None)
return self.local_if_not_shadowed_
def set_local_if_not_shadowed(self, local):
self.set_local_if_not_shadowed_ = local
def rewrite(self):
return self.rewrite_
def slot(self):
return self.rewite.AsSlot() if self.rewrite_ != None else None
def type(self):
return self.type_
# added by keisuke
def Accept(self, v):
return v.VisitVariable(self)
# added by keisuke
def fun(self):
return self.fun_
def set_fun(self, fun):
assert(isinstance(fun, FunctionLiteral))
self.fun_ = fun
class AstNode:
def Accept(self, unused_v): assert(False)
# Type testing & conversion.
def AsStatement(self): return None
def AsExpressionStatement(self): return None
def AsEmptyStatement(self): return None
def AsExpression(self): return None
def AsLiteral(self): return None
def AsSlot(self): return None
def AsVariableProxy(self): return None
def AsProperty(self): return None
def AsCall(self): return None
def AsTargetCollector(self): return None
def AsBreakableStatement(self): return None
def AsIterationStatement(self): return None
def AsUnaryOperation(self): return None
def AsBinaryOperation(self): return None
def AsAssignment(self): return None
def AsFunctionLiteral(self): return None
def AsMaterializedLiteral(self): return None
def AsObjectLiteral(self): return None
def AsArrayLiteral(self): return None
class Statement(AstNode):
def AsStatement(self): return self
def AsReturnStatement(self): return None
def IsEmpty(self): return self.AsEmptyStatement() != None
class Expression(AstNode):
# enum Context
# Not assigned a context yet, or else will not be visited during
# code generation.
kUninitialized = 0
# Evaluated for its side effects.
kEffect = 1
# Evaluated for its value (and side effects).
kValue = 2
# Evaluated for control flow (and side effects).
kTest = 3
# Evaluated for control flow and side effects. Value is also
# needed if true.
kValueTest = 4
# Evaluated for control flow and side effects. Value is also
# needed if false.
kTestValue = 5
def __init__(self):
self.context_ = self.kUninitialized
def AsExpression(self): return self
def IsValidJSON(self): return False
def IsValidLeftHandSide(self): return False
def MarkAsStatement(self): pass # do nothing
# Static type information for this expression.
#def type(self): return self.type_
def type(self): return None
def context(self): return self.context_
def set_context(self, context): self.context_ = context
class BreakableStatement(Statement):
# enum Type
TARGET_FOR_ANONYMOUS = 0
TARGET_FOR_NAMED_ONLY = 1
# The labels associated with this statement. May be NULL;
# if it is != NULL, guaranteed to contain at least one entry.
def labels(self): return self.labels_
def AsBreakableStatement(self): return self
def break_target(self): return self.break_target_
def is_target_for_anonymous(self):
return self.type_ == self.TARGET_FOR_ANONYMOUS
def __init__(self, labels, type):
self.labels_ = labels
self.type_ = type
assert(labels == None or len(labels) > 0)
class Block(BreakableStatement):
def __init__(self, labels, unused_capacity, is_initializer_block):
BreakableStatement.__init__(self, labels, self.TARGET_FOR_NAMED_ONLY)
self.statements_ = []
self.is_initializer_block_ = is_initializer_block