snarkvm_console_network_environment/traits/
parse_string.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16/// From <https://github.com/Geal/nom/blob/main/examples/string.rs>
17pub mod string_parser {
18    /// This example shows an example of how to parse an escaped string. The
19    /// rules for the string are similar to JSON and rust. A string is:
20    ///
21    /// - Enclosed by double quotes
22    /// - Can contain any raw unescaped code point besides \ and "
23    /// - Matches the following escape sequences: \b, \f, \n, \r, \t, \", \\, \/
24    /// - Matches code points like Rust: \u{XXXX}, where XXXX can be up to 6
25    ///   hex characters
26    /// - an escape followed by whitespace consumes all whitespace between the
27    ///   escape and the next non-whitespace character
28    use nom::{
29        Err::Error,
30        IResult,
31        branch::alt,
32        bytes::streaming::{is_not, take_while_m_n},
33        character::streaming::{char, multispace1},
34        combinator::{map, map_opt, map_res, value, verify},
35        error::{ErrorKind, FromExternalError, ParseError},
36        multi::fold_many0,
37        sequence::{delimited, preceded},
38    };
39
40    /// Checks for supported code points.
41    ///
42    /// We regard the following characters as safe:
43    /// - Horizontal tab (code 9).
44    /// - Line feed (code 10).
45    /// - Carriage return (code 13).
46    /// - Space (code 32).
47    /// - Visible ASCII (codes 33-126).
48    /// - Non-ASCII Unicode scalar values (codes 128+) except
49    ///   * bidi embeddings, overrides and their termination (codes U+202A-U+202E)
50    ///   * isolates (codes U+2066-U+2069)
51    ///
52    /// The Unicode bidi characters are well-known for presenting Trojan Source dangers.
53    /// The ASCII backspace (code 8) can be also used to make text look different from what it is,
54    /// and a similar danger may apply to delete (126).
55    /// Other ASCII control characters
56    /// (except for horizontal tab, space, line feed, and carriage return, which are allowed)
57    /// may or may not present dangers, but we see no good reason for allowing them.
58    /// At some point we may want to disallow additional non-ASCII characters,
59    /// if we see no good reason to allow them.
60    ///
61    /// Note that we say 'Unicode scalar values' above,
62    /// because we read UTF-8-decoded characters,
63    /// and thus we will never encounter surrogate code points,
64    /// and we do not need to explicitly exclude them in this function.
65    pub fn is_char_supported(c: char) -> bool {
66        !is_char_unsupported(c)
67    }
68
69    /// Checks for unsupported "invisible" code points.
70    fn is_char_unsupported(c: char) -> bool {
71        let code = c as u32;
72
73        // A quick early return, as anything above is supported.
74        if code > 0x2069 {
75            return false;
76        }
77
78        // A "divide and conquer" approach for greater performance; ranges are
79        // checked before single values and all the comparisons get "reused".
80        if code < 0x202a {
81            if code <= 31 { !(9..14).contains(&code) || code == 11 || code == 12 } else { code == 127 }
82        } else {
83            code <= 0x202e || code >= 0x2066
84        }
85    }
86
87    /// Parse a Unicode sequence, of the form u{XXXX}, where XXXX is 1 to 6
88    /// hexadecimal numerals. We will combine this later with [parse_escaped_char]
89    /// to parse sequences like \u{00AC}.
90    fn parse_unicode<'a, E>(input: &'a str) -> IResult<&'a str, char, E>
91    where
92        E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,
93    {
94        // `take_while_m_n` parses between `m` and `n` bytes (inclusive) that match
95        // a predicate. `parse_hex` here parses between 1 and 6 hexadecimal numerals.
96        let parse_hex = take_while_m_n(1, 6, |c: char| c.is_ascii_hexdigit());
97
98        // `preceded` takes a prefix parser, and if it succeeds, returns the result
99        // of the body parser. In this case, it parses u{XXXX}.
100        let parse_delimited_hex = preceded(
101            char('u'),
102            // `delimited` is like `preceded`, but it parses both a prefix and a suffix.
103            // It returns the result of the middle parser. In this case, it parses
104            // {XXXX}, where XXXX is 1 to 6 hex numerals, and returns XXXX
105            delimited(char('{'), parse_hex, char('}')),
106        );
107
108        // `map_res` takes the result of a parser and applies a function that returns
109        // a Result. In this case we take the hex bytes from parse_hex and attempt to
110        // convert them to a u32.
111        let parse_u32 = map_res(parse_delimited_hex, move |hex| u32::from_str_radix(hex, 16));
112
113        // map_opt is like map_res, but it takes an Option instead of a Result. If
114        // the function returns None, map_opt returns an error. In this case, because
115        // not all u32 values are valid Unicode code points, we have to fallibly
116        // convert to char with from_u32.
117        map_opt(parse_u32, std::char::from_u32)(input)
118    }
119
120    /// Parse an escaped character: \n, \t, \r, \u{00AC}, etc.
121    fn parse_escaped_char<'a, E>(input: &'a str) -> IResult<&'a str, char, E>
122    where
123        E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,
124    {
125        preceded(
126            char('\\'),
127            // `alt` tries each parser in sequence, returning the result of
128            // the first successful match
129            alt((
130                parse_unicode,
131                // The `value` parser returns a fixed value (the first argument) if its
132                // parser (the second argument) succeeds. In these cases, it looks for
133                // the marker characters (n, r, t, etc.) and returns the matching
134                // character (\n, \r, \t, etc.).
135                value('\n', char('n')),
136                value('\r', char('r')),
137                value('\t', char('t')),
138                value('\u{08}', char('b')),
139                value('\u{0C}', char('f')),
140                value('\\', char('\\')),
141                value('/', char('/')),
142                value('"', char('"')),
143            )),
144        )(input)
145    }
146
147    /// Parse a backslash, followed by any amount of whitespace. This is used later
148    /// to discard any escaped whitespace.
149    fn parse_escaped_whitespace<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> {
150        preceded(char('\\'), multispace1)(input)
151    }
152
153    /// Parse a non-empty block of text that doesn't include \ or "
154    fn parse_literal<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> {
155        // Return an error if the literal contains an unsupported code point.
156        if input.chars().any(is_char_unsupported) {
157            return Err(Error(E::from_error_kind("String literal contains invalid codepoint", ErrorKind::Char)));
158        }
159
160        // `is_not` parses a string of 0 or more characters that aren't one of the
161        // given characters.
162        let not_quote_slash = is_not("\"\\");
163
164        // `verify` runs a parser, then runs a verification function on the output of
165        // the parser. The verification function accepts output only if it
166        // returns true. In this case, we want to ensure that the output of is_not
167        // is non-empty.
168        verify(not_quote_slash, |s: &str| !s.is_empty())(input)
169    }
170
171    /// A string fragment contains a fragment of a string being parsed: either
172    /// a non-empty Literal (a series of non-escaped characters), a single
173    /// parsed escaped character, or a block of escaped whitespace.
174    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
175    enum StringFragment<'a> {
176        Literal(&'a str),
177        EscapedChar(char),
178        EscapedWS,
179    }
180
181    /// Combine parse_literal, parse_escaped_whitespace, and parse_escaped_char
182    /// into a StringFragment.
183    fn parse_fragment<'a, E>(input: &'a str) -> IResult<&'a str, StringFragment<'a>, E>
184    where
185        E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,
186    {
187        alt((
188            // The `map` combinator runs a parser, then applies a function to the output
189            // of that parser.
190            map(parse_literal, StringFragment::Literal),
191            map(parse_escaped_char, StringFragment::EscapedChar),
192            value(StringFragment::EscapedWS, parse_escaped_whitespace),
193        ))(input)
194    }
195
196    /// Parse a string. Use a loop of parse_fragment and push all of the fragments
197    /// into an output string.
198    pub fn parse_string<'a, E>(input: &'a str) -> IResult<&'a str, String, E>
199    where
200        E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,
201    {
202        // fold_many0 is the equivalent of iterator::fold. It runs a parser in a loop,
203        // and for each output value, calls a folding function on each output value.
204        let build_string = fold_many0(
205            // Our parser function– parses a single string fragment
206            parse_fragment,
207            // Our init value, an empty string
208            String::new,
209            // Our folding function. For each fragment, append the fragment to the
210            // string.
211            |mut string, fragment| {
212                match fragment {
213                    StringFragment::Literal(s) => string.push_str(s),
214                    StringFragment::EscapedChar(c) => string.push(c),
215                    StringFragment::EscapedWS => {}
216                }
217                string
218            },
219        );
220
221        // Finally, parse the string. Note that, if `build_string` could accept a raw
222        // " character, the closing delimiter " would never match. When using
223        // `delimited` with a looping parser (like fold_many0), be sure that the
224        // loop won't accidentally match your closing delimiter!
225        delimited(char('"'), build_string, char('"'))(input)
226    }
227}
228
229#[test]
230fn test_parse_string() {
231    // to use parse_string_wrapper instead of string_parser::parse_string::<nom::error::VerboseError<&str>> in the tests below:
232    fn parse_string_wrapper(input: &str) -> crate::ParserResult<String> {
233        string_parser::parse_string(input)
234    }
235
236    // tests some correct string literals:
237    assert_eq!(("", String::from("")), parse_string_wrapper("\"\"").unwrap());
238    assert_eq!(("", String::from("abc")), parse_string_wrapper("\"abc\"").unwrap());
239    assert_eq!((" and more", String::from("abc")), parse_string_wrapper("\"abc\" and more").unwrap());
240    assert_eq!(("", String::from("\r")), parse_string_wrapper("\"\r\"").unwrap());
241    assert_eq!(("", String::from("4\u{4141}x\x09")), parse_string_wrapper("\"4\u{4141}x\x09\"").unwrap());
242
243    // test rejection of disallowed characters:
244    assert!(parse_string_wrapper("\"hel\x08lo\"").is_err());
245    assert!(parse_string_wrapper("\"hel\x1flo\"").is_err());
246    assert!(parse_string_wrapper("\"hel\u{2069}lo\"").is_err());
247}