Skip to main content

xur_bytecode/lower/
mod.rs

1//! Lowering resolved syntax to bytecode, one function at a time.
2//!
3//! Functions are lowered on demand, the first time they are called, so a
4//! program only pays for the code it runs and modules imported at runtime
5//! need no up-front work.
6
7mod expr;
8mod pat;
9
10use std::collections::HashMap;
11use std::sync::Arc;
12
13use xur_ast::{
14    Attribute, Block as AstBlock, Expr, FnRetTy, LitKind, MetaItemInner, MetaItemKind, NodeId,
15    Param, Ty, TyKind,
16};
17use xur_resolve::{DefId, DefKind, ModuleIdx, Namespace, Program, Res, Resolutions};
18use xur_span::{Span, Symbol};
19
20use crate::ir::{
21    Block, BlockId, Constant, Decorator, DefRef, Function, Inst, InstKind, Reg, RtType, Terminator,
22    TypeArg,
23};
24use crate::items::{ItemIndex, ItemRef};
25
26/// Lowers the function or constant `def`, or returns `None` if `def` is
27/// neither. A constant lowers to a function without parameters that
28/// computes its value.
29pub fn lower(program: &Program, items: &ItemIndex, def: DefId) -> Option<Function> {
30    let resolutions = program.resolutions();
31    let name = resolutions.def_path(def);
32    match items.get(def)? {
33        ItemRef::Fn {
34            item,
35            attrs,
36            module,
37            impl_generics,
38        } => {
39            let mut lowerer = Lowerer::new(program, items, module);
40            let impl_type_param_count = if let Some(generics) = impl_generics {
41                for param in &generics.params {
42                    lowerer.type_params.push(resolutions.node_defs[&param.id]);
43                    lowerer.type_param_names.push(param.ident.name);
44                    lowerer.type_param_required.push(param.required);
45                }
46                generics.params.len() as u32
47            } else {
48                0
49            };
50            lowerer.impl_type_param_count = impl_type_param_count;
51            for param in &item.generics.params {
52                lowerer.type_params.push(resolutions.node_defs[&param.id]);
53                lowerer.type_param_names.push(param.ident.name);
54                lowerer.type_param_required.push(param.required);
55            }
56            if let FnRetTy::Ty(ty) = &item.decl.output {
57                lowerer.ret_ty = lowerer.rt_type(ty);
58            }
59            lowerer.params(&item.decl.inputs);
60            let value = lowerer.block(&item.body);
61            lowerer.ret(value, item.body.span);
62            let params = item.decl.inputs.len() as u32;
63            let decorators = extract_decorators(resolutions, module, attrs);
64            let mut func = lowerer.finish(name, 0, params, item.body.span);
65            func.decorators = decorators;
66            Some(func)
67        }
68        ItemRef::Const { item, module } => {
69            let mut lowerer = Lowerer::new(program, items, module);
70            let value = lowerer.expr(&item.expr);
71            lowerer.terminate(Terminator::Return(value), item.expr.span);
72            Some(lowerer.finish(name, 0, 0, item.expr.span))
73        }
74        ItemRef::Ctor { .. } | ItemRef::Enum { .. } => None,
75    }
76}
77
78/// A block under construction.
79struct BlockData {
80    insts: Vec<Inst>,
81    term: Option<(Terminator, Span)>,
82}
83
84/// Where `break` and `continue` go in the innermost loop.
85struct LoopScope {
86    break_to: BlockId,
87    continue_to: BlockId,
88    /// Where `break value` puts the loop's value.
89    result: Reg,
90}
91
92struct Lowerer<'a> {
93    program: &'a Program,
94    resolutions: &'a Resolutions,
95    items: &'a ItemIndex,
96    module: ModuleIdx,
97    blocks: Vec<BlockData>,
98    current: BlockId,
99    registers: u32,
100    /// The register of each local variable, by its binding pattern.
101    locals: HashMap<NodeId, Reg>,
102    loops: Vec<LoopScope>,
103    impl_type_param_count: u32,
104    /// The definitions of the function's type parameters, in order.
105    type_params: Vec<DefId>,
106    type_param_names: Vec<Symbol>,
107    type_param_required: Vec<bool>,
108    closures: Vec<Arc<Function>>,
109    /// For each parameter, which type param index it uses.
110    param_type_params: Vec<Option<u32>>,
111    param_names: Vec<Option<Symbol>>,
112    param_types: Vec<Option<RtType>>,
113    /// The declared return type, checked on return.
114    ret_ty: Option<RtType>,
115    /// A type hint from a `let x: Type = call()` binding, passed as a type
116    /// arg to the call when it has none of its own.
117    hint_type_arg: Option<TypeArg>,
118}
119
120impl<'a> Lowerer<'a> {
121    fn new(program: &'a Program, items: &'a ItemIndex, module: ModuleIdx) -> Self {
122        let mut lowerer = Self {
123            program,
124            resolutions: program.resolutions(),
125            items,
126            module,
127            blocks: Vec::new(),
128            current: BlockId(0),
129            registers: 0,
130            locals: HashMap::new(),
131            loops: Vec::new(),
132            impl_type_param_count: 0,
133            type_params: Vec::new(),
134            type_param_names: Vec::new(),
135            type_param_required: Vec::new(),
136            closures: Vec::new(),
137            param_type_params: Vec::new(),
138            param_names: Vec::new(),
139            param_types: Vec::new(),
140            ret_ty: None,
141            hint_type_arg: None,
142        };
143        lowerer.current = lowerer.new_block();
144        lowerer
145    }
146
147    fn finish(self, name: String, captures: u32, params: u32, span: Span) -> Function {
148        let blocks = self
149            .blocks
150            .into_iter()
151            .map(|block| {
152                let (term, term_span) = block.term.unwrap_or((Terminator::Unreachable, span));
153                Block {
154                    insts: block.insts,
155                    term,
156                    term_span,
157                }
158            })
159            .collect();
160        Function {
161            name,
162            module: self.module,
163            captures,
164            params,
165            registers: self.registers,
166            impl_type_param_count: self.impl_type_param_count,
167            type_params: self.type_param_names,
168            type_param_required: self.type_param_required,
169            param_type_params: self.param_type_params,
170            param_names: self.param_names,
171            param_types: self.param_types,
172            ret_type: self.ret_ty,
173            decorators: Vec::new(),
174            blocks,
175            closures: self.closures,
176            span,
177        }
178    }
179
180    /// Binds the parameters, which arrive in the registers after any
181    /// captures, checking those whose type is written.
182    fn params(&mut self, params: &[Param]) {
183        let registers: Vec<_> = params.iter().map(|_| self.new_reg()).collect();
184        for (param, reg) in params.iter().zip(registers) {
185            self.param_type_params
186                .push(self.type_param_index(&param.ty));
187            let name = match &param.pat.kind {
188                xur_ast::PatKind::Ident(ident) => Some(ident.name),
189                _ => None,
190            };
191            self.param_names.push(name);
192            self.param_types.push(self.rt_type(&param.ty));
193            self.check_type(reg, &param.ty, param.span);
194            self.bind_irrefutable(&param.pat, reg);
195        }
196    }
197
198    /// If `ty` is a bare type parameter, returns its index.
199    fn type_param_index(&self, ty: &Ty) -> Option<u32> {
200        if let TyKind::Path(path) = &ty.kind
201            && let Some(&Res::Def(DefKind::TyParam, param)) = self.resolutions.res.get(&path.id)
202        {
203            self.type_params
204                .iter()
205                .position(|&p| p == param)
206                .map(|i| i as u32)
207        } else {
208            None
209        }
210    }
211
212    /// Returns `value`, checking it against the declared return type.
213    fn ret(&mut self, value: Reg, span: Span) {
214        if let Some(ty) = self.ret_ty.clone() {
215            self.emit(
216                InstKind::CheckType {
217                    value,
218                    ty,
219                    coerce: false,
220                },
221                span,
222            );
223        }
224        self.terminate(Terminator::Return(value), span);
225    }
226
227    /// Checks at runtime that `value` has the type `ty`, if `ty` is written
228    /// and concrete. No coercion — use `check_type_coerce` for `as`.
229    fn check_type(&mut self, value: Reg, ty: &Ty, span: Span) {
230        if let Some(ty) = self.rt_type(ty) {
231            self.emit(
232                InstKind::CheckType {
233                    value,
234                    ty,
235                    coerce: false,
236                },
237                span,
238            );
239        }
240    }
241
242    /// Checks and coerces `value` to `ty` (the `as` operator).
243    fn check_type_coerce(&mut self, value: Reg, ty: &Ty, span: Span) {
244        if let Some(ty) = self.rt_type(ty) {
245            self.emit(
246                InstKind::CheckType {
247                    value,
248                    ty,
249                    coerce: true,
250                },
251                span,
252            );
253        }
254    }
255
256    /// The runtime check for a written type, or `None` if nothing about
257    /// it can be checked.
258    fn rt_type(&self, ty: &Ty) -> Option<RtType> {
259        crate::types::rt_type(self.resolutions, ty)
260    }
261
262    fn new_reg(&mut self) -> Reg {
263        let reg = Reg(self.registers);
264        self.registers += 1;
265        reg
266    }
267
268    fn new_block(&mut self) -> BlockId {
269        let id = BlockId(self.blocks.len() as u32);
270        self.blocks.push(BlockData {
271            insts: Vec::new(),
272            term: None,
273        });
274        id
275    }
276
277    fn switch_to(&mut self, block: BlockId) {
278        self.current = block;
279    }
280
281    fn emit(&mut self, kind: InstKind, span: Span) {
282        self.blocks[self.current.0 as usize]
283            .insts
284            .push(Inst { kind, span });
285    }
286
287    /// Ends the current block. Code lowered after a `return`, `break` or
288    /// `continue` goes into a fresh block that nothing jumps to.
289    fn terminate(&mut self, term: Terminator, span: Span) {
290        let block = &mut self.blocks[self.current.0 as usize];
291        if block.term.is_none() {
292            block.term = Some((term, span));
293        }
294    }
295
296    /// Ends the current block and continues in a new, unreachable one.
297    fn diverge(&mut self, term: Terminator, span: Span) {
298        self.terminate(term, span);
299        let dead = self.new_block();
300        self.switch_to(dead);
301    }
302
303    fn constant(&mut self, value: Constant, span: Span) -> Reg {
304        let dst = self.new_reg();
305        self.emit(InstKind::Const { dst, value }, span);
306        dst
307    }
308
309    fn unit(&mut self, span: Span) -> Reg {
310        self.constant(Constant::Unit, span)
311    }
312
313    fn error(&mut self, message: impl Into<String>, span: Span) -> Reg {
314        self.emit(
315            InstKind::Error {
316                message: message.into(),
317            },
318            span,
319        );
320        self.unit(span)
321    }
322
323    /// Lowers a block, returning the register holding its value.
324    fn block(&mut self, block: &AstBlock) -> Reg {
325        self.block_value(block)
326    }
327
328    fn expr_or_unit(&mut self, expr: Option<&Expr>, span: Span) -> Reg {
329        match expr {
330            Some(expr) => self.expr(expr),
331            None => self.unit(span),
332        }
333    }
334}
335
336fn extract_decorators(
337    resolutions: &Resolutions,
338    module: ModuleIdx,
339    attrs: &[Attribute],
340) -> Vec<Decorator> {
341    let module_def = resolutions.module_defs[module.0];
342    let mut decorators = Vec::new();
343    for attr in attrs {
344        let segments = &attr.meta.path.segments;
345        if segments.len() != 1 || segments[0].ident.name.as_str() != "decorate" {
346            continue;
347        }
348        let MetaItemKind::List(items) = &attr.meta.kind else {
349            continue;
350        };
351        for item in items {
352            let MetaItemInner::MetaItem(meta) = item else {
353                continue;
354            };
355            let def = resolve_path_in_module(resolutions, module_def, &meta.path.segments);
356            let Some(def) = def else { continue };
357            let args = match &meta.kind {
358                MetaItemKind::Word => Vec::new(),
359                MetaItemKind::List(inner) => inner
360                    .iter()
361                    .filter_map(|a| match a {
362                        MetaItemInner::Lit(lit) => lit_to_constant(lit),
363                        _ => None,
364                    })
365                    .collect(),
366                _ => Vec::new(),
367            };
368            decorators.push(Decorator { def, args });
369        }
370    }
371    decorators
372}
373
374fn resolve_path_in_module(
375    resolutions: &Resolutions,
376    module_def: DefId,
377    segments: &[xur_ast::PathSegment],
378) -> Option<DefRef> {
379    if segments.len() == 1 {
380        let name = segments[0].ident.name;
381        let res = resolutions.lookup(module_def, Namespace::Value, name)?;
382        return res_to_def_ref(res);
383    }
384    // Multi-segment: resolve the first as a module, then walk.
385    let mut scope = module_def;
386    for (i, seg) in segments.iter().enumerate() {
387        let name = seg.ident.name;
388        let is_last = i + 1 == segments.len();
389        if is_last {
390            let res = resolutions.lookup(scope, Namespace::Value, name)?;
391            return res_to_def_ref(res);
392        }
393        let res = resolutions
394            .lookup(scope, Namespace::Value, name)
395            .or_else(|| resolutions.lookup(scope, Namespace::Type, name))?;
396        match res {
397            Res::Def(DefKind::Mod, def) => scope = def,
398            Res::Def(DefKind::Enum, def) => scope = def,
399            _ => return None,
400        }
401    }
402    None
403}
404
405fn res_to_def_ref(res: Res) -> Option<DefRef> {
406    match res {
407        Res::Def(DefKind::Fn, def) => Some(DefRef::Fn(def)),
408        Res::Def(DefKind::NativeFn(id), _) => Some(DefRef::Native(id)),
409        Res::Def(DefKind::Const, def) => Some(DefRef::Const(def)),
410        _ => None,
411    }
412}
413
414fn lit_to_constant(lit: &xur_ast::Lit) -> Option<Constant> {
415    match &lit.kind {
416        LitKind::Bool(b) => Some(Constant::Bool(*b)),
417        LitKind::Int(i) => Some(Constant::Int(*i as i64)),
418        LitKind::Float(digits) => digits.as_str().parse().ok().map(Constant::Float),
419        LitKind::Str(s) => Some(Constant::Str(s.as_str().into())),
420        _ => None,
421    }
422}