forked from amber-lang/amber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compute.rs
64 lines (60 loc) · 1.83 KB
/
compute.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use crate::utils::TranslateMetadata;
pub enum ArithType {
BcSed
}
pub enum ArithOp {
Add,
Sub,
Mul,
Div,
Modulo,
Neg,
Gt,
Ge,
Lt,
Le,
Eq,
Neq,
Not,
And,
Or
}
pub fn translate_computation(meta: &TranslateMetadata, operation: ArithOp, left: Option<String>, right: Option<String>) -> String {
match meta.arith_module {
ArithType::BcSed => {
let (left, right) = (left.unwrap_or_default(), right.unwrap_or_default());
let mut math_lib_flag = true;
// Removes trailing zeros from the expression
let sed_regex = "/\\./ s/\\.\\{0,1\\}0\\{1,\\}$//";
let op = match operation {
ArithOp::Add => "+",
ArithOp::Sub => "-",
ArithOp::Mul => "*",
ArithOp::Div => "/",
ArithOp::Modulo => {
math_lib_flag = false;
"%"
},
ArithOp::Neg => "-",
ArithOp::Gt => ">",
ArithOp::Ge => ">=",
ArithOp::Lt => "<",
ArithOp::Le => "<=",
ArithOp::Eq => "==",
ArithOp::Neq => "!=",
ArithOp::Not => "!",
ArithOp::And => "&&",
ArithOp::Or => "||"
};
let math_lib_flag = if math_lib_flag { "-l" } else { "" };
meta.gen_subprocess(&format!("echo {left} '{op}' {right} | bc {math_lib_flag} | sed '{sed_regex}'"))
}
}
}
pub fn translate_computation_eval(meta: &mut TranslateMetadata, operation: ArithOp, left: Option<String>, right: Option<String>) -> String {
let old_eval = meta.eval_ctx;
meta.eval_ctx = true;
let result = translate_computation(meta, operation, left, right);
meta.eval_ctx = old_eval;
result
}