Debian Codegraph @

debian/missing-sources/winnow/examples/string/parser.rs

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