stof/data/lang/
expr.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//
// Copyright 2024 Formata, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use anyhow::{anyhow, Result};
use nanoid::nanoid;
use serde::{Deserialize, Serialize};
use crate::{IntoDataRef, SDoc, SField, SFunc, SType, SVal};
use super::{Statement, Statements, StatementsRes};


/// Stof expression.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Expr {
    Literal(SVal),
    Tuple(Vec<Expr>),
    Array(Vec<Expr>),

    /// Variable expression.
    /// Use a variable from the symbol table.
    /// Get a field from an ID ('.' separated path)
    /// Get a function from an ID ('.' separated path)
    Variable(String),

    Cast(SType, Box<Expr>),
    TypeOf(Box<Expr>),
    TypeName(Box<Expr>),

    Call {
        scope: String,
        name: String,
        params: Vec<Expr>,
    },

    Block(Statements),
    NewObject(Statements),

    Add(Vec<Expr>),
    Sub(Vec<Expr>),
    Mul(Vec<Expr>),
    Div(Vec<Expr>),
    Rem(Vec<Expr>),

    And(Vec<Expr>),
    Or(Vec<Expr>),
    Not(Box<Expr>),

    Eq(Box<Expr>, Box<Expr>),
    Neq(Box<Expr>, Box<Expr>),
    Gte(Box<Expr>, Box<Expr>),
    Lte(Box<Expr>, Box<Expr>),
    Gt(Box<Expr>, Box<Expr>),
    Lt(Box<Expr>, Box<Expr>),
}
impl<T> From<T> for Expr where T: Into<SVal> {
    fn from(value: T) -> Self {
        Self::Literal(value.into())
    }
}
impl Expr {
    /// Execute this expression.
    pub fn exec(&self, pid: &str, doc: &mut SDoc) -> Result<SVal> {
        match self {
            Expr::Variable(id) => {
                // Look for a symbol first!
                if let Some(symbol) = doc.get_symbol(pid, &id) {
                    let val = symbol.var();
                    return Ok(val);
                }

                // See if we are referencing self or super only
                if id == "self" {
                    if let Some(self_ref) = doc.self_ptr(pid) {
                        if doc.perms.can_read_scope(&doc.graph, &self_ref, Some(&self_ref)) {
                            return Ok(SVal::Object(self_ref));
                        }
                        return Ok(SVal::Null);
                    } else {
                        return Ok(SVal::Null);
                    }
                } else if id == "super" {
                    if let Some(self_ref) = doc.self_ptr(pid) {
                        if let Some(node) = self_ref.node(&doc.graph) {
                            if let Some(parent) = &node.parent {
                                if doc.perms.can_read_scope(&doc.graph, parent, Some(&self_ref)) {
                                    return Ok(SVal::Object(parent.clone()));
                                }
                            }
                        }
                        return Ok(SVal::Null);
                    } else {
                        return Ok(SVal::Null);
                    }
                }

                // Get the context object we are working with!
                let mut context = None;
                if id.starts_with("self") || id.starts_with("super") {
                    context = doc.self_ptr(pid);
                }
                let mut context_path = id.clone();
                {
                    let mut path: Vec<&str> = id.split('.').collect();
                    if path.len() > 1 {
                        if let Some(symbol) = doc.get_symbol(pid, path.remove(0)) {
                            match symbol.var() {
                                SVal::Object(nref) => {
                                    context = Some(nref.clone());
                                    context_path = path.join(".");
                                },
                                _ => {}
                            }
                        }
                    }
                }

                // Look for a field first
                if let Some(field) = SField::field(&doc.graph, &context_path, '.', context.as_ref()) {
                    if doc.perms.can_read_field(&doc.graph, &field, doc.self_ptr(pid).as_ref()) {
                        return Ok(field.value);
                    }
                    return Ok(SVal::Null);
                }
                
                // Look for an object in the graph next
                let obj_path = context_path.replace('.', "/");
                if let Some(node) = doc.graph.node_ref(&obj_path, context.as_ref()) {
                    if doc.perms.can_read_scope(&doc.graph, &node, doc.self_ptr(pid).as_ref()) {
                        return Ok(SVal::Object(node));
                    }
                    return Ok(SVal::Null);
                }

                // Look for a function in the graph
                if let Some(func) = SFunc::func(&doc.graph, &context_path, '.', context.as_ref()) {
                    if doc.perms.can_read_func(&doc.graph, &func, doc.self_ptr(pid).as_ref()) {
                        return Ok(SVal::FnPtr(func.data_ref()));
                    }
                    return Ok(SVal::Null);
                }

                // Not able to find a variable for this symbol, so return null
                Ok(SVal::Null)
            },
            Expr::Literal(val) => {
                Ok(val.clone())
            },
            Expr::Tuple(vals) => {
                let mut vec: Vec<SVal> = Vec::new();
                for val in vals {
                    vec.push(val.exec(pid, doc)?);
                }
                Ok(SVal::Tuple(vec))
            },
            Expr::Array(vals) => {
                let mut vec: Vec<SVal> = Vec::new();
                for val in vals {
                    vec.push(val.exec(pid, doc)?);
                }
                Ok(SVal::Array(vec))
            },
            Expr::Block(statements) => {
                doc.new_scope(pid);
                let res = statements.exec(pid, doc)?;
                doc.end_scope(pid);

                match res {
                    StatementsRes::Break |
                    StatementsRes::Continue |
                    StatementsRes::None => {
                        // Nothing to do here
                    },
                    StatementsRes::Return(v) => {
                        if v {
                            // block returned something to the stack!
                            return Ok(doc.pop(pid).unwrap());
                        }
                    }
                }
                // Block did not return anything!
                Ok(SVal::Void)
            },
            Expr::NewObject(statements) => {
                let stof_object;
                if let Some(parent) = doc.self_ptr(pid) {
                    stof_object = doc.graph.insert_node(&format!("obj{}", nanoid!(7)), Some(&parent));
                } else {
                    stof_object = doc.graph.insert_node(&format!("obj{}", nanoid!(7)), None);
                }

                // Parse initialization statements and execute them
                let mut init_statements = Vec::new();
                for statement in &statements.statements {
                    match statement {
                        Statement::Assign(name, expr) => {
                            let init_statement = Statement::Assign(format!("self.{}", &name).into(), expr.clone());
                            init_statements.push(init_statement);
                        },
                        Statement::Declare(name, expr) => {
                            let init_statement = Statement::Declare(format!("self.{}", &name).into(), expr.clone());
                            init_statements.push(init_statement);
                        }
                        _ => {}
                    }
                }

                // Execute initialization statements!
                // Make sure to set new object as self_ptr for new sub-objects!
                doc.push_self(pid, stof_object.clone());
                let init_statements = Statements::from(init_statements);
                let _ = init_statements.exec(pid, doc);
                doc.pop_self(pid);

                return Ok(SVal::Object(stof_object));
            },
            Expr::Cast(stype, expr) => {
                let value = expr.exec(pid, doc)?;
                let target = stype.clone();

                if value.stype(&doc.graph) == target {
                    return Ok(value);
                }
                return Ok(value.cast(target, pid, doc)?);
            },
            Expr::TypeOf(expr) => {
                let value = expr.exec(pid, doc)?;
                let value_type = value.stype(&doc.graph);
                if value_type.is_object() { // No custom object types here
                    return Ok(SVal::String("obj".to_string()));
                }
                let type_of = value_type.type_of();
                Ok(SVal::String(type_of))
            },
            Expr::TypeName(expr) => {
                let value = expr.exec(pid, doc)?;
                Ok(SVal::String(value.type_name(&doc.graph)))
            },
            Expr::Not(expr) => {
                let value = expr.exec(pid, doc)?;
                Ok(SVal::Bool(!value.truthy()))
            },
            Expr::Call { scope, name, params } => {
                // Scope can be a symbol, library name, or path to a field, object, or function
                let variable = Self::Variable(scope.replace('/', "."));
                let variable_value = variable.exec(pid, doc)?;

                let mut library_name = String::default();
                if !variable_value.is_empty() {
                    let stype = variable_value.stype(&doc.graph);
                    library_name = match stype {
                        SType::Null |
                        SType::Void => String::default(),
                        SType::Array => "Array".to_owned(),
                        SType::FnPtr => "Function".to_owned(),
                        SType::String => "String".to_owned(),
                        SType::Number(_) => "Number".to_owned(),
                        SType::Bool => "Bool".to_owned(),
                        SType::Tuple(_) => "Tuple".to_owned(),
                        SType::Blob => "Blob".to_owned(),
                        SType::Object(_typename) => {
                            "Object".to_owned()
                        },
                    };
                }
                if let Some(lib) = doc.library(&library_name) {
                    let stype = variable_value.stype(&doc.graph);

                    // If the type is an object, try getting the function from that objects scope
                    match &variable_value {
                        SVal::Object(nref) => {
                            // Look for a function on the object itself first! Always higher priority than a prototype
                            if let Some(func) = SFunc::func(&doc.graph, name, '.', Some(&nref)) {
                                let mut func_params = Vec::new();
                                for expr in params {
                                    let val = expr.exec(pid, doc)?;
                                    if !val.is_void() {
                                        func_params.push(val);
                                    }
                                }
                                let current_symbol_table = doc.new_table(pid);
                                let res = func.call(pid, doc, func_params, true)?;
                                doc.set_table(pid, current_symbol_table);
                                return Ok(res);
                            }

                            // Look for a prototype on this object next
                            if let Some(prototype_field) = SField::field(&doc.graph, "__prototype__", '.', Some(nref)) {
                                if let Some(prototype) = doc.graph.node_ref(&prototype_field.to_string(), None) {
                                    // prototype is the exact type we are referencing... we need to check typestack here!
                                    let mut current = Some(prototype);

                                    let mut func_name = name.clone();
                                    let mut type_scope_resolution: Vec<&str> = name.split("::").collect();
                                    if type_scope_resolution.len() == 2 {
                                        func_name = type_scope_resolution.pop().unwrap().to_string();

                                        let scope_type = type_scope_resolution.pop().unwrap();
                                        let mut found = false;
                                        while let Some(typename_field) = SField::field(&doc.graph, "typename", '.', current.as_ref()) {
                                            if typename_field.to_string() == scope_type {
                                                found = true;
                                                break;
                                            }
                                            if let Some(node) = current.clone().unwrap().node(&doc.graph) {
                                                if let Some(parent_ref) = &node.parent {
                                                    current = Some(parent_ref.clone());
                                                } else {
                                                    break;
                                                }
                                            } else {
                                                break;
                                            }
                                        }
                                        if !found {
                                            return Err(anyhow!("Cannot find the requested type scope in the extends stack of this object for the requested function call"));
                                        }
                                    } else if type_scope_resolution.len() > 1 {
                                        return Err(anyhow!("Cannot specify more than one type scope for a function call"));
                                    }

                                    while current.is_some() {
                                        if let Some(func) = SFunc::func(&doc.graph, &func_name, '.', current.as_ref()) {
                                            let mut func_params = Vec::new();
                                            for expr in params {
                                                let val = expr.exec(pid, doc)?;
                                                if !val.is_void() {
                                                    func_params.push(val);
                                                }
                                            }
                                            let current_symbol_table = doc.new_table(pid);
                                            // Set self to the object still...
                                            doc.push_self(pid, nref.clone());
                                            let res = func.call(pid, doc, func_params, false)?;
                                            doc.pop_self(pid);
                                            doc.set_table(pid, current_symbol_table);
                                            return Ok(res);
                                        }
                                        if let Some(node) = current.unwrap().node(&doc.graph) {
                                            if let Some(parent_ref) = &node.parent {
                                                current = Some(parent_ref.clone());
                                            } else {
                                                break;
                                            }
                                        } else {
                                            break;
                                        }
                                    }
                                }
                            }
                        },
                        _ => {}
                    }

                    let mut func_params = vec![variable_value.clone()];
                    for expr in params {
                        let val = expr.exec(pid, doc)?;
                        if !val.is_void() {
                            func_params.push(val);
                        }
                    }

                    // For the standard libraries, allow them to access the current symbol table...
                    // This includes Function.call, allowing arrow functions to capture outer scope when called
                    //let current_symbol_table = doc.new_table(pid);
                    doc.new_scope(pid);
                    let res = lib.call(pid, doc, name, &mut func_params)?;
                    doc.end_scope(pid);
                    //doc.set_table(pid, current_symbol_table);

                    // Update the symbol with the mutated parameter if it's the right type
                    let new_symbol_val = func_params.first().unwrap().clone();
                    if new_symbol_val.stype(&doc.graph) == stype {
                        doc.set_variable(pid, &scope, new_symbol_val);
                    }

                    return Ok(res);
                }

                // If here, scope is not a field, func, object, or symbol
                // Check to see if scope is a library itself before falling back to std lib
                if let Some(lib) = doc.library(&scope) {
                    let mut func_params = Vec::new();
                    for expr in params {
                        let val = expr.exec(pid, doc)?;
                        if !val.is_void() {
                            func_params.push(val);
                        }
                    }
                    let current_symbol_table = doc.new_table(pid);
                    let res = lib.call(pid, doc, name, &mut func_params)?;
                    doc.set_table(pid, current_symbol_table);
                    return Ok(res);
                } else if let Some(lib) = doc.library("std") {
                    let mut func_params = Vec::new();
                    for expr in params {
                        let val = expr.exec(pid, doc)?;
                        if !val.is_void() {
                            func_params.push(val);
                        }
                    }
                    let current_symbol_table = doc.new_table(pid);
                    let res = lib.call(pid, doc, name, &mut func_params)?;
                    
                    doc.set_table(pid, current_symbol_table);
                    return Ok(res);
                }
                Err(anyhow!("Function/Call does not exist: {}({:?})", name, params))
            },
            Expr::And(exprs) => {
                for expr in exprs {
                    let val = expr.exec(pid, doc)?;
                    if !val.truthy() {
                        return Ok(SVal::Bool(false));
                    }
                }
                Ok(SVal::Bool(true))
            },
            Expr::Or(exprs) => {
                for expr in exprs {
                    let val = expr.exec(pid, doc)?;
                    if val.truthy() {
                        return Ok(SVal::Bool(true));
                    }
                }
                Ok(SVal::Bool(false))
            },
            Expr::Add(exprs) => {
                let mut res = SVal::Void;
                let mut first = true;
                for expr in exprs {
                    let val = expr.exec(pid, doc)?;
                    if first {
                        res = val;
                        first = false;
                    } else {
                        res = res.add(&val, doc)?;
                    }
                }
                Ok(res)
            },
            Expr::Sub(exprs) => {
                let mut res = SVal::Void;
                let mut first = true;
                for expr in exprs {
                    let val = expr.exec(pid, doc)?;
                    if first {
                        res = val;
                        first = false;
                    } else {
                        res = res.sub(&val)?;
                    }
                }
                Ok(res)
            },
            Expr::Mul(exprs) => {
                let mut res = SVal::Void;
                let mut first = true;
                for expr in exprs {
                    let val = expr.exec(pid, doc)?;
                    if first {
                        res = val;
                        first = false;
                    } else {
                        res = res.mul(&val)?;
                    }
                }
                Ok(res)
            },
            Expr::Div(exprs) => {
                let mut res = SVal::Void;
                let mut first = true;
                for expr in exprs {
                    let val = expr.exec(pid, doc)?;
                    if first {
                        res = val;
                        first = false;
                    } else {
                        res = res.div(&val)?;
                    }
                }
                Ok(res)
            },
            Expr::Rem(exprs) => {
                let mut res = SVal::Void;
                let mut first = true;
                for expr in exprs {
                    let val = expr.exec(pid, doc)?;
                    if first {
                        res = val;
                        first = false;
                    } else {
                        res = res.rem(&val)?;
                    }
                }
                Ok(res)
            },
            Expr::Eq(lhs, rhs) => {
                let lhs = lhs.exec(pid, doc)?;
                let rhs = rhs.exec(pid, doc)?;
                Ok(lhs.equal(&rhs)?)
            },
            Expr::Neq(lhs, rhs) => {
                let lhs = lhs.exec(pid, doc)?;
                let rhs = rhs.exec(pid, doc)?;
                Ok(lhs.neq(&rhs)?)
            },
            Expr::Gte(lhs, rhs) => {
                let lhs = lhs.exec(pid, doc)?;
                let rhs = rhs.exec(pid, doc)?;
                Ok(lhs.gte(&rhs)?)
            },
            Expr::Lte(lhs, rhs) => {
                let lhs = lhs.exec(pid, doc)?;
                let rhs = rhs.exec(pid, doc)?;
                Ok(lhs.lte(&rhs)?)
            },
            Expr::Gt(lhs, rhs) => {
                let lhs = lhs.exec(pid, doc)?;
                let rhs = rhs.exec(pid, doc)?;
                Ok(lhs.gt(&rhs)?)
            },
            Expr::Lt(lhs, rhs) => {
                let lhs = lhs.exec(pid, doc)?;
                let rhs = rhs.exec(pid, doc)?;
                Ok(lhs.lt(&rhs)?)
            },
        }
    }

    /// Is variable expression?
    pub fn is_variable(&self) -> bool {
        match self {
            Expr::Variable(_) => true,
            _ => false,
        }
    }

    /// Is literal expression?
    pub fn is_literal(&self) -> bool {
        match self {
            Expr::Literal(_) => true,
            _ => false,
        }
    }
}