Skip to main content

tokora/parse/
input.rs

1use core::mem::MaybeUninit;
2
3use hybrid_arraydeque::{ArrayDeque, ArraySize, array::Array, typenum};
4
5use crate::{
6  Emitter, Lexer, Source, Token,
7  cache::Peeked,
8  combinator::*,
9  emitter::EmitterView,
10  input::{Complete, Completeness, DelimClass, InputRef, SurfaceIncomplete},
11  located::Located,
12  parse::try_parse::input::ParseAttempt,
13  punct::*,
14  slice::Sliced,
15  span::Spanned,
16  utils::{PhantomLocated, PhantomSliced, PhantomSpan, Trimmed},
17};
18
19// Named only by the `separated_by_*_while` family the macro below mints.
20#[cfg(feature = "many")]
21use crate::token::PunctuatorToken;
22
23use super::*;
24
25mod sealed {
26  pub trait Sealed {}
27}
28
29/// A trait for parsers that specify the capacity of their peek buffer.
30///
31/// Peek windows are capped at `U32` (32 tokens): `Window` is implemented for
32/// `typenum::U1` through `typenum::U32` only.
33pub trait Window: sealed::Sealed {
34  /// The capacity of the peek buffer.
35  type CAPACITY: ArraySize;
36
37  /// Create an uninitialized array of the specified capacity.
38  #[inline(always)]
39  fn array<T>() -> Array<MaybeUninit<T>, Self::CAPACITY> {
40    Array::uninit()
41  }
42
43  /// Create a deque of the specified capacity.
44  #[inline(always)]
45  fn deque<T>() -> ArrayDeque<MaybeUninit<T>, Self::CAPACITY> {
46    ArrayDeque::new()
47  }
48}
49
50macro_rules! peek_buf_capacity_impl_for_typenum {
51  ($($size:literal), + $(,)?) => {
52    paste::paste! {
53      $(
54        impl sealed::Sealed for typenum::[< U $size >] {}
55
56        impl Window for typenum::[< U $size >] {
57          type CAPACITY = typenum::[< U $size >];
58        }
59      )*
60    }
61  };
62}
63
64// Peek windows are capped at `U32`: only `typenum::U1..=U32` receive a `Window` impl.
65seq_macro::seq!(N in 1..=32 {
66  peek_buf_capacity_impl_for_typenum! {
67    #(N,)*
68  }
69});
70
71/// Decision action for conditional parsing.
72///
73/// # The emitter's operations, not the emitter
74///
75/// The second parameter is an [`EmitterView`] — the emitter's own methods under their own names,
76/// in a value that implements no emitter trait. It used to be `&mut E`, and `&mut E` **is** an
77/// emitter: a condition handed one could wrap it and install the wrapper as the context of a
78/// second parse over a **different** buffer, so a recording sink pinned to one source recorded a
79/// foreign parse's structure and materialized it over its own bytes. A view has nothing to install.
80///
81/// Everything a condition could do to the emitter it can still do to the view — the whole
82/// diagnostic surface, the CST structuring surface, and every capability channel — so a condition
83/// still decides *and reports* inline, with no rewind. See [`EmitterView`] for the four members
84/// deliberately withheld (all four are the input layer's own bookkeeping, and none was ever
85/// callable from a condition without desynchronizing the parse).
86pub trait Decision<'inp, L, E, W, Lang: ?Sized = ()> {
87  /// Decide the next action based on the peeked tokens.
88  fn decide(
89    &mut self,
90    toks: Peeked<'_, 'inp, L, W>,
91    emitter: EmitterView<'_, 'inp, L, E, Lang>,
92  ) -> Result<Action, E::Error>
93  where
94    L: Lexer<'inp>,
95    E: Emitter<'inp, L, Lang>,
96    W: Window;
97}
98
99impl<'inp, F, L, E, W, Lang: ?Sized> Decision<'inp, L, E, W, Lang> for F
100where
101  F: FnMut(Peeked<'_, 'inp, L, W>, EmitterView<'_, 'inp, L, E, Lang>) -> Result<Action, E::Error>,
102  L: Lexer<'inp>,
103  E: Emitter<'inp, L, Lang>,
104  W: Window,
105{
106  #[inline(always)]
107  fn decide(
108    &mut self,
109    toks: Peeked<'_, 'inp, L, W>,
110    emitter: EmitterView<'_, 'inp, L, E, Lang>,
111  ) -> Result<Action, E::Error>
112  where
113    W: Window,
114  {
115    (self)(toks, emitter)
116  }
117}
118
119/// Width-1 decision adapters in grammar vocabulary.
120///
121/// Each constructor returns a concrete type implementing [`Decision`] **pinned at
122/// `W = U1`**, which is what kills the turbofish: the driver's window parameter infers
123/// from the adapter, so the call site carries no `::<_, U1>` and no [`Peeked`] in the
124/// hook. A `W`-generic impl re-ambiguates it.
125///
126/// A second blanket closure impl would break coherence with the `FnMut` blanket above,
127/// so concrete adapter types are the house pattern here — see `WhileNext` in
128/// `combinator/list.rs`.
129mod decision_adapters {
130  use super::*;
131
132  /// Continue while the head satisfies `pred`; stop at a failing head or end of input.
133  pub struct WhileHead<F>(pub(super) F);
134  /// Continue while the head's kind equals `kind` — the punct-tail idiom.
135  pub struct WhileKind<K>(pub(super) K);
136
137  impl<F> core::fmt::Debug for WhileHead<F> {
138    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
139      f.debug_struct("WhileHead").finish_non_exhaustive()
140    }
141  }
142
143  impl<K: core::fmt::Debug> core::fmt::Debug for WhileKind<K> {
144    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
145      f.debug_struct("WhileKind").field("kind", &self.0).finish()
146    }
147  }
148
149  impl<'inp, F, L, E, Lang: ?Sized> Decision<'inp, L, E, typenum::U1, Lang> for WhileHead<F>
150  where
151    F: FnMut(&L::Token) -> bool,
152    L: Lexer<'inp>,
153    E: Emitter<'inp, L, Lang>,
154  {
155    #[inline(always)]
156    fn decide(
157      &mut self,
158      mut toks: Peeked<'_, 'inp, L, typenum::U1>,
159      _emitter: EmitterView<'_, 'inp, L, E, Lang>,
160    ) -> Result<Action, E::Error> {
161      use crate::cache::PeekedTokenExt as _;
162      Ok(match toks.pop_front() {
163        Some(t) if (self.0)(t.token()) => Action::Continue,
164        _ => Action::Stop,
165      })
166    }
167  }
168
169  impl<'inp, K, L, E, Lang: ?Sized> Decision<'inp, L, E, typenum::U1, Lang> for WhileKind<K>
170  where
171    K: PartialEq<<L::Token as Token<'inp>>::Kind>,
172    L: Lexer<'inp>,
173    E: Emitter<'inp, L, Lang>,
174  {
175    #[inline(always)]
176    fn decide(
177      &mut self,
178      mut toks: Peeked<'_, 'inp, L, typenum::U1>,
179      _emitter: EmitterView<'_, 'inp, L, E, Lang>,
180    ) -> Result<Action, E::Error> {
181      use crate::cache::PeekedTokenExt as _;
182      Ok(match toks.pop_front() {
183        Some(t) if self.0 == t.token().kind() => Action::Continue,
184        _ => Action::Stop,
185      })
186    }
187  }
188}
189pub use decision_adapters::{WhileHead, WhileKind};
190
191/// Continue while the head satisfies `pred` — width-1, no turbofish, no [`Peeked`].
192///
193/// The closure takes the head by reference. Bare-closure parameters do not infer through
194/// an impl-side `Fn` bound, so a closure written inline needs a `|t: &Tok|` ascription; a
195/// named function needs none. [`while_kind`] needs neither.
196///
197/// "Until" is the same adapter with one `!`: `while_head(|t: &Tok| !t.is_semicolon())`.
198#[inline(always)]
199pub fn while_head<F>(pred: F) -> WhileHead<F> {
200  decision_adapters::WhileHead(pred)
201}
202
203/// Continue while the head's kind equals `kind` — zero annotation at the call site.
204#[inline(always)]
205pub fn while_kind<K>(kind: K) -> WhileKind<K> {
206  decision_adapters::WhileKind(kind)
207}
208
209/// A parser adapter that pins the enclosed parser's output type to `O`.
210///
211/// A parser with several output impls — `Collect`, `With`, `FailWith`, `Accepted` — is
212/// ambiguous at every downstream site that does not name the output. `Pinned<P, O>`
213/// implements [`ParseInput`]/[`TryParseInput`] at exactly one `O`,
214/// so the ambiguity stops there instead of being re-annotated at every use.
215///
216/// Build one with [`pinned`].
217pub struct Pinned<P, O> {
218  inner: P,
219  // `fn() -> O`, not `O`: the adapter stores no `O`, so it must not inherit `O`'s
220  // auto-traits — `pinned::<*const u8, _>(p)` must not un-`Send` a `Send` parser. A
221  // fn-pointer phantom is `Send + Sync` unconditionally and keeps covariance in `O`.
222  // Variance and auto-traits are public API the moment they ship.
223  _pin: core::marker::PhantomData<fn() -> O>,
224}
225
226impl<P: core::fmt::Debug, O> core::fmt::Debug for Pinned<P, O> {
227  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
228    f.debug_struct("Pinned")
229      .field("inner", &self.inner)
230      .finish()
231  }
232}
233
234/// Pins `parser`'s output type to `O2`, so a receiver with several output impls stops
235/// being ambiguous downstream.
236///
237/// ```ignore
238/// let items = pinned::<Vec<i64>, _>(element.repeated_while(cond).collect())
239///   .parse_input(inp)?;
240/// let n = items.len(); // resolves: the output type is no longer a variable
241/// ```
242///
243/// # Why this is a free function and not a method
244///
245/// The fluent spelling would have to be a **blanket** trait method — bounding it by
246/// [`ParseInput`] means naming the very parameters whose ambiguity it exists to kill, and
247/// a `Self`-returning method on `ParseInput` re-ambiguates (the next call sees fresh
248/// inference variables). A blanket method plants a candidate on **every `Sized` type** in
249/// the consumer's program, and a by-value candidate is picked before a consumer's
250/// same-named `&self` method.
251///
252/// That was accepted while it was believed such a collision must be loud, because `O2` is
253/// not determined by the receiver. It is not: a caller can supply `O2` with a turbofish,
254/// and if the return value is discarded the call compiles and the consumer's method
255/// silently stops running — with no error and no warning. Worse, an extension method that
256/// exists to *pin a type* has no inferred spelling at all, so the turbofish is its only
257/// spelling and the silent path is the default rather than a corner.
258///
259/// A free function resolves by path, plants nothing in method space, and cannot shadow
260/// anything. The fluent form remains purely additive later if the hazard is ever
261/// understood well enough to price it.
262#[inline(always)]
263pub fn pinned<O2, P>(parser: P) -> Pinned<P, O2> {
264  Pinned {
265    inner: parser,
266    _pin: core::marker::PhantomData,
267  }
268}
269
270impl<'inp, L, O, Ctx, Lang: ?Sized, Cmpl, P> ParseInput<'inp, L, O, Ctx, Lang, Cmpl>
271  for Pinned<P, O>
272where
273  P: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
274{
275  #[inline(always)]
276  fn parse_input(
277    &mut self,
278    input: &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
279  ) -> Result<O, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>
280  where
281    L: Lexer<'inp>,
282    Ctx: ParseContext<'inp, L, Lang>,
283    Cmpl: Completeness,
284  {
285    self.inner.parse_input(input)
286  }
287}
288
289impl<'inp, L, O, Ctx, Lang: ?Sized, Cmpl, P> crate::TryParseInput<'inp, L, O, Ctx, Lang, Cmpl>
290  for Pinned<P, O>
291where
292  P: crate::TryParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
293{
294  #[inline(always)]
295  fn try_parse_input(
296    &mut self,
297    input: &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
298  ) -> Result<ParseAttempt<O>, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>
299  where
300    L: Lexer<'inp>,
301    Ctx: ParseContext<'inp, L, Lang>,
302    Cmpl: Completeness,
303  {
304    self.inner.try_parse_input(input)
305  }
306}
307
308/// A trait for parsers that accumulate their results into a container.
309pub trait Accumulator<'inp, L, Container, Ctx, Lang: ?Sized = (), Cmpl = Complete> {
310  /// Collects the parsed elements into the specified container.
311  #[inline(always)]
312  fn collect(self) -> Collect<Self, Container, Ctx, Lang, Cmpl>
313  where
314    Self: Sized,
315    Container: Default,
316    Collect<Self, Container, Ctx, Lang, Cmpl>: ParseInput<'inp, L, Container, Ctx, Lang, Cmpl>,
317  {
318    Collect::new(self, Container::default())
319  }
320
321  /// Collects the parsed elements with the given container.
322  ///
323  /// `container` is the **first attempt's** storage, and shares that attempt's fate: an attempt
324  /// that fails drops the seed along with whatever it collected on top of it, so a reused
325  /// collector never starts from a previous attempt's leftovers. A second attempt therefore
326  /// starts from `Container::default()`, exactly as [`collect`](Self::collect) does.
327  #[inline(always)]
328  fn collect_with(self, container: Container) -> Collect<Self, Container, Ctx, Lang, Cmpl>
329  where
330    Self: Sized,
331    Collect<Self, Container, Ctx, Lang, Cmpl>: ParseInput<'inp, L, Container, Ctx, Lang, Cmpl>,
332  {
333    Collect::new(self, container)
334  }
335}
336
337impl<'inp, P, Container, L, Ctx, Lang: ?Sized, Cmpl>
338  Accumulator<'inp, L, Container, Ctx, Lang, Cmpl> for P
339where
340  Collect<P, Container, Ctx, Lang, Cmpl>: ParseInput<'inp, L, Container, Ctx, Lang, Cmpl>,
341{
342}
343
344macro_rules! define_separated_by {
345  ($($name:ident),+$(,)?) => {
346    paste::paste! {
347      $(
348        #[doc = "Creates a `SeparatedWhile` combinator which separates elements by the `" $name:snake "` separator and applies this parser repeatedly."]
349        ///
350        /// See [`separated_while`](crate::ParseInput::separated_while) for details.
351        #[cfg(feature = "many")]
352        #[cfg_attr(docsrs, doc(cfg(feature = "many")))]
353        #[inline(always)]
354        fn [< separated_by_ $name:snake _while>]<Condition, W>(
355          self,
356          condition: Condition,
357        ) -> SeparatedWhile<Self, $name<(), (), Lang>, Condition, O, W, L, Ctx, Lang, Cmpl>
358        where
359          Self: Sized,
360          L: Lexer<'inp>,
361          L::Token: PunctuatorToken<'inp>,
362          Ctx: ParseContext<'inp, L, Lang>,
363          Condition: Decision<'inp, L, Ctx::Emitter, W, Lang>,
364          W: Window,
365        {
366          SeparatedWhile::new::<$name<(), (), Lang>>(self, condition)
367        }
368      )*
369    }
370  };
371}
372
373macro_rules! define_delimited_by {
374  ($($method:ident => $delimiter:ident),+$(,)?) => {
375    $(
376      #[doc = concat!(
377        "Wraps this parser in a committed `",
378        stringify!($delimiter),
379        "` delimiter pair by delegating to `ParseInput::delimited`."
380      )]
381      #[inline(always)]
382      fn $method(
383        self,
384      ) -> impl for<'c> FnMut(
385        &mut InputRef<'inp, 'c, L, Ctx, Lang, Cmpl>,
386      ) -> crate::combinator::DelimitedOf<'inp, $delimiter<(), (), Lang>, L, Ctx, Lang, O>
387      where
388        Self: Sized,
389        $delimiter<(), (), Lang>: crate::delimiter::TypedDelimiter<'inp, L, Lang>,
390        L: Lexer<'inp>,
391        Ctx: ComposableParseContext<'inp, L, Lang>,
392        Cmpl: SurfaceIncomplete<'inp, L, Ctx, Lang>,
393      {
394        self.delimited::<$delimiter<(), (), Lang>>()
395      }
396    )+
397  };
398}
399
400macro_rules! define_try_delimited_by {
401  ($($method:ident => $delimiter:ident),+$(,)?) => {
402    $(
403      #[doc = concat!(
404        "Wraps this parser in an attempted `",
405        stringify!($delimiter),
406        "` delimiter pair by delegating to `ParseInput::try_delimited`."
407      )]
408      ///
409      /// Delegation is the contract, not an implementation detail: this method is the
410      /// fluent form of the free function and holds no state machine of its own, so the
411      /// two surfaces cannot drift apart.
412      #[inline(always)]
413      fn $method(
414        self,
415      ) -> impl for<'c> FnMut(
416        &mut InputRef<'inp, 'c, L, Ctx, Lang, Cmpl>,
417      ) -> crate::combinator::TryDelimitedOf<'inp, $delimiter<(), (), Lang>, L, Ctx, Lang, O>
418      where
419        Self: Sized,
420        $delimiter<(), (), Lang>: crate::delimiter::TypedDelimiter<'inp, L, Lang>,
421        L: Lexer<'inp>,
422        Ctx: ComposableParseContext<'inp, L, Lang>,
423        Cmpl: SurfaceIncomplete<'inp, L, Ctx, Lang>,
424      {
425        self.try_delimited::<$delimiter<(), (), Lang>>()
426      }
427    )+
428  };
429}
430
431/// Core trait implemented by every parser combinator.
432///
433/// This mirrors the ergonomics of libraries like `winnow`: a parser is
434/// simply something that can mutate an [`InputRef`] and either produce
435/// a value or a spanned error using the configured `Emitter`.
436///
437/// Since 0.3.0 the trait carries the input's [`Completeness`] typestate as its trailing
438/// `Cmpl` parameter (defaulted to [`Complete`], so every pre-0.3.0 spelling reads
439/// unchanged). A parser written generic over `Cmpl` is a **write-once** parser: the same
440/// item runs under the complete drivers ([`Parse`](crate::Parse)) and the Sans-I/O partial
441/// driver ([`parse_partial`]). Builder methods return adapters that
442/// carry the same parameter, so a whole combinator chain stays mode-generic until a drive
443/// site pins it.
444pub trait ParseInput<'inp, L, O, Ctx, Lang: ?Sized = (), Cmpl = Complete> {
445  /// Try to parse from the given input.
446  fn parse_input(
447    &mut self,
448    input: &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
449  ) -> Result<O, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>
450  where
451    L: Lexer<'inp>,
452    Ctx: ParseContext<'inp, L, Lang>,
453    Cmpl: Completeness;
454
455  /// Wraps this parser in a committed delimiter pair.
456  ///
457  /// This is the method form of [`delimited`]. The delimiter type
458  /// selects the opener and closer, while this parser produces the enclosed data.
459  #[inline(always)]
460  fn delimited<D>(
461    self,
462  ) -> impl for<'c> FnMut(
463    &mut InputRef<'inp, 'c, L, Ctx, Lang, Cmpl>,
464  ) -> crate::combinator::DelimitedOf<'inp, D, L, Ctx, Lang, O>
465  where
466    Self: Sized,
467    D: crate::delimiter::TypedDelimiter<'inp, L, Lang>,
468    L: Lexer<'inp>,
469    Ctx: ComposableParseContext<'inp, L, Lang>,
470    Cmpl: SurfaceIncomplete<'inp, L, Ctx, Lang>,
471  {
472    crate::combinator::delimited::<D, L, Ctx, Lang, Self, O, Cmpl>(self)
473  }
474
475  define_delimited_by! {
476    delimited_by_parens => Paren,
477    delimited_by_braces => Brace,
478    delimited_by_brackets => Bracket,
479    delimited_by_angles => Angle,
480  }
481
482  /// Wraps this parser in an attempted delimiter pair.
483  ///
484  /// This is the method form of [`try_delimited`], the attempt twin of
485  /// [`delimited`](Self::delimited): only the **opener** is tentative. The attempt declines
486  /// — `Ok(None)`, zero consumption — when the `D` opener is definitely absent or the input
487  /// genuinely ended; a terminal scanner stop is not a decline. Once the opener is consumed
488  /// the parse is committed, so this parser's errors and the missing-closer diagnostics
489  /// behave exactly as the committed form's do.
490  ///
491  /// Delegation is the contract, not an implementation detail: the body is
492  /// `crate::combinator::try_delimited(self)` and nothing else, so the free function and this
493  /// method cannot drift apart.
494  ///
495  /// The free form remains the escape hatch when the enclosed output type has to be named in
496  /// a turbofish: `O` is a parameter of this trait rather than of the method, so it can only
497  /// be pinned here by annotating the enclosed parser or its container.
498  #[inline(always)]
499  fn try_delimited<D>(
500    self,
501  ) -> impl for<'c> FnMut(
502    &mut InputRef<'inp, 'c, L, Ctx, Lang, Cmpl>,
503  ) -> crate::combinator::TryDelimitedOf<'inp, D, L, Ctx, Lang, O>
504  where
505    Self: Sized,
506    D: crate::delimiter::TypedDelimiter<'inp, L, Lang>,
507    L: Lexer<'inp>,
508    Ctx: ComposableParseContext<'inp, L, Lang>,
509    Cmpl: SurfaceIncomplete<'inp, L, Ctx, Lang>,
510  {
511    crate::combinator::try_delimited::<D, L, Ctx, Lang, Self, O, Cmpl>(self)
512  }
513
514  define_try_delimited_by! {
515    try_delimited_by_parens => Paren,
516    try_delimited_by_braces => Brace,
517    try_delimited_by_brackets => Bracket,
518    try_delimited_by_angles => Angle,
519  }
520
521  /// Wraps the output of this parser in a `Spanned` with the span of the parsed input.
522  ///
523  /// The span is a **lookahead span**, from [`InputRef::cursor`] before this parser runs to
524  /// `cursor` after it; [`spanned_trimmed`](Self::spanned_trimmed) measures the **trimmed span**
525  /// instead, with the same output type. See [the two span rules](crate::span#the-two-span-rules).
526  #[inline(always)]
527  fn spanned(self) -> With<PhantomSpan, Self, Cmpl>
528  where
529    Self: Sized,
530    L: Lexer<'inp>,
531  {
532    With::new(PhantomSpan::phantom(), self)
533  }
534
535  /// Wraps the output of this parser in a `Sliced` with the source slice of the parsed input.
536  ///
537  /// The slice covers the **lookahead span**; [`sliced_trimmed`](Self::sliced_trimmed) slices the
538  /// **trimmed span** instead, with the same output type.
539  #[inline(always)]
540  fn sliced(self) -> With<PhantomSliced, Self, Cmpl>
541  where
542    Self: Sized,
543    L: Lexer<'inp>,
544  {
545    With::new(PhantomSliced::phantom(), self)
546  }
547
548  /// Wraps the output of this parser in a `Located` with the span and source slice of the parsed input.
549  ///
550  /// Both are the **lookahead span**'s; [`located_trimmed`](Self::located_trimmed) gives the
551  /// **trimmed span**'s instead, with the same output type.
552  #[inline(always)]
553  fn located(self) -> With<PhantomLocated, Self, Cmpl>
554  where
555    Self: Sized,
556    L: Lexer<'inp>,
557  {
558    With::new(PhantomLocated::phantom(), self)
559  }
560
561  /// Wraps the output of this parser in a `Spanned` with the **trimmed span** of the parsed
562  /// input: from the start of the first token it consumes to the committed position after it.
563  ///
564  /// The trimmed counterpart of [`spanned`](Self::spanned), with the same output type, so a
565  /// grammar switches rule by changing the method name. `spanned` measures from lookahead position
566  /// to lookahead position. Under a lexer that skips bytes between tokens — whitespace, comments —
567  /// that span takes in the skipped bytes after a node whose parser peeked past its last token,
568  /// and the skipped bytes before a node entered with nothing cached. The trimmed span takes in
569  /// neither, and under a lexer that skips nothing the two agree.
570  /// [The two span rules](crate::span#the-two-span-rules) says when each fits, and lists the spans
571  /// that stay lookahead-measured: only the parser this builds measures the trimmed span.
572  ///
573  /// A parser that consumes nothing gets the empty span at the next token's start, or at the
574  /// committed position when no token follows.
575  ///
576  /// ```
577  /// # use core::convert::Infallible;
578  /// # use tokora::{
579  /// #   InputRef, Lexer, Parse as _, ParseInput as _, Parser, ParserContext, SimpleSpan, Token,
580  /// #   emitter::Fatal,
581  /// # };
582  /// # #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
583  /// # struct WordKind;
584  /// # impl core::fmt::Display for WordKind {
585  /// #   fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_str("word") }
586  /// # }
587  /// # #[derive(Clone, Debug)]
588  /// # struct Word;
589  /// # impl Token<'_> for Word {
590  /// #   type Kind = WordKind;
591  /// #   type Error = Infallible;
592  /// #   const SCAN_LOOKAHEAD: tokora::ScanLookahead = tokora::ScanLookahead::Unbounded;
593  /// #   fn kind(&self) -> WordKind { WordKind }
594  /// #   fn is_trivia(&self) -> bool { false }
595  /// # }
596  /// # // `[a-z]+` words; the spaces between them are skipped and never reach the parser.
597  /// # struct WordLexer<'a> { src: &'a str, start: usize, end: usize, state: () }
598  /// # impl<'a> Lexer<'a> for WordLexer<'a> {
599  /// #   type State = (); type Source = str; type Token = Word;
600  /// #   type Span = SimpleSpan; type Offset = usize;
601  /// #   fn new(src: &'a str) -> Self { Self { src, start: 0, end: 0, state: () } }
602  /// #   fn with_state(src: &'a str, state: ()) -> Self { Self { src, start: 0, end: 0, state } }
603  /// #   fn check(&self) -> Result<(), Infallible> { Ok(()) }
604  /// #   fn state(&self) -> &() { &self.state }
605  /// #   fn state_mut(&mut self) -> &mut () { &mut self.state }
606  /// #   fn into_state(self) {}
607  /// #   fn source(&self) -> &'a str { self.src }
608  /// #   fn span(&self) -> SimpleSpan { SimpleSpan::new(self.start, self.end) }
609  /// #   fn slice(&self) -> &'a str { &self.src[self.start..self.end] }
610  /// #   fn lex(&mut self) -> Option<Result<Word, Infallible>> {
611  /// #     let b = self.src.as_bytes();
612  /// #     self.start = self.end;
613  /// #     while self.start < b.len() && b[self.start] == b' ' { self.start += 1; }
614  /// #     if self.start >= b.len() { self.end = self.start; return None; }
615  /// #     let mut e = self.start;
616  /// #     while e < b.len() && b[e] != b' ' { e += 1; }
617  /// #     self.end = e;
618  /// #     Some(Ok(Word))
619  /// #   }
620  /// #   fn read_frontier(&self) -> tokora::ReadFrontier<usize> { tokora::ReadFrontier::SpanEnd }
621  /// #   fn bump(&mut self, n: &usize) { self.end += *n; }
622  /// # }
623  /// # #[derive(Debug, PartialEq)]
624  /// # struct Error;
625  /// # impl From<Infallible> for Error { fn from(e: Infallible) -> Self { match e {} } }
626  /// # impl<'a, T, K: Clone, S, Lg: ?Sized> From<tokora::error::UnexpectedToken<'a, T, K, S, Lg>>
627  /// #   for Error { fn from(_: tokora::error::UnexpectedToken<'a, T, K, S, Lg>) -> Self { Error } }
628  /// type Ctx<'a> = ParserContext<'a, WordLexer<'a>, Fatal<Error>>;
629  ///
630  /// // A word, then a look at the next token for an optional tail that is not there.
631  /// fn word_then_look<'inp>(
632  ///   inp: &mut InputRef<'inp, '_, WordLexer<'inp>, Ctx<'inp>>,
633  /// ) -> Result<(), Error> {
634  ///   inp.next()?;
635  ///   inp.peek_one()?;
636  ///   Ok(())
637  /// }
638  ///
639  /// // Both consume the first word, so the measured node is entered with nothing cached.
640  /// fn lookahead<'inp>(
641  ///   inp: &mut InputRef<'inp, '_, WordLexer<'inp>, Ctx<'inp>>,
642  /// ) -> Result<SimpleSpan, Error> {
643  ///   inp.next()?;
644  ///   Ok(word_then_look.spanned().parse_input(inp)?.span)
645  /// }
646  /// fn trimmed<'inp>(
647  ///   inp: &mut InputRef<'inp, '_, WordLexer<'inp>, Ctx<'inp>>,
648  /// ) -> Result<SimpleSpan, Error> {
649  ///   inp.next()?;
650  ///   Ok(word_then_look.spanned_trimmed().parse_input(inp)?.span)
651  /// }
652  ///
653  /// let src = "one   two   three";
654  /// // The lookahead span opens at the end of `one` and closes at `three`, where the peek left
655  /// // the lookahead: the spaces on both sides of `two` are inside it.
656  /// let by_lookahead = Parser::with_context(ParserContext::new(Fatal::new()))
657  ///   .apply(lookahead)
658  ///   .parse_str(src);
659  /// assert_eq!(by_lookahead, Ok(SimpleSpan::new(3, 12)));
660  /// // The trimmed span is `two` and nothing else.
661  /// let by_trimmed = Parser::with_context(ParserContext::new(Fatal::new()))
662  ///   .apply(trimmed)
663  ///   .parse_str(src);
664  /// assert_eq!(by_trimmed, Ok(SimpleSpan::new(6, 9)));
665  /// ```
666  ///
667  /// # The end is the committed position
668  ///
669  /// The end is [`span().end()`](InputRef::span), the end of the last token this parser
670  /// committed, except where [`InputRef::span_since_trimmed`] names otherwise: a skip or a recovery
671  /// sync that reaches end of input commits the lexer's end, so `x.padded().spanned_trimmed()` over
672  /// `"x  "` ends at the end of the input.
673  ///
674  /// # The start is a peek
675  ///
676  /// The start is [`InputRef::cursor_trimmed`], which peeks the next token before this parser
677  /// runs. Under a cache that retains tokens that costs no second lex; under a zero-capacity cache
678  /// the parser lexes the token again — except a token a non-final input withholds, which is lexed
679  /// once under either cache. The next token is also lexed *early*, under the lexer state current
680  /// here, and that can change an outcome:
681  ///
682  /// - for a parser that would not have read that token, its lexer-error diagnostics, a fatal
683  ///   emitter's rejection of one (which becomes this parser's `Err`), a limit trip and the token
684  ///   budget charge all happen anyway;
685  /// - for a parser that would have read it, a fatal rejection leaves the committed position
686  ///   before the rejected lexeme rather than past it;
687  /// - a parser that switches the lexer state before its first token gets its start from a token
688  ///   lexed under the old state, so switch the state outside this wrapper;
689  /// - on a non-final partial input whose next token is withheld, the start is the committed
690  ///   position, and a parser that then consumes nothing is anchored there, where the sealed parse
691  ///   would anchor it at the next token's start.
692  ///
693  /// `cursor_trimmed` states each of these in full.
694  #[inline(always)]
695  fn spanned_trimmed(self) -> With<Trimmed<PhantomSpan>, Self, Cmpl>
696  where
697    Self: Sized,
698    L: Lexer<'inp>,
699  {
700    With::new(Trimmed(PhantomSpan::phantom()), self)
701  }
702
703  /// Wraps the output of this parser in a `Sliced` with the source slice of its **trimmed span**:
704  /// the trimmed counterpart of [`sliced`](Self::sliced), with the same output type.
705  ///
706  /// The slice covers exactly the span [`spanned_trimmed`](Self::spanned_trimmed) reports, with no
707  /// skipped byte before the first token or after the committed position; a parser that consumes
708  /// nothing gets the empty slice where that span is empty. The start is the same peek, with the
709  /// same consequences: the next token is lexed early, under the lexer state current here, so its
710  /// lexer-error diagnostics, a fatal rejection of one, a limit trip and the token-budget charge
711  /// happen even for a parser that would not have read it, and a fatal rejection leaves the
712  /// committed position before the rejected lexeme. `spanned_trimmed` and
713  /// [`InputRef::cursor_trimmed`] spell these out.
714  #[inline(always)]
715  fn sliced_trimmed(self) -> With<Trimmed<PhantomSliced>, Self, Cmpl>
716  where
717    Self: Sized,
718    L: Lexer<'inp>,
719  {
720    With::new(Trimmed(PhantomSliced::phantom()), self)
721  }
722
723  /// Wraps the output of this parser in a `Located` with the span and source slice of its
724  /// **trimmed span**: the trimmed counterpart of [`located`](Self::located), with the same output
725  /// type.
726  ///
727  /// The span is the one [`spanned_trimmed`](Self::spanned_trimmed) reports and the slice is the
728  /// one [`sliced_trimmed`](Self::sliced_trimmed) reports, so neither takes in a skipped byte on
729  /// either side. The start is the same peek, with the same consequences: the next token is lexed
730  /// early, under the lexer state current here, so its lexer-error diagnostics, a fatal rejection
731  /// of one, a limit trip and the token-budget charge happen even for a parser that would not have
732  /// read it, and a fatal rejection leaves the committed position before the rejected lexeme.
733  /// `spanned_trimmed` and [`InputRef::cursor_trimmed`] spell these out.
734  #[inline(always)]
735  fn located_trimmed(self) -> With<Trimmed<PhantomLocated>, Self, Cmpl>
736  where
737    Self: Sized,
738    L: Lexer<'inp>,
739  {
740    With::new(Trimmed(PhantomLocated::phantom()), self)
741  }
742
743  /// Ignores the output of this parser.
744  #[inline(always)]
745  fn ignored(self) -> Ignore<Self, O, L, Ctx, Lang, Cmpl>
746  where
747    Self: Sized,
748    L: Lexer<'inp>,
749    Ignore<Self, O, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, (), Ctx, Lang, Cmpl>,
750  {
751    Ignore::new(self)
752  }
753
754  /// Creates a parser over a mutable reference to this parser.
755  #[inline(always)]
756  fn by_ref(&mut self) -> &mut ByRef<Self> {
757    ByRef::from_ref_mut(self)
758  }
759
760  /// Creates a `FoldWhile` combinator that accumulates results while a condition is met.
761  #[cfg(feature = "fold")]
762  #[cfg_attr(docsrs, doc(cfg(feature = "fold")))]
763  #[inline(always)]
764  fn fold_while<Condition, Init, Acc, W>(
765    self,
766    pred: Condition,
767    init: Init,
768    acc: Acc,
769  ) -> FoldWhile<Self, Condition, Init, Acc, O, W, L, Ctx, Lang, Cmpl>
770  where
771    Self: Sized,
772    L: Lexer<'inp>,
773    Ctx: ParseContext<'inp, L, Lang>,
774    Condition: Decision<'inp, L, Ctx::Emitter, W, Lang>,
775    W: Window,
776    FoldWhile<Self, Condition, Init, Acc, O, W, L, Ctx, Lang, Cmpl>:
777      ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
778  {
779    FoldWhile::new(self, pred, init, acc)
780  }
781
782  /// Creates a `TryFoldWhile` combinator that accumulates results while a condition is met.
783  ///
784  /// See also [`try_fold_while_with`](Self::try_fold_while_with).
785  #[cfg(feature = "fold")]
786  #[cfg_attr(docsrs, doc(cfg(feature = "fold")))]
787  #[inline(always)]
788  fn try_fold_while<Condition, Init, Acc, W>(
789    self,
790    pred: Condition,
791    init: Init,
792    acc: Acc,
793  ) -> TryFoldWhile<Self, Condition, Init, Acc, O, W, L, Ctx, Lang, Cmpl>
794  where
795    Self: Sized,
796    L: Lexer<'inp>,
797    Ctx: ParseContext<'inp, L, Lang>,
798    Init: FnMut() -> O,
799    Acc: FnMut(O, O) -> Result<O, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
800    Condition: Decision<'inp, L, Ctx::Emitter, W, Lang>,
801    W: Window,
802    TryFoldWhile<Self, Condition, Init, Acc, O, W, L, Ctx, Lang, Cmpl>:
803      ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
804  {
805    TryFoldWhile::new(self, pred, init, acc)
806  }
807
808  /// Creates a `TryFoldWhileWith` combinator that accumulates results while a condition is met,
809  /// with access to parsing state.
810  #[cfg(feature = "fold")]
811  #[cfg_attr(docsrs, doc(cfg(feature = "fold")))]
812  #[inline(always)]
813  fn try_fold_while_with<Condition, Init, Acc, W>(
814    self,
815    pred: Condition,
816    init: Init,
817    acc: Acc,
818  ) -> TryFoldWhileWith<Self, Condition, Init, Acc, O, W, L, Ctx, Lang, Cmpl>
819  where
820    Self: Sized,
821    L: Lexer<'inp>,
822    Ctx: ParseContext<'inp, L, Lang>,
823    Init: FnMut() -> O,
824    Acc: FnMut(
825      O,
826      O,
827      ParseState<'_, 'inp, '_, L, Ctx, Lang, Cmpl>,
828    ) -> Result<O, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
829    Condition: Decision<'inp, L, Ctx::Emitter, W, Lang>,
830    W: Window,
831    TryFoldWhileWith<Self, Condition, Init, Acc, O, W, L, Ctx, Lang, Cmpl>:
832      ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
833  {
834    TryFoldWhileWith::new(self, pred, init, acc)
835  }
836
837  /// Creates a `RFoldWhile` combinator that applies this parser repeatedly,
838  /// while a condition is met, and folds results in reverse order.
839  ///
840  /// This buffers all parsed outputs before folding them from right to left.
841  ///
842  /// See also [`fold_while`](Self::fold_while).
843  #[cfg(all(feature = "fold", any(feature = "alloc", feature = "std")))]
844  #[cfg_attr(
845    docsrs,
846    doc(cfg(all(feature = "fold", any(feature = "alloc", feature = "std"))))
847  )]
848  #[inline(always)]
849  fn rfold_while<Condition, Init, Acc, W>(
850    self,
851    condition: Condition,
852    init: Init,
853    acc: Acc,
854  ) -> RFoldWhile<Self, Condition, Init, Acc, L, O, W, Ctx, Lang, Cmpl>
855  where
856    Self: Sized,
857    L: Lexer<'inp>,
858    Ctx: ParseContext<'inp, L, Lang>,
859    Init: FnMut() -> O,
860    Acc: FnMut(O, O) -> O,
861    Condition: Decision<'inp, L, Ctx::Emitter, W, Lang>,
862    W: Window,
863    RFoldWhile<Self, Condition, Init, Acc, L, O, W, Ctx, Lang, Cmpl>:
864      ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
865  {
866    RFoldWhile::new(self, condition, init, acc)
867  }
868
869  /// Creates a `RepeatedWhile` combinator that applies this parser repeatedly, where **you
870  /// provide the lookahead logic**.
871  ///
872  /// The parser will be called repeatedly until:
873  /// - Your condition function returns `Action::Stop` - you decided to stop based on lookahead
874  /// - It returns `Err(e)` - fatal error
875  ///
876  /// ## Key Behavior
877  ///
878  /// Unlike [`repeated()`](crate::TryParseInput::repeated), this parser doesn't need built-in
879  /// lookahead:
880  /// - **You provide** a condition function that peeks ahead at tokens
881  /// - Condition decides `Continue` or `Stop` based on what it sees
882  /// - Element parser is only called when condition says `Continue`
883  ///
884  /// ## Type Parameters
885  ///
886  /// - `W`: Window size for lookahead (e.g., `U1` for 1 token, `U2` for 2 tokens)
887  ///
888  /// ## See Also
889  ///
890  /// - [`repeated`](crate::TryParseInput::repeated) - Parser has lookahead, no separator
891  /// - [`Action`] - The decision type (`Continue` or `Stop`)
892  #[cfg(feature = "many")]
893  #[cfg_attr(docsrs, doc(cfg(feature = "many")))]
894  #[inline(always)]
895  fn repeated_while<Condition, W>(
896    self,
897    condition: Condition,
898  ) -> RepeatedWhile<Self, Condition, O, W, L, Ctx, Lang, Cmpl>
899  where
900    Self: Sized,
901    L: Lexer<'inp>,
902    Ctx: ParseContext<'inp, L, Lang>,
903    Condition: Decision<'inp, L, Ctx::Emitter, W, Lang>,
904    W: Window,
905  {
906    RepeatedWhile::new(self, condition)
907  }
908
909  /// Creates a `SeparatedWhile` combinator that parses separated elements, where **you
910  /// provide the lookahead logic**.
911  ///
912  /// The parser will be called repeatedly to parse elements separated by the given separator,
913  /// until:
914  /// - Your condition function returns `Action::Stop` - you decided to stop based on lookahead
915  /// - It returns `Err(e)` - fatal error
916  ///
917  /// ## Key Behavior
918  ///
919  /// Unlike [`separated()`](crate::TryParseInput::separated), this parser doesn't need built-in
920  /// lookahead:
921  /// - **You provide** a condition function that peeks ahead at tokens
922  /// - Condition decides `Continue` or `Stop` based on what it sees
923  /// - Element parser is only called when condition says `Continue`
924  /// - Separator is parsed between elements
925  ///
926  /// ## Type Parameters
927  ///
928  /// - `W`: Window size for lookahead (e.g., `U1` for 1 token, `U2` for 2 tokens)
929  ///
930  /// ## See Also
931  ///
932  /// - [`separated`](crate::TryParseInput::separated) - Parser has lookahead, with separator
933  /// - [`Action`] - The decision type (`Continue` or `Stop`)
934  #[cfg(feature = "many")]
935  #[cfg_attr(docsrs, doc(cfg(feature = "many")))]
936  #[inline(always)]
937  fn separated_while<Sep, Condition, W>(
938    self,
939    condition: Condition,
940  ) -> SeparatedWhile<Self, Sep, Condition, O, W, L, Ctx, Lang, Cmpl>
941  where
942    Self: Sized,
943    L: Lexer<'inp>,
944    Ctx: ParseContext<'inp, L, Lang>,
945    Condition: Decision<'inp, L, Ctx::Emitter, W, Lang>,
946    Sep: Punctuator<'inp, L, Lang>,
947    W: Window,
948  {
949    SeparatedWhile::new::<Sep>(self, condition)
950  }
951
952  define_separated_by!(
953    Comma,
954    Semicolon,
955    Dot,
956    Colon,
957    Pipe,
958    Ampersand,
959    Hyphen,
960    Underscore,
961    DoubleColon,
962    Arrow,
963    FatArrow,
964    Tilde,
965    Slash,
966    Backslash,
967    Percent,
968    Dollar,
969    Hash,
970    At,
971  );
972
973  /// Method form of the free [`labelled`](crate::combinator::labelled).
974  #[inline(always)]
975  fn labelled(self, name: &'static str) -> crate::combinator::Labelled<Self>
976  where
977    Self: Sized,
978  {
979    crate::combinator::labelled(name, self)
980  }
981
982  /// Method form of the free [`traced`].
983  #[cfg(feature = "trace")]
984  #[cfg_attr(docsrs, doc(cfg(feature = "trace")))]
985  #[inline(always)]
986  fn traced(self, name: &'static str) -> crate::trace::Traced<Self>
987  where
988    Self: Sized,
989  {
990    crate::trace::traced(name, self)
991  }
992
993  /// Method form of the free [`traced`].
994  ///
995  /// With `trace` off this is the identity, exactly as the free function is.
996  #[cfg(not(feature = "trace"))]
997  #[cfg_attr(docsrs, doc(cfg(not(feature = "trace"))))]
998  #[inline(always)]
999  fn traced(self, _name: &'static str) -> Self
1000  where
1001    Self: Sized,
1002  {
1003    self
1004  }
1005
1006  /// Method form of the free [`list`](crate::combinator::list) — named `list_until` because
1007  /// the `until` argument is the distinguishing half.
1008  ///
1009  /// # Availability
1010  ///
1011  /// Complete inputs only ([`Complete`](crate::input::Complete)), and the context must be a
1012  /// [`ComposableParseContext`]. The completeness pin is **inherited from the free
1013  /// [`list`](crate::combinator::list)**, which carries it already: this method cannot be wider
1014  /// than the function it delegates to, and widening that function would re-bound a pre-existing
1015  /// item. Streaming callers keep the element-level primitives. (Contrast
1016  /// [`select!`](crate::select), whose runtime is new here and is therefore generic over
1017  /// completeness.)
1018  ///
1019  /// The `alloc`/`std` gate is the free function's too — `list` returns a `Vec`.
1020  #[cfg(all(feature = "many", any(feature = "alloc", feature = "std")))]
1021  #[cfg_attr(
1022    docsrs,
1023    doc(cfg(all(feature = "many", any(feature = "alloc", feature = "std"))))
1024  )]
1025  #[inline(always)]
1026  fn list_until<Until>(
1027    self,
1028    until: Until,
1029  ) -> impl for<'c> FnMut(
1030    &mut InputRef<'inp, 'c, L, Ctx, Lang>,
1031  ) -> crate::combinator::ListOf<'inp, L, Ctx, Lang, O>
1032  where
1033    Self: Sized + ParseInput<'inp, L, O, Ctx, Lang>,
1034    L: Lexer<'inp>,
1035    Ctx: ComposableParseContext<'inp, L, Lang>,
1036    Until: FnMut(&L::Token) -> bool,
1037  {
1038    crate::combinator::list(self, until)
1039  }
1040
1041  /// Method form of the free [`separated1`](crate::combinator::separated1) — the
1042  /// committed-first "light" list shape, fluent.
1043  ///
1044  /// # Availability
1045  ///
1046  /// Same as [`list_until`](Self::list_until): complete inputs only, and a
1047  /// [`ComposableParseContext`]. The pin is inherited from the free
1048  /// [`separated1`](crate::combinator::separated1), and so is the `alloc`/`std` gate — the
1049  /// free function returns a `Vec`.
1050  #[cfg(all(feature = "many", any(feature = "alloc", feature = "std")))]
1051  #[cfg_attr(
1052    docsrs,
1053    doc(cfg(all(feature = "many", any(feature = "alloc", feature = "std"))))
1054  )]
1055  #[inline(always)]
1056  fn separated1_by<Sep, Peek>(
1057    self,
1058    peek: Peek,
1059  ) -> impl for<'c> FnMut(
1060    &mut InputRef<'inp, 'c, L, Ctx, Lang>,
1061  ) -> crate::combinator::Separated1Of<'inp, L, Ctx, Lang, O>
1062  where
1063    Self: Sized + ParseInput<'inp, L, O, Ctx, Lang>,
1064    L: Lexer<'inp>,
1065    Ctx: ComposableParseContext<'inp, L, Lang>,
1066    Sep: Punctuator<'inp, L, Lang>,
1067    Peek: FnMut(&L::Token) -> bool,
1068  {
1069    crate::combinator::separated1::<Sep, L, Ctx, Lang, Self, O, Peek>(self, peek)
1070  }
1071
1072  /// Creates a `PeekThen` combinator that peeks at most `N` tokens first from the input before parsing.
1073  ///
1074  /// If the condition handler `C` returns `Ok(())`, the inner parser is applied, otherwise,
1075  /// parsing is stopped and return the error from the handler.
1076  #[cfg(feature = "peek")]
1077  #[cfg_attr(docsrs, doc(cfg(feature = "peek")))]
1078  fn peek_then<C, W>(self, condition: C) -> PeekThen<Self, C, L::Token, W, Cmpl>
1079  where
1080    Self: Sized,
1081    L: Lexer<'inp>,
1082    Ctx: ParseContext<'inp, L, Lang>,
1083    C: FnMut(
1084      Peeked<'_, 'inp, L, W>,
1085      EmitterView<'_, 'inp, L, Ctx::Emitter, Lang>,
1086    ) -> Result<(), <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1087    W: Window,
1088    PeekThen<Self, C, L::Token, W, Cmpl>: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1089  {
1090    PeekThen::of(self, condition)
1091  }
1092
1093  /// Creates a `PeekThen` combinator that peeks at most `N` tokens first from the input before parsing.
1094  ///
1095  /// If the condition handler `C` returns `Ok(Action::Continue)`, the inner parser is applied,
1096  /// otherwise returns `None`.
1097  #[cfg(feature = "peek")]
1098  #[cfg_attr(docsrs, doc(cfg(feature = "peek")))]
1099  #[doc(alias = "or_not")]
1100  fn peek_then_try<C, W>(self, condition: C) -> PeekThen<Self, C, L::Token, W, Cmpl>
1101  where
1102    Self: Sized,
1103    L: Lexer<'inp>,
1104    Ctx: ParseContext<'inp, L, Lang>,
1105    C: Decision<'inp, L, Ctx::Emitter, W, Lang>,
1106    W: Window,
1107    PeekThen<Self, C, L::Token, W, Cmpl>: crate::TryParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1108  {
1109    PeekThen::of(self, condition)
1110  }
1111
1112  /// The width-1 twin of [`peek_then`](Self::peek_then): the condition sees `Some(head)`
1113  /// or `None` (end of input) in grammar vocabulary.
1114  ///
1115  /// No [`Peeked`], no typenum, and no emitter parameter — so a hook written as a named
1116  /// function does not have to name `Ctx` in its signature just to be callable here.
1117  #[cfg(feature = "peek")]
1118  #[cfg_attr(docsrs, doc(cfg(feature = "peek")))]
1119  #[inline(always)]
1120  fn peek_then_head<C>(
1121    self,
1122    mut condition: C,
1123  ) -> PeekThen<
1124    Self,
1125    impl FnMut(
1126      Peeked<'_, 'inp, L, typenum::U1>,
1127      EmitterView<'_, 'inp, L, Ctx::Emitter, Lang>,
1128    ) -> Result<(), <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1129    L::Token,
1130    typenum::U1,
1131    Cmpl,
1132  >
1133  where
1134    Self: Sized,
1135    L: Lexer<'inp>,
1136    Ctx: ParseContext<'inp, L, Lang>,
1137    C: FnMut(
1138      Option<Spanned<&L::Token, &L::Span>>,
1139    ) -> Result<(), <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1140  {
1141    PeekThen::of(
1142      self,
1143      move |mut toks: Peeked<'_, 'inp, L, typenum::U1>,
1144            _emitter: EmitterView<'_, 'inp, L, Ctx::Emitter, Lang>| {
1145        use crate::cache::PeekedTokenExt as _;
1146        match toks.pop_front() {
1147          Some(t) => condition(Some(Spanned::new(t.span(), t.token()))),
1148          None => condition(None),
1149        }
1150      },
1151    )
1152  }
1153
1154  /// Map the output of this parser using the given function.
1155  #[cfg(feature = "map")]
1156  #[cfg_attr(docsrs, doc(cfg(feature = "map")))]
1157  #[inline(always)]
1158  fn map<U, F>(self, f: F) -> Map<Self, F, L, Ctx, O, U, Lang, Cmpl>
1159  where
1160    Self: Sized,
1161    F: FnMut(O) -> U,
1162    L: Lexer<'inp>,
1163    Map<Self, F, L, Ctx, O, U, Lang, Cmpl>: ParseInput<'inp, L, U, Ctx, Lang, Cmpl>,
1164  {
1165    Map::new(self, f)
1166  }
1167
1168  /// Map the output of this parser using the given function.
1169  #[cfg(feature = "map")]
1170  #[cfg_attr(docsrs, doc(cfg(feature = "map")))]
1171  #[inline(always)]
1172  fn map_with<U, F>(self, f: F) -> MapWith<Self, F, L, Ctx, O, U, Lang, Cmpl>
1173  where
1174    Self: Sized,
1175    L: Lexer<'inp>,
1176    F: FnMut(O, ParseState<'_, 'inp, '_, L, Ctx, Lang, Cmpl>) -> U,
1177    MapWith<Self, F, L, Ctx, O, U, Lang, Cmpl>: ParseInput<'inp, L, U, Ctx, Lang, Cmpl>,
1178  {
1179    MapWith::new(self, f)
1180  }
1181
1182  /// Filter the output of this parser using a validation function.
1183  #[cfg(feature = "filter")]
1184  #[cfg_attr(docsrs, doc(cfg(feature = "filter")))]
1185  #[inline(always)]
1186  fn filter<F>(self, validator: F) -> Filter<Self, F, O, L, Ctx, Lang, Cmpl>
1187  where
1188    Self: Sized,
1189    L: Lexer<'inp>,
1190    F: FnMut(&O) -> Result<(), <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1191    Ctx: ParseContext<'inp, L, Lang>,
1192    Filter<Self, F, O, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1193  {
1194    Filter::of(self, validator)
1195  }
1196
1197  /// Filter the output of this parser using a validation function.
1198  #[cfg(feature = "filter")]
1199  #[cfg_attr(docsrs, doc(cfg(feature = "filter")))]
1200  #[inline(always)]
1201  fn filter_with<F>(self, validator: F) -> FilterWith<Self, F, O, L, Ctx, Lang, Cmpl>
1202  where
1203    Self: Sized,
1204    L: Lexer<'inp>,
1205    F: FnMut(
1206      &O,
1207      ParseState<'_, 'inp, '_, L, Ctx, Lang, Cmpl>,
1208    ) -> Result<(), <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1209    Ctx: ParseContext<'inp, L, Lang>,
1210    FilterWith<Self, F, O, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1211  {
1212    FilterWith::of(self, validator)
1213  }
1214
1215  /// Filter and map the output of this parser using a validation/transformation function.
1216  ///
1217  /// The parser must produce a `Spanned<O>` value. The mapper receives
1218  /// the data and span, and returns `Ok(new_value)` or an error.
1219  #[cfg(feature = "filter")]
1220  #[cfg_attr(docsrs, doc(cfg(feature = "filter")))]
1221  #[inline(always)]
1222  fn filter_map<U, F>(self, mapper: F) -> FilterMap<Self, F, O, U, L, Ctx, Lang, Cmpl>
1223  where
1224    Self: Sized,
1225    L: Lexer<'inp>,
1226    F: FnMut(O) -> Result<U, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1227    Ctx: ParseContext<'inp, L, Lang>,
1228    FilterMap<Self, F, O, U, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, U, Ctx, Lang, Cmpl>,
1229  {
1230    FilterMap::of(self, mapper)
1231  }
1232
1233  /// Filter and map the output of this parser using a validation/transformation function.
1234  ///
1235  /// The parser must produce a `Spanned<O>` value. The mapper receives
1236  /// the data and span, and returns `Ok(new_value)` or an error.
1237  #[cfg(feature = "filter")]
1238  #[cfg_attr(docsrs, doc(cfg(feature = "filter")))]
1239  #[inline(always)]
1240  fn filter_map_with<U, F>(self, mapper: F) -> FilterMapWith<Self, F, O, U, L, Ctx, Lang, Cmpl>
1241  where
1242    Self: Sized,
1243    L: Lexer<'inp>,
1244    F: FnMut(
1245      O,
1246      ParseState<'_, 'inp, '_, L, Ctx, Lang, Cmpl>,
1247    ) -> Result<U, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1248    Ctx: ParseContext<'inp, L, Lang>,
1249    FilterMapWith<Self, F, O, U, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, U, Ctx, Lang, Cmpl>,
1250  {
1251    FilterMapWith::of(self, mapper)
1252  }
1253
1254  /// Validate the output of this parser with full location context.
1255  #[cfg(feature = "validate")]
1256  #[cfg_attr(docsrs, doc(cfg(feature = "validate")))]
1257  #[inline(always)]
1258  fn validate<F>(self, validator: F) -> Validate<Self, F, O, L, Ctx, Lang, Cmpl>
1259  where
1260    Self: Sized,
1261    L: Lexer<'inp>,
1262    F: FnMut(&O) -> Result<(), <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1263    Ctx: ParseContext<'inp, L, Lang>,
1264  {
1265    Validate::of(self, validator)
1266  }
1267
1268  /// Validate the output of this parser with full location context.
1269  #[cfg(feature = "validate")]
1270  #[cfg_attr(docsrs, doc(cfg(feature = "validate")))]
1271  #[inline(always)]
1272  fn validate_with<F>(self, validator: F) -> ValidateWith<Self, F, O, L, Ctx, Lang, Cmpl>
1273  where
1274    Self: Sized,
1275    L: Lexer<'inp>,
1276    F: FnMut(
1277      &O,
1278      ParseState<'_, 'inp, '_, L, Ctx, Lang, Cmpl>,
1279    ) -> Result<(), <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1280    Ctx: ParseContext<'inp, L, Lang>,
1281  {
1282    ValidateWith::of(self, validator)
1283  }
1284
1285  /// Sequence this parser with another, ignoring the output of the second.
1286  #[cfg(feature = "then")]
1287  #[cfg_attr(docsrs, doc(cfg(feature = "then")))]
1288  #[inline(always)]
1289  fn then_ignore<G, U>(self, second: G) -> ThenIgnore<Self, G, O, U, L, Ctx, Lang, Cmpl>
1290  where
1291    Self: Sized,
1292    L: Lexer<'inp>,
1293    G: ParseInput<'inp, L, U, Ctx, Lang, Cmpl>,
1294    Ctx: ParseContext<'inp, L, Lang>,
1295    ThenIgnore<Self, G, O, U, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1296  {
1297    ThenIgnore::new(self, second)
1298  }
1299
1300  /// Sequence this parser with a fixed value, ignoring the output of the first.
1301  #[cfg(feature = "then")]
1302  #[cfg_attr(docsrs, doc(cfg(feature = "then")))]
1303  #[inline(always)]
1304  fn then_value<F, U>(self, value: F) -> ThenValue<Self, F, O, U, L, Ctx, Lang, Cmpl>
1305  where
1306    Self: Sized,
1307    L: Lexer<'inp>,
1308    Ctx: ParseContext<'inp, L, Lang>,
1309    F: FnMut() -> U,
1310  {
1311    ThenValue::new(self, value)
1312  }
1313
1314  /// Sequence this parser with another, using the first result to determine the second parser.
1315  #[cfg(feature = "then")]
1316  #[cfg_attr(docsrs, doc(cfg(feature = "then")))]
1317  #[inline(always)]
1318  fn and_then<T, U>(self, then: T) -> AndThen<Self, T, O, U, L, Ctx, Lang, Cmpl>
1319  where
1320    Self: Sized,
1321    T: FnMut(O) -> Result<U, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1322    L: Lexer<'inp>,
1323    Ctx: ParseContext<'inp, L, Lang>,
1324    AndThen<Self, T, O, U, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, U, Ctx, Lang, Cmpl>,
1325  {
1326    AndThen::new(self, then)
1327  }
1328
1329  /// Sequence this parser with another, using the first result to determine the second parser.
1330  #[cfg(feature = "then")]
1331  #[cfg_attr(docsrs, doc(cfg(feature = "then")))]
1332  #[inline(always)]
1333  fn and_then_with<T, U>(self, then: T) -> AndThenWith<Self, T, O, U, L, Ctx, Lang, Cmpl>
1334  where
1335    Self: Sized,
1336    T: FnMut(
1337      O,
1338      ParseState<'_, 'inp, '_, L, Ctx, Lang, Cmpl>,
1339    ) -> Result<U, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1340    Ctx: ParseContext<'inp, L, Lang>,
1341    L: Lexer<'inp>,
1342    AndThenWith<Self, T, O, U, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, U, Ctx, Lang, Cmpl>,
1343  {
1344    AndThenWith::new(self, then)
1345  }
1346
1347  /// Sequence this parser with another, keeping both outputs.
1348  #[cfg(feature = "then")]
1349  #[cfg_attr(docsrs, doc(cfg(feature = "then")))]
1350  #[inline(always)]
1351  fn then<T, U>(self, then: T) -> Then<Self, T, O, U, L, Ctx, Lang, Cmpl>
1352  where
1353    Self: Sized,
1354    L: Lexer<'inp>,
1355    T: ParseInput<'inp, L, U, Ctx, Lang, Cmpl>,
1356    Ctx: ParseContext<'inp, L, Lang>,
1357    Then<Self, T, O, U, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, (O, U), Ctx, Lang, Cmpl>,
1358  {
1359    Then::new(self, then)
1360  }
1361
1362  /// Sequence this parser with another, ignoring the output of the first.
1363  #[cfg(feature = "then")]
1364  #[cfg_attr(docsrs, doc(cfg(feature = "then")))]
1365  #[inline(always)]
1366  fn ignore_then<G, U>(self, second: G) -> IgnoreThen<Self, G, O, U, L, Ctx, Lang, Cmpl>
1367  where
1368    Self: Sized,
1369    L: Lexer<'inp>,
1370    G: ParseInput<'inp, L, U, Ctx, Lang, Cmpl>,
1371    IgnoreThen<Self, G, O, U, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, U, Ctx, Lang, Cmpl>,
1372  {
1373    IgnoreThen::new(self, second)
1374  }
1375
1376  /// Recover from errors by trying an alternative parser with backtracking.
1377  ///
1378  /// If this parser fails, the input position is reset to where it was before parsing,
1379  /// and the recovery parser is tried from the original position. This enables trying
1380  /// completely different parsing strategies when the primary approach fails.
1381  ///
1382  /// # Use Cases
1383  ///
1384  /// - **Alternative interpretations**: Try parsing as different constructs
1385  /// - **Fallback values**: Return error/placeholder nodes on failure
1386  /// - **Resilient parsing**: Continue parsing to find more issues
1387  ///
1388  /// # Example
1389  ///
1390  /// ```ignore
1391  /// // Parse expression or fallback to error node
1392  /// let parser = parse_expression()
1393  ///     .recover(parse_error_node());
1394  ///
1395  /// // Input: "1 + 2"      → Ok(BinaryOp(Add, 1, 2))
1396  /// // Input: "@ invalid" → Ok(ErrorNode(...))
1397  /// ```
1398  ///
1399  /// # Comparison with inplace_recover
1400  ///
1401  /// - `recover()`: Resets to starting position, tries alternative from beginning
1402  /// - `inplace_recover()`: Continues from error position, typically skips ahead
1403  ///
1404  /// See [`Recover`] for detailed documentation and more examples.
1405  #[inline(always)]
1406  fn recover<R>(self, recovery: R) -> Recover<Self, R, O, L, Ctx, Lang, Cmpl>
1407  where
1408    Self: Sized,
1409    L: Lexer<'inp>,
1410    R: RecoverInput<'inp, L, O, Ctx, Lang, Cmpl>,
1411    Ctx: ParseContext<'inp, L, Lang>,
1412    Recover<Self, R, O, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1413  {
1414    Recover::new(self, recovery)
1415  }
1416
1417  /// Recover from errors without backtracking, continuing from the error position.
1418  ///
1419  /// If this parser fails, the recovery parser starts from where the error occurred,
1420  /// not from the original starting position. This is typically used to skip ahead to
1421  /// a synchronization point (like a semicolon or brace) to resume parsing.
1422  ///
1423  /// # Use Cases
1424  ///
1425  /// - **Panic mode recovery**: Skip tokens until reaching a safe point
1426  /// - **Resynchronization**: Find the next statement/block boundary
1427  /// - **Performance**: Avoid checkpoint overhead when backtracking isn't needed
1428  ///
1429  /// # Example
1430  ///
1431  /// ```ignore
1432  /// // Parse statement, skip to semicolon on error
1433  /// let parser = parse_statement()
1434  ///     .inplace_recover(
1435  ///         skip_to(|tok| matches!(tok, Token::Semicolon))
1436  ///             .then_ignore(any())
1437  ///             .map(|_| Statement::Error)
1438  ///     );
1439  ///
1440  /// // Input: "let x = 1;"     → Ok(LetStmt { .. })
1441  /// // Input: "bad ### ; ok"   → Ok(Statement::Error)
1442  /// //             ^^^ ^
1443  /// //        error, skip to semicolon from here
1444  /// ```
1445  ///
1446  /// # Comparison with recover
1447  ///
1448  /// - `recover()`: Resets to starting position, tries alternative from beginning
1449  /// - `inplace_recover()`: Continues from error position, typically skips ahead
1450  ///
1451  /// See [`InplaceRecover`] for detailed documentation and more examples.
1452  #[inline(always)]
1453  fn inplace_recover<R>(self, recovery: R) -> InplaceRecover<Self, R, O, L, Ctx, Lang, Cmpl>
1454  where
1455    Self: Sized,
1456    L: Lexer<'inp>,
1457    R: InplaceRecoverInput<'inp, L, O, Ctx, Lang, Cmpl>,
1458    Ctx: ParseContext<'inp, L, Lang>,
1459    InplaceRecover<Self, R, O, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1460  {
1461    InplaceRecover::new(self, recovery)
1462  }
1463
1464  /// Recover from errors by skipping — nesting-aware — to a synchronization point and
1465  /// retrying this parser.
1466  ///
1467  /// If this parser fails, the input rolls back to where the attempt began, then
1468  /// [`sync_balanced`](InputRef::sync_balanced) skips forward using `classifier` (which token
1469  /// kinds open/close delimiter pairs — see [`Balance`](crate::input::Balance)) and the
1470  /// depth-0 sync predicate `pred`, and the parser is retried from the sync point. Each
1471  /// committed skip is reported once through
1472  /// [`emit_skipped_region`](crate::Emitter::emit_skipped_region).
1473  ///
1474  /// A retry cycle that consumes nothing bails out with the original error (the
1475  /// zero-consumption progress guard), and an [`Incomplete`](crate::error::Incomplete) error
1476  /// is re-raised untouched without any skipping — the never-recoverable law.
1477  ///
1478  /// # Example
1479  ///
1480  /// ```ignore
1481  /// use tokora::input::Balance;
1482  ///
1483  /// // Parse a statement; on failure skip to the next `;` (never one inside braces) and retry.
1484  /// let parser = parse_statement().skip_then_retry(
1485  ///     |kind| match kind {
1486  ///         TokenKind::LBrace => Balance::Open('{'),
1487  ///         TokenKind::RBrace => Balance::Close('{'),
1488  ///         _ => Balance::Neutral,
1489  ///     },
1490  ///     |tok| matches!(tok.data(), Token::Semi),
1491  /// );
1492  /// ```
1493  ///
1494  /// See [`SkipThenRetry`] for the full loop and progress-guard contract.
1495  #[inline(always)]
1496  fn skip_then_retry<D, F>(
1497    self,
1498    classifier: D,
1499    pred: F,
1500  ) -> SkipThenRetry<Self, D, F, O, L, Ctx, Lang, Cmpl>
1501  where
1502    Self: Sized,
1503    L: Lexer<'inp>,
1504    D: DelimClass<<L::Token as Token<'inp>>::Kind>,
1505    F: FnMut(Spanned<&L::Token, &L::Span>) -> bool,
1506    Ctx: ParseContext<'inp, L, Lang>,
1507    SkipThenRetry<Self, D, F, O, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1508  {
1509    SkipThenRetry::new(self, classifier, pred)
1510  }
1511
1512  /// Creates a parser that accepts any token with optional padding.
1513  #[inline(always)]
1514  fn padded(self) -> Padded<Self, O, L, Ctx, Lang, Cmpl>
1515  where
1516    Self: Sized,
1517    L: Lexer<'inp>,
1518    Padded<Self, O, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1519  {
1520    Padded::new(self)
1521  }
1522
1523  /// Creates a parser that accepts any token with optional padding.
1524  #[inline(always)]
1525  fn padded_left(self) -> PaddedLeft<Self, O, L, Ctx, Lang, Cmpl>
1526  where
1527    Self: Sized,
1528    L: Lexer<'inp>,
1529    PaddedLeft<Self, O, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1530  {
1531    PaddedLeft::new(self)
1532  }
1533
1534  /// Creates a parser that accepts any token with optional padding.
1535  #[inline(always)]
1536  fn padded_right(self) -> PaddedRight<Self, O, L, Ctx, Lang, Cmpl>
1537  where
1538    Self: Sized,
1539    L: Lexer<'inp>,
1540    PaddedRight<Self, O, L, Ctx, Lang, Cmpl>: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1541  {
1542    PaddedRight::new(self)
1543  }
1544}
1545
1546impl<'inp, F, L, O, Ctx, Lang: ?Sized, Cmpl> ParseInput<'inp, L, O, Ctx, Lang, Cmpl> for F
1547where
1548  F: FnMut(
1549    &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
1550  ) -> Result<O, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error>,
1551  L: Lexer<'inp>,
1552  Ctx: ParseContext<'inp, L, Lang>,
1553  Cmpl: Completeness,
1554{
1555  #[inline(always)]
1556  fn parse_input(
1557    &mut self,
1558    input: &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
1559  ) -> Result<O, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error> {
1560    (self)(input)
1561  }
1562}
1563
1564impl<'inp, F, L, O, Ctx, Lang: ?Sized, Cmpl> ParseInput<'inp, L, O, Ctx, Lang, Cmpl>
1565  for &mut ByRef<F>
1566where
1567  F: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1568  L: Lexer<'inp>,
1569  Ctx: ParseContext<'inp, L, Lang>,
1570  Cmpl: Completeness,
1571{
1572  #[inline(always)]
1573  fn parse_input(
1574    &mut self,
1575    input: &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
1576  ) -> Result<O, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error> {
1577    (**self).parse_input(input)
1578  }
1579}
1580
1581impl<'inp, L, O, Ctx, P, Lang: ?Sized, Cmpl>
1582  ParseInput<'inp, L, Spanned<O, L::Span>, Ctx, Lang, Cmpl> for With<PhantomSpan, P, Cmpl>
1583where
1584  P: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1585  L: Lexer<'inp>,
1586  Ctx: ParseContext<'inp, L, Lang>,
1587  Cmpl: Completeness,
1588{
1589  #[inline(always)]
1590  fn parse_input(
1591    &mut self,
1592    inp: &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
1593  ) -> Result<Spanned<O, L::Span>, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error> {
1594    let cursor = inp.cursor().clone();
1595    self
1596      .secondary
1597      .parse_input(inp)
1598      .map(|output| Spanned::new(inp.span_since(&cursor), output))
1599  }
1600}
1601
1602impl<'inp, L, O, Ctx, P, Lang: ?Sized, Cmpl>
1603  ParseInput<'inp, L, Sliced<O, <L::Source as Source<L::Offset>>::Slice<'inp>>, Ctx, Lang, Cmpl>
1604  for With<PhantomSliced, P, Cmpl>
1605where
1606  P: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1607  L: Lexer<'inp>,
1608  Ctx: ParseContext<'inp, L, Lang>,
1609  Cmpl: Completeness,
1610{
1611  #[inline(always)]
1612  fn parse_input(
1613    &mut self,
1614    inp: &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
1615  ) -> Result<
1616    Sliced<O, <L::Source as Source<L::Offset>>::Slice<'inp>>,
1617    <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error,
1618  > {
1619    let cursor = inp.cursor().clone();
1620    self.secondary.parse_input(inp).map(|output| {
1621      Sliced::new(
1622        inp
1623          .slice_since(&cursor)
1624          .expect("parser should guarantee slice"),
1625        output,
1626      )
1627    })
1628  }
1629}
1630
1631impl<'inp, L, O, Ctx, P, Lang: ?Sized, Cmpl>
1632  ParseInput<
1633    'inp,
1634    L,
1635    Located<O, L::Span, <L::Source as Source<L::Offset>>::Slice<'inp>>,
1636    Ctx,
1637    Lang,
1638    Cmpl,
1639  > for With<PhantomLocated, P, Cmpl>
1640where
1641  P: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1642  L: Lexer<'inp>,
1643  Ctx: ParseContext<'inp, L, Lang>,
1644  Cmpl: Completeness,
1645{
1646  #[inline(always)]
1647  fn parse_input(
1648    &mut self,
1649    inp: &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
1650  ) -> Result<
1651    Located<O, L::Span, <L::Source as Source<L::Offset>>::Slice<'inp>>,
1652    <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error,
1653  > {
1654    let cursor = inp.cursor().clone();
1655    self.secondary.parse_input(inp).map(|output| {
1656      Located::new(
1657        inp
1658          .slice_since(&cursor)
1659          .expect("parser should guarantee slice"),
1660        inp.span_since(&cursor),
1661        output,
1662      )
1663    })
1664  }
1665}
1666
1667impl<'inp, L, O, Ctx, P, Lang: ?Sized, Cmpl>
1668  ParseInput<'inp, L, Spanned<O, L::Span>, Ctx, Lang, Cmpl> for With<Trimmed<PhantomSpan>, P, Cmpl>
1669where
1670  P: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1671  L: Lexer<'inp>,
1672  Ctx: ParseContext<'inp, L, Lang>,
1673  Cmpl: Completeness,
1674{
1675  #[inline(always)]
1676  fn parse_input(
1677    &mut self,
1678    inp: &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
1679  ) -> Result<Spanned<O, L::Span>, <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error> {
1680    let start = inp.cursor_trimmed()?;
1681    self
1682      .secondary
1683      .parse_input(inp)
1684      .map(|output| Spanned::new(inp.span_since_trimmed(&start), output))
1685  }
1686}
1687
1688impl<'inp, L, O, Ctx, P, Lang: ?Sized, Cmpl>
1689  ParseInput<'inp, L, Sliced<O, <L::Source as Source<L::Offset>>::Slice<'inp>>, Ctx, Lang, Cmpl>
1690  for With<Trimmed<PhantomSliced>, P, Cmpl>
1691where
1692  P: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1693  L: Lexer<'inp>,
1694  Ctx: ParseContext<'inp, L, Lang>,
1695  Cmpl: Completeness,
1696{
1697  #[inline(always)]
1698  fn parse_input(
1699    &mut self,
1700    inp: &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
1701  ) -> Result<
1702    Sliced<O, <L::Source as Source<L::Offset>>::Slice<'inp>>,
1703    <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error,
1704  > {
1705    let start = inp.cursor_trimmed()?;
1706    self.secondary.parse_input(inp).map(|output| {
1707      Sliced::new(
1708        inp
1709          .slice_since_trimmed(&start)
1710          .expect("parser should guarantee slice"),
1711        output,
1712      )
1713    })
1714  }
1715}
1716
1717impl<'inp, L, O, Ctx, P, Lang: ?Sized, Cmpl>
1718  ParseInput<
1719    'inp,
1720    L,
1721    Located<O, L::Span, <L::Source as Source<L::Offset>>::Slice<'inp>>,
1722    Ctx,
1723    Lang,
1724    Cmpl,
1725  > for With<Trimmed<PhantomLocated>, P, Cmpl>
1726where
1727  P: ParseInput<'inp, L, O, Ctx, Lang, Cmpl>,
1728  L: Lexer<'inp>,
1729  Ctx: ParseContext<'inp, L, Lang>,
1730  Cmpl: Completeness,
1731{
1732  #[inline(always)]
1733  fn parse_input(
1734    &mut self,
1735    inp: &mut InputRef<'inp, '_, L, Ctx, Lang, Cmpl>,
1736  ) -> Result<
1737    Located<O, L::Span, <L::Source as Source<L::Offset>>::Slice<'inp>>,
1738    <Ctx::Emitter as Emitter<'inp, L, Lang>>::Error,
1739  > {
1740    let start = inp.cursor_trimmed()?;
1741    self.secondary.parse_input(inp).map(|output| {
1742      Located::new(
1743        inp
1744          .slice_since_trimmed(&start)
1745          .expect("parser should guarantee slice"),
1746        inp.span_since_trimmed(&start),
1747        output,
1748      )
1749    })
1750  }
1751}
1752
1753/// Extension trait for unwrapping `Option` outputs.
1754pub trait ParseInputUnwrapExt<'inp, L, O, Ctx, Lang: ?Sized, Cmpl = Complete> {
1755  /// Creates an `Unwrapped` parser that unwraps the `Option` result of this parser.
1756  #[inline(always)]
1757  #[track_caller]
1758  fn unwrap(self) -> Unwrapped<Self, O, Ctx, Lang, Cmpl>
1759  where
1760    Self: Sized + ParseInput<'inp, L, Option<O>, Ctx, Lang, Cmpl>,
1761  {
1762    Unwrapped::new(self)
1763  }
1764}
1765
1766impl<'inp, F, L, O, Ctx, Lang: ?Sized, Cmpl> ParseInputUnwrapExt<'inp, L, O, Ctx, Lang, Cmpl> for F
1767where
1768  F: ParseInput<'inp, L, Option<O>, Ctx, Lang, Cmpl>,
1769  L: Lexer<'inp>,
1770  Ctx: ParseContext<'inp, L, Lang>,
1771{
1772}