use crate::cst::{
children_of, kind_of, new_node, push_child, set_children, set_extra, span_of, Item,
};
fn is_opener(directive: &str) -> bool {
matches!(directive, "if" | "ifdef" | "ifndef")
}
fn is_branch(directive: &str) -> bool {
matches!(directive, "elif" | "elifdef" | "elifndef" | "else")
}
fn leading_conditional_directive(item: &Item) -> Option<(usize, String)> {
let node = item.as_node()?;
if kind_of(node) != "external_declaration" {
return None;
}
for child in children_of(node) {
let Some(child_node) = child.as_node() else {
continue;
};
if kind_of(child_node) == "conditional_directive" {
let directive = crate::cst::extra_of(child_node, "directive")
.and_then(|item| match item {
Item::Val(tabnas::Value::String(text)) => Some(text),
_ => None,
})
.unwrap_or_default();
return Some((child_node, directive));
}
}
None
}
pub fn structure_conditional_groups(parent: usize) {
structure_from(parent, &mut std::collections::HashSet::new());
}
fn structure_from(root: usize, seen: &mut std::collections::HashSet<usize>) {
let mut pending = vec![root];
while let Some(parent) = pending.pop() {
if !seen.insert(parent) {
continue;
}
let out = fold_children(parent);
pending.extend(
out.iter()
.rev()
.filter_map(Item::as_node)
.filter(|node| !kind_of(*node).is_empty()),
);
}
}
fn fold_children(parent: usize) -> Vec<Item> {
let children = children_of(parent);
let matches = index_conditional_groups(&children);
let out = fold_range(&children, 0, children.len(), &matches);
set_children(parent, out.clone());
out
}
#[derive(Debug)]
struct ConditionalMatch {
end: usize,
branches: Vec<usize>,
}
#[derive(Debug)]
struct ConditionalFrame {
open: usize,
branches: Vec<usize>,
}
fn index_conditional_groups(
children: &[Item],
) -> std::collections::HashMap<usize, ConditionalMatch> {
let mut matches = std::collections::HashMap::new();
let mut stack: Vec<ConditionalFrame> = Vec::new();
for (index, child) in children.iter().enumerate() {
let Some((_, word)) = leading_conditional_directive(child) else {
continue;
};
if is_opener(&word) {
stack.push(ConditionalFrame {
open: index,
branches: Vec::new(),
});
} else if is_branch(&word) {
if let Some(frame) = stack.last_mut() {
frame.branches.push(index);
}
} else if word == "endif" {
if let Some(frame) = stack.pop() {
matches.insert(
frame.open,
ConditionalMatch {
end: index,
branches: frame.branches,
},
);
}
}
}
matches
}
fn fold_range(
children: &[Item],
from: usize,
to: usize,
matches: &std::collections::HashMap<usize, ConditionalMatch>,
) -> Vec<Item> {
let mut out = Vec::with_capacity(to - from);
let mut index = from;
while index < to {
if let Some(group_match) = matches
.get(&index)
.filter(|group_match| group_match.end < to)
{
out.push(Item::Node(build_conditional_group(
children,
index,
group_match,
matches,
)));
index = group_match.end + 1;
} else {
out.push(children[index].clone());
index += 1;
}
}
out
}
fn build_conditional_group(
children: &[Item],
from: usize,
group_match: &ConditionalMatch,
matches: &std::collections::HashMap<usize, ConditionalMatch>,
) -> usize {
let group_span = children[from]
.as_node()
.map(span_of)
.unwrap_or_else(crate::cst::Span::zero);
let group = new_node("conditional_group", Some(group_span));
let mut starts = Vec::with_capacity(group_match.branches.len() + 1);
starts.push(from);
starts.extend(group_match.branches.iter().copied());
for (index, start) in starts.iter().copied().enumerate() {
let end = starts.get(index + 1).copied().unwrap_or(group_match.end);
push_child(
group,
Item::Node(build_branch(children, start, end, matches)),
);
}
set_extra(group, "endif", children[group_match.end].clone());
push_child(group, children[group_match.end].clone());
group
}
fn build_branch(
children: &[Item],
from: usize,
to: usize,
matches: &std::collections::HashMap<usize, ConditionalMatch>,
) -> usize {
let head = children[from].clone();
let head_span = head
.as_node()
.map(span_of)
.unwrap_or_else(crate::cst::Span::zero);
let branch = new_node("conditional_branch", Some(head_span));
let word = leading_conditional_directive(&head)
.map(|(_, word)| word)
.unwrap_or_else(|| "unknown".to_string());
set_extra(branch, "branchKind", Item::str(word));
set_extra(branch, "directive", head.clone());
let mut final_children = vec![head];
final_children.extend(fold_range(children, from + 1, to, matches));
set_children(branch, final_children);
branch
}