-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathstatement.py
More file actions
3887 lines (3228 loc) · 144 KB
/
statement.py
File metadata and controls
3887 lines (3228 loc) · 144 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
# 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.
import inspect
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Literal, Optional, Pattern, Sequence, Union
from libcst import CSTLogicError
from libcst._add_slots import add_slots
from libcst._maybe_sentinel import MaybeSentinel
from libcst._nodes.base import CSTNode, CSTValidationError
from libcst._nodes.expression import (
_BaseParenthesizedNode,
Annotation,
Arg,
Asynchronous,
Attribute,
BaseAssignTargetExpression,
BaseDelTargetExpression,
BaseExpression,
ConcatenatedString,
ExpressionPosition,
From,
LeftCurlyBrace,
LeftParen,
LeftSquareBracket,
List,
Name,
Parameters,
RightCurlyBrace,
RightParen,
RightSquareBracket,
SimpleString,
Tuple,
)
from libcst._nodes.internal import (
CodegenState,
visit_body_sequence,
visit_optional,
visit_required,
visit_sentinel,
visit_sequence,
)
from libcst._nodes.op import (
AssignEqual,
BaseAugOp,
BitOr,
Colon,
Comma,
Dot,
ImportStar,
Semicolon,
)
from libcst._nodes.whitespace import (
BaseParenthesizableWhitespace,
EmptyLine,
ParenthesizedWhitespace,
SimpleWhitespace,
TrailingWhitespace,
)
from libcst._visitors import CSTVisitorT
_INDENT_WHITESPACE_RE: Pattern[str] = re.compile(r"[ \f\t]+", re.UNICODE)
class BaseSuite(CSTNode, ABC):
"""
A dummy base-class for both :class:`SimpleStatementSuite` and :class:`IndentedBlock`.
This exists to simplify type definitions and isinstance checks.
A suite is a group of statements controlled by a clause. A suite can be one or
more semicolon-separated simple statements on the same line as the header,
following the header’s colon, or it can be one or more indented statements on
subsequent lines.
-- https://docs.python.org/3/reference/compound_stmts.html
"""
__slots__ = ()
body: Union[Sequence["BaseStatement"], Sequence["BaseSmallStatement"]]
class BaseStatement(CSTNode, ABC):
"""
A class that exists to allow for typing to specify that any statement is allowed
in a particular location.
"""
__slots__ = ()
class BaseSmallStatement(CSTNode, ABC):
"""
Encapsulates a small statement, like ``del`` or ``pass``, and optionally adds a
trailing semicolon. A small statement is always contained inside a
:class:`SimpleStatementLine` or :class:`SimpleStatementSuite`. This exists to
simplify type definitions and isinstance checks.
"""
__slots__ = ()
#: An optional semicolon that appears after a small statement. This is optional
#: for the last small statement in a :class:`SimpleStatementLine` or
#: :class:`SimpleStatementSuite`, but all other small statements inside a simple
#: statement must contain a semicolon to disambiguate multiple small statements
#: on the same line.
semicolon: Union[Semicolon, MaybeSentinel] = MaybeSentinel.DEFAULT
@abstractmethod
def _codegen_impl(
self, state: CodegenState, default_semicolon: bool = False
) -> None: ...
@add_slots
@dataclass(frozen=True)
class Del(BaseSmallStatement):
"""
Represents a ``del`` statement. ``del`` is always followed by a target.
"""
#: The target expression will be deleted. This can be a name, a tuple,
#: an item of a list, an item of a dictionary, or an attribute.
target: BaseDelTargetExpression
#: The whitespace after the ``del`` keyword.
whitespace_after_del: SimpleWhitespace = SimpleWhitespace.field(" ")
#: Optional semicolon when this is used in a statement line. This semicolon
#: owns the whitespace on both sides of it when it is used.
semicolon: Union[Semicolon, MaybeSentinel] = MaybeSentinel.DEFAULT
def _validate(self) -> None:
if (
self.whitespace_after_del.empty
and not self.target._safe_to_use_with_word_operator(
ExpressionPosition.RIGHT
)
):
raise CSTValidationError("Must have at least one space after 'del'.")
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Del":
return Del(
target=visit_required(self, "target", self.target, visitor),
whitespace_after_del=visit_required(
self, "whitespace_after_del", self.whitespace_after_del, visitor
),
semicolon=visit_sentinel(self, "semicolon", self.semicolon, visitor),
)
def _codegen_impl(
self, state: CodegenState, default_semicolon: bool = False
) -> None:
with state.record_syntactic_position(self):
state.add_token("del")
self.whitespace_after_del._codegen(state)
self.target._codegen(state)
semicolon = self.semicolon
if isinstance(semicolon, MaybeSentinel):
if default_semicolon:
state.add_token("; ")
elif isinstance(semicolon, Semicolon):
semicolon._codegen(state)
@add_slots
@dataclass(frozen=True)
class Pass(BaseSmallStatement):
"""
Represents a ``pass`` statement.
"""
#: Optional semicolon when this is used in a statement line. This semicolon
#: owns the whitespace on both sides of it when it is used.
semicolon: Union[Semicolon, MaybeSentinel] = MaybeSentinel.DEFAULT
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Pass":
return Pass(
semicolon=visit_sentinel(self, "semicolon", self.semicolon, visitor)
)
def _codegen_impl(
self, state: CodegenState, default_semicolon: bool = False
) -> None:
with state.record_syntactic_position(self):
state.add_token("pass")
semicolon = self.semicolon
if isinstance(semicolon, MaybeSentinel):
if default_semicolon:
state.add_token("; ")
elif isinstance(semicolon, Semicolon):
semicolon._codegen(state)
@add_slots
@dataclass(frozen=True)
class Break(BaseSmallStatement):
"""
Represents a ``break`` statement, which is used to break out of a :class:`For`
or :class:`While` loop early.
"""
#: Optional semicolon when this is used in a statement line. This semicolon
#: owns the whitespace on both sides of it when it is used.
semicolon: Union[Semicolon, MaybeSentinel] = MaybeSentinel.DEFAULT
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Break":
return Break(
semicolon=visit_sentinel(self, "semicolon", self.semicolon, visitor)
)
def _codegen_impl(
self, state: CodegenState, default_semicolon: bool = False
) -> None:
with state.record_syntactic_position(self):
state.add_token("break")
semicolon = self.semicolon
if isinstance(semicolon, MaybeSentinel):
if default_semicolon:
state.add_token("; ")
elif isinstance(semicolon, Semicolon):
semicolon._codegen(state)
@add_slots
@dataclass(frozen=True)
class Continue(BaseSmallStatement):
"""
Represents a ``continue`` statement, which is used to skip to the next iteration
in a :class:`For` or :class:`While` loop.
"""
#: Optional semicolon when this is used in a statement line. This semicolon
#: owns the whitespace on both sides of it when it is used.
semicolon: Union[Semicolon, MaybeSentinel] = MaybeSentinel.DEFAULT
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Continue":
return Continue(
semicolon=visit_sentinel(self, "semicolon", self.semicolon, visitor)
)
def _codegen_impl(
self, state: CodegenState, default_semicolon: bool = False
) -> None:
with state.record_syntactic_position(self):
state.add_token("continue")
semicolon = self.semicolon
if isinstance(semicolon, MaybeSentinel):
if default_semicolon:
state.add_token("; ")
elif isinstance(semicolon, Semicolon):
semicolon._codegen(state)
@add_slots
@dataclass(frozen=True)
class Return(BaseSmallStatement):
"""
Represents a ``return`` or a ``return x`` statement.
"""
#: The optional expression that will be evaluated and returned.
value: Optional[BaseExpression] = None
#: Optional whitespace after the ``return`` keyword before the optional
#: value expression.
whitespace_after_return: Union[SimpleWhitespace, MaybeSentinel] = (
MaybeSentinel.DEFAULT
)
#: Optional semicolon when this is used in a statement line. This semicolon
#: owns the whitespace on both sides of it when it is used.
semicolon: Union[Semicolon, MaybeSentinel] = MaybeSentinel.DEFAULT
def _validate(self) -> None:
value = self.value
if value is not None:
whitespace_after_return = self.whitespace_after_return
has_no_gap = (
not isinstance(whitespace_after_return, MaybeSentinel)
and whitespace_after_return.empty
)
if has_no_gap and not value._safe_to_use_with_word_operator(
ExpressionPosition.RIGHT
):
raise CSTValidationError("Must have at least one space after 'return'.")
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Return":
return Return(
whitespace_after_return=visit_sentinel(
self, "whitespace_after_return", self.whitespace_after_return, visitor
),
value=visit_optional(self, "value", self.value, visitor),
semicolon=visit_sentinel(self, "semicolon", self.semicolon, visitor),
)
def _codegen_impl(
self, state: CodegenState, default_semicolon: bool = False
) -> None:
with state.record_syntactic_position(self):
state.add_token("return")
whitespace_after_return = self.whitespace_after_return
value = self.value
if isinstance(whitespace_after_return, MaybeSentinel):
if value is not None:
state.add_token(" ")
else:
whitespace_after_return._codegen(state)
if value is not None:
value._codegen(state)
semicolon = self.semicolon
if isinstance(semicolon, MaybeSentinel):
if default_semicolon:
state.add_token("; ")
elif isinstance(semicolon, Semicolon):
semicolon._codegen(state)
@add_slots
@dataclass(frozen=True)
class Expr(BaseSmallStatement):
"""
An expression used as a statement, where the result is unused and unassigned.
The most common place you will find this is in function calls where the return
value is unneeded.
"""
#: The expression itself. Python will evaluate the expression but not assign
#: the result anywhere.
value: BaseExpression
#: Optional semicolon when this is used in a statement line. This semicolon
#: owns the whitespace on both sides of it when it is used.
semicolon: Union[Semicolon, MaybeSentinel] = MaybeSentinel.DEFAULT
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Expr":
return Expr(
value=visit_required(self, "value", self.value, visitor),
semicolon=visit_sentinel(self, "semicolon", self.semicolon, visitor),
)
def _codegen_impl(
self, state: CodegenState, default_semicolon: bool = False
) -> None:
with state.record_syntactic_position(self):
self.value._codegen(state)
semicolon = self.semicolon
if isinstance(semicolon, MaybeSentinel):
if default_semicolon:
state.add_token("; ")
elif isinstance(semicolon, Semicolon):
semicolon._codegen(state)
class _BaseSimpleStatement(CSTNode, ABC):
"""
A simple statement is a series of small statements joined together by semicolons.
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
Whitespace between each small statement is owned by the small statements themselves.
It can be found on the required semicolon that will be attached to each non-terminal
small statement.
"""
__slots__ = ()
#: Sequence of small statements. All but the last statement are required to have
#: a semicolon.
body: Sequence[BaseSmallStatement]
#: Any trailing comment and the final ``NEWLINE``, which is part of small statement's
#: grammar.
trailing_whitespace: TrailingWhitespace
def _validate(self) -> None:
body = self.body
for small_stmt in body[:-1]:
if small_stmt.semicolon is None:
raise CSTValidationError(
"All but the last SmallStatement in a SimpleStatementLine or "
+ "SimpleStatementSuite must have a trailing semicolon. Otherwise, "
+ "there's no way to syntatically disambiguate each SmallStatement "
+ "on the same line."
)
def _codegen_impl(self, state: CodegenState) -> None:
body = self.body
if body:
laststmt = len(body) - 1
with state.record_syntactic_position(self, end_node=body[laststmt]):
for idx, stmt in enumerate(body):
stmt._codegen(state, default_semicolon=(idx != laststmt))
else:
# Empty simple statement blocks are not syntactically valid in Python
# unless they contain a 'pass' statement, so add one here.
with state.record_syntactic_position(self):
state.add_token("pass")
self.trailing_whitespace._codegen(state)
@add_slots
@dataclass(frozen=True)
class SimpleStatementLine(_BaseSimpleStatement, BaseStatement):
"""
A simple statement that's part of an IndentedBlock or Module. A simple statement is
a series of small statements joined together by semicolons.
This isn't differentiated from a :class:`SimpleStatementSuite` in the grammar, but
because a :class:`SimpleStatementLine` can own additional whitespace that a
:class:`SimpleStatementSuite` doesn't have, we're differentiating it in the CST.
"""
#: Sequence of small statements. All but the last statement are required to have
#: a semicolon.
body: Sequence[BaseSmallStatement]
#: Sequence of empty lines appearing before this simple statement line.
leading_lines: Sequence[EmptyLine] = ()
#: Any optional trailing comment and the final ``NEWLINE`` at the end of the line.
trailing_whitespace: TrailingWhitespace = TrailingWhitespace.field()
def _visit_and_replace_children(
self, visitor: CSTVisitorT
) -> "SimpleStatementLine":
return SimpleStatementLine(
leading_lines=visit_sequence(
self, "leading_lines", self.leading_lines, visitor
),
body=visit_sequence(self, "body", self.body, visitor),
trailing_whitespace=visit_required(
self, "trailing_whitespace", self.trailing_whitespace, visitor
),
)
def _is_removable(self) -> bool:
# If we have an empty body, we are removable since we don't represent
# anything concrete.
return not self.body
def _codegen_impl(self, state: CodegenState) -> None:
for ll in self.leading_lines:
ll._codegen(state)
state.add_indent_tokens()
_BaseSimpleStatement._codegen_impl(self, state)
@add_slots
@dataclass(frozen=True)
class SimpleStatementSuite(_BaseSimpleStatement, BaseSuite):
"""
A simple statement that's used as a suite. A simple statement is a series of small
statements joined together by semicolons. A suite is the thing that follows the
colon in a compound statement.
.. code-block::
if test:<leading_whitespace><body><trailing_whitespace>
This isn't differentiated from a :class:`SimpleStatementLine` in the grammar, but
because the two classes need to track different whitespace, we're differentiating
it in the CST.
"""
#: Sequence of small statements. All but the last statement are required to have
#: a semicolon.
body: Sequence[BaseSmallStatement]
#: The whitespace between the colon in the parent statement and the body.
leading_whitespace: SimpleWhitespace = SimpleWhitespace.field(" ")
#: Any optional trailing comment and the final ``NEWLINE`` at the end of the line.
trailing_whitespace: TrailingWhitespace = TrailingWhitespace.field()
def _visit_and_replace_children(
self, visitor: CSTVisitorT
) -> "SimpleStatementSuite":
return SimpleStatementSuite(
leading_whitespace=visit_required(
self, "leading_whitespace", self.leading_whitespace, visitor
),
body=visit_sequence(self, "body", self.body, visitor),
trailing_whitespace=visit_required(
self, "trailing_whitespace", self.trailing_whitespace, visitor
),
)
def _codegen_impl(self, state: CodegenState) -> None:
self.leading_whitespace._codegen(state)
_BaseSimpleStatement._codegen_impl(self, state)
@add_slots
@dataclass(frozen=True)
class Else(CSTNode):
"""
An ``else`` clause that appears optionally after an :class:`If`, :class:`While`,
:class:`Try`, or :class:`For` statement.
This node does not match ``elif`` clauses in :class:`If` statements. It also
does not match the required ``else`` clause in an :class:`IfExp` expression
(``a = if b else c``).
"""
#: The body of else clause.
body: BaseSuite
#: Sequence of empty lines appearing before this compound statement line.
leading_lines: Sequence[EmptyLine] = ()
#: The whitespace appearing after the ``else`` keyword but before the colon.
whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("")
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Else":
return Else(
leading_lines=visit_sequence(
self, "leading_lines", self.leading_lines, visitor
),
whitespace_before_colon=visit_required(
self, "whitespace_before_colon", self.whitespace_before_colon, visitor
),
body=visit_required(self, "body", self.body, visitor),
)
def _codegen_impl(self, state: CodegenState) -> None:
for ll in self.leading_lines:
ll._codegen(state)
state.add_indent_tokens()
with state.record_syntactic_position(self, end_node=self.body):
state.add_token("else")
self.whitespace_before_colon._codegen(state)
state.add_token(":")
self.body._codegen(state)
class BaseCompoundStatement(BaseStatement, ABC):
"""
Encapsulates a compound statement, like ``if True: pass`` or ``while True: pass``.
This exists to simplify type definitions and isinstance checks.
Compound statements contain (groups of) other statements; they affect or control
the execution of those other statements in some way. In general, compound
statements span multiple lines, although in simple incarnations a whole compound
statement may be contained in one line.
-- https://docs.python.org/3/reference/compound_stmts.html
"""
__slots__ = ()
#: The body of this compound statement.
body: BaseSuite
#: Any empty lines or comments appearing before this statement.
leading_lines: Sequence[EmptyLine]
@add_slots
@dataclass(frozen=True)
class If(BaseCompoundStatement):
"""
An ``if`` statement. ``test`` holds a single test expression.
``elif`` clauses don’t have a special representation in the AST, but rather appear as
extra :class:`If` nodes within the ``orelse`` section of the previous one.
"""
#: The expression that, when evaluated, should give us a truthy/falsey value.
test: BaseExpression # TODO: should be a test_nocond
#: The body of this compound statement.
body: BaseSuite
#: An optional ``elif`` or ``else`` clause. :class:`If` signifies an ``elif`` block.
#: :class:`Else` signifies an ``else`` block. ``None`` signifies no ``else`` or
#:``elif`` block.
orelse: Union["If", Else, None] = None
#: Sequence of empty lines appearing before this compound statement line.
leading_lines: Sequence[EmptyLine] = ()
#: The whitespace appearing after the ``if`` keyword but before the test expression.
whitespace_before_test: SimpleWhitespace = SimpleWhitespace.field(" ")
#: The whitespace appearing after the test expression but before the colon.
whitespace_after_test: SimpleWhitespace = SimpleWhitespace.field("")
def _validate(self) -> None:
if (
self.whitespace_before_test.empty
and not self.test._safe_to_use_with_word_operator(ExpressionPosition.RIGHT)
):
raise CSTValidationError("Must have at least one space after 'if' keyword.")
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "If":
return If(
leading_lines=visit_sequence(
self, "leading_lines", self.leading_lines, visitor
),
whitespace_before_test=visit_required(
self, "whitespace_before_test", self.whitespace_before_test, visitor
),
test=visit_required(self, "test", self.test, visitor),
whitespace_after_test=visit_required(
self, "whitespace_after_test", self.whitespace_after_test, visitor
),
body=visit_required(self, "body", self.body, visitor),
orelse=visit_optional(self, "orelse", self.orelse, visitor),
)
def _codegen_impl(self, state: CodegenState, is_elif: bool = False) -> None:
for ll in self.leading_lines:
ll._codegen(state)
state.add_indent_tokens()
end_node = self.body if self.orelse is None else self.orelse
with state.record_syntactic_position(self, end_node=end_node):
state.add_token("elif" if is_elif else "if")
self.whitespace_before_test._codegen(state)
self.test._codegen(state)
self.whitespace_after_test._codegen(state)
state.add_token(":")
self.body._codegen(state)
orelse = self.orelse
if orelse is not None:
if isinstance(orelse, If): # special-case elif
orelse._codegen(state, is_elif=True)
else: # is an Else clause
orelse._codegen(state)
@add_slots
@dataclass(frozen=True)
class IndentedBlock(BaseSuite):
"""
Represents a block of statements beginning with an ``INDENT`` token and ending in a
``DEDENT`` token. Used as the body of compound statements, such as an if statement's
body.
A common alternative to an :class:`IndentedBlock` is a :class:`SimpleStatementSuite`,
which can also be used as a :class:`BaseSuite`, meaning that it can be used as the
body of many compound statements.
An :class:`IndentedBlock` always occurs after a colon in a
:class:`BaseCompoundStatement`, so it owns the trailing whitespace for the compound
statement's clause.
.. code-block::
if test: # IndentedBlock's header
body
"""
#: Sequence of statements belonging to this indented block.
body: Sequence[BaseStatement]
#: Any optional trailing comment and the final ``NEWLINE`` at the end of the line.
header: TrailingWhitespace = TrailingWhitespace.field()
#: A string represents a specific indentation. A ``None`` value uses the modules's
#: default indentation. This is included because indentation is allowed to be
#: inconsistent across a file, just not ambiguously.
indent: Optional[str] = None
#: Any trailing comments or lines after the dedent that are owned by this indented
#: block. Statements own preceeding and same-line trailing comments, but not
#: trailing lines, so it falls on :class:`IndentedBlock` to own it. In the case
#: that a statement follows an :class:`IndentedBlock`, that statement will own the
#: comments and lines that are at the same indent as the statement, and this
#: :class:`IndentedBlock` will own the comments and lines that are indented further.
footer: Sequence[EmptyLine] = ()
def _validate(self) -> None:
indent = self.indent
if indent is not None:
if len(indent) == 0:
raise CSTValidationError(
"An indented block must have a non-zero width indent."
)
if _INDENT_WHITESPACE_RE.fullmatch(indent) is None:
raise CSTValidationError(
"An indent must be composed of only whitespace characters."
)
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "IndentedBlock":
return IndentedBlock(
header=visit_required(self, "header", self.header, visitor),
indent=self.indent,
body=visit_body_sequence(self, "body", self.body, visitor),
footer=visit_sequence(self, "footer", self.footer, visitor),
)
def _codegen_impl(self, state: CodegenState) -> None:
self.header._codegen(state)
indent = self.indent
state.increase_indent(state.default_indent if indent is None else indent)
if self.body:
first_statement = self.body[0]
if (
isinstance(first_statement, (FunctionDef, ClassDef))
and first_statement.decorators
):
# If the first statement is a function or class definition, we need to
# use the position of the first decorator instead of the function/class definition.
with state.record_syntactic_position(
self, start_node=first_statement.decorators[0], end_node=self.body[-1]
):
for stmt in self.body:
# IndentedBlock is responsible for adjusting the current indentation level,
# but its children are responsible for actually adding that indentation to
# the token list.
stmt._codegen(state)
else:
with state.record_syntactic_position(
self, start_node=first_statement, end_node=self.body[-1]
):
for stmt in self.body:
# IndentedBlock is responsible for adjusting the current indentation level,
# but its children are responsible for actually adding that indentation to
# the token list.
stmt._codegen(state)
else:
# Empty indented blocks are not syntactically valid in Python unless
# they contain a 'pass' statement, so add one here.
state.add_indent_tokens()
with state.record_syntactic_position(self):
state.add_token("pass")
state.add_token(state.default_newline)
for f in self.footer:
f._codegen(state)
state.decrease_indent()
@add_slots
@dataclass(frozen=True)
class AsName(CSTNode):
"""
An ``as name`` clause inside an :class:`ExceptHandler`, :class:`ImportAlias` or
:class:`WithItem` node.
"""
#: Identifier that the parent node will be aliased to.
name: Union[Name, Tuple, List]
#: Whitespace between the parent node and the ``as`` keyword.
whitespace_before_as: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ")
#: Whitespace between the ``as`` keyword and the name.
whitespace_after_as: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ")
def _validate(self) -> None:
if (
self.whitespace_after_as.empty
and not self.name._safe_to_use_with_word_operator(ExpressionPosition.RIGHT)
):
raise CSTValidationError(
"There must be at least one space between 'as' and name."
)
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "AsName":
return AsName(
whitespace_before_as=visit_required(
self, "whitespace_before_as", self.whitespace_before_as, visitor
),
name=visit_required(self, "name", self.name, visitor),
whitespace_after_as=visit_required(
self, "whitespace_after_as", self.whitespace_after_as, visitor
),
)
def _codegen_impl(self, state: CodegenState) -> None:
self.whitespace_before_as._codegen(state)
state.add_token("as")
self.whitespace_after_as._codegen(state)
self.name._codegen(state)
@add_slots
@dataclass(frozen=True)
class ExceptHandler(CSTNode):
"""
An ``except`` clause that appears optionally after a :class:`Try` statement.
"""
#: The body of the except.
body: BaseSuite
#: The type of exception this catches. Can be a tuple in some cases,
#: or ``None`` if the code is catching all exceptions.
type: Optional[BaseExpression] = None
#: The optional name that a caught exception is assigned to.
name: Optional[AsName] = None
#: Sequence of empty lines appearing before this compound statement line.
leading_lines: Sequence[EmptyLine] = ()
#: The whitespace between the ``except`` keyword and the type attribute.
whitespace_after_except: SimpleWhitespace = SimpleWhitespace.field(" ")
#: The whitespace after any type or name node (whichever comes last) and
#: the colon.
whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("")
def _validate(self) -> None:
name = self.name
if self.type is None and name is not None:
raise CSTValidationError("Cannot have a name for an empty type.")
if name is not None and not isinstance(name.name, Name):
raise CSTValidationError(
"Must use a Name node for AsName name inside ExceptHandler."
)
type_ = self.type
if type_ is not None and self.whitespace_after_except.empty:
# Space is only required when the first char in `type` could start
# an identifier. In the most common cases, we want to allow
# grouping or tuple parens.
if isinstance(type_, Name) and not type_.lpar:
raise CSTValidationError(
"Must have at least one space after except when ExceptHandler has a type."
)
name = self.name
if (
type_ is not None
and name is not None
and name.whitespace_before_as.empty
and not type_._safe_to_use_with_word_operator(ExpressionPosition.LEFT)
):
raise CSTValidationError(
"Must have at least one space before as keyword in an except handler."
)
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ExceptHandler":
return ExceptHandler(
leading_lines=visit_sequence(
self, "leading_lines", self.leading_lines, visitor
),
whitespace_after_except=visit_required(
self, "whitespace_after_except", self.whitespace_after_except, visitor
),
type=visit_optional(self, "type", self.type, visitor),
name=visit_optional(self, "name", self.name, visitor),
whitespace_before_colon=visit_required(
self, "whitespace_before_colon", self.whitespace_before_colon, visitor
),
body=visit_required(self, "body", self.body, visitor),
)
def _codegen_impl(self, state: CodegenState) -> None:
for ll in self.leading_lines:
ll._codegen(state)
state.add_indent_tokens()
with state.record_syntactic_position(self, end_node=self.body):
state.add_token("except")
self.whitespace_after_except._codegen(state)
typenode = self.type
if typenode is not None:
typenode._codegen(state)
namenode = self.name
if namenode is not None:
namenode._codegen(state)
self.whitespace_before_colon._codegen(state)
state.add_token(":")
self.body._codegen(state)
@add_slots
@dataclass(frozen=True)
class ExceptStarHandler(CSTNode):
"""
An ``except*`` clause that appears after a :class:`TryStar` statement.
"""
#: The body of the except.
body: BaseSuite
#: The type of exception this catches. Can be a tuple in some cases.
type: BaseExpression
#: The optional name that a caught exception is assigned to.
name: Optional[AsName] = None
#: Sequence of empty lines appearing before this compound statement line.
leading_lines: Sequence[EmptyLine] = ()
#: The whitespace between the ``except`` keyword and the star.
whitespace_after_except: SimpleWhitespace = SimpleWhitespace.field("")
#: The whitespace between the star and the type.
whitespace_after_star: SimpleWhitespace = SimpleWhitespace.field(" ")
#: The whitespace after any type or name node (whichever comes last) and
#: the colon.
whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("")
def _validate(self) -> None:
name = self.name
if name is not None and not isinstance(name.name, Name):
raise CSTValidationError(
"Must use a Name node for AsName name inside ExceptHandler."
)
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ExceptStarHandler":
return ExceptStarHandler(
leading_lines=visit_sequence(
self, "leading_lines", self.leading_lines, visitor
),
whitespace_after_except=visit_required(
self, "whitespace_after_except", self.whitespace_after_except, visitor
),
whitespace_after_star=visit_required(
self, "whitespace_after_star", self.whitespace_after_star, visitor
),
type=visit_required(self, "type", self.type, visitor),
name=visit_optional(self, "name", self.name, visitor),
whitespace_before_colon=visit_required(
self, "whitespace_before_colon", self.whitespace_before_colon, visitor
),
body=visit_required(self, "body", self.body, visitor),
)
def _codegen_impl(self, state: CodegenState) -> None:
for ll in self.leading_lines:
ll._codegen(state)
state.add_indent_tokens()
with state.record_syntactic_position(self, end_node=self.body):
state.add_token("except")
self.whitespace_after_except._codegen(state)
state.add_token("*")
self.whitespace_after_star._codegen(state)
typenode = self.type
if typenode is not None:
typenode._codegen(state)
namenode = self.name
if namenode is not None:
namenode._codegen(state)
self.whitespace_before_colon._codegen(state)
state.add_token(":")
self.body._codegen(state)
@add_slots
@dataclass(frozen=True)
class Finally(CSTNode):
"""
A ``finally`` clause that appears optionally after a :class:`Try` statement.
"""
#: The body of the except.
body: BaseSuite
#: Sequence of empty lines appearing before this compound statement line.
leading_lines: Sequence[EmptyLine] = ()
#: The whitespace that appears after the ``finally`` keyword but before
#: the colon.
whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("")
def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Finally":
return Finally(
leading_lines=visit_sequence(
self, "leading_lines", self.leading_lines, visitor
),
whitespace_before_colon=visit_required(
self, "whitespace_before_colon", self.whitespace_before_colon, visitor
),
body=visit_required(self, "body", self.body, visitor),
)
def _codegen_impl(self, state: CodegenState) -> None:
for ll in self.leading_lines:
ll._codegen(state)
state.add_indent_tokens()
with state.record_syntactic_position(self, end_node=self.body):
state.add_token("finally")
self.whitespace_before_colon._codegen(state)
state.add_token(":")
self.body._codegen(state)