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    /// The function's type parameters, which calls bind by position.
51    pub type_params: Vec<Symbol>,
52    pub blocks: Vec<Block>,
53    /// The bodies of closures created by this function, by index.
54    pub closures: Vec<Arc<Function>>,
55    pub span: Span,
56}
57
58#[derive(Debug)]
59pub struct Block {
60    pub insts: Vec<Inst>,
61    pub term: Terminator,
62    /// Where the terminator came from, for its runtime errors.
63    pub term_span: Span,
64}
65
66#[derive(Debug)]
67pub struct Inst {
68    pub kind: InstKind,
69    pub span: Span,
70}
71
72#[derive(Debug, Clone, PartialEq)]
73pub enum Constant {
74    Unit,
75    Bool(bool),
76    Int(i64),
77    Float(f64),
78    Str(Arc<str>),
79}
80
81/// A definition used as a value.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum DefRef {
84    /// A function written in Xur.
85    Fn(DefId),
86    /// A tuple struct's or tuple variant's constructor, as a function.
87    Ctor(DefId),
88    /// A constant, evaluated the first time it is used.
89    Const(DefId),
90    Module(DefId),
91    Native(NativeFnId),
92}
93
94/// A type written in the source, as checked at runtime. Xur is checked
95/// dynamically: where a type is written it is enforced when the value
96/// arrives, and where it isn't (or is generic) anything goes.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum RtType {
99    /// Not checked: no type, `_`, or a type parameter.
100    Any,
101    Unit,
102    Bool,
103    Str,
104    Float,
105    /// An integer type, with the range its values must be in.
106    Int {
107        name: &'static str,
108        min: i64,
109        max: i64,
110    },
111    Tuple(Vec<RtType>),
112    /// A list. Only the list itself is checked, not each element, so a
113    /// check doesn't take time proportional to the list's length.
114    List,
115    /// A struct or enum defined in Xur, by its definition.
116    Adt {
117        def: DefId,
118        name: String,
119    },
120    Native {
121        id: NativeTypeId,
122        name: String,
123    },
124}
125
126/// A type argument of a call, as in `type_name::<T>()`.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub enum TypeArg {
129    /// A type known when the code was lowered, by name.
130    Named(String),
131    /// The caller's type parameter with this index.
132    Param(u32),
133}
134
135#[derive(Debug)]
136pub enum InstKind {
137    Const {
138        dst: Reg,
139        value: Constant,
140    },
141    Copy {
142        dst: Reg,
143        src: Reg,
144    },
145    Def {
146        dst: Reg,
147        def: DefRef,
148    },
149    Unary {
150        dst: Reg,
151        op: UnOp,
152        src: Reg,
153    },
154    /// Every binary operator but the short-circuiting `&&` and `||`, which
155    /// are lowered to branches.
156    Binary {
157        dst: Reg,
158        op: BinOpKind,
159        lhs: Reg,
160        rhs: Reg,
161    },
162    Call {
163        dst: Reg,
164        callee: Reg,
165        args: Vec<Reg>,
166        type_args: Vec<TypeArg>,
167    },
168    /// `receiver.method(args)`, dispatched on the receiver at runtime.
169    MethodCall {
170        dst: Reg,
171        receiver: Reg,
172        method: Symbol,
173        args: Vec<Reg>,
174    },
175    /// `base.field`: a field of a native value, or a module's member.
176    Field {
177        dst: Reg,
178        base: Reg,
179        field: Symbol,
180    },
181    Index {
182        dst: Reg,
183        base: Reg,
184        index: Reg,
185    },
186    SetIndex {
187        base: Reg,
188        index: Reg,
189        value: Reg,
190    },
191    Tuple {
192        dst: Reg,
193        items: Vec<Reg>,
194    },
195    List {
196        dst: Reg,
197        items: Vec<Reg>,
198    },
199    /// An instance of a struct or variant defined in Xur.
200    Adt {
201        dst: Reg,
202        ctor: DefId,
203        fields: Vec<Reg>,
204    },
205    Range {
206        dst: Reg,
207        start: Option<Reg>,
208        end: Option<Reg>,
209        inclusive: bool,
210    },
211    /// A closure running `closures[function]` of the current function,
212    /// capturing the values in `captures`.
213    Closure {
214        dst: Reg,
215        function: u32,
216        captures: Vec<Reg>,
217    },
218    /// Whether `value` is an instance of the struct or variant `ctor`.
219    IsCtor {
220        dst: Reg,
221        value: Reg,
222        ctor: DefId,
223    },
224    /// Whether `value` is a tuple of `len` elements.
225    IsTuple {
226        dst: Reg,
227        value: Reg,
228        len: u32,
229    },
230    /// Element `index` of a tuple, or field `index` of a struct or variant.
231    Project {
232        dst: Reg,
233        value: Reg,
234        index: u32,
235    },
236    /// Fails at runtime unless `value` has type `ty`.
237    CheckType {
238        value: Reg,
239        ty: RtType,
240    },
241    /// Starts iterating over `iterable`, for a `for` loop.
242    IterStart {
243        dst: Reg,
244        iterable: Reg,
245    },
246    /// Fails at runtime with `message`; lowered for code that resolution
247    /// already reported as broken.
248    Error {
249        message: String,
250    },
251}
252
253#[derive(Debug)]
254pub enum Terminator {
255    Goto(BlockId),
256    Branch {
257        cond: Reg,
258        then: BlockId,
259        otherwise: BlockId,
260    },
261    Return(Reg),
262    /// Advances the iterator `iter`: with its next item in `item`, continue
263    /// at `body`; when it is exhausted, at `done`.
264    Next {
265        iter: Reg,
266        item: Reg,
267        body: BlockId,
268        done: BlockId,
269    },
270    /// No pattern matched the value; a runtime error.
271    NoMatch,
272    /// Never reached: the end of code after a `return`, `break` or
273    /// `continue`.
274    Unreachable,
275}
276
277impl std::fmt::Display for RtType {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        match self {
280            Self::Any => f.write_str("_"),
281            Self::Unit => f.write_str("()"),
282            Self::Bool => f.write_str("bool"),
283            Self::Str => f.write_str("str"),
284            Self::Float => f.write_str("float"),
285            Self::Int { name, .. } => f.write_str(name),
286            Self::Tuple(tys) => {
287                let tys: Vec<_> = tys.iter().map(ToString::to_string).collect();
288                write!(f, "({})", tys.join(", "))
289            }
290            Self::List => f.write_str("[_]"),
291            Self::Adt { name, .. } | Self::Native { name, .. } => f.write_str(name),
292        }
293    }
294}