-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathlib.rs
3552 lines (3353 loc) · 119 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![cfg_attr(not(any(doc, feature = "std", test)), no_std)]
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg), deny(rustdoc::all))]
#![cfg_attr(feature = "nightly", allow(internal_features))]
#![cfg_attr(
feature = "nightly",
feature(never_type, rustc_attrs, fn_traits, tuple_trait, unboxed_closures)
)]
//
// README.md links these files via the main branch. For docs.rs we however want to link them
// to the version of the documented crate since the files in the main branch may diverge.
#![doc = concat!("[`examples/brainfuck.rs`]: ", blob_url_prefix!(), "/examples/brainfuck.rs")]
#![doc = concat!("[JSON parser]: ", blob_url_prefix!(), "/examples/json.rs")]
#![doc = concat!("[examples/nano_rust.rs]: ", blob_url_prefix!(), "/examples/nano_rust.rs")]
#![doc = concat!("[tutorial]: ", blob_url_prefix!(), "/tutorial.md")]
//
#![doc = include_str!("../README.md")]
#![deny(missing_docs, clippy::undocumented_unsafe_blocks)]
#![allow(
clippy::should_implement_trait,
clippy::type_complexity,
clippy::result_unit_err
)]
// TODO: Talk about `.map` and purity assumptions
extern crate alloc;
extern crate core;
macro_rules! blob_url_prefix {
() => {
concat!(
"https://github.com/zesterer/chumsky/blob/",
env!("VERGEN_GIT_SHA")
)
};
}
macro_rules! go_extra {
( $O :ty ) => {
#[inline(always)]
fn go_emit(&self, inp: &mut InputRef<'a, '_, I, E>) -> PResult<Emit, $O> {
ParserSealed::<I, $O, E>::go::<Emit>(self, inp)
}
#[inline(always)]
fn go_check(&self, inp: &mut InputRef<'a, '_, I, E>) -> PResult<Check, $O> {
ParserSealed::<I, $O, E>::go::<Check>(self, inp)
}
};
}
macro_rules! go_cfg_extra {
( $O :ty ) => {
#[inline(always)]
fn go_emit_cfg(
&self,
inp: &mut InputRef<'a, '_, I, E>,
cfg: Self::Config,
) -> PResult<Emit, $O> {
ConfigParserSealed::<I, $O, E>::go_cfg::<Emit>(self, inp, cfg)
}
#[inline(always)]
fn go_check_cfg(
&self,
inp: &mut InputRef<'a, '_, I, E>,
cfg: Self::Config,
) -> PResult<Check, $O> {
ConfigParserSealed::<I, $O, E>::go_cfg::<Check>(self, inp, cfg)
}
};
}
mod blanket;
#[cfg(feature = "unstable")]
pub mod cache;
pub mod combinator;
pub mod container;
#[cfg(feature = "either")]
pub mod either;
pub mod error;
#[cfg(feature = "extension")]
pub mod extension;
pub mod extra;
#[cfg(docsrs)]
pub mod guide;
pub mod input;
#[cfg(feature = "label")]
pub mod label;
#[cfg(feature = "lexical-numbers")]
pub mod number;
#[cfg(feature = "pratt")]
pub mod pratt;
pub mod primitive;
mod private;
pub mod recovery;
pub mod recursive;
#[cfg(feature = "regex")]
pub mod regex;
pub mod span;
mod stream;
pub mod text;
pub mod util;
/// Commonly used functions, traits and types.
///
/// *Listen, three eyes,” he said, “don’t you try to outweird me, I get stranger things than you free with my breakfast
/// cereal.”*
pub mod prelude {
#[cfg(feature = "lexical-numbers")]
pub use super::number::number;
#[cfg(feature = "pratt")]
pub use super::pratt::{InfixOp, Pratt};
#[cfg(feature = "regex")]
pub use super::regex::regex;
pub use super::{
error::{Cheap, EmptyErr, Error as _, Rich, Simple},
extra,
input::Input,
primitive::{
any, any_ref, choice, custom, empty, end, group, just, map_ctx, none_of, one_of, todo,
},
recovery::{nested_delimiters, skip_then_retry_until, skip_until, via_parser},
recursive::{recursive, Recursive},
span::{SimpleSpan, Span as _},
text, Boxed, ConfigIterParser, ConfigParser, IterParser, ParseResult, Parser,
};
pub use crate::{select, select_ref};
}
use crate::input::InputOwn;
use alloc::{boxed::Box, rc::Rc, string::String, sync::Arc, vec, vec::Vec};
#[cfg(feature = "nightly")]
use core::marker::Tuple;
use core::{
borrow::Borrow,
cell::{Cell, RefCell, UnsafeCell},
cmp::{Eq, Ordering},
fmt,
hash::Hash,
marker::PhantomData,
mem::MaybeUninit,
ops::{Range, RangeFrom},
panic::Location,
str::FromStr,
};
use hashbrown::HashMap;
#[cfg(feature = "serde")]
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "label")]
use self::label::{LabelError, Labelled};
use self::{
combinator::*,
container::*,
error::Error,
extra::ParserExtra,
input::{BorrowInput, Emitter, ExactSizeInput, InputRef, SliceInput, StrInput, ValueInput},
prelude::*,
primitive::Any,
private::{
Check, ConfigIterParserSealed, ConfigParserSealed, Emit, IPResult, IterParserSealed,
Located, MaybeUninitExt, Mode, PResult, ParserSealed, Sealed,
},
recovery::{RecoverWith, Strategy},
span::Span,
text::*,
util::{MaybeMut, MaybeRef},
};
#[cfg(all(feature = "extension", doc))]
use self::{extension::v1::*, primitive::custom, stream::Stream};
/// A type that allows mentioning type parameters *without* all of the customary omission of auto traits that comes
/// with `PhantomData`.
struct EmptyPhantom<T>(core::marker::PhantomData<T>);
impl<T> EmptyPhantom<T> {
const fn new() -> Self {
Self(core::marker::PhantomData)
}
}
impl<T> Copy for EmptyPhantom<T> {}
impl<T> Clone for EmptyPhantom<T> {
fn clone(&self) -> Self {
*self
}
}
// SAFETY: This is safe because `EmptyPhantom` doesn't actually contain a `T`.
unsafe impl<T> Send for EmptyPhantom<T> {}
// SAFETY: This is safe because `EmptyPhantom` doesn't actually contain a `T`.
unsafe impl<T> Sync for EmptyPhantom<T> {}
impl<T> Unpin for EmptyPhantom<T> {}
impl<T> core::panic::UnwindSafe for EmptyPhantom<T> {}
impl<T> core::panic::RefUnwindSafe for EmptyPhantom<T> {}
#[cfg(feature = "sync")]
mod sync {
use super::*;
pub(crate) type RefC<T> = alloc::sync::Arc<T>;
pub(crate) type RefW<T> = alloc::sync::Weak<T>;
pub(crate) type DynParser<'a, 'b, I, O, E> = dyn Parser<'a, I, O, E> + Send + Sync + 'b;
/// A trait that requires either nothing or `Send` and `Sync` bounds depending on whether the `sync` feature is
/// enabled. Used to constrain API usage succinctly and easily.
pub trait MaybeSync: Send + Sync {}
impl<T: Send + Sync> MaybeSync for T {}
}
#[cfg(not(feature = "sync"))]
mod sync {
use super::*;
pub(crate) type RefC<T> = alloc::rc::Rc<T>;
pub(crate) type RefW<T> = alloc::rc::Weak<T>;
pub(crate) type DynParser<'a, 'b, I, O, E> = dyn Parser<'a, I, O, E> + 'b;
/// A trait that requires either nothing or `Send` and `Sync` bounds depending on whether the `sync` feature is
/// enabled. Used to constrain API usage succinctly and easily.
pub trait MaybeSync {}
impl<T> MaybeSync for T {}
}
use sync::{DynParser, MaybeSync, RefC, RefW};
/// The result of performing a parse on an input with [`Parser`].
///
/// Unlike `Result`, this type is designed to express the fact that generating outputs and errors are not
/// mutually-exclusive operations: it is possible for a parse to produce non-terminal errors (see
/// [`Parser::recover_with`] while still producing useful output).
///
/// If you don't care for recovered outputs and you with to treat success/failure as a binary, you may use
/// [`ParseResult::into_result`].
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ParseResult<T, E> {
output: Option<T>,
errs: Vec<E>,
}
impl<T, E> ParseResult<T, E> {
pub(crate) fn new(output: Option<T>, errs: Vec<E>) -> ParseResult<T, E> {
ParseResult { output, errs }
}
/// Whether this result contains output
pub fn has_output(&self) -> bool {
self.output.is_some()
}
/// Whether this result has any errors
pub fn has_errors(&self) -> bool {
!self.errs.is_empty()
}
/// Get a reference to the output of this result, if it exists
pub fn output(&self) -> Option<&T> {
self.output.as_ref()
}
/// Get an iterator over the parse errors for this result. The iterator will produce no items if there were no
/// errors.
pub fn errors(&self) -> impl ExactSizeIterator<Item = &E> + DoubleEndedIterator {
self.errs.iter()
}
/// Convert this `ParseResult` into an option containing the output, if any exists
pub fn into_output(self) -> Option<T> {
self.output
}
/// Convert this `ParseResult` into a vector containing any errors. The vector will be empty if there were no
/// errors.
pub fn into_errors(self) -> Vec<E> {
self.errs
}
/// Convert this `ParseResult` into a tuple containing the output, if any existed, and errors, if any were
/// encountered.
pub fn into_output_errors(self) -> (Option<T>, Vec<E>) {
(self.output, self.errs)
}
/// Convert this `ParseResult` into a standard `Result`. This discards output if parsing generated any errors,
/// matching the old behavior of [`Parser::parse`].
pub fn into_result(self) -> Result<T, Vec<E>> {
if self.errs.is_empty() {
self.output.ok_or(self.errs)
} else {
Err(self.errs)
}
}
/// Convert this `ParseResult` into the output. If any errors were generated (including non-fatal errors!), a
/// panic will occur instead.
///
/// The use of this function is discouraged in user-facing code. However, it may be convenient for use in tests.
#[track_caller]
pub fn unwrap(self) -> T
where
E: fmt::Debug,
{
if self.has_errors() {
panic!(
"called `ParseResult::unwrap` on a parse result containing errors: {:?}",
&self.errs
)
} else {
self.output.expect("parser generated no errors or output")
}
}
}
/// A trait implemented by parsers.
///
/// Parsers take inputs of type `I`, which will implement [`Input`]. Refer to the documentation on [`Input`] for examples
/// of common input types. It will then attempt to parse them into a value of type `O`, which may be just about any type.
/// In doing so, they may encounter errors. These need not be fatal to the parsing process: syntactic errors can be
/// recovered from and a valid output may still be generated alongside any syntax errors that were encountered along the
/// way. Usually, this output comes in the form of an
/// [Abstract Syntax Tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (AST).
///
/// The final type parameter, `E`, is expected to be one of the type in the [`extra`] module,
/// implementing [`ParserExtra`]. This trait is used to encapsulate the various types a parser
/// uses that are not simply its input and output. Refer to the documentation on the [`ParserExtra`] trait
/// for more detail on the contained types. If not provided, it will default to [`extra::Default`],
/// which will have the least overhead, but also the least meaningful errors.
///
/// The lifetime of the parser is used for zero-copy output - the input is bound by the lifetime,
/// and returned values or parser state may take advantage of this to borrow tokens or slices of the
/// input and hold on to them, if the input supports this.
///
/// You cannot directly implement this trait yourself. If you feel like the built-in parsers are not enough for you,
/// there are several options in increasing order of complexity:
///
/// 1) Try using combinators like [`Parser::try_map`] and [`Parser::validate`] to implement custom error generation
///
/// 2) Use [`custom`] to implement your own parsing logic inline within an existing parser
///
/// 3) Use chumsky's [`extension`] API to write an extension parser that feels like it's native to chumsky
///
/// 4) If you believe you've found a common use-case that's missing from chumsky, you could open a pull request to
/// implement it in chumsky itself.
#[cfg_attr(
feature = "nightly",
rustc_on_unimplemented(
message = "`{Self}` is not a parser from `{I}` to `{O}`",
label = "This parser is not compatible because it does not implement `Parser<{I}, {O}>`",
note = "You should check that the output types of your parsers are consistent with the combinators you're using",
)
)]
pub trait Parser<'a, I: Input<'a>, O, E: ParserExtra<'a, I> = extra::Default>:
ParserSealed<'a, I, O, E>
{
/// Parse a stream of tokens, yielding an output if possible, and any errors encountered along the way.
///
/// If `None` is returned (i.e: parsing failed) then there will *always* be at least one item in the error `Vec`.
/// If you want to include non-default state, use [`Parser::parse_with_state`] instead.
///
/// Although the signature of this function looks complicated, it's simpler than you think! You can pass a
/// [`&[T]`], a [`&str`], [`Stream`], or anything implementing [`Input`] to it.
fn parse(&self, input: I) -> ParseResult<O, E::Error>
where
I: Input<'a>,
E::State: Default,
E::Context: Default,
{
self.parse_with_state(input, &mut E::State::default())
}
/// Parse a stream of tokens, yielding an output if possible, and any errors encountered along the way.
/// The provided state will be passed on to parsers that expect it, such as [`map_with_state`](Parser::map_with_state).
///
/// If `None` is returned (i.e: parsing failed) then there will *always* be at least one item in the error `Vec`.
/// If you want to just use a default state value, use [`Parser::parse`] instead.
///
/// Although the signature of this function looks complicated, it's simpler than you think! You can pass a
/// [`&[T]`], a [`&str`], [`Stream`], or anything implementing [`Input`] to it.
fn parse_with_state(&self, input: I, state: &mut E::State) -> ParseResult<O, E::Error>
where
I: Input<'a>,
E::Context: Default,
{
let mut own = InputOwn::new_state(input, state);
let mut inp = own.as_ref_start();
let res = self.then_ignore(end()).go::<Emit>(&mut inp);
let alt = inp.errors.alt.take();
let mut errs = own.into_errs();
let out = match res {
Ok(out) => Some(out),
Err(()) => {
errs.push(alt.expect("error but no alt?").err);
None
}
};
ParseResult::new(out, errs)
}
/// Parse a stream of tokens, ignoring any output, and returning any errors encountered along the way.
///
/// If parsing failed, then there will *always* be at least one item in the returned `Vec`.
/// If you want to include non-default state, use [`Parser::check_with_state`] instead.
///
/// Although the signature of this function looks complicated, it's simpler than you think! You can pass a
/// [`&[T]`], a [`&str`], [`Stream`], or anything implementing [`Input`] to it.
fn check(&self, input: I) -> ParseResult<(), E::Error>
where
Self: Sized,
I: Input<'a>,
E::State: Default,
E::Context: Default,
{
self.check_with_state(input, &mut E::State::default())
}
/// Parse a stream of tokens, ignoring any output, and returning any errors encountered along the way.
///
/// If parsing failed, then there will *always* be at least one item in the returned `Vec`.
/// If you want to just use a default state value, use [`Parser::check`] instead.
///
/// Although the signature of this function looks complicated, it's simpler than you think! You can pass a
/// [`&[T]`], a [`&str`], [`Stream`], or anything implementing [`Input`] to it.
fn check_with_state(&self, input: I, state: &mut E::State) -> ParseResult<(), E::Error>
where
Self: Sized,
I: Input<'a>,
E::Context: Default,
{
let mut own = InputOwn::new_state(input, state);
let mut inp = own.as_ref_start();
let res = self.then_ignore(end()).go::<Check>(&mut inp);
let alt = inp.errors.alt.take();
let mut errs = own.into_errs();
let out = match res {
Ok(()) => Some(()),
Err(()) => {
errs.push(alt.expect("error but no alt?").err);
None
}
};
ParseResult::new(out, errs)
}
/// Map from a slice of the input based on the current parser's span to a value.
///
/// The returned value may borrow data from the input slice, making this function very useful
/// for creating zero-copy AST output values
fn map_slice<U, F: Fn(I::Slice) -> U>(self, f: F) -> MapSlice<'a, Self, I, O, E, F, U>
where
Self: Sized,
I: SliceInput<'a>,
{
MapSlice {
parser: self,
mapper: f,
phantom: EmptyPhantom::new(),
}
}
/// Convert the output of this parser into a slice of the input, based on the current parser's
/// span.
///
/// This is effectively a special case of [`map_slice`](Parser::map_slice)`(|x| x)`
fn slice(self) -> Slice<Self, O>
where
Self: Sized,
{
Slice {
parser: self,
phantom: EmptyPhantom::new(),
}
}
/// Filter the output of this parser, accepting only inputs that match the given predicate.
///
/// The output type of this parser is `I`, the input that was found.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// let lowercase = any::<_, extra::Err<Simple<char>>>()
/// .filter(char::is_ascii_lowercase)
/// .repeated()
/// .at_least(1)
/// .collect::<String>();
///
/// assert_eq!(lowercase.parse("hello").into_result(), Ok("hello".to_string()));
/// assert!(lowercase.parse("Hello").has_errors());
/// ```
fn filter<F: Fn(&O) -> bool>(self, f: F) -> Filter<Self, F>
where
Self: Sized,
{
Filter {
parser: self,
filter: f,
}
}
/// Map the output of this parser to another value.
///
/// The output type of this parser is `U`, the same as the function's output.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// #[derive(Debug, PartialEq)]
/// enum Token { Word(String), Num(u64) }
///
/// let word = any::<_, extra::Err<Simple<char>>>()
/// .filter(|c: &char| c.is_alphabetic())
/// .repeated().at_least(1)
/// .collect::<String>()
/// .map(Token::Word);
///
/// let num = any::<_, extra::Err<Simple<char>>>()
/// .filter(|c: &char| c.is_ascii_digit())
/// .repeated().at_least(1)
/// .collect::<String>()
/// .map(|s| Token::Num(s.parse().unwrap()));
///
/// let token = word.or(num);
///
/// assert_eq!(token.parse("test").into_result(), Ok(Token::Word("test".to_string())));
/// assert_eq!(token.parse("42").into_result(), Ok(Token::Num(42)));
/// ```
fn map<U, F: Fn(O) -> U>(self, f: F) -> Map<Self, O, F>
where
Self: Sized,
{
Map {
parser: self,
mapper: f,
phantom: EmptyPhantom::new(),
}
}
/// Works the same as [`Parser::map`], but the second argument for the mapper F is the parser's
/// current context.
///
/// Primarily used to modify existing context using the result of a parser, before passing to a
/// `*_with_ctx` method. Also useful when the output of a parser is dependent on the currenct
/// context.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
///
/// fn palindrome_parser<'a>() -> impl Parser<'a, &'a str, String> {
/// recursive(|chain| {
/// choice((
/// just(String::new())
/// .configure(|cfg, ctx: &String| cfg.seq(ctx.clone()))
/// .then_ignore(end()),
/// any()
/// .map_with_ctx(|x, ctx| format!("{x}{ctx}"))
/// .ignore_with_ctx(chain),
/// ))
/// })
/// .with_ctx(String::new())
/// }
///
/// assert_eq!(palindrome_parser().parse("abccba").into_result().as_deref(), Ok("cba"));
/// assert_eq!(palindrome_parser().parse("hello olleh").into_result().as_deref(), Ok(" olleh"));
/// assert!(palindrome_parser().parse("abccb").into_result().is_err());
/// ```
fn map_with_ctx<U, F: Fn(O, &E::Context) -> U>(self, f: F) -> MapWithContext<Self, O, F>
where
Self: Sized,
{
MapWithContext {
parser: self,
mapper: f,
phantom: EmptyPhantom::new(),
}
}
/// Map the output of this parser to another value.
/// If the output of this parser isn't a tuple, use [`Parser::map`].
///
/// The output type of this parser is `U`, the same as the function's output.
///
/// # Examples
///
/// ```
/// # use chumsky::prelude::*;
/// #[derive(Clone, Copy, Debug, PartialEq, Eq)]
/// pub enum Value {
/// One(u8),
/// Two(u8, u8),
/// Three(u8, u8, u8),
/// }
///
/// fn parser<'a>() -> impl Parser<'a, &'a [u8], Vec<Value>> {
/// choice((
/// just(1).ignore_then(any()).map(Value::One),
/// just(2)
/// .ignore_then(group((any(), any())))
/// .map_group(Value::Two),
/// just(3)
/// .ignore_then(group((any(), any(), any())))
/// .map_group(Value::Three),
/// ))
/// .repeated()
/// .collect()
/// }
///
/// let bytes = &[3, 1, 2, 3, 1, 127, 2, 21, 69];
/// assert_eq!(
/// parser().parse(bytes).into_result(),
/// Ok(vec![
/// Value::Three(1, 2, 3),
/// Value::One(127),
/// Value::Two(21, 69)
/// ])
/// );
/// ```
#[cfg(feature = "nightly")]
fn map_group<F: Fn<O>>(self, f: F) -> MapGroup<Self, O, F>
where
Self: Sized,
O: Tuple,
{
MapGroup {
parser: self,
mapper: f,
phantom: EmptyPhantom::new(),
}
}
/// Map the output of this parser to another value, making use of the pattern's span when doing so.
///
/// This is very useful when generating an AST that attaches a span to each AST node.
///
/// The output type of this parser is `U`, the same as the function's output.
///
/// # Examples
///
/// ```
/// # use chumsky::prelude::*;
///
/// // It's common for AST nodes to use a wrapper type that allows attaching span information to them
/// #[derive(Debug, PartialEq)]
/// pub struct Spanned<T>(T, SimpleSpan<usize>);
///
/// let ident = text::ascii::ident::<_, _, extra::Err<Simple<char>>>()
/// .map_with_span(Spanned) // Equivalent to `.map_with_span(|ident, span| Spanned(ident, span))`
/// .padded();
///
/// assert_eq!(ident.parse("hello").into_result(), Ok(Spanned("hello", (0..5).into())));
/// assert_eq!(ident.parse(" hello ").into_result(), Ok(Spanned("hello", (7..12).into())));
/// ```
fn map_with_span<U, F: Fn(O, I::Span) -> U>(self, f: F) -> MapWithSpan<Self, O, F>
where
Self: Sized,
{
MapWithSpan {
parser: self,
mapper: f,
phantom: EmptyPhantom::new(),
}
}
/// Transform the output of this parser to the pattern's span.
///
/// This is commonly used when you know what pattern you've parsed and are only interested in the span of the
/// pattern.
///
/// The output type of this parser is `I::Span`.
///
/// # Examples
///
/// ```
/// # use chumsky::prelude::*;
///
/// // It's common for AST nodes to use a wrapper type that allows attaching span information to them
/// #[derive(Debug, PartialEq)]
/// pub enum Expr<'a> {
/// Int(&'a str, SimpleSpan),
/// // The span is that of the operator, '+'
/// Add(Box<Expr<'a>>, SimpleSpan, Box<Expr<'a>>),
/// }
///
/// let int = text::int::<_, _, extra::Err<Simple<char>>>(10)
/// .slice()
/// .map_with_span(Expr::Int)
/// .padded();
///
/// let add_op = just('+').to_span().padded();
/// let sum = int.foldl(
/// add_op.then(int).repeated(),
/// |a, (op_span, b)| Expr::Add(Box::new(a), op_span, Box::new(b)),
/// );
///
/// assert_eq!(sum.parse("42 + 7 + 13").into_result(), Ok(Expr::Add(
/// Box::new(Expr::Add(
/// Box::new(Expr::Int("42", (0..2).into())),
/// (3..4).into(),
/// Box::new(Expr::Int("7", (5..6).into())),
/// )),
/// (7..8).into(),
/// Box::new(Expr::Int("13", (9..11).into())),
/// )));
/// ```
fn to_span(self) -> ToSpan<Self, O>
where
Self: Sized,
{
ToSpan {
parser: self,
phantom: EmptyPhantom::new(),
}
}
/// Map the output of this parser to another value, making use of the parser's state when doing so.
///
/// This is very useful for parsing non context-free grammars.
///
/// The output type of this parser is `U`, the same as the function's output.
///
/// # Examples
///
/// ## General
///
/// ```
/// # use chumsky::prelude::*;
/// use std::ops::Range;
/// use lasso::{Rodeo, Spur};
///
/// // It's common for AST nodes to use interned versions of identifiers
/// // Keys are generally smaller, faster to compare, and can be `Copy`
/// #[derive(Copy, Clone)]
/// pub struct Ident(Spur);
///
/// let ident = text::ascii::ident::<_, _, extra::Full<Simple<char>, Rodeo, ()>>()
/// .map_with_state(|ident, span, state| Ident(state.get_or_intern(ident)))
/// .padded()
/// .repeated()
/// .at_least(1)
/// .collect::<Vec<_>>();
///
/// // Test out parser
///
/// let mut interner = Rodeo::new();
///
/// match ident.parse_with_state("hello", &mut interner).into_result() {
/// Ok(idents) => {
/// assert_eq!(interner.resolve(&idents[0].0), "hello");
/// }
/// Err(e) => panic!("Parsing Failed: {:?}", e),
/// }
///
/// match ident.parse_with_state("hello hello", &mut interner).into_result() {
/// Ok(idents) => {
/// assert_eq!(idents[0].0, idents[1].0);
/// }
/// Err(e) => panic!("Parsing Failed: {:?}", e),
/// }
/// ```
///
/// See [`Parser::foldl_with_state`] for an example showing arena allocation via parser state.
fn map_with_state<U, F: Fn(O, I::Span, &mut E::State) -> U>(
self,
f: F,
) -> MapWithState<Self, O, F>
where
Self: Sized,
{
MapWithState {
parser: self,
mapper: f,
phantom: EmptyPhantom::new(),
}
}
/// After a successful parse, apply a fallible function to the output. If the function produces an error, treat it
/// as a parsing error.
///
/// If you wish parsing of this pattern to continue when an error is generated instead of halting, consider using
/// [`Parser::validate`] instead.
///
/// The output type of this parser is `U`, the [`Ok`] return value of the function.
///
/// # Examples
///
/// ```
/// # use chumsky::prelude::*;
/// let byte = text::int::<_, _, extra::Err<Rich<char>>>(10)
/// .try_map(|s: &str, span| s
/// .parse::<u8>()
/// .map_err(|e| Rich::custom(span, e)));
///
/// assert!(byte.parse("255").has_output());
/// assert!(byte.parse("256").has_errors()); // Out of range
/// ```
#[doc(alias = "filter_map")]
fn try_map<U, F: Fn(O, I::Span) -> Result<U, E::Error>>(self, f: F) -> TryMap<Self, O, F>
where
Self: Sized,
{
TryMap {
parser: self,
mapper: f,
phantom: EmptyPhantom::new(),
}
}
/// After a successful parse, apply a fallible function to the output, making use of the parser's state when
/// doing so. If the function produces an error, treat it as a parsing error.
///
/// If you wish parsing of this pattern to continue when an error is generated instead of halting, consider using
/// [`Parser::validate`] instead.
///
/// The output type of this parser is `U`, the [`Ok`] return value of the function.
fn try_map_with_state<U, F: Fn(O, I::Span, &mut E::State) -> Result<U, E::Error>>(
self,
f: F,
) -> TryMapWithState<Self, O, F>
where
Self: Sized,
{
TryMapWithState {
parser: self,
mapper: f,
phantom: EmptyPhantom::new(),
}
}
/// Ignore the output of this parser, yielding `()` as an output instead.
///
/// This can be used to reduce the cost of parsing by avoiding unnecessary allocations (most collections containing
/// [ZSTs](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
/// [do not allocate](https://doc.rust-lang.org/std/vec/struct.Vec.html#guarantees)). For example, it's common to
/// want to ignore whitespace in many grammars (see [`text::whitespace`]).
///
/// The output type of this parser is `()`.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// // A parser that parses any number of whitespace characters without allocating
/// let whitespace = any::<_, extra::Err<Simple<char>>>()
/// .filter(|c: &char| c.is_whitespace())
/// .ignored()
/// .repeated()
/// .collect::<Vec<_>>();
///
/// assert_eq!(whitespace.parse(" ").into_result(), Ok(vec![(); 4]));
/// assert!(whitespace.parse(" hello").has_errors());
/// ```
fn ignored(self) -> Ignored<Self, O>
where
Self: Sized,
{
Ignored {
parser: self,
phantom: EmptyPhantom::new(),
}
}
/// Memoize the parser such that later attempts to parse the same input 'remember' the attempt and exit early.
///
/// If you're finding that certain inputs produce exponential behavior in your parser, strategically applying
/// memoization to a ['garden path'](https://en.wikipedia.org/wiki/Garden-path_sentence) rule is often an effective
/// way to solve the problem. At the limit, applying memoization to all combinators will turn any parser into one
/// with `O(n)`, albeit with very significant per-element overhead and high memory usage.
///
/// Memoization also works with recursion, so this can be used to write parsers using
/// [left recursion](https://en.wikipedia.org/wiki/Left_recursion).
// TODO: Example
#[cfg(feature = "memoization")]
fn memoized(self) -> Memoized<Self>
where
Self: Sized,
{
Memoized { parser: self }
}
/// Transform all outputs of this parser to a predetermined value.
///
/// The output type of this parser is `U`, the type of the predetermined value.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// #[derive(Clone, Debug, PartialEq)]
/// enum Op { Add, Sub, Mul, Div }
///
/// let op = just::<_, _, extra::Err<Simple<char>>>('+').to(Op::Add)
/// .or(just('-').to(Op::Sub))
/// .or(just('*').to(Op::Mul))
/// .or(just('/').to(Op::Div));
///
/// assert_eq!(op.parse("+").into_result(), Ok(Op::Add));
/// assert_eq!(op.parse("/").into_result(), Ok(Op::Div));
/// ```
fn to<U: Clone>(self, to: U) -> To<Self, O, U>
where
Self: Sized,
{
To {
parser: self,
to,
phantom: EmptyPhantom::new(),
}
}
/// Label this parser with the given label.
///
/// Labelling a parser makes all errors generated by the parser refer to the label rather than any sub-elements
/// within the parser. For example, labelling a parser for an expression would yield "expected expression" errors
/// rather than "expected integer, string, binary op, etc." errors.
// TODO: Example
#[cfg(feature = "label")]
fn labelled<L>(self, label: L) -> Labelled<Self, L>
where
Self: Sized,
E::Error: LabelError<'a, I, L>,
{
Labelled {
parser: self,
label,
is_context: false,
}
}
/// Parse one thing and then another thing, yielding a tuple of the two outputs.
///
/// The output type of this parser is `(O, U)`, a combination of the outputs of both parsers.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// let word = any::<_, extra::Err<Simple<char>>>()
/// .filter(|c: &char| c.is_alphabetic())
/// .repeated()
/// .at_least(1)
/// .collect::<String>();
/// let two_words = word.then_ignore(just(' ')).then(word);
///
/// assert_eq!(two_words.parse("dog cat").into_result(), Ok(("dog".to_string(), "cat".to_string())));
/// assert!(two_words.parse("hedgehog").has_errors());
/// ```
fn then<U, B: Parser<'a, I, U, E>>(self, other: B) -> Then<Self, B, O, U, E>
where
Self: Sized,
{
Then {
parser_a: self,
parser_b: other,
phantom: EmptyPhantom::new(),
}
}
/// Parse one thing and then another thing, yielding only the output of the latter.
///
/// The output type of this parser is `U`, the same as the second parser.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// let zeroes = any::<_, extra::Err<Simple<char>>>().filter(|c: &char| *c == '0').ignored().repeated().collect::<Vec<_>>();
/// let digits = any().filter(|c: &char| c.is_ascii_digit())
/// .repeated()
/// .collect::<String>();
/// let integer = zeroes
/// .ignore_then(digits)
/// .from_str()
/// .unwrapped();
///
/// assert_eq!(integer.parse("00064").into_result(), Ok(64));
/// assert_eq!(integer.parse("32").into_result(), Ok(32));
/// ```
fn ignore_then<U, B: Parser<'a, I, U, E>>(self, other: B) -> IgnoreThen<Self, B, O, E>
where
Self: Sized,
{
IgnoreThen {
parser_a: self,
parser_b: other,
phantom: EmptyPhantom::new(),
}
}
/// Parse one thing and then another thing, yielding only the output of the former.
///
/// The output type of this parser is `O`, the same as the original parser.
///
/// # Examples
///
/// ```
/// # use chumsky::{prelude::*, error::Simple};
/// let word = any::<_, extra::Err<Simple<char>>>()
/// .filter(|c: &char| c.is_alphabetic())
/// .repeated()
/// .at_least(1)