use cpp_parser::CppTokenData;
use crate::{
directive::{Directive, DirectiveKind, SpannedDirective, scan_directives},
guard::{Branch, Guard, GuardStack, Visibility},
macros::{MacroBindings, MacroTable},
};
#[derive(Debug, Clone, Default)]
pub struct FilePreprocessing {
pub directives: Vec<SpannedDirective>,
pub macros: MacroTable,
pub unclosed_guard: Guard,
pub skipped_regions: Vec<(usize, usize)>,
}
impl FilePreprocessing {
pub fn is_skipped(&self, offset: usize) -> bool {
self.skipped_regions
.iter()
.any(|(from, to)| *from <= offset && offset < *to)
}
pub fn macros_at(&self, offset: usize) -> PositionalMacros<'_> {
PositionalMacros {
table: &self.macros,
offset,
}
}
pub fn visibility_at(&self, offset: usize) -> Visibility {
let guard = self.guard_at(offset);
let macros = self.macros_at(offset);
guard.visibility(¯os)
}
pub fn guard_at(&self, offset: usize) -> Guard {
let mut stack = GuardStack::new();
for spanned in &self.directives {
if spanned.range.end_offset() > offset {
break;
}
if let Some(branch) = branch_of(&spanned.directive, spanned.range) {
stack.observe(spanned.directive.kind(), branch);
}
}
stack.guard()
}
}
pub struct PositionalMacros<'a> {
table: &'a dyn MacroBindings,
offset: usize,
}
impl PositionalMacros<'_> {
fn is_msvc(&self) -> bool {
self.table.definition_at("_MSC_VER", self.offset).is_some()
&& self.table.definition_at("__clang__", self.offset).is_none()
}
}
impl crate::condition::MacroValues for PositionalMacros<'_> {
fn lookup(&self, name: &str) -> crate::condition::Lookup<'_> {
use crate::condition::Lookup;
self.table
.definition_at(name, self.offset)
.map_or(Lookup::Undefined, Lookup::Defined)
}
fn builtin_operator(&self, name: &str, operand: &str) -> Option<crate::condition::Value> {
if name == "__has_cpp_attribute" {
let msvc = self.is_msvc();
let answer = crate::preprocess::cooked::attribute_support_in(operand, msvc);
if crate::probes::attributes() {
eprintln!(
"cppls-trace: __has_cpp_attribute({operand:?}) at {} -> {answer:?}",
self.offset
);
}
return answer.map(crate::condition::Value::Known);
}
self.table.builtin_operator(name, operand)
}
}
pub fn preprocess(source: &str, tokens: &[CppTokenData]) -> FilePreprocessing {
preprocess_with(source, tokens, None)
}
pub fn preprocess_with_a_seed(
source: &str,
tokens: &[CppTokenData],
seed: &crate::Marked,
) -> FilePreprocessing {
preprocess_using(source, tokens, &mut |name, offset| {
crate::MacroValues::lookup(
&crate::index::environment::MacrosHere::from_walk(seed, offset),
name,
) != crate::Lookup::Undefined
})
}
pub fn preprocess_with(
source: &str,
tokens: &[CppTokenData],
environment: Option<&dyn cpp_parser::MacroFacts>,
) -> FilePreprocessing {
preprocess_using(source, tokens, &mut |name, offset| {
environment.is_some_and(|facts| facts.kind_of(name, offset).is_some())
})
}
fn preprocess_using(
source: &str,
tokens: &[CppTokenData],
is_a_macro: &mut dyn FnMut(&str, usize) -> bool,
) -> FilePreprocessing {
let directives = scan_directives(source, tokens);
let mut macros = MacroTable::new();
let mut stack = GuardStack::new();
let mut live: Vec<bool> = Vec::new();
let mut skipped_regions: Vec<(usize, usize)> = Vec::new();
let mut openings: Vec<(usize, bool)> = Vec::new();
for spanned in &directives {
let kind = spanned.directive.kind();
let skipped = live.iter().any(|taken| !taken);
match &spanned.directive {
Directive::Define(define) if !skipped => {
if let Some(definition) = &define.macro_def {
macros.define(definition.clone());
}
}
Directive::Undef { name: Some(name) } if !skipped => {
macros.undefine(name, spanned.range.start_offset);
}
_ => {}
}
if let Some(branch) = branch_of(&spanned.directive, spanned.range) {
let taken = crate::index::environment::a_branch_is_taken(
is_a_macro,
kind,
&branch,
spanned.range.start_offset,
);
let here = spanned.range.start_offset;
let settled = |taken: Option<bool>| taken.unwrap_or(true);
match kind {
DirectiveKind::If | DirectiveKind::Ifdef | DirectiveKind::Ifndef => {
let taken = settled(taken);
live.push(taken);
openings.push((here, taken));
}
DirectiveKind::Elif | DirectiveKind::Else => {
let before = live.pop();
if let Some((opened, was_taken)) = openings.pop()
&& !was_taken
{
skipped_regions.push((opened, here));
}
let answer = match (kind, taken, before) {
(DirectiveKind::Else, _, Some(before)) => Some(!before),
_ => taken,
};
let taken = settled(answer);
live.push(taken);
openings.push((here, taken));
}
DirectiveKind::Endif => {
live.pop();
if let Some((opened, was_taken)) = openings.pop()
&& !was_taken
{
skipped_regions.push((opened, spanned.range.end_offset()));
}
}
_ => {}
}
stack.observe(kind, branch);
}
}
skipped_regions.sort_unstable();
FilePreprocessing {
unclosed_guard: stack.guard(),
directives,
macros,
skipped_regions,
}
}
fn branch_of(directive: &Directive, range: cpp_parser::SourceRange) -> Option<Branch> {
let kind = directive.kind();
if !(kind.opens_a_condition() || kind.closes_a_condition()) {
return None;
}
let (tokens, name) = match directive {
Directive::Conditional { condition, .. } => (condition.clone(), None),
Directive::Ifdef { name, .. } => (Vec::new(), Some(name.clone())),
_ => (Vec::new(), None),
};
Some(Branch::new(kind, tokens, name, range))
}
pub fn candidate_macro_names(preprocessing: &FilePreprocessing) -> Vec<&str> {
let mut names: Vec<&str> = preprocessing
.directives
.iter()
.filter_map(|spanned| spanned.directive.defines())
.map(|definition| &*definition.name)
.collect();
names.sort_unstable();
names.dedup();
names
}
pub fn opens_unclosed_region(directive: &Directive) -> bool {
matches!(
directive.kind(),
DirectiveKind::If | DirectiveKind::Ifdef | DirectiveKind::Ifndef
)
}
pub mod condition;
pub mod cooked;
pub mod directive;
pub mod expand;
pub mod guard;
pub mod guards;
pub mod macros;