go-rs 0.1.2

Go on the fusevm bytecode VM — compiles to fusevm::Chunk, runs on a shared three-tier Cranelift JIT
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
//! The Go abstract syntax tree go-rs parses into and lowers from.
//!
//! Models a single-file `package main` program: a package clause, imports,
//! `type T struct` declarations, and top-level `func` / method declarations.
//! `func main` is the entry point; every other `func` (and every method)
//! becomes a fusevm subroutine (see [`crate::compiler`]). The grammar covers
//! arithmetic/control flow, composite types (slices, maps, structs, interfaces,
//! indexing, `range`, composite literals), and concurrency (`go`, `chan`, `<-`,
//! `close`) lowered onto fusevm's cooperative scheduler.

/// A parsed Go source file.
#[derive(Debug, Clone)]
pub struct Program {
    /// The package name (`package main` → `"main"`).
    pub package: String,
    /// Imported package paths, in source order (e.g. `"fmt"`).
    pub imports: Vec<String>,
    /// `type T struct { … }` declarations.
    pub types: Vec<StructDecl>,
    /// `type I interface { … }` declarations (method-set names).
    pub interfaces: Vec<InterfaceDecl>,
    /// The body of `func main`, run in the global scope.
    pub main: Vec<Stmt>,
    /// Every top-level `func` other than `main` (including methods), lowered to
    /// subroutines.
    pub funcs: Vec<Func>,
    /// `type Name <base>` over a non-struct, non-interface base, as name → the
    /// base type as written. A defined type shares its base's representation, so
    /// it is transparent to every operation; the name is carried only where Go
    /// makes it observable — `%T`, `%#v` and method dispatch.
    pub defined: Vec<(String, String)>,
}

/// A `type T struct { field T; … }` declaration.
#[derive(Debug, Clone)]
pub struct StructDecl {
    pub name: String,
    pub fields: Vec<Param>,
}

/// A `type I interface { m(...) ...; … }` declaration — its method-set names.
#[derive(Debug, Clone)]
pub struct InterfaceDecl {
    pub name: String,
    /// The method set, each entry encoded by [`method_sig`].
    pub methods: Vec<String>,
}

/// The canonical encoding of one method in a method set: `name/arity:results`
/// (`Unwrap/0:error`, `Unwrap/0:[]error`, `Is/1:bool`).
///
/// Interface satisfaction compares method *signatures*, not just names — the
/// `errors` package turns on telling `Unwrap() error` from `Unwrap() []error`
/// apart. Parameter *types* are not part of the encoding, only how many there
/// are: go-rs cannot tell a named parameter from an unnamed one in an interface
/// method without a full type parse, and two same-named methods that differ only
/// in parameter types do not arise in practice.
pub fn method_sig(name: &str, arity: usize, results: &[String]) -> String {
    format!("{name}/{arity}:{}", results.join(","))
}

/// A top-level function or method declaration.
#[derive(Debug, Clone)]
pub struct Func {
    pub name: String,
    /// The receiver for a method (`func (r T) m()`); `None` for a plain `func`.
    pub receiver: Option<Param>,
    pub params: Vec<Param>,
    /// True if the last parameter is variadic (`args ...T`); inside the body it
    /// binds a slice of the trailing arguments.
    pub variadic: bool,
    /// Result types in declaration order.
    pub results: Vec<String>,
    /// Result names, aligned with `results` (`""` for an unnamed result). When
    /// any result is named, they become zero-initialized locals the body can read
    /// and assign, and a bare `return` yields their current values.
    pub result_names: Vec<String>,
    pub body: Vec<Stmt>,
    pub line: u32,
}

/// A single function parameter: a name and its declared Go type.
#[derive(Debug, Clone)]
pub struct Param {
    pub name: String,
    pub ty: String,
}

/// A statement.
#[derive(Debug, Clone)]
pub enum Stmt {
    /// `var name [T] [= init]`.
    Var {
        name: String,
        ty: Option<String>,
        init: Option<Expr>,
        line: u32,
    },
    /// `name, ... := expr, ...` (short variable declaration).
    Short {
        names: Vec<String>,
        values: Vec<Expr>,
        line: u32,
    },
    /// `target op= value` (op = `=`, `+=`, `-=`, `*=`, `/=`, `%=`). The target
    /// is an lvalue: an identifier, an index (`x[i]`), or a field (`x.f`).
    Assign {
        target: Expr,
        op: AssignOp,
        value: Expr,
        line: u32,
    },
    /// `t0, t1, … = v0, v1, …` — parallel assignment to existing lvalues. All
    /// right-hand sides are evaluated before any assignment (so `a, b = b, a`
    /// swaps).
    AssignMulti {
        targets: Vec<Expr>,
        values: Vec<Expr>,
        line: u32,
    },
    /// `target++` / `target--` (target is an lvalue expression).
    IncDec { target: Expr, inc: bool, line: u32 },
    /// A bare expression evaluated for effect (e.g. a call).
    ExprStmt(Expr),
    /// `return [expr [, expr …]]` — zero, one, or multiple result values.
    Return(Vec<Expr>, u32),
    /// `if [init;] cond { then } [else els]`.
    If {
        init: Option<Box<Stmt>>,
        cond: Expr,
        then: Vec<Stmt>,
        els: Vec<Stmt>,
        line: u32,
    },
    /// `for [init;] [cond;] [post] { body }` — covers the infinite, condition-
    /// only, and three-clause forms.
    For {
        /// The `label:` written before this loop, if any. See [`Stmt::Break`].
        label: Option<String>,
        init: Option<Box<Stmt>>,
        cond: Option<Expr>,
        post: Option<Box<Stmt>>,
        body: Vec<Stmt>,
        line: u32,
    },
    /// `for [key[, val]] := range iter { body }` over a slice, map, or string.
    /// `define` is true for `:=`, false for `=`; `key`/`val` are `None` for the
    /// blank identifier `_` or an omitted value.
    ForRange {
        /// The `label:` written before this loop, if any.
        label: Option<String>,
        key: Option<String>,
        val: Option<String>,
        define: bool,
        iter: Expr,
        body: Vec<Stmt>,
        line: u32,
    },
    /// `go f(args)` — spawn a goroutine running the named function.
    Go { call: Expr, line: u32 },
    /// `defer f(args)` — evaluate `f` and `args` now, call at function return in
    /// LIFO order.
    Defer { call: Expr, line: u32 },
    /// `ch <- val` — send `val` on channel `ch`.
    Send { chan: Expr, val: Expr, line: u32 },
    /// `select { case …: …; default: … }` over channel operations.
    Select {
        cases: Vec<SelectClause>,
        default: Option<Vec<Stmt>>,
        line: u32,
    },
    /// `switch [init;] [tag] { case …: …; default: … }`. With no `tag`, each
    /// case expression is a boolean condition (expression switch). Cases run the
    /// first match then break (no implicit fallthrough).
    Switch {
        /// The `label:` written before this switch, if any — a labeled `break`
        /// may leave a `switch`, though a labeled `continue` may not.
        label: Option<String>,
        init: Option<Box<Stmt>>,
        tag: Option<Expr>,
        cases: Vec<SwitchCase>,
        default: Option<Vec<Stmt>>,
        line: u32,
    },
    /// `switch [init;] [v :=] x.(type) { case T: … }` — dispatch on the runtime
    /// type of `x`. `bind` names the value (as `v`) inside each case body.
    TypeSwitch {
        init: Option<Box<Stmt>>,
        bind: Option<String>,
        expr: Expr,
        cases: Vec<TypeSwitchCase>,
        default: Option<Vec<Stmt>>,
        line: u32,
    },
    /// `fallthrough` — transfer to the next `switch` case's body.
    Fallthrough(u32),
    /// `break`.
    /// `break` / `break label` — the label names an enclosing labeled loop or
    /// `switch`, which is the one this leaves.
    Break(u32, Option<String>),
    /// `continue`.
    /// `continue` / `continue label` — the label names the enclosing labeled
    /// loop whose next iteration to step to.
    Continue(u32, Option<String>),
    /// A `{ ... }` block.
    Block(Vec<Stmt>),
}

/// One `case` clause of a `switch`: the case expressions (`case a, b:` matches
/// either) and the statements to run.
#[derive(Debug, Clone)]
pub struct SwitchCase {
    pub exprs: Vec<Expr>,
    pub body: Vec<Stmt>,
}

/// One `case` clause of a type switch: the case types (`case int, string:`) and
/// the statements to run.
#[derive(Debug, Clone)]
pub struct TypeSwitchCase {
    pub types: Vec<String>,
    pub body: Vec<Stmt>,
}

/// One `case` clause of a `select`.
#[derive(Debug, Clone)]
pub struct SelectClause {
    pub comm: SelectComm,
    pub body: Vec<Stmt>,
}

/// The communication operation of a `select` case.
#[derive(Debug, Clone)]
pub enum SelectComm {
    /// `case [v :=] <-ch:` — receive, optionally binding the value.
    Recv {
        bind: Option<String>,
        /// The `ok` of `case v, ok := <-ch:` — false when the channel is closed
        /// and drained, which is a *ready* case rather than a blocked one.
        ok_bind: Option<String>,
        chan: Expr,
    },
    /// `case ch <- val:` — send.
    Send { chan: Expr, val: Expr },
}

/// Compound-assignment operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssignOp {
    Set,
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    BitAnd,
    BitOr,
    BitXor,
    Shl,
    Shr,
    AndNot,
}

/// An expression.
#[derive(Debug, Clone)]
pub enum Expr {
    Int(i64),
    /// A float literal: its `f64` value plus, when representable, an exact
    /// decimal `(mantissa, scale)` (`mantissa · 10⁻ˢᶜᵃˡᵉ`) for constant folding.
    Float(f64, Option<(i128, i32)>),
    Str(String),
    Bool(bool),
    Ident(String),
    /// A unary operation (`-x`, `!x`).
    Unary {
        op: UnOp,
        rhs: Box<Expr>,
    },
    /// A binary operation.
    Binary {
        op: BinOp,
        lhs: Box<Expr>,
        rhs: Box<Expr>,
    },
    /// A call `func(args)`. `spread` is true for `f(xs...)` — the last argument
    /// is a slice expanded into the callee's variadic parameter.
    Call {
        func: Box<Expr>,
        args: Vec<Expr>,
        spread: bool,
        line: u32,
    },
    /// A selector `recv.field` (e.g. `fmt.Println`, or a struct field read).
    Selector {
        recv: Box<Expr>,
        field: String,
    },
    /// An index `recv[index]` — slice element or map lookup.
    Index {
        recv: Box<Expr>,
        index: Box<Expr>,
    },
    /// A slice expression `recv[low:high]` (either bound optional: `s[lo:]`,
    /// `s[:hi]`, `s[:]`), or the three-index full slice `recv[low:high:max]`
    /// whose `max` caps the result's capacity at `max - low`.
    Slice {
        recv: Box<Expr>,
        low: Option<Box<Expr>>,
        high: Option<Box<Expr>>,
        max: Option<Box<Expr>>,
    },
    /// A slice composite literal `[]T{elems}`, or — when `array_len` is set — a
    /// fixed-size array literal `[N]T{elems}` / `[...]T{elems}`.
    ///
    /// Both build the same heap object; the length is what separates them, and
    /// it is what the *static* type says. A Go array is a **value**: it is
    /// copied at assignment, argument bind, return, container read/store,
    /// channel send, `append` and `range`. A slice is a reference. Carrying the
    /// length here is what lets the compiler name the type `[N]T` rather than
    /// `[]T` and so fire those copies (`Compiler::emit_copy_for`).
    SliceLit {
        elem_ty: String,
        elems: Vec<Expr>,
        array_len: Option<usize>,
    },
    /// A map composite literal `map[K]V{k: v, …}`.
    MapLit {
        key_ty: String,
        val_ty: String,
        pairs: Vec<(Expr, Expr)>,
    },
    /// A struct composite literal `T{…}` (positional or `field: value`).
    StructLit {
        type_name: String,
        fields: Vec<(Option<String>, Expr)>,
    },
    /// `make([]T, len)` (a slice) or `make(map[K]V)` (a map). `elem_zero` is the
    /// slice element's zero value, `elem_ty` the element type as written (which
    /// fixes the width of arithmetic on an element).
    Make {
        is_map: bool,
        elem_ty: String,
        len: Option<Box<Expr>>,
        /// `make([]T, len, cap)`'s third argument. The slice's backing array is
        /// `cap` long, so `cap(s)` reports it and appends up to it write in
        /// place instead of reallocating.
        cap: Option<Box<Expr>>,
        elem_zero: Box<Expr>,
    },
    /// `make(chan T, cap)` — a channel with buffer capacity `cap` (0 if omitted).
    /// `elem_ty` is the written `T`: a receive from a closed channel yields that
    /// type's zero value, which the compiler can only emit if it kept the type.
    MakeChan {
        cap: Option<Box<Expr>>,
        elem_ty: String,
    },
    /// `<-ch` — receive a value from channel `ch`.
    Recv {
        chan: Box<Expr>,
    },
    /// A function literal `func(params) results { body }` — a closure. Captured
    /// variables (free vars of the body) are bound by value at creation.
    FuncLit {
        params: Vec<Param>,
        results: Vec<String>,
        body: Vec<Stmt>,
    },
    /// A type assertion `expr.(ty)` (`ty == "type"` marks the type-switch guard).
    TypeAssert {
        expr: Box<Expr>,
        ty: String,
    },
}

/// Unary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
    Neg,
    Not,
    /// `^x` — bitwise complement.
    BitNot,
    /// `&x` — address-of. go-rs composite values are heap handles (reference
    /// types), so this is a no-copy reference.
    Addr,
    /// `*p` — pointer dereference; identity on a go-rs handle.
    Deref,
}

/// Binary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Eq,
    Ne,
    Lt,
    Gt,
    Le,
    Ge,
    And,
    Or,
    /// Bitwise `&` `|` `^` `<<` `>>` `&^` (integer operations).
    BitAnd,
    BitOr,
    BitXor,
    Shl,
    Shr,
    AndNot,
}

/// Attach a `label:` to the statement it introduces. Only a `for` or a `switch`
/// can carry one, because those are the only things a labeled `break` or
/// `continue` can name; anything else is a compile error rather than a label
/// that silently binds to nothing.
pub fn set_stmt_label(s: &mut Stmt, name: &str) -> bool {
    match s {
        Stmt::For { label, .. } | Stmt::ForRange { label, .. } | Stmt::Switch { label, .. } => {
            *label = Some(name.to_string());
            true
        }
        _ => false,
    }
}

/// The element type of a written fixed-size array type `[N]T`, or `None` for
/// anything else — including the slice type `[]T`, whose empty bracket is the
/// one thing that distinguishes the two spellings.
///
/// `[N]T` is the *value* form and `[]T` the reference form, so this predicate is
/// what every copy site consults. `N` is already folded to a decimal literal by
/// the parser, so it never contains a bracket of its own and the first `]` is
/// the closing one. A size the parser could not fold is written `[]T`, which
/// reads here as a slice — the pre-array behaviour, not a wrong answer about a
/// different type.
pub fn array_elem_ty(ty: &str) -> Option<&str> {
    let rest = ty.strip_prefix('[')?;
    let close = rest.find(']')?;
    if close == 0 {
        return None; // `[]T` — a slice.
    }
    Some(&rest[close + 1..])
}

/// The length of a written fixed-size array type `[N]T`, or `None`.
pub fn array_len_of(ty: &str) -> Option<usize> {
    let rest = ty.strip_prefix('[')?;
    let close = rest.find(']')?;
    rest[..close].parse().ok()
}