uiua_parser 0.17.0-rc.2

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
//! Splitting primitive names

use std::{collections::HashMap, fmt, sync::LazyLock};

use enum_iterator::Sequence;

use crate::{ast::NumWord, Complex, SysOp};

use super::Primitive;

static ALIASES: LazyLock<HashMap<Primitive, &[&str]>> = LazyLock::new(|| {
    [
        (Primitive::Identity, &["id"] as &[_]),
        (Primitive::Gap, &["ga"]),
        (Primitive::Pop, &["po"]),
        (Primitive::Fix, &["fx"]),
        (Primitive::Box, &["bx"]),
        (Primitive::MemberOf, &["elem"]),
        (Primitive::IndexIn, &["idx"]),
        (Primitive::ProgressiveIndexOf, &["pidx"]),
        (Primitive::Switch, &["sw"]),
        (Primitive::Stencil, &["st"]),
        (Primitive::Floor, &["flr", "flor"]),
        (Primitive::Range, &["ran"]),
        (Primitive::Partition, &["par"]),
        (Primitive::Dup, &["dup"]),
        (Primitive::Deshape, &["flat"]),
        (Primitive::Ne, &["ne", "neq"]),
        (Primitive::Eq, &["eq"]),
        (Primitive::Lt, &["lt"]),
        (Primitive::Le, &["le", "leq"]),
        (Primitive::Gt, &["gt"]),
        (Primitive::Ge, &["ge", "geq"]),
        (Primitive::Utf8, &["utf"]),
        (Primitive::First, &["fst"]),
        (Primitive::Last, &["lst"]),
        (Primitive::Slf, &["slf"]),
        (Primitive::Select, &["sel"]),
        (Primitive::Parse, &["prs"]),
        (Primitive::Rand, &["rnd"]),
        (Primitive::Voxels, &["project"]),
    ]
    .into()
});

/// A numeric syntax component that can be parsed along with primitive names
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Sequence)]
pub enum NumComponent {
    /// The real complex unit
    R,
    /// The imaginary complex unit
    I,
}

/// A parsed primitive component
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Sequence)]
pub enum PrimComponent {
    /// A primitive
    Prim(Primitive),
    /// A numeric component
    Num(NumComponent),
    /// Subscript 0
    Sub0,
    /// Subscript 2
    Sub2,
}

impl From<Primitive> for PrimComponent {
    fn from(prim: Primitive) -> Self {
        PrimComponent::Prim(prim)
    }
}

impl From<NumComponent> for PrimComponent {
    fn from(num: NumComponent) -> Self {
        PrimComponent::Num(num)
    }
}

impl PrimComponent {
    /// Get the name of this component
    pub fn name(&self) -> &'static str {
        match self {
            PrimComponent::Prim(prim) => prim.name(),
            PrimComponent::Num(num) => num.name(),
            PrimComponent::Sub0 => "â‚€",
            PrimComponent::Sub2 => "â‚‚",
        }
    }
    /// Try to parse a component from a name prefix
    pub fn from_format_name(name: &str) -> Option<Self> {
        (Primitive::from_format_name(name).map(Into::into))
            .or_else(|| NumComponent::from_format_name(name).map(Into::into))
    }
}

impl NumComponent {
    /// Get the name of this numeric component
    pub fn name(&self) -> &'static str {
        use NumComponent::*;
        match self {
            R => "r",
            I => "i",
        }
    }
    /// Get the number value
    pub fn value(&self) -> NumWord {
        use NumComponent::*;
        match self {
            R => Complex::ONE.into(),
            I => Complex::I.into(),
        }
    }
    /// Try to parse a numeric component from a name prefix
    pub fn from_format_name(name: &str) -> Option<Self> {
        use NumComponent::*;
        Some(match name {
            "r" => R,
            "i" => I,
            _ => return None,
        })
    }
}

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

impl fmt::Display for PrimComponent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PrimComponent::Prim(prim) => prim.fmt(f),
            PrimComponent::Num(num) => num.fmt(f),
            PrimComponent::Sub0 | PrimComponent::Sub2 => self.name().fmt(f),
        }
    }
}

impl Primitive {
    /// Get the short aliases for this primitive
    pub fn aliases(&self) -> &'static [&'static str] {
        ALIASES.get(self).copied().unwrap_or_default()
    }
    /// Try to parse a primitive from a name prefix
    pub fn from_format_name(name: &str) -> Option<Self> {
        if name.chars().any(char::is_uppercase) {
            return None;
        }
        if name.len() < 2 {
            return None;
        }
        static REVERSE_ALIASES: LazyLock<HashMap<&'static str, Primitive>> = LazyLock::new(|| {
            ALIASES
                .iter()
                .flat_map(|(prim, aliases)| aliases.iter().map(|&s| (s, *prim)))
                .collect()
        });
        if let Some(prim) = REVERSE_ALIASES.get(name) {
            return Some(*prim);
        }
        if let Some(prim) = Primitive::non_deprecated().find(|p| p.name() == name) {
            return Some(prim);
        }
        if let Some(prim) = Primitive::all().find(|p| p.glyph().is_none() && p.name() == name) {
            return Some(prim);
        }
        if let Some(prim) = SysOp::ALL.iter().find(|s| s.name() == name) {
            return Some(Primitive::Sys(*prim));
        }
        if name.len() < 3 {
            return None;
        }
        let mut matching = Primitive::non_deprecated()
            .filter(|p| p.glyph().is_some() && p.name().starts_with(name));
        let res = matching.next()?;
        let exact_match = res.name() == name;
        (exact_match || matching.next().is_none()).then_some(res)
    }
    /// The list of strings where each character maps to an entire primitive
    pub fn multi_aliases() -> &'static [(&'static str, &'static [(PrimComponent, &'static str)])] {
        use Primitive::*;
        macro_rules! alias {
            ($(($s:ident, $prim:expr)),* $(,)*) => {
                (
                    concat!($(stringify!($s)),*),
                    &[$((PrimComponent::Prim($prim), stringify!($s))),*]
                )
            }
        }
        &[
            alias!((a, Assert), (w, With), (m, Match)),
            alias!((d, Div), (o, On), (r, Range)),
            alias!((p, Partition), (b, Box), (b, By), (n, Ne)),
            alias!((p, Partition), (p, Parse), (b, By), (n, Ne)),
            alias!((p, Partition), (i, Identity), (b, By), (n, Ne)),
            alias!((k, Keep), (b, By), (n, Ne)),
            alias!((f, Fork), (t, Take), (d, Drop)),
            alias!((f, Fork), (d, Drop), (t, Take)),
            alias!((d, Drop), (n, Neg), (o, On), (d, Drop)),
            alias!(
                (a, Anti),
                (d, Drop),
                (n, Neg),
                (o, On),
                (a, Anti),
                (d, Drop)
            ),
            alias!((p, Dip), (e, Pop), (r, Under), (f, Now)),
            alias!((s, Un), (et, By)),
            alias!((wr, Sub), (en, By), (ch, Not)),
            alias!((sel, Select), (first, First)),
            alias!((l, Un), (og, Exp)),
            alias!((wi, Stencil), (n, Identity)),
            (
                "kork",
                &[
                    (PrimComponent::Prim(Keep), "kor"),
                    (PrimComponent::Sub2, "k"),
                ],
            ),
            (
                "each",
                &[
                    (PrimComponent::Prim(Rows), "eac"),
                    (PrimComponent::Sub0, "h"),
                ],
            ),
        ]
    }
    /// Look up a multi-alias from [`Self::multi_aliases`]
    pub fn get_multi_alias(name: &str) -> Option<&'static [(PrimComponent, &'static str)]> {
        Self::multi_aliases()
            .iter()
            .find(|(alias, _)| *alias == name)
            .map(|(_, aliases)| *aliases)
    }
}

/// Try to parse multiple primitives from the concatenation of their name prefixes
pub fn split_name(name: &str) -> Option<Vec<(PrimComponent, &str)>> {
    let mut indices: Vec<usize> = name.char_indices().map(|(i, _)| i).collect();
    indices.push(name.len());
    // Forward parsing
    let mut prims = Vec::new();
    let mut start = 0;
    'outer: loop {
        if start == indices.len() {
            return Some(prims);
        }
        let start_index = indices[start];
        for len in (1..=indices.len() - start).rev() {
            let end_index = indices.get(start + len).copied().unwrap_or(name.len());
            if start_index == end_index {
                continue;
            }
            let sub_name = &name[start_index..end_index];
            // Normal primitive matching
            if let Some(p) = PrimComponent::from_format_name(sub_name) {
                if sub_name.len() > 1 || p.name().len() == 1 {
                    prims.push((p, sub_name));
                    start += len;
                    continue 'outer;
                }
            }
            // Greek
            if sub_name.chars().count() == 1 {
                for prim in [Primitive::Eta, Primitive::Pi, Primitive::Tau] {
                    if sub_name.chars().next() == prim.glyph() {
                        prims.push((prim.into(), sub_name));
                        start += len;
                        continue 'outer;
                    }
                }
            }
            if sub_name.len() == 1 {
                continue;
            }
            // 1-letter planet notation
            let unforked = sub_name.strip_prefix('f').unwrap_or(sub_name);
            if unforked
                .strip_suffix(['i', 'p', 'f'])
                .unwrap_or(unforked)
                .chars()
                .all(|c| "gd".contains(c))
            {
                for (i, c) in sub_name.char_indices() {
                    let prim = match c {
                        'f' if i == 0 => Primitive::Fork,
                        'f' => Primitive::Fix,
                        'g' => Primitive::Gap,
                        'd' => Primitive::Dip,
                        'i' => Primitive::Identity,
                        'p' => Primitive::Pop,
                        _ => unreachable!(),
                    };
                    prims.push((prim.into(), &sub_name[i..i + 1]))
                }
                start += len;
                continue 'outer;
            }
            // Aliases
            if let Some(ps) = Primitive::get_multi_alias(sub_name) {
                prims.extend(ps.iter().map(|(p, s)| (*p, *s)));
                start += len;
                continue 'outer;
            }
        }
        break;
    }
    // Backward parsing
    prims.clear();
    let mut end = indices.len() - 1;
    'outer: loop {
        if end == 0 {
            prims.reverse();
            return Some(prims);
        }
        let end_index = indices[end];
        for len in (1..=end).rev() {
            let start_index = indices.get(end - len).copied().unwrap_or(0);
            let sub_name = &name[start_index..end_index];
            // Normal primitive matching
            if let Some(p) = Primitive::from_format_name(sub_name) {
                if sub_name.len() > 1 || p.name().len() == 1 {
                    prims.push((p.into(), sub_name));
                    end -= len;
                    continue 'outer;
                }
            }
            // Greek
            if sub_name.chars().count() == 1 {
                for prim in [Primitive::Eta, Primitive::Pi, Primitive::Tau] {
                    if sub_name.chars().next() == prim.glyph() {
                        prims.push((prim.into(), sub_name));
                        end -= len;
                        continue 'outer;
                    }
                }
            }
            if sub_name.len() == 1 {
                continue;
            }
            // 1-letter planet notation
            if sub_name
                .strip_prefix('f')
                .unwrap_or(sub_name)
                .strip_suffix(['i', 'p'])
                .unwrap_or(sub_name)
                .chars()
                .all(|c| "gd".contains(c))
                && sub_name != "fi"
            {
                for (i, c) in sub_name.char_indices().rev() {
                    let prim = match c {
                        'f' => Primitive::Fork,
                        'g' => Primitive::Gap,
                        'd' => Primitive::Dip,
                        'i' => Primitive::Identity,
                        'p' => Primitive::Pop,
                        _ => unreachable!(),
                    };
                    prims.push((prim.into(), &sub_name[i..i + 1]))
                }
                end -= len;
                continue 'outer;
            }
            // Dip fix
            if sub_name
                .strip_suffix('f')
                .unwrap_or(sub_name)
                .chars()
                .all(|c| c == 'd')
            {
                for (i, c) in sub_name.char_indices().rev() {
                    let prim = match c {
                        'd' => Primitive::Dip,
                        'f' => Primitive::Fix,
                        _ => unreachable!(),
                    };
                    prims.push((prim.into(), &sub_name[i..i + 1]))
                }
                end -= len;
                continue 'outer;
            }
            // Aliases
            if let Some(ps) = Primitive::get_multi_alias(sub_name) {
                prims.extend(ps.iter().rev().map(|(p, s)| (*p, *s)));
                end -= len;
                continue 'outer;
            }
            // Greek
            if sub_name.chars().count() == 1 {
                for prim in [Primitive::Eta, Primitive::Pi, Primitive::Tau] {
                    if sub_name.chars().next() == prim.glyph() {
                        prims.push((prim.into(), sub_name));
                        end -= len;
                        continue 'outer;
                    }
                }
            }
        }
        break;
    }
    None
}