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 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());
}
#[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_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)
);
}
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 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 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), []);
}