use cpp_parser::{CppSyntaxKind, CppSyntaxNode, CppSyntaxTree};
use crate::{
directive::{Directive, DirectiveKind, SpannedDirective},
preprocess::{FilePreprocessing, preprocess},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Guard {
None,
PragmaOnce,
Macro(Box<str>),
}
impl Guard {
pub fn is_guarded(&self) -> bool {
!matches!(self, Guard::None)
}
pub fn blocks_a_visit(&self, is_defined: impl Fn(&str) -> bool) -> bool {
match self {
Guard::None => false,
Guard::PragmaOnce => true,
Guard::Macro(name) => is_defined(name),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileGuard {
pub guard: Guard,
pub defines: Vec<Box<str>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GuardAnalysis {
pub guard: Guard,
pub defines: Vec<Box<str>>,
}
pub fn analyse_guards(preprocessing: &FilePreprocessing, root: &CppSyntaxNode) -> GuardAnalysis {
let defines: Vec<Box<str>> = preprocessing
.directives
.iter()
.filter_map(|spanned| spanned.directive.defines())
.map(|definition| definition.name.clone())
.collect();
GuardAnalysis {
guard: detect_guard(&preprocessing.directives, root),
defines,
}
}
pub fn detect_guard(directives: &[SpannedDirective], root: &CppSyntaxNode) -> Guard {
if has_pragma_once(directives) {
return Guard::PragmaOnce;
}
detect_macro_guard(directives, root).unwrap_or(Guard::None)
}
pub fn detect_guard_from_tokens(
directives: &[SpannedDirective],
tokens: &[cpp_parser::CppTokenData],
) -> Guard {
if has_pragma_once(directives) {
return Guard::PragmaOnce;
}
detect_macro_guard_if(directives, |offset| {
declares_something_before_tokens(tokens, directives, offset)
})
.unwrap_or(Guard::None)
}
pub fn has_a_macro_guard_from_tokens(
directives: &[SpannedDirective],
tokens: &[cpp_parser::CppTokenData],
) -> bool {
detect_macro_guard_if(directives, |offset| {
declares_something_before_tokens(tokens, directives, offset)
})
.is_some()
}
pub fn declares_something_before_tokens(
tokens: &[cpp_parser::CppTokenData],
directives: &[SpannedDirective],
offset: usize,
) -> bool {
tokens.iter().any(|token| {
let at = token.range.start_offset;
at < offset
&& !crate::token::is_trivia(token.kind)
&& !directives
.iter()
.any(|spanned| spanned.range.start_offset <= at && at < spanned.range.end_offset())
})
}
fn has_pragma_once(directives: &[SpannedDirective]) -> bool {
directives.iter().any(|spanned| match &spanned.directive {
Directive::Pragma { tokens } => tokens.first().is_some_and(|token| token.text() == "once"),
_ => false,
})
}
fn detect_macro_guard(directives: &[SpannedDirective], root: &CppSyntaxNode) -> Option<Guard> {
detect_macro_guard_if(directives, |offset| declares_something_before(root, offset))
}
fn detect_macro_guard_if(
directives: &[SpannedDirective],
has_code_before: impl Fn(usize) -> bool,
) -> Option<Guard> {
let opener = directives.iter().position(|spanned| {
spanned.condition_depth == 0 && matches!(spanned.directive.kind(), DirectiveKind::Ifndef)
})?;
if has_code_before(directives[opener].range.start_offset) {
return None;
}
let name = match &directives[opener].directive {
Directive::Ifdef { name, .. } => name.clone(),
_ => return None,
};
let definition = directives
.get(opener + 1)
.filter(|spanned| spanned.condition_depth == 1)
.and_then(|spanned| spanned.directive.defines())?;
if definition.name != name {
return None;
}
Some(Guard::Macro(name))
}
fn declares_something_before(root: &CppSyntaxNode, offset: usize) -> bool {
fn is_code(node: &CppSyntaxNode) -> bool {
match CppSyntaxKind::from(node.kind()) {
CppSyntaxKind::DocComment | CppSyntaxKind::PreprocessorDirective => false,
CppSyntaxKind::TranslationUnit => node.children().any(|child| is_code(&child)),
_ => true,
}
}
root.children()
.any(|child| (u32::from(child.text_range().start()) as usize) < offset && is_code(&child))
}
pub fn analyse(source: &str, tree: &CppSyntaxTree) -> GuardAnalysis {
let preprocessing = preprocess(source, tree.get_tokens());
analyse_guards(&preprocessing, &tree.get_red_root())
}
#[cfg(test)]
mod tests {
use super::*;
use cpp_parser::{CppParser, ParserConfig};
fn guards_of(source: &str) -> GuardAnalysis {
let tree = CppParser::parse(source, ParserConfig::default());
analyse(source, &tree)
}
#[test]
fn a_header_with_no_guard_has_none() {
assert_eq!(guards_of("int x;\n").guard, Guard::None);
}
#[test]
fn pragma_once_is_recognised() {
assert_eq!(guards_of("#pragma once\nint x;\n").guard, Guard::PragmaOnce);
}
#[test]
fn the_ifndef_idiom_is_recognised() {
assert_eq!(
guards_of("#ifndef FOO_H\n#define FOO_H\nint x;\n#endif\n").guard,
Guard::Macro("FOO_H".into())
);
}
#[test]
fn a_comment_before_the_guard_is_allowed() {
assert_eq!(
guards_of("// a header\n#ifndef FOO_H\n#define FOO_H\nint x;\n#endif\n").guard,
Guard::Macro("FOO_H".into())
);
}
#[test]
fn code_before_the_guard_means_it_is_not_a_guard() {
assert_eq!(
guards_of("int outside;\n#ifndef FOO_H\n#define FOO_H\nint x;\n#endif\n").guard,
Guard::None
);
}
#[test]
fn a_region_that_defines_a_different_name_is_not_a_guard() {
assert_eq!(
guards_of("#ifndef A\n#define B\nint x;\n#endif\n").guard,
Guard::None
);
}
#[test]
fn an_ifndef_without_its_define_is_not_a_guard() {
assert_eq!(
guards_of("#ifndef FOO_H\nint x;\n#endif\n").guard,
Guard::None
);
}
#[test]
fn a_nested_define_is_not_the_guards() {
assert_eq!(
guards_of("#ifndef FOO_H\n#if X\n#define FOO_H\n#endif\n#endif\n").guard,
Guard::None
);
}
#[test]
fn pragma_once_wins_over_a_macro_guard() {
assert_eq!(
guards_of("#pragma once\n#ifndef FOO_H\n#define FOO_H\nint x;\n#endif\n").guard,
Guard::PragmaOnce
);
}
#[test]
fn a_macro_guard_only_blocks_a_visit_once_its_macro_is_defined() {
let guard = guards_of("#ifndef FOO_H\n#define FOO_H\nint x;\n#endif\n").guard;
assert!(!guard.blocks_a_visit(|_| false), "not seen yet");
assert!(guard.blocks_a_visit(|name| name == "FOO_H"), "already seen");
}
#[test]
fn pragma_once_always_blocks_a_second_visit() {
assert!(Guard::PragmaOnce.blocks_a_visit(|_| false));
assert!(!Guard::None.blocks_a_visit(|_| true));
}
#[test]
fn the_macros_a_file_defines_are_collected() {
let analysis = guards_of("#define A 1\n#define B 2\n#undef A\n#define C 3\n");
assert_eq!(
analysis.defines,
vec!["A".into(), "B".into(), "C".into()],
"every definition, in order, including one that was later undefined"
);
}
}