uiua 0.18.1

A stack-based array programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
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
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
use std::{
    borrow::Borrow,
    cell::RefCell,
    collections::HashMap,
    fmt,
    hash::{Hash, Hasher},
    iter::once,
    mem::{discriminant, swap, take},
    ops::Deref,
    slice::{self, SliceIndex},
    sync::Arc,
};

use ecow::{EcoString, EcoVec, eco_vec};
use indexmap::IndexSet;
use rapidhash::quality::RapidHasher;
use serde::*;

use crate::{
    AestheticHash, Assembly, BindingKind, DynamicFunction, Function, ImplPrimitive, Primitive,
    Purity, Signature, Value,
    check::SigCheckError,
    compile::invert::{InversionError, InversionResult},
};

node!(
    /// Create an array
    Array {
        len: usize,
        inner: Arc<Node>,
        boxed: bool,
        allow_ext: bool,
        prim: Option<Primitive>,
        span: usize
    },
    /// Get a global value
    CallGlobal(index(usize), sig(Signature)),
    /// Call a recursive macro
    CallMacro { index: usize, sig: Signature, span: usize },
    /// Bind a global value
    BindGlobal { index: usize, span: usize },
    /// Set a value's label
    Label(label(EcoString), span(usize)),
    /// Remove a value's label
    RemoveLabel(label(Option<EcoString>), span(usize)),
    /// Format with a string
    Format(parts(EcoVec<EcoString>), span(usize)),
    /// Match a format pattern
    MatchFormatPattern(parts(EcoVec<EcoString>), span(usize)),
    /// A custom inverse
    CustomInverse(cust(Arc<CustomInverse>), span(usize)),
    /// A switch with branches
    Switch { branches: Ops, sig: Signature, under_cond: bool, span: usize },
    /// Unpack an array onto the stack
    Unpack {
        count: usize,
        unbox: bool,
        allow_ext: bool,
        prim: Option<Primitive>,
        span: usize
    },
    /// Set some values for an output comment
    SetOutputComment { i: usize, n: usize },
    /// Call a Rust function
    Dynamic(func(DynamicFunction)),
    /// Push some values to the under stack
    PushUnder(n(usize), span(usize)),
    /// Copy some values to the under stack
    CopyToUnder(n(usize), span(usize)),
    /// Pop some values from the under stack
    PopUnder(n(usize), span(usize)),
    /// Do not inline this node
    NoInline(inner(Arc<Node>)),
    /// Track the caller of this node
    TrackCaller(inner(Arc<SigNode>)),
    /// Push a value onto the stack
    Push(val(Value)),
    /// Run a primitive function
    (#[serde(untagged)] rep),
    Prim(prim(Primitive), span(usize)),
    /// Run an implementation primitive function
    (#[serde(untagged)] rep),
    ImplPrim(prim(ImplPrimitive), span(usize)),
    /// Run a modifier
    (#[serde(untagged)] rep),
    Mod(prim(Primitive), args(Ops), span(usize)),
    /// Run an implementation modifier
    (#[serde(untagged)] rep),
    ImplMod(prim(ImplPrimitive), args(Ops), span(usize)),
    /// Call a function
    (#[serde(untagged)] rep),
    Call(func(Function), span(usize)),
    /// Run some nodes in sequence.
    ///
    /// Do not edit the list directly. Use functions like [`Node::push`] and [`Node::prepend`] instead.
    (#[serde(untagged)] rep),
    Run(nodes(EcoVec<Node>)),
);

/// A node with a signature
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct SigNode {
    /// The node
    pub node: Node,
    /// The signature
    pub sig: Signature,
}

impl SigNode {
    /// Create a new signature node
    pub fn new(sig: impl Into<Signature>, node: impl Into<Node>) -> Self {
        Self {
            node: node.into(),
            sig: sig.into(),
        }
    }
    /// Call this node on N sets of arguments
    pub fn on_all(self, n: usize, span: usize) -> SigNode {
        let sig = self.sig;
        let mut sig = sig.with_under(sig.under_args() * n, sig.under_outputs() * n);
        sig.update_args_outputs(|a, o| (a * n, o * n));
        let node = match n {
            0 => Node::empty(),
            1 => self.node,
            n => {
                let mut sn = self;
                let inner = sn.clone();
                let prev_pow_2 = (n as f64).log2() as usize;
                for _ in 0..prev_pow_2 {
                    let mut sig = sn.sig;
                    sig.update_args_outputs(|a, o| (a * 2, o * 2));
                    let node = Node::Mod(Primitive::Both, eco_vec![sn], span);
                    sn = SigNode::new(sig, node);
                }
                let remain = n - 2usize.pow(prev_pow_2 as u32);
                if remain > 0 {
                    let SigNode { mut sig, node } = sn;
                    let args = inner.sig.args();
                    let mut both = node.clone();
                    for _ in 0..remain {
                        for _ in 0..args {
                            let inner = SigNode::new(sig, both);
                            both = Node::Mod(Primitive::Dip, eco_vec![inner], span);
                        }
                        both.push(inner.node.clone());
                        sig.update_args_outputs(|a, o| {
                            (a + args, o + args + inner.sig.outputs() - inner.sig.args())
                        });
                    }
                    both
                } else {
                    sn.node
                }
            }
        };
        SigNode::new(sig, node)
    }
    /// Dip before calling this node
    pub fn dipped(self, depth: usize, span: usize) -> SigNode {
        let mut sig = self.sig;
        sig.update_args_outputs(|a, o| (a + depth, o + depth));
        let node = match depth {
            0 => self.node,
            1 => Node::Mod(Primitive::Dip, eco_vec![self], span),
            n => Node::ImplMod(ImplPrimitive::DipN(n), eco_vec![self], span),
        };
        SigNode::new(sig, node)
    }
    /// Gap before calling this node
    pub fn gapped(mut self, depth: usize, span: usize) -> SigNode {
        let mut sig = self.sig;
        sig.update_args(|a| a + depth);
        for _ in 0..depth {
            self.node.prepend(Node::Prim(Primitive::Pop, span));
        }
        self
    }
}

impl From<SigNode> for Node {
    fn from(sn: SigNode) -> Self {
        sn.node
    }
}

impl From<Arc<Node>> for Node {
    fn from(node: Arc<Node>) -> Self {
        Arc::unwrap_or_clone(node)
    }
}

impl From<SigNode> for (Node, Signature) {
    fn from(sn: SigNode) -> Self {
        (sn.node, sn.sig)
    }
}

impl Serialize for SigNode {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        (self.sig.args(), self.sig.outputs(), &self.node).serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for SigNode {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let (args, outputs, node) = <(usize, usize, Node)>::deserialize(deserializer)?;
        Ok(SigNode::new(Signature::new(args, outputs), node))
    }
}

pub(crate) type Ops = EcoVec<SigNode>;

/// A custom inverse node
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(default)]
pub struct CustomInverse {
    /// The normal function to call
    pub normal: InversionResult<SigNode>,
    /// The un inverse
    #[serde(skip_serializing_if = "Option::is_none")]
    pub un: Option<SigNode>,
    /// The under inverse
    #[serde(skip_serializing_if = "Option::is_none")]
    pub under: Option<(SigNode, SigNode)>,
    /// The anti inverse
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anti: Option<SigNode>,
    /// Whether this was created with obverse
    ///
    /// Inverses that are not set by obverse may be overridden
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub is_obverse: bool,
}

impl Default for CustomInverse {
    fn default() -> Self {
        Self {
            normal: Ok(SigNode::default()),
            un: None,
            under: None,
            anti: None,
            is_obverse: false,
        }
    }
}

impl From<InversionError> for CustomInverse {
    fn from(e: InversionError) -> Self {
        Self {
            normal: Err(e),
            ..Default::default()
        }
    }
}

impl fmt::Debug for CustomInverse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = if self.is_obverse {
            f.debug_struct("obverse")
        } else {
            f.debug_struct("custom inverse")
        };
        if let Ok(normal) = &self.normal {
            s.field("normal", &normal.node);
        } else {
            s.field("normal", &self.normal.as_ref().map(|sn| &sn.node));
        }
        if let Some(un) = &self.un {
            s.field("un", &un.node);
        }
        if let Some(anti) = &self.anti {
            s.field("anti", &anti.node);
        }
        if let Some(under) = &self.under {
            s.field("do", &under.0.node);
            s.field("undo", &under.1.node);
        }
        s.finish()
    }
}

impl CustomInverse {
    /// Get the signature of the custom inverse
    pub fn sig(&self) -> Result<Signature, SigCheckError> {
        Ok(match &self.normal {
            Ok(n) => n.sig,
            Err(e) => {
                if let Some(un) = &self.un {
                    un.sig.inverse()
                } else if let Some(anti) = &self.anti {
                    anti.sig
                        .anti()
                        .ok_or_else(|| SigCheckError::from(e.to_string()).no_inverse())?
                } else {
                    return match e {
                        InversionError::Signature(e) => Err(e.clone()),
                        e => Err(SigCheckError::from(e.to_string()).no_inverse()),
                    };
                }
            }
        })
    }
    /// Iterate over all nodes
    pub fn nodes(&self) -> impl Iterator<Item = &SigNode> {
        (self.normal.as_ref().into_iter())
            .chain(self.un.as_ref())
            .chain(self.anti.as_ref())
            .chain(self.under.as_ref().into_iter().flat_map(|(b, a)| [a, b]))
    }
    /// Iterate mutably over all nodes
    pub fn nodes_mut(&mut self) -> impl Iterator<Item = &mut SigNode> {
        (self.normal.as_mut().into_iter())
            .chain(self.un.as_mut())
            .chain(self.anti.as_mut())
            .chain(self.under.as_mut().into_iter().flat_map(|(b, a)| [a, b]))
    }
}

impl Default for Node {
    fn default() -> Self {
        Self::empty()
    }
}

impl Node {
    /// Create an empty node
    pub const fn empty() -> Self {
        Self::Run(EcoVec::new())
    }
    /// Create a push node from a value
    pub fn new_push(val: impl Into<Value>) -> Self {
        let mut value = val.into();
        value.try_shrink();
        value.derive_sortedness();
        Self::Push(value)
    }
    /// Get a slice of the nodes in this node
    pub fn as_slice(&self) -> &[Node] {
        if let Node::Run(nodes) = self {
            nodes
        } else {
            slice::from_ref(self)
        }
    }
    /// Get a mutable slice of the nodes in this node
    pub fn as_mut_slice(&mut self) -> &mut [Node] {
        match self {
            Node::Run(nodes) => nodes.make_mut(),
            other => slice::from_mut(other),
        }
    }
    /// Slice the node to get a subnode
    pub fn slice<R>(&self, range: R) -> Self
    where
        R: SliceIndex<[Node], Output = [Node]>,
    {
        Self::from_iter(self.as_slice()[range].iter().cloned())
    }
    /// Get a mutable vector of the nodes in this node
    ///
    /// Transforms the node into a [`Node::Run`] if it is not already a [`Node::Run`]
    pub fn as_vec(&mut self) -> &mut EcoVec<Node> {
        match self {
            Node::Run(nodes) => nodes,
            other => {
                let first = take(other);
                let Node::Run(nodes) = other else {
                    unreachable!()
                };
                nodes.push(first);
                nodes
            }
        }
    }
    /// Turn the node into a vector
    pub fn into_vec(self) -> EcoVec<Node> {
        if let Node::Run(nodes) = self {
            nodes
        } else {
            eco_vec![self]
        }
    }
    /// Flatten runs of nodes
    pub fn normalize(&mut self) {
        if let Node::Run(nodes) = self {
            if nodes.len() == 1 {
                *self = take(nodes).remove(0);
                self.normalize();
            } else if nodes.iter().any(|node| matches!(node, Node::Run(_))) {
                *self = take(nodes).into_iter().flatten().collect();
                self.normalize();
            }
        }
    }
    /// Truncate the node to a certain length
    pub fn truncate(&mut self, len: usize) {
        if let Node::Run(nodes) = self {
            nodes.truncate(len);
            if nodes.len() == 1 {
                *self = take(nodes).remove(0);
            }
        } else if len == 0 {
            *self = Node::default();
        }
    }
    /// Split the node at the given index
    #[track_caller]
    pub fn split_off(&mut self, index: usize) -> Self {
        if let Node::Run(nodes) = self {
            let removed = EcoVec::from(&nodes[index..]);
            nodes.truncate(index);
            Node::Run(removed)
        } else if index == 0 {
            take(self)
        } else if index == 1 {
            Node::empty()
        } else {
            panic!(
                "Index {index} out of bounds of node with length {}",
                self.len()
            );
        }
    }
    /// Mutably iterate over the nodes of this node
    ///
    /// Transforms the node into a [`Node::Run`] if it is not already a [`Node::Run`]
    pub fn iter_mut(&mut self) -> slice::IterMut<Self> {
        self.as_mut_slice().iter_mut()
    }
    /// Push a node onto the end of the node
    ///
    /// Transforms the node into a [`Node::Run`] if it is not already a [`Node::Run`]
    pub fn push(&mut self, mut node: Node) {
        if let Node::Run(nodes) = self {
            if nodes.is_empty() {
                *self = node;
            } else {
                match node {
                    Node::Run(other) => nodes.extend(other),
                    node => nodes.push(node),
                }
            }
        } else if let Node::Run(nodes) = &node {
            if !nodes.is_empty() {
                swap(self, &mut node);
                self.as_vec().insert(0, node);
            }
        } else {
            self.as_vec().push(node);
        }
    }
    /// Push a node onto the beginning of the node
    ///
    /// Transforms the node into a [`Node::Run`] if it is not already a [`Node::Run`]
    pub fn prepend(&mut self, mut node: Node) {
        if let Node::Run(nodes) = self {
            if nodes.is_empty() {
                *self = node;
            } else {
                match node {
                    Node::Run(mut other) => {
                        swap(nodes, &mut other);
                        nodes.extend(other)
                    }
                    node => nodes.insert(0, node),
                }
            }
        } else if let Node::Run(nodes) = &node {
            if !nodes.is_empty() {
                swap(self, &mut node);
                self.as_vec().push(node);
            }
        } else {
            self.as_vec().insert(0, node);
        }
    }
    /// Pop a node from the end of this node
    pub fn pop(&mut self) -> Option<Node> {
        match self {
            Node::Run(nodes) => {
                let res = nodes.pop();
                if nodes.len() == 1 {
                    *self = take(nodes).remove(0);
                }
                res
            }
            node => Some(take(node)),
        }
    }
    /// Clear the node
    pub fn clear(&mut self) {
        *self = Node::empty();
    }
    pub(crate) fn as_flipped_primitive(&self) -> Option<(Primitive, bool)> {
        match self {
            Node::Prim(prim, _) => Some((*prim, false)),
            Node::Run(nodes) => match nodes.as_slice() {
                [Node::Prim(Primitive::Flip, _), Node::Prim(prim, _)] => Some((*prim, true)),
                _ => None,
            },
            _ => None,
        }
    }
    pub(crate) fn as_primitive(&self) -> Option<Primitive> {
        self.as_flipped_primitive()
            .filter(|(_, flipped)| !flipped)
            .map(|(prim, _)| prim)
    }
    pub(crate) fn as_flipped_impl_primitive(&self) -> Option<(ImplPrimitive, bool)> {
        match self {
            Node::ImplPrim(prim, _) => Some((*prim, false)),
            Node::Run(nodes) => match nodes.as_slice() {
                [Node::Prim(Primitive::Flip, _), Node::ImplPrim(prim, _)] => Some((*prim, true)),
                _ => None,
            },
            _ => None,
        }
    }
    pub(crate) fn as_impl_primitive(&self) -> Option<ImplPrimitive> {
        self.as_flipped_impl_primitive()
            .filter(|(_, flipped)| !flipped)
            .map(|(prim, _)| prim)
    }
    /// Call a function on the last node in the tree, recursing into function calls
    pub fn last_mut_recursive<T>(
        &mut self,
        asm: &mut Assembly,
        f: impl Fn(&mut Node) -> T + Copy,
    ) -> Option<T> {
        fn recurse<T>(
            target: Option<usize>,
            sub: Option<usize>,
            node: &mut Node,
            asm: &mut Assembly,
            f: impl FnOnce(&mut Node) -> T + Copy,
        ) -> Option<T> {
            let mut this_node = match target {
                Some(i) => asm.functions[i].inner(),
                None => node.inner(),
            };
            if let Some(i) = sub {
                this_node = this_node.get(i)?;
            }
            match this_node {
                Node::Run(nodes) if sub.is_none() => {
                    for i in (0..nodes.len()).rev() {
                        if let Some(res) = recurse(target, Some(i), node, asm, f) {
                            return Some(res);
                        }
                    }
                    None
                }
                Node::Call(func, _) => recurse(Some(func.index), None, node, asm, f),
                _ => {
                    let mut node = match target {
                        Some(i) => asm.functions.make_mut()[i].inner_mut(),
                        None => node.inner_mut(),
                    };
                    if let Some(i) = sub {
                        node = node.as_mut_slice().get_mut(i)?.inner_mut();
                    }
                    Some(f(node))
                }
            }
        }
        recurse(None, None, self, asm, f)
    }
    pub(crate) fn inner(&self) -> &Node {
        match self {
            Node::NoInline(inner) => inner.inner(),
            Node::TrackCaller(inner) => inner.node.inner(),
            Node::CustomInverse(cust, ..) => {
                if let Ok(sn) = cust.normal.as_ref() {
                    sn.node.inner()
                } else {
                    self
                }
            }
            node => node,
        }
    }
    fn inner_mut(&mut self) -> &mut Node {
        match self {
            Node::NoInline(inner) => Arc::make_mut(inner).inner_mut(),
            Node::TrackCaller(inner) => Arc::make_mut(inner).node.inner_mut(),
            node => node,
        }
    }
    pub(crate) fn hash_with_span(&self, hasher: &mut impl Hasher) {
        self.hash(hasher);
        if let Some(span) = self.span() {
            span.hash(hasher);
        }
    }
    /// `⊓ bracket` several nodes
    pub fn bracket<I>(nodes: I, span: usize) -> Node
    where
        I: IntoIterator<Item = SigNode>,
        I::IntoIter: ExactSizeIterator,
    {
        let mut nodes = nodes.into_iter();
        let size = nodes.len();
        match size {
            0 => Node::empty(),
            1 => nodes.next().unwrap().node,
            2 => Node::Mod(Primitive::Bracket, nodes.collect(), span),
            _ => {
                let first = nodes.next().unwrap();
                let second = Self::bracket(nodes, span).sig_node().unwrap();
                Node::Mod(Primitive::Bracket, eco_vec![first, second], span)
            }
        }
    }
    /// Get the child [`Node`]s of this node
    pub fn sub_nodes(&self) -> Box<dyn Iterator<Item = &Node> + '_> {
        match self {
            Node::Run(nodes) => Box::new(nodes.iter()),
            Node::Array { inner, .. } | Node::NoInline(inner) => Box::new(once(&**inner)),
            Node::TrackCaller(inner) => Box::new(once(&inner.node)),
            Node::Mod(_, args, _) | Node::ImplMod(_, args, _) => {
                Box::new(args.iter().map(|sn| &sn.node))
            }
            Node::CustomInverse(cust, _) => Box::new(cust.nodes().map(|sn| &sn.node)),
            Node::Switch { branches, .. } => Box::new(branches.iter().map(|sn| &sn.node)),
            _ => Box::new([].into_iter()),
        }
    }
    /// Get the child [`Node`]s of this node
    pub fn sub_nodes_mut(&mut self) -> Box<dyn Iterator<Item = &mut Node> + '_> {
        match self {
            Node::Run(nodes) => Box::new(nodes.make_mut().iter_mut()),
            Node::Array { inner, .. } | Node::NoInline(inner) => {
                Box::new(once(Arc::make_mut(inner)))
            }
            Node::TrackCaller(inner) => Box::new(once(&mut Arc::make_mut(inner).node)),
            Node::Mod(_, args, _) | Node::ImplMod(_, args, _) => {
                Box::new(args.make_mut().iter_mut().map(|sn| &mut sn.node))
            }
            Node::CustomInverse(cust, _) => {
                Box::new(Arc::make_mut(cust).nodes_mut().map(|sn| &mut sn.node))
            }
            Node::Switch { branches, .. } => {
                Box::new(branches.make_mut().iter_mut().map(|sn| &mut sn.node))
            }
            _ => Box::new([].into_iter()),
        }
    }
}

impl From<&[Node]> for Node {
    fn from(nodes: &[Node]) -> Self {
        Node::from_iter(nodes.iter().cloned())
    }
}

impl<const N: usize> From<[Node; N]> for Node {
    fn from(nodes: [Node; N]) -> Self {
        Node::from_iter(nodes)
    }
}

impl From<EcoVec<Node>> for Node {
    fn from(nodes: EcoVec<Node>) -> Self {
        if nodes.len() == 1 {
            nodes.into_iter().next().unwrap()
        } else {
            Node::Run(nodes)
        }
    }
}

impl FromIterator<Node> for Node {
    fn from_iter<T: IntoIterator<Item = Node>>(iter: T) -> Self {
        let mut iter = iter.into_iter();
        let Some(mut node) = iter.next() else {
            return Node::default();
        };
        for n in iter {
            node.push(n);
        }
        node
    }
}

impl Extend<Node> for Node {
    fn extend<T: IntoIterator<Item = Node>>(&mut self, iter: T) {
        for node in iter.into_iter().flatten() {
            self.push(node);
        }
    }
}

impl fmt::Debug for Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Node::Run(eco_vec) => {
                let mut tuple = f.debug_tuple("");
                for node in eco_vec {
                    tuple.field(node);
                }
                tuple.finish()
            }
            Node::Push(value) => write!(f, "push {value}"),
            Node::Prim(prim, _) => write!(f, "{prim}"),
            Node::ImplPrim(impl_prim, _) => write!(f, "{impl_prim:?}"),
            Node::Mod(prim, args, _) => {
                let mut tuple = f.debug_tuple(&prim.to_string());
                for sn in args {
                    tuple.field(&sn.node);
                }
                tuple.finish()
            }
            Node::ImplMod(impl_prim, args, _) => {
                let mut tuple = f.debug_tuple(&format!("{impl_prim:?}"));
                for sn in args {
                    tuple.field(&sn.node);
                }
                tuple.finish()
            }
            Node::Array {
                len,
                inner,
                boxed: true,
                ..
            } => {
                write!(f, "{}{}{{", Primitive::Len, len)?;
                inner.fmt(f)?;
                write!(f, "}}")
            }
            Node::Array {
                len,
                inner,
                boxed: false,
                ..
            } => {
                write!(f, "{}{}[", Primitive::Len, len)?;
                inner.fmt(f)?;
                write!(f, "]")
            }
            Node::Call(func, _) => write!(f, "call {}", func.id),
            Node::CallGlobal(index, _) => write!(f, "<call global {index}>"),
            Node::CallMacro { index, .. } => write!(f, "<call macro {index}>"),
            Node::BindGlobal { index, .. } => write!(f, "<bind global {index}>"),
            Node::Label(label, _) => write!(f, "${label}"),
            Node::RemoveLabel(..) => write!(f, "remove label"),
            Node::Format(parts, _) => {
                write!(f, "$\"")?;
                for (i, part) in parts.iter().enumerate() {
                    if i > 0 {
                        write!(f, "_")?
                    }
                    write!(f, "{part}")?
                }
                write!(f, "\"")
            }
            Node::MatchFormatPattern(parts, _) => {
                write!(f, "°$\"")?;
                for (i, part) in parts.iter().enumerate() {
                    if i > 0 {
                        write!(f, "_")?
                    }
                    write!(f, "{part}")?
                }
                write!(f, "\"")
            }
            Node::Switch {
                branches,
                sig,
                under_cond,
                ..
            } => {
                write!(f, "{sig}")?;
                if *under_cond || sig.under() != (0, 0) {
                    write!(f, "⍜({})", sig.under())?;
                }
                write!(f, "(")?;
                for (i, br) in branches.iter().enumerate() {
                    if i > 0 {
                        write!(f, "|")?;
                    }
                    br.node.fmt(f)?;
                }
                write!(f, ")")
            }
            Node::CustomInverse(cust, _) => cust.fmt(f),
            Node::Unpack {
                count,
                unbox: false,
                ..
            } => write!(f, "<unpack {count}>"),
            Node::Unpack {
                count, unbox: true, ..
            } => write!(f, "<unpack (unbox) {count}>"),
            Node::SetOutputComment { i, n, .. } => write!(f, "<set output comment {i}({n})>"),
            Node::Dynamic(func) => write!(f, "<dynamic function {}>", func.index),
            Node::PushUnder(count, _) => write!(f, "push-u-{count}"),
            Node::CopyToUnder(count, _) => write!(f, "copy-u-{count}"),
            Node::PopUnder(count, _) => write!(f, "pop-u-{count}"),
            Node::NoInline(inner) => f.debug_tuple("no-inline").field(inner.as_ref()).finish(),
            Node::TrackCaller(inner) => {
                f.debug_tuple("track-caller").field(inner.as_ref()).finish()
            }
        }
    }
}

impl Node {
    /// Check if the node is totally pure
    pub fn is_pure<'a>(&'a self, asm: &'a Assembly) -> bool {
        self.is_min_purity(Purity::Pure, asm)
    }
    /// Check if the node is pure
    pub fn is_min_purity<'a>(&'a self, min_purity: Purity, asm: &'a Assembly) -> bool {
        fn recurse<'a>(
            node: &'a Node,
            purity: Purity,
            asm: &'a Assembly,
            visited: &mut IndexSet<&'a Function>,
        ) -> bool {
            let len = visited.len();
            let is = match node {
                Node::Run(nodes) => nodes.iter().all(|node| recurse(node, purity, asm, visited)),
                Node::Prim(prim, _) => prim.purity() >= purity,
                Node::ImplPrim(prim, _) => prim.purity() >= purity,
                Node::Mod(prim, args, _) => {
                    prim.purity() >= purity
                        && args
                            .iter()
                            .all(|arg| recurse(&arg.node, purity, asm, visited))
                }
                Node::ImplMod(prim, args, _) => {
                    prim.purity() >= purity
                        && args
                            .iter()
                            .all(|arg| recurse(&arg.node, purity, asm, visited))
                }
                Node::Array { inner, .. } => recurse(inner, purity, asm, visited),
                Node::Call(func, _) => {
                    if (func.origin.binding()).is_some_and(|i| asm.bindings[i].meta.external) {
                        false
                    } else {
                        visited.insert(func) && recurse(&asm[func], purity, asm, visited)
                    }
                }
                Node::CallGlobal(index, _) => {
                    if let Some(binding) = asm.bindings.get(*index) {
                        match &binding.kind {
                            BindingKind::Const(_) => true,
                            BindingKind::Func(f) => {
                                visited.insert(f) && recurse(&asm[f], purity, asm, visited)
                            }
                            _ => false,
                        }
                    } else {
                        false
                    }
                }
                Node::Switch { branches, .. } => branches
                    .iter()
                    .all(|br| recurse(&br.node, purity, asm, visited)),
                Node::CustomInverse(cust, _) => (cust.normal.as_ref().ok())
                    .or(cust.un.as_ref())
                    .is_some_and(|sn| recurse(&sn.node, purity, asm, visited)),
                Node::TrackCaller(sn) => recurse(&sn.node, purity, asm, visited),
                Node::NoInline(n) => recurse(n, purity, asm, visited),
                Node::Dynamic(_) => false,
                _ => true,
            };
            visited.truncate(len);
            is
        }

        thread_local! {
            static CACHE: RefCell<HashMap<(u64, Purity), bool>> = RefCell::default();
        }

        let mut hasher = RapidHasher::new(1);
        self.hash(&mut hasher);
        let hash = hasher.finish();
        CACHE.with(|cache| {
            *(cache.borrow_mut().entry((hash, min_purity)))
                .or_insert_with(|| recurse(self, min_purity, asm, &mut IndexSet::new()))
        })
    }
    /// Check if the node has a bound runtime
    pub fn is_limit_bounded<'a>(&'a self, asm: &'a Assembly) -> bool {
        fn recurse<'a>(
            node: &'a Node,
            asm: &'a Assembly,
            visited: &mut IndexSet<&'a Function>,
        ) -> bool {
            let len = visited.len();
            let is = match node {
                Node::Run(nodes) => nodes.iter().all(|node| recurse(node, asm, visited)),
                Node::Prim(Primitive::Send | Primitive::Recv, _) => false,
                Node::Prim(Primitive::Sys(op), _) if op.purity() <= Purity::Mutating => false,
                Node::Mod(_, args, _) | Node::ImplMod(_, args, _) => {
                    args.iter().all(|arg| recurse(&arg.node, asm, visited))
                }
                Node::Array { inner, .. } => recurse(inner, asm, visited),
                Node::Call(func, _) => visited.insert(func) && recurse(&asm[func], asm, visited),
                Node::CallGlobal(index, _) => {
                    if let Some(binding) = asm.bindings.get(*index) {
                        match &binding.kind {
                            BindingKind::Const(Some(_)) => true,
                            BindingKind::Func(f) => {
                                visited.insert(f) && recurse(&asm[f], asm, visited)
                            }
                            _ => false,
                        }
                    } else {
                        false
                    }
                }
                Node::Switch { branches, .. } => {
                    branches.iter().all(|br| recurse(&br.node, asm, visited))
                }
                Node::CustomInverse(cust, _) => (cust.normal.as_ref().ok())
                    .or(cust.un.as_ref())
                    .is_some_and(|sn| recurse(&sn.node, asm, visited)),
                Node::TrackCaller(sn) => recurse(&sn.node, asm, visited),
                Node::NoInline(n) => recurse(n, asm, visited),
                _ => true,
            };
            visited.truncate(len);
            is
        }
        recurse(self, asm, &mut IndexSet::new())
    }
    /// Check if the node is recursive
    pub fn is_recursive(&self, asm: &Assembly) -> bool {
        fn recurse<'a>(
            node: &'a Node,
            asm: &'a Assembly,
            visited: &mut IndexSet<&'a Function>,
        ) -> bool {
            let len = visited.len();
            let is = match node {
                Node::Run(nodes) => nodes.iter().any(|node| recurse(node, asm, visited)),
                Node::Mod(_, args, _) | Node::ImplMod(_, args, _) => {
                    args.iter().any(|sn| recurse(&sn.node, asm, visited))
                }
                Node::Call(f, _) => !visited.insert(f) || recurse(&asm[f], asm, visited),
                Node::Switch { branches, .. } => {
                    branches.iter().any(|br| recurse(&br.node, asm, visited))
                }
                Node::CustomInverse(cust, _) => (cust.normal.as_ref().ok())
                    .or(cust.un.as_ref())
                    .is_some_and(|sn| recurse(&sn.node, asm, visited)),
                Node::Array { inner, .. } => recurse(inner, asm, visited),
                Node::TrackCaller(sn) => recurse(&sn.node, asm, visited),
                Node::NoInline(n) => recurse(n, asm, visited),
                _ => false,
            };
            visited.truncate(len);
            is
        }
        recurse(self, asm, &mut IndexSet::new())
    }
    /// Check if the node is callable
    pub fn check_callability<'a>(
        &'a self,
        asm: &'a Assembly,
    ) -> Result<(), (InversionError, Option<&'a Function>, Vec<usize>)> {
        fn recurse<'a>(
            node: &'a Node,
            asm: &'a Assembly,
            spans: &mut Vec<usize>,
            visited: &mut IndexSet<&'a Function>,
        ) -> Option<(InversionError, Option<&'a Function>)> {
            let len = visited.len();
            let e = match node {
                Node::Run(nodes) => nodes.iter().find_map(|n| recurse(n, asm, spans, visited)),
                Node::Call(f, span) => {
                    if visited.insert(f) {
                        recurse(&asm[f], asm, spans, visited).map(|(e, mut func)| {
                            spans.push(*span);
                            func.get_or_insert(f);
                            (e, func)
                        })
                    } else {
                        None
                    }
                }
                Node::CustomInverse(cust, span) => cust.normal.as_ref().err().cloned().map(|e| {
                    spans.push(*span);
                    (e, None)
                }),
                Node::Switch { branches, .. } => branches
                    .iter()
                    .find_map(|br| recurse(&br.node, asm, spans, visited)),
                Node::Array { inner, .. } => recurse(inner, asm, spans, visited),
                Node::TrackCaller(sn) => recurse(&sn.node, asm, spans, visited),
                Node::NoInline(n) => recurse(n, asm, spans, visited),
                _ => None,
            };
            visited.truncate(len);
            e
        }
        let mut spans = Vec::new();
        if let Some((e, func)) = recurse(self, asm, &mut spans, &mut IndexSet::new()) {
            Err((e, func, spans))
        } else {
            Ok(())
        }
    }
    /// Check if the node is known to always throw
    ///
    /// May have false negatives. Will not have false positives.
    pub fn is_noreturn<'a>(&'a self, asm: &'a Assembly) -> bool {
        use Primitive::*;
        fn recurse<'a>(
            node: &'a Node,
            asm: &'a Assembly,
            visited: &mut IndexSet<&'a Function>,
        ) -> bool {
            let len = visited.len();
            let res = 'blk: {
                if let Some(i) =
                    (node.as_slice().iter()).position(|n| matches!(n, Node::Prim(Assert, _)))
                {
                    let init = &node.as_slice()[..i];
                    let noreturn = match init {
                        [.., Node::Push(val), Node::Prim(Dup | Flip, _)] if *val != 1 => true,
                        [
                            ..,
                            Node::Format(..) | Node::Prim(Couple | Join, _) | Node::Array { .. },
                            Node::Prim(Dup, _),
                        ] => true,
                        [.., Node::Push(val), Node::Push(_)] if *val != 1 => true,
                        [.., Node::Mod(Dip, args, _)]
                            if args.len() == 1
                                && matches!(&args[0].node, Node::Push(val) if *val != 1) =>
                        {
                            true
                        }
                        _ => false,
                    };
                    if noreturn {
                        break 'blk true;
                    }
                }
                match node {
                    Node::Mod(Dip | Gap | On | By | With | Off, inner, _) => {
                        recurse(&inner[0].node, asm, visited)
                    }
                    Node::Call(f, _) => visited.insert(f) && recurse(&asm[f], asm, visited),
                    _ => false,
                }
            };
            visited.truncate(len);
            res
        }
        recurse(self, asm, &mut IndexSet::new())
    }
}

impl Deref for Node {
    type Target = [Node];
    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl AsRef<[Node]> for Node {
    fn as_ref(&self) -> &[Node] {
        self.as_slice()
    }
}

impl Borrow<[Node]> for Node {
    fn borrow(&self) -> &[Node] {
        self.as_slice()
    }
}

impl<'a> IntoIterator for &'a Node {
    type Item = &'a Node;
    type IntoIter = slice::Iter<'a, Node>;
    fn into_iter(self) -> Self::IntoIter {
        self.as_slice().iter()
    }
}

impl<'a> IntoIterator for &'a mut Node {
    type Item = &'a mut Node;
    type IntoIter = slice::IterMut<'a, Node>;
    fn into_iter(self) -> Self::IntoIter {
        self.as_mut_slice().iter_mut()
    }
}

impl IntoIterator for Node {
    type Item = Node;
    type IntoIter = ecow::vec::IntoIter<Node>;
    fn into_iter(self) -> Self::IntoIter {
        self.into_vec().into_iter()
    }
}

macro_rules! node {
    ($(
        $(#[$attr:meta])*
        $((#[$rep_attr:meta] rep),)?
        $name:ident
        $(($($tup_name:ident($tup_type:ty)),* $(,)?))?
        $({$($field_name:ident : $field_type:ty),* $(,)?})?
    ),* $(,)?) => {
        /// A Uiua execution tree node
        ///
        /// A node is a tree structure of instructions. It can be used as both a single unit as well as a list.
        #[derive(Clone, Serialize, Deserialize)]
        #[repr(u8)]
        #[allow(missing_docs)]
        #[serde(from = "NodeRep", into = "NodeRep")]
        pub enum Node {
            $(
                $(#[$attr])*
                $name $(($($tup_type),*))? $({$($field_name : $field_type),*})?,
            )*
        }

        macro_rules! field_span {
            (span, $sp:ident) => {
                return Some($sp)
            };
            ($sp:ident, $sp2:ident) => {};
        }

        impl Node {
            /// Get the span index of this instruction
            #[allow(unreachable_code, unused)]
            pub fn span(&self) -> Option<usize> {
                if let Node::Run(nodes) = &self {
                    return nodes.iter().find_map(Node::span);
                }
                (|| match self {
                    $(
                        Self::$name $(($($tup_name),*))? $({$($field_name),*})? => {
                            $($(field_span!($tup_name, $tup_name);)*)*
                            $($(field_span!($field_name, $field_name);)*)*
                            return None;
                        },
                    )*
                })().copied()
            }
            /// Get a mutable reference to the span index of this instruction
            #[allow(unreachable_code, unused)]
            pub fn span_mut(&mut self) -> Option<&mut usize> {
                match self {
                    $(
                        Self::$name $(($($tup_name),*))? $({$($field_name),*})? => {
                            $($(field_span!($tup_name, $tup_name);)*)*
                            $($(field_span!($field_name, $field_name);)*)*
                            return None;
                        },
                    )*
                }
            }
        }

        impl PartialEq for Node {
            #[allow(unused_variables)]
            fn eq(&self, other: &Self) -> bool {
                let mut hasher = RapidHasher::new(1);
                self.hash(&mut hasher);
                let hash = hasher.finish();
                let mut other_hasher = RapidHasher::new(1);
                other.hash(&mut other_hasher);
                let other_hash = other_hasher.finish();
                hash == other_hash
            }
        }

        impl Eq for Node {}

        impl Hash for Node {
            #[allow(unused_variables)]
            fn hash<H: Hasher>(&self, state: &mut H) {
                macro_rules! hash_field {
                    (span span) => {};
                    (val $val:ident) => {Hash::hash(&AestheticHash($val), state)};
                    ($nm:ident $_nm:ident) => {Hash::hash($nm, state)};
                }
                match self {
                    $(
                        Self::$name $(($($tup_name),*))? $({$($field_name),*})? => {
                            discriminant(self).hash(state);
                            $($(hash_field!($field_name $field_name);)*)?
                            $($(hash_field!($tup_name $tup_name);)*)?
                        }
                    )*
                }
            }
        }

        #[derive(Serialize, Deserialize)]
        #[serde(rename_all = "snake_case")]
        pub(crate) enum NodeRep {
            #[serde(rename = "e")]
            Empty(),
            $(
                $(#[$rep_attr])?
                $name(
                    $($($tup_type),*)?
                    $($($field_type),*)?
                ),
            )*
        }

        impl From<NodeRep> for Node {
            fn from(rep: NodeRep) -> Self {
                match rep {
                    NodeRep::Empty() => Self::empty(),
                    $(
                        NodeRep::$name (
                            $($($tup_name,)*)?
                            $($($field_name,)*)?
                        ) => Self::$name $(($($tup_name),*))? $({$($field_name),*})?,
                    )*
                }
            }
        }

        impl From<Node> for NodeRep {
            fn from(instr: Node) -> Self {
                match instr {
                    Node::Run(nodes) if nodes.is_empty() => NodeRep::Empty(),
                    $(
                        Node::$name $(($($tup_name),*))? $({$($field_name),*})? => NodeRep::$name (
                            $($($tup_name),*)?
                            $($($field_name),*)?
                        ),
                    )*
                }
            }
        }
    };
}
use node;