swift-syntax icon indicating copy to clipboard operation
swift-syntax copied to clipboard

expect macro compiler error when custom comparison operator and range

Open grantneufeld opened this issue 7 months ago • 1 comments

Description

When using a custom comparison operator with a range, the #expect macro produces a compiler error.

Reproduction

Code (system) under test:

infix operator =* : ComparisonPrecedence

public struct Values: Collection, Sequence {
    public typealias Element = Int
    private var collection: [Element]
    
    // ... functions and properties for protocol conformance
    
    public static func =* <S: Sequence>(
        lhs: Self, rhs: S
    ) -> Bool where S.Element == Element {
        lhs.collection.sorted() == rhs.sorted()
    }
}

Test:

@Test
func custom_operator_example() {
    let sut = Values([1, 2, 3])
    #expect(sut =* [1, 2, 3]) // ✅ true
    #expect(sut =* Set([1, 2, 3])) // ✅ true

    #expect(sut =* 1...3) // 🛑 error
    // 3 compiler errors:
    // Operator function '=*' requires that 'Int' conform to 'Sequence'
    // Cannot convert value of type 'ClosedRange<Int>' to closure result type 'Bool'
    // Cannot convert value of type 'Bool' to expected argument type 'Int'
}

Taking the comparison out of the macro works:

    let result = sut =* 1...3
    #expect(result) // ✅ true

expanding the failing macro reveals:

Testing.__checkBinaryOperation(sut =* 1,{ $0 ... $1() },3,expression: .__fromBinaryOperation(.__fromSyntaxNode("sut =* 1"),"...",.__fromSyntaxNode("3")),comments: [],isRequired: false,sourceLocation: Testing.SourceLocation.__here()).__expected()

Expected behavior

The expect macro should produce valid code when a custom operator is used in a statement along with a range operator.

Environment

Testing Library Version: 124.4 Target Platform: arm64e-apple-macos14.0

swift-driver version: 1.120.5 Apple Swift version 6.1.2 (swiftlang-6.1.2.1.2 clang-1700.0.13.5) Target: arm64-apple-macosx15.0

Darwin Mac.ht.home 24.6.0 Darwin Kernel Version 24.6.0: Mon Jul 14 11:30:29 PDT 2025; root:xnu-11417.140.69~1/RELEASE_ARM64_T6000 arm64

Additional information

No response

grantneufeld avatar Aug 09 '25 14:08 grantneufeld

Custom operator precedence is not available during macro expansion, so the syntax tree we see is malformed.

grynspan avatar Aug 09 '25 14:08 grynspan