| 1 |
// For the full copyright and license information, please view the LICENSE |
| 2 |
// file that was distributed with this source code. |
| 3 |
|
| 4 |
//! Primitive combinators. |
| 5 |
|
| 6 |
use std::str::FromStr; |
| 7 |
|
| 8 |
use winnow::{ |
| 9 |
ascii::{digit1, Uint}, |
| 10 |
combinator::{alt, delimited, not, opt, peek, preceded, repeat, separated}, |
| 11 |
error::{ContextError, ParserError, StrContext, StrContextValue}, |
| 12 |
stream::AsChar, |
| 13 |
token::{none_of, one_of, take_while}, |
| 14 |
Parser, |
| 15 |
}; |
| 16 |
|
| 17 |
/// Allow spaces and comments before a parser |
| 18 |
/// |
| 19 |
/// Every token parser should be wrapped in this to allow spaces and comments. |
| 20 |
/// It is only preceding, because that allows us to check mandatory whitespace |
| 21 |
/// after running the parser. |
| 22 |
pub(super) fn s<'a, O, E>(p: impl Parser<&'a str, O, E>) -> impl Parser<&'a str, O, E> |
| 23 |
where |
| 24 |
E: ParserError<&'a str>, |
| 25 |
{ |
| 26 |
preceded(space, p) |
| 27 |
} |
| 28 |
|
| 29 |
/// Same as winnow's `multispace0`, but also accepting `\v` and `\f`, like |
| 30 |
/// the whitespace GNU `date` accepts between tokens |
| 31 |
fn multispace0<'a, E>(input: &mut &'a str) -> winnow::Result<&'a str, E> |
| 32 |
where |
| 33 |
E: ParserError<&'a str>, |
| 34 |
{ |
| 35 |
take_while(0.., (' ', '\t', '\n', '\x0B', '\x0C', '\r')).parse_next(input) |
| 36 |
} |
| 37 |
|
| 38 |
/// Same as [`multispace0`], but requiring at least one character |
| 39 |
pub(super) fn multispace1<'a, E>(input: &mut &'a str) -> winnow::Result<&'a str, E> |
| 40 |
where |
| 41 |
E: ParserError<&'a str>, |
| 42 |
{ |
| 43 |
take_while(1.., (' ', '\t', '\n', '\x0B', '\x0C', '\r')).parse_next(input) |
| 44 |
} |
| 45 |
|
| 46 |
/// Parse the space in-between tokens |
| 47 |
/// |
| 48 |
/// You probably want to use the [`s`] combinator instead. |
| 49 |
pub(super) fn space<'a, E>(input: &mut &'a str) -> winnow::Result<(), E> |
| 50 |
where |
| 51 |
E: ParserError<&'a str>, |
| 52 |
{ |
| 53 |
separated(0.., multispace0, alt((comment, ignored_hyphen_or_plus))).parse_next(input) |
| 54 |
} |
| 55 |
|
| 56 |
/// A hyphen or plus is ignored when it is not followed by a digit |
| 57 |
/// |
| 58 |
/// This includes being followed by a comment! Compare these inputs: |
| 59 |
/// ```txt |
| 60 |
/// - 12 weeks |
| 61 |
/// - (comment) 12 weeks |
| 62 |
/// ``` |
| 63 |
/// The last comment should be ignored. |
| 64 |
/// |
| 65 |
/// The plus is undocumented, but it seems to be ignored. |
| 66 |
fn ignored_hyphen_or_plus<'a, E>(input: &mut &'a str) -> winnow::Result<(), E> |
| 67 |
where |
| 68 |
E: ParserError<&'a str>, |
| 69 |
{ |
| 70 |
( |
| 71 |
alt(('-', '+')), |
| 72 |
multispace0, |
| 73 |
peek(not(take_while(1, AsChar::is_dec_digit))), |
| 74 |
) |
| 75 |
.void() |
| 76 |
.parse_next(input) |
| 77 |
} |
| 78 |
|
| 79 |
/// Parse a comment |
| 80 |
/// |
| 81 |
/// A comment is given between parentheses, which must be balanced. Any other |
| 82 |
/// tokens can be within the comment. |
| 83 |
fn comment<'a, E>(input: &mut &'a str) -> winnow::Result<(), E> |
| 84 |
where |
| 85 |
E: ParserError<&'a str>, |
| 86 |
{ |
| 87 |
delimited( |
| 88 |
'(', |
| 89 |
repeat(0.., alt((none_of(['(', ')']).void(), comment))), |
| 90 |
')', |
| 91 |
) |
| 92 |
.parse_next(input) |
| 93 |
} |
| 94 |
|
| 95 |
/// Parse a signed decimal integer. |
| 96 |
/// |
| 97 |
/// Rationale for not using `winnow::ascii::dec_int`: When upgrading winnow from |
| 98 |
/// 0.5 to 0.7, we discovered that `winnow::ascii::dec_int` now accepts only the |
| 99 |
/// following two forms: |
| 100 |
/// |
| 101 |
/// - 0 |
| 102 |
/// - [+-]?[1-9][0-9]* |
| 103 |
/// |
| 104 |
/// Inputs like [+-]?0[0-9]* (e.g., `+012`) are therefore rejected. We provide a |
| 105 |
/// custom implementation to support such zero-prefixed integers. |
| 106 |
#[allow(unused)] |
| 107 |
pub(super) fn dec_int<'a, E>(input: &mut &'a str) -> winnow::Result<i32, E> |
| 108 |
where |
| 109 |
E: ParserError<&'a str>, |
| 110 |
{ |
| 111 |
(opt(one_of(['+', '-'])), digit1) |
| 112 |
.void() |
| 113 |
.take() |
| 114 |
.verify_map(|s: &str| s.parse().ok()) |
| 115 |
.parse_next(input) |
| 116 |
} |
| 117 |
|
| 118 |
/// Parse an unsigned decimal integer. |
| 119 |
/// |
| 120 |
/// See the rationale for `dec_int` for why we don't use |
| 121 |
/// `winnow::ascii::dec_uint`. |
| 122 |
pub(super) fn dec_uint<'a, O, E>(input: &mut &'a str) -> winnow::Result<O, E> |
| 123 |
where |
| 124 |
O: Uint + FromStr, |
| 125 |
E: ParserError<&'a str>, |
| 126 |
{ |
| 127 |
dec_uint_str |
| 128 |
.verify_map(|s: &str| s.parse().ok()) |
| 129 |
.parse_next(input) |
| 130 |
} |
| 131 |
|
| 132 |
/// Parse an unsigned decimal integer as a string slice. |
| 133 |
pub(super) fn dec_uint_str<'a, E>(input: &mut &'a str) -> winnow::Result<&'a str, E> |
| 134 |
where |
| 135 |
E: ParserError<&'a str>, |
| 136 |
{ |
| 137 |
digit1.void().take().parse_next(input) |
| 138 |
} |
| 139 |
|
| 140 |
/// Parse a colon preceded by whitespace. |
| 141 |
pub(super) fn colon<'a, E>(input: &mut &'a str) -> winnow::Result<(), E> |
| 142 |
where |
| 143 |
E: ParserError<&'a str>, |
| 144 |
{ |
| 145 |
s(':').void().parse_next(input) |
| 146 |
} |
| 147 |
|
| 148 |
/// Parse a plus or minus character optionally preceeded by whitespace. |
| 149 |
pub(super) fn plus_or_minus<'a, E>(input: &mut &'a str) -> winnow::Result<char, E> |
| 150 |
where |
| 151 |
E: ParserError<&'a str>, |
| 152 |
{ |
| 153 |
s(alt(('+', '-'))).parse_next(input) |
| 154 |
} |
| 155 |
|
| 156 |
/// Create a context error with a reason. |
| 157 |
pub(super) fn ctx_err(reason: &'static str) -> ContextError { |
| 158 |
let mut err = ContextError::new(); |
| 159 |
err.push(StrContext::Expected(StrContextValue::Description(reason))); |
| 160 |
err |
| 161 |
} |
| 162 |
|
| 163 |
#[cfg(test)] |
| 164 |
mod tests { |
| 165 |
use super::*; |
| 166 |
|
| 167 |
#[test] |
| 168 |
fn parse_dec_int() { |
| 169 |
for (input, expected) in [ |
| 170 |
("123", 123), // positive without sign |
| 171 |
("+123", 123), // positive with '+' sign |
| 172 |
("-123", -123), // negative with '-' sign |
| 173 |
("0", 0), // zero |
| 174 |
("+0", 0), // zero with '+' sign |
| 175 |
("-0", 0), // zero with '-' sign (parses as 0) |
| 176 |
("012", 12), // zero-prefixed (the main reason for this function) |
| 177 |
("+012", 12), // zero-prefixed with '+' sign |
| 178 |
("-012", -12), // zero-prefixed with '-' sign |
| 179 |
("00123", 123), // multiple leading zeros |
| 180 |
("2147483647", 2147483647), // i32::MAX |
| 181 |
("-2147483648", -2147483648), // i32::MIN |
| 182 |
] { |
| 183 |
let mut s = input; |
| 184 |
assert_eq!( |
| 185 |
dec_int::<ContextError>(&mut s).unwrap(), |
| 186 |
expected, |
| 187 |
"{input}" |
| 188 |
); |
| 189 |
} |
| 190 |
|
| 191 |
for input in [ |
| 192 |
"", // empty string |
| 193 |
"+", // sign without digits |
| 194 |
"-", // sign without digits |
| 195 |
"abc", // non-numeric |
| 196 |
"12a", // starts with digits but has non-digit after (but should parse "12" successfully) |
| 197 |
] { |
| 198 |
let mut s = input; |
| 199 |
let result = dec_int::<ContextError>(&mut s); |
| 200 |
// Note: "12a" will actually succeed and parse "12", leaving "a" unparsed |
| 201 |
if input == "12a" { |
| 202 |
assert_eq!(result.unwrap(), 12, "{input}"); |
| 203 |
assert_eq!(s, "a", "Should leave 'a' unparsed"); |
| 204 |
} else { |
| 205 |
assert!(result.is_err(), "{input} should fail"); |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
// Test overflow cases |
| 210 |
for input in [ |
| 211 |
"2147483648", // i32::MAX + 1 |
| 212 |
"-2147483649", // i32::MIN - 1 |
| 213 |
"99999999999", // way too large |
| 214 |
] { |
| 215 |
let mut s = input; |
| 216 |
assert!( |
| 217 |
dec_int::<ContextError>(&mut s).is_err(), |
| 218 |
"{input} should overflow" |
| 219 |
); |
| 220 |
} |
| 221 |
} |
| 222 |
} |