lling-llang 0.1.0

WFST framework for text normalization and grammar correction
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
//! Context-free grammar representation.

use std::fmt;

use rustc_hash::FxHashMap;
use smallvec::SmallVec;

use super::types::{NonTerminal, RuleId, Symbol, Terminal};

/// A production rule in the grammar.
///
/// Represents a rule of the form: LHS → RHS₁ RHS₂ ... RHSₙ
#[derive(Clone, Debug)]
pub struct Production {
    /// Rule identifier.
    pub id: RuleId,
    /// Left-hand side (non-terminal being defined).
    pub lhs: NonTerminal,
    /// Right-hand side (sequence of symbols).
    pub rhs: SmallVec<[Symbol; 4]>,
    /// Log probability of this production (for PCFG).
    pub log_prob: f32,
}

impl Production {
    /// Create a new production.
    pub fn new(id: RuleId, lhs: NonTerminal, rhs: SmallVec<[Symbol; 4]>) -> Self {
        Self {
            id,
            lhs,
            rhs,
            log_prob: 0.0,
        }
    }

    /// Create a production with a probability.
    pub fn with_prob(
        id: RuleId,
        lhs: NonTerminal,
        rhs: SmallVec<[Symbol; 4]>,
        log_prob: f32,
    ) -> Self {
        Self {
            id,
            lhs,
            rhs,
            log_prob,
        }
    }

    /// Check if this is an epsilon production (A → ε).
    pub fn is_epsilon(&self) -> bool {
        self.rhs.is_empty() || (self.rhs.len() == 1 && self.rhs[0].is_epsilon())
    }

    /// Get the length of the right-hand side.
    pub fn rhs_len(&self) -> usize {
        if self.is_epsilon() {
            0
        } else {
            self.rhs.len()
        }
    }

    /// Get the symbol at a given position in the RHS.
    pub fn rhs_at(&self, pos: usize) -> Option<&Symbol> {
        self.rhs.get(pos)
    }
}

impl fmt::Display for Production {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.lhs)?;
        if self.rhs.is_empty() {
            write!(f, " ε")?;
        } else {
            for sym in &self.rhs {
                write!(f, " {}", sym)?;
            }
        }
        Ok(())
    }
}

/// Error type for grammar operations.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GrammarError {
    /// No start symbol defined.
    NoStartSymbol,
    /// Undefined non-terminal referenced.
    UndefinedNonTerminal(NonTerminal),
    /// Empty grammar (no productions).
    EmptyGrammar,
    /// Duplicate rule ID.
    DuplicateRuleId(RuleId),
}

impl fmt::Display for GrammarError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GrammarError::NoStartSymbol => write!(f, "no start symbol defined"),
            GrammarError::UndefinedNonTerminal(nt) => write!(f, "undefined non-terminal: {}", nt),
            GrammarError::EmptyGrammar => write!(f, "empty grammar (no productions)"),
            GrammarError::DuplicateRuleId(id) => write!(f, "duplicate rule ID: {}", id),
        }
    }
}

impl std::error::Error for GrammarError {}

/// A context-free grammar.
///
/// Stores productions and provides efficient lookup by LHS non-terminal.
#[derive(Clone, Debug)]
pub struct Grammar {
    /// Start symbol.
    pub start: NonTerminal,
    /// All productions indexed by rule ID.
    productions: Vec<Production>,
    /// Productions indexed by LHS non-terminal.
    by_lhs: Vec<SmallVec<[RuleId; 8]>>,
    /// Non-terminal name mapping (for display).
    nt_names: FxHashMap<NonTerminal, String>,
    /// Terminal to vocabulary ID mapping.
    terminal_vocab: FxHashMap<String, Terminal>,
    /// Vocabulary ID to terminal name mapping.
    vocab_names: FxHashMap<Terminal, String>,
    /// Number of non-terminals.
    num_non_terminals: usize,
}

impl Grammar {
    /// Create a new grammar.
    pub fn new(
        start: NonTerminal,
        productions: Vec<Production>,
        num_non_terminals: usize,
    ) -> Result<Self, GrammarError> {
        if productions.is_empty() {
            return Err(GrammarError::EmptyGrammar);
        }

        // Build by_lhs index
        let mut by_lhs: Vec<SmallVec<[RuleId; 8]>> = vec![SmallVec::new(); num_non_terminals];

        for prod in &productions {
            let nt_idx = prod.lhs.index() as usize;
            if nt_idx >= num_non_terminals {
                return Err(GrammarError::UndefinedNonTerminal(prod.lhs));
            }
            by_lhs[nt_idx].push(prod.id);
        }

        Ok(Self {
            start,
            productions,
            by_lhs,
            nt_names: FxHashMap::default(),
            terminal_vocab: FxHashMap::default(),
            vocab_names: FxHashMap::default(),
            num_non_terminals,
        })
    }

    /// Get the start symbol.
    pub fn start(&self) -> NonTerminal {
        self.start
    }

    /// Get a production by rule ID.
    pub fn production(&self, id: RuleId) -> Option<&Production> {
        self.productions.get(id.index() as usize)
    }

    /// Get all productions for a given LHS non-terminal.
    pub fn productions_for(&self, lhs: NonTerminal) -> impl Iterator<Item = &Production> {
        let nt_idx = lhs.index() as usize;
        self.by_lhs
            .get(nt_idx)
            .into_iter()
            .flat_map(|rules| rules.iter())
            .filter_map(|&id| self.production(id))
    }

    /// Get all productions.
    pub fn productions(&self) -> &[Production] {
        &self.productions
    }

    /// Get the number of productions.
    pub fn num_productions(&self) -> usize {
        self.productions.len()
    }

    /// Get the number of non-terminals.
    pub fn num_non_terminals(&self) -> usize {
        self.num_non_terminals
    }

    /// Set the name for a non-terminal (for display).
    pub fn set_nt_name(&mut self, nt: NonTerminal, name: String) {
        self.nt_names.insert(nt, name);
    }

    /// Get the name of a non-terminal.
    pub fn nt_name(&self, nt: NonTerminal) -> Option<&str> {
        self.nt_names.get(&nt).map(|s| s.as_str())
    }

    /// Register a terminal with its vocabulary ID and name.
    pub fn register_terminal(&mut self, name: String, terminal: Terminal) {
        self.terminal_vocab.insert(name.clone(), terminal);
        self.vocab_names.insert(terminal, name);
    }

    /// Look up a terminal by name.
    pub fn terminal_by_name(&self, name: &str) -> Option<Terminal> {
        self.terminal_vocab.get(name).copied()
    }

    /// Get the name of a terminal.
    pub fn terminal_name(&self, terminal: Terminal) -> Option<&str> {
        self.vocab_names.get(&terminal).map(|s| s.as_str())
    }

    /// Check if this grammar has nullable non-terminals (can derive ε).
    pub fn compute_nullable(&self) -> Vec<bool> {
        let mut nullable = vec![false; self.num_non_terminals];
        let mut changed = true;

        while changed {
            changed = false;
            for prod in &self.productions {
                if nullable[prod.lhs.index() as usize] {
                    continue;
                }

                // Check if RHS is nullable
                let rhs_nullable = prod.rhs.iter().all(|sym| match sym {
                    Symbol::Epsilon => true,
                    Symbol::Terminal(_) => false,
                    Symbol::NonTerminal(nt) => nullable[nt.index() as usize],
                });

                if rhs_nullable {
                    nullable[prod.lhs.index() as usize] = true;
                    changed = true;
                }
            }
        }

        nullable
    }

    /// Compute FIRST sets for all non-terminals.
    pub fn compute_first_sets(&self) -> Vec<FxHashMap<Terminal, bool>> {
        let nullable = self.compute_nullable();
        let mut first: Vec<FxHashMap<Terminal, bool>> =
            vec![FxHashMap::default(); self.num_non_terminals];
        let mut changed = true;

        while changed {
            changed = false;

            for prod in &self.productions {
                let lhs_idx = prod.lhs.index() as usize;

                for sym in &prod.rhs {
                    match sym {
                        Symbol::Terminal(t) => {
                            if !first[lhs_idx].contains_key(t) {
                                first[lhs_idx].insert(*t, true);
                                changed = true;
                            }
                            break; // Terminal found, stop
                        }
                        Symbol::NonTerminal(nt) => {
                            let nt_idx = nt.index() as usize;
                            // Add FIRST(nt) to FIRST(lhs)
                            for (&t, _) in &first[nt_idx].clone() {
                                if !first[lhs_idx].contains_key(&t) {
                                    first[lhs_idx].insert(t, true);
                                    changed = true;
                                }
                            }
                            // If nt is not nullable, stop
                            if !nullable[nt_idx] {
                                break;
                            }
                        }
                        Symbol::Epsilon => {
                            // Skip epsilon
                        }
                    }
                }
            }
        }

        first
    }
}

impl fmt::Display for Grammar {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Grammar (start: {})", self.start)?;
        for prod in &self.productions {
            writeln!(f, "  {}", prod)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn simple_grammar() -> Grammar {
        // S → NP VP
        // NP → Det N
        // VP → V NP
        let productions = vec![
            Production::new(
                RuleId::new(0),
                NonTerminal::new(0), // S
                smallvec::smallvec![Symbol::non_terminal(1), Symbol::non_terminal(2)], // NP VP
            ),
            Production::new(
                RuleId::new(1),
                NonTerminal::new(1), // NP
                smallvec::smallvec![Symbol::non_terminal(3), Symbol::non_terminal(4)], // Det N
            ),
            Production::new(
                RuleId::new(2),
                NonTerminal::new(2), // VP
                smallvec::smallvec![Symbol::non_terminal(5), Symbol::non_terminal(1)], // V NP
            ),
        ];

        Grammar::new(NonTerminal::new(0), productions, 6).expect("valid grammar")
    }

    #[test]
    fn test_grammar_creation() {
        let grammar = simple_grammar();
        assert_eq!(grammar.start(), NonTerminal::new(0));
        assert_eq!(grammar.num_productions(), 3);
        assert_eq!(grammar.num_non_terminals(), 6);
    }

    #[test]
    fn test_production_access() {
        let grammar = simple_grammar();

        let prod = grammar.production(RuleId::new(0)).expect("rule 0");
        assert_eq!(prod.lhs, NonTerminal::new(0));
        assert_eq!(prod.rhs.len(), 2);
    }

    #[test]
    fn test_productions_for_lhs() {
        let grammar = simple_grammar();

        let s_prods: Vec<_> = grammar.productions_for(NonTerminal::new(0)).collect();
        assert_eq!(s_prods.len(), 1);
        assert_eq!(s_prods[0].id, RuleId::new(0));
    }

    #[test]
    fn test_epsilon_production() {
        let prod = Production::new(RuleId::new(0), NonTerminal::new(0), SmallVec::new());
        assert!(prod.is_epsilon());
        assert_eq!(prod.rhs_len(), 0);

        let prod2 = Production::new(
            RuleId::new(1),
            NonTerminal::new(0),
            smallvec::smallvec![Symbol::epsilon()],
        );
        assert!(prod2.is_epsilon());
    }

    #[test]
    fn test_production_display() {
        let prod = Production::new(
            RuleId::new(0),
            NonTerminal::new(0),
            smallvec::smallvec![Symbol::non_terminal(1), Symbol::terminal(5)],
        );
        let display = format!("{}", prod);
        assert!(display.contains("NT(0)"));
        assert!(display.contains(""));
    }

    #[test]
    fn test_empty_grammar_error() {
        let result = Grammar::new(NonTerminal::new(0), vec![], 1);
        assert!(matches!(result, Err(GrammarError::EmptyGrammar)));
    }

    #[test]
    fn test_nt_names() {
        let mut grammar = simple_grammar();
        grammar.set_nt_name(NonTerminal::new(0), "S".to_string());
        grammar.set_nt_name(NonTerminal::new(1), "NP".to_string());

        assert_eq!(grammar.nt_name(NonTerminal::new(0)), Some("S"));
        assert_eq!(grammar.nt_name(NonTerminal::new(1)), Some("NP"));
        assert_eq!(grammar.nt_name(NonTerminal::new(5)), None);
    }

    #[test]
    fn test_terminal_registration() {
        let mut grammar = simple_grammar();
        grammar.register_terminal("the".to_string(), Terminal::new(100));

        assert_eq!(grammar.terminal_by_name("the"), Some(Terminal::new(100)));
        assert_eq!(grammar.terminal_name(Terminal::new(100)), Some("the"));
        assert_eq!(grammar.terminal_by_name("unknown"), None);
    }

    #[test]
    fn test_nullable_computation() {
        // S → A B
        // A → ε
        // B → b
        let productions = vec![
            Production::new(
                RuleId::new(0),
                NonTerminal::new(0), // S
                smallvec::smallvec![Symbol::non_terminal(1), Symbol::non_terminal(2)],
            ),
            Production::new(
                RuleId::new(1),
                NonTerminal::new(1), // A → ε
                smallvec::smallvec![Symbol::epsilon()],
            ),
            Production::new(
                RuleId::new(2),
                NonTerminal::new(2), // B → b
                smallvec::smallvec![Symbol::terminal(0)],
            ),
        ];

        let grammar = Grammar::new(NonTerminal::new(0), productions, 3).expect("valid grammar");
        let nullable = grammar.compute_nullable();

        assert!(!nullable[0]); // S not nullable
        assert!(nullable[1]); // A is nullable
        assert!(!nullable[2]); // B not nullable
    }
}