forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonNameBinder.cs
More file actions
878 lines (741 loc) · 29.3 KB
/
PythonNameBinder.cs
File metadata and controls
878 lines (741 loc) · 29.3 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
// 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.
using MSAst = System.Linq.Expressions;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
/*
* The name binding:
*
* The name binding happens in 4 passes.
*
* The first pass is a full recursive walk of the AST. During this walk, all scopes are established
* (created by functions, classes, comprehensions, generators, and the AST root),
* and in each scope all variables are collected that are defined (local or parameter)
* or declared (global or nonlocal) there. Also, for each scope, all references used in the
* scope are collected but kept unresolved as yet.
*
* The second pass uses the collected stack of all scopes and has each scope resolve its references.
* The references can be resolved locally within the scope or as free variables,
* either as globals or as references to lexically enclosing scopes.
*
* The second pass happens in post-order (a scope is processed after processing all its nested scopes).
* Consequently, when the scope is processing its free variables, it also knows already
* which of its locals are being lifted to the closure.
*
* The third pass goes over all the scopes again, this time in pre-order (except for the root AST).
* In this pass, all scopes build theirs closures, if needed. Becasue nested scopes are processed
* after their encompassing scope, scopes may use the already prepared closure
* from their parent.
*
* During the fourth pass, each scope is being inspected by the FlowChecker,
* which analyzes the data flow in the scope. Information collected during this analysis
* allows for some optimizations later on, when the expression trees are being constructed.
*/
namespace IronPython.Compiler.Ast {
using Ast = MSAst.Expression;
internal class DefineBinder : PythonWalkerNonRecursive {
private PythonNameBinder _binder;
public DefineBinder(PythonNameBinder binder) {
_binder = binder;
}
public override bool Walk(NameExpression node) {
_binder.DefineName(node.Name);
return false;
}
public override bool Walk(ParenthesisExpression node) {
return true;
}
public override bool Walk(TupleExpression node) {
return true;
}
public override bool Walk(ListExpression node) {
return true;
}
}
internal class DeleteBinder : PythonWalkerNonRecursive {
private PythonNameBinder _binder;
public DeleteBinder(PythonNameBinder binder) {
_binder = binder;
}
public override bool Walk(NameExpression node) {
_binder.DefineDeleted(node.Name);
return false;
}
}
internal class PythonNameBinder : PythonWalker {
private PythonAst _globalScope;
internal ScopeStatement _currentScope;
private List<ScopeStatement> _scopes = new List<ScopeStatement>();
private List<ILoopStatement> _loops = new List<ILoopStatement>();
private List<int> _finallyCount = new List<int>();
#region Recursive binders
private readonly DefineBinder _define;
private readonly DeleteBinder _delete;
#endregion
public CompilerContext Context { get; }
private PythonNameBinder(CompilerContext context) {
_define = new DefineBinder(this);
_delete = new DeleteBinder(this);
Context = context;
}
#region Public surface
internal static void BindAst(PythonAst ast, CompilerContext context) {
Assert.NotNull(ast, context);
PythonNameBinder binder = new PythonNameBinder(context);
binder.Bind(ast);
}
#endregion
private void Bind(PythonAst unboundAst) {
Assert.NotNull(unboundAst);
_currentScope = _globalScope = unboundAst;
_finallyCount.Add(0);
// Find all scopes and variables
unboundAst.Walk(this);
// Bind scopes
foreach (ScopeStatement scope in _scopes) {
scope.Bind(this);
}
// Bind globals
unboundAst.Bind(this);
// Finish binding w/ outer most scopes first.
for (int i = _scopes.Count - 1; i >= 0; i--) {
_scopes[i].FinishBind(this);
}
// Finish globals
unboundAst.FinishBind(this);
// Run flow checker
foreach (ScopeStatement scope in _scopes) {
FlowChecker.Check(scope);
}
}
private void PushScope(ScopeStatement node) {
node.Parent = _currentScope;
_currentScope = node;
_finallyCount.Add(0);
}
private void PopScope() {
_scopes.Add(_currentScope);
_currentScope = _currentScope.Parent;
_finallyCount.RemoveAt(_finallyCount.Count - 1);
}
internal PythonReference Reference(string name) {
return _currentScope.Reference(name);
}
internal PythonVariable DefineName(string name) {
return _currentScope.EnsureVariable(name);
}
internal PythonVariable DefineParameter(string name) {
return _currentScope.DefineParameter(name);
}
internal PythonVariable DefineDeleted(string name) {
PythonVariable variable = _currentScope.EnsureVariable(name);
variable.RegisterDeletion();
return variable;
}
internal void ReportSyntaxWarning(string message, Node node) {
Context.Errors.Add(Context.SourceUnit, message, node.Span, ErrorCodes.SyntaxError, Severity.Warning);
}
internal void ReportSyntaxError(string message, Node node) {
Context.Errors.Add(Context.SourceUnit, message, node.Span, ErrorCodes.SyntaxError, Severity.FatalError);
}
#region AstBinder Overrides
// AssignmentStatement
public override bool Walk(AssignmentStatement node) {
node.Parent = _currentScope;
foreach (Expression e in node.Left) {
e.Walk(_define);
}
return true;
}
// AnnotatedAssignStatement
public override bool Walk(AnnotatedAssignStatement node) {
node.Parent = _currentScope;
node.Target.Walk(_define);
return true;
}
// AugmentedAssignStatement
public override bool Walk(AugmentedAssignStatement node) {
node.Parent = _currentScope;
node.Left.Walk(_define);
return true;
}
public override void PostWalk(CallExpression node) {
if (node.NeedsLocalsDictionary()) {
_currentScope.NeedsLocalsDictionary = true;
}
}
// ClassDefinition
public override bool Walk(ClassDefinition node) {
node.PythonVariable = DefineName(node.Name);
// Base references are in the outer context
foreach (var b in node.Bases) b.Walk(this);
foreach (var a in node.Keywords) a.Walk(this);
// process the decorators in the outer context
if (node.Decorators != null) {
foreach (Expression dec in node.Decorators) {
dec.Walk(this);
}
}
PushScope(node);
node.ModuleNameVariable = _globalScope.EnsureGlobalVariable("__name__");
// define the __doc__ and the __module__
if (node.Body.Documentation != null) {
node.DocVariable = DefineName("__doc__");
}
node.ModVariable = DefineName("__module__");
// Walk the body
node.Body.Walk(this);
return false;
}
// ClassDefinition
public override void PostWalk(ClassDefinition node) {
Debug.Assert(node == _currentScope);
PopScope();
}
// DelStatement
public override bool Walk(DelStatement node) {
node.Parent = _currentScope;
foreach (Expression e in node.Expressions) {
e.Walk(_delete);
}
return true;
}
// Comprehensions
private void WalkComprehensionIterators(Comprehension node) {
node.Parent = _currentScope;
// Special walk case: first (outermost) "for" iterator
// See also: PythonAst.LookupVisitor.VisitComprehension(...)
var outermostFor = (ComprehensionFor)node.Iterators[0];
outermostFor.List.Walk(this);
PushScope(node.Scope);
Walk(outermostFor);
outermostFor.Left.Walk(this);
PostWalk(outermostFor);
// Regular walk cases: remaining iterators/conditionals
for (int i = 1; i < node.Iterators.Count; i++) {
node.Iterators[i].Walk(this);
}
}
public override bool Walk(ListComprehension node) {
WalkComprehensionIterators(node);
node.Item.Walk(this);
return false;
}
public override void PostWalk(ListComprehension node) {
base.PostWalk(node);
PopScope();
if (node.Scope.NeedsLocalsDictionary) {
_currentScope.NeedsLocalsDictionary = true;
}
}
public override bool Walk(SetComprehension node) {
WalkComprehensionIterators(node);
node.Item.Walk(this);
return false;
}
public override void PostWalk(SetComprehension node) {
base.PostWalk(node);
PopScope();
if (node.Scope.NeedsLocalsDictionary) {
_currentScope.NeedsLocalsDictionary = true;
}
}
public override bool Walk(DictionaryComprehension node) {
WalkComprehensionIterators(node);
node.Key.Walk(this);
node.Value.Walk(this);
return false;
}
public override void PostWalk(DictionaryComprehension node) {
base.PostWalk(node);
PopScope();
if (node.Scope.NeedsLocalsDictionary) {
_currentScope.NeedsLocalsDictionary = true;
}
}
public override void PostWalk(ConditionalExpression node) {
node.Parent = _currentScope;
base.PostWalk(node);
}
// This is generated by the scripts\generate_walker.py script.
// That will scan all types that derive from the IronPython AST nodes that aren't interesting for scopes
// and inject into here.
#region Generated Python Name Binder Propagate Current Scope
// *** BEGIN GENERATED CODE ***
// generated by function: gen_python_name_binder from: generate_walker.py
// AndExpression
public override bool Walk(AndExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// AssertStatement
public override bool Walk(AssertStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// AsyncForStatement
public override bool Walk(AsyncForStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// AsyncWithStatement
public override bool Walk(AsyncWithStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// AwaitExpression
public override bool Walk(AwaitExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// BinaryExpression
public override bool Walk(BinaryExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ComprehensionIf
public override bool Walk(ComprehensionIf node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ConditionalExpression
public override bool Walk(ConditionalExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ConstantExpression
public override bool Walk(ConstantExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// DictionaryExpression
public override bool Walk(DictionaryExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// DottedName
public override bool Walk(DottedName node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// EmptyStatement
public override bool Walk(EmptyStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ErrorExpression
public override bool Walk(ErrorExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ExpressionStatement
public override bool Walk(ExpressionStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// FormattedValueExpression
public override bool Walk(FormattedValueExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// GeneratorExpression
public override bool Walk(GeneratorExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// IfStatement
public override bool Walk(IfStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// IfStatementTest
public override bool Walk(IfStatementTest node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// IndexExpression
public override bool Walk(IndexExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// JoinedStringExpression
public override bool Walk(JoinedStringExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// Keyword
public override bool Walk(Keyword node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// LambdaExpression
public override bool Walk(LambdaExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ListExpression
public override bool Walk(ListExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// MemberExpression
public override bool Walk(MemberExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ModuleName
public override bool Walk(ModuleName node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// OrExpression
public override bool Walk(OrExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// Parameter
public override bool Walk(Parameter node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ParenthesisExpression
public override bool Walk(ParenthesisExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// RelativeModuleName
public override bool Walk(RelativeModuleName node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// SetExpression
public override bool Walk(SetExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// SliceExpression
public override bool Walk(SliceExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// StarredExpression
public override bool Walk(StarredExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// SuiteStatement
public override bool Walk(SuiteStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// TryStatementHandler
public override bool Walk(TryStatementHandler node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// TupleExpression
public override bool Walk(TupleExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// UnaryExpression
public override bool Walk(UnaryExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// YieldExpression
public override bool Walk(YieldExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// YieldFromExpression
public override bool Walk(YieldFromExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// *** END GENERATED CODE ***
#endregion
public override bool Walk(RaiseStatement node) {
node.Parent = _currentScope;
node.InFinally = _finallyCount[_finallyCount.Count - 1] != 0;
return base.Walk(node);
}
// ForEachStatement
public override bool Walk(ForStatement node) {
node.Parent = _currentScope;
if (_currentScope is FunctionDefinition) {
_currentScope.ShouldInterpret = false;
}
// we only push the loop for the body of the loop
// so we need to walk the for statement ourselves
node.Left.Walk(_define);
node.Left?.Walk(this);
node.List?.Walk(this);
PushLoop(node);
node.Body?.Walk(this);
PopLoop();
node.Else?.Walk(this);
return false;
}
#if DEBUG
private static int _labelId;
#endif
private void PushLoop(ILoopStatement node) {
#if DEBUG
node.BreakLabel = Ast.Label("break" + _labelId++);
node.ContinueLabel = Ast.Label("continue" + _labelId++);
#else
node.BreakLabel = Ast.Label("break");
node.ContinueLabel = Ast.Label("continue");
#endif
_loops.Add(node);
}
private void PopLoop() {
_loops.RemoveAt(_loops.Count - 1);
}
public override bool Walk(WhileStatement node) {
node.Parent = _currentScope;
// we only push the loop for the body of the loop
// so we need to walk the while statement ourselves
node.Test?.Walk(this);
PushLoop(node);
node.Body?.Walk(this);
PopLoop();
node.ElseStatement?.Walk(this);
return false;
}
public override bool Walk(BreakStatement node) {
node.Parent = _currentScope;
node.LoopStatement = _loops[_loops.Count - 1];
return base.Walk(node);
}
public override bool Walk(ContinueStatement node) {
node.Parent = _currentScope;
node.LoopStatement = _loops[_loops.Count - 1];
return base.Walk(node);
}
public override bool Walk(ReturnStatement node) {
node.Parent = _currentScope;
if (_currentScope is FunctionDefinition funcDef) {
funcDef._hasReturn = true;
}
return base.Walk(node);
}
// WithStatement
public override bool Walk(WithStatement node) {
node.Parent = _currentScope;
_currentScope.ContainsExceptionHandling = true;
if (node.Variable != null) {
var assignError = node.Variable.CheckAssign();
if (assignError != null) {
ReportSyntaxError(assignError, node);
}
node.Variable.Walk(_define);
}
return true;
}
// FromImportStatement
public override bool Walk(FromImportStatement node) {
node.Parent = _currentScope;
if (node.Names != FromImportStatement.Star) {
PythonVariable[] variables = new PythonVariable[node.Names.Count];
node.Root.Parent = _currentScope;
for (int i = 0; i < node.Names.Count; i++) {
string name = node.AsNames[i] ?? node.Names[i];
variables[i] = DefineName(name);
}
node.Variables = variables;
} else {
Debug.Assert(_currentScope != null);
_currentScope.ContainsImportStar = true;
_currentScope.NeedsLocalsDictionary = true;
_currentScope.HasLateBoundVariableSets = true;
}
return true;
}
// FunctionDefinition
public override bool Walk(FunctionDefinition node) {
node._nameVariable = _globalScope.EnsureGlobalVariable("__name__");
// Name is defined in the enclosing context
if (!node.IsLambda) {
node.PythonVariable = DefineName(node.Name);
}
// process the default arg values in the outer context
foreach (Parameter p in node.Parameters) {
p.DefaultValue?.Walk(this);
p.Annotation?.Walk(this);
}
// process the decorators in the outer context
if (node.Decorators != null) {
foreach (Expression dec in node.Decorators) {
dec.Walk(this);
}
}
node.ReturnAnnotation?.Walk(this);
PushScope(node);
foreach (Parameter p in node.Parameters) {
p.Parent = _currentScope;
p.PythonVariable = DefineParameter(p.Name);
}
node.Body.Walk(this);
return false;
}
// FunctionDefinition
public override void PostWalk(FunctionDefinition node) {
Debug.Assert(_currentScope == node);
PopScope();
}
// GlobalStatement
public override bool Walk(GlobalStatement node) {
node.Parent = _currentScope;
foreach (string n in node.Names) {
PythonVariable conflict;
// Check current scope for conflicting variable
bool assignedGlobal = false;
if (_currentScope.TryGetVariable(n, out conflict)) {
// conflict?
switch (conflict.Kind) {
case VariableKind.Global:
break;
case VariableKind.Local:
assignedGlobal = true;
ReportSyntaxError($"name '{n}' is assigned to before global declaration", node);
break;
case VariableKind.Parameter:
ReportSyntaxError($"name '{n}' is parameter and global", node);
break;
case VariableKind.Nonlocal:
ReportSyntaxError($"name '{n}' is nonlocal and global", node);
break;
}
}
// Check for the name being referenced previously
if (_currentScope.IsReferenced(n) && !assignedGlobal) {
ReportSyntaxError($"name '{n}' is used prior to global declaration", node);
}
// Create the variable in the global context or mark it as global
PythonVariable variable = _globalScope.EnsureGlobalVariable(n);
if (conflict == null) {
// no previously defined variables, add it to the current scope
_currentScope.AddGlobalVariable(variable);
}
}
return true;
}
public override bool Walk(NameExpression node) {
node.Parent = _currentScope;
node.Reference = Reference(node.Name);
return true;
}
// NonlocalStatement
public override bool Walk(NonlocalStatement node) {
node.Parent = _currentScope;
if (_currentScope == _globalScope)
ReportSyntaxError($"nonlocal declaration not allowed at module level", node);
foreach (string n in node.Names) {
PythonVariable conflict;
// Check current scope for conflicting variable
if (_currentScope.TryGetVariable(n, out conflict)) {
// conflict?
switch (conflict.Kind) {
case VariableKind.Global:
ReportSyntaxError($"name '{n}' is nonlocal and global", node);
break;
case VariableKind.Local:
ReportSyntaxError($"name '{n}' is assigned to before nonlocal declaration", node);
break;
case VariableKind.Parameter:
ReportSyntaxError($"name '{n}' is parameter and nonlocal", node);
break;
case VariableKind.Nonlocal:
// no conflict, name redeclared as nonlocal
break;
}
}
// Check for the name being referenced previously
if (_currentScope.IsReferenced(n) && conflict is null) {
ReportSyntaxError($"name '{n}' is used prior to nonlocal declaration", node);
}
_currentScope.EnsureNonlocalVariable(n, node);
}
return true;
}
// PythonAst
public override bool Walk(PythonAst node) {
Debug.Assert(_currentScope == node);
node.Parent = _currentScope;
node.DocVariable = DefineName("__doc__");
if (node.IsModule) {
node.NameVariable = DefineName("__name__");
node.PackageVariable = DefineName("__package__");
node.SpecVariable = DefineName("__spec__");
node.FileVariable = DefineName("__file__");
// commonly used module variables that we want defined for optimization purposes
DefineName("__path__");
DefineName("__builtins__");
}
return true;
}
// PythonAst
public override void PostWalk(PythonAst node) {
// Do not add the global suite to the list of processed nodes,
// the publishing must be done after the class local binding.
Debug.Assert(_currentScope == node);
Debug.Assert(_currentScope == _currentScope.Parent);
_finallyCount.RemoveAt(_finallyCount.Count - 1);
}
// ImportStatement
public override bool Walk(ImportStatement node) {
node.Parent = _currentScope;
PythonVariable[] variables = new PythonVariable[node.Names.Count];
for (int i = 0; i < node.Names.Count; i++) {
string name = node.AsNames[i] ?? node.Names[i].Names[0];
variables[i] = DefineName(name);
node.Names[i].Parent = _currentScope;
}
node.Variables = variables;
return true;
}
// TryStatement
public override bool Walk(TryStatement node) {
// we manually walk the TryStatement so we can track finally blocks.
node.Parent = _currentScope;
_currentScope.ContainsExceptionHandling = true;
node.Body.Walk(this);
foreach (TryStatementHandler tsh in node.Handlers) {
tsh.Target?.Walk(_define);
tsh.Parent = _currentScope;
tsh.Walk(this);
}
node.Else?.Walk(this);
if (node.Finally != null) {
_finallyCount[_finallyCount.Count - 1]++;
node.Finally.Walk(this);
_finallyCount[_finallyCount.Count - 1]--;
}
return false;
}
// ListComprehensionFor
public override bool Walk(ComprehensionFor node) {
node.Parent = _currentScope;
node.Left.Walk(_define);
return true;
}
// CallExpression
public override bool Walk(CallExpression node) {
node.Parent = _currentScope;
if (node.Target is NameExpression nameExpr && nameExpr.Name == "super"
&& _currentScope is not ClassDefinition
&& node.Args.Count == 0 && node.Kwargs.Count == 0) {
_currentScope.ContainsSuperCall = true;
}
return true;
}
#endregion
}
}