valhallac

Compiler for set-theoretic programming language.
git clone git://git.knutsen.co/valhallac
Log | Files | Refs | README | LICENSE

ast.rs (21758B)


  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
use std::{fmt, ops};
use std::collections::VecDeque;

use crate::site::{Site, Location};

/// Identifiers, node representing a name that
/// will represent a value stored.
#[derive(Clone)]
pub struct IdentNode {
    /// The name of the identifier.
    pub value : String,

    /// Type it holds.
    pub static_type : StaticTypes,

    /// Source location.
    pub site : Site,
}

/// Different types of possible number types in the language.
/// Max size is determined by max pointer size.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum Numerics {
    /// Naturals are unsigned ints.
    Natural(usize),
    /// Integers are signed.
    Integer(isize),
    /// Reals are represented as a double.
    Real(f64)
}

fn strongest_cast(left : Numerics, right : Numerics) -> StaticTypes {
    let mut cast = StaticTypes::TNatural;
    match left {
        Numerics::Real(_) => cast = StaticTypes::TReal,
        Numerics::Integer(_) => cast = StaticTypes::TInteger,
        _ => ()
    };
    if cast == StaticTypes::TReal { return cast; }
    match right {
        Numerics::Real(_) => cast = StaticTypes::TReal,
        Numerics::Integer(_) => cast = StaticTypes::TInteger,
        _ => ()
    };
    cast
}

macro_rules! new_base {
    ($arg:expr, $base:ident) => {
        match &$arg {
            Numerics::Natural(n) => *n as $base,
            Numerics::Integer(n) => *n as $base,
            Numerics::Real(n)    => *n as $base,
        };
    };
}

macro_rules! fold_on_numeric {
    ($op:tt, $left:expr, $right:expr) => {
        {
            let cast = strongest_cast($left, $right);
            match cast {
                StaticTypes::TNatural => (new_base!($left, usize) $op new_base!($right, usize)).to_numeric(),
                StaticTypes::TInteger => (new_base!($left, isize) $op new_base!($right, isize)).to_numeric(),
                StaticTypes::TReal    => (new_base!($left,   f64) $op new_base!($right,   f64)).to_numeric(),
                _ => panic!("Numeric porting non-numeric type?")
            }
        }
    };
}

impl ops::Add<Numerics> for Numerics {
    type Output = Numerics;
    fn add(self, right : Numerics) -> Numerics {
        fold_on_numeric!(+, self, right)
    }
}

impl ops::Sub<Numerics> for Numerics {
    type Output = Numerics;
    fn sub(self, right : Numerics) -> Numerics {
        if fold_on_numeric!(>, right, self) == Numerics::Natural(1) {
            if let Numerics::Natural(u) = right {
                return fold_on_numeric!(-, self, Numerics::Integer(u as isize));
            }
        }
        fold_on_numeric!(-, self, right)
    }
}

impl ops::Mul<Numerics> for Numerics {
    type Output = Numerics;
    fn mul(self, right : Numerics) -> Numerics {
        fold_on_numeric!(*, self, right)
    }
}

impl ops::Div<Numerics> for Numerics {
    type Output = Numerics;
    fn div(self, right : Numerics) -> Numerics {
        fold_on_numeric!(/, self, right)
    }
}

/// Parse a string of more than two chars with a specified radix, into an ast::Numeric.
fn parse_with_radix(neg : bool, s : &str, radix : u32) -> Numerics {
    let unsigned = usize::from_str_radix(s.get(2..).unwrap(), radix).unwrap();
    if neg {
        return Numerics::Integer(-(unsigned as isize));
    }
    return Numerics::Natural(unsigned);
}

/// Converts primitive types into ast::Numerics.
pub trait ToNumeric { fn to_numeric(&self) -> Numerics; }
impl ToNumeric for &str {
    fn to_numeric(&self) -> Numerics {
        let mut test_str = <&str>::clone(self).to_ascii_lowercase();

        let is_neg = self.starts_with('-');
        if is_neg { test_str = test_str.get(1..).unwrap().to_string(); }

        return match test_str.get(0..2) {
            Some("0x") => parse_with_radix(is_neg, &test_str, 16),
            Some("0o") => parse_with_radix(is_neg, &test_str,  8),
            Some("0b") => parse_with_radix(is_neg, &test_str,  2),
            Some(_) => {
                let exp_notation : Vec<&str> = test_str.split('e').collect();
                let     mantissa : &str = exp_notation.get(0).unwrap();
                let mut exponent : &str = exp_notation.get(1).unwrap_or(&"0");
                if exponent.is_empty() { exponent = "0"; }
                let exponent : i32 = exponent.parse().unwrap();

                if mantissa.contains('.') || exponent < 0 {
                    let mut number = mantissa.parse::<f64>().unwrap() * 10f64.powi(exponent);
                    if is_neg { number *= -1f64; }
                    return Numerics::Real(number);
                }

                let number : usize = mantissa.parse().unwrap();
                if is_neg {
                    return Numerics::Integer(-(number as isize) * 10isize.pow(exponent as u32));
                }
                return Numerics::Natural(number * 10usize.pow(exponent as u32));
            }
            None => {
                if is_neg {
                    return Numerics::Integer(-test_str.parse::<isize>().unwrap());
                }
                Numerics::Natural(test_str.parse::<usize>().unwrap())
            }
        };
    }
}

impl ToNumeric for bool {
    fn to_numeric(&self) -> Numerics { Numerics::Natural(if *self { 1 } else { 0 }) }
}

impl ToNumeric for usize {
    fn to_numeric(&self) -> Numerics { Numerics::Natural(*self) }
}
impl ToNumeric for u32 {
    fn to_numeric(&self) -> Numerics { Numerics::Natural(*self as usize) }
}
impl ToNumeric for isize {
    fn to_numeric(&self) -> Numerics {
        if *self > 0 { return Numerics::Natural(*self as usize); }
        Numerics::Integer(*self)
    }
}
impl ToNumeric for i32 {
    fn to_numeric(&self) -> Numerics {
        if *self > 0 { return Numerics::Natural(*self as usize); }
        Numerics::Integer(*self as isize)
    }
}
impl ToNumeric for f64 {
    fn to_numeric(&self) -> Numerics { Numerics::Real(*self) }
}

impl fmt::Display for Numerics {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let printable = match self {
            Numerics::Natural(n) => n.to_string(),
            Numerics::Integer(n) => n.to_string(),
            Numerics::Real(n)    => n.to_string(),
        };
        write!(f, "{}", printable)
    }
}

/// Node that represents a number.
#[derive(Clone)]
pub struct NumNode {
    /// Holds a the numeric value.
    pub value : Numerics,

    /// Source location.
    pub site : Site,
}


/// Node for holding strings.
#[derive(Clone)]
pub struct StrNode {
    /// Contents of the utf-8 string.
    pub value : String,

    /// Source location.
    pub site : Site,
}

/// Symbol Node.
#[derive(Clone)]
pub struct SymNode {
    /// Value/name stored as a string and
    /// excludes the colon (:) in front.
    pub value : String,

    /// Source location.
    pub site : Site,
}

/// Call Node has a pointer to the callee node
/// and a list of operand nodes.
#[derive(Clone)]
pub struct CallNode {
    /// Pointer to heap allocated calling node.
    pub callee : Box<Nodes>,
    /// Pointer to list of operand nodes.
    pub operands : Vec<Nodes>,

    /// What type it returns.
    pub return_type : StaticTypes,

    /// Source location.
    pub site : Site,
}

/// Represents a block of code / compound statements
/// in order of when they will be executed.
#[derive(Clone)]
pub struct BlockNode {
    /// Pointer to list of nodes in the code block.
    pub statements : Vec<Nodes>,

    /// Source location.
    pub site : Site,
}

#[derive(Clone)]
pub struct FileNode {
    pub filename : String,
    /// Source location.
    pub site : Site,
}

#[derive(Clone)]
pub struct NilNode {
    /// Source location.
    pub site : Site,
}

/// All base types, determined at compile time.
/// The order the types are presented below, is
/// generally how we reference the types in the
/// compiled bytecode numerically (e.g. TReal => 3).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StaticTypes {
    TNatural, TInteger, TReal,
    TString, TSymbol,
    TSet(Box<StaticTypes>),
    /// TFunction(boxed operand type, boxed return type)
    TFunction(Box<StaticTypes>, Box<StaticTypes>),

    TNil,
    TUnknown
}

impl StaticTypes {
    pub fn set_inner(&self) -> Option<StaticTypes> {
        if let StaticTypes::TSet(box_inner) = self {
            return Some(*box_inner.clone());
        }
        None
    }

    pub fn is_number(&self) -> bool {
        match self {
            StaticTypes::TNatural
            | StaticTypes::TInteger
            | StaticTypes::TReal => true,
            _ => false
        }
    }
}

impl fmt::Display for StaticTypes {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let ss;
        let s = match self {
            StaticTypes::TNatural => "natural",
            StaticTypes::TInteger => "integer",
            StaticTypes::TReal    => "real",
            StaticTypes::TString  => "string",
            StaticTypes::TSymbol  => "symbol",
            StaticTypes::TSet(st) => match *st.clone() {
                StaticTypes::TNatural => "Nat",
                StaticTypes::TInteger => "Int",
                StaticTypes::TReal    => "Real",
                StaticTypes::TString  => "String",
                StaticTypes::TSymbol  => "Sym",
                StaticTypes::TFunction(o, r) => {
                    ss = format!("({} \u{1f852} {})", o, r);
                    ss.as_str()
                },
                StaticTypes::TNil     => "Empty",
                StaticTypes::TUnknown => "Any",
                _ => {
                    ss = format!("Set {}", st);
                    ss.as_str()
                },
            },
            StaticTypes::TFunction(o, r) => {
                ss = format!("({} \u{21a6} {})", o, r);
                ss.as_str()
            },
            StaticTypes::TNil     => "nothing",
            StaticTypes::TUnknown => "unknown",
        };
        write!(f, "{}", s)
    }
}

/// All node types.
#[derive(Clone)]
pub enum Nodes {
    Ident(IdentNode),
    Num(NumNode),
    Str(StrNode),
    Sym(SymNode),
    Call(CallNode),
    Block(BlockNode),
    File(FileNode),
    Nil(NilNode),
}


impl fmt::Display for Nodes {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let yt = self.yield_type();
        let printable = match self {
            Nodes::Ident(node)  => format!("%ident{{ :value \"{}\"; :yield {} }}", node.value, yt),
            Nodes::Num(node)    => format!("%num{{ :value {}; :yield {} }}", node.value, yt),
            Nodes::Str(node)    => format!("%str{{ :value \"{}\"; :yield {} }}", node.value, yt),
            Nodes::Sym(node)    => format!("%sym{{ :value \":{}\"; :yield {} }}", node.value, yt),
            Nodes::Call(node)   => format!(
                "%call{{\n  :yield {}\n  :callee ({})\n  :operands [|\n    {}\n  |]\n}}", yt, node.callee,
                node.operands.iter().map(Nodes::to_string).collect::<Vec<String>>().join("\n    ")),
            Nodes::Block(node)  => format!("%block{{ {} }}",
                node.statements
                .iter()
                .map(Nodes::to_string)
                .collect::<Vec<String>>()
                .join("\n")),
            Nodes::File(node)   => format!("%file{{ :filename {} }}", node.filename),
            Nodes::Nil(_)       => String::from("()"),
        };
        write!(f, "{}", printable)
    }
}

macro_rules! unwrap_enum {
    ($e:expr, $m:path) => {
        match $e {
            $m(inner) => Some(&inner),
            _ => None
        }
    };
}


impl Nodes {
    pub fn site(&self) -> Site {
        match self {
            Nodes::Ident(n) => n.site.to_owned(),
            Nodes::Call(n)  => n.site.to_owned(),
            Nodes::Num(n)   => n.site.to_owned(),
            Nodes::Str(n)   => n.site.to_owned(),
            Nodes::Sym(n)   => n.site.to_owned(),
            Nodes::Nil(n)   => n.site.to_owned(),
            Nodes::Block(n) => n.site.to_owned(),
            Nodes::File(n)  => n.site.to_owned(),
        }
    }

    pub fn location(&self) -> Location {
        self.site().location
    }

    /// Function that returns the statically known type
    /// of any syntactic node generated.
    pub fn yield_type(&self) -> StaticTypes {
        match self {
            Nodes::Num(num) => {
                match num.value {
                    Numerics::Natural(_) => StaticTypes::TNatural,
                    Numerics::Integer(_) => StaticTypes::TInteger,
                    Numerics::Real(_)    => StaticTypes::TReal,
                }
            },
            Nodes::Str(_) => StaticTypes::TString,
            Nodes::Sym(_) => StaticTypes::TSymbol,
            Nodes::Ident(ident) => {
                match ident.value.as_str() {
                    "Nat"  => StaticTypes::TSet(Box::new(StaticTypes::TNatural)),
                    "Int"  => StaticTypes::TSet(Box::new(StaticTypes::TInteger)),
                    "Real" => StaticTypes::TSet(Box::new(StaticTypes::TReal)),
                    "Str" | "String" => StaticTypes::TSet(Box::new(StaticTypes::TString)),
                    "Sym" | "Symbol" => StaticTypes::TSet(Box::new(StaticTypes::TSymbol)),
                    "Empty" => StaticTypes::TSet(Box::new(StaticTypes::TNil)),
                    "Any" | "Anything" => StaticTypes::TSet(Box::new(StaticTypes::TUnknown)),
                    _ => ident.static_type.to_owned()
                }
            },
            Nodes::Call(call) => {
                match &*call.callee {
                    Nodes::Ident(ident) => {
                        match ident.value.as_str() {
                            "Set" => return StaticTypes::TSet(Box::new(call.operands[0].yield_type())),
                            _ => ()
                        };
                    },
                    Nodes::Call(sub_call) => {
                        if let Nodes::Ident(ident) = &*sub_call.callee {
                            match ident.value.as_str() {
                                "->" => {
                                    return StaticTypes::TSet(
                                        Box::new(StaticTypes::TFunction(
                                            Box::new(sub_call.operands[0].yield_type()),
                                            Box::new(call.operands[0].yield_type()))));
                                },
                                _ => ()
                            }
                        }
                    }
                    _ => ()
                };
                call.return_type.to_owned()
            },
            Nodes::Block(_)
            | Nodes::File(_) => StaticTypes::TUnknown,
            Nodes::Nil(_)    => StaticTypes::TNil,
        }
    }

    pub fn change_yield(&mut self, new_yield : StaticTypes) {
        match self {
            Nodes::Ident(i) => i.static_type = new_yield,
            Nodes::Call(c)  => c.return_type = new_yield,
            _ => panic!("Cannot change static yield type of node with inherent type.")
        }
    }

    pub fn node_type(&self) -> &str {
        match self {
            Nodes::Ident(_) => "identifier",
            Nodes::Num(_)   => "numeric",
            Nodes::Str(_)   => "string literal",
            Nodes::Sym(_)   => "symbol",
            Nodes::Nil(_)   => "nothing",
            Nodes::Call(_)  => "application",
            Nodes::Block(_) => "code block",
            _ => "ungrammatical meta node"
        }
    }

    pub fn get_name(&self) -> Option<&str> {
        match self {
            Nodes::Str(n)   => Some(n.value.as_str()),
            Nodes::Sym(n)   => Some(n.value.as_str()),
            Nodes::Ident(n) => Some(n.value.as_str()),
            _ => None
        }
    }

    pub fn ident(&self) -> Option<&IdentNode> { unwrap_enum!(self, Nodes::Ident) }
    pub fn   num(&self) -> Option<&NumNode>   { unwrap_enum!(self, Nodes::Num)   }
    pub fn   str(&self) -> Option<&StrNode>   { unwrap_enum!(self, Nodes::Str)   }
    pub fn   sym(&self) -> Option<&SymNode>   { unwrap_enum!(self, Nodes::Sym)   }
    pub fn  call(&self) -> Option<&CallNode>  { unwrap_enum!(self, Nodes::Call)  }
    pub fn block(&self) -> Option<&BlockNode> { unwrap_enum!(self, Nodes::Block) }
    pub fn  file(&self) -> Option<&FileNode>  { unwrap_enum!(self, Nodes::File)  }
    pub fn   nil(&self) -> Option<&NilNode>   { unwrap_enum!(self, Nodes::Nil)   }

    pub fn is_ident(&self) -> bool { self.ident().is_some() }
    pub fn is_num(&self)   -> bool { self.num().is_some()   }
    pub fn is_str(&self)   -> bool { self.str().is_some()   }
    pub fn is_sym(&self)   -> bool { self.sym().is_some()   }
    pub fn is_call(&self)  -> bool { self.call().is_some()  }
    pub fn is_block(&self) -> bool { self.block().is_some() }
    pub fn is_file(&self)  -> bool { self.file().is_some()  }
    pub fn is_nil(&self)   -> bool { self.nil().is_some()   }



    pub fn is_atomic(&self) -> bool {
        match self {
            Nodes::Ident(_)
            | Nodes::Num(_)
            | Nodes::Str(_)
            | Nodes::Sym(_)
            | Nodes::Nil(_)  => true,
            _ => false
        }
    }

    pub fn is_numeric(&self) -> bool {
        match self {
            Nodes::Num(_)=> true,
            _ => false
        }
    }
}

impl IdentNode {
    pub fn new(value : &str, site : Site) -> Nodes {
        Nodes::Ident(IdentNode {
            value: value.to_string(),
            static_type: StaticTypes::TUnknown,
            site
        })
    }
}

impl NumNode {
    pub fn new<Num : ToNumeric>(number : Num, site : Site) -> Nodes {
        let value = number.to_numeric();
        Nodes::Num(NumNode { value, site })
    }
}

impl StrNode {
    pub fn new(value : &str, site : Site) -> Nodes
        { Nodes::Str(StrNode { value: value.to_string(), site }) }
}

impl SymNode {
    pub fn new(value : &str, site : Site) -> Nodes
        { Nodes::Sym(SymNode { value: value[1..].to_string(), site }) }
}

impl CallNode {
    pub fn new(callee : Nodes, operands : Vec<Nodes>, site : Site) -> Nodes {
        Nodes::Call(CallNode {
            callee: Box::new(callee),
            operands,
            return_type: StaticTypes::TUnknown,
            site
        })
    }

    pub fn set_return_type(&mut self, new_type : StaticTypes) {
        self.return_type = new_type;
    }

    /// The base (bottom-most) callee for a call chain.
    pub fn base_call(&self) -> Nodes {
        let mut last_call : &CallNode = self;
        loop {
            if let Nodes::Call(call) = &*last_call.callee {
                last_call = call;
            } else {
                return (*last_call.callee).clone();
            }
        }
    }


    /// List of callee and operands in a list, in a double ended queue.
    pub fn collect_deque(&self) -> VecDeque<Nodes> {
        fn make_argument_vector(call_node : &Nodes,
                                operands : VecDeque<Nodes>) -> VecDeque<Nodes> {
            let mut pushable = operands;

            if let Nodes::Call(call) = call_node {
                pushable.push_front(call.operands[0].clone());
                return make_argument_vector(&*call.callee, pushable);
            }

            pushable.push_front(call_node.clone());
            return pushable;
        }

        make_argument_vector(
            &Nodes::Call(self.clone()),
            VecDeque::new())
    }

    /// Flatten a function call into a list containing the
    /// callee at the head, and arguments at tail (LISP style).
    /// ---
    /// Mainly for easier flattened/non-recursive
    /// iteration over function calls.
    pub fn collect(&self) -> Vec<Nodes> {
        Vec::from(self.collect_deque())
    }

    /// Collects only operands/arguments to a call.
    pub fn collect_operands(&self) -> Vec<Nodes> {
        let mut list = self.collect_deque();
        list.pop_front();
        Vec::from(list)
    }

    pub fn is_unary(&self) -> bool {
        self.callee.ident().is_some() && !self.operands.is_empty()
    }

    pub fn is_binary(&self) -> bool {
        let sub_call = self.callee.call();
        sub_call.is_some() && !self.operands.is_empty() && sub_call.unwrap().is_unary()
    }

    pub fn operand(&self) -> Option<&Nodes> {
        self.operands.last()
    }
}

impl FileNode {
    pub fn new(filename : String, site : Site) -> Nodes
        { Nodes::File(FileNode { filename, site }) }
}

impl NilNode {
    pub fn new(site : Site) -> Nodes { Nodes::Nil(NilNode { site }) }
}

/// Root branch of the AST.
pub struct Root {
    pub branches : Vec<Nodes>,
    pub filename : String
}

impl Root {
    pub fn new(filename : &str) -> Self {
        Root { branches: Vec::new(), filename: filename.to_owned() }
    }
}

const TAB : &str = "  ";

pub fn pretty_print(node : &Nodes, depth : usize) -> String {
    let tab = TAB.repeat(depth);
    match node {
        Nodes::Call(n) => format!(
            "{tab}%call{{\n{tab}{T}:yield {yt}\n{tab}{T}:callee (\n{calling}\n{tab}{T})\n{tab}{T}:operand [|{op}|]\n{tab}}}",
            tab=tab, T=TAB,
            yt=n.return_type,
            calling=pretty_print(&*n.callee, depth + 2),
            op=(if n.operands.is_empty() { String::from(" ") } else { format!(
                "\n{ops}\n{tab}{T}",
                ops=pretty_print(&n.operands[0], depth + 2),
                tab=tab, T=TAB) })
        ),
        // TODO: Pretty Print Blocks.
        Nodes::Block(_) => node.to_string(),
        _ => format!("{}{}", tab, node)
    }
}


impl fmt::Display for Root {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let str_mapped : Vec<String> = self.branches.iter().map(|n| pretty_print(n, 0)).collect();
        write!(f, "[|\n  {}\n|]", str_mapped.join("\n").split('\n').collect::<Vec<&str>>().join("\n  "))
    }
}