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::{Block as AstBlock, Expr, FnRetTy, NodeId, Param, Ty, TyKind};
14use xur_resolve::{DefId, DefKind, LangItems, ModuleIdx, PrimTy, Program, Res, Resolutions};
15use xur_span::{Span, Symbol};
16
17use crate::ir::{Block, BlockId, Constant, Function, Inst, InstKind, Reg, RtType, Terminator};
18use crate::items::{ItemIndex, ItemRef};
19
20/// Lowers the function or constant `def`, or returns `None` if `def` is
21/// neither. A constant lowers to a function without parameters that
22/// computes its value.
23pub fn lower(program: &Program, items: &ItemIndex, def: DefId) -> Option<Function> {
24    let resolutions = program.resolutions();
25    let name = resolutions.def_path(def);
26    match items.get(def)? {
27        ItemRef::Fn { item, module } => {
28            let mut lowerer = Lowerer::new(program, items, module);
29            for param in &item.generics.params {
30                lowerer.type_params.push(resolutions.node_defs[&param.id]);
31                lowerer.type_param_names.push(param.ident.name);
32            }
33            if let FnRetTy::Ty(ty) = &item.decl.output {
34                lowerer.ret_ty = lowerer.rt_type(ty);
35            }
36            lowerer.params(&item.decl.inputs);
37            let value = lowerer.block(&item.body);
38            lowerer.ret(value, item.body.span);
39            let params = item.decl.inputs.len() as u32;
40            Some(lowerer.finish(name, 0, params, item.body.span))
41        }
42        ItemRef::Const { item, module } => {
43            let mut lowerer = Lowerer::new(program, items, module);
44            let value = lowerer.expr(&item.expr);
45            lowerer.terminate(Terminator::Return(value), item.expr.span);
46            Some(lowerer.finish(name, 0, 0, item.expr.span))
47        }
48        ItemRef::Ctor(_) => None,
49    }
50}
51
52/// A block under construction.
53struct BlockData {
54    insts: Vec<Inst>,
55    term: Option<(Terminator, Span)>,
56}
57
58/// Where `break` and `continue` go in the innermost loop.
59struct LoopScope {
60    break_to: BlockId,
61    continue_to: BlockId,
62    /// Where `break value` puts the loop's value.
63    result: Reg,
64}
65
66struct Lowerer<'a> {
67    program: &'a Program,
68    resolutions: &'a Resolutions,
69    items: &'a ItemIndex,
70    lang: LangItems,
71    module: ModuleIdx,
72    blocks: Vec<BlockData>,
73    current: BlockId,
74    registers: u32,
75    /// The register of each local variable, by its binding pattern.
76    locals: HashMap<NodeId, Reg>,
77    loops: Vec<LoopScope>,
78    /// The definitions of the function's type parameters, in order.
79    type_params: Vec<DefId>,
80    type_param_names: Vec<Symbol>,
81    closures: Vec<Arc<Function>>,
82    /// The declared return type, checked on return.
83    ret_ty: Option<RtType>,
84}
85
86impl<'a> Lowerer<'a> {
87    fn new(program: &'a Program, items: &'a ItemIndex, module: ModuleIdx) -> Self {
88        let mut lowerer = Self {
89            program,
90            resolutions: program.resolutions(),
91            items,
92            lang: program.lang_items(),
93            module,
94            blocks: Vec::new(),
95            current: BlockId(0),
96            registers: 0,
97            locals: HashMap::new(),
98            loops: Vec::new(),
99            type_params: Vec::new(),
100            type_param_names: Vec::new(),
101            closures: Vec::new(),
102            ret_ty: None,
103        };
104        lowerer.current = lowerer.new_block();
105        lowerer
106    }
107
108    fn finish(self, name: String, captures: u32, params: u32, span: Span) -> Function {
109        let blocks = self
110            .blocks
111            .into_iter()
112            .map(|block| {
113                let (term, term_span) = block.term.unwrap_or((Terminator::Unreachable, span));
114                Block {
115                    insts: block.insts,
116                    term,
117                    term_span,
118                }
119            })
120            .collect();
121        Function {
122            name,
123            module: self.module,
124            captures,
125            params,
126            registers: self.registers,
127            type_params: self.type_param_names,
128            blocks,
129            closures: self.closures,
130            span,
131        }
132    }
133
134    /// Binds the parameters, which arrive in the registers after any
135    /// captures, checking those whose type is written.
136    fn params(&mut self, params: &[Param]) {
137        let registers: Vec<_> = params.iter().map(|_| self.new_reg()).collect();
138        for (param, reg) in params.iter().zip(registers) {
139            self.check_type(reg, &param.ty, param.span);
140            self.bind_irrefutable(&param.pat, reg);
141        }
142    }
143
144    /// Returns `value`, checking it against the declared return type.
145    fn ret(&mut self, value: Reg, span: Span) {
146        if let Some(ty) = self.ret_ty.clone() {
147            self.emit(InstKind::CheckType { value, ty }, span);
148        }
149        self.terminate(Terminator::Return(value), span);
150    }
151
152    /// Checks at runtime that `value` has the type `ty`, if `ty` is written
153    /// and concrete.
154    fn check_type(&mut self, value: Reg, ty: &Ty, span: Span) {
155        if let Some(ty) = self.rt_type(ty) {
156            self.emit(InstKind::CheckType { value, ty }, span);
157        }
158    }
159
160    /// The runtime check for a written type, or `None` if nothing about
161    /// it can be checked.
162    fn rt_type(&self, ty: &Ty) -> Option<RtType> {
163        match self.rt_type_or_any(ty) {
164            RtType::Any => None,
165            ty => Some(ty),
166        }
167    }
168
169    fn rt_type_or_any(&self, ty: &Ty) -> RtType {
170        match &ty.kind {
171            TyKind::Path(path) => match self.resolutions.res.get(&path.id) {
172                Some(Res::PrimTy(prim)) => prim_rt_type(*prim),
173                Some(&Res::Def(DefKind::Struct | DefKind::Enum, def)) => RtType::Adt {
174                    def,
175                    name: self.resolutions.def_path(def),
176                },
177                Some(&Res::Def(DefKind::NativeType(id), def)) => RtType::Native {
178                    id,
179                    name: self.resolutions.def_path(def),
180                },
181                _ => RtType::Any,
182            },
183            TyKind::Tuple(tys) if tys.is_empty() => RtType::Unit,
184            TyKind::Tuple(tys) => {
185                RtType::Tuple(tys.iter().map(|ty| self.rt_type_or_any(ty)).collect())
186            }
187            TyKind::Paren(ty) => self.rt_type_or_any(ty),
188            TyKind::List(_) => RtType::List,
189            TyKind::Infer | TyKind::ImplicitSelf | TyKind::Err => RtType::Any,
190        }
191    }
192
193    fn new_reg(&mut self) -> Reg {
194        let reg = Reg(self.registers);
195        self.registers += 1;
196        reg
197    }
198
199    fn new_block(&mut self) -> BlockId {
200        let id = BlockId(self.blocks.len() as u32);
201        self.blocks.push(BlockData {
202            insts: Vec::new(),
203            term: None,
204        });
205        id
206    }
207
208    fn switch_to(&mut self, block: BlockId) {
209        self.current = block;
210    }
211
212    fn emit(&mut self, kind: InstKind, span: Span) {
213        self.blocks[self.current.0 as usize]
214            .insts
215            .push(Inst { kind, span });
216    }
217
218    /// Ends the current block. Code lowered after a `return`, `break` or
219    /// `continue` goes into a fresh block that nothing jumps to.
220    fn terminate(&mut self, term: Terminator, span: Span) {
221        let block = &mut self.blocks[self.current.0 as usize];
222        if block.term.is_none() {
223            block.term = Some((term, span));
224        }
225    }
226
227    /// Ends the current block and continues in a new, unreachable one.
228    fn diverge(&mut self, term: Terminator, span: Span) {
229        self.terminate(term, span);
230        let dead = self.new_block();
231        self.switch_to(dead);
232    }
233
234    fn constant(&mut self, value: Constant, span: Span) -> Reg {
235        let dst = self.new_reg();
236        self.emit(InstKind::Const { dst, value }, span);
237        dst
238    }
239
240    fn unit(&mut self, span: Span) -> Reg {
241        self.constant(Constant::Unit, span)
242    }
243
244    fn error(&mut self, message: impl Into<String>, span: Span) -> Reg {
245        self.emit(
246            InstKind::Error {
247                message: message.into(),
248            },
249            span,
250        );
251        self.unit(span)
252    }
253
254    /// Lowers a block, returning the register holding its value.
255    fn block(&mut self, block: &AstBlock) -> Reg {
256        self.block_value(block)
257    }
258
259    fn expr_or_unit(&mut self, expr: Option<&Expr>, span: Span) -> Reg {
260        match expr {
261            Some(expr) => self.expr(expr),
262            None => self.unit(span),
263        }
264    }
265}
266
267fn prim_rt_type(prim: PrimTy) -> RtType {
268    let int = |name, min, max| RtType::Int { name, min, max };
269    match prim {
270        PrimTy::Bool => RtType::Bool,
271        PrimTy::Str => RtType::Str,
272        PrimTy::F32 | PrimTy::F64 => RtType::Float,
273        PrimTy::U8 => int("u8", 0, u8::MAX.into()),
274        PrimTy::U16 => int("u16", 0, u16::MAX.into()),
275        PrimTy::U32 => int("u32", 0, u32::MAX.into()),
276        PrimTy::U64 => int("u64", 0, i64::MAX),
277        PrimTy::Usize => int("usize", 0, i64::MAX),
278        PrimTy::I8 => int("i8", i8::MIN.into(), i8::MAX.into()),
279        PrimTy::I16 => int("i16", i16::MIN.into(), i16::MAX.into()),
280        PrimTy::I32 => int("i32", i32::MIN.into(), i32::MAX.into()),
281        PrimTy::I64 => int("i64", i64::MIN, i64::MAX),
282        PrimTy::Isize => int("isize", i64::MIN, i64::MAX),
283    }
284}