rustpython-compiler 0.1.0

Compiler for python code into bytecode for the rustpython VM.
Documentation
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
/* 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/master/Python/symtable.c
*/

use crate::error::{CompileError, CompileErrorType};
use rustpython_parser::ast;
use rustpython_parser::lexer::Location;
use std::collections::HashMap;

pub fn make_symbol_table(program: &ast::Program) -> Result<SymbolScope, SymbolTableError> {
    let mut builder = SymbolTableBuilder::new();
    builder.enter_scope();
    builder.scan_program(program)?;
    assert_eq!(builder.scopes.len(), 1);

    let symbol_table = builder.scopes.pop().unwrap();
    analyze_symbol_table(&symbol_table, None)?;
    Ok(symbol_table)
}

pub fn statements_to_symbol_table(
    statements: &[ast::LocatedStatement],
) -> Result<SymbolScope, SymbolTableError> {
    let mut builder = SymbolTableBuilder::new();
    builder.enter_scope();
    builder.scan_statements(statements)?;
    assert_eq!(builder.scopes.len(), 1);

    let symbol_table = builder.scopes.pop().unwrap();
    analyze_symbol_table(&symbol_table, None)?;
    Ok(symbol_table)
}

#[derive(Debug)]
pub enum SymbolRole {
    Global,
    Nonlocal,
    Used,
    Assigned,
}

/// Captures all symbols in the current scope, and has a list of subscopes in this scope.
pub struct SymbolScope {
    /// A set of symbols present on this scope level.
    pub symbols: HashMap<String, SymbolRole>,

    /// A list of subscopes in the order as found in the
    /// AST nodes.
    pub sub_scopes: Vec<SymbolScope>,
}

#[derive(Debug)]
pub struct SymbolTableError {
    error: String,
    location: Location,
}

impl From<SymbolTableError> for CompileError {
    fn from(error: SymbolTableError) -> Self {
        CompileError {
            error: CompileErrorType::SyntaxError(error.error),
            location: error.location,
        }
    }
}

type SymbolTableResult = Result<(), SymbolTableError>;

impl SymbolScope {
    pub fn new() -> Self {
        SymbolScope {
            symbols: HashMap::new(),
            sub_scopes: vec![],
        }
    }

    pub fn lookup(&self, name: &str) -> Option<&SymbolRole> {
        self.symbols.get(name)
    }
}

impl std::fmt::Debug for SymbolScope {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "SymbolScope({:?} symbols, {:?} sub scopes)",
            self.symbols.len(),
            self.sub_scopes.len()
        )
    }
}

/* Perform some sort of analysis on nonlocals, globals etc..
  See also: https://github.com/python/cpython/blob/master/Python/symtable.c#L410
*/
fn analyze_symbol_table(
    symbol_scope: &SymbolScope,
    parent_symbol_scope: Option<&SymbolScope>,
) -> SymbolTableResult {
    // Analyze sub scopes:
    for sub_scope in &symbol_scope.sub_scopes {
        analyze_symbol_table(&sub_scope, Some(symbol_scope))?;
    }

    // Analyze symbols:
    for (symbol_name, symbol_role) in &symbol_scope.symbols {
        analyze_symbol(symbol_name, symbol_role, parent_symbol_scope)?;
    }

    Ok(())
}

#[allow(clippy::single_match)]
fn analyze_symbol(
    symbol_name: &str,
    symbol_role: &SymbolRole,
    parent_symbol_scope: Option<&SymbolScope>,
) -> SymbolTableResult {
    match symbol_role {
        SymbolRole::Nonlocal => {
            // check if name is defined in parent scope!
            if let Some(parent_symbol_scope) = parent_symbol_scope {
                if !parent_symbol_scope.symbols.contains_key(symbol_name) {
                    return Err(SymbolTableError {
                        error: format!("no binding for nonlocal '{}' found", symbol_name),
                        location: Default::default(),
                    });
                }
            } else {
                return Err(SymbolTableError {
                    error: format!(
                        "nonlocal {} defined at place without an enclosing scope",
                        symbol_name
                    ),
                    location: Default::default(),
                });
            }
        }
        // TODO: add more checks for globals
        _ => {}
    }
    Ok(())
}

pub struct SymbolTableBuilder {
    // Scope stack.
    pub scopes: Vec<SymbolScope>,
}

impl SymbolTableBuilder {
    pub fn new() -> Self {
        SymbolTableBuilder { scopes: vec![] }
    }

    pub fn enter_scope(&mut self) {
        let scope = SymbolScope::new();
        self.scopes.push(scope);
    }

    fn leave_scope(&mut self) {
        // Pop scope and add to subscopes of parent scope.
        let scope = self.scopes.pop().unwrap();
        self.scopes.last_mut().unwrap().sub_scopes.push(scope);
    }

    pub fn scan_program(&mut self, program: &ast::Program) -> SymbolTableResult {
        self.scan_statements(&program.statements)?;
        Ok(())
    }

    pub fn scan_statements(&mut self, statements: &[ast::LocatedStatement]) -> SymbolTableResult {
        for statement in statements {
            self.scan_statement(statement)?;
        }
        Ok(())
    }

    fn scan_parameters(&mut self, parameters: &[ast::Parameter]) -> SymbolTableResult {
        for parameter in parameters {
            self.scan_parameter(parameter)?;
        }
        Ok(())
    }

    fn scan_parameter(&mut self, parameter: &ast::Parameter) -> SymbolTableResult {
        self.register_name(&parameter.arg, SymbolRole::Assigned)
    }

    fn scan_parameters_annotations(&mut self, parameters: &[ast::Parameter]) -> SymbolTableResult {
        for parameter in parameters {
            self.scan_parameter_annotation(parameter)?;
        }
        Ok(())
    }

    fn scan_parameter_annotation(&mut self, parameter: &ast::Parameter) -> SymbolTableResult {
        if let Some(annotation) = &parameter.annotation {
            self.scan_expression(&annotation)?;
        }
        Ok(())
    }

    fn scan_statement(&mut self, statement: &ast::LocatedStatement) -> SymbolTableResult {
        match &statement.node {
            ast::Statement::Global { names } => {
                for name in names {
                    self.register_name(name, SymbolRole::Global)?;
                }
            }
            ast::Statement::Nonlocal { names } => {
                for name in names {
                    self.register_name(name, SymbolRole::Nonlocal)?;
                }
            }
            ast::Statement::FunctionDef {
                name,
                body,
                args,
                decorator_list,
                returns,
            }
            | ast::Statement::AsyncFunctionDef {
                name,
                body,
                args,
                decorator_list,
                returns,
            } => {
                self.scan_expressions(decorator_list)?;
                self.register_name(name, SymbolRole::Assigned)?;

                self.enter_function(args)?;

                self.scan_statements(body)?;
                if let Some(expression) = returns {
                    self.scan_expression(expression)?;
                }
                self.leave_scope();
            }
            ast::Statement::ClassDef {
                name,
                body,
                bases,
                keywords,
                decorator_list,
            } => {
                self.register_name(name, SymbolRole::Assigned)?;
                self.enter_scope();
                self.scan_statements(body)?;
                self.leave_scope();
                self.scan_expressions(bases)?;
                for keyword in keywords {
                    self.scan_expression(&keyword.value)?;
                }
                self.scan_expressions(decorator_list)?;
            }
            ast::Statement::Expression { expression } => self.scan_expression(expression)?,
            ast::Statement::If { test, body, orelse } => {
                self.scan_expression(test)?;
                self.scan_statements(body)?;
                if let Some(code) = orelse {
                    self.scan_statements(code)?;
                }
            }
            ast::Statement::For {
                target,
                iter,
                body,
                orelse,
            }
            | ast::Statement::AsyncFor {
                target,
                iter,
                body,
                orelse,
            } => {
                self.scan_expression(target)?;
                self.scan_expression(iter)?;
                self.scan_statements(body)?;
                if let Some(code) = orelse {
                    self.scan_statements(code)?;
                }
            }
            ast::Statement::While { test, body, orelse } => {
                self.scan_expression(test)?;
                self.scan_statements(body)?;
                if let Some(code) = orelse {
                    self.scan_statements(code)?;
                }
            }
            ast::Statement::Break | ast::Statement::Continue | ast::Statement::Pass => {
                // No symbols here.
            }
            ast::Statement::Import { import_parts } => {
                for part in import_parts {
                    if let Some(alias) = &part.alias {
                        // `import mymodule as myalias`
                        self.register_name(alias, SymbolRole::Assigned)?;
                    } else {
                        if part.symbols.is_empty() {
                            // `import module`
                            self.register_name(&part.module, SymbolRole::Assigned)?;
                        } else {
                            // `from mymodule import myimport`
                            for symbol in &part.symbols {
                                if let Some(alias) = &symbol.alias {
                                    // `from mymodule import myimportname as myalias`
                                    self.register_name(alias, SymbolRole::Assigned)?;
                                } else {
                                    self.register_name(&symbol.symbol, SymbolRole::Assigned)?;
                                }
                            }
                        }
                    }
                }
            }
            ast::Statement::Return { value } => {
                if let Some(expression) = value {
                    self.scan_expression(expression)?;
                }
            }
            ast::Statement::Assert { test, msg } => {
                self.scan_expression(test)?;
                if let Some(expression) = msg {
                    self.scan_expression(expression)?;
                }
            }
            ast::Statement::Delete { targets } => {
                self.scan_expressions(targets)?;
            }
            ast::Statement::Assign { targets, value } => {
                self.scan_expressions(targets)?;
                self.scan_expression(value)?;
            }
            ast::Statement::AugAssign { target, value, .. } => {
                self.scan_expression(target)?;
                self.scan_expression(value)?;
            }
            ast::Statement::With { items, body } => {
                for item in items {
                    self.scan_expression(&item.context_expr)?;
                    if let Some(expression) = &item.optional_vars {
                        self.scan_expression(expression)?;
                    }
                }
                self.scan_statements(body)?;
            }
            ast::Statement::Try {
                body,
                handlers,
                orelse,
                finalbody,
            } => {
                self.scan_statements(body)?;
                for handler in handlers {
                    if let Some(expression) = &handler.typ {
                        self.scan_expression(expression)?;
                    }
                    if let Some(name) = &handler.name {
                        self.register_name(name, SymbolRole::Assigned)?;
                    }
                    self.scan_statements(&handler.body)?;
                }
                if let Some(code) = orelse {
                    self.scan_statements(code)?;
                }
                if let Some(code) = finalbody {
                    self.scan_statements(code)?;
                }
            }
            ast::Statement::Raise { exception, cause } => {
                if let Some(expression) = exception {
                    self.scan_expression(expression)?;
                }
                if let Some(expression) = cause {
                    self.scan_expression(expression)?;
                }
            }
        }
        Ok(())
    }

    fn scan_expressions(&mut self, expressions: &[ast::Expression]) -> SymbolTableResult {
        for expression in expressions {
            self.scan_expression(expression)?;
        }
        Ok(())
    }

    fn scan_expression(&mut self, expression: &ast::Expression) -> SymbolTableResult {
        match expression {
            ast::Expression::Binop { a, b, .. } => {
                self.scan_expression(a)?;
                self.scan_expression(b)?;
            }
            ast::Expression::BoolOp { a, b, .. } => {
                self.scan_expression(a)?;
                self.scan_expression(b)?;
            }
            ast::Expression::Compare { vals, .. } => {
                self.scan_expressions(vals)?;
            }
            ast::Expression::Subscript { a, b } => {
                self.scan_expression(a)?;
                self.scan_expression(b)?;
            }
            ast::Expression::Attribute { value, .. } => {
                self.scan_expression(value)?;
            }
            ast::Expression::Dict { elements } => {
                for (key, value) in elements {
                    if let Some(key) = key {
                        self.scan_expression(key)?;
                    } else {
                        // dict unpacking marker
                    }
                    self.scan_expression(value)?;
                }
            }
            ast::Expression::Await { value } => {
                self.scan_expression(value)?;
            }
            ast::Expression::Yield { value } => {
                if let Some(expression) = value {
                    self.scan_expression(expression)?;
                }
            }
            ast::Expression::YieldFrom { value } => {
                self.scan_expression(value)?;
            }
            ast::Expression::Unop { a, .. } => {
                self.scan_expression(a)?;
            }
            ast::Expression::True
            | ast::Expression::False
            | ast::Expression::None
            | ast::Expression::Ellipsis => {}
            ast::Expression::Number { .. } => {}
            ast::Expression::Starred { value } => {
                self.scan_expression(value)?;
            }
            ast::Expression::Bytes { .. } => {}
            ast::Expression::Tuple { elements }
            | ast::Expression::Set { elements }
            | ast::Expression::List { elements }
            | ast::Expression::Slice { elements } => {
                self.scan_expressions(elements)?;
            }
            ast::Expression::Comprehension { kind, generators } => {
                match **kind {
                    ast::ComprehensionKind::GeneratorExpression { ref element }
                    | ast::ComprehensionKind::List { ref element }
                    | ast::ComprehensionKind::Set { ref element } => {
                        self.scan_expression(element)?;
                    }
                    ast::ComprehensionKind::Dict { ref key, ref value } => {
                        self.scan_expression(&key)?;
                        self.scan_expression(&value)?;
                    }
                }

                for generator in generators {
                    self.scan_expression(&generator.target)?;
                    self.scan_expression(&generator.iter)?;
                    for if_expr in &generator.ifs {
                        self.scan_expression(if_expr)?;
                    }
                }
            }
            ast::Expression::Call {
                function,
                args,
                keywords,
            } => {
                self.scan_expression(function)?;
                self.scan_expressions(args)?;
                for keyword in keywords {
                    self.scan_expression(&keyword.value)?;
                }
            }
            ast::Expression::String { value } => {
                self.scan_string_group(value)?;
            }
            ast::Expression::Identifier { name } => {
                self.register_name(name, SymbolRole::Used)?;
            }
            ast::Expression::Lambda { args, body } => {
                self.enter_function(args)?;
                self.scan_expression(body)?;
                self.leave_scope();
            }
            ast::Expression::IfExpression { test, body, orelse } => {
                self.scan_expression(test)?;
                self.scan_expression(body)?;
                self.scan_expression(orelse)?;
            }
        }
        Ok(())
    }

    fn enter_function(&mut self, args: &ast::Parameters) -> SymbolTableResult {
        // Evaluate eventual default parameters:
        self.scan_expressions(&args.defaults)?;
        for kw_default in &args.kw_defaults {
            if let Some(expression) = kw_default {
                self.scan_expression(&expression)?;
            }
        }

        // Annotations are scanned in outer scope:
        self.scan_parameters_annotations(&args.args)?;
        self.scan_parameters_annotations(&args.kwonlyargs)?;
        if let ast::Varargs::Named(name) = &args.vararg {
            self.scan_parameter_annotation(name)?;
        }
        if let ast::Varargs::Named(name) = &args.kwarg {
            self.scan_parameter_annotation(name)?;
        }

        self.enter_scope();

        // Fill scope with parameter names:
        self.scan_parameters(&args.args)?;
        self.scan_parameters(&args.kwonlyargs)?;
        if let ast::Varargs::Named(name) = &args.vararg {
            self.scan_parameter(name)?;
        }
        if let ast::Varargs::Named(name) = &args.kwarg {
            self.scan_parameter(name)?;
        }
        Ok(())
    }

    fn scan_string_group(&mut self, group: &ast::StringGroup) -> SymbolTableResult {
        match group {
            ast::StringGroup::Constant { .. } => {}
            ast::StringGroup::FormattedValue { value, .. } => {
                self.scan_expression(value)?;
            }
            ast::StringGroup::Joined { values } => {
                for subgroup in values {
                    self.scan_string_group(subgroup)?;
                }
            }
        }
        Ok(())
    }

    #[allow(clippy::single_match)]
    fn register_name(&mut self, name: &str, role: SymbolRole) -> SymbolTableResult {
        let scope_depth = self.scopes.len();
        let current_scope = self.scopes.last_mut().unwrap();
        let location = Default::default();
        if current_scope.symbols.contains_key(name) {
            // Role already set..
            match role {
                SymbolRole::Global => {
                    return Err(SymbolTableError {
                        error: format!("name '{}' is used prior to global declaration", name),
                        location,
                    })
                }
                SymbolRole::Nonlocal => {
                    return Err(SymbolTableError {
                        error: format!("name '{}' is used prior to nonlocal declaration", name),
                        location,
                    })
                }
                _ => {
                    // Ok?
                }
            }
        } else {
            match role {
                SymbolRole::Nonlocal => {
                    if scope_depth < 2 {
                        return Err(SymbolTableError {
                            error: format!("cannot define nonlocal '{}' at top level.", name),
                            location,
                        });
                    }
                }
                _ => {
                    // Ok!
                }
            }
            current_scope.symbols.insert(name.to_string(), role);
        }
        Ok(())
    }
}