1use crate::{JITRunTime, context::BuildContext, rt::PendingFn};
2use anyhow::{Context, Result, anyhow};
3use compiler::{Symbol, infer_generic_args_from_types, substitute_stmt, substitute_type};
4use cranelift::{codegen::ir::FuncRef, prelude::*};
5use cranelift_module::{FuncId, Module};
6use dynamic::Type;
7
8#[derive(Debug)]
9pub enum FnVariant {
10 Native { ty: Type, fn_id: FuncId, context: Option<usize> }, Inline { fn_ptr: fn(Option<&mut BuildContext>, Vec<Value>) -> Result<(Option<Value>, Type)>, arg_tys: Vec<Type> }, Compiled(Vec<(Type, FuncId)>),
13}
14
15impl FnVariant {
16 pub fn is_compiled(&self) -> bool {
17 if let Self::Compiled(_) = self { true } else { false }
18 }
19}
20
21use crate::get_type;
22use cranelift_module::Linkage;
23use parser::{Expr, ExprKind, Span, Stmt, StmtKind};
24use smol_str::SmolStr;
25
26#[derive(Debug)]
27pub enum FnInfo {
28 Call { fn_id: FuncId, arg_tys: Vec<Type>, caps: Vec<usize>, ret: Type, context: Option<usize> },
30 Inline { fn_ptr: fn(Option<&mut BuildContext>, Vec<Value>) -> Result<(Option<Value>, Type)>, arg_tys: Vec<Type> },
31}
32
33impl FnInfo {
34 pub fn get_id(&self) -> Result<FuncId> {
35 if let Self::Call { fn_id, arg_tys: _, caps: _, ret: _, context: _ } = self { Ok(*fn_id) } else { Err(anyhow!("Inline 函数没有 FuncId")) }
36 }
37
38 pub fn arg_tys(&self) -> Result<&[Type]> {
39 match self {
40 Self::Call { fn_id: _, arg_tys, caps: _, ret: _, context: _ } => Ok(arg_tys),
41 Self::Inline { fn_ptr: _, arg_tys } => Ok(arg_tys),
42 }
43 }
44
45 pub fn get_type(&self) -> Result<Type> {
46 match self {
47 Self::Call { fn_id: _, arg_tys: _, caps: _, ret, context: _ } => Ok(ret.clone()),
48 Self::Inline { fn_ptr, arg_tys: _ } => fn_ptr(None, vec![]).map(|(_, t)| t),
49 }
50 }
51}
52
53impl JITRunTime {
54 fn coerce_returns(stmt: &Stmt, ret_ty: &Type) -> Stmt {
55 let kind = match &stmt.kind {
56 StmtKind::Return(Some(expr)) if ret_ty.is_void() => StmtKind::Return(None),
57 StmtKind::Return(Some(expr)) => StmtKind::Return(Some(Expr::new(ExprKind::Typed { value: Box::new(expr.clone()), ty: ret_ty.clone() }, expr.span))),
58 StmtKind::Block(stmts) => {
59 let last = stmts.len().saturating_sub(1);
60 StmtKind::Block(stmts.iter().enumerate().map(|(idx, stmt)| if idx == last { Self::coerce_returns(stmt, ret_ty) } else { stmt.clone() }).collect())
61 }
62 StmtKind::If { cond, then_body, else_body } => {
63 StmtKind::If { cond: cond.clone(), then_body: Box::new(Self::coerce_returns(then_body, ret_ty)), else_body: else_body.as_ref().map(|body| Box::new(Self::coerce_returns(body, ret_ty))) }
64 }
65 StmtKind::While { cond, body } => StmtKind::While { cond: cond.clone(), body: Box::new(Self::coerce_returns(body, ret_ty)) },
66 StmtKind::Loop(body) => StmtKind::Loop(Box::new(Self::coerce_returns(body, ret_ty))),
67 StmtKind::For { pat, range, body } => StmtKind::For { pat: pat.clone(), range: range.clone(), body: Box::new(Self::coerce_returns(body, ret_ty)) },
68 _ => stmt.kind.clone(),
69 };
70 Stmt::new(kind, stmt.span)
71 }
72
73 pub fn add_inline(&mut self, name: &str, args: Vec<Type>, ret: Type, f: fn(Option<&mut BuildContext>, Vec<Value>) -> Result<(Option<Value>, Type)>) -> Result<u32> {
74 let id = self.compiler.add_symbol(name, Symbol::native(args.clone(), ret));
75 self.fns.insert(id, FnVariant::Inline { fn_ptr: f.into(), arg_tys: args });
76 if let Some((def, method)) = name.split_once("::") {
77 let def_id = self.get_id(def)?;
78 if let Some((_, define)) = self.compiler.symbols.get_symbol_mut(def_id) {
79 if let Symbol::Struct(Type::Struct { params, fields }, _) = define {
80 fields.push((method.into(), Type::Symbol { id, params: params.clone() }));
81 }
82 }
83 }
84 Ok(id)
85 }
86
87 pub fn get_fn_ref(&mut self, ctx: &mut BuildContext, fn_id: FuncId) -> FuncRef {
88 ctx.get_fn_ref(fn_id).unwrap_or_else(|| {
89 let fn_ref = self.module.declare_func_in_func(fn_id, &mut ctx.builder.func);
90 ctx.fn_refs.push((fn_id, fn_ref));
91 fn_ref
92 })
93 }
94
95 pub fn adjust_args(&mut self, ctx: &mut BuildContext, args: Vec<(Value, Type)>, arg_tys: &[Type]) -> Result<Vec<Value>> {
96 let mut results = Vec::<Value>::new();
97 for ((arg, ty), arg_ty) in args.into_iter().zip(arg_tys.iter()) {
98 if ty != *arg_ty {
99 results.push(self.convert(ctx, (arg, ty), arg_ty.clone())?);
100 } else {
101 results.push(arg);
102 }
103 }
104 Ok(results)
105 }
106
107 pub fn get_fn(&self, id: u32, want_tys: &[Type]) -> Result<FnInfo> {
108 if let Some(fn_info) = self.fns.get(&id) {
109 match fn_info {
110 FnVariant::Compiled(fns) => {
111 for (ty, fn_id) in fns.iter() {
112 if let Type::Fn { tys, ret } = ty.clone() {
113 if tys.len() != want_tys.len() {
114 continue;
115 }
116 let mut real_types = Vec::new();
117 for (ty1, ty2) in tys.iter().zip(want_tys.iter()) {
118 if ty1 != ty2 {
119 if ty1.is_any() || ty2.is_any() {
120 real_types.push(ty1.clone());
121 }
122 else {
124 break;
125 }
126 } else {
127 real_types.push(ty1.clone());
128 }
129 }
130 if real_types.len() == want_tys.len() {
131 return Ok(FnInfo::Call { fn_id: *fn_id, arg_tys: real_types, caps: Vec::new(), ret: ret.as_ref().clone(), context: None });
132 }
133 }
134 }
135 }
136 FnVariant::Inline { fn_ptr, arg_tys } => {
137 return Ok(FnInfo::Inline { fn_ptr: fn_ptr.clone(), arg_tys: arg_tys.clone() });
138 }
139 FnVariant::Native { ty, fn_id, context } => {
140 if let Type::Fn { tys, ret } = ty.clone() {
141 return Ok(FnInfo::Call { fn_id: *fn_id, arg_tys: tys, caps: Vec::new(), ret: ret.as_ref().clone(), context: *context });
142 }
143 }
144 }
145 }
146 Err(anyhow!("未发现函数 {}", id))
147 }
148
149 pub fn get_sig(&mut self, arg_tys: &[Type], ret: Type) -> Result<Signature> {
150 if let Some(st) = self.sigs.iter().find_map(|s| if s.0 == arg_tys && ret == s.2 { Some(s.1.clone()) } else { None }) {
151 return Ok(st);
152 }
153 let mut sig = self.module.make_signature();
154 for arg in arg_tys.iter() {
155 sig.params.push(AbiParam::new(get_type(arg)?));
156 }
157 if !ret.is_void() {
158 sig.returns.push(AbiParam::new(get_type(&ret)?));
159 }
160 self.sigs.push((arg_tys.to_vec(), sig.clone(), ret.clone()));
161 Ok(sig)
162 }
163
164 fn declare_compiled_fn(&mut self, name_id: Option<&(SmolStr, u32)>, arg_tys: &[Type], ret_ty: Type) -> Result<FuncId> {
165 let sig = self.get_sig(arg_tys, ret_ty.clone())?;
166 log::info!("{:?} {:?}", name_id, sig);
167 if let Some((name, id)) = name_id {
168 let fn_id = self.module.declare_function(&name, Linkage::Local, &sig)?;
169 let variant = (Type::Fn { tys: arg_tys.to_vec(), ret: std::rc::Rc::new(ret_ty.clone()) }, fn_id);
170 if let Some(FnVariant::Compiled(fns)) = self.fns.get_mut(id) {
171 fns.push(variant);
172 } else {
173 self.fns.insert(*id, FnVariant::Compiled(vec![variant]));
174 }
175 Ok(fn_id)
176 } else {
177 Ok(self.module.declare_anonymous_function(&sig)?)
178 }
179 }
180
181 fn define_compiled_fn(&mut self, fn_id: FuncId, name_id: Option<&(SmolStr, u32)>, arg_tys: &[Type], ret_ty: Type, stmt: &Stmt) -> Result<()> {
182 let sig = self.get_sig(arg_tys, ret_ty.clone())?;
183 #[cfg(feature = "ir-disassembly")]
184 let fn_name = name_id.map(|(name, _)| name.clone());
185 let mut ctx = self.module.make_context();
186 ctx.func.signature = sig.clone();
187
188 let mut func_ctx = FunctionBuilderContext::new();
189 let builder = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
190
191 let mut build_ctx = BuildContext::new(builder, &arg_tys)?;
192 self.compile_depth += 1;
193 let stmt = Self::coerce_returns(stmt, &ret_ty);
194 let gen_result = self.gen_stmt(&mut build_ctx, &stmt, None, None);
195 self.compile_depth -= 1;
196 gen_result?;
197
198 build_ctx.builder.seal_all_blocks();
199 #[cfg(feature = "ir-disassembly")]
200 {
201 let ir = format!("{}", ctx.func.display());
202 if let Some(name) = fn_name {
203 self.ir_disassembly.insert(name, ir);
204 }
205 }
206 self.module.define_function(fn_id, &mut ctx).with_context(|| name_id.map(|(name, _)| format!("define function {}", name)).unwrap_or_else(|| "define anonymous function".to_string()))?;
207 log::info!("{:?}", ctx.func);
208 Ok(())
209 }
210
211 pub(crate) fn compile_fn(&mut self, name_id: Option<(SmolStr, u32)>, arg_tys: &[Type], ret_ty: Type, stmt: &Stmt) -> Result<FuncId> {
212 let drain_pending = self.compile_depth == 0;
213 let fn_id = self.declare_compiled_fn(name_id.as_ref(), arg_tys, ret_ty.clone())?;
214 self.define_compiled_fn(fn_id, name_id.as_ref(), arg_tys, ret_ty, stmt)?;
215 if drain_pending {
216 self.drain_pending_fns()?;
217 }
218 Ok(fn_id)
219 }
220
221 fn drain_pending_fns(&mut self) -> Result<()> {
222 while let Some(pending) = self.pending_fns.pop_front() {
223 let name_id = (pending.name, pending.symbol_id);
224 self.define_compiled_fn(pending.fn_id, Some(&name_id), &pending.arg_tys, pending.ret_ty, &pending.body)?;
225 }
226 Ok(())
227 }
228
229 pub fn gen_fn(&mut self, ctx: Option<&BuildContext>, id: u32, arg_tys: &[Type]) -> Result<FnInfo> {
230 self.gen_fn_with_params(ctx, id, arg_tys, &[])
231 }
232
233 pub fn gen_fn_with_params(&mut self, ctx: Option<&BuildContext>, id: u32, arg_tys: &[Type], generic_args: &[Type]) -> Result<FnInfo> {
234 let mut arg_tys: Vec<Type> = arg_tys.iter().map(|ty| self.compiler.symbols.get_type(ty).unwrap()).collect();
235 if generic_args.is_empty()
236 && let Ok(info) = self.get_fn(id, &arg_tys)
237 {
238 return Ok(info);
239 }
240 let (name, s) = self.compiler.symbols.get_symbol(id).map(|(n, s)| (n.clone(), s.clone()))?;
241 if let Symbol::Fn { ty, args, generic_params, cap, body, is_pub: _ } = s.clone() {
242 if let Type::Fn { tys: decl_tys, ret: _ } = ty {
243 let inferred_generic_args = if generic_args.is_empty() { infer_generic_args_from_types(&generic_params, &decl_tys, &arg_tys) } else { generic_args.to_vec() };
244 let generic_args = if generic_params.is_empty() { &[] } else { inferred_generic_args.as_slice() };
245 let decl_tys = if generic_params.is_empty() { decl_tys } else { decl_tys.iter().map(|ty| substitute_type(ty, &generic_params, generic_args)).collect() };
246 while arg_tys.len() < decl_tys.len() {
247 arg_tys.push(self.compiler.symbols.get_type(&decl_tys[arg_tys.len()]).unwrap_or(Type::Any));
248 }
249 let ret_ty = self.compiler.infer_fn_with_params(id, &arg_tys, generic_args)?;
250 if let Some(FnVariant::Compiled(fns)) = self.fns.get(&id) {
251 for (ty, fn_id) in fns {
252 if let Type::Fn { tys, ret } = ty
253 && tys == &arg_tys
254 && ret.as_ref() == &ret_ty
255 {
256 return Ok(FnInfo::Call { fn_id: *fn_id, arg_tys: arg_tys.to_vec(), caps: Vec::new(), ret: ret_ty, context: None });
257 }
258 }
259 }
260 let mut compile_cap = cap.clone();
261 let body = if generic_params.is_empty() {
262 body.as_ref().clone()
263 } else {
264 let mut compile_tys = decl_tys.clone();
265 let substituted = substitute_stmt(body.as_ref(), &generic_params, generic_args);
266 let saved_state = self.compiler.take_local_state();
267 let compiled_body = self.compiler.compile_fn(&args, &mut compile_tys, substituted, &mut compile_cap);
268 self.compiler.restore_local_state(saved_state);
269 Stmt::new(StmtKind::Block(compiled_body?), Span::default())
270 };
271 for v in compile_cap.vars.iter() {
272 ctx.as_ref().map(|ctx| arg_tys.push(ctx.vars[*v].get_ty()));
273 }
274 let fn_id = if self.compile_depth > 0 {
275 let fn_id = self.declare_compiled_fn(Some(&(name.clone(), id)), &arg_tys, ret_ty.clone())?;
276 self.pending_fns.push_back(PendingFn { name: name.clone(), symbol_id: id, fn_id, arg_tys: arg_tys.clone(), ret_ty: ret_ty.clone(), body });
277 fn_id
278 } else {
279 let fn_id = self.compile_fn(Some((name.clone(), id)), &arg_tys, ret_ty.clone(), &body)?;
280 self.drain_pending_fns()?;
281 self.module.finalize_definitions()?;
282 fn_id
283 };
284 return Ok(FnInfo::Call { fn_id, arg_tys: arg_tys.to_vec(), caps: compile_cap.vars.clone(), ret: ret_ty, context: None });
285 }
286 let ret_ty = self.compiler.infer_fn_with_params(id, &arg_tys, generic_args)?;
287 for v in cap.vars.iter() {
288 ctx.as_ref().map(|ctx| arg_tys.push(ctx.vars[*v].get_ty()));
289 }
290 let body = if generic_params.is_empty() { body.as_ref().clone() } else { substitute_stmt(body.as_ref(), &generic_params, generic_args) };
291 let fn_id = if self.compile_depth > 0 {
292 let fn_id = self.declare_compiled_fn(Some(&(name.clone(), id)), &arg_tys, ret_ty.clone())?;
293 self.pending_fns.push_back(PendingFn { name: name.clone(), symbol_id: id, fn_id, arg_tys: arg_tys.clone(), ret_ty: ret_ty.clone(), body });
294 fn_id
295 } else {
296 let fn_id = self.compile_fn(Some((name.clone(), id)), &arg_tys, ret_ty.clone(), &body)?;
297 self.drain_pending_fns()?;
298 self.module.finalize_definitions()?;
299 fn_id
300 };
301 return Ok(FnInfo::Call { fn_id, arg_tys: arg_tys.to_vec(), caps: cap.vars.clone(), ret: ret_ty, context: None });
302 }
303 Err(anyhow!("生成函数 {} 失败", id))
304 }
305}