1use super::{JITRunTime, context::BuildContext};
2use cranelift::prelude::*;
3use cranelift_module::{DataDescription, Module};
4use dynamic::{Dynamic, Type};
5use parser::{BinaryOp, Expr};
6
7use anyhow::{Result, anyhow};
8
9impl JITRunTime {
10 fn any_to_string(&mut self, ctx: &mut BuildContext, vt: (Value, Type)) -> Result<Value> {
11 let value = self.convert(ctx, vt, Type::Any)?;
12 self.call(ctx, self.get_method(&Type::Any, "to_string")?, vec![value]).map(|(v, _)| v)
13 }
14
15 fn any_logic(&mut self, ctx: &mut BuildContext, left: Value, op: BinaryOp, right: Value) -> Result<(Value, Type)> {
16 let op = ctx.builder.ins().iconst(types::I32, i32::from(op) as i64);
17 self.call(ctx, self.get_method(&Type::Any, "logic")?, vec![left, op, right])
18 }
19
20 fn any_binary(&mut self, ctx: &mut BuildContext, left: Value, op: BinaryOp, right: Value) -> Result<(Value, Type)> {
21 let op = ctx.builder.ins().iconst(types::I32, i32::from(op) as i64);
22 self.call(ctx, self.get_method(&Type::Any, "binary")?, vec![left, op, right])
23 }
24
25 fn struct_to_dynamic(&mut self, ctx: &mut BuildContext, base: Value, ty: &Type) -> Result<Value> {
26 let Type::Struct { params: _, fields: _ } = ty else {
27 return Err(anyhow!("不是结构体 {:?}", ty));
28 };
29 let id = self.module.declare_anonymous_data(true, false)?;
30 let mut desc = DataDescription::new();
31 let ty_ptr = Box::into_raw(Box::new(ty.clone()));
32 desc.define((ty_ptr as i64).to_le_bytes().into());
33 self.module.define_data(id, &desc)?;
34 let ty_data = self.module.declare_data_in_func(id, &mut ctx.builder.func);
35 let ty_addr = ctx.builder.ins().global_value(crate::ptr_type(), ty_data);
36 let ty_ptr = ctx.builder.ins().load(crate::ptr_type(), MemFlags::new(), ty_addr, 0);
37 let f = self.get_fn(self.get_id("__struct_from_ptr")?, &[Type::I64, Type::I64])?;
38 self.call(ctx, f, vec![base, ty_ptr]).map(|(v, _)| v)
39 }
40
41 pub(crate) fn bool_value(&mut self, ctx: &mut BuildContext, vt: (Value, Type)) -> Result<Value> {
42 if vt.1.is_bool() {
43 Ok(vt.0)
44 } else if vt.1.is_any() {
45 self.call(ctx, self.get_method(&Type::Any, "to_bool")?, vec![vt.0]).map(|(v, _)| v)
46 } else if vt.1.is_int() || vt.1.is_uint() {
47 Ok(ctx.builder.ins().icmp_imm(IntCC::NotEqual, vt.0, 0))
48 } else if vt.1.is_f32() {
49 let zero = ctx.builder.ins().f32const(0.0);
50 Ok(ctx.builder.ins().fcmp(FloatCC::NotEqual, vt.0, zero))
51 } else if vt.1.is_f64() {
52 let zero = ctx.builder.ins().f64const(0.0);
53 Ok(ctx.builder.ins().fcmp(FloatCC::NotEqual, vt.0, zero))
54 } else {
55 Err(anyhow!("cannot convert {:?} to bool", vt.1))
56 }
57 }
58
59 pub fn convert(&mut self, ctx: &mut BuildContext, vt: (Value, Type), ty: Type) -> Result<Value> {
60 let vt = if matches!(vt.1, Type::Symbol { .. }) {
61 let resolved = self.compiler.symbols.get_type(&vt.1).unwrap_or_else(|_| vt.1.clone());
62 (vt.0, resolved)
63 } else {
64 vt
65 };
66 if vt.1 != ty {
67 if ty.is_any() {
68 if vt.1.is_struct() {
69 return self.struct_to_dynamic(ctx, vt.0, &vt.1);
70 } else if vt.1.is_bool() {
71 return self.call(ctx, self.get_method(&Type::Any, "from_bool")?, vec![vt.0]).map(|(v, _)| v);
72 } else if vt.1.is_uint() {
73 let v = if vt.1.width() < 8 { ctx.builder.ins().uextend(types::I64, vt.0) } else { vt.0 };
74 return self.call(ctx, self.get_method(&Type::Any, "from_i64")?, vec![v]).map(|(v, _)| v);
75 } else if vt.1.is_int() {
76 let v = if vt.1.width() < 8 { ctx.builder.ins().sextend(types::I64, vt.0) } else { vt.0 };
77 return self.call(ctx, self.get_method(&Type::Any, "from_i64")?, vec![v]).map(|(v, _)| v);
78 } else if vt.1.is_f32() {
79 let v = ctx.builder.ins().fpromote(types::F64, vt.0);
80 return self.call(ctx, self.get_method(&Type::Any, "from_f64")?, vec![v]).map(|(v, _)| v);
81 } else if vt.1.is_f64() {
82 return self.call(ctx, self.get_method(&Type::Any, "from_f64")?, vec![vt.0]).map(|(v, _)| v);
83 } else if vt.1.is_str() {
84 return Ok(vt.0);
85 } else if matches!(vt.1, Type::Symbol { .. }) {
86 return Ok(vt.0);
87 }
88 } else if vt.1.is_any() {
89 if ty.is_bool() {
90 return self.call(ctx, self.get_method(&Type::Any, "to_bool")?, vec![vt.0]).map(|(v, _)| v);
91 } else if ty.is_str() {
92 return self.call(ctx, self.get_method(&Type::Any, "to_string")?, vec![vt.0]).map(|(v, _)| v);
93 } else if ty.is_int() | ty.is_uint() {
94 let (v, _) = self.call(ctx, self.get_method(&Type::Any, "to_i64")?, vec![vt.0])?;
95 return Ok(match ty.width() {
96 1 => ctx.builder.ins().ireduce(types::I8, v),
97 2 => ctx.builder.ins().ireduce(types::I16, v),
98 4 => ctx.builder.ins().ireduce(types::I32, v),
99 _ => v,
100 });
101 } else if ty.is_f32() {
102 let v = self.call(ctx, self.get_method(&Type::Any, "to_f64")?, vec![vt.0]).map(|(v, _)| v)?;
103 return Ok(ctx.builder.ins().fdemote(types::F32, v));
104 } else if ty.is_f64() {
105 return self.call(ctx, self.get_method(&Type::Any, "to_f64")?, vec![vt.0]).map(|(v, _)| v);
106 } else {
107 return Ok(vt.0);
108 }
109 } else if ty.is_str() {
110 return self.any_to_string(ctx, vt);
111 } else if ty.is_int() || ty.is_uint() {
112 if vt.1.is_f32() || vt.1.is_f64() {
113 let target = crate::get_type(&ty)?;
114 if ty.is_uint() {
115 return Ok(ctx.builder.ins().fcvt_to_uint(target, vt.0));
116 } else if ty.is_int() {
117 return Ok(ctx.builder.ins().fcvt_to_sint(target, vt.0));
118 }
119 }
120 if vt.1.is_int() || vt.1.is_uint() || vt.1.is_bool() {
121 let target = crate::get_type(&ty)?;
122 let actual = ctx.builder.func.dfg.value_type(vt.0);
123 if actual == target {
124 return Ok(vt.0);
125 }
126 if actual.is_int() && target.is_int() {
127 if actual.bits() > target.bits() {
128 return Ok(ctx.builder.ins().ireduce(target, vt.0));
129 }
130 if actual.bits() < target.bits() {
131 return if vt.1.is_int() { Ok(ctx.builder.ins().sextend(target, vt.0)) } else { Ok(ctx.builder.ins().uextend(target, vt.0)) };
132 }
133 }
134 }
135 if vt.1.is_str() {
136 let (v, _) = self.call(ctx, self.get_method(&Type::Any, "to_i64")?, vec![vt.0])?;
137 return Ok(match ty.width() {
138 1 => ctx.builder.ins().ireduce(types::I8, v),
139 2 => ctx.builder.ins().ireduce(types::I16, v),
140 4 => ctx.builder.ins().ireduce(types::I32, v),
141 _ => v,
142 });
143 }
144 } else if ty.is_f32() {
145 if vt.1.is_int() {
146 return Ok(ctx.builder.ins().fcvt_from_sint(types::F32, vt.0));
147 } else if vt.1.is_uint() {
148 return Ok(ctx.builder.ins().fcvt_from_uint(types::F32, vt.0));
149 } else if vt.1.is_f64() {
150 return Ok(ctx.builder.ins().fdemote(types::F32, vt.0));
151 }
152 } else if ty.is_f64() {
153 if vt.1.is_int() {
154 return Ok(ctx.builder.ins().fcvt_from_sint(types::F64, vt.0));
155 } else if vt.1.is_uint() {
156 return Ok(ctx.builder.ins().fcvt_from_uint(types::F64, vt.0));
157 } else if vt.1.is_f32() {
158 return Ok(ctx.builder.ins().fpromote(types::F64, vt.0));
159 }
160 } else if let Type::Symbol { id: _, params: _ } = ty {
161 log::info!("convert {:?} -> {:?}", vt, ty);
162 return Ok(vt.0); }
164 if vt.1.is_bool() {
165 let v = ctx.builder.ins().sextend(types::I64, vt.0);
166 return self.call(ctx, self.get_method(&Type::Any, "from_i64")?, vec![v]).map(|(v, _)| v);
167 }
168 log::error!("未实现 {:?} {:?}", vt, ty); Ok(vt.0)
170 } else {
171 Ok(vt.0)
172 }
173 }
174
175 pub(crate) fn binary(&mut self, ctx: &mut BuildContext, left: (Value, Type), op: BinaryOp, right: &Expr) -> Result<(Value, Type)> {
176 if matches!(op, BinaryOp::And | BinaryOp::Or) {
178 return self.short_circuit_logic(ctx, left, op, right);
179 }
180 let right_ty_hint = if right.is_value() { right.clone().value().ok().map(|v| v.get_type()) } else { self.get_dynamic(right).map(|v| v.get_type()) };
181 let right = if right.is_value() {
182 let right = right.clone().value()?;
183 if right.is_f32() {
184 (ctx.builder.ins().f32const(right.as_float().unwrap() as f32), Type::F32)
185 } else if right.is_f64() {
186 (ctx.builder.ins().f64const(right.as_float().unwrap() as f64), Type::F64)
187 } else if left.1.is_any() {
188 if right.is_int() {
189 (ctx.builder.ins().iconst(types::I64, right.as_int().unwrap()), Type::I64)
190 } else if right.is_null() {
191 self.call(ctx, self.get_method(&Type::Any, "null")?, vec![])?
192 } else {
193 ctx.get_const(&right)?
194 }
195 } else {
196 return self.binary_imm(ctx, left, op, right);
197 }
198 } else {
199 self.eval(ctx, right)?.get(ctx).ok_or_else(|| anyhow!("没有返回值: {:?}", right))?
200 };
201 let right_ty = right_ty_hint.as_ref().unwrap_or(&right.1);
202 let ty = if (op.is_add() || op.is_logic()) && (left.1.is_str() || right.1.is_str() || right_ty.is_str()) {
203 Type::Str
204 } else if (op.is_add() || op.is_logic()) && (left.1.is_any() || right.1.is_any()) {
205 Type::Any
206 } else {
207 left.1.clone() + right.1.clone()
208 }; if ty.is_str() && op.is_add() {
210 let left = self.convert(ctx, left, Type::Any)?;
211 let right = self.convert(ctx, right, Type::Any)?;
212 let result = self.any_binary(ctx, left, op, right)?.0;
213 return Ok((result, ty));
214 }
215 let left = self.convert(ctx, left, ty.clone())?;
216 let right = self.convert(ctx, right, ty.clone())?;
217 if ty.is_any() {
218 if op.is_logic() {
219 return self.any_logic(ctx, left, op, right);
220 } else {
221 return self.any_binary(ctx, left, op, right);
222 }
223 }
224 if ty.is_str() && op.is_logic() {
225 return self.any_logic(ctx, left, op, right);
226 }
227 match op {
228 BinaryOp::Add | BinaryOp::AddAssign => {
229 if ty.is_int() || ty.is_uint() {
230 return Ok((ctx.builder.ins().iadd(left, right), ty));
231 } else if ty.is_float() {
232 return Ok((ctx.builder.ins().fadd(left, right), ty));
233 } else if ty.is_str() {
234 let result = self.any_binary(ctx, left, op, right)?.0;
235 return Ok((result, ty));
236 }
237 }
238 BinaryOp::Sub | BinaryOp::SubAssign => {
239 if ty.is_int() || ty.is_uint() {
240 return Ok((ctx.builder.ins().isub(left, right), ty));
241 } else if ty.is_float() {
242 return Ok((ctx.builder.ins().fsub(left, right), ty));
243 }
244 }
245 BinaryOp::Mul | BinaryOp::MulAssign => {
246 if ty.is_int() || ty.is_uint() {
247 return Ok((ctx.builder.ins().imul(left, right), ty));
248 } else if ty.is_float() {
249 return Ok((ctx.builder.ins().fmul(left, right), ty));
250 }
251 }
252 BinaryOp::Div | BinaryOp::DivAssign => {
253 if ty.is_int() {
254 return Ok((ctx.builder.ins().sdiv(left, right), ty));
255 } else if ty.is_uint() {
256 return Ok((ctx.builder.ins().udiv(left, right), ty));
257 } else if ty.is_float() {
258 return Ok((ctx.builder.ins().fdiv(left, right), ty));
259 }
260 }
261 BinaryOp::Mod | BinaryOp::ModAssign => {
262 if ty.is_int() {
263 return Ok((ctx.builder.ins().srem(left, right), ty));
264 } else if ty.is_uint() {
265 return Ok((ctx.builder.ins().urem(left, right), ty));
266 }
267 }
268 BinaryOp::Shl | BinaryOp::ShlAssign => {
269 if ty.is_int() || ty.is_uint() {
270 return Ok((ctx.builder.ins().ishl(left, right), ty));
271 }
272 }
273 BinaryOp::Shr | BinaryOp::ShrAssign => {
274 if ty.is_int() {
275 return Ok((ctx.builder.ins().sshr(left, right), ty));
276 } else if ty.is_uint() {
277 return Ok((ctx.builder.ins().ushr(left, right), ty));
278 }
279 }
280 BinaryOp::BitAnd | BinaryOp::BitAndAssign => {
281 return Ok((ctx.builder.ins().band(left, right), ty));
282 }
283 BinaryOp::BitOr | BinaryOp::BitOrAssign => {
284 return Ok((ctx.builder.ins().bor(left, right), ty));
285 }
286 BinaryOp::BitXor | BinaryOp::BitXorAssign => {
287 return Ok((ctx.builder.ins().bxor(left, right), ty));
288 }
289 BinaryOp::Eq => {
290 if ty.is_int() | ty.is_uint() || ty.is_bool() {
291 return Ok((ctx.builder.ins().icmp(IntCC::Equal, left, right), Type::Bool));
292 } else if ty.is_float() {
293 return Ok((ctx.builder.ins().fcmp(FloatCC::Equal, left, right), Type::Bool));
294 }
295 }
296 BinaryOp::Ne => {
297 if ty.is_int() | ty.is_uint() || ty.is_bool() {
298 return Ok((ctx.builder.ins().icmp(IntCC::NotEqual, left, right), Type::Bool));
299 } else if ty.is_float() {
300 return Ok((ctx.builder.ins().fcmp(FloatCC::NotEqual, left, right), Type::Bool));
301 }
302 }
303 BinaryOp::Lt => {
304 if ty.is_int() {
305 return Ok((ctx.builder.ins().icmp(IntCC::SignedLessThan, left, right), Type::Bool));
306 } else if ty.is_uint() {
307 return Ok((ctx.builder.ins().icmp(IntCC::UnsignedLessThan, left, right), Type::Bool));
308 } else if ty.is_float() {
309 return Ok((ctx.builder.ins().fcmp(FloatCC::LessThan, left, right), Type::Bool));
310 }
311 }
312 BinaryOp::Le => {
313 if ty.is_int() {
314 return Ok((ctx.builder.ins().icmp(IntCC::SignedLessThanOrEqual, left, right), Type::Bool));
315 } else if ty.is_uint() {
316 return Ok((ctx.builder.ins().icmp(IntCC::UnsignedLessThanOrEqual, left, right), Type::Bool));
317 } else if ty.is_float() {
318 return Ok((ctx.builder.ins().fcmp(FloatCC::LessThanOrEqual, left, right), Type::Bool));
319 }
320 }
321 BinaryOp::Gt => {
322 if ty.is_int() {
323 return Ok((ctx.builder.ins().icmp(IntCC::SignedGreaterThan, left, right), Type::Bool));
324 } else if ty.is_uint() {
325 return Ok((ctx.builder.ins().icmp(IntCC::UnsignedGreaterThan, left, right), Type::Bool));
326 } else if ty.is_float() {
327 return Ok((ctx.builder.ins().fcmp(FloatCC::GreaterThan, left, right), Type::Bool));
328 }
329 }
330 BinaryOp::Ge => {
331 if ty.is_int() {
332 return Ok((ctx.builder.ins().icmp(IntCC::SignedGreaterThanOrEqual, left, right), Type::Bool));
333 } else if ty.is_uint() {
334 return Ok((ctx.builder.ins().icmp(IntCC::UnsignedGreaterThanOrEqual, left, right), Type::Bool));
335 } else if ty.is_float() {
336 return Ok((ctx.builder.ins().fcmp(FloatCC::GreaterThanOrEqual, left, right), Type::Bool));
337 }
338 }
339 _ => {}
340 }
341 panic!("未实现 {:?} {:?} {:?} {:?}", left, op, right, ty)
342 }
343
344 pub(crate) fn binary_imm<'a>(&mut self, ctx: &'a mut BuildContext, left: (Value, Type), op: BinaryOp, right: Dynamic) -> Result<(Value, Type)> {
345 let ty = left.1.clone() + right.get_type();
346 if ty.is_str() && op.is_add() {
347 let left = self.convert(ctx, left, Type::Any)?;
348 let right_vt = ctx.get_const(&right).or_else(|_| {
349 let idx = self.compiler.get_const(right.clone());
350 self.get_const_value(ctx, idx)
351 })?;
352 let right = self.convert(ctx, right_vt, Type::Any)?;
353 let result = self.any_binary(ctx, left, op, right)?.0;
354 return Ok((result, ty));
355 }
356 let left = self.convert(ctx, left, ty.clone())?;
357 if ty.is_str() && op.is_logic() {
358 let right_vt = ctx.get_const(&right).or_else(|_| {
359 let idx = self.compiler.get_const(right.clone());
360 self.get_const_value(ctx, idx)
361 })?;
362 let right = self.convert(ctx, right_vt, Type::Str)?;
363 return self.any_logic(ctx, left, op, right);
364 }
365 match op {
366 BinaryOp::Add | BinaryOp::AddAssign => {
367 if ty.is_str() {
368 let right_vt = ctx.get_const(&right).or_else(|_| {
369 let idx = self.compiler.get_const(right.clone());
370 self.get_const_value(ctx, idx)
371 })?;
372 let right = self.convert(ctx, right_vt, Type::Str)?;
373 let result = self.any_binary(ctx, left, op, right)?.0;
374 return Ok((result, ty));
375 }
376 if ty.is_int() | ty.is_uint() {
377 return Ok((ctx.builder.ins().iadd_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
378 }
379 }
380 BinaryOp::Sub | BinaryOp::SubAssign => {
381 if ty.is_int() | ty.is_uint() {
382 return Ok((ctx.builder.ins().iadd_imm(left, -right.as_int().ok_or(anyhow!("非整数"))?), ty));
383 }
384 }
385 BinaryOp::Mul | BinaryOp::MulAssign => {
386 if ty.is_int() | ty.is_uint() {
387 return Ok((ctx.builder.ins().imul_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
388 }
389 }
390 BinaryOp::Div | BinaryOp::DivAssign => {
391 if ty.is_int() {
392 return Ok((ctx.builder.ins().sdiv_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
393 } else if ty.is_uint() {
394 return Ok((ctx.builder.ins().udiv_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
395 }
396 }
397 BinaryOp::Shl | BinaryOp::ShlAssign => {
398 if ty.is_int() || ty.is_uint() {
399 return Ok((ctx.builder.ins().ishl_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
400 }
401 }
402 BinaryOp::Shr | BinaryOp::ShrAssign => {
403 if ty.is_int() {
404 return Ok((ctx.builder.ins().sshr_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
405 } else if ty.is_uint() {
406 return Ok((ctx.builder.ins().ushr_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
407 }
408 }
409 BinaryOp::BitAnd | BinaryOp::BitAndAssign => {
410 return Ok((ctx.builder.ins().band_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
411 }
412 BinaryOp::BitOr | BinaryOp::BitOrAssign => {
413 return Ok((ctx.builder.ins().bor_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
414 }
415 BinaryOp::BitXor | BinaryOp::BitXorAssign => {
416 return Ok((ctx.builder.ins().bxor_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
417 }
418 BinaryOp::Eq => {
419 if ty.is_int() | ty.is_uint() {
420 return Ok((ctx.builder.ins().icmp_imm(IntCC::Equal, left, right.as_int().unwrap()), Type::Bool));
421 }
422 }
423 BinaryOp::Ne => {
424 if ty.is_int() | ty.is_uint() {
425 return Ok((ctx.builder.ins().icmp_imm(IntCC::NotEqual, left, right.as_int().unwrap()), Type::Bool));
426 }
427 }
428 BinaryOp::Le => {
429 if ty.is_int() {
430 return Ok((ctx.builder.ins().icmp_imm(IntCC::SignedLessThanOrEqual, left, right.as_int().unwrap()), Type::Bool));
431 } else if ty.is_uint() {
432 return Ok((ctx.builder.ins().icmp_imm(IntCC::UnsignedLessThanOrEqual, left, right.as_int().unwrap()), Type::Bool));
433 }
434 }
435 BinaryOp::Lt => {
436 if ty.is_int() {
437 return Ok((ctx.builder.ins().icmp_imm(IntCC::SignedLessThan, left, right.as_int().unwrap()), Type::Bool));
438 } else if ty.is_uint() {
439 return Ok((ctx.builder.ins().icmp_imm(IntCC::UnsignedLessThan, left, right.as_int().unwrap()), Type::Bool));
440 }
441 }
442 BinaryOp::Ge => {
443 if ty.is_int() {
444 return Ok((ctx.builder.ins().icmp_imm(IntCC::SignedGreaterThanOrEqual, left, right.as_int().unwrap()), Type::Bool));
445 } else if ty.is_uint() {
446 return Ok((ctx.builder.ins().icmp_imm(IntCC::UnsignedGreaterThanOrEqual, left, right.as_int().unwrap()), Type::Bool));
447 }
448 }
449 BinaryOp::Gt => {
450 if ty.is_int() {
451 return Ok((ctx.builder.ins().icmp_imm(IntCC::SignedGreaterThan, left, right.as_int().unwrap()), Type::Bool));
452 } else if ty.is_uint() {
453 return Ok((ctx.builder.ins().icmp_imm(IntCC::UnsignedGreaterThan, left, right.as_int().unwrap()), Type::Bool));
454 }
455 }
456 BinaryOp::Mod | BinaryOp::ModAssign => {
457 if ty.is_int() {
458 return Ok((ctx.builder.ins().srem_imm(left, right.as_int().unwrap()), ty));
459 } else if ty.is_uint() {
460 return Ok((ctx.builder.ins().urem_imm(left, right.as_int().unwrap()), ty));
461 }
462 }
463 exp => {
464 panic!("不支持的操作 {:?}", exp)
465 }
466 }
467 panic!("未实现 {:?} {:?} {:?}", ty, op, right.get_type())
468 }
469}