Skip to main content

vm/
context.rs

1use crate::get_type;
2use anyhow::{Result, anyhow};
3use cranelift::codegen::ir::FuncRef;
4use cranelift::prelude::{FunctionBuilder, InstBuilder, Value, Variable, types};
5use cranelift_module::FuncId;
6use dynamic::{Dynamic, Type};
7use smol_str::SmolStr;
8
9#[derive(Clone, Debug)]
10pub enum LocalVar {
11    None,
12    Variable { var: Variable, ty: Type },
13    Value { val: Value, ty: Type },
14    Closure { id: u32, captures: Vec<(Value, Type)> },
15}
16
17impl Into<LocalVar> for (Value, Type) {
18    fn into(self) -> LocalVar {
19        LocalVar::Value { val: self.0, ty: self.1 }
20    }
21}
22
23impl LocalVar {
24    pub(crate) fn normalize_for_var(ctx: &mut BuildContext, val: Value, ty: &Type) -> Value {
25        let Ok(expected) = get_type(ty) else {
26            return val;
27        };
28        let actual = ctx.builder.func.dfg.value_type(val);
29        if actual == expected {
30            return val;
31        }
32
33        if ty.is_bool() && actual.bits() == 1 {
34            let zero = ctx.builder.ins().iconst(types::I8, 0);
35            let one = ctx.builder.ins().iconst(types::I8, 1);
36            return ctx.builder.ins().select(val, one, zero);
37        }
38
39        if expected.is_int() && actual.is_int() {
40            if actual.bits() > expected.bits() {
41                return ctx.builder.ins().ireduce(expected, val);
42            }
43            if actual.bits() < expected.bits() {
44                return if ty.is_uint() { ctx.builder.ins().uextend(expected, val) } else { ctx.builder.ins().sextend(expected, val) };
45            }
46        }
47
48        if expected.is_float() && actual.is_float() {
49            if actual.bits() > expected.bits() {
50                return ctx.builder.ins().fdemote(expected, val);
51            }
52            if actual.bits() < expected.bits() {
53                return ctx.builder.ins().fpromote(expected, val);
54            }
55        }
56
57        val
58    }
59
60    pub fn is_closure(&self) -> bool {
61        if let Self::Closure { .. } = self { true } else { false }
62    }
63
64    pub fn get_ty(&self) -> Type {
65        match self {
66            Self::Value { val: _, ty } => ty.clone(),
67            Self::Variable { var: _, ty } => ty.clone(),
68            _ => Type::Any,
69        }
70    }
71
72    pub fn new(ctx: &mut BuildContext, val: Value, ty: Type) -> Result<Self> {
73        let val = Self::normalize_for_var(ctx, val, &ty);
74        let var = ctx.builder.declare_var(get_type(&ty)?);
75        ctx.builder.def_var(var, val);
76        Ok(Self::Variable { var, ty })
77    }
78
79    pub fn get(self, ctx: &mut BuildContext) -> Option<(Value, Type)> {
80        match self {
81            Self::Value { val, ty } => Some((val, ty)),
82            Self::Variable { var, ty } => Some((ctx.builder.use_var(var), ty)),
83            _ => None,
84        }
85    }
86
87    pub fn set(&self, ctx: &mut BuildContext, val: Value) {
88        if let Self::Variable { var, ty } = self {
89            let val = Self::normalize_for_var(ctx, val, ty);
90            ctx.builder.def_var(var.clone(), val);
91        }
92    }
93}
94
95//用来生成 函数代码的上下文
96pub struct BuildContext<'a> {
97    pub builder: FunctionBuilder<'a>,
98    pub(crate) vars: Vec<LocalVar>,
99    pub(crate) local_type_hints: Vec<Option<Type>>,
100    pub(crate) fn_name: Option<SmolStr>,
101    pub(crate) fn_refs: Vec<(FuncId, FuncRef)>,
102    pub(crate) ret_ty: Type,
103}
104
105impl<'a> BuildContext<'a> {
106    pub fn new(builder: FunctionBuilder<'a>, arg_tys: &[Type], ret_ty: Type) -> Result<Self> {
107        Self::with_local_type_hints(builder, arg_tys, ret_ty, Vec::new())
108    }
109
110    pub fn with_local_type_hints(mut builder: FunctionBuilder<'a>, arg_tys: &[Type], ret_ty: Type, local_type_hints: Vec<Option<Type>>) -> Result<Self> {
111        let entry_block = builder.create_block();
112        builder.append_block_params_for_function_params(entry_block);
113        builder.switch_to_block(entry_block);
114        let mut vars = Vec::new();
115        for (idx, ty) in arg_tys.iter().enumerate() {
116            vars.push(LocalVar::Value { val: builder.block_params(entry_block)[idx], ty: ty.clone() });
117        }
118        Ok(Self { builder, vars, local_type_hints, fn_name: None, fn_refs: Vec::new(), ret_ty })
119    }
120
121    pub fn get_fn_ref(&mut self, fn_id: FuncId) -> Option<FuncRef> {
122        self.fn_refs.iter().find_map(|f| if f.0 == fn_id { Some(f.1.clone()) } else { None })
123    }
124
125    pub fn get_var(&mut self, idx: u32) -> Result<LocalVar> {
126        self.vars.get(idx as usize).cloned().ok_or(anyhow!("未发现变量 {}", idx))
127    }
128
129    pub fn get_var_ty(&self, idx: u32) -> Option<Type> {
130        self.vars.get(idx as usize).map(|v| v.get_ty())
131    }
132
133    pub fn local_type_hint(&self, idx: u32) -> Option<Type> {
134        self.local_type_hints.get(idx as usize).cloned().flatten()
135    }
136
137    pub fn set_var(&mut self, idx: u32, val: LocalVar) -> Result<()> {
138        let idx = idx as usize;
139        if idx >= self.vars.len() {
140            self.vars.resize(idx + 1, LocalVar::None);
141        }
142
143        match val {
144            LocalVar::Closure { .. } | LocalVar::None => self.vars[idx] = val,
145            val => {
146                if let Some(vt) = val.get(self) {
147                    if matches!(self.vars[idx], LocalVar::None | LocalVar::Value { .. }) {
148                        let v = LocalVar::new(self, vt.0, vt.1)?;
149                        self.vars[idx] = v;
150                    } else {
151                        let v = self.vars[idx].clone();
152                        v.set(self, vt.0);
153                    }
154                }
155            }
156        }
157        Ok(())
158    }
159
160    pub fn get_const(&mut self, v: &Dynamic) -> Result<(Value, Type)> {
161        let ty = v.get_type();
162        if ty.is_f32() {
163            return Ok((self.builder.ins().f32const(v.as_float().unwrap() as f32), ty));
164        } else if ty.is_f64() {
165            return Ok((self.builder.ins().f64const(v.as_float().unwrap()), ty));
166        } else if ty.is_int() || ty.is_uint() {
167            return match ty.width() {
168                1 => Ok((self.builder.ins().iconst(types::I8, v.as_int().unwrap()), ty)),
169                2 => Ok((self.builder.ins().iconst(types::I16, v.as_int().unwrap()), ty)),
170                4 => Ok((self.builder.ins().iconst(types::I32, v.as_int().unwrap()), ty)),
171                8 => Ok((self.builder.ins().iconst(types::I64, v.as_int().unwrap()), ty)),
172                _ => panic!("const {:?}", v),
173            };
174        } else if ty.is_bool() {
175            return if v.is_true() { Ok((self.builder.ins().iconst(types::I8, 1), ty)) } else { Ok((self.builder.ins().iconst(types::I8, 0), ty)) };
176        }
177        Err(anyhow!("未实现 {:?}", v))
178    }
179}