aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_syntax/src/yellow/builder.rs
blob: 35dbaec05bd563df381ff048fbb7511372166dba (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
use rowan::GreenNodeBuilder;
use {
    parser_impl::Sink,
    yellow::{GreenNode, SyntaxError, RaTypes},
    SyntaxKind, TextRange, TextUnit,
};

pub(crate) struct GreenBuilder<'a> {
    text: &'a str,
    pos: TextUnit,
    errors: Vec<SyntaxError>,
    inner: GreenNodeBuilder<RaTypes>,
}

impl<'a> Sink<'a> for GreenBuilder<'a> {
    type Tree = (GreenNode, Vec<SyntaxError>);

    fn new(text: &'a str) -> Self {
        GreenBuilder {
            text,
            pos: 0.into(),
            errors: Vec::new(),
            inner: GreenNodeBuilder::new(),
        }
    }

    fn leaf(&mut self, kind: SyntaxKind, len: TextUnit) {
        let range = TextRange::offset_len(self.pos, len);
        self.pos += len;
        let text = self.text[range].into();
        self.inner.leaf(kind, text);
    }

    fn start_internal(&mut self, kind: SyntaxKind) {
        self.inner.start_internal(kind)
    }

    fn finish_internal(&mut self) {
        self.inner.finish_internal();
    }

    fn error(&mut self, message: String) {
        self.errors.push(SyntaxError {
            msg: message,
            offset: self.pos,
        })
    }

    fn finish(self) -> (GreenNode, Vec<SyntaxError>) {
        (self.inner.finish(), self.errors)
    }
}