Skip to main content

xur_bytecode/
ir.rs

1//! The instruction set.
2//!
3//! A [`Function`] is a control-flow graph of [`Block`]s over virtual
4//! registers. Each block runs its instructions in order and ends in a
5//! [`Terminator`] that picks the next block. Registers hold dynamically
6//! typed values; nothing here assumes types, so the same code can be
7//! interpreted or, later, compiled by a JIT that specialises it.
8
9use std::fmt;
10use std::sync::Arc;
11
12use xur_ast::{BinOpKind, UnOp};
13use xur_resolve::{DefId, ModuleIdx, NativeFnId, NativeTypeId};
14use xur_span::{Span, Symbol};
15
16/// A virtual register of a function.
17#[derive(Clone, Copy, PartialEq, Eq, Hash)]
18pub struct Reg(pub u32);
19
20impl fmt::Debug for Reg {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        write!(f, "r{}", self.0)
23    }
24}
25
26/// A basic block of a function; `BlockId(0)` is the entry.
27#[derive(Clone, Copy, PartialEq, Eq, Hash)]
28pub struct BlockId(pub u32);
29
30impl fmt::Debug for BlockId {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        write!(f, "bb{}", self.0)
33    }
34}
35
36#[derive(Debug)]
37pub struct Function {
38    /// The function's path, e.g. `Shape::area`, or `<closure>`.
39    pub name: String,
40    /// The module the function is in, for module-relative operations such
41    /// as `std::import` of a relative path.
42    pub module: ModuleIdx,
43    /// For a closure, the number of captured values, passed in the first
44    /// registers.
45    pub captures: u32,
46    /// The number of parameters, passed in the registers after the
47    /// captures.
48    pub params: u32,
49    pub registers: u32,
50    /// How many of `type_params` come from the enclosing impl block.
51    pub impl_type_param_count: u32,
52    /// The function's type parameters, which calls bind by position.
53    pub type_params: Vec<Symbol>,
54    /// Which type parameters are required (`T!`): the caller must provide
55    /// a concrete type, not `_`.
56    pub type_param_required: Vec<bool>,
57    /// For each parameter, the type-parameter index it uses, if any.
58    /// Enables runtime inference of generic args from argument values.
59    pub param_type_params: Vec<Option<u32>>,
60    /// The declared name of each parameter, for reflection.
61    pub param_names: Vec<Option<Symbol>>,
62    /// The declared type of each parameter, for reflection.
63    pub param_types: Vec<Option<RtType>>,
64    /// The declared return type, for reflection.
65    pub ret_type: Option<RtType>,
66    pub decorators: Vec<Decorator>,
67    pub blocks: Vec<Block>,
68    /// The bodies of closures created by this function, by index.
69    pub closures: Vec<Arc<Function>>,
70    pub span: Span,
71}
72
73#[derive(Debug)]
74pub struct Block {
75    pub insts: Vec<Inst>,
76    pub term: Terminator,
77    /// Where the terminator came from, for its runtime errors.
78    pub term_span: Span,
79}
80
81#[derive(Debug)]
82pub struct Inst {
83    pub kind: InstKind,
84    pub span: Span,
85}
86
87#[derive(Debug, Clone, PartialEq)]
88pub enum Constant {
89    Unit,
90    Bool(bool),
91    Int(i64),
92    Float(f64),
93    Str(Arc<str>),
94    Bytes(Arc<[u8]>),
95}
96
97/// A definition used as a value.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum DefRef {
100    /// A function written in Xur.
101    Fn(DefId),
102    /// A tuple struct's or tuple variant's constructor, as a function.
103    Ctor(DefId),
104    /// A constant, evaluated the first time it is used.
105    Const(DefId),
106    Module(DefId),
107    Native(NativeFnId),
108}
109
110pub use xur_resolve::RtType;
111
112/// A decorator applied to a function: `#[decorate(wrapper)]` or
113/// `#[decorate(wrapper(1, "tag"))]`.
114#[derive(Debug, Clone)]
115pub struct Decorator {
116    pub def: DefRef,
117    pub args: Vec<Constant>,
118}
119
120/// The fields a record is built with.
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum RecordFields {
123    /// `E::V(a, b)`, or none for `E::V`.
124    Positional(Vec<Reg>),
125    /// `E::V { x: a, y: b }`, as written.
126    Named(Vec<(Symbol, Reg)>),
127}
128
129/// A type argument of a call, as in `type_name::<T>()`.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum TypeArg {
132    /// A type known when the code was lowered: its name, and the struct,
133    /// enum or native type it is, if any.
134    Named { name: String, def: Option<DefId> },
135    /// The caller's type parameter with this index.
136    Param(u32),
137    /// `@`: record mode — values are coerced to records, and `T::new()`
138    /// creates an empty record.
139    Record,
140}
141
142#[derive(Debug)]
143pub enum InstKind {
144    Const {
145        dst: Reg,
146        value: Constant,
147    },
148    Copy {
149        dst: Reg,
150        src: Reg,
151    },
152    Def {
153        dst: Reg,
154        def: DefRef,
155    },
156    Unary {
157        dst: Reg,
158        op: UnOp,
159        src: Reg,
160    },
161    /// Every binary operator but the short-circuiting `&&` and `||`, which
162    /// are lowered to branches.
163    Binary {
164        dst: Reg,
165        op: BinOpKind,
166        lhs: Reg,
167        rhs: Reg,
168    },
169    Call {
170        dst: Reg,
171        callee: Reg,
172        args: Vec<Reg>,
173        type_args: Vec<TypeArg>,
174    },
175    /// `receiver.method(args)`, dispatched on the receiver at runtime.
176    MethodCall {
177        dst: Reg,
178        receiver: Reg,
179        method: Symbol,
180        args: Vec<Reg>,
181    },
182    /// `base.field`: a named field of a struct or native value, an element
183    /// of a tuple by number, or a module's member.
184    Field {
185        dst: Reg,
186        base: Reg,
187        field: Symbol,
188    },
189    /// A copy of `base` with `field` set to `value`. Structs are values, so
190    /// `p.x = 1` stores an updated copy back in `p`.
191    SetField {
192        dst: Reg,
193        base: Reg,
194        field: Symbol,
195        value: Reg,
196    },
197    Index {
198        dst: Reg,
199        base: Reg,
200        index: Reg,
201    },
202    SetIndex {
203        base: Reg,
204        index: Reg,
205        value: Reg,
206    },
207    Tuple {
208        dst: Reg,
209        items: Vec<Reg>,
210    },
211    List {
212        dst: Reg,
213        items: Vec<Reg>,
214    },
215    /// `#{k: v, ...}`: keys and values are interleaved `[k0, v0, k1, v1, ...]`.
216    Map {
217        dst: Reg,
218        entries: Vec<Reg>,
219    },
220    /// An instance of a struct or variant defined in Xur.
221    Adt {
222        dst: Reg,
223        ctor: DefId,
224        fields: Vec<Reg>,
225    },
226    Range {
227        dst: Reg,
228        start: Option<Reg>,
229        end: Option<Reg>,
230        inclusive: bool,
231    },
232    /// A closure running `closures[function]` of the current function,
233    /// capturing the values in `captures`.
234    Closure {
235        dst: Reg,
236        function: u32,
237        captures: Vec<Reg>,
238    },
239    /// Whether `value` is an instance of the struct or variant `ctor`.
240    IsCtor {
241        dst: Reg,
242        value: Reg,
243        ctor: DefId,
244    },
245    /// `@{ a: 1, b: "x" }`: an anonymous record with named fields.
246    RecordLit {
247        dst: Reg,
248        fields: Vec<(Symbol, Reg)>,
249    },
250    /// A record of the native type `ty`, registered from a Rust type's
251    /// shape: of its enum variant `variant`, or the struct itself. The VM
252    /// checks the fields against the shape.
253    Record {
254        dst: Reg,
255        ty: NativeTypeId,
256        variant: Option<Symbol>,
257        fields: RecordFields,
258    },
259    /// Whether `value` is a record of `ty`, and of `variant` if given.
260    IsRecord {
261        dst: Reg,
262        value: Reg,
263        ty: NativeTypeId,
264        variant: Option<Symbol>,
265    },
266    /// Whether `value` is a record with exactly `len` fields: a struct
267    /// pattern without `..` must name them all.
268    RecordArity {
269        dst: Reg,
270        value: Reg,
271        len: u32,
272    },
273    /// Whether `value` is a tuple of `len` elements.
274    IsTuple {
275        dst: Reg,
276        value: Reg,
277        len: u32,
278    },
279    /// Whether `value` is a list of exactly `len` elements, or at least
280    /// `len` when `at_least` is true.
281    IsList {
282        dst: Reg,
283        value: Reg,
284        len: u32,
285        at_least: bool,
286    },
287    /// Element `index` of a tuple, or field `index` of a struct or variant.
288    Project {
289        dst: Reg,
290        value: Reg,
291        index: u32,
292    },
293    /// Fails at runtime unless `value` has type `ty`. When `coerce` is
294    /// true (the `as` operator), Record → Adt coercion is attempted;
295    /// otherwise the type must match exactly.
296    CheckType {
297        value: Reg,
298        ty: RtType,
299        coerce: bool,
300    },
301    /// Starts iterating over `iterable`, for a `for` loop.
302    IterStart {
303        dst: Reg,
304        iterable: Reg,
305    },
306    /// `T::name(args)` where `T` is a type parameter, resolved and called
307    /// at runtime. When `T` is a concrete type, dispatches to its associated
308    /// function; when unresolved, falls back to record operations.
309    TyParamCall {
310        dst: Reg,
311        type_param: u32,
312        method: Symbol,
313        args: Vec<Reg>,
314    },
315    /// A type used as a value: produces `Value::Type(ty)`.
316    TypeLiteral {
317        dst: Reg,
318        ty: RtType,
319    },
320    /// Dereferences a pointer: `*ptr`.
321    Deref {
322        dst: Reg,
323        ptr: Reg,
324    },
325    /// Whether `value` is the "unwrap" variant of a `#[try(unwrap = V)]`
326    /// enum. At runtime: finds the parent enum, reads the attr, resolves
327    /// the variant, and checks. `dst` is true when the variant matches;
328    /// `inner` holds the unwrapped field 0 in that case.
329    IsTryUnwrap {
330        dst: Reg,
331        inner: Reg,
332        value: Reg,
333    },
334    /// Fails at runtime with `message`; lowered for code that resolution
335    /// already reported as broken.
336    Error {
337        message: String,
338    },
339}
340
341#[derive(Debug)]
342pub enum Terminator {
343    Goto(BlockId),
344    Branch {
345        cond: Reg,
346        then: BlockId,
347        otherwise: BlockId,
348    },
349    Return(Reg),
350    /// Returns `value` as a `?` early-return. Like [`Return`](Self::Return),
351    /// but the VM, when tracing is on, records the `?` location so an error
352    /// that reaches `main` shows the chain of `?`s it passed through.
353    TryReturn(Reg),
354    /// Advances the iterator `iter`: with its next item in `item`, continue
355    /// at `body`; when it is exhausted, at `done`.
356    Next {
357        iter: Reg,
358        item: Reg,
359        body: BlockId,
360        done: BlockId,
361    },
362    /// No pattern matched the value; a runtime error.
363    NoMatch,
364    /// Never reached: the end of code after a `return`, `break` or
365    /// `continue`.
366    Unreachable,
367}