use super::{assert_reported, assert_silent_about, codes_in, codes_of};
use crate::DiagnosticCode;
#[test]
fn a_local_nothing_reads_is_reported() {
let unused = codes_of("int main() { int never_used = 1; return 0; }\n");
assert_reported(
&unused,
DiagnosticCode::Unused,
"`never_used` is written once in the file",
);
let used = codes_of("int main() { int used = 1; return used; }\n");
assert_silent_about(
&used,
DiagnosticCode::Unused,
"`used` is read on the next line",
);
}
#[test]
fn a_marked_variable_is_silent() {
let underscored = codes_of("int main() { int _unused = 1; return 0; }\n");
assert_silent_about(
&underscored,
DiagnosticCode::Unused,
"a leading underscore is a deliberate choice",
);
let attributed = codes_of("void f() {\n [[maybe_unused]] int local = 3;\n}\n");
assert_silent_about(
&attributed,
DiagnosticCode::Unused,
"the attribute is the reader answering the rule's question",
);
}
#[test]
fn a_lifetime_object_is_silent() {
let codes = codes_of("struct Guard { ~Guard(); };\nvoid f() {\n Guard guard;\n}\n");
assert_silent_about(
&codes,
DiagnosticCode::Unused,
"only a builtin's type says by itself that it has no destructor",
);
}
#[test]
fn a_name_written_elsewhere_in_the_file_is_silent() {
let codes = codes_of("void f() {\n int count = 1;\n}\nvoid g() {\n int count = 2;\n}\n");
assert_silent_about(
&codes,
DiagnosticCode::Unused,
"`count` is written twice in the file, so neither declaration is certainly unread",
);
}
#[test]
fn a_parameter_and_a_global_are_not_locals() {
let parameter = codes_of("void f(int unused_parameter) { }\n");
assert_silent_about(
¶meter,
DiagnosticCode::Unused,
"a parameter is not reported",
);
let global = codes_of("int global_value = 0;\nvoid f() { }\n");
assert_silent_about(
&global,
DiagnosticCode::Unused,
"a file-scope variable is not a local",
);
}
#[test]
fn a_header_is_not_a_source_file() {
let codes = codes_in(
&[("/p/a.h", "void f() {\n int unused_in_a_header = 3;\n}\n")],
"/p/a.h",
);
assert_silent_about(&codes, DiagnosticCode::Unused, "the file is a header");
}
#[test]
fn a_use_written_as_a_macro_argument_counts() {
let source = "\
#define checkvalres(res) { if (res == -1) break; }
static int f (int o) {
switch (o) {
case 1: {
int res = 0;
checkvalres(res);
return res;
}
}
return 0;
}
";
let codes = codes_of(source);
assert_silent_about(
&codes,
DiagnosticCode::Unused,
"`res` is read by the macro invocation and by the return",
);
}
#[test]
fn a_use_inside_a_header_macro_counts() {
let files = [
(
"/p/limits.h",
"#define cast_sizet(x) ((size_t)(x))\n\
#define CHECK(x) { if ((x) == -1) break; }\n",
),
(
"/p/a.c",
"#include \"limits.h\"\n\
int f (int o, long n) {\n\
switch (o) {\n\
case 1: {\n\
int res = g(o, cast_sizet(n));\n\
CHECK(res);\n\
return res;\n\
}\n\
}\n\
return 0;\n\
}\n",
),
];
let codes = codes_in(&files, "/p/a.c");
assert_silent_about(
&codes,
DiagnosticCode::Unused,
"`res` is read by the header macro's argument and by the return",
);
}