use super::{assert_reported, assert_silent_about, codes_of};
use crate::DiagnosticCode;
#[test]
fn an_assignment_as_the_whole_condition_is_reported() {
let if_stat = codes_of("void f() {\n int x = 0;\n if (x = 1) { return; }\n}\n");
assert_reported(
&if_stat,
DiagnosticCode::AssignmentInCondition,
"`x = 1` is the condition",
);
let while_stat =
codes_of("int read();\nvoid f() {\n int line = 0;\n while (line = read()) { }\n}\n");
assert_reported(
&while_stat,
DiagnosticCode::AssignmentInCondition,
"`line = read()` is the condition",
);
}
#[test]
fn an_assignment_whose_right_side_compares_is_still_reported() {
let codes = codes_of(
"void f() {\n int x = 0;\n int a = 1;\n int b = 2;\n if (x = a < b) { return; }\n}\n",
);
assert_reported(
&codes,
DiagnosticCode::AssignmentInCondition,
"the operator under the condition is `=`",
);
}
#[test]
fn a_comparison_is_silent() {
let equal = codes_of("void f() {\n int x = 0;\n if (x == 1) { return; }\n}\n");
assert_silent_about(
&equal,
DiagnosticCode::AssignmentInCondition,
"`==` is a comparison",
);
let at_least = codes_of("void f(int a, int b) {\n if (a >= b) { return; }\n}\n");
assert_silent_about(
&at_least,
DiagnosticCode::AssignmentInCondition,
"the `=` of `>=` is not the condition's operator",
);
}
#[test]
fn a_compound_condition_is_silent() {
let and_chain = codes_of(
"void f() {\n int x = 0;\n bool ok = true;\n if (x = 1 && ok) { return; }\n}\n",
);
assert_silent_about(
&and_chain,
DiagnosticCode::AssignmentInCondition,
"the condition is a `&&`, not an assignment",
);
let comma = codes_of(
"void f() {\n int x = 0;\n int y = 1;\n if (x = y, x > 0) { return; }\n}\n",
);
assert_silent_about(
&comma,
DiagnosticCode::AssignmentInCondition,
"the comma expression's last operand is what is tested",
);
let inside_a_literal =
codes_of("void f() {\n const char* s = 0;\n if (s == \"a=b\") { return; }\n}\n");
assert_silent_about(
&inside_a_literal,
DiagnosticCode::AssignmentInCondition,
"the `=` is inside a string literal",
);
}
#[test]
fn an_assignment_inside_an_expression_is_silent() {
let argument =
codes_of("void g(int v);\nvoid f() {\n int x = 0;\n if (g(x = 1)) { return; }\n}\n");
assert_silent_about(
&argument,
DiagnosticCode::AssignmentInCondition,
"the assignment is an argument, not the condition",
);
let idiom = codes_of(
"struct Q { int value() const; };\nvoid f(Q q) {\n int op = 0;\n if ((op = q.value()) != 0) { return; }\n}\n",
);
assert_silent_about(
&idiom,
DiagnosticCode::AssignmentInCondition,
"the assignment is parenthesised and its result is compared",
);
}