quick-lint-js
quick-lint-js copied to clipboard
10$: Warn on if("x"||"y"), case "x"||"y":, etc.
if ("x" || "y") { // expect: diagnostic
}
switch (s) {
case "x" || "y": // expect: diagnostic
break;
}
Could I ask what coding language this is expected to be done in?
@ybl3 C++.
The patch would probably look like this:
- Add a new diagnostic type. See docs: https://quick-lint-js.com/contribute/create-diagnostic/
- Add a function in src/quick-lint-js/fe/parse.cpp similar to
parser::error_on_sketchy_condition
. Call this function as appropriate. - Add a test case in test/test-parse-warning.cpp based on an existing test case.
Cool, I claim this for-hire task. I expect payment after I complete this task. I will email the quick-lint-js team if I am assigned this task. I am doing this for a University of Michigan assignment.
@ybl3 Do you need any help with this task?
Is this warning only for || conditions, or for all conditions with string literals? Also, should I consider all string literals, including empty ones ("")? Also, is this warning more geared towards someone that accidentally put quotation marks around a variable name, or just for preventing unnecessary code, or both?
Is this warning only for || conditions, or for all conditions with string literals?
Good question. I think we should do just ||
for now.
Also, should I consider all string literals, including empty ones ("")?
Yes. We might want to emit different messages in these different cases.
Also, is this warning more geared towards someone that accidentally put quotation marks around a variable name, or just for preventing unnecessary code, or both?
For case "x"||"y":
, the suggestion should be to write case "x": case "y":
instead.
For if ("x" || "y")
, I don't know what was intended, but we can say that the condition will always be true (similar to E0346).
if ("x" === s || "y" === s) { // Code to execute if s is either "x" or "y" }
switch (s) { case "x": // Code to execute if s is "x" break; case "y": // Code to execute if s is "y" break; default: // Code to execute if s is neither "x" nor "y" break; }
The issue lies in the incorrect use of logical operators || within the if statement and the switch case. In C++, logical operators like || are used for combining conditions, but they cannot be directly used to compare values as done in the code snippet.