forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsymboltable.rs
More file actions
3126 lines (2917 loc) · 124 KB
/
Copy pathsymboltable.rs
File metadata and controls
3126 lines (2917 loc) · 124 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
/* Python code is pre-scanned for symbols in the ast.
This ensures that global and nonlocal keywords are picked up.
Then the compiler can use the symbol table to generate proper
load and store instructions for names.
Inspirational file: https://github.com/python/cpython/blob/main/Python/symtable.c
*/
use crate::{
IndexMap, IndexSet,
error::{CodegenError, CodegenErrorType},
};
use alloc::{borrow::Cow, fmt};
use bitflags::bitflags;
use ruff_python_ast as ast;
use ruff_text_size::{Ranged, TextRange};
use rustpython_compiler_core::{PositionEncoding, SourceFile, SourceLocation};
/// Captures all symbols in the current scope, and has a list of sub-scopes in this scope.
#[derive(Clone)]
pub struct SymbolTable {
/// The name of this symbol table. Often the name of the class or function.
pub name: String,
/// The type of symbol table
pub typ: CompilerScope,
/// The line number in the source code where this symboltable begins.
pub line_number: u32,
// Return True if the block is a nested class or function
pub is_nested: bool,
/// Whether this function-like scope was created directly in a class block.
pub is_method: bool,
/// A set of symbols present on this scope level.
pub symbols: IndexMap<String, Symbol>,
/// A list of sub-scopes in the order as found in the
/// AST nodes.
pub sub_tables: Vec<Self>,
/// Cursor pointing to the next sub-table to consume during compilation.
pub next_sub_table: usize,
/// Variable names in definition order (parameters first, then locals)
pub varnames: Vec<String>,
/// Whether this class scope needs an implicit __class__ cell
pub needs_class_closure: bool,
/// Whether this class scope needs an implicit __classdict__ cell
pub needs_classdict: bool,
/// Whether this type param scope can see the parent class scope
pub can_see_class_scope: bool,
/// Whether this scope contains yield/yield from (is a generator function)
pub is_generator: bool,
/// Whether this scope contains await or async comprehension machinery.
pub is_coroutine: bool,
/// Whether this comprehension scope should be inlined (PEP 709)
/// True for list/set/dict comprehensions in non-generator expressions
pub comp_inlined: bool,
/// PEP 649: Reference to annotation scope for this block
/// Annotations are compiled as a separate `__annotate__` function
pub annotation_block: Option<Box<Self>>,
/// True only for deferred function/class/module annotation scopes that
/// should resolve outer names as if they were siblings of the owning
/// function body, matching CPython's PEP 649 lookup rules.
pub skip_enclosing_function_scope: bool,
/// PEP 649: Whether this scope has conditional annotations
/// (annotations inside if/for/while/etc. blocks or at module level)
pub has_conditional_annotations: bool,
/// Whether `from __future__ import annotations` is active
pub future_annotations: bool,
/// Names of type parameters that should still be mangled in type param scopes.
/// When Some, only names in this set are mangled; other names are left unmangled.
/// Set on type param blocks for generic classes; inherited by non-class child scopes.
pub mangled_names: Option<IndexSet<String>>,
}
impl SymbolTable {
fn new(name: String, typ: CompilerScope, line_number: u32, is_nested: bool) -> Self {
Self {
name,
typ,
line_number,
is_nested,
is_method: false,
symbols: IndexMap::default(),
sub_tables: vec![],
next_sub_table: 0,
varnames: Vec::new(),
needs_class_closure: false,
needs_classdict: false,
can_see_class_scope: false,
is_generator: false,
is_coroutine: false,
comp_inlined: false,
annotation_block: None,
skip_enclosing_function_scope: false,
has_conditional_annotations: false,
future_annotations: false,
mangled_names: None,
}
}
pub fn scan_program(
program: &ast::ModModule,
source_file: SourceFile,
) -> SymbolTableResult<Self> {
let mut builder = SymbolTableBuilder::new(source_file);
builder.scan_statements(program.body.as_ref())?;
builder.finish()
}
pub fn scan_expr(
expr: &ast::ModExpression,
source_file: SourceFile,
) -> SymbolTableResult<Self> {
let mut builder = SymbolTableBuilder::new(source_file);
builder.scan_expression(expr.body.as_ref(), ExpressionContext::Load)?;
builder.finish()
}
#[must_use]
pub fn lookup(&self, name: &str) -> Option<&Symbol> {
self.symbols.get(name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompilerScope {
Module,
Class,
Function,
AsyncFunction,
Lambda,
Comprehension,
TypeParams,
/// PEP 649: Annotation scope for deferred evaluation
Annotation,
}
impl fmt::Display for CompilerScope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Module => write!(f, "module"),
Self::Class => write!(f, "class"),
Self::Function => write!(f, "function"),
Self::AsyncFunction => write!(f, "async function"),
Self::Lambda => write!(f, "lambda"),
Self::Comprehension => write!(f, "comprehension"),
Self::TypeParams => write!(f, "type parameter"),
Self::Annotation => write!(f, "annotation"),
// TODO missing types from the C implementation
// if self._table.type == _symtable.TYPE_TYPE_VAR_BOUND:
// return "TypeVar bound"
// if self._table.type == _symtable.TYPE_TYPE_ALIAS:
// return "type alias"
}
}
}
/// Indicator for a single symbol what the scope of this symbol is.
/// The scope can be unknown, which is unfortunate, but not impossible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolScope {
Unknown,
Local,
GlobalExplicit,
GlobalImplicit,
Free,
Cell,
}
bitflags! {
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct SymbolFlags: u16 {
const REFERENCED = 0x001; // USE
const ASSIGNED = 0x002; // DEF_LOCAL
const PARAMETER = 0x004; // DEF_PARAM
const ANNOTATED = 0x008; // DEF_ANNOT
const IMPORTED = 0x010; // DEF_IMPORT
const NONLOCAL = 0x020; // DEF_NONLOCAL
// indicates if the symbol gets a value assigned by a named expression in a comprehension
// this is required to correct the scope in the analysis.
const ASSIGNED_IN_COMPREHENSION = 0x040;
// indicates that the symbol is used a bound iterator variable. We distinguish this case
// from normal assignment to detect disallowed re-assignment to iterator variables.
const ITER = 0x080;
/// indicates that the symbol is a free variable in a class method from the scope that the
/// class is defined in, e.g.:
/// ```python
/// def foo(x):
/// class A:
/// def method(self):
/// return x // is_free_class
/// ```
const FREE_CLASS = 0x100; // DEF_FREE_CLASS
const GLOBAL = 0x200; // DEF_GLOBAL
const COMP_ITER = 0x400; // DEF_COMP_ITER
const COMP_CELL = 0x800; // DEF_COMP_CELL
const TYPE_PARAM = 0x1000; // DEF_TYPE_PARAM
const BOUND = Self::ASSIGNED.bits() | Self::PARAMETER.bits() | Self::IMPORTED.bits() | Self::ITER.bits() | Self::TYPE_PARAM.bits();
}
}
/// A single symbol in a table. Has various properties such as the scope
/// of the symbol, and also the various uses of the symbol.
#[derive(Debug, Clone)]
pub struct Symbol {
pub name: String,
pub scope: SymbolScope,
pub flags: SymbolFlags,
}
impl Symbol {
fn new(name: &str) -> Self {
Self {
name: name.to_owned(),
// table,
scope: SymbolScope::Unknown,
flags: SymbolFlags::empty(),
}
}
#[must_use]
pub const fn is_global(&self) -> bool {
matches!(
self.scope,
SymbolScope::GlobalExplicit | SymbolScope::GlobalImplicit
)
}
#[must_use]
pub const fn is_local(&self) -> bool {
matches!(self.scope, SymbolScope::Local | SymbolScope::Cell)
}
#[must_use]
pub const fn is_bound(&self) -> bool {
self.flags.intersects(SymbolFlags::BOUND)
}
}
#[derive(Debug)]
pub struct SymbolTableError {
error: String,
location: Option<SourceLocation>,
}
impl SymbolTableError {
#[must_use]
pub fn into_codegen_error(self, source_path: String) -> CodegenError {
CodegenError {
location: self.location,
error: CodegenErrorType::SyntaxError(self.error),
source_path,
}
}
}
type SymbolTableResult<T = ()> = Result<T, SymbolTableError>;
impl core::fmt::Debug for SymbolTable {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"SymbolTable({:?} symbols, {:?} sub scopes)",
self.symbols.len(),
self.sub_tables.len()
)
}
}
/* Perform some sort of analysis on nonlocals, globals etc..
See also: https://github.com/python/cpython/blob/main/Python/symtable.c#L410
*/
fn analyze_symbol_table(symbol_table: &mut SymbolTable) -> SymbolTableResult {
let mut analyzer = SymbolTableAnalyzer::default();
// Discard the newfree set at the top level - it's only needed for propagation
// Pass None for class_entry at top level
let _newfree = analyzer.analyze_symbol_table(symbol_table, None)?;
Ok(())
}
/* Drop __class__ and __classdict__ from free variables in class scope
and set the appropriate flags. Equivalent to CPython's drop_class_free().
See: https://github.com/python/cpython/blob/main/Python/symtable.c#L884
This function removes __class__ and __classdict__ from the
`newfree` set (which contains free variables collected from all child scopes)
and sets the corresponding flags on the class's symbol table entry.
*/
fn drop_class_free(symbol_table: &mut SymbolTable, newfree: &mut IndexSet<String>) {
// Check if __class__ is in the free variables collected from children
// If found, it means a child scope (method) references __class__
if newfree.shift_remove("__class__") {
symbol_table.needs_class_closure = true;
}
// Check if __classdict__ is in the free variables collected from children
if newfree.shift_remove("__classdict__") {
symbol_table.needs_classdict = true;
}
// Classes with function definitions need __classdict__ for PEP 649
// (but not when `from __future__ import annotations` is active)
if !symbol_table.needs_classdict && !symbol_table.future_annotations {
let has_functions = symbol_table.sub_tables.iter().any(|t| {
matches!(
t.typ,
CompilerScope::Function | CompilerScope::AsyncFunction
)
});
if has_functions {
symbol_table.needs_classdict = true;
}
}
// Check if __conditional_annotations__ is in the free variables collected from children
// Remove it from free set - it's handled specially in class scope
if newfree.shift_remove("__conditional_annotations__") {
symbol_table.has_conditional_annotations = true;
}
}
/// PEP 709: Merge symbols from an inlined comprehension into the parent scope.
/// Matches symtable.c inline_comprehension().
fn inline_comprehension(
parent_symbols: &mut SymbolMap,
comp: &SymbolTable,
comp_free: &mut IndexSet<String>,
inlined_cells: &mut IndexSet<String>,
parent_type: CompilerScope,
) -> IndexSet<String> {
let mut removed_class_implicit = IndexSet::default();
for (name, sub_symbol) in &comp.symbols {
// Skip the .0 parameter
if sub_symbol.flags.contains(SymbolFlags::PARAMETER) {
continue;
}
// Track inlined cells
if sub_symbol.scope == SymbolScope::Cell
|| sub_symbol.flags.contains(SymbolFlags::COMP_CELL)
{
inlined_cells.insert(name.clone());
}
// Handle __class__ in ClassBlock
let scope = if sub_symbol.scope == SymbolScope::Free
&& parent_type == CompilerScope::Class
&& matches!(
name.as_str(),
"__class__" | "__classdict__" | "__conditional_annotations__"
) {
comp_free.swap_remove(name);
removed_class_implicit.insert(name.clone());
SymbolScope::GlobalImplicit
} else {
sub_symbol.scope
};
if let Some(existing) = parent_symbols.get(name) {
// Name exists in parent
if existing.is_bound() && parent_type != CompilerScope::Class {
// Check if the name is free in any child of the comprehension
let is_free_in_child = comp.sub_tables.iter().any(|child| {
child
.symbols
.get(name)
.is_some_and(|s| s.scope == SymbolScope::Free)
});
if !is_free_in_child {
comp_free.swap_remove(name);
}
}
} else {
// Name doesn't exist in parent, copy the comprehension binding.
// This matches CPython's inline_comprehension(): newly introduced
// comprehension locals stay locals in the parent scope.
let mut symbol = sub_symbol.clone();
symbol.scope = scope;
parent_symbols.insert(name.clone(), symbol);
}
}
removed_class_implicit
}
type SymbolMap = IndexMap<String, Symbol>;
mod stack {
use alloc::vec::Vec;
use core::ptr::NonNull;
pub(super) struct StackStack<T> {
v: Vec<NonNull<T>>,
}
impl<T> Default for StackStack<T> {
fn default() -> Self {
Self { v: Vec::new() }
}
}
impl<T> StackStack<T> {
/// Appends a reference to this stack for the duration of the function `f`. When `f`
/// returns, the reference will be popped off the stack.
#[cfg(feature = "std")]
pub(super) fn with_append<F, R>(&mut self, x: &mut T, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
{
self.v.push(x.into());
let res = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| f(self)));
self.v.pop();
res.unwrap_or_else(|x| std::panic::resume_unwind(x))
}
/// Appends a reference to this stack for the duration of the function `f`. When `f`
/// returns, the reference will be popped off the stack.
///
/// Without std, panic cleanup is not guaranteed (no catch_unwind).
#[cfg(not(feature = "std"))]
pub fn with_append<F, R>(&mut self, x: &mut T, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
{
self.v.push(x.into());
let result = f(self);
self.v.pop();
result
}
pub(super) fn iter(&self) -> impl DoubleEndedIterator<Item = &T> + '_ {
self.as_ref().iter().copied()
}
pub(super) fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> + '_ {
self.as_mut().iter_mut().map(|x| &mut **x)
}
// pub fn top(&self) -> Option<&T> {
// self.as_ref().last().copied()
// }
// pub fn top_mut(&mut self) -> Option<&mut T> {
// self.as_mut().last_mut().map(|x| &mut **x)
// }
pub(super) fn len(&self) -> usize {
self.v.len()
}
pub(super) fn is_empty(&self) -> bool {
self.len() == 0
}
pub(super) fn as_ref(&self) -> &[&T] {
unsafe { &*(self.v.as_slice() as *const [NonNull<T>] as *const [&T]) }
}
pub(super) fn as_mut(&mut self) -> &mut [&mut T] {
unsafe { &mut *(self.v.as_mut_slice() as *mut [NonNull<T>] as *mut [&mut T]) }
}
}
}
use stack::StackStack;
/// Symbol table analysis. Can be used to analyze a fully
/// build symbol table structure. It will mark variables
/// as local variables for example.
#[derive(Default)]
#[repr(transparent)]
struct SymbolTableAnalyzer {
tables: StackStack<(SymbolMap, CompilerScope, bool)>,
}
impl SymbolTableAnalyzer {
/// Analyze a symbol table and return the set of free variables.
/// See symtable.c analyze_block().
/// class_entry: PEP 649 - enclosing class symbols for annotation scopes
fn analyze_symbol_table(
&mut self,
symbol_table: &mut SymbolTable,
class_entry: Option<&SymbolMap>,
) -> SymbolTableResult<IndexSet<String>> {
let symbols = core::mem::take(&mut symbol_table.symbols);
let sub_tables = &mut *symbol_table.sub_tables;
let annotation_block = &mut symbol_table.annotation_block;
// PEP 649: Determine class_entry to pass to children
let is_class = symbol_table.typ == CompilerScope::Class;
// Clone class symbols if needed for child scopes with can_see_class_scope
let needs_class_symbols = (is_class
&& (sub_tables.iter().any(|st| st.can_see_class_scope)
|| annotation_block
.as_ref()
.is_some_and(|b| b.can_see_class_scope)))
|| (!is_class
&& class_entry.is_some()
&& sub_tables.iter().any(|st| st.can_see_class_scope));
let class_symbols_clone = if is_class && needs_class_symbols {
Some(symbols.clone())
} else {
None
};
// Collect (child_free, is_inlined) pairs from child scopes.
// We need to process inlined comprehensions after the closure
// when we have access to symbol_table.symbols.
let mut child_frees: Vec<(IndexSet<String>, bool)> = Vec::new();
let mut annotation_free: Option<IndexSet<String>> = None;
let mut info = (
symbols,
symbol_table.typ,
symbol_table.skip_enclosing_function_scope,
);
self.tables.with_append(&mut info, |list| {
let inner_scope = unsafe { &mut *(list as *mut _ as *mut Self) };
for sub_table in sub_tables.iter_mut() {
let child_class_entry = if sub_table.can_see_class_scope {
if is_class {
class_symbols_clone.as_ref()
} else {
class_entry
}
} else {
None
};
let child_free = inner_scope.analyze_symbol_table(sub_table, child_class_entry)?;
child_frees.push((child_free, sub_table.comp_inlined));
}
// PEP 649: Analyze annotation block if present
if let Some(annotation_table) = annotation_block {
let ann_class_entry = if annotation_table.can_see_class_scope {
if is_class {
class_symbols_clone.as_ref()
} else {
class_entry
}
} else {
None
};
let child_free =
inner_scope.analyze_symbol_table(annotation_table, ann_class_entry)?;
annotation_free = Some(child_free);
}
Ok(())
})?;
symbol_table.symbols = info.0;
// PEP 709: Process inlined comprehensions.
// Merge symbols from inlined comps into parent scope without bail-out.
let mut inlined_cells: IndexSet<String> = IndexSet::default();
let mut newfree = IndexSet::default();
for (idx, (mut child_free, is_inlined)) in child_frees.into_iter().enumerate() {
if is_inlined {
let removed_class_implicit = inline_comprehension(
&mut symbol_table.symbols,
&symbol_table.sub_tables[idx],
&mut child_free,
&mut inlined_cells,
symbol_table.typ,
);
for name in removed_class_implicit {
symbol_table.sub_tables[idx]
.symbols
.shift_remove(name.as_str());
}
}
newfree.extend(child_free);
}
if let Some(ann_free) = annotation_free
&& symbol_table.typ == CompilerScope::Class
{
// Annotation-only free variables should not leak into function
// bodies. We only need to propagate them through class scopes so
// drop_class_free() can materialize implicit class cells when
// annotation scopes reference them.
newfree.extend(ann_free);
}
let sub_tables = &*symbol_table.sub_tables;
for symbol in symbol_table.symbols.values_mut() {
if inlined_cells.contains(&symbol.name) {
symbol.flags.insert(SymbolFlags::COMP_CELL);
}
}
// Analyze symbols in current scope
let function_like_scope = SymbolTableBuilder::is_function_like_scope(symbol_table.typ);
for symbol in symbol_table.symbols.values_mut() {
self.analyze_symbol(
symbol,
symbol_table.typ,
symbol_table.skip_enclosing_function_scope,
sub_tables,
class_entry,
)?;
// CPython analyze_cells(): once a function-like scope owns a
// child-requested name as a cell, that name is no longer free in
// the enclosing scope.
if function_like_scope && symbol.scope == SymbolScope::Cell {
newfree.shift_remove(symbol.name.as_str());
}
// Collect free variables from this scope
if symbol.scope == SymbolScope::Free || symbol.flags.contains(SymbolFlags::FREE_CLASS) {
newfree.insert(symbol.name.clone());
}
}
// PEP 709 / CPython symtable.c:
// - only promote LOCAL -> CELL in function-like scopes, where
// analyze_cells() runs. Module and class scopes keep their normal
// scope and rely on DEF_COMP_CELL for comprehension-only cells.
for symbol in symbol_table.symbols.values_mut() {
if inlined_cells.contains(&symbol.name)
&& function_like_scope
&& symbol.scope == SymbolScope::Local
{
symbol.scope = SymbolScope::Cell;
}
}
// Handle class-specific implicit cells
if symbol_table.typ == CompilerScope::Class {
drop_class_free(symbol_table, &mut newfree);
}
// CPython update_symbols(..., classflag): after class implicit frees
// are dropped, a class block, or an annotation/type-params block that
// can see a class scope, records existing child-free names with
// DEF_FREE_CLASS. This preserves the current scope's own lookup kind
// (for example GLOBAL_IMPLICIT via __classdict__) while still making
// the name available as a closure cell for nested children such as
// generator expressions.
if symbol_table.typ == CompilerScope::Class {
for name in &newfree {
if let Some(symbol) = symbol_table.symbols.get_mut(name) {
symbol.flags.insert(SymbolFlags::FREE_CLASS);
}
}
} else if symbol_table.can_see_class_scope {
for name in &newfree {
if let Some(symbol) = symbol_table.symbols.get_mut(name)
&& !symbol.is_local()
{
symbol.flags.insert(SymbolFlags::FREE_CLASS);
}
}
}
Ok(newfree)
}
fn analyze_symbol(
&mut self,
symbol: &mut Symbol,
st_typ: CompilerScope,
skip_enclosing_function_scope: bool,
sub_tables: &[SymbolTable],
class_entry: Option<&SymbolMap>,
) -> SymbolTableResult {
if symbol
.flags
.contains(SymbolFlags::ASSIGNED_IN_COMPREHENSION)
&& st_typ == CompilerScope::Comprehension
{
// propagate symbol to next higher level that can hold it,
// i.e., function or module. Comprehension is skipped and
// Class is not allowed and detected as error.
//symbol.scope = SymbolScope::Nonlocal;
self.analyze_symbol_comprehension(symbol, 0)?
} else {
match symbol.scope {
SymbolScope::Free => {
if !self.tables.as_ref().is_empty() {
let scope_depth = self.tables.as_ref().len();
// check if the name is already defined in any outer scope
if scope_depth < 2
|| self.found_in_outer_scope(
&symbol.name,
st_typ,
skip_enclosing_function_scope,
) != Some(SymbolScope::Free)
{
return Err(SymbolTableError {
error: format!("no binding for nonlocal '{}' found", symbol.name),
// TODO: accurate location info, somehow
location: None,
});
}
// Check if the nonlocal binding refers to a type parameter
if symbol.flags.contains(SymbolFlags::NONLOCAL) {
for (symbols, _typ, _skip) in self.tables.iter().rev() {
if let Some(sym) = symbols.get(&symbol.name) {
if sym.flags.contains(SymbolFlags::TYPE_PARAM) {
return Err(SymbolTableError {
error: format!(
"nonlocal binding not allowed for type parameter '{}'",
symbol.name
),
location: None,
});
}
if sym.is_bound() {
break;
}
}
}
}
} else {
return Err(SymbolTableError {
error: format!(
"nonlocal {} defined at place without an enclosing scope",
symbol.name
),
// TODO: accurate location info, somehow
location: None,
});
}
}
SymbolScope::GlobalExplicit | SymbolScope::GlobalImplicit => {
// TODO: add more checks for globals?
}
SymbolScope::Local | SymbolScope::Cell => {
// all is well
}
SymbolScope::Unknown => {
// Try hard to figure out what the scope of this symbol is.
let scope = if symbol.is_bound() {
if symbol.flags.contains(SymbolFlags::COMP_CELL)
&& matches!(st_typ, CompilerScope::Module | CompilerScope::Class)
{
// CPython keeps comprehension-only cells in
// module/class scopes as normal local/name
// bindings and uses DEF_COMP_CELL to allocate the
// synthetic cell slot. The spliced comp child
// should not force the outer name itself to CELL.
SymbolScope::Local
} else {
self.found_in_inner_scope(sub_tables, &symbol.name, st_typ)
.unwrap_or(SymbolScope::Local)
}
} else if let Some(scope) = class_entry
.and_then(|class_symbols| class_symbols.get(&symbol.name))
.and_then(|class_sym| {
if class_sym.flags.contains(SymbolFlags::GLOBAL) {
Some(SymbolScope::GlobalExplicit)
} else if class_sym.is_bound() && class_sym.scope != SymbolScope::Free {
// If name is bound in enclosing class, use GlobalImplicit
// so it can be accessed via __classdict__
Some(SymbolScope::GlobalImplicit)
} else {
None
}
})
{
scope
} else if let Some(scope) = self.found_in_outer_scope(
&symbol.name,
st_typ,
skip_enclosing_function_scope,
) {
// If found in enclosing scope (function/TypeParams), use that
scope
} else if self.tables.is_empty() {
// Don't make assumptions when we don't know.
SymbolScope::Unknown
} else {
// If there are scopes above we assume global.
SymbolScope::GlobalImplicit
};
symbol.scope = scope;
}
}
}
Ok(())
}
fn found_in_outer_scope(
&mut self,
name: &str,
st_typ: CompilerScope,
skip_enclosing_function_scope: bool,
) -> Option<SymbolScope> {
let mut decl_depth = None;
for (i, (symbols, typ, _skip)) in self.tables.iter().rev().enumerate() {
if matches!(typ, CompilerScope::Module)
|| matches!(typ, CompilerScope::Class if name != "__class__" && name != "__classdict__" && name != "__conditional_annotations__")
{
continue;
}
// Real PEP 649 annotation blocks resolve names as siblings of the
// owning function body. Other annotation-like scopes such as type
// aliases and TypeVar bound/default evaluators keep normal lexical
// lookup and therefore leave this path disabled.
if st_typ == CompilerScope::Annotation
&& skip_enclosing_function_scope
&& i == 0
&& matches!(
typ,
CompilerScope::Function | CompilerScope::AsyncFunction | CompilerScope::Lambda
)
{
continue;
}
// __class__ and __classdict__ are implicitly declared in class scope
// This handles the case where nested scopes reference them
if (name == "__class__" || name == "__classdict__")
&& matches!(typ, CompilerScope::Class)
{
decl_depth = Some(i);
break;
}
// __conditional_annotations__ is implicitly declared in class scope
// for classes with conditional annotations
if name == "__conditional_annotations__" && matches!(typ, CompilerScope::Class) {
decl_depth = Some(i);
break;
}
if let Some(sym) = symbols.get(name) {
match sym.scope {
SymbolScope::GlobalExplicit => return Some(SymbolScope::GlobalExplicit),
SymbolScope::GlobalImplicit => {}
_ => {
if sym.is_bound() {
decl_depth = Some(i);
break;
}
}
}
}
}
if let Some(decl_depth) = decl_depth {
// decl_depth is the number of tables between the current one and
// the one that declared the cell var
// For implicit class scope variables (__classdict__, __conditional_annotations__),
// only propagate free to annotation/type-param scopes, not regular functions.
// Regular method functions don't need these in their freevars.
let is_class_implicit =
name == "__classdict__" || name == "__conditional_annotations__";
for (table, typ, _skip) in self.tables.iter_mut().rev().take(decl_depth) {
if let CompilerScope::Class = typ {
if let Some(free_class) = table.get_mut(name) {
free_class.flags.insert(SymbolFlags::FREE_CLASS)
} else {
let mut symbol = Symbol::new(name);
symbol.flags.insert(SymbolFlags::FREE_CLASS);
symbol.scope = SymbolScope::Free;
table.insert(name.to_owned(), symbol);
}
} else if is_class_implicit
&& matches!(
typ,
CompilerScope::Function
| CompilerScope::AsyncFunction
| CompilerScope::Lambda
)
{
// Skip: don't add __classdict__/__conditional_annotations__
// as free vars in regular functions — only annotation/type scopes need them
} else if !table.contains_key(name) {
let mut symbol = Symbol::new(name);
symbol.scope = SymbolScope::Free;
table.insert(name.to_owned(), symbol);
}
}
}
decl_depth.map(|_| SymbolScope::Free)
}
fn found_in_inner_scope(
&self,
sub_tables: &[SymbolTable],
name: &str,
st_typ: CompilerScope,
) -> Option<SymbolScope> {
sub_tables.iter().find_map(|st| {
// PEP 709: For inlined comprehensions, check their children
// instead of the comp itself (its symbols are merged into parent).
if st.comp_inlined {
return self.found_in_inner_scope(&st.sub_tables, name, st_typ);
}
let sym = st.symbols.get(name)?;
if sym.scope == SymbolScope::Free
|| (sym.flags.contains(SymbolFlags::FREE_CLASS)
&& !matches!(st_typ, CompilerScope::Module))
{
if st_typ == CompilerScope::Class && name != "__class__" {
None
} else {
Some(SymbolScope::Cell)
}
} else if sym.scope == SymbolScope::GlobalExplicit && self.tables.is_empty() {
// the symbol is defined on the module level, and an inner scope declares
// a global that points to it
Some(SymbolScope::GlobalExplicit)
} else {
None
}
})
}
// Implements the symbol analysis and scope extension for names
// assigned by a named expression in a comprehension. See:
// https://github.com/python/cpython/blob/7b78e7f9fd77bb3280ee39fb74b86772a7d46a70/Python/symtable.c#L1435
fn analyze_symbol_comprehension(
&mut self,
symbol: &mut Symbol,
parent_offset: usize,
) -> SymbolTableResult {
// when this is called, we expect to be in the direct parent scope of the scope that contains 'symbol'
let last = self.tables.iter_mut().rev().nth(parent_offset).unwrap();
let symbols = &mut last.0;
let table_type = last.1;
// it is not allowed to use an iterator variable as assignee in a named expression
if symbol.flags.contains(SymbolFlags::ITER) {
return Err(SymbolTableError {
error: format!(
"assignment expression cannot rebind comprehension iteration variable {}",
symbol.name
),
// TODO: accurate location info, somehow
location: None,
});
}
match table_type {
CompilerScope::Module => {
symbol.scope = SymbolScope::GlobalImplicit;
}
CompilerScope::Class => {
// named expressions are forbidden in comprehensions on class scope
return Err(SymbolTableError {
error: "assignment expression within a comprehension cannot be used in a class body".to_string(),
// TODO: accurate location info, somehow
location: None,
});
}
CompilerScope::Function | CompilerScope::AsyncFunction | CompilerScope::Lambda => {
if let Some(parent_symbol) = symbols.get_mut(&symbol.name) {
if let SymbolScope::Unknown = parent_symbol.scope {
// this information is new, as the assignment is done in inner scope
parent_symbol.flags.insert(SymbolFlags::ASSIGNED);
}
symbol.scope = if parent_symbol.is_global() {
parent_symbol.scope
} else {
SymbolScope::Free
};
} else {
let mut cloned_sym = symbol.clone();
cloned_sym.scope = SymbolScope::Cell;
last.0.insert(cloned_sym.name.to_owned(), cloned_sym);
}
}
CompilerScope::Comprehension => {
// TODO check for conflicts - requires more context information about variables
match symbols.get_mut(&symbol.name) {
Some(parent_symbol) => {
// check if assignee is an iterator in top scope
if parent_symbol.flags.contains(SymbolFlags::ITER) {
return Err(SymbolTableError {
error: format!(
"assignment expression cannot rebind comprehension iteration variable {}",
symbol.name
),
location: None,
});
}
// we synthesize the assignment to the symbol from inner scope
parent_symbol.flags.insert(SymbolFlags::ASSIGNED); // more checks are required
}
None => {
// extend the scope of the inner symbol
// as we are in a nested comprehension, we expect that the symbol is needed