quick-lint-js icon indicating copy to clipboard operation
quick-lint-js copied to clipboard

10$: Warn on if("x"||"y"), case "x"||"y":, etc.

Open strager opened this issue 1 year ago • 8 comments

if ("x" || "y") { // expect: diagnostic
}

switch (s) {
  case "x" || "y": // expect: diagnostic
    break;
}

strager avatar Mar 19 '23 01:03 strager

Could I ask what coding language this is expected to be done in?

ybl3 avatar Mar 29 '23 18:03 ybl3

@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.

strager avatar Mar 29 '23 19:03 strager

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 avatar Mar 29 '23 19:03 ybl3

@ybl3 Do you need any help with this task?

strager avatar Apr 11 '23 22:04 strager

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?

ybl3 avatar Apr 12 '23 07:04 ybl3

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).

strager avatar Apr 12 '23 07:04 strager

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; }

Ripak2005 avatar Feb 03 '24 07:02 Ripak2005

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.

AdityaSripalle avatar Feb 24 '24 17:02 AdityaSripalle