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