2018-01-01 13:10:56 +01:00
|
|
|
use {Token, File, FileBuilder, Sink, SyntaxKind};
|
2017-12-31 15:54:33 +01:00
|
|
|
|
2017-12-31 21:34:29 +01:00
|
|
|
use syntax_kinds::*;
|
|
|
|
|
2018-01-01 13:10:56 +01:00
|
|
|
mod event_parser;
|
|
|
|
use self::event_parser::Event;
|
|
|
|
|
2017-12-31 21:34:29 +01:00
|
|
|
|
|
|
|
pub fn parse(text: String, tokens: &[Token]) -> File {
|
2018-01-01 13:10:56 +01:00
|
|
|
let events = event_parser::parse(&text, tokens);
|
2018-01-01 20:13:04 +01:00
|
|
|
from_events_to_file(text, tokens, events)
|
2018-01-01 13:10:56 +01:00
|
|
|
}
|
|
|
|
|
2018-01-01 20:13:04 +01:00
|
|
|
fn from_events_to_file(
|
|
|
|
text: String,
|
|
|
|
tokens: &[Token],
|
|
|
|
events: Vec<Event>,
|
|
|
|
) -> File {
|
2017-12-31 21:34:29 +01:00
|
|
|
let mut builder = FileBuilder::new(text);
|
2018-01-01 20:13:04 +01:00
|
|
|
let mut idx = 0;
|
2018-01-01 13:10:56 +01:00
|
|
|
for event in events {
|
|
|
|
match event {
|
|
|
|
Event::Start { kind } => builder.start_internal(kind),
|
2018-01-01 20:13:04 +01:00
|
|
|
Event::Finish => {
|
|
|
|
while idx < tokens.len() {
|
|
|
|
let token = tokens[idx];
|
|
|
|
if is_insignificant(token.kind) {
|
|
|
|
idx += 1;
|
|
|
|
builder.leaf(token.kind, token.len);
|
|
|
|
} else {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
builder.finish_internal()
|
|
|
|
},
|
|
|
|
Event::Token { kind, mut n_raw_tokens } => loop {
|
|
|
|
let token = tokens[idx];
|
|
|
|
if !is_insignificant(token.kind) {
|
|
|
|
n_raw_tokens -= 1;
|
|
|
|
}
|
|
|
|
idx += 1;
|
|
|
|
builder.leaf(token.kind, token.len);
|
|
|
|
if n_raw_tokens == 0 {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
},
|
2018-01-01 13:10:56 +01:00
|
|
|
}
|
|
|
|
}
|
2017-12-31 21:34:29 +01:00
|
|
|
builder.finish()
|
2018-01-01 13:10:56 +01:00
|
|
|
}
|
2018-01-01 20:13:04 +01:00
|
|
|
|
|
|
|
fn is_insignificant(kind: SyntaxKind) -> bool {
|
|
|
|
match kind {
|
|
|
|
WHITESPACE | COMMENT => true,
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|