use cpp_code_analysis::sema::check::{RuleSeverity, RuleTag};
use cpp_code_analysis::{
CompilerConfig, DiagnosticCode, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
};
fn codes_of(source: &str) -> Vec<DiagnosticCode> {
codes_of_a_file("/p/a.cpp", source)
}
fn codes_of_a_file(path: &str, source: &str) -> Vec<DiagnosticCode> {
let files = MemoryFiles::new().with_file(path, 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(path)]);
session.want_cooked_reading(std::path::Path::new(path));
session.index_everything();
session
.diagnostics(std::path::Path::new(path))
.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_body_is_not_checked() {
let codes = codes_of(TEMPLATE);
assert!(
codes.is_empty(),
"nothing in a template body is knowable before instantiation: {codes:?}"
);
}
#[test]
fn a_real_class_still_reports_an_undefined_member() {
let declares_it = codes_of("struct C { int n; };\nvoid g() { C x; x.n; }\n");
assert!(
declares_it.is_empty(),
"`C` declares `n`, so there is nothing to say: {declares_it:?}"
);
let does_not = codes_of("struct C { int n; };\nvoid g() { C x; x.m; }\n");
assert!(
does_not.contains(&DiagnosticCode::UndefinedField),
"`C` is a class that declares no `m`, which is the finding this check exists for: {does_not:?}"
);
let both = codes_of(
"template <class C> void f() { C x; x.m; return; }\n\
struct C { int n; };\n\
void g() { C x; x.m; return; }\n",
);
assert!(
both.contains(&DiagnosticCode::UndefinedField),
"the class `C` outside the template still declares no `m`: {both:?}"
);
}
const TEMPLATE: &str = r#"template <class C, class Fn>
constexpr int consteval_validate_destruction(Fn op) {
C x{42};
op(x);
return x.n;
}
"#;
#[test]
fn the_reported_file_reports_only_its_unresolved_includes() {
let codes = codes_of(REPORTED);
assert_eq!(
codes,
vec![
DiagnosticCode::IncludeNotFound,
DiagnosticCode::IncludeNotFound,
DiagnosticCode::IncludeNotFound
],
"the file parses; the only claim the checks make about it is about the machine's include paths"
);
}
const REPORTED: &str = r#"#include <iostream>
#include <string>
#include <cstdio>
int main() {
int a = 1, b = 2;
int sum = a + b;
std::cout << "The sum of " << a << " and " << b << " is: " << sum << std::endl;
std::string full;
std::cout << "Full name: " << full << std::endl;
std::cout << "hello world " << std::endl;
full.size();
full.length();
full.size();
printf("Full name Length: %zu\n", full.size());
// printf("Full name Length using length(): %zu\n", full.length());
return 0;
}
"#;
#[test]
fn a_file_with_nothing_wrong_reports_nothing() {
let codes = codes_of("int add(int a, int b) { return a + b; }\n");
assert!(
codes.is_empty(),
"a plain function is not a finding: {codes:?}"
);
}
#[test]
fn syntax_error_is_reported() {
let codes = codes_of("int main( { return 0; }\n");
assert!(
codes.contains(&DiagnosticCode::SyntaxError),
"an unclosed parameter list does not parse: {codes:?}"
);
}
#[test]
fn unused_is_reported_for_a_local_nothing_reads() {
let codes = codes_of("int main() { int never_used = 1; return 0; }\n");
assert!(
codes.contains(&DiagnosticCode::Unused),
"`never_used` is written once in the file: {codes:?}"
);
}
#[test]
fn unused_is_not_reported_for_a_local_that_is_used() {
let codes = codes_of("int main() { int used = 1; return used; }\n");
assert!(
!codes.contains(&DiagnosticCode::Unused),
"`used` is read on the next line: {codes:?}"
);
}
#[test]
fn unused_is_not_reported_for_a_name_that_says_it_is_deliberate() {
let codes = codes_of("int main() { int _unused = 1; return 0; }\n");
assert!(
!codes.contains(&DiagnosticCode::Unused),
"a leading underscore is a deliberate choice: {codes:?}"
);
}
#[test]
fn include_not_found_is_reported_for_a_header_nobody_has() {
let codes = codes_of("#include <vectr>\nint main() { return 0; }\n");
assert!(
codes.contains(&DiagnosticCode::IncludeNotFound),
"`<vectr>` is not a header: {codes:?}"
);
}
#[test]
fn an_unresolved_include_is_underlined_on_its_own_line() {
const SOURCE: &str = "#include <asio.hpp>\n// https://stackoverflow.com/questions/1598985/c-read-binary-stdin\n\
#ifdef _WIN32\n#include <fcntl.h>\n#endif\nint main() { return 0; }\n";
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(),
);
let path = std::path::Path::new("/p/a.cpp");
session.add_project_files([std::path::PathBuf::from(path)]);
session.want_cooked_reading(path);
session.index_everything();
let found = session.diagnostics(path).expect("a cooked reading");
let underlined: Vec<&str> = found
.checks
.iter()
.filter(|finding| finding.code == DiagnosticCode::IncludeNotFound)
.map(|finding| &SOURCE[finding.range.start_offset..finding.range.end_offset()])
.collect();
assert_eq!(
underlined,
vec!["#include <asio.hpp>", "#include <fcntl.h>"],
"one finding per directive, each on its own line — and never the comment under it: {underlined:?}"
);
}
#[test]
fn macro_redefined_is_reported_for_a_second_different_definition() {
let codes = codes_of("#define MAX 10\n#define MAX 20\nint main() { return MAX; }\n");
assert!(
codes.contains(&DiagnosticCode::MacroRedefined),
"one name, two bodies, no `#undef`: {codes:?}"
);
}
#[test]
fn macro_redefined_is_not_reported_for_an_identical_definition() {
let codes = codes_of("#define MAX 10\n#define MAX 10\nint main() { return MAX; }\n");
assert!(
!codes.contains(&DiagnosticCode::MacroRedefined),
"an identical redefinition is legal: {codes:?}"
);
}
#[test]
fn a_greater_equal_is_not_an_assignment() {
let source = "\
int f(int a, int b) {
if (a >= b) {
return 1;
}
if (a <= b) {
return 2;
}
if (a == b) {
return 3;
}
if (a = b) {
return 4;
}
return 0;
}
";
let found = codes_with_lines(source);
let lines: Vec<usize> = found
.iter()
.filter(|(code, _)| *code == DiagnosticCode::AssignmentInCondition)
.map(|(_, line)| *line)
.collect();
for (line, written) in [(1, "a >= b"), (4, "a <= b"), (7, "a == b")] {
assert!(
!lines.contains(&line),
"`if ({written})` is a comparison, not an assignment: {found:?}"
);
}
assert!(
lines.contains(&10),
"`if (a = b)` is the defect this check exists for: {found:?}"
);
}
#[test]
fn unnecessary_branch_is_reported_for_a_literal_condition() {
let codes = codes_of("int main() { if (false) { return 1; } return 0; }\n");
assert!(
codes.contains(&DiagnosticCode::UnnecessaryBranch),
"`if (false)` cannot run: {codes:?}"
);
}
#[test]
fn unnecessary_branch_is_not_reported_for_a_name() {
let codes = codes_of("int main() { if (DEBUG) { return 1; } return 0; }\n");
assert!(
!codes.contains(&DiagnosticCode::UnnecessaryBranch),
"`DEBUG` is not a literal: {codes:?}"
);
}
#[test]
fn a_finding_after_a_comment_lands_on_the_line_the_reader_wrote() {
let source = "// a comment the cook removes\nint main() { int never_used = 1; return 0; }\n";
let lines = lines_of(&codes_with_lines(source));
assert_eq!(
lines,
vec![(DiagnosticCode::Unused, 1)],
"the unused local is on line 1, where it is written"
);
let file_at = source.find("never_used").expect("the fixture writes it");
let rendering = cpp_parser::CppParser::parse(
"int main() { int never_used = 1; return 0; }\n",
cpp_parser::ParserConfig::default(),
);
let rendering_at = rendering
.get_red_root()
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.find(|token| token.text() == "never_used")
.map(|token| usize::from(token.text_range().start()))
.expect("the local is in the rendering too");
assert!(
rendering_at < file_at,
"the rendering is shorter than the file ({rendering_at} vs {file_at}), which is why the crossing exists"
);
}
fn codes_with_lines(source: &str) -> Vec<(DiagnosticCode, usize)> {
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| {
let at = finding.range.start_offset.min(source.len());
(finding.code, source[..at].matches('\n').count())
})
.collect()
})
.unwrap_or_default()
}
fn lines_of(codes: &[(DiagnosticCode, usize)]) -> Vec<(DiagnosticCode, usize)> {
codes.to_vec()
}
#[test]
fn unused_is_a_hint_that_a_client_may_grey_out() {
assert_eq!(DiagnosticCode::Unused.severity(), RuleSeverity::Hint);
assert_eq!(DiagnosticCode::Unused.tags(), &[RuleTag::Unnecessary]);
assert_eq!(DiagnosticCode::SyntaxError.severity(), RuleSeverity::Error);
assert_eq!(
DiagnosticCode::UnnecessaryBranch.severity(),
RuleSeverity::Warning
);
assert!(DiagnosticCode::ParamTypeCheck.tags().is_empty());
assert_eq!(
DiagnosticCode::IncludeNotFound.severity(),
RuleSeverity::Warning
);
}
#[test]
fn assign_type_check_reports_both_places_a_value_is_assigned() {
let declared = "int count = \"three\";\nint main() { return count; }\n";
assert!(
codes_of(declared).contains(&DiagnosticCode::AssignTypeCheck),
"a string is not an int: {:?}",
codes_of(declared)
);
let assigned = "int main() { int count = 0; count = \"four\"; return count; }\n";
assert!(
codes_of(assigned).contains(&DiagnosticCode::AssignTypeCheck),
"and the same question at an assignment: {:?}",
codes_of(assigned)
);
}
#[test]
fn assign_type_check_stays_quiet_about_a_name_the_file_declares_two_ways() {
let source = "struct Source { std::size_t GetLine(std::size_t offset); };\n\
void one(Source &s, std::size_t offset) {\n\
\x20 auto line = s.GetLine(offset);\n\
\x20 auto next = line;\n\
}\n\
void two() {\n\
\x20 std::size_t line = 1;\n\
\x20 line = 2;\n\
}\n";
assert!(
!codes_of(source).contains(&DiagnosticCode::AssignTypeCheck),
"neither `line` is judged"
);
let wrong = "void f() {\n int count = \"zero\";\n}\n";
assert!(
codes_of(wrong).contains(&DiagnosticCode::AssignTypeCheck),
"one written type is one answer"
);
}
#[test]
fn assign_type_check_stays_quiet_when_the_target_is_a_class_it_cannot_see_into() {
let source =
"#include <string>\nstd::string line = 1231;\nint main() { return (int)line.size(); }\n";
assert!(
!codes_of(source).contains(&DiagnosticCode::AssignTypeCheck),
"a conversion nobody modelled is not a fact about the program: {:?}",
codes_of(source)
);
}
#[test]
fn access_invisible_is_reported_outside_the_class() {
let source = "class Widget {\n int secret;\npublic:\n int size;\n};\n\nint main() { Widget w; return w.secret; }\n";
assert!(
codes_of(source).contains(&DiagnosticCode::AccessInvisible),
"`secret` is private and `main` is not Widget: {:?}",
codes_of(source)
);
}
#[test]
fn access_invisible_is_not_reported_for_a_public_member_or_from_inside() {
let public_member =
"class Widget {\npublic:\n int size;\n};\n\nint main() { Widget w; return w.size; }\n";
assert!(
!codes_of(public_member).contains(&DiagnosticCode::AccessInvisible),
"`size` is public: {:?}",
codes_of(public_member)
);
let from_inside =
"class Widget {\n int secret;\npublic:\n int mine() { return secret; }\n};\n";
assert!(
!codes_of(from_inside).contains(&DiagnosticCode::AccessInvisible),
"a member function may read its own class private member: {:?}",
codes_of(from_inside)
);
}
#[test]
fn missing_return_is_reported_for_a_body_that_never_returns() {
assert!(
codes_of("int count() { }\nint main() { return count(); }\n")
.contains(&DiagnosticCode::MissingReturn),
"the body returns nothing and the type is not void"
);
}
#[test]
fn missing_return_is_a_control_flow_question() {
let reported = [
"int only_one(int x) { if (x) return 1; }",
"int sometimes(int x) { if (x) throw x; }",
"int breaks() { while (true) { break; } }",
"int counted(int n) { for (int i = 0; i < n; ++i) { } }",
"int never() { if (false) return 1; }",
];
for source in reported {
assert!(
codes_of(source).contains(&DiagnosticCode::MissingReturn),
"this body can reach its closing brace: {source}"
);
}
let silent = [
"int both(int x) { if (x) return 1; else return 2; }",
"int by_switch(int x) { switch (x) { case 1: return 1; case 2: return 2; default: return 0; } }",
"int by_switch_with_blocks(int x) { switch (x) { case 1: { return 1; } default: { return 0; } } }",
"int by_switch_that_throws(int x) { switch (x) { case 1: return 1; default: throw x; } }",
"int throws() { throw 1; }",
"int throws_in_else(int x) { if (x) return 1; else throw 1; }",
"int forever() { while (true) { } }",
"int for_ever() { for (;;) { } }",
"int do_forever() { do { } while (true); }",
"int always() { if (true) return 1; }",
"auto deduced(int x) { if (x) return 1; }",
"struct S { S(int x) { if (x) { } } };",
];
for source in silent {
assert!(
!codes_of(source).contains(&DiagnosticCode::MissingReturn),
"no path reaches the end here: {source}"
);
}
}
#[test]
fn missing_return_is_silent_for_a_decorated_constructor_and_destructor() {
let decorated = "\
struct A {
explicit A(int x) : x_(x) {}
virtual ~A() {}
A() = default;
int x_;
};
struct B : A {
B() : A(0) {}
~B() override {}
};
struct C {
inline C() {}
constexpr C(int x) : x_(x) {}
~C() noexcept {}
int x_;
};
";
assert_eq!(
codes_of(decorated),
[],
"a constructor and a destructor promise nothing, whatever they are written with"
);
let written = "\
struct S { int f() { } };
int broken() { }
";
let found = codes_of(written);
assert!(
found
.iter()
.filter(|code| **code == DiagnosticCode::MissingReturn)
.count()
== 2,
"and the functions that do write a return type still report: {found:?}"
);
}
#[test]
fn missing_return_reads_the_declared_type_rather_than_the_word_void() {
let reported = [
"void *buffer() { }",
"struct W { int x; };\nstatic W make() { }",
"typedef int myint;\nstatic myint count() { }",
];
for source in reported {
assert!(
codes_of(source).contains(&DiagnosticCode::MissingReturn),
"something is promised here: {source}"
);
}
let silent = [
"typedef void nothing;\nstatic nothing stop() { }",
"static UNRESOLVED_TYPE stop() { }",
];
for source in silent {
assert!(
!codes_of(source).contains(&DiagnosticCode::MissingReturn),
"nothing is proven to be promised here: {source}"
);
}
}
#[test]
fn missing_return_is_not_reported_for_void_or_for_a_returning_body() {
assert!(
!codes_of("void stop() { }\nint main() { return 0; }\n")
.contains(&DiagnosticCode::MissingReturn),
"void expects nothing"
);
assert!(
!codes_of("int count() { return 1; }\nint main() { return count(); }\n")
.contains(&DiagnosticCode::MissingReturn),
"a body that returns is the ordinary case"
);
}
#[test]
fn the_users_own_condition_is_not_reported() {
let source = "\
int main(int argc, char** argv) {
if (arg == \"--port\" && i + 1 < argc) {
return 2;
}
const auto message = readMessage();
return (int)message;
}
";
let codes = codes_of(source);
assert!(
!codes.contains(&DiagnosticCode::AssignmentInCondition),
"a compound condition is not this rule: {codes:?}"
);
}
#[test]
fn a_less_than_in_a_condition_is_not_an_assignment() {
let source = "\
int main(int argc, char** argv) {
if (argc == 2 && argc + 1 < argc) {
const auto message = argc;
return message;
}
return 0;
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::AssignmentInCondition),
"two comparisons are not an assignment: {:?}",
codes_of(source)
);
}
#[test]
fn a_class_in_this_file_that_no_value_can_build_is_reported() {
let source = "\
struct MyString {
int size;
};
int main() {
MyString line = 1231;
return line.size;
}
";
let codes = codes_of(source);
assert!(
codes.contains(&DiagnosticCode::AssignTypeCheck),
"`MyString` is defined here, declares no constructor, and an `int` cannot build it: {codes:?}"
);
}
#[test]
fn a_finding_underlines_only_the_construct_it_is_about() {
let header = "struct MyString { int size; };\n";
let source = "#include \"mystring.h\"\n\nint main() {\n int count = \"three\";\n return count;\n}\n";
let (_, range) = first_finding_of(source, header, DiagnosticCode::AssignTypeCheck);
assert_eq!(
&source[range.start_offset..range.end_offset()],
"\"three\"",
"the finding is about the value, not about the statement it is written in"
);
}
#[test]
fn a_member_reached_through_a_using_alias_is_not_undefined() {
let source = "\
struct Base { int size; };
using Alias = Base;
void use() {
Alias a;
(void)a.size;
}
";
let codes = codes_of(source);
assert!(
!codes.contains(&DiagnosticCode::UndefinedField),
"the alias names `Base`, and `Base` has `size`: {codes:?}"
);
}
#[test]
fn a_deduced_auto_is_not_a_conversion_question() {
let source = "\
struct Widget { int n; };
Widget& make();
void use() {
int value = 1;
auto plain = value;
auto* pointer = &value;
auto& reference = make();
const auto& constant = make();
auto&& forwarded = make();
(void)plain; (void)pointer; (void)reference; (void)constant; (void)forwarded;
}
";
let codes = codes_of(source);
assert!(
!codes.contains(&DiagnosticCode::AssignTypeCheck),
"a deduced type is not a written one, so nothing here can fail to convert: {codes:?}"
);
}
fn first_finding_of(
source: &str,
header: &str,
code: DiagnosticCode,
) -> (usize, cpp_parser::SourceRange) {
let files = MemoryFiles::new()
.with_file("/p/a.cpp", source)
.with_file("/p/mystring.h", header);
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"),
std::path::PathBuf::from("/p/mystring.h"),
]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
for finding in session
.diagnostics(std::path::Path::new("/p/a.cpp"))
.map(|found| found.checks)
.unwrap_or_default()
{
if finding.code == code {
return (0, finding.range);
}
}
panic!("no `{}` finding", code.name());
}
#[test]
fn undefined_field_is_reported_for_a_name_the_class_does_not_have() {
let source = "\
struct Widget {
int size;
};
int main() {
Widget w;
return w.sizze;
}
";
assert!(
codes_of(source).contains(&DiagnosticCode::UndefinedField),
"`sizze` is not a member of `Widget`: {:?}",
codes_of(source)
);
}
#[test]
fn undefined_field_is_not_reported_for_a_member_that_is_there() {
let source = "\
struct Widget {
int size;
};
int main() {
Widget w;
return w.size;
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::UndefinedField),
"`size` is a member of `Widget`: {:?}",
codes_of(source)
);
}
#[test]
fn an_include_in_a_fixture_does_not_resolve_unless_the_test_proves_it_does() {
let header = "// a header\nstruct FromTheHeader { int size; };\n";
let source =
"#include \"big.h\"\n\nint main() {\n int never_used = 1;\n return never_used;\n}\n";
let files = MemoryFiles::new()
.with_file("/p/a.cpp", source)
.with_file("/p/big.h", header);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default().with_include_path("/p"),
);
session.add_project_files([
std::path::PathBuf::from("/p/a.cpp"),
std::path::PathBuf::from("/p/big.h"),
]);
session.index_everything();
let _ = session.view("/p/a.cpp");
session.index_everything();
let view = session.view("/p/a.cpp").expect("a view");
eprintln!(
"INCLUDE: view text {} bytes, file {} bytes, inlined={}",
view.source.len(),
source.len(),
view.source.contains("FromTheHeader")
);
assert!(
!view.source.contains("FromTheHeader"),
"if this ever starts passing, every test that assumed an include resolves needs revisiting"
);
}
#[test]
fn a_class_from_another_file_answers_unknown_rather_than_wrong() {
let cannot = "struct Widget {\n Widget(Widget&& other);\n int size;\n};\n";
let can = "struct Widget {\n Widget(int size);\n int size;\n};\n";
let source = "\
int main() {
Widget w = 1231;
return 0;
}
";
assert!(
!codes_with_two_files(source, cannot).contains(&DiagnosticCode::AssignTypeCheck),
"a class whose members are not in the index is not judged: {:?}",
codes_with_two_files(source, cannot)
);
assert!(
!codes_with_two_files(source, can).contains(&DiagnosticCode::AssignTypeCheck),
"and the one with the right constructor is not reported either: {:?}",
codes_with_two_files(source, can)
);
}
fn codes_with_two_files(source: &str, other: &str) -> Vec<DiagnosticCode> {
let files = MemoryFiles::new()
.with_file("/p/a.cpp", source)
.with_file("/p/other.h", other);
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"),
std::path::PathBuf::from("/p/other.h"),
]);
session.index_everything();
let _ = session.view("/p/a.cpp");
session.index_everything();
session
.diagnostics(std::path::Path::new("/p/a.cpp"))
.map(|found| found.checks.iter().map(|finding| finding.code).collect())
.unwrap_or_default()
}
#[test]
fn a_callee_from_another_file_is_not_judged_until_the_lookup_answers() {
let other = "int scale(int value, int factor);\n";
let too_many = "\
int main() {
int x = scale(1, 2, 3);
return x;
}
";
let here = "\
int scale(int value, int factor) { return value * factor; }
int main() {
int x = scale(1, 2, 3);
return x;
}
";
assert!(
codes_of(here).contains(&DiagnosticCode::ArgumentCount),
"a callee declared in this file is judged: {:?}",
codes_of(here)
);
assert!(
!codes_with_two_files(too_many, other).contains(&DiagnosticCode::ArgumentCount),
"and one declared in another file is not judged yet: {:?}",
codes_with_two_files(too_many, other)
);
}
#[test]
fn a_function_templates_type_that_carries_its_header_is_not_judged() {
let source = "\
template<class Service>
void AddService(Service service) {
int unused_index = 0;
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::MissingReturn),
"`void` after a template header is still `void`: {:?}",
codes_of(source)
);
let really_missing = "\
int AddService(int service) {
int unused_index = 0;
}
";
assert!(
codes_of(really_missing).contains(&DiagnosticCode::MissingReturn),
"and an `int` function with no return is still a finding: {:?}",
codes_of(really_missing)
);
}
#[test]
fn a_construction_and_a_default_argument_are_not_conversions_to_judge() {
let constructions = "\
enum class LineSpaceType { Keep };
struct LineSpace { LineSpace(LineSpaceType); };
LineSpace line_space_after_if_statement = LineSpace(LineSpaceType::Keep);
";
assert!(
!codes_of(constructions).contains(&DiagnosticCode::AssignTypeCheck),
"the initialiser names the target type: {:?}",
codes_of(constructions)
);
let defaults = "\
struct Position { Position(int line, int character); };
struct Range { Range(Position start = Position(0, 0)); };
";
assert!(
!codes_of(defaults).contains(&DiagnosticCode::AssignTypeCheck),
"a default argument is the parameter's declaration, not a variable's: {:?}",
codes_of(defaults)
);
let real_mismatch = "\
void g() {
int count = \"four\";
}
";
assert!(
codes_of(real_mismatch).contains(&DiagnosticCode::AssignTypeCheck),
"and a string assigned to an int is still a finding: {:?}",
codes_of(real_mismatch)
);
}
#[test]
fn a_call_whose_name_is_also_a_type_is_not_judged_for_arity() {
let source = "\
struct NameStyleRule {
int value;
};
void NameStyleRule(int first, int second) {}
void g() {
NameStyleRule(1);
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::ArgumentCount),
"the name is a type here, so the call constructs rather than calls: {:?}",
codes_of(source)
);
}
#[test]
fn an_arrow_is_judged_against_the_class_it_reaches() {
let through_a_pointer = "\
struct Session {
void Run();
};
void g(Session *session) {
session->Run();
}
";
assert_eq!(codes_of(through_a_pointer), [], "`Run` is the pointee's");
let a_missing_member = "\
struct Session {
void Run();
};
void g(Session *session) {
session->Missing();
}
";
assert_eq!(
codes_of(a_missing_member),
[DiagnosticCode::UndefinedField],
"`Session` has no `Missing`, and the arrow reaches `Session`"
);
let an_untraceable_arrow = "\
struct Session {
void Run();
};
struct Pointer {
Missing *operator->();
};
void g(Pointer pointer) {
pointer->Run();
}
";
assert_eq!(
codes_of(an_untraceable_arrow),
[],
"the pointee cannot be typed, so nothing is said"
);
}
#[test]
fn a_member_call_is_not_judged_against_a_free_function_of_the_same_name() {
let source = "\
struct Session {
void Run();
};
void Run(int value, int other) {}
void g(Session session) {
session.Run();
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::ArgumentCount),
"`session.Run()` is the member, not the free `Run(int, int)`: {:?}",
codes_of(source)
);
}
#[test]
fn a_templates_own_parameter_is_silent_to_the_type_check_and_the_arity_check_still_judges_it() {
let silent = "\
template <typename T>
void take(T value);
void g() {
take(1);
take(\"one\");
}
";
assert!(
!codes_of(silent).contains(&DiagnosticCode::ParamTypeCheck),
"a `T` parameter is the argument's own type however it was deduced: {:?}",
codes_of(silent)
);
let wrong_arity = "\
template <typename T>
void take(T value);
void g() {
take(1, 2);
}
";
assert!(
codes_of(wrong_arity).contains(&DiagnosticCode::ArgumentCount),
"the arity of a template is in its tokens, so it is judged: {:?}",
codes_of(wrong_arity)
);
}
#[test]
fn an_overload_set_is_resolved_rather_than_judged_against_its_last_declaration() {
let well_formed = "\
void f(int) {}
void f(int, int) {}
void g() {
f(1);
f(1, 2);
}
";
assert!(
!codes_of(well_formed).contains(&DiagnosticCode::ArgumentCount),
"every call fits a declaration: {:?}",
codes_of(well_formed)
);
let nothing_fits = "\
void f(int) {}
void f(int, int) {}
void g() {
f(1, 2, 3);
}
";
assert!(
codes_of(nothing_fits).contains(&DiagnosticCode::ArgumentCount),
"no declaration takes three arguments: {:?}",
codes_of(nothing_fits)
);
}
#[test]
fn every_code_has_a_name_and_the_name_comes_back() {
for code in DiagnosticCode::ALL {
let name = code.name();
assert!(!name.is_empty(), "{code:?} has no name");
assert_eq!(
DiagnosticCode::from_name(name),
Some(code),
"`{name}` does not come back as {code:?}"
);
}
}
#[test]
fn a_parameter_pack_is_not_a_fixed_arity() {
let declarations = "\
template <class... Args>
void forward_all(Args&&... args);
template <class... Args>
void forward_plain(Args... args);
void classic(const char* format, ...);
";
let calls = "\
#include \"other.h\"
void use() {
forward_all(1, 2, 3);
forward_plain(1, 2, 3);
classic(\"%d %d %d\", 1, 2, 3);
}
";
let codes = codes_with_two_files(calls, declarations);
assert!(
!codes.contains(&DiagnosticCode::ArgumentCount),
"every callee here takes as many arguments as it is given: {codes:?}"
);
}
#[test]
fn a_member_written_inside_a_template_class_is_found() {
let source = "\
template <class T>
struct Box {
void push(T value);
};
void g(Box<int> box) {
box.push(1);
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::UndefinedField),
"`push` is a member of the template: {:?}",
codes_of(source)
);
}
#[test]
fn a_member_reached_through_an_alias_to_a_template_is_found() {
let source = "\
namespace nlohmann {
template <class T>
class basic_json {
public:
void push_back(T value);
};
using json = basic_json<int>;
}
void g(nlohmann::json array) {
array.push_back(3);
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::UndefinedField),
"`push_back` is a member of `basic_json`, which `json` names: {:?}",
codes_of(source)
);
}
#[test]
fn the_nlohmann_shape_keeps_its_member() {
let source = "\
namespace nlohmann {
template <class T>
class basic_json {
public:
using array_t = int;
static array_t array();
void push_back(int value);
};
using json = basic_json<int>;
}
template <class T>
nlohmann::json SerializeArray(std::vector<T>& vec) {
nlohmann::json array = nlohmann::json::array();
for (auto& v : vec) {
array.push_back(1);
(void)v;
}
return array;
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::UndefinedField),
"`push_back` is a member of `basic_json`: {:?}",
codes_of(source)
);
}
#[test]
fn a_member_of_a_class_with_an_unread_base_is_not_reported() {
let source = "\
struct D : Missing {
void f();
};
void g(D d) {
d.not_read_anywhere();
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::UndefinedField),
"the list is partial, so the absence is not evidence: {:?}",
codes_of(source)
);
}
#[test]
fn a_two_parameter_constructor_cannot_be_built_from_one_value() {
let source = "\
struct S {
S(int count, int other);
};
void g() {
S s = 123;
}
";
assert!(
codes_of(source).contains(&DiagnosticCode::AssignTypeCheck),
"one value cannot fill two parameters: {:?}",
codes_of(source)
);
let defaulted = "\
struct S {
S(int count, int other = 0);
};
void g() {
S s = 123;
}
";
assert!(
!codes_of(defaulted).contains(&DiagnosticCode::AssignTypeCheck),
"a defaulted parameter does not need a value: {:?}",
codes_of(defaulted)
);
}
#[test]
fn a_member_parameter_is_checked_after_instantiation() {
let source = "\
namespace std {
template <class T>
class vector {
public:
void push_back(T value);
};
}
void f() {
std::vector<int> v;
v.push_back(\"text\");
}
";
assert!(
codes_of(source).contains(&DiagnosticCode::ParamTypeCheck)
|| codes_of(source).contains(&DiagnosticCode::ArgumentCount),
"an `int` parameter does not take a string literal: {:?}",
codes_of(source)
);
}
#[test]
fn a_member_call_whose_argument_fits_is_silent() {
let source = "\
namespace std {
template <class T>
class vector {
public:
void push_back(T value);
};
}
void f() {
std::vector<int> v;
v.push_back(1);
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::ParamTypeCheck),
"an `int` for an `int` is right: {:?}",
codes_of(source)
);
}
#[test]
fn a_template_parameter_is_not_a_missing_include() {
const DB_H: &str = "\
template <class K, class V, class Container>
class DBase {
public:
V* find(const K& key);
private:
Container _hash;
};
";
let codes = codes_of_files(
&[
("/p/container.h", "class Container {};\n"),
("/p/db.h", DB_H),
],
"/p/db.h",
);
assert!(
!codes.contains(&DiagnosticCode::MissingInclude),
"`Container` is the class's own template parameter: {codes:?}"
);
const USES_A_STRANGER: &str = "\
void f(NotHere* value) {}
";
let codes = codes_of_files(
&[
("/p/nothere.h", "class NotHere {};\n"),
("/p/uses.cpp", USES_A_STRANGER),
],
"/p/uses.cpp",
);
assert!(
codes.contains(&DiagnosticCode::MissingInclude),
"a type the file neither declares nor includes is the rule's own case: {codes:?}"
);
}
#[test]
fn a_forward_declaration_in_an_included_header_is_not_a_missing_include() {
let codes = codes_of_files(
&[
("/p/mark.h", "class Parser;\n"),
(
"/p/tree.h",
"#include \"mark.h\"\nstruct Tree {\n void Build(Parser& p);\n};\n",
),
(
"/p/parser.h",
"class Parser {\npublic:\n int Parse();\n};\n",
),
],
"/p/tree.h",
);
assert!(
!codes.contains(&DiagnosticCode::MissingInclude),
"the forward declaration in mark.h is what the reference needs: {codes:?}"
);
let codes = codes_of_files(
&[
(
"/p/tree.h",
"struct Tree {\n void Build(Parser& p);\n};\n",
),
(
"/p/parser.h",
"class Parser {\npublic:\n int Parse();\n};\n",
),
],
"/p/tree.h",
);
assert!(
codes.contains(&DiagnosticCode::MissingInclude),
"nothing in this file reaches `Parser`: {codes:?}"
);
}
fn codes_of_files(files: &[(&str, &str)], asking: &str) -> Vec<DiagnosticCode> {
let mut memory = MemoryFiles::new();
for (path, text) in files {
memory = memory.with_file(*path, *text);
}
let providers = SessionFiles::new(OpenDocuments::new(), memory);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
let paths: Vec<std::path::PathBuf> = files
.iter()
.map(|(path, _)| std::path::PathBuf::from(path))
.collect();
session.add_project_files(paths);
session.want_cooked_reading(std::path::Path::new(asking));
session.index_everything();
session
.diagnostics(std::path::Path::new(asking))
.map(|found| {
found
.checks
.iter()
.map(|finding| finding.code)
.chain(found.errors.iter().map(|error| error.code))
.collect()
})
.unwrap_or_default()
}
#[test]
fn a_member_argument_is_checked_through_a_header_and_against_every_overload() {
let header = "\
#pragma once
#include <cstddef>
template <class T>
struct Box {
void push_back(const T& value);
void push_back(T&& value);
T& front();
};
";
let file = "\
#include \"box.h\"
void f() {
Box<int> b;
b.push_back(\"text\");
}
";
let codes = codes_of_files(&[("/p/box.h", header), ("/p/a.cpp", file)], "/p/a.cpp");
assert!(
codes.contains(&DiagnosticCode::ParamTypeCheck),
"a string literal for a `const int&` parameter is not right: {codes:?}"
);
let fits = file.replace("b.push_back(\"text\");", "b.push_back(1);");
let codes = codes_of_files(&[("/p/box.h", header), ("/p/a.cpp", &fits)], "/p/a.cpp");
assert!(
!codes.contains(&DiagnosticCode::ParamTypeCheck),
"an `int` for an `int` is right: {codes:?}"
);
}
#[test]
fn a_default_argument_written_in_the_header_is_not_a_missing_argument() {
let header = "\
void report(int a, int b = 0);
int twice(int a, int b = 1);
";
let source = "\
#include \"api.h\"
void report(int a, int b) { (void)a; (void)b; }
int twice(int a, int b) { return a * b; }
void use() {
report(1);
report(1, 2);
(void)twice(2);
}
";
let codes = codes_of_files(&[("/p/api.h", header), ("/p/a.cpp", source)], "/p/a.cpp");
assert!(
!codes.contains(&DiagnosticCode::ArgumentCount),
"both parameters are defaulted in the header: {codes:?}"
);
let strict = "\
#include \"api.h\"
void only(int a, int b);
void report(int a, int b) { (void)a; (void)b; }
int twice(int a, int b) { return a * b; }
void use() { only(1); }
";
let header_with_only = format!("{header}void only(int a, int b);\n");
let codes = codes_of_files(
&[("/p/api.h", &header_with_only), ("/p/a.cpp", strict)],
"/p/a.cpp",
);
assert!(
codes.contains(&DiagnosticCode::ArgumentCount),
"`only` has no defaulted parameter: {codes:?}"
);
}
#[test]
fn an_overload_that_takes_the_argument_keeps_the_check_silent() {
let one_fits = "\
struct Widget {
void resize(int width);
void resize(const char* text);
};
void f() {
Widget w;
w.resize(\"wide\");
}
";
assert!(
!codes_of(one_fits).contains(&DiagnosticCode::ParamTypeCheck),
"the second overload takes a string literal: {:?}",
codes_of(one_fits)
);
let none_fit = "\
struct Widget {
void resize(int width);
void resize(double width);
};
void f() {
Widget w;
w.resize(\"wide\");
}
";
assert!(
codes_of(none_fit).contains(&DiagnosticCode::ParamTypeCheck),
"neither overload takes a string literal, so this is a finding: {:?}",
codes_of(none_fit)
);
}
#[test]
fn a_member_call_on_a_plain_class_is_checked() {
let source = "\
struct Widget {
void resize(int width);
};
void f() {
Widget w;
w.resize(\"wide\");
}
";
assert!(
codes_of(source).contains(&DiagnosticCode::ParamTypeCheck),
"a string literal for an `int` is not right: {:?}",
codes_of(source)
);
}
#[test]
fn a_member_call_with_too_many_arguments_is_a_different_finding() {
let source = "\
struct Widget {
void resize(int width);
};
void f() {
Widget w;
w.resize(1, 2);
}
";
assert!(
codes_of(source).contains(&DiagnosticCode::ArgumentCount),
"one parameter, two arguments: {:?}",
codes_of(source)
);
}
#[test]
fn a_free_function_call_is_still_checked() {
let source = "\
void resize(int) { }
void f() {
resize(\"wide\");
}
";
assert!(
codes_of(source).contains(&DiagnosticCode::ParamTypeCheck),
"the free path is unchanged: {:?}",
codes_of(source)
);
}
#[test]
fn a_named_parameter_is_checked_too() {
let source = "\
void resize(int width) { }
void f() {
resize(\"wide\");
}
";
assert!(
codes_of(source).contains(&DiagnosticCode::ParamTypeCheck),
"the name is not part of the type: {:?}",
codes_of(source)
);
}
#[test]
fn an_assignment_compared_against_something_is_quiet() {
let idiom = "struct Q { int value() const; };\n\
void f(Q q) {\n int op = 0;\n if ((op = q.value()) != 0) { return; }\n}\n";
assert!(
!codes_of(idiom).contains(&DiagnosticCode::AssignmentInCondition),
"a compared assignment is the shape the rule allows: {:?}",
codes_of(idiom)
);
for reported in [
"void f() {\n int x = 0;\n if (x = 1) { return; }\n}\n",
"void f() {\n int x = 0; int a = 0; int b = 0;\n if (x = a < b) { return; }\n}\n",
] {
assert!(
codes_of(reported).contains(&DiagnosticCode::AssignmentInCondition),
"{reported}: {:?}",
codes_of(reported)
);
}
}
#[test]
fn zero_is_a_null_pointer_constant() {
let source = "\
struct P {
P(int* pointer);
};
void f() {
P p = 0;
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::AssignTypeCheck),
"`0` is the null pointer constant: {:?}",
codes_of(source)
);
}
#[test]
fn a_member_of_a_class_template_is_checked_after_substitution() {
let header = "\
namespace std {
template <class _Tp>
class vector {
public:
using value_type = _Tp;
void push_back(const value_type& __x);
};
}
";
let source = "\
#include \"vector.h\"
int main()
{
std::vector<int> anotherVec;
anotherVec.push_back(\"123131\");
return 0;
}
";
let codes = codes_of_files(&[("/p/vector.h", header), ("/p/a.cpp", source)], "/p/a.cpp");
{
let files = MemoryFiles::new()
.with_file("/p/vector.h", header)
.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/vector.h"),
std::path::PathBuf::from("/p/a.cpp"),
]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.want_cooked_reading(std::path::Path::new("/p/vector.h"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("held");
match session.members_of(&view, "std::vector<int>") {
cpp_code_analysis::Known::Yes(list) => {
for member in &list.members {
eprintln!(
"PROBE {:?} kind {:?} params {:?} type_of {:?}",
member.fact.name,
member.fact.kind,
member.fact.parameter_list(),
member.fact.type_of
);
}
}
other => eprintln!("PROBE members_of: {other:?}"),
}
}
assert!(
codes.contains(&DiagnosticCode::ParamTypeCheck),
"the argument is a string literal and the parameter is `const int&`: {codes:?}"
);
}
#[test]
fn a_member_parameter_written_with_the_class_alias_is_checked() {
let header = "\
namespace std {
template <class _Tp>
class vector {
public:
using value_type = _Tp;
void push_back(const value_type& __x);
};
}
";
let source = "\
#include \"vector.h\"
int main()
{
std::vector<int> anotherVec;
anotherVec.push_back(\"123131\");
return 0;
}
";
let file = "/p/vector.h";
let caller = "/p/a.cpp";
let mut memory = MemoryFiles::new()
.with_file(file, header)
.with_file(caller, source);
let providers = SessionFiles::new(OpenDocuments::new(), memory.clone());
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files([
std::path::PathBuf::from(file),
std::path::PathBuf::from(caller),
]);
session.want_cooked_reading(std::path::Path::new(file));
session.want_cooked_reading(std::path::Path::new(caller));
session.index_everything();
let codes: Vec<DiagnosticCode> = session
.diagnostics(std::path::Path::new(caller))
.map(|found| found.checks.iter().map(|finding| finding.code).collect())
.unwrap_or_default();
let _ = &mut memory;
assert!(
codes.contains(&DiagnosticCode::ParamTypeCheck),
"the argument is a string literal and the parameter is `const value_type&` = `const int&`: {codes:?}"
);
}
#[test]
fn an_int_does_not_convert_to_a_string() {
let source = "\
namespace std {
class string {
public:
string(const char* text);
};
}
void writeMessage(const std::string& json);
void f() {
writeMessage(123131);
}
";
let found = codes_of(source);
println!("codes: {found:?}");
assert!(
found.contains(&DiagnosticCode::ParamTypeCheck),
"an `int` is not a `std::string`: {found:?}"
);
}
#[test]
fn a_diagnostic_follows_the_locale() {
let source = "int f() { int unused_local = 1; return 0; }\n";
let messages = |locale: &str| {
cpp_parser::set_locale(locale);
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.message.clone())
.collect::<Vec<_>>()
})
.unwrap_or_default()
};
let english = messages("en");
let chinese = messages("zh-CN");
cpp_parser::set_locale("en");
println!("en: {english:?}\nzh: {chinese:?}");
let unused = |list: &[String]| {
list.iter()
.find(|message| message.contains("unused_local"))
.cloned()
.unwrap_or_else(|| panic!("the unused check reports it: {list:?}"))
};
assert!(
unused(&english).contains("never used"),
"{:?}",
unused(&english)
);
assert!(
unused(&chinese).contains("从未使用"),
"the message is translated: {:?}",
unused(&chinese)
);
}
#[test]
fn an_argument_that_does_not_satisfy_its_concept_is_reported() {
let source = "\
template <std::integral T>
T twice(T value) { return value + value; }
int f() {
twice(2);
twice(\"text\");
return 0;
}
";
let messages = messages_of(source);
println!("{messages:?}");
let finding = messages
.iter()
.find(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied)
.unwrap_or_else(|| panic!("the `const char*` call is reported: {messages:?}"));
assert!(finding.1.contains("std::integral"), "{finding:?}");
assert!(
finding.1.contains("char"),
"the message names the type that was passed: {finding:?}"
);
assert_eq!(
messages
.iter()
.filter(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied)
.count(),
1,
"`twice(2)` satisfies it and is silent: {messages:?}"
);
}
#[test]
fn a_templated_base_is_compared_by_the_class_it_names() {
let derives = "\
template <std::derived_from<std::vector<int>> T>
void take(T value);
struct Derived : public std::vector<int> {};
int f() {
Derived d;
take(d);
return 0;
}
";
let messages = messages_of(derives);
assert!(
!messages
.iter()
.any(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied),
"`Derived` derives from `std::vector<int>`: {messages:?}"
);
let does_not = "\
template <std::derived_from<std::vector<int>> T>
void take(T value);
struct Plain {};
int f() {
Plain p;
take(p);
return 0;
}
";
let messages = messages_of(does_not);
assert!(
messages
.iter()
.any(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied),
"`Plain` derives from nothing: {messages:?}"
);
}
#[test]
fn an_undecidable_concept_says_nothing() {
let source = "\
template <class T>
concept Small = sizeof(T) <= 4;
template <Small T>
T keep(T value) { return value; }
int f() {
keep(1.0);
return 0;
}
";
let messages = messages_of(source);
assert!(
!messages
.iter()
.any(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied),
"{messages:?}"
);
}
fn messages_of(source: &str) -> Vec<(DiagnosticCode, String)> {
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, finding.message.clone()))
.collect()
})
.unwrap_or_default()
}
#[test]
fn the_project_config_turns_rules_off_and_on() {
let source = "int f() { int unused_local = 1; return 0; }\n";
let messages_with = |config: &str| {
let files = MemoryFiles::new()
.with_file("/p/a.cpp", source)
.with_file("/p/.cppls.toml", config);
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)
.collect::<Vec<_>>()
})
.unwrap_or_default()
};
assert!(
messages_with("").contains(&DiagnosticCode::Unused),
"the rule is on by default"
);
let disabled = messages_with("[diagnostics]\ndisable = [\"unused\"]\n");
assert!(
!disabled.contains(&DiagnosticCode::Unused),
"`disable` turns it off: {disabled:?}"
);
let only = messages_with("[diagnostics]\nenable = [\"param-type-check\"]\n");
assert!(
!only.contains(&DiagnosticCode::Unused),
"`enable` is `only these`: {only:?}"
);
}
#[test]
fn a_concept_over_the_class_hierarchy_and_over_objectness() {
let hierarchy = "\
struct Base { virtual ~Base(); };
struct Derived : public Base { };
template <std::derived_from<Base> T>
void handle(T& value);
void f(Derived d, int n) {
handle(d);
handle(n);
}
";
let messages = messages_of(hierarchy);
println!("{messages:?}");
let concept_findings: Vec<&(DiagnosticCode, String)> = messages
.iter()
.filter(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied)
.collect();
assert_eq!(
concept_findings.len(),
1,
"`handle(n)` is not derived from `Base`: {messages:?}"
);
assert!(
concept_findings[0].1.contains("derived_from"),
"{concept_findings:?}"
);
let objectness = "\
template <std::copyable T>
T copy_of(T value) { return value; }
int f(int n) {
copy_of(n);
return 0;
}
";
let messages = messages_of(objectness);
println!("{messages:?}");
assert!(
!messages
.iter()
.any(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied),
"`int` is copyable and the check must not guess about a class: {messages:?}"
);
}
#[test]
fn a_constraint_declared_in_a_header_is_checked_at_the_call() {
let header = "\
#pragma once
struct Base { virtual ~Base(); };
struct Derived : public Base { };
template <std::derived_from<Base> T>
void handle(T& value);
";
let source = "\
#include \"b.h\"
void f(Derived d, int n) {
handle(d);
handle(n);
}
";
let files = MemoryFiles::new()
.with_file("/p/b.h", header)
.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/b.h"),
std::path::PathBuf::from("/p/a.cpp"),
]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let messages: Vec<(DiagnosticCode, String)> = session
.diagnostics(std::path::Path::new("/p/a.cpp"))
.map(|found| {
found
.checks
.iter()
.map(|finding| (finding.code, finding.message.clone()))
.collect()
})
.unwrap_or_default();
println!("{messages:?}");
let concept_findings: Vec<&(DiagnosticCode, String)> = messages
.iter()
.filter(|(code, _)| *code == DiagnosticCode::ConceptNotSatisfied)
.collect();
assert_eq!(
concept_findings.len(),
1,
"`handle(n)` is reported from the header's constraint: {messages:?}"
);
assert!(
concept_findings[0].1.contains("derived_from"),
"{concept_findings:?}"
);
}
fn codes_of_with(source: &str, path: &str, standard: Option<&str>) -> Vec<DiagnosticCode> {
let files = MemoryFiles::new().with_file(path, source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let config = CompilerConfig {
standard: standard.map(|standard| standard.into()),
..CompilerConfig::default()
};
let mut session = Session::with_config("/p", providers, WatchFilter::new("/p"), config);
session.add_project_files([std::path::PathBuf::from(path)]);
session.want_cooked_reading(std::path::Path::new(path));
session.index_everything();
session
.diagnostics(std::path::Path::new(path))
.map(|found| {
found
.checks
.iter()
.map(|finding| finding.code)
.chain(found.errors.iter().map(|error| error.code))
.collect()
})
.unwrap_or_default()
}
#[test]
fn a_c_project_is_not_told_to_write_named_casts() {
const SOURCE: &str = "\
typedef struct { int v; } T;
int f(void) { double d = 1.5; T t; t.v = (int)d; return t.v; }
";
let in_c = codes_of_with(SOURCE, "/p/a.c", Some("gnu11"));
assert!(
!in_c.contains(&DiagnosticCode::CStyleCast),
"a C program has no named casts, so the rule is not about it: {in_c:?}"
);
let tmp = codes_of_with(SOURCE, "/p/a.cpp", Some("gnu++17"));
assert!(
tmp.contains(&DiagnosticCode::CStyleCast),
"the same cast in C++ is the rule's own case: {tmp:?}"
);
}
#[test]
fn a_cast_argument_is_not_a_missing_argument() {
const SOURCE: &str = "\
static void three(int a, int b, int c) { (void)a; (void)b; (void)c; }
void one(int x) { three((int)x, 2, 3); }
void two(int x) { three((int)x, 2, x == 0); }
";
let codes = codes_of_with(SOURCE, "/p/a.c", Some("gnu11"));
assert!(
!codes.contains(&DiagnosticCode::ArgumentCount),
"every call here passes three arguments: {codes:?}"
);
let wrong = "static void two_args(int a, int b) { (void)a; (void)b; }\nvoid f(int x) { two_args((int)x, 2, 3); }\n";
assert!(
codes_of_with(wrong, "/p/a.c", Some("gnu11")).contains(&DiagnosticCode::ArgumentCount),
"three arguments for two parameters is the rule's own case"
);
}
#[test]
fn a_c_style_cast_is_reported_in_cpp_and_not_in_c() {
let source = "int f(double c) { return (unsigned)c; }\n";
assert!(
codes_of_a_file("/p/a.cpp", source).contains(&DiagnosticCode::CStyleCast),
"the fixture must produce the finding where the rule applies"
);
assert!(
!codes_of_a_file("/p/a.c", source).contains(&DiagnosticCode::CStyleCast),
"…and not in a `.c` file, where `(unsigned)c` is how the conversion is written"
);
}
#[test]
fn a_nested_class_has_its_members() {
let nested = "\
class outer {
public:
class inner {
public:
inner(bool e) : at_end_(e) {}
bool operator!=(const inner &other) const { return at_end_ != other.at_end_; }
private:
bool at_end_ = true;
};
};
";
assert_eq!(
codes_of(nested),
[],
"a member written in the class is not undefined: {:?}",
codes_of(nested)
);
let missing = "\
class outer {
public:
class inner {
public:
int at_end_ = 0;
};
};
void f() { outer::inner i; i.missing_; }
";
assert_eq!(
codes_of(missing),
[DiagnosticCode::UndefinedField],
"a member the nested class does not declare is still reported"
);
}
#[test]
fn a_coroutine_body_has_no_missing_return() {
for (name, source) in [
(
"co_yield",
"generator make(int from) {\n for (int i = 0; i < from; ++i) { co_yield i; }\n}\n",
),
(
"co_return",
"int compute(int v) {\n co_return v + 1;\n}\n",
),
(
"co_await",
"int wait(int v) {\n int x = co_await v;\n return x;\n}\n",
),
] {
assert_eq!(
codes_of(source),
[],
"{name}: a coroutine body needs no `return`"
);
}
assert_eq!(
codes_of("int count() {\n}\n"),
[DiagnosticCode::MissingReturn],
"a plain function with no return is still reported"
);
}
#[test]
fn a_name_that_nothing_declares_is_reported() {
let source = "\
struct Widget { int size; };
void f() {
missing.size;
}
";
assert_eq!(
codes_of(source),
[DiagnosticCode::UndefinedName],
"nothing declares `missing`"
);
}
#[test]
fn a_declared_name_is_not_reported_and_a_later_one_is() {
let declared = "\
struct Widget { int size; };
void f() {
Widget w;
w.size;
}
";
assert_eq!(codes_of(declared), [], "`w` is declared two lines up");
let later = "\
struct Widget { int size; };
void f() {
w.size;
}
Widget w;
";
assert_eq!(
codes_of(later),
[DiagnosticCode::UndefinedName],
"`w` is declared after the use, so it is not visible there"
);
}
#[test]
fn the_rule_is_quiet_where_a_name_may_be_declared_elsewhere() {
let macro_defined = "\
struct Widget { int size; };
#define receiver w
void f() {
Widget w;
receiver.size;
}
";
assert_eq!(codes_of(macro_defined), []);
let templated = "\
template <class T>
struct Derived : T {
void f() { count.size; }
};
";
assert_eq!(codes_of(templated), [], "a template body is not judged");
let lambda = "\
struct Widget { int size; };
void f() {
Widget w;
auto g = [&w]() { w.size; };
}
";
assert_eq!(
codes_of(lambda),
[],
"a capture is not a name the scope tree holds"
);
let from_a_header = "\
#include \"b.h\"
void f() {
from_header.size;
}
";
let header = "\
struct Widget { int size; };
extern Widget from_header;
";
let codes: Vec<DiagnosticCode> = codes_of_a_two_file_fixture(from_a_header, header);
assert_eq!(codes, [], "`from_header` is declared in the header");
}
fn codes_of_a_two_file_fixture(source: &str, header: &str) -> Vec<DiagnosticCode> {
let files = MemoryFiles::new()
.with_file("/p/a.cpp", source)
.with_file("/p/b.h", header);
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"),
std::path::PathBuf::from("/p/b.h"),
]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.want_cooked_reading(std::path::Path::new("/p/b.h"));
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_call_to_a_name_nothing_declares_is_reported() {
let undeclared = "\
void f() {
printh(\"x\", 12);
}
";
assert_eq!(
codes_of(undeclared),
[DiagnosticCode::UndefinedName],
"nothing declares `printh`, and its arguments are a string literal and an int"
);
let adl = "\
struct Widget { int size; };
void f(Widget w) {
swap(w, w);
}
";
assert_eq!(codes_of(adl), [], "`swap` may be found by ADL");
let macro_call = "\
#define LOG(x) report(x)
void report(int value);
void f() {
LOG(1);
}
";
assert_eq!(codes_of(macro_call), []);
let from_a_header = "\
void log_name(const char *name, int count);
";
let caller = "\
#include \"b.h\"
void f() {
log_name(\"x\", 1);
}
";
assert_eq!(
codes_of_a_two_file_fixture(caller, from_a_header),
[],
"`log_name` is declared in the header"
);
}
#[test]
fn a_name_declared_twice_in_one_scope_is_reported() {
let twice = "\
void f() {
int count = 1;
int count = 2;
}
";
assert_eq!(codes_of(twice), [DiagnosticCode::Redefinition]);
let twice_with_auto = "\
struct W { int size; };
void f() {
auto x = 123;
auto x = W{};
}
";
assert_eq!(codes_of(twice_with_auto), [DiagnosticCode::Redefinition]);
let shadows_a_parameter = "\
void f(int count) {
int count = 2;
}
";
assert_eq!(
codes_of(shadows_a_parameter),
[DiagnosticCode::Redefinition]
);
}
#[test]
fn a_repeat_the_language_has_a_reading_for_is_quiet() {
let two_blocks = "\
void f() {
{ int count = 1; }
{ int count = 2; }
}
";
assert_eq!(codes_of(two_blocks), []);
let overloads = "\
void run();
void run(int value);
void f() { run(); run(1); }
";
assert_eq!(codes_of(overloads), []);
let forward_and_definition = "\
class Widget;
class Widget { int size; };
";
assert_eq!(codes_of(forward_and_definition), []);
let extern_and_definition = "\
extern int value;
int value = 0;
";
assert_eq!(codes_of(extern_and_definition), []);
let shadowing = "\
void f() {
int count = 1;
{ int count = 2; }
}
";
assert_eq!(codes_of(shadowing), []);
}
#[test]
fn a_braced_initialiser_and_a_const_copy_are_not_failed_conversions() {
let codes = codes_of_a_file(
"/p/corpus.c",
"\
struct point { int x; int y; };
struct point origin = {0, 0};
struct point unit = {.x = 1, .y = 1};
",
);
assert!(
!codes.contains(&DiagnosticCode::AssignTypeCheck),
"a braced initialiser is the initialiser of the target's own type: {codes:?}"
);
let codes = codes_of_a_file(
"/p/corpus.c",
"\
struct point { int x; int y; };
static const struct point origin = {0, 0};
struct point copy = origin;
",
);
assert!(
!codes.contains(&DiagnosticCode::AssignTypeCheck),
"a `const` object converts to its own unqualified type: {codes:?}"
);
}
#[test]
fn the_c_spellings_void_restrict_and_static_assert_produce_no_finding() {
let codes = codes_of_a_file(
"/p/void.c",
"\
int f(void);
int g(void) { return f(); }
",
);
assert!(
!codes.contains(&DiagnosticCode::ArgumentCount),
"`(void)` declares no parameters: {codes:?}"
);
let codes = codes_of_with(
"/p/restrict.c",
"\
int sum(int *restrict left, int *restrict right) { return *left + *right; }
",
Some("c17"),
);
assert!(
!codes.contains(&DiagnosticCode::Redefinition),
"`restrict` qualifies a pointer and declares nothing: {codes:?}"
);
let codes = codes_of_with(
"/p/assert.c",
"\
int f(void) {
_Static_assert(1, \"a compile-time claim\");
return 0;
}
",
Some("c17"),
);
assert!(
!codes.contains(&DiagnosticCode::UndefinedName),
"`_Static_assert` is C11's declaration: {codes:?}"
);
}
#[test]
fn the_cpp_only_rules_are_known_by_name() {
let marked: Vec<DiagnosticCode> = DiagnosticCode::ALL
.iter()
.copied()
.filter(|code| code.is_cpp_only())
.collect();
assert_eq!(
marked,
vec![
DiagnosticCode::AccessInvisible,
DiagnosticCode::ModuleNote,
DiagnosticCode::UseNullptr,
DiagnosticCode::UseOverride,
DiagnosticCode::CStyleCast,
DiagnosticCode::UseAuto,
DiagnosticCode::ImplicitBoolConversion,
DiagnosticCode::ConceptNotSatisfied,
DiagnosticCode::DanglingField,
DiagnosticCode::UeNaming,
DiagnosticCode::UeGenerateBody,
DiagnosticCode::UeGeneratedHeader,
DiagnosticCode::UeMacroScope,
DiagnosticCode::UeSpecifier,
DiagnosticCode::ContractOnVirtualFunction,
DiagnosticCode::ContractOnDefaultedFunction,
DiagnosticCode::OverrideNonexistent,
DiagnosticCode::FinalMisplaced,
DiagnosticCode::FinalClassDerived,
DiagnosticCode::OverrideOfFinal,
DiagnosticCode::AbstractClassInstantiated,
DiagnosticCode::PureVirtualNotOverridden,
]
);
}
#[test]
fn c_files_are_not_told_to_write_cpp_style() {
let source = "\
int *p = NULL;
void f(int n) {
if (n) {
p = (int *)p;
}
}
";
let cpp_only = [
DiagnosticCode::UseNullptr,
DiagnosticCode::ImplicitBoolConversion,
DiagnosticCode::CStyleCast,
];
let in_c = codes_of_with(source, "/p/style.c", Some("c17"));
for code in cpp_only {
assert!(
!in_c.contains(&code),
"{code:?} is C++ only, and this file is compiled as C: {in_c:?}"
);
}
let in_cpp = codes_of_with(source, "/p/style.cpp", Some("c++20"));
for code in cpp_only {
assert!(
in_cpp.contains(&code),
"{code:?} should fire in C++: {in_cpp:?}"
);
}
}
#[test]
fn compiler_builtins_and_c_keyword_constructs_are_not_undefined_names() {
let codes = codes_of_with(
"/p/builtins.c",
"\
static int probe(int value) {
if (__builtin_expect(value > 0, 1)) {
return (int)__builtin_offsetof(struct point, y);
}
return __builtin_constant_p(value);
}
",
Some("gnu17"),
);
assert!(
!codes.contains(&DiagnosticCode::UndefinedName),
"`__builtin_*` is the implementation's: {codes:?}"
);
let codes = codes_of_with(
"/p/keywords.c",
"\
int classify(int value) {
_Static_assert(sizeof(int) >= 2, \"an int is at least two bytes\");
return _Generic(value, int: 1, default: 0);
}
",
Some("c17"),
);
assert!(
!codes.contains(&DiagnosticCode::UndefinedName),
"`_Static_assert` and `_Generic` are keywords, not calls: {codes:?}"
);
}
#[test]
fn a_headers_c11_construct_and_a_compiler_builtin_are_not_undefined_names() {
let codes = codes_of_with(
"/p/headers.c",
"\
int classify(int value) {
if (__builtin_expect(value > 0, 1)) {
return 1;
}
return _Generic(value, int: 2, default: 3);
}
",
Some("gnu17"),
);
assert!(
!codes.contains(&DiagnosticCode::UndefinedName),
"a builtin and a keyword construct are both not names: {codes:?}"
);
}
#[test]
fn a_struct_from_a_call_and_a_static_restrict_function_are_quiet() {
let codes = codes_of_with(
"/p/copy.c",
"\
struct point { int x; int y; };
struct point make(void) { struct point made = {0, 0}; return made; }
struct point copy = make();
",
Some("c17"),
);
assert!(
!codes.contains(&DiagnosticCode::AssignTypeCheck),
"a `struct point` initialised from a `struct point` is a copy: {codes:?}"
);
let codes = codes_of_with(
"/p/static.c",
"\
static int strict(int *restrict left, int *restrict right) { return *left + *right; }
",
Some("c17"),
);
assert!(
!codes.contains(&DiagnosticCode::Redefinition),
"`restrict` on a `static` function's parameter is a qualifier: {codes:?}"
);
}
#[test]
fn a_calling_convention_before_the_name_is_not_part_of_the_return_type() {
let codes = codes_of_with(
"/p/cdecl.c",
"\
typedef struct { int quot; int rem; } div_t;
extern div_t __cdecl div(int numerator, int denominator);
div_t divided = div(7, 2);
",
Some("gnu17"),
);
assert!(
!codes.contains(&DiagnosticCode::AssignTypeCheck),
"`__cdecl` is a calling convention, not a type: {codes:?}"
);
}
#[test]
fn a_type_behind_two_typedefs_converts_to_itself() {
let codes = codes_of_with(
"/p/two_levels.c",
"\
typedef struct { int quot; int rem; } _div_t;
typedef _div_t div_t;
extern div_t div(int numerator, int denominator);
div_t divided = div(7, 2);
",
Some("gnu17"),
);
assert!(
!codes.contains(&DiagnosticCode::AssignTypeCheck),
"`div_t` and the type of `div(…)` are one type: {codes:?}"
);
}
#[test]
fn a_conversion_whose_declaration_is_in_a_header_is_still_a_conversion() {
let header = "\
#ifndef STDLIB_H
#define STDLIB_H
typedef struct { int quot; int rem; } _div_t;
typedef _div_t div_t;
extern div_t __cdecl div(int numerator, int denominator);
#endif
";
let source = "\
#include \"stdlib.h\"
div_t divided = div(7, 2);
";
let files = MemoryFiles::new()
.with_file("/p/stdlib.h", header)
.with_file("/p/library.c", source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let config = CompilerConfig {
standard: Some("gnu17".into()),
..CompilerConfig::default()
};
let mut session = Session::with_config("/p", providers, WatchFilter::new("/p"), config);
session.add_project_files([
std::path::PathBuf::from("/p/stdlib.h"),
std::path::PathBuf::from("/p/library.c"),
]);
session.want_cooked_reading(std::path::Path::new("/p/library.c"));
session.index_everything();
while session.pending_work() > 0 {
session.advance(64);
}
let codes: Vec<DiagnosticCode> = session
.diagnostics(std::path::Path::new("/p/library.c"))
.map(|found| {
found
.checks
.into_iter()
.map(|finding| finding.code)
.collect()
})
.unwrap_or_default();
assert!(
!codes.contains(&DiagnosticCode::AssignTypeCheck),
"`div_t` from a header is the same type as `div_t` in the file: {codes:?}"
);
}
#[test]
fn a_header_declaration_counts_even_when_the_definition_is_later_in_the_file() {
let header = "\
#ifndef STDLIB_H
#define STDLIB_H
typedef struct { int quot; int rem; } _div_t;
typedef _div_t div_t;
extern div_t div(int numerator, int denominator);
#endif
";
let source = "\
#include \"stdlib.h\"
div_t divided = div(7, 2);
div_t div(int numerator, int denominator) {
div_t result;
result.quot = numerator / denominator;
result.rem = numerator % denominator;
return result;
}
";
let files = MemoryFiles::new()
.with_file("/p/stdlib.h", header)
.with_file("/p/library.c", source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let config = CompilerConfig {
standard: Some("gnu17".into()),
..CompilerConfig::default()
};
let mut session = Session::with_config("/p", providers, WatchFilter::new("/p"), config);
session.add_project_files([
std::path::PathBuf::from("/p/stdlib.h"),
std::path::PathBuf::from("/p/library.c"),
]);
session.want_cooked_reading(std::path::Path::new("/p/library.c"));
session.index_everything();
while session.pending_work() > 0 {
session.advance(64);
}
let codes: Vec<DiagnosticCode> = session
.diagnostics(std::path::Path::new("/p/library.c"))
.map(|found| {
found
.checks
.into_iter()
.map(|finding| finding.code)
.collect()
})
.unwrap_or_default();
assert!(
!codes.contains(&DiagnosticCode::UndefinedName),
"the header declares `div` before the use: {codes:?}"
);
}
#[test]
fn only_an_unparenthesised_expression_body_is_a_macro_parentheses_finding() {
let codes = codes_of_a_file(
"/p/macros.c",
"\
#define TWICE(x) x * 2
#define CALL(f, v) f(v)
#define STRINGIFY(v) #v
#define DECLARE(name, v) static int name = (v)
#define FRAGMENT(name) COLOUR_##name = 1,
// **The corpus's own shapes**, with the line continuations that make a body more than one line: a statement
// expression, a `do { } while (0)`, and a declaration list.
#define STATEMENT(x) \
({ \
int t = (x); \
t * t; \
})
#define ASSERT(c) \
do { \
if (!(c)) { \
} \
} while (0)
#define DEFINE(name, v) \
static int name = (v)
",
);
assert!(
codes.contains(&DiagnosticCode::MacroParentheses),
"`x * 2` is the shape this rule exists for: {codes:?}"
);
assert_eq!(
codes
.iter()
.filter(|code| **code == DiagnosticCode::MacroParentheses)
.count(),
1,
"and it is the only one: {codes:?}"
);
}
#[test]
fn a_generic_selection_with_typed_associations_parses() {
let codes = codes_of_with(
"\
static int name_of(int value) {
return (int)strlen(_Generic((value), int: \"int\", double: \"double\", long: \"long\", char*: \"char *\", const char*: \"const char *\", default: \"other\"));
}
",
"/p/generic.c",
Some("gnu17"),
);
assert!(
!codes.contains(&DiagnosticCode::SyntaxError),
"a `_Generic` with six associations is C11: {codes:?}"
);
}
#[test]
fn a_generic_macro_pasted_into_a_call_parses() {
let codes = codes_of_with(
"\
#define CORPUS_TYPE_NAME(value) _Generic((value), \
int: \"int\", \
double: \"double\", \
long: \"long\", \
char *: \"char *\", \
const char *: \"const char *\", \
default: \"other\")
static int name_of(int integer) {
return (int)strlen(CORPUS_TYPE_NAME(integer));
}
",
"/p/generic_macro.c",
Some("gnu17"),
);
assert!(
!codes.contains(&DiagnosticCode::SyntaxError),
"the macro's body is one `_Generic` selection: {codes:?}"
);
}
#[test]
fn an_x_macro_pastes_its_names() {
let codes = codes_of_with(
"\
#define LIST(X) X(red, 0) X(green, 1)
#define ENTRY(name, value) COLOUR_##name = value,
#define NAME_ENTRY(name, value) #name,
enum colours { LIST(ENTRY) COLOUR_COUNT };
static const char *const NAMES[] = {LIST(NAME_ENTRY) \"count\"};
",
"/p/xmacro.c",
Some("gnu17"),
);
assert!(
!codes.contains(&DiagnosticCode::SyntaxError),
"the pasted names are identifiers: {codes:?}"
);
}
#[test]
fn a_macro_that_expands_to_a_generic_selection_is_one_argument() {
let codes = codes_of_with(
"\
extern unsigned long long strlen(const char *text);
#define TYPE_NAME(value) _Generic((value), int: \"int\", double: \"double\", long: \"long\", default: \"other\")
static int name_of(int integer) {
return (int)strlen(TYPE_NAME(integer));
}
",
"/p/one_argument.c",
Some("gnu17"),
);
assert!(
!codes.contains(&DiagnosticCode::ArgumentCount),
"one argument, four associations inside it: {codes:?}"
);
}
#[test]
fn a_local_in_a_statement_expression_is_not_a_redefinition() {
let codes = codes_of_with(
"\
#define SQUARE(value) ({ int squared = (value); squared * squared; })
static int twice(int first, int second) {
int a = SQUARE(first);
int b = SQUARE(second);
return a + b;
}
",
"/p/statement.c",
Some("gnu17"),
);
assert!(
!codes.contains(&DiagnosticCode::Redefinition),
"two statement expressions, two scopes: {codes:?}"
);
}
#[test]
fn the_corpus_square_body_reads_its_last_statement_as_an_expression() {
let codes = codes_of_with(
"\
#define SQUARE(value) \
({ \
int corpus_square = (value); \
corpus_square *corpus_square; \
})
static int squared(int value) {
int total = 0;
total += SQUARE(value);
return total;
}
",
"/p/square.c",
Some("gnu17"),
);
assert!(
!codes.contains(&DiagnosticCode::Redefinition),
"`corpus_square *corpus_square;` is a multiplication: {codes:?}"
);
}
#[test]
fn a_restrict_parameter_after_other_declarations_is_not_a_name() {
let codes = codes_of_with(
"\
static int a_const_int = 7;
static int *const const_pointer = (int *)&a_const_int;
static const int *const const_pointer_to_const = &a_const_int;
static volatile int a_volatile_int = 3;
static volatile const int volatile_const_int = 4;
static int restrict_sum(int *restrict left, int *restrict right) {
return *left + *right;
}
",
"/p/restrict.c",
Some("c17"),
);
assert!(
!codes.contains(&DiagnosticCode::Redefinition),
"two `restrict` parameters are two qualifiers: {codes:?}"
);
}
#[test]
fn an_unnamed_namespaces_member_is_visible_later_in_the_file() {
let codes = codes_of(
"\
namespace {
int helper(int value) { return value + 1; }
int counter = 0;
}
int use_helper(int value) { return helper(value) + counter; }
",
);
assert!(
!codes.contains(&DiagnosticCode::UndefinedName),
"an unnamed namespace's members are visible here: {codes:?}"
);
}
#[test]
fn a_marked_or_lifetime_object_is_not_reported_unused() {
let marked = codes_of(
"\
void f() {
[[maybe_unused]] int local = 3;
}
",
);
assert!(
!marked.contains(&DiagnosticCode::Unused),
"the attribute is the answer: {marked:?}"
);
let lifetime = codes_of(
"\
struct Guard { explicit Guard(int& counter) : counter_(counter) { ++counter_; } ~Guard() { --counter_; } int& counter_; };
void f() {
int counter = 0;
Guard guard(counter);
}
",
);
assert!(
!lifetime.contains(&DiagnosticCode::Unused),
"an object whose use is its lifetime is not unused: {lifetime:?}"
);
let plain = codes_of(
"\
void f() {
int local = 3;
}
",
);
assert!(
plain.contains(&DiagnosticCode::Unused),
"an unmarked builtin is still reported: {plain:?}"
);
}
#[test]
fn a_variable_named_like_its_type_keeps_that_type() {
let codes = codes_of(
"\
void f() {
std::any any = 1;
any = std::string{\"anything\"};
}
",
);
assert!(
!codes.contains(&DiagnosticCode::AssignTypeCheck),
"`std::any any` is an `std::any`, and both assignments convert: {codes:?}"
);
}
#[test]
fn a_variadic_macro_call_is_not_an_argument_count_finding() {
let codes = codes_of_with(
"\
#define SUM(count, ...) (sum_impl)(count __VA_OPT__(, ) __VA_ARGS__)
int sum_impl(int count, ...);
int f(void) {
int total = 0;
return SUM(total, 1, 2, 3);
}
",
"/p/variadic.c",
Some("gnu17"),
);
assert!(
!codes.contains(&DiagnosticCode::ArgumentCount),
"a variadic macro takes any number of arguments: {codes:?}"
);
}
#[test]
fn a_variadic_macro_whose_callee_is_a_definition_is_not_an_argument_count_finding() {
let codes = codes_of_with(
"\
#define C23_SUM(count, ...) (c23_sum_impl)(count __VA_OPT__(, ) __VA_ARGS__)
static int c23_sum_impl(int count, ...) { return count; }
int c23_va_opt(int count, ...) { return C23_SUM(count, 1, 2, 3) + count; }
",
"/p/vaopt.c",
Some("c23"),
);
assert!(
!codes.contains(&DiagnosticCode::ArgumentCount),
"a variadic callee takes any number of arguments: {codes:?}"
);
}
#[test]
fn the_include_directory_beside_src_resolves_a_quoted_include() {
let root = std::env::temp_dir().join("cppls-include-layout");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("include")).expect("the layout is created");
std::fs::create_dir_all(root.join("src")).expect("the layout is created");
std::fs::write(
root.join("include/techniques.h"),
"struct Widget { int size() const; };\n",
)
.expect("the header is written");
let source =
"#include \"techniques.h\"\n\nint use() { Widget widget; return widget.size(); }\n";
std::fs::write(root.join("src/techniques.cpp"), source).expect("the source is written");
let mut session = cpp_code_analysis::Session::open(
root.clone(),
cpp_code_analysis::SessionFiles::new(
cpp_code_analysis::OpenDocuments::new(),
cpp_code_analysis::DiskFiles,
),
cpp_code_analysis::WatchFilter::new(&root),
);
session.add_project_files([
root.join("src/techniques.cpp"),
root.join("include/techniques.h"),
]);
session.index_everything();
session.cook(root.join("src/techniques.cpp"));
let found = session
.diagnostics(root.join("src/techniques.cpp"))
.expect("the file is analysed");
let codes: Vec<&str> = found.checks.iter().map(|check| check.code.name()).collect();
assert!(
!codes.contains(&"include-not-found"),
"`include/` beside `src/` is on the search path: {codes:?}"
);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn a_parameter_that_is_the_callees_template_parameter_takes_anything() {
let codes = codes_of_with(
"\
struct Opt {
template <typename U>
int value_or(U&& other) const;
};
int f() {
Opt o;
return o.value_or(0);
}
",
"/p/a.cpp",
Some("c++20"),
);
assert!(
!codes.contains(&DiagnosticCode::ParamTypeCheck),
"`U` is deduced from the argument: {codes:?}"
);
}
#[test]
fn a_template_parameter_member_overload_set_is_silent() {
let codes = codes_of_with(
"\
struct Opt {
template <typename U> int value_or(U&& other) const &;
template <typename U> int value_or(U&& other) &&;
};
int f() {
Opt o;
return o.value_or(0);
}
",
"/p/a.cpp",
Some("c++20"),
);
assert!(
!codes.contains(&DiagnosticCode::ParamTypeCheck),
"neither overload has a type to check `0` against: {codes:?}"
);
}
#[test]
fn a_friends_code_may_read_what_is_private() {
let codes = codes_of_with(
"\
class Holder {\
friend class Borrower;\
int secret = 1;\
};\
class Borrower {\
public:\
int peek(Holder& holder) { return holder.secret; }\
};\
",
"/p/a.cpp",
Some("c++20"),
);
assert!(
!codes.contains(&DiagnosticCode::AccessInvisible),
"the friend declaration permits it: {codes:?}"
);
}
#[test]
fn an_out_of_class_definition_may_read_its_own_private_member() {
let codes = codes_of_with(
"\
struct Outer {
struct Inner {
int peek() const;
private:
int secret = 1;
};
};
int peek() const;\
private:\
int secret = 1;\
};\
int Holder::peek() const { return secret; }\
",
"/p/a.cpp",
Some("c++20"),
);
assert!(
!codes.contains(&DiagnosticCode::AccessInvisible),
"the definition is the class's own code: {codes:?}"
);
}
#[test]
fn a_template_parameter_is_not_judged_against_a_concept() {
let codes = codes_of_with(
"\
template <class _Tp>
concept floating = __is_floating_point(_Tp);
void takes_a_float(floating auto value) { (void)value; }
void takes_an_int(int value) { (void)value; }
template <class _Tp>
void forward_it(_Tp&& value) {
takes_an_int(1);
(void)value;
}
",
"/p/a.cpp",
Some("c++20"),
);
assert!(
!codes.contains(&DiagnosticCode::ConceptNotSatisfied),
"a parameter is not a type: {codes:?}"
);
}
#[test]
fn missing_return_is_silent_for_an_out_of_class_constructor_and_destructor() {
let source = "\
struct S { S(int x); ~S(); int f(); };
S::S(int x) : _x(x) { Initialize(); }
S::~S() { }
int S::f() { }
int free_function() { }
";
let codes = codes_of(source);
let reports = codes
.iter()
.filter(|code| **code == DiagnosticCode::MissingReturn)
.count();
assert_eq!(
reports, 2,
"`int S::f()` and `int free_function()` promise a return and have none: {codes:?}"
);
}
#[test]
fn a_template_parameter_parameter_is_never_a_mismatch() {
let source = "
namespace std {
template <class T> T&& move(T& value) noexcept;
template <class _Ty> class vector {
public:
void push_back(const _Ty& value);
};
class string {};
}
void f() {
std::vector<std::string> lines;
std::string line;
lines.push_back(std::move(line));
}
";
assert!(
!codes_of(source).contains(&DiagnosticCode::ParamTypeCheck),
"`const _Ty&` takes what the call decides: {:?}",
codes_of(source)
);
}
fn errors_of_a_file(path: &str, source: &str) -> Vec<String> {
let files = MemoryFiles::new().with_file(path, 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(path)]);
session.want_cooked_reading(std::path::Path::new(path));
session.index_everything();
session
.diagnostics(std::path::Path::new(path))
.map(|found| {
found
.errors
.iter()
.map(|error| error.message.clone())
.collect()
})
.unwrap_or_default()
}
#[test]
fn a_c_file_may_name_things_cpp_reserves() {
let c = errors_of_a_file(
"/p/a.c",
"struct O { int x; };\nstruct O new = { 0 };\nvoid f(int delete) { (void)delete; }\n",
);
assert!(c.is_empty(), "those are names in C: {c:?}");
let cpp = errors_of_a_file("/p/a.cpp", "int new = 0;\n");
assert!(
!cpp.is_empty(),
"the same text in C++ is the keyword, and the declaration is not one"
);
}
#[test]
fn a_dereference_in_a_call_argument_is_not_a_redeclaration() {
let dereference = "\
void xfree(void *p);
void f(char **matches) { xfree(*matches); }
";
assert_eq!(
codes_of_a_file("/p/a.c", dereference),
Vec::new(),
"a call's argument declares nothing"
);
let declaration = "\
struct T { int n; };
void f(void) {
T (*p);
(void)p;
}
";
assert_eq!(
codes_of_a_file("/p/a.c", declaration),
Vec::new(),
"`T (*p);` declares `p` and nothing repeats"
);
let repeated = "\
void f(void) {
int count = 1;
int count = 2;
(void)count;
}
";
assert_eq!(
codes_of_a_file("/p/a.c", repeated),
[DiagnosticCode::Redefinition],
"two variables of one name in one scope is what the rule is for"
);
}
#[test]
fn the_null_pointer_constant_returns_from_a_pointer_function() {
let null_constant = "\
int *find(int n) {
if (n > 0) {
return 0;
}
return 0;
}
";
assert_eq!(
codes_of_a_file("/p/a.c", null_constant),
Vec::new(),
"`return 0;` is a null pointer, not a type error"
);
let mismatched = "\
int *find(int n) {
return n;
}
";
assert_eq!(
codes_of_a_file("/p/a.c", mismatched),
[DiagnosticCode::ReturnTypeMismatch],
"`int` does not convert to `int *`"
);
}