1use crate::value::Value;
2use crate::ast::Token;
3use crate::lang::exec_expr;
4use crate::vm::Mink;
5use crate::grammar;
6
7pub struct Script {
8 pub name: String,
9 actions: Vec<Token>,
10}
11
12impl Script {
13 pub fn new(name: impl Into<String>, code: impl Into<String>) -> Self {
14 let code = code.into();
15 let lines: Vec<&str> = code.split("\n").collect();
16
17 let mut actions: Vec<Token> = Vec::new();
18 for line in lines {
19 if line.trim().is_empty() { continue; }
20 actions.push(grammar::LineParser::new().parse(line).unwrap());
21 }
22
23 Self::from_actions(name, actions)
24 }
25 pub(crate) fn from_actions(name: impl Into<String>, actions: Vec<Token>) -> Self {
26 Self {
27 name: name.into(),
28 actions,
29 }
30 }
31
32 pub fn exec(&self, vm: &Mink) {
33 let actions = self.actions.clone();
34 let mut temp: Vec<(String, Value)> = Vec::new();
35
36 for action in actions {
37 match action {
38 Token::Assign(n, v) => {
39 let mut find_var: Option<usize> = None;
40 for var in 0..temp.len() {
41 if temp[var].0.clone() == n.clone() {
42 find_var = Some(var);
43 continue;
44 }
45 }
46
47 if let Some(var) = find_var {
48 temp[var].1 = exec_expr(v, &temp);
49 } else {
50 temp.push((n, exec_expr(v, &temp)));
51 }
52 },
53 Token::FuncCall(n, a) => {
54 let mut args: Vec<Value> = Vec::new();
55 for arg in a { args.push(exec_expr(arg, &temp)); }
56 if let Some(func) = vm.get_func(n) {
57 func.exec(vm, args);
58 }
59 },
60 _ => {},
61 }
62 }
63 }
64}