python-syntax 0.1.0

Python 3 parser
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
use std::fmt::{self, Display};

use crate::source::Span;

#[derive(Debug, Clone)]
pub enum Program {
    Module(Module),
    Interactive(Interactive),
    Eval(Eval),
}

#[derive(Debug, Clone)]
pub struct Module {
    pub body: Vec<Statement>,
}

#[derive(Debug, Clone)]
pub struct Interactive {
    pub body: Vec<Statement>,
}

#[derive(Debug, Clone)]
pub struct Eval {
    pub body: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct FunctionDef {
    pub span: Span,
    pub name: String,
    pub args: Box<Arguments>,
    pub body: Vec<Statement>,
    pub decorator_list: Vec<Expression>,
    pub returns: Option<Box<Expression>>,
}

pub type AsyncFunctionDef = FunctionDef;

#[derive(Debug, Clone)]
pub struct ClassDef {
    pub span: Span,
    pub name: String,
    pub bases: Vec<Expression>,
    pub keywords: Vec<Keyword>,
    pub body: Vec<Statement>,
    pub decorator_list: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct Return {
    pub span: Span,
    pub value: Option<Box<Expression>>,
}

#[derive(Debug, Clone)]
pub struct Delete {
    pub span: Span,
    pub targets: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct Assign {
    pub span: Span,
    pub targets: Vec<Expression>,
    pub value: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct AugAssign {
    pub span: Span,
    pub target: Box<Expression>,
    pub op: OpKind,
    pub value: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct AnnAssign {
    pub span: Span,
    pub target: Box<Expression>,
    pub annotation: Box<Expression>,
    pub value: Option<Box<Expression>>,
    pub simple: bool,
}

#[derive(Debug, Clone)]
pub struct For {
    pub span: Span,
    pub target: Box<Expression>,
    pub iter: Box<Expression>,
    pub body: Vec<Statement>,
    pub orelse: Vec<Statement>,
}

pub type AsyncFor = For;

#[derive(Debug, Clone)]
pub struct While {
    pub span: Span,
    pub test: Box<Expression>,
    pub body: Vec<Statement>,
    pub orelse: Vec<Statement>,
}

#[derive(Debug, Clone)]
pub struct If {
    pub span: Span,
    pub test: Box<Expression>,
    pub body: Vec<Statement>,
    pub orelse: Vec<Statement>,
}

#[derive(Debug, Clone)]
pub struct With {
    pub span: Span,
    pub items: Vec<WithItem>,
    pub body: Vec<Statement>,
}

pub type AsyncWith = With;

#[derive(Debug, Clone)]
pub struct Raise {
    pub span: Span,
    pub exc: Option<Box<Expression>>,
    pub cause: Option<Box<Expression>>,
}

#[derive(Debug, Clone)]
pub struct Try {
    pub span: Span,
    pub body: Vec<Statement>,
    pub handlers: Vec<ExceptHandler>,
    pub orelse: Vec<Statement>,
    pub finalbody: Vec<Statement>,
}

#[derive(Debug, Clone)]
pub struct Assert {
    pub span: Span,
    pub test: Box<Expression>,
    pub msg: Option<Box<Expression>>,
}

#[derive(Debug, Clone)]
pub struct Import {
    pub span: Span,
    pub names: Vec<Alias>,
}

#[derive(Debug, Clone)]
pub struct ImportFrom {
    pub span: Span,
    pub module: Option<String>,
    pub names: Vec<Alias>,
    pub level: usize,
}

#[derive(Debug, Clone)]
pub struct Global {
    pub span: Span,
    pub names: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct Nonlocal {
    pub span: Span,
    pub names: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct Expr {
    pub span: Span,
    pub value: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct Pass {
    pub span: Span,
}

#[derive(Debug, Clone)]
pub struct Break {
    pub span: Span,
}

#[derive(Debug, Clone)]
pub struct Continue {
    pub span: Span,
}

#[derive(Debug, Clone)]
pub enum Statement {
    FunctionDef(FunctionDef),
    AsyncFunctionDef(AsyncFunctionDef),
    ClassDef(ClassDef),
    Return(Return),
    Delete(Delete),
    Assign(Assign),
    AugAssign(AugAssign),
    AnnAssign(AnnAssign),
    For(For),
    AsyncFor(AsyncFor),
    While(While),
    If(If),
    With(With),
    AsyncWith(AsyncWith),
    Raise(Raise),
    Try(Try),
    Assert(Assert),
    Import(Import),
    ImportFrom(ImportFrom),
    Global(Global),
    Nonlocal(Nonlocal),
    Expr(Expr),
    Pass(Pass),
    Break(Break),
    Continue(Continue),
}

impl Statement {
    pub fn span(&self) -> &Span {
        match self {
            Statement::FunctionDef(x) => &x.span,
            Statement::AsyncFunctionDef(x) => &x.span,
            Statement::ClassDef(x) => &x.span,
            Statement::Return(x) => &x.span,
            Statement::Delete(x) => &x.span,
            Statement::Assign(x) => &x.span,
            Statement::AugAssign(x) => &x.span,
            Statement::AnnAssign(x) => &x.span,
            Statement::For(x) => &x.span,
            Statement::AsyncFor(x) => &x.span,
            Statement::While(x) => &x.span,
            Statement::If(x) => &x.span,
            Statement::With(x) => &x.span,
            Statement::AsyncWith(x) => &x.span,
            Statement::Raise(x) => &x.span,
            Statement::Try(x) => &x.span,
            Statement::Assert(x) => &x.span,
            Statement::Import(x) => &x.span,
            Statement::ImportFrom(x) => &x.span,
            Statement::Global(x) => &x.span,
            Statement::Nonlocal(x) => &x.span,
            Statement::Expr(x) => &x.span,
            Statement::Pass(x) => &x.span,
            Statement::Break(x) => &x.span,
            Statement::Continue(x) => &x.span,
        }
    }
}

#[derive(Debug, Clone)]
pub struct BoolOp {
    pub span: Span,
    pub left: Box<Expression>,
    pub op: BoolOpKind,
    pub right: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct BinOp {
    pub span: Span,
    pub left: Box<Expression>,
    pub op: OpKind,
    pub right: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct UnaryOp {
    pub span: Span,
    pub op: UnaryOpKind,
    pub operand: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct Lambda {
    pub span: Span,
    pub args: Box<Arguments>,
    pub body: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct IfExp {
    pub span: Span,
    pub test: Box<Expression>,
    pub body: Box<Expression>,
    pub orelse: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct Dict {
    pub span: Span,
    pub keys: Vec<Option<Expression>>,
    pub values: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct Set {
    pub span: Span,
    pub elts: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct ListComp {
    pub span: Span,
    pub elt: Box<Expression>,
    pub generators: Vec<Comprehension>,
}

#[derive(Debug, Clone)]
pub struct SetComp {
    pub span: Span,
    pub elt: Box<Expression>,
    pub generators: Vec<Comprehension>,
}

#[derive(Debug, Clone)]
pub struct DictComp {
    pub span: Span,
    pub key: Box<Expression>,
    pub value: Box<Expression>,
    pub generators: Vec<Comprehension>,
}

#[derive(Debug, Clone)]
pub struct GeneratorExp {
    pub span: Span,
    pub elt: Box<Expression>,
    pub generators: Vec<Comprehension>,
}

#[derive(Debug, Clone)]
pub struct Await {
    pub span: Span,
    pub value: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct Yield {
    pub span: Span,
    pub value: Option<Box<Expression>>,
}

#[derive(Debug, Clone)]
pub struct YieldFrom {
    pub span: Span,
    pub value: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct Compare {
    pub span: Span,
    pub left: Box<Expression>,
    pub ops: Vec<ComparisonOpKind>,
    pub comparators: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct Call {
    pub span: Span,
    pub func: Box<Expression>,
    pub args: Vec<Expression>,
    pub keywords: Vec<Keyword>,
}

#[derive(Debug, Clone)]
pub struct Num {
    pub span: Span,
    pub value: NumKind,
}

#[derive(Debug, Clone)]
pub struct Str {
    pub span: Span,
    pub value: String,
}

#[derive(Debug, Clone)]
pub struct FormattedValue {
    pub span: Span,
    pub value: Box<Expression>,
    pub conversion: Option<Conversion>,
    pub format_spec: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct JoinedStr {
    pub span: Span,
    pub values: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct Bytes {
    pub span: Span,
    pub value: Vec<u8>,
}

#[derive(Debug, Clone)]
pub struct NameConstant {
    pub span: Span,
    pub value: Singleton,
}

#[derive(Debug, Clone)]
pub struct Ellipsis {
    pub span: Span,
}

#[derive(Debug, Clone)]
pub struct Attribute {
    pub span: Span,
    pub value: Box<Expression>,
    pub attr: String,
}

#[derive(Debug, Clone)]
pub struct Subscript {
    pub span: Span,
    pub value: Box<Expression>,
    pub slice: Slice,
}

#[derive(Debug, Clone)]
pub struct Starred {
    pub span: Span,
    pub value: Box<Expression>,
}

#[derive(Debug, Clone)]
pub struct Name {
    pub span: Span,
    pub id: String,
}

#[derive(Debug, Clone)]
pub struct List {
    pub span: Span,
    pub elts: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub struct Tuple {
    pub span: Span,
    pub elts: Vec<Expression>,
}

#[derive(Debug, Clone)]
pub enum Expression {
    BoolOp(BoolOp),
    BinOp(BinOp),
    UnaryOp(UnaryOp),
    Lambda(Lambda),
    IfExp(IfExp),
    Dict(Dict),
    Set(Set),
    ListComp(ListComp),
    SetComp(SetComp),
    DictComp(DictComp),
    GeneratorExp(GeneratorExp),
    Await(Await),
    Yield(Yield),
    YieldFrom(YieldFrom),
    Compare(Compare),
    Call(Call),
    Num(Num),
    Str(Str),
    FormattedValue(FormattedValue),
    JoinedStr(JoinedStr),
    Bytes(Bytes),
    NameConstant(NameConstant),
    Ellipsis(Ellipsis),
    Attribute(Attribute),
    Subscript(Subscript),
    Starred(Starred),
    Name(Name),
    List(List),
    Tuple(Tuple),
}

impl Expression {
    pub fn span(&self) -> &Span {
        match self {
            Expression::BoolOp(x) => &x.span,
            Expression::BinOp(x) => &x.span,
            Expression::UnaryOp(x) => &x.span,
            Expression::Lambda(x) => &x.span,
            Expression::IfExp(x) => &x.span,
            Expression::Dict(x) => &x.span,
            Expression::Set(x) => &x.span,
            Expression::ListComp(x) => &x.span,
            Expression::SetComp(x) => &x.span,
            Expression::DictComp(x) => &x.span,
            Expression::GeneratorExp(x) => &x.span,
            Expression::Await(x) => &x.span,
            Expression::Yield(x) => &x.span,
            Expression::YieldFrom(x) => &x.span,
            Expression::Compare(x) => &x.span,
            Expression::Call(x) => &x.span,
            Expression::Num(x) => &x.span,
            Expression::Str(x) => &x.span,
            Expression::FormattedValue(x) => &x.span,
            Expression::JoinedStr(x) => &x.span,
            Expression::Bytes(x) => &x.span,
            Expression::NameConstant(x) => &x.span,
            Expression::Ellipsis(x) => &x.span,
            Expression::Attribute(x) => &x.span,
            Expression::Subscript(x) => &x.span,
            Expression::Starred(x) => &x.span,
            Expression::Name(x) => &x.span,
            Expression::List(x) => &x.span,
            Expression::Tuple(x) => &x.span,
        }
    }
}

#[derive(Debug, Clone)]
pub enum Slice {
    Slice {
        lower: Option<Box<Expression>>,
        upper: Option<Box<Expression>>,
        step: Option<Box<Expression>>,
    },
    ExtSlice {
        dims: Vec<Slice>,
    },
    Index {
        value: Box<Expression>,
    },
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum BoolOpKind {
    And,
    Or,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum OpKind {
    Addition,
    Subtraction,
    Multiplication,
    MatrixMultiplication,
    Division,
    Modulo,
    Power,
    LeftShift,
    RightShift,
    BitOr,
    BitXor,
    BitAnd,
    FloorDivision,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum UnaryOpKind {
    Invert,
    Not,
    Plus,
    Minus,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ComparisonOpKind {
    Equal,
    NotEqual,
    Less,
    LessEqual,
    Greater,
    GreaterEqual,
    Is,
    IsNot,
    In,
    NotIn,
}

#[derive(Debug, Clone)]
pub struct Comprehension {
    pub target: Box<Expression>,
    pub iter: Box<Expression>,
    pub ifs: Vec<Expression>,
    pub is_async: bool,
}

#[derive(Debug, Clone)]
pub struct ExceptHandler {
    pub span: Span,
    pub typ: Option<Box<Expression>>,
    pub name: Option<String>,
    pub body: Vec<Statement>,
}

#[derive(Debug, Clone, Default)]
pub struct Arguments {
    pub args: Vec<Arg>,
    pub vararg: Option<Arg>,
    pub kwonlyargs: Vec<Arg>,
    pub kwarg: Option<Arg>,
}

#[derive(Debug, Clone)]
pub struct Arg {
    pub span: Span,
    pub arg: String,
    pub annotation: Option<Box<Expression>>,
    pub kind: ArgKind,
}

#[derive(Debug, Clone)]
pub enum ArgKind {
    Required,
    Optional(Box<Expression>),
    Vararg,
    Kwarg,
}

#[derive(Debug, Clone)]
pub struct Keyword {
    pub arg: Option<String>,
    pub value: Box<Expression>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Alias {
    pub identifier: String,
    pub asname: Option<String>,
}

#[derive(Debug, Clone)]
pub struct WithItem {
    pub context_expr: Box<Expression>,
    pub optional_vars: Option<Box<Expression>>,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Singleton {
    None,
    True,
    False,
}

#[derive(Debug, Clone, PartialEq)]
pub enum NumKind {
    Integer(num_bigint::BigUint),
    Float(f64),
    Complex(f64),
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Conversion {
    Str,
    Repr,
    Ascii,
}

fn write_joined<I, T, S>(f: &mut fmt::Formatter<'_>, i: I, sep: S) -> fmt::Result
where
    I: IntoIterator<Item = T>,
    T: Display,
    S: Display,
{
    let mut iter = i.into_iter();
    if let Some(e) = iter.next() {
        write!(f, "{}", e)?;
    }
    for e in iter {
        write!(f, "{}{}", sep, e)?;
    }
    Ok(())
}

fn write_escaped(f: &mut fmt::Formatter<'_>, b: u8) -> fmt::Result {
    match b {
        b' ' => f.write_str(" "),
        b'"' => f.write_str("\\\""),
        b'\\' => f.write_str("\\"),
        b'\n' => f.write_str("\\n"),
        b'\r' => f.write_str("\\r"),
        b'\t' => f.write_str("\\t"),
        b'\x07' => f.write_str("\\a"),
        b'\x08' => f.write_str("\\b"),
        b'\x0c' => f.write_str("\\f"),
        b'\x0b' => f.write_str("\\v"),
        b if b.is_ascii_graphic() => f.write_str(&char::from(b).to_string()),
        b => write!(f, "\\x{:x}", b),
    }
}

fn write_indent(f: &mut fmt::Formatter<'_>, level: usize) -> fmt::Result {
    for _ in 0..level * 4 {
        f.write_str(" ")?;
    }
    Ok(())
}

impl Display for Program {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Program::Module(p) => write!(f, "{}", p),
            Program::Interactive(p) => write!(f, "{}", p),
            Program::Eval(p) => write!(f, "{}", p),
        }
    }
}

impl Display for Module {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_joined(f, &self.body, "\n")
    }
}

impl Display for Interactive {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_joined(f, &self.body, "\n")
    }
}

impl Display for Eval {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.body)
    }
}

fn write_body(f: &mut fmt::Formatter<'_>, indent: usize, body: &[Statement]) -> fmt::Result {
    for e in body {
        e.fmt_indented(f, indent)?;
        f.write_str("\n")?;
    }
    Ok(())
}

fn write_funcdef(
    f: &mut fmt::Formatter<'_>,
    indent: usize,
    node: &FunctionDef,
    is_async: bool,
) -> fmt::Result {
    for dec in &node.decorator_list {
        writeln!(f, "@{}", dec)?;
        write_indent(f, indent)?;
    }
    if is_async {
        f.write_str("async ")?;
    }
    write!(f, "def {}({})", node.name, node.args)?;
    if let Some(returns) = &node.returns {
        write!(f, " -> {}", returns)?;
    }
    f.write_str(":\n")?;
    write_body(f, indent + 1, &node.body)?;
    Ok(())
}

fn write_for(f: &mut fmt::Formatter<'_>, indent: usize, node: &For, is_async: bool) -> fmt::Result {
    if is_async {
        f.write_str("async ")?;
    }
    writeln!(f, "for {} in {}:", node.target, node.iter)?;
    write_body(f, indent + 1, &node.body)?;
    if !node.orelse.is_empty() {
        write_indent(f, indent)?;
        f.write_str("else:\n")?;
        write_body(f, indent + 1, &node.orelse)?;
    }
    Ok(())
}

fn write_if(f: &mut fmt::Formatter<'_>, indent: usize, node: &If) -> fmt::Result {
    writeln!(f, "if {}:", node.test)?;
    write_body(f, indent + 1, &node.body)?;
    match node.orelse.as_slice() {
        [Statement::If(s)] => {
            write_indent(f, indent)?;
            f.write_str("el")?;
            write_if(f, indent, s)?;
        }
        [] => (),
        s => {
            write_indent(f, indent)?;
            f.write_str("else:\n")?;
            write_body(f, indent + 1, s)?;
        }
    };
    Ok(())
}

fn write_with(
    f: &mut fmt::Formatter<'_>,
    indent: usize,
    node: &With,
    is_async: bool,
) -> fmt::Result {
    if is_async {
        f.write_str("async ")?;
    }
    f.write_str("with ")?;
    write_joined(f, &node.items, ", ")?;
    f.write_str(":\n")?;
    write_body(f, indent + 1, &node.body)
}

impl Statement {
    fn fmt_indented(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
        write_indent(f, indent)?;
        match self {
            Statement::FunctionDef(node) => write_funcdef(f, indent, node, false),
            Statement::AsyncFunctionDef(node) => write_funcdef(f, indent, node, true),
            Statement::ClassDef(node) => {
                for dec in &node.decorator_list {
                    writeln!(f, "@{}", dec)?;
                    write_indent(f, indent)?;
                }
                write!(f, "class {}", node.name)?;
                if !node.bases.is_empty() || !node.keywords.is_empty() {
                    f.write_str("(")?;
                    write_joined(f, &node.bases, ", ")?;
                    if !node.bases.is_empty() && !node.keywords.is_empty() {
                        f.write_str(", ")?;
                    }
                    write_joined(f, &node.keywords, ", ")?;
                    f.write_str(")")?;
                }
                f.write_str(":\n")?;
                write_body(f, indent + 1, &node.body)
            }
            Statement::Return(Return { value, .. }) => match value {
                Some(v) => write!(f, "return {}", v),
                _ => write!(f, "return"),
            },
            Statement::Delete(Delete { targets, .. }) => {
                write!(f, "del ")?;
                write_joined(f, targets, ", ")
            }
            Statement::Assign(Assign { targets, value, .. }) => {
                write_joined(f, targets, " = ")?;
                write!(f, " = {}", value)
            }
            Statement::AugAssign(AugAssign {
                target, op, value, ..
            }) => write!(f, "{} {}= {}", target, op, value),
            Statement::AnnAssign(node) => {
                write!(f, "{}: {}", node.target, node.annotation)?;
                if let Some(value) = &node.value {
                    write!(f, " = {}", value)?;
                }
                Ok(())
            }
            Statement::For(node) => write_for(f, indent, node, false),
            Statement::AsyncFor(node) => write_for(f, indent, node, true),
            Statement::While(node) => {
                writeln!(f, "while {}:", node.test)?;
                write_body(f, indent + 1, &node.body)?;
                if !node.orelse.is_empty() {
                    write_indent(f, indent)?;
                    f.write_str("else:\n")?;
                    write_body(f, indent + 1, &node.orelse)?;
                }
                Ok(())
            }
            Statement::If(node) => write_if(f, indent, node),
            Statement::With(node) => write_with(f, indent, node, false),
            Statement::AsyncWith(node) => write_with(f, indent, node, true),
            Statement::Raise(Raise { exc, cause, .. }) => {
                write!(f, "raise")?;
                if let Some(exc) = exc {
                    write!(f, " {}", exc)?;
                }
                if let Some(cause) = cause {
                    write!(f, " from {}", cause)?;
                }
                Ok(())
            }
            Statement::Try(node) => {
                f.write_str("try:\n")?;
                write_body(f, indent + 1, &node.body)?;
                for hdl in &node.handlers {
                    hdl.fmt_indented(f, indent)?;
                }
                if !node.orelse.is_empty() {
                    write_indent(f, indent)?;
                    f.write_str("else:\n")?;
                    write_body(f, indent + 1, &node.orelse)?;
                }
                if !node.finalbody.is_empty() {
                    write_indent(f, indent)?;
                    f.write_str("finally:\n")?;
                    write_body(f, indent + 1, &node.finalbody)?;
                }
                Ok(())
            }
            Statement::Assert(Assert { test, msg, .. }) => {
                write!(f, "assert {}", test)?;
                if let Some(msg) = msg {
                    write!(f, ", {}", msg)?;
                }
                Ok(())
            }
            Statement::Import(Import { names, .. }) => {
                f.write_str("import ")?;
                write_joined(f, names, ", ")
            }
            Statement::ImportFrom(node) => {
                f.write_str("from ")?;
                for _ in 0..node.level {
                    f.write_str(".")?;
                }
                if let Some(module) = &node.module {
                    write!(f, "{}", module)?;
                }
                f.write_str(" import ")?;
                write_joined(f, &node.names, ", ")
            }
            Statement::Global(Global { names, .. }) => {
                f.write_str("global ")?;
                write_joined(f, names, ", ")
            }
            Statement::Nonlocal(Nonlocal { names, .. }) => {
                f.write_str("nonlocal ")?;
                write_joined(f, names, ", ")
            }
            Statement::Expr(Expr { value, .. }) => write!(f, "{}", value),
            Statement::Pass(_) => f.write_str("pass"),
            Statement::Break(_) => f.write_str("break"),
            Statement::Continue(_) => f.write_str("continue"),
        }
    }
}

impl Display for Statement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_indented(f, 0)
    }
}

impl Display for Expression {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Expression::BoolOp(node) => write!(f, "{} {} {}", node.left, node.op, node.right),
            Expression::BinOp(node) => write!(f, "{} {} {}", node.left, node.op, node.right),
            Expression::UnaryOp(UnaryOp { op, operand, .. }) => write!(f, "{} {}", op, operand),
            Expression::Lambda(Lambda { args, body, .. }) => write!(f, "lambda {}: {}", args, body),
            Expression::IfExp(node) => {
                write!(f, "{} if {} else {}", node.body, node.test, node.orelse)
            }
            Expression::Dict(Dict { keys, values, .. }) => {
                fn write_kv(
                    f: &mut fmt::Formatter<'_>,
                    key: &Option<Expression>,
                    value: &Expression,
                ) -> fmt::Result {
                    match key {
                        Some(k) => write!(f, "{}: ", k)?,
                        _ => write!(f, "**")?,
                    };
                    write!(f, "{}", value)
                }
                f.write_str("{")?;
                let mut iter = keys.iter().zip(values);
                if let Some((k, v)) = iter.next() {
                    write_kv(f, k, v)?;
                }
                for (k, v) in iter {
                    write!(f, ", ")?;
                    write_kv(f, k, v)?;
                }
                f.write_str("}")
            }
            Expression::Set(Set { elts, .. }) => {
                f.write_str("{")?;
                write_joined(f, elts, ", ")?;
                f.write_str("}")
            }
            Expression::ListComp(node) => {
                write!(f, "[{} ", node.elt)?;
                write_joined(f, &node.generators, " ")?;
                f.write_str("]")
            }
            Expression::SetComp(node) => {
                write!(f, "{{{} ", node.elt)?;
                write_joined(f, &node.generators, " ")?;
                f.write_str("}")
            }
            Expression::DictComp(node) => {
                write!(f, "{{{}: {} ", node.key, node.value)?;
                write_joined(f, &node.generators, " ")?;
                f.write_str("}")
            }
            Expression::GeneratorExp(node) => {
                write!(f, "({} ", node.elt)?;
                write_joined(f, &node.generators, " ")?;
                f.write_str(")")
            }
            Expression::Await(Await { value, .. }) => write!(f, "await {}", value),
            Expression::Yield(Yield { value, .. }) => match value {
                Some(value) => write!(f, "yield {}", value),
                _ => write!(f, "yield"),
            },
            Expression::YieldFrom(YieldFrom { value, .. }) => write!(f, "yield from {}", value),
            Expression::Compare(node) => {
                write!(f, "{}", node.left)?;
                for (op, e) in node.ops.iter().zip(&node.comparators) {
                    write!(f, " {} {}", op, e)?
                }
                Ok(())
            }
            Expression::Call(node) => {
                write!(f, "{}(", node.func)?;
                write_joined(f, &node.args, ", ")?;
                if !node.args.is_empty() && !node.keywords.is_empty() {
                    f.write_str(", ")?;
                }
                write_joined(f, &node.keywords, ", ")?;
                f.write_str(")")
            }
            Expression::Num(Num { value, .. }) => write!(f, "{}", value),
            Expression::Str(Str { value, .. }) => {
                f.write_str("\"")?;
                for b in value.bytes() {
                    write_escaped(f, b)?;
                }
                f.write_str("\"")
            }
            Expression::FormattedValue(FormattedValue { .. }) => unimplemented!(),
            Expression::JoinedStr(JoinedStr { .. }) => unimplemented!(),
            Expression::Bytes(Bytes { value, .. }) => {
                f.write_str("b\"")?;
                for b in value {
                    write_escaped(f, *b)?;
                }
                f.write_str("\"")
            }
            Expression::NameConstant(NameConstant { value, .. }) => write!(f, "{}", value),
            Expression::Ellipsis(Ellipsis { .. }) => write!(f, "..."),
            Expression::Attribute(Attribute { value, attr, .. }) => write!(f, "{}.{}", value, attr),
            Expression::Subscript(Subscript { value, slice, .. }) => {
                write!(f, "{}[{}]", value, slice)
            }
            Expression::Starred(Starred { value, .. }) => write!(f, "*{}", value),
            Expression::Name(Name { id, .. }) => write!(f, "{}", id),
            Expression::List(List { elts, .. }) => {
                f.write_str("[")?;
                write_joined(f, elts, ", ")?;
                f.write_str("]")
            }
            Expression::Tuple(Tuple { elts, .. }) => {
                f.write_str("(")?;
                write_joined(f, elts, ", ")?;
                f.write_str(")")
            }
        }
    }
}

impl Display for Slice {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Slice::Slice { lower, upper, step } => {
                if let Some(lower) = lower {
                    write!(f, "{}", lower)?;
                }
                f.write_str(":")?;
                if let Some(upper) = upper {
                    write!(f, "{}", upper)?;
                }
                f.write_str(":")?;
                if let Some(step) = step {
                    write!(f, "{}", step)?;
                }
                Ok(())
            }
            Slice::ExtSlice { dims } => write_joined(f, dims, ","),
            Slice::Index { value } => write!(f, "{}", value),
        }
    }
}

impl Display for BoolOpKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            BoolOpKind::And => "and",
            BoolOpKind::Or => "or",
        };
        f.write_str(s)
    }
}

impl Display for OpKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            OpKind::Addition => "+",
            OpKind::Subtraction => "-",
            OpKind::Multiplication => "*",
            OpKind::MatrixMultiplication => "@",
            OpKind::Division => "/",
            OpKind::Modulo => "%",
            OpKind::Power => "**",
            OpKind::LeftShift => "<<",
            OpKind::RightShift => ">>",
            OpKind::BitOr => "|",
            OpKind::BitXor => "^",
            OpKind::BitAnd => "&",
            OpKind::FloorDivision => "//",
        };
        f.write_str(s)
    }
}

impl Display for UnaryOpKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            UnaryOpKind::Invert => "~",
            UnaryOpKind::Not => "not",
            UnaryOpKind::Plus => "+",
            UnaryOpKind::Minus => "-",
        };
        f.write_str(s)
    }
}

impl Display for ComparisonOpKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            ComparisonOpKind::Equal => "==",
            ComparisonOpKind::NotEqual => "!=",
            ComparisonOpKind::Less => "<",
            ComparisonOpKind::LessEqual => "<=",
            ComparisonOpKind::Greater => ">",
            ComparisonOpKind::GreaterEqual => ">=",
            ComparisonOpKind::Is => "is",
            ComparisonOpKind::IsNot => "is not",
            ComparisonOpKind::In => "in",
            ComparisonOpKind::NotIn => "not in",
        };
        f.write_str(s)
    }
}

impl Display for Comprehension {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_async {
            f.write_str("async ")?;
        }
        write!(f, "for {} in {}", self.target, self.iter)?;
        for e in &self.ifs {
            write!(f, " if {}", e)?;
        }
        Ok(())
    }
}

impl ExceptHandler {
    fn fmt_indented(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
        write_indent(f, indent)?;
        f.write_str("except")?;
        if let Some(typ) = &self.typ {
            write!(f, " {}", typ)?;
        }
        if let Some(name) = &self.name {
            write!(f, " as {}", name)?;
        }
        f.write_str(":\n")?;
        write_body(f, indent + 1, &self.body)
    }
}

impl Display for Arguments {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_joined(
            f,
            self.args
                .iter()
                .chain(&self.vararg)
                .chain(&self.kwonlyargs)
                .chain(&self.kwarg),
            ", ",
        )
    }
}

impl Display for Arg {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            ArgKind::Vararg => f.write_str("*")?,
            ArgKind::Kwarg => f.write_str("**")?,
            _ => (),
        }
        f.write_str(&self.arg)?;
        if let Some(a) = &self.annotation {
            write!(f, ": {}", &a)?;
        }
        if let ArgKind::Optional(default) = &self.kind {
            write!(f, " = {}", &default)?;
        }
        Ok(())
    }
}

impl Display for Keyword {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.arg {
            Some(arg) => write!(f, "{}={}", arg, self.value),
            _ => write!(f, "**{}", self.value),
        }
    }
}

impl Display for Alias {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.identifier)?;
        if let Some(asname) = &self.asname {
            write!(f, " as {}", asname)?;
        }
        Ok(())
    }
}

impl Display for WithItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.context_expr)?;
        if let Some(vars) = &self.optional_vars {
            write!(f, " as {}", vars)?;
        }
        Ok(())
    }
}

impl Display for NumKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NumKind::Integer(n) => write!(f, "{}", n),
            NumKind::Float(n) | NumKind::Complex(n) => write!(f, "{}", n),
        }
    }
}

impl Display for Singleton {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Singleton::None => "None",
            Singleton::True => "True",
            Singleton::False => "False",
        };
        f.write_str(s)
    }
}