use crate::syntax::layout_of;
use crate::syntax::meta::{Layout, LayoutItem, LayoutItemKind, List};
use crate::syntax::node::{SyntaxElement, SyntaxNode};
use crate::syntax::node_kind::NodeKind;
use crate::syntax::validate::error::{Missing, ValidationError};
pub(crate) fn check_node(node: &SyntaxNode, err: &mut ValidationError) {
match layout_of(node.kind()) {
Layout::Sequence(seq) => {
debug_assert_eq!(node.kind(), seq.kind);
match_children(node, seq.items, err);
}
Layout::List(list) => match_list(node, list, err),
Layout::Choice(_) => debug_assert!(
false,
"{:?} has a choice layout but was materialized as a node",
node.kind()
),
}
}
fn match_list(node: &SyntaxNode, list: &List, err: &mut ValidationError) {
let mut expect_element = true;
let mut previous: Option<SyntaxElement> = None;
let mut saw_any = false;
for child in node.children_with_tokens() {
let is_element = accepts(list.element, &child);
let is_separator = accepts(list.separator, &child);
if !is_element && !is_separator {
err.push_extraneous(child);
continue;
}
let as_element = if expect_element {
is_element
} else {
!is_separator
};
if as_element != expect_element {
let expected = if expect_element {
list.element
} else {
list.separator
};
err.push_missing(Missing::new(previous.clone(), node.clone(), *expected));
}
expect_element = !as_element;
previous = Some(child);
saw_any = true;
}
if !saw_any {
err.push_missing(Missing::new(None, node.clone(), *list.element));
} else if expect_element {
err.push_missing(Missing::new(previous, node.clone(), *list.element));
}
}
fn match_children(node: &SyntaxNode, items: &[LayoutItem], err: &mut ValidationError) {
let mut pos = 0usize;
let mut filled: Vec<Option<SyntaxElement>> = vec![None; items.len()];
for child in node.children_with_tokens() {
match (pos..items.len()).find(|&j| accepts(&items[j], &child)) {
Some(k) => {
pos = if items[k].repeated { k } else { k + 1 };
filled[k] = Some(child);
}
None => err.push_extraneous(child),
}
}
for (i, item) in items.iter().enumerate() {
if !item.optional && filled[i].is_none() {
let previous = (0..i).rev().find_map(|j| filled[j].clone());
err.push_missing(Missing::new(previous, node.clone(), *item));
}
}
}
fn accepts(item: &LayoutItem, child: &SyntaxElement) -> bool {
match (child, item.kind) {
(SyntaxElement::Token(t), LayoutItemKind::Token(k)) => t.kind() == k,
(SyntaxElement::Token(t), LayoutItemKind::TokenChoice(ks)) => ks.contains(&t.kind()),
(SyntaxElement::Node(n), LayoutItemKind::Node(k)) => node_satisfies(n.kind(), k),
(SyntaxElement::Node(n), LayoutItemKind::NodeChoice(ks)) => {
ks.iter().any(|&k| node_satisfies(n.kind(), k))
}
_ => false,
}
}
fn node_satisfies(actual: NodeKind, expected: NodeKind) -> bool {
if actual == expected {
return true;
}
match layout_of(expected) {
Layout::Choice(choice) => choice
.options
.iter()
.any(|&option| node_satisfies(actual, option)),
Layout::Sequence(_) | Layout::List(_) => false,
}
}