forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_ast.cs
More file actions
executable file
·3075 lines (2575 loc) · 107 KB
/
_ast.cs
File metadata and controls
executable file
·3075 lines (2575 loc) · 107 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
//
// Copyright (c) Jeff Hardy 2010.
// Copyright (c) Dan Eloff 2008-2009.
//
using System;
using System.Collections;
using System.Collections.Generic;
using Generic = System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Compiler;
using IronPython.Compiler.Ast;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using System.Runtime.InteropServices;
using AstExpression = IronPython.Compiler.Ast.Expression;
[assembly: PythonModule("_ast", typeof(IronPython.Modules._ast))]
namespace IronPython.Modules
{
public static class _ast
{
public const string __version__ = "62047";
public const int PyCF_ONLY_AST = 0x400;
private class ThrowingErrorSink : ErrorSink
{
public static new readonly ThrowingErrorSink/*!*/ Default = new ThrowingErrorSink();
private ThrowingErrorSink() {
}
public override void Add(SourceUnit sourceUnit, string message, SourceSpan span, int errorCode, Severity severity) {
if (severity == Severity.Warning) {
PythonOps.SyntaxWarning(message, sourceUnit, span, errorCode);
} else {
throw PythonOps.SyntaxError(message, sourceUnit, span, errorCode);
}
}
}
internal static PythonAst ConvertToPythonAst(CodeContext codeContext, AST source, string filename) {
Statement stmt;
PythonCompilerOptions options = new PythonCompilerOptions(ModuleOptions.ExecOrEvalCode);
SourceUnit unit = new SourceUnit(codeContext.LanguageContext, NullTextContentProvider.Null, filename, SourceCodeKind.AutoDetect);
CompilerContext compilerContext = new CompilerContext(unit, options, ErrorSink.Default);
bool printExpression = false;
if (source is Expression) {
Expression exp = (Expression)source;
stmt = new ReturnStatement(expr.Revert(exp.body));
} else if (source is Module) {
Module module = (Module)source;
stmt = _ast.stmt.RevertStmts(module.body);
} else if (source is Interactive) {
Interactive interactive = (Interactive)source;
stmt = _ast.stmt.RevertStmts(interactive.body);
printExpression = true;
} else
throw PythonOps.TypeError("unsupported type of AST: {0}",(source.GetType()));
return new PythonAst(stmt, false, ModuleOptions.ExecOrEvalCode, printExpression, compilerContext, new int[] {} );
}
internal static AST BuildAst(CodeContext context, SourceUnit sourceUnit, PythonCompilerOptions opts, string mode) {
using (Parser parser = Parser.CreateParser(
new CompilerContext(sourceUnit, opts, ThrowingErrorSink.Default),
(PythonOptions)context.LanguageContext.Options)) {
PythonAst ast = parser.ParseFile(true);
return ConvertToAST(ast, mode);
}
}
private static mod ConvertToAST(PythonAst pythonAst, string kind) {
ContractUtils.RequiresNotNull(pythonAst, nameof(pythonAst));
ContractUtils.RequiresNotNull(kind, nameof(kind));
return ConvertToAST((SuiteStatement)pythonAst.Body, kind);
}
private static mod ConvertToAST(SuiteStatement suite, string kind) {
ContractUtils.RequiresNotNull(suite, nameof(suite));
ContractUtils.RequiresNotNull(kind, nameof(kind));
switch (kind) {
case "exec":
return new Module(suite);
case "eval":
return new Expression(suite);
case "single":
return new Interactive(suite);
default:
throw new ArgumentException("kind must be 'exec' or 'eval' or 'single'");
}
}
[PythonType]
public abstract class AST
{
protected int? _lineno; // both lineno and col_offset are expected to be int, in cpython anything is accepted
protected int? _col_offset;
public PythonTuple _fields { get; protected set; } = new PythonTuple();
public PythonTuple _attributes { get; protected set; } = new PythonTuple();
public int lineno {
get {
if (_lineno != null) return (int)_lineno;
throw PythonOps.AttributeErrorForMissingAttribute(PythonTypeOps.GetName(this), "lineno");
}
set { _lineno = value; }
}
public int col_offset {
get {
if (_col_offset != null) return (int)_col_offset;
throw PythonOps.AttributeErrorForMissingAttribute(PythonTypeOps.GetName(this), "col_offset");
}
set { _col_offset = value; }
}
public void __setstate__(PythonDictionary state) {
restoreProperties(_attributes, state);
restoreProperties(_fields, state);
}
internal void restoreProperties(IEnumerable<object> names, IDictionary source) {
foreach (object name in names) {
if (name is string) {
try {
string key = (string)name;
this.GetType().GetProperty(key).SetValue(this, source[key], null);
} catch (Generic.KeyNotFoundException) {
// ignore missing
}
}
}
}
internal void storeProperties(IEnumerable<object> names, IDictionary target) {
foreach (object name in names) {
if (name is string) {
string key = (string)name;
object val;
try {
val = this.GetType().GetProperty(key).GetValue(this, null);
target.Add(key, val);
} catch (System.Reflection.TargetInvocationException) {
// field not set
}
}
}
}
internal PythonDictionary getstate() {
PythonDictionary d = new PythonDictionary(10);
storeProperties(_fields, d);
storeProperties(_attributes, d);
return d;
}
public virtual object/*!*/ __reduce__() {
return PythonTuple.MakeTuple(DynamicHelpers.GetPythonType(this), new PythonTuple(), getstate());
}
public virtual object/*!*/ __reduce_ex__(int protocol) {
return __reduce__();
}
protected void GetSourceLocation(Node node) {
_lineno = node.Start.Line;
// IronPython counts from 1; CPython counts from 0
_col_offset = node.Start.Column - 1;
}
internal static PythonList ConvertStatements(Statement stmt) {
return ConvertStatements(stmt, false);
}
internal static PythonList ConvertStatements(Statement stmt, bool allowNull) {
if (stmt == null)
if (allowNull)
return PythonOps.MakeEmptyList(0);
else
throw new ArgumentNullException(nameof(stmt));
if (stmt is SuiteStatement) {
SuiteStatement suite = (SuiteStatement)stmt;
PythonList list = PythonOps.MakeEmptyList(suite.Statements.Count);
foreach (Statement s in suite.Statements)
if (s is SuiteStatement) // multiple stmt in a line
foreach (Statement s2 in ((SuiteStatement)s).Statements)
list.Add(Convert(s2));
else
list.Add(Convert(s));
return list;
}
return PythonOps.MakeListNoCopy(Convert(stmt));
}
internal static stmt Convert(Statement stmt) {
stmt ast;
if (stmt is FunctionDefinition)
ast = new FunctionDef((FunctionDefinition)stmt);
else if (stmt is ReturnStatement)
ast = new Return((ReturnStatement)stmt);
else if (stmt is AssignmentStatement)
ast = new Assign((AssignmentStatement)stmt);
else if (stmt is AugmentedAssignStatement)
ast = new AugAssign((AugmentedAssignStatement)stmt);
else if (stmt is DelStatement)
ast = new Delete((DelStatement)stmt);
else if (stmt is ExpressionStatement)
ast = new Expr((ExpressionStatement)stmt);
else if (stmt is ForStatement)
ast = new For((ForStatement)stmt);
else if (stmt is WhileStatement)
ast = new While((WhileStatement)stmt);
else if (stmt is IfStatement)
ast = new If((IfStatement)stmt);
else if (stmt is WithStatement)
ast = new With((WithStatement)stmt);
else if (stmt is RaiseStatement)
ast = new Raise((RaiseStatement)stmt);
else if (stmt is TryStatement)
ast = Convert((TryStatement)stmt);
else if (stmt is AssertStatement)
ast = new Assert((AssertStatement)stmt);
else if (stmt is ImportStatement)
ast = new Import((ImportStatement)stmt);
else if (stmt is FromImportStatement)
ast = new ImportFrom((FromImportStatement)stmt);
else if (stmt is GlobalStatement)
ast = new Global((GlobalStatement)stmt);
else if (stmt is ClassDefinition)
ast = new ClassDef((ClassDefinition)stmt);
else if (stmt is BreakStatement)
ast = new Break();
else if (stmt is ContinueStatement)
ast = new Continue();
else if (stmt is EmptyStatement)
ast = new Pass();
else
throw new ArgumentTypeException("Unexpected statement type: " + stmt.GetType());
ast.GetSourceLocation(stmt);
return ast;
}
internal static stmt Convert(TryStatement stmt) {
if (stmt.Finally != null) {
PythonList body;
if (stmt.Handlers != null && stmt.Handlers.Count != 0) {
stmt tryExcept = new TryExcept(stmt);
tryExcept.GetSourceLocation(stmt);
body = PythonOps.MakeListNoCopy(tryExcept);
} else
body = ConvertStatements(stmt.Body);
return new TryFinally(body, ConvertStatements(stmt.Finally));
}
return new TryExcept(stmt);
}
internal static PythonList ConvertAliases(IList<DottedName> names, IList<string> asnames) {
PythonList list = PythonOps.MakeEmptyList(names.Count);
if (names == FromImportStatement.Star) // does it ever happen?
list.Add(new alias("*", null));
else
for (int i = 0; i < names.Count; i++)
list.Add(new alias(names[i].MakeString(), asnames[i]));
return list;
}
internal static PythonList ConvertAliases(IList<string> names, IList<string> asnames) {
PythonList list = PythonOps.MakeEmptyList(names.Count);
if (names == FromImportStatement.Star)
list.Add(new alias("*", null));
else
for (int i = 0; i < names.Count; i++)
list.Add(new alias(names[i], asnames[i]));
return list;
}
internal static slice TrySliceConvert(AstExpression expr) {
if (expr is SliceExpression)
return new Slice((SliceExpression)expr);
if (expr is ConstantExpression && ((ConstantExpression)expr).Value == PythonOps.Ellipsis)
return Ellipsis.Instance;
if (expr is TupleExpression && ((TupleExpression)expr).IsExpandable)
return new ExtSlice(((Tuple)Convert(expr)).elts);
return null;
}
internal static expr Convert(AstExpression expr) {
return Convert(expr, Load.Instance);
}
internal static expr Convert(AstExpression expr, expr_context ctx) {
expr ast;
if (expr is ConstantExpression)
ast = Convert((ConstantExpression)expr);
else if (expr is NameExpression)
ast = new Name((NameExpression)expr, ctx);
else if (expr is UnaryExpression) {
var unaryOp = new UnaryOp((UnaryExpression)expr);
ast = unaryOp.TryTrimTrivialUnaryOp();
} else if (expr is BinaryExpression)
ast = Convert((BinaryExpression)expr);
else if (expr is AndExpression)
ast = new BoolOp((AndExpression)expr);
else if (expr is OrExpression)
ast = new BoolOp((OrExpression)expr);
else if (expr is CallExpression)
ast = new Call((CallExpression)expr);
else if (expr is ParenthesisExpression)
return Convert(((ParenthesisExpression)expr).Expression);
else if (expr is LambdaExpression)
ast = new Lambda((LambdaExpression)expr);
else if (expr is ListExpression)
ast = new List((ListExpression)expr, ctx);
else if (expr is TupleExpression)
ast = new Tuple((TupleExpression)expr, ctx);
else if (expr is DictionaryExpression)
ast = new Dict((DictionaryExpression)expr);
else if (expr is ListComprehension)
ast = new ListComp((ListComprehension)expr);
else if (expr is GeneratorExpression)
ast = new GeneratorExp((GeneratorExpression)expr);
else if (expr is MemberExpression)
ast = new Attribute((MemberExpression)expr, ctx);
else if (expr is YieldExpression yieldExpression)
ast = yieldExpression.IsYieldFrom ? (expr)new YieldFrom(yieldExpression) : new Yield(yieldExpression);
else if (expr is ConditionalExpression)
ast = new IfExp((ConditionalExpression)expr);
else if (expr is IndexExpression)
ast = new Subscript((IndexExpression)expr, ctx);
else if (expr is SetExpression)
ast = new Set((SetExpression)expr);
else if (expr is DictionaryComprehension)
ast = new DictComp((DictionaryComprehension)expr);
else if (expr is SetComprehension)
ast = new SetComp((SetComprehension)expr);
else if (expr is StarredExpression)
ast = new Starred((StarredExpression)expr, ctx);
else
throw new ArgumentTypeException("Unexpected expression type: " + expr.GetType());
ast.GetSourceLocation(expr);
return ast;
}
internal static expr Convert(ConstantExpression expr) {
expr ast;
if (expr.Value == null || expr.Value is bool)
return new NameConstant(expr.Value);
if (expr.Value is int || expr.Value is double || expr.Value is Int64 || expr.Value is BigInteger || expr.Value is Complex)
ast = new Num(expr.Value);
else if (expr.Value is string)
ast = new Str((string)expr.Value);
else if (expr.Value is IronPython.Runtime.Bytes)
ast = new Str(Converter.ConvertToString(expr.Value));
else
throw new ArgumentTypeException("Unexpected constant type: " + expr.Value.GetType());
return ast;
}
internal static expr Convert(BinaryExpression expr) {
AST op = Convert(expr.Operator);
if (BinaryExpression.IsComparison(expr)) {
return new Compare(expr);
}
if (op is @operator) {
return new BinOp(expr, (@operator)op);
}
throw new ArgumentTypeException("Unexpected operator type: " + op.GetType());
}
internal static AST Convert(Node node) {
AST ast;
if (node is TryStatementHandler)
ast = new ExceptHandler((TryStatementHandler)node);
else
throw new ArgumentTypeException("Unexpected node type: " + node.GetType());
ast.GetSourceLocation(node);
return ast;
}
internal static PythonList Convert(IList<ComprehensionIterator> iterators) {
ComprehensionIterator[] iters = new ComprehensionIterator[iterators.Count];
iterators.CopyTo(iters, 0);
PythonList comps = new PythonList();
int start = 1;
for (int i = 0; i < iters.Length; i++) {
if (i == 0 || iters[i] is ComprehensionIf)
if (i == iters.Length - 1)
i++;
else
continue;
ComprehensionIf[] ifs = new ComprehensionIf[i - start];
Array.Copy(iters, start, ifs, 0, ifs.Length);
comps.Add(new comprehension((ComprehensionFor)iters[start - 1], ifs));
start = i + 1;
}
return comps;
}
internal static PythonList Convert(ComprehensionIterator[] iters) {
var cfCollector = new List<ComprehensionFor>();
var cifCollector = new List<List<ComprehensionIf>>();
List<ComprehensionIf> cif = null;
for (int i = 0; i < iters.Length; i++) {
if (iters[i] is ComprehensionFor) {
ComprehensionFor cf = (ComprehensionFor)iters[i];
cfCollector.Add(cf);
cif = new List<ComprehensionIf>();
cifCollector.Add(cif);
} else {
ComprehensionIf ci = (ComprehensionIf)iters[i];
cif.Add(ci);
}
}
PythonList comps = new PythonList();
for (int i = 0; i < cfCollector.Count; i++)
comps.Add(new comprehension(cfCollector[i], cifCollector[i].ToArray()));
return comps;
}
internal static AST Convert(PythonOperator op) {
// We treat operator classes as singletons here to keep overhead down
// But we cannot fully make them singletons if we wish to keep compatibility wity CPython
switch (op) {
case PythonOperator.Add:
return Add.Instance;
case PythonOperator.BitwiseAnd:
return BitAnd.Instance;
case PythonOperator.BitwiseOr:
return BitOr.Instance;
case PythonOperator.TrueDivide:
return Div.Instance;
case PythonOperator.Equal:
return Eq.Instance;
case PythonOperator.FloorDivide:
return FloorDiv.Instance;
case PythonOperator.GreaterThan:
return Gt.Instance;
case PythonOperator.GreaterThanOrEqual:
return GtE.Instance;
case PythonOperator.In:
return In.Instance;
case PythonOperator.Invert:
return Invert.Instance;
case PythonOperator.Is:
return Is.Instance;
case PythonOperator.IsNot:
return IsNot.Instance;
case PythonOperator.LeftShift:
return LShift.Instance;
case PythonOperator.LessThan:
return Lt.Instance;
case PythonOperator.LessThanOrEqual:
return LtE.Instance;
case PythonOperator.Mod:
return Mod.Instance;
case PythonOperator.Multiply:
return Mult.Instance;
case PythonOperator.Negate:
return USub.Instance;
case PythonOperator.Not:
return Not.Instance;
case PythonOperator.NotEqual:
return NotEq.Instance;
case PythonOperator.NotIn:
return NotIn.Instance;
case PythonOperator.Pos:
return UAdd.Instance;
case PythonOperator.Power:
return Pow.Instance;
case PythonOperator.RightShift:
return RShift.Instance;
case PythonOperator.Subtract:
return Sub.Instance;
case PythonOperator.Xor:
return BitXor.Instance;
default:
throw new ArgumentException("Unexpected PythonOperator: " + op, nameof(op));
}
}
}
[PythonType]
public class alias : AST
{
public alias() {
_fields = new PythonTuple(new[] { "name", "asname" });
}
public alias(string name, [Optional]string asname)
: this() {
this.name = name;
this.asname = asname;
}
public string name { get; set; }
public string asname { get; set; }
}
[PythonType("arg")]
public class ArgType : AST
{
public ArgType() {
_fields = new PythonTuple(new[] { "arg", "annotation" });
}
public ArgType(string arg, object annotation) : this() {
this.arg = arg;
this.annotation = annotation;
}
internal ArgType(Parameter parameter) {
arg = parameter.Name;
annotation = Convert(parameter.Annotation);
}
public string arg { get; set; }
public object annotation { get; set; }
}
[PythonType]
public class arguments : AST
{
public arguments() {
_fields = new PythonTuple(new[] { "args", "vararg", "kwonlyargs", "kw_defaults", "kwarg", "defaults" });
}
public arguments(PythonList args, [Optional]string vararg, [Optional]PythonList kwonlyargs, [Optional]PythonList kw_defaults, [Optional]string kwarg, PythonList defaults)
: this() {
this.args = args;
this.vararg = vararg;
this.kwonlyargs = kwonlyargs;
this.kw_defaults = kw_defaults;
this.kwarg = kwarg;
this.defaults = defaults;
}
internal arguments(IList<Parameter> parameters)
: this() {
args = PythonOps.MakeEmptyList(parameters.Count);
defaults = PythonOps.MakeEmptyList(parameters.Count);
foreach (Parameter param in parameters) {
switch (param.Kind) {
case ParameterKind.List:
vararg = param.Name;
break;
case ParameterKind.Dictionary:
kwarg = param.Name;
break;
case ParameterKind.KeywordOnly:
kwonlyargs.Add(new ArgType(param));
kw_defaults.Add(param.DefaultValue == null ? null : Convert(param.DefaultValue));
break;
default:
args.Add(new ArgType(param));
if (param.DefaultValue != null)
defaults.Add(Convert(param.DefaultValue));
break;
}
}
}
internal Parameter[] Revert() {
var parameters = new List<Parameter>();
for (var i = kwonlyargs.Count - 1; i >= 0; i--) {
var kwonlyarg = (ArgType)kwonlyargs[i];
var param = new Parameter(kwonlyarg.arg, ParameterKind.KeywordOnly) {
Annotation = expr.Revert(kwonlyarg.annotation),
DefaultValue = expr.Revert(kw_defaults[i])
};
}
int argIdx = args.Count - 1;
for (int defIdx = defaults.Count - 1; defIdx >= 0; defIdx--, argIdx--) {
var arg = (ArgType)args[argIdx];
parameters.Add(new Parameter(arg.arg) {
Annotation = expr.Revert(arg.annotation),
DefaultValue = expr.Revert(defaults[defIdx])
});
}
while (argIdx >= 0) {
var arg = (ArgType)args[argIdx--];
parameters.Add(new Parameter(arg.arg) {
Annotation = expr.Revert(arg.annotation)
});
}
parameters.Reverse();
if (vararg != null)
parameters.Add(new Parameter(vararg, ParameterKind.List));
if (kwarg != null)
parameters.Add(new Parameter(kwarg, ParameterKind.Dictionary));
return parameters.ToArray();
}
public PythonList args { get; set; }
public string vararg { get; set; }
public PythonList kwonlyargs { get; set; }
public PythonList kw_defaults { get; set; }
public string kwarg { get; set; }
public PythonList defaults { get; set; }
}
[PythonType]
public abstract class boolop : AST
{
}
[PythonType]
public abstract class cmpop : AST
{
internal abstract PythonOperator Revert();
}
[PythonType]
public class comprehension : AST
{
public comprehension() {
_fields = new PythonTuple(new[] { "target", "iter", "ifs" });
}
public comprehension(expr target, expr iter, PythonList ifs)
: this() {
this.target = target;
this.iter = iter;
this.ifs = ifs;
}
internal comprehension(ComprehensionFor listFor, ComprehensionIf[] listIfs)
: this() {
target = Convert(listFor.Left, Store.Instance);
iter = Convert(listFor.List);
ifs = PythonOps.MakeEmptyList(listIfs.Length);
foreach (ComprehensionIf listIf in listIfs)
ifs.Add(Convert(listIf.Test));
}
internal static ComprehensionIterator[] RevertComprehensions(PythonList comprehensions) {
var comprehensionIterators = new List<ComprehensionIterator>();
foreach (comprehension comp in comprehensions) {
ComprehensionFor cf = new ComprehensionFor(expr.Revert(comp.target), expr.Revert(comp.iter));
comprehensionIterators.Add(cf);
foreach (expr ifs in comp.ifs) {
comprehensionIterators.Add(new ComprehensionIf(expr.Revert(ifs)));
}
}
return comprehensionIterators.ToArray();
}
public expr target { get; set; }
public expr iter { get; set; }
public PythonList ifs { get; set; }
}
[PythonType]
public class excepthandler : AST
{
public excepthandler() {
_attributes = new PythonTuple(new[] { "lineno", "col_offset" });
}
}
[PythonType]
public abstract class expr : AST
{
protected expr() {
_attributes = new PythonTuple(new[] { "lineno", "col_offset" });
}
internal virtual AstExpression Revert() {
throw PythonOps.TypeError("Unexpected expr type: {0}", GetType());
}
internal static AstExpression Revert(expr ex) {
return ex?.Revert();
}
internal static AstExpression Revert(object ex) {
if (ex == null)
return null;
Debug.Assert(ex is expr);
return ((expr)ex).Revert();
}
internal static AstExpression[] RevertExprs(PythonList exprs) {
// it is assumed that list elements are expr
AstExpression[] ret = new AstExpression[exprs.Count];
for (int i = 0; i < exprs.Count; i++)
ret[i] = ((expr)exprs[i]).Revert();
return ret;
}
}
[PythonType]
public abstract class expr_context : AST
{
}
[PythonType]
public class keyword : AST
{
public keyword() {
_fields = new PythonTuple(new[] { "arg", "value" });
}
public keyword(string arg, expr value)
: this() {
this.arg = arg;
this.value = value;
}
internal keyword(IronPython.Compiler.Ast.Arg arg)
: this() {
this.arg = arg.Name;
value = Convert(arg.Expression);
}
public string arg { get; set; }
public expr value { get; set; }
}
[PythonType]
public abstract class mod : AST
{
internal abstract PythonList GetStatements();
}
[PythonType]
public abstract class @operator : AST
{
internal abstract PythonOperator Revert();
}
[PythonType]
public abstract class slice : AST
{
}
[PythonType]
public abstract class stmt : AST
{
protected stmt() {
_attributes = new PythonTuple(new[] { "lineno", "col_offset" });
}
internal virtual Statement Revert() {
throw PythonOps.TypeError("Unexpected statement type: {0}", GetType());
}
internal static Statement RevertStmts(PythonList stmts) {
if (stmts.Count == 1)
return ((stmt)stmts[0]).Revert();
Statement[] statements = new Statement[stmts.Count];
for (int i = 0; i < stmts.Count; i++)
statements[i] = ((stmt)stmts[i]).Revert();
return new SuiteStatement(statements);
}
}
[PythonType]
public abstract class unaryop : AST
{
internal abstract PythonOperator Revert();
}
[PythonType]
public class Add : @operator
{
internal static readonly Add Instance = new Add();
internal override PythonOperator Revert() => PythonOperator.Add;
}
[PythonType]
public class And : boolop
{
internal static readonly And Instance = new And();
}
[PythonType]
public class Assert : stmt
{
public Assert() {
_fields = new PythonTuple(new[] { "test", "msg" });
}
public Assert(expr test, expr msg, [Optional]int? lineno, [Optional]int? col_offset)
: this() {
this.test = test;
this.msg = msg;
_lineno = lineno;
_col_offset = col_offset;
}
internal Assert(AssertStatement stmt)
: this() {
test = Convert(stmt.Test);
if (stmt.Message != null)
msg = Convert(stmt.Message);
}
internal override Statement Revert() {
return new AssertStatement(expr.Revert(test), expr.Revert(msg));
}
public expr test { get; set; }
public expr msg { get; set; }
}
[PythonType]
public class Assign : stmt
{
public Assign() {
_fields = new PythonTuple(new[] { "targets", "value" });
}
public Assign(PythonList targets, expr value, [Optional]int? lineno, [Optional]int? col_offset)
: this() {
this.targets = targets;
this.value = value;
_lineno = lineno;
_col_offset = col_offset;
}
internal Assign(AssignmentStatement stmt)
: this() {
targets = PythonOps.MakeEmptyList(stmt.Left.Count);
foreach (AstExpression expr in stmt.Left)
targets.Add(Convert(expr, Store.Instance));
value = Convert(stmt.Right);
}
internal override Statement Revert() {
return new AssignmentStatement(expr.RevertExprs(targets), expr.Revert(value));
}
public PythonList targets { get; set; }
public expr value { get; set; }
}
[PythonType]
public class Attribute : expr
{
public Attribute() {
_fields = new PythonTuple(new[] { "value", "attr", "ctx" });
}
public Attribute(expr value, string attr, expr_context ctx,
[Optional]int? lineno, [Optional]int? col_offset)
: this() {
this.value = value;
this.attr = attr;
this.ctx = ctx;
_lineno = lineno;
_col_offset = col_offset;
}
internal Attribute(MemberExpression attr, expr_context ctx)
: this() {
value = Convert(attr.Target);
this.attr = attr.Name;
this.ctx = ctx;
}
internal override AstExpression Revert() {
return new MemberExpression(expr.Revert(value), attr);
}
public expr value { get; set; }
public string attr { get; set; }
public expr_context ctx { get; set; }
}
[PythonType]
public class AugAssign : stmt
{
public AugAssign() {
_fields = new PythonTuple(new[] { "target", "op", "value" });
}
public AugAssign(expr target, @operator op, expr value,
[Optional]int? lineno, [Optional]int? col_offset)
: this() {
this.target = target;
this.op = op;
this.value = value;
_lineno = lineno;
_col_offset = col_offset;
}
internal AugAssign(AugmentedAssignStatement stmt)
: this() {
target = Convert(stmt.Left, Store.Instance);
value = Convert(stmt.Right);
op = (@operator)Convert(stmt.Operator);
}
internal override Statement Revert() {
return new AugmentedAssignStatement(op.Revert(), expr.Revert(target), expr.Revert(value));
}
public expr target { get; set; }
public @operator op { get; set; }
public expr value { get; set; }
}
/// <summary>
/// Not used.
/// </summary>
[PythonType]
public class AugLoad : expr_context
{
}
/// <summary>
/// Not used.
/// </summary>
[PythonType]
public class AugStore : expr_context
{
}
[PythonType]
public class BinOp : expr
{
public BinOp() {
_fields = new PythonTuple(new[] { "left", "op", "right" });
}
public BinOp(expr left, @operator op, expr right, [Optional]int? lineno, [Optional]int? col_offset)
: this() {
this.left = left;
this.op = op;
this.right = right;
_lineno = lineno;
_col_offset = col_offset;
}
internal BinOp(BinaryExpression expr, @operator op)
: this() {
left = Convert(expr.Left);
right = Convert(expr.Right);
this.op = op;
}
internal override AstExpression Revert() {
return new BinaryExpression(op.Revert(), expr.Revert(left), expr.Revert(right));
}