aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_syntax/src/parsing/builder.rs
blob: ee0e2cce7ae5f2a1a341ba33e8004ffa319c7823 (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
use crate::{
    SmolStr, SyntaxKind, SyntaxError, SyntaxErrorKind, TextUnit,
    parsing::{TreeSink, ParseError},
    syntax_node::{GreenNode, RaTypes},
};

use rowan::GreenNodeBuilder;

pub(crate) struct GreenBuilder {
    text_pos: TextUnit,
    errors: Vec<SyntaxError>,
    inner: GreenNodeBuilder<RaTypes>,
}

impl Default for GreenBuilder {
    fn default() -> GreenBuilder {
        GreenBuilder {
            text_pos: TextUnit::default(),
            errors: Vec::new(),
            inner: GreenNodeBuilder::new(),
        }
    }
}

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

    fn leaf(&mut self, kind: SyntaxKind, text: SmolStr) {
        self.text_pos += TextUnit::of_str(text.as_str());
        self.inner.leaf(kind, text);
    }

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

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

    fn error(&mut self, error: ParseError) {
        let error = SyntaxError::new(SyntaxErrorKind::ParseError(error), self.text_pos);
        self.errors.push(error)
    }

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