65 lines
1.6 KiB
Rust
Raw Normal View History

2018-07-29 13:51:55 +03:00
use {
2018-07-31 23:38:19 +03:00
parser_impl::Sink,
2018-08-25 12:10:35 +03:00
yellow::{GreenNode, SyntaxError},
2018-07-29 13:51:55 +03:00
SyntaxKind, TextRange, TextUnit,
};
2018-08-01 10:40:07 +03:00
pub(crate) struct GreenBuilder<'a> {
text: &'a str,
2018-08-08 21:14:18 +03:00
parents: Vec<(SyntaxKind, usize)>,
children: Vec<GreenNode>,
2018-07-29 13:51:55 +03:00
pos: TextUnit,
2018-07-29 15:16:07 +03:00
errors: Vec<SyntaxError>,
2018-07-29 13:51:55 +03:00
}
2018-08-01 10:40:07 +03:00
impl<'a> Sink<'a> for GreenBuilder<'a> {
2018-08-25 12:10:35 +03:00
type Tree = (GreenNode, Vec<SyntaxError>);
2018-07-29 15:16:07 +03:00
2018-08-01 10:40:07 +03:00
fn new(text: &'a str) -> Self {
2018-07-29 13:51:55 +03:00
GreenBuilder {
text,
2018-08-08 21:14:18 +03:00
parents: Vec::new(),
children: Vec::new(),
2018-07-29 13:51:55 +03:00
pos: 0.into(),
errors: Vec::new(),
}
}
fn leaf(&mut self, kind: SyntaxKind, len: TextUnit) {
let range = TextRange::offset_len(self.pos, len);
self.pos += len;
2018-07-29 16:19:16 +03:00
let text = &self.text[range];
2018-08-08 21:14:18 +03:00
self.children.push(
GreenNode::new_leaf(kind, text)
);
2018-07-29 13:51:55 +03:00
}
fn start_internal(&mut self, kind: SyntaxKind) {
2018-08-08 21:14:18 +03:00
let len = self.children.len();
self.parents.push((kind, len));
2018-07-29 13:51:55 +03:00
}
fn finish_internal(&mut self) {
2018-08-08 21:14:18 +03:00
let (kind, first_child) = self.parents.pop().unwrap();
2018-08-09 01:59:36 +03:00
let children: Vec<_> = self.children
2018-08-08 21:14:18 +03:00
.drain(first_child..)
.collect();
self.children.push(
2018-08-09 01:59:36 +03:00
GreenNode::new_branch(kind, children.into_boxed_slice())
2018-08-08 21:14:18 +03:00
);
2018-07-29 13:51:55 +03:00
}
2018-07-29 14:37:48 +03:00
fn error(&mut self, message: String) {
2018-07-30 14:08:06 +03:00
self.errors.push(SyntaxError {
2018-08-09 21:27:44 +03:00
msg: message,
2018-07-30 14:08:06 +03:00
offset: self.pos,
})
2018-07-29 13:51:55 +03:00
}
2018-07-29 15:16:07 +03:00
2018-08-25 12:10:35 +03:00
fn finish(mut self) -> (GreenNode, Vec<SyntaxError>) {
2018-08-08 21:14:18 +03:00
assert_eq!(self.children.len(), 1);
let root = self.children.pop().unwrap();
2018-08-25 12:10:35 +03:00
(root, self.errors)
2018-07-29 13:51:55 +03:00
}
}