aboutsummaryrefslogtreecommitdiff
path: root/src/_tutorial/chapter_2.rs
blob: c27b7196eabf77ecf3739b86255d68d730d4c74d (plain)
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
//! # Chapter 2: Tokens and Tags
//!
//! The simplest *useful* parser you can write is one which matches tokens.
//!
//! ## Tokens
//!
//! [`Stream`] provides some core operations to help with parsing. For example, to process a
//! single token, you can do:
//! ```rust
//! # use winnow::Parser;
//! # use winnow::PResult;
//! use winnow::stream::Stream;
//! use winnow::error::ParserError;
//! use winnow::error::ErrorKind;
//! use winnow::error::ErrMode;
//!
//! fn parse_prefix(input: &mut &str) -> PResult<char> {
//!     let c = input.next_token().ok_or_else(|| {
//!         ErrMode::from_error_kind(input, ErrorKind::Token)
//!     })?;
//!     if c != '0' {
//!         return Err(ErrMode::from_error_kind(input, ErrorKind::Verify));
//!     }
//!     Ok(c)
//! }
//!
//! fn main()  {
//!     let mut input = "0x1a2b Hello";
//!
//!     let output = parse_prefix.parse_next(&mut input).unwrap();
//!
//!     assert_eq!(input, "x1a2b Hello");
//!     assert_eq!(output, '0');
//!
//!     assert!(parse_prefix.parse_next(&mut "d").is_err());
//! }
//! ```
//!
//! [`any`] and [`Parser::verify`] are [`Parser`] building blocks on top of [`Stream`]:
//! ```rust
//! # use winnow::PResult;
//! use winnow::Parser;
//! use winnow::token::any;
//!
//! fn parse_prefix(input: &mut &str) -> PResult<char> {
//!     any.verify(|c| *c == '0').parse_next(input)
//! }
//! #
//! # fn main()  {
//! #     let mut input = "0x1a2b Hello";
//! #
//! #     let output = parse_prefix.parse_next(&mut input).unwrap();
//! #
//! #     assert_eq!(input, "x1a2b Hello");
//! #     assert_eq!(output, '0');
//! #
//! #     assert!(parse_prefix.parse_next(&mut "d").is_err());
//! # }
//! ```
//!
//! Matching a single token literal is common enough that [`Parser`] is implemented for
//! `char`.
//!
//! ```rust
//! # use winnow::PResult;
//! use winnow::Parser;
//!
//! fn parse_prefix(input: &mut &str) -> PResult<char> {
//!     '0'.parse_next(input)
//! }
//! #
//! # fn main()  {
//! #     let mut input = "0x1a2b Hello";
//! #
//! #     let output = parse_prefix.parse_next(&mut input).unwrap();
//! #
//! #     assert_eq!(input, "x1a2b Hello");
//! #     assert_eq!(output, '0');
//! #
//! #     assert!(parse_prefix.parse_next(&mut "d").is_err());
//! # }
//! ```
//!
//! ## Tags
//!
//! [`Stream`] also supports processing slices of tokens:
//! ```rust
//! # use winnow::Parser;
//! # use winnow::PResult;
//! use winnow::stream::Stream;
//! use winnow::error::ParserError;
//! use winnow::error::ErrorKind;
//! use winnow::error::ErrMode;
//!
//! fn parse_prefix<'s>(input: &mut &'s str) -> PResult<&'s str> {
//!     let expected = "0x";
//!     if input.len() < expected.len() {
//!         return Err(ErrMode::from_error_kind(input, ErrorKind::Slice));
//!     }
//!     let actual = input.next_slice(expected.len());
//!     if actual != expected {
//!         return Err(ErrMode::from_error_kind(input, ErrorKind::Verify));
//!     }
//!     Ok(actual)
//! }
//!
//! fn main()  {
//!     let mut input = "0x1a2b Hello";
//!
//!     let output = parse_prefix.parse_next(&mut input).unwrap();
//!     assert_eq!(input, "1a2b Hello");
//!     assert_eq!(output, "0x");
//!
//!     assert!(parse_prefix.parse_next(&mut "0o123").is_err());
//! }
//! ```
//!
//! Again, matching a literal is common enough that [`Parser`] is implemented for `&str`:
//! ```rust
//! # use winnow::PResult;
//! use winnow::Parser;
//!
//! fn parse_prefix<'s>(input: &mut &'s str) -> PResult<&'s str> {
//!     "0x".parse_next(input)
//! }
//! #
//! # fn main()  {
//! #     let mut input = "0x1a2b Hello";
//! #
//! #     let output = parse_prefix.parse_next(&mut input).unwrap();
//! #     assert_eq!(input, "1a2b Hello");
//! #     assert_eq!(output, "0x");
//! #
//! #     assert!(parse_prefix.parse_next(&mut "0o123").is_err());
//! # }
//! ```
//!
//! In `winnow`, we call this type of parser a [`tag`]. See [`token`] for additional individual
//! and token-slice parsers.
//!
//! ## Character Classes
//!
//! Selecting a single `char` or a [`tag`] is fairly limited. Sometimes, you will want to select one of several
//! `chars` of a specific class, like digits. For this, we use the [`one_of`] parser:
//!
//! ```rust
//! # use winnow::Parser;
//! # use winnow::PResult;
//! use winnow::token::one_of;
//!
//! fn parse_digits(input: &mut &str) -> PResult<char> {
//!     one_of(('0'..='9', 'a'..='f', 'A'..='F')).parse_next(input)
//! }
//!
//! fn main() {
//!     let mut input = "1a2b Hello";
//!
//!     let output = parse_digits.parse_next(&mut input).unwrap();
//!     assert_eq!(input, "a2b Hello");
//!     assert_eq!(output, '1');
//!
//!     assert!(parse_digits.parse_next(&mut "Z").is_err());
//! }
//! ```
//!
//! > **Aside:** [`one_of`] might look straightforward, a function returning a value that implements `Parser`.
//! > Let's look at it more closely as its used above (resolving all generic parameters):
//! > ```rust
//! > # use winnow::prelude::*;
//! > # use winnow::error::InputError;
//! > pub fn one_of<'i>(
//! >     list: &'static [char]
//! > ) -> impl Parser<&'i str, char, InputError<&'i str>> {
//! >     // ...
//! > #    winnow::token::one_of(list)
//! > }
//! > ```
//! > If you have not programmed in a language where functions are values, the type signature of the
//! > [`one_of`] function might be a surprise.
//! > The function [`one_of`] *returns a function*. The function it returns is a
//! > `Parser`, taking a `&str` and returning an `PResult`. This is a common pattern in winnow for
//! > configurable or stateful parsers.
//!
//! Some of character classes are common enough that a named parser is provided, like with:
//! - [`line_ending`][crate::ascii::line_ending]: Recognizes an end of line (both `\n` and `\r\n`)
//! - [`newline`][crate::ascii::newline]: Matches a newline character `\n`
//! - [`tab`][crate::ascii::tab]: Matches a tab character `\t`
//!
//! You can then capture sequences of these characters with parsers like [`take_while`].
//! ```rust
//! # use winnow::Parser;
//! # use winnow::PResult;
//! use winnow::token::take_while;
//!
//! fn parse_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//!     take_while(1.., ('0'..='9', 'a'..='f', 'A'..='F')).parse_next(input)
//! }
//!
//! fn main() {
//!     let mut input = "1a2b Hello";
//!
//!     let output = parse_digits.parse_next(&mut input).unwrap();
//!     assert_eq!(input, " Hello");
//!     assert_eq!(output, "1a2b");
//!
//!     assert!(parse_digits.parse_next(&mut "Z").is_err());
//! }
//! ```
//!
//! We could simplify this further by using one of the built-in character classes, [`hex_digit1`]:
//! ```rust
//! # use winnow::Parser;
//! # use winnow::PResult;
//! use winnow::ascii::hex_digit1;
//!
//! fn parse_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//!     hex_digit1.parse_next(input)
//! }
//!
//! fn main() {
//!     let mut input = "1a2b Hello";
//!
//!     let output = parse_digits.parse_next(&mut input).unwrap();
//!     assert_eq!(input, " Hello");
//!     assert_eq!(output, "1a2b");
//!
//!     assert!(parse_digits.parse_next(&mut "Z").is_err());
//! }
//! ```
//!
//! See [`ascii`] for more text-based parsers.

#![allow(unused_imports)]
use crate::ascii;
use crate::ascii::hex_digit1;
use crate::stream::ContainsToken;
use crate::stream::Stream;
use crate::token;
use crate::token::any;
use crate::token::one_of;
use crate::token::tag;
use crate::token::take_while;
use crate::Parser;
use std::ops::RangeInclusive;

pub use super::chapter_1 as previous;
pub use super::chapter_3 as next;
pub use crate::_tutorial as table_of_contents;