From 3aa54d6bda64e3b8ccc8ee97981303da71f3001a Mon Sep 17 00:00:00 2001 From: Anders Schack-Mulligen Date: Thu, 3 Dec 2026 13:16:58 +0100 Subject: [PATCH 1/4] Unified: Add more BinaryExpr AST classes in AstExtra. --- .../lib/codeql/unified/internal/AstExtra.qll | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/unified/ql/lib/codeql/unified/internal/AstExtra.qll b/unified/ql/lib/codeql/unified/internal/AstExtra.qll index 80944c2359b4..6a4f09efb56c 100644 --- a/unified/ql/lib/codeql/unified/internal/AstExtra.qll +++ b/unified/ql/lib/codeql/unified/internal/AstExtra.qll @@ -43,6 +43,46 @@ module Public { override Expr getValue() { result = this.getRight() } } + /** A compound assignment with a bitwise AND operator. */ + class AssignBitwiseAndExpr extends CompoundAssignExpr { + AssignBitwiseAndExpr() { this.getOperator().getValue() = "&=" } + } + + /** A compound assignment with a bitwise OR operator. */ + class AssignBitwiseOrExpr extends CompoundAssignExpr { + AssignBitwiseOrExpr() { this.getOperator().getValue() = "|=" } + } + + /** A compound assignment with a bitwise XOR operator. */ + class AssignBitwiseXorExpr extends CompoundAssignExpr { + AssignBitwiseXorExpr() { this.getOperator().getValue() = "^=" } + } + + /** A compound assignment with a short-circuiting logical AND operator. */ + class AssignLogicalAndExpr extends CompoundAssignExpr { + AssignLogicalAndExpr() { this.getOperator().getValue() = "&&=" } + } + + /** A compound assignment with a short-circuiting logical OR operator. */ + class AssignLogicalOrExpr extends CompoundAssignExpr { + AssignLogicalOrExpr() { this.getOperator().getValue() = "||=" } + } + + /** A compound assignment with a short-circuiting null-coalescing operator. */ + class AssignNullCoalescingExpr extends CompoundAssignExpr { + AssignNullCoalescingExpr() { this.getOperator().getValue() = "??=" } + } + + /** A bitwise AND expression. */ + class BitwiseAndExpr extends BinaryExpr { + BitwiseAndExpr() { this.getOperator().getValue() = "&" } + } + + /** A bitwise OR expression. */ + class BitwiseOrExpr extends BinaryExpr { + BitwiseOrExpr() { this.getOperator().getValue() = "|" } + } + /** A short-circuiting logical AND expression. */ class LogicalAndExpr extends BinaryExpr { LogicalAndExpr() { this.getOperator().getValue() = "&&" } @@ -63,6 +103,20 @@ module Public { LogicalNotExpr() { this.getOperator().(PrefixOperator).getValue() = "!" } } + private predicate equalityTest(string op, boolean polarity) { + op = "==" and polarity = true + or + op = "!=" and polarity = false + } + + /** An equality test expression. This includes both equals and not-equals comparisons. */ + class EqualityTest extends BinaryExpr { + EqualityTest() { equalityTest(this.getOperator().getValue(), _) } + + /** Gets a boolean indicating whether this is an equals test (true) or a not-equals test (false). */ + boolean getPolarity() { equalityTest(this.getOperator().getValue(), result) } + } + /** * Declaration of a local or top-level variable. */ From a0197d861a35760770c8926614d11fd538e12f21 Mon Sep 17 00:00:00 2001 From: Anders Schack-Mulligen Date: Thu, 3 Dec 2026 13:17:54 +0100 Subject: [PATCH 2/4] Unified: Add Guards instantiation. --- .../unified/internal/controlflow/Guards.qll | 182 ++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 unified/ql/lib/codeql/unified/internal/controlflow/Guards.qll diff --git a/unified/ql/lib/codeql/unified/internal/controlflow/Guards.qll b/unified/ql/lib/codeql/unified/internal/controlflow/Guards.qll new file mode 100644 index 000000000000..0e26ca2bc16f --- /dev/null +++ b/unified/ql/lib/codeql/unified/internal/controlflow/Guards.qll @@ -0,0 +1,182 @@ +/** + * Provides classes and predicates for reasoning about guards and the control + * flow elements controlled by those guards. + */ +overlay[local?] +module; + +private import unified +private import unified as U +private import codeql.controlflow.Guards as SharedGuards +private import codeql.controlflow.SuccessorType +private import codeql.unified.internal.typeinference.TypeInference as T +private import codeql.unified.internal.ExprPositions as EP + +private module GuardsInput implements SharedGuards::InputSig { + class NormalExitNode = ControlFlow::NormalExitNode; + + class AstNode = U::AstNode; + + class Expr = U::Expr; + + predicate nodeIsAfterValue(ControlFlowNode node, Expr e, ConditionalSuccessor s) { + node.isAfterValue(e, s) + } + + private newtype TConstantValue = + // TODO: More cases. Chars? Enums? + TStringValue(string value) { any(Expr e).getStringValue() = value } + + class ConstantValue extends TConstantValue { + string toString() { this = TStringValue(result) } + } + + abstract class ConstantExpr extends Expr { + predicate isNull() { none() } + + boolean asBooleanValue() { none() } + + int asIntegerValue() { none() } + + ConstantValue asConstantValue() { none() } + } + + private class NullConstant extends ConstantExpr instanceof U::Token { + NullConstant() { + // TODO: This might be fine as a general purpose condition for + // identifying null literals, but if so it should moved to a more + // general location + this.getValue() = ["null", "nil"] + } + + override predicate isNull() { any() } + } + + private class BooleanConstant extends ConstantExpr instanceof U::BooleanLiteral { + override boolean asBooleanValue() { result.toString() = super.getValue() } + } + + private class IntegerConstant extends ConstantExpr instanceof U::IntLiteral { + override int asIntegerValue() { result = super.getValue().toInt() } + } + + private class StringConstant extends ConstantExpr { + StringConstant() { exists(this.getStringValue()) } + + override ConstantValue asConstantValue() { result = TStringValue(this.getStringValue()) } + } + + class NonNullExpr extends Expr { + NonNullExpr() { + none() // TODO + } + } + + class Case extends AstNode instanceof U::SwitchCase { + Expr getSwitchExpr() { exists(U::SwitchExpr s | s.getValue() = result and s.getACase() = this) } + + AstNode getAPattern() { result = super.getPattern() } + } + + predicate nonDeconstructingSubPattern(AstNode pattern, AstNode subPattern) { + pattern.(U::ConditionalPattern).getPattern() = subPattern or + pattern.(U::ExprPattern).getExpr() = subPattern or + pattern.(U::NamedPattern).getSubPattern() = subPattern or + pattern.(U::OrPattern).getAPattern() = subPattern + } + + class AndExpr extends BinaryExpr { + AndExpr() { + this instanceof BitwiseAndExpr or + this instanceof LogicalAndExpr or + this instanceof AssignBitwiseAndExpr or + this instanceof AssignLogicalAndExpr + } + } + + class OrExpr extends BinaryExpr { + OrExpr() { + this instanceof BitwiseOrExpr or + this instanceof LogicalOrExpr or + this instanceof AssignBitwiseOrExpr or + this instanceof AssignLogicalOrExpr + } + } + + class NotExpr = U::LogicalNotExpr; + + class IdExpr extends Expr { + IdExpr() { this instanceof AssignExpr or this instanceof TypeCastExpr } + + Expr getEqualChildExpr() { + result = this.(AssignExpr).getValue() + or + result = this.(TypeCastExpr).getExpr() + } + } + + predicate equalityTest(Expr eqtest, Expr left, Expr right, boolean polarity) { + exists(U::EqualityTest eq | eq = eqtest | + eq.getLeft() = left and eq.getRight() = right and eq.getPolarity() = polarity + ) + } + + class ConditionalExpr = U::IfExpr; + + class Parameter = U::Parameter; + + import codeql.unified.internal.dataflow.ParameterPositions + + class NonOverridableMethod extends Callable { + NonOverridableMethod() { + // TODO: The concept of non-overridability likely belongs in a language plugin + // TODO: This logic isn't quite right, but just a placeholder for now + this instanceof ConstructorDeclaration or + this.(FunctionDeclaration).hasModifier("static") or + this.(FunctionDeclaration).hasModifier("private") or + this.(FunctionDeclaration).hasModifier("final") + } + + Parameter getParameter(ParameterPosition ppos) { + result.getDeclaringCallable() = this and + ( + ppos.asPositional() = result.getPositionalIndex() + or + ppos.asNamed() = result.getExternalName() + ) + } + + Expr getAReturnExpr() { EP::isReturnedExpr(this, result) } + } + + class NonOverridableMethodCall extends Expr instanceof CallExpr { + NonOverridableMethodCall() { + unique(Callable c | c = T::resolveCallTarget(this)) instanceof NonOverridableMethod + } + + NonOverridableMethod getMethod() { result = T::resolveCallTarget(this) } + + Expr getArgument(ArgumentPosition apos) { + exists(Argument arg | + super.getAnArgument() = arg and + arg.getValue() = result + | + apos.asPositional() = arg.getPositionalIndex() + or + apos.asNamed() = arg.getName() + ) + } + } +} + +private module GuardsImpl = SharedGuards::Make; + +private module LogicInput_v1 implements GuardsImpl::LogicInputSig { + import Ssa +} + +class GuardValue = GuardsImpl::GuardValue; + +private module Guards_v1 = GuardsImpl::Logic; + +class Guard = Guards_v1::Guard; From 84c8b2a7571b2d8d6c08e7f56e73a08f6f7f7541 Mon Sep 17 00:00:00 2001 From: aschackmull <28296824+aschackmull@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:32:49 +0000 Subject: [PATCH 3/4] Unified: Add Guards inline test ported from Java. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../ql/test/library-tests/guards/Guards.swift | 221 ++++++++++++++++++ .../guards/GuardsInline.expected | 90 +++++++ .../test/library-tests/guards/GuardsInline.ql | 52 +++++ .../library-tests/guards/GuardsInline.qlref | 2 + 4 files changed, 365 insertions(+) create mode 100644 unified/ql/test/library-tests/guards/Guards.swift create mode 100644 unified/ql/test/library-tests/guards/GuardsInline.expected create mode 100644 unified/ql/test/library-tests/guards/GuardsInline.ql create mode 100644 unified/ql/test/library-tests/guards/GuardsInline.qlref diff --git a/unified/ql/test/library-tests/guards/Guards.swift b/unified/ql/test/library-tests/guards/Guards.swift new file mode 100644 index 000000000000..77fa710cc952 --- /dev/null +++ b/unified/ql/test/library-tests/guards/Guards.swift @@ -0,0 +1,221 @@ +struct GuardError: Error { + let msg: String +} + +class C {} + +func chk() { } + +func g(_ lbl: Any) -> Bool { return "\(lbl)".count > 10 } + +func checkTrue(_ b: Bool, _ msg: String) throws { + if !b { throw GuardError(msg: msg) } +} + +func checkFalse(_ b: Bool, _ msg: String) throws { + try checkTrue(!b, msg) +} + +func t1(_ a: [Int]?, _ s0: String) { + var s = s0 + if g("A") { + chk() // $ guarded=g(A):true + } else { + chk() // $ guarded=g(A):false + } + + let b = g(1) ? g(2) : true + if b != false { + chk() // $ guarded=IfExpr:true guarded='b != false:true' guarded=b:true + } else { + chk() // $ guarded=IfExpr:false guarded='b != false:false' guarded=b:false guarded=g(1):true guarded=g(2):false + } + let sz = a != nil ? a!.count : 0 + var i = 0 + while i < sz { + chk() // $ guarded='i < sz:true' MISSING: guarded='a != nil:true' guarded='sz:Lower bound 1' guarded='IfExpr:Lower bound 1' guarded='... .count:Lower bound 1' guarded='a:not null' + let e = a![i] + if e > 2 { break } + i += 1 + } + chk() // nothing guards here + + if g(3) { + s = "bar" + } + switch s { + case "bar": + chk() // $ guarded='"bar":match' guarded='s:bar' + case "foo": + chk() // $ guarded='"bar":no match' guarded='s:not bar' guarded='s0:not bar' guarded='"foo":match' guarded='s:foo' guarded='s0:foo' guarded=g(3):false + default: + chk() // $ guarded='"bar":no match' guarded='"foo":no match' guarded='s:not bar' guarded='s:not foo' guarded='s0:not bar' guarded=g(3):false + } + + let o: Any? = g(4) ? nil : s + if o is String { + chk() // $ guarded=TypeTestExpr:true MISSING: guarded='o:not null' guarded='IfExpr:not null' guarded=g(4):false guarded='s:not null' + } +} + +func t2() throws { + try checkTrue(g(1), "A") + try checkFalse(g(2), "B") + chk() // $ guarded='checkTrue(...):no exception' guarded='checkFalse(...):no exception' SPURIOUS: guarded='g(...):no exception' MISSING: guarded=g(1):true guarded=g(2):false +} + +func t3() { + var b = g(1) && (g(2) || g(3)) + if b { + chk() // $ guarded=b:true guarded='g(...) && ... \|\| ...:true' guarded=g(1):true guarded='g(...) \|\| g(...):true' + } else { + chk() // $ guarded=b:false guarded='g(...) && ... \|\| ...:false' + } + b = g(4) || !g(5) + if b { + chk() // $ guarded=b:true guarded='g(...) \|\| ! ...:true' + } else { + chk() // $ guarded=b:false guarded='g(...) \|\| ! ...:false' guarded=g(4):false guarded='! ...:false' guarded=g(5):true + } +} + +enum Val { + case E1 + case E2 + case E3 +} + +func t4() { + var x: Val? = nil // unique value + if g(1) { x = Val.E1 } // unique value + if g(2) { x = Val.E2 } + if g("Alt2") { x = Val.E2 } + if g(3) { x = Val.E3 } // unique value + if x == nil { + chk() // $ guarded='x == nil:true' guarded='x:null' MISSING: guarded=g(1):false guarded=g(2):false guarded=g(Alt2):false guarded=g(3):false + } + switch x { + case .E1: + chk() // $ guarded='... .E1:match' MISSING: guarded='x:E1' guarded=g(1):true guarded=g(2):false guarded=g(Alt2):false guarded=g(3):false + case .E2: + chk() // $ guarded='... .E1:no match' guarded='... .E2:match' MISSING: guarded='x:not E1' guarded='x:E2' guarded=g(3):false + case .E3: + chk() // $ guarded='... .E1:no match' guarded='... .E2:no match' guarded='... .E3:match' MISSING: guarded='x:not E1' guarded='x:not E2' guarded='x:E3' guarded=g(3):true + case nil: + break + } + let o: C? = g(4) ? C() : nil + if o == nil { + chk() // $ guarded='o == nil:true' guarded='o:null' guarded='IfExpr:null' MISSING: guarded=g(4):false + } else { + chk() // $ guarded='o == nil:false' guarded='o:not null' guarded='IfExpr:not null' guarded='C(...):not null' guarded=g(4):true + } +} + +func t5(_ foo: String?) { + var base = foo + if base == nil { + base = "/user" + } + if base == "/" { + chk() // $ guarded='base == "/":true' guarded='base:/' guarded='base:not null' guarded='base == nil:false' guarded='foo:/' guarded='foo:not null' + } +} + +func t6() { + var o: C? = nil + if g(1) { + o = C() + if g(2) { } + } + if o != nil { + chk() // $ guarded='o != nil:true' guarded='o:not null' guarded='C(...):not null' guarded=g(1):true + } else { + chk() // $ guarded='o != nil:false' guarded='o:null' MISSING: guarded=g(1):false + } +} + +func t7(_ a: [Int]) { + var found = false + var i = 0 + while i < a.count { + let answer = a[i] == 42 + if answer { + found = true + } + if found { + chk() // $ guarded=found:true guarded='i < ... .count:true' MISSING: guarded='... .count:Lower bound 1' + } + i += 1 + } + if found { + chk() // $ guarded=found:true guarded='i < ... .count:false' MISSING: guarded='i:Lower bound 0' + } +} + +func testNotNull1(_ input: String?) -> Bool { + return input != nil && input!.count > 0 +} + +func testNotNull2(_ input: String?) -> Bool { + if input == nil { return false } + return input!.count > 0 +} + +func getNumOrDefault(_ number: Int?) -> Int { + return number == nil ? 0 : number! +} + +func concatNonNull(_ s1: String?, _ s2: String?) -> String? { + if s1 == nil || s2 == nil { return nil } + return s1! + s2! +} + +func testEnumWrapper(_ flag: Bool) -> Status { + return flag ? Status.SUCCESS : Status.FAILURE +} + +enum Status { case SUCCESS, FAILURE } + +func testWrappers(_ s: String?, _ i: Int?) { + if testNotNull1(s) { + chk() // $ guarded=testNotNull1(...):true MISSING: guarded='s:not null' + } else { + chk() // $ guarded=testNotNull1(...):false + } + + if testNotNull2(s) { + chk() // $ guarded=testNotNull2(...):true MISSING: guarded='s:not null' + } else { + chk() // $ guarded=testNotNull2(...):false + } + + if 0 == getNumOrDefault(i) { + chk() // $ guarded='0 == getNumOrDefault(...):true' guarded='getNumOrDefault(...):0' + } else { + chk() // $ guarded='0 == getNumOrDefault(...):false' guarded='getNumOrDefault(...):not 0' MISSING: guarded='i:not 0' guarded='i:not null' + } + + if nil == concatNonNull(s, "suffix") { + chk() // $ guarded='concatNonNull(...):null' guarded='nil == concatNonNull(...):true' + } else { + chk() // $ guarded='concatNonNull(...):not null' guarded='nil == concatNonNull(...):false' MISSING: guarded='s:not null' + } + + switch testEnumWrapper(g(1)) { + case .SUCCESS: + chk() // $ guarded='... .SUCCESS:match' MISSING: guarded='testEnumWrapper(...):SUCCESS' guarded=g(1):true + case .FAILURE: + chk() // $ guarded='... .SUCCESS:no match' MISSING: guarded='testEnumWrapper(...):not SUCCESS' guarded='testEnumWrapper(...):FAILURE' guarded='... .FAILURE:match' guarded=g(1):false + } +} + +func ensureNotNull(_ o: Any?) throws { + if o == nil { throw GuardError(msg: "null") } +} + +func testExceptionWrapper(_ s: String?) throws { + chk() // nothing guards here + try ensureNotNull(s) + chk() // $ guarded='ensureNotNull(...):no exception' MISSING: guarded='s:not null' +} diff --git a/unified/ql/test/library-tests/guards/GuardsInline.expected b/unified/ql/test/library-tests/guards/GuardsInline.expected new file mode 100644 index 000000000000..a05e66d82c12 --- /dev/null +++ b/unified/ql/test/library-tests/guards/GuardsInline.expected @@ -0,0 +1,90 @@ +| Guards.swift:22:5:22:9 | chk(...) | g(A):true | +| Guards.swift:24:5:24:9 | chk(...) | g(A):false | +| Guards.swift:29:5:29:9 | chk(...) | 'b != false:true' | +| Guards.swift:29:5:29:9 | chk(...) | IfExpr:true | +| Guards.swift:29:5:29:9 | chk(...) | b:true | +| Guards.swift:31:5:31:9 | chk(...) | 'b != false:false' | +| Guards.swift:31:5:31:9 | chk(...) | IfExpr:false | +| Guards.swift:31:5:31:9 | chk(...) | b:false | +| Guards.swift:31:5:31:9 | chk(...) | g(1):true | +| Guards.swift:31:5:31:9 | chk(...) | g(2):false | +| Guards.swift:36:5:36:9 | chk(...) | 'i < sz:true' | +| Guards.swift:48:5:48:9 | chk(...) | '"bar":match' | +| Guards.swift:48:5:48:9 | chk(...) | 's:bar' | +| Guards.swift:50:5:50:9 | chk(...) | '"bar":no match' | +| Guards.swift:50:5:50:9 | chk(...) | '"foo":match' | +| Guards.swift:50:5:50:9 | chk(...) | 's0:foo' | +| Guards.swift:50:5:50:9 | chk(...) | 's0:not bar' | +| Guards.swift:50:5:50:9 | chk(...) | 's:foo' | +| Guards.swift:50:5:50:9 | chk(...) | 's:not bar' | +| Guards.swift:50:5:50:9 | chk(...) | g(3):false | +| Guards.swift:52:5:52:9 | chk(...) | '"bar":no match' | +| Guards.swift:52:5:52:9 | chk(...) | '"foo":no match' | +| Guards.swift:52:5:52:9 | chk(...) | 's0:not bar' | +| Guards.swift:52:5:52:9 | chk(...) | 's:not bar' | +| Guards.swift:52:5:52:9 | chk(...) | 's:not foo' | +| Guards.swift:52:5:52:9 | chk(...) | g(3):false | +| Guards.swift:57:5:57:9 | chk(...) | TypeTestExpr:true | +| Guards.swift:64:3:64:7 | chk(...) | 'checkFalse(...):no exception' | +| Guards.swift:64:3:64:7 | chk(...) | 'checkTrue(...):no exception' | +| Guards.swift:64:3:64:7 | chk(...) | 'g(...):no exception' | +| Guards.swift:70:5:70:9 | chk(...) | 'g(...) && ... \|\| ...:true' | +| Guards.swift:70:5:70:9 | chk(...) | 'g(...) \|\| g(...):true' | +| Guards.swift:70:5:70:9 | chk(...) | b:true | +| Guards.swift:70:5:70:9 | chk(...) | g(1):true | +| Guards.swift:72:5:72:9 | chk(...) | 'g(...) && ... \|\| ...:false' | +| Guards.swift:72:5:72:9 | chk(...) | b:false | +| Guards.swift:76:5:76:9 | chk(...) | 'g(...) \|\| ! ...:true' | +| Guards.swift:76:5:76:9 | chk(...) | b:true | +| Guards.swift:78:5:78:9 | chk(...) | '! ...:false' | +| Guards.swift:78:5:78:9 | chk(...) | 'g(...) \|\| ! ...:false' | +| Guards.swift:78:5:78:9 | chk(...) | b:false | +| Guards.swift:78:5:78:9 | chk(...) | g(4):false | +| Guards.swift:78:5:78:9 | chk(...) | g(5):true | +| Guards.swift:95:5:95:9 | chk(...) | 'x == nil:true' | +| Guards.swift:95:5:95:9 | chk(...) | 'x:null' | +| Guards.swift:99:5:99:9 | chk(...) | '... .E1:match' | +| Guards.swift:101:5:101:9 | chk(...) | '... .E1:no match' | +| Guards.swift:101:5:101:9 | chk(...) | '... .E2:match' | +| Guards.swift:103:5:103:9 | chk(...) | '... .E1:no match' | +| Guards.swift:103:5:103:9 | chk(...) | '... .E2:no match' | +| Guards.swift:103:5:103:9 | chk(...) | '... .E3:match' | +| Guards.swift:109:5:109:9 | chk(...) | 'IfExpr:null' | +| Guards.swift:109:5:109:9 | chk(...) | 'o == nil:true' | +| Guards.swift:109:5:109:9 | chk(...) | 'o:null' | +| Guards.swift:111:5:111:9 | chk(...) | 'C(...):not null' | +| Guards.swift:111:5:111:9 | chk(...) | 'IfExpr:not null' | +| Guards.swift:111:5:111:9 | chk(...) | 'o == nil:false' | +| Guards.swift:111:5:111:9 | chk(...) | 'o:not null' | +| Guards.swift:111:5:111:9 | chk(...) | g(4):true | +| Guards.swift:121:5:121:9 | chk(...) | 'base == "/":true' | +| Guards.swift:121:5:121:9 | chk(...) | 'base == nil:false' | +| Guards.swift:121:5:121:9 | chk(...) | 'base:/' | +| Guards.swift:121:5:121:9 | chk(...) | 'base:not null' | +| Guards.swift:121:5:121:9 | chk(...) | 'foo:/' | +| Guards.swift:121:5:121:9 | chk(...) | 'foo:not null' | +| Guards.swift:132:5:132:9 | chk(...) | 'C(...):not null' | +| Guards.swift:132:5:132:9 | chk(...) | 'o != nil:true' | +| Guards.swift:132:5:132:9 | chk(...) | 'o:not null' | +| Guards.swift:132:5:132:9 | chk(...) | g(1):true | +| Guards.swift:134:5:134:9 | chk(...) | 'o != nil:false' | +| Guards.swift:134:5:134:9 | chk(...) | 'o:null' | +| Guards.swift:147:7:147:11 | chk(...) | 'i < ... .count:true' | +| Guards.swift:147:7:147:11 | chk(...) | found:true | +| Guards.swift:152:5:152:9 | chk(...) | 'i < ... .count:false' | +| Guards.swift:152:5:152:9 | chk(...) | found:true | +| Guards.swift:182:5:182:9 | chk(...) | testNotNull1(...):true | +| Guards.swift:184:5:184:9 | chk(...) | testNotNull1(...):false | +| Guards.swift:188:5:188:9 | chk(...) | testNotNull2(...):true | +| Guards.swift:190:5:190:9 | chk(...) | testNotNull2(...):false | +| Guards.swift:194:5:194:9 | chk(...) | '0 == getNumOrDefault(...):true' | +| Guards.swift:194:5:194:9 | chk(...) | 'getNumOrDefault(...):0' | +| Guards.swift:196:5:196:9 | chk(...) | '0 == getNumOrDefault(...):false' | +| Guards.swift:196:5:196:9 | chk(...) | 'getNumOrDefault(...):not 0' | +| Guards.swift:200:5:200:9 | chk(...) | 'concatNonNull(...):null' | +| Guards.swift:200:5:200:9 | chk(...) | 'nil == concatNonNull(...):true' | +| Guards.swift:202:5:202:9 | chk(...) | 'concatNonNull(...):not null' | +| Guards.swift:202:5:202:9 | chk(...) | 'nil == concatNonNull(...):false' | +| Guards.swift:207:5:207:9 | chk(...) | '... .SUCCESS:match' | +| Guards.swift:209:5:209:9 | chk(...) | '... .SUCCESS:no match' | +| Guards.swift:220:3:220:7 | chk(...) | 'ensureNotNull(...):no exception' | diff --git a/unified/ql/test/library-tests/guards/GuardsInline.ql b/unified/ql/test/library-tests/guards/GuardsInline.ql new file mode 100644 index 000000000000..7a6d83eb3960 --- /dev/null +++ b/unified/ql/test/library-tests/guards/GuardsInline.ql @@ -0,0 +1,52 @@ +import unified +import codeql.unified.internal.controlflow.Guards +import codeql.util.Boolean + +private string ppLiteral(Expr e) { + result = e.getStringValue() + or + result = e.(IntLiteral).getValue() +} + +string ppGuard(Guard g, Boolean branch) { + exists(CallExpr call, Argument arg | + call = g and + call.getAnArgument() = arg and + result = + call.getCallee().(Token).getValue() + "(" + ppLiteral(arg.getValue()) + ")" + ":" + branch + ) + or + exists(BinaryExpr bin | + bin = g and + result = + "'" + bin.getLeft() + " " + bin.getOperator().getValue() + " " + bin.getRight() + ":" + branch + + "'" + ) +} + +bindingset[s] +private string quoteIfSpaces(string s) { + if s.matches("% %") then result = "'" + s + "'" else result = s +} + +query predicate guarded(CallExpr call, string guard) { + call.getCallee().(Token).getValue() = "chk" and + exists(Guard g, BasicBlock bb, boolean branch | + g.controls(bb, branch) and + call.getBasicBlock() = bb + | + guard = ppGuard(g, branch) + or + not exists(ppGuard(g, branch)) and + guard = quoteIfSpaces(g.toString() + ":" + branch) + ) + or + call.getCallee().(Token).getValue() = "chk" and + exists(Guard g, BasicBlock bb, GuardValue val | + g.valueControls(bb, val) and + not exists(val.asBooleanValue()) and + call.getBasicBlock() = bb + | + guard = "'" + g.toString() + ":" + val + "'" + ) +} diff --git a/unified/ql/test/library-tests/guards/GuardsInline.qlref b/unified/ql/test/library-tests/guards/GuardsInline.qlref new file mode 100644 index 000000000000..a9492ac8f238 --- /dev/null +++ b/unified/ql/test/library-tests/guards/GuardsInline.qlref @@ -0,0 +1,2 @@ +query: GuardsInline.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql From 63904babac48f84f3d569e043a3dc8846a7faed9 Mon Sep 17 00:00:00 2001 From: aschackmull <28296824+aschackmull@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:20:40 +0000 Subject: [PATCH 4/4] Unified: Improve Swift guard reasoning Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../unified/internal/controlflow/Guards.qll | 51 +++++++- .../ql/test/library-tests/guards/Guards.swift | 116 ++++++++++++++++-- .../guards/GuardsInline.expected | 41 ++++++- 3 files changed, 190 insertions(+), 18 deletions(-) diff --git a/unified/ql/lib/codeql/unified/internal/controlflow/Guards.qll b/unified/ql/lib/codeql/unified/internal/controlflow/Guards.qll index 0e26ca2bc16f..05ff403fbc0c 100644 --- a/unified/ql/lib/codeql/unified/internal/controlflow/Guards.qll +++ b/unified/ql/lib/codeql/unified/internal/controlflow/Guards.qll @@ -10,6 +10,8 @@ private import unified as U private import codeql.controlflow.Guards as SharedGuards private import codeql.controlflow.SuccessorType private import codeql.unified.internal.typeinference.TypeInference as T +private import codeql.unified.internal.typeinference.TypeInferencePluginSwift as SwiftTypes +private import codeql.unified.internal.typeinference.TypeMention as TM private import codeql.unified.internal.ExprPositions as EP private module GuardsInput implements SharedGuards::InputSig { @@ -68,7 +70,23 @@ private module GuardsInput implements SharedGuards::InputSig; private module LogicInput_v1 implements GuardsImpl::LogicInputSig { import Ssa + + predicate additionalNullCheck( + GuardsImpl::PreGuard guard, GuardsImpl::GuardValue val, Expr e, boolean isNull + ) { + exists(TypeTestExpr test, T::Type testedType | + guard = test and + test.getOperator().getValue() = "is" and + e = test.getExpr() and + testedType = unique(T::Type t | t = test.getType().(TM::TypeMention).getType()) and + // In Swift, `nil is Any` and `nil is T?` can both be true. + testedType.asClass().hasModifier(["class", "actor", "struct", "enum"]) and + not testedType instanceof SwiftTypes::OptionalType and + val.asBooleanValue() = true and + isNull = false + ) + } } class GuardValue = GuardsImpl::GuardValue; diff --git a/unified/ql/test/library-tests/guards/Guards.swift b/unified/ql/test/library-tests/guards/Guards.swift index 77fa710cc952..976cbe30393e 100644 --- a/unified/ql/test/library-tests/guards/Guards.swift +++ b/unified/ql/test/library-tests/guards/Guards.swift @@ -28,7 +28,7 @@ func t1(_ a: [Int]?, _ s0: String) { if b != false { chk() // $ guarded=IfExpr:true guarded='b != false:true' guarded=b:true } else { - chk() // $ guarded=IfExpr:false guarded='b != false:false' guarded=b:false guarded=g(1):true guarded=g(2):false + chk() // $ guarded=IfExpr:false guarded='IfExpr:not null' guarded='b != false:false' guarded=b:false guarded='b:not null' guarded=g(1):true guarded=g(2):false } let sz = a != nil ? a!.count : 0 var i = 0 @@ -54,14 +54,14 @@ func t1(_ a: [Int]?, _ s0: String) { let o: Any? = g(4) ? nil : s if o is String { - chk() // $ guarded=TypeTestExpr:true MISSING: guarded='o:not null' guarded='IfExpr:not null' guarded=g(4):false guarded='s:not null' + chk() // $ guarded=TypeTestExpr:true guarded='o:not null' guarded='IfExpr:not null' guarded=g(4):false guarded='s:not null' } } func t2() throws { try checkTrue(g(1), "A") try checkFalse(g(2), "B") - chk() // $ guarded='checkTrue(...):no exception' guarded='checkFalse(...):no exception' SPURIOUS: guarded='g(...):no exception' MISSING: guarded=g(1):true guarded=g(2):false + chk() // $ guarded='checkTrue(...):no exception' guarded='checkFalse(...):no exception' guarded=g(1):true guarded=g(2):false SPURIOUS: guarded='g(...):no exception' } func t3() { @@ -106,9 +106,9 @@ func t4() { } let o: C? = g(4) ? C() : nil if o == nil { - chk() // $ guarded='o == nil:true' guarded='o:null' guarded='IfExpr:null' MISSING: guarded=g(4):false + chk() // $ guarded='o == nil:true' guarded='o:null' guarded='IfExpr:null' guarded=g(4):false } else { - chk() // $ guarded='o == nil:false' guarded='o:not null' guarded='IfExpr:not null' guarded='C(...):not null' guarded=g(4):true + chk() // $ guarded='o == nil:false' guarded='o:not null' guarded='IfExpr:not null' guarded=g(4):true } } @@ -129,9 +129,9 @@ func t6() { if g(2) { } } if o != nil { - chk() // $ guarded='o != nil:true' guarded='o:not null' guarded='C(...):not null' guarded=g(1):true + chk() // $ guarded='o != nil:true' guarded='o:not null' guarded=g(1):true } else { - chk() // $ guarded='o != nil:false' guarded='o:null' MISSING: guarded=g(1):false + chk() // $ guarded='o != nil:false' guarded='o:null' guarded=g(1):false } } @@ -185,13 +185,13 @@ func testWrappers(_ s: String?, _ i: Int?) { } if testNotNull2(s) { - chk() // $ guarded=testNotNull2(...):true MISSING: guarded='s:not null' + chk() // $ guarded=testNotNull2(...):true guarded='s:not null' } else { chk() // $ guarded=testNotNull2(...):false } if 0 == getNumOrDefault(i) { - chk() // $ guarded='0 == getNumOrDefault(...):true' guarded='getNumOrDefault(...):0' + chk() // $ guarded='0 == getNumOrDefault(...):true' guarded='getNumOrDefault(...):0' guarded='getNumOrDefault(...):not null' } else { chk() // $ guarded='0 == getNumOrDefault(...):false' guarded='getNumOrDefault(...):not 0' MISSING: guarded='i:not 0' guarded='i:not null' } @@ -199,7 +199,7 @@ func testWrappers(_ s: String?, _ i: Int?) { if nil == concatNonNull(s, "suffix") { chk() // $ guarded='concatNonNull(...):null' guarded='nil == concatNonNull(...):true' } else { - chk() // $ guarded='concatNonNull(...):not null' guarded='nil == concatNonNull(...):false' MISSING: guarded='s:not null' + chk() // $ guarded='concatNonNull(...):not null' guarded='nil == concatNonNull(...):false' guarded='s:not null' } switch testEnumWrapper(g(1)) { @@ -217,5 +217,99 @@ func ensureNotNull(_ o: Any?) throws { func testExceptionWrapper(_ s: String?) throws { chk() // nothing guards here try ensureNotNull(s) - chk() // $ guarded='ensureNotNull(...):no exception' MISSING: guarded='s:not null' + chk() // $ guarded='ensureNotNull(...):no exception' guarded='s:not null' +} + +func namedCheck(_ other: String?, value: String?) -> Bool { + if value == nil { return false } + return true +} + +func testFunctionWrappers(_ first: String?, _ second: String?) { + if namedCheck(first, value: second) { + chk() // $ guarded=namedCheck(...):true guarded='second:not null' + } + + func localCheck(_ value: String?) -> Bool { + if value == nil { return false } + return true + } + if localCheck(first) { + chk() // $ guarded=localCheck(...):true guarded='first:not null' + } +} + +class OverridableCheck { + func accepts(_ value: String?) -> Bool { + if value == nil { return false } + return true + } +} + +class AlwaysAccept: OverridableCheck { + override func accepts(_ value: String?) -> Bool { + return true + } +} + +private dynamic func dynamicCheck(_ value: String?) -> Bool { + if value == nil { return false } + return true +} + +func testDynamicDispatch(_ checker: OverridableCheck, _ value: String?) { + if checker.accepts(value) { + chk() // $ guarded='... .accepts(...):true' + } + if dynamicCheck(value) { + chk() // $ guarded=dynamicCheck(...):true + } +} + +class Failable { + init?() { return nil } +} + +class InheritedFailable: Failable {} + +func testFailableInitializers(_ flag: Bool) { + let first = flag ? Failable() : nil + if first == nil { + chk() // $ guarded='first == nil:true' guarded='first:null' guarded='IfExpr:null' + } + let second = flag ? InheritedFailable() : nil + if second == nil { + chk() // $ guarded='second == nil:true' guarded='second:null' guarded='IfExpr:null' + } +} + +typealias Text = String +typealias MaybeText = String? + +func testTypeTests(_ value: Any?) { + if value is String { + chk() // $ guarded=TypeTestExpr:true guarded='value:not null' + } else { + chk() // $ guarded=TypeTestExpr:false + } + if value is Text { + chk() // $ guarded=TypeTestExpr:true guarded='value:not null' + } + if value is String? { + chk() // $ guarded=TypeTestExpr:true + } + if value is MaybeText { + chk() // $ guarded=TypeTestExpr:true + } + if value is Any { + chk() // $ guarded=TypeTestExpr:true + } +} + +func testLiteralEquality(_ value: String?) { + if value == "safe" { + chk() // $ guarded='value == "safe":true' guarded='value:safe' guarded='value:not null' + } else { + chk() // $ guarded='value == "safe":false' guarded='value:not safe' + } } diff --git a/unified/ql/test/library-tests/guards/GuardsInline.expected b/unified/ql/test/library-tests/guards/GuardsInline.expected index a05e66d82c12..7592b395ada7 100644 --- a/unified/ql/test/library-tests/guards/GuardsInline.expected +++ b/unified/ql/test/library-tests/guards/GuardsInline.expected @@ -3,7 +3,9 @@ | Guards.swift:29:5:29:9 | chk(...) | 'b != false:true' | | Guards.swift:29:5:29:9 | chk(...) | IfExpr:true | | Guards.swift:29:5:29:9 | chk(...) | b:true | +| Guards.swift:31:5:31:9 | chk(...) | 'IfExpr:not null' | | Guards.swift:31:5:31:9 | chk(...) | 'b != false:false' | +| Guards.swift:31:5:31:9 | chk(...) | 'b:not null' | | Guards.swift:31:5:31:9 | chk(...) | IfExpr:false | | Guards.swift:31:5:31:9 | chk(...) | b:false | | Guards.swift:31:5:31:9 | chk(...) | g(1):true | @@ -24,10 +26,16 @@ | Guards.swift:52:5:52:9 | chk(...) | 's:not bar' | | Guards.swift:52:5:52:9 | chk(...) | 's:not foo' | | Guards.swift:52:5:52:9 | chk(...) | g(3):false | +| Guards.swift:57:5:57:9 | chk(...) | 'IfExpr:not null' | +| Guards.swift:57:5:57:9 | chk(...) | 'o:not null' | +| Guards.swift:57:5:57:9 | chk(...) | 's:not null' | | Guards.swift:57:5:57:9 | chk(...) | TypeTestExpr:true | +| Guards.swift:57:5:57:9 | chk(...) | g(4):false | | Guards.swift:64:3:64:7 | chk(...) | 'checkFalse(...):no exception' | | Guards.swift:64:3:64:7 | chk(...) | 'checkTrue(...):no exception' | | Guards.swift:64:3:64:7 | chk(...) | 'g(...):no exception' | +| Guards.swift:64:3:64:7 | chk(...) | g(1):true | +| Guards.swift:64:3:64:7 | chk(...) | g(2):false | | Guards.swift:70:5:70:9 | chk(...) | 'g(...) && ... \|\| ...:true' | | Guards.swift:70:5:70:9 | chk(...) | 'g(...) \|\| g(...):true' | | Guards.swift:70:5:70:9 | chk(...) | b:true | @@ -52,7 +60,7 @@ | Guards.swift:109:5:109:9 | chk(...) | 'IfExpr:null' | | Guards.swift:109:5:109:9 | chk(...) | 'o == nil:true' | | Guards.swift:109:5:109:9 | chk(...) | 'o:null' | -| Guards.swift:111:5:111:9 | chk(...) | 'C(...):not null' | +| Guards.swift:109:5:109:9 | chk(...) | g(4):false | | Guards.swift:111:5:111:9 | chk(...) | 'IfExpr:not null' | | Guards.swift:111:5:111:9 | chk(...) | 'o == nil:false' | | Guards.swift:111:5:111:9 | chk(...) | 'o:not null' | @@ -63,28 +71,57 @@ | Guards.swift:121:5:121:9 | chk(...) | 'base:not null' | | Guards.swift:121:5:121:9 | chk(...) | 'foo:/' | | Guards.swift:121:5:121:9 | chk(...) | 'foo:not null' | -| Guards.swift:132:5:132:9 | chk(...) | 'C(...):not null' | | Guards.swift:132:5:132:9 | chk(...) | 'o != nil:true' | | Guards.swift:132:5:132:9 | chk(...) | 'o:not null' | | Guards.swift:132:5:132:9 | chk(...) | g(1):true | | Guards.swift:134:5:134:9 | chk(...) | 'o != nil:false' | | Guards.swift:134:5:134:9 | chk(...) | 'o:null' | +| Guards.swift:134:5:134:9 | chk(...) | g(1):false | | Guards.swift:147:7:147:11 | chk(...) | 'i < ... .count:true' | | Guards.swift:147:7:147:11 | chk(...) | found:true | | Guards.swift:152:5:152:9 | chk(...) | 'i < ... .count:false' | | Guards.swift:152:5:152:9 | chk(...) | found:true | | Guards.swift:182:5:182:9 | chk(...) | testNotNull1(...):true | | Guards.swift:184:5:184:9 | chk(...) | testNotNull1(...):false | +| Guards.swift:188:5:188:9 | chk(...) | 's:not null' | | Guards.swift:188:5:188:9 | chk(...) | testNotNull2(...):true | | Guards.swift:190:5:190:9 | chk(...) | testNotNull2(...):false | | Guards.swift:194:5:194:9 | chk(...) | '0 == getNumOrDefault(...):true' | | Guards.swift:194:5:194:9 | chk(...) | 'getNumOrDefault(...):0' | +| Guards.swift:194:5:194:9 | chk(...) | 'getNumOrDefault(...):not null' | | Guards.swift:196:5:196:9 | chk(...) | '0 == getNumOrDefault(...):false' | | Guards.swift:196:5:196:9 | chk(...) | 'getNumOrDefault(...):not 0' | | Guards.swift:200:5:200:9 | chk(...) | 'concatNonNull(...):null' | | Guards.swift:200:5:200:9 | chk(...) | 'nil == concatNonNull(...):true' | | Guards.swift:202:5:202:9 | chk(...) | 'concatNonNull(...):not null' | | Guards.swift:202:5:202:9 | chk(...) | 'nil == concatNonNull(...):false' | +| Guards.swift:202:5:202:9 | chk(...) | 's:not null' | | Guards.swift:207:5:207:9 | chk(...) | '... .SUCCESS:match' | | Guards.swift:209:5:209:9 | chk(...) | '... .SUCCESS:no match' | | Guards.swift:220:3:220:7 | chk(...) | 'ensureNotNull(...):no exception' | +| Guards.swift:220:3:220:7 | chk(...) | 's:not null' | +| Guards.swift:230:5:230:9 | chk(...) | 'second:not null' | +| Guards.swift:230:5:230:9 | chk(...) | namedCheck(...):true | +| Guards.swift:238:5:238:9 | chk(...) | 'first:not null' | +| Guards.swift:238:5:238:9 | chk(...) | localCheck(...):true | +| Guards.swift:262:5:262:9 | chk(...) | '... .accepts(...):true' | +| Guards.swift:265:5:265:9 | chk(...) | dynamicCheck(...):true | +| Guards.swift:278:5:278:9 | chk(...) | 'IfExpr:null' | +| Guards.swift:278:5:278:9 | chk(...) | 'first == nil:true' | +| Guards.swift:278:5:278:9 | chk(...) | 'first:null' | +| Guards.swift:282:5:282:9 | chk(...) | 'IfExpr:null' | +| Guards.swift:282:5:282:9 | chk(...) | 'second == nil:true' | +| Guards.swift:282:5:282:9 | chk(...) | 'second:null' | +| Guards.swift:291:5:291:9 | chk(...) | 'value:not null' | +| Guards.swift:291:5:291:9 | chk(...) | TypeTestExpr:true | +| Guards.swift:293:5:293:9 | chk(...) | TypeTestExpr:false | +| Guards.swift:296:5:296:9 | chk(...) | 'value:not null' | +| Guards.swift:296:5:296:9 | chk(...) | TypeTestExpr:true | +| Guards.swift:299:5:299:9 | chk(...) | TypeTestExpr:true | +| Guards.swift:302:5:302:9 | chk(...) | TypeTestExpr:true | +| Guards.swift:305:5:305:9 | chk(...) | TypeTestExpr:true | +| Guards.swift:311:5:311:9 | chk(...) | 'value == "safe":true' | +| Guards.swift:311:5:311:9 | chk(...) | 'value:not null' | +| Guards.swift:311:5:311:9 | chk(...) | 'value:safe' | +| Guards.swift:313:5:313:9 | chk(...) | 'value == "safe":false' | +| Guards.swift:313:5:313:9 | chk(...) | 'value:not safe' |