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
use std::fmt;

/// Is a rule a basic rule or an incremental alternative?
/// See https://tools.ietf.org/html/rfc5234#section-3.3
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Definition {
    /// Basic Rule Definition
    Basic,
    /// Incremental Alternative
    Incremental,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Rule {
    name: String,
    node: Node,
    definition: Definition,
}

impl Rule {
    pub fn new(name: &str, node: Node) -> Rule {
        Rule {
            name: name.into(),
            node,
            definition: Definition::Basic,
        }
    }

    pub fn definition(mut self, definition: Definition) -> Self {
        self.definition = definition;
        self
    }

    pub fn get_name(&self) -> &str {
        &self.name
    }

    pub fn get_node(&self) -> &Node {
        &self.node
    }

    pub fn get_definition(&self) -> Definition {
        self.definition
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Node {
    Alternation(Vec<Node>),
    Concatenation(Vec<Node>),
    Repetition(Repetition),
    Rulename(String),
    Group(Box<Node>),
    Optional(Box<Node>),
    CharVal(String),
    NumVal(Range),
    ProseVal(String),
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Repetition {
    repeat: Repeat,
    node: Box<Node>,
}

impl Repetition {
    pub fn new(repeat: Repeat, node: Node) -> Self {
        Self {
            repeat,
            node: Box::new(node),
        }
    }

    pub fn get_repeat(&self) -> &Repeat {
        &self.repeat
    }

    pub fn get_node(&self) -> &Node {
        &self.node
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct Repeat {
    min: Option<usize>,
    max: Option<usize>,
}

impl Repeat {
    pub fn new() -> Self {
        Self {
            min: None,
            max: None,
        }
    }

    pub fn with(min: Option<usize>, max: Option<usize>) -> Self {
        Self { min, max }
    }

    pub fn get_min(&self) -> Option<usize> {
        self.min
    }

    pub fn get_max(&self) -> Option<usize> {
        self.max
    }

    pub fn get_min_max(&self) -> (Option<usize>, Option<usize>) {
        (self.min, self.max)
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Range {
    OneOf(Vec<u32>), // FIXME: out of spec, but useful?
    Range(u32, u32),
}

impl fmt::Display for Rule {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.name)?;
        match self.definition {
            Definition::Basic => write!(f, " = ")?,
            Definition::Incremental => write!(f, " =/ ")?,
        }
        write!(f, "{}", self.node)
    }
}

impl fmt::Display for Node {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Node::Alternation(nodes) => {
                if let Some((last, elements)) = nodes.split_last() {
                    for item in elements {
                        write!(f, "{} / ", item)?;
                    }
                    write!(f, "{}", last)?;
                }
            }
            Node::Concatenation(nodes) => {
                if let Some((last, elements)) = nodes.split_last() {
                    for item in elements {
                        write!(f, "{} ", item)?;
                    }
                    write!(f, "{}", last)?;
                }
            }
            Node::Repetition(Repetition { repeat, node }) => {
                if let Some(min) = repeat.min {
                    write!(f, "{}", min)?;
                }

                write!(f, "*")?;

                if let Some(max) = repeat.max {
                    write!(f, "{}", max)?;
                }

                write!(f, "{}", node)?;
            }
            Node::Rulename(name) => {
                write!(f, "{}", name)?;
            }
            Node::Group(node) => {
                write!(f, "({})", node)?;
            }
            Node::Optional(node) => {
                write!(f, "[{}]", node)?;
            }
            Node::CharVal(str) => {
                write!(f, "\"{}\"", str)?;
            }
            Node::NumVal(range) => {
                write!(f, "%x")?;
                match range {
                    Range::OneOf(allowed) => {
                        if let Some((last, elements)) = allowed.split_last() {
                            for item in elements {
                                write!(f, "{:02X}.", item)?;
                            }
                            write!(f, "{:02X}", last)?;
                        }
                    }
                    Range::Range(from, to) => {
                        write!(f, "{:02X}-{:02X}", from, to)?;
                    }
                }
            }
            Node::ProseVal(str) => {
                write!(f, "<{}>", str)?;
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_display_rule() {
        let test = Rule::new("rule", Node::Rulename("A".into()));
        let expected = "rule = A";
        let got = test.to_string();
        assert_eq!(expected, got);

        let test =
            Rule::new("rule", Node::Rulename("A".into())).definition(Definition::Incremental);
        let expected = "rule =/ A";
        let got = test.to_string();
        assert_eq!(expected, got);
    }

    #[test]
    fn test_display_prose() {
        let rule = Rule::new("rule", Node::ProseVal("test".into()));
        assert_eq!("rule = <test>", rule.to_string());
    }

    #[test]
    fn test_impl_trait() {
        // Make sure that others can implement their own traits for Rule.
        trait Foo {
            fn foo(&self);
        }

        impl Foo for Rule {
            fn foo(&self) {
                println!("{}", self.name);
            }
        }
    }
}