lexigram-lib 0.10.0

Full library of the lexigram lexer/parser generator
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
// Copyright (c) 2025 Redglyph (@gmail.com). All Rights Reserved.

use std::collections::{BTreeSet, HashMap};
use std::ops::Deref;
use iter_index::IndexerIterator;
use vectree::VecTree;

// exposes lexigram-core:
pub use lexigram_core;
pub use lexigram_core::{AltId, TokenId, VarId};
pub use lexigram_core::CollectJoin;
pub use lexigram_core::alt;
pub use lexigram_core::fixed_sym_table;
pub use lexigram_core::log;
pub use lexigram_core::char_reader;
use lexigram_core::CharLen;
pub use lexigram_core::segmap;
pub use lexigram_core::seg;
pub use lexigram_core::lexer;
pub use lexigram_core::parser;

mod macros;
mod adaptors;
mod cproduct;
pub mod build;
pub mod segments;
pub mod dfa;
pub mod lexergen;
pub mod lexi;
pub mod grammar;
pub mod parsergen;
pub mod file_utils;
mod name_fixer;
pub use name_fixer::{NameFixer, NameTransformer};
mod symbol_table;
pub mod rtsgen;
mod tests;

pub use symbol_table::SymbolTable;

// package name & version
pub const LIB_PKG_NAME: &str = env!("CARGO_PKG_NAME");
pub const LIB_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");

// Regular expressions / DFA, See:
// - https://blog.burntsushi.net/regex-internals/
// - https://en.wikipedia.org/wiki/Tagged_Deterministic_Finite_Automaton
// - https://arxiv.org/abs/2206.01398
//
// See also:
// - Ref: https://en.wikipedia.org/wiki/Comparison_of_parser_generators
//
// UTF-8:
// - https://www.ibm.com/docs/en/db2/11.5?topic=support-unicode-character-encoding
// - std::char::encode_utf8_raw(...)
//
// Misc
// - https://re2c.org/
// - https://www.genivia.com/get-reflex.html
// - https://nothings.org/computer/lexing.html
// - https://github.com/maciejhirsz/logos
// - https://alic.dev/blog/fast-lexing

// ---------------------------------------------------------------------------------------------
// Shared types

/// Unit type used as generic parameter to indicate general, non-normalized form.
///
/// - `Dfa<General>` may have accepting states with IDs smaller than non-accepting states' IDs, or non-incremntal IDs.
/// - `RuleTreeSet<General>` may include any operators like `*`, `+`, and `?`, and doesn't have a restriction on depth.
/// - `ProdRuleSet<General>` may be ambiguous, left-recursive, and/or need left factorization, depending on the target.
#[derive(Clone, Debug)]
pub struct General;

// `ProdRuleSet<LL>` has rules that aren't left-recursive and are left-factorized.
// #[derive(Clone, Debug)]
// pub struct LL1;
pub use lexigram_core::LL1;

/// `ProdRuleSet<LR>` is used to create bottom-up parsers.
#[derive(Clone, Debug)]
pub struct LR;

// [`LRParserTables<LALR>`](parsergen::lr::LRParserTables<LALR>) is built from `ProdRuleSet<LR>`
// #[derive(Clone, Debug)]
// pub struct LALR;
pub use lexigram_core::LALR;
use lexigram_core::lexer::{CaretCol, Pos, PosSpan};
use lexigram_core::parser::ParserToken;

pub use make_stream::{make_stream, MakeStreamIterator};

/// Unit type used as generic parameter to indicate normalized form.
///
/// - `Dfa<Normalized>` always has incremental state numbers, starting at 0, with all the accepting states at the end.
/// - `RuleTreeSet<Normalized>` only has `|`, `&`, and symbols, and must have one of the 3 following patterns:
///   - a symbol
///   - a `&` with only symbols as children
///   - a `|` with only `&(symbols)` or symbols as children
#[derive(Clone, Debug)]
pub struct Normalized;

// ---------------------------------------------------------------------------------------------
// General helper functions

/// Gathers `iter_item` in a vector and pushes it into `v`.
pub(crate) fn vaddi<I, T>(v: &mut Vec<Vec<T>>, iter_item: I) -> usize
    where I: IntoIterator<Item=T> + Clone
{
    let new_index = v.len();
    v.push(Vec::from_iter(iter_item));
    new_index
}

/// Takes `lines` of columns and outputs lines of strings in which the columns
/// are aligned. The minimum width of each column can be preset with the optional `min_widths` vector.
///
/// The final width of each column is the 1 + maximum number of characters - not bytes - of the strings
/// representing that column in all the lines (the +1 makes sure columns are separated by at least one
/// space). The last column is left as-is; no spaces are added to adjust its width.
pub fn columns_to_str(cols: Vec<Vec<String>>, min_widths: Option<Vec<usize>>) -> Vec<String> {
    let min_widths = min_widths.unwrap_or(vec![0; cols.first().map(|v| v.len()).unwrap_or(0)]);
    let ncol = min_widths.len();
    let mut width = cols.iter().fold(min_widths, |acc, s| {
        assert_eq!(s.len(), ncol, "number of columns is not consistently {ncol}");
        acc.into_iter().zip(s).map(|(a, s)| a.max(s.charlen() + 1)).collect()
    });
    if let Some(x) = width.last_mut() { *x = 0 };
    cols.into_iter().map(|v| v.into_iter().zip(&width).map(|(mut s, w)| {
        for _ in 0..w.saturating_sub(s.charlen()) { s.push(' ') }
        s
    }).collect::<String>()).collect()
}

pub fn indent_source(parts: Vec<Vec<String>>, indent: usize) -> String {
    // SAFETY: ' ' is ASCII, and `indent` is >= 0
    let s = unsafe { String::from_utf8_unchecked(vec![32; indent]) };
    let mut source = String::new();
    let mut first = true;
    for part in parts {
        if !first {
            source.push('\n');
        }
        first = false;
        for string in part {
            for line in string.split("\n") {
                let cured_line = line.trim_end();
                if !cured_line.is_empty() {
                    source.push_str(&s);
                }
                source.push_str(cured_line);
                source.push('\n');
            }
        }
    }
    source
}

mod make_stream {
    use std::str::SplitAsciiWhitespace;
    use iter_index::Indexer;
    use super::*;

    /// Makes a stream for the parser from an input string and basic token information.
    ///
    /// For tests purposes only.
    ///
    /// The caret information is very crude:
    /// the column increments on each token, and the line remains at 1. All space characters are discarded and used to separate tokens,
    /// so there must be at least one space between each token.
    ///
    /// Arguments:
    /// * [tokens]: Iterable of `(&str, Option<&str>)`, or something that can be converted to it; e.g. the `SYMBOLS_T` generated by
    ///   Lexigram is fine.
    ///   * The first `&str` is the **name** of the token used in the grammar,
    ///   * the `Option<&str>` is the **fixed value** it scans (like a keyword) or `None` if it's variable (like an identifier or a number).
    /// * [include_tnames]: When true, the token names are used to scan the input when the fixed value doesn't exist. When false,
    ///   only the fixed values are used to scan the input.
    /// * [id]: The [TokenId] of an identifier: anything that isn't in the `Option<&str>` items and which starts with a non-digit will
    ///   be converted into that token. Put a very large number if not used.
    /// * [num]: The [TokenId] of a number: anything starting with a digit which isn't in the `Option<&str>` items will be converted into
    ///   that token. Put a very large number if not used.
    /// * [verbose]: When true, prints out the tokens as they're issued.
    ///
    /// ## Example
    ///
    /// This example will stream tokens `A`, `Id(a)`, `Id(b)`, `Id(c)`, `C`:
    /// ```ignore
    /// use lexigram_lib::make_stream;
    ///
    /// static SYMBOLS_T: [(&str, Option<&str>); 3] = [("A", None), ("C", None), ("Id", None)];
    /// // ...
    ///
    /// let stream = make_stream("A a b c C", SYMBOLS_T, true, 2, 9999, false);
    /// let mut listener = Listener::new();
    /// let mut wrapper = Wrapper::new(listener, false);
    /// let result = parser.parse_stream(&mut wrapper, stream);
    /// ```
    pub fn make_stream<S, T>(
        input: &str,
        tokens: T,
        include_tnames: bool,
        id: Option<TokenId>,
        num: Option<TokenId>,
        verbose: bool
    ) -> impl Iterator<Item=ParserToken>
    where
        S: std::hash::Hash + Eq + std::borrow::Borrow<str>,
        T: IntoIterator<Item=(S, Option<S>)>,
    {
        MakeStreamIterator::new(input, tokens, include_tnames, id, num, verbose)
    }

    enum MakeStreamMode { Token, Error(String, PosSpan), Eof }

    pub struct MakeStreamIterator<'s, S> {
        items: Indexer<SplitAsciiWhitespace<'s>, CaretCol>,
        mode: MakeStreamMode,
        symbols: HashMap<S, TokenId>,
        id: Option<TokenId>,
        num: Option<TokenId>,
        verbose: bool
   }

    impl<'s, S> MakeStreamIterator<'s, S>
    where
        S: std::hash::Hash + Eq + std::borrow::Borrow<str>,
    {
        pub fn new<T: IntoIterator<Item=(S, Option<S>)>> (
            input: &'s str,
            tokens: T,
            include_tnames: bool,
            id: Option<TokenId>,
            num: Option<TokenId>,
            verbose: bool
        ) -> Self {
            let symbols: HashMap<S, TokenId> = tokens.into_iter().index::<TokenId>()
                .filter_map(|(t, (s, fixed_maybe))|
                    if let Some(fixed) = fixed_maybe {
                        Some((fixed, t))
                    } else {
                        if include_tnames {
                            Some((s, t))
                        } else {
                            None
                        }
                    })
                .collect::<HashMap<_, _>>();
            MakeStreamIterator {
                items: input.split_ascii_whitespace().index_start::<CaretCol>(1),
                mode: MakeStreamMode::Token,
                symbols,
                id,
                num,
                verbose
            }
        }
    }

    impl<S> Iterator for MakeStreamIterator<'_, S>
    where
        S: std::hash::Hash + Eq + std::borrow::Borrow<str>,
    {
        type Item = ParserToken;

        fn next(&mut self) -> Option<Self::Item> {
            let next = match &mut self.mode {
                MakeStreamMode::Token => {
                    if let Some((pos, w)) = self.items.next() {
                        let pos_span = PosSpan::new(Pos(1, pos), Pos(1, pos));
                        if let Some(s) = self.symbols.get(w) {
                            Some((*s, w.to_string(), pos_span))
                        } else if let Some(num) = self.num && w.chars().next().unwrap().is_ascii_digit() {
                            Some((num, w.to_string(), pos_span))
                        } else if let Some(id) = self.id && w.chars().next().unwrap().is_ascii_alphabetic() {
                            Some((id, w.to_string(), pos_span))
                        } else {
                            self.mode = MakeStreamMode::Error(
                                format!("invalid character {w:?} at {pos_span}"),
                                pos_span
                            );
                            None
                        }
                    } else {
                        self.mode = MakeStreamMode::Eof;
                        None
                    }
                }
                MakeStreamMode::Error(msg, pos_span) => {
                    let parser_token = (TokenId::MAX, std::mem::take(msg), std::mem::take(pos_span));
                    self.mode = MakeStreamMode::Token;
                    Some(parser_token)
                }
                MakeStreamMode::Eof => None,
            };
            if self.verbose {
                if let Some((token, str, pos)) = &next {
                    println!(">> token {token}: {str:?} at {pos}");
                } else {
                    println!(">> None");
                }
            }
            next
        }
    }
}

// ---------------------------------------------------------------------------------------------
// Source generation helper traits and types

/// Adds empty lines between blocks of text
pub trait SourceSpacer {
    /// Adds an empty string to the vector, but only if the last vector string isn't empty. If the vector is
    /// empty, doesn't add anything.
    fn add_space(&mut self);
}

impl SourceSpacer for Vec<String> {
    fn add_space(&mut self) {
        if let Some(line) = self.last() {
            if !line.is_empty() {
                self.push("".to_string());
            }
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct StructLibs {
    libs: BTreeSet<String>
}

impl StructLibs {
    pub fn new() -> Self {
        StructLibs::default()
    }

    pub fn add<T: Into<String>>(&mut self, lib: T) {
        self.libs.insert(lib.into());
    }

    pub fn extend<I: IntoIterator<Item=T>, T: Into<String>>(&mut self, libs: I) {
        self.libs.extend(libs.into_iter().map(|s| s.into()));
    }

    #[cfg(test)]
    fn tree_to_string(t: &VecTree<String>, idx: usize) -> String {
        let children = t.children(idx).iter().map(|child| {
            if t.children(*child).len() > 0 {
                format!("{}[{}]", t.get(*child), Self::tree_to_string(t, *child))
            } else {
                t.get(*child).to_string()
            }
        }).to_vec();
        children.join(", ")
    }

    fn to_tree(&self) -> VecTree<String> {
        let mut tree = VecTree::new();
        let root = tree.add_root(String::new());
        for lib in &self.libs {
            let mut idx = root;
            for md in lib.split("::") {
                idx = tree.children(idx).iter()
                    .find_map(|&i| {
                        if tree.get(i) == md { Some(i) } else { None }
                    })
                    .unwrap_or_else(|| {
                        tree.add(Some(idx), md.to_string())
                    });
            }
            tree.add(Some(idx), "self".to_string());
        }
        tree
    }

    pub fn gen_source_code(&self) -> Vec<String> {
        let mut stack = Vec::<Vec<String>>::new();
        let tree = self.to_tree();
        for node in tree.iter_post_depth_simple() {
            if node.depth as usize >= stack.len() && node.depth > 0 {
                while node.depth as usize > stack.len() {
                    stack.push(vec![]);
                }
                stack.last_mut().unwrap().push(node.to_string())
            } else if node.depth > 0 {
                let sub = stack.pop().unwrap();
                stack.last_mut().unwrap().push(
                    if sub.len() > 1 {
                        format!("{}::{{{}}}", node.deref(), sub.join(", "))
                    } else if sub.last().unwrap() == "self" {
                        node.deref().to_string()
                    } else {
                        format!("{}::{}", node.deref(), sub[0])
                    });
            }
        }
        stack.pop().unwrap_or(vec![]).into_iter().map(|s| format!("use {s};")).to_vec()
    }
}

// ---------------------------------------------------------------------------------------------

#[cfg(test)]
mod libtests {
    use lexigram_core::CharLen;
    use super::*;
    use lexigram_core::log::{BufLog, Logger};
    use crate::build::{BuildError, BuildErrorSource};

    #[test]
    fn test_column_to_str() {
        let a = vec![
            vec!["1".to_string(), "2".to_string()],
            vec!["◄10".to_string(), "20".to_string()],
            vec!["100".to_string(), "200".to_string()],
        ];
        let b = vec![
            vec!["1".to_string(), "◄20".to_string(), "3000".to_string()],
            vec!["10".to_string(), "2000".to_string(), "3".to_string()],
            vec!["1000".to_string(), "2".to_string(), "300".to_string()],
        ];
        let tests = vec![
            (a.clone(), Some(vec![2, 0]), "1   2\n◄10 20\n100 200"),
            (a, None, "1   2\n◄10 20\n100 200"),
            (b.clone(), Some(vec![3, 2, 0]), "1    ◄20  3000\n10   2000 3\n1000 2    300"),
            (b, Some(vec![8, 2, 0]), "1       ◄20  3000\n10      2000 3\n1000    2    300"),
            (vec![], Some(vec![]), ""),
            (vec![], Some(vec![1, 2, 3]), ""),
            (vec![], None, ""),
        ];
        for (i, (v, w, expected)) in tests.into_iter().enumerate() {
            let result_v = columns_to_str(v, w);
            let result = result_v.join("\n");
            assert_eq!(result, expected, "failed with test {i}")
        }
    }

    #[test]
    fn test_col_to_string() {
        let x = std::collections::BTreeSet::<u32>::from([10, 20, 25]);
        assert_eq!(x.iter().join(", "), "10, 20, 25");
    }

    #[test]
    fn test_to_vec() {
        assert_eq!((0..5).to_vec(), vec![0, 1, 2, 3, 4]);
    }

    #[test]
    fn test_charlen() {
        assert_eq!("".charlen(), 0);
        assert_eq!("12345".charlen(), 5);
        assert_eq!("◄123►".to_string().charlen(), 5);
    }

    #[test]
    fn test_add_space() {
        let mut src = Vec::<String>::new();
        src.add_space();
        assert!(src.is_empty());
        src.push("1".to_string());
        assert_eq!(src, vec!["1".to_string()]);
        src.add_space();
        assert_eq!(src, vec!["1".to_string(), "".to_string()]);
        src.add_space();
        assert_eq!(src, vec!["1".to_string(), "".to_string()]);
        src.push("2".to_string());
        assert_eq!(src, vec!["1".to_string(), "".to_string(), "2".to_string()]);
        src.add_space();
        assert_eq!(src, vec!["1".to_string(), "".to_string(), "2".to_string(), "".to_string()]);
        src.add_space();
        assert_eq!(src, vec!["1".to_string(), "".to_string(), "2".to_string(), "".to_string()]);
    }

    #[test]
    fn test_struct_libs() {
        const VERBOSE: bool = false;
        let mut l = StructLibs::new();
        let l1 = ["a", "a::a1", "a::b1", "a::a1::a2", "a::a1::b2"];
        let l2 = vec!["a::a1::a2::a3"];
        let l3 = vec!["a::c1::a2".to_string()];
        l.extend(l1);
        l.add("b");
        l.extend(l2);
        l.extend(l3);
        let tree = l.to_tree();
        if VERBOSE {
            println!("{}", tree.iter_post_depth_simple().map(|n| format!("({}){}", n.depth, n.deref())).join(", "));
            println!("{}", StructLibs::tree_to_string(&tree, tree.get_root().unwrap()));
        }
        let src = l.gen_source_code();
        if VERBOSE {
            println!("{}", src.join("\n"));
        }
        assert_eq!(src, ["use a::{self, a1::{self, a2::{self, a3}, b2}, b1, c1::a2};", "use b;"]);

        let src_empty = StructLibs::new().gen_source_code();
        assert_eq!(src_empty, Vec::<String>::new());
    }

    #[test]
    fn test_build_error() {
        fn build() -> Result<(), BuildError> {
            let mut log = BufLog::new();
            log.add_error("the test generated a fake error successfully");
            Err(BuildError::new(log, BuildErrorSource::ParserGen))
        }
        let err = build().err().expect("build() should return an error");
        assert_eq!(err.to_string(), "Errors have occurred in ParserGen:\n- ERROR  : the test generated a fake error successfully\n");
    }
}

// ---------------------------------------------------------------------------------------------