use super::{assert_reported, assert_silent_about, codes_of, named_findings_in};
use crate::DiagnosticCode;
#[test]
fn a_second_definition_with_a_different_body_is_reported() {
let object_like = codes_of("#define MAX 10\n#define MAX 20\nint main() { return MAX; }\n");
assert_reported(
&object_like,
DiagnosticCode::MacroRedefined,
"`MAX` changes from 10 to 20",
);
let function_like = codes_of(
"#define TWICE(x) ((x) * 2)\n#define TWICE(x) ((x) * 3)\nint f(int n) { return TWICE(n); }\n",
);
assert_reported(
&function_like,
DiagnosticCode::MacroRedefined,
"a function-like macro's replacement list changed too",
);
}
#[test]
fn an_identical_definition_is_not_reported() {
let object_like = codes_of("#define MAX 10\n#define MAX 10\nint main() { return MAX; }\n");
assert_silent_about(
&object_like,
DiagnosticCode::MacroRedefined,
"the two replacement lists are the same text",
);
let function_like = codes_of(
"#define TWICE(x) ((x) * 2)\n#define TWICE(x) ((x) * 2)\nint f(int n) { return TWICE(n); }\n",
);
assert_silent_about(
&function_like,
DiagnosticCode::MacroRedefined,
"and so are these two",
);
}
#[test]
fn an_undef_between_the_two_is_not_a_redefinition() {
let codes =
codes_of("#define MAX 10\n#undef MAX\n#define MAX 20\nint main() { return MAX; }\n");
assert_silent_about(
&codes,
DiagnosticCode::MacroRedefined,
"no definition was in force when the second `MAX` was written",
);
}
#[test]
fn a_definition_in_a_dead_branch_is_not_in_force() {
let codes = codes_of(
"#if 0\n#define MAX 10\n#else\n#define MAX 20\n#endif\nint main() { return MAX; }\n",
);
assert_silent_about(
&codes,
DiagnosticCode::MacroRedefined,
"the two definitions are in mutually exclusive branches, so at most one is in force",
);
}
#[test]
fn a_definition_in_a_header_this_file_does_not_include_is_not_a_redefinition() {
let findings = named_findings_in(
&[
("/p/other.h", "#define MAX 10\n"),
(
"/p/a.cpp",
"#define MAX 20\n#define MIN 1\n#define MIN 2\nint main() { return MIN; }\n",
),
],
"/p/a.cpp",
);
assert!(
!findings
.iter()
.any(|(code, name)| *code == DiagnosticCode::MacroRedefined && name == "MAX"),
"`MAX` is defined once in this file, and the header is not included: {findings:?}"
);
assert!(
findings
.iter()
.any(|(code, name)| *code == DiagnosticCode::MacroRedefined && name == "MIN"),
"while `MIN` really is redefined in this file: {findings:?}"
);
let findings = named_findings_in(
&[
("/p/api.h", "#define MAX 10\n"),
("/p/a.cpp", "#include \"api.h\"\n#define MAX 20\n"),
],
"/p/a.cpp",
);
assert!(
!findings
.iter()
.any(|(code, name)| *code == DiagnosticCode::MacroRedefined && name == "MAX"),
"the rule compares this file's own definitions, not the headers': {findings:?}"
);
}