typeward 0.6.0

A type-driven parser combinator library for Rust.
Documentation
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
//! Input types and traits for parsing.

mod bytes_input;
mod read_input_buf;
mod read_input_stream;
mod shared;
mod str_input;

use std::borrow::Cow;

pub use read_input_buf::{ReadInput, ReadInputBuf};
pub use read_input_stream::{ReadInputStream, ReadInputStreamInput};

use crate::error::{ParseError, ParseResult};
use stable_pattern::Pattern;

/// Abstract parser input that supports consuming textual prefixes.
///
/// This trait is implemented for both borrowed and streaming input forms.
/// Unlike iterator-style inputs, an `Input` is a cheap, copyable cursor: it
/// must be `Copy`, so any shared state (buffers, readers, cursors) should live
/// behind references or interior mutability.
///
/// Implementing this trait for a custom source requires only four methods:
///
/// - [`Input::input_len`]
/// - [`Input::display`]
/// - [`Input::take_char`]
/// - [`Input::slice_to`]
///
/// Everything else has a working default. Override [`Input::position`] if you
/// want accurate spans and offsets, and override any other method when you can
/// provide a faster or more precise implementation.
///
/// # Borrowed vs streaming inputs
///
/// Borrowed inputs (`&str`, `&[u8]`, [`ReadInput`]) can return text borrowed
/// directly from the source and therefore also implement [`BorrowInput`].
///
/// Streaming inputs ([`ReadInputStream`]) may need to reuse their internal
/// buffer, so their text results are always owned. They also expose fallible
/// variants such as [`Input::try_trim_start`] because reads can fail; the
/// infallible [`Input::trim_start`] keeps the input unchanged if that happens.
///
/// # Example
///
/// ```
/// use std::borrow::Cow;
/// use typeward::error::ParseResult;
/// use typeward::input::Input;
///
/// #[derive(Clone, Copy)]
/// struct MyInput<'a>(&'a str);
///
/// impl<'a> Input<'a> for MyInput<'a> {
///     fn input_len(self) -> usize {
///         self.0.len()
///     }
///
///     fn display(self) -> Cow<'a, str> {
///         self.0.into()
///     }
///
///     fn take_char(self) -> ParseResult<Option<(char, Self)>> {
///         let mut chars = self.0.chars();
///         Ok(chars.next().map(|ch| (ch, Self(chars.as_str()))))
///     }
///
///     fn slice_to(self, end: Self) -> ParseResult<Self> {
///         let consumed = self.0.len() - end.0.len();
///         Ok(Self(&self.0[..consumed]))
///     }
/// }
///
/// let (value, rest): (String, _) =
///     typeward::parse::Parse::parse(MyInput("hello world")).unwrap();
/// assert_eq!(value, "hello");
/// assert_eq!(rest.0, " world");
/// ```
pub trait Input<'a>: Copy + Sized {
    /// Returns the number of remaining units in the input.
    ///
    /// Borrowed inputs usually report an exact byte length. Streaming inputs
    /// cannot know it before reaching the end, so they report a lower bound and
    /// [`Self::remaining_len`] returns `None` instead. Prefer
    /// [`Self::remaining_len`] when an exact length or `None` is required.
    fn input_len(self) -> usize;

    /// Returns a stable absolute position for this input when one is available.
    ///
    /// The value only needs to be comparable with positions returned by other
    /// inputs from the same source. Built-in borrowed inputs use the address of
    /// the underlying bytes; streaming inputs use their absolute offset.
    /// Inputs that cannot expose a stable position may return `None`.
    fn position(self) -> Option<usize> {
        None
    }

    /// Returns the number of remaining bytes when it can be known without
    /// buffering additional input.
    ///
    /// The default mirrors [`Self::input_len`]. Streaming inputs return `None`
    /// until their end is known instead of exposing the sentinel length used by
    /// `input_len`.
    fn remaining_len(self) -> Option<usize> {
        Some(self.input_len())
    }

    /// Returns the remaining input as a debug-friendly string.
    fn display(self) -> Cow<'a, str>;

    /// Takes the first character and returns it with the remaining input.
    ///
    /// Returns `Ok(None)` at the end of input. Streaming inputs may buffer more
    /// data to decode a multi-byte character.
    fn take_char(self) -> ParseResult<Option<(char, Self)>>;

    /// Trims leading whitespace and returns the remaining input.
    ///
    /// On streaming inputs a read failure leaves the input unchanged; use
    /// [`Self::try_trim_start`] when the failure must be reported.
    #[must_use]
    fn trim_start(self) -> Self {
        self.try_trim_start().unwrap_or(self)
    }

    /// Fallible variant of [`Self::trim_start`].
    ///
    /// Stream-backed inputs override this so read and decoding failures are not
    /// silently treated as "no whitespace".
    fn try_trim_start(self) -> ParseResult<Self> {
        let (_, rest) = self.take_while(|c: char| c.is_whitespace())?;
        Ok(rest)
    }

    /// Returns true when no input remains.
    ///
    /// On streaming inputs a read failure is treated as "input remains"; use
    /// [`Self::try_is_empty`] when the failure must be reported.
    fn is_empty(self) -> bool {
        self.try_is_empty().unwrap_or(false)
    }

    /// Fallible variant of [`Self::is_empty`].
    ///
    /// Stream-backed inputs override this so read and decoding failures are not
    /// silently treated as "input remains".
    fn try_is_empty(self) -> ParseResult<bool> {
        Ok(self.take_char()?.is_none())
    }

    /// Attempts to strip a literal prefix and returns remaining input on success.
    fn strip_prefix(self, prefix: &str) -> ParseResult<Option<Self>> {
        let mut rest = self;
        for expected in prefix.chars() {
            match rest.take_char()? {
                Some((found, next)) if found == expected => rest = next,
                Some(_) | None => return Ok(None),
            }
        }
        Ok(Some(rest))
    }

    /// Advances the input by `bytes` and returns the remaining input.
    ///
    /// Implementations should return an error if `bytes` exceeds the remaining
    /// input length or violates input encoding boundaries.
    fn advance(self, bytes: usize) -> ParseResult<Self> {
        let mut rest = self;
        let mut remaining = bytes;

        while remaining > 0 {
            let Some((ch, next)) = rest.take_char()? else {
                return Err(ParseError::fatal(
                    "invalid input bounds while advancing input",
                ));
            };

            let width = ch.len_utf8();
            if width > remaining {
                return Err(ParseError::fatal(
                    "invalid UTF-8 boundary while advancing input",
                ));
            }

            remaining -= width;
            rest = next;
        }

        Ok(rest)
    }

    /// Finds the next occurrence of `needle` and returns input starting at that match.
    fn find(self, needle: &str) -> ParseResult<Option<Self>> {
        let mut rest = self;

        loop {
            if rest.strip_prefix(needle)?.is_some() {
                return Ok(Some(rest));
            }

            match rest.take_char()? {
                Some((_, next)) => rest = next,
                None => return Ok(None),
            }
        }
    }

    /// Returns the input segment from `self` up to (but excluding) `end`.
    ///
    /// Both values must be suffixes of the same original input.
    fn slice_to(self, end: Self) -> ParseResult<Self>;

    /// Takes exactly one character or reports unexpected end of input.
    fn take_char1(self) -> ParseResult<(char, Self)> {
        match self.take_char()? {
            Some(value) => Ok(value),
            None => Err(ParseError::UnexpectedEOF),
        }
    }

    /// Consumes a maximal prefix matching `predicate`.
    ///
    /// Returns the matched prefix and remaining input. The matched prefix may be
    /// borrowed or owned depending on the input implementation.
    ///
    /// The default implementation inspects the pattern one character at a time.
    /// Override it when you can support multi-character patterns directly.
    ///
    /// Streaming inputs also evaluate the pattern per character, so use a
    /// `char`, character predicate, or single-character string there.
    fn take_while<P>(self, predicate: P) -> ParseResult<(Cow<'a, str>, Self)>
    where
        P: for<'b> Pattern<'b> + Copy,
    {
        // A pattern that matches the empty string must not consume input.
        if predicate.strip_prefix_of("").is_some() {
            return Ok((Cow::Owned(String::new()), self));
        }

        let mut matched = String::new();
        let mut rest = self;

        while let Some((ch, next)) = rest.take_char()? {
            let mut encoded = [0_u8; 4];
            let ch_str = ch.encode_utf8(&mut encoded);
            if predicate.strip_prefix_of(ch_str).is_some() {
                matched.push(ch);
                rest = next;
            } else {
                break;
            }
        }

        Ok((Cow::Owned(matched), rest))
    }

    /// Consumes a non-empty maximal prefix matching `predicate`.
    fn take_while1<P>(self, predicate: P) -> ParseResult<(Cow<'a, str>, Self)>
    where
        P: for<'b> Pattern<'b> + Copy,
    {
        let (value, rest) = self.take_while(predicate)?;
        if value.is_empty() {
            return Err(ParseError::custom(
                "expected at least one matching character",
            ));
        }
        Ok((value, rest))
    }

    /// Consumes a prefix until `predicate` matches.
    ///
    /// Returns the consumed prefix and remaining input. The consumed prefix may be
    /// borrowed or owned depending on the input implementation.
    ///
    /// The default implementation inspects the pattern one character at a time.
    /// Override it when you can support multi-character patterns directly, or
    /// prefer [`Self::take_till_str`] for literal delimiters.
    fn take_till<P>(self, predicate: P) -> ParseResult<(Cow<'a, str>, Self)>
    where
        P: for<'b> Pattern<'b> + Copy,
    {
        // A pattern that matches the empty string stops before consuming input.
        if predicate.strip_prefix_of("").is_some() {
            return Ok((Cow::Owned(String::new()), self));
        }

        let mut matched = String::new();
        let mut rest = self;

        while let Some((ch, next)) = rest.take_char()? {
            let mut encoded = [0_u8; 4];
            let ch_str = ch.encode_utf8(&mut encoded);
            if predicate.strip_prefix_of(ch_str).is_some() {
                break;
            }

            matched.push(ch);
            rest = next;
        }

        Ok((Cow::Owned(matched), rest))
    }

    /// Consumes a prefix until the literal `needle` matches.
    ///
    /// This is the literal-string counterpart to [`Self::take_till`]. The
    /// default uses [`Self::find`], so it supports multi-character delimiters
    /// even when the input only provides [`Self::take_char`]. Inputs that can
    /// search incrementally should override it so they do not have to buffer
    /// the entire remaining source.
    fn take_till_str(self, needle: &str) -> ParseResult<(Cow<'a, str>, Self)> {
        if needle.is_empty() {
            return Ok((Cow::Owned(String::new()), self));
        }

        match self.find(needle)? {
            Some(end) => {
                let (matched, _) = self.slice_to(end)?.take_while(|_: char| true)?;
                Ok((matched, end))
            }
            None => self.take_while(|_: char| true),
        }
    }

    /// Consumes a non-empty prefix until `predicate` matches.
    fn take_till1<P>(self, predicate: P) -> ParseResult<(Cow<'a, str>, Self)>
    where
        P: for<'b> Pattern<'b> + Copy,
    {
        let (value, rest) = self.take_till(predicate)?;
        if value.is_empty() {
            return Err(ParseError::custom(
                "expected at least one character before the delimiter",
            ));
        }
        Ok((value, rest))
    }
}

/// Marker trait for inputs whose matched text can be borrowed from the source.
///
/// Parsers that yield borrowed values (for example `&'a str`) should require
/// this trait instead of plain [`Input`].
pub trait BorrowInput<'a>: Input<'a> {
    /// Consumes a maximal prefix matching `predicate` and returns a borrowed match.
    fn take_while_borrowed<P>(self, predicate: P) -> ParseResult<(&'a str, Self)>
    where
        P: for<'b> Pattern<'b> + Copy;

    /// Consumes a prefix until `predicate` matches and returns a borrowed match.
    fn take_till_borrowed<P>(self, predicate: P) -> ParseResult<(&'a str, Self)>
    where
        P: for<'b> Pattern<'b> + Copy;
}

/// Converts a textual fragment produced by an [`Input`] into a parser output type.
///
/// This enables a single parser implementation to support both borrowed outputs
/// on [`BorrowInput`] and owned outputs on streaming-friendly [`Input`] types.
pub trait FromInputStr<'a, I>: AsRef<str> + Sized
where
    I: Input<'a>,
{
    /// Converts a textual fragment into the output type.
    fn from_input_str(value: Cow<'a, str>) -> ParseResult<Self>;
}

impl<'a, I> FromInputStr<'a, I> for String
where
    I: Input<'a>,
{
    fn from_input_str(value: Cow<'a, str>) -> ParseResult<Self> {
        Ok(value.into_owned())
    }
}

impl<'a, I> FromInputStr<'a, I> for Cow<'a, str>
where
    I: Input<'a>,
{
    fn from_input_str(value: Cow<'a, str>) -> ParseResult<Self> {
        Ok(value)
    }
}

impl<'a, I> FromInputStr<'a, I> for &'a str
where
    I: BorrowInput<'a>,
{
    fn from_input_str(value: Cow<'a, str>) -> ParseResult<Self> {
        match value {
            Cow::Borrowed(value) => Ok(value),
            Cow::Owned(_) => Err(ParseError::custom(
                "borrowed output requires borrow-capable input",
            )),
        }
    }
}

#[cfg(test)]
mod tests;