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