mylang_lexer/
with_pos.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
//! 文字のイテレータを「位置・文字ペア」のイテレータに変換するアダプタ

use mylang_token::Pos;

pub struct WithPos<I>
where
    I: Iterator<Item = char> + Sized,
{
    pos: Pos,
    chars: I,
}

impl<I> Iterator for WithPos<I>
where
    I: Iterator<Item = char>,
{
    type Item = (Pos, char);

    fn next(&mut self) -> Option<Self::Item> {
        self.chars.next().map(|c| {
            let prev_pos = self.pos.clone();

            if c == '\n' {
                self.pos.next_line();
            } else {
                self.pos.next_char();
            }

            (prev_pos, c)
        })
    }
}

pub trait WithPosExt: Iterator<Item = char> + Sized {
    fn with_pos(self) -> WithPos<Self>;
}

impl<I> WithPosExt for I
where
    I: Iterator<Item = char> + Sized,
{
    fn with_pos(self) -> WithPos<Self> {
        WithPos {
            pos: Pos::default(),
            chars: self,
        }
    }
}