-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathparser.py
More file actions
3137 lines (2595 loc) · 119 KB
/
parser.py
File metadata and controls
3137 lines (2595 loc) · 119 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
# -*- coding: utf-8 -*-
# Copyright JS Foundation and other contributors, https://js.foundation/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import absolute_import, unicode_literals
from .objects import Object
from .compat import basestring, unicode
from .utils import format
from .error_handler import ErrorHandler
from .messages import Messages
from .scanner import RawToken, Scanner, SourceLocation, Position, RegExp
from .token import Token, TokenName
from .syntax import Syntax
from . import nodes as Node
class Value(object):
def __init__(self, value):
self.value = value
class Params(object):
def __init__(self, simple=None, message=None, stricted=None, firstRestricted=None, inFor=None, paramSet=None, params=None, get=None):
self.simple = simple
self.message = message
self.stricted = stricted
self.firstRestricted = firstRestricted
self.inFor = inFor
self.paramSet = paramSet
self.params = params
self.get = get
class Config(Object):
def __init__(self, range=False, loc=False, source=None, tokens=False, comment=False, tolerant=False, **options):
self.range = range
self.loc = loc
self.source = source
self.tokens = tokens
self.comment = comment
self.tolerant = tolerant
for k, v in options.items():
setattr(self, k, v)
class Context(object):
def __init__(self, isModule=False, allowAwait=False, allowIn=True, allowStrictDirective=True, allowYield=True, firstCoverInitializedNameError=None, isAssignmentTarget=False, isBindingElement=False, inFunctionBody=False, inIteration=False, inSwitch=False, labelSet=None, strict=False):
self.isModule = isModule
self.allowAwait = allowAwait
self.allowIn = allowIn
self.allowStrictDirective = allowStrictDirective
self.allowYield = allowYield
self.firstCoverInitializedNameError = firstCoverInitializedNameError
self.isAssignmentTarget = isAssignmentTarget
self.isBindingElement = isBindingElement
self.inFunctionBody = inFunctionBody
self.inIteration = inIteration
self.inSwitch = inSwitch
self.labelSet = {} if labelSet is None else labelSet
self.strict = strict
class Marker(object):
def __init__(self, index=None, line=None, column=None):
self.index = index
self.line = line
self.column = column
class TokenEntry(Object):
def __init__(self, type=None, value=None, regex=None, range=None, loc=None):
self.type = type
self.value = value
self.regex = regex
self.range = range
self.loc = loc
class Parser(object):
def __init__(self, code, options={}, delegate=None):
self.config = Config(**options)
self.delegate = delegate
self.errorHandler = ErrorHandler()
self.errorHandler.tolerant = self.config.tolerant
self.scanner = Scanner(code, self.errorHandler)
self.scanner.trackComment = self.config.comment
self.operatorPrecedence = {
'||': 1,
'&&': 2,
'|': 3,
'^': 4,
'&': 5,
'==': 6,
'!=': 6,
'===': 6,
'!==': 6,
'<': 7,
'>': 7,
'<=': 7,
'>=': 7,
'instanceof': 7,
'in': 7,
'<<': 8,
'>>': 8,
'>>>': 8,
'+': 9,
'-': 9,
'*': 11,
'/': 11,
'%': 11,
}
self.lookahead = RawToken(
type=Token.EOF,
value='',
lineNumber=self.scanner.lineNumber,
lineStart=0,
start=0,
end=0
)
self.hasLineTerminator = False
self.context = Context(
isModule=False,
allowAwait=False,
allowIn=True,
allowStrictDirective=True,
allowYield=True,
firstCoverInitializedNameError=None,
isAssignmentTarget=False,
isBindingElement=False,
inFunctionBody=False,
inIteration=False,
inSwitch=False,
labelSet={},
strict=False
)
self.tokens = []
self.startMarker = Marker(
index=0,
line=self.scanner.lineNumber,
column=0
)
self.lastMarker = Marker(
index=0,
line=self.scanner.lineNumber,
column=0
)
self.nextToken()
self.lastMarker = Marker(
index=self.scanner.index,
line=self.scanner.lineNumber,
column=self.scanner.index - self.scanner.lineStart
)
def throwError(self, messageFormat, *args):
msg = format(messageFormat, *args)
index = self.lastMarker.index
line = self.lastMarker.line
column = self.lastMarker.column + 1
raise self.errorHandler.createError(index, line, column, msg)
def tolerateError(self, messageFormat, *args):
msg = format(messageFormat, *args)
index = self.lastMarker.index
line = self.scanner.lineNumber
column = self.lastMarker.column + 1
self.errorHandler.tolerateError(index, line, column, msg)
# Throw an exception because of the token.
def unexpectedTokenError(self, token=None, message=None):
msg = message or Messages.UnexpectedToken
if token:
if not message:
typ = token.type
if typ is Token.EOF:
msg = Messages.UnexpectedEOS
elif typ is Token.Identifier:
msg = Messages.UnexpectedIdentifier
elif typ is Token.NumericLiteral:
msg = Messages.UnexpectedNumber
elif typ is Token.StringLiteral:
msg = Messages.UnexpectedString
elif typ is Token.Template:
msg = Messages.UnexpectedTemplate
elif typ is Token.Keyword:
if self.scanner.isFutureReservedWord(token.value):
msg = Messages.UnexpectedReserved
elif self.context.strict and self.scanner.isStrictModeReservedWord(token.value):
msg = Messages.StrictReservedWord
else:
msg = Messages.UnexpectedToken
value = token.value
else:
value = 'ILLEGAL'
msg = msg.replace('%0', unicode(value), 1)
if token and isinstance(token.lineNumber, int):
index = token.start
line = token.lineNumber
lastMarkerLineStart = self.lastMarker.index - self.lastMarker.column
column = token.start - lastMarkerLineStart + 1
return self.errorHandler.createError(index, line, column, msg)
else:
index = self.lastMarker.index
line = self.lastMarker.line
column = self.lastMarker.column + 1
return self.errorHandler.createError(index, line, column, msg)
def throwUnexpectedToken(self, token=None, message=None):
raise self.unexpectedTokenError(token, message)
def tolerateUnexpectedToken(self, token=None, message=None):
self.errorHandler.tolerate(self.unexpectedTokenError(token, message))
def collectComments(self):
if not self.config.comment:
self.scanner.scanComments()
else:
comments = self.scanner.scanComments()
if comments:
for e in comments:
if e.multiLine:
node = Node.BlockComment(self.scanner.source[e.slice[0]:e.slice[1]])
else:
node = Node.LineComment(self.scanner.source[e.slice[0]:e.slice[1]])
if self.config.range:
node.range = e.range
if self.config.loc:
node.loc = e.loc
if self.delegate:
metadata = SourceLocation(
start=Position(
line=e.loc.start.line,
column=e.loc.start.column,
offset=e.range[0],
),
end=Position(
line=e.loc.end.line,
column=e.loc.end.column,
offset=e.range[1],
)
)
new_node = self.delegate(node, metadata)
if new_node is not None:
node = new_node
# From internal representation to an external structure
def getTokenRaw(self, token):
return self.scanner.source[token.start:token.end]
def convertToken(self, token):
t = TokenEntry(
type=TokenName[token.type],
value=self.getTokenRaw(token),
)
if self.config.range:
t.range = [token.start, token.end]
if self.config.loc:
t.loc = SourceLocation(
start=Position(
line=self.startMarker.line,
column=self.startMarker.column,
),
end=Position(
line=self.scanner.lineNumber,
column=self.scanner.index - self.scanner.lineStart,
),
)
if token.type is Token.RegularExpression:
t.regex = RegExp(
pattern=token.pattern,
flags=token.flags,
)
return t
def nextToken(self):
token = self.lookahead
self.lastMarker.index = self.scanner.index
self.lastMarker.line = self.scanner.lineNumber
self.lastMarker.column = self.scanner.index - self.scanner.lineStart
self.collectComments()
if self.scanner.index != self.startMarker.index:
self.startMarker.index = self.scanner.index
self.startMarker.line = self.scanner.lineNumber
self.startMarker.column = self.scanner.index - self.scanner.lineStart
next = self.scanner.lex()
self.hasLineTerminator = token.lineNumber != next.lineNumber
if next and self.context.strict and next.type is Token.Identifier:
if self.scanner.isStrictModeReservedWord(next.value):
next.type = Token.Keyword
self.lookahead = next
if self.config.tokens and next.type is not Token.EOF:
self.tokens.append(self.convertToken(next))
return token
def nextRegexToken(self):
self.collectComments()
token = self.scanner.scanRegExp()
if self.config.tokens:
# Pop the previous token, '/' or '/='
# self is added from the lookahead token.
self.tokens.pop()
self.tokens.append(self.convertToken(token))
# Prime the next lookahead.
self.lookahead = token
self.nextToken()
return token
def createNode(self):
return Marker(
index=self.startMarker.index,
line=self.startMarker.line,
column=self.startMarker.column,
)
def startNode(self, token, lastLineStart=0):
column = token.start - token.lineStart
line = token.lineNumber
if column < 0:
column += lastLineStart
line -= 1
return Marker(
index=token.start,
line=line,
column=column,
)
def finalize(self, marker, node):
if self.config.range:
node.range = [marker.index, self.lastMarker.index]
if self.config.loc:
node.loc = SourceLocation(
start=Position(
line=marker.line,
column=marker.column,
),
end=Position(
line=self.lastMarker.line,
column=self.lastMarker.column,
),
)
if self.config.source:
node.loc.source = self.config.source
if self.delegate:
metadata = SourceLocation(
start=Position(
line=marker.line,
column=marker.column,
offset=marker.index,
),
end=Position(
line=self.lastMarker.line,
column=self.lastMarker.column,
offset=self.lastMarker.index,
)
)
new_node = self.delegate(node, metadata)
if new_node is not None:
node = new_node
return node
# Expect the next token to match the specified punctuator.
# If not, an exception will be thrown.
def expect(self, value):
token = self.nextToken()
if token.type is not Token.Punctuator or token.value != value:
self.throwUnexpectedToken(token)
# Quietly expect a comma when in tolerant mode, otherwise delegates to expect().
def expectCommaSeparator(self):
if self.config.tolerant:
token = self.lookahead
if token.type is Token.Punctuator and token.value == ',':
self.nextToken()
elif token.type is Token.Punctuator and token.value == ';':
self.nextToken()
self.tolerateUnexpectedToken(token)
else:
self.tolerateUnexpectedToken(token, Messages.UnexpectedToken)
else:
self.expect(',')
# Expect the next token to match the specified keyword.
# If not, an exception will be thrown.
def expectKeyword(self, keyword):
token = self.nextToken()
if token.type is not Token.Keyword or token.value != keyword:
self.throwUnexpectedToken(token)
# Return true if the next token matches the specified punctuator.
def match(self, *value):
return self.lookahead.type is Token.Punctuator and self.lookahead.value in value
# Return true if the next token matches the specified keyword
def matchKeyword(self, *keyword):
return self.lookahead.type is Token.Keyword and self.lookahead.value in keyword
# Return true if the next token matches the specified contextual keyword
# (where an identifier is sometimes a keyword depending on the context)
def matchContextualKeyword(self, *keyword):
return self.lookahead.type is Token.Identifier and self.lookahead.value in keyword
# Return true if the next token is an assignment operator
def matchAssign(self):
if self.lookahead.type is not Token.Punctuator:
return False
op = self.lookahead.value
return op in ('=', '*=', '**=', '/=', '%=', '+=', '-=', '<<=', '>>=', '>>>=', '&=', '^=', '|=')
# Cover grammar support.
#
# When an assignment expression position starts with an left parenthesis, the determination of the type
# of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
# or the first comma. This situation also defers the determination of all the expressions nested in the pair.
#
# There are three productions that can be parsed in a parentheses pair that needs to be determined
# after the outermost pair is closed. They are:
#
# 1. AssignmentExpression
# 2. BindingElements
# 3. AssignmentTargets
#
# In order to avoid exponential backtracking, we use two flags to denote if the production can be
# binding element or assignment target.
#
# The three productions have the relationship:
#
# BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
#
# with a single exception that CoverInitializedName when used directly in an Expression, generates
# an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
# first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
#
# isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
# effect the current flags. This means the production the parser parses is only used as an expression. Therefore
# the CoverInitializedName check is conducted.
#
# inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
# the flags outside of the parser. This means the production the parser parses is used as a part of a potential
# pattern. The CoverInitializedName check is deferred.
def isolateCoverGrammar(self, parseFunction):
previousIsBindingElement = self.context.isBindingElement
previousIsAssignmentTarget = self.context.isAssignmentTarget
previousFirstCoverInitializedNameError = self.context.firstCoverInitializedNameError
self.context.isBindingElement = True
self.context.isAssignmentTarget = True
self.context.firstCoverInitializedNameError = None
result = parseFunction()
if self.context.firstCoverInitializedNameError is not None:
self.throwUnexpectedToken(self.context.firstCoverInitializedNameError)
self.context.isBindingElement = previousIsBindingElement
self.context.isAssignmentTarget = previousIsAssignmentTarget
self.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError
return result
def inheritCoverGrammar(self, parseFunction):
previousIsBindingElement = self.context.isBindingElement
previousIsAssignmentTarget = self.context.isAssignmentTarget
previousFirstCoverInitializedNameError = self.context.firstCoverInitializedNameError
self.context.isBindingElement = True
self.context.isAssignmentTarget = True
self.context.firstCoverInitializedNameError = None
result = parseFunction()
self.context.isBindingElement = self.context.isBindingElement and previousIsBindingElement
self.context.isAssignmentTarget = self.context.isAssignmentTarget and previousIsAssignmentTarget
self.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError or self.context.firstCoverInitializedNameError
return result
def consumeSemicolon(self):
if self.match(';'):
self.nextToken()
elif not self.hasLineTerminator:
if self.lookahead.type is not Token.EOF and not self.match('}'):
self.throwUnexpectedToken(self.lookahead)
self.lastMarker.index = self.startMarker.index
self.lastMarker.line = self.startMarker.line
self.lastMarker.column = self.startMarker.column
# https://tc39.github.io/ecma262/#sec-primary-expression
def parsePrimaryExpression(self):
node = self.createNode()
typ = self.lookahead.type
if typ is Token.Identifier:
if (self.context.isModule or self.context.allowAwait) and self.lookahead.value == 'await':
self.tolerateUnexpectedToken(self.lookahead)
expr = self.parseFunctionExpression() if self.matchAsyncFunction() else self.finalize(node, Node.Identifier(self.nextToken().value))
elif typ in (
Token.NumericLiteral,
Token.StringLiteral,
):
if self.context.strict and self.lookahead.octal:
self.tolerateUnexpectedToken(self.lookahead, Messages.StrictOctalLiteral)
self.context.isAssignmentTarget = False
self.context.isBindingElement = False
token = self.nextToken()
raw = self.getTokenRaw(token)
expr = self.finalize(node, Node.Literal(token.value, raw))
elif typ is Token.BooleanLiteral:
self.context.isAssignmentTarget = False
self.context.isBindingElement = False
token = self.nextToken()
raw = self.getTokenRaw(token)
expr = self.finalize(node, Node.Literal(token.value == 'true', raw))
elif typ is Token.NullLiteral:
self.context.isAssignmentTarget = False
self.context.isBindingElement = False
token = self.nextToken()
raw = self.getTokenRaw(token)
expr = self.finalize(node, Node.Literal(None, raw))
elif typ is Token.Template:
expr = self.parseTemplateLiteral()
elif typ is Token.Punctuator:
value = self.lookahead.value
if value == '(':
self.context.isBindingElement = False
expr = self.inheritCoverGrammar(self.parseGroupExpression)
elif value == '[':
expr = self.inheritCoverGrammar(self.parseArrayInitializer)
elif value == '{':
expr = self.inheritCoverGrammar(self.parseObjectInitializer)
elif value in ('/', '/='):
self.context.isAssignmentTarget = False
self.context.isBindingElement = False
self.scanner.index = self.startMarker.index
token = self.nextRegexToken()
raw = self.getTokenRaw(token)
expr = self.finalize(node, Node.RegexLiteral(token.regex, raw, token.pattern, token.flags))
else:
expr = self.throwUnexpectedToken(self.nextToken())
elif typ is Token.Keyword:
if not self.context.strict and self.context.allowYield and self.matchKeyword('yield'):
expr = self.parseIdentifierName()
elif not self.context.strict and self.matchKeyword('let'):
expr = self.finalize(node, Node.Identifier(self.nextToken().value))
else:
self.context.isAssignmentTarget = False
self.context.isBindingElement = False
if self.matchKeyword('function'):
expr = self.parseFunctionExpression()
elif self.matchKeyword('this'):
self.nextToken()
expr = self.finalize(node, Node.ThisExpression())
elif self.matchKeyword('class'):
expr = self.parseClassExpression()
elif self.matchImportCall():
expr = self.parseImportCall()
else:
expr = self.throwUnexpectedToken(self.nextToken())
else:
expr = self.throwUnexpectedToken(self.nextToken())
return expr
# https://tc39.github.io/ecma262/#sec-array-initializer
def parseSpreadElement(self):
node = self.createNode()
self.expect('...')
arg = self.inheritCoverGrammar(self.parseAssignmentExpression)
return self.finalize(node, Node.SpreadElement(arg))
def parseArrayInitializer(self):
node = self.createNode()
elements = []
self.expect('[')
while not self.match(']'):
if self.match(','):
self.nextToken()
elements.append(None)
elif self.match('...'):
element = self.parseSpreadElement()
if not self.match(']'):
self.context.isAssignmentTarget = False
self.context.isBindingElement = False
self.expect(',')
elements.append(element)
else:
elements.append(self.inheritCoverGrammar(self.parseAssignmentExpression))
if not self.match(']'):
self.expect(',')
self.expect(']')
return self.finalize(node, Node.ArrayExpression(elements))
# https://tc39.github.io/ecma262/#sec-object-initializer
def parsePropertyMethod(self, params):
self.context.isAssignmentTarget = False
self.context.isBindingElement = False
previousStrict = self.context.strict
previousAllowStrictDirective = self.context.allowStrictDirective
self.context.allowStrictDirective = params.simple
body = self.isolateCoverGrammar(self.parseFunctionSourceElements)
if self.context.strict and params.firstRestricted:
self.tolerateUnexpectedToken(params.firstRestricted, params.message)
if self.context.strict and params.stricted:
self.tolerateUnexpectedToken(params.stricted, params.message)
self.context.strict = previousStrict
self.context.allowStrictDirective = previousAllowStrictDirective
return body
def parsePropertyMethodFunction(self):
isGenerator = False
node = self.createNode()
previousAllowYield = self.context.allowYield
self.context.allowYield = True
params = self.parseFormalParameters()
method = self.parsePropertyMethod(params)
self.context.allowYield = previousAllowYield
return self.finalize(node, Node.FunctionExpression(None, params.params, method, isGenerator))
def parsePropertyMethodAsyncFunction(self):
node = self.createNode()
previousAllowYield = self.context.allowYield
previousAwait = self.context.allowAwait
self.context.allowYield = False
self.context.allowAwait = True
params = self.parseFormalParameters()
method = self.parsePropertyMethod(params)
self.context.allowYield = previousAllowYield
self.context.allowAwait = previousAwait
return self.finalize(node, Node.AsyncFunctionExpression(None, params.params, method))
def parseObjectPropertyKey(self):
node = self.createNode()
token = self.nextToken()
typ = token.type
if typ in (
Token.StringLiteral,
Token.NumericLiteral,
):
if self.context.strict and token.octal:
self.tolerateUnexpectedToken(token, Messages.StrictOctalLiteral)
raw = self.getTokenRaw(token)
key = self.finalize(node, Node.Literal(token.value, raw))
elif typ in (
Token.Identifier,
Token.BooleanLiteral,
Token.NullLiteral,
Token.Keyword,
):
key = self.finalize(node, Node.Identifier(token.value))
elif typ is Token.Punctuator:
if token.value == '[':
key = self.isolateCoverGrammar(self.parseAssignmentExpression)
self.expect(']')
else:
key = self.throwUnexpectedToken(token)
else:
key = self.throwUnexpectedToken(token)
return key
def isPropertyKey(self, key, value):
return (
(key.type is Syntax.Identifier and key.name == value) or
(key.type is Syntax.Literal and key.value == value)
)
def parseObjectProperty(self, hasProto):
node = self.createNode()
token = self.lookahead
key = None
value = None
computed = False
method = False
shorthand = False
isAsync = False
if token.type is Token.Identifier:
id = token.value
self.nextToken()
computed = self.match('[')
isAsync = not self.hasLineTerminator and (id == 'async') and not (self.match(':', '(', '*', ','))
key = self.parseObjectPropertyKey() if isAsync else self.finalize(node, Node.Identifier(id))
elif self.match('*'):
self.nextToken()
else:
computed = self.match('[')
key = self.parseObjectPropertyKey()
lookaheadPropertyKey = self.qualifiedPropertyName(self.lookahead)
if token.type is Token.Identifier and not isAsync and token.value == 'get' and lookaheadPropertyKey:
kind = 'get'
computed = self.match('[')
key = self.parseObjectPropertyKey()
self.context.allowYield = False
value = self.parseGetterMethod()
elif token.type is Token.Identifier and not isAsync and token.value == 'set' and lookaheadPropertyKey:
kind = 'set'
computed = self.match('[')
key = self.parseObjectPropertyKey()
value = self.parseSetterMethod()
elif token.type is Token.Punctuator and token.value == '*' and lookaheadPropertyKey:
kind = 'init'
computed = self.match('[')
key = self.parseObjectPropertyKey()
value = self.parseGeneratorMethod()
method = True
else:
if not key:
self.throwUnexpectedToken(self.lookahead)
kind = 'init'
if self.match(':') and not isAsync:
if not computed and self.isPropertyKey(key, '__proto__'):
if hasProto.value:
self.tolerateError(Messages.DuplicateProtoProperty)
hasProto.value = True
self.nextToken()
value = self.inheritCoverGrammar(self.parseAssignmentExpression)
elif self.match('('):
value = self.parsePropertyMethodAsyncFunction() if isAsync else self.parsePropertyMethodFunction()
method = True
elif token.type is Token.Identifier:
id = self.finalize(node, Node.Identifier(token.value))
if self.match('='):
self.context.firstCoverInitializedNameError = self.lookahead
self.nextToken()
shorthand = True
init = self.isolateCoverGrammar(self.parseAssignmentExpression)
value = self.finalize(node, Node.AssignmentPattern(id, init))
else:
shorthand = True
value = id
else:
self.throwUnexpectedToken(self.nextToken())
return self.finalize(node, Node.Property(kind, key, computed, value, method, shorthand))
def parseObjectInitializer(self):
node = self.createNode()
self.expect('{')
properties = []
hasProto = Value(False)
while not self.match('}'):
properties.append(self.parseSpreadElement() if self.match('...') else self.parseObjectProperty(hasProto))
if not self.match('}'):
self.expectCommaSeparator()
self.expect('}')
return self.finalize(node, Node.ObjectExpression(properties))
# https://tc39.github.io/ecma262/#sec-template-literals
def parseTemplateHead(self):
assert self.lookahead.head, 'Template literal must start with a template head'
node = self.createNode()
token = self.nextToken()
raw = token.value
cooked = token.cooked
return self.finalize(node, Node.TemplateElement(raw, cooked, token.tail))
def parseTemplateElement(self):
if self.lookahead.type is not Token.Template:
self.throwUnexpectedToken()
node = self.createNode()
token = self.nextToken()
raw = token.value
cooked = token.cooked
return self.finalize(node, Node.TemplateElement(raw, cooked, token.tail))
def parseTemplateLiteral(self):
node = self.createNode()
expressions = []
quasis = []
quasi = self.parseTemplateHead()
quasis.append(quasi)
while not quasi.tail:
expressions.append(self.parseExpression())
quasi = self.parseTemplateElement()
quasis.append(quasi)
return self.finalize(node, Node.TemplateLiteral(quasis, expressions))
# https://tc39.github.io/ecma262/#sec-grouping-operator
def reinterpretExpressionAsPattern(self, expr):
typ = expr.type
if typ in (
Syntax.Identifier,
Syntax.MemberExpression,
Syntax.RestElement,
Syntax.AssignmentPattern,
):
pass
elif typ is Syntax.SpreadElement:
expr.type = Syntax.RestElement
self.reinterpretExpressionAsPattern(expr.argument)
elif typ is Syntax.ArrayExpression:
expr.type = Syntax.ArrayPattern
for elem in expr.elements:
if elem is not None:
self.reinterpretExpressionAsPattern(elem)
elif typ is Syntax.ObjectExpression:
expr.type = Syntax.ObjectPattern
for prop in expr.properties:
self.reinterpretExpressionAsPattern(prop if prop.type is Syntax.SpreadElement else prop.value)
elif typ is Syntax.AssignmentExpression:
expr.type = Syntax.AssignmentPattern
del expr.operator
self.reinterpretExpressionAsPattern(expr.left)
else:
# Allow other node type for tolerant parsing.
pass
def parseGroupExpression(self):
self.expect('(')
if self.match(')'):
self.nextToken()
if not self.match('=>'):
self.expect('=>')
expr = Node.ArrowParameterPlaceHolder([])
else:
startToken = self.lookahead
params = []
if self.match('...'):
expr = self.parseRestElement(params)
self.expect(')')
if not self.match('=>'):
self.expect('=>')
expr = Node.ArrowParameterPlaceHolder([expr])
else:
arrow = False
self.context.isBindingElement = True
expr = self.inheritCoverGrammar(self.parseAssignmentExpression)
if self.match(','):
expressions = []
self.context.isAssignmentTarget = False
expressions.append(expr)
while self.lookahead.type is not Token.EOF:
if not self.match(','):
break
self.nextToken()
if self.match(')'):
self.nextToken()
for expression in expressions:
self.reinterpretExpressionAsPattern(expression)
arrow = True
expr = Node.ArrowParameterPlaceHolder(expressions)
elif self.match('...'):
if not self.context.isBindingElement:
self.throwUnexpectedToken(self.lookahead)
expressions.append(self.parseRestElement(params))
self.expect(')')
if not self.match('=>'):
self.expect('=>')
self.context.isBindingElement = False
for expression in expressions:
self.reinterpretExpressionAsPattern(expression)
arrow = True
expr = Node.ArrowParameterPlaceHolder(expressions)
else:
expressions.append(self.inheritCoverGrammar(self.parseAssignmentExpression))
if arrow:
break
if not arrow:
expr = self.finalize(self.startNode(startToken), Node.SequenceExpression(expressions))
if not arrow:
self.expect(')')
if self.match('=>'):
if expr.type is Syntax.Identifier and expr.name == 'yield':
arrow = True
expr = Node.ArrowParameterPlaceHolder([expr])
if not arrow:
if not self.context.isBindingElement:
self.throwUnexpectedToken(self.lookahead)
if expr.type is Syntax.SequenceExpression:
for expression in expr.expressions:
self.reinterpretExpressionAsPattern(expression)
else:
self.reinterpretExpressionAsPattern(expr)
if expr.type is Syntax.SequenceExpression:
parameters = expr.expressions
else:
parameters = [expr]
expr = Node.ArrowParameterPlaceHolder(parameters)
self.context.isBindingElement = False
return expr
# https://tc39.github.io/ecma262/#sec-left-hand-side-expressions
def parseArguments(self):
self.expect('(')
args = []
if not self.match(')'):
while True:
if self.match('...'):
expr = self.parseSpreadElement()
else:
expr = self.isolateCoverGrammar(self.parseAssignmentExpression)
args.append(expr)
if self.match(')'):
break
self.expectCommaSeparator()
if self.match(')'):
break
self.expect(')')