liblevenshtein 0.9.1

Levenshtein/Universal Automata for approximate string matching using various dictionary backends
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
//! Lazy DFA construction for NFA simulation.
//!
//! This module provides lazy (on-demand) DFA construction from NFAs.
//! Instead of constructing the full DFA upfront (which can have exponentially
//! many states), we construct DFA states lazily as they are encountered during
//! matching.
//!
//! # Advantages
//!
//! - **Memory efficient**: Only constructs states that are actually visited
//! - **Fast startup**: No upfront powerset construction
//! - **Cache-friendly**: Frequently used transitions are cached
//!
//! # Design
//!
//! A DFA state corresponds to a set of NFA states (the powerset construction).
//! We cache the mapping from (DFA_state, character) -> DFA_state for fast lookup.
//!
//! # Examples
//!
//! ```ignore
//! use liblevenshtein::phonetic::nfa::{LazyDFAChar, NFAChar};
//!
//! let nfa = /* build NFA for pattern */;
//! let mut dfa = LazyDFAChar::new(nfa);
//!
//! // Check if string matches
//! assert!(dfa.accepts("phone"));
//! assert!(!dfa.accepts("xyz"));
//!
//! // Subsequent queries benefit from cached transitions
//! assert!(dfa.accepts("phone")); // Uses cached transitions
//! ```

use super::state_set::StateSet;
use super::types::StateId;
use super::{NFAChar, NFA};
use rustc_hash::FxHashMap;

// ============================================================================
// Character-level Lazy DFA
// ============================================================================

/// A DFA state represented as a sorted vector of NFA states.
///
/// We use a sorted `Vec` instead of `HashSet` for:
/// - Deterministic hashing (order-independent)
/// - Cache-friendly iteration
/// - Efficient equality comparison
pub type DFAStateChar = Vec<StateId>;

/// Compact ID for a DFA state (H8 optimization).
/// Using u32 for cache-friendly key size while supporting millions of states.
type DFAStateId = u32;

/// Lazy DFA for character-level NFA simulation.
///
/// Constructs DFA states on-demand during matching, caching transitions
/// for efficient repeated queries.
///
/// # H8 Optimization: State ID Caching
///
/// Instead of using `Vec<StateId>` as cache keys (which requires O(n) hash
/// and comparison), we assign each unique DFA state a compact numeric ID.
/// Cache lookups become O(1) instead of O(n).
#[derive(Debug, Clone)]
pub struct LazyDFAChar {
    /// The underlying NFA
    nfa: NFAChar,
    /// Cached transitions: (state_id, char) -> state_id (H8: O(1) keys)
    cache: FxHashMap<(DFAStateId, char), DFAStateId>,
    /// Registry mapping DFA states to compact IDs
    state_to_id: FxHashMap<DFAStateChar, DFAStateId>,
    /// Reverse mapping: ID -> DFA state
    id_to_state: Vec<DFAStateChar>,
    /// The initial DFA state ID
    initial_state_id: DFAStateId,
    /// Cache of which DFA state IDs are accepting
    accepting_cache: FxHashMap<DFAStateId, bool>,
}

impl LazyDFAChar {
    /// Create a new lazy DFA from an NFA.
    pub fn new(nfa: NFAChar) -> Self {
        // Compute initial state as epsilon closure of NFA start
        let initial_closure = nfa.epsilon_closure_single(nfa.start());
        let initial_state = Self::set_to_state(&initial_closure);

        // Register the initial state with ID 0
        let mut state_to_id = FxHashMap::default();
        state_to_id.insert(initial_state.clone(), 0);
        let id_to_state = vec![initial_state];

        Self {
            nfa,
            cache: FxHashMap::default(),
            state_to_id,
            id_to_state,
            initial_state_id: 0,
            accepting_cache: FxHashMap::default(),
        }
    }

    /// Convert a set of NFA states to a canonical DFA state representation.
    fn set_to_state(states: &StateSet) -> DFAStateChar {
        let mut vec: Vec<StateId> = states.iter().collect();
        vec.sort_unstable();
        vec
    }

    /// Convert a DFA state back to a StateSet for NFA operations.
    fn state_to_set(state: &DFAStateChar) -> StateSet {
        state.iter().copied().collect()
    }

    /// Get or create a state ID for a DFA state (H8 optimization).
    #[inline]
    fn get_or_create_id(&mut self, state: DFAStateChar) -> DFAStateId {
        if let Some(&id) = self.state_to_id.get(&state) {
            return id;
        }
        let id = self.id_to_state.len() as DFAStateId;
        self.state_to_id.insert(state.clone(), id);
        self.id_to_state.push(state);
        id
    }

    /// Get the DFA state for an ID.
    #[inline]
    fn get_state(&self, id: DFAStateId) -> &DFAStateChar {
        &self.id_to_state[id as usize]
    }

    /// Get the initial DFA state.
    #[inline]
    pub fn initial_state(&self) -> &DFAStateChar {
        self.get_state(self.initial_state_id)
    }

    /// Check if a DFA state is accepting (by ID).
    #[inline]
    fn is_accepting_id(&mut self, state_id: DFAStateId) -> bool {
        if let Some(&accepting) = self.accepting_cache.get(&state_id) {
            return accepting;
        }

        let state = self.get_state(state_id);
        let accepting = state.iter().any(|&s| self.nfa.is_final(s));
        self.accepting_cache.insert(state_id, accepting);
        accepting
    }

    /// Check if a DFA state is accepting.
    ///
    /// A DFA state is accepting if any of its constituent NFA states is final.
    pub fn is_accepting(&mut self, state: &DFAStateChar) -> bool {
        // Look up the state ID (should exist if we're checking acceptance)
        if let Some(&state_id) = self.state_to_id.get(state) {
            self.is_accepting_id(state_id)
        } else {
            // State not registered - compute directly
            state.iter().any(|&s| self.nfa.is_final(s))
        }
    }

    /// Compute the transition from a DFA state ID on a character (H8 core).
    #[inline]
    fn transition_id(&mut self, state_id: DFAStateId, c: char) -> DFAStateId {
        // Check cache first - O(1) lookup with compact key
        let cache_key = (state_id, c);
        if let Some(&next_id) = self.cache.get(&cache_key) {
            return next_id;
        }

        // Compute transition: for each NFA state, collect states reachable on c
        let state = self.get_state(state_id).clone(); // Clone needed for borrow checker
        let current_set = Self::state_to_set(&state);
        let mut next_set = StateSet::new();

        for nfa_state in current_set.iter() {
            for trans in self.nfa.transitions_from(nfa_state) {
                if trans.label.matches(c) && trans.label.consumes_input() {
                    next_set.insert(trans.to);
                }
            }
        }

        // Apply epsilon closure
        let next_closure = self.nfa.epsilon_closure(&next_set);
        let next_state = Self::set_to_state(&next_closure);

        // Get or create ID for next state
        let next_id = self.get_or_create_id(next_state);

        // Cache the result with compact key
        self.cache.insert(cache_key, next_id);
        next_id
    }

    /// Compute the transition from a DFA state on a character.
    ///
    /// This is the core lazy construction: we compute DFA states on-demand
    /// and cache the results.
    pub fn transition(&mut self, state: &DFAStateChar, c: char) -> DFAStateChar {
        // Get or create state ID
        let state_id = if let Some(&id) = self.state_to_id.get(state) {
            id
        } else {
            self.get_or_create_id(state.clone())
        };

        let next_id = self.transition_id(state_id, c);
        self.get_state(next_id).clone()
    }

    /// Check if an input string is accepted by the NFA.
    ///
    /// Uses lazy DFA construction with caching for efficient matching.
    /// H8 optimization: internally uses state IDs for O(1) cache lookups.
    pub fn accepts(&mut self, input: &str) -> bool {
        let mut current_id = self.initial_state_id;

        for c in input.chars() {
            current_id = self.transition_id(current_id, c);
            // Check for dead state (empty state has a dedicated ID or is checked)
            if self.get_state(current_id).is_empty() {
                return false;
            }
        }

        self.is_accepting_id(current_id)
    }

    /// Get the number of cached transitions.
    #[inline]
    pub fn cache_size(&self) -> usize {
        self.cache.len()
    }

    /// Get the number of unique DFA states discovered.
    #[inline]
    pub fn state_count(&self) -> usize {
        self.id_to_state.len()
    }

    /// Clear the transition cache.
    ///
    /// Useful for memory management in long-running applications.
    /// Note: This also clears the state registry, resetting to initial state only.
    pub fn clear_cache(&mut self) {
        self.cache.clear();
        self.accepting_cache.clear();
        // Reset state registry to only contain the initial state
        let initial = self.id_to_state[0].clone();
        self.state_to_id.clear();
        self.state_to_id.insert(initial.clone(), 0);
        self.id_to_state.clear();
        self.id_to_state.push(initial);
    }

    /// Get cache statistics.
    pub fn cache_stats(&self) -> CacheStats {
        CacheStats {
            transition_cache_size: self.cache.len(),
            accepting_cache_size: self.accepting_cache.len(),
        }
    }
}

// ============================================================================
// Byte-level Lazy DFA
// ============================================================================

/// A DFA state for byte-level NFA.
pub type DFAState = Vec<StateId>;

/// Lazy DFA for byte-level NFA simulation.
///
/// # H8 Optimization: State ID Caching
///
/// Uses compact numeric IDs for cache keys instead of Vec<StateId>.
#[derive(Debug, Clone)]
pub struct LazyDFA {
    /// The underlying NFA
    nfa: NFA,
    /// Cached transitions: (state_id, byte) -> state_id (H8: O(1) keys)
    cache: FxHashMap<(DFAStateId, u8), DFAStateId>,
    /// Registry mapping DFA states to compact IDs
    state_to_id: FxHashMap<DFAState, DFAStateId>,
    /// Reverse mapping: ID -> DFA state
    id_to_state: Vec<DFAState>,
    /// The initial DFA state ID
    initial_state_id: DFAStateId,
    /// Cache of which DFA state IDs are accepting
    accepting_cache: FxHashMap<DFAStateId, bool>,
}

impl LazyDFA {
    /// Create a new lazy DFA from an NFA.
    pub fn new(nfa: NFA) -> Self {
        let initial_closure = nfa.epsilon_closure_single(nfa.start());
        let initial_state = Self::set_to_state(&initial_closure);

        // Register the initial state with ID 0
        let mut state_to_id = FxHashMap::default();
        state_to_id.insert(initial_state.clone(), 0);
        let id_to_state = vec![initial_state];

        Self {
            nfa,
            cache: FxHashMap::default(),
            state_to_id,
            id_to_state,
            initial_state_id: 0,
            accepting_cache: FxHashMap::default(),
        }
    }

    /// Convert a set of NFA states to a canonical DFA state.
    fn set_to_state(states: &StateSet) -> DFAState {
        let mut vec: Vec<StateId> = states.iter().collect();
        vec.sort_unstable();
        vec
    }

    /// Convert a DFA state back to a StateSet.
    fn state_to_set(state: &DFAState) -> StateSet {
        state.iter().copied().collect()
    }

    /// Get or create a state ID for a DFA state (H8 optimization).
    #[inline]
    fn get_or_create_id(&mut self, state: DFAState) -> DFAStateId {
        if let Some(&id) = self.state_to_id.get(&state) {
            return id;
        }
        let id = self.id_to_state.len() as DFAStateId;
        self.state_to_id.insert(state.clone(), id);
        self.id_to_state.push(state);
        id
    }

    /// Get the DFA state for an ID.
    #[inline]
    fn get_state(&self, id: DFAStateId) -> &DFAState {
        &self.id_to_state[id as usize]
    }

    /// Get the initial DFA state.
    #[inline]
    pub fn initial_state(&self) -> &DFAState {
        self.get_state(self.initial_state_id)
    }

    /// Check if a DFA state is accepting (by ID).
    #[inline]
    fn is_accepting_id(&mut self, state_id: DFAStateId) -> bool {
        if let Some(&accepting) = self.accepting_cache.get(&state_id) {
            return accepting;
        }

        let state = self.get_state(state_id);
        let accepting = state.iter().any(|&s| self.nfa.is_final(s));
        self.accepting_cache.insert(state_id, accepting);
        accepting
    }

    /// Check if a DFA state is accepting.
    pub fn is_accepting(&mut self, state: &DFAState) -> bool {
        if let Some(&state_id) = self.state_to_id.get(state) {
            self.is_accepting_id(state_id)
        } else {
            state.iter().any(|&s| self.nfa.is_final(s))
        }
    }

    /// Compute the transition from a DFA state ID on a byte (H8 core).
    #[inline]
    fn transition_id(&mut self, state_id: DFAStateId, b: u8) -> DFAStateId {
        let cache_key = (state_id, b);
        if let Some(&next_id) = self.cache.get(&cache_key) {
            return next_id;
        }

        let state = self.get_state(state_id).clone();
        let current_set = Self::state_to_set(&state);
        let mut next_set = StateSet::new();

        for nfa_state in current_set.iter() {
            for trans in self.nfa.transitions_from(nfa_state) {
                if trans.label.matches(b) && trans.label.consumes_input() {
                    next_set.insert(trans.to);
                }
            }
        }

        let next_closure = self.nfa.epsilon_closure(&next_set);
        let next_state = Self::set_to_state(&next_closure);

        let next_id = self.get_or_create_id(next_state);
        self.cache.insert(cache_key, next_id);
        next_id
    }

    /// Compute the transition from a DFA state on a byte.
    pub fn transition(&mut self, state: &DFAState, b: u8) -> DFAState {
        let state_id = if let Some(&id) = self.state_to_id.get(state) {
            id
        } else {
            self.get_or_create_id(state.clone())
        };

        let next_id = self.transition_id(state_id, b);
        self.get_state(next_id).clone()
    }

    /// Check if input is accepted.
    pub fn accepts(&mut self, input: &[u8]) -> bool {
        let mut current_id = self.initial_state_id;

        for &b in input {
            current_id = self.transition_id(current_id, b);
            if self.get_state(current_id).is_empty() {
                return false;
            }
        }

        self.is_accepting_id(current_id)
    }

    /// Get the number of cached transitions.
    #[inline]
    pub fn cache_size(&self) -> usize {
        self.cache.len()
    }

    /// Get the number of unique DFA states discovered.
    #[inline]
    pub fn state_count(&self) -> usize {
        self.id_to_state.len()
    }

    /// Clear the transition cache.
    pub fn clear_cache(&mut self) {
        self.cache.clear();
        self.accepting_cache.clear();
        let initial = self.id_to_state[0].clone();
        self.state_to_id.clear();
        self.state_to_id.insert(initial.clone(), 0);
        self.id_to_state.clear();
        self.id_to_state.push(initial);
    }

    /// Get cache statistics.
    pub fn cache_stats(&self) -> CacheStats {
        CacheStats {
            transition_cache_size: self.cache.len(),
            accepting_cache_size: self.accepting_cache.len(),
        }
    }
}

// ============================================================================
// Cache Statistics
// ============================================================================

/// Statistics about the lazy DFA cache.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CacheStats {
    /// Number of cached transition entries
    pub transition_cache_size: usize,
    /// Number of cached accepting state entries
    pub accepting_cache_size: usize,
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::phonetic::nfa::compiler::{compile, compile_bytes};
    use crate::phonetic::regex::{parse, parse_bytes};

    #[test]
    fn test_lazy_dfa_simple() {
        let nfa = compile(&parse("abc").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFAChar::new(nfa);

        assert!(dfa.accepts("abc"));
        assert!(!dfa.accepts("ab"));
        assert!(!dfa.accepts("abcd"));
        assert!(!dfa.accepts("xyz"));
    }

    #[test]
    fn test_lazy_dfa_alternation() {
        let nfa = compile(&parse("cat|dog").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFAChar::new(nfa);

        assert!(dfa.accepts("cat"));
        assert!(dfa.accepts("dog"));
        assert!(!dfa.accepts("ca"));
        assert!(!dfa.accepts("do"));
        assert!(!dfa.accepts("catdog"));
    }

    #[test]
    fn test_lazy_dfa_star() {
        let nfa = compile(&parse("a*").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFAChar::new(nfa);

        assert!(dfa.accepts(""));
        assert!(dfa.accepts("a"));
        assert!(dfa.accepts("aa"));
        assert!(dfa.accepts("aaa"));
        assert!(!dfa.accepts("b"));
        assert!(!dfa.accepts("ab"));
    }

    #[test]
    fn test_lazy_dfa_plus() {
        let nfa = compile(&parse("a+").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFAChar::new(nfa);

        assert!(!dfa.accepts(""));
        assert!(dfa.accepts("a"));
        assert!(dfa.accepts("aa"));
        assert!(dfa.accepts("aaa"));
        assert!(!dfa.accepts("b"));
    }

    #[test]
    fn test_lazy_dfa_char_class() {
        let nfa = compile(&parse("[aeiou]+").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFAChar::new(nfa);

        assert!(dfa.accepts("a"));
        assert!(dfa.accepts("aeiou"));
        assert!(dfa.accepts("oui"));
        assert!(!dfa.accepts(""));
        assert!(!dfa.accepts("xyz"));
    }

    #[test]
    fn test_lazy_dfa_complex() {
        let nfa = compile(&parse("(ph|f)one").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFAChar::new(nfa);

        assert!(dfa.accepts("phone"));
        assert!(dfa.accepts("fone"));
        assert!(!dfa.accepts("bone"));
        assert!(!dfa.accepts("phon"));
    }

    #[test]
    fn test_lazy_dfa_caching() {
        let nfa = compile(&parse("test").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFAChar::new(nfa);

        // First query builds cache
        assert!(dfa.accepts("test"));
        let stats1 = dfa.cache_stats();
        assert!(stats1.transition_cache_size > 0);

        // Second query uses cache (size shouldn't change)
        assert!(dfa.accepts("test"));
        let stats2 = dfa.cache_stats();
        assert_eq!(stats1.transition_cache_size, stats2.transition_cache_size);
    }

    #[test]
    fn test_lazy_dfa_cache_clear() {
        let nfa = compile(&parse("test").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFAChar::new(nfa);

        assert!(dfa.accepts("test"));
        assert!(dfa.cache_size() > 0);

        dfa.clear_cache();
        assert_eq!(dfa.cache_size(), 0);

        // Should still work after clearing
        assert!(dfa.accepts("test"));
    }

    #[test]
    fn test_lazy_dfa_bytes() {
        let nfa = compile_bytes(&parse_bytes(b"hello").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFA::new(nfa);

        assert!(dfa.accepts(b"hello"));
        assert!(!dfa.accepts(b"world"));
        assert!(!dfa.accepts(b"hell"));
    }

    #[test]
    fn test_lazy_dfa_bytes_alternation() {
        let nfa = compile_bytes(&parse_bytes(b"yes|no").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFA::new(nfa);

        assert!(dfa.accepts(b"yes"));
        assert!(dfa.accepts(b"no"));
        assert!(!dfa.accepts(b"maybe"));
    }

    #[test]
    fn test_lazy_dfa_epsilon_pattern() {
        // Use a pattern that accepts empty string (empty alternation or a*)
        let nfa = compile(&parse("a*").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFAChar::new(nfa);

        // a* accepts empty string
        assert!(dfa.accepts(""));
        assert!(dfa.accepts("a"));
        assert!(dfa.accepts("aa"));
    }

    #[test]
    fn test_lazy_dfa_optional() {
        let nfa = compile(&parse("colou?r").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let mut dfa = LazyDFAChar::new(nfa);

        assert!(dfa.accepts("color"));
        assert!(dfa.accepts("colour"));
        assert!(!dfa.accepts("colr"));
        assert!(!dfa.accepts("colouur"));
    }
}