pythonrs 0.1.10

Python as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a PyHost heap — the first compiled standalone Python runtime
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
//! Python abstract syntax tree.
//!
//! Faithful to CPython's surface grammar as far as pythonrs lowers it today:
//! every node here has a direct lowering in `compiler.rs`. Unlike Ruby, Python
//! is statement-oriented — most control flow is a `Stmt` that yields no value —
//! so the tree separates `Stmt` (blocks of these form suites) from `Expr`.

/// A binary arithmetic/bit operator (Python `a <op> b`). Comparison and boolean
/// operators are separate (`Compare`, `BoolOp`) because Python chains them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,      // `/` — true division (always float in Python 3)
    FloorDiv, // `//`
    Mod,      // `%`
    Pow,      // `**`
    MatMul,   // `@`
    BitAnd,
    BitOr,
    BitXor,
    Shl,
    Shr,
}

/// A boolean short-circuit operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoolOp {
    And,
    Or,
}

/// A comparison operator (one link of a `Compare` chain).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CmpOp {
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    Is,
    IsNot,
    In,
    NotIn,
}

/// A unary operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
    Neg,    // -x
    Pos,    // +x
    Not,    // not x
    Invert, // ~x
}

/// A formatted-string segment (`f"..."`).
#[derive(Debug, Clone, PartialEq)]
pub enum FStrPart {
    Lit(String),
    /// `{expr!conv:spec}` — `conv` is 's'/'r'/'a' or none. `spec` is the format
    /// spec parsed as its own mini joined-string: an empty vec means no spec,
    /// literal text is a `Lit`, and a nested replacement field (`{w}` in
    /// `{x:{w}.2f}`) is an `Expr` evaluated at runtime and spliced into the spec.
    Expr {
        expr: Box<Expr>,
        /// The field's source text, verbatim. f-strings ignore it; a t-string
        /// exposes it as `Interpolation.expression` (PEP 750), which is the whole
        /// point of a template — the consumer sees what was written, not just the
        /// value it evaluated to.
        src: String,
        conv: Option<char>,
        spec: Vec<FStrPart>,
    },
}

/// One `(target, iter, ifs)` clause of a comprehension.
#[derive(Debug, Clone, PartialEq)]
pub struct Comprehension {
    pub target: Box<Expr>,
    pub iter: Box<Expr>,
    pub ifs: Vec<Expr>,
    /// `async for` clause (an asynchronous comprehension), driven via `__anext__`.
    pub is_async: bool,
}

/// A keyword argument at a call site: `name=value`, or `**mapping` when `name`
/// is `None`.
#[derive(Debug, Clone, PartialEq)]
pub struct Keyword {
    pub name: Option<String>,
    pub value: Expr,
}

/// A source span for traceback carets: character columns within a 1-based
/// `line`. `line == 0` marks "no span" (synthetic/desugared nodes). When
/// `anchor_end > anchor_start`, the `[anchor_start, anchor_end)` sub-range
/// renders the secondary caret `^` and the rest of `[start, end)` renders the
/// primary caret `~` — CPython's `~^~` binary-op and `~~~^^^` subscript/call
/// anchoring. With no anchor the whole `[start, end)` renders `^`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub struct Span {
    pub line: u32,
    pub start: u32,
    pub end: u32,
    pub anchor_start: u32,
    pub anchor_end: u32,
    /// This op is the direct call value of an `x = f(...)` / `return f(...)`
    /// statement, whose caret CPython suppresses when the call raises.
    pub suppress: bool,
}

impl Span {
    pub const NONE: Span = Span {
        line: 0,
        start: 0,
        end: 0,
        anchor_start: 0,
        anchor_end: 0,
        suppress: false,
    };
    pub fn is_some(&self) -> bool {
        self.line != 0
    }
    pub fn has_anchor(&self) -> bool {
        self.anchor_end > self.anchor_start
    }
}

/// A Python expression.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    None,
    True,
    False,
    Ellipsis,
    Int(i64),
    /// An integer literal too wide for `i64` (kept as text; host promotes it).
    BigInt(String),
    Float(f64),
    Complex(f64),
    Str(String),
    Bytes(Vec<u8>),
    FString(Vec<FStrPart>),
    /// PEP 750 `t"..."` — evaluates to a `string.templatelib.Template`, not a str.
    TString(Vec<FStrPart>),

    /// A bare name (`x`); the compiler resolves scope (LEGB) at runtime.
    Name(String),

    List(Vec<Expr>),
    Tuple(Vec<Expr>),
    Set(Vec<Expr>),
    /// key/value pairs; a `None` key is a `**mapping` spread.
    Dict(Vec<(Option<Expr>, Expr)>),

    /// `*expr` — a starred element (call arg / assignment target / iterable
    /// unpack).
    Starred(Box<Expr>),

    BoolOp(BoolOp, Vec<Expr>),
    UnaryOp(UnOp, Box<Expr>),
    BinOp(BinOp, Box<Expr>, Box<Expr>),
    /// `a < b <= c` — a chained comparison: left plus (op, rhs) links.
    Compare(Box<Expr>, Vec<(CmpOp, Expr)>),

    /// `body if test else orelse`.
    IfExp {
        test: Box<Expr>,
        body: Box<Expr>,
        orelse: Box<Expr>,
    },

    /// A call `func(args, keywords)`.
    Call {
        func: Box<Expr>,
        args: Vec<Expr>,
        keywords: Vec<Keyword>,
    },
    /// `value.attr`.
    Attribute(Box<Expr>, String),
    /// `value[slice]`.
    Subscript(Box<Expr>, Box<Expr>),
    /// `lo:hi:step` inside a subscript. Any bound may be absent.
    Slice {
        lo: Option<Box<Expr>>,
        hi: Option<Box<Expr>>,
        step: Option<Box<Expr>>,
    },

    /// `lambda params: body`.
    Lambda {
        params: Params,
        body: Box<Expr>,
    },

    ListComp(Box<Expr>, Vec<Comprehension>),
    SetComp(Box<Expr>, Vec<Comprehension>),
    /// `{k: v for ...}`.
    DictComp(Box<Expr>, Box<Expr>, Vec<Comprehension>),
    GenExp(Box<Expr>, Vec<Comprehension>),

    /// `yield expr` / `yield` (None) as an expression.
    Yield(Option<Box<Expr>>),
    YieldFrom(Box<Expr>),
    /// `await expr`.
    Await(Box<Expr>),

    /// `:=` walrus in an expression context.
    NamedExpr(Box<Expr>, Box<Expr>),

    /// An expression carrying its source span, attached by the parser to the
    /// caret-bearing forms (name load, binary op, subscript, call, attribute,
    /// unary op). The compiler peels it and records the span for the raising op;
    /// every other consumer treats `Spanned(e, _)` as `e` via `Expr::unspanned`.
    Spanned(Box<Expr>, Span),
}

impl Expr {
    /// Peel any `Spanned` wrapper(s), returning the underlying expression. Used
    /// wherever code matches on expression structure (assignment targets, walrus
    /// targets, constant folding) so a wrapped node is treated as its inner form.
    pub fn unspanned(&self) -> &Expr {
        let mut e = self;
        while let Expr::Spanned(inner, _) = e {
            e = inner;
        }
        e
    }
    /// The span wrapping this expression, or `Span::NONE`.
    pub fn span(&self) -> Span {
        match self {
            Expr::Spanned(_, s) => *s,
            _ => Span::NONE,
        }
    }
}

/// A formal-parameter list for a `def`/`lambda`.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Params {
    /// Positional-or-keyword parameter names, in order.
    pub names: Vec<String>,
    /// Default expressions for the trailing `defaults.len()` positional params.
    pub defaults: Vec<Expr>,
    /// Count of leading positional-only params (before `/`).
    pub posonly: usize,
    /// `*args` collector name, if any (bare `*` records `Some("")` to open the
    /// keyword-only section without collecting).
    pub star: Option<String>,
    /// Keyword-only parameter names (after `*`).
    pub kwonly: Vec<String>,
    /// Defaults for keyword-only params (`None` = required).
    pub kwonly_defaults: Vec<Option<Expr>>,
    /// `**kwargs` collector name, if any.
    pub kwargs: Option<String>,
    /// Parameter/return annotations in source order, as `(name, expr)` pairs
    /// (the return annotation uses the name `"return"`). Evaluated at def time to
    /// build the function's `__annotations__` dict. Empty for a `lambda` or an
    /// unannotated `def`.
    pub annotations: Vec<(String, Expr)>,
}

/// One `except` clause of a `try`.
#[derive(Debug, Clone, PartialEq)]
pub struct ExceptHandler {
    /// The exception type expression(s); `None` is a bare `except:`.
    pub typ: Option<Expr>,
    /// `as name` binding.
    pub name: Option<String>,
    pub body: Vec<Stmt>,
    /// `except*` (exception groups).
    pub star: bool,
}

/// One `with` item: `context_expr [as optional_vars]`.
#[derive(Debug, Clone, PartialEq)]
pub struct WithItem {
    pub context: Expr,
    pub vars: Option<Expr>,
}

/// A Python statement.
#[derive(Debug, Clone, PartialEq)]
pub enum StmtKind {
    /// An expression evaluated for effect (its value is discarded, except at the
    /// REPL top level).
    Expr(Expr),
    /// `targets... = value` (chained assignment: `a = b = expr`).
    Assign {
        targets: Vec<Expr>,
        value: Expr,
    },
    /// `target op= value`.
    AugAssign {
        target: Expr,
        op: BinOp,
        value: Expr,
    },
    /// `target: annotation [= value]`.
    AnnAssign {
        target: Expr,
        annotation: Expr,
        value: Option<Expr>,
    },

    If {
        test: Expr,
        body: Vec<Stmt>,
        orelse: Vec<Stmt>,
    },
    While {
        test: Expr,
        body: Vec<Stmt>,
        orelse: Vec<Stmt>,
    },
    For {
        target: Expr,
        iter: Expr,
        body: Vec<Stmt>,
        orelse: Vec<Stmt>,
        is_async: bool,
    },
    With {
        items: Vec<WithItem>,
        body: Vec<Stmt>,
        is_async: bool,
    },

    FuncDef {
        name: String,
        params: Params,
        body: Vec<Stmt>,
        decorators: Vec<Expr>,
        is_async: bool,
    },
    ClassDef {
        name: String,
        bases: Vec<Expr>,
        keywords: Vec<Keyword>,
        body: Vec<Stmt>,
        decorators: Vec<Expr>,
    },

    Return(Option<Expr>),
    Delete(Vec<Expr>),
    Pass,
    Break,
    Continue,

    Import(Vec<Alias>),
    ImportFrom {
        module: Option<String>,
        names: Vec<Alias>,
        level: usize,
    },

    Global(Vec<String>),
    Nonlocal(Vec<String>),

    Raise {
        exc: Option<Expr>,
        cause: Option<Expr>,
    },
    Try {
        body: Vec<Stmt>,
        handlers: Vec<ExceptHandler>,
        orelse: Vec<Stmt>,
        finalbody: Vec<Stmt>,
    },
    Assert {
        test: Expr,
        msg: Option<Expr>,
    },
    /// `match subject: case ...` — structural pattern matching (Python 3.10).
    Match {
        subject: Expr,
        cases: Vec<MatchCase>,
    },
}

/// One `case pattern [if guard]: body` of a `match`.
#[derive(Debug, Clone, PartialEq)]
pub struct MatchCase {
    pub pattern: Pattern,
    pub guard: Option<Expr>,
    pub body: Vec<Stmt>,
}

/// A `match` pattern (PEP 634).
#[derive(Debug, Clone, PartialEq)]
pub enum Pattern {
    /// `_` — matches anything, binds nothing.
    Wildcard,
    /// A capture name — matches anything, binds it.
    Capture(String),
    /// A literal or dotted-value pattern (`1`, `"x"`, `None`, `Color.RED`),
    /// matched by `==`.
    Value(Expr),
    /// `p | q | ...` — matches if any alternative matches.
    Or(Vec<Pattern>),
    /// `pattern as name` — matches the sub-pattern and binds `name` to the whole.
    As(Box<Pattern>, String),
    /// `[p, *rest, q]` — a sequence pattern. `star` is the index of the `*` slot.
    Sequence {
        elems: Vec<Pattern>,
        star: Option<usize>,
    },
    /// `*name` / `*_` inside a sequence pattern.
    Star(Option<String>),
    /// `{key: p, ..., **rest}` — a mapping pattern.
    Mapping {
        keys: Vec<(Expr, Pattern)>,
        rest: Option<String>,
    },
    /// `ClassName(pos..., kw=pat...)` — a class pattern.
    Class {
        cls: Expr,
        pos: Vec<Pattern>,
        kw: Vec<(String, Pattern)>,
    },
}

/// An `import` alias: `name [as asname]`.
#[derive(Debug, Clone, PartialEq)]
pub struct Alias {
    pub name: String,
    pub asname: Option<String>,
}

/// A statement plus its 1-based source line (for tracebacks and DAP markers).
#[derive(Debug, Clone, PartialEq)]
pub struct Stmt {
    pub kind: StmtKind,
    pub line: u32,
}

impl Stmt {
    pub fn new(kind: StmtKind, line: u32) -> Stmt {
        Stmt { kind, line }
    }
}

impl From<StmtKind> for Stmt {
    /// Wrap a `StmtKind` as a synthetic statement (line 0). Used for desugared
    /// bodies with no source line; the debug marker skips line-0 statements so
    /// they never become spurious breakpoint targets.
    fn from(kind: StmtKind) -> Stmt {
        Stmt { kind, line: 0 }
    }
}