use std::path::Path;
use crate::Visibility;
use crate::cache::summary::SummaryGuards;
use crate::preprocess::condition::MacroValues;
use super::Over;
use super::{Env, Skeleton, Step, skeleton::Action};
pub const MAX_DEPTH: usize = 200;
#[derive(Debug, Clone)]
pub struct Composed {
pub final_env: Env,
pub after_each_include: Vec<(usize, Env)>,
pub unknown_guards: usize,
pub unresolved_includes: usize,
pub depth_exceeded: usize,
pub unknown: Vec<(usize, String)>,
pub skipped_includes: Vec<(usize, String, &'static str, String)>,
}
pub const UNKNOWN_EXAMPLES: usize = 64;
fn guard_text(guards: &SummaryGuards, guard: crate::FactGuard) -> String {
let crate::FactGuard::Region(region) = guard else {
return "unconditional".to_string();
};
let mut parts: Vec<String> = Vec::new();
let mut current = Some(region);
while let Some(index) = current {
let Some(conditional) = guards.conditionals.get(index as usize) else {
break;
};
if let Some(branch) = conditional.branches.first() {
parts.push(format!(
"{:?} {}",
branch.kind,
branch.condition.as_deref().unwrap_or("")
));
}
current = conditional.parent;
}
parts.join(" && ")
}
fn step_label(step: &Step) -> String {
match &step.action {
Action::Define(definition) => definition.name().to_string(),
Action::Undef(name) => name.to_string(),
Action::Include(include) => include.path.display().to_string(),
}
}
pub trait IncludeHandler {
fn include(&mut self, path: &Path, env: &Env, depth: usize) -> Option<Env>;
}
pub fn compose(
skeleton: &Skeleton,
guards: &SummaryGuards,
incoming: &Env,
seed: &dyn MacroValues,
look_up: &mut impl FnMut(&Path) -> Option<(Skeleton, SummaryGuards)>,
) -> Composed {
fold(
skeleton,
guards,
incoming,
seed,
&mut Nested { seed, look_up },
0,
)
}
struct Nested<'a> {
seed: &'a dyn MacroValues,
look_up: &'a mut dyn FnMut(&Path) -> Option<(Skeleton, SummaryGuards)>,
}
impl IncludeHandler for Nested<'_> {
fn include(&mut self, path: &Path, env: &Env, depth: usize) -> Option<Env> {
let (skeleton, guards) = (self.look_up)(path)?;
Some(fold(&skeleton, &guards, env, self.seed, self, depth + 1).final_env)
}
}
pub(crate) fn fold(
skeleton: &Skeleton,
guards: &SummaryGuards,
incoming: &Env,
seed: &dyn MacroValues,
handler: &mut dyn IncludeHandler,
depth: usize,
) -> Composed {
Fold {
env: incoming.clone(),
history: vec![(0, incoming.clone())],
after_each_include: Vec::new(),
unknown_guards: 0,
unknown: Vec::new(),
skipped_includes: Vec::new(),
depth_exceeded: 0,
seed,
handler,
depth,
}
.run(skeleton, guards)
}
struct Fold<'a> {
env: Env,
history: Vec<(usize, Env)>,
after_each_include: Vec<(usize, Env)>,
unknown_guards: usize,
unknown: Vec<(usize, String)>,
skipped_includes: Vec<(usize, String, &'static str, String)>,
depth_exceeded: usize,
seed: &'a dyn MacroValues,
handler: &'a mut dyn IncludeHandler,
depth: usize,
}
impl Fold<'_> {
fn run(mut self, skeleton: &Skeleton, guards: &SummaryGuards) -> Composed {
let held = guards.own_guard_holds(&self.env);
if held != Some(true) {
if held.is_none() {
self.unknown_guards += 1;
}
return self.finish(skeleton);
}
for step in skeleton.steps() {
let visibility = guards.visibility_of(step.guard, step.at, |condition_at| {
Over::new(self.env_at(condition_at), self.seed)
});
if let Some(wanted) = crate::probes::step_name()
&& step_label(step).contains(wanted)
{
let over = Over::new(self.env_at(step.at), self.seed);
eprintln!(
"[step] {} at {} -> {:?} | env {} | under {} | __cplusplus {:?} | seed complete {}",
step_label(step),
step.at,
visibility,
self.env.len(),
guard_text(guards, step.guard),
MacroValues::lookup(&over, "__cplusplus"),
self.seed.is_complete()
);
}
match visibility {
Visibility::Active => {}
Visibility::Inactive => {
self.note_a_skipped_include(step, guards, "Inactive");
continue;
}
Visibility::Unknown => {
self.note_a_skipped_include(step, guards, "Unknown");
self.unknown_guards += 1;
if self.unknown.len() < UNKNOWN_EXAMPLES {
self.unknown.push((
step.at,
format!(
"{} under {}",
step_label(step),
guard_text(guards, step.guard)
),
));
}
continue;
}
}
self.apply(step);
self.history.push((step.at, self.env.clone()));
}
self.finish(skeleton)
}
fn finish(self, skeleton: &Skeleton) -> Composed {
Composed {
final_env: self.env,
after_each_include: self.after_each_include,
unknown_guards: self.unknown_guards,
unknown: self.unknown,
skipped_includes: self.skipped_includes,
unresolved_includes: skeleton.unresolved_includes(),
depth_exceeded: self.depth_exceeded,
}
}
fn note_a_skipped_include(
&mut self,
step: &Step,
guards: &SummaryGuards,
visibility: &'static str,
) {
if !matches!(step.action, Action::Include(_))
|| self.skipped_includes.len() >= UNKNOWN_EXAMPLES
{
return;
}
self.skipped_includes.push((
step.at,
step_label(step),
visibility,
guard_text(guards, step.guard),
));
}
fn apply(&mut self, step: &Step) {
match &step.action {
Action::Define(definition) => {
self.env = self.env.define(definition.clone());
}
Action::Undef(name) => {
self.env = self.env.undef(name);
}
Action::Include(include) => {
if self.depth >= MAX_DEPTH {
self.depth_exceeded += 1;
return;
}
if let Some(after) = (self.handler).include(&include.path, &self.env, self.depth) {
self.env = after.clone();
self.after_each_include.push((step.at, after));
}
}
}
}
fn env_at(&self, offset: usize) -> Env {
for (at, env) in self.history.iter().rev() {
if *at <= offset {
return env.clone();
}
}
self.history
.first()
.map(|(_, env)| env.clone())
.unwrap_or_default()
}
}