genco/fmt/
cursor.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
use crate::fmt;
use crate::lang::Lang;
use crate::tokens::Item;

/// Trait for peeking items.
pub(super) trait Parse<L>
where
    L: Lang,
{
    type Output: ?Sized;

    /// Parse the given item into its output.
    fn parse(item: &Item<L>) -> fmt::Result<&Self::Output>;

    /// Test if the peek matches the given item.
    fn peek(item: &Item<L>) -> bool;
}

/// Peek for a literal.
pub(super) struct Literal(());

impl<L> Parse<L> for Literal
where
    L: Lang,
{
    type Output = str;

    #[inline]
    fn peek(item: &Item<L>) -> bool {
        matches!(item, Item::Literal(..))
    }

    #[inline]
    fn parse(item: &Item<L>) -> fmt::Result<&Self::Output> {
        match item {
            Item::Literal(s) => Ok(s),
            _ => Err(core::fmt::Error),
        }
    }
}

/// Peek for an eval marker.
pub(super) struct CloseEval(());

impl<L> Parse<L> for CloseEval
where
    L: Lang,
{
    type Output = ();

    #[inline]
    fn peek(item: &Item<L>) -> bool {
        matches!(item, Item::CloseEval)
    }

    #[inline]
    fn parse(item: &Item<L>) -> fmt::Result<&Self::Output> {
        match item {
            Item::CloseEval => Ok(&()),
            _ => Err(core::fmt::Error),
        }
    }
}

/// Parser helper.
pub(super) struct Cursor<'a, L>
where
    L: Lang,
{
    items: &'a [Item<L>],
}

impl<'a, L> Cursor<'a, L>
where
    L: Lang,
{
    pub(super) fn new(items: &'a [Item<L>]) -> Self {
        Self { items }
    }

    /// Get the next item.
    pub(super) fn next(&mut self) -> Option<&Item<L>> {
        let (first, rest) = self.items.split_first()?;
        self.items = rest;
        Some(first)
    }

    #[inline]
    pub(super) fn peek<P>(&self) -> bool
    where
        P: Parse<L>,
    {
        if let Some(item) = self.items.first() {
            P::peek(item)
        } else {
            false
        }
    }

    #[inline]
    pub(super) fn peek1<P>(&self) -> bool
    where
        P: Parse<L>,
    {
        if let Some(item) = self.items.get(1) {
            P::peek(item)
        } else {
            false
        }
    }

    #[inline]
    pub(super) fn parse<P>(&mut self) -> fmt::Result<&P::Output>
    where
        P: Parse<L>,
    {
        let item = self.next().ok_or(core::fmt::Error)?;
        P::parse(item)
    }
}