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 天 11 小时
- 30 天内合并 PR
- 129
贡献指南
从这里开始
- 先读完整个 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 未关闭false-positive
难度 4/5 3-5 天 新手友好度 15/100
-
false-positive
难度 3/5 1-2 天 新手友好度 68/100
相似的 Issue
-
难度 2/5 1-3 小时 新手友好度 90/100
duckdb/duckdb-python#627 ·
-
难度 2/5 1-3 小时 新手友好度 78/100
phpstan/phpstan-doctrine#794 ·
-
难度 2/5 1-3 小时 新手友好度 88/100
-
难度 1/5 1 小时以内 新手友好度 78/100
nearform/ag-grid-url-sync#160 ·
-
难度 2/5 1-3 小时 新手友好度 78/100
idean3885/claude-ops-agent#521 ·