forked from Instagram/LibCST
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpression.py
1630 lines (1470 loc) · 52.8 KB
/
expression.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
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-unsafe
import re
import typing
from tokenize import (
Floatnumber as FLOATNUMBER_RE,
Imagnumber as IMAGNUMBER_RE,
Intnumber as INTNUMBER_RE,
)
from libcst._excep import CSTLogicError
from libcst._exceptions import ParserSyntaxError, PartialParserSyntaxError
from libcst._maybe_sentinel import MaybeSentinel
from libcst._nodes.expression import (
Arg,
Asynchronous,
Attribute,
Await,
BinaryOperation,
BooleanOperation,
Call,
Comparison,
ComparisonTarget,
CompFor,
CompIf,
ConcatenatedString,
Dict,
DictComp,
DictElement,
Element,
Ellipsis,
Float,
FormattedString,
FormattedStringExpression,
FormattedStringText,
From,
GeneratorExp,
IfExp,
Imaginary,
Index,
Integer,
Lambda,
LeftCurlyBrace,
LeftParen,
LeftSquareBracket,
List,
ListComp,
Name,
NamedExpr,
Param,
Parameters,
RightCurlyBrace,
RightParen,
RightSquareBracket,
Set,
SetComp,
Slice,
StarredDictElement,
StarredElement,
Subscript,
SubscriptElement,
Tuple,
UnaryOperation,
Yield,
)
from libcst._nodes.op import (
Add,
And,
AssignEqual,
BaseBinaryOp,
BaseBooleanOp,
BaseCompOp,
BitAnd,
BitInvert,
BitOr,
BitXor,
Colon,
Comma,
Divide,
Dot,
Equal,
FloorDivide,
GreaterThan,
GreaterThanEqual,
In,
Is,
IsNot,
LeftShift,
LessThan,
LessThanEqual,
MatrixMultiply,
Minus,
Modulo,
Multiply,
Not,
NotEqual,
NotIn,
Or,
Plus,
Power,
RightShift,
Subtract,
)
from libcst._nodes.whitespace import SimpleWhitespace
from libcst._parser.custom_itertools import grouper
from libcst._parser.production_decorator import with_production
from libcst._parser.types.config import ParserConfig
from libcst._parser.types.partials import (
ArglistPartial,
AttributePartial,
CallPartial,
FormattedStringConversionPartial,
FormattedStringFormatSpecPartial,
SlicePartial,
SubscriptPartial,
WithLeadingWhitespace,
)
from libcst._parser.types.token import Token
from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace
BINOP_TOKEN_LUT: typing.Dict[str, typing.Type[BaseBinaryOp]] = {
"*": Multiply,
"@": MatrixMultiply,
"/": Divide,
"%": Modulo,
"//": FloorDivide,
"+": Add,
"-": Subtract,
"<<": LeftShift,
">>": RightShift,
"&": BitAnd,
"^": BitXor,
"|": BitOr,
}
BOOLOP_TOKEN_LUT: typing.Dict[str, typing.Type[BaseBooleanOp]] = {"and": And, "or": Or}
COMPOP_TOKEN_LUT: typing.Dict[str, typing.Type[BaseCompOp]] = {
"<": LessThan,
">": GreaterThan,
"==": Equal,
"<=": LessThanEqual,
">=": GreaterThanEqual,
"in": In,
"is": Is,
}
# N.B. This uses a `testlist | star_expr`, not a `testlist_star_expr` because
# `testlist_star_expr` may not always be representable by a non-partial node, since it's
# only used as part of `expr_stmt`.
@with_production("expression_input", "(testlist | star_expr) ENDMARKER")
def convert_expression_input(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
(child, endmarker) = children
# HACK: UGLY! REMOVE THIS SOON!
# Unwrap WithLeadingWhitespace if it exists. It shouldn't exist by this point, but
# testlist isn't fully implemented, and we currently leak these partial objects.
if isinstance(child, WithLeadingWhitespace):
child = child.value
return child
@with_production("namedexpr_test", "test [':=' test]", version=">=3.8")
def convert_namedexpr_test(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
test, *assignment = children
if len(assignment) == 0:
return test
# Convert all of the operations that have no precedence in a loop
(walrus, value) = assignment
return WithLeadingWhitespace(
NamedExpr(
target=test.value,
whitespace_before_walrus=parse_parenthesizable_whitespace(
config, walrus.whitespace_before
),
whitespace_after_walrus=parse_parenthesizable_whitespace(
config, walrus.whitespace_after
),
value=value.value,
),
test.whitespace_before,
)
@with_production("test", "or_test ['if' or_test 'else' test] | lambdef")
def convert_test(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
if len(children) == 1:
(child,) = children
return child
else:
(body, if_token, test, else_token, orelse) = children
return WithLeadingWhitespace(
IfExp(
body=body.value,
test=test.value,
orelse=orelse.value,
whitespace_before_if=parse_parenthesizable_whitespace(
config, if_token.whitespace_before
),
whitespace_after_if=parse_parenthesizable_whitespace(
config, if_token.whitespace_after
),
whitespace_before_else=parse_parenthesizable_whitespace(
config, else_token.whitespace_before
),
whitespace_after_else=parse_parenthesizable_whitespace(
config, else_token.whitespace_after
),
),
body.whitespace_before,
)
@with_production("test_nocond", "or_test | lambdef_nocond")
def convert_test_nocond(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
(child,) = children
return child
@with_production("lambdef", "'lambda' [varargslist] ':' test")
@with_production("lambdef_nocond", "'lambda' [varargslist] ':' test_nocond")
def convert_lambda(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
lambdatoken, *params, colontoken, test = children
# Grab the whitespace around the colon. If there are no params, then
# the colon owns the whitespace before and after it. If there are
# any params, then the last param owns the whitespace before the colon.
# We handle the parameter movement below.
colon = Colon(
whitespace_before=parse_parenthesizable_whitespace(
config, colontoken.whitespace_before
),
whitespace_after=parse_parenthesizable_whitespace(
config, colontoken.whitespace_after
),
)
# Unpack optional parameters
if len(params) == 0:
parameters = Parameters()
whitespace_after_lambda = MaybeSentinel.DEFAULT
else:
(parameters,) = params
whitespace_after_lambda = parse_parenthesizable_whitespace(
config, lambdatoken.whitespace_after
)
# Handle pre-colon whitespace
if parameters.star_kwarg is not None:
if parameters.star_kwarg.comma == MaybeSentinel.DEFAULT:
parameters = parameters.with_changes(
star_kwarg=parameters.star_kwarg.with_changes(
whitespace_after_param=colon.whitespace_before
)
)
elif parameters.kwonly_params:
if parameters.kwonly_params[-1].comma == MaybeSentinel.DEFAULT:
parameters = parameters.with_changes(
kwonly_params=(
*parameters.kwonly_params[:-1],
parameters.kwonly_params[-1].with_changes(
whitespace_after_param=colon.whitespace_before
),
)
)
elif isinstance(parameters.star_arg, Param):
if parameters.star_arg.comma == MaybeSentinel.DEFAULT:
parameters = parameters.with_changes(
star_arg=parameters.star_arg.with_changes(
whitespace_after_param=colon.whitespace_before
)
)
elif parameters.params:
if parameters.params[-1].comma == MaybeSentinel.DEFAULT:
parameters = parameters.with_changes(
params=(
*parameters.params[:-1],
parameters.params[-1].with_changes(
whitespace_after_param=colon.whitespace_before
),
)
)
# Colon doesn't own its own pre-whitespace now.
colon = colon.with_changes(whitespace_before=SimpleWhitespace(""))
# Return a lambda
return WithLeadingWhitespace(
Lambda(
whitespace_after_lambda=whitespace_after_lambda,
params=parameters,
body=test.value,
colon=colon,
),
lambdatoken.whitespace_before,
)
@with_production("or_test", "and_test ('or' and_test)*")
@with_production("and_test", "not_test ('and' not_test)*")
def convert_boolop(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
leftexpr, *rightexprs = children
if len(rightexprs) == 0:
return leftexpr
whitespace_before = leftexpr.whitespace_before
leftexpr = leftexpr.value
# Convert all of the operations that have no precedence in a loop
for op, rightexpr in grouper(rightexprs, 2):
if op.string not in BOOLOP_TOKEN_LUT:
raise ParserSyntaxError(
f"Unexpected token '{op.string}'!",
lines=config.lines,
raw_line=0,
raw_column=0,
)
leftexpr = BooleanOperation(
left=leftexpr,
# pyre-ignore Pyre thinks that the type of the LUT is CSTNode.
operator=BOOLOP_TOKEN_LUT[op.string](
whitespace_before=parse_parenthesizable_whitespace(
config, op.whitespace_before
),
whitespace_after=parse_parenthesizable_whitespace(
config, op.whitespace_after
),
),
right=rightexpr.value,
)
return WithLeadingWhitespace(leftexpr, whitespace_before)
@with_production("not_test", "'not' not_test | comparison")
def convert_not_test(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
if len(children) == 1:
(child,) = children
return child
else:
nottoken, nottest = children
return WithLeadingWhitespace(
UnaryOperation(
operator=Not(
whitespace_after=parse_parenthesizable_whitespace(
config, nottoken.whitespace_after
)
),
expression=nottest.value,
),
nottoken.whitespace_before,
)
@with_production("comparison", "expr (comp_op expr)*")
def convert_comparison(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
if len(children) == 1:
(child,) = children
return child
lhs, *rest = children
comparisons: typing.List[ComparisonTarget] = []
for operator, comparator in grouper(rest, 2):
comparisons.append(
ComparisonTarget(operator=operator, comparator=comparator.value)
)
return WithLeadingWhitespace(
Comparison(left=lhs.value, comparisons=tuple(comparisons)),
lhs.whitespace_before,
)
@with_production(
"comp_op", "('<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not')"
)
def convert_comp_op(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
if len(children) == 1:
(op,) = children
if op.string in COMPOP_TOKEN_LUT:
# A regular comparison containing one token
# pyre-ignore Pyre thinks that the type of the LUT is CSTNode.
return COMPOP_TOKEN_LUT[op.string](
whitespace_before=parse_parenthesizable_whitespace(
config, op.whitespace_before
),
whitespace_after=parse_parenthesizable_whitespace(
config, op.whitespace_after
),
)
elif op.string in ["!=", "<>"]:
# Not equal, which can take two forms in some cases
return NotEqual(
whitespace_before=parse_parenthesizable_whitespace(
config, op.whitespace_before
),
value=op.string,
whitespace_after=parse_parenthesizable_whitespace(
config, op.whitespace_after
),
)
else:
# this should be unreachable
raise ParserSyntaxError(
f"Unexpected token '{op.string}'!",
lines=config.lines,
raw_line=0,
raw_column=0,
)
else:
# A two-token comparison
leftcomp, rightcomp = children
if leftcomp.string == "not" and rightcomp.string == "in":
return NotIn(
whitespace_before=parse_parenthesizable_whitespace(
config, leftcomp.whitespace_before
),
whitespace_between=parse_parenthesizable_whitespace(
config, leftcomp.whitespace_after
),
whitespace_after=parse_parenthesizable_whitespace(
config, rightcomp.whitespace_after
),
)
elif leftcomp.string == "is" and rightcomp.string == "not":
return IsNot(
whitespace_before=parse_parenthesizable_whitespace(
config, leftcomp.whitespace_before
),
whitespace_between=parse_parenthesizable_whitespace(
config, leftcomp.whitespace_after
),
whitespace_after=parse_parenthesizable_whitespace(
config, rightcomp.whitespace_after
),
)
else:
# this should be unreachable
raise ParserSyntaxError(
f"Unexpected token '{leftcomp.string} {rightcomp.string}'!",
lines=config.lines,
raw_line=0,
raw_column=0,
)
@with_production("star_expr", "'*' expr")
def convert_star_expr(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
star, expr = children
return WithLeadingWhitespace(
StarredElement(
expr.value,
whitespace_before_value=parse_parenthesizable_whitespace(
config, expr.whitespace_before
),
# atom is responsible for parenthesis and trailing_whitespace if they exist
# testlist_comp, exprlist, dictorsetmaker, etc are responsible for the comma
# if it exists.
),
whitespace_before=star.whitespace_before,
)
@with_production("expr", "xor_expr ('|' xor_expr)*")
@with_production("xor_expr", "and_expr ('^' and_expr)*")
@with_production("and_expr", "shift_expr ('&' shift_expr)*")
@with_production("shift_expr", "arith_expr (('<<'|'>>') arith_expr)*")
@with_production("arith_expr", "term (('+'|'-') term)*")
@with_production("term", "factor (('*'|'@'|'/'|'%'|'//') factor)*", version=">=3.5")
@with_production("term", "factor (('*'|'/'|'%'|'//') factor)*", version="<3.5")
def convert_binop(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
leftexpr, *rightexprs = children
if len(rightexprs) == 0:
return leftexpr
whitespace_before = leftexpr.whitespace_before
leftexpr = leftexpr.value
# Convert all of the operations that have no precedence in a loop
for op, rightexpr in grouper(rightexprs, 2):
if op.string not in BINOP_TOKEN_LUT:
raise ParserSyntaxError(
f"Unexpected token '{op.string}'!",
lines=config.lines,
raw_line=0,
raw_column=0,
)
leftexpr = BinaryOperation(
left=leftexpr,
# pyre-ignore Pyre thinks that the type of the LUT is CSTNode.
operator=BINOP_TOKEN_LUT[op.string](
whitespace_before=parse_parenthesizable_whitespace(
config, op.whitespace_before
),
whitespace_after=parse_parenthesizable_whitespace(
config, op.whitespace_after
),
),
right=rightexpr.value,
)
return WithLeadingWhitespace(leftexpr, whitespace_before)
@with_production("factor", "('+'|'-'|'~') factor | power")
def convert_factor(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
if len(children) == 1:
(child,) = children
return child
op, factor = children
# First, tokenize the unary operator
if op.string == "+":
opnode = Plus(
whitespace_after=parse_parenthesizable_whitespace(
config, op.whitespace_after
)
)
elif op.string == "-":
opnode = Minus(
whitespace_after=parse_parenthesizable_whitespace(
config, op.whitespace_after
)
)
elif op.string == "~":
opnode = BitInvert(
whitespace_after=parse_parenthesizable_whitespace(
config, op.whitespace_after
)
)
else:
raise ParserSyntaxError(
f"Unexpected token '{op.string}'!",
lines=config.lines,
raw_line=0,
raw_column=0,
)
return WithLeadingWhitespace(
UnaryOperation(operator=opnode, expression=factor.value), op.whitespace_before
)
@with_production("power", "atom_expr ['**' factor]")
def convert_power(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
if len(children) == 1:
(child,) = children
return child
left, power, right = children
return WithLeadingWhitespace(
BinaryOperation(
left=left.value,
operator=Power(
whitespace_before=parse_parenthesizable_whitespace(
config, power.whitespace_before
),
whitespace_after=parse_parenthesizable_whitespace(
config, power.whitespace_after
),
),
right=right.value,
),
left.whitespace_before,
)
@with_production("atom_expr", "atom_expr_await | atom_expr_trailer")
def convert_atom_expr(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
(child,) = children
return child
@with_production("atom_expr_await", "AWAIT atom_expr_trailer")
def convert_atom_expr_await(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
keyword, expr = children
return WithLeadingWhitespace(
Await(
whitespace_after_await=parse_parenthesizable_whitespace(
config, keyword.whitespace_after
),
expression=expr.value,
),
keyword.whitespace_before,
)
@with_production("atom_expr_trailer", "atom trailer*")
def convert_atom_expr_trailer(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
atom, *trailers = children
whitespace_before = atom.whitespace_before
atom = atom.value
# Need to walk through all trailers from left to right and construct
# a series of nodes based on each partial type. We can't do this with
# left recursion due to limits in the parser.
for trailer in trailers:
if isinstance(trailer, SubscriptPartial):
atom = Subscript(
value=atom,
whitespace_after_value=parse_parenthesizable_whitespace(
config, trailer.whitespace_before
),
lbracket=trailer.lbracket,
# pyre-fixme[6]: Expected `Sequence[SubscriptElement]` for 4th param
# but got `Union[typing.Sequence[SubscriptElement], Index, Slice]`.
slice=trailer.slice,
rbracket=trailer.rbracket,
)
elif isinstance(trailer, AttributePartial):
atom = Attribute(value=atom, dot=trailer.dot, attr=trailer.attr)
elif isinstance(trailer, CallPartial):
# If the trailing argument doesn't have a comma, then it owns the
# trailing whitespace before the rpar. Otherwise, the comma owns
# it.
if (
len(trailer.args) > 0
and trailer.args[-1].comma == MaybeSentinel.DEFAULT
):
args = (
*trailer.args[:-1],
trailer.args[-1].with_changes(
whitespace_after_arg=trailer.rpar.whitespace_before
),
)
else:
args = trailer.args
atom = Call(
func=atom,
whitespace_after_func=parse_parenthesizable_whitespace(
config, trailer.lpar.whitespace_before
),
whitespace_before_args=trailer.lpar.value.whitespace_after,
# pyre-fixme[6]: Expected `Sequence[Arg]` for 4th param but got
# `Tuple[object, ...]`.
args=tuple(args),
)
else:
# This is an invalid trailer, so lets give up
raise CSTLogicError()
return WithLeadingWhitespace(atom, whitespace_before)
@with_production(
"trailer", "trailer_arglist | trailer_subscriptlist | trailer_attribute"
)
def convert_trailer(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
(child,) = children
return child
@with_production("trailer_arglist", "'(' [arglist] ')'")
def convert_trailer_arglist(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
lpar, *arglist, rpar = children
return CallPartial(
lpar=WithLeadingWhitespace(
LeftParen(
whitespace_after=parse_parenthesizable_whitespace(
config, lpar.whitespace_after
)
),
lpar.whitespace_before,
),
args=() if not arglist else arglist[0].args,
rpar=RightParen(
whitespace_before=parse_parenthesizable_whitespace(
config, rpar.whitespace_before
)
),
)
@with_production("trailer_subscriptlist", "'[' subscriptlist ']'")
def convert_trailer_subscriptlist(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
(lbracket, subscriptlist, rbracket) = children
return SubscriptPartial(
lbracket=LeftSquareBracket(
whitespace_after=parse_parenthesizable_whitespace(
config, lbracket.whitespace_after
)
),
slice=subscriptlist.value,
rbracket=RightSquareBracket(
whitespace_before=parse_parenthesizable_whitespace(
config, rbracket.whitespace_before
)
),
whitespace_before=lbracket.whitespace_before,
)
@with_production("subscriptlist", "subscript (',' subscript)* [',']")
def convert_subscriptlist(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
# This is a list of SubscriptElement, so construct as such by grouping every
# subscript with an optional comma and adding to a list.
elements = []
for slice, comma in grouper(children, 2):
if comma is None:
elements.append(SubscriptElement(slice=slice.value))
else:
elements.append(
SubscriptElement(
slice=slice.value,
comma=Comma(
whitespace_before=parse_parenthesizable_whitespace(
config, comma.whitespace_before
),
whitespace_after=parse_parenthesizable_whitespace(
config, comma.whitespace_after
),
),
)
)
return WithLeadingWhitespace(elements, children[0].whitespace_before)
@with_production("subscript", "test | [test] ':' [test] [sliceop]")
def convert_subscript(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
if len(children) == 1 and not isinstance(children[0], Token):
# This is just an index node
(test,) = children
return WithLeadingWhitespace(Index(test.value), test.whitespace_before)
if isinstance(children[-1], SlicePartial):
# We got a partial slice as the final param. Extract the final
# bits of the full subscript.
*others, sliceop = children
whitespace_before = others[0].whitespace_before
second_colon = sliceop.second_colon
step = sliceop.step
else:
# We can just parse this below, without taking extras from the
# partial child.
others = children
whitespace_before = others[0].whitespace_before
second_colon = MaybeSentinel.DEFAULT
step = None
# We need to create a partial slice to pass up. So, align so we have
# a list that's always [Optional[Test], Colon, Optional[Test]].
if isinstance(others[0], Token):
# First token is a colon, so insert an empty test on the LHS. We
# know the RHS is a test since it's not a sliceop.
slicechildren = [None, *others]
else:
# First token is non-colon, so its a test.
slicechildren = [*others]
if len(slicechildren) < 3:
# Now, we have to fill in the RHS. We know its two long
# at this point if its not already 3.
slicechildren = [*slicechildren, None]
lower, first_colon, upper = slicechildren
return WithLeadingWhitespace(
Slice(
lower=lower.value if lower is not None else None,
first_colon=Colon(
whitespace_before=parse_parenthesizable_whitespace(
config,
first_colon.whitespace_before,
),
whitespace_after=parse_parenthesizable_whitespace(
config,
first_colon.whitespace_after,
),
),
upper=upper.value if upper is not None else None,
second_colon=second_colon,
step=step,
),
whitespace_before=whitespace_before,
)
@with_production("sliceop", "':' [test]")
def convert_sliceop(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
if len(children) == 2:
colon, test = children
step = test.value
else:
(colon,) = children
step = None
return SlicePartial(
second_colon=Colon(
whitespace_before=parse_parenthesizable_whitespace(
config, colon.whitespace_before
),
whitespace_after=parse_parenthesizable_whitespace(
config, colon.whitespace_after
),
),
step=step,
)
@with_production("trailer_attribute", "'.' NAME")
def convert_trailer_attribute(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
dot, name = children
return AttributePartial(
dot=Dot(
whitespace_before=parse_parenthesizable_whitespace(
config, dot.whitespace_before
),
whitespace_after=parse_parenthesizable_whitespace(
config, dot.whitespace_after
),
),
attr=Name(name.string),
)
@with_production(
"atom",
"atom_parens | atom_squarebrackets | atom_curlybraces | atom_string | atom_basic | atom_ellipses",
)
def convert_atom(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
(child,) = children
return child
@with_production("atom_basic", "NAME | NUMBER | 'None' | 'True' | 'False'")
def convert_atom_basic(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
(child,) = children
if child.type.name == "NAME":
# This also handles 'None', 'True', and 'False' directly, but we
# keep it in the grammar to be more correct.
return WithLeadingWhitespace(Name(child.string), child.whitespace_before)
elif child.type.name == "NUMBER":
# We must determine what type of number it is since we split node
# types up this way.
if re.fullmatch(INTNUMBER_RE, child.string):
return WithLeadingWhitespace(Integer(child.string), child.whitespace_before)
elif re.fullmatch(FLOATNUMBER_RE, child.string):
return WithLeadingWhitespace(Float(child.string), child.whitespace_before)
elif re.fullmatch(IMAGNUMBER_RE, child.string):
return WithLeadingWhitespace(
Imaginary(child.string), child.whitespace_before
)
else:
raise ParserSyntaxError(
f"Unparseable number {child.string}",
lines=config.lines,
raw_line=0,
raw_column=0,
)
else:
raise ParserSyntaxError(
f"Logic error, unexpected token {child.type.name}",
lines=config.lines,
raw_line=0,
raw_column=0,
)
@with_production("atom_squarebrackets", "'[' [testlist_comp_list] ']'")
def convert_atom_squarebrackets(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
lbracket_tok, *body, rbracket_tok = children
lbracket = LeftSquareBracket(
whitespace_after=parse_parenthesizable_whitespace(
config, lbracket_tok.whitespace_after
)
)
rbracket = RightSquareBracket(
whitespace_before=parse_parenthesizable_whitespace(
config, rbracket_tok.whitespace_before
)
)
if len(body) == 0:
list_node = List((), lbracket=lbracket, rbracket=rbracket)
else: # len(body) == 1
# body[0] is a List or ListComp
list_node = body[0].value.with_changes(lbracket=lbracket, rbracket=rbracket)
return WithLeadingWhitespace(list_node, lbracket_tok.whitespace_before)
@with_production("atom_curlybraces", "'{' [dictorsetmaker] '}'")
def convert_atom_curlybraces(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
lbrace_tok, *body, rbrace_tok = children
lbrace = LeftCurlyBrace(
whitespace_after=parse_parenthesizable_whitespace(
config, lbrace_tok.whitespace_after
)
)
rbrace = RightCurlyBrace(
whitespace_before=parse_parenthesizable_whitespace(
config, rbrace_tok.whitespace_before
)
)
if len(body) == 0:
dict_or_set_node = Dict((), lbrace=lbrace, rbrace=rbrace)
else: # len(body) == 1
dict_or_set_node = body[0].value.with_changes(lbrace=lbrace, rbrace=rbrace)
return WithLeadingWhitespace(dict_or_set_node, lbrace_tok.whitespace_before)
@with_production("atom_parens", "'(' [yield_expr|testlist_comp_tuple] ')'")
def convert_atom_parens(
config: ParserConfig, children: typing.Sequence[typing.Any]
) -> typing.Any:
lpar_tok, *atoms, rpar_tok = children
lpar = LeftParen(
whitespace_after=parse_parenthesizable_whitespace(
config, lpar_tok.whitespace_after
)
)
rpar = RightParen(
whitespace_before=parse_parenthesizable_whitespace(
config, rpar_tok.whitespace_before
)
)
if len(atoms) == 1:
# inner_atom is a _BaseParenthesizedNode
inner_atom = atoms[0].value
return WithLeadingWhitespace(
inner_atom.with_changes(
# pyre-fixme[60]: Expected to unpack an iterable, but got `unknown`.
lpar=(lpar, *inner_atom.lpar),
# pyre-fixme[60]: Expected to unpack an iterable, but got `unknown`.
rpar=(*inner_atom.rpar, rpar),
),
lpar_tok.whitespace_before,
)
else:
return WithLeadingWhitespace(
Tuple((), lpar=(lpar,), rpar=(rpar,)), lpar_tok.whitespace_before
)