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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
use crate::{
  diagnostics::{Diagnostics, DiagnosticsConfig},
  maybe_grow, multi_iterator, ENTRY_POINT,
};
// use hvmc::ast::get_typ;
use indexmap::{IndexMap, IndexSet};
use interner::global::{GlobalPool, GlobalString};
use itertools::Itertools;
use std::{borrow::Cow, collections::HashMap, hash::Hash, ops::Deref};

pub mod builtins;
pub mod check;
pub mod display;
pub mod load_book;
pub mod net_to_term;
pub mod parser;
pub mod term_to_net;
pub mod transform;

pub use net_to_term::{net_to_term, ReadbackError};
pub use term_to_net::{book_to_hvm, term_to_hvm};

pub static STRINGS: GlobalPool<String> = GlobalPool::new();
#[derive(Debug)]
pub struct Ctx<'book> {
  pub book: &'book mut Book,
  pub info: Diagnostics,
}

impl Ctx<'_> {
  pub fn new(book: &mut Book, diagnostics_cfg: DiagnosticsConfig) -> Ctx {
    Ctx { book, info: Diagnostics::new(diagnostics_cfg) }
  }
}

/// The representation of a program.
#[derive(Debug, Clone, Default)]
pub struct Book {
  /// The function definitions.
  pub defs: IndexMap<Name, Definition>,

  /// The algebraic datatypes defined by the program
  pub adts: Adts,

  /// To which type does each constructor belong to.
  pub ctrs: Constructors,

  /// A custom or default "main" entrypoint.
  pub entrypoint: Option<Name>,
}

pub type Adts = IndexMap<Name, Adt>;
pub type Constructors = IndexMap<Name, Name>;

/// A pattern matching function definition.
#[derive(Debug, Clone)]
pub struct Definition {
  pub name: Name,
  pub rules: Vec<Rule>,
  pub builtin: bool,
}

/// A pattern matching rule of a definition.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Rule {
  pub pats: Vec<Pattern>,
  pub body: Term,
}

#[derive(Debug, Default, PartialEq, Eq, Hash)]
pub enum Term {
  Lam {
    tag: Tag,
    pat: Box<Pattern>,
    bod: Box<Term>,
  },
  Var {
    nam: Name,
  },
  Link {
    nam: Name,
  },
  Let {
    pat: Box<Pattern>,
    val: Box<Term>,
    nxt: Box<Term>,
  },
  Do {
    typ: Name,
    bod: Box<Term>,
  },
  Ask {
    pat: Box<Pattern>,
    val: Box<Term>,
    nxt: Box<Term>,
  },
  Use {
    nam: Option<Name>,
    val: Box<Term>,
    nxt: Box<Term>,
  },
  App {
    tag: Tag,
    fun: Box<Term>,
    arg: Box<Term>,
  },
  /// Either a tuple or a superposition
  Fan {
    fan: FanKind,
    tag: Tag,
    els: Vec<Term>,
  },
  Num {
    val: Num,
  },
  Nat {
    val: u32,
  },
  Str {
    val: GlobalString,
  },
  List {
    els: Vec<Term>,
  },
  /// A numeric operation between built-in numbers.
  Oper {
    opr: Op,
    fst: Box<Term>,
    snd: Box<Term>,
  },
  /// Pattern matching on an ADT.
  Mat {
    arg: Box<Term>,
    bnd: Option<Name>,
    with: Vec<Name>,
    arms: Vec<MatchRule>,
  },
  /// Native pattern matching on numbers
  Swt {
    arg: Box<Term>,
    bnd: Option<Name>,
    with: Vec<Name>,
    pred: Option<Name>,
    arms: Vec<Term>,
  },
  Fold {
    bnd: Option<Name>,
    arg: Box<Term>,
    with: Vec<Name>,
    arms: Vec<MatchRule>,
  },
  Bend {
    bind: Vec<Option<Name>>,
    init: Vec<Term>,
    cond: Box<Term>,
    step: Box<Term>,
    base: Box<Term>,
  },
  Open {
    typ: Name,
    var: Name,
    bod: Box<Term>,
  },
  Ref {
    nam: Name,
  },
  Era,
  #[default]
  Err,
}

pub type MatchRule = (Option<Name>, Vec<Option<Name>>, Term);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FanKind {
  Tup,
  Dup,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Op {
  ADD,
  SUB,
  MUL,
  DIV,
  REM,
  EQ,
  NEQ,
  LT,
  GT,
  AND,
  OR,
  XOR,
  SHL,
  SHR,
  /// atan(a, b)
  ATN,
  /// log_a(b)
  LOG,
  // a^b
  POW,
}

#[derive(Debug, Clone, Copy)]
pub enum Num {
  U24(u32),
  I24(i32),
  F24(f32),
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Pattern {
  Var(Option<Name>),
  Chn(Name),
  Ctr(Name, Vec<Pattern>),
  Num(u32),
  /// Either a tuple or a duplication
  Fan(FanKind, Tag, Vec<Pattern>),
  Lst(Vec<Pattern>),
  Str(GlobalString),
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum Tag {
  Named(Name),
  Numeric(u16),
  Auto,
  #[default]
  Static,
}

/// A user defined datatype
#[derive(Debug, Clone, Default)]
pub struct Adt {
  pub ctrs: IndexMap<Name, Vec<CtrField>>,
  pub builtin: bool,
}

#[derive(Debug, Clone, Default)]
pub struct CtrField {
  pub nam: Name,
  pub rec: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Name(GlobalString);

/* Implementations */

impl PartialEq<str> for Name {
  fn eq(&self, other: &str) -> bool {
    &**self == other
  }
}

impl PartialEq<&str> for Name {
  fn eq(&self, other: &&str) -> bool {
    self == *other
  }
}

impl PartialEq<Option<Name>> for Name {
  fn eq(&self, other: &Option<Name>) -> bool {
    if let Some(other) = other.as_ref() {
      self == other
    } else {
      false
    }
  }
}

impl PartialEq<Name> for Option<Name> {
  fn eq(&self, other: &Name) -> bool {
    other.eq(self)
  }
}

impl PartialEq<Option<&Name>> for Name {
  fn eq(&self, other: &Option<&Name>) -> bool {
    if let Some(other) = other {
      &self == other
    } else {
      false
    }
  }
}

impl PartialEq<Name> for Option<&Name> {
  fn eq(&self, other: &Name) -> bool {
    other.eq(self)
  }
}

pub fn num_to_name(mut num: u64) -> String {
  let mut name = String::new();
  loop {
    let c = (num % 26) as u8 + b'a';
    name.push(c as char);
    num /= 26;
    if num == 0 {
      break;
    }
  }
  name
}

impl Tag {
  pub fn adt_name(name: &Name) -> Self {
    Self::Named(name.clone())
  }
}

impl Clone for Term {
  fn clone(&self) -> Self {
    maybe_grow(|| match self {
      Self::Lam { tag, pat, bod } => Self::Lam { tag: tag.clone(), pat: pat.clone(), bod: bod.clone() },
      Self::Var { nam } => Self::Var { nam: nam.clone() },
      Self::Link { nam } => Self::Link { nam: nam.clone() },
      Self::Let { pat, val, nxt } => Self::Let { pat: pat.clone(), val: val.clone(), nxt: nxt.clone() },
      Self::Do { typ, bod } => Self::Do { typ: typ.clone(), bod: bod.clone() },
      Self::Ask { pat, val, nxt } => Self::Ask { pat: pat.clone(), val: val.clone(), nxt: nxt.clone() },
      Self::Use { nam, val, nxt } => Self::Use { nam: nam.clone(), val: val.clone(), nxt: nxt.clone() },
      Self::App { tag, fun, arg } => Self::App { tag: tag.clone(), fun: fun.clone(), arg: arg.clone() },
      Self::Fan { fan, tag, els } => Self::Fan { fan: *fan, tag: tag.clone(), els: els.clone() },
      Self::Num { val } => Self::Num { val: *val },
      Self::Nat { val } => Self::Nat { val: *val },
      Self::Str { val } => Self::Str { val: val.clone() },
      Self::List { els } => Self::List { els: els.clone() },
      Self::Oper { opr, fst, snd } => Self::Oper { opr: *opr, fst: fst.clone(), snd: snd.clone() },
      Self::Mat { arg, bnd, with, arms } => {
        Self::Mat { arg: arg.clone(), bnd: bnd.clone(), with: with.clone(), arms: arms.clone() }
      }
      Self::Swt { arg, bnd, with, pred, arms } => Self::Swt {
        arg: arg.clone(),
        bnd: bnd.clone(),
        with: with.clone(),
        pred: pred.clone(),
        arms: arms.clone(),
      },
      Self::Fold { bnd, arg, with, arms } => {
        Self::Fold { bnd: bnd.clone(), arg: arg.clone(), with: with.clone(), arms: arms.clone() }
      }
      Self::Bend { bind, init, cond, step, base } => Self::Bend {
        bind: bind.clone(),
        init: init.clone(),
        cond: cond.clone(),
        step: step.clone(),
        base: base.clone(),
      },
      Self::Open { typ, var, bod: nxt } => {
        Self::Open { typ: typ.clone(), var: var.clone(), bod: nxt.clone() }
      }
      Self::Ref { nam } => Self::Ref { nam: nam.clone() },
      Self::Era => Self::Era,
      Self::Err => Self::Err,
    })
  }
}

impl Drop for Term {
  fn drop(&mut self) {
    loop {
      // Each iteration moves a child with nested nodes to the last child.
      // When no nested on the left, we can just drop it and they'll be handled
      // by the special cases;
      let mut i = self.children_mut().filter(|x| x.children().next().is_some());

      // No nested children, just drop everything
      let Some(b) = i.next() else { break };

      // Only one child with nested nodes, move it up to be the new root.
      // Non-nested (height=0) children are dropped recursively.
      if { i }.next().is_none() {
        *self = std::mem::take(b);
        continue;
      }

      // Rotate the tree right:
      // ```text
      //     a            b
      //    / \          / \
      //   b   e   ->   c   a
      //  / \              / \
      // c   d            d   e
      // ```
      let tmp = Term::Err;
      let d = std::mem::replace(b.children_mut().next_back().unwrap(), tmp);
      let b = std::mem::replace(b, d);
      let a = std::mem::replace(self, b);
      let tmp = std::mem::replace(self.children_mut().next_back().unwrap(), a);
      std::mem::forget(tmp);
    }
  }
}

impl From<Option<Name>> for Pattern {
  fn from(value: Option<Name>) -> Self {
    Pattern::Var(value)
  }
}

impl Term {
  /* Common construction patterns */

  /// Lambda with a static tag
  pub fn lam(pat: Pattern, bod: Term) -> Self {
    Self::tagged_lam(Tag::Static, pat, bod)
  }

  /// Lambda with any tag
  pub fn tagged_lam(tag: Tag, pat: Pattern, bod: Term) -> Self {
    Term::Lam { tag, pat: Box::new(pat), bod: Box::new(bod) }
  }

  /// Wraps a term in lambdas, so that the outermost lambda is the first given element.
  pub fn rfold_lams(term: Term, pats: impl DoubleEndedIterator<Item = Option<Name>>) -> Self {
    pats.into_iter().rfold(term, |bod, nam| Self::lam(Pattern::Var(nam), bod))
  }

  pub fn var_or_era(nam: Option<Name>) -> Self {
    if let Some(nam) = nam {
      Term::Var { nam }
    } else {
      Term::Era
    }
  }

  pub fn app(fun: Term, arg: Term) -> Self {
    Self::tagged_app(Tag::Static, fun, arg)
  }

  pub fn tagged_app(tag: Tag, fun: Term, arg: Term) -> Self {
    Term::App { tag, fun: Box::new(fun), arg: Box::new(arg) }
  }

  /// Make a call term by folding args around a called function term with applications.
  pub fn call(called: Term, args: impl IntoIterator<Item = Term>) -> Self {
    args.into_iter().fold(called, Term::app)
  }

  pub fn tagged_call(tag: Tag, called: Term, args: impl IntoIterator<Item = Term>) -> Self {
    args.into_iter().fold(called, |acc, arg| Term::tagged_app(tag.clone(), acc, arg))
  }

  /// Apply a variable to a term by the var name.
  pub fn arg_call(fun: Term, arg: Name) -> Self {
    Term::app(fun, Term::Var { nam: arg })
  }

  pub fn r#ref(name: &str) -> Self {
    Term::Ref { nam: Name::new(name) }
  }

  pub fn str(str: &str) -> Self {
    Term::Str { val: STRINGS.get(str) }
  }

  pub fn sub_num(arg: Term, val: Num) -> Term {
    if val.is_zero() {
      arg
    } else {
      Term::Oper { opr: Op::SUB, fst: Box::new(arg), snd: Box::new(Term::Num { val }) }
    }
  }

  pub fn add_num(arg: Term, val: Num) -> Term {
    if val.is_zero() {
      arg
    } else {
      Term::Oper { opr: Op::ADD, fst: Box::new(arg), snd: Box::new(Term::Num { val }) }
    }
  }

  pub fn pattern(&self) -> Option<&Pattern> {
    match self {
      Term::Lam { pat, .. } | Term::Let { pat, .. } => Some(pat),
      _ => None,
    }
  }

  pub fn pattern_mut(&mut self) -> Option<&mut Pattern> {
    match self {
      Term::Lam { pat, .. } | Term::Let { pat, .. } => Some(pat),
      _ => None,
    }
  }

  /* Iterators */
  pub fn children(&self) -> impl DoubleEndedIterator<Item = &Term> + Clone {
    multi_iterator!(ChildrenIter { Zero, One, Two, Vec, Mat, Swt, Bend, Fold });
    match self {
      Term::Mat { arg, bnd: _, with: _, arms } => {
        ChildrenIter::Mat([arg.as_ref()].into_iter().chain(arms.iter().map(|r| &r.2)))
      }
      Term::Swt { arg, bnd: _, with: _, pred: _, arms } => {
        ChildrenIter::Swt([arg.as_ref()].into_iter().chain(arms))
      }
      Term::Bend { bind: _, init, cond, step, base } => {
        ChildrenIter::Bend(init.iter().chain([cond.as_ref(), step.as_ref(), base.as_ref()]))
      }
      Term::Fold { bnd: _, arg, with: _, arms } => {
        ChildrenIter::Fold([arg.as_ref()].into_iter().chain(arms.iter().map(|r| &r.2)))
      }
      Term::Fan { els, .. } | Term::List { els } => ChildrenIter::Vec(els),
      Term::Let { val: fst, nxt: snd, .. }
      | Term::Ask { val: fst, nxt: snd, .. }
      | Term::Use { val: fst, nxt: snd, .. }
      | Term::App { fun: fst, arg: snd, .. }
      | Term::Oper { fst, snd, .. } => ChildrenIter::Two([fst.as_ref(), snd.as_ref()]),
      Term::Lam { bod, .. } | Term::Do { bod, .. } | Term::Open { bod, .. } => {
        ChildrenIter::One([bod.as_ref()])
      }
      Term::Var { .. }
      | Term::Link { .. }
      | Term::Num { .. }
      | Term::Nat { .. }
      | Term::Str { .. }
      | Term::Ref { .. }
      | Term::Era
      | Term::Err => ChildrenIter::Zero([]),
    }
  }

  pub fn children_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Term> {
    multi_iterator!(ChildrenIter { Zero, One, Two, Vec, Mat, Swt, Bend, Fold });
    match self {
      Term::Mat { arg, bnd: _, with: _, arms } => {
        ChildrenIter::Mat([arg.as_mut()].into_iter().chain(arms.iter_mut().map(|r| &mut r.2)))
      }
      Term::Swt { arg, bnd: _, with: _, pred: _, arms } => {
        ChildrenIter::Swt([arg.as_mut()].into_iter().chain(arms))
      }
      Term::Bend { bind: _, init, cond, step, base } => {
        ChildrenIter::Bend(init.iter_mut().chain([cond.as_mut(), step.as_mut(), base.as_mut()]))
      }
      Term::Fold { bnd: _, arg, with: _, arms } => {
        ChildrenIter::Fold([arg.as_mut()].into_iter().chain(arms.iter_mut().map(|r| &mut r.2)))
      }
      Term::Fan { els, .. } | Term::List { els } => ChildrenIter::Vec(els),
      Term::Let { val: fst, nxt: snd, .. }
      | Term::Ask { val: fst, nxt: snd, .. }
      | Term::Use { val: fst, nxt: snd, .. }
      | Term::App { fun: fst, arg: snd, .. }
      | Term::Oper { fst, snd, .. } => ChildrenIter::Two([fst.as_mut(), snd.as_mut()]),
      Term::Lam { bod, .. } | Term::Do { bod, .. } | Term::Open { bod, .. } => {
        ChildrenIter::One([bod.as_mut()])
      }
      Term::Var { .. }
      | Term::Link { .. }
      | Term::Num { .. }
      | Term::Nat { .. }
      | Term::Str { .. }
      | Term::Ref { .. }
      | Term::Era
      | Term::Err => ChildrenIter::Zero([]),
    }
  }

  /// An iterator over the subterms with an iterator over the binds
  /// introduced by the current term for each subterm.
  ///
  /// Must only be called after fix_matches.
  ///
  /// Example: A lambda introduces 1 bind for it's only subterm,
  /// while a let expression introduces 0 binds for the value and
  /// many binds for the next term.
  pub fn children_with_binds(
    &self,
  ) -> impl DoubleEndedIterator<Item = (&Term, impl DoubleEndedIterator<Item = &Option<Name>> + Clone)> + Clone
  {
    multi_iterator!(ChildrenIter { Zero, One, Two, Vec, Mat, Swt, Bend, Fold });
    multi_iterator!(BindsIter { Zero, One, Mat, Pat, Bend });
    match self {
      Term::Mat { arg, bnd: _, with: _, arms } => ChildrenIter::Mat(
        [(arg.as_ref(), BindsIter::Zero([]))]
          .into_iter()
          .chain(arms.iter().map(move |r| (&r.2, BindsIter::Mat(r.1.iter())))),
      ),
      Term::Swt { arg, bnd: _, with: _, pred, arms } => {
        let (succ, nums) = arms.split_last().unwrap();
        ChildrenIter::Swt(
          [(arg.as_ref(), BindsIter::Zero([]))]
            .into_iter()
            .chain(nums.iter().map(move |x| (x, BindsIter::Zero([]))))
            .chain([(succ, BindsIter::One([pred]))]),
        )
      }
      Term::Bend { bind, init, cond, step, base } => {
        ChildrenIter::Bend(init.iter().map(|x| (x, BindsIter::Zero([]))).chain([
          (cond.as_ref(), BindsIter::Bend(bind.iter())),
          (step.as_ref(), BindsIter::Bend(bind.iter())),
          (base.as_ref(), BindsIter::Bend(bind.iter())),
        ]))
      }
      Term::Fold { bnd: _, arg, with: _, arms } => ChildrenIter::Fold(
        [(arg.as_ref(), BindsIter::Zero([]))]
          .into_iter()
          .chain(arms.iter().map(move |r| (&r.2, BindsIter::Mat(r.1.iter())))),
      ),
      Term::Fan { els, .. } | Term::List { els } => {
        ChildrenIter::Vec(els.iter().map(|el| (el, BindsIter::Zero([]))))
      }
      Term::Let { pat, val, nxt, .. } | Term::Ask { pat, val, nxt, .. } => {
        ChildrenIter::Two([(val.as_ref(), BindsIter::Zero([])), (nxt.as_ref(), BindsIter::Pat(pat.binds()))])
      }
      Term::Use { nam, val, nxt, .. } => {
        ChildrenIter::Two([(val.as_ref(), BindsIter::Zero([])), (nxt.as_ref(), BindsIter::One([nam]))])
      }
      Term::App { fun: fst, arg: snd, .. } | Term::Oper { fst, snd, .. } => {
        ChildrenIter::Two([(fst.as_ref(), BindsIter::Zero([])), (snd.as_ref(), BindsIter::Zero([]))])
      }
      Term::Lam { pat, bod, .. } => ChildrenIter::One([(bod.as_ref(), BindsIter::Pat(pat.binds()))]),
      Term::Do { bod, .. } => ChildrenIter::One([(bod.as_ref(), BindsIter::Zero([]))]),
      Term::Var { .. }
      | Term::Link { .. }
      | Term::Num { .. }
      | Term::Nat { .. }
      | Term::Str { .. }
      | Term::Ref { .. }
      | Term::Era
      | Term::Err => ChildrenIter::Zero([]),
      Term::Open { .. } => unreachable!("Open should be removed in earlier pass"),
    }
  }

  /// Must only be called after fix_matches.
  pub fn children_mut_with_binds(
    &mut self,
  ) -> impl DoubleEndedIterator<Item = (&mut Term, impl DoubleEndedIterator<Item = &Option<Name>> + Clone)>
  {
    multi_iterator!(ChildrenIter { Zero, One, Two, Vec, Mat, Swt, Bend, Fold });
    multi_iterator!(BindsIter { Zero, One, Mat, Pat, Bend });
    match self {
      Term::Mat { arg, bnd: _, with: _, arms: rules } => ChildrenIter::Mat(
        [(arg.as_mut(), BindsIter::Zero([]))]
          .into_iter()
          .chain(rules.iter_mut().map(move |r| (&mut r.2, BindsIter::Mat(r.1.iter())))),
      ),
      Term::Swt { arg, bnd: _, with: _, pred, arms: rules } => {
        let (succ, nums) = rules.split_last_mut().unwrap();
        ChildrenIter::Swt(
          [(arg.as_mut(), BindsIter::Zero([]))]
            .into_iter()
            .chain(nums.iter_mut().map(move |x| (x, BindsIter::Zero([]))))
            .chain([(succ, BindsIter::One([&*pred]))]),
        )
      }
      Term::Bend { bind, init, cond, step, base } => {
        ChildrenIter::Bend(init.iter_mut().map(|x| (x, BindsIter::Zero([]))).chain([
          (cond.as_mut(), BindsIter::Bend(bind.iter())),
          (step.as_mut(), BindsIter::Bend(bind.iter())),
          (base.as_mut(), BindsIter::Bend(bind.iter())),
        ]))
      }
      Term::Fold { bnd: _, arg, with: _, arms } => ChildrenIter::Fold(
        [(arg.as_mut(), BindsIter::Zero([]))]
          .into_iter()
          .chain(arms.iter_mut().map(move |r| (&mut r.2, BindsIter::Mat(r.1.iter())))),
      ),
      Term::Fan { els, .. } | Term::List { els } => {
        ChildrenIter::Vec(els.iter_mut().map(|el| (el, BindsIter::Zero([]))))
      }
      Term::Let { pat, val, nxt, .. } | Term::Ask { pat, val, nxt, .. } => {
        ChildrenIter::Two([(val.as_mut(), BindsIter::Zero([])), (nxt.as_mut(), BindsIter::Pat(pat.binds()))])
      }
      Term::Use { nam, val, nxt } => {
        ChildrenIter::Two([(val.as_mut(), BindsIter::Zero([])), (nxt.as_mut(), BindsIter::One([&*nam]))])
      }
      Term::App { fun: fst, arg: snd, .. } | Term::Oper { fst, snd, .. } => {
        ChildrenIter::Two([(fst.as_mut(), BindsIter::Zero([])), (snd.as_mut(), BindsIter::Zero([]))])
      }
      Term::Lam { pat, bod, .. } => ChildrenIter::One([(bod.as_mut(), BindsIter::Pat(pat.binds()))]),
      Term::Do { bod, .. } => ChildrenIter::One([(bod.as_mut(), BindsIter::Zero([]))]),
      Term::Var { .. }
      | Term::Link { .. }
      | Term::Num { .. }
      | Term::Nat { .. }
      | Term::Str { .. }
      | Term::Ref { .. }
      | Term::Era
      | Term::Err => ChildrenIter::Zero([]),
      Term::Open { .. } => unreachable!("Open should be removed in earlier pass"),
    }
  }

  /// Must only be called after fix_matches.
  pub fn children_mut_with_binds_mut(
    &mut self,
  ) -> impl DoubleEndedIterator<Item = (&mut Term, impl DoubleEndedIterator<Item = &mut Option<Name>>)> {
    multi_iterator!(ChildrenIter { Zero, One, Two, Vec, Mat, Swt, Fold });
    multi_iterator!(BindsIter { Zero, One, Mat, Pat });
    match self {
      Term::Mat { arg, bnd: _, with: _, arms: rules } => ChildrenIter::Mat(
        [(arg.as_mut(), BindsIter::Zero([]))]
          .into_iter()
          .chain(rules.iter_mut().map(move |r| (&mut r.2, BindsIter::Mat(r.1.iter_mut())))),
      ),
      Term::Swt { arg, bnd: _, with: _, pred, arms: rules } => {
        let (succ, nums) = rules.split_last_mut().unwrap();
        ChildrenIter::Swt(
          [(arg.as_mut(), BindsIter::Zero([]))]
            .into_iter()
            .chain(nums.iter_mut().map(move |x| (x, BindsIter::Zero([]))))
            .chain([(succ, BindsIter::One([pred]))]),
        )
      }
      Term::Bend { .. } => {
        unreachable!("Term::Bend can't implement children_mut_with_binds_mut")
      }
      Term::Fold { bnd: _, arg, with: _, arms } => ChildrenIter::Fold(
        [(arg.as_mut(), BindsIter::Zero([]))]
          .into_iter()
          .chain(arms.iter_mut().map(move |r| (&mut r.2, BindsIter::Mat(r.1.iter_mut())))),
      ),
      Term::Fan { els, .. } | Term::List { els } => {
        ChildrenIter::Vec(els.iter_mut().map(|el| (el, BindsIter::Zero([]))))
      }
      Term::Use { nam, val, nxt } => {
        ChildrenIter::Two([(val.as_mut(), BindsIter::Zero([])), (nxt.as_mut(), BindsIter::One([nam]))])
      }
      Term::Let { pat, val, nxt, .. } | Term::Ask { pat, val, nxt, .. } => ChildrenIter::Two([
        (val.as_mut(), BindsIter::Zero([])),
        (nxt.as_mut(), BindsIter::Pat(pat.binds_mut())),
      ]),
      Term::App { fun: fst, arg: snd, .. } | Term::Oper { fst, snd, .. } => {
        ChildrenIter::Two([(fst.as_mut(), BindsIter::Zero([])), (snd.as_mut(), BindsIter::Zero([]))])
      }
      Term::Lam { pat, bod, .. } => ChildrenIter::One([(bod.as_mut(), BindsIter::Pat(pat.binds_mut()))]),
      Term::Do { bod, .. } => ChildrenIter::One([(bod.as_mut(), BindsIter::Zero([]))]),
      Term::Var { .. }
      | Term::Link { .. }
      | Term::Num { .. }
      | Term::Nat { .. }
      | Term::Str { .. }
      | Term::Ref { .. }
      | Term::Era
      | Term::Err => ChildrenIter::Zero([]),
      Term::Open { .. } => unreachable!("Open should be removed in earlier pass"),
    }
  }

  /* Common checks and transformations */

  /// Substitute the occurrences of a variable in a term with the given term.
  ///
  /// Caution: can cause invalid shadowing of variables if used incorrectly.
  /// Ex: Using subst to beta-reduce `(@a @b a b)` converting it into `@b b`.
  ///
  /// NOTE: Expects var bind information to be properly stored in match expressions,
  /// so it must run AFTER `fix_match_terms`.
  ///
  /// NOTE: Since it doesn't (can't) handle `with` clauses in match terms,
  /// it must be run only AFTER `with` linearization.
  pub fn subst(&mut self, from: &Name, to: &Term) {
    maybe_grow(|| {
      for (child, binds) in self.children_mut_with_binds() {
        if !binds.flat_map(|b| b.as_ref()).contains(from) {
          child.subst(from, to);
        }
      }
    });

    if let Term::Var { nam } = self {
      if nam == from {
        *self = to.clone();
      }
    }
  }

  /// Substitute the occurrence of an unscoped variable with the given term.
  pub fn subst_unscoped(&mut self, from: &Name, to: &Term) {
    maybe_grow(|| {
      // We don't check the unscoped binds because there can be only one bind of an unscoped var.
      // TODO: potentially there could be some situation where this causes an incorrect program to compile?
      for child in self.children_mut() {
        child.subst_unscoped(from, to);
      }
    });

    if let Term::Link { nam } = self {
      if nam == from {
        *self = to.clone();
      }
    }
  }

  /// Collects all the free variables that a term has
  /// and the number of times each var is used
  pub fn free_vars(&self) -> HashMap<Name, u64> {
    fn go_term(term: &Term, free_vars: &mut HashMap<Name, u64>) {
      maybe_grow(|| {
        if let Term::Var { nam } = term {
          *free_vars.entry(nam.clone()).or_default() += 1;
        }

        for (child, binds) in term.children_with_binds() {
          let mut new_scope = Default::default();
          go_term(child, &mut new_scope);

          for nam in binds.flatten() {
            new_scope.remove(nam);
          }

          free_vars.extend(new_scope);
        }
      })
    }

    let mut free_vars = Default::default();
    go_term(self, &mut free_vars);
    free_vars
  }

  /// Returns the set of declared and the set of used unscoped variables
  pub fn unscoped_vars(&self) -> (IndexSet<Name>, IndexSet<Name>) {
    fn go_pat(pat: &Pattern, decls: &mut IndexSet<Name>) {
      maybe_grow(|| {
        if let Pattern::Chn(name) = pat {
          decls.insert(name.clone());
        }

        for child in pat.children() {
          go_pat(child, decls);
        }
      })
    }
    fn go_term(term: &Term, decls: &mut IndexSet<Name>, uses: &mut IndexSet<Name>) {
      maybe_grow(|| {
        if let Term::Link { nam } = term {
          uses.insert(nam.clone());
        }

        if let Some(pat) = term.pattern() {
          go_pat(pat, decls)
        }

        for child in term.children() {
          go_term(child, decls, uses);
        }
      })
    }
    let mut decls = Default::default();
    let mut uses = Default::default();
    go_term(self, &mut decls, &mut uses);
    (decls, uses)
  }

  pub fn has_unscoped(&self) -> bool {
    maybe_grow(|| {
      let mut has_unscoped = match self {
        Term::Let { pat, .. } if pat.has_unscoped() => true,
        Term::Link { .. } => true,
        _ => false,
      };
      for child in self.children() {
        if has_unscoped {
          return true;
        }
        has_unscoped |= child.has_unscoped()
      }
      has_unscoped
    })
  }
}

impl Num {
  pub fn is_zero(&self) -> bool {
    match self {
      Num::U24(val) => *val == 0,
      Num::I24(val) => *val == 0,
      Num::F24(val) => *val == 0.0,
    }
  }

  pub fn to_bits(&self) -> u32 {
    match self {
      Num::U24(val) => hvm::hvm::Numb::new_u24(*val).0,
      Num::I24(val) => hvm::hvm::Numb::new_i24(*val).0,
      Num::F24(val) => hvm::hvm::Numb::new_f24(*val).0,
    }
  }

  pub fn from_bits(bits: u32) -> Self {
    match hvm::hvm::Numb::get_typ(&hvm::hvm::Numb(bits)) {
      hvm::hvm::TY_U24 => Num::U24(hvm::hvm::Numb::get_u24(&hvm::hvm::Numb(bits))),
      hvm::hvm::TY_I24 => Num::I24(hvm::hvm::Numb::get_i24(&hvm::hvm::Numb(bits))),
      hvm::hvm::TY_F24 => Num::F24(hvm::hvm::Numb::get_f24(&hvm::hvm::Numb(bits))),
      _ => unreachable!("Invalid Num bits"),
    }
  }
}

impl Hash for Num {
  fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
    self.to_bits().hash(state);
  }
}

impl PartialEq for Num {
  fn eq(&self, other: &Self) -> bool {
    self.to_bits() == other.to_bits()
  }
}

impl Eq for Num {}

impl Pattern {
  pub fn binds(&self) -> impl DoubleEndedIterator<Item = &Option<Name>> + Clone {
    self.iter().filter_map(|pat| match pat {
      Pattern::Var(nam) => Some(nam),
      _ => None,
    })
  }

  pub fn binds_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Option<Name>> {
    // Can't have a Pattern::iter_mut() since it has a tree-like structure.
    let mut binds = vec![];
    let mut to_visit = vec![self];
    while let Some(pat) = to_visit.pop() {
      match pat {
        Pattern::Var(nam) => binds.push(nam),
        _ => to_visit.extend(pat.children_mut().rev()),
      }
    }
    binds.into_iter()
  }

  /// Returns an iterator over each immediate child sub-pattern of `self`.
  /// Considers Lists as its own pattern and not a sequence of Cons.
  pub fn children(&self) -> impl DoubleEndedIterator<Item = &Pattern> + Clone {
    multi_iterator!(ChildrenIter { Zero, Vec });
    match self {
      Pattern::Ctr(_, els) | Pattern::Fan(.., els) | Pattern::Lst(els) => ChildrenIter::Vec(els.iter()),
      Pattern::Var(_) | Pattern::Chn(_) | Pattern::Num(_) | Pattern::Str(_) => ChildrenIter::Zero([]),
    }
  }

  pub fn children_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Pattern> {
    multi_iterator!(ChildrenIter { Zero, Vec });
    match self {
      Pattern::Ctr(_, els) | Pattern::Fan(.., els) | Pattern::Lst(els) => ChildrenIter::Vec(els.iter_mut()),
      Pattern::Var(_) | Pattern::Chn(_) | Pattern::Num(_) | Pattern::Str(_) => ChildrenIter::Zero([]),
    }
  }

  /// Returns an iterator over each subpattern in depth-first, left to right order.
  // TODO: Not lazy.
  pub fn iter(&self) -> impl DoubleEndedIterator<Item = &Pattern> + Clone {
    let mut to_visit = vec![self];
    let mut els = vec![];
    while let Some(pat) = to_visit.pop() {
      els.push(pat);
      to_visit.extend(pat.children().rev());
    }
    els.into_iter()
  }

  pub fn is_wildcard(&self) -> bool {
    matches!(self, Pattern::Var(_) | Pattern::Chn(_))
  }

  pub fn to_term(&self) -> Term {
    match self {
      Pattern::Var(nam) => Term::var_or_era(nam.clone()),
      Pattern::Chn(nam) => Term::Link { nam: nam.clone() },
      Pattern::Ctr(ctr, args) => {
        Term::call(Term::Ref { nam: ctr.clone() }, args.iter().map(|arg| arg.to_term()))
      }
      Pattern::Num(val) => Term::Num { val: Num::U24(*val) },
      Pattern::Fan(fan, tag, args) => {
        Term::Fan { fan: *fan, tag: tag.clone(), els: args.iter().map(|p| p.to_term()).collect() }
      }
      Pattern::Lst(_) | Pattern::Str(_) => todo!(),
    }
  }

  pub fn has_unscoped(&self) -> bool {
    match self {
      Pattern::Chn(_) => true,
      Pattern::Var(_) | Pattern::Str(_) | Pattern::Num(_) => false,
      Pattern::Ctr(_, x) | Pattern::Fan(_, _, x) | Pattern::Lst(x) => x.iter().any(|x| x.has_unscoped()),
    }
  }
}

impl Rule {
  pub fn arity(&self) -> usize {
    self.pats.len()
  }
}

impl Definition {
  pub fn arity(&self) -> usize {
    self.rules[0].arity()
  }

  #[track_caller]
  pub fn assert_no_pattern_matching_rules(&self) {
    assert!(self.rules.len() == 1, "Definition rules should have been removed in earlier pass");
    assert!(self.rules[0].pats.is_empty(), "Definition args should have been removed in an earlier pass");
  }

  #[track_caller]
  pub fn rule(&self) -> &Rule {
    self.assert_no_pattern_matching_rules();
    &self.rules[0]
  }

  #[track_caller]
  pub fn rule_mut(&mut self) -> &mut Rule {
    self.assert_no_pattern_matching_rules();
    &mut self.rules[0]
  }
}

impl Name {
  pub fn new<'a, V: Into<Cow<'a, str>>>(value: V) -> Name {
    Name(STRINGS.get(value))
  }

  pub fn is_generated(&self) -> bool {
    // Generated def names use $ while var names use %
    self.contains("__") || self.contains('%')
  }

  pub fn def_name_from_generated(&self) -> Name {
    if let Some((nam, _)) = self.split_once("__") {
      Name::new(nam)
    } else {
      self.clone()
    }
  }
}

impl Default for Name {
  fn default() -> Self {
    Self::new("")
  }
}

impl From<u64> for Name {
  fn from(value: u64) -> Self {
    Name::new(num_to_name(value).as_str())
  }
}

impl From<u32> for Name {
  fn from(value: u32) -> Self {
    Name::new(num_to_name(value as u64).as_str())
  }
}

impl Deref for Name {
  type Target = str;

  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

impl AsRef<str> for Name {
  fn as_ref(&self) -> &str {
    &self.0
  }
}

impl Book {
  pub fn hvmc_entrypoint(&self) -> &str {
    match self.entrypoint.as_ref().map(|e| e.as_ref()) {
      Some("main" | "Main") | None => ENTRY_POINT,
      Some(nam) => nam,
    }
  }
}

#[test]
fn num_to_from_bits() {
  let a = [
    Num::U24(0),
    Num::U24(0xFFFFFF),
    Num::U24(12345),
    Num::I24(0),
    Num::I24(0x7FFFFF),
    Num::I24(12345),
    Num::I24(-12345),
    Num::F24(0.0),
    Num::I24(-0),
    Num::F24(0xFFFFFF as f32),
    Num::F24(0.0),
    Num::F24(-0.0),
    Num::F24(0.00123),
    Num::F24(12345.023),
    Num::F24(-1235.3849),
    Num::F24(1.0),
    Num::F24(-1.0),
    Num::F24(12323658716.0),
    Num::F24(-12323658716.0),
    Num::F24(-0.00000000000000001),
    Num::F24(0.00000000000000001),
    Num::F24(5447856134985749851.3457896137815694178),
    Num::F24(-5447856134985749851.3457896137815694178),
  ];
  for b in a {
    assert_eq!(b, Num::from_bits(Num::to_bits(&b)));
  }
}