gml_parser/
parser.rs

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
/*!
A nom-based GML parser.
*/

use std::collections::HashMap;

use nom::{
    bytes::complete::{escaped_transform, is_not, tag, take, take_while},
    character::complete::{digit1, multispace0, multispace1, space0},
    character::{is_alphabetic, is_alphanumeric},
    combinator::{self, map_res, recognize, verify},
    error::{ErrorKind, FromExternalError, ParseError},
    sequence::tuple,
    IResult,
};

use crate::gml::{Edge, Gml, GmlItem, Node, Value};

pub trait GmlParseError<'a>:
    ParseError<&'a str>
    + FromExternalError<&'a str, std::num::ParseIntError>
    + FromExternalError<&'a str, std::num::ParseFloatError>
    + FromExternalError<&'a str, &'a str>
    + std::fmt::Debug
{
}
impl<'a, T> GmlParseError<'a> for T where
    T: ParseError<&'a str>
        + FromExternalError<&'a str, std::num::ParseIntError>
        + FromExternalError<&'a str, std::num::ParseFloatError>
        + FromExternalError<&'a str, &'a str>
        + std::fmt::Debug
{
}

/// Take `count` characters and make sure they all satisfy `cond`.
fn take_verify<'a, E: GmlParseError<'a>>(
    count: u32,
    cond: impl Fn(char) -> bool,
) -> impl Fn(&'a str) -> IResult<&'a str, &'a str, E> {
    move |i| verify(take(count), |s: &str| s.chars().all(&cond))(i)
}

/// Parse a GML key.
pub fn key<'a, E: GmlParseError<'a>>(input: &'a str) -> IResult<&'a str, &'a str, E> {
    // a key starts with the a character [a-zA-Z_], and has remaining characters [a-zA-Z0-9_]
    let take_first = take_verify(1, |chr| is_alphabetic(chr as u8) || chr == '_');
    let take_remaining = take_while(|chr| is_alphanumeric(chr as u8) || chr == '_');
    let (input, key) = recognize(tuple((take_first, take_remaining)))(input)?;
    Ok((input, key))
}

/// Parse a GML item (a key + value).
pub fn item<'a, E: GmlParseError<'a>>(input: &'a str) -> IResult<&'a str, GmlItem<'a>, E> {
    match key(input)? {
        (input, "node") => node(input).map(|(input, node)| (input, GmlItem::Node(node))),
        (input, "edge") => edge(input).map(|(input, edge)| (input, GmlItem::Edge(edge))),
        (input, "directed") => {
            int_as_bool(input).map(|(input, value)| (input, GmlItem::Directed(value)))
        }
        (input, name) => {
            value(input).map(|(input, value)| (input, GmlItem::KeyValue((name.into(), value))))
        }
    }
}

/// Parse a GML graph.
pub fn gml<'a, E: GmlParseError<'a>>(input: &'a str) -> IResult<&'a str, Gml<'a>, E> {
    let (input, _) = multispace0(input)?;
    let (input, _) = tag("graph")(input)?;
    let (input, _) = space0(input)?;
    let (input, _) = tag("[")(input)?;
    let (input, _) = newline(input)?;

    let (input, (items, _)) = nom::multi::many_till(item, tag("]"))(input)?;

    let [nodes, edges, directed, others]: [Vec<_>; 4] = partition(items.into_iter(), |x| match x {
        GmlItem::Node(_) => 0,
        GmlItem::Edge(_) => 1,
        GmlItem::Directed(_) => 2,
        GmlItem::KeyValue(_) => 3,
    });

    let nodes: Vec<_> = nodes
        .into_iter()
        .map(|x| {
            if let GmlItem::Node(x) = x {
                x
            } else {
                panic!()
            }
        })
        .collect();
    let edges: Vec<_> = edges
        .into_iter()
        .map(|x| {
            if let GmlItem::Edge(x) = x {
                x
            } else {
                panic!()
            }
        })
        .collect();
    let others: Vec<_> = others
        .into_iter()
        .map(|x| {
            if let GmlItem::KeyValue(x) = x {
                x
            } else {
                panic!()
            }
        })
        .collect();

    if directed.len() > 1 {
        result_str_to_nom(
            input,
            Err("The 'directed' key must only be specified once"),
            ErrorKind::Fail,
        )?;
    }
    let directed = match directed.first() {
        Some(GmlItem::Directed(x)) => *x,
        Some(_) => panic!(),
        // GML graphs are undirected by default
        None => false,
    };

    let expected_len = others.len();
    let others: HashMap<_, _> = others.into_iter().collect();
    if others.len() != expected_len {
        result_str_to_nom(
            input,
            Err("Duplicate keys are not supported"),
            ErrorKind::Fail,
        )?;
    }

    let (input, _) = multispace0(input)?;

    Ok((
        input,
        Gml {
            directed,
            nodes,
            edges,
            other: others,
        },
    ))
}

/// Parse a GML node.
fn node<'a, E: GmlParseError<'a>>(input: &'a str) -> IResult<&'a str, Node<'a>, E> {
    let (input, _) = space0(input)?;
    let (input, _) = tag("[")(input)?;
    let (input, _) = newline(input)?;

    let (input, (key_values, _)) = nom::multi::many_till(tuple((key, value)), tag("]"))(input)?;
    let expected_len = key_values.len();
    let mut key_values: HashMap<_, _> = key_values.into_iter().collect();
    if key_values.len() != expected_len {
        result_str_to_nom(
            input,
            Err("Duplicate keys are not supported"),
            ErrorKind::Fail,
        )?;
    }

    let (input, _) = newline(input)?;

    let id = match key_values.remove("id") {
        Some(Value::Int(x)) => Some(x as u32),
        Some(_) => result_str_to_nom(input, Err("Incorrect 'id' type"), ErrorKind::Fail)?,
        None => None,
    };

    Ok((input, Node::new(id, key_values)))
}

/// Parse a GML edge.
fn edge<'a, E: GmlParseError<'a>>(input: &'a str) -> IResult<&'a str, Edge<'a>, E> {
    let (input, _) = space0(input)?;
    let (input, _) = tag("[")(input)?;
    let (input, _) = newline(input)?;

    let (input, (key_values, _)) = nom::multi::many_till(tuple((key, value)), tag("]"))(input)?;
    let expected_len = key_values.len();
    let mut key_values: HashMap<_, _> = key_values.into_iter().collect();
    if key_values.len() != expected_len {
        result_str_to_nom(
            input,
            Err("Duplicate keys are not supported"),
            ErrorKind::Fail,
        )?;
    }

    let (input, _) = newline(input)?;

    let source = match key_values.remove("source") {
        Some(Value::Int(x)) => x,
        Some(_) => result_str_to_nom(input, Err("Incorrect 'source' type"), ErrorKind::Fail)?,
        None => result_str_to_nom(input, Err("'source' doesn't exist"), ErrorKind::NoneOf)?,
    };

    let target = match key_values.remove("target") {
        Some(Value::Int(x)) => x,
        Some(_) => result_str_to_nom(input, Err("Incorrect 'target' type"), ErrorKind::Fail)?,
        None => result_str_to_nom(input, Err("'target' doesn't exist"), ErrorKind::NoneOf)?,
    };

    Ok((input, Edge::new(source as u32, target as u32, key_values)))
}

fn value<'a, E: GmlParseError<'a>>(input: &'a str) -> IResult<&'a str, Value<'a>, E> {
    let (input, _) = space0(input)?;

    let (input, (value, _)) = nom::branch::alt((
        tuple((int, newline)),
        tuple((float, newline)),
        tuple((string, newline)),
    ))(input)?;

    Ok((input, value))
}

fn int<'a, E: GmlParseError<'a>>(input: &'a str) -> IResult<&'a str, Value<'a>, E> {
    let (input, value) = map_res(recognize(digit1), str::parse)(input)?;
    Ok((input, Value::Int(value)))
}

fn float<'a, E: GmlParseError<'a>>(input: &'a str) -> IResult<&'a str, Value<'a>, E> {
    let (input, value) = map_res(nom::number::complete::recognize_float, str::parse)(input)?;
    Ok((input, Value::Float(value)))
}

/// Parse a GML string.
fn string<'a, E: GmlParseError<'a>>(input: &'a str) -> IResult<&'a str, Value<'a>, E> {
    let (input, _) = tag("\"")(input)?;
    let (input, value) = escaped_transform(
        is_not("\""),
        '\\',
        nom::branch::alt((
            combinator::value("\\", tag("\\")),
            combinator::value("\"", tag("\"")),
        )),
    )(input)?;
    let (input, _) = tag("\"")(input)?;

    Ok((input, Value::Str(value.into())))
}

fn newline<'a, E: GmlParseError<'a>>(input: &'a str) -> IResult<&'a str, &'a str, E> {
    recognize(tuple((space0, multispace1, space0)))(input)
}

fn int_to_bool(x: i32) -> Result<bool, &'static str> {
    match x {
        1 => Ok(true),
        0 => Ok(false),
        _ => Err("Bool must be 0 or 1"),
    }
}

fn int_as_bool<'a, E: GmlParseError<'a>>(input: &'a str) -> IResult<&'a str, bool, E> {
    let (input, value) = value(input)?;

    let value = match value {
        Value::Int(x) => result_str_to_nom(input, int_to_bool(x), ErrorKind::Fail)?,
        _ => result_str_to_nom(input, Err("Value was not an integer"), ErrorKind::Fail)?,
    };

    Ok((input, value))
}

fn result_str_to_nom<'a, T, E: GmlParseError<'a>>(
    input: &'a str,
    result: Result<T, &'a str>,
    error_kind: ErrorKind,
) -> Result<T, nom::Err<E>> {
    result.map_err(|e| nom::Err::Failure(E::from_external_error(input, error_kind, e)))
}

fn partition<I, B, F, const N: usize>(iter: I, f: F) -> [B; N]
where
    I: Iterator + Sized,
    B: Default + Extend<I::Item>,
    [B; N]: Default,
    F: FnMut(&I::Item) -> usize,
{
    #[inline]
    fn extend<'a, T, B: Extend<T>, const N: usize>(
        mut f: impl FnMut(&T) -> usize + 'a,
        collections: &'a mut [B; N],
    ) -> impl FnMut((), T) + 'a {
        move |(), x| {
            collections[f(&x)].extend(Some(x));
        }
    }

    let mut collections: [B; N] = Default::default();

    iter.fold((), extend(f, &mut collections));

    collections
}