use cpp_parser::SourceRange;
use crate::{
condition::{MacroValues, evaluate_recording},
directive::DirectiveKind,
token::Token,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Branch {
pub kind: DirectiveKind,
pub tokens: Vec<Token>,
pub name: Option<Box<str>>,
pub range: SourceRange,
parsed: std::sync::OnceLock<Option<crate::preprocess::condition::ConditionExpr>>,
fixed: std::sync::OnceLock<bool>,
constant: std::sync::OnceLock<Option<bool>>,
}
impl Branch {
pub fn new(
kind: DirectiveKind,
tokens: Vec<Token>,
name: Option<Box<str>>,
range: SourceRange,
) -> Branch {
Branch {
kind,
tokens,
name,
range,
parsed: std::sync::OnceLock::new(),
fixed: std::sync::OnceLock::new(),
constant: std::sync::OnceLock::new(),
}
}
pub fn holds(&self, macros: &impl MacroValues) -> Option<bool> {
if let Some(wanted) = crate::probes::guard_name() {
let mentions = self
.tokens
.iter()
.any(|token| token.text().contains(wanted));
if mentions {
let answer = match self.kind {
DirectiveKind::If | DirectiveKind::Elif => {
evaluate_recording(&self.tokens, macros).0.is_true()
}
DirectiveKind::Ifdef => is_defined(self.name.as_deref(), macros),
DirectiveKind::Ifndef => {
is_defined(self.name.as_deref(), macros).map(|defined| !defined)
}
DirectiveKind::Else => Some(true),
_ => None,
};
println!(
"cppls-guard: {:?} mentions {wanted} -> {answer:?}",
self.tokens
.iter()
.map(|token| token.text())
.collect::<Vec<_>>()
.join(" ")
);
return answer;
}
}
match self.kind {
DirectiveKind::If | DirectiveKind::Elif => self.an_expression_holds(macros),
DirectiveKind::Ifdef => is_defined(self.name.as_deref(), macros),
DirectiveKind::Ifndef => {
is_defined(self.name.as_deref(), macros).map(|defined| !defined)
}
DirectiveKind::Else => Some(true),
_ => None,
}
}
fn an_expression_holds(&self, macros: &impl MacroValues) -> Option<bool> {
if let Some(held) = self.constant.get() {
return *held;
}
if *self.fixed.get().unwrap_or(&false) {
return match self.parsed.get().and_then(Option::as_ref) {
Some(expr) => crate::preprocess::condition::eval(expr, macros).is_true(),
None => None,
};
}
if let Some(held) = a_constant_condition(&self.tokens) {
let _ = self.constant.set(Some(held));
return Some(held);
}
if !a_replacement_can_change_the_parse(&self.tokens) {
let parsed = crate::preprocess::condition::parse_condition(&self.tokens).ok();
let held = parsed
.as_ref()
.map(|expr| crate::preprocess::condition::eval(expr, macros).is_true())
.unwrap_or(None);
let _ = self.parsed.set(parsed);
let _ = self.fixed.set(true);
return held;
}
let (value, expression) = evaluate_recording(&self.tokens, macros);
if let Some(expression) = expression {
let _ = self.parsed.set(Some(expression));
let _ = self.fixed.set(true);
}
value.is_true()
}
}
fn a_replacement_can_change_the_parse(tokens: &[Token]) -> bool {
use crate::token::is_trivia;
let significant: Vec<&Token> = tokens
.iter()
.filter(|token| !is_trivia(token.kind))
.collect();
for (index, token) in significant.iter().enumerate() {
if token.kind != cpp_parser::CppTokenKind::Identifier {
continue;
}
let is_a_call_shape = significant
.get(index + 1)
.is_some_and(|next| next.kind == cpp_parser::CppTokenKind::LeftParen);
if !is_a_call_shape {
continue;
}
if token.text() == "defined"
|| crate::preprocess::condition::is_a_builtin_operator(token.text())
{
continue;
}
return true;
}
false
}
fn a_constant_condition(tokens: &[Token]) -> Option<bool> {
let mut significant = tokens
.iter()
.filter(|token| !crate::token::is_trivia(token.kind));
let only = significant.next()?;
if significant.next().is_some() {
return None;
}
let value = only.text().parse::<i128>().ok()?;
Some(value != 0)
}
fn is_defined(name: Option<&str>, macros: &impl MacroValues) -> Option<bool> {
name.and_then(|name| {
if crate::preprocess::condition::is_a_builtin_operator(name) {
return Some(true);
}
macros.lookup(name).is_defined()
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Region {
pub branches: Vec<Branch>,
pub active_branch: usize,
}
impl Region {
pub fn visibility(&self, macros: &impl MacroValues) -> Option<bool> {
let mut unknown_before = false;
for (index, branch) in self.branches.iter().enumerate() {
let holds = branch.holds(macros);
if index < self.active_branch {
match holds {
Some(true) => return Some(false),
Some(false) => {}
None => unknown_before = true,
}
continue;
}
if index > self.active_branch {
break;
}
return match (holds, unknown_before) {
(None, _) => None,
(Some(false), _) => Some(false),
(Some(true), true) => None,
(Some(true), false) => Some(true),
};
}
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Visibility {
Active,
Inactive,
Unknown,
}
impl Visibility {
pub fn is_reachable(self) -> bool {
!matches!(self, Visibility::Inactive)
}
pub fn is_diagnosable(self) -> bool {
matches!(self, Visibility::Active)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Guard {
regions: Vec<Region>,
}
impl Guard {
pub fn empty() -> Self {
Guard {
regions: Vec::new(),
}
}
pub fn is_empty(&self) -> bool {
self.regions.is_empty()
}
pub fn regions(&self) -> &[Region] {
&self.regions
}
pub fn depth(&self) -> usize {
self.regions.len()
}
pub fn innermost_branch(&self) -> Option<&Branch> {
let region = self.regions.last()?;
region.branches.get(region.active_branch)
}
pub fn visibility(&self, macros: &impl MacroValues) -> Visibility {
let mut unknown = false;
for region in &self.regions {
match region.visibility(macros) {
Some(true) => {}
Some(false) => return Visibility::Inactive,
None => unknown = true,
}
}
if unknown {
Visibility::Unknown
} else {
Visibility::Active
}
}
}
#[derive(Debug, Clone, Default)]
pub struct GuardStack {
stack: Vec<Region>,
}
impl GuardStack {
pub fn new() -> Self {
Self::default()
}
pub fn guard(&self) -> Guard {
Guard {
regions: self.stack.clone(),
}
}
pub fn depth(&self) -> usize {
self.stack.len()
}
pub fn observe(&mut self, kind: DirectiveKind, branch: Branch) {
match kind {
DirectiveKind::If | DirectiveKind::Ifdef | DirectiveKind::Ifndef => {
self.stack.push(Region {
branches: vec![branch],
active_branch: 0,
});
}
DirectiveKind::Elif | DirectiveKind::Else => {
if let Some(region) = self.stack.last_mut() {
region.branches.push(branch);
region.active_branch = region.branches.len() - 1;
}
}
DirectiveKind::Endif => {
self.stack.pop();
}
_ => {}
}
}
}