use cpp_code_analysis::sema::check::diagnostic_code::DiagnosticCode;
#[test]
fn the_style_codes_are_named_and_round_trip() {
let expected = [
(
"braces-around-statements",
DiagnosticCode::BracesAroundStatements,
),
("use-nullptr", DiagnosticCode::UseNullptr),
("use-override", DiagnosticCode::UseOverride),
("simplify-boolean-expr", DiagnosticCode::SimplifyBooleanExpr),
("else-after-return", DiagnosticCode::ElseAfterReturn),
("cstyle-cast", DiagnosticCode::CStyleCast),
("use-auto", DiagnosticCode::UseAuto),
("macro-parentheses", DiagnosticCode::MacroParentheses),
(
"implicit-bool-conversion",
DiagnosticCode::ImplicitBoolConversion,
),
];
for (name, code) in expected {
assert_eq!(code.name(), name);
assert_eq!(DiagnosticCode::from_name(name), Some(code));
assert!(DiagnosticCode::ALL.contains(&code), "{name} is in ALL");
}
assert_eq!(
DiagnosticCode::ALL.len(),
31,
"every code is in the list, `redefinition` included"
);
}
#[test]
fn a_one_statement_body_is_reported() {
let found = codes_of("void f(bool ready) {\n if (ready) return;\n}\n");
assert!(
found.contains(&DiagnosticCode::BracesAroundStatements),
"{found:?}"
);
let braced = codes_of("void f(bool ready) {\n if (ready) { return; }\n}\n");
assert!(
!braced.contains(&DiagnosticCode::BracesAroundStatements),
"{braced:?}"
);
}
#[test]
fn a_null_macro_is_reported() {
let found = codes_of("void f(int*);\nvoid g() {\n f(NULL);\n}\n");
assert!(found.contains(&DiagnosticCode::UseNullptr), "{found:?}");
let nullptr = codes_of("void f(int*);\nvoid g() {\n f(nullptr);\n}\n");
assert!(
!nullptr.contains(&DiagnosticCode::UseNullptr),
"{nullptr:?}"
);
}
#[test]
fn an_override_without_the_keyword_is_reported() {
let found =
codes_of("struct Base { virtual void f(); };\nstruct Derived : Base { void f(); };\n");
assert!(found.contains(&DiagnosticCode::UseOverride), "{found:?}");
let says_so = codes_of(
"struct Base { virtual void f(); };\nstruct Derived : Base { void f() override; };\n",
);
assert!(
!says_so.contains(&DiagnosticCode::UseOverride),
"{says_so:?}"
);
}
#[test]
fn an_override_is_named_and_located_in_a_file_with_a_comment() {
let source = "\
// the cook drops this comment, so the file's offsets and the rendering's differ
struct Base {
virtual void really_overrides();
virtual void renamed_out();
};
struct Derived : Base {
void really_overrides() override;
void renamed_out();
};
";
let findings = findings_of(source);
let override_findings: Vec<&cpp_code_analysis::Finding> = findings
.iter()
.filter(|finding| finding.code == DiagnosticCode::UseOverride)
.collect();
assert_eq!(
override_findings.len(),
1,
"one member forgot the keyword: {findings:?}"
);
let finding = override_findings[0];
assert!(
finding.message.contains("renamed_out"),
"the message names the member: {}",
finding.message
);
let at = finding.range.start_offset;
assert!(
source[at..].starts_with("renamed_out"),
"the range is on the name the message is about, not at {at}: {:?}",
&source[at.saturating_sub(20)..(at + 20).min(source.len())]
);
}
#[test]
fn a_comparison_against_true_is_reported() {
let found = codes_of("void f(bool ready) {\n if (ready == true) { return; }\n}\n");
assert!(
found.contains(&DiagnosticCode::SimplifyBooleanExpr),
"{found:?}"
);
let plain = codes_of("void f(bool ready) {\n if (ready) { return; }\n}\n");
assert!(
!plain.contains(&DiagnosticCode::SimplifyBooleanExpr),
"{plain:?}"
);
}
#[test]
fn an_else_after_a_return_is_reported() {
let found =
codes_of("void f(bool ready) {\n if (ready) { return; } else { g(); }\n}\nvoid g();\n");
assert!(
found.contains(&DiagnosticCode::ElseAfterReturn),
"{found:?}"
);
let flat =
codes_of("void f(bool ready) {\n if (ready) { return; }\n g();\n}\nvoid g();\n");
assert!(!flat.contains(&DiagnosticCode::ElseAfterReturn), "{flat:?}");
}
#[test]
fn a_c_style_cast_is_reported() {
let found = codes_of("void f(double n) {\n int i = (int)n;\n}\n");
assert!(found.contains(&DiagnosticCode::CStyleCast), "{found:?}");
let named = codes_of("void f(double n) {\n int i = static_cast<int>(n);\n}\n");
assert!(!named.contains(&DiagnosticCode::CStyleCast), "{named:?}");
}
fn codes_of(source: &str) -> Vec<DiagnosticCode> {
use cpp_code_analysis::{
CompilerConfig, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
};
let files = MemoryFiles::new().with_file("/p/a.cpp", source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
session
.diagnostics(std::path::Path::new("/p/a.cpp"))
.map(|found| {
found
.checks
.iter()
.map(|finding| finding.code)
.chain(found.errors.iter().map(|error| error.code))
.collect()
})
.unwrap_or_default()
}
fn findings_of(source: &str) -> Vec<cpp_code_analysis::Finding> {
use cpp_code_analysis::{
CompilerConfig, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
};
let files = MemoryFiles::new().with_file("/p/a.cpp", source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
session
.diagnostics(std::path::Path::new("/p/a.cpp"))
.map(|found| found.checks.clone())
.unwrap_or_default()
}
#[test]
fn a_full_iterator_spelling_is_reported() {
let found = codes_of("void f() {\n std::vector<int>::iterator it;\n (void)it;\n}\n");
assert!(found.contains(&DiagnosticCode::UseAuto), "{found:?}");
let not_an_iterator =
codes_of("void f() {\n std::vector<int>::value_type value;\n (void)value;\n}\n");
assert!(
!not_an_iterator.contains(&DiagnosticCode::UseAuto),
"{not_an_iterator:?}"
);
}
#[test]
fn an_unparenthesised_macro_is_reported() {
let found = codes_of("#define TWICE(x) x * 2\nint f(int n) { return TWICE(n + 1); }\n");
assert!(
found.contains(&DiagnosticCode::MacroParentheses),
"{found:?}"
);
let parenthesised =
codes_of("#define TWICE(x) ((x) * 2)\nint f(int n) { return TWICE(n + 1); }\n");
assert!(
!parenthesised.contains(&DiagnosticCode::MacroParentheses),
"{parenthesised:?}"
);
for quiet in [
"#define ANSWER 42\nint f() { return ANSWER; }\n",
"#define MAX(a, b) ((a) > (b) ? (a) : (b))\nint f(int x, int y) { return MAX(x, y); }\n",
] {
let found = codes_of(quiet);
assert!(
!found.contains(&DiagnosticCode::MacroParentheses),
"{quiet}: {found:?}"
);
}
}
#[test]
fn a_comment_and_a_string_literal_are_not_code() {
let in_a_comment = codes_of("// NULL is what we used to write\nint f() { return 0; }\n");
assert!(
!in_a_comment.contains(&DiagnosticCode::UseNullptr),
"a comment is not a use: {in_a_comment:?}"
);
let in_a_string = codes_of("void f();\nvoid g() { f(\"NULL\"); }\n");
assert!(
!in_a_string.contains(&DiagnosticCode::UseNullptr),
"a string literal is not a use: {in_a_string:?}"
);
let cast_in_a_comment = codes_of("// we removed (int) casts everywhere\nvoid f() { }\n");
assert!(
!cast_in_a_comment.contains(&DiagnosticCode::CStyleCast),
"a comment is not a cast: {cast_in_a_comment:?}"
);
let boolean_in_a_string = codes_of(
"void f(bool ready) {\n if (ready) { g(\"x == true y\"); }\n}\nvoid g(const char*);\n",
);
assert!(
!boolean_in_a_string.contains(&DiagnosticCode::SimplifyBooleanExpr),
"a string is not a condition: {boolean_in_a_string:?}"
);
let macro_in_a_comment = codes_of("/*\n#define TWICE(x) x * 2\n*/\nint f() { return 0; }\n");
assert!(
!macro_in_a_comment.contains(&DiagnosticCode::MacroParentheses),
"a commented-out macro is not a macro: {macro_in_a_comment:?}"
);
}
#[test]
fn an_arithmetic_condition_is_an_implicit_conversion() {
let reported = codes_of("void f(int count) {\n if (count) { return; }\n}\n");
assert!(
reported.contains(&DiagnosticCode::ImplicitBoolConversion),
"an `int` in a condition is a conversion: {reported:?}"
);
let quiet = codes_of("void f(bool ready) {\n if (ready) { return; }\n}\n");
assert!(
!quiet.contains(&DiagnosticCode::ImplicitBoolConversion),
"a `bool` is not converted to `bool`: {quiet:?}"
);
let a_pointer = codes_of("void f(int* p) {\n if (p) { return; }\n}\n");
assert!(
!a_pointer.contains(&DiagnosticCode::ImplicitBoolConversion),
"`if (ptr)` is the nullable-pointer idiom: {a_pointer:?}"
);
let looped = codes_of("void f(int n) {\n while (n) { --n; }\n}\n");
assert!(
looped.contains(&DiagnosticCode::ImplicitBoolConversion),
"`while (n)` converts too: {looped:?}"
);
}
#[test]
fn a_preprocessor_condition_is_not_a_cast() {
for quiet in [
"#if (_MSC_VER)\nint f();\n#endif\n",
"#if (ASIO_USE_TS_EXECUTOR_AS_DEFAULT)\nint f();\n#endif\n",
"#if (_MSC_VER)\nint a;\n#elif (OTHER)\nint b;\n#endif\n",
] {
let found = codes_of(quiet);
assert!(
!found.contains(&DiagnosticCode::CStyleCast),
"{quiet}: {found:?}"
);
}
let still_reported = codes_of("#define CAST(x) (int)(x)\nvoid f(int n) { (void)CAST(n); }\n");
assert!(
still_reported.contains(&DiagnosticCode::CStyleCast),
"the cast in the macro body is written in the file: {still_reported:?}"
);
}
#[test]
fn a_parameter_list_is_not_a_cast() {
for quiet in [
"using handler = void (const Widget& value);\nstruct Widget { };\n",
"void f(int (int n));\n",
"void g(void (*callback)(int value));\n",
] {
let found = codes_of(quiet);
assert!(
!found.contains(&DiagnosticCode::CStyleCast),
"{quiet}: {found:?}"
);
}
let still = codes_of("struct Widget { };\nvoid f(const Widget& w) { (void)(Widget)w; }\n");
assert!(
still.contains(&DiagnosticCode::CStyleCast),
"a cast is a type with no name after it: {still:?}"
);
}
#[test]
fn a_c_style_cast_is_not_a_rule_in_c() {
let source = "void f(double n) {\n int i = (int)n;\n (void)i;\n}\n";
let cpp = codes_of_with(source, "-std=c++17");
assert!(
cpp.contains(&DiagnosticCode::CStyleCast),
"C++ has `static_cast`, so the cast should be named: {cpp:?}"
);
let c = codes_of_with(source, "-std=c11");
assert!(
!c.contains(&DiagnosticCode::CStyleCast),
"C has no other cast to recommend: {c:?}"
);
let unconfigured = codes_of(source);
assert!(
unconfigured.contains(&DiagnosticCode::CStyleCast),
"`None` is not C: {unconfigured:?}"
);
}
fn codes_of_with(source: &str, standard: &str) -> Vec<DiagnosticCode> {
use cpp_code_analysis::{
CompilerConfig, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
};
let files = MemoryFiles::new().with_file("/p/a.cpp", source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let config = CompilerConfig {
extra_args: vec![standard.to_string()],
..CompilerConfig::default()
};
let mut session = Session::with_config("/p", providers, WatchFilter::new("/p"), config);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
session
.diagnostics(std::path::Path::new("/p/a.cpp"))
.map(|found| {
found
.checks
.iter()
.map(|finding| finding.code)
.chain(found.errors.iter().map(|error| error.code))
.collect()
})
.unwrap_or_default()
}
#[test]
fn a_template_argument_is_not_a_cast() {
for quiet in [
"struct Executor { };\ntemplate <class T = (Executor)> struct Box { T value; };\n",
"template <class T, class U = (T)> struct Pair { T first; U second; };\n",
] {
let found = codes_of(quiet);
assert!(
!found.contains(&DiagnosticCode::CStyleCast),
"{quiet}: {found:?}"
);
}
let still = codes_of("void f(double n) { int i = (int)n; (void)i; }\n");
assert!(
still.contains(&DiagnosticCode::CStyleCast),
"a cast is still a cast: {still:?}"
);
}