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
//! Core FST traits defining the fundamental interface for weighted finite-state transducers.
//!
//! This module provides the foundational traits that all FST implementations must satisfy.
//! The trait hierarchy is designed to support a range of FST implementations from simple
//! in-memory structures to lazy, on-demand computed automata.
//!
//! # Trait Hierarchy
//!
//! ```text
//! Fst<W> Read-only access to FST structure
//! |
//! +-- MutableFst<W> Construction and modification operations
//! |
//! +-- ExpandedFst<W> Direct slice access to arc arrays
//! |
//! +-- LazyFst<W> On-demand state expansion
//! ```
//!
//! # Type Definitions
//!
//! - [`StateId`]: 32-bit unsigned integer for state identification
//! - [`Label`]: 32-bit unsigned integer for input/output symbols
//! - [`NO_STATE_ID`]: Sentinel value indicating no state (similar to `None`)
//! - [`NO_LABEL`]: Reserved label value 0 for epsilon transitions
//!
//! # References
//!
//! - Mohri, M. (1997). Finite-State Transducers in Language and Speech Processing.
//! *Computational Linguistics*, 23(2), 269-311.
//!
//! - Mohri, M., Pereira, F., & Riley, M. (2002). Weighted Finite-State Transducers
//! in Speech Recognition. *Computer Speech & Language*, 16(1), 69-88.
use crate;
use crateFstProperties;
use crateSemiring;
use crateResult;
use Debug;
/// State identifier type.
///
/// States are identified by 32-bit unsigned integers, allowing up to 2^32 - 1 states
/// (reserving `u32::MAX` as the sentinel value [`NO_STATE_ID`]). States are typically
/// numbered consecutively from 0.
pub type StateId = u32;
/// Label type for input/output symbols.
///
/// Labels are 32-bit unsigned integers representing symbols from the input or output
/// alphabet. Label 0 is reserved for epsilon (empty string) transitions, following
/// the convention established in OpenFst.
pub type Label = u32;
/// Special state ID indicating no state exists.
///
/// This sentinel value is used to represent the absence of a state, similar to
/// `Option::None`. Common uses include indicating that an FST has no start state
/// or that a lookup operation failed to find a matching state.
pub const NO_STATE_ID: StateId = u32MAX;
/// Special label reserved for epsilon transitions.
///
/// Epsilon transitions consume no input and produce no output, allowing the
/// transducer to change states without reading or writing symbols. This is
/// essential for representing optional elements, alternations, and other
/// patterns that cannot be expressed with purely synchronous transitions.
pub const NO_LABEL: Label = 0;
/// Core trait for all FST types providing read-only access.
///
/// The `Fst` trait defines the fundamental interface for weighted finite-state transducers,
/// providing operations to query the structure, navigate states, and access weights.
/// This trait corresponds to the abstract FST interface described in the OpenFst library
/// design (Allauzen et al., 2007).
///
/// # Type Parameters
///
/// - `W`: The semiring type for arc and final state weights. Must implement [`Semiring`].
///
/// # Associated Types
///
/// - `ArcIter<'a>`: Iterator type for traversing arcs from a state. Must implement
/// [`ArcIterator<W>`] and be valid for the lifetime of the FST reference.
///
/// # Complexity
///
/// The following complexity bounds apply to conforming implementations:
///
/// | Operation | Time Complexity | Notes |
/// |-----------|----------------|-------|
/// | `start()` | $`O(1)`$ | Direct field access |
/// | `final_weight(s)` | $`O(1)`$ | Direct state lookup |
/// | `num_arcs(s)` | $`O(1)`$ | Cached or computed |
/// | `num_states()` | $`O(1)`$ | Cached value |
/// | `arcs(s)` | $`O(1)`$ to create | Iterator creation |
/// | `states()` | $`O(1)`$ to create | Range iterator |
/// | `num_arcs_total()` | $`O(V)`$ | Sums over all states |
///
/// # Implementation Guidelines
///
/// When implementing this trait:
/// - `start()` must return `None` for FSTs with no designated initial state
/// - `final_weight(s)` must return `None` for non-final states and invalid state IDs
/// - Arc iterators must yield arcs in a consistent order across multiple iterations
/// - States are numbered consecutively from 0 to `num_states() - 1`
/// - Label 0 is reserved for epsilon transitions per the OpenFst convention
///
/// # Thread Safety
///
/// All FST implementations are required to be `Send + Sync`, enabling safe sharing
/// between threads for read-only operations. Mutable access requires appropriate
/// synchronization through external means or the [`ConcurrentFst`] implementation.
///
/// # Examples
///
/// ## Basic FST Traversal
///
/// ```rust
/// use arcweight::prelude::*;
///
/// fn analyze_fst<W: Semiring>(fst: &impl Fst<W>) {
/// if let Some(start) = fst.start() {
/// println!("FST has {} states", fst.num_states());
/// println!("Start state: {}", start);
///
/// // Iterate over arcs from start state
/// for arc in fst.arcs(start) {
/// println!("Arc: {} -> {} / {} : {}",
/// arc.ilabel, arc.olabel, arc.weight, arc.nextstate);
/// }
///
/// // Check if start state is final
/// if let Some(weight) = fst.final_weight(start) {
/// println!("Start state is final with weight: {}", weight);
/// }
/// } else {
/// println!("Empty FST (no start state)");
/// }
/// }
/// ```
///
/// ## Depth-First Traversal
///
/// ```rust
/// use arcweight::prelude::*;
/// use std::collections::HashSet;
///
/// fn count_reachable_states<W: Semiring>(fst: &impl Fst<W>) -> usize {
/// let mut visited = HashSet::new();
/// let mut stack = Vec::new();
///
/// if let Some(start) = fst.start() {
/// stack.push(start);
/// }
///
/// while let Some(state) = stack.pop() {
/// if visited.insert(state) {
/// for arc in fst.arcs(state) {
/// if !visited.contains(&arc.nextstate) {
/// stack.push(arc.nextstate);
/// }
/// }
/// }
/// }
///
/// visited.len()
/// }
/// ```
///
/// # References
///
/// - Allauzen, C., Riley, M., Schalkwyk, J., Skut, W., & Mohri, M. (2007).
/// OpenFst: A General and Efficient Weighted Finite-State Transducer Library.
/// In *Proc. CIAA 2007*, LNCS 4783, pp. 11-23. Springer.
///
/// # See Also
///
/// - [`MutableFst`] for FSTs that support modification
/// - [`ExpandedFst`] for FSTs with direct slice access to arcs
/// - [`LazyFst`] for on-demand computed FSTs
///
/// [`VectorFst`]: crate::fst::VectorFst
/// [`ConstFst`]: crate::fst::ConstFst
/// [`CacheFst`]: crate::fst::CacheFst
/// [`ConcurrentFst`]: crate::fst::ConcurrentFst
/// Trait for FSTs that support modification operations.
///
/// The `MutableFst` trait extends [`Fst`] with operations for constructing and
/// modifying FST structure. This includes adding states and arcs, setting start
/// and final states, and managing the FST's topology. Implementations provide
/// the foundation for FST construction algorithms and dynamic modifications.
///
/// # Type Parameters
///
/// - `W`: The semiring type for arc and final state weights.
///
/// # Complexity
///
/// The following complexity bounds apply to conforming implementations:
///
/// | Operation | Time Complexity | Notes |
/// |-----------|----------------|-------|
/// | `add_state()` | $`O(1)`$ amortized | May trigger reallocation |
/// | `add_arc(s, arc)` | $`O(1)`$ amortized | Appends to state's arc list |
/// | `set_start(s)` | $`O(1)`$ | Direct field assignment |
/// | `set_final(s, w)` | $`O(1)`$ | Direct state update |
/// | `delete_arcs(s)` | $`O(k)`$ | $`k`$ = arcs from state |
/// | `clear()` | $`O(V + E)`$ | Deallocates all storage |
///
/// # Implementation Guidelines
///
/// When implementing this trait:
/// - `add_state()` must return a unique, sequential state ID starting from 0
/// - State IDs must remain valid after insertion (no compaction during mutation)
/// - `set_final()` with `W::zero()` should remove final status (semiring zero)
/// - `clear()` must reset to an empty FST with no states or arcs
/// - Memory reservations are optimization hints and may be ignored
///
/// # Construction Patterns
///
/// ## Basic FST Construction
///
/// ```rust
/// use arcweight::prelude::*;
///
/// fn build_simple_fst() -> VectorFst<TropicalWeight> {
/// let mut fst = VectorFst::new();
///
/// // Add states
/// let s0 = fst.add_state();
/// let s1 = fst.add_state();
///
/// // Set start state
/// fst.set_start(s0);
///
/// // Add an arc: input 'a', output 'b', weight 1.5
/// fst.add_arc(s0, Arc::new(
/// 'a' as u32,
/// 'b' as u32,
/// TropicalWeight::new(1.5),
/// s1
/// ));
///
/// // Make s1 final with identity weight
/// fst.set_final(s1, TropicalWeight::one());
///
/// fst
/// }
/// ```
///
/// ## Efficient Batch Construction
///
/// ```rust
/// use arcweight::prelude::*;
///
/// fn build_trie_fst(words: &[&str]) -> VectorFst<BooleanWeight> {
/// let mut fst = VectorFst::new();
///
/// // Pre-allocate for better performance
/// let estimated_states = words.iter().map(|w| w.len()).sum::<usize>();
/// fst.reserve_states(estimated_states);
///
/// let start = fst.add_state();
/// fst.set_start(start);
///
/// for word in words {
/// let mut current = start;
/// for ch in word.chars() {
/// let next = fst.add_state();
/// fst.add_arc(current, Arc::new(
/// ch as u32, ch as u32, BooleanWeight::one(), next
/// ));
/// current = next;
/// }
/// fst.set_final(current, BooleanWeight::one());
/// }
///
/// fst
/// }
/// ```
///
/// # References
///
/// - Allauzen, C., Riley, M., Schalkwyk, J., Skut, W., & Mohri, M. (2007).
/// OpenFst: A General and Efficient Weighted Finite-State Transducer Library.
/// In *Proc. CIAA 2007*, LNCS 4783, pp. 11-23. Springer.
///
/// # See Also
///
/// - [`Fst`] for read-only operations
/// - [`VectorFst`] for the primary mutable implementation
/// - [`ConcurrentFst`] for thread-safe mutable access
///
/// [`VectorFst`]: crate::fst::VectorFst
/// [`ConcurrentFst`]: crate::fst::ConcurrentFst
/// Trait for FSTs with all states and arcs expanded in memory.
///
/// The `ExpandedFst` trait is implemented by FST types that maintain all arc data
/// in contiguous memory, enabling direct slice access for high-performance operations.
/// This is in contrast to lazy or on-demand FSTs where arcs may be computed at access time.
///
/// # Type Parameters
///
/// - `W`: The semiring type for arc weights.
///
/// # Performance Benefits
///
/// Direct slice access provides several advantages over iterator-based access:
///
/// - **Zero iterator overhead**: No per-element virtual dispatch
/// - **Cache efficiency**: Contiguous memory enables hardware prefetching
/// - **SIMD compatibility**: Slice operations can be vectorized
/// - **Multiple passes**: Efficient for algorithms requiring repeated arc access
///
/// # Complexity
///
/// | Operation | Time Complexity | Notes |
/// |-----------|----------------|-------|
/// | `arcs_slice(s)` | $`O(1)`$ | Returns slice reference |
/// | Slice iteration | $`O(k)`$ | $`k`$ = arcs from state |
///
/// # Examples
///
/// ## Counting Epsilon Arcs
///
/// ```rust
/// use arcweight::prelude::*;
///
/// fn count_epsilon_arcs<W: Semiring>(fst: &impl ExpandedFst<W>) -> usize {
/// fst.states()
/// .map(|state| {
/// fst.arcs_slice(state)
/// .iter()
/// .filter(|arc| arc.ilabel == 0)
/// .count()
/// })
/// .sum()
/// }
/// ```
///
/// ## Parallel Arc Processing
///
/// ```rust
/// use arcweight::prelude::*;
///
/// fn find_max_weight_arc<W: Semiring + Ord>(
/// fst: &impl ExpandedFst<W>,
/// state: StateId
/// ) -> Option<&Arc<W>> {
/// fst.arcs_slice(state)
/// .iter()
/// .max_by(|a, b| a.weight.partial_cmp(&b.weight).unwrap())
/// }
/// ```
///
/// # Implementations
///
/// This trait is implemented by FST types that store arcs in memory:
///
/// - [`VectorFst`]: Dynamic construction with slice access
/// - [`ConstFst`]: Optimized read-only with contiguous storage
/// - [`CsrFst`]: Cache-optimized CSR format
///
/// Note: Lazy FST types ([`LazyFstImpl`], [`CacheFst`]) do not implement this trait
/// because their arcs may be computed on demand.
///
/// [`VectorFst`]: crate::fst::VectorFst
/// [`ConstFst`]: crate::fst::ConstFst
/// [`CsrFst`]: crate::fst::CsrFst
/// [`LazyFstImpl`]: crate::fst::LazyFstImpl
/// [`CacheFst`]: crate::fst::CacheFst
/// Trait for FSTs with on-demand (lazy) state computation.
///
/// The `LazyFst` trait extends [`Fst`] with explicit state expansion operations
/// for FSTs where states and arcs are computed dynamically rather than stored
/// in memory. This is essential for handling very large or infinite state spaces
/// that cannot be materialized entirely.
///
/// # Type Parameters
///
/// - `W`: The semiring type for arc weights.
///
/// # Use Cases
///
/// - **Composition**: On-the-fly computation of composed FST state pairs
/// - **Grammar intersection**: Dynamic exploration of parse forests
/// - **Search spaces**: State spaces too large to enumerate fully
/// - **External data**: States backed by databases or network services
///
/// # Examples
///
/// ```no_run
/// use arcweight::prelude::*;
/// use arcweight::fst::LazyFst;
///
/// fn expand_and_process<W: Semiring>(
/// fst: &impl LazyFst<W>,
/// state: StateId
/// ) -> arcweight::Result<()> {
/// // Ensure state is expanded before accessing arcs
/// fst.expand(state)?;
///
/// // Now arcs are available
/// for arc in fst.arcs(state) {
/// println!("Arc to state {}", arc.nextstate);
/// }
///
/// Ok(())
/// }
/// ```
///
/// # References
///
/// - Mohri, M., Pereira, F., & Riley, M. (2000). The Design Principles of a
/// Weighted Finite-State Transducer Library. *Theoretical Computer Science*,
/// 231(1), 17-32.