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
use std::fmt::Debug;
use std::marker::PhantomData;
use std::sync::Arc;

use anyhow::Result;

use crate::fst_properties::FstProperties;
use crate::fst_traits::final_states_iterator::FinalStatesIterator;
use crate::fst_traits::iterators::StateIterator;
use crate::fst_traits::paths_iterator::PathsIterator;
use crate::fst_traits::string_paths_iterator::StringPathsIterator;
use crate::fst_traits::FstIterator;
use crate::semirings::Semiring;
use crate::trs::Trs;
use crate::{StateId, SymbolTable};

/// Trait defining necessary methods for a wFST to access start states and final states.
pub trait CoreFst<W: Semiring> {
    /// Weight use in the wFST. This type must implement the Semiring trait.
    type TRS: Trs<W>;

    /// Returns the ID of the start state of the wFST if it exists else none.
    ///
    /// # Example
    ///
    /// ```
    /// # use rustfst::fst_traits::{CoreFst, MutableFst};
    /// # use rustfst::fst_impls::VectorFst;
    /// # use rustfst::semirings::BooleanWeight;
    /// // 1 - Create an FST
    /// let mut fst = VectorFst::<BooleanWeight>::new();
    /// let s = fst.add_state();
    /// fst.set_start(s);
    ///
    /// // 2 - Access the start state
    /// let start_state = fst.start();
    /// assert_eq!(start_state, Some(s));
    /// ```
    fn start(&self) -> Option<StateId>;

    /// Retrieves the final weight of a state (if the state is a final one).
    ///
    /// # Example
    ///
    /// ```
    /// # use rustfst::fst_traits::{CoreFst, MutableFst, ExpandedFst};
    /// # use rustfst::fst_impls::VectorFst;
    /// # use rustfst::semirings::{BooleanWeight, Semiring};
    /// // 1 - Create an FST
    /// let mut fst = VectorFst::<BooleanWeight>::new();
    /// let s1 = fst.add_state();
    /// let s2 = fst.add_state();
    /// fst.set_final(s2, BooleanWeight::one());
    ///
    /// // 2 - Access the final weight of each state
    /// assert_eq!(fst.final_weight(s1).unwrap(), None);
    /// assert_eq!(fst.final_weight(s2).unwrap(), Some(BooleanWeight::one()));
    /// assert!(fst.final_weight(s2 + 1).is_err());
    /// ```
    fn final_weight(&self, state: StateId) -> Result<Option<W>>;

    /// Retrieves the final weight of a state (if the state is a final one).
    ///
    /// # Safety
    ///
    /// Unsafe behaviour if `state` is not present in Fst.
    ///
    unsafe fn final_weight_unchecked(&self, state: StateId) -> Option<W>;

    /// Number of trs leaving a specific state in the wFST.
    ///
    /// # Example
    ///
    /// ```
    /// # use rustfst::fst_traits::{CoreFst, MutableFst, ExpandedFst};
    /// # use rustfst::fst_impls::VectorFst;
    /// # use rustfst::semirings::{BooleanWeight, Semiring};
    /// # use rustfst::Tr;
    /// let mut fst = VectorFst::<BooleanWeight>::new();
    /// let s1 = fst.add_state();
    /// let s2 = fst.add_state();
    ///
    /// assert_eq!(fst.num_trs(s1).unwrap(), 0);
    /// fst.add_tr(s1, Tr::new(3, 5, BooleanWeight::new(true), s2));
    /// assert_eq!(fst.num_trs(s1).unwrap(), 1);
    /// ```
    fn num_trs(&self, s: StateId) -> Result<usize>;

    /// Number of trs leaving a specific state in the wFST.
    ///
    /// # Safety
    ///
    /// Unsafe behaviour if `state` is not present in Fst.
    ///
    unsafe fn num_trs_unchecked(&self, state: StateId) -> usize;

    /// Returns whether or not the state with identifier passed as parameters is a final state.
    ///
    /// # Example
    ///
    /// ```
    /// # use rustfst::fst_traits::{CoreFst, MutableFst, ExpandedFst};
    /// # use rustfst::fst_impls::VectorFst;
    /// # use rustfst::semirings::{BooleanWeight, Semiring};
    /// // 1 - Create an FST
    /// let mut fst = VectorFst::<BooleanWeight>::new();
    /// let s1 = fst.add_state();
    /// let s2 = fst.add_state();
    /// fst.set_final(s2, BooleanWeight::one());
    ///
    /// // 2 - Test if a state is final
    /// assert_eq!(fst.is_final(s1).unwrap(), false);
    /// assert_eq!(fst.is_final(s2).unwrap(), true);
    /// assert!(fst.is_final(s2 + 1).is_err());
    /// ```
    #[inline]
    fn is_final(&self, state_id: StateId) -> Result<bool> {
        Ok(self
            .final_weight(state_id)?
            .map(|final_weight| final_weight != W::zero())
            .unwrap_or(false))
    }

    /// Returns whether or not the state with identifier passed as parameters is a final state.
    ///
    /// # Safety
    ///
    /// Unsafe behaviour if `state` is not present in Fst.
    ///
    #[inline]
    unsafe fn is_final_unchecked(&self, state: StateId) -> bool {
        self.final_weight_unchecked(state).is_some()
    }

    /// Check whether a state is the start state or not.
    #[inline]
    fn is_start(&self, state_id: StateId) -> bool {
        Some(state_id) == self.start()
    }

    /// Get an iterator on the transitions leaving state `state`.
    fn get_trs(&self, state_id: StateId) -> Result<Self::TRS>;

    /// Get an iterator on the transitions leaving state `state`.
    ///
    /// # Safety
    ///
    /// Unsafe behaviour if `state` is not present in Fst.
    ///
    unsafe fn get_trs_unchecked(&self, state: StateId) -> Self::TRS;

    /// Retrieve the `FstProperties` stored in the Fst. As a result, all the properties returned
    /// are verified by the Fst but some other properties might be true as well despite the flag
    /// not being set.
    fn properties(&self) -> FstProperties;

    /// Apply a mask to the `FstProperties` returned.
    fn properties_with_mask(&self, mask: FstProperties) -> FstProperties {
        self.properties() & mask
    }

    /// Retrieve the `FstProperties` in the Fst and check that all the
    /// properties in `props_known` are known (not the same as true). If not an error is returned.
    ///
    /// A property is known if we known for sure if it is true of false.
    fn properties_check(&self, props_known: FstProperties) -> Result<FstProperties> {
        let props = self.properties();
        if !props.knows(props_known) {
            bail!(
                "Properties are not known : {:?}. Properties of the Fst : {:?}",
                props_known,
                props
            )
        }
        Ok(props)
    }

    /// Returns the number of trs with epsilon input labels leaving a state.
    ///
    /// # Example :
    /// ```
    /// # use rustfst::fst_traits::{MutableFst, Fst, CoreFst};
    /// # use rustfst::fst_impls::VectorFst;
    /// # use rustfst::semirings::{Semiring, IntegerWeight};
    /// # use rustfst::EPS_LABEL;
    /// # use rustfst::Tr;
    /// let mut fst = VectorFst::<IntegerWeight>::new();
    /// let s0 = fst.add_state();
    /// let s1 = fst.add_state();
    ///
    /// fst.add_tr(s0, Tr::new(EPS_LABEL, 18, IntegerWeight::one(), s1));
    /// fst.add_tr(s0, Tr::new(76, EPS_LABEL, IntegerWeight::one(), s1));
    /// fst.add_tr(s0, Tr::new(EPS_LABEL, 18, IntegerWeight::one(), s1));
    /// fst.add_tr(s0, Tr::new(45, 18, IntegerWeight::one(), s0));
    /// fst.add_tr(s1, Tr::new(76, 18, IntegerWeight::one(), s1));
    ///
    /// assert_eq!(fst.num_input_epsilons(s0).unwrap(), 2);
    /// assert_eq!(fst.num_input_epsilons(s1).unwrap(), 0);
    /// ```
    fn num_input_epsilons(&self, state: StateId) -> Result<usize>;

    /// Returns the number of trs with epsilon output labels leaving a state.
    ///
    /// # Example :
    /// ```
    /// # use rustfst::fst_traits::{MutableFst, Fst, CoreFst};
    /// # use rustfst::fst_impls::VectorFst;
    /// # use rustfst::semirings::{Semiring, IntegerWeight};
    /// # use rustfst::EPS_LABEL;
    /// # use rustfst::Tr;
    /// let mut fst = VectorFst::<IntegerWeight>::new();
    /// let s0 = fst.add_state();
    /// let s1 = fst.add_state();
    ///
    /// fst.add_tr(s0, Tr::new(EPS_LABEL, 18, IntegerWeight::one(), s1));
    /// fst.add_tr(s0, Tr::new(76, EPS_LABEL, IntegerWeight::one(), s1));
    /// fst.add_tr(s0, Tr::new(EPS_LABEL, 18, IntegerWeight::one(), s1));
    /// fst.add_tr(s0, Tr::new(45, 18, IntegerWeight::one(), s0));
    /// fst.add_tr(s1, Tr::new(76, 18, IntegerWeight::one(), s1));
    ///
    /// assert_eq!(fst.num_output_epsilons(s0).unwrap(), 1);
    /// assert_eq!(fst.num_output_epsilons(s1).unwrap(), 0);
    /// ```
    fn num_output_epsilons(&self, state: StateId) -> Result<usize>;
}

/// Trait defining the minimum interface necessary for a wFST.
pub trait Fst<W: Semiring>:
    CoreFst<W> + for<'b> StateIterator<'b> + Debug + for<'c> FstIterator<'c, W>
{
    /// Retrieves the input `SymbolTable` associated to the Fst.
    /// If no SymbolTable has been previously attached then `None` is returned.
    fn input_symbols(&self) -> Option<&Arc<SymbolTable>>;

    /// Retrieves the output `SymbolTable` associated to the Fst.
    /// If no SymbolTable has been previously attached then `None` is returned.
    fn output_symbols(&self) -> Option<&Arc<SymbolTable>>;

    /// Attaches an output `SymbolTable` to the Fst.
    /// The `SymbolTable` is not duplicated with the use of Arc.
    fn set_input_symbols(&mut self, symt: Arc<SymbolTable>);

    /// Attaches an output `SymbolTable` to the Fst.
    /// The `SymbolTable` is not duplicated with the use of Arc.
    fn set_output_symbols(&mut self, symt: Arc<SymbolTable>);

    /// Removes the input symbol table from the Fst and retrieves it.
    fn take_input_symbols(&mut self) -> Option<Arc<SymbolTable>>;
    /// Removes the output symbol table from the Fst and retrieves it.
    fn take_output_symbols(&mut self) -> Option<Arc<SymbolTable>>;

    /// Returns an Iterator on the final states along with their weight.
    fn final_states_iter(&self) -> FinalStatesIterator<W, Self>
    where
        Self: std::marker::Sized,
    {
        FinalStatesIterator {
            fst: self,
            state_iter: self.states_iter(),
            w: PhantomData,
        }
    }

    /// Returns an Iterator on the paths accepted by the Fst.
    ///
    /// # Example :
    /// ```
    /// # use std::sync::Arc;
    /// # use rustfst::fst_impls::VectorFst;
    /// # use rustfst::semirings::TropicalWeight;
    /// # use rustfst::{Semiring, SymbolTable, symt};
    /// # use rustfst::utils::transducer;
    /// # use rustfst::fst_traits::Fst;
    /// let mut fst : VectorFst<_> = transducer(&[1, 2, 3], &[4, 5], TropicalWeight::one());
    ///
    /// let paths : Vec<_> = fst.paths_iter().collect();
    /// assert_eq!(paths.len(), 1);
    /// assert_eq!(paths[0].ilabels.as_slice(), &[1, 2, 3]);
    /// assert_eq!(paths[0].olabels.as_slice(), &[4, 5]);
    /// assert_eq!(&paths[0].weight, &TropicalWeight::one());
    /// ```
    fn paths_iter(&self) -> PathsIterator<W, Self>
    where
        Self: std::marker::Sized,
    {
        PathsIterator::new(self)
    }

    /// Returns an Iterator on the paths accepted by the Fst. Plus, handles the SymbolTable
    /// allowing to retrieve the strings instead of only the sequence of labels.
    ///
    /// # Example :
    /// ```
    /// # use std::sync::Arc;
    /// # use rustfst::fst_impls::VectorFst;
    /// # use rustfst::semirings::TropicalWeight;
    /// # use rustfst::{Semiring, SymbolTable, symt};
    /// # use rustfst::utils::transducer;
    /// # use rustfst::fst_traits::Fst;
    /// let mut fst : VectorFst<_> = transducer(&[1, 2, 3], &[4, 5], TropicalWeight::one());
    /// let symt = symt!["a", "b", "c", "d", "e"];
    /// let symt = Arc::new(symt);
    /// fst.set_input_symbols(Arc::clone(&symt));
    /// fst.set_output_symbols(Arc::clone(&symt));
    ///
    /// let paths : Vec<_> = fst.string_paths_iter().unwrap().collect();
    /// assert_eq!(paths.len(), 1);
    /// assert_eq!(paths[0].ilabels(), &[1, 2, 3]);
    /// assert_eq!(paths[0].olabels(), &[4, 5]);
    /// assert_eq!(paths[0].weight(), &TropicalWeight::one());
    /// assert_eq!(paths[0].istring().unwrap(), "a b c".to_string());
    /// assert_eq!(paths[0].ostring().unwrap(), "d e".to_string());
    /// ```
    fn string_paths_iter(&self) -> Result<StringPathsIterator<W, Self>>
    where
        Self: std::marker::Sized,
    {
        StringPathsIterator::new(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fst_traits::MutableFst;
    use crate::prelude::TropicalWeight;
    use crate::prelude::VectorFst;

    #[test]
    fn test_is_final() -> Result<()> {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s = fst.add_state();
        assert!(!fst.is_final(s)?);
        fst.set_final(s, TropicalWeight::zero())?;
        assert!(!fst.is_final(s)?);
        fst.set_final(s, TropicalWeight::one())?;
        assert!(fst.is_final(s)?);
        Ok(())
    }
}