Repository navigation
Expand file tree
/
Copy path_ast.cs
More file actions
executable file
·3638 lines (3083 loc) · 121 KB
/
Copy path_ast.cs
File metadata and controls
executable file
·3638 lines (3083 loc) · 121 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ****************************************************************************
*
* Copyright (c) Jeff Hardy 2010.
* Copyright (c) Dan Eloff 2008-2009.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using Generic = System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using IronPython.Compiler;
using IronPython.Compiler.Ast;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using IronPython.Runtime.Exceptions;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using PyOperator = IronPython.Compiler.PythonOperator;
using PythonList = IronPython.Runtime.List;
using System.Runtime.InteropServices;
using AstExpression = IronPython.Compiler.Ast.Expression;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
using Complex = Microsoft.Scripting.Math.Complex64;
#endif
[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 ) {
Statement stmt;
PythonCompilerOptions options = new PythonCompilerOptions(ModuleOptions.ExecOrEvalCode);
SourceUnit unit = new SourceUnit(codeContext.LanguageContext, NullTextContentProvider.Null, "", 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) {
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, "pythonAst");
ContractUtils.RequiresNotNull(kind, "kind");
return ConvertToAST((SuiteStatement)pythonAst.Body, kind);
}
private static mod ConvertToAST(SuiteStatement suite, string kind) {
ContractUtils.RequiresNotNull(suite, "suite");
ContractUtils.RequiresNotNull(kind, "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
{
private PythonTuple __fields = new PythonTuple(); // Genshi assumes _fields in not None
private PythonTuple __attributes = new PythonTuple(); // Genshi assumes _fields in not None
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 { return __fields; }
protected set { __fields = value; }
}
public PythonTuple _attributes {
get { return __attributes; }
protected set { __attributes = value; }
}
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("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 ExecStatement)
ast = new Exec((ExecStatement)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)
ast = new Yield((YieldExpression)expr);
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 BackQuoteExpression)
ast = new Repr((BackQuoteExpression)expr);
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
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)
return new Name("None", Load.Instance);
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);
} else {
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) {
Generic.List<ComprehensionFor> cfCollector =
new Generic.List<ComprehensionFor>();
Generic.List<Generic.List<ComprehensionIf>> cifCollector =
new Generic.List<Generic.List<ComprehensionIf>>();
Generic.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 Generic.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(PyOperator 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 PyOperator.Add:
return Add.Instance;
case PyOperator.BitwiseAnd:
return BitAnd.Instance;
case PyOperator.BitwiseOr:
return BitOr.Instance;
case PyOperator.Divide:
return Div.Instance;
case PyOperator.Equal:
return Eq.Instance;
case PyOperator.FloorDivide:
return FloorDiv.Instance;
case PyOperator.GreaterThan:
return Gt.Instance;
case PyOperator.GreaterThanOrEqual:
return GtE.Instance;
case PyOperator.In:
return In.Instance;
case PyOperator.Invert:
return Invert.Instance;
case PyOperator.Is:
return Is.Instance;
case PyOperator.IsNot:
return IsNot.Instance;
case PyOperator.LeftShift:
return LShift.Instance;
case PyOperator.LessThan:
return Lt.Instance;
case PyOperator.LessThanOrEqual:
return LtE.Instance;
case PyOperator.Mod:
return Mod.Instance;
case PyOperator.Multiply:
return Mult.Instance;
case PyOperator.Negate:
return USub.Instance;
case PyOperator.Not:
return Not.Instance;
case PyOperator.NotEqual:
return NotEq.Instance;
case PyOperator.NotIn:
return NotIn.Instance;
case PyOperator.Pos:
return UAdd.Instance;
case PyOperator.Power:
return Pow.Instance;
case PyOperator.RightShift:
return RShift.Instance;
case PyOperator.Subtract:
return Sub.Instance;
case PyOperator.Xor:
return BitXor.Instance;
default:
throw new ArgumentException("Unexpected PyOperator: " + op, "op");
}
}
}
[PythonType]
public class alias : AST
{
private string _name;
private string _asname; // Optional
public alias() {
_fields = new PythonTuple(new[] { "name", "asname" });
}
internal alias(string name, [Optional]string asname)
: this() {
_name = name;
_asname = asname;
}
public string name {
get { return _name; }
set { _name = value; }
}
public string asname {
get { return _asname; }
set { _asname = value; }
}
}
[PythonType]
public class arguments : AST
{
private PythonList _args;
private string _vararg; // Optional
private string _kwarg; // Optional
private PythonList _defaults;
public arguments() {
_fields = new PythonTuple(new[] { "args", "vararg", "kwarg", "defaults" });
}
public arguments(PythonList args, [Optional]string vararg, [Optional]string kwarg, PythonList defaults)
:this() {
_args = args;
_vararg = vararg;
_kwarg = kwarg;
_kwarg = kwarg;
_defaults = defaults;
}
internal arguments(IList<Parameter> parameters)
: this() {
_args = PythonOps.MakeEmptyList(parameters.Count);
_defaults = PythonOps.MakeEmptyList(parameters.Count);
foreach (Parameter param in parameters) {
if (param.IsList)
_vararg = param.Name;
else if (param.IsDictionary)
_kwarg = param.Name;
else {
args.Add(new Name(param));
if (param.DefaultValue != null)
defaults.Add(Convert(param.DefaultValue));
}
}
}
internal arguments(Parameter[] parameters)
: this(parameters as IList<Parameter>) {
}
internal Parameter[] Revert() {
List<Parameter> parameters = new List<Parameter>();
int argIdx = args.Count - 1;
for (int defIdx = defaults.Count - 1; defIdx >= 0; defIdx--, argIdx--) {
Name name = (Name)args[argIdx];
Parameter p = new Parameter(name.id);
p.DefaultValue = expr.Revert(defaults[defIdx]);
parameters.Add(p);
}
while (argIdx >= 0) {
Name name = (Name)args[argIdx--];
parameters.Add(new Parameter(name.id));
}
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 { return _args; }
set { _args = value; }
}
public string vararg {
get { return _vararg; }
set { _vararg = value; }
}
public string kwarg {
get { return _kwarg; }
set { _kwarg = value; }
}
public PythonList defaults {
get { return _defaults; }
set { _defaults = value; }
}
}
[PythonType]
public abstract class boolop : AST
{
}
[PythonType]
public abstract class cmpop : AST
{
internal PythonOperator Revert() {
if (this == Eq.Instance)
return PyOperator.Equal;
if (this == Gt.Instance)
return PyOperator.GreaterThan;
if (this == GtE.Instance)
return PyOperator.GreaterThanOrEqual;
if (this == In.Instance)
return PyOperator.In;
if (this == Is.Instance)
return PyOperator.Is;
if (this == IsNot.Instance)
return PyOperator.IsNot;
if (this == Lt.Instance)
return PyOperator.LessThan;
if (this == LtE.Instance)
return PyOperator.LessThanOrEqual;
if (this == NotEq.Instance)
return PythonOperator.NotEqual;
if (this == NotIn.Instance)
return PythonOperator.NotIn;
throw PythonOps.TypeError("Unexpected compare operator: {0}", GetType());
}
}
[PythonType]
public class comprehension : AST
{
private expr _target;
private expr _iter;
private PythonList _ifs;
public comprehension() {
_fields = new PythonTuple(new[] { "target", "iter", "ifs" });
}
public comprehension(expr target, expr iter, PythonList ifs)
: this() {
_target = target;
_iter = iter;
_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) {
Generic.List<ComprehensionIterator> comprehensionIterators =
new Generic.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 { return _target; }
set { _target = value; }
}
public expr iter {
get { return _iter; }
set { _iter = value; }
}
public PythonList ifs {
get { return _ifs; }
set { _ifs = value; }
}
}
[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) {
if (ex == null)
return null;
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
{
private string _arg;
private expr _value;
public keyword() {
_fields = new PythonTuple(new[] { "arg", "value" });
}
public keyword(string arg, expr value)
: this() {
_arg = arg;
_value = value;
}
internal keyword(IronPython.Compiler.Ast.Arg arg)
: this() {
_arg = arg.Name;
_value = Convert(arg.Expression);
}
public string arg {
get { return _arg; }
set { _arg = value; }
}
public expr value {
get { return _value; }
set { _value = value; }
}
}
[PythonType]
public abstract class mod : AST
{
internal abstract PythonList GetStatements();
}
[PythonType]
public abstract class @operator : AST
{
internal PythonOperator Revert() {
if (this == Add.Instance)
return PythonOperator.Add;
if (this == BitAnd.Instance)
return PyOperator.BitwiseAnd;
if (this == BitOr.Instance)
return PyOperator.BitwiseOr;
if (this == Div.Instance)
return PyOperator.Divide;
if (this == FloorDiv.Instance)
return PyOperator.FloorDivide;
if (this == LShift.Instance)
return PyOperator.LeftShift;
if (this == Mod.Instance)
return PythonOperator.Mod;
if (this == Mult.Instance)
return PythonOperator.Multiply;
if (this == Pow.Instance)
return PythonOperator.Power;
if (this == RShift.Instance)
return PyOperator.RightShift;
if (this == Sub.Instance)
return PythonOperator.Subtract;
if (this == BitXor.Instance)
return PythonOperator.Xor;
throw PythonOps.TypeError("Unexpected unary operator: {0}", GetType());
}
}
[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 PyOperator Revert() {
if (this == Invert.Instance)
return PyOperator.Invert;
if (this == USub.Instance)
return PythonOperator.Negate;
if (this == Not.Instance)
return PythonOperator.Not;
if (this == UAdd.Instance)
return PythonOperator.Pos;
throw PythonOps.TypeError("Unexpected unary operator: {0}", GetType());
}
}
[PythonType]
public class Add : @operator
{
internal static Add Instance = new Add();
}
[PythonType]
public class And : boolop
{
internal static And Instance = new And();
}
[PythonType]
public class Assert : stmt
{
private expr _test;
private expr _msg; // Optional
public Assert() {
_fields = new PythonTuple(new[] { "test", "msg" });
}
public Assert(expr test, expr msg, [Optional]int? lineno, [Optional]int? col_offset)
: this() {
_test = test;
_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 { return _test; }
set { _test = value; }
}
public expr msg {
get { return _msg; }
set { _msg = value; }
}
}
[PythonType]
public class Assign : stmt
{
private PythonList _targets;
private expr _value;
public Assign() {
_fields = new PythonTuple(new[] { "targets", "value" });
}
public Assign(PythonList targets, expr value, [Optional]int? lineno, [Optional]int? col_offset)
: this() {
_targets = targets;
_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 { return _targets; }