Skip to main content

lrtable/
mod.rs

1#![allow(clippy::cognitive_complexity)]
2#![allow(clippy::too_many_arguments)]
3#![allow(clippy::type_complexity)]
4#![forbid(unsafe_code)]
5#![deny(unreachable_pub)]
6
7use std::{hash::Hash, mem::size_of};
8
9use num_traits::{AsPrimitive, PrimInt, Unsigned};
10#[cfg(feature = "serde")]
11use serde::{Deserialize, Serialize};
12#[cfg(feature = "wincode")]
13use wincode::{SchemaRead, SchemaWrite};
14
15mod itemset;
16mod pager;
17mod stategraph;
18pub mod statetable;
19
20#[cfg(test)]
21mod test_utils;
22
23pub use crate::{
24    stategraph::StateGraph,
25    statetable::{Action, StateTable, StateTableError, StateTableErrorKind},
26};
27use cfgrammar::yacc::YaccGrammar;
28
29macro_rules! IdxNewtype {
30    ($(#[$attr:meta])* $n: ident) => {
31        $(#[$attr])*
32        #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
33        #[cfg_attr(feature="serde", derive(Serialize, Deserialize))]
34        #[cfg_attr(feature="wincode", derive(SchemaRead, SchemaWrite))]
35        pub struct $n<T>(pub T);
36
37        impl<T: PrimInt + Unsigned> From<$n<T>> for usize {
38            fn from($n(st): $n<T>) -> Self {
39                debug_assert!(size_of::<usize>() >= size_of::<T>());
40                num_traits::cast(st).unwrap()
41            }
42        }
43
44        impl<T: PrimInt + Unsigned> From<$n<T>> for u32 {
45            fn from($n(st): $n<T>) -> Self {
46                debug_assert!(size_of::<u32>() >= size_of::<T>());
47                num_traits::cast(st).unwrap()
48            }
49        }
50
51        impl<T: PrimInt + Unsigned> $n<T> {
52            pub fn as_storaget(&self) -> T {
53                let $n(st) = self;
54                *st
55            }
56        }
57    }
58}
59
60IdxNewtype!(
61    /// A type specifically for state table indices.
62    ///
63    /// It is guaranteed that `StIdx` can be converted, without loss of precision, to `usize` with
64    /// the idiom `usize::from(...)`.
65    StIdx
66);
67
68#[derive(Clone, Copy)]
69pub enum Minimiser {
70    Pager,
71}
72
73pub fn from_yacc<StorageT: 'static + Hash + PrimInt + Unsigned>(
74    grm: &YaccGrammar<StorageT>,
75    m: Minimiser,
76) -> Result<(StateGraph<StorageT>, StateTable<StorageT>), StateTableError<StorageT>>
77where
78    usize: AsPrimitive<StorageT>,
79{
80    match m {
81        Minimiser::Pager => {
82            let sg = pager::pager_stategraph(grm);
83            let st = StateTable::new(grm, &sg)?;
84            Ok((sg, st))
85        }
86    }
87}