use super::Warning;
struct Feature {
name: &'static str,
path: &'static str,
when: fn(roxmltree::Node) -> bool,
}
const FEATURES: &[Feature] = &[
Feature {
name: "a repeated <lanes> of one layer",
path: "lanes",
when: repeats_a_layer,
},
Feature {
name: "<roadSection>",
path: "roadSection",
when: not_in_a_crossing,
},
];
fn not_in_a_crossing(node: roxmltree::Node) -> bool {
node.parent_element()
.is_none_or(|p| p.attribute("type") != Some("crossing"))
}
fn repeats_a_layer(node: roxmltree::Node) -> bool {
let temporary = |n: &roxmltree::Node| n.attribute("layer") == Some("temporary");
node.prev_siblings()
.skip(1)
.any(|n| n.has_tag_name("lanes") && temporary(&n) == temporary(&node))
}
const NO_ID: &str = "(no id)";
fn leaf(path: &str) -> &str {
path.rsplit('/').next().unwrap_or(path)
}
fn matches_trail(feature: &Feature, trail: &[&str]) -> bool {
match feature.path.strip_prefix("**/") {
Some(_) => true,
None => feature.path.split('/').eq(trail.iter().copied()),
}
}
fn visit<'a>(node: roxmltree::Node<'a, 'a>, trail: &mut Vec<&'a str>, counts: &mut [usize]) {
let name = node.tag_name().name();
trail.push(match name {
"left" | "right" => "side",
name => name,
});
for (count, feature) in counts.iter_mut().zip(FEATURES) {
if leaf(feature.path) == name && matches_trail(feature, trail) && (feature.when)(node) {
*count += 1;
}
}
if name != "userData" {
for child in node.children().filter(|n| n.is_element()) {
visit(child, trail, counts);
}
}
trail.pop();
}
fn scan<'a>(
nodes: impl Iterator<Item = roxmltree::Node<'a, 'a>>,
ids: (&str, &str),
out: &mut Vec<Warning>,
) {
let mut counts = vec![0usize; FEATURES.len()];
let mut trail = Vec::new();
for node in nodes.filter(|n| n.is_element()) {
visit(node, &mut trail, &mut counts);
}
for (feature, count) in FEATURES.iter().zip(counts) {
if count > 0 {
out.push(Warning::Ignored {
road_id: ids.0.to_string(),
junction_id: ids.1.to_string(),
feature: feature.name.to_string(),
count,
});
}
}
}
pub(super) fn place(root: roxmltree::Node) -> Vec<Warning> {
let mut out = Vec::new();
let others = root
.children()
.filter(|n| !n.has_tag_name("road") && !n.has_tag_name("junction"));
scan(others, ("", ""), &mut out);
for junction in root.children().filter(|n| n.has_tag_name("junction")) {
let id = junction.attribute("id").unwrap_or(NO_ID);
scan(junction.children(), ("", id), &mut out);
}
for road in root.children().filter(|n| n.has_tag_name("road")) {
let id = road.attribute("id").unwrap_or(NO_ID);
scan(road.children(), (id, ""), &mut out);
}
out
}