C#: cs/simplifiable-boolean-expression false positive on Nullable<bool> compared with a literal
還沒有人認領這個 Issue。
評估
研究方向
先從 SimplifyBoolExpr.ql 中的 simplifyBinaryExpr 開始,然後檢查 == 和 != 字面量情況如何判定運算元型別。使用 issue 中的 nullable-bool 範例,驗證比較不再產生 alert,同時現有的簡化行為維持不變。
由索引模型根據 Issue 內容生成。
描述
Description of the false positive
cs/simplifiable-boolean-expression flags x == false and x == true when x is a bool? (Nullable<bool>), suggesting !x / x. The suggestion is not equivalent and does not compile: !x on a bool? is CS0266/CS0023, and using a bool? directly as a condition is CS0266. Comparing a nullable bool with a literal is the idiomatic way to write "has a value and it is false", and it is also the form EF Core translates cleanly (x is false is not allowed in an expression tree, and x.HasValue && !x.Value is what the rule is meant to steer people away from).
simplifyBinaryExpr in SimplifyBoolExpr.ql only matches on the operator; it never checks the operand's type. Restricting the ==/!=-with-literal cases to operands whose type is bool (not Nullable<bool>) would remove the false positive.
The alert is raised as a Code Quality finding on every PR touching one of these comparisons, and there is no way to filter a rule under Code Quality's default setup, so it recurs.
Code samples or links to source code
public class Rule
{
public bool? ScanToLocation { get; set; }
public int? LocationId { get; set; }
}
// Flagged: "The expression 'A == false' can be simplified to '!A'."
// !r.ScanToLocation does not compile for a bool?.
var rules = context.Rules
.Where(r => r.ScanToLocation == false && r.LocationId != null)
.ToList();
// Also flagged, same problem
var off = rules.Where(r => r.ScanToLocation == false);
Expected: no alert when the operand is Nullable<bool>.
URL to the alert on GitHub code scanning (optional)
Private repository (Code Quality PR comments, CodeQL CLI 2.27.0 with the code-quality suite).
- 主要語言
- CodeQL
- 星號
- 10.1k
- 分支
- 2.1k
- 平均合併
- 2 天 10 小時
- 30 天內合併 PR
- 134
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
github/codeql 的其他 Issue
-
難度 2/5 1-3 小時 新手友好度 84/100
-
難度 2/5 1-3 小時 新手友好度 78/100
-
false-positive
難度 2/5 1-3 小時 新手友好度 70/100
-
false-positive
難度 3/5 1-2 天 新手友好度 68/100
-
難度 4/5 3-5 天 新手友好度 55/100
相似的 Issue
-
難度 2/5 1-3 小時 新手友好度 88/100
use-agent-os/agent-os#3314 ·
-
agentic-workflows
難度 1/5 1 小時以內 新手友好度 85/100
githubnext/rig#534 ·
-
documentation low-priority templates
難度 2/5 1-3 小時 新手友好度 85/100
jesseray718/openroot#87 ·
-
factory-active factory-automatic task-bug-reproduction-cannot-reproduce task-identify-harness-labels-done task-identify-issue-type-done
難度 2/5 1-3 小時 新手友好度 84/100
-
enhancement
難度 2/5 1-3 小時 新手友好度 74/100
ReedClanton/NixOS#41 ·