pest/parser_state.rs
1// pest. The Elegant Parser
2// Copyright (c) 2018 Dragoș Tiselice
3//
4// Licensed under the Apache License, Version 2.0
5// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
6// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. All files in the project carrying such notice may not be copied,
8// modified, or distributed except according to those terms.
9
10//! The core functionality of parsing grammar.
11//! State of parser during the process of rules handling.
12
13use alloc::borrow::{Cow, ToOwned};
14use alloc::boxed::Box;
15use alloc::collections::BTreeSet;
16use alloc::rc::Rc;
17use alloc::string::String;
18use alloc::sync::Arc;
19use alloc::vec;
20use alloc::vec::Vec;
21use core::fmt::{Debug, Display, Formatter};
22use core::num::NonZeroUsize;
23use core::ops::Deref; // used in BorrowedOrRc.as_str
24use core::ops::Range;
25use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
26
27use crate::RuleType;
28use crate::error::{Error, ErrorVariant};
29use crate::iterators::pairs::new;
30use crate::iterators::{QueueableToken, pairs};
31use crate::position::Position;
32use crate::span::Span;
33use crate::stack::Stack;
34
35/// The current lookahead status of a [`ParserState`].
36///
37/// [`ParserState`]: struct.ParserState.html
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39pub enum Lookahead {
40 /// The positive predicate, written as an ampersand &,
41 /// attempts to match its inner expression.
42 /// If the inner expression succeeds, parsing continues,
43 /// but at the same position as the predicate —
44 /// &foo ~ bar is thus a kind of "AND" statement:
45 /// "the input string must match foo AND bar".
46 /// If the inner expression fails,
47 /// the whole expression fails too.
48 Positive,
49 /// The negative predicate, written as an exclamation mark !,
50 /// attempts to match its inner expression.
51 /// If the inner expression fails, the predicate succeeds
52 /// and parsing continues at the same position as the predicate.
53 /// If the inner expression succeeds, the predicate fails —
54 /// !foo ~ bar is thus a kind of "NOT" statement:
55 /// "the input string must match bar but NOT foo".
56 Negative,
57 /// No lookahead (i.e. it will consume input).
58 None,
59}
60
61/// The current atomicity of a [`ParserState`].
62///
63/// [`ParserState`]: struct.ParserState.html
64#[derive(Clone, Copy, Debug, Eq, PartialEq)]
65pub enum Atomicity {
66 /// prevents implicit whitespace: inside an atomic rule,
67 /// the tilde ~ means "immediately followed by",
68 /// and repetition operators (asterisk * and plus sign +)
69 /// have no implicit separation. In addition, all other rules
70 /// called from an atomic rule are also treated as atomic.
71 /// (interior matching rules are silent)
72 Atomic,
73 /// The same as atomic, but inner tokens are produced as normal.
74 CompoundAtomic,
75 /// implicit whitespace is enabled
76 NonAtomic,
77}
78
79/// Type alias to simplify specifying the return value of chained closures.
80pub type ParseResult<S> = Result<S, S>;
81
82/// Match direction for the stack. Used in `PEEK[a..b]`/`stack_match_peek_slice`.
83#[derive(Clone, Copy, Debug, Eq, PartialEq)]
84pub enum MatchDir {
85 /// from the bottom to the top of the stack
86 BottomToTop,
87 /// from the top to the bottom of the stack
88 TopToBottom,
89}
90
91static CALL_LIMIT: AtomicUsize = AtomicUsize::new(0);
92
93/// Sets the maximum cumulative number of counted parser-state calls.
94///
95/// Invocations of [`ParserState::rule`], [`ParserState::sequence`],
96/// [`ParserState::repeat`], [`ParserState::optional`], [`ParserState::lookahead`],
97/// [`ParserState::atomic`], and [`ParserState::stack_push`] consume this budget.
98/// Calls are not refunded after returning or backtracking. Repetition counts
99/// its entry, not each iteration of its closure. Primitive matches and
100/// [`ParserState::restore_on_err`] do not consume this cumulative budget.
101/// A refused entry fails the parse with "call limit reached", even if an
102/// alternative or optional expression would otherwise recover.
103///
104/// This process-wide setting is captured when each [`ParserState`] is created.
105/// `None` disables the cumulative budget. Available native stack space is
106/// checked automatically in `std` builds on the [default native targets].
107/// Other targets require the `stack-guard` feature (which enables `std`).
108/// These checks are independent of this setting; insufficient space fails
109/// parsing with "stack limit reached".
110/// Stack checking is best-effort when native stack bounds cannot be determined
111/// and is not available in `no_std` builds. It cannot protect arbitrary user
112/// callbacks or work outside the parser's guarded entry points.
113/// It is not an elapsed-time or memory limit: individual operations and
114/// user closures may perform work without additional counted calls.
115/// See the [resource-limit guidance] for enforcing deadlines.
116///
117/// [resource-limit guidance]: https://github.com/pest-parser/pest/blob/master/SECURITY.md#parsing-untrusted-input
118/// [default native targets]: https://github.com/pest-parser/pest/blob/master/README.md#native-stack-guard
119pub fn set_call_limit(limit: Option<NonZeroUsize>) {
120 CALL_LIMIT.store(
121 limit.map(|limit| limit.get()).unwrap_or(0),
122 Ordering::Relaxed,
123 );
124}
125
126static ERROR_DETAIL: AtomicBool = AtomicBool::new(false);
127
128/// Sets whether information for more error details
129/// should be collected. This is useful for debugging
130/// parser errors (as it leads to more comprehensive
131/// error messages), but it has a higher performance cost.
132/// (hence, it's off by default)
133///
134/// # Arguments
135///
136/// * `enabled` - Whether to enable the collection for
137/// more error details.
138pub fn set_error_detail(enabled: bool) {
139 ERROR_DETAIL.store(enabled, Ordering::Relaxed);
140}
141
142#[derive(Clone, Copy, Debug, Eq, PartialEq)]
143enum LimitKind {
144 Call,
145 Stack,
146}
147
148/// Native stack space that must be available at every parser checkpoint,
149/// because a parser may use that much before it reaches its next checkpoint.
150const REQUIRED_STACK_SPACE: usize = 64 * 1024;
151
152/// Most checkpoints that may rely on a single stack measurement, however much
153/// space it found. A parser state that continues on another stack therefore
154/// measures again before long.
155const MAX_ENTRIES_PER_STACK_PROBE: usize = 127;
156
157#[inline]
158fn remaining_stack() -> Option<usize> {
159 #[cfg(feature = "std")]
160 return pest_stack_guard::remaining_stack();
161 #[cfg(not(feature = "std"))]
162 return None;
163}
164
165/// Returns how many checkpoints after the measuring one may rely on its stack
166/// measurement.
167///
168/// A parser is assumed to use at most `REQUIRED_STACK_SPACE` between two
169/// checkpoints, which measuring at every checkpoint relies on as well. Each
170/// covered checkpoint may therefore lower the measured space by that much and
171/// must still find the reserve available. As a result, measurements become
172/// more frequent as the stack fills up, and every checkpoint measures once
173/// fewer than two reserves remain. Unknown stack bounds are queried again
174/// after the maximum interval.
175fn entries_covered_by(stack_space: Option<usize>) -> usize {
176 stack_space.map_or(MAX_ENTRIES_PER_STACK_PROBE, |remaining| {
177 (remaining / REQUIRED_STACK_SPACE)
178 .saturating_sub(1)
179 .min(MAX_ENTRIES_PER_STACK_PROBE)
180 })
181}
182
183#[derive(Debug)]
184struct CallLimitTracker {
185 current_call_limit: Option<(usize, usize)>,
186 limit_reached: Option<LimitKind>,
187 /// Checkpoints that may still rely on the last stack measurement. This is
188 /// zero once a limit is reached, so that later entries take the slow path
189 /// and are rejected there.
190 entries_before_stack_probe: usize,
191}
192
193impl Default for CallLimitTracker {
194 fn default() -> Self {
195 let call_limit = CALL_LIMIT.load(Ordering::Relaxed);
196 Self {
197 current_call_limit: (call_limit > 0).then_some((0, call_limit)),
198 limit_reached: None,
199 entries_before_stack_probe: 0,
200 }
201 }
202}
203
204impl CallLimitTracker {
205 #[inline]
206 fn limit_reached(&self) -> bool {
207 self.limit_reached.is_some()
208 }
209
210 fn error_message(&self) -> Option<&'static str> {
211 self.limit_reached.map(|cause| match cause {
212 LimitKind::Call => "call limit reached",
213 LimitKind::Stack => "stack limit reached",
214 })
215 }
216
217 /// Records the limit that stops the parse and ends any stack measurement
218 /// reuse, so that every later entry is rejected as well.
219 fn reject(&mut self, cause: LimitKind) {
220 self.limit_reached = Some(cause);
221 self.entries_before_stack_probe = 0;
222 }
223
224 /// Admits a parser checkpoint, charging the call budget if `count_call`.
225 ///
226 /// This runs on every rule and combinator entry, so it only does the
227 /// bookkeeping inline and leaves measuring the stack to `enter_probing_stack`.
228 #[inline]
229 fn enter(&mut self, count_call: bool) -> bool {
230 if self.entries_before_stack_probe == 0 {
231 return self.enter_probing_stack(count_call);
232 }
233 if count_call && let Some((current, limit)) = &mut self.current_call_limit {
234 if *current >= *limit {
235 self.reject(LimitKind::Call);
236 return false;
237 }
238 *current += 1;
239 }
240 self.entries_before_stack_probe -= 1;
241 true
242 }
243
244 #[cold]
245 #[inline(never)]
246 fn enter_probing_stack(&mut self, count_call: bool) -> bool {
247 if self.limit_reached() {
248 return false;
249 }
250 if count_call
251 && self
252 .current_call_limit
253 .is_some_and(|(current, limit)| current >= limit)
254 {
255 self.reject(LimitKind::Call);
256 return false;
257 }
258 let remaining = remaining_stack();
259 self.enter_with_stack(count_call, remaining)
260 }
261
262 fn enter_with_stack(&mut self, count_call: bool, stack_space: Option<usize>) -> bool {
263 if self.limit_reached() {
264 return false;
265 }
266 let cause = if count_call
267 && self
268 .current_call_limit
269 .is_some_and(|(current, limit)| current >= limit)
270 {
271 Some(LimitKind::Call)
272 } else if stack_space.is_some_and(|remaining| remaining < REQUIRED_STACK_SPACE) {
273 Some(LimitKind::Stack)
274 } else {
275 None
276 };
277 if let Some(cause) = cause {
278 self.reject(cause);
279 return false;
280 }
281 if count_call && let Some((current, _)) = &mut self.current_call_limit {
282 *current += 1;
283 }
284 self.entries_before_stack_probe = entries_covered_by(stack_space);
285 true
286 }
287}
288
289/// Number of call stacks that may result from a sequence of rules parsing.
290const CALL_STACK_INITIAL_CAPACITY: usize = 20;
291/// Max (un)expected number of tokens that we may see on the parsing error position.
292const EXPECTED_TOKENS_INITIAL_CAPACITY: usize = 30;
293/// Max rule children number for which we'll extend calls stacks.
294///
295/// In case rule we're working with has too many children rules that failed in parsing,
296/// we don't want to store long stacks for all of them. If rule has more than this number
297/// of failed children, they all will be collapsed in a parent rule.
298const CALL_STACK_CHILDREN_THRESHOLD: usize = 4;
299
300/// Structure tracking errored parsing call (associated with specific `ParserState` function).
301#[derive(Debug, Hash, PartialEq, Eq, Clone, PartialOrd, Ord)]
302pub enum ParseAttempt<R> {
303 /// Call of `rule` errored.
304 Rule(R),
305 /// Call of token element (e.g., `match_string` or `match_insensitive`) errored.
306 /// Works as indicator of that leaf node is not a rule. In order to get the token value we
307 /// can address `ParseAttempts` `(un)expected_tokens`.
308 Token,
309}
310
311impl<R> ParseAttempt<R> {
312 pub fn get_rule(&self) -> Option<&R> {
313 match self {
314 ParseAttempt::Rule(r) => Some(r),
315 ParseAttempt::Token => None,
316 }
317 }
318}
319
320/// Rules call stack.
321/// Contains sequence of rule calls that resulted in new parsing attempt.
322#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
323pub struct RulesCallStack<R> {
324 /// Deepest rule caused a parsing error (ParseAttempt::Token transformed into a rule).
325 pub deepest: ParseAttempt<R>,
326 /// Most top rule covering `deepest`.
327 pub parent: Option<R>,
328}
329
330impl<R> RulesCallStack<R> {
331 fn new(deepest: ParseAttempt<R>) -> RulesCallStack<R> {
332 RulesCallStack {
333 deepest,
334 parent: None,
335 }
336 }
337}
338
339#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
340pub enum ParsingToken {
341 Sensitive { token: String },
342 Insensitive { token: String },
343 Range { start: char, end: char },
344 BuiltInRule,
345}
346
347impl Display for ParsingToken {
348 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
349 match self {
350 ParsingToken::Sensitive { token } => write!(f, "{token}"),
351 ParsingToken::Insensitive { token } => write!(f, "{}", token.to_uppercase()),
352 ParsingToken::Range { start, end } => write!(f, "{start}..{end}"),
353 ParsingToken::BuiltInRule => write!(f, "BUILTIN_RULE"),
354 }
355 }
356}
357/// A helper that provides efficient string handling without unnecessary copying.
358/// We use `Arc<String>` instead of `Cow<'i, str>` to avoid copying strings when cloning the `Owned` variant, since
359/// `Arc::clone` only increments a reference count. [SpanOrLiteral] needs to be [Send] and [Sync]`, so we use [Arc]
360/// instead of [Rc].
361///
362/// (We need to clone this struct to detach it from the `&self` borrow in [SpanOrLiteral::as_borrowed_or_rc], so that
363/// we can then call `self.match_string` (a `mut self` method).
364#[derive(Debug, Clone)]
365enum BorrowedOrArc<'i> {
366 Borrowed(&'i str),
367 Owned(Arc<String>),
368}
369
370/// A holder for a literal string, for use in `push_literal`. This is typically a `&'static str`, but is an owned
371/// `Rc<String>` for the pest vm.
372impl<'i> BorrowedOrArc<'i> {
373 fn as_str<'a: 'i>(&'a self) -> &'a str {
374 match self {
375 BorrowedOrArc::Borrowed(s) => s,
376 BorrowedOrArc::Owned(s) => s.deref(),
377 }
378 }
379}
380
381impl From<Cow<'static, str>> for BorrowedOrArc<'_> {
382 fn from(value: Cow<'static, str>) -> Self {
383 match value {
384 Cow::Borrowed(s) => Self::Borrowed(s),
385 Cow::Owned(s) => Self::Owned(Arc::new(s)),
386 }
387 }
388}
389
390#[derive(Debug, Clone)]
391enum SpanOrLiteral<'i> {
392 Span(Span<'i>),
393 Literal(BorrowedOrArc<'i>),
394}
395
396impl<'i> SpanOrLiteral<'i> {
397 #[inline]
398 fn as_borrowed_or_rc(&self) -> BorrowedOrArc<'i> {
399 match self {
400 Self::Span(s) => BorrowedOrArc::Borrowed(s.as_str()),
401 Self::Literal(s) => s.clone(),
402 }
403 }
404}
405
406/// Structure that tracks all the parsing attempts made on the max position.
407/// We want to give an error hint about parsing rules that succeeded
408/// at the farthest input position.
409/// The intuition is such rules will be most likely the query user initially wanted to write.
410#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
411pub struct ParseAttempts<R> {
412 /// Indicates whether the parsing attempts are tracked.
413 enabled: bool,
414 /// Vec of rule calls sequences awaiting tokens at the same `max_position`.
415 /// If there are several stacks in vec, it means all those rule stacks are "equal"
416 /// because their attempts occurred on the same position.
417 pub call_stacks: Vec<RulesCallStack<R>>,
418 /// Tokens that could be putted at `max_position`
419 /// in order to get a valid grammar query.
420 expected_tokens: Vec<ParsingToken>,
421 /// Tokens that we've prohibited to be putted at `max_position`
422 /// in order to get a valid grammar query.
423 unexpected_tokens: Vec<ParsingToken>,
424 /// Max position at which we were expecting to see one of `expected_tokens`.
425 pub max_position: usize,
426}
427
428impl<R: RuleType> ParseAttempts<R> {
429 /// Create new `ParseAttempts` instance with `call_stacks` and `expected_tokens`
430 /// initialized with capacity.
431 pub fn new() -> Self {
432 Self {
433 call_stacks: Vec::with_capacity(CALL_STACK_INITIAL_CAPACITY),
434 expected_tokens: Vec::with_capacity(EXPECTED_TOKENS_INITIAL_CAPACITY),
435 unexpected_tokens: Vec::with_capacity(EXPECTED_TOKENS_INITIAL_CAPACITY),
436 max_position: 0,
437 enabled: ERROR_DETAIL.load(Ordering::Relaxed),
438 }
439 }
440
441 /// Get number of currently present call stacks.
442 fn call_stacks_number(&self) -> usize {
443 self.call_stacks.len()
444 }
445
446 pub fn expected_tokens(&self) -> Vec<ParsingToken> {
447 self.expected_tokens
448 .iter()
449 .cloned()
450 .collect::<BTreeSet<_>>()
451 .into_iter()
452 .collect()
453 }
454
455 pub fn unexpected_tokens(&self) -> Vec<ParsingToken> {
456 self.unexpected_tokens
457 .iter()
458 .cloned()
459 .collect::<BTreeSet<_>>()
460 .into_iter()
461 .collect()
462 }
463
464 /// Retrieve call stacks.
465 pub fn call_stacks(&self) -> Vec<RulesCallStack<R>> {
466 self.call_stacks
467 .iter()
468 .cloned()
469 .collect::<BTreeSet<_>>()
470 .into_iter()
471 .collect()
472 }
473
474 /// In case we've tried to parse a rule, which start position is bigger than previous
475 /// `max_position` it means that we've advanced in our parsing and found better candidate.
476 ///
477 /// `start_index` is:
478 /// * Number of call stacks present in state at the moment current `rule` was called. The idea
479 /// is that we'd like to update only those stacks that originated from the current `rule` and
480 /// not from those that were called previously.
481 /// * 0 in case we've successfully parsed some token since the moment `rule` was called.
482 fn try_add_new_stack_rule(&mut self, rule: R, start_index: usize) {
483 let mut non_token_call_stacks = Vec::new();
484 let mut token_call_stack_met = false;
485 for call_stack in self.call_stacks.iter().skip(start_index) {
486 if matches!(call_stack.deepest, ParseAttempt::Token) {
487 token_call_stack_met = true;
488 } else {
489 non_token_call_stacks.push(call_stack.clone())
490 }
491 }
492 if token_call_stack_met && non_token_call_stacks.is_empty() {
493 // If `non_token_call_stacks` is not empty we wouldn't like to add a new standalone
494 // `RulesCallStack::new(ParseAttempt::Token)` (that will later be transformed into a
495 // rule) as soon as it doesn't give us any useful additional info.
496 non_token_call_stacks.push(RulesCallStack::new(ParseAttempt::Token));
497 }
498 self.call_stacks
499 .splice(start_index.., non_token_call_stacks);
500
501 let children_number_over_threshold =
502 self.call_stacks_number() - start_index >= CALL_STACK_CHILDREN_THRESHOLD;
503 if children_number_over_threshold {
504 self.call_stacks.truncate(start_index);
505 self.call_stacks
506 .push(RulesCallStack::new(ParseAttempt::Rule(rule)));
507 } else {
508 for call_stack in self.call_stacks.iter_mut().skip(start_index) {
509 if matches!(call_stack.deepest, ParseAttempt::Token) {
510 call_stack.deepest = ParseAttempt::Rule(rule);
511 } else {
512 call_stack.parent = Some(rule);
513 }
514 }
515 }
516 }
517
518 /// If `expected` flag is set to false, it means we've successfully parsed token being in the
519 /// state of negative lookahead and want to track `token` in the `unexpected_tokens`. Otherwise,
520 /// we want to track it the `expected_tokens`. Let's call chosen vec a `target_vec`.
521 ///
522 /// In case `position` is:
523 /// * Equal to `max_position`, add `token` to `target_vec`,
524 /// * Bigger than `max_position`, set `token` as the only new element of `target_vec`.
525 #[allow(clippy::comparison_chain)]
526 fn try_add_new_token(
527 &mut self,
528 token: ParsingToken,
529 start_position: usize,
530 position: usize,
531 negative_lookahead: bool,
532 ) {
533 let target_vec_push_token = |attempts: &mut ParseAttempts<R>| {
534 let target_vec = if negative_lookahead {
535 &mut attempts.unexpected_tokens
536 } else {
537 &mut attempts.expected_tokens
538 };
539 target_vec.push(token);
540 };
541
542 if position > self.max_position {
543 if negative_lookahead && start_position > self.max_position {
544 // We encountered a sequence under negative lookahead.
545 // We would like to track only first failed token in this sequence (which
546 // `start_position` should be equal to `self.max_position`).
547 return;
548 }
549 target_vec_push_token(self);
550
551 if negative_lookahead {
552 // In case of successful parsing of token under negative lookahead the only
553 // thing we'd like to do is to track the token in the `unexpected_tokens`.
554 return;
555 }
556 self.max_position = position;
557 self.expected_tokens.clear();
558 self.unexpected_tokens.clear();
559 self.call_stacks.clear();
560 self.call_stacks
561 .push(RulesCallStack::new(ParseAttempt::Token));
562 } else if position == self.max_position {
563 target_vec_push_token(self);
564 self.call_stacks
565 .push(RulesCallStack::new(ParseAttempt::Token));
566 }
567 }
568
569 /// Reset state in case we've successfully parsed some token in
570 /// `match_string` or `match_insensitive`.
571 fn nullify_expected_tokens(&mut self, new_max_position: usize) {
572 self.call_stacks.clear();
573 self.expected_tokens.clear();
574 self.unexpected_tokens.clear();
575 self.max_position = new_max_position;
576 }
577}
578
579impl<R: RuleType> Default for ParseAttempts<R> {
580 fn default() -> Self {
581 Self::new()
582 }
583}
584
585/// The complete state of a [`Parser`].
586///
587/// [`Parser`]: trait.Parser.html
588#[derive(Debug)]
589pub struct ParserState<'i, R: RuleType> {
590 /// Current position from which we try to apply some parser function.
591 /// Initially is 0.
592 /// E.g., we are parsing `create user 'Bobby'` query, we parsed "create" via `match_insensitive`
593 /// and switched our `position` from 0 to the length of "create".
594 ///
595 /// E.g., see `match_string` -> `self.position.match_string(string)` which updates `self.pos`.
596 position: Position<'i>,
597 /// Queue representing rules partially (`QueueableToken::Start`) and
598 /// totally (`QueueableToken::End`) parsed. When entering rule we put it in the queue in a state
599 /// of `Start` and after all its sublogic (subrules or strings) are parsed, we change it to
600 /// `End` state.
601 queue: Vec<QueueableToken<'i, R>>,
602 /// Status set in case specific lookahead logic is used in grammar.
603 /// See `Lookahead` for more information.
604 lookahead: Lookahead,
605 /// Rules that we HAVE expected, tried to parse, but failed.
606 pos_attempts: Vec<R>,
607 /// Rules that we have NOT expected, tried to parse, but failed.
608 neg_attempts: Vec<R>,
609 /// Max position in the query from which we've tried to parse some rule but failed.
610 attempt_pos: usize,
611 /// Current atomicity status. For more information see `Atomicity`.
612 atomicity: Atomicity,
613 /// Helper structure tracking `Stack` status (used in case grammar contains stack PUSH/POP
614 /// invocations).
615 stack: Stack<SpanOrLiteral<'i>>,
616 /// Tracks cumulative parser-state calls and call/stack limit exhaustion.
617 call_tracker: CallLimitTracker,
618 /// Together with tracking of `pos_attempts` and `attempt_pos`
619 /// as a pair of (list of rules that we've tried to parse but failed, max parsed position)
620 /// we track those rules (which we've tried to parse at the same max pos) at this helper struct.
621 ///
622 /// Note, that we may try to parse several rules on different positions. We want to track only
623 /// those rules, which attempt position is bigger, because we consider that it's nearer to the
624 /// query that user really wanted to pass.
625 ///
626 /// E.g. we have a query `create user "Bobby"` and two root rules:
627 /// * CreateUser = { "create" ~ "user" ~ Name }
628 /// * CreateTable = { "create" ~ "table" ~ Name }
629 /// * Name = { SOME_DEFINITION }
630 ///
631 /// While parsing the query we'll update tracker position to the start of "Bobby", because we'd
632 /// successfully parse "create" + "user" (and not "table").
633 parse_attempts: ParseAttempts<R>,
634}
635
636/// Creates a `ParserState` from a `&str`, supplying it to a closure `f`.
637///
638/// # Examples
639///
640/// ```
641/// # use pest;
642/// let input = "";
643/// pest::state::<(), _>(input, |s| Ok(s)).unwrap();
644/// ```
645#[allow(clippy::perf)]
646pub fn state<'i, R: RuleType, F>(input: &'i str, f: F) -> Result<pairs::Pairs<'i, R>, Error<R>>
647where
648 F: FnOnce(Box<ParserState<'i, R>>) -> ParseResult<Box<ParserState<'i, R>>>,
649{
650 let state = ParserState::new(input);
651
652 match f(state) {
653 Ok(state) if !state.call_tracker.limit_reached() => {
654 let len = state.queue.len();
655 Ok(new(Rc::new(state.queue), input, None, 0, len))
656 }
657 Ok(mut state) | Err(mut state) => {
658 let variant = if let Some(message) = state.call_tracker.error_message() {
659 ErrorVariant::CustomError {
660 message: message.to_owned(),
661 }
662 } else {
663 state.pos_attempts.sort();
664 state.pos_attempts.dedup();
665 state.neg_attempts.sort();
666 state.neg_attempts.dedup();
667 ErrorVariant::ParsingError {
668 positives: state.pos_attempts.clone(),
669 negatives: state.neg_attempts.clone(),
670 }
671 };
672
673 if state.parse_attempts.enabled {
674 Err(Error::new_from_pos_with_parsing_attempts(
675 variant,
676 Position::new_internal(input, state.attempt_pos),
677 state.parse_attempts.clone(),
678 ))
679 } else {
680 Err(Error::new_from_pos(
681 variant,
682 Position::new_internal(input, state.attempt_pos),
683 ))
684 }
685 }
686 }
687}
688
689impl<'i, R: RuleType> ParserState<'i, R> {
690 /// Allocates a fresh `ParserState` object to the heap and returns the owned `Box`. This `Box`
691 /// will be passed from closure to closure based on the needs of the specified `Parser`.
692 ///
693 /// # Examples
694 ///
695 /// ```
696 /// # use pest;
697 /// let input = "";
698 /// let state: Box<pest::ParserState<&str>> = pest::ParserState::new(input);
699 /// ```
700 pub fn new(input: &'i str) -> Box<Self> {
701 Box::new(ParserState {
702 position: Position::from_start(input),
703 queue: vec![],
704 lookahead: Lookahead::None,
705 pos_attempts: vec![],
706 neg_attempts: vec![],
707 attempt_pos: 0,
708 atomicity: Atomicity::NonAtomic,
709 stack: Stack::new(),
710 call_tracker: Default::default(),
711 parse_attempts: ParseAttempts::new(),
712 })
713 }
714
715 /// Get all parse attempts after process of parsing is finished.
716 pub fn get_parse_attempts(&self) -> &ParseAttempts<R> {
717 &self.parse_attempts
718 }
719
720 /// Returns a reference to the current `Position` of the `ParserState`.
721 ///
722 /// # Examples
723 ///
724 /// ```
725 /// # use pest;
726 /// # #[allow(non_camel_case_types)]
727 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
728 /// enum Rule {
729 /// ab
730 /// }
731 ///
732 /// let input = "ab";
733 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
734 /// let position = state.position();
735 /// assert_eq!(position.pos(), 0);
736 /// ```
737 pub fn position(&self) -> &Position<'i> {
738 &self.position
739 }
740
741 /// Returns the current atomicity of the `ParserState`.
742 ///
743 /// # Examples
744 ///
745 /// ```
746 /// # use pest;
747 /// # use pest::Atomicity;
748 /// # #[allow(non_camel_case_types)]
749 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
750 /// enum Rule {
751 /// ab
752 /// }
753 ///
754 /// let input = "ab";
755 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
756 /// let atomicity = state.atomicity();
757 /// assert_eq!(atomicity, Atomicity::NonAtomic);
758 /// ```
759 pub fn atomicity(&self) -> Atomicity {
760 self.atomicity
761 }
762
763 #[inline]
764 fn inc_call_check_limit(mut self: Box<Self>) -> ParseResult<Box<Self>> {
765 if !self.call_tracker.enter(true) {
766 return Err(self);
767 }
768 Ok(self)
769 }
770
771 /// Checks native stack headroom without consuming a counted parser call.
772 #[doc(hidden)]
773 #[inline]
774 pub fn check_stack_limit(mut self: Box<Self>) -> ParseResult<Box<Self>> {
775 if !self.call_tracker.enter(false) {
776 return Err(self);
777 }
778 Ok(self)
779 }
780
781 /// Wrapper needed to generate tokens. This will associate the `R` type rule to the closure
782 /// meant to match the rule.
783 ///
784 /// # Examples
785 ///
786 /// ```
787 /// # use pest;
788 /// # #[allow(non_camel_case_types)]
789 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
790 /// enum Rule {
791 /// a
792 /// }
793 ///
794 /// let input = "a";
795 /// let pairs: Vec<_> = pest::state(input, |state| {
796 /// state.rule(Rule::a, |s| Ok(s))
797 /// }).unwrap().collect();
798 ///
799 /// assert_eq!(pairs.len(), 1);
800 /// ```
801 #[inline]
802 pub fn rule<F>(mut self: Box<Self>, rule: R, f: F) -> ParseResult<Box<Self>>
803 where
804 F: FnOnce(Box<Self>) -> ParseResult<Box<Self>>,
805 {
806 self = self.inc_call_check_limit()?;
807 // Position from which this `rule` starts parsing.
808 let actual_pos = self.position.pos();
809 // Remember index of the `self.queue` element that will be associated with this `rule`.
810 let index = self.queue.len();
811
812 let (pos_attempts_index, neg_attempts_index) = if actual_pos == self.attempt_pos {
813 (self.pos_attempts.len(), self.neg_attempts.len())
814 } else {
815 // Attempts have not been cleared yet since the attempt_pos is older.
816 (0, 0)
817 };
818
819 if self.lookahead == Lookahead::None && self.atomicity != Atomicity::Atomic {
820 // Pair's position will only be known after running the closure.
821 self.queue.push(QueueableToken::Start {
822 end_token_index: 0,
823 input_pos: actual_pos,
824 });
825 }
826
827 // Remember attempts number before `f` call.
828 // In `track` using this variable we can say, how many attempts were added
829 // during children rules traversal.
830 let attempts = self.attempts_at(actual_pos);
831 // Number of call stacks present in `self.parse_attempts` before `f` call.
832 // We need to remember this number only in case there wasn't found any farther attempt.
833 // E.g. we are handling rule, on start position of which may be tested two
834 // children rules. At the moment we'll return from `f` call below,
835 // there will be two more children rules in `self.parse_attempts` that we'll
836 // consider to be the children of current `rule`.
837 let mut remember_call_stacks_number = self.parse_attempts.call_stacks_number();
838 // Max parsing attempt position at the moment of `rule` handling.
839 // It case it's raised during children rules handling, it means
840 // we've made a parsing progress.
841 let remember_max_position = self.parse_attempts.max_position;
842
843 let result = f(self);
844
845 let mut try_add_rule_to_stack = |new_state: &mut Box<ParserState<'_, R>>| {
846 if new_state.parse_attempts.max_position > remember_max_position {
847 // It means that one of `match_string` or e.g. `match_insensitive` function calls
848 // have already erased `self.parse_attempts.call_stacks` and that previously
849 // remembered values are not valid anymore.
850 remember_call_stacks_number = 0;
851 }
852 if !matches!(new_state.atomicity, Atomicity::Atomic) {
853 new_state
854 .parse_attempts
855 .try_add_new_stack_rule(rule, remember_call_stacks_number);
856 }
857 };
858
859 match result {
860 Ok(mut new_state) => {
861 if new_state.lookahead == Lookahead::Negative {
862 new_state.track(
863 rule,
864 actual_pos,
865 pos_attempts_index,
866 neg_attempts_index,
867 attempts,
868 );
869 }
870
871 if new_state.lookahead == Lookahead::None
872 && new_state.atomicity != Atomicity::Atomic
873 {
874 // Index of `QueueableToken::End` token added below
875 // that corresponds to previously added `QueueableToken::Start` token.
876 let new_index = new_state.queue.len();
877 match new_state.queue[index] {
878 QueueableToken::Start {
879 ref mut end_token_index,
880 ..
881 } => *end_token_index = new_index,
882 _ => unreachable!(),
883 };
884
885 let new_pos = new_state.position.pos();
886
887 new_state.queue.push(QueueableToken::End {
888 start_token_index: index,
889 rule,
890 tag: None,
891 input_pos: new_pos,
892 });
893 }
894
895 // Note, that we need to count positive parsing results too, because we can fail in
896 // optional rule call inside which may lie the farthest
897 // parsed token.
898 if new_state.parse_attempts.enabled {
899 try_add_rule_to_stack(&mut new_state);
900 }
901 Ok(new_state)
902 }
903 Err(mut new_state) => {
904 if new_state.lookahead != Lookahead::Negative {
905 new_state.track(
906 rule,
907 actual_pos,
908 pos_attempts_index,
909 neg_attempts_index,
910 attempts,
911 );
912 if new_state.parse_attempts.enabled {
913 try_add_rule_to_stack(&mut new_state);
914 }
915 }
916
917 if new_state.lookahead == Lookahead::None
918 && new_state.atomicity != Atomicity::Atomic
919 {
920 new_state.queue.truncate(index);
921 }
922
923 Err(new_state)
924 }
925 }
926 }
927
928 /// Tag current node
929 ///
930 /// # Examples
931 ///
932 /// Try to recognize the one specified in a set of characters
933 ///
934 /// ```
935 /// use pest::{state, ParseResult, ParserState, iterators::Pair};
936 /// #[allow(non_camel_case_types)]
937 /// #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
938 /// enum Rule {
939 /// character,
940 /// }
941 /// fn mark_c(state: Box<ParserState<Rule>>) -> ParseResult<Box<ParserState<Rule>>> {
942 /// state.sequence(|state| {
943 /// character(state)
944 /// .and_then(|state| character(state))
945 /// .and_then(|state| character(state))
946 /// .and_then(|state| state.tag_node("c"))
947 /// .and_then(|state| character(state))
948 /// })
949 /// }
950 /// fn character(state: Box<ParserState<Rule>>) -> ParseResult<Box<ParserState<Rule>>> {
951 /// state.rule(Rule::character, |state| state.match_range('a'..'z'))
952 /// }
953 ///
954 /// let input = "abcd";
955 /// let pairs = state(input, mark_c).unwrap();
956 /// // find all node tag as `c`
957 /// let find: Vec<Pair<Rule>> = pairs.filter(|s| s.as_node_tag() == Some("c")).collect();
958 /// assert_eq!(find[0].as_str(), "c")
959 /// ```
960 #[inline]
961 pub fn tag_node(mut self: Box<Self>, tag: &'i str) -> ParseResult<Box<Self>> {
962 if self.lookahead != Lookahead::None {
963 return Ok(self);
964 }
965 if let Some(QueueableToken::End { tag: old, .. }) = self.queue.last_mut() {
966 *old = Some(tag)
967 }
968 Ok(self)
969 }
970
971 /// Get number of allowed rules attempts + prohibited rules attempts.
972 fn attempts_at(&self, pos: usize) -> usize {
973 if self.attempt_pos == pos {
974 self.pos_attempts.len() + self.neg_attempts.len()
975 } else {
976 0
977 }
978 }
979
980 fn track(
981 &mut self,
982 rule: R,
983 pos: usize,
984 pos_attempts_index: usize,
985 neg_attempts_index: usize,
986 prev_attempts: usize,
987 ) {
988 if self.atomicity == Atomicity::Atomic {
989 return;
990 }
991
992 // If nested rules made no progress, there is no use to report them; it's only useful to
993 // track the current rule, the exception being when only one attempt has been made during
994 // the children rules.
995 let curr_attempts = self.attempts_at(pos);
996 if curr_attempts > prev_attempts && curr_attempts - prev_attempts == 1 {
997 return;
998 }
999
1000 if pos == self.attempt_pos {
1001 self.pos_attempts.truncate(pos_attempts_index);
1002 self.neg_attempts.truncate(neg_attempts_index);
1003 }
1004
1005 if pos > self.attempt_pos {
1006 self.pos_attempts.clear();
1007 self.neg_attempts.clear();
1008 self.attempt_pos = pos;
1009 }
1010
1011 let attempts = if self.lookahead != Lookahead::Negative {
1012 &mut self.pos_attempts
1013 } else {
1014 &mut self.neg_attempts
1015 };
1016
1017 if pos == self.attempt_pos {
1018 attempts.push(rule);
1019 }
1020 }
1021
1022 /// Starts a sequence of transformations provided by `f` from the `Box<ParserState>`. Returns
1023 /// the same `Result` returned by `f` in the case of an `Ok`, or `Err` with the current
1024 /// `Box<ParserState>` otherwise.
1025 ///
1026 /// This method is useful to parse sequences that only match together which usually come in the
1027 /// form of chained `Result`s with
1028 /// [`Result::and_then`](https://doc.rust-lang.org/std/result/enum.Result.html#method.and_then).
1029 ///
1030 ///
1031 /// # Examples
1032 ///
1033 /// ```
1034 /// # use pest;
1035 /// # #[allow(non_camel_case_types)]
1036 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1037 /// enum Rule {
1038 /// a
1039 /// }
1040 ///
1041 /// let input = "a";
1042 /// let pairs: Vec<_> = pest::state(input, |state| {
1043 /// state.sequence(|s| {
1044 /// s.rule(Rule::a, |s| Ok(s)).and_then(|s| {
1045 /// s.match_string("b")
1046 /// })
1047 /// }).or_else(|s| {
1048 /// Ok(s)
1049 /// })
1050 /// }).unwrap().collect();
1051 ///
1052 /// assert_eq!(pairs.len(), 0);
1053 /// ```
1054 #[inline]
1055 pub fn sequence<F>(mut self: Box<Self>, f: F) -> ParseResult<Box<Self>>
1056 where
1057 F: FnOnce(Box<Self>) -> ParseResult<Box<Self>>,
1058 {
1059 self = self.inc_call_check_limit()?;
1060 let token_index = self.queue.len();
1061 let initial_pos = self.position;
1062
1063 let result = f(self.checkpoint());
1064
1065 match result {
1066 Ok(new_state) => Ok(new_state.checkpoint_ok()),
1067 Err(mut new_state) => {
1068 // Restore the initial position and truncate the token queue.
1069 new_state.position = initial_pos;
1070 new_state.queue.truncate(token_index);
1071 Err(new_state.restore())
1072 }
1073 }
1074 }
1075
1076 /// Repeatedly applies the transformation provided by `f` from the `Box<ParserState>`. Returns
1077 /// `Ok` with the updated `Box<ParserState>` returned by `f` wrapped up in an `Err`.
1078 ///
1079 /// # Examples
1080 ///
1081 /// ```
1082 /// # use pest;
1083 /// # #[allow(non_camel_case_types)]
1084 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1085 /// enum Rule {
1086 /// ab
1087 /// }
1088 ///
1089 /// let input = "aab";
1090 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1091 /// let mut result = state.repeat(|s| {
1092 /// s.match_string("a")
1093 /// });
1094 /// assert!(result.is_ok());
1095 /// assert_eq!(result.unwrap().position().pos(), 2);
1096 ///
1097 /// state = pest::ParserState::new(input);
1098 /// result = state.repeat(|s| {
1099 /// s.match_string("b")
1100 /// });
1101 /// assert!(result.is_ok());
1102 /// assert_eq!(result.unwrap().position().pos(), 0);
1103 /// ```
1104 #[inline]
1105 pub fn repeat<F>(mut self: Box<Self>, mut f: F) -> ParseResult<Box<Self>>
1106 where
1107 F: FnMut(Box<Self>) -> ParseResult<Box<Self>>,
1108 {
1109 self = self.inc_call_check_limit()?;
1110 let mut result = f(self);
1111
1112 loop {
1113 match result {
1114 Ok(state) => result = f(state),
1115 Err(state) if state.call_tracker.limit_reached() => return Err(state),
1116 Err(state) => return Ok(state),
1117 };
1118 }
1119 }
1120
1121 /// Optionally applies the transformation provided by `f` from the `Box<ParserState>`. Returns
1122 /// `Ok` with the updated `Box<ParserState>` returned by `f` regardless of the `Result`.
1123 ///
1124 /// # Examples
1125 ///
1126 /// ```
1127 /// # use pest;
1128 /// # #[allow(non_camel_case_types)]
1129 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1130 /// enum Rule {
1131 /// ab
1132 /// }
1133 ///
1134 /// let input = "ab";
1135 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1136 /// let result = state.optional(|s| {
1137 /// s.match_string("ab")
1138 /// });
1139 /// assert!(result.is_ok());
1140 ///
1141 /// state = pest::ParserState::new(input);
1142 /// let result = state.optional(|s| {
1143 /// s.match_string("ac")
1144 /// });
1145 /// assert!(result.is_ok());
1146 /// ```
1147 #[inline]
1148 pub fn optional<F>(mut self: Box<Self>, f: F) -> ParseResult<Box<Self>>
1149 where
1150 F: FnOnce(Box<Self>) -> ParseResult<Box<Self>>,
1151 {
1152 self = self.inc_call_check_limit()?;
1153 match f(self) {
1154 Err(state) if state.call_tracker.limit_reached() => Err(state),
1155 Ok(state) | Err(state) => Ok(state),
1156 }
1157 }
1158
1159 /// Generic function to handle result of char/string/range parsing
1160 /// in order to track (un)expected tokens.
1161 fn handle_token_parse_result(
1162 &mut self,
1163 start_position: usize,
1164 token: ParsingToken,
1165 parse_succeeded: bool,
1166 ) {
1167 // New position after tracked parsed element for case of `parse_succeeded` is true.
1168 // Position of parsing failure otherwise.
1169 let current_pos = self.position.pos();
1170
1171 if parse_succeeded {
1172 if self.lookahead == Lookahead::Negative {
1173 self.parse_attempts
1174 .try_add_new_token(token, start_position, current_pos, true);
1175 } else if current_pos > self.parse_attempts.max_position {
1176 self.parse_attempts.nullify_expected_tokens(current_pos);
1177 }
1178 } else if self.lookahead != Lookahead::Negative {
1179 self.parse_attempts
1180 .try_add_new_token(token, start_position, current_pos, false);
1181 }
1182 }
1183
1184 /// Attempts to match a single character based on a filter function. Returns `Ok` with the
1185 /// updated `Box<ParserState>` if successful, or `Err` with the updated `Box<ParserState>`
1186 /// otherwise.
1187 ///
1188 /// # Examples
1189 ///
1190 /// ```
1191 /// # use pest;
1192 /// # #[allow(non_camel_case_types)]
1193 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1194 /// enum Rule {}
1195 ///
1196 /// let input = "ab";
1197 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1198 /// let result = state.match_char_by(|c| c.is_ascii());
1199 /// assert!(result.is_ok());
1200 /// assert_eq!(result.unwrap().position().pos(), 1);
1201 ///
1202 /// let input = "❤";
1203 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1204 /// let result = state.match_char_by(|c| c.is_ascii());
1205 /// assert!(result.is_err());
1206 /// assert_eq!(result.unwrap_err().position().pos(), 0);
1207 /// ```
1208 #[inline]
1209 pub fn match_char_by<F>(mut self: Box<Self>, f: F) -> ParseResult<Box<Self>>
1210 where
1211 F: FnOnce(char) -> bool,
1212 {
1213 let start_position = self.position.pos();
1214 let succeeded = self.position.match_char_by(f);
1215 if self.parse_attempts.enabled {
1216 let token = ParsingToken::BuiltInRule;
1217 self.handle_token_parse_result(start_position, token, succeeded);
1218 }
1219 if succeeded { Ok(self) } else { Err(self) }
1220 }
1221
1222 /// Attempts to match the given string. Returns `Ok` with the updated `Box<ParserState>` if
1223 /// successful, or `Err` with the updated `Box<ParserState>` otherwise.
1224 ///
1225 /// # Examples
1226 ///
1227 /// ```
1228 /// # use pest;
1229 /// # #[allow(non_camel_case_types)]
1230 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1231 /// enum Rule {}
1232 ///
1233 /// let input = "ab";
1234 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1235 /// let mut result = state.match_string("ab");
1236 /// assert!(result.is_ok());
1237 /// assert_eq!(result.unwrap().position().pos(), 2);
1238 ///
1239 /// state = pest::ParserState::new(input);
1240 /// result = state.match_string("ac");
1241 /// assert!(result.is_err());
1242 /// assert_eq!(result.unwrap_err().position().pos(), 0);
1243 /// ```
1244 #[inline]
1245 pub fn match_string(mut self: Box<Self>, string: &str) -> ParseResult<Box<Self>> {
1246 let start_position = self.position.pos();
1247 let succeeded = self.position.match_string(string);
1248 if self.parse_attempts.enabled {
1249 let token = ParsingToken::Sensitive {
1250 token: String::from(string),
1251 };
1252 self.handle_token_parse_result(start_position, token, succeeded);
1253 }
1254 if succeeded { Ok(self) } else { Err(self) }
1255 }
1256
1257 /// Pushes the given literal to the stack, and always returns `Ok(Box<ParserState>)`.
1258 ///
1259 /// # Examples
1260 ///
1261 /// ```
1262 /// # use pest;
1263 /// # #[allow(non_camel_case_types)]
1264 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1265 /// enum Rule {}
1266 ///
1267 /// let input = "ab";
1268 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1269 ///
1270 /// let mut result = state.stack_push_literal("a");
1271 /// assert!(result.is_ok());
1272 /// assert_eq!(result.as_ref().unwrap().position().pos(), 0);
1273 ///
1274 /// let mut result = result.unwrap().stack_pop();
1275 /// assert!(result.is_ok());
1276 /// assert_eq!(result.unwrap().position().pos(), 1);
1277 /// ```
1278 #[inline]
1279 pub fn stack_push_literal(
1280 mut self: Box<Self>,
1281 string: impl Into<Cow<'static, str>>,
1282 ) -> ParseResult<Box<Self>> {
1283 // convert string into a Literal, and then into a BorrowedOrRc
1284 self.stack
1285 .push(SpanOrLiteral::Literal(string.into().into()));
1286 Ok(self)
1287 }
1288
1289 /// Attempts to case-insensitively match the given string. Returns `Ok` with the updated
1290 /// `Box<ParserState>` if successful, or `Err` with the updated `Box<ParserState>` otherwise.
1291 ///
1292 /// # Examples
1293 ///
1294 /// ```
1295 /// # use pest;
1296 /// # #[allow(non_camel_case_types)]
1297 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1298 /// enum Rule {}
1299 ///
1300 /// let input = "ab";
1301 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1302 /// let mut result = state.match_insensitive("AB");
1303 /// assert!(result.is_ok());
1304 /// assert_eq!(result.unwrap().position().pos(), 2);
1305 ///
1306 /// state = pest::ParserState::new(input);
1307 /// result = state.match_insensitive("AC");
1308 /// assert!(result.is_err());
1309 /// assert_eq!(result.unwrap_err().position().pos(), 0);
1310 /// ```
1311 #[inline]
1312 pub fn match_insensitive(mut self: Box<Self>, string: &str) -> ParseResult<Box<Self>> {
1313 let start_position: usize = self.position().pos();
1314 let succeeded = self.position.match_insensitive(string);
1315 if self.parse_attempts.enabled {
1316 let token = ParsingToken::Insensitive {
1317 token: String::from(string),
1318 };
1319 self.handle_token_parse_result(start_position, token, succeeded);
1320 }
1321 if succeeded { Ok(self) } else { Err(self) }
1322 }
1323
1324 /// Attempts to match a single character from the given range. Returns `Ok` with the updated
1325 /// `Box<ParserState>` if successful, or `Err` with the updated `Box<ParserState>` otherwise.
1326 ///
1327 /// # Caution
1328 /// The provided `range` is interpreted as inclusive.
1329 ///
1330 /// # Examples
1331 ///
1332 /// ```
1333 /// # use pest;
1334 /// # #[allow(non_camel_case_types)]
1335 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1336 /// enum Rule {}
1337 ///
1338 /// let input = "ab";
1339 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1340 /// let mut result = state.match_range('a'..'z');
1341 /// assert!(result.is_ok());
1342 /// assert_eq!(result.unwrap().position().pos(), 1);
1343 ///
1344 /// state = pest::ParserState::new(input);
1345 /// result = state.match_range('A'..'Z');
1346 /// assert!(result.is_err());
1347 /// assert_eq!(result.unwrap_err().position().pos(), 0);
1348 /// ```
1349 #[inline]
1350 pub fn match_range(mut self: Box<Self>, range: Range<char>) -> ParseResult<Box<Self>> {
1351 let start_position = self.position().pos();
1352 let token = ParsingToken::Range {
1353 start: range.start,
1354 end: range.end,
1355 };
1356 let succeeded = self.position.match_range(range);
1357 if self.parse_attempts.enabled {
1358 self.handle_token_parse_result(start_position, token, succeeded);
1359 }
1360 if succeeded { Ok(self) } else { Err(self) }
1361 }
1362
1363 /// Attempts to skip `n` characters forward. Returns `Ok` with the updated `Box<ParserState>`
1364 /// if successful, or `Err` with the updated `Box<ParserState>` otherwise.
1365 ///
1366 /// # Examples
1367 ///
1368 /// ```
1369 /// # use pest;
1370 /// # #[allow(non_camel_case_types)]
1371 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1372 /// enum Rule {}
1373 ///
1374 /// let input = "ab";
1375 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1376 /// let mut result = state.skip(1);
1377 /// assert!(result.is_ok());
1378 /// assert_eq!(result.unwrap().position().pos(), 1);
1379 ///
1380 /// state = pest::ParserState::new(input);
1381 /// result = state.skip(3);
1382 /// assert!(result.is_err());
1383 /// assert_eq!(result.unwrap_err().position().pos(), 0);
1384 /// ```
1385 #[inline]
1386 pub fn skip(mut self: Box<Self>, n: usize) -> ParseResult<Box<Self>> {
1387 if self.position.skip(n) {
1388 Ok(self)
1389 } else {
1390 Err(self)
1391 }
1392 }
1393
1394 /// Attempts to skip forward until one of the given strings is found. Returns `Ok` with the
1395 /// updated `Box<ParserState>` whether or not one of the strings is found.
1396 ///
1397 /// # Examples
1398 ///
1399 /// ```
1400 /// # use pest;
1401 /// # #[allow(non_camel_case_types)]
1402 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1403 /// enum Rule {}
1404 ///
1405 /// let input = "abcd";
1406 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1407 /// let mut result = state.skip_until(&["c", "d"]);
1408 /// assert!(result.is_ok());
1409 /// assert_eq!(result.unwrap().position().pos(), 2);
1410 /// ```
1411 #[inline]
1412 pub fn skip_until(mut self: Box<Self>, strings: &[&str]) -> ParseResult<Box<Self>> {
1413 self.position.skip_until(strings);
1414 Ok(self)
1415 }
1416
1417 /// Attempts to match the start of the input. Returns `Ok` with the current `Box<ParserState>`
1418 /// if the parser has not yet advanced, or `Err` with the current `Box<ParserState>` otherwise.
1419 ///
1420 /// # Examples
1421 ///
1422 /// ```
1423 /// # use pest;
1424 /// # #[allow(non_camel_case_types)]
1425 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1426 /// enum Rule {}
1427 ///
1428 /// let input = "ab";
1429 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1430 /// let mut result = state.start_of_input();
1431 /// assert!(result.is_ok());
1432 ///
1433 /// state = pest::ParserState::new(input);
1434 /// state = state.match_string("ab").unwrap();
1435 /// result = state.start_of_input();
1436 /// assert!(result.is_err());
1437 /// ```
1438 #[inline]
1439 pub fn start_of_input(self: Box<Self>) -> ParseResult<Box<Self>> {
1440 if self.position.at_start() {
1441 Ok(self)
1442 } else {
1443 Err(self)
1444 }
1445 }
1446
1447 /// Attempts to match the end of the input. Returns `Ok` with the current `Box<ParserState>` if
1448 /// there is no input remaining, or `Err` with the current `Box<ParserState>` otherwise.
1449 ///
1450 /// # Examples
1451 ///
1452 /// ```
1453 /// # use pest;
1454 /// # #[allow(non_camel_case_types)]
1455 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1456 /// enum Rule {}
1457 ///
1458 /// let input = "ab";
1459 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1460 /// let mut result = state.end_of_input();
1461 /// assert!(result.is_err());
1462 ///
1463 /// state = pest::ParserState::new(input);
1464 /// state = state.match_string("ab").unwrap();
1465 /// result = state.end_of_input();
1466 /// assert!(result.is_ok());
1467 /// ```
1468 #[inline]
1469 pub fn end_of_input(self: Box<Self>) -> ParseResult<Box<Self>> {
1470 if self.position.at_end() {
1471 Ok(self)
1472 } else {
1473 Err(self)
1474 }
1475 }
1476
1477 /// Starts a lookahead transformation provided by `f` from the `Box<ParserState>`. It returns
1478 /// `Ok` with the current `Box<ParserState>` if `f` also returns an `Ok`, or `Err` with the current
1479 /// `Box<ParserState>` otherwise. If `is_positive` is `false`, it swaps the `Ok` and `Err`
1480 /// together, negating the `Result`.
1481 ///
1482 /// # Examples
1483 ///
1484 /// ```
1485 /// # use pest;
1486 /// # #[allow(non_camel_case_types)]
1487 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1488 /// enum Rule {
1489 /// a
1490 /// }
1491 ///
1492 /// let input = "a";
1493 /// let pairs: Vec<_> = pest::state(input, |state| {
1494 /// state.lookahead(true, |state| {
1495 /// state.rule(Rule::a, |s| Ok(s))
1496 /// })
1497 /// }).unwrap().collect();
1498 ///
1499 /// assert_eq!(pairs.len(), 0);
1500 /// ```
1501 #[inline]
1502 pub fn lookahead<F>(mut self: Box<Self>, is_positive: bool, f: F) -> ParseResult<Box<Self>>
1503 where
1504 F: FnOnce(Box<Self>) -> ParseResult<Box<Self>>,
1505 {
1506 self = self.inc_call_check_limit()?;
1507 let initial_lookahead = self.lookahead;
1508
1509 self.lookahead = if is_positive {
1510 match initial_lookahead {
1511 Lookahead::None | Lookahead::Positive => Lookahead::Positive,
1512 Lookahead::Negative => Lookahead::Negative,
1513 }
1514 } else {
1515 match initial_lookahead {
1516 Lookahead::None | Lookahead::Positive => Lookahead::Negative,
1517 Lookahead::Negative => Lookahead::Positive,
1518 }
1519 };
1520
1521 let initial_pos = self.position;
1522
1523 let result = f(self.checkpoint());
1524
1525 let result_state = match result {
1526 Ok(mut new_state) => {
1527 new_state.position = initial_pos;
1528 new_state.lookahead = initial_lookahead;
1529 Ok(new_state.restore())
1530 }
1531 Err(mut new_state) => {
1532 new_state.position = initial_pos;
1533 new_state.lookahead = initial_lookahead;
1534 Err(new_state.restore())
1535 }
1536 };
1537
1538 let exhausted = match &result_state {
1539 Ok(state) | Err(state) => state.call_tracker.limit_reached(),
1540 };
1541 if exhausted {
1542 return Err(result_state.unwrap_or_else(|state| state));
1543 }
1544 if is_positive {
1545 result_state
1546 } else {
1547 match result_state {
1548 Ok(state) => Err(state),
1549 Err(state) => Ok(state),
1550 }
1551 }
1552 }
1553
1554 /// Transformation which stops `Token`s from being generated according to `is_atomic`.
1555 /// Used as wrapper over `rule` (or even another `atomic`) call.
1556 ///
1557 /// # Examples
1558 ///
1559 /// ```
1560 /// # use pest::{self, Atomicity};
1561 /// # #[allow(non_camel_case_types)]
1562 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1563 /// enum Rule {
1564 /// a
1565 /// }
1566 ///
1567 /// let input = "a";
1568 /// let pairs: Vec<_> = pest::state(input, |state| {
1569 /// state.atomic(Atomicity::Atomic, |s| {
1570 /// s.rule(Rule::a, |s| Ok(s))
1571 /// })
1572 /// }).unwrap().collect();
1573 ///
1574 /// assert_eq!(pairs.len(), 0);
1575 /// ```
1576 #[inline]
1577 pub fn atomic<F>(mut self: Box<Self>, atomicity: Atomicity, f: F) -> ParseResult<Box<Self>>
1578 where
1579 F: FnOnce(Box<Self>) -> ParseResult<Box<Self>>,
1580 {
1581 self = self.inc_call_check_limit()?;
1582 // In case child parsing call is another `atomic` it will have its own atomicity status.
1583 let initial_atomicity = self.atomicity;
1584 // In case child atomicity is the same as we've demanded, we shouldn't do nothing.
1585 // E.g. we have the following rules:
1586 // * RootRule = @{ InnerRule }
1587 // * InnerRule = @{ ... }
1588 let should_toggle = self.atomicity != atomicity;
1589
1590 // Note that we take atomicity of the top rule and not of the leaf (inner).
1591 if should_toggle {
1592 self.atomicity = atomicity;
1593 }
1594
1595 let result = f(self);
1596
1597 match result {
1598 Ok(mut new_state) => {
1599 if should_toggle {
1600 new_state.atomicity = initial_atomicity;
1601 }
1602 Ok(new_state)
1603 }
1604 Err(mut new_state) => {
1605 if should_toggle {
1606 new_state.atomicity = initial_atomicity;
1607 }
1608 Err(new_state)
1609 }
1610 }
1611 }
1612
1613 /// Evaluates the result of closure `f` and pushes the span of the input consumed from before
1614 /// `f` is called to after `f` is called to the stack. Returns `Ok(Box<ParserState>)` if `f` is
1615 /// called successfully, or `Err(Box<ParserState>)` otherwise.
1616 ///
1617 /// # Examples
1618 ///
1619 /// ```
1620 /// # use pest;
1621 /// # #[allow(non_camel_case_types)]
1622 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1623 /// enum Rule {}
1624 ///
1625 /// let input = "ab";
1626 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1627 /// let mut result = state.stack_push(|state| state.match_string("a"));
1628 /// assert!(result.is_ok());
1629 /// assert_eq!(result.unwrap().position().pos(), 1);
1630 /// ```
1631 #[inline]
1632 pub fn stack_push<F>(mut self: Box<Self>, f: F) -> ParseResult<Box<Self>>
1633 where
1634 F: FnOnce(Box<Self>) -> ParseResult<Box<Self>>,
1635 {
1636 self = self.inc_call_check_limit()?;
1637 let start = self.position;
1638
1639 let result = f(self);
1640
1641 match result {
1642 Ok(mut state) => {
1643 let end = state.position;
1644 state.stack.push(SpanOrLiteral::Span(start.span(&end)));
1645 Ok(state)
1646 }
1647 Err(state) => Err(state),
1648 }
1649 }
1650
1651 /// Peeks the top of the stack and attempts to match the string. Returns `Ok(Box<ParserState>)`
1652 /// if the string is matched successfully, or `Err(Box<ParserState>)` otherwise.
1653 ///
1654 /// # Panics
1655 ///
1656 /// Panics if the stack is empty.
1657 ///
1658 /// # Examples
1659 ///
1660 /// ```
1661 /// # use pest;
1662 /// # #[allow(non_camel_case_types)]
1663 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1664 /// enum Rule {}
1665 ///
1666 /// let input = "aa";
1667 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1668 /// let mut result = state.stack_push(|state| state.match_string("a")).and_then(
1669 /// |state| state.stack_peek()
1670 /// );
1671 /// assert!(result.is_ok());
1672 /// assert_eq!(result.unwrap().position().pos(), 2);
1673 /// ```
1674 #[inline]
1675 pub fn stack_peek(self: Box<Self>) -> ParseResult<Box<Self>> {
1676 let string = self
1677 .stack
1678 .peek()
1679 .expect("peek was called on empty stack")
1680 .as_borrowed_or_rc();
1681 self.match_string(string.as_str())
1682 }
1683
1684 /// Pops the top of the stack and attempts to match the string. Returns `Ok(Box<ParserState>)`
1685 /// if the string is matched successfully, or `Err(Box<ParserState>)` otherwise.
1686 ///
1687 /// # Panics
1688 ///
1689 /// Panics if the stack is empty.
1690 ///
1691 /// # Examples
1692 ///
1693 /// ```
1694 /// # use pest;
1695 /// # #[allow(non_camel_case_types)]
1696 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1697 /// enum Rule {}
1698 ///
1699 /// let input = "aa";
1700 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1701 /// let mut result = state.stack_push(|state| state.match_string("a")).and_then(
1702 /// |state| state.stack_pop()
1703 /// );
1704 /// assert!(result.is_ok());
1705 /// assert_eq!(result.unwrap().position().pos(), 2);
1706 /// ```
1707 #[inline]
1708 pub fn stack_pop(mut self: Box<Self>) -> ParseResult<Box<Self>> {
1709 let string = self
1710 .stack
1711 .pop()
1712 .expect("pop was called on empty stack")
1713 .as_borrowed_or_rc();
1714 self.match_string(string.as_str())
1715 }
1716
1717 /// Matches part of the state of the stack.
1718 ///
1719 /// # Examples
1720 ///
1721 /// ```
1722 /// # use pest::{self, MatchDir};
1723 /// # #[allow(non_camel_case_types)]
1724 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1725 /// enum Rule {}
1726 ///
1727 /// let input = "abcd cd cb";
1728 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1729 /// let mut result = state
1730 /// .stack_push(|state| state.match_string("a"))
1731 /// .and_then(|state| state.stack_push(|state| state.match_string("b")))
1732 /// .and_then(|state| state.stack_push(|state| state.match_string("c")))
1733 /// .and_then(|state| state.stack_push(|state| state.match_string("d")))
1734 /// .and_then(|state| state.match_string(" "))
1735 /// .and_then(|state| state.stack_match_peek_slice(2, None, MatchDir::BottomToTop))
1736 /// .and_then(|state| state.match_string(" "))
1737 /// .and_then(|state| state.stack_match_peek_slice(1, Some(-1), MatchDir::TopToBottom));
1738 /// assert!(result.is_ok());
1739 /// assert_eq!(result.unwrap().position().pos(), 10);
1740 /// ```
1741 #[inline]
1742 pub fn stack_match_peek_slice(
1743 mut self: Box<Self>,
1744 start: i32,
1745 end: Option<i32>,
1746 match_dir: MatchDir,
1747 ) -> ParseResult<Box<Self>> {
1748 let range = match constrain_idxs(start, end, self.stack.len()) {
1749 Some(r) => r,
1750 None => return Err(self),
1751 };
1752 // return true if an empty sequence is requested
1753 if range.end <= range.start {
1754 return Ok(self);
1755 }
1756
1757 let mut position = self.position;
1758 let result = {
1759 let mut iter_b2t = self.stack[range].iter();
1760 let matcher =
1761 |span: &SpanOrLiteral<'_>| position.match_string(span.as_borrowed_or_rc().as_str());
1762 match match_dir {
1763 MatchDir::BottomToTop => iter_b2t.all(matcher),
1764 MatchDir::TopToBottom => iter_b2t.rev().all(matcher),
1765 }
1766 };
1767 if result {
1768 self.position = position;
1769 Ok(self)
1770 } else {
1771 Err(self)
1772 }
1773 }
1774
1775 /// Matches the full state of the stack.
1776 ///
1777 /// # Examples
1778 ///
1779 /// ```
1780 /// # use pest;
1781 /// # #[allow(non_camel_case_types)]
1782 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1783 /// enum Rule {}
1784 ///
1785 /// let input = "abba";
1786 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1787 /// let mut result = state
1788 /// .stack_push(|state| state.match_string("a"))
1789 /// .and_then(|state| { state.stack_push(|state| state.match_string("b")) })
1790 /// .and_then(|state| state.stack_match_peek());
1791 /// assert!(result.is_ok());
1792 /// assert_eq!(result.unwrap().position().pos(), 4);
1793 /// ```
1794 #[inline]
1795 pub fn stack_match_peek(self: Box<Self>) -> ParseResult<Box<Self>> {
1796 self.stack_match_peek_slice(0, None, MatchDir::TopToBottom)
1797 }
1798
1799 /// Matches the full state of the stack. This method will clear the stack as it evaluates.
1800 ///
1801 /// # Examples
1802 ///
1803 /// ```
1804 /// /// # use pest;
1805 /// # #[allow(non_camel_case_types)]
1806 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1807 /// enum Rule {}
1808 ///
1809 /// let input = "aaaa";
1810 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1811 /// let mut result = state.stack_push(|state| state.match_string("a")).and_then(|state| {
1812 /// state.stack_push(|state| state.match_string("a"))
1813 /// }).and_then(|state| state.stack_match_peek());
1814 /// assert!(result.is_ok());
1815 /// assert_eq!(result.unwrap().position().pos(), 4);
1816 /// ```
1817 #[inline]
1818 pub fn stack_match_pop(mut self: Box<Self>) -> ParseResult<Box<Self>> {
1819 let mut position = self.position;
1820 let mut result = true;
1821 while let Some(span) = self.stack.pop() {
1822 result = position.match_string(span.as_borrowed_or_rc().as_str());
1823 if !result {
1824 break;
1825 }
1826 }
1827
1828 if result {
1829 self.position = position;
1830 Ok(self)
1831 } else {
1832 Err(self)
1833 }
1834 }
1835
1836 /// Drops the top of the stack. Returns `Ok(Box<ParserState>)` if there was a value to drop, or
1837 /// `Err(Box<ParserState>)` otherwise.
1838 ///
1839 /// # Examples
1840 ///
1841 /// ```
1842 /// # use pest;
1843 /// # #[allow(non_camel_case_types)]
1844 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1845 /// enum Rule {}
1846 ///
1847 /// let input = "aa";
1848 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1849 /// let mut result = state.stack_push(|state| state.match_string("a")).and_then(
1850 /// |state| state.stack_drop()
1851 /// );
1852 /// assert!(result.is_ok());
1853 /// assert_eq!(result.unwrap().position().pos(), 1);
1854 /// ```
1855 #[inline]
1856 pub fn stack_drop(mut self: Box<Self>) -> ParseResult<Box<Self>> {
1857 match self.stack.pop() {
1858 Some(_) => Ok(self),
1859 None => Err(self),
1860 }
1861 }
1862
1863 /// Restores the original state of the `ParserState` when `f` returns an `Err`. Currently,
1864 /// this method only restores the stack.
1865 ///
1866 /// # Examples
1867 ///
1868 /// ```
1869 /// # use pest;
1870 /// # #[allow(non_camel_case_types)]
1871 /// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1872 /// enum Rule {}
1873 ///
1874 /// let input = "ab";
1875 /// let mut state: Box<pest::ParserState<'_, Rule>> = pest::ParserState::new(input);
1876 /// let mut result = state.restore_on_err(|state| state.stack_push(|state|
1877 /// state.match_string("a")).and_then(|state| state.match_string("a"))
1878 /// );
1879 ///
1880 /// assert!(result.is_err());
1881 ///
1882 /// // Since the the rule doesn't match, the "a" pushed to the stack will be removed.
1883 /// let catch_panic = std::panic::catch_unwind(|| result.unwrap_err().stack_pop());
1884 /// assert!(catch_panic.is_err());
1885 /// ```
1886 #[inline]
1887 pub fn restore_on_err<F>(mut self: Box<Self>, f: F) -> ParseResult<Box<Self>>
1888 where
1889 F: FnOnce(Box<Self>) -> ParseResult<Box<Self>>,
1890 {
1891 self = self.check_stack_limit()?;
1892 match f(self.checkpoint()) {
1893 Ok(state) => Ok(state.checkpoint_ok()),
1894 Err(state) => Err(state.restore()),
1895 }
1896 }
1897
1898 // Mark the current state as a checkpoint and return the `Box`.
1899 #[inline]
1900 pub(crate) fn checkpoint(mut self: Box<Self>) -> Box<Self> {
1901 self.stack.snapshot();
1902 self
1903 }
1904
1905 // The checkpoint was cleared successfully
1906 // so remove it without touching other stack state.
1907 #[inline]
1908 pub(crate) fn checkpoint_ok(mut self: Box<Self>) -> Box<Self> {
1909 self.stack.clear_snapshot();
1910 self
1911 }
1912
1913 // Restore the current state to the most recent checkpoint.
1914 #[inline]
1915 pub(crate) fn restore(mut self: Box<Self>) -> Box<Self> {
1916 self.stack.restore();
1917 self
1918 }
1919}
1920
1921/// Helper function used only in case stack operations (PUSH/POP) are used in grammar.
1922fn constrain_idxs(start: i32, end: Option<i32>, len: usize) -> Option<Range<usize>> {
1923 let start_norm = normalize_index(start, len)?;
1924 let end_norm = end.map_or(Some(len), |e| normalize_index(e, len))?;
1925 Some(start_norm..end_norm)
1926}
1927
1928/// `constrain_idxs` helper function.
1929/// Normalizes the index using its sequence’s length.
1930/// Returns `None` if the normalized index is OOB.
1931fn normalize_index(i: i32, len: usize) -> Option<usize> {
1932 if i > len as i32 {
1933 None
1934 } else if i >= 0 {
1935 Some(i as usize)
1936 } else {
1937 let real_i = len as i32 + i;
1938 if real_i >= 0 {
1939 Some(real_i as usize)
1940 } else {
1941 None
1942 }
1943 }
1944}
1945
1946#[cfg(test)]
1947mod test {
1948 use super::*;
1949
1950 type TestState = Box<ParserState<'static, ()>>;
1951 type TestResult = ParseResult<TestState>;
1952 type Combinator = fn(TestState, fn(TestState) -> TestResult) -> TestResult;
1953
1954 const COMBINATORS: [(&str, Combinator); 9] = [
1955 ("rule", |state, inner| state.rule((), inner)),
1956 ("sequence", ParserState::sequence),
1957 ("repeat", ParserState::repeat),
1958 ("optional", ParserState::optional),
1959 ("positive lookahead", |state, inner| {
1960 state.lookahead(true, inner)
1961 }),
1962 ("negative lookahead", |state, inner| {
1963 state.lookahead(false, inner)
1964 }),
1965 ("atomic", |state, inner| {
1966 state.atomic(Atomicity::Atomic, inner)
1967 }),
1968 ("stack_push", ParserState::stack_push),
1969 ("restore_on_err", ParserState::restore_on_err),
1970 ];
1971
1972 fn tracker_at_calls(calls: usize, limit: usize) -> CallLimitTracker {
1973 CallLimitTracker {
1974 current_call_limit: Some((calls, limit)),
1975 limit_reached: None,
1976 entries_before_stack_probe: 0,
1977 }
1978 }
1979
1980 #[test]
1981 fn stack_limit_probe_boundary_and_unknown_bounds() {
1982 for stack_space in [
1983 None,
1984 Some(REQUIRED_STACK_SPACE),
1985 Some(REQUIRED_STACK_SPACE - 1),
1986 ] {
1987 let mut tracker = tracker_at_calls(0, 10);
1988 let allowed = stack_space != Some(REQUIRED_STACK_SPACE - 1);
1989 assert_eq!(tracker.enter_with_stack(true, stack_space), allowed);
1990 assert_eq!(tracker.current_call_limit, Some((usize::from(allowed), 10)));
1991 if !allowed {
1992 assert_eq!(tracker.error_message(), Some("stack limit reached"));
1993 assert!(!tracker.enter_with_stack(true, None));
1994 for count_call in [false, true] {
1995 assert!(!tracker.enter(count_call));
1996 }
1997 assert_eq!(tracker.current_call_limit, Some((0, 10)));
1998 }
1999 }
2000 }
2001
2002 #[test]
2003 fn stack_measurement_covers_entries_that_keep_the_reserve() {
2004 assert_eq!(entries_covered_by(None), MAX_ENTRIES_PER_STACK_PROBE);
2005 for (reserves, covered) in [
2006 (1, 0),
2007 (2, 1),
2008 (3, 2),
2009 (MAX_ENTRIES_PER_STACK_PROBE + 1, MAX_ENTRIES_PER_STACK_PROBE),
2010 (MAX_ENTRIES_PER_STACK_PROBE + 2, MAX_ENTRIES_PER_STACK_PROBE),
2011 ] {
2012 for partial_reserve in [0, REQUIRED_STACK_SPACE - 1] {
2013 let remaining = reserves * REQUIRED_STACK_SPACE + partial_reserve;
2014 assert_eq!(entries_covered_by(Some(remaining)), covered, "{remaining}");
2015 }
2016 }
2017 assert_eq!(
2018 entries_covered_by(Some(usize::MAX)),
2019 MAX_ENTRIES_PER_STACK_PROBE
2020 );
2021 }
2022
2023 #[test]
2024 fn stack_measurement_is_reused_for_covered_entries() {
2025 for count_call in [false, true] {
2026 let mut tracker = tracker_at_calls(0, 10);
2027 assert!(tracker.enter_with_stack(count_call, Some(3 * REQUIRED_STACK_SPACE)));
2028 for covered in [1, 0] {
2029 assert!(tracker.enter(count_call));
2030 assert_eq!(tracker.entries_before_stack_probe, covered);
2031 }
2032 assert_eq!(
2033 tracker.current_call_limit,
2034 Some((3 * usize::from(count_call), 10))
2035 );
2036 assert!(!tracker.limit_reached());
2037 }
2038 }
2039
2040 #[test]
2041 fn call_limit_applies_to_covered_entries() {
2042 let mut tracker = tracker_at_calls(1, 2);
2043 assert!(tracker.enter_with_stack(true, None));
2044 assert_eq!(
2045 tracker.entries_before_stack_probe,
2046 MAX_ENTRIES_PER_STACK_PROBE
2047 );
2048 assert!(tracker.enter(false));
2049 assert!(!tracker.limit_reached());
2050 assert!(!tracker.enter(true));
2051 assert_eq!(tracker.error_message(), Some("call limit reached"));
2052 assert_eq!(tracker.entries_before_stack_probe, 0);
2053 for count_call in [false, true] {
2054 assert!(!tracker.enter(count_call));
2055 }
2056 assert_eq!(tracker.current_call_limit, Some((2, 2)));
2057 }
2058
2059 #[test]
2060 fn call_limit_counts_shallow_work() {
2061 let result = state::<(), _>("xxxxxxxxxxxxxxxx", |mut state| {
2062 state.call_tracker = tracker_at_calls(0, 3);
2063 state.repeat(|state| state.sequence(|state| state.match_string("x")))
2064 });
2065 assert_eq!(
2066 result.unwrap_err().variant,
2067 ErrorVariant::CustomError {
2068 message: "call limit reached".to_owned()
2069 }
2070 );
2071 }
2072
2073 #[test]
2074 fn call_limit_preserves_combinator_charges() {
2075 for (name, combinator) in COMBINATORS {
2076 for input in ["x", "y"] {
2077 for initial_calls in [0, 2] {
2078 let mut state = ParserState::new(input);
2079 state.call_tracker = tracker_at_calls(initial_calls, 10);
2080 let result = combinator(state, |state| state.match_string("x"));
2081 let should_succeed = match name {
2082 "repeat" | "optional" => true,
2083 "negative lookahead" => input != "x",
2084 _ => input == "x",
2085 };
2086 assert_eq!(result.is_ok(), should_succeed, "{name}");
2087 let state = result.unwrap_or_else(|state| state);
2088 assert_eq!(
2089 state.call_tracker.current_call_limit,
2090 Some((initial_calls + usize::from(name != "restore_on_err"), 10)),
2091 "{name} on {input:?}"
2092 );
2093 assert!(!state.call_tracker.limit_reached(), "{name}");
2094 assert_eq!(state.lookahead, Lookahead::None, "{name}");
2095 assert_eq!(state.atomicity, Atomicity::NonAtomic, "{name}");
2096 }
2097 }
2098 }
2099 }
2100
2101 #[test]
2102 fn call_limit_boundary() {
2103 for (name, combinator) in COMBINATORS {
2104 if name == "restore_on_err" {
2105 continue;
2106 }
2107 for initial_calls in [0, 2] {
2108 for remaining in [1, 2] {
2109 let limit = initial_calls + remaining;
2110 let mut state = ParserState::new("x");
2111 state.call_tracker = tracker_at_calls(initial_calls, limit);
2112 let result = combinator(state, |state| {
2113 state.rule((), |state| state.match_string("x"))
2114 });
2115 let state = result.unwrap_or_else(|state| state);
2116 assert_eq!(
2117 state.call_tracker.current_call_limit,
2118 Some((limit, limit)),
2119 "{name}"
2120 );
2121 let exhausted = remaining == 1 || name == "repeat";
2122 assert_eq!(state.call_tracker.limit_reached(), exhausted, "{name}");
2123 if exhausted {
2124 let state = combinator(state, |_| {
2125 panic!("exhausted state must not reenter a helper")
2126 })
2127 .unwrap_err();
2128 assert_eq!(
2129 state.call_tracker.current_call_limit,
2130 Some((limit, limit)),
2131 "{name}"
2132 );
2133 }
2134 }
2135 }
2136 }
2137 }
2138
2139 #[test]
2140 fn call_limit_restore_on_err_checkpoints() {
2141 for limit in [1, 2] {
2142 for succeeds in [false, true] {
2143 let mut state = ParserState::<()>::new("xy");
2144 state.call_tracker = tracker_at_calls(0, limit);
2145 state
2146 .stack
2147 .push(SpanOrLiteral::Span(Span::new("xy", 0, 1).unwrap()));
2148 let state = state.checkpoint();
2149 let result = state.restore_on_err(|mut state| {
2150 state.stack.pop();
2151 state.restore_on_err(|state| {
2152 state.sequence(|mut state| {
2153 state
2154 .stack
2155 .push(SpanOrLiteral::Span(Span::new("xy", 1, 2).unwrap()));
2156 let state = state.match_string("x").unwrap();
2157 if succeeds { Ok(state) } else { Err(state) }
2158 })
2159 })
2160 });
2161 assert_eq!(result.is_ok(), succeeds);
2162 let state = result.unwrap_or_else(|state| state);
2163 assert_eq!(state.call_tracker.current_call_limit, Some((1, limit)));
2164 assert!(!state.call_tracker.limit_reached());
2165 assert_eq!(state.position.pos(), usize::from(succeeds));
2166 let top = state.stack.peek().unwrap().as_borrowed_or_rc();
2167 assert_eq!(top.as_str(), if succeeds { "y" } else { "x" });
2168 let state = state.restore();
2169 assert_eq!(state.stack.len(), 1);
2170 assert_eq!(
2171 state.stack.peek().unwrap().as_borrowed_or_rc().as_str(),
2172 "x"
2173 );
2174 }
2175 }
2176 }
2177
2178 #[test]
2179 fn call_limit_accumulates_on_backtracking() {
2180 let input = "xxxxxxxxxxxxxxxx";
2181 let mut state = ParserState::<()>::new(input);
2182 state.call_tracker = tracker_at_calls(0, 100);
2183 let state = state
2184 .repeat(|state| {
2185 state
2186 .sequence(|state| state.match_string("y"))
2187 .or_else(|state| state.sequence(|state| state.match_string("x")))
2188 })
2189 .unwrap();
2190 assert_eq!(state.position.pos(), input.len());
2191 assert_eq!(state.call_tracker.current_call_limit, Some((35, 100)));
2192 assert!(!state.call_tracker.limit_reached());
2193 }
2194
2195 #[test]
2196 fn call_limit_cannot_be_swallowed() {
2197 for (name, combinator) in COMBINATORS {
2198 for error_detail in [false, true] {
2199 let result = state::<(), _>("", |mut state| {
2200 state.call_tracker = tracker_at_calls(0, 1);
2201 state.parse_attempts.enabled = error_detail;
2202 combinator(state, |state| {
2203 state.rule((), |state| {
2204 state.rule((), |_| panic!("over-limit closure must not run"))
2205 })
2206 })
2207 .or_else(Ok)
2208 });
2209 assert_eq!(
2210 result.expect_err(name).variant,
2211 ErrorVariant::CustomError {
2212 message: "call limit reached".to_owned(),
2213 },
2214 "{name}, error_detail={error_detail}"
2215 );
2216 }
2217 }
2218 }
2219
2220 #[test]
2221 fn call_limit_stops_recovering_combinator_continuations() {
2222 for (name, combinator) in COMBINATORS {
2223 if !matches!(name, "optional" | "repeat" | "negative lookahead") {
2224 continue;
2225 }
2226 let mut state = ParserState::new("");
2227 state.call_tracker = tracker_at_calls(0, 1);
2228 let result: TestResult = combinator(state, |state| {
2229 state.rule((), |_| panic!("over-budget body must not run"))
2230 })
2231 .map(|_| panic!("fatal resource rejection must stop continuations"));
2232 assert!(result.is_err(), "{name}");
2233 }
2234 }
2235
2236 #[test]
2237 fn normalize_index_pos() {
2238 assert_eq!(normalize_index(4, 6), Some(4));
2239 assert_eq!(normalize_index(5, 5), Some(5));
2240 assert_eq!(normalize_index(6, 3), None);
2241 }
2242
2243 #[test]
2244 fn normalize_index_neg() {
2245 assert_eq!(normalize_index(-4, 6), Some(2));
2246 assert_eq!(normalize_index(-5, 5), Some(0));
2247 assert_eq!(normalize_index(-6, 3), None);
2248 }
2249}