Debian Codegraph @

debian/rust-vendor/winnow/src/combinator/core.rs

raw
1 use crate::combinator::trace;
2 use crate::error::{ModalError, ParserError};
3 use crate::stream::Stream;
4 use crate::{Parser, Result};
5
6 /// Apply a [`Parser`], producing `None` on [`ErrMode::Backtrack`][crate::error::ErrMode::Backtrack].
7 ///
8 /// To chain an error up, see [`cut_err`].
9 ///
10 /// # Example
11 ///
12 /// ```rust
13 /// # #[cfg(feature = "ascii")] {
14 /// # use winnow::prelude::*;
15 /// use winnow::combinator::opt;
16 /// use winnow::ascii::alpha1;
17 ///
18 /// fn parser<'i>(i: &mut &'i str) -> ModalResult<Option<&'i str>> {
19 /// opt(alpha1).parse_next(i)
20 /// }
21 ///
22 /// assert_eq!(parser.parse_peek("abcd;"), Ok((";", Some("abcd"))));
23 /// assert_eq!(parser.parse_peek("123;"), Ok(("123;", None)));
24 /// # }
25 /// ```
26 pub fn opt<Input: Stream, Output, Error, ParseNext>(
27 mut parser: ParseNext,
28 ) -> impl Parser<Input, Option<Output>, Error>
29 where
30 ParseNext: Parser<Input, Output, Error>,
31 Error: ParserError<Input>,
32 {
33 trace("opt", move |input: &mut Input| {
34 let start = input.checkpoint();
35 match parser.parse_next(input) {
36 Ok(o) => Ok(Some(o)),
37 Err(e) if e.is_backtrack() => {
38 input.reset(&start);
39 Ok(None)
40 }
41 Err(e) => Err(e),
42 }
43 })
44 }
45
46 /// Calls the parser if the condition is met.
47 ///
48 /// # Example
49 ///
50 /// ```rust
51 /// # #[cfg(feature = "ascii")] {
52 /// # use winnow::prelude::*;
53 /// # use winnow::combinator::opt;
54 /// use winnow::combinator::cond;
55 /// use winnow::ascii::alpha1;
56 ///
57 /// fn parser<'i>(i: &mut &'i str) -> ModalResult<Option<&'i str>> {
58 /// let prefix = opt("-").parse_next(i)?;
59 /// let condition = prefix.is_some();
60 /// cond(condition, alpha1).parse_next(i)
61 /// }
62 ///
63 /// assert_eq!(parser.parse_peek("-abcd;"), Ok((";", Some("abcd"))));
64 /// assert_eq!(parser.parse_peek("abcd;"), Ok(("abcd;", None)));
65 /// assert!(parser.parse_peek("-123;").is_err());
66 /// assert_eq!(parser.parse_peek("123;"), Ok(("123;", None)));
67 /// # }
68 /// ```
69 pub fn cond<Input, Output, Error, ParseNext>(
70 cond: bool,
71 mut parser: ParseNext,
72 ) -> impl Parser<Input, Option<Output>, Error>
73 where
74 Input: Stream,
75 ParseNext: Parser<Input, Output, Error>,
76 Error: ParserError<Input>,
77 {
78 trace("cond", move |input: &mut Input| {
79 if cond {
80 parser.parse_next(input).map(Some)
81 } else {
82 Ok(None)
83 }
84 })
85 }
86
87 /// Apply the parser without advancing the input.
88 ///
89 /// To lookahead and only advance on success, see [`opt`].
90 ///
91 /// # Example
92 ///
93 /// ```rust
94 /// # #[cfg(feature = "ascii")] {
95 /// # use winnow::prelude::*;
96 /// use winnow::combinator::peek;
97 /// use winnow::ascii::alpha1;
98 ///
99 /// fn parser<'i>(input: &mut &'i str) -> ModalResult<&'i str> {
100 /// peek(alpha1).parse_next(input)
101 /// }
102 ///
103 /// assert_eq!(parser.parse_peek("abcd;"), Ok(("abcd;", "abcd")));
104 /// assert!(parser.parse_peek("123;").is_err());
105 /// # }
106 /// ```
107 #[doc(alias = "look_ahead")]
108 #[doc(alias = "rewind")]
109 pub fn peek<Input, Output, Error, ParseNext>(
110 mut parser: ParseNext,
111 ) -> impl Parser<Input, Output, Error>
112 where
113 Input: Stream,
114 Error: ParserError<Input>,
115 ParseNext: Parser<Input, Output, Error>,
116 {
117 trace("peek", move |input: &mut Input| {
118 let start = input.checkpoint();
119 let res = parser.parse_next(input);
120 input.reset(&start);
121 res
122 })
123 }
124
125 /// Match the end of the [`Stream`]
126 ///
127 /// Otherwise, it will error.
128 ///
129 /// # Effective Signature
130 ///
131 /// Assuming you are parsing a `&str` [Stream]:
132 /// ```rust
133 /// # use winnow::prelude::*;;
134 /// pub fn eof<'i>(input: &mut &'i str) -> ModalResult<&'i str>
135 /// # {
136 /// # winnow::combinator::eof.parse_next(input)
137 /// # }
138 /// ```
139 ///
140 /// # Example
141 ///
142 /// ```rust
143 /// # use std::str;
144 /// # use winnow::combinator::eof;
145 /// # use winnow::prelude::*;
146 ///
147 /// fn parser<'i>(input: &mut &'i str) -> ModalResult<&'i str> {
148 /// eof.parse_next(input)
149 /// }
150 /// assert!(parser.parse_peek("abc").is_err());
151 /// assert_eq!(parser.parse_peek(""), Ok(("", "")));
152 /// ```
153 #[doc(alias = "end")]
154 #[doc(alias = "eoi")]
155 pub fn eof<Input, Error>(input: &mut Input) -> Result<<Input as Stream>::Slice, Error>
156 where
157 Input: Stream,
158 Error: ParserError<Input>,
159 {
160 trace("eof", move |input: &mut Input| {
161 if input.eof_offset() == 0 {
162 Ok(input.next_slice(0))
163 } else {
164 Err(ParserError::from_input(input))
165 }
166 })
167 .parse_next(input)
168 }
169
170 /// Succeeds if the child parser returns an error.
171 ///
172 /// <div class="warning">
173 ///
174 /// **Note:** This does not advance the [`Stream`]
175 ///
176 /// </div>
177 ///
178 /// # Example
179 ///
180 /// ```rust
181 /// # #[cfg(feature = "ascii")] {
182 /// # use winnow::prelude::*;
183 /// use winnow::combinator::not;
184 /// use winnow::ascii::alpha1;
185 ///
186 /// fn parser<'i>(input: &mut &'i str) -> ModalResult<()> {
187 /// not(alpha1).parse_next(input)
188 /// }
189 ///
190 /// assert_eq!(parser.parse_peek("123"), Ok(("123", ())));
191 /// assert!(parser.parse_peek("abcd").is_err());
192 /// # }
193 /// ```
194 pub fn not<Input, Output, Error, ParseNext>(mut parser: ParseNext) -> impl Parser<Input, (), Error>
195 where
196 Input: Stream,
197 Error: ParserError<Input>,
198 ParseNext: Parser<Input, Output, Error>,
199 {
200 trace("not", move |input: &mut Input| {
201 let start = input.checkpoint();
202 let res = parser.parse_next(input);
203 input.reset(&start);
204 match res {
205 Ok(_) => Err(ParserError::from_input(input)),
206 Err(e) if e.is_backtrack() => Ok(()),
207 Err(e) => Err(e),
208 }
209 })
210 }
211
212 /// Transforms an [`ErrMode::Backtrack`][crate::error::ErrMode::Backtrack] (recoverable) to [`ErrMode::Cut`][crate::error::ErrMode::Cut] (unrecoverable)
213 ///
214 /// This commits the parse result, preventing alternative branch paths like with
215 /// [`winnow::combinator::alt`][crate::combinator::alt].
216 ///
217 /// See the [tutorial][crate::_tutorial::chapter_7] for more details.
218 ///
219 /// # Example
220 ///
221 /// Without `cut_err`:
222 /// ```rust
223 /// # #[cfg(feature = "ascii")] {
224 /// # use winnow::token::one_of;
225 /// # use winnow::token::rest;
226 /// # use winnow::ascii::digit1;
227 /// # use winnow::combinator::alt;
228 /// # use winnow::combinator::preceded;
229 /// # use winnow::prelude::*;
230 ///
231 /// fn parser<'i>(input: &mut &'i str) -> ModalResult<&'i str> {
232 /// alt((
233 /// preceded(one_of(['+', '-']), digit1),
234 /// rest
235 /// )).parse_next(input)
236 /// }
237 ///
238 /// assert_eq!(parser.parse_peek("+10 ab"), Ok((" ab", "10")));
239 /// assert_eq!(parser.parse_peek("ab"), Ok(("", "ab")));
240 /// assert_eq!(parser.parse_peek("+"), Ok(("", "+")));
241 /// # }
242 /// ```
243 ///
244 /// With `cut_err`:
245 /// ```rust
246 /// # #[cfg(feature = "ascii")] {
247 /// # use winnow::{error::ErrMode, error::ContextError};
248 /// # use winnow::prelude::*;
249 /// # use winnow::token::one_of;
250 /// # use winnow::token::rest;
251 /// # use winnow::ascii::digit1;
252 /// # use winnow::combinator::alt;
253 /// # use winnow::combinator::preceded;
254 /// use winnow::combinator::cut_err;
255 ///
256 /// fn parser<'i>(input: &mut &'i str) -> ModalResult<&'i str> {
257 /// alt((
258 /// preceded(one_of(['+', '-']), cut_err(digit1)),
259 /// rest
260 /// )).parse_next(input)
261 /// }
262 ///
263 /// assert_eq!(parser.parse_peek("+10 ab"), Ok((" ab", "10")));
264 /// assert_eq!(parser.parse_peek("ab"), Ok(("", "ab")));
265 /// assert_eq!(parser.parse_peek("+"), Err(ErrMode::Cut(ContextError::new())));
266 /// # }
267 /// ```
268 pub fn cut_err<Input, Output, Error, ParseNext>(
269 mut parser: ParseNext,
270 ) -> impl Parser<Input, Output, Error>
271 where
272 Input: Stream,
273 Error: ParserError<Input> + ModalError,
274 ParseNext: Parser<Input, Output, Error>,
275 {
276 trace("cut_err", move |input: &mut Input| {
277 parser.parse_next(input).map_err(|e| e.cut())
278 })
279 }
280
281 /// Transforms an [`ErrMode::Cut`][crate::error::ErrMode::Cut] (unrecoverable) to [`ErrMode::Backtrack`][crate::error::ErrMode::Backtrack] (recoverable)
282 ///
283 /// This attempts the parse, allowing other parsers to be tried on failure, like with
284 /// [`winnow::combinator::alt`][crate::combinator::alt].
285 pub fn backtrack_err<Input, Output, Error, ParseNext>(
286 mut parser: ParseNext,
287 ) -> impl Parser<Input, Output, Error>
288 where
289 Input: Stream,
290 Error: ParserError<Input> + ModalError,
291 ParseNext: Parser<Input, Output, Error>,
292 {
293 trace("backtrack_err", move |input: &mut Input| {
294 parser.parse_next(input).map_err(|e| e.backtrack())
295 })
296 }
297
298 /// A placeholder for a not-yet-implemented [`Parser`]
299 ///
300 /// This is analogous to the [`todo!`] macro and helps with prototyping.
301 ///
302 /// # Panic
303 ///
304 /// This will panic when parsing
305 ///
306 /// # Example
307 ///
308 /// ```rust
309 /// # use winnow::prelude::*;
310 /// # use winnow::combinator::todo;
311 ///
312 /// fn parser(input: &mut &str) -> ModalResult<u64> {
313 /// todo(input)
314 /// }
315 /// ```
316 #[track_caller]
317 pub fn todo<Input, Output, Error>(input: &mut Input) -> Result<Output, Error>
318 where
319 Input: Stream,
320 Error: ParserError<Input>,
321 {
322 #![allow(clippy::todo)]
323 trace("todo", move |_input: &mut Input| {
324 todo!("unimplemented parse")
325 })
326 .parse_next(input)
327 }
328
329 /// Succeed, consuming no input
330 ///
331 /// For example, it can be used as the last alternative in `alt` to
332 /// specify the default case.
333 ///
334 /// Useful with:
335 /// - [`Parser::value`]
336 /// - [`Parser::default_value`]
337 /// - [`Parser::map`]
338 ///
339 /// <div class="warning">
340 ///
341 /// **Note:** This never advances the [`Stream`]
342 ///
343 /// </div>
344 ///
345 /// # Example
346 ///
347 /// ```rust
348 /// # use winnow::prelude::*;
349 /// use winnow::combinator::alt;
350 /// use winnow::combinator::empty;
351 ///
352 /// fn sign(input: &mut &str) -> ModalResult<isize> {
353 /// alt((
354 /// '-'.value(-1),
355 /// '+'.value(1),
356 /// empty.value(1)
357 /// )).parse_next(input)
358 /// }
359 /// assert_eq!(sign.parse_peek("+10"), Ok(("10", 1)));
360 /// assert_eq!(sign.parse_peek("-10"), Ok(("10", -1)));
361 /// assert_eq!(sign.parse_peek("10"), Ok(("10", 1)));
362 /// ```
363 #[doc(alias = "value")]
364 #[doc(alias = "success")]
365 #[inline]
366 pub fn empty<Input, Error>(_input: &mut Input) -> Result<(), Error>
367 where
368 Input: Stream,
369 Error: ParserError<Input>,
370 {
371 Ok(())
372 }
373
374 /// A parser which always fails.
375 ///
376 /// For example, it can be used as the last alternative in `alt` to
377 /// control the error message given.
378 ///
379 /// # Example
380 ///
381 /// ```rust
382 /// # use winnow::{error::ErrMode, error::InputError};
383 /// # use winnow::prelude::*;
384 /// use winnow::combinator::fail;
385 ///
386 /// fn parser<'i>(input: &mut &'i str) -> ModalResult<(), InputError<&'i str>> {
387 /// fail.parse_next(input)
388 /// }
389 ///
390 /// assert_eq!(parser.parse_peek("string"), Err(ErrMode::Backtrack(InputError::at("string"))));
391 /// ```
392 #[doc(alias = "unexpected")]
393 #[inline]
394 pub fn fail<Input, Output, Error>(i: &mut Input) -> Result<Output, Error>
395 where
396 Input: Stream,
397 Error: ParserError<Input>,
398 {
399 trace("fail", |i: &mut Input| Err(ParserError::from_input(i))).parse_next(i)
400 }