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
1301 lines (1214 loc) · 47.9 KB
/
symboltable.rs
File metadata and controls
1301 lines (1214 loc) · 47.9 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::{
error::{CodegenError, CodegenErrorType},
IndexMap,
};
use bitflags::bitflags;
use rustpython_ast as ast;
use rustpython_compiler_core::Location;
use std::{borrow::Cow, fmt};
/// Captures all symbols in the current scope, and has a list of subscopes 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: SymbolTableType,
/// The line number in the sourcecode where this symboltable begins.
pub line_number: usize,
// Return True if the block is a nested class or function
pub is_nested: bool,
/// A set of symbols present on this scope level.
pub symbols: IndexMap<String, Symbol>,
/// A list of subscopes in the order as found in the
/// AST nodes.
pub sub_tables: Vec<SymbolTable>,
}
impl SymbolTable {
fn new(name: String, typ: SymbolTableType, line_number: usize, is_nested: bool) -> Self {
SymbolTable {
name,
typ,
line_number,
is_nested,
symbols: IndexMap::default(),
sub_tables: vec![],
}
}
pub fn scan_program(program: &[ast::Stmt]) -> SymbolTableResult<Self> {
let mut builder = SymbolTableBuilder::new();
builder.scan_statements(program)?;
builder.finish()
}
pub fn scan_expr(expr: &ast::Expr) -> SymbolTableResult<Self> {
let mut builder = SymbolTableBuilder::new();
builder.scan_expression(expr, ExpressionContext::Load)?;
builder.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolTableType {
Module,
Class,
Function,
Comprehension,
}
impl fmt::Display for SymbolTableType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SymbolTableType::Module => write!(f, "module"),
SymbolTableType::Class => write!(f, "class"),
SymbolTableType::Function => write!(f, "function"),
SymbolTableType::Comprehension => write!(f, "comprehension"),
}
}
}
/// 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! {
pub struct SymbolFlags: u16 {
const REFERENCED = 0x001;
const ASSIGNED = 0x002;
const PARAMETER = 0x004;
const ANNOTATED = 0x008;
const IMPORTED = 0x010;
const NONLOCAL = 0x020;
// 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 unallowed 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;
const BOUND = Self::ASSIGNED.bits | Self::PARAMETER.bits | Self::IMPORTED.bits | Self::ITER.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 table: SymbolTableRef,
pub scope: SymbolScope,
pub flags: SymbolFlags,
}
impl Symbol {
fn new(name: &str) -> Self {
Symbol {
name: name.to_owned(),
// table,
scope: SymbolScope::Unknown,
flags: SymbolFlags::empty(),
}
}
pub fn is_global(&self) -> bool {
matches!(
self.scope,
SymbolScope::GlobalExplicit | SymbolScope::GlobalImplicit
)
}
pub fn is_local(&self) -> bool {
matches!(self.scope, SymbolScope::Local | SymbolScope::Cell)
}
pub fn is_bound(&self) -> bool {
self.flags.intersects(SymbolFlags::BOUND)
}
}
#[derive(Debug)]
pub struct SymbolTableError {
error: String,
location: Location,
}
impl SymbolTableError {
pub fn into_codegen_error(self, source_path: String) -> CodegenError {
CodegenError {
error: CodegenErrorType::SyntaxError(self.error),
location: self.location.with_col_offset(1),
source_path,
}
}
}
type SymbolTableResult<T = ()> = Result<T, SymbolTableError>;
impl SymbolTable {
pub fn lookup(&self, name: &str) -> Option<&Symbol> {
self.symbols.get(name)
}
}
impl std::fmt::Debug for SymbolTable {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::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();
analyzer.analyze_symbol_table(symbol_table)
}
type SymbolMap = IndexMap<String, Symbol>;
mod stack {
use std::panic;
use std::ptr::NonNull;
pub 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.
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 res = panic::catch_unwind(panic::AssertUnwindSafe(|| f(self)));
self.v.pop();
res.unwrap_or_else(|x| panic::resume_unwind(x))
}
pub fn iter(&self) -> impl Iterator<Item = &T> + DoubleEndedIterator + '_ {
self.as_ref().iter().copied()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> + DoubleEndedIterator + '_ {
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 fn len(&self) -> usize {
self.v.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn as_ref(&self) -> &[&T] {
unsafe { &*(self.v.as_slice() as *const [NonNull<T>] as *const [&T]) }
}
pub 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, SymbolTableType)>,
}
impl SymbolTableAnalyzer {
fn analyze_symbol_table(&mut self, symbol_table: &mut SymbolTable) -> SymbolTableResult {
let symbols = std::mem::take(&mut symbol_table.symbols);
let sub_tables = &mut *symbol_table.sub_tables;
let mut info = (symbols, symbol_table.typ);
self.tables.with_append(&mut info, |list| {
let inner_scope = unsafe { &mut *(list as *mut _ as *mut SymbolTableAnalyzer) };
// Analyze sub scopes:
for sub_table in sub_tables.iter_mut() {
inner_scope.analyze_symbol_table(sub_table)?;
}
Ok(())
})?;
symbol_table.symbols = info.0;
// Analyze symbols:
for symbol in symbol_table.symbols.values_mut() {
self.analyze_symbol(symbol, symbol_table.typ, sub_tables)?;
}
Ok(())
}
fn analyze_symbol(
&mut self,
symbol: &mut Symbol,
st_typ: SymbolTableType,
sub_tables: &mut [SymbolTable],
) -> SymbolTableResult {
if symbol
.flags
.contains(SymbolFlags::ASSIGNED_IN_COMPREHENSION)
&& st_typ == SymbolTableType::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
// therefore
if scope_depth < 2
|| self.found_in_outer_scope(&symbol.name) != Some(SymbolScope::Free)
{
return Err(SymbolTableError {
error: format!("no binding for nonlocal '{}' found", symbol.name),
// TODO: accurate location info, somehow
location: Location::default(),
});
}
} else {
return Err(SymbolTableError {
error: format!(
"nonlocal {} defined at place without an enclosing scope",
symbol.name
),
// TODO: accurate location info, somehow
location: Location::default(),
});
}
}
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() {
self.found_in_inner_scope(sub_tables, &symbol.name, st_typ)
.unwrap_or(SymbolScope::Local)
} else if let Some(scope) = self.found_in_outer_scope(&symbol.name) {
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) -> Option<SymbolScope> {
let mut decl_depth = None;
for (i, (symbols, typ)) in self.tables.iter().rev().enumerate() {
if matches!(typ, SymbolTableType::Module)
|| matches!(typ, SymbolTableType::Class if name != "__class__")
{
continue;
}
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 (table, typ) in self.tables.iter_mut().rev().take(decl_depth) {
if let SymbolTableType::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 !table.contains_key(name) {
let mut symbol = Symbol::new(name);
symbol.scope = SymbolScope::Free;
// symbol.is_referenced = true;
table.insert(name.to_owned(), symbol);
}
}
}
decl_depth.map(|_| SymbolScope::Free)
}
fn found_in_inner_scope(
&self,
sub_tables: &[SymbolTable],
name: &str,
st_typ: SymbolTableType,
) -> Option<SymbolScope> {
sub_tables.iter().find_map(|st| {
st.symbols.get(name).and_then(|sym| {
if sym.scope == SymbolScope::Free || sym.flags.contains(SymbolFlags::FREE_CLASS) {
if st_typ == SymbolTableType::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: Location::default(),
});
}
match table_type {
SymbolTableType::Module => {
symbol.scope = SymbolScope::GlobalImplicit;
}
SymbolTableType::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: Location::default(),
});
}
SymbolTableType::Function => {
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);
}
}
SymbolTableType::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),
// TODO: accurate location info, somehow
location: Location::default(),
});
}
// 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
// outside, too, and set it therefore to non-local scope. I.e., we expect to
// find a definition on a higher level
let mut cloned_sym = symbol.clone();
cloned_sym.scope = SymbolScope::Free;
last.0.insert(cloned_sym.name.to_owned(), cloned_sym);
}
}
self.analyze_symbol_comprehension(symbol, parent_offset + 1)?;
}
}
Ok(())
}
}
#[derive(Debug, Clone)]
enum SymbolUsage {
Global,
Nonlocal,
Used,
Assigned,
Imported,
AnnotationAssigned,
Parameter,
AnnotationParameter,
AssignedNamedExprInCompr,
Iter,
}
struct SymbolTableBuilder {
class_name: Option<String>,
// Scope stack.
tables: Vec<SymbolTable>,
future_annotations: bool,
}
/// Enum to indicate in what mode an expression
/// was used.
/// In cpython this is stored in the AST, but I think this
/// is not logical, since it is not context free.
#[derive(Copy, Clone, PartialEq)]
enum ExpressionContext {
Load,
Store,
Delete,
Iter,
IterDefinitionExp,
}
impl SymbolTableBuilder {
fn new() -> Self {
let mut this = Self {
class_name: None,
tables: vec![],
future_annotations: false,
};
this.enter_scope("top", SymbolTableType::Module, 0);
this
}
fn finish(mut self) -> Result<SymbolTable, SymbolTableError> {
assert_eq!(self.tables.len(), 1);
let mut symbol_table = self.tables.pop().unwrap();
analyze_symbol_table(&mut symbol_table)?;
Ok(symbol_table)
}
fn enter_scope(&mut self, name: &str, typ: SymbolTableType, line_number: usize) {
let is_nested = self
.tables
.last()
.map(|table| table.is_nested || table.typ == SymbolTableType::Function)
.unwrap_or(false);
let table = SymbolTable::new(name.to_owned(), typ, line_number, is_nested);
self.tables.push(table);
}
/// Pop symbol table and add to sub table of parent table.
fn leave_scope(&mut self) {
let table = self.tables.pop().unwrap();
self.tables.last_mut().unwrap().sub_tables.push(table);
}
fn scan_statements(&mut self, statements: &[ast::Stmt]) -> SymbolTableResult {
for statement in statements {
self.scan_statement(statement)?;
}
Ok(())
}
fn scan_parameters(&mut self, parameters: &[ast::Arg]) -> SymbolTableResult {
for parameter in parameters {
self.scan_parameter(parameter)?;
}
Ok(())
}
fn scan_parameter(&mut self, parameter: &ast::Arg) -> SymbolTableResult {
let usage = if parameter.node.annotation.is_some() {
SymbolUsage::AnnotationParameter
} else {
SymbolUsage::Parameter
};
self.register_name(¶meter.node.arg, usage, parameter.location)
}
fn scan_parameters_annotations(&mut self, parameters: &[ast::Arg]) -> SymbolTableResult {
for parameter in parameters {
self.scan_parameter_annotation(parameter)?;
}
Ok(())
}
fn scan_parameter_annotation(&mut self, parameter: &ast::Arg) -> SymbolTableResult {
if let Some(annotation) = ¶meter.node.annotation {
self.scan_annotation(annotation)?;
}
Ok(())
}
fn scan_annotation(&mut self, annotation: &ast::Expr) -> SymbolTableResult {
if self.future_annotations {
Ok(())
} else {
self.scan_expression(annotation, ExpressionContext::Load)
}
}
fn scan_statement(&mut self, statement: &ast::Stmt) -> SymbolTableResult {
use ast::StmtKind::*;
let location = statement.location;
if let ImportFrom { module, names, .. } = &statement.node {
if module.as_deref() == Some("__future__") {
for feature in names {
if feature.node.name == "annotations" {
self.future_annotations = true;
}
}
}
}
match &statement.node {
Global { names } => {
for name in names {
self.register_name(name, SymbolUsage::Global, location)?;
}
}
Nonlocal { names } => {
for name in names {
self.register_name(name, SymbolUsage::Nonlocal, location)?;
}
}
FunctionDef {
name,
body,
args,
decorator_list,
returns,
..
}
| AsyncFunctionDef {
name,
body,
args,
decorator_list,
returns,
..
} => {
self.scan_expressions(decorator_list, ExpressionContext::Load)?;
self.register_name(name, SymbolUsage::Assigned, location)?;
if let Some(expression) = returns {
self.scan_annotation(expression)?;
}
self.enter_function(name, args, location.row())?;
self.scan_statements(body)?;
self.leave_scope();
}
ClassDef {
name,
body,
bases,
keywords,
decorator_list,
} => {
self.enter_scope(name, SymbolTableType::Class, location.row());
let prev_class = std::mem::replace(&mut self.class_name, Some(name.to_owned()));
self.register_name("__module__", SymbolUsage::Assigned, location)?;
self.register_name("__qualname__", SymbolUsage::Assigned, location)?;
self.register_name("__doc__", SymbolUsage::Assigned, location)?;
self.register_name("__class__", SymbolUsage::Assigned, location)?;
self.scan_statements(body)?;
self.leave_scope();
self.class_name = prev_class;
self.scan_expressions(bases, ExpressionContext::Load)?;
for keyword in keywords {
self.scan_expression(&keyword.node.value, ExpressionContext::Load)?;
}
self.scan_expressions(decorator_list, ExpressionContext::Load)?;
self.register_name(name, SymbolUsage::Assigned, location)?;
}
Expr { value } => self.scan_expression(value, ExpressionContext::Load)?,
If { test, body, orelse } => {
self.scan_expression(test, ExpressionContext::Load)?;
self.scan_statements(body)?;
self.scan_statements(orelse)?;
}
For {
target,
iter,
body,
orelse,
..
}
| AsyncFor {
target,
iter,
body,
orelse,
..
} => {
self.scan_expression(target, ExpressionContext::Store)?;
self.scan_expression(iter, ExpressionContext::Load)?;
self.scan_statements(body)?;
self.scan_statements(orelse)?;
}
While { test, body, orelse } => {
self.scan_expression(test, ExpressionContext::Load)?;
self.scan_statements(body)?;
self.scan_statements(orelse)?;
}
Break | Continue | Pass => {
// No symbols here.
}
Import { names } | ImportFrom { names, .. } => {
for name in names {
if let Some(alias) = &name.node.asname {
// `import mymodule as myalias`
self.register_name(alias, SymbolUsage::Imported, location)?;
} else {
// `import module`
self.register_name(
name.node.name.split('.').next().unwrap(),
SymbolUsage::Imported,
location,
)?;
}
}
}
Return { value } => {
if let Some(expression) = value {
self.scan_expression(expression, ExpressionContext::Load)?;
}
}
Assert { test, msg } => {
self.scan_expression(test, ExpressionContext::Load)?;
if let Some(expression) = msg {
self.scan_expression(expression, ExpressionContext::Load)?;
}
}
Delete { targets } => {
self.scan_expressions(targets, ExpressionContext::Delete)?;
}
Assign { targets, value, .. } => {
self.scan_expressions(targets, ExpressionContext::Store)?;
self.scan_expression(value, ExpressionContext::Load)?;
}
AugAssign { target, value, .. } => {
self.scan_expression(target, ExpressionContext::Store)?;
self.scan_expression(value, ExpressionContext::Load)?;
}
AnnAssign {
target,
annotation,
value,
simple,
} => {
// https://github.com/python/cpython/blob/main/Python/symtable.c#L1233
match &target.node {
ast::ExprKind::Name { id, .. } if *simple > 0 => {
self.register_name(id, SymbolUsage::AnnotationAssigned, location)?;
}
_ => {
self.scan_expression(target, ExpressionContext::Store)?;
}
}
self.scan_annotation(annotation)?;
if let Some(value) = value {
self.scan_expression(value, ExpressionContext::Load)?;
}
}
With { items, body, .. } | AsyncWith { items, body, .. } => {
for item in items {
self.scan_expression(&item.context_expr, ExpressionContext::Load)?;
if let Some(expression) = &item.optional_vars {
self.scan_expression(expression, ExpressionContext::Store)?;
}
}
self.scan_statements(body)?;
}
Try {
body,
handlers,
orelse,
finalbody,
} => {
self.scan_statements(body)?;
for handler in handlers {
let ast::ExcepthandlerKind::ExceptHandler { type_, name, body } = &handler.node;
if let Some(expression) = type_ {
self.scan_expression(expression, ExpressionContext::Load)?;
}
if let Some(name) = name {
self.register_name(name, SymbolUsage::Assigned, location)?;
}
self.scan_statements(body)?;
}
self.scan_statements(orelse)?;
self.scan_statements(finalbody)?;
}
Match {
subject: _,
cases: _,
} => {
return Err(SymbolTableError {
error: "match expression is not implemented yet".to_owned(),
location: Location::default(),
});
}
Raise { exc, cause } => {
if let Some(expression) = exc {
self.scan_expression(expression, ExpressionContext::Load)?;
}
if let Some(expression) = cause {
self.scan_expression(expression, ExpressionContext::Load)?;
}
}
}
Ok(())
}
fn scan_expressions(
&mut self,
expressions: &[ast::Expr],
context: ExpressionContext,
) -> SymbolTableResult {
for expression in expressions {
self.scan_expression(expression, context)?;
}
Ok(())
}
fn scan_expression(
&mut self,
expression: &ast::Expr,
context: ExpressionContext,
) -> SymbolTableResult {
use ast::ExprKind::*;
let location = expression.location;
match &expression.node {
BinOp { left, right, .. } => {
self.scan_expression(left, context)?;
self.scan_expression(right, context)?;
}
BoolOp { values, .. } => {
self.scan_expressions(values, context)?;
}
Compare {
left, comparators, ..
} => {
self.scan_expression(left, context)?;
self.scan_expressions(comparators, context)?;
}
Subscript { value, slice, .. } => {
self.scan_expression(value, ExpressionContext::Load)?;
self.scan_expression(slice, ExpressionContext::Load)?;
}
Attribute { value, .. } => {
self.scan_expression(value, ExpressionContext::Load)?;
}
Dict { keys, values } => {
let (packed, unpacked) = values.split_at(keys.len());
for (key, value) in keys.iter().zip(packed) {
self.scan_expression(key, context)?;
self.scan_expression(value, context)?;
}
for value in unpacked {
// dict unpacking marker
self.scan_expression(value, context)?;
}
}
Await { value } => {
self.scan_expression(value, context)?;
}
Yield { value } => {
if let Some(expression) = value {
self.scan_expression(expression, context)?;
}
}
YieldFrom { value } => {
self.scan_expression(value, context)?;
}
UnaryOp { operand, .. } => {
self.scan_expression(operand, context)?;
}
Constant { .. } => {}
Starred { value, .. } => {
self.scan_expression(value, context)?;
}
Tuple { elts, .. } | Set { elts, .. } | List { elts, .. } => {
self.scan_expressions(elts, context)?;
}
Slice { lower, upper, step } => {
if let Some(lower) = lower {
self.scan_expression(lower, context)?;
}
if let Some(upper) = upper {
self.scan_expression(upper, context)?;
}
if let Some(step) = step {
self.scan_expression(step, context)?;
}
}
GeneratorExp { elt, generators } => {
self.scan_comprehension("genexpr", elt, None, generators, location)?;
}
ListComp { elt, generators } => {
self.scan_comprehension("genexpr", elt, None, generators, location)?;
}
SetComp { elt, generators } => {
self.scan_comprehension("genexpr", elt, None, generators, location)?;
}
DictComp {
key,
value,
generators,
} => {
self.scan_comprehension("genexpr", key, Some(value), generators, location)?;
}
Call {
func,
args,
keywords,
} => {
match context {
ExpressionContext::IterDefinitionExp => {
self.scan_expression(func, ExpressionContext::IterDefinitionExp)?;
}
_ => {
self.scan_expression(func, ExpressionContext::Load)?;
}
}
self.scan_expressions(args, ExpressionContext::Load)?;
for keyword in keywords {
self.scan_expression(&keyword.node.value, ExpressionContext::Load)?;
}
}
FormattedValue {
value, format_spec, ..
} => {
self.scan_expression(value, ExpressionContext::Load)?;
if let Some(spec) = format_spec {
self.scan_expression(spec, ExpressionContext::Load)?;
}
}
JoinedStr { values } => {
for value in values {
self.scan_expression(value, ExpressionContext::Load)?;
}
}
Name { id, .. } => {
// Determine the contextual usage of this symbol:
match context {
ExpressionContext::Delete => {
self.register_name(id, SymbolUsage::Assigned, location)?;
self.register_name(id, SymbolUsage::Used, location)?;
}
ExpressionContext::Load | ExpressionContext::IterDefinitionExp => {
self.register_name(id, SymbolUsage::Used, location)?;
}
ExpressionContext::Store => {
self.register_name(id, SymbolUsage::Assigned, location)?;
}
ExpressionContext::Iter => {
self.register_name(id, SymbolUsage::Iter, location)?;
}
}
// Interesting stuff about the __class__ variable:
// https://docs.python.org/3/reference/datamodel.html?highlight=__class__#creating-the-class-object
if context == ExpressionContext::Load
&& self.tables.last().unwrap().typ == SymbolTableType::Function
&& id == "super"
{