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