Skip to content

Commit 266f404

Browse files
Fix some holes in documentation (#720)
* Add examples to error type docs * Add relevant links in error type docs * Fix Simple::found docs to match Rich::found docs * Add example to Parser::into_iter docs * Add example to Parser::to_slice docs * Fix cargo fmt not liking my trailing whitespace in comments (does it even matter?...) * Replace into_iter doc example
1 parent fe1b999 commit 266f404

File tree

2 files changed

+107
-5
lines changed

2 files changed

+107
-5
lines changed

src/error.rs

Lines changed: 61 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,17 @@ pub trait Error<'a, I: Input<'a>>:
8686

8787
/// A ZST error type that tracks only whether a parse error occurred at all. This type is for when
8888
/// you want maximum parse speed, at the cost of all error reporting.
89+
///
90+
/// # Examples
91+
///
92+
/// ```
93+
/// use chumsky::prelude::*;
94+
///
95+
/// let parser = just::<_, _, extra::Err<EmptyErr>>("valid");
96+
/// let error = parser.parse("invalid").into_errors()[0];
97+
///
98+
/// assert_eq!(error, EmptyErr::default());
99+
/// ```
89100
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
90101
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Copy, Clone, Default)]
91102
pub struct EmptyErr(());
@@ -109,8 +120,19 @@ impl fmt::Display for EmptyErr {
109120
}
110121
}
111122

112-
/// A very cheap error type that tracks only the error span. This type is most useful when you want fast parsing but do
113-
/// not particularly care about the quality of error messages.
123+
/// A very cheap error type that tracks only the error span ([`SimpleSpan`] by default).
124+
/// This type is most useful when you want fast parsing but do not particularly care about the quality of error messages.
125+
///
126+
/// # Examples
127+
///
128+
/// ```
129+
/// use chumsky::prelude::*;
130+
///
131+
/// let parser = just::<_, _, extra::Err<Cheap>>("+");
132+
/// let error = parser.parse("-").into_errors()[0];
133+
///
134+
/// assert_eq!(error.span(), &SimpleSpan::new(0,1));
135+
/// ```
114136
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
115137
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
116138
pub struct Cheap<S = SimpleSpan<usize>> {
@@ -119,6 +141,8 @@ pub struct Cheap<S = SimpleSpan<usize>> {
119141

120142
impl<S> Cheap<S> {
121143
/// Get the span than that error related to.
144+
///
145+
/// If the span type is unspecified, it is [`SimpleSpan`].
122146
pub fn span(&self) -> &S {
123147
&self.span
124148
}
@@ -156,8 +180,20 @@ where
156180
}
157181
}
158182

159-
/// A simple error type that tracks the error span and found token. This type is most useful when you want fast parsing
183+
/// A simple error type that tracks the error span ([`SimpleSpan`] by default) and found token. This type is most useful when you want fast parsing
160184
/// but do not particularly care about the quality of error messages.
185+
///
186+
/// # Examples
187+
///
188+
/// ```
189+
/// use chumsky::prelude::*;
190+
///
191+
/// let parser = just::<_, _, extra::Err<Simple<char>>>("+");
192+
/// let error = parser.parse("-").into_errors()[0];
193+
///
194+
/// assert_eq!(error.span(), &SimpleSpan::new(0,1));
195+
/// assert_eq!(error.found(), Some(&'-'));
196+
/// ```
161197
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
162198
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
163199
pub struct Simple<'a, T, S = SimpleSpan<usize>> {
@@ -167,11 +203,13 @@ pub struct Simple<'a, T, S = SimpleSpan<usize>> {
167203

168204
impl<T, S> Simple<'_, T, S> {
169205
/// Get the span than that error related to.
206+
///
207+
/// If the span type is unspecified, it is [`SimpleSpan`].
170208
pub fn span(&self) -> &S {
171209
&self.span
172210
}
173211

174-
/// Get the token, if any, that was found at the error location.
212+
/// Get the token found by this error when parsing. `None` implies that the error expected the end of input.
175213
pub fn found(&self) -> Option<&T> {
176214
self.found.as_deref()
177215
}
@@ -537,6 +575,23 @@ where
537575
///
538576
/// Please note that it uses a [`Vec`] to remember expected symbols. If you find this to be too slow, you can
539577
/// implement [`Error`] for your own error type or use [`Simple`] instead.
578+
///
579+
/// This error type stores a span ([`SimpleSpan`] by default), a [`RichReason`], and a list of expected [`RichPattern`] with their spans.
580+
///
581+
/// # Examples
582+
///
583+
/// ```
584+
/// use chumsky::prelude::*;
585+
/// use chumsky::error::{RichReason, RichPattern};
586+
///
587+
/// let parser = one_of::<_, _, extra::Err<Rich<char>>>("1234");
588+
/// let error = parser.parse("5").into_errors()[0].clone();
589+
///
590+
/// assert_eq!(error.span(), &SimpleSpan::new(0,1));
591+
/// assert!(matches!(error.reason(), &RichReason::ExpectedFound {..}));
592+
/// assert_eq!(error.found(), Some(&'5'));
593+
///
594+
/// ```
540595
#[derive(Clone, PartialEq, Eq, Hash)]
541596
pub struct Rich<'a, T, S = SimpleSpan<usize>> {
542597
span: S,
@@ -574,6 +629,8 @@ impl<'a, T, S> Rich<'a, T, S> {
574629
}
575630

576631
/// Get the span associated with this error.
632+
///
633+
/// If the span type is unspecified, it is [`SimpleSpan`].
577634
pub fn span(&self) -> &S {
578635
&self.span
579636
}

src/lib.rs

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,34 @@ pub trait Parser<'src, I: Input<'src>, O, E: ParserExtra<'src, I> = extra::Defau
452452

453453
/// Convert the output of this parser into a slice of the input, based on the current parser's
454454
/// span.
455+
///
456+
/// Note: unlike the parser `.repeated().collect()`, this method includes all tokens that are
457+
/// "ignored" by the parser, including any padding, separators, and sub-parsers with
458+
/// [`Parser::ignored`], [`Parser::ignore_then`], and [`Parser::then_ignore`].
459+
///
460+
/// # Examples
461+
/// Example with input of type `&str` (token type is `char`).
462+
/// ```
463+
/// # use chumsky::prelude::*;
464+
/// // Matches a number with underscores that is surrounded by apostrophes.
465+
/// let quoted_numeric = any::<&str, extra::Err<Simple<char>>>()
466+
/// .filter(|c: &char| c.is_digit(10))
467+
/// .separated_by(just("_").repeated().at_most(1))
468+
/// .to_slice()
469+
/// .padded_by(just("'"));
470+
/// assert_eq!(quoted_numeric.parse("'1_23'").into_result(), Ok("1_23"));
471+
/// ```
472+
/// Example with input of type `&[u32]` (token type is `u32`).
473+
/// ```
474+
/// # use chumsky::prelude::*;
475+
/// // Matches even numbers, then ignoring the rest of the input when an odd number is reached.
476+
/// let even_matcher = any::<&[u32], extra::Err<Simple<u32>>>()
477+
/// .filter(|c: &u32| c % 2 == 0)
478+
/// .repeated()
479+
/// .to_slice()
480+
/// .lazy();
481+
/// assert_eq!(even_matcher.parse(&[2, 4, 8, 5, 6]).unwrap(), &[2, 4, 8]);
482+
/// ```
455483
fn to_slice(self) -> ToSlice<Self, O>
456484
where
457485
Self: Sized,
@@ -2036,7 +2064,24 @@ pub trait Parser<'src, I: Input<'src>, O, E: ParserExtra<'src, I> = extra::Defau
20362064
/// The resulting iterable parser will emit each element of the output type in turn.
20372065
///
20382066
/// This is *broadly* analogous to functions like [`Vec::into_iter`], but operating at the level of parser outputs.
2039-
// TODO: Example
2067+
///
2068+
/// # Examples
2069+
///
2070+
/// ```
2071+
/// # use chumsky::prelude::*;
2072+
/// // Parses whole integers
2073+
/// let num = text::int::<&str, extra::Default>(10).padded().map(|x: &str| x.parse::<u64>().unwrap());
2074+
/// // Parses a range like `0..4` into a vector like `[0, 1, 2, 3]`
2075+
/// let range = num.then_ignore(just("..")).then(num)
2076+
/// .map(|(x, y)| x..y)
2077+
/// .into_iter()
2078+
/// .collect::<Vec<u64>>();
2079+
/// // Parses a list of numbers into a vector
2080+
/// let list = num.separated_by(just(',')).collect::<Vec<u64>>();
2081+
/// let set = range.or(list);
2082+
/// assert_eq!(set.parse("0, 1, 2, 3").unwrap(), [0, 1, 2, 3]);
2083+
/// assert_eq!(set.parse("0..4").unwrap(), [0, 1, 2, 3]);
2084+
/// ```
20402085
fn into_iter(self) -> IntoIter<Self, O>
20412086
where
20422087
Self: Sized,

0 commit comments

Comments
 (0)