-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathast.rs
More file actions
1795 lines (1673 loc) Β· 41.7 KB
/
Copy pathast.rs
File metadata and controls
1795 lines (1673 loc) Β· 41.7 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
use is_macro::Is;
use std::borrow::Cow;
use std::fmt::{self};
use std::sync::Arc;
use miette::{SourceOffset, SourceSpan};
use crate::intern::StrId;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] // #[serde(tag = "type")]
pub struct Node {
/// Start offset in source
pub start: u32,
/// End offset in source
pub end: u32,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] // #[serde(tag = "type")]
pub struct TextRange {
pub start: u32,
pub end: u32,
}
impl fmt::Display for Node {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.start, self.end)
}
}
impl Node {
pub fn new(start: u32, end: u32) -> Self {
Self { start, end }
}
pub fn len(&self) -> u32 {
self.end - self.start
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
pub trait GetNode {
fn get_node(&self) -> Node;
}
impl From<Node> for SourceSpan {
fn from(val: Node) -> Self {
Self::new(SourceOffset::from(val.start as usize), val.len() as usize)
}
}
// The following structs are used to represent the AST
// https://docs.python.org/3/library/ast.html#abstract-grammar
#[derive(Debug, Clone)]
pub struct Module {
pub node: Node,
pub body: Vec<Statement>,
}
// Use box to reduce the enum size
#[derive(Debug, Clone, Is)]
pub enum Statement {
AssignStatement(Box<Assign>),
AnnAssignStatement(Box<AnnAssign>),
AugAssignStatement(Box<AugAssign>),
ExpressionStatement(Box<Expression>),
Assert(Box<Assert>),
Pass(Box<Pass>),
Delete(Box<Delete>),
ReturnStmt(Box<Return>),
Raise(Box<Raise>),
BreakStmt(Box<Break>),
ContinueStmt(Box<Continue>),
Import(Box<Import>),
ImportFrom(Box<ImportFrom>),
Global(Box<Global>),
Nonlocal(Box<Nonlocal>),
IfStatement(Box<If>),
WhileStatement(Box<While>),
ForStatement(Box<For>),
AsyncForStatement(Box<AsyncFor>),
WithStatement(Box<With>),
AsyncWithStatement(Box<AsyncWith>),
TryStatement(Box<Try>),
TryStarStatement(Box<TryStar>),
FunctionDef(Arc<FunctionDef>),
AsyncFunctionDef(Arc<AsyncFunctionDef>),
ClassDef(Arc<ClassDef>),
MatchStmt(Box<Match>),
TypeAlias(Box<TypeAlias>),
}
impl GetNode for Statement {
fn get_node(&self) -> Node {
match self {
Statement::AssignStatement(s) => s.node,
Statement::AnnAssignStatement(s) => s.node,
Statement::AugAssignStatement(s) => s.node,
Statement::ExpressionStatement(s) => s.get_node(),
Statement::Assert(s) => s.node,
Statement::Pass(s) => s.node,
Statement::Delete(s) => s.node,
Statement::ReturnStmt(s) => s.node,
Statement::Raise(s) => s.node,
Statement::BreakStmt(s) => s.node,
Statement::ContinueStmt(s) => s.node,
Statement::Import(s) => s.node,
Statement::ImportFrom(s) => s.node,
Statement::Global(s) => s.node,
Statement::Nonlocal(s) => s.node,
Statement::IfStatement(s) => s.node,
Statement::WhileStatement(s) => s.node,
Statement::ForStatement(s) => s.node,
Statement::AsyncForStatement(s) => s.node,
Statement::WithStatement(s) => s.node,
Statement::AsyncWithStatement(s) => s.node,
Statement::TryStatement(s) => s.node,
Statement::TryStarStatement(s) => s.node,
Statement::FunctionDef(s) => s.node,
Statement::AsyncFunctionDef(s) => s.node,
Statement::ClassDef(s) => s.node,
Statement::MatchStmt(s) => s.node,
Statement::TypeAlias(s) => s.node,
}
}
}
#[derive(Debug, Clone)]
pub struct Assign {
pub node: Node,
pub targets: Vec<Expression>,
pub value: Expression,
}
#[derive(Debug, Clone)]
pub struct AnnAssign {
pub node: Node,
pub target: Expression,
pub annotation: Expression,
pub value: Option<Expression>,
pub simple: bool,
}
#[derive(Debug, Clone)]
pub struct AugAssign {
pub node: Node,
pub target: Expression,
pub op: AugAssignOp,
pub value: Expression,
}
#[derive(Debug, Clone)]
pub enum AugAssignOp {
Add,
Sub,
Mult,
MatMult,
Div,
Mod,
Pow,
LShift,
RShift,
BitOr,
BitXor,
BitAnd,
FloorDiv,
}
#[derive(Debug, Clone)]
pub struct Assert {
pub node: Node,
pub test: Expression,
pub msg: Option<Expression>,
}
#[derive(Debug, Clone)]
pub struct Pass {
pub node: Node,
}
#[derive(Debug, Clone)]
pub struct Delete {
pub node: Node,
pub targets: Vec<Expression>,
}
#[derive(Debug, Clone)]
pub struct Return {
pub node: Node,
pub value: Option<Expression>,
}
// https://docs.python.org/3/library/ast.html#ast.Raise
#[derive(Debug, Clone)]
pub struct Raise {
pub node: Node,
pub exc: Option<Expression>,
pub cause: Option<Expression>,
}
// https://docs.python.org/3/library/ast.html#ast.Break
#[derive(Debug, Clone)]
pub struct Break {
pub node: Node,
}
// https://docs.python.org/3/library/ast.html#ast.Continue
#[derive(Debug, Clone)]
pub struct Continue {
pub node: Node,
}
// https://docs.python.org/3/library/ast.html#ast.Import
#[derive(Debug, Clone)]
pub struct Import {
pub node: Node,
pub names: Vec<Alias>,
}
// https://docs.python.org/3/library/ast.html#ast.alias
#[derive(Debug, Clone)]
pub struct Alias {
pub node: Node,
pub name: String,
pub asname: Option<String>,
}
impl Alias {
pub fn name(&self) -> String {
if let Some(asname) = &self.asname {
asname.clone()
} else {
self.name.clone()
}
}
}
// https://docs.python.org/3/library/ast.html#ast.ImportFrom
#[derive(Debug, Clone)]
pub struct ImportFrom {
pub node: Node,
pub module: String,
pub names: Vec<Alias>,
pub level: usize,
}
// https://docs.python.org/3/library/ast.html#ast.Global
#[derive(Debug, Clone)]
pub struct Global {
pub node: Node,
pub names: Vec<String>,
}
// https://docs.python.org/3/library/ast.html#ast.Nonlocal
#[derive(Debug, Clone)]
pub struct Nonlocal {
pub node: Node,
pub names: Vec<String>,
}
#[derive(Debug, Clone, Is)]
pub enum Expression {
Constant(Box<Constant>),
List(Box<List>),
Tuple(Box<Tuple>),
Dict(Box<Dict>),
Set(Box<Set>),
Name(Box<Name>),
BoolOp(Box<BoolOperation>),
UnaryOp(Box<UnaryOperation>),
BinOp(Box<BinOp>),
NamedExpr(Box<NamedExpression>),
#[is(name = "yield_expr")]
Yield(Box<Yield>),
YieldFrom(Box<YieldFrom>),
Starred(Box<Starred>),
Generator(Box<Generator>),
ListComp(Box<ListComp>),
SetComp(Box<SetComp>),
DictComp(Box<DictComp>),
Attribute(Box<Attribute>),
Subscript(Box<Subscript>),
Slice(Box<Slice>),
Call(Box<Call>),
#[is(name = "await_expr")]
Await(Box<Await>),
Compare(Box<Compare>),
Lambda(Box<Lambda>),
IfExp(Box<IfExp>),
JoinedStr(Box<JoinedStr>),
FormattedValue(Box<FormattedValue>),
}
impl GetNode for Expression {
fn get_node(&self) -> Node {
match self {
Expression::Constant(c) => c.node,
Expression::List(l) => l.node,
Expression::Tuple(t) => t.node,
Expression::Dict(d) => d.node,
Expression::Set(s) => s.node,
Expression::Name(n) => n.node,
Expression::BoolOp(b) => b.node,
Expression::UnaryOp(u) => u.node,
Expression::BinOp(b) => b.node,
Expression::NamedExpr(n) => n.node,
Expression::Yield(y) => y.node,
Expression::YieldFrom(y) => y.node,
Expression::Starred(s) => s.node,
Expression::Generator(g) => g.node,
Expression::ListComp(l) => l.node,
Expression::SetComp(s) => s.node,
Expression::DictComp(d) => d.node,
Expression::Attribute(a) => a.node,
Expression::Subscript(s) => s.node,
Expression::Slice(s) => s.node,
Expression::Call(c) => c.node,
Expression::Await(a) => a.node,
Expression::Compare(c) => c.node,
Expression::Lambda(l) => l.node,
Expression::IfExp(i) => i.node,
Expression::JoinedStr(j) => j.node,
Expression::FormattedValue(f) => f.node,
}
}
}
// https://docs.python.org/3/reference/expressions.html#atom-identifiers
#[derive(Clone)]
pub struct Name {
pub node: Node,
pub id: String,
pub parenthesized: bool,
}
impl Name {
pub fn get_value<'a>(&self, source: &'a str) -> &'a str {
&source[(self.node.start) as usize..(self.node.end) as usize]
}
}
impl fmt::Debug for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Name")
.field("node", &self.node)
.field("id", &self.id)
.finish()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Constant {
pub node: Node,
pub value: ConstantValue,
}
impl Constant {
pub fn get_value<'a>(&self, source: &'a str) -> Cow<'a, str> {
match &self.value {
ConstantValue::Str(quote_type) => match quote_type {
QuoteType::Single => Cow::Borrowed(
&source[(self.node.start + 1) as usize..(self.node.end - 1) as usize],
),
QuoteType::Triple => Cow::Borrowed(
&source[(self.node.start + 3) as usize..(self.node.end - 3) as usize],
),
QuoteType::Concat => {
let input = &source[(self.node.start) as usize..(self.node.end) as usize];
let mut result = String::new();
let mut chars = input.chars().peekable();
while let Some(c) = chars.next() {
let quote_type = match c {
'\'' => {
if chars.peek() == Some(&'\'') && chars.nth(1) == Some('\'') {
// Triple single quote
"'''"
} else {
// Single quote
"'"
}
}
'"' => {
if chars.peek() == Some(&'"') && chars.nth(1) == Some('"') {
// Triple double quote
"\"\"\""
} else {
// Double quote
"\""
}
}
_ => continue, // Ignore any non-quote characters
};
// Extract content between quotes
let mut content = String::new();
let mut quote_ending = quote_type.chars().peekable();
for next_char in chars.by_ref() {
// Check for quote ending
if Some(&next_char) == quote_ending.peek() {
quote_ending.next();
if quote_ending.peek().is_none() {
break; // End of the string literal
}
} else {
content.push(next_char);
quote_ending = quote_type.chars().peekable(); // Reset the ending check
}
}
// Concatenate the cleaned-up string
result.push_str(&content);
}
Cow::Owned(result)
}
},
ConstantValue::Bool(b) => {
if *b {
Cow::Borrowed("true")
} else {
Cow::Borrowed("false")
}
},
ConstantValue::Int => Cow::Borrowed(
&source[self.node.start as usize..self.node.end as usize],
),
ConstantValue::Float => Cow::Borrowed(
&source[self.node.start as usize..self.node.end as usize],
),
_ => todo!("Call the parser and get the value"),
}
}
}
#[derive(Clone, PartialEq, Debug)]
pub enum ConstantValue {
None,
Ellipsis,
Bool(bool),
// If the string start with triple quotes or single
// true => triple
// false => single
Str(QuoteType),
// Str,
Bytes,
Tuple,
// Numbers are string because we don't care about the value rn.
Int,
Float,
Complex,
}
#[derive(Clone, PartialEq, Debug)]
pub enum QuoteType {
Single,
Triple,
// When this string was created because two strings were concatenated
Concat,
}
impl From<&str> for QuoteType {
fn from(value: &str) -> Self {
if value.starts_with("\"\"\"") || value.starts_with("'''") {
return Self::Triple;
}
Self::Single
}
}
#[derive(Debug, Clone)]
pub struct List {
pub node: Node,
pub elements: Vec<Expression>,
}
#[derive(Debug, Clone)]
pub struct Tuple {
pub node: Node,
pub elements: Vec<Expression>,
}
#[derive(Debug, Clone)]
pub struct Dict {
pub node: Node,
pub keys: Vec<Expression>,
pub values: Vec<Expression>,
}
#[derive(Debug, Clone)]
pub struct Set {
pub node: Node,
pub elements: Vec<Expression>,
}
// https://docs.python.org/3/library/ast.html#ast.BoolOp
#[derive(Debug, Clone)]
pub struct BoolOperation {
pub node: Node,
pub op: BooleanOperator,
pub values: Vec<Expression>,
}
#[derive(Debug, Clone)]
pub enum BooleanOperator {
And,
Or,
}
// https://docs.python.org/3/library/ast.html#ast.UnaryOp
#[derive(Debug, Clone)]
pub struct UnaryOperation {
pub node: Node,
pub op: UnaryOperator,
pub operand: Expression,
}
#[derive(Debug, Clone)]
pub enum UnaryOperator {
Not,
Invert,
UAdd,
USub,
}
// https://docs.python.org/3/library/ast.html#ast.BinOp
#[derive(Debug, Clone)]
pub struct BinOp {
pub node: Node,
pub op: BinaryOperator,
pub left: Expression,
pub right: Expression,
}
#[derive(Debug, Clone, PartialEq)]
pub enum BinaryOperator {
Add,
Sub,
Mult,
MatMult,
Div,
Mod,
Pow,
LShift,
RShift,
BitOr,
BitXor,
BitAnd,
FloorDiv,
}
impl std::fmt::Display for BinaryOperator {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let op_str = match self {
BinaryOperator::Add => "+",
BinaryOperator::Sub => "-",
BinaryOperator::Mult => "*",
BinaryOperator::MatMult => "@",
BinaryOperator::Div => "/",
BinaryOperator::Mod => "%",
BinaryOperator::Pow => "**",
BinaryOperator::LShift => "<<",
BinaryOperator::RShift => ">>",
BinaryOperator::BitOr => "|",
BinaryOperator::BitXor => "^",
BinaryOperator::BitAnd => "&",
BinaryOperator::FloorDiv => "//",
};
write!(f, "{}", op_str)
}
}
// https://docs.python.org/3/library/ast.html#ast.NamedExpr
#[derive(Debug, Clone)]
pub struct NamedExpression {
pub node: Node,
pub target: Expression,
pub value: Expression,
}
// https://docs.python.org/3/library/ast.html#ast.Yield
#[derive(Debug, Clone)]
pub struct Yield {
pub node: Node,
pub value: Option<Expression>,
}
// https://docs.python.org/3/library/ast.html#ast.YieldFrom
#[derive(Debug, Clone)]
pub struct YieldFrom {
pub node: Node,
pub value: Expression,
}
// https://docs.python.org/3/library/ast.html#ast.Starred
#[derive(Debug, Clone)]
pub struct Starred {
pub node: Node,
pub value: Expression,
}
// https://docs.python.org/3/library/ast.html#ast.GeneratorExp
#[derive(Debug, Clone)]
pub struct Generator {
pub node: Node,
pub element: Expression,
pub generators: Vec<Comprehension>,
}
#[derive(Debug, Clone)]
pub struct ListComp {
pub node: Node,
pub element: Expression,
pub generators: Vec<Comprehension>,
}
#[derive(Debug, Clone)]
pub struct SetComp {
pub node: Node,
pub element: Expression,
pub generators: Vec<Comprehension>,
}
#[derive(Debug, Clone)]
pub struct DictComp {
pub node: Node,
pub key: Expression,
pub value: Expression,
pub generators: Vec<Comprehension>,
}
// https://docs.python.org/3/library/ast.html#ast.comprehension
#[derive(Debug, Clone)]
pub struct Comprehension {
pub node: Node,
pub target: Expression,
pub iter: Expression,
pub ifs: Vec<Expression>,
pub is_async: bool,
}
// https://docs.python.org/3/library/ast.html#ast.Attribute
#[derive(Debug, Clone)]
pub struct Attribute {
pub node: Node,
/// The x in x.y
pub value: Expression,
/// The y in x.y
pub attr: String,
}
// https://docs.python.org/3/library/ast.html#ast.Subscript
#[derive(Debug, Clone)]
pub struct Subscript {
pub node: Node,
pub value: Expression,
pub slice: Expression,
}
// https://docs.python.org/3/library/ast.html#ast.Slice
// can be used for Subscript
#[derive(Debug, Clone)]
pub struct Slice {
pub node: Node,
pub lower: Option<Expression>,
pub upper: Option<Expression>,
pub step: Option<Expression>,
}
// https://docs.python.org/3/library/ast.html#ast.Call
#[derive(Debug, Clone)]
pub struct Call {
pub node: Node,
pub func: Expression,
pub args: Vec<Expression>,
pub keywords: Vec<Keyword>,
pub starargs: Option<Expression>,
pub kwargs: Option<Expression>,
}
#[derive(Debug, Clone)]
pub struct Keyword {
pub node: Node,
pub arg: Option<String>,
pub value: Expression,
}
// https://docs.python.org/3/library/ast.html#ast.Await
#[derive(Debug, Clone)]
pub struct Await {
pub node: Node,
pub value: Expression,
}
// https://docs.python.org/3/library/ast.html#ast.Compare
#[derive(Debug, Clone)]
pub struct Compare {
pub node: Node,
pub left: Expression,
pub ops: Vec<ComparisonOperator>,
pub comparators: Vec<Expression>,
}
#[derive(Debug, Clone)]
pub enum ComparisonOperator {
Eq,
NotEq,
Lt,
LtE,
Gt,
GtE,
Is,
IsNot,
In,
NotIn,
}
// https://docs.python.org/3/library/ast.html#ast.Lambda
#[derive(Debug, Clone)]
pub struct Lambda {
pub node: Node,
pub args: Arguments,
pub body: Expression,
}
// https://docs.python.org/3/library/ast.html#ast.arguments
#[derive(Debug, Clone)]
pub struct Arguments {
pub node: Node,
pub posonlyargs: Vec<Arg>,
pub args: Vec<Arg>,
pub vararg: Option<Arg>,
pub kwonlyargs: Vec<Arg>,
pub kw_defaults: Vec<Option<Expression>>,
pub kwarg: Option<Arg>,
pub defaults: Vec<Expression>,
}
impl Arguments {
pub fn len(&self) -> usize {
self.posonlyargs.len()
+ self.args.len()
+ self.kwonlyargs.len()
+ if self.vararg.is_some() { 1 } else { 0 }
+ if self.kwarg.is_some() { 1 } else { 0 }
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl IntoIterator for Arguments {
type Item = Arg;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
let mut args = self.posonlyargs;
args.extend(self.args);
if let Some(vararg) = self.vararg {
args.push(vararg);
}
args.extend(self.kwonlyargs);
args.into_iter()
}
}
impl std::fmt::Display for Arguments {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut args = vec![];
for arg in &self.args {
args.push(arg.arg.clone());
}
for arg in &self.kwonlyargs {
args.push(arg.arg.clone());
}
if let Some(vararg) = &self.vararg {
args.push(vararg.arg.clone());
}
if let Some(kwarg) = &self.kwarg {
args.push(kwarg.arg.clone());
}
write!(f, "({})", args.join(", "))
}
}
// https://docs.python.org/3/library/ast.html#ast.arg
#[derive(Debug, Clone)]
pub struct Arg {
pub node: Node,
pub arg: String,
pub annotation: Option<Expression>,
}
// https://docs.python.org/3/library/ast.html#ast.IfExp
#[derive(Debug, Clone)]
pub struct IfExp {
pub node: Node,
pub test: Expression,
pub body: Expression,
pub orelse: Expression,
}
// https://docs.python.org/3/library/ast.html#ast.FormattedValue
#[derive(Debug, Clone)]
pub struct FormattedValue {
pub node: Node,
pub value: Expression,
pub conversion: i32,
pub format_spec: Option<Expression>,
}
// https://docs.python.org/3/library/ast.html#ast.JoinedStr
#[derive(Debug, Clone)]
pub struct JoinedStr {
pub node: Node,
pub values: Vec<Expression>,
}
// https://docs.python.org/3/library/ast.html#ast.If
#[derive(Debug, Clone)]
pub struct If {
pub node: Node,
pub test: Expression,
pub body: Vec<Statement>,
pub orelse: Vec<Statement>,
}
impl If {
pub fn update_orelse(&mut self, other_or_else: Vec<Statement>) {
self.orelse = other_or_else;
}
}
// https://docs.python.org/3/library/ast.html#ast.While
#[derive(Debug, Clone)]
pub struct While {
pub node: Node,
pub test: Expression,
pub body: Vec<Statement>,
pub orelse: Vec<Statement>,
}
// https://docs.python.org/3/library/ast.html#ast.For
#[derive(Debug, Clone)]
pub struct For {
pub node: Node,
pub target: Expression,
pub iter: Expression,
pub body: Vec<Statement>,
pub orelse: Vec<Statement>,
}
// https://docs.python.org/3/library/ast.html#ast.AsyncFor
#[derive(Debug, Clone)]
pub struct AsyncFor {
pub node: Node,
pub target: Expression,
pub iter: Expression,
pub body: Vec<Statement>,
pub orelse: Vec<Statement>,
}
// https://docs.python.org/3/library/ast.html#ast.With
#[derive(Debug, Clone)]
pub struct With {
pub node: Node,
pub items: Vec<WithItem>,
pub body: Vec<Statement>,
}
// https://docs.python.org/3/library/ast.html#ast.AsyncWith
#[derive(Debug, Clone)]
pub struct AsyncWith {
pub node: Node,
pub items: Vec<WithItem>,
pub body: Vec<Statement>,
}
// https://docs.python.org/3/library/ast.html#ast.withitem
// can be used for With
#[derive(Debug, Clone)]
pub struct WithItem {
pub node: Node,
pub context_expr: Expression,
pub optional_vars: Option<Expression>,
}
// https://docs.python.org/3/library/ast.html#ast.Try
#[derive(Debug, Clone)]
pub struct Try {
pub node: Node,
pub body: Vec<Statement>,
pub handlers: Vec<ExceptHandler>,
pub orelse: Vec<Statement>,
pub finalbody: Vec<Statement>,
}
// https://docs.python.org/3/library/ast.html#ast.TryStar
#[derive(Debug, Clone)]
pub struct TryStar {
pub node: Node,
pub body: Vec<Statement>,
pub handlers: Vec<ExceptHandler>,
pub orelse: Vec<Statement>,
pub finalbody: Vec<Statement>,
}
// https://docs.python.org/3/library/ast.html#ast.ExceptHandler
#[derive(Debug, Clone)]
pub struct ExceptHandler {
pub node: Node,
pub typ: Option<Expression>,
pub name: Option<String>,
pub body: Vec<Statement>,
}
// https://docs.python.org/3/library/ast.html#functiondef
#[derive(Debug, Clone)]
pub struct FunctionDef {
pub node: Node,
pub name: StrId,
pub args: Arguments,
pub body: Vec<Statement>,
pub decorator_list: Vec<Expression>,
pub returns: Option<Expression>,
pub type_comment: Option<String>,
pub type_params: Vec<TypeParam>,
}
// https://docs.python.org/3/library/ast.html#ast.AsyncFunctionDef
#[derive(Debug, Clone)]
pub struct AsyncFunctionDef {
pub node: Node,
pub name: StrId,
pub args: Arguments,
pub body: Vec<Statement>,
pub decorator_list: Vec<Expression>,
pub returns: Option<Expression>,
pub type_comment: Option<String>,
pub type_params: Vec<TypeParam>,
}
impl AsyncFunctionDef {
#[allow(clippy::too_many_arguments)]
pub fn new(
node: Node,
name: StrId,
args: Arguments,
body: Vec<Statement>,
decorator_list: Vec<Expression>,
returns: Option<Expression>,
type_comment: Option<&str>,
type_params: Vec<TypeParam>,
) -> Self {
Self {
node,
name,
args,
body,
decorator_list,
returns,
type_comment: type_comment.map(|s| s.to_owned()),
type_params,
}
}
pub fn to_function_def(&self) -> FunctionDef {
FunctionDef {
node: self.node,
name: self.name,
args: self.args.clone(),
body: self.body.clone(),
decorator_list: self.decorator_list.clone(),
returns: self.returns.clone(),
type_comment: self.type_comment.clone(),
type_params: self.type_params.clone(),
}
}
}
// https://docs.python.org/3/library/ast.html#ast.ClassDef
#[derive(Debug, Clone)]
pub struct ClassDef {
pub node: Node,
pub name: StrId,
pub bases: Vec<Expression>,
pub keywords: Vec<Keyword>,
pub body: Vec<Statement>,
pub decorator_list: Vec<Expression>,
pub type_params: Vec<TypeParam>,