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
use crate::{Symbol, Terminal};
use std::fmt::{Debug, Display, Error, Formatter};
use std::hash::Hash;
use std::ops::Index;
pub type Rhs = Vec<Symbol>;
#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct Pr(pub Symbol, pub Rhs);
impl Display for Pr {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(
f,
"{}: {};",
self.0,
self.1
.iter()
.fold(Vec::new(), |mut acc, s| {
acc.push(format!("{}", s));
acc
})
.join(" ")
)
}
}
impl Default for Pr {
fn default() -> Self {
Self(Symbol::N("".to_owned()), Rhs::default())
}
}
impl Pr {
pub fn new(n: &str, r: Rhs) -> Self {
if !r.iter().all(Self::is_allowed_symbol) {
panic!("Unexpected symbol kind!");
}
Self(Symbol::N(n.to_owned()), r)
}
pub fn get_n(&self) -> String {
self.0.get_n().unwrap()
}
pub fn get_n_str(&self) -> &str {
self.0.get_n_ref().unwrap()
}
pub fn get_r(&self) -> &Rhs {
&self.1
}
pub fn take(self) -> (String, Rhs) {
(self.0.get_n().unwrap(), self.1)
}
pub fn set_n(&mut self, n: String) {
self.0 = Symbol::N(n);
}
pub fn is_empty(&self) -> bool {
self.1.is_empty()
}
pub fn len(&self) -> usize {
self.1.len()
}
fn is_allowed_symbol(s: &Symbol) -> bool {
!(matches!(s, Symbol::T(Terminal::Eps)))
}
pub fn format<R>(&self, scanner_state_resolver: &R) -> String
where
R: Fn(&[usize]) -> String,
{
format!(
"{}: {};",
self.0,
self.1
.iter()
.fold(Vec::new(), |mut acc, s| {
acc.push(s.format(scanner_state_resolver));
acc
})
.join(" ")
)
}
}
impl Index<usize> for Pr {
type Output = Symbol;
fn index(&self, idx: usize) -> &Self::Output {
if idx == 0 {
&self.0
} else {
&self.1[idx]
}
}
}