uiua_parser 0.19.0-dev.4

Uiua parser implementation
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
//! Uiua's abstract syntax tree

use std::{collections::BTreeMap, fmt, iter::once, mem::discriminant};

use ecow::EcoString;
use serde::*;

use crate::{
    BindingCounts, CodeSpan, Complex, Ident, Primitive, SemanticComment, Signature, Sp, Subscript,
    SubscriptNumber, SubscriptToken, parse::ident_modifier_args,
};

/// A top-level item
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "value")]
pub enum Item {
    /// Just some code
    Words(Vec<Sp<Word>>),
    /// A binding
    Binding(Binding),
    /// An import
    Import(Import),
    /// A scope
    Module(Sp<ScopedModule>),
    /// A line of data definitions
    Data(Vec<DataDef>),
}

impl PartialEq for Item {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Item::Words(a), Item::Words(b)) => words_eq(a, b),
            (Item::Binding(a), Item::Binding(b)) => a == b,
            (Item::Import(a), Item::Import(b)) => a == b,
            (Item::Module(a), Item::Module(b)) => a == b,
            (Item::Data(a), Item::Data(b)) => a == b,
            _ => false,
        }
    }
}

fn words_eq(a: &[Sp<Word>], b: &[Sp<Word>]) -> bool {
    a.iter().map(|w| &w.value).eq(b.iter().map(|w| &w.value))
}

impl Item {
    /// Get the span of this item
    pub fn span(&self) -> Option<CodeSpan> {
        match self {
            Item::Words(words) => (words.first().zip(words.last()))
                .map(|(first, last)| first.span.clone().merge(last.span.clone())),
            Item::Binding(binding) => Some(binding.span()),
            Item::Import(import) => Some(import.span()),
            Item::Module(module) => Some(module.span.clone()),
            Item::Data(data) => {
                (data.first().zip(data.last())).map(|(first, last)| first.span().merge(last.span()))
            }
        }
    }
    /// Get a string representation of the kind of this item
    pub fn kind_str(&self) -> &'static str {
        match self {
            Item::Words(_) => "words",
            Item::Binding(_) => "binding",
            Item::Import(_) => "import",
            Item::Module(_) => "module",
            Item::Data(_) => "data definition",
        }
    }
    /// Operate on words or provide a default
    pub fn words_or<'a, T>(&'a self, default: T, on_words: impl FnOnce(&'a [Sp<Word>]) -> T) -> T {
        match self {
            Item::Words(words) => on_words(words),
            _ => default,
        }
    }
    /// Whether this item is an empty line
    pub fn is_empty_line(&self) -> bool {
        self.words_or(false, |words| {
            words.iter().all(|w| matches!(w.value, Word::Spaces))
        })
    }
}

/// A binding
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Binding {
    /// The name of the binding
    pub name: Sp<Ident>,
    /// The span of the arrow
    pub arrow_span: CodeSpan,
    /// Whether the binding is public
    pub public: bool,
    /// Whether the binding is a code macro
    pub code_macro: bool,
    /// The signature
    pub signature: Option<Sp<Signature>>,
    /// The code
    pub words: Vec<Sp<Word>>,
    /// Character counts for golfing
    pub counts: BindingCounts,
}

impl Binding {
    /// Get the span of this binding
    pub fn span(&self) -> CodeSpan {
        (self.name.span.clone()).merge(if let Some(last_word) = self.words.last() {
            last_word.span.clone()
        } else {
            self.arrow_span.clone()
        })
    }
}

/// A scoped module
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ScopedModule {
    /// The span of the opening delimiter
    pub open_span: CodeSpan,
    /// Whether the module is public
    pub public: bool,
    /// The module kind
    pub kind: ModuleKind,
    /// The items
    pub items: Vec<Item>,
    /// The local imports exported from the module
    pub imports: Option<ImportLine>,
    /// The span of the closing delimiter
    pub close_span: Option<CodeSpan>,
}

/// The kind of a module
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ModuleKind {
    /// A named module
    Named(Sp<Ident>),
    /// A test scope
    Test,
}

/// An import
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Import {
    /// The name given to the imported module
    pub name: Option<Sp<Ident>>,
    /// The span of the ~
    pub tilde_span: CodeSpan,
    /// Whether the import is public
    pub public: bool,
    /// The import path
    pub path: Sp<String>,
    /// The import lines
    pub lines: Vec<Option<ImportLine>>,
}

/// A line of imported items
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImportLine {
    /// The span of the ~
    pub tilde_span: CodeSpan,
    /// Whether the imports are public
    pub public: bool,
    /// The imported items
    pub items: Vec<Sp<Ident>>,
}

impl Import {
    /// The full span of the import
    pub fn span(&self) -> CodeSpan {
        let first = (self.name.as_ref())
            .map(|n| n.span.clone())
            .unwrap_or_else(|| self.path.span.clone());
        let last = (self.items().last())
            .map(|(i, _)| i.span.clone())
            .unwrap_or_else(|| self.path.span.clone());
        first.merge(last)
    }
    /// The imported items
    pub fn items(&self) -> impl Iterator<Item = (&Sp<Ident>, bool)> {
        (self.lines.iter().flatten())
            .flat_map(|line| line.items.iter().map(|item| (item, line.public)))
    }
}

/// A data definition
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DataDef {
    /// The span of the ~ or |
    pub init_span: CodeSpan,
    /// Whether the def is public
    pub public: bool,
    /// Whether this is a variant
    pub variant: bool,
    /// The name of the module
    pub name: Option<Sp<Ident>>,
    /// The fields of the data definition
    pub fields: Option<DataFields>,
    /// The function
    pub func: Option<Vec<Sp<Word>>>,
}

/// The fields of a data definition
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DataFields {
    /// Whether the array is boxed
    pub boxed: bool,
    /// The open delimiter span
    pub open_span: CodeSpan,
    /// The data fields
    pub fields: Vec<DataField>,
    /// Comments after the fields
    pub post_comments: Option<Comments>,
    /// A trailing newline
    pub trailing_newline: bool,
    /// The close delimiter span
    pub close_span: Option<CodeSpan>,
}

/// A data field
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DataField {
    /// Leading comments
    pub comments: Option<Comments>,
    /// The name of the field
    pub name: Sp<Ident>,
    /// The validator of the field
    pub validator: Option<FieldValidator>,
    /// An inline comment when there is no init
    pub eol_comment: Option<Sp<EcoString>>,
    /// The default value of the field
    pub init: Option<FieldInit>,
    /// The span of a trailing bar
    pub bar_span: Option<CodeSpan>,
}

/// A data field validator
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FieldValidator {
    /// The span of the colon (may be an open paren)
    pub open_span: CodeSpan,
    /// The validator function
    pub words: Vec<Sp<Word>>,
    /// The closing paren span (if a paren was used to open)
    pub close_span: Option<CodeSpan>,
}

/// A data field initializer
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FieldInit {
    /// The span of the assignment arrow
    pub arrow_span: CodeSpan,
    /// The initializing words
    pub words: Vec<Sp<Word>>,
}

impl DataDef {
    /// Get the span of this data definition
    pub fn span(&self) -> CodeSpan {
        let end = self
            .fields
            .as_ref()
            .map(|fields| fields.span())
            .unwrap_or_else(|| {
                self.name
                    .as_ref()
                    .map(|name| name.span.clone())
                    .unwrap_or_else(|| self.init_span.clone())
            });
        let mut span = (self.init_span.clone()).merge(end);
        if let Some(words) = &self.func
            && let Some(word) = words.last()
        {
            span = span.merge(word.span.clone());
        }
        span
    }
}

impl DataFields {
    /// Get the span of these fields
    pub fn span(&self) -> CodeSpan {
        let end = self
            .close_span
            .clone()
            .or_else(|| {
                self.fields.last().map(|field| {
                    field
                        .bar_span
                        .clone()
                        .unwrap_or_else(|| field.name.span.clone())
                })
            })
            .unwrap_or_else(|| self.open_span.clone());
        self.open_span.clone().merge(end)
    }
}

impl DataField {
    /// Get the span of the field
    pub fn span(&self) -> CodeSpan {
        let Some(end) = self.bar_span.clone().or_else(|| {
            self.init.as_ref().map(|d| {
                d.words
                    .last()
                    .map(|w| w.span.clone())
                    .unwrap_or_else(|| d.arrow_span.clone())
            })
        }) else {
            return self.name.span.clone();
        };
        self.name.span.clone().merge(end)
    }
}

/// A cluster of comments
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Comments {
    /// The normal comment lines
    pub lines: Vec<Sp<EcoString>>,
    /// The semantic comments
    pub semantic: BTreeMap<SemanticComment, CodeSpan>,
}

/// An inline macro
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct InlineMacro {
    /// The function
    pub func: Sp<Func>,
    /// The span of a `^` that makes this an array macro
    pub caret_span: Option<CodeSpan>,
    /// The identifier, which consists of only exclamation marks
    pub ident: Sp<Ident>,
}

/// A word
#[derive(Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
#[serde(tag = "type", content = "value")]
pub enum Word {
    Number(NumWord, String),
    Char(String),
    String(String),
    MultilineString(Vec<Sp<String>>),
    FormatString(Vec<String>),
    MultilineFormatString(Vec<Sp<Vec<String>>>),
    Label(Option<String>),
    Ref(Ref, Vec<ChainComponent>),
    IncompleteRef(Vec<RefComponent>),
    Strand(Vec<Sp<Word>>),
    Array(Arr),
    Func(Func),
    Pack(FunctionPack),
    Primitive(Primitive),
    Modified(Box<Modified>),
    Placeholder(Option<usize>),
    PlaceholderN,
    Comment(EcoString),
    Spaces,
    BreakLine,
    FlipLine,
    SemanticComment(SemanticComment),
    TypeSigComment { i: usize },
    OutputComment { i: usize, n: usize },
    Subscripted(Box<Subscripted>),
    InlineMacro(Box<InlineMacro>),
}

impl PartialEq for Word {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Number(a_n, a_s), Self::Number(b_n, b_s)) => a_n == b_n && a_s == b_s,
            (Self::Char(a), Self::Char(b)) => a == b,
            (Self::String(a), Self::String(b)) => a == b,
            (Self::Label(a), Self::Label(b)) => a == b,
            (Self::FormatString(a), Self::FormatString(b)) => a == b,
            (Self::MultilineFormatString(a), Self::MultilineFormatString(b)) => a == b,
            (Self::Ref(a, ach), Self::Ref(b, bch)) => a == b && ach == bch,
            (Self::Strand(a), Self::Strand(b)) => words_eq(a, b),
            (Self::Array(a), Self::Array(b)) => a.lines == b.lines,
            (Self::Func(a), Self::Func(b)) => a.lines == b.lines,
            (Self::Pack(a), Self::Pack(b)) => (a.branches.iter().flat_map(|br| &br.value.lines))
                .eq(b.branches.iter().flat_map(|br| &br.value.lines)),
            (Self::Primitive(a), Self::Primitive(b)) => a == b,
            (Self::Modified(a), Self::Modified(b)) => {
                a.modifier == b.modifier
                    && a.code_operands()
                        .map(|w| &w.value)
                        .eq(b.code_operands().map(|w| &w.value))
            }
            (Self::Placeholder(_), Self::Placeholder(_)) => false,
            (Self::Comment(a), Self::Comment(b)) => a == b,
            _ => discriminant(self) == discriminant(other),
        }
    }
}

impl Word {
    /// Whether this word is code
    pub fn is_code(&self) -> bool {
        !matches!(
            self,
            Word::Comment(_) | Word::Spaces | Word::BreakLine | Word::FlipLine
        )
    }
    /// Whether this word is a literal
    pub fn is_literal(&self) -> bool {
        match self {
            Word::Number(..) | Word::Char(_) | Word::String(_) => true,
            Word::Array(arr) => arr.lines.iter().all(|item| {
                item.words_or(false, |words| {
                    (words.iter())
                        .filter(|w| w.value.is_code())
                        .all(|w| w.value.is_literal())
                })
            }),
            Word::Strand(items) => items.iter().all(|w| w.value.is_literal()),
            _ => false,
        }
    }
    /// Whether this word must come at the end of a line
    pub fn is_end_of_line(&self) -> bool {
        match self {
            Word::Comment(_)
            | Word::SemanticComment(_)
            | Word::OutputComment { .. }
            | Word::MultilineString(_)
            | Word::MultilineFormatString(_) => true,
            Word::Modified(m) => m.operands.last().is_some_and(|w| w.value.is_end_of_line()),
            _ => false,
        }
    }
}

impl fmt::Debug for Word {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Word::Number(s, ..) => write!(f, "{s:?}"),
            Word::Char(char) => write!(f, "{char:?}"),
            Word::String(string) => write!(f, "{string:?}"),
            Word::MultilineString(string) => write!(f, "$ {string:?}"),
            Word::FormatString(parts) => {
                write!(f, "$\"")?;
                for part in parts {
                    let escaped = format!("{part:?}");
                    let part = &escaped[1..escaped.len() - 1];
                    write!(f, "{part}")?;
                }
                write!(f, "\"")
            }
            Word::MultilineFormatString(lines) => {
                for line in lines {
                    write!(f, "$ ")?;
                    for part in &line.value {
                        let escaped = format!("{part:?}");
                        let part = &escaped[1..escaped.len() - 1];
                        write!(f, "{part}")?;
                    }
                }
                Ok(())
            }
            Word::Label(Some(label)) => write!(f, "${label}"),
            Word::Label(None) => write!(f, "$_"),
            Word::Ref(r, chained) => {
                write!(f, "ref({r}")?;
                for comp in chained {
                    write!(f, "{}", comp.item)?;
                }
                write!(f, ")")
            }
            Word::IncompleteRef(path) => {
                write!(f, "incomplete_ref({}~...)", path[0].module.value)
            }
            Word::Array(arr) => arr.fmt(f),
            Word::Strand(items) => write!(f, "strand({items:?})"),
            Word::Func(func) => func.fmt(f),
            Word::Pack(pack) => pack.fmt(f),
            Word::Primitive(prim) => prim.fmt(f),
            Word::Modified(modified) => modified.fmt(f),
            Word::Spaces => write!(f, "' '"),
            Word::Comment(comment) => write!(f, "# {comment}"),
            Word::Placeholder(Some(i)) => write!(f, "^{i}"),
            Word::Placeholder(None) => write!(f, "^"),
            Word::PlaceholderN => write!(f, "^n"),
            Word::BreakLine => write!(f, "break_line"),
            Word::FlipLine => write!(f, "unbreak_line"),
            Word::SemanticComment(comment) => write!(f, "{comment}"),
            Word::OutputComment { i, n } => write!(f, "output_comment({i}/{n})"),
            Word::TypeSigComment { i } => write!(f, "type_sig_comment({i}"),
            Word::Subscripted(sub) => sub.fmt(f),
            Word::InlineMacro(mac) => {
                write!(f, "inline_macro({:?}{}))", mac.func.value, mac.ident.value)
            }
        }
    }
}

/// A refered-to item
#[derive(Clone, Serialize, Deserialize)]
pub struct Ref {
    /// The module path of the item
    pub path: Vec<RefComponent>,
    /// The name of the item
    pub name: Sp<Ident>,
}

/// A component of a reference
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefComponent {
    /// The name of the module
    pub module: Sp<Ident>,
    /// The span of the .
    pub dot_span: CodeSpan,
}

/// A component of a reference
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChainComponent {
    /// The span of the ‥
    pub dot_span: CodeSpan,
    /// The ref of the item
    pub item: Ref,
}

impl Ref {
    /// Get the span of this reference
    pub fn span(&self) -> CodeSpan {
        if let Some(comp) = self.path.first() {
            comp.module.span.clone().merge(self.name.span.clone())
        } else {
            self.name.span.clone()
        }
    }
    /// Get the number of modifier arguments this reference's name implies
    pub fn modifier_args(&self) -> usize {
        ident_modifier_args(&self.name.value)
    }
    /// Get the root module of this reference
    pub fn root_module(&self) -> Option<&Ident> {
        self.path.first().map(|c| &c.module.value)
    }
    /// Get all `Ref`s that desugar from chaining this ref with some names
    pub fn chain_refs(
        self,
        chained: impl IntoIterator<Item = ChainComponent>,
    ) -> impl Iterator<Item = Self> {
        let mut prev = self.name.clone();
        once(self).chain(chained.into_iter().map(move |comp| {
            let mut path = vec![RefComponent {
                module: prev.clone(),
                dot_span: comp.dot_span,
            }];
            path.extend(comp.item.path);
            let r = Ref {
                path,
                name: comp.item.name,
            };
            prev = r.name.clone();
            r
        }))
    }
}

impl PartialEq for Ref {
    fn eq(&self, other: &Self) -> bool {
        self.path
            .iter()
            .map(|c| &c.module.value)
            .eq(other.path.iter().map(|c| &c.module.value))
            && self.name.value == other.name.value
    }
}

impl Eq for Ref {}

impl fmt::Debug for Ref {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for comp in &self.path {
            write!(f, "{}~", comp.module.value)?;
        }
        write!(f, "{}", self.name.value)
    }
}

impl fmt::Display for Ref {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for comp in &self.path {
            write!(f, "{}~", comp.module.value)?;
        }
        write!(f, "{}", self.name.value)
    }
}

/// A stack array notation term
#[derive(Clone, Serialize, Deserialize)]
pub struct Arr {
    /// The span of preceding `↓`
    pub down_span: Option<CodeSpan>,
    /// The words in the array
    pub lines: Vec<Item>,
    /// Whether this is a box array
    pub boxes: bool,
    /// Whether a closing bracket was found
    pub closed: bool,
}

impl Arr {
    /// Get the lines that contain words
    pub fn word_lines(&self) -> impl DoubleEndedIterator<Item = &[Sp<Word>]> {
        self.lines
            .iter()
            .filter_map(|line| match line {
                Item::Words(words) => Some(words),
                _ => None,
            })
            .map(|v| v.as_slice())
    }
    /// Get the mutable lines that contain words
    pub fn word_lines_mut(&mut self) -> impl Iterator<Item = &mut Vec<Sp<Word>>> {
        self.lines.iter_mut().filter_map(|line| match line {
            Item::Words(words) => Some(words),
            _ => None,
        })
    }
}

impl fmt::Debug for Arr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut d = f.debug_tuple("arr");
        for line in &self.lines {
            match line {
                Item::Words(line) => {
                    for word in line {
                        d.field(&word.value);
                    }
                    if line.is_empty() {
                        d.field(&"newline");
                    }
                }
                item => {
                    d.field(item);
                }
            }
        }
        d.finish()
    }
}

/// An inline function
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct Func {
    /// The function's signature
    pub signature: Option<Sp<Signature>>,
    /// The function's code
    pub lines: Vec<Item>,
    /// Whether a closing parenthesis was found
    pub closed: bool,
}

impl Func {
    /// Get the lines of the function without leading or trailing empty lines
    pub fn trimmed_lines(&self) -> &[Item] {
        let mut lines = self.lines.as_slice();
        while lines.first().is_some_and(Item::is_empty_line) {
            lines = &lines[1..];
        }
        while lines.last().is_some_and(Item::is_empty_line) {
            lines = &lines[..lines.len() - 1];
        }
        lines
    }
    /// Whether the function visibly has multiple lines
    pub fn is_multiline(&self) -> bool {
        self.trimmed_lines().len() > 1
    }
    /// Get the lines that contain words
    pub fn word_lines(&self) -> impl Iterator<Item = &[Sp<Word>]> {
        self.lines
            .iter()
            .filter_map(|line| match line {
                Item::Words(words) => Some(words),
                _ => None,
            })
            .map(|v| v.as_slice())
    }
    /// Get the mutable lines that contain words
    pub fn word_lines_mut(&mut self) -> impl Iterator<Item = &mut Vec<Sp<Word>>> {
        self.lines.iter_mut().filter_map(|line| match line {
            Item::Words(words) => Some(words),
            _ => None,
        })
    }
}

impl fmt::Debug for Func {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut d = f.debug_tuple("func");
        // d.field(&self.id);
        for line in &self.lines {
            match line {
                Item::Words(line) => {
                    for word in line {
                        d.field(&word.value);
                    }
                    if line.is_empty() {
                        d.field(&"newline");
                    }
                }
                item => {
                    d.field(item);
                }
            }
        }
        d.finish()
    }
}

/// A function pack
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionPack {
    /// The span of preceding `↓`
    pub down_span: Option<CodeSpan>,
    /// Whether this is an array pack (and whether it boxes)
    pub is_array: Option<bool>,
    /// The branches of the pack
    pub branches: Vec<Sp<Func>>,
    /// Whether a closing parenthesis was found
    pub closed: bool,
}

impl FunctionPack {
    /// Iterate over the branches in lexical order
    pub fn lexical_order(&self) -> impl DoubleEndedIterator<Item = &Sp<Func>> {
        let mut branches: Vec<_> = self.branches.iter().collect();
        branches.sort_by_key(|func| func.span.start.col);
        if self.down_span.is_some() {
            branches.sort_by_key(|func| -(func.span.start.line as i32));
        } else {
            branches.sort_by_key(|func| func.span.start.line);
        }
        branches.into_iter()
    }
    /// Iterate over the branches in lexical order
    pub fn into_lexical_order(self) -> impl DoubleEndedIterator<Item = Sp<Func>> {
        let mut branches = self.branches;
        branches.sort_by_key(|func| func.span.start.col);
        if self.down_span.is_some() {
            branches.sort_by_key(|func| -(func.span.start.line as i32));
        } else {
            branches.sort_by_key(|func| func.span.start.line);
        }
        branches.into_iter()
    }
}

/// A modifier with operands
#[derive(Clone, Serialize, Deserialize)]
pub struct Modified {
    /// The modifier itself
    pub modifier: Sp<Modifier>,
    /// The operands
    pub operands: Vec<Sp<Word>>,
    /// Whether this was generated with a function pack
    pub pack_expansion: bool,
}

impl Modified {
    /// Get an iterator over the functions that are actual code
    pub fn code_operands(&self) -> impl DoubleEndedIterator<Item = &Sp<Word>> {
        self.operands.iter().filter(|word| word.value.is_code())
    }
}

impl fmt::Debug for Modified {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.modifier.value)?;
        for word in &self.operands {
            write!(f, "({:?})", word.value)?;
        }
        Ok(())
    }
}

/// A modifier
#[derive(Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value")]
pub enum Modifier {
    /// A primitive modifier
    Primitive(Primitive),
    /// A user-defined modifier
    Ref(Ref),
    /// An inline macro
    Macro(Box<InlineMacro>),
}

impl fmt::Debug for Modifier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Modifier::Primitive(prim) => prim.fmt(f),
            Modifier::Ref(refer) => write!(f, "ref({refer:?})"),
            Modifier::Macro(mac) => write!(f, "macro({:?}{})", mac.func, mac.ident),
        }
    }
}

impl fmt::Display for Modifier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Modifier::Primitive(prim) => prim.format().fmt(f),
            Modifier::Ref(refer) => write!(f, "{refer}"),
            Modifier::Macro(mac) => match ident_modifier_args(&mac.ident.value) {
                0 | 1 => write!(f, "monadic inline macro"),
                2 => write!(f, "dyadic inline macro"),
                3 => write!(f, "triadic inline macro"),
                4 => write!(f, "tetradic inline macro"),
                _ => write!(f, "inline macro"),
            },
        }
    }
}

impl Modifier {
    /// Get the number of arguments this modifier takes
    pub fn args(&self) -> usize {
        match self {
            Modifier::Primitive(prim) => prim.modifier_args().unwrap_or(0),
            Modifier::Ref(r) => r.modifier_args(),
            Modifier::Macro(mac) => ident_modifier_args(&mac.ident.value),
        }
    }
    /// Get the number of arguments this modifier takes given a subscript
    pub fn subscript_margs<N>(&self, sub: Option<&Subscript<N>>) -> usize {
        match self {
            Modifier::Primitive(prim) => prim.subscript_margs(sub).unwrap_or_else(|| self.args()),
            m => m.args(),
        }
    }
}

/// An argument setter
#[derive(Clone, Serialize, Deserialize)]
pub struct ArgSetter {
    /// The name of the field
    pub ident: Sp<Ident>,
    /// The span of the colon
    pub colon_span: CodeSpan,
}

impl fmt::Debug for ArgSetter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:", self.ident.value)
    }
}

impl ArgSetter {
    /// Get the full span
    pub fn span(&self) -> CodeSpan {
        self.ident.span.clone().merge(self.colon_span.clone())
    }
}

/// A subscripted word
#[derive(Clone, Serialize, Deserialize)]
pub struct Subscripted {
    /// The subscript
    pub script: Sp<SubscriptToken>,
    /// The modified word
    pub word: Sp<Word>,
}

impl fmt::Debug for Subscripted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.word.value.fmt(f)?;
        write!(f, "{}", self.script.value)
    }
}

/// A number word
#[derive(Clone, PartialEq, Serialize, Deserialize)]
#[allow(missing_docs)]
pub enum NumWord {
    Real(f64),
    Infinity(bool),
    Complex(Complex),
    Err(String),
    #[cfg(feature = "multivector")]
    Blade(crate::Multivector),
}

impl From<f64> for NumWord {
    fn from(value: f64) -> Self {
        Self::Real(value).normalize()
    }
}

#[cfg(feature = "multivector")]
impl From<crate::Multivector> for NumWord {
    fn from(mv: crate::Multivector) -> Self {
        Self::Blade(mv).normalize()
    }
}

impl From<SubscriptNumber> for NumWord {
    fn from(sn: SubscriptNumber) -> Self {
        match sn {
            SubscriptNumber::Int(i) => NumWord::Real(i.into()),
            SubscriptNumber::I => NumWord::Complex(Complex::I),
            SubscriptNumber::NegI => NumWord::Complex(-Complex::I),
            SubscriptNumber::R => NumWord::Complex(Complex::ONE),
            SubscriptNumber::NegR => NumWord::Complex(-Complex::ONE),
        }
    }
}

impl From<Complex> for NumWord {
    fn from(value: Complex) -> Self {
        Self::Complex(value)
    }
}

impl From<Result<f64, String>> for NumWord {
    fn from(value: Result<f64, String>) -> Self {
        match value {
            Ok(v) => v.into(),
            Err(e) => Self::Err(e),
        }
    }
}

impl From<Result<Complex, String>> for NumWord {
    fn from(value: Result<Complex, String>) -> Self {
        match value {
            Ok(v) => Self::Complex(v),
            Err(e) => Self::Err(e),
        }
    }
}

#[cfg(feature = "multivector")]
impl From<Result<crate::Multivector, String>> for NumWord {
    fn from(mv: Result<crate::Multivector, String>) -> Self {
        match mv {
            Ok(v) => Self::Blade(v),
            Err(e) => Self::Err(e),
        }
    }
}

impl NumWord {
    fn normalize(self) -> Self {
        match self {
            Self::Real(f64::INFINITY) => Self::Infinity(false),
            Self::Real(f64::NEG_INFINITY) => Self::Infinity(true),
            _ => self,
        }
    }
    /// Map the number with another
    pub fn map_with<R, C>(
        self,
        other: Self,
        real: impl FnOnce(f64, f64) -> R,
        complex: impl FnOnce(Complex, Complex) -> C,
    ) -> Self
    where
        C: Into<Self>,
        R: Into<Self>,
    {
        match (self, other) {
            (Self::Real(a), Self::Real(b)) => real(a, b).into(),
            (Self::Infinity(false), b) => Self::Real(f64::INFINITY).map_with(b, real, complex),
            (Self::Infinity(true), b) => Self::Real(f64::NEG_INFINITY).map_with(b, real, complex),
            (a, Self::Infinity(false)) => a.map_with(Self::Real(f64::INFINITY), real, complex),
            (a, Self::Infinity(true)) => a.map_with(Self::Real(f64::NEG_INFINITY), real, complex),
            (Self::Complex(a), Self::Complex(b)) => complex(a, b).into(),
            (Self::Real(a), Self::Complex(b)) => complex(a.into(), b).into(),
            (Self::Complex(a), Self::Real(b)) => complex(a, b.into()).into(),
            (Self::Err(e), _) | (_, Self::Err(e)) => Self::Err(e),
            #[cfg(feature = "multivector")]
            (Self::Blade(_), _) | (_, Self::Blade(_)) => Self::Err(
                "Attempted to map multivector token with another. \
                This is a bug in the interpreter"
                    .into(),
            ),
        }
        .normalize()
    }
}

impl fmt::Debug for NumWord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl fmt::Display for NumWord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NumWord::Real(r) => write!(f, "{r}"),
            NumWord::Infinity(false) => write!(f, ""),
            NumWord::Infinity(true) => write!(f, "-∞"),
            NumWord::Complex(c) => write!(f, "{c}"),
            #[cfg(feature = "multivector")]
            NumWord::Blade(mv) => write!(f, "{mv}"),
            NumWord::Err(e) => write!(f, "error({e})"),
        }
    }
}