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