snarkvm_console_network_environment/helpers/
sanitizer.rs

1// Copyright 2024 Aleo Network Foundation
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
16use crate::{ParserResult, string_parser::is_char_supported};
17
18use nom::{
19    branch::alt,
20    bytes::complete::tag,
21    character::complete::{anychar, char, line_ending, multispace1},
22    combinator::{cut, map, recognize, value, verify},
23    error::{ErrorKind, VerboseError, VerboseErrorKind},
24    multi::fold_many0,
25    sequence::{preceded, terminated},
26};
27
28pub struct Sanitizer;
29
30impl Sanitizer {
31    /// Removes all leading whitespaces and comments from the given input, returning the sanitized input.
32    pub fn parse(string: &str) -> ParserResult<&str> {
33        preceded(Self::parse_whitespaces, Self::parse_comments)(string)
34    }
35
36    /// Removes leading whitespaces from the given input.
37    pub fn parse_whitespaces(string: &str) -> ParserResult<&str> {
38        recognize(Self::many0_(alt((multispace1, tag("\\\n")))))(string)
39    }
40
41    /// Removes multiple leading comments from the given input.
42    pub fn parse_comments(string: &str) -> ParserResult<&str> {
43        recognize(Self::many0_(terminated(Self::parse_comment, Self::parse_whitespaces)))(string)
44    }
45
46    /// Removes the first leading comment from the given input.
47    pub fn parse_comment(string: &str) -> ParserResult<&str> {
48        preceded(
49            char('/'),
50            alt((preceded(char('/'), cut(Self::str_till_eol)), preceded(char('*'), cut(Self::str_till_star_slash)))),
51        )(string)
52    }
53
54    /// Parse a safe character (in the sense explained in [string_parser::is_char_supported]).
55    /// Returns an error if no character is found or a non-safe character is found.
56    /// The character is returned, along with the remaining input.
57    ///
58    /// This is used for otherwise unconstrained characters
59    /// in (line and block) comments and in string literals.
60    ///
61    /// Note also that the `nom` documentation for `anychar` says that
62    /// it matches one byte as a character.
63    /// However, simple experiments show that it matches a Unicode character,
64    /// e.g. attempting to parse `"\u{4141}"` yields one CJK character and exhausts the input,
65    /// as opposed to returning `A` and leaving another `A` in the input.
66    pub fn parse_safe_char(string: &str) -> ParserResult<char> {
67        fn is_safe(ch: &char) -> bool {
68            is_char_supported(*ch)
69        }
70        verify(anychar, is_safe)(string)
71    }
72}
73
74impl Sanitizer {
75    /// End-of-input parser.
76    ///
77    /// Yields `()` if the parser is at the end of the input; an error otherwise.
78    fn eoi(string: &str) -> ParserResult<()> {
79        match string.is_empty() {
80            true => Ok((string, ())),
81            false => {
82                Err(nom::Err::Error(VerboseError { errors: vec![(string, VerboseErrorKind::Nom(ErrorKind::Eof))] }))
83            }
84        }
85    }
86
87    /// A newline parser that accepts:
88    ///
89    /// - A newline.
90    /// - The end of input.
91    fn eol(string: &str) -> ParserResult<()> {
92        alt((
93            Self::eoi, // this one goes first because it’s very cheap
94            value((), line_ending),
95        ))(string)
96    }
97
98    /// Apply the `f` parser until `g` succeeds. Both parsers consume the input.
99    fn till<'a, A, B, F, G>(mut f: F, mut g: G) -> impl FnMut(&'a str) -> ParserResult<'a, ()>
100    where
101        F: FnMut(&'a str) -> ParserResult<'a, A>,
102        G: FnMut(&'a str) -> ParserResult<'a, B>,
103    {
104        move |mut i| loop {
105            if let Ok((i2, _)) = g(i) {
106                break Ok((i2, ()));
107            }
108
109            let (i2, _) = f(i)?;
110            i = i2;
111        }
112    }
113
114    /// Parse a string until the end of line.
115    ///
116    /// This parser accepts the multiline annotation (\) to break the string on several lines.
117    ///
118    /// Discard any leading newline.
119    fn str_till_eol(string: &str) -> ParserResult<&str> {
120        // A heuristic approach is applied here in order to avoid costly parsing operations in the
121        // most common scenarios: non-parsing methods are used to verify if the string has multiple
122        // lines and if there are any unsafe characters.
123        if let Some((before, after)) = string.split_once('\n') {
124            let is_multiline = before.ends_with('\\');
125
126            if !is_multiline {
127                let contains_unsafe_chars = !before.chars().all(is_char_supported);
128
129                if !contains_unsafe_chars {
130                    Ok((after, before))
131                } else {
132                    // `eoi` is used here instead of `eol`, since the earlier call to `split_once`
133                    // already removed the newline
134                    recognize(Self::till(value((), Sanitizer::parse_safe_char), Self::eoi))(before)
135                }
136            } else {
137                map(
138                    recognize(Self::till(
139                        alt((value((), tag("\\\n")), value((), Sanitizer::parse_safe_char))),
140                        Self::eol,
141                    )),
142                    |i| {
143                        if i.as_bytes().last() == Some(&b'\n') { &i[0..i.len() - 1] } else { i }
144                    },
145                )(string)
146            }
147        } else {
148            Ok((string, ""))
149        }
150    }
151
152    /// Parse a string until `*/` is encountered.
153    ///
154    /// This is used to parse the body of a block comment, after the opening `/*`.
155    ///
156    /// Return the body of the comment, i.e. what is between `/*` and `*/`.
157    fn str_till_star_slash(string: &str) -> ParserResult<&str> {
158        map(recognize(Self::till(value((), Sanitizer::parse_safe_char), tag("*/"))), |i| {
159            &i[0..i.len() - 2] // subtract 2 to discard the closing `*/`
160        })(string)
161    }
162
163    /// A version of many0 that discards the result of the parser, preventing allocating.
164    fn many0_<'a, A, F>(mut f: F) -> impl FnMut(&'a str) -> ParserResult<'a, ()>
165    where
166        F: FnMut(&'a str) -> ParserResult<'a, A>,
167    {
168        move |string| fold_many0(&mut f, || (), |_, _| ())(string)
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    #[test]
177    fn test_parse_safe_char() {
178        // test correct acceptance of ASCII and non-ASCII:
179        assert_eq!(("", 'A'), Sanitizer::parse_safe_char("A").unwrap());
180        assert_eq!((" and more", 'A'), Sanitizer::parse_safe_char("A and more").unwrap());
181        assert_eq!(("", '\u{4141}'), Sanitizer::parse_safe_char("\u{4141}").unwrap());
182        assert_eq!((" and more", '\u{4141}'), Sanitizer::parse_safe_char("\u{4141} and more").unwrap());
183
184        // test rejection and acceptance of ASCII control characters:
185        assert!(Sanitizer::parse_safe_char("\x00").is_err());
186        assert!(Sanitizer::parse_safe_char("\x01").is_err());
187        assert!(Sanitizer::parse_safe_char("\x02").is_err());
188        assert!(Sanitizer::parse_safe_char("\x03").is_err());
189        assert!(Sanitizer::parse_safe_char("\x04").is_err());
190        assert!(Sanitizer::parse_safe_char("\x05").is_err());
191        assert!(Sanitizer::parse_safe_char("\x06").is_err());
192        assert!(Sanitizer::parse_safe_char("\x07").is_err());
193        assert!(Sanitizer::parse_safe_char("\x08").is_err());
194        assert!(Sanitizer::parse_safe_char("\x09").is_ok());
195        assert!(Sanitizer::parse_safe_char("\x0a").is_ok());
196        assert!(Sanitizer::parse_safe_char("\x0b").is_err());
197        assert!(Sanitizer::parse_safe_char("\x0c").is_err());
198        assert!(Sanitizer::parse_safe_char("\x0d").is_ok());
199        assert!(Sanitizer::parse_safe_char("\x0e").is_err());
200        assert!(Sanitizer::parse_safe_char("\x0f").is_err());
201        assert!(Sanitizer::parse_safe_char("\x10").is_err());
202        assert!(Sanitizer::parse_safe_char("\x11").is_err());
203        assert!(Sanitizer::parse_safe_char("\x12").is_err());
204        assert!(Sanitizer::parse_safe_char("\x13").is_err());
205        assert!(Sanitizer::parse_safe_char("\x14").is_err());
206        assert!(Sanitizer::parse_safe_char("\x15").is_err());
207        assert!(Sanitizer::parse_safe_char("\x16").is_err());
208        assert!(Sanitizer::parse_safe_char("\x17").is_err());
209        assert!(Sanitizer::parse_safe_char("\x18").is_err());
210        assert!(Sanitizer::parse_safe_char("\x19").is_err());
211        assert!(Sanitizer::parse_safe_char("\x1a").is_err());
212        assert!(Sanitizer::parse_safe_char("\x1b").is_err());
213        assert!(Sanitizer::parse_safe_char("\x1c").is_err());
214        assert!(Sanitizer::parse_safe_char("\x1d").is_err());
215        assert!(Sanitizer::parse_safe_char("\x1e").is_err());
216        assert!(Sanitizer::parse_safe_char("\x1f").is_err());
217        assert!(Sanitizer::parse_safe_char("\x7f").is_err());
218
219        // test rejection of bidi characters, and acceptance of the ones just above/below:
220        assert!(Sanitizer::parse_safe_char("\u{2029}").is_ok());
221        assert!(Sanitizer::parse_safe_char("\u{202a}").is_err());
222        assert!(Sanitizer::parse_safe_char("\u{202b}").is_err());
223        assert!(Sanitizer::parse_safe_char("\u{202c}").is_err());
224        assert!(Sanitizer::parse_safe_char("\u{202d}").is_err());
225        assert!(Sanitizer::parse_safe_char("\u{202e}").is_err());
226        assert!(Sanitizer::parse_safe_char("\u{202f}").is_ok());
227        assert!(Sanitizer::parse_safe_char("\u{2065}").is_ok());
228        assert!(Sanitizer::parse_safe_char("\u{2066}").is_err());
229        assert!(Sanitizer::parse_safe_char("\u{2067}").is_err());
230        assert!(Sanitizer::parse_safe_char("\u{2068}").is_err());
231        assert!(Sanitizer::parse_safe_char("\u{2069}").is_err());
232        assert!(Sanitizer::parse_safe_char("\u{206a}").is_ok());
233    }
234
235    #[test]
236    fn test_sanitize() {
237        // Whitespaces
238        assert_eq!(("hello world", ""), Sanitizer::parse("hello world").unwrap());
239        assert_eq!(("hello world", ""), Sanitizer::parse(" hello world").unwrap());
240        assert_eq!(("hello world", ""), Sanitizer::parse("  hello world").unwrap());
241        assert_eq!(("hello world", ""), Sanitizer::parse("\nhello world").unwrap());
242        assert_eq!(("hello world", ""), Sanitizer::parse(" \nhello world").unwrap());
243        assert_eq!(("hello world ", ""), Sanitizer::parse("hello world ").unwrap());
244
245        // Comments
246        assert_eq!(("hello world", "// hello\n"), Sanitizer::parse("// hello\nhello world").unwrap());
247        assert_eq!(("hello world", "/* hello */"), Sanitizer::parse("/* hello */hello world").unwrap());
248        assert_eq!(("hello world", "/* hello */\n"), Sanitizer::parse("/* hello */\nhello world").unwrap());
249        assert_eq!(("hello world", "/** hello */"), Sanitizer::parse("/** hello */hello world").unwrap());
250        assert_eq!(("hello world", "/** hello */\n"), Sanitizer::parse("/** hello */\nhello world").unwrap());
251        assert_eq!(("/\nhello world", ""), Sanitizer::parse("/\nhello world").unwrap());
252
253        // Whitespaces and comments
254        assert_eq!(("hello world", "// hello\n"), Sanitizer::parse(" \n// hello\nhello world").unwrap());
255        assert_eq!(("hello world", "/* hello */\n"), Sanitizer::parse(" \n /* hello */\nhello world").unwrap());
256        assert_eq!(("hello world", "/** hello */\n"), Sanitizer::parse(" \n\t  /** hello */\nhello world").unwrap());
257        assert_eq!(("/\nhello world", ""), Sanitizer::parse(" /\nhello world").unwrap());
258    }
259
260    #[test]
261    fn test_whitespaces() {
262        assert_eq!(("hello world", ""), Sanitizer::parse_whitespaces("hello world").unwrap());
263        assert_eq!(("hello world", " "), Sanitizer::parse_whitespaces(" hello world").unwrap());
264        assert_eq!(("hello world", "  "), Sanitizer::parse_whitespaces("  hello world").unwrap());
265        assert_eq!(("hello world", "\n"), Sanitizer::parse_whitespaces("\nhello world").unwrap());
266        assert_eq!(("hello world", " \n"), Sanitizer::parse_whitespaces(" \nhello world").unwrap());
267        assert_eq!(("hello world", "\t"), Sanitizer::parse_whitespaces("\thello world").unwrap());
268        assert_eq!(("hello world", " \t"), Sanitizer::parse_whitespaces(" \thello world").unwrap());
269        assert_eq!(("hello world", " \n\t"), Sanitizer::parse_whitespaces(" \n\thello world").unwrap());
270        assert_eq!(("hello world ", ""), Sanitizer::parse_whitespaces("hello world ").unwrap());
271    }
272
273    #[test]
274    fn test_comments() {
275        assert_eq!(("hello world", "// hello\n"), Sanitizer::parse_comments("// hello\nhello world").unwrap());
276        assert_eq!(("hello world", "/* hello */\n"), Sanitizer::parse_comments("/* hello */\nhello world").unwrap());
277        assert_eq!(("hello world", "/** hello */\n"), Sanitizer::parse_comments("/** hello */\nhello world").unwrap());
278        assert_eq!(("/\nhello world", ""), Sanitizer::parse_comments("/\nhello world").unwrap());
279        assert_eq!(
280            ("hello world", "// hel\u{4141}lo\n"),
281            Sanitizer::parse_comments("// hel\u{4141}lo\nhello world").unwrap()
282        );
283        assert_eq!(
284            ("hello world", "/* multi\n   line comment\n*/\n"),
285            Sanitizer::parse_comments("/* multi\n   line comment\n*/\nhello world").unwrap()
286        );
287        assert_eq!(
288            ("hello world", "// multiple\n// line\n// comments\n"),
289            Sanitizer::parse_comments("// multiple\n// line\n// comments\nhello world").unwrap()
290        );
291        assert_eq!(
292            ("hello world", "/* multi\n   line comment\n*/\n/* and\n   another\n   one\n*/\n"),
293            Sanitizer::parse_comments("/* multi\n   line comment\n*/\n/* and\n   another\n   one\n*/\nhello world")
294                .unwrap()
295        );
296        assert_eq!(
297            ("hello world", "/* multi\n   line comment\n*/\n// two single\n// line comments\n/* and\n   another\n   multi-liner\n*/\n"),
298            Sanitizer::parse_comments("/* multi\n   line comment\n*/\n// two single\n// line comments\n/* and\n   another\n   multi-liner\n*/\nhello world").unwrap()
299        );
300        assert!(Sanitizer::parse_comments("// hel\x08lo\nhello world").is_err());
301        assert!(Sanitizer::parse_comments("// hel\u{2066}lo\nhello world").is_err());
302        assert!(Sanitizer::parse_comments("/* hel\x7flo */\nhello world").is_err());
303        assert!(Sanitizer::parse_comments("/* hel\u{202d}lo */\nhello world").is_err());
304        assert!(Sanitizer::parse_comments("/** hel\x00lo */\nhello world").is_err());
305        assert!(Sanitizer::parse_comments("/** hel\u{202a}lo */\nhello world").is_err());
306    }
307}