use std::path::Path;
use crate::ProjectIndex;
use crate::condition::{Lookup, MacroValues};
use crate::guard::Visibility;
use crate::include::config::CompilerConfig;
use crate::include::graph::Marked;
use crate::summary::{FactGuard, FileSummary, MacroFact, MacroKind};
pub struct MacrosHere<'a> {
seed: std::borrow::Cow<'a, Marked>,
file: Option<&'a FileSummary>,
offset: usize,
}
impl<'a> MacrosHere<'a> {
pub fn from_walk(state: &'a Marked, offset: usize) -> Self {
MacrosHere {
seed: std::borrow::Cow::Borrowed(state),
file: None,
offset,
}
}
pub fn from_summary(state: Marked, file: &'a FileSummary, offset: usize) -> Self {
MacrosHere {
seed: std::borrow::Cow::Owned(state),
file: Some(file),
offset,
}
}
}
impl MacroValues for MacrosHere<'_> {
fn lookup(&self, name: &str) -> Lookup<'_> {
if let Some(fact) = self.last_word_about(name) {
return match fact.kind {
MacroKind::Definition => {
match self.alias_of(fact, ALIAS_DEPTH) {
Some(alias) => self.lookup(alias),
None => Lookup::DefinedWithoutAValue,
}
}
MacroKind::Undefinition => Lookup::Undefined,
};
}
self.seed.as_ref().lookup(name)
}
}
const ALIAS_DEPTH: usize = 8;
impl<'a> MacrosHere<'a> {
fn alias_of(&self, fact: &'a MacroFact, depth: usize) -> Option<&'a str> {
if depth == 0 {
return None;
}
fact.alias.as_deref()
}
fn last_word_about(&self, name: &str) -> Option<&'a MacroFact> {
self.file?
.macros
.iter()
.filter(|fact| {
&*fact.name == name
&& fact.guard == FactGuard::Unconditional
&& fact.range.start_offset <= self.offset
})
.max_by_key(|fact| fact.range.start_offset)
}
}
pub fn compilation_environment(
config: &CompilerConfig,
toolchain: Option<&crate::include::toolchain::Toolchain>,
configured: bool,
) -> Marked {
let mut marked = Marked::default();
for definition in crate::predefined_macros_of(config) {
marked.define_on_the_command_line(&definition.name, definition.value.as_deref());
}
if let Some(toolchain) = toolchain {
for (name, value) in toolchain.macros() {
marked.define_on_the_command_line(name, value);
}
}
for definition in &config.defines {
marked.define_on_the_command_line(&definition.name, definition.value.as_deref());
}
for name in &config.undefines {
marked.undefine(name);
}
if configured {
marked
} else {
marked.incomplete()
}
}
pub fn fact_in_force(seed: &Marked, file: &FileSummary, fact: &MacroFact) -> bool {
a_guard_is_in_force(file, fact, |condition_at| {
MacrosHere::from_walk(seed, condition_at)
})
}
pub fn a_guard_is_in_force<M: crate::MacroValues>(
file: &FileSummary,
fact: &MacroFact,
macros_at: impl Fn(usize) -> M,
) -> bool {
a_guard_holds(file, fact.guard, fact.range.start_offset, macros_at)
}
pub struct KnownMacros<'a> {
facts: &'a dyn cpp_parser::MacroFacts,
offset: usize,
}
impl<'a> KnownMacros<'a> {
pub fn new(facts: &'a dyn cpp_parser::MacroFacts, offset: usize) -> Self {
KnownMacros { facts, offset }
}
}
impl crate::condition::MacroValues for KnownMacros<'_> {
fn lookup(&self, name: &str) -> crate::condition::Lookup<'_> {
match self.facts.kind_of(name, self.offset) {
Some(_) => crate::condition::Lookup::DefinedWithoutAValue,
None => crate::condition::Lookup::Undefined,
}
}
}
pub fn a_branch_is_taken(
is_a_macro: &mut dyn FnMut(&str, usize) -> bool,
kind: crate::DirectiveKind,
branch: &crate::preprocess::guard::Branch,
offset: usize,
) -> Option<bool> {
match kind {
crate::DirectiveKind::Ifdef => {
let name = branch.name.as_deref()?;
Some(is_a_macro(name, offset))
}
crate::DirectiveKind::Ifndef => {
let name = branch.name.as_deref()?;
Some(!is_a_macro(name, offset))
}
_ => None,
}
}
pub fn a_guard_holds<M: crate::MacroValues>(
file: &FileSummary,
guard: FactGuard,
offset: usize,
macros_at: impl Fn(usize) -> M,
) -> bool {
a_guard_holds_measured(file, guard, offset, macros_at)
}
pub fn a_guard_visibility<M: crate::MacroValues>(
file: &FileSummary,
fact: &MacroFact,
macros_at: impl Fn(usize) -> M,
) -> crate::preprocess::guard::Visibility {
if matches!(fact.guard, FactGuard::Unconditional) {
return crate::preprocess::guard::Visibility::Active;
}
file.guards
.visibility_of(fact.guard, fact.range.start_offset, ¯os_at)
}
fn a_guard_holds_measured<M: crate::MacroValues>(
file: &FileSummary,
guard: FactGuard,
offset: usize,
macros_at: impl Fn(usize) -> M,
) -> bool {
if matches!(guard, FactGuard::Unconditional) {
return true;
}
let visibility = file.guards.visibility_of(guard, offset, ¯os_at);
visibility == Visibility::Active
}
pub fn visibility_at(
index: &ProjectIndex,
path: &Path,
guard: FactGuard,
offset: usize,
) -> Visibility {
if guard == FactGuard::Unconditional {
return Visibility::Active;
}
let Some(summary) = index.summary(path) else {
return Visibility::Unknown;
};
summary.guards.visibility_of(guard, offset, |condition_at| {
MacrosHere::from_summary(index.macros_at(path, condition_at), summary, condition_at)
})
}
#[cfg(test)]
mod tests {
use super::visibility_at;
use crate::cache::SummaryKey;
use crate::guard::Visibility;
use crate::index::ProjectIndex;
use crate::summary::{FactGuard, SummaryGuards};
use std::path::Path;
fn index_of(source: &str, defines: &[&str]) -> ProjectIndex {
index_of_with(source, defines, false)
}
fn index_of_with(source: &str, defines: &[&str], complete: bool) -> ProjectIndex {
let path = Path::new("/p/widget.h");
let summary = crate::index::summarize(path, source, SummaryKey::new(0, 0));
let mut macros = crate::Marked::default();
for name in defines {
macros.define_on_the_command_line(name, None);
}
let mut index = ProjectIndex::new().with_macros(if complete {
macros
} else {
macros.incomplete()
});
index.insert(summary);
index
}
fn guard_of(source: &str, defines: &[&str], needle: &str) -> (ProjectIndex, FactGuard, usize) {
let index = index_of(source, defines);
let (guard, offset) = guard_in(&index, source, needle);
(index, guard, offset)
}
fn guard_in(index: &ProjectIndex, source: &str, needle: &str) -> (FactGuard, usize) {
let offset = source.find(needle).expect("the needle is in the fixture");
let guard = index
.summary(Path::new("/p/widget.h"))
.expect("the file is indexed")
.macros
.iter()
.find(|fact| fact.range.start_offset == offset)
.map(|fact| fact.guard)
.expect("a fact starts at the needle");
(guard, offset)
}
fn guard_of_in_complete(
source: &str,
defines: &[&str],
needle: &str,
) -> (ProjectIndex, FactGuard, usize) {
let index = index_of_with(source, defines, true);
let (guard, offset) = guard_in(&index, source, needle);
(index, guard, offset)
}
#[test]
fn a_conditional_define_is_in_force_only_when_its_branch_was_taken() {
let source = "#if FOO\n#define X 1\n#endif\n#if BAR\n#define Y 2\n#endif\n";
let path = Path::new("/p/widget.h");
let summary = crate::index::summarize(path, source, SummaryKey::new(0, 0));
let fact = |name: &str| {
summary
.macros
.iter()
.find(|fact| &*fact.name == name)
.expect("the fixture defines it")
};
let mut seed = crate::Marked::default();
seed.define_on_the_command_line("FOO", Some("1"));
assert!(
super::fact_in_force(&seed, &summary, fact("X")),
"`FOO` is defined, so that branch was taken"
);
assert!(
!super::fact_in_force(&seed, &summary, fact("Y")),
"nothing defines `BAR`, so that branch was not taken"
);
let source = "#define Z 3\n";
let summary = crate::index::summarize(path, source, SummaryKey::new(0, 0));
assert!(
super::fact_in_force(&crate::Marked::default(), &summary, &summary.macros[0]),
"a `#define` outside every conditional is a fact about the file"
);
}
#[test]
fn a_name_nothing_defines_is_not_defined_when_the_inputs_are_complete() {
let source = "int early;\n#ifndef NT_INCLUDED\n#include \"winnt.h\"\n#endif\n";
let path = Path::new("/p/widget.h");
let (guard, offset) = include_guard(&index_of_with(source, &[], true));
assert_eq!(
visibility_at(&index_of_with(source, &[], true), path, guard, offset),
Visibility::Active,
"nothing defines it, and the caller said nothing else can: the include is certain"
);
assert_eq!(
visibility_at(&index_of(source, &[]), path, guard, offset),
Visibility::Unknown
);
}
fn include_guard(index: &ProjectIndex) -> (FactGuard, usize) {
let summary = index
.summary(Path::new("/p/widget.h"))
.expect("the file is indexed");
let include = summary
.includes
.first()
.expect("the fixture includes a file");
(include.guard, include.range.start_offset)
}
#[test]
fn the_files_own_guard_is_transparent_to_everything_inside_it() {
let source = "#ifndef WIDGET_H\n#define WIDGET_H\n#if __cplusplus\n#define INNER 1\n#endif\n#endif\n";
let path = Path::new("/p/widget.h");
let (index, guard, offset) = guard_of_in_complete(source, &["__cplusplus"], "INNER");
assert_eq!(
visibility_at(&index, path, guard, offset),
Visibility::Active,
"the condition is `#if __cplusplus`, and the guard around it is not a condition at all"
);
let summary = index.summary(path).expect("the file is indexed");
assert_eq!(summary.guards.own_guard, Some(0));
assert!(
summary.guards.conditions_of(0).is_empty(),
"and asking about the guard itself gets no condition back"
);
}
#[test]
fn code_outside_every_conditional_is_active_without_being_evaluated() {
let index = index_of("#define NAME 1\n", &[]);
let path = Path::new("/p/widget.h");
assert_eq!(
visibility_at(&index, path, FactGuard::Unconditional, 0),
Visibility::Active
);
assert!(
index.macros().is_empty(),
"and it did not need an environment to say so"
);
}
#[test]
fn a_condition_the_environment_decides_is_decided() {
let source = "#ifdef X\n#define INNER 1\n#endif\n";
let path = Path::new("/p/widget.h");
let (index, guard, offset) = guard_of(source, &["X"], "INNER");
assert_eq!(
visibility_at(&index, path, guard, offset),
Visibility::Active
);
let (index, guard, offset) = guard_of(source, &[], "INNER");
assert_eq!(
visibility_at(&index, path, guard, offset),
Visibility::Unknown,
"a name nothing the index read mentions is not 'not defined'"
);
let (index, guard, offset) = guard_of_in_complete(source, &[], "INNER");
assert_eq!(
visibility_at(&index, path, guard, offset),
Visibility::Inactive,
"nothing defines `X`, and the caller said nothing else can"
);
let source = "#if 0\n#define INNER 1\n#endif\n";
let (index, guard, offset) = guard_of(source, &[], "INNER");
assert_eq!(
visibility_at(&index, path, guard, offset),
Visibility::Inactive
);
}
#[test]
fn a_region_the_summary_does_not_describe_is_unknown_rather_than_taken() {
let source = "#ifdef X\n#define INNER 1\n#endif\n";
let mut index = index_of(source, &["X"]);
let path = Path::new("/p/widget.h");
let summary = index.summary(path).expect("the file is indexed");
let mut stripped = summary.clone();
stripped.guards = SummaryGuards {
regions: summary.guards.regions.clone(),
conditionals: Vec::new(),
..SummaryGuards::default()
};
index.insert(stripped);
assert_eq!(
visibility_at(&index, path, FactGuard::Region(0), 0),
Visibility::Unknown
);
}
#[test]
fn a_name_the_file_defines_inside_the_region_is_not_evidence_about_the_region() {
let source = "int early;\n#ifndef WRAPPER\n#define WRAPPER 1\n#define INNER 2\n#endif\n";
let (index, guard, offset) = guard_of(source, &[], "INNER");
assert_eq!(
visibility_at(&index, Path::new("/p/widget.h"), guard, offset),
Visibility::Unknown,
"nothing outside the region says whether `WRAPPER` was defined when the `#ifndef` was read"
);
let (index, guard, offset) = guard_of(source, &["WRAPPER"], "INNER");
assert_eq!(
visibility_at(&index, Path::new("/p/widget.h"), guard, offset),
Visibility::Inactive,
"with WRAPPER defined the guard is not taken, and the body is not in the translation unit"
);
}
}