bel_format/
parser_utils.rs

1pub mod string {
2    //! This example shows an example of how to parse an escaped string. The
3    //! rules for the string are similar to JSON and rust. A string is:
4    //!
5    //! - Enclosed by double quotes
6    //! - Can contain any raw unescaped code point besides \ and "
7    //! - Matches the following escape sequences: \b, \f, \n, \r, \t, \", \\, \/
8    //! - Matches code points like Rust: \u{XXXX}, where XXXX can be up to 6
9    //!   hex characters
10    //! - an escape followed by whitespace consumes all whitespace between the
11    //!   escape and the next non-whitespace character
12    extern crate nom;
13
14    // #[global_allocator]
15    // static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
16
17    use nom::branch::alt;
18    use nom::bytes::streaming::{is_not, take_while_m_n};
19    use nom::character::streaming::{char, multispace1};
20    use nom::combinator::{map, map_opt, map_res, value, verify};
21    use nom::error::{FromExternalError, ParseError};
22    use nom::multi::fold_many0;
23    use nom::sequence::{delimited, preceded};
24    use nom::IResult;
25
26    // parser combinators are constructed from the bottom up:
27    // first we write parsers for the smallest elements (escaped characters),
28    // then combine them into larger parsers.
29
30    /// Parse a unicode sequence, of the form u{XXXX}, where XXXX is 1 to 6
31    /// hexadecimal numerals. We will combine this later with parse_escaped_char
32    /// to parse sequences like \u{00AC}.
33    fn parse_unicode<'a, E>(input: &'a str) -> IResult<&'a str, char, E>
34    where
35    E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,
36    {
37        // `take_while_m_n` parses between `m` and `n` bytes (inclusive) that match
38        // a predicate. `parse_hex` here parses between 1 and 6 hexadecimal numerals.
39        let parse_hex = take_while_m_n(1, 6, |c: char| c.is_ascii_hexdigit());
40
41        // `preceeded` takes a prefix parser, and if it succeeds, returns the result
42        // of the body parser. In this case, it parses u{XXXX}.
43        let parse_delimited_hex = preceded(
44            char('u'),
45            // `delimited` is like `preceded`, but it parses both a prefix and a suffix.
46            // It returns the result of the middle parser. In this case, it parses
47            // {XXXX}, where XXXX is 1 to 6 hex numerals, and returns XXXX
48            delimited(char('{'), parse_hex, char('}')),
49        );
50
51        // `map_res` takes the result of a parser and applies a function that returns
52        // a Result. In this case we take the hex bytes from parse_hex and attempt to
53        // convert them to a u32.
54        let parse_u32 = map_res(parse_delimited_hex, move |hex| u32::from_str_radix(hex, 16));
55
56        // map_opt is like map_res, but it takes an Option instead of a Result. If
57        // the function returns None, map_opt returns an error. In this case, because
58        // not all u32 values are valid unicode code points, we have to fallibly
59        // convert to char with from_u32.
60        map_opt(parse_u32, |value| std::char::from_u32(value))(input)
61    }
62
63    /// Parse an escaped character: \n, \t, \r, \u{00AC}, etc.
64    fn parse_escaped_char<'a, E>(input: &'a str) -> IResult<&'a str, char, E>
65    where
66    E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,
67    {
68        preceded(
69            char('\\'),
70            // `alt` tries each parser in sequence, returning the result of
71            // the first successful match
72            alt((
73            parse_unicode,
74            // The `value` parser returns a fixed value (the first argument) if its
75            // parser (the second argument) succeeds. In these cases, it looks for
76            // the marker characters (n, r, t, etc) and returns the matching
77            // character (\n, \r, \t, etc).
78            value('\n', char('n')),
79            value('\r', char('r')),
80            value('\t', char('t')),
81            value('\u{08}', char('b')),
82            value('\u{0C}', char('f')),
83            value('\\', char('\\')),
84            value('/', char('/')),
85            value('"', char('"')),
86            )),
87        )(input)
88    }
89
90    /// Parse a backslash, followed by any amount of whitespace. This is used later
91    /// to discard any escaped whitespace.
92    fn parse_escaped_whitespace<'a, E: ParseError<&'a str>>(
93    input: &'a str,
94    ) -> IResult<&'a str, &'a str, E> {
95        preceded(char('\\'), multispace1)(input)
96    }
97    /// Parse a non-empty block of text that doesn't include \ or "
98    fn parse_literal<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> {
99    // `is_not` parses a string of 0 or more characters that aren't one of the
100    // given characters.
101    let not_quote_slash = is_not("\"\\");
102
103    // `verify` runs a parser, then runs a verification function on the output of
104    // the parser. The verification function accepts out output only if it
105    // returns true. In this case, we want to ensure that the output of is_not
106    // is non-empty.
107    verify(not_quote_slash, |s: &str| !s.is_empty())(input)
108    }
109
110    /// A string fragment contains a fragment of a string being parsed: either
111    /// a non-empty Literal (a series of non-escaped characters), a single
112    /// parsed escaped character, or a block of escaped whitespace.
113    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
114    enum StringFragment<'a> {
115        Literal(&'a str),
116        EscapedChar(char),
117        EscapedWS,
118    }
119
120    /// Combine parse_literal, parse_escaped_whitespace, and parse_escaped_char
121    /// into a StringFragment.
122    fn parse_fragment<'a, E>(input: &'a str) -> IResult<&'a str, StringFragment<'a>, E>
123    where
124    E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,
125    {
126        alt((
127            // The `map` combinator runs a parser, then applies a function to the output
128            // of that parser.
129            map(parse_literal, StringFragment::Literal),
130            map(parse_escaped_char, StringFragment::EscapedChar),
131            value(StringFragment::EscapedWS, parse_escaped_whitespace),
132        ))(input)
133    }
134
135    pub fn some_string<'a, E>(source: &'a str) -> IResult<&'a str, String, E>
136    where E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,
137    {
138        // fold_many0 is the equivalent of iterator::fold. It runs a parser in a loop,
139        // and for each output value, calls a folding function on each output value.
140        fold_many0(
141            // Our parser function– parses a single string fragment
142            parse_fragment,
143            // Our init value, an empty string
144            String::new(),
145            // Our folding function. For each fragment, append the fragment to the
146            // string.
147            |mut string, fragment| {
148            match fragment {
149                StringFragment::Literal(s) => string.push_str(s),
150                StringFragment::EscapedChar(c) => string.push(c),
151                StringFragment::EscapedWS => {}
152            }
153            string
154            },
155        )(source)
156    }
157    
158
159    /// Parse a string. Use a loop of parse_fragment and push all of the fragments
160    /// into an output string.
161    pub fn parse_string_impl<'a, E>(input: &'a str) -> IResult<&'a str, String, E>
162    where E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,
163    {
164        // Finally, parse the string. Note that, if `build_string` could accept a raw
165        // " character, the closing delimiter " would never match. When using
166        // `delimited` with a looping parser (like fold_many0), be sure that the
167        // loop won't accidentally match your closing delimiter!
168        delimited(char('"'), some_string, char('"'))(input)
169    }
170
171    pub fn parse_string(
172        source: &str
173    ) -> Result<(&str, String), nom::Err<nom::error::Error<&str>>>
174    {
175        match parse_string_impl(source) {
176            Err(err) => Err(err),
177            Ok(val) => Ok(val),
178        }
179    }
180}