roan_engine/interpreter/
access.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
use crate::{context::Context, module::Module, value::Value, vm::VM};
use anyhow::Result;
use roan_ast::{AccessExpr, AccessKind, Expr, GetSpan};
use roan_error::error::RoanError::{
    PropertyNotFoundError, StaticContext, StaticMemberAccess, UndefinedFunctionError,
};

impl Module {
    /// Interpret an access expression.
    ///
    /// # Arguments
    /// * `access` - [AccessExpr] expression to interpret.
    /// * `ctx` - The context in which to interpret the access expression.
    /// * `vm` - The virtual machine to use.
    ///
    /// # Returns
    /// The result of the access expression.
    pub fn interpret_access(
        &mut self,
        access: AccessExpr,
        ctx: &mut Context,
        vm: &mut VM,
    ) -> Result<Value> {
        match access.access.clone() {
            AccessKind::Field(field_expr) => {
                let base = access.base.clone();

                self.interpret_expr(&base, ctx, vm)?;
                let base = vm.pop().unwrap();

                Ok(self.access_field(base, &field_expr, ctx, vm)?)
            }
            AccessKind::Index(index_expr) => {
                self.interpret_expr(&index_expr, ctx, vm)?;
                let index = vm.pop().unwrap();

                self.interpret_expr(&access.base, ctx, vm)?;
                let base = vm.pop().unwrap();

                Ok(base.access_index(index))
            }
            AccessKind::StaticMethod(expr) => {
                let base = access.base.as_ref().clone();

                let (struct_name, span) = match base {
                    Expr::Variable(v) => (v.ident.clone(), v.token.span.clone()),
                    _ => return Err(StaticMemberAccess(access.span()).into()),
                };

                let struct_def = self.get_struct(&struct_name, span)?;

                let expr = expr.as_ref().clone();
                match expr {
                    Expr::Call(call) => {
                        let method_name = call.callee.clone();
                        let method = struct_def.find_static_method(&method_name);

                        if method.is_none() {
                            return Err(UndefinedFunctionError(
                                method_name,
                                call.token.span.clone(),
                            )
                            .into());
                        }

                        let method = method.unwrap();

                        let args = call
                            .args
                            .iter()
                            .map(|arg| {
                                self.interpret_expr(arg, ctx, vm)?;
                                Ok(vm.pop().unwrap())
                            })
                            .collect::<Result<Vec<_>>>()?;

                        let mut def_module = ctx.query_module(&struct_def.defining_module).unwrap();

                        self.execute_user_defined_function(
                            method.clone(),
                            &mut def_module,
                            args,
                            ctx,
                            vm,
                            &call,
                        )?;

                        Ok(vm.pop().unwrap())
                    }
                    _ => return Err(StaticContext(expr.span()).into()),
                }
            }
        }
    }

    /// Access a field of a value.
    ///
    /// # Arguments
    /// * `value` - The [Value] to access the field of.
    /// * `expr` - The [Expr] representing the field to access.
    /// * `ctx` - The context in which to access the field.
    ///
    /// # Returns
    /// The value of the field.
    pub fn access_field(
        &mut self,
        value: Value,
        expr: &Expr,
        ctx: &mut Context,
        vm: &mut VM,
    ) -> Result<Value> {
        match expr {
            Expr::Call(call) => {
                let value_clone = value.clone();
                if let Value::Struct(struct_def, _) = value_clone {
                    let field = struct_def.find_method(&call.callee);

                    if field.is_none() {
                        return Err(PropertyNotFoundError(call.callee.clone(), expr.span()).into());
                    }

                    let field = field.unwrap();
                    let mut args = vec![value.clone()];
                    for arg in call.args.iter() {
                        self.interpret_expr(arg, ctx, vm)?;
                        args.push(vm.pop().expect("Expected value on stack"));
                    }

                    let mut def_module = ctx.query_module(&struct_def.defining_module).unwrap();

                    self.execute_user_defined_function(
                        field.clone(),
                        &mut def_module,
                        args,
                        ctx,
                        vm,
                        call,
                    )?;

                    return Ok(vm.pop().expect("Expected value on stack"));
                }

                let methods = value.builtin_methods();
                if let Some(method) = methods.get(&call.callee) {
                    let mut args = vec![value.clone()];
                    for arg in call.args.iter() {
                        self.interpret_expr(arg, ctx, vm)?;
                        args.push(vm.pop().expect("Expected value on stack"));
                    }

                    self.execute_native_function(method.clone(), args, vm)?;

                    Ok(vm.pop().expect("Expected value on stack"))
                } else {
                    Err(PropertyNotFoundError(call.callee.clone(), expr.span()).into())
                }
            }
            Expr::Variable(lit) => {
                let name = lit.ident.clone();
                match value {
                    Value::Struct(_, fields) => {
                        let field = fields.get(&name).ok_or_else(|| {
                            PropertyNotFoundError(name.clone(), lit.token.span.clone())
                        })?;

                        Ok(field.clone())
                    }
                    Value::Object(fields) => {
                        let field = fields.get(&name).ok_or_else(|| {
                            PropertyNotFoundError(name.clone(), lit.token.span.clone())
                        })?;

                        Ok(field.clone())
                    }
                    _ => Err(PropertyNotFoundError(name.clone(), lit.token.span.clone()).into()),
                }
            }
            _ => {
                self.interpret_expr(expr, ctx, vm)?;

                let field = vm.pop().expect("Expected value on stack");

                Ok(field)
            }
        }
    }
}