forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_symtable.rs
More file actions
335 lines (270 loc) · 8.84 KB
/
Copy path_symtable.rs
File metadata and controls
335 lines (270 loc) · 8.84 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
pub(crate) use _symtable::module_def;
#[pymodule]
mod _symtable {
use crate::{
Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::{PyDictRef, PyUtf8StrRef},
compiler,
types::Representable,
};
use alloc::fmt;
use rustpython_codegen::symboltable::{
CompilerScope, Symbol, SymbolFlags, SymbolScope, SymbolTable,
};
// Consts as defined at
// https://github.com/python/cpython/blob/6cb20a219a860eaf687b2d968b41c480c7461909/Include/internal/pycore_symtable.h#L156
#[pyattr]
pub(super) const DEF_GLOBAL: i32 = 1;
#[pyattr]
pub(super) const DEF_LOCAL: i32 = 2;
#[pyattr]
pub(super) const DEF_PARAM: i32 = 2 << 1;
#[pyattr]
pub(super) const DEF_NONLOCAL: i32 = 2 << 2;
#[pyattr]
pub(super) const USE: i32 = 2 << 3;
#[pyattr]
pub(super) const DEF_FREE: i32 = 2 << 4;
#[pyattr]
pub(super) const DEF_FREE_CLASS: i32 = 2 << 5;
#[pyattr]
pub(super) const DEF_IMPORT: i32 = 2 << 6;
#[pyattr]
pub(super) const DEF_ANNOT: i32 = 2 << 7;
#[pyattr]
pub(super) const DEF_COMP_ITER: i32 = 2 << 8;
#[pyattr]
pub(super) const DEF_TYPE_PARAM: i32 = 2 << 9;
#[pyattr]
pub(super) const DEF_COMP_CELL: i32 = 2 << 10;
#[pyattr]
pub(super) const DEF_BOUND: i32 = DEF_LOCAL | DEF_PARAM | DEF_IMPORT;
#[pyattr]
pub(super) const SCOPE_OFFSET: i32 = 12;
#[pyattr]
pub(super) const SCOPE_MASK: i32 = DEF_GLOBAL | DEF_LOCAL | DEF_PARAM | DEF_NONLOCAL;
#[pyattr]
pub(super) const LOCAL: i32 = 1;
#[pyattr]
pub(super) const GLOBAL_EXPLICIT: i32 = 2;
#[pyattr]
pub(super) const GLOBAL_IMPLICIT: i32 = 3;
#[pyattr]
pub(super) const FREE: i32 = 4;
#[pyattr]
pub(super) const CELL: i32 = 5;
#[pyattr]
pub(super) const GENERATOR: i32 = 1;
#[pyattr]
pub(super) const GENERATOR_EXPRESSION: i32 = 2;
#[pyattr]
pub(super) const SCOPE_OFF: i32 = SCOPE_OFFSET;
#[pyattr]
pub(super) const TYPE_FUNCTION: i32 = 0;
#[pyattr]
pub(super) const TYPE_CLASS: i32 = 1;
#[pyattr]
pub(super) const TYPE_MODULE: i32 = 2;
#[pyattr]
pub(super) const TYPE_ANNOTATION: i32 = 3;
#[pyattr]
pub(super) const TYPE_TYPE_VAR_BOUND: i32 = 4;
#[pyattr]
pub(super) const TYPE_TYPE_ALIAS: i32 = 5;
#[pyattr]
pub(super) const TYPE_TYPE_PARAMETERS: i32 = 6;
#[pyattr]
pub(super) const TYPE_TYPE_VARIABLE: i32 = 7;
#[pyfunction]
fn symtable(
source: PyUtf8StrRef,
filename: PyUtf8StrRef,
mode: PyUtf8StrRef,
vm: &VirtualMachine,
) -> PyResult<PyRef<PySymbolTable>> {
let mode = mode
.as_str()
.parse::<compiler::Mode>()
.map_err(|err| vm.new_value_error(err.to_string()))?;
let symtable = compiler::compile_symtable(source.as_str(), mode, filename.as_str())
.map_err(|err| vm.new_syntax_error(&err, Some(source.as_str())))?;
let py_symbol_table = to_py_symbol_table(symtable);
Ok(py_symbol_table.into_ref(&vm.ctx))
}
const fn to_py_symbol_table(symtable: SymbolTable) -> PySymbolTable {
PySymbolTable { symtable }
}
#[pyattr]
#[pyclass(name = "symtable entry")]
#[derive(PyPayload)]
struct PySymbolTable {
symtable: SymbolTable,
}
impl fmt::Debug for PySymbolTable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SymbolTable()")
}
}
#[pyclass(with(Representable))]
impl PySymbolTable {
#[pygetset]
fn name(&self) -> String {
self.symtable.name.clone()
}
#[pygetset(name = "type")]
fn typ(&self) -> i32 {
match self.symtable.typ {
CompilerScope::Function
| CompilerScope::AsyncFunction
| CompilerScope::Lambda
| CompilerScope::Comprehension => TYPE_FUNCTION,
CompilerScope::Class => TYPE_CLASS,
CompilerScope::Module => TYPE_MODULE,
CompilerScope::Annotation => TYPE_ANNOTATION,
CompilerScope::TypeParams => TYPE_TYPE_PARAMETERS,
}
}
#[pygetset]
const fn lineno(&self) -> u32 {
self.symtable.line_number
}
#[pygetset]
fn children(&self, vm: &VirtualMachine) -> Vec<PyObjectRef> {
self.symtable
.sub_tables
.iter()
.flat_map(|t| {
if t.comp_inlined {
// Flatten: replace inlined comprehension tables with their children
t.sub_tables.iter().collect::<Vec<_>>()
} else {
vec![t]
}
})
.map(|t| to_py_symbol_table(t.clone()).into_pyobject(vm))
.collect()
}
#[pygetset]
fn id(&self) -> usize {
self as *const Self as *const core::ffi::c_void as usize
}
#[pygetset]
fn identifiers(&self, vm: &VirtualMachine) -> Vec<PyObjectRef> {
self.symtable
.symbols
.keys()
.map(|s| vm.ctx.new_str(s.as_str()).into())
.collect()
}
#[pygetset]
fn symbols(&self, vm: &VirtualMachine) -> PyDictRef {
let dict = vm.ctx.new_dict();
for (name, symbol) in &self.symtable.symbols {
dict.set_item(name, vm.new_pyobj(symbol.flags.bits()), vm)
.unwrap();
}
dict
}
#[pygetset]
const fn nested(&self) -> bool {
self.symtable.is_nested
}
}
impl Representable for PySymbolTable {
#[inline]
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
Ok(format!(
"<{} {}({}), line {}>",
Self::class(&vm.ctx).name(),
zelf.symtable.name,
zelf.id(),
zelf.symtable.line_number
))
}
}
#[pyattr]
#[pyclass(name = "Symbol")]
#[derive(PyPayload)]
struct PySymbol {
symbol: Symbol,
namespaces: Vec<SymbolTable>,
is_top_scope: bool,
}
impl fmt::Debug for PySymbol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Symbol()")
}
}
#[pyclass]
impl PySymbol {
#[pymethod]
fn get_name(&self) -> String {
self.symbol.name.clone()
}
#[pymethod]
const fn is_global(&self) -> bool {
self.symbol.is_global() || (self.is_top_scope && self.symbol.is_bound())
}
#[pymethod]
const fn is_declared_global(&self) -> bool {
matches!(self.symbol.scope, SymbolScope::GlobalExplicit)
}
#[pymethod]
const fn is_local(&self) -> bool {
self.symbol.is_local() || (self.is_top_scope && self.symbol.is_bound())
}
#[pymethod]
const fn is_imported(&self) -> bool {
self.symbol.flags.contains(SymbolFlags::IMPORTED)
}
#[pymethod]
const fn is_nested(&self) -> bool {
// TODO
false
}
#[pymethod]
const fn is_nonlocal(&self) -> bool {
self.symbol.flags.contains(SymbolFlags::NONLOCAL)
}
#[pymethod]
const fn is_referenced(&self) -> bool {
self.symbol.flags.contains(SymbolFlags::REFERENCED)
}
#[pymethod]
const fn is_assigned(&self) -> bool {
self.symbol.flags.contains(SymbolFlags::ASSIGNED)
}
#[pymethod]
const fn is_parameter(&self) -> bool {
self.symbol.flags.contains(SymbolFlags::PARAMETER)
}
#[pymethod]
const fn is_free(&self) -> bool {
matches!(self.symbol.scope, SymbolScope::Free)
}
#[pymethod]
const fn is_namespace(&self) -> bool {
!self.namespaces.is_empty()
}
#[pymethod]
const fn is_annotated(&self) -> bool {
self.symbol.flags.contains(SymbolFlags::ANNOTATED)
}
#[pymethod]
fn get_namespaces(&self, vm: &VirtualMachine) -> Vec<PyObjectRef> {
self.namespaces
.iter()
.map(|table| to_py_symbol_table(table.clone()).into_pyobject(vm))
.collect()
}
#[pymethod]
fn get_namespace(&self, vm: &VirtualMachine) -> PyResult {
if self.namespaces.len() != 1 {
return Err(vm.new_value_error("namespace is bound to multiple namespaces"));
}
Ok(to_py_symbol_table(self.namespaces.first().unwrap().clone())
.into_ref(&vm.ctx)
.into())
}
}
}