Skip to main content

vm/
binary.rs

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        if vt.1 != ty {
61            if ty.is_any() {
62                if vt.1.is_struct() {
63                    return self.struct_to_dynamic(ctx, vt.0, &vt.1);
64                } else if vt.1.is_bool() {
65                    return self.call(ctx, self.get_method(&Type::Any, "from_bool")?, vec![vt.0]).map(|(v, _)| v);
66                } else if vt.1.is_uint() {
67                    let v = if vt.1.width() < 8 { ctx.builder.ins().uextend(types::I64, vt.0) } else { vt.0 };
68                    return self.call(ctx, self.get_method(&Type::Any, "from_i64")?, vec![v]).map(|(v, _)| v);
69                } else if vt.1.is_int() {
70                    let v = if vt.1.width() < 8 { ctx.builder.ins().sextend(types::I64, vt.0) } else { vt.0 };
71                    return self.call(ctx, self.get_method(&Type::Any, "from_i64")?, vec![v]).map(|(v, _)| v);
72                } else if vt.1.is_f32() {
73                    let v = ctx.builder.ins().fpromote(types::F64, vt.0);
74                    return self.call(ctx, self.get_method(&Type::Any, "from_f64")?, vec![v]).map(|(v, _)| v);
75                } else if vt.1.is_f64() {
76                    return self.call(ctx, self.get_method(&Type::Any, "from_f64")?, vec![vt.0]).map(|(v, _)| v);
77                } else if vt.1.is_str() {
78                    return Ok(vt.0);
79                }
80            } else if vt.1.is_any() {
81                if ty.is_bool() {
82                    return self.call(ctx, self.get_method(&Type::Any, "to_bool")?, vec![vt.0]).map(|(v, _)| v);
83                } else if ty.is_str() {
84                    return self.call(ctx, self.get_method(&Type::Any, "to_string")?, vec![vt.0]).map(|(v, _)| v);
85                } else if ty.is_int() | ty.is_uint() {
86                    let (v, _) = self.call(ctx, self.get_method(&Type::Any, "to_i64")?, vec![vt.0])?;
87                    return Ok(match ty.width() {
88                        1 => ctx.builder.ins().ireduce(types::I8, v),
89                        2 => ctx.builder.ins().ireduce(types::I16, v),
90                        4 => ctx.builder.ins().ireduce(types::I32, v),
91                        _ => v,
92                    });
93                } else if ty.is_f32() {
94                    let v = self.call(ctx, self.get_method(&Type::Any, "to_f64")?, vec![vt.0]).map(|(v, _)| v)?;
95                    return Ok(ctx.builder.ins().fdemote(types::F32, v));
96                } else if ty.is_f64() {
97                    return self.call(ctx, self.get_method(&Type::Any, "to_f64")?, vec![vt.0]).map(|(v, _)| v);
98                } else {
99                    return Ok(vt.0);
100                }
101            } else if ty.is_str() {
102                return self.any_to_string(ctx, vt);
103            } else if ty.is_int() || ty.is_uint() {
104                if vt.1.is_f32() || vt.1.is_f64() {
105                    let target = crate::get_type(&ty)?;
106                    if ty.is_uint() {
107                        return Ok(ctx.builder.ins().fcvt_to_uint(target, vt.0));
108                    } else if ty.is_int() {
109                        return Ok(ctx.builder.ins().fcvt_to_sint(target, vt.0));
110                    }
111                }
112                if vt.1.is_int() || vt.1.is_uint() || vt.1.is_bool() {
113                    let target = crate::get_type(&ty)?;
114                    let actual = ctx.builder.func.dfg.value_type(vt.0);
115                    if actual == target {
116                        return Ok(vt.0);
117                    }
118                    if actual.is_int() && target.is_int() {
119                        if actual.bits() > target.bits() {
120                            return Ok(ctx.builder.ins().ireduce(target, vt.0));
121                        }
122                        if actual.bits() < target.bits() {
123                            return if vt.1.is_int() { Ok(ctx.builder.ins().sextend(target, vt.0)) } else { Ok(ctx.builder.ins().uextend(target, vt.0)) };
124                        }
125                    }
126                }
127            } else if ty.is_f32() {
128                if vt.1.is_int() {
129                    return Ok(ctx.builder.ins().fcvt_from_sint(types::F32, vt.0));
130                } else if vt.1.is_uint() {
131                    return Ok(ctx.builder.ins().fcvt_from_uint(types::F32, vt.0));
132                } else if vt.1.is_f64() {
133                    return Ok(ctx.builder.ins().fdemote(types::F32, vt.0));
134                }
135            } else if ty.is_f64() {
136                if vt.1.is_int() {
137                    return Ok(ctx.builder.ins().fcvt_from_sint(types::F64, vt.0));
138                } else if vt.1.is_uint() {
139                    return Ok(ctx.builder.ins().fcvt_from_uint(types::F64, vt.0));
140                } else if vt.1.is_f32() {
141                    return Ok(ctx.builder.ins().fpromote(types::F64, vt.0));
142                }
143            } else if let Type::Symbol { id: _, params: _ } = ty {
144                log::info!("convert {:?} -> {:?}", vt, ty);
145                return Ok(vt.0); //结构类型 可以看作 External 类型
146            }
147            if vt.1.is_bool() {
148                let v = ctx.builder.ins().sextend(types::I64, vt.0);
149                return self.call(ctx, self.get_method(&Type::Any, "from_i64")?, vec![v]).map(|(v, _)| v);
150            }
151            log::error!("未实现 {:?} {:?}", vt, ty); //暂时还没有实现 struct 的 初始化
152            Ok(vt.0)
153        } else {
154            Ok(vt.0)
155        }
156    }
157
158    pub(crate) fn binary(&mut self, ctx: &mut BuildContext, left: (Value, Type), op: BinaryOp, right: &Expr) -> Result<(Value, Type)> {
159        //处理可以计算的简单情形
160        if matches!(op, BinaryOp::And | BinaryOp::Or) {
161            return self.short_circuit_logic(ctx, left, op, right);
162        }
163        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()) };
164        let right = if right.is_value() {
165            let right = right.clone().value()?;
166            if right.is_f32() {
167                (ctx.builder.ins().f32const(right.as_float().unwrap() as f32), Type::F32)
168            } else if right.is_f64() {
169                (ctx.builder.ins().f64const(right.as_float().unwrap() as f64), Type::F64)
170            } else if left.1.is_any() {
171                if right.is_int() {
172                    (ctx.builder.ins().iconst(types::I64, right.as_int().unwrap()), Type::I64)
173                } else if right.is_null() {
174                    self.call(ctx, self.get_method(&Type::Any, "null")?, vec![])?
175                } else {
176                    ctx.get_const(&right)?
177                }
178            } else {
179                return self.binary_imm(ctx, left, op, right);
180            }
181        } else {
182            self.eval(ctx, right)?.get(ctx).ok_or_else(|| anyhow!("没有返回值: {:?}", right))?
183        };
184        let right_ty = right_ty_hint.as_ref().unwrap_or(&right.1);
185        let ty = if (op.is_add() || op.is_logic()) && (left.1.is_str() || right.1.is_str() || right_ty.is_str()) {
186            Type::Str
187        } else if (op.is_add() || op.is_logic()) && (left.1.is_any() || right.1.is_any()) {
188            Type::Any
189        } else {
190            left.1.clone() + right.1.clone()
191        }; //为了支持字符串的加法需要单独处理
192        if ty.is_str() && op.is_add() {
193            let left = self.convert(ctx, left, Type::Any)?;
194            let right = self.convert(ctx, right, Type::Any)?;
195            let result = self.any_binary(ctx, left, op, right)?.0;
196            return Ok((result, ty));
197        }
198        let left = self.convert(ctx, left, ty.clone())?;
199        let right = self.convert(ctx, right, ty.clone())?;
200        if ty.is_any() {
201            if op.is_logic() {
202                return self.any_logic(ctx, left, op, right);
203            } else {
204                return self.any_binary(ctx, left, op, right);
205            }
206        }
207        if ty.is_str() && op.is_logic() {
208            return self.any_logic(ctx, left, op, right);
209        }
210        match op {
211            BinaryOp::Add | BinaryOp::AddAssign => {
212                if ty.is_int() || ty.is_uint() {
213                    return Ok((ctx.builder.ins().iadd(left, right), ty));
214                } else if ty.is_float() {
215                    return Ok((ctx.builder.ins().fadd(left, right), ty));
216                } else if ty.is_str() {
217                    let result = self.any_binary(ctx, left, op, right)?.0;
218                    return Ok((result, ty));
219                }
220            }
221            BinaryOp::Sub | BinaryOp::SubAssign => {
222                if ty.is_int() || ty.is_uint() {
223                    return Ok((ctx.builder.ins().isub(left, right), ty));
224                } else if ty.is_float() {
225                    return Ok((ctx.builder.ins().fsub(left, right), ty));
226                }
227            }
228            BinaryOp::Mul | BinaryOp::MulAssign => {
229                if ty.is_int() || ty.is_uint() {
230                    return Ok((ctx.builder.ins().imul(left, right), ty));
231                } else if ty.is_float() {
232                    return Ok((ctx.builder.ins().fmul(left, right), ty));
233                }
234            }
235            BinaryOp::Div | BinaryOp::DivAssign => {
236                if ty.is_int() {
237                    return Ok((ctx.builder.ins().sdiv(left, right), ty));
238                } else if ty.is_uint() {
239                    return Ok((ctx.builder.ins().udiv(left, right), ty));
240                } else if ty.is_float() {
241                    return Ok((ctx.builder.ins().fdiv(left, right), ty));
242                }
243            }
244            BinaryOp::Mod | BinaryOp::ModAssign => {
245                if ty.is_int() {
246                    return Ok((ctx.builder.ins().srem(left, right), ty));
247                } else if ty.is_uint() {
248                    return Ok((ctx.builder.ins().urem(left, right), ty));
249                }
250            }
251            BinaryOp::Shl | BinaryOp::ShlAssign => {
252                if ty.is_int() || ty.is_uint() {
253                    return Ok((ctx.builder.ins().ishl(left, right), ty));
254                }
255            }
256            BinaryOp::Shr | BinaryOp::ShrAssign => {
257                if ty.is_int() {
258                    return Ok((ctx.builder.ins().sshr(left, right), ty));
259                } else if ty.is_uint() {
260                    return Ok((ctx.builder.ins().ushr(left, right), ty));
261                }
262            }
263            BinaryOp::BitAnd | BinaryOp::BitAndAssign => {
264                return Ok((ctx.builder.ins().band(left, right), ty));
265            }
266            BinaryOp::BitOr | BinaryOp::BitOrAssign => {
267                return Ok((ctx.builder.ins().bor(left, right), ty));
268            }
269            BinaryOp::BitXor | BinaryOp::BitXorAssign => {
270                return Ok((ctx.builder.ins().bxor(left, right), ty));
271            }
272            BinaryOp::Eq => {
273                if ty.is_int() | ty.is_uint() || ty.is_bool() {
274                    return Ok((ctx.builder.ins().icmp(IntCC::Equal, left, right), Type::Bool));
275                } else if ty.is_float() {
276                    return Ok((ctx.builder.ins().fcmp(FloatCC::Equal, left, right), Type::Bool));
277                }
278            }
279            BinaryOp::Ne => {
280                if ty.is_int() | ty.is_uint() || ty.is_bool() {
281                    return Ok((ctx.builder.ins().icmp(IntCC::NotEqual, left, right), Type::Bool));
282                } else if ty.is_float() {
283                    return Ok((ctx.builder.ins().fcmp(FloatCC::NotEqual, left, right), Type::Bool));
284                }
285            }
286            BinaryOp::Lt => {
287                if ty.is_int() {
288                    return Ok((ctx.builder.ins().icmp(IntCC::SignedLessThan, left, right), Type::Bool));
289                } else if ty.is_uint() {
290                    return Ok((ctx.builder.ins().icmp(IntCC::UnsignedLessThan, left, right), Type::Bool));
291                } else if ty.is_float() {
292                    return Ok((ctx.builder.ins().fcmp(FloatCC::LessThan, left, right), Type::Bool));
293                }
294            }
295            BinaryOp::Le => {
296                if ty.is_int() {
297                    return Ok((ctx.builder.ins().icmp(IntCC::SignedLessThanOrEqual, left, right), Type::Bool));
298                } else if ty.is_uint() {
299                    return Ok((ctx.builder.ins().icmp(IntCC::UnsignedLessThanOrEqual, left, right), Type::Bool));
300                } else if ty.is_float() {
301                    return Ok((ctx.builder.ins().fcmp(FloatCC::LessThanOrEqual, left, right), Type::Bool));
302                }
303            }
304            BinaryOp::Gt => {
305                if ty.is_int() {
306                    return Ok((ctx.builder.ins().icmp(IntCC::SignedGreaterThan, left, right), Type::Bool));
307                } else if ty.is_uint() {
308                    return Ok((ctx.builder.ins().icmp(IntCC::UnsignedGreaterThan, left, right), Type::Bool));
309                } else if ty.is_float() {
310                    return Ok((ctx.builder.ins().fcmp(FloatCC::GreaterThan, left, right), Type::Bool));
311                }
312            }
313            BinaryOp::Ge => {
314                if ty.is_int() {
315                    return Ok((ctx.builder.ins().icmp(IntCC::SignedGreaterThanOrEqual, left, right), Type::Bool));
316                } else if ty.is_uint() {
317                    return Ok((ctx.builder.ins().icmp(IntCC::UnsignedGreaterThanOrEqual, left, right), Type::Bool));
318                } else if ty.is_float() {
319                    return Ok((ctx.builder.ins().fcmp(FloatCC::GreaterThanOrEqual, left, right), Type::Bool));
320                }
321            }
322            _ => {}
323        }
324        panic!("未实现 {:?} {:?} {:?} {:?}", left, op, right, ty)
325    }
326
327    pub(crate) fn binary_imm<'a>(&mut self, ctx: &'a mut BuildContext, left: (Value, Type), op: BinaryOp, right: Dynamic) -> Result<(Value, Type)> {
328        let ty = left.1.clone() + right.get_type();
329        if ty.is_str() && op.is_add() {
330            let left = self.convert(ctx, left, Type::Any)?;
331            let right_vt = ctx.get_const(&right).or_else(|_| {
332                let idx = self.compiler.get_const(right.clone());
333                self.get_const_value(ctx, idx)
334            })?;
335            let right = self.convert(ctx, right_vt, Type::Any)?;
336            let result = self.any_binary(ctx, left, op, right)?.0;
337            return Ok((result, ty));
338        }
339        let left = self.convert(ctx, left, ty.clone())?;
340        if ty.is_str() && op.is_logic() {
341            let right_vt = ctx.get_const(&right).or_else(|_| {
342                let idx = self.compiler.get_const(right.clone());
343                self.get_const_value(ctx, idx)
344            })?;
345            let right = self.convert(ctx, right_vt, Type::Str)?;
346            return self.any_logic(ctx, left, op, right);
347        }
348        match op {
349            BinaryOp::Add | BinaryOp::AddAssign => {
350                if ty.is_str() {
351                    let right_vt = ctx.get_const(&right).or_else(|_| {
352                        let idx = self.compiler.get_const(right.clone());
353                        self.get_const_value(ctx, idx)
354                    })?;
355                    let right = self.convert(ctx, right_vt, Type::Str)?;
356                    let result = self.any_binary(ctx, left, op, right)?.0;
357                    return Ok((result, ty));
358                }
359                if ty.is_int() | ty.is_uint() {
360                    return Ok((ctx.builder.ins().iadd_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
361                }
362            }
363            BinaryOp::Sub | BinaryOp::SubAssign => {
364                if ty.is_int() | ty.is_uint() {
365                    return Ok((ctx.builder.ins().iadd_imm(left, -right.as_int().ok_or(anyhow!("非整数"))?), ty));
366                }
367            }
368            BinaryOp::Mul | BinaryOp::MulAssign => {
369                if ty.is_int() | ty.is_uint() {
370                    return Ok((ctx.builder.ins().imul_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
371                }
372            }
373            BinaryOp::Div | BinaryOp::DivAssign => {
374                if ty.is_int() {
375                    return Ok((ctx.builder.ins().sdiv_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
376                } else if ty.is_uint() {
377                    return Ok((ctx.builder.ins().udiv_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
378                }
379            }
380            BinaryOp::Shl | BinaryOp::ShlAssign => {
381                if ty.is_int() || ty.is_uint() {
382                    return Ok((ctx.builder.ins().ishl_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
383                }
384            }
385            BinaryOp::Shr | BinaryOp::ShrAssign => {
386                if ty.is_int() {
387                    return Ok((ctx.builder.ins().sshr_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
388                } else if ty.is_uint() {
389                    return Ok((ctx.builder.ins().ushr_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
390                }
391            }
392            BinaryOp::BitAnd | BinaryOp::BitAndAssign => {
393                return Ok((ctx.builder.ins().band_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
394            }
395            BinaryOp::BitOr | BinaryOp::BitOrAssign => {
396                return Ok((ctx.builder.ins().bor_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
397            }
398            BinaryOp::BitXor | BinaryOp::BitXorAssign => {
399                return Ok((ctx.builder.ins().bxor_imm(left, right.as_int().ok_or(anyhow!("非整数"))?), ty));
400            }
401            BinaryOp::Eq => {
402                if ty.is_int() | ty.is_uint() {
403                    return Ok((ctx.builder.ins().icmp_imm(IntCC::Equal, left, right.as_int().unwrap()), Type::Bool));
404                }
405            }
406            BinaryOp::Ne => {
407                if ty.is_int() | ty.is_uint() {
408                    return Ok((ctx.builder.ins().icmp_imm(IntCC::NotEqual, left, right.as_int().unwrap()), Type::Bool));
409                }
410            }
411            BinaryOp::Le => {
412                if ty.is_int() {
413                    return Ok((ctx.builder.ins().icmp_imm(IntCC::SignedLessThanOrEqual, left, right.as_int().unwrap()), Type::Bool));
414                } else if ty.is_uint() {
415                    return Ok((ctx.builder.ins().icmp_imm(IntCC::UnsignedLessThanOrEqual, left, right.as_int().unwrap()), Type::Bool));
416                }
417            }
418            BinaryOp::Lt => {
419                if ty.is_int() {
420                    return Ok((ctx.builder.ins().icmp_imm(IntCC::SignedLessThan, left, right.as_int().unwrap()), Type::Bool));
421                } else if ty.is_uint() {
422                    return Ok((ctx.builder.ins().icmp_imm(IntCC::UnsignedLessThan, left, right.as_int().unwrap()), Type::Bool));
423                }
424            }
425            BinaryOp::Ge => {
426                if ty.is_int() {
427                    return Ok((ctx.builder.ins().icmp_imm(IntCC::SignedGreaterThanOrEqual, left, right.as_int().unwrap()), Type::Bool));
428                } else if ty.is_uint() {
429                    return Ok((ctx.builder.ins().icmp_imm(IntCC::UnsignedGreaterThanOrEqual, left, right.as_int().unwrap()), Type::Bool));
430                }
431            }
432            BinaryOp::Gt => {
433                if ty.is_int() {
434                    return Ok((ctx.builder.ins().icmp_imm(IntCC::SignedGreaterThan, left, right.as_int().unwrap()), Type::Bool));
435                } else if ty.is_uint() {
436                    return Ok((ctx.builder.ins().icmp_imm(IntCC::UnsignedGreaterThan, left, right.as_int().unwrap()), Type::Bool));
437                }
438            }
439            BinaryOp::Mod | BinaryOp::ModAssign => {
440                if ty.is_int() {
441                    return Ok((ctx.builder.ins().srem_imm(left, right.as_int().unwrap()), ty));
442                } else if ty.is_uint() {
443                    return Ok((ctx.builder.ins().urem_imm(left, right.as_int().unwrap()), ty));
444                }
445            }
446            exp => {
447                panic!("不支持的操作 {:?}", exp)
448            }
449        }
450        panic!("未实现 {:?} {:?} {:?}", ty, op, right.get_type())
451    }
452}