avid 0.6.1

A plug-and-play scripting language
Documentation
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
use std::{fmt, mem};

// If you are using rust-analyzer, this `unresolved-import`
// error is because `ObjectType` is generated via a macro.
// There is no error on the final build.
use crate::{
    ast::{self, Ast},
    boo::Boo,
    func::{AvidFunc, Callable},
    parser::{Operation, OpType},
    promises::Promises,
    typing::{Object, ObjectType},
    Error, ErrorKind,
};

// This puts it into scope for the documentation
#[allow(unused_imports)]
use crate::builder::Builder;

/// The actual state of the interpreter.
///
/// # NOTE
/// While the Avid struct is memory safe and multiple can be used at the same time,
/// as of right now, you cannot send it directly between threads. Instead, compile
/// the source code into an [Ast] and send that between threads, then build an Avid
/// instance with [Avid::from_ast()] and run it there.
///
/// # Examples
/// ```
/// use avid::Builder;
///
/// let src = "\"Hello, World!\" print";
/// let avid = Builder::new(src).build().unwrap();
///
/// // Prints `Hello, World!`
/// avid.run(None).unwrap();
/// ```
#[allow(unused)]
pub struct Avid<'a, 'b> {
    pub(crate) stack: Stack,
    pub(crate) ops: Vec<Boo<'b, Operation>>,
    // An index into the operations array
    pub(crate) current_op: usize,
    pub(crate) provided: Vec<Option<Boo<'b, Callable<'b, 'a>>>>,
}

impl fmt::Debug for Avid<'_, '_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Avid")
            .field("stack", &self.stack)
            .field("ops", &self.ops)
            .field("current_op", &self.current_op)
            .field(
                "provided",
                &self
                    .provided
                    .iter()
                    .map(|_| "<AvidFunc>")
                    .collect::<Vec<_>>(),
            )
            .finish()
    }
}

impl PartialEq for Avid<'_, '_> {
    fn eq(&self, other: &Self) -> bool {
        self.stack == other.stack
            && self.ops == other.ops
            && self.current_op == other.current_op
            && self.provided.len() == other.provided.len()
    }
}

impl<'a, 'b> Avid<'a, 'b> {
    /// Runs the Avid program, consuming it in the process.
    ///
    /// If `promised` is `Some`, it must contain an implementation (the value) for each
    /// promised item (the key). If it doesn't, this will return an error. On a
    /// success, this returns the value of the stack at the end of the program.
    ///
    /// # Examples
    /// ```
    /// use avid::Builder;
    ///
    /// let src = "5 -3 4 +";
    /// let avid = Builder::new(src).build().unwrap();
    ///
    /// let mut final_stack = avid.run(None).unwrap();
    ///
    /// let [should_be_five, should_be_one] = final_stack.pop().unwrap();
    ///
    /// assert_eq!(should_be_five.unwrap_num(), 5);
    /// assert_eq!(should_be_one.unwrap_num(), 1);
    /// ```
    pub fn run(mut self, mut promised: Option<&mut Promises>) -> crate::Result<Stack> {
        while !self.is_finished() {
            self.advance(&mut promised)?;
        }
        Ok(self.stack)
    }

    /// A faster way to create an [Avid] instance from some source code.
    ///
    /// This is equivalent to the following (but shorter for ease of use):
    /// ```
    /// # use avid::Builder;
    /// # let src = "";
    /// Builder::new(src).build();
    /// ```
    ///
    /// If you want to customise the configuration of the Avid instance-to-be, build it
    /// with a [Builder] and use the configuration methods on that.
    pub fn new(src: &str) -> crate::Result<Avid> {
        Builder::new(src).build()
    }

    /// Initialises an [Avid] instance from an [Ast].
    ///
    /// For more information on the differences between an [Ast] and an Avid instance,
    /// see [the documentation for Ast](Ast).
    ///
    /// # Examples
    /// ```
    /// use avid::*;
    ///
    /// let src = "1 2 + print";
    /// let ast = Ast::new(src).unwrap();
    ///
    /// let avid = Avid::from_ast(ast);
    ///
    /// // Prints "3"
    /// avid.run(None).unwrap();
    /// ```
    pub fn from_ast(ast: Ast<'a>) -> Self {
        let provided = ast
            .provided
            .into_iter()
            .map(|x| x.map(|y| <ast::SendCallable<'_> as Into<Callable<'_, '_>>>::into(y).into()))
            .collect();
        Self {
            stack: Stack::new(),
            ops: ast.ops.into_iter().map(|x| x.into()).collect(),
            current_op: 0,
            provided,
        }
    }

    /// Initialises an [Avid] instance from an [Ast] without consuming it.
    ///
    /// This function is different from [Avid::from_ast()] because it does not consume
    /// the [Ast], so that can be reused afterwards. However, **Avid instances created
    /// with this function will probably be slower because of cache locality**.
    ///
    /// For more information on the differences between an [Ast] and an Avid instance,
    /// see [the documentation for Ast](Ast).
    ///
    /// # Examples
    /// ```
    /// use avid::*;
    ///
    /// let src = "1 2 + print";
    /// let mut ast = Ast::new(src).unwrap();
    ///
    /// let avid = Avid::from_ast_mut(&mut ast);
    ///
    /// // Prints "3"
    /// avid.run(None).unwrap();
    ///
    /// // The ast can still be used!
    /// drop(ast);
    /// ```
    pub fn from_ast_mut(ast: &'b mut Ast<'a>) -> Self {
        let ops = ast.ops.iter_mut().map(|x| x.into()).collect();
        let provided = ast
            .provided
            .iter_mut()
            .map(|x| x.as_mut().map(|y| Callable::Borrowed(y).into()))
            .collect();
        Self {
            stack: Stack::new(),
            current_op: 0,
            ops,
            provided,
        }
    }

    /// The same as [Avid::run], but it does not consume the instance in the process.
    ///
    /// Note: if the struct contains any closures that borrow outside variables,
    /// those variables won't be able to be used until the instance goes out of
    /// scope.
    ///
    /// # Examples
    /// ```
    /// use avid::{Builder, Stack};
    ///
    /// let mut x = 0;
    /// let src = "inc-x";
    ///
    /// let mut avid = Builder::new(src)
    ///     .register_fn("inc-x", |_: &mut Stack| {
    ///         x += 1;
    ///         Ok(())
    ///     })
    ///     .build().unwrap();
    ///
    /// avid.run_mut(None).unwrap();
    ///
    /// // Can be run a second time, as it was not consumed.
    /// avid.run_mut(None).unwrap();
    ///
    /// // This would not work because `x` is still borrowed
    /// // assert_eq!(x, 1);
    ///
    /// drop(avid);
    ///
    /// // Now that `avid` is no longer in scope, this will work.
    /// assert_eq!(x, 1);
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn run_mut(&mut self, mut promised: Option<&mut Promises>) -> crate::Result<Stack> {
        while !self.is_finished() {
            self.advance(&mut promised)?;
        }
        let mut s = Stack::new();
        mem::swap(&mut s, &mut self.stack);
        Ok(s)
    }

    fn is_finished(&self) -> bool {
        self.ops.len() <= self.current_op
    }

    fn advance(&mut self, promised: &mut Option<&mut Promises>) -> crate::Result<()> {
        // Whether to go to the next one or not
        let current_op = &*self.ops[self.current_op];
        let increment: bool = match &current_op.typ {
            // The whilemarker does nothing and is just there to make parsing easier
            OpType::WhileMarker => true,
            OpType::DoMarker => panic!("Avid should never be given a do marker!"),
            OpType::Bool(b) => {
                self.stack.push(Object::Bool(*b));
                true
            }
            OpType::If(offset) => {
                let [cond] = self.stack.pop().map_err(|k| Error::new(k, current_op.loc.clone()))?;

                if !cond.truthy() {
                    // Skip `if` block
                    self.current_op += offset;
                }
                true
            }
            OpType::End(offset) => {
                if let Some(offset) = offset {
                    self.current_op -= offset;
                    false
                } else {
                    true
                }
            }
            OpType::Int(i) => {
                self.stack.push(Object::Num(*i));
                true
            }
            OpType::String(s) => {
                self.stack.push(Object::String(s.clone()));
                true
            }
            OpType::Provided(p) => {
                self.provided
                    .get_mut(*p)
                    .expect("Avid.provided should always have valid functions!")
                    .as_mut()
                    .expect("Avid.provided should always have valid functions!")
                    .call(&mut self.stack).map_err(|k| Error::new(k, current_op.loc.clone()))?;
                true
            }
            OpType::Promise(p) => {
                if let Some(promises) = promised {
                    if let Some(action) = promises.fns.get_mut(p) {
                        action.call(&mut self.stack).map_err(|k| Error::new(k, current_op.loc.clone()))?;
                        true
                    } else {
                        return Err(Error::new(ErrorKind::UnfulfilledPromise {
                            expected: p.clone(),
                        }, current_op.loc.clone()));
                    }
                } else {
                    return Err(Error::new(ErrorKind::UnfulfilledPromise {
                        expected: p.clone(),
                    }, current_op.loc.clone()));
                }
            }
        };

        if increment {
            self.current_op += 1;
        }

        Ok(())
    }
}

/// Stack that holds data while an Avid program is running.
///
/// When writing a function that will be called in an Avid program,
/// this is the way to get data to and from the program.
///
/// # Examples
/// ```
/// use std::mem::swap;
/// use avid::{Builder, Stack, Object};
///
/// let src = "1 2 3 print-stack print";
///
/// let avid = Builder::new(src)
///     .register_fn("print-stack", |s: &mut Stack| {
///         let mut new_stack = Stack::new();
///         swap(s, &mut new_stack);
///
///         println!("Stack = `{:?}`", new_stack.into_objects());
///
///         s.push(Object::String("MSG: Stack has been printed!".to_string()));
///
///         Ok(())
///     }).build().unwrap();
///
/// // Prints "[1, 2, 3]"
/// //        "MSG: Stack has been printed!"
/// avid.run(None).unwrap();
/// ```
#[derive(Debug, PartialEq, Default)]
pub struct Stack {
    dat: Vec<Object>,
}

impl Stack {
    /// Creates a new, empty stack.
    ///
    /// # Examples
    /// ```
    /// use avid::Stack;
    ///
    /// let mut stack = Stack::new();
    ///
    /// assert!(stack.pop::<1>().is_err());
    ///
    /// assert!(stack.into_objects().is_empty());
    /// ```
    pub fn new() -> Self {
        Stack { dat: Vec::new() }
    }

    /// Converts a [Stack] into its internal list of objects, discarding any
    /// other data.
    ///
    /// # Examples
    /// ```
    /// use avid::{Object, Stack};
    ///
    /// let mut stack = Stack::new();
    ///
    /// stack.push(Object::Num(1));
    /// stack.push(Object::Num(2));
    /// stack.push(Object::Num(3));
    ///
    /// assert_eq!(stack.into_objects(), vec![Object::Num(1), Object::Num(2), Object::Num(3)]);
    /// ```
    pub fn into_objects(self) -> Vec<Object> {
        self.dat
    }

    // TODO(#13): Fix the awkward wording in the documentation of Stack::push
    /// Pushes an Object onto the stack.
    ///
    /// This is the main way that functions in Avid interact with data, and thus you'll often want
    /// to use this function when you want your custom functions to send data to the Avid
    /// interpreter.
    ///
    /// # Examples
    /// ```
    /// use std::time::SystemTime;
    ///
    /// use avid::{Builder, Stack, Object};
    ///
    /// let src = "\"There have been \" print get-unix-mins print \" minutes since the start of unix time!\" print";
    ///
    /// let avid = Builder::new(src)
    ///     .register_fn("get-unix-mins", |s: &mut Stack| {
    ///         let current_time = SystemTime::now();
    ///         let elapsed_unix_time = current_time.duration_since(SystemTime::UNIX_EPOCH).unwrap();
    ///         let elapsed_mins = elapsed_unix_time.as_secs() / 60;
    ///
    ///         s.push(Object::Num(elapsed_mins as isize));
    ///         Ok(())
    ///     }).build().unwrap();
    ///
    /// avid.run(None).unwrap();
    /// ```
    pub fn push(&mut self, t: Object) {
        self.dat.push(t)
    }

    /// Pops any number of elements from the top of the stack and returns them.
    ///
    /// This method should be used when the to-be-registered function can take any type,
    /// for example the `print` function. If the to-be-registered function must take
    /// specific types, use [pop_typed](Stack::pop_typed).
    ///
    /// If there are fewer than `NUM` objects on the stack, no objects are popped and an
    /// error is returned.
    ///
    /// # Examples
    /// ```
    /// use avid::{Stack, Object};
    ///
    /// let mut stack = Stack::new();
    ///
    /// stack.push(Object::Num(1));
    /// stack.push(Object::Num(2));
    /// stack.push(Object::Num(3));
    ///
    /// // You can pop and get a list by specifying NUM in
    /// // a turbofish
    /// let top_elem_list = stack.pop::<1>().unwrap();
    ///
    /// assert_eq!(top_elem_list, [Object::Num(3)]);
    ///
    /// // You do not need to specify NUM if you are unpacking
    /// // it though!
    /// let [one, two] = stack.pop().unwrap();
    ///
    /// assert_eq!(one, Object::Num(1));
    /// assert_eq!(two, Object::Num(2));
    /// ```
    ///
    /// Note that the stack is assumed to be layed out left-to-right. This means that if this
    /// is the stack:
    ///
    /// `1 2 3 4 5`
    ///
    /// Then `pop::<2>()` will return `[4, 5]`, as those are the last two in the stack, but with
    /// the stack's order preserved.
    ///
    /// TL;DR: When using this function, the top-most elements on the stack will be the last
    /// ones in the returned list.
    pub fn pop<const NUM: usize>(&mut self) -> crate::Result<[Object; NUM], ErrorKind> {
        let len = self.dat.len();

        if len < NUM {
            Err(ErrorKind::NotEnoughArgs {
                expected: NUM,
                got: len,
            }) // c.f. line 286
        } else {
            let res: [Object; NUM] = self
                .dat
                .drain((len - NUM)..len)
                .collect::<Vec<_>>()
                .try_into()
                .expect("Should always have drained the right number of elements from stack!");

            Ok(res)
        }
    }

    /// Checks for types at the top of the stack, then pops the requisite items if they match.
    ///
    /// This function returns an error in two different circumstances: when there are fewer than
    /// `NUM` elements on the stack, and when the types of the elements on the top of the stack
    /// do not match the expected types given.
    ///
    /// If the calling function does not need to check for types, use [pop](Stack::pop).
    ///
    /// # Examples
    /// ```
    /// use avid::{Stack, Object, ObjectType};
    ///
    /// let mut stack = Stack::new();
    ///
    /// stack.push(Object::Num(1));
    ///
    /// let res = stack.pop_typed(&[ObjectType::Num, ObjectType::Num]);
    ///
    /// // Error: Not Enough Arguments
    /// assert!(res.is_err());
    ///
    /// stack.push(Object::String("A".to_string()));
    ///
    /// let res = stack.pop_typed(&[ObjectType::Num, ObjectType::Num]);
    ///
    /// // Error: Incorrect Types
    /// assert!(res.is_err());
    ///
    /// // Get rid of the `"A"`
    /// stack.pop::<1>().unwrap();
    ///
    /// stack.push(Object::Num(2));
    ///
    /// let res = stack.pop_typed(&[ObjectType::Num, ObjectType::Num]);
    ///
    /// assert!(res.is_ok());
    /// ```
    pub fn pop_typed<const NUM: usize>(
        &mut self,
        expected_types: &'static [ObjectType; NUM],
    ) -> crate::Result<[Object; NUM], ErrorKind> {
        if self.dat.len() < NUM {
            return Err(ErrorKind::NotEnoughArgs {
                expected: NUM,
                got: self.dat.len(),
            });
        }

        let typs = self
            .dat
            .iter()
            .skip(self.dat.len() - NUM)
            .map(Object::get_type)
            .collect::<Vec<_>>();

        for (expected_typ, actual_typ) in expected_types.iter().zip(typs.iter()) {
            if expected_typ != actual_typ {
                return Err(ErrorKind::IncorrectType {
                    expected: expected_types,
                    got: typs,
                });
            }
        }

        self.pop::<NUM>()
    }
}