1use std::fmt::{self, Display};
2
3use crate::source::Span;
4
5#[derive(Debug, Clone)]
6pub enum Program {
7 Module(Module),
8 Interactive(Interactive),
9 Eval(Eval),
10}
11
12#[derive(Debug, Clone)]
13pub struct Module {
14 pub body: Vec<Statement>,
15}
16
17#[derive(Debug, Clone)]
18pub struct Interactive {
19 pub body: Vec<Statement>,
20}
21
22#[derive(Debug, Clone)]
23pub struct Eval {
24 pub body: Box<Expression>,
25}
26
27#[derive(Debug, Clone)]
28pub struct FunctionDef {
29 pub span: Span,
30 pub name: String,
31 pub args: Box<Arguments>,
32 pub body: Vec<Statement>,
33 pub decorator_list: Vec<Expression>,
34 pub returns: Option<Box<Expression>>,
35}
36
37pub type AsyncFunctionDef = FunctionDef;
38
39#[derive(Debug, Clone)]
40pub struct ClassDef {
41 pub span: Span,
42 pub name: String,
43 pub bases: Vec<Expression>,
44 pub keywords: Vec<Keyword>,
45 pub body: Vec<Statement>,
46 pub decorator_list: Vec<Expression>,
47}
48
49#[derive(Debug, Clone)]
50pub struct Return {
51 pub span: Span,
52 pub value: Option<Box<Expression>>,
53}
54
55#[derive(Debug, Clone)]
56pub struct Delete {
57 pub span: Span,
58 pub targets: Vec<Expression>,
59}
60
61#[derive(Debug, Clone)]
62pub struct Assign {
63 pub span: Span,
64 pub targets: Vec<Expression>,
65 pub value: Box<Expression>,
66}
67
68#[derive(Debug, Clone)]
69pub struct AugAssign {
70 pub span: Span,
71 pub target: Box<Expression>,
72 pub op: OpKind,
73 pub value: Box<Expression>,
74}
75
76#[derive(Debug, Clone)]
77pub struct AnnAssign {
78 pub span: Span,
79 pub target: Box<Expression>,
80 pub annotation: Box<Expression>,
81 pub value: Option<Box<Expression>>,
82 pub simple: bool,
83}
84
85#[derive(Debug, Clone)]
86pub struct For {
87 pub span: Span,
88 pub target: Box<Expression>,
89 pub iter: Box<Expression>,
90 pub body: Vec<Statement>,
91 pub orelse: Vec<Statement>,
92}
93
94pub type AsyncFor = For;
95
96#[derive(Debug, Clone)]
97pub struct While {
98 pub span: Span,
99 pub test: Box<Expression>,
100 pub body: Vec<Statement>,
101 pub orelse: Vec<Statement>,
102}
103
104#[derive(Debug, Clone)]
105pub struct If {
106 pub span: Span,
107 pub test: Box<Expression>,
108 pub body: Vec<Statement>,
109 pub orelse: Vec<Statement>,
110}
111
112#[derive(Debug, Clone)]
113pub struct With {
114 pub span: Span,
115 pub items: Vec<WithItem>,
116 pub body: Vec<Statement>,
117}
118
119pub type AsyncWith = With;
120
121#[derive(Debug, Clone)]
122pub struct Raise {
123 pub span: Span,
124 pub exc: Option<Box<Expression>>,
125 pub cause: Option<Box<Expression>>,
126}
127
128#[derive(Debug, Clone)]
129pub struct Try {
130 pub span: Span,
131 pub body: Vec<Statement>,
132 pub handlers: Vec<ExceptHandler>,
133 pub orelse: Vec<Statement>,
134 pub finalbody: Vec<Statement>,
135}
136
137#[derive(Debug, Clone)]
138pub struct Assert {
139 pub span: Span,
140 pub test: Box<Expression>,
141 pub msg: Option<Box<Expression>>,
142}
143
144#[derive(Debug, Clone)]
145pub struct Import {
146 pub span: Span,
147 pub names: Vec<Alias>,
148}
149
150#[derive(Debug, Clone)]
151pub struct ImportFrom {
152 pub span: Span,
153 pub module: Option<String>,
154 pub names: Vec<Alias>,
155 pub level: usize,
156}
157
158#[derive(Debug, Clone)]
159pub struct Global {
160 pub span: Span,
161 pub names: Vec<String>,
162}
163
164#[derive(Debug, Clone)]
165pub struct Nonlocal {
166 pub span: Span,
167 pub names: Vec<String>,
168}
169
170#[derive(Debug, Clone)]
171pub struct Expr {
172 pub span: Span,
173 pub value: Box<Expression>,
174}
175
176#[derive(Debug, Clone)]
177pub struct Pass {
178 pub span: Span,
179}
180
181#[derive(Debug, Clone)]
182pub struct Break {
183 pub span: Span,
184}
185
186#[derive(Debug, Clone)]
187pub struct Continue {
188 pub span: Span,
189}
190
191#[derive(Debug, Clone)]
192pub enum Statement {
193 FunctionDef(FunctionDef),
194 AsyncFunctionDef(AsyncFunctionDef),
195 ClassDef(ClassDef),
196 Return(Return),
197 Delete(Delete),
198 Assign(Assign),
199 AugAssign(AugAssign),
200 AnnAssign(AnnAssign),
201 For(For),
202 AsyncFor(AsyncFor),
203 While(While),
204 If(If),
205 With(With),
206 AsyncWith(AsyncWith),
207 Raise(Raise),
208 Try(Try),
209 Assert(Assert),
210 Import(Import),
211 ImportFrom(ImportFrom),
212 Global(Global),
213 Nonlocal(Nonlocal),
214 Expr(Expr),
215 Pass(Pass),
216 Break(Break),
217 Continue(Continue),
218}
219
220impl Statement {
221 pub fn span(&self) -> &Span {
222 match self {
223 Statement::FunctionDef(x) => &x.span,
224 Statement::AsyncFunctionDef(x) => &x.span,
225 Statement::ClassDef(x) => &x.span,
226 Statement::Return(x) => &x.span,
227 Statement::Delete(x) => &x.span,
228 Statement::Assign(x) => &x.span,
229 Statement::AugAssign(x) => &x.span,
230 Statement::AnnAssign(x) => &x.span,
231 Statement::For(x) => &x.span,
232 Statement::AsyncFor(x) => &x.span,
233 Statement::While(x) => &x.span,
234 Statement::If(x) => &x.span,
235 Statement::With(x) => &x.span,
236 Statement::AsyncWith(x) => &x.span,
237 Statement::Raise(x) => &x.span,
238 Statement::Try(x) => &x.span,
239 Statement::Assert(x) => &x.span,
240 Statement::Import(x) => &x.span,
241 Statement::ImportFrom(x) => &x.span,
242 Statement::Global(x) => &x.span,
243 Statement::Nonlocal(x) => &x.span,
244 Statement::Expr(x) => &x.span,
245 Statement::Pass(x) => &x.span,
246 Statement::Break(x) => &x.span,
247 Statement::Continue(x) => &x.span,
248 }
249 }
250}
251
252#[derive(Debug, Clone)]
253pub struct BoolOp {
254 pub span: Span,
255 pub left: Box<Expression>,
256 pub op: BoolOpKind,
257 pub right: Box<Expression>,
258}
259
260#[derive(Debug, Clone)]
261pub struct BinOp {
262 pub span: Span,
263 pub left: Box<Expression>,
264 pub op: OpKind,
265 pub right: Box<Expression>,
266}
267
268#[derive(Debug, Clone)]
269pub struct UnaryOp {
270 pub span: Span,
271 pub op: UnaryOpKind,
272 pub operand: Box<Expression>,
273}
274
275#[derive(Debug, Clone)]
276pub struct Lambda {
277 pub span: Span,
278 pub args: Box<Arguments>,
279 pub body: Box<Expression>,
280}
281
282#[derive(Debug, Clone)]
283pub struct IfExp {
284 pub span: Span,
285 pub test: Box<Expression>,
286 pub body: Box<Expression>,
287 pub orelse: Box<Expression>,
288}
289
290#[derive(Debug, Clone)]
291pub struct Dict {
292 pub span: Span,
293 pub keys: Vec<Option<Expression>>,
294 pub values: Vec<Expression>,
295}
296
297#[derive(Debug, Clone)]
298pub struct Set {
299 pub span: Span,
300 pub elts: Vec<Expression>,
301}
302
303#[derive(Debug, Clone)]
304pub struct ListComp {
305 pub span: Span,
306 pub elt: Box<Expression>,
307 pub generators: Vec<Comprehension>,
308}
309
310#[derive(Debug, Clone)]
311pub struct SetComp {
312 pub span: Span,
313 pub elt: Box<Expression>,
314 pub generators: Vec<Comprehension>,
315}
316
317#[derive(Debug, Clone)]
318pub struct DictComp {
319 pub span: Span,
320 pub key: Box<Expression>,
321 pub value: Box<Expression>,
322 pub generators: Vec<Comprehension>,
323}
324
325#[derive(Debug, Clone)]
326pub struct GeneratorExp {
327 pub span: Span,
328 pub elt: Box<Expression>,
329 pub generators: Vec<Comprehension>,
330}
331
332#[derive(Debug, Clone)]
333pub struct Await {
334 pub span: Span,
335 pub value: Box<Expression>,
336}
337
338#[derive(Debug, Clone)]
339pub struct Yield {
340 pub span: Span,
341 pub value: Option<Box<Expression>>,
342}
343
344#[derive(Debug, Clone)]
345pub struct YieldFrom {
346 pub span: Span,
347 pub value: Box<Expression>,
348}
349
350#[derive(Debug, Clone)]
351pub struct Compare {
352 pub span: Span,
353 pub left: Box<Expression>,
354 pub ops: Vec<ComparisonOpKind>,
355 pub comparators: Vec<Expression>,
356}
357
358#[derive(Debug, Clone)]
359pub struct Call {
360 pub span: Span,
361 pub func: Box<Expression>,
362 pub args: Vec<Expression>,
363 pub keywords: Vec<Keyword>,
364}
365
366#[derive(Debug, Clone)]
367pub struct Num {
368 pub span: Span,
369 pub value: NumKind,
370}
371
372#[derive(Debug, Clone)]
373pub struct Str {
374 pub span: Span,
375 pub value: String,
376}
377
378#[derive(Debug, Clone)]
379pub struct FormattedValue {
380 pub span: Span,
381 pub value: Box<Expression>,
382 pub conversion: Option<Conversion>,
383 pub format_spec: Box<Expression>,
384}
385
386#[derive(Debug, Clone)]
387pub struct JoinedStr {
388 pub span: Span,
389 pub values: Vec<Expression>,
390}
391
392#[derive(Debug, Clone)]
393pub struct Bytes {
394 pub span: Span,
395 pub value: Vec<u8>,
396}
397
398#[derive(Debug, Clone)]
399pub struct NameConstant {
400 pub span: Span,
401 pub value: Singleton,
402}
403
404#[derive(Debug, Clone)]
405pub struct Ellipsis {
406 pub span: Span,
407}
408
409#[derive(Debug, Clone)]
410pub struct Attribute {
411 pub span: Span,
412 pub value: Box<Expression>,
413 pub attr: String,
414}
415
416#[derive(Debug, Clone)]
417pub struct Subscript {
418 pub span: Span,
419 pub value: Box<Expression>,
420 pub slice: Slice,
421}
422
423#[derive(Debug, Clone)]
424pub struct Starred {
425 pub span: Span,
426 pub value: Box<Expression>,
427}
428
429#[derive(Debug, Clone)]
430pub struct Name {
431 pub span: Span,
432 pub id: String,
433}
434
435#[derive(Debug, Clone)]
436pub struct List {
437 pub span: Span,
438 pub elts: Vec<Expression>,
439}
440
441#[derive(Debug, Clone)]
442pub struct Tuple {
443 pub span: Span,
444 pub elts: Vec<Expression>,
445}
446
447#[derive(Debug, Clone)]
448pub enum Expression {
449 BoolOp(BoolOp),
450 BinOp(BinOp),
451 UnaryOp(UnaryOp),
452 Lambda(Lambda),
453 IfExp(IfExp),
454 Dict(Dict),
455 Set(Set),
456 ListComp(ListComp),
457 SetComp(SetComp),
458 DictComp(DictComp),
459 GeneratorExp(GeneratorExp),
460 Await(Await),
461 Yield(Yield),
462 YieldFrom(YieldFrom),
463 Compare(Compare),
464 Call(Call),
465 Num(Num),
466 Str(Str),
467 FormattedValue(FormattedValue),
468 JoinedStr(JoinedStr),
469 Bytes(Bytes),
470 NameConstant(NameConstant),
471 Ellipsis(Ellipsis),
472 Attribute(Attribute),
473 Subscript(Subscript),
474 Starred(Starred),
475 Name(Name),
476 List(List),
477 Tuple(Tuple),
478}
479
480impl Expression {
481 pub fn span(&self) -> &Span {
482 match self {
483 Expression::BoolOp(x) => &x.span,
484 Expression::BinOp(x) => &x.span,
485 Expression::UnaryOp(x) => &x.span,
486 Expression::Lambda(x) => &x.span,
487 Expression::IfExp(x) => &x.span,
488 Expression::Dict(x) => &x.span,
489 Expression::Set(x) => &x.span,
490 Expression::ListComp(x) => &x.span,
491 Expression::SetComp(x) => &x.span,
492 Expression::DictComp(x) => &x.span,
493 Expression::GeneratorExp(x) => &x.span,
494 Expression::Await(x) => &x.span,
495 Expression::Yield(x) => &x.span,
496 Expression::YieldFrom(x) => &x.span,
497 Expression::Compare(x) => &x.span,
498 Expression::Call(x) => &x.span,
499 Expression::Num(x) => &x.span,
500 Expression::Str(x) => &x.span,
501 Expression::FormattedValue(x) => &x.span,
502 Expression::JoinedStr(x) => &x.span,
503 Expression::Bytes(x) => &x.span,
504 Expression::NameConstant(x) => &x.span,
505 Expression::Ellipsis(x) => &x.span,
506 Expression::Attribute(x) => &x.span,
507 Expression::Subscript(x) => &x.span,
508 Expression::Starred(x) => &x.span,
509 Expression::Name(x) => &x.span,
510 Expression::List(x) => &x.span,
511 Expression::Tuple(x) => &x.span,
512 }
513 }
514}
515
516#[derive(Debug, Clone)]
517pub enum Slice {
518 Slice {
519 lower: Option<Box<Expression>>,
520 upper: Option<Box<Expression>>,
521 step: Option<Box<Expression>>,
522 },
523 ExtSlice {
524 dims: Vec<Slice>,
525 },
526 Index {
527 value: Box<Expression>,
528 },
529}
530
531#[derive(Debug, Clone, Copy, Eq, PartialEq)]
532pub enum BoolOpKind {
533 And,
534 Or,
535}
536
537#[derive(Debug, Clone, Copy, Eq, PartialEq)]
538pub enum OpKind {
539 Addition,
540 Subtraction,
541 Multiplication,
542 MatrixMultiplication,
543 Division,
544 Modulo,
545 Power,
546 LeftShift,
547 RightShift,
548 BitOr,
549 BitXor,
550 BitAnd,
551 FloorDivision,
552}
553
554#[derive(Debug, Clone, Copy, Eq, PartialEq)]
555pub enum UnaryOpKind {
556 Invert,
557 Not,
558 Plus,
559 Minus,
560}
561
562#[derive(Debug, Clone, Copy, Eq, PartialEq)]
563pub enum ComparisonOpKind {
564 Equal,
565 NotEqual,
566 Less,
567 LessEqual,
568 Greater,
569 GreaterEqual,
570 Is,
571 IsNot,
572 In,
573 NotIn,
574}
575
576#[derive(Debug, Clone)]
577pub struct Comprehension {
578 pub target: Box<Expression>,
579 pub iter: Box<Expression>,
580 pub ifs: Vec<Expression>,
581 pub is_async: bool,
582}
583
584#[derive(Debug, Clone)]
585pub struct ExceptHandler {
586 pub span: Span,
587 pub typ: Option<Box<Expression>>,
588 pub name: Option<String>,
589 pub body: Vec<Statement>,
590}
591
592#[derive(Debug, Clone, Default)]
593pub struct Arguments {
594 pub args: Vec<Arg>,
595 pub vararg: Option<Arg>,
596 pub kwonlyargs: Vec<Arg>,
597 pub kwarg: Option<Arg>,
598}
599
600#[derive(Debug, Clone)]
601pub struct Arg {
602 pub span: Span,
603 pub arg: String,
604 pub annotation: Option<Box<Expression>>,
605 pub kind: ArgKind,
606}
607
608#[derive(Debug, Clone)]
609pub enum ArgKind {
610 Required,
611 Optional(Box<Expression>),
612 Vararg,
613 Kwarg,
614}
615
616#[derive(Debug, Clone)]
617pub struct Keyword {
618 pub arg: Option<String>,
619 pub value: Box<Expression>,
620}
621
622#[derive(Debug, Clone, Eq, PartialEq)]
623pub struct Alias {
624 pub identifier: String,
625 pub asname: Option<String>,
626}
627
628#[derive(Debug, Clone)]
629pub struct WithItem {
630 pub context_expr: Box<Expression>,
631 pub optional_vars: Option<Box<Expression>>,
632}
633
634#[derive(Debug, Clone, Copy, Eq, PartialEq)]
635pub enum Singleton {
636 None,
637 True,
638 False,
639}
640
641#[derive(Debug, Clone, PartialEq)]
642pub enum NumKind {
643 Integer(num_bigint::BigUint),
644 Float(f64),
645 Complex(f64),
646}
647
648#[derive(Debug, Clone, Copy, Eq, PartialEq)]
649pub enum Conversion {
650 Str,
651 Repr,
652 Ascii,
653}
654
655fn write_joined<I, T, S>(f: &mut fmt::Formatter<'_>, i: I, sep: S) -> fmt::Result
656where
657 I: IntoIterator<Item = T>,
658 T: Display,
659 S: Display,
660{
661 let mut iter = i.into_iter();
662 if let Some(e) = iter.next() {
663 write!(f, "{}", e)?;
664 }
665 for e in iter {
666 write!(f, "{}{}", sep, e)?;
667 }
668 Ok(())
669}
670
671fn write_escaped(f: &mut fmt::Formatter<'_>, b: u8) -> fmt::Result {
672 match b {
673 b' ' => f.write_str(" "),
674 b'"' => f.write_str("\\\""),
675 b'\\' => f.write_str("\\"),
676 b'\n' => f.write_str("\\n"),
677 b'\r' => f.write_str("\\r"),
678 b'\t' => f.write_str("\\t"),
679 b'\x07' => f.write_str("\\a"),
680 b'\x08' => f.write_str("\\b"),
681 b'\x0c' => f.write_str("\\f"),
682 b'\x0b' => f.write_str("\\v"),
683 b if b.is_ascii_graphic() => f.write_str(&char::from(b).to_string()),
684 b => write!(f, "\\x{:x}", b),
685 }
686}
687
688fn write_indent(f: &mut fmt::Formatter<'_>, level: usize) -> fmt::Result {
689 for _ in 0..level * 4 {
690 f.write_str(" ")?;
691 }
692 Ok(())
693}
694
695impl Display for Program {
696 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
697 match self {
698 Program::Module(p) => write!(f, "{}", p),
699 Program::Interactive(p) => write!(f, "{}", p),
700 Program::Eval(p) => write!(f, "{}", p),
701 }
702 }
703}
704
705impl Display for Module {
706 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707 write_joined(f, &self.body, "\n")
708 }
709}
710
711impl Display for Interactive {
712 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
713 write_joined(f, &self.body, "\n")
714 }
715}
716
717impl Display for Eval {
718 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
719 write!(f, "{}", self.body)
720 }
721}
722
723fn write_body(f: &mut fmt::Formatter<'_>, indent: usize, body: &[Statement]) -> fmt::Result {
724 for e in body {
725 e.fmt_indented(f, indent)?;
726 f.write_str("\n")?;
727 }
728 Ok(())
729}
730
731fn write_funcdef(
732 f: &mut fmt::Formatter<'_>,
733 indent: usize,
734 node: &FunctionDef,
735 is_async: bool,
736) -> fmt::Result {
737 for dec in &node.decorator_list {
738 writeln!(f, "@{}", dec)?;
739 write_indent(f, indent)?;
740 }
741 if is_async {
742 f.write_str("async ")?;
743 }
744 write!(f, "def {}({})", node.name, node.args)?;
745 if let Some(returns) = &node.returns {
746 write!(f, " -> {}", returns)?;
747 }
748 f.write_str(":\n")?;
749 write_body(f, indent + 1, &node.body)?;
750 Ok(())
751}
752
753fn write_for(f: &mut fmt::Formatter<'_>, indent: usize, node: &For, is_async: bool) -> fmt::Result {
754 if is_async {
755 f.write_str("async ")?;
756 }
757 writeln!(f, "for {} in {}:", node.target, node.iter)?;
758 write_body(f, indent + 1, &node.body)?;
759 if !node.orelse.is_empty() {
760 write_indent(f, indent)?;
761 f.write_str("else:\n")?;
762 write_body(f, indent + 1, &node.orelse)?;
763 }
764 Ok(())
765}
766
767fn write_if(f: &mut fmt::Formatter<'_>, indent: usize, node: &If) -> fmt::Result {
768 writeln!(f, "if {}:", node.test)?;
769 write_body(f, indent + 1, &node.body)?;
770 match node.orelse.as_slice() {
771 [Statement::If(s)] => {
772 write_indent(f, indent)?;
773 f.write_str("el")?;
774 write_if(f, indent, s)?;
775 }
776 [] => (),
777 s => {
778 write_indent(f, indent)?;
779 f.write_str("else:\n")?;
780 write_body(f, indent + 1, s)?;
781 }
782 };
783 Ok(())
784}
785
786fn write_with(
787 f: &mut fmt::Formatter<'_>,
788 indent: usize,
789 node: &With,
790 is_async: bool,
791) -> fmt::Result {
792 if is_async {
793 f.write_str("async ")?;
794 }
795 f.write_str("with ")?;
796 write_joined(f, &node.items, ", ")?;
797 f.write_str(":\n")?;
798 write_body(f, indent + 1, &node.body)
799}
800
801impl Statement {
802 fn fmt_indented(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
803 write_indent(f, indent)?;
804 match self {
805 Statement::FunctionDef(node) => write_funcdef(f, indent, node, false),
806 Statement::AsyncFunctionDef(node) => write_funcdef(f, indent, node, true),
807 Statement::ClassDef(node) => {
808 for dec in &node.decorator_list {
809 writeln!(f, "@{}", dec)?;
810 write_indent(f, indent)?;
811 }
812 write!(f, "class {}", node.name)?;
813 if !node.bases.is_empty() || !node.keywords.is_empty() {
814 f.write_str("(")?;
815 write_joined(f, &node.bases, ", ")?;
816 if !node.bases.is_empty() && !node.keywords.is_empty() {
817 f.write_str(", ")?;
818 }
819 write_joined(f, &node.keywords, ", ")?;
820 f.write_str(")")?;
821 }
822 f.write_str(":\n")?;
823 write_body(f, indent + 1, &node.body)
824 }
825 Statement::Return(Return { value, .. }) => match value {
826 Some(v) => write!(f, "return {}", v),
827 _ => write!(f, "return"),
828 },
829 Statement::Delete(Delete { targets, .. }) => {
830 write!(f, "del ")?;
831 write_joined(f, targets, ", ")
832 }
833 Statement::Assign(Assign { targets, value, .. }) => {
834 write_joined(f, targets, " = ")?;
835 write!(f, " = {}", value)
836 }
837 Statement::AugAssign(AugAssign {
838 target, op, value, ..
839 }) => write!(f, "{} {}= {}", target, op, value),
840 Statement::AnnAssign(node) => {
841 write!(f, "{}: {}", node.target, node.annotation)?;
842 if let Some(value) = &node.value {
843 write!(f, " = {}", value)?;
844 }
845 Ok(())
846 }
847 Statement::For(node) => write_for(f, indent, node, false),
848 Statement::AsyncFor(node) => write_for(f, indent, node, true),
849 Statement::While(node) => {
850 writeln!(f, "while {}:", node.test)?;
851 write_body(f, indent + 1, &node.body)?;
852 if !node.orelse.is_empty() {
853 write_indent(f, indent)?;
854 f.write_str("else:\n")?;
855 write_body(f, indent + 1, &node.orelse)?;
856 }
857 Ok(())
858 }
859 Statement::If(node) => write_if(f, indent, node),
860 Statement::With(node) => write_with(f, indent, node, false),
861 Statement::AsyncWith(node) => write_with(f, indent, node, true),
862 Statement::Raise(Raise { exc, cause, .. }) => {
863 write!(f, "raise")?;
864 if let Some(exc) = exc {
865 write!(f, " {}", exc)?;
866 }
867 if let Some(cause) = cause {
868 write!(f, " from {}", cause)?;
869 }
870 Ok(())
871 }
872 Statement::Try(node) => {
873 f.write_str("try:\n")?;
874 write_body(f, indent + 1, &node.body)?;
875 for hdl in &node.handlers {
876 hdl.fmt_indented(f, indent)?;
877 }
878 if !node.orelse.is_empty() {
879 write_indent(f, indent)?;
880 f.write_str("else:\n")?;
881 write_body(f, indent + 1, &node.orelse)?;
882 }
883 if !node.finalbody.is_empty() {
884 write_indent(f, indent)?;
885 f.write_str("finally:\n")?;
886 write_body(f, indent + 1, &node.finalbody)?;
887 }
888 Ok(())
889 }
890 Statement::Assert(Assert { test, msg, .. }) => {
891 write!(f, "assert {}", test)?;
892 if let Some(msg) = msg {
893 write!(f, ", {}", msg)?;
894 }
895 Ok(())
896 }
897 Statement::Import(Import { names, .. }) => {
898 f.write_str("import ")?;
899 write_joined(f, names, ", ")
900 }
901 Statement::ImportFrom(node) => {
902 f.write_str("from ")?;
903 for _ in 0..node.level {
904 f.write_str(".")?;
905 }
906 if let Some(module) = &node.module {
907 write!(f, "{}", module)?;
908 }
909 f.write_str(" import ")?;
910 write_joined(f, &node.names, ", ")
911 }
912 Statement::Global(Global { names, .. }) => {
913 f.write_str("global ")?;
914 write_joined(f, names, ", ")
915 }
916 Statement::Nonlocal(Nonlocal { names, .. }) => {
917 f.write_str("nonlocal ")?;
918 write_joined(f, names, ", ")
919 }
920 Statement::Expr(Expr { value, .. }) => write!(f, "{}", value),
921 Statement::Pass(_) => f.write_str("pass"),
922 Statement::Break(_) => f.write_str("break"),
923 Statement::Continue(_) => f.write_str("continue"),
924 }
925 }
926}
927
928impl Display for Statement {
929 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
930 self.fmt_indented(f, 0)
931 }
932}
933
934impl Display for Expression {
935 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
936 match self {
937 Expression::BoolOp(node) => write!(f, "{} {} {}", node.left, node.op, node.right),
938 Expression::BinOp(node) => write!(f, "{} {} {}", node.left, node.op, node.right),
939 Expression::UnaryOp(UnaryOp { op, operand, .. }) => write!(f, "{} {}", op, operand),
940 Expression::Lambda(Lambda { args, body, .. }) => write!(f, "lambda {}: {}", args, body),
941 Expression::IfExp(node) => {
942 write!(f, "{} if {} else {}", node.body, node.test, node.orelse)
943 }
944 Expression::Dict(Dict { keys, values, .. }) => {
945 fn write_kv(
946 f: &mut fmt::Formatter<'_>,
947 key: &Option<Expression>,
948 value: &Expression,
949 ) -> fmt::Result {
950 match key {
951 Some(k) => write!(f, "{}: ", k)?,
952 _ => write!(f, "**")?,
953 };
954 write!(f, "{}", value)
955 }
956 f.write_str("{")?;
957 let mut iter = keys.iter().zip(values);
958 if let Some((k, v)) = iter.next() {
959 write_kv(f, k, v)?;
960 }
961 for (k, v) in iter {
962 write!(f, ", ")?;
963 write_kv(f, k, v)?;
964 }
965 f.write_str("}")
966 }
967 Expression::Set(Set { elts, .. }) => {
968 f.write_str("{")?;
969 write_joined(f, elts, ", ")?;
970 f.write_str("}")
971 }
972 Expression::ListComp(node) => {
973 write!(f, "[{} ", node.elt)?;
974 write_joined(f, &node.generators, " ")?;
975 f.write_str("]")
976 }
977 Expression::SetComp(node) => {
978 write!(f, "{{{} ", node.elt)?;
979 write_joined(f, &node.generators, " ")?;
980 f.write_str("}")
981 }
982 Expression::DictComp(node) => {
983 write!(f, "{{{}: {} ", node.key, node.value)?;
984 write_joined(f, &node.generators, " ")?;
985 f.write_str("}")
986 }
987 Expression::GeneratorExp(node) => {
988 write!(f, "({} ", node.elt)?;
989 write_joined(f, &node.generators, " ")?;
990 f.write_str(")")
991 }
992 Expression::Await(Await { value, .. }) => write!(f, "await {}", value),
993 Expression::Yield(Yield { value, .. }) => match value {
994 Some(value) => write!(f, "yield {}", value),
995 _ => write!(f, "yield"),
996 },
997 Expression::YieldFrom(YieldFrom { value, .. }) => write!(f, "yield from {}", value),
998 Expression::Compare(node) => {
999 write!(f, "{}", node.left)?;
1000 for (op, e) in node.ops.iter().zip(&node.comparators) {
1001 write!(f, " {} {}", op, e)?
1002 }
1003 Ok(())
1004 }
1005 Expression::Call(node) => {
1006 write!(f, "{}(", node.func)?;
1007 write_joined(f, &node.args, ", ")?;
1008 if !node.args.is_empty() && !node.keywords.is_empty() {
1009 f.write_str(", ")?;
1010 }
1011 write_joined(f, &node.keywords, ", ")?;
1012 f.write_str(")")
1013 }
1014 Expression::Num(Num { value, .. }) => write!(f, "{}", value),
1015 Expression::Str(Str { value, .. }) => {
1016 f.write_str("\"")?;
1017 for b in value.bytes() {
1018 write_escaped(f, b)?;
1019 }
1020 f.write_str("\"")
1021 }
1022 Expression::FormattedValue(FormattedValue { .. }) => unimplemented!(),
1023 Expression::JoinedStr(JoinedStr { .. }) => unimplemented!(),
1024 Expression::Bytes(Bytes { value, .. }) => {
1025 f.write_str("b\"")?;
1026 for b in value {
1027 write_escaped(f, *b)?;
1028 }
1029 f.write_str("\"")
1030 }
1031 Expression::NameConstant(NameConstant { value, .. }) => write!(f, "{}", value),
1032 Expression::Ellipsis(Ellipsis { .. }) => write!(f, "..."),
1033 Expression::Attribute(Attribute { value, attr, .. }) => write!(f, "{}.{}", value, attr),
1034 Expression::Subscript(Subscript { value, slice, .. }) => {
1035 write!(f, "{}[{}]", value, slice)
1036 }
1037 Expression::Starred(Starred { value, .. }) => write!(f, "*{}", value),
1038 Expression::Name(Name { id, .. }) => write!(f, "{}", id),
1039 Expression::List(List { elts, .. }) => {
1040 f.write_str("[")?;
1041 write_joined(f, elts, ", ")?;
1042 f.write_str("]")
1043 }
1044 Expression::Tuple(Tuple { elts, .. }) => {
1045 f.write_str("(")?;
1046 write_joined(f, elts, ", ")?;
1047 f.write_str(")")
1048 }
1049 }
1050 }
1051}
1052
1053impl Display for Slice {
1054 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1055 match self {
1056 Slice::Slice { lower, upper, step } => {
1057 if let Some(lower) = lower {
1058 write!(f, "{}", lower)?;
1059 }
1060 f.write_str(":")?;
1061 if let Some(upper) = upper {
1062 write!(f, "{}", upper)?;
1063 }
1064 f.write_str(":")?;
1065 if let Some(step) = step {
1066 write!(f, "{}", step)?;
1067 }
1068 Ok(())
1069 }
1070 Slice::ExtSlice { dims } => write_joined(f, dims, ","),
1071 Slice::Index { value } => write!(f, "{}", value),
1072 }
1073 }
1074}
1075
1076impl Display for BoolOpKind {
1077 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1078 let s = match self {
1079 BoolOpKind::And => "and",
1080 BoolOpKind::Or => "or",
1081 };
1082 f.write_str(s)
1083 }
1084}
1085
1086impl Display for OpKind {
1087 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1088 let s = match self {
1089 OpKind::Addition => "+",
1090 OpKind::Subtraction => "-",
1091 OpKind::Multiplication => "*",
1092 OpKind::MatrixMultiplication => "@",
1093 OpKind::Division => "/",
1094 OpKind::Modulo => "%",
1095 OpKind::Power => "**",
1096 OpKind::LeftShift => "<<",
1097 OpKind::RightShift => ">>",
1098 OpKind::BitOr => "|",
1099 OpKind::BitXor => "^",
1100 OpKind::BitAnd => "&",
1101 OpKind::FloorDivision => "//",
1102 };
1103 f.write_str(s)
1104 }
1105}
1106
1107impl Display for UnaryOpKind {
1108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 let s = match self {
1110 UnaryOpKind::Invert => "~",
1111 UnaryOpKind::Not => "not",
1112 UnaryOpKind::Plus => "+",
1113 UnaryOpKind::Minus => "-",
1114 };
1115 f.write_str(s)
1116 }
1117}
1118
1119impl Display for ComparisonOpKind {
1120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1121 let s = match self {
1122 ComparisonOpKind::Equal => "==",
1123 ComparisonOpKind::NotEqual => "!=",
1124 ComparisonOpKind::Less => "<",
1125 ComparisonOpKind::LessEqual => "<=",
1126 ComparisonOpKind::Greater => ">",
1127 ComparisonOpKind::GreaterEqual => ">=",
1128 ComparisonOpKind::Is => "is",
1129 ComparisonOpKind::IsNot => "is not",
1130 ComparisonOpKind::In => "in",
1131 ComparisonOpKind::NotIn => "not in",
1132 };
1133 f.write_str(s)
1134 }
1135}
1136
1137impl Display for Comprehension {
1138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1139 if self.is_async {
1140 f.write_str("async ")?;
1141 }
1142 write!(f, "for {} in {}", self.target, self.iter)?;
1143 for e in &self.ifs {
1144 write!(f, " if {}", e)?;
1145 }
1146 Ok(())
1147 }
1148}
1149
1150impl ExceptHandler {
1151 fn fmt_indented(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
1152 write_indent(f, indent)?;
1153 f.write_str("except")?;
1154 if let Some(typ) = &self.typ {
1155 write!(f, " {}", typ)?;
1156 }
1157 if let Some(name) = &self.name {
1158 write!(f, " as {}", name)?;
1159 }
1160 f.write_str(":\n")?;
1161 write_body(f, indent + 1, &self.body)
1162 }
1163}
1164
1165impl Display for Arguments {
1166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1167 write_joined(
1168 f,
1169 self.args
1170 .iter()
1171 .chain(&self.vararg)
1172 .chain(&self.kwonlyargs)
1173 .chain(&self.kwarg),
1174 ", ",
1175 )
1176 }
1177}
1178
1179impl Display for Arg {
1180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1181 match &self.kind {
1182 ArgKind::Vararg => f.write_str("*")?,
1183 ArgKind::Kwarg => f.write_str("**")?,
1184 _ => (),
1185 }
1186 f.write_str(&self.arg)?;
1187 if let Some(a) = &self.annotation {
1188 write!(f, ": {}", &a)?;
1189 }
1190 if let ArgKind::Optional(default) = &self.kind {
1191 write!(f, " = {}", &default)?;
1192 }
1193 Ok(())
1194 }
1195}
1196
1197impl Display for Keyword {
1198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1199 match &self.arg {
1200 Some(arg) => write!(f, "{}={}", arg, self.value),
1201 _ => write!(f, "**{}", self.value),
1202 }
1203 }
1204}
1205
1206impl Display for Alias {
1207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1208 write!(f, "{}", self.identifier)?;
1209 if let Some(asname) = &self.asname {
1210 write!(f, " as {}", asname)?;
1211 }
1212 Ok(())
1213 }
1214}
1215
1216impl Display for WithItem {
1217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1218 write!(f, "{}", self.context_expr)?;
1219 if let Some(vars) = &self.optional_vars {
1220 write!(f, " as {}", vars)?;
1221 }
1222 Ok(())
1223 }
1224}
1225
1226impl Display for NumKind {
1227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1228 match self {
1229 NumKind::Integer(n) => write!(f, "{}", n),
1230 NumKind::Float(n) | NumKind::Complex(n) => write!(f, "{}", n),
1231 }
1232 }
1233}
1234
1235impl Display for Singleton {
1236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1237 let s = match self {
1238 Singleton::None => "None",
1239 Singleton::True => "True",
1240 Singleton::False => "False",
1241 };
1242 f.write_str(s)
1243 }
1244}