2018-07-29 05:51:55 -05:00
|
|
|
use {
|
2018-07-31 15:38:19 -05:00
|
|
|
parser_impl::Sink,
|
2018-08-08 13:14:18 -05:00
|
|
|
yellow::{GreenNode, SyntaxError, SyntaxNode, SyntaxRoot},
|
2018-07-29 05:51:55 -05:00
|
|
|
SyntaxKind, TextRange, TextUnit,
|
|
|
|
};
|
|
|
|
|
2018-08-01 02:40:07 -05:00
|
|
|
pub(crate) struct GreenBuilder<'a> {
|
|
|
|
text: &'a str,
|
2018-08-08 13:14:18 -05:00
|
|
|
parents: Vec<(SyntaxKind, usize)>,
|
|
|
|
children: Vec<GreenNode>,
|
2018-07-29 05:51:55 -05:00
|
|
|
pos: TextUnit,
|
2018-07-29 07:16:07 -05:00
|
|
|
errors: Vec<SyntaxError>,
|
2018-07-29 05:51:55 -05:00
|
|
|
}
|
|
|
|
|
2018-08-01 02:40:07 -05:00
|
|
|
impl<'a> Sink<'a> for GreenBuilder<'a> {
|
2018-07-29 07:16:07 -05:00
|
|
|
type Tree = SyntaxNode;
|
|
|
|
|
2018-08-01 02:40:07 -05:00
|
|
|
fn new(text: &'a str) -> Self {
|
2018-07-29 05:51:55 -05:00
|
|
|
GreenBuilder {
|
|
|
|
text,
|
2018-08-08 13:14:18 -05:00
|
|
|
parents: Vec::new(),
|
|
|
|
children: Vec::new(),
|
2018-07-29 05:51:55 -05: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 08:19:16 -05:00
|
|
|
let text = &self.text[range];
|
2018-08-08 13:14:18 -05:00
|
|
|
self.children.push(
|
|
|
|
GreenNode::new_leaf(kind, text)
|
|
|
|
);
|
2018-07-29 05:51:55 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn start_internal(&mut self, kind: SyntaxKind) {
|
2018-08-08 13:14:18 -05:00
|
|
|
let len = self.children.len();
|
|
|
|
self.parents.push((kind, len));
|
2018-07-29 05:51:55 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn finish_internal(&mut self) {
|
2018-08-08 13:14:18 -05:00
|
|
|
let (kind, first_child) = self.parents.pop().unwrap();
|
|
|
|
let children = self.children
|
|
|
|
.drain(first_child..)
|
|
|
|
.collect();
|
|
|
|
self.children.push(
|
|
|
|
GreenNode::new_branch(kind, children)
|
|
|
|
);
|
2018-07-29 05:51:55 -05:00
|
|
|
}
|
|
|
|
|
2018-07-29 06:37:48 -05:00
|
|
|
fn error(&mut self, message: String) {
|
2018-07-30 06:08:06 -05:00
|
|
|
self.errors.push(SyntaxError {
|
|
|
|
message,
|
|
|
|
offset: self.pos,
|
|
|
|
})
|
2018-07-29 05:51:55 -05:00
|
|
|
}
|
2018-07-29 07:16:07 -05:00
|
|
|
|
2018-08-08 13:14:18 -05:00
|
|
|
fn finish(mut self) -> SyntaxNode {
|
|
|
|
assert_eq!(self.children.len(), 1);
|
|
|
|
let root = self.children.pop().unwrap();
|
|
|
|
let root = SyntaxRoot::new(root, self.errors);
|
2018-07-29 19:21:17 -05:00
|
|
|
SyntaxNode::new_owned(root)
|
2018-07-29 05:51:55 -05:00
|
|
|
}
|
|
|
|
}
|