rust/src/yellow/builder.rs

63 lines
1.6 KiB
Rust
Raw Normal View History

2018-07-29 05:51:55 -05:00
use {
2018-07-31 15:38:19 -05:00
parser_impl::Sink,
2018-07-30 06:08:06 -05:00
yellow::{GreenNode, GreenNodeBuilder, 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-07-29 08:19:16 -05:00
stack: Vec<GreenNodeBuilder>,
2018-07-29 05:51:55 -05:00
pos: TextUnit,
root: Option<GreenNode>,
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,
stack: Vec::new(),
pos: 0.into(),
root: None,
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];
let leaf = GreenNodeBuilder::new_leaf(kind, text);
2018-07-29 05:51:55 -05:00
let parent = self.stack.last_mut().unwrap();
2018-07-29 08:19:16 -05:00
parent.push_child(leaf)
2018-07-29 05:51:55 -05:00
}
fn start_internal(&mut self, kind: SyntaxKind) {
2018-07-29 08:19:16 -05:00
self.stack.push(GreenNodeBuilder::new_internal(kind))
2018-07-29 05:51:55 -05:00
}
fn finish_internal(&mut self) {
2018-07-29 08:19:16 -05:00
let builder = self.stack.pop().unwrap();
let node = builder.build();
2018-07-29 05:51:55 -05:00
if let Some(parent) = self.stack.last_mut() {
2018-07-29 08:19:16 -05:00
parent.push_child(node);
2018-07-29 05:51:55 -05:00
} else {
self.root = Some(node);
}
}
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
fn finish(self) -> SyntaxNode {
let root = SyntaxRoot::new(self.root.unwrap(), self.errors);
SyntaxNode::new_owned(root)
2018-07-29 05:51:55 -05:00
}
}