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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::rc::Rc;
use std::slice::Iter;

use uuid::Uuid;

use crate::ast::ModulePath as AstModulePath;
use crate::ast::*;
use crate::feature::PresentFeatures;

use super::control_flow::CFG;
use super::error::AnalysisError;
use super::metadata::Metadata;
use super::type_cons::*;

pub const UNIT_TYPE: &'static str = "Unit";
pub const INT_TYPE: &'static str = "int";
pub const FLOAT_TYPE: &'static str = "float";
pub const STRING_TYPE: &'static str = "String";
pub const BOOL_TYPE: &'static str = "bool";

pub struct Program {
    universe: Universe,
    metadata: Metadata,
    features: PresentFeatures,
}

impl Program {
    pub(super) fn new(universe: Universe, metadata: Metadata, features: PresentFeatures) -> Program {
        Program {
            universe: universe,
            metadata: metadata,
            features: features,
        }
    }

    pub(super) fn analysis_context<'a>(
        &'a mut self,
    ) -> (&'a mut Universe, &'a mut Metadata, &'a mut PresentFeatures) {
        (&mut self.universe, &mut self.metadata, &mut self.features)
    }

    pub(super) fn universe(&self) -> &Universe {
        &self.universe
    }

    pub fn all_fns(&self) -> impl Iterator<Item=(FnId, &Function)> {
        self.universe.all_fns()
    }

    pub fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    pub fn features(&self) -> &PresentFeatures {
        &self.features
    }

    pub(super) fn universe_mut(&mut self) -> &mut Universe {
        &mut self.universe
    }

    pub(super) fn metadata_mut(&mut self) -> &mut Metadata {
        &mut self.metadata
    }

    pub(super) fn features_mut(&mut self) -> &mut PresentFeatures {
        &mut self.features
    }
}

#[derive(Clone, Debug)]
pub struct Universe {
    generated_type_cons_map: RefCell<HashMap<TypeId, TypeCons>>,
    type_cons_map: HashMap<TypeId, TypeCons>,
    fn_map: HashMap<FnId, Function>,
    builtin_fn_map: HashMap<FnId, BuiltinFunction>,
    module_map: HashMap<ModuleId, Module>,
    module_name: HashMap<Ident, ModuleId>,
    id_counter: Cell<u64>,
    std_scope: ScopedData,
    unit: TypeId,
    int: TypeId,
    float: TypeId,
    string: TypeId,
    boolean: TypeId,
}

impl Universe {
    pub fn std() -> Universe {
        let unit = (TypeId(0), internal_module_path!(UNIT_TYPE), TypeCons::Unit);
        let int = (TypeId(1), internal_module_path!(INT_TYPE), TypeCons::Int);
        let float = (
            TypeId(2),
            internal_module_path!(FLOAT_TYPE),
            TypeCons::Float,
        );
        let string = (
            TypeId(3),
            internal_module_path!(STRING_TYPE),
            TypeCons::String,
        );
        let boolean = (TypeId(4), internal_module_path!(BOOL_TYPE), TypeCons::Bool);

        let type_map = vec![
            unit.clone(),
            int.clone(),
            float.clone(),
            string.clone(),
            boolean.clone(),
        ];

        Universe {
            generated_type_cons_map: RefCell::new(HashMap::new()),
            type_cons_map: type_map
                .clone()
                .into_iter()
                .map(|(id, _, tc)| (id, tc))
                .collect(),
            fn_map: HashMap::new(),
            builtin_fn_map: HashMap::new(),
            module_map: HashMap::new(),
            module_name: HashMap::new(),
            id_counter: Cell::new(5),
            std_scope: ScopedData {
                type_cons_map: type_map
                    .clone()
                    .into_iter()
                    .map(|(id, path, _)| (path, id))
                    .collect(),
                var_map: HashMap::new(),
                var_type_map: HashMap::new(),
                fn_map: HashMap::new(),
                type_param_map: HashMap::new(),
            },
            unit: unit.0,
            int: int.0,
            float: float.0,
            string: string.0,
            boolean: boolean.0,
        }
    }

    pub fn std_scope(&self) -> ScopedData {
        self.std_scope.clone()
    }

    pub fn unit(&self) -> TypeId {
        self.unit
    }

    pub fn int(&self) -> TypeId {
        self.int
    }

    pub fn float(&self) -> TypeId {
        self.float
    }

    pub fn string(&self) -> TypeId {
        self.string
    }

    pub fn boolean(&self) -> TypeId {
        self.boolean
    }

    pub fn map_module(&mut self, mod_id: ModuleId, name: Ident, module: Module) {
        if self.module_name.insert(name, mod_id).is_some() {
            unimplemented!("Overriding module with the same name.");
        }

        self.module_map.insert(mod_id, module);
    }

    pub fn get_module(&self, id: ModuleId) -> &Module {
        self.module_map.get(&id).unwrap()
    }

    pub fn module_id(&self, name: &Ident) -> Option<ModuleId> {
        self.module_name.get(name).map(|id| id.clone())
    }

    /// Only used when function analysis returns a recoverable error.
    /// Unmap to not have a partial function.
    pub fn unmap_fn(&mut self, fn_id: FnId) {
        self.fn_map.remove(&fn_id);
    }

    pub fn insert_fn(&mut self, fn_id: FnId, type_id: TypeId, fn_scope: ScopedData, cfg: CFG) {
        let function = Function {
            fn_type: type_id,
            cfg: Rc::new(cfg),
            fn_scope: fn_scope,
        };

        if self.fn_map.insert(fn_id, function).is_some() {
            panic!(
                "Attempting to override Function with FnId {} in the Universe",
                fn_id.0
            );
        }
    }

    pub fn insert_builtin_fn(&mut self, fn_id: FnId, fn_type: TypeId) {
        let builtin = BuiltinFunction { fn_type: fn_type };

        if self.builtin_fn_map.insert(fn_id, builtin).is_some() {
            panic!(
                "Attempting to override builtin function with FnId {} in the Universe",
                fn_id.0
            );
        }
    }

    pub fn manual_insert_type_cons(&mut self, type_id: TypeId, cons: TypeCons) {
        if self.type_cons_map.insert(type_id, cons).is_some() {
            panic!("Duplicate type constructor for type id");
        }
    }

    pub fn insert_type_cons(&mut self, cons: TypeCons) -> TypeId {
        let type_id = self.new_type_id();
        self.manual_insert_type_cons(type_id, cons);
        type_id
    }

    pub fn insert_generated_type_cons(&self, cons: TypeCons) -> TypeId {
        let type_id = self.new_type_id();
        let mut borrow = self.generated_type_cons_map.borrow_mut();

        if borrow.insert(type_id, cons).is_some() {
            panic!("Duplicate type constructor for type id");
        }

        type_id
    }

    pub fn get_type_cons(&self, id: TypeId) -> Option<TypeCons> {
        self.type_cons_map.get(&id).map(|cons| cons.clone()).or({
            let borrow = self.generated_type_cons_map.borrow();
            borrow.get(&id).map(|cons| cons.clone())
        })
    }

    pub fn get_fn(&self, id: FnId) -> &Function {
        self.fn_map.get(&id).unwrap()
    }

    pub fn get_builtin_fn(&self, id: FnId) -> &BuiltinFunction {
        self.builtin_fn_map.get(&id).unwrap()
    }

    fn inc_counter(&self) -> u64 {
        let curr = self.id_counter.get();
        let next = curr + 1;
        self.id_counter.set(next);

        curr
    }

    pub fn new_type_id(&self) -> TypeId {
        TypeId(self.inc_counter())
    }

    pub fn new_type_param_id(&self) -> TypeParamId {
        TypeParamId(self.inc_counter())
    }

    pub fn new_field_id(&self) -> FieldId {
        FieldId(self.inc_counter())
    }

    pub fn new_var_id(&self) -> VarId {
        VarId(self.inc_counter())
    }

    pub fn new_fn_id(&self) -> FnId {
        FnId(self.inc_counter())
    }

    pub fn new_tmp_id(&self) -> TmpId {
        TmpId(self.inc_counter())
    }

    pub fn new_loop_id(&self) -> LoopId {
        LoopId(self.inc_counter())
    }

    pub fn new_branching_id(&self) -> BranchingId {
        BranchingId(self.inc_counter())
    }

    pub fn static_types(&self) -> Vec<(TypeId, TypeCons)> {
        self.type_cons_map
            .iter()
            .map(|(id, cons)| (id.clone(), cons.clone()))
            .collect()
    }

    pub fn all_fns(&self) -> impl Iterator<Item=(FnId, &Function)> {
        self.fn_map
            .iter()
            .map(|(id, f)| (id.clone(), f))
    }

    pub fn all_modules(&self) -> Vec<(&Ident, &ModuleId)> {
        self.module_name.iter().collect()
    }
}

#[derive(Clone, Debug)]
pub struct Module {
    id: ModuleId,
    module_scope: ScopedData,
    owned_types: Vec<TypeId>,
    owned_fns: Vec<FnId>,
    dependencies: Vec<ModuleId>,
}

impl Module {
    pub fn new(
        module_scope: ScopedData,
        owned_t: Vec<TypeId>,
        owned_fns: Vec<FnId>,
        dependencies: Vec<ModuleId>,
        id: ModuleId,
    ) -> Module {
        Module {
            id: id,
            module_scope: module_scope,
            owned_types: owned_t,
            owned_fns: owned_fns,
            dependencies: dependencies,
        }
    }

    pub fn module_id(&self) -> ModuleId {
        self.id
    }

    pub fn module_scope(&self) -> &ScopedData {
        &self.module_scope
    }

    pub fn owned_types(&self) -> &[TypeId] {
        &self.owned_types
    }

    pub fn owned_fns(&self) -> &[FnId] {
        &self.owned_fns
    }

    pub fn dependencies(&self) -> &[ModuleId] {
        &self.dependencies
    }
}

#[derive(Clone, Debug)]
pub struct ScopedData {
    type_cons_map: HashMap<ModulePath, TypeId>,
    var_map: HashMap<Ident, VarId>,
    var_type_map: HashMap<VarId, Type>,
    fn_map: HashMap<ModulePath, FnId>,
    type_param_map: HashMap<Ident, (TypeParamId, Option<AbstractType>)>,
}

impl ScopedData {
    pub fn insert_fn(&mut self, name: ModulePath, fn_id: FnId) {
        // TODO: Fn name override behaviour?
        self.fn_map.insert(name, fn_id);
    }

    pub fn unmap_fn(&mut self, name: &ModulePath) {
        self.fn_map.remove(&name).unwrap();
    }

    pub fn type_cons<'a, 'b, 'c>(
        &'a self,
        _universe: &'b Universe,
        path: &'c ModulePath,
    ) -> Option<TypeId> {
        self.type_cons_map.get(path).map(|id| id.clone())
    }

    pub fn insert_type_cons(&mut self, path: ModulePath, id: TypeId) -> Option<TypeId> {
        self.type_cons_map.insert(path, id)
    }

    pub fn binding_info(&self, name: &AstNode<Ident>) -> Result<BindingInfo, AnalysisError> {
        match self.var_map.get(name.data()) {
            Some(v_id) => Ok(BindingInfo::Var(
                v_id.clone(),
                self.var_type_map.get(v_id).unwrap().clone(),
            )),
            None => {
                let p = ModulePath(vec![name.data().clone()]);
                self.fn_map
                    .get(&p)
                    .map(|f| BindingInfo::Fn(f.clone()))
                    .ok_or(AnalysisError::UnknownBinding(name.data().clone(), name.span()))
            }
        }
    }

    pub fn var_info(&self, name: &AstNode<Ident>) -> Result<(VarId, Type), AnalysisError> {
        let var_id = self
            .var_map
            .get(name.data())
            .ok_or(AnalysisError::UnknownBinding(name.data().clone(), name.span()))?
            .clone();
        let type_id = self.var_type_map.get(&var_id).unwrap().clone();

        Ok((var_id, type_id))
    }

    pub fn insert_var(&mut self, name: Ident, id: VarId, var_type: Type) {
        self.var_map.insert(name, id);

        if self.var_type_map.insert(id, var_type).is_some() {
            panic!("Attempting to override variable {} with a different type. Shadowing should produce a new variable id.", id);
        }
    }

    pub fn get_fn(&self, path: &AstModulePath) -> Result<FnId, AnalysisError> {
        self.fn_map
            .get(&path.clone().into())
            .map(|id| id.clone())
            .ok_or(AnalysisError::UnknownFn(path.clone()))
    }

    pub fn insert_type_param(&mut self, 
                             ident: Ident, 
                             id: TypeParamId, 
                             constraint: Option<AbstractType>) -> bool {
        self.type_param_map.insert(ident, (id, constraint)).is_some()
    }

    pub fn type_param<'a, 'b>(&'a self, ident: &'b Ident) 
        -> Option<(TypeParamId, Option<&'a AbstractType>)> {
        self.type_param_map
            .get(ident)
            .map(|(id, constraint)| (id.clone(), constraint.as_ref()))
    }

    pub fn type_params<'a>(&'a self) 
        -> impl Iterator<Item = (TypeParamId, Option<&'a AbstractType>)> + 'a {
        self.type_param_map
            .values()
            .map(|(id, constraint)| (id.clone(), constraint.as_ref()))
    }

    pub fn all_types(&self) -> impl Iterator<Item=(&ModulePath, TypeId)> {
        self.type_cons_map
            .iter()
            .map(|(path, id)| (path, id.clone()))
    }

    pub fn all_fns(&self) -> impl Iterator<Item=(&ModulePath, FnId)> {
        self.fn_map
            .iter()
            .map(|(path, id)| (path, id.clone()))
    }
}

pub enum BindingInfo {
    Var(VarId, Type),
    Fn(FnId),
}

#[derive(Clone, Debug)]
pub struct BuiltinFunction {
    fn_type: TypeId,
}

impl BuiltinFunction {
    pub fn fn_type(&self) -> TypeId {
        self.fn_type
    }
}

#[derive(Clone, Debug)]
pub struct Function {
    fn_type: TypeId,
    cfg: Rc<CFG>,
    fn_scope: ScopedData,
}

impl Function {
    pub fn fn_type(&self) -> TypeId {
        self.fn_type
    }

    pub fn cfg(&self) -> Rc<CFG> {
        self.cfg.clone()
    }

    pub(super) fn fn_scope(&self) -> &ScopedData {
        &self.fn_scope
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum BindingId {
    Var(VarId),
    Fn(FnId),
}

impl From<VarId> for BindingId {
    fn from(id: VarId) -> BindingId {
        BindingId::Var(id)
    }
}

impl From<FnId> for BindingId {
    fn from(id: FnId) -> BindingId {
        BindingId::Fn(id)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TypeId(u64);

impl ::std::fmt::Display for TypeId {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "TypeId[{}]", self.0)
    }
}

impl TypeId {
    pub fn raw(&self) -> u64 {
        self.0
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TypeParamId(u64);

impl ::std::fmt::Display for TypeParamId {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "TypeParamId[{}]", self.0)
    }
}

impl TypeParamId {
    pub fn raw(&self) -> u64 {
        self.0
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FieldId(u64);

impl ::std::fmt::Display for FieldId {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "FieldId[{}]", self.0)
    }
}

impl FieldId {
    pub fn raw(&self) -> u64 {
        self.0
    }
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DataId {
    VarId(VarId),
    TmpId(TmpId),
}

impl ::std::fmt::Display for DataId {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        match *self {
            DataId::VarId(ref id) => id.fmt(f),
            DataId::TmpId(ref id) => id.fmt(f),
        }
    }
}

impl From<VarId> for DataId {
    fn from(id: VarId) -> DataId {
        DataId::VarId(id)
    }
}

impl From<TmpId> for DataId {
    fn from(id: TmpId) -> DataId {
        DataId::TmpId(id)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VarId(u64);

impl ::std::fmt::Display for VarId {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "VarId[{}]", self.0)
    }
}

impl VarId {
    pub fn raw(&self) -> u64 {
        self.0
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FnId(u64);

impl ::std::fmt::Display for FnId {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "FnId[{}]", self.0)
    }
}

impl FnId {
    pub fn raw(&self) -> u64 {
        self.0
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TmpId(u64);

impl ::std::fmt::Display for TmpId {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "TmpId[{}]", self.0)
    }
}

impl TmpId {
    pub fn raw(&self) -> u64 {
        self.0
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LoopId(u64);

impl ::std::fmt::Display for LoopId {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "LoopId[{}]", self.0)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BranchingId(u64);

impl ::std::fmt::Display for BranchingId {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "BranchingId[{}]", self.0)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ModuleId(Uuid);

impl ::std::fmt::Display for ModuleId {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "ModuleId[{}]", self.0)
    }
}

impl ModuleId {
    pub fn new() -> ModuleId {
        ModuleId(Uuid::new_v4())
    }

    pub fn raw(&self) -> Uuid {
        self.0
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ModulePath(pub Vec<Ident>);

impl ModulePath {
    pub fn new(v: Vec<Ident>) -> ModulePath {
        ModulePath(v)
    }

    pub fn iter(&self) -> Iter<Ident> {
        self.0.iter()
    }
}

impl fmt::Display for ModulePath {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let buffer = self.0.iter().fold(String::new(), |mut buffer, ref item| {
            buffer.push_str(&item.0);
            buffer
        });
        write!(f, "{}", buffer)
    }
}

impl From<AstModulePath> for ModulePath {
    fn from(p: AstModulePath) -> ModulePath {
        ModulePath::new(p.0.into_iter().map(|node| node.data().clone()).collect())
    }
}

impl From<Ident> for ModulePath {
    fn from(i: Ident) -> ModulePath {
        let mut v = Vec::with_capacity(1);
        v.push(i);
        ModulePath(v)
    }
}