kari 0.1.0

An embeddable programming language, writting in and for Rust
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use std::{
    collections::HashMap,
    fmt,
};

use crate::data::{
    stack::Stack,
    types::{
        Type,
        Typed,
    },
};


#[derive(Debug)]
pub struct Functions<T> {
    scopes:        HashMap<Scope, HashMap<String, Node<T>>>,
    root:          Scope,
    parents:       HashMap<Scope, Scope>,
    names:         HashMap<Scope, String>,
    next_scope_id: u64,
}

impl<T> Functions<T>
    where T: Clone
{
    pub fn new() -> Self {
        let root = Scope {
            id: 0,
        };

        let mut scopes = HashMap::new();
        scopes.insert(root, HashMap::new());

        let mut names = HashMap::new();
        names.insert(root, "<root>".into());

        Self {
            scopes,
            root,
            parents:       HashMap::new(),
            names,
            next_scope_id: 1,
        }
    }

    pub fn define<S>(&mut self,
        scope: Scope,
        name:  S,
        args:  &[&'static dyn Type],
        f:     T,
    )
        -> Result<&mut Self, DefineError>
        where S: Into<String>
    {
        let name = name.into();

        let functions = self.scopes.get_mut(&scope)
            .expect("Scope not found");

        if args.len() == 0 {
            if let Some(node) = functions.get(&name) {
                let mut conflicting = Vec::new();
                node.all_paths(Vec::new(), &mut conflicting);

                return Err(
                    DefineError {
                        name,
                        conflicting,
                        scope_id: scope.id,
                    }
                );
            }

            functions.insert(
                name,
                Node::Function(f),
            );
            return Ok(self);
        }

        let node = functions
            .entry(name.clone())
            .or_insert(Node::Type(HashMap::new()));

        node.insert(args, f)
            .map_err(|conflicting|
                DefineError {
                    name,
                    conflicting,
                    scope_id: scope.id,
                }
            )?;

        Ok(self)
    }

    pub fn get(&self, scope: Scope, name: &str, stack: &Stack)
        -> Result<T, GetError>
    {
        let mut scope = scope;

        loop {
            match self.get_inner(scope, name, stack) {
                Ok(function) => return Ok(function),

                Err(error) => {
                    match self.parents.get(&scope) {
                        Some(parent) => scope = *parent,
                        None         => return Err(error),
                    }
                }
            }
        }
    }

    fn get_inner(&self, scope: Scope, name: &str, stack: &Stack)
        -> Result<T, GetError>
    {
        let functions = self.scopes.get(&scope)
            .expect("Scope not found");

        let mut node = functions.get(name)
            .ok_or_else(||
                GetError {
                    candidates: self.candidates_for(&functions, name),
                    scope:      self.scope_name(scope),
                }
            )?;

        for expr in stack.peek() {
            let map = match node {
                Node::Type(map)   => map,
                Node::Function(f) => return Ok(f.clone()),
            };

            node = map.get(expr.get_type())
                .ok_or_else(||
                    GetError {
                        candidates: self.candidates_for(functions, name),
                        scope:      self.scope_name(scope),
                    }
                )?;
        }

        match node {
            Node::Type(_) => {
                Err(
                    GetError {
                        candidates: self.candidates_for(functions, name),
                        scope:      self.scope_name(scope),
                    }
                )
            }
            Node::Function(f) => {
                Ok(f.clone())
            }
        }
    }

    fn candidates_for(&self, functions: &HashMap<String, Node<T>>, name: &str)
        -> Signatures
    {
        let mut candidates = Vec::new();

        if let Some(node) = functions.get(name) {
            node.all_paths(Vec::new(), &mut candidates);
        }

        candidates
    }

    pub fn root_scope(&self) -> Scope {
        self.root
    }

    pub fn new_scope(&mut self, parent: Scope, name: impl Into<String>)
        -> Scope
    {
        assert!(self.next_scope_id < u64::max_value());

        let id = self.next_scope_id;
        self.next_scope_id += 1;

        let scope = Scope {
            id
        };
        self.scopes.insert(scope, HashMap::new());
        self.parents.insert(scope, parent);
        self.names.insert(scope, name.into());

        scope
    }

    fn scope_name(&self, scope: Scope) -> String {
        let mut scope = scope;

        let mut name = self.names.get(&scope)
            // Shouldn't panic. If the scope exists, the name must exist.
            .unwrap()
            .clone();

        while let Some(parent) = self.parents.get(&scope) {
            let parent_name = &self.names.get(&parent)
                // Shouldn't panic. If the scope exists, the name must exist.
                .unwrap();

            name.insert_str(0, " -> ");
            name.insert_str(0, parent_name);

            scope = *parent;
        }

        name
    }
}


#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Scope {
    id: u64,
}


#[derive(Debug)]
enum Node<T> {
    Type(HashMap<&'static dyn Type, Node<T>>),
    Function(T),
}

impl<T> Node<T> {
    fn insert(&mut self, args: &[&'static dyn Type], f: T)
        -> Result<(), Signatures>
    {
        let map = match self {
            Node::Type(map) => {
                map
            }
            Node::Function(_) => {
                return Err(
                    // We know there is one conflicting function, because we
                    // just loaded it from the map. We need to add an empty
                    // `Vec` for it to `conflicting`. Its type will be
                    // backfilled when the recursive `insert` calls return.
                    vec![Vec::new()],
                )
            }
        };

        let (&t, args) = match args.split_last() {
            Some(result) => result,

            None => {
                // We've run out of arguments to look at while unpacking the
                // already existing nodes on the path to our functions. This
                // means that a less specific function is already defined.

                let mut conflicting = Vec::new();
                self.all_paths(Vec::new(), &mut conflicting);

                return Err(conflicting);
            }
        };

        if let Some(node) = map.get_mut(t) {
            return node.insert(args, f)
                .map_err(|mut conflicting| {
                    for signature in &mut conflicting {
                        signature.insert(0, t);
                    }
                    conflicting
                });
        }

        let mut node = Node::Function(f);

        for &t in args {
            let mut map = HashMap::new();
            map.insert(
                t,
                node,
            );
            node = Node::Type(map);
        }

        map.insert(
            t,
            node,
        );

        Ok(())
    }

    fn all_paths(&self,
        current_path: Vec<&'static dyn Type>,
        paths:        &mut Signatures,
    ) {
        match self {
            Node::Type(map) => {
                for (ty, node) in map.iter() {
                    let mut path = current_path.clone();
                    path.insert(0, *ty);
                    node.all_paths(path, paths);
                }
            }
            Node::Function(_) => {
                paths.push(current_path);
            }
        }
    }
}


#[derive(Debug, Eq, PartialEq)]
pub struct DefineError {
    pub name:        String,
    pub conflicting: Signatures,
    pub scope_id:    u64,
}

impl fmt::Display for DefineError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Conflicting function found defining `{}` in scope {}:\n",
            self.name, self.scope_id,
        )?;

        for conflicting in &self.conflicting {
            write!(f, "{:?}\n", conflicting)?;
        }

        Ok(())
    }
}


#[derive(Debug, Eq, PartialEq)]
pub struct GetError {
    pub candidates: Signatures,
    pub scope:      String,
}


pub type Signatures = Vec<Vec<&'static dyn Type>>;


#[cfg(test)]
mod tests {
    use crate::data::{
        stack::Stack,
        token::Span,
        types::{
            self as t,
            Type,
        },
        value::{
            self,
            Value as _,
        },
    };

    use super::{
        DefineError,
        Functions,
    };


    type Result = std::result::Result<(), DefineError>;


    #[test]
    fn it_should_return_none_if_function_wasnt_defined() {
        let functions = Functions::<()>::new();
        let scope     = functions.root_scope();
        let stack     = Stack::new();

        let result = functions.get(scope, "a", &stack);

        assert!(result.is_err());
    }

    #[test]
    fn it_should_return_functions_that_were_defined() -> Result {
        let mut functions = Functions::new();
        let     scope     = functions.root_scope();
        let mut stack     = Stack::new();

        functions
            .define(scope, "a", &[&t::Number, &t::Float], 1)?;
        stack
            .push(value::Number::new(0, Span::default()))
            .push(value::Float::new(0.0, Span::default()));

        let result = functions.get(scope, "a", &stack);

        assert_eq!(result, Ok(1));
        Ok(())
    }

    #[test]
    fn it_should_return_the_function_that_matches_the_types_on_the_stack()
        -> Result
    {
        let mut functions = Functions::new();
        let     scope     = functions.root_scope();
        let mut stack     = Stack::new();

        functions
            .define(scope, "a", &[&t::Number, &t::Float ], 1)?
            .define(scope, "a", &[&t::Number, &t::Number], 2)?;
        stack
            .push(value::Number::new(0, Span::default()))
            .push(value::Float::new(0.0, Span::default()));

        let result = functions.get(scope, "a", &stack);

        assert_eq!(result, Ok(1));
        Ok(())
    }

    #[test]
    fn it_should_return_function_without_args_regardless_of_stack() -> Result {
        let mut functions = Functions::new();
        let     scope     = functions.root_scope();
        let mut stack     = Stack::new();

        functions
            .define(scope, "a", &[], 1)?;
        stack
            .push(value::Number::new(0, Span::default()))
            .push(value::Float::new(0.0, Span::default()));

        let result = functions.get(scope, "a", &stack);

        assert_eq!(result, Ok(1));
        Ok(())
    }

    #[test]
    fn it_should_return_list_of_candidates_if_function_doesnt_match_stack()
        -> Result
    {
        let mut functions = Functions::new();
        let     scope     = functions.root_scope();
        let mut stack     = Stack::new();

        functions
            .define(scope, "a", &[&t::Number, &t::Float], 1)?
            .define(scope, "a", &[&t::Float, &t::Float],  2)?;
        stack
            .push(value::Number::new(0, Span::default()))
            .push(value::Number::new(0, Span::default()));

        let error = match functions.get(scope, "a", &stack) {
            Ok(_)      => panic!("Expected error"),
            Err(error) => error,
        };

        assert!(
            error.candidates.contains(&vec![&t::Number as &dyn Type, &t::Float])
        );
        assert!(
            error.candidates.contains(&vec![&t::Float, &t::Float])
        );

        Ok(())
    }

    #[test]
    fn it_should_reject_functions_that_are_already_defined() -> Result {
        let mut functions = Functions::new();
        let     scope     = functions.root_scope();

        let result = functions
            .define(scope, "a", &[&t::Number, &t::Number], 1)?
            .define(scope, "a", &[&t::Number, &t::Number], 2);

        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn it_should_reject_functions_more_specific_than_a_defined_function()
        -> Result
    {
        let mut functions = Functions::new();
        let     scope     = functions.root_scope();

        let err = functions
            .define(scope, "a", &[&t::Number, &t::Number], 1)?
            .define(scope, "a", &[&t::Number], 2)
            .unwrap_err();

        assert_eq!(err.name, String::from("a"));
        assert_eq!(err.conflicting.len(), 1);
        assert!(err.conflicting.contains(&vec![&t::Number, &t::Number]));

        Ok(())
    }

    #[test]
    fn it_should_reject_no_arg_functions_if_name_is_already_taken() -> Result {
        // This is a special case of the previous test case. Functions with no
        // arguments are specially handled in the code, so we also need a
        // special test for them.

        let mut functions = Functions::new();
        let     scope     = functions.root_scope();

        let err = functions
            .define(scope, "a", &[&t::Number], 1)?
            .define(scope, "a", &[], 2)
            .unwrap_err();

        assert_eq!(err.name, String::from("a"));
        assert_eq!(err.conflicting.len(), 1);
        assert!(err.conflicting.contains(&vec![&t::Number]));

        Ok(())
    }

    #[test]
    fn it_should_reject_functions_less_specific_than_a_defined_function()
        -> Result
    {
        let mut functions = Functions::new();
        let     scope     = functions.root_scope();

        let err = functions
            .define(scope, "a", &[&t::Number], 1)?
            .define(scope, "a", &[&t::Number, &t::Number], 2)
            .unwrap_err();

        assert_eq!(err.name, String::from("a"));
        assert_eq!(err.conflicting.len(), 1);
        assert!(err.conflicting.contains(&vec![&t::Number]));

        Ok(())
    }

    #[test]
    fn it_should_find_function_defined_in_parent_scope()
        -> Result
    {
        let mut functions = Functions::new();
        let     stack     = Stack::new();

        let parent_scope = functions.root_scope();
        let child_scope  = functions.new_scope(parent_scope, "child");

        functions
            .define(parent_scope, "a", &[], 1)?;

        let result = functions.get(child_scope, "a", &stack);

        assert_eq!(result, Ok(1));
        Ok(())
    }

    #[test]
    fn it_should_not_find_function_defined_in_child_scope()
        -> Result
    {
        let mut functions = Functions::new();
        let     stack     = Stack::new();

        let parent_scope = functions.root_scope();
        let child_scope  = functions.new_scope(parent_scope, "child");

        functions
            .define(child_scope, "a", &[], 1)?;

        let result = functions.get(parent_scope, "a", &stack);

        assert!(result.is_err());
        Ok(())
    }
}