Skip to content

Error compiling @differentiable computed property (within a struct) if defined in a different file from its use site. #63169

Closed
@fibrechannelscsi

Description

@fibrechannelscsi

Description
If we have a struct containing a @differentiable computed property (with explicit get/set directives) in the same file that it is used, then the program compiles successfully. However, If this struct is in a different file, the compilation fails. The error message is as follows:

reproducer.swift:12:59: error: expression is not differentiable
var localStruct = TestStruct(); localStruct.g = x; return localStruct.g
                                              ^

reproducer.swift:12:59: note: cannot differentiate functions that have not been marked '@differentiable' and that are defined in other files
var localStruct = TestStruct(); localStruct.g = x; return localStruct.g
                                              ^

Steps to reproduce
This reproducer requires two Swift files, in the same directory (for example, insides Sources/ProjectName).

File 1:

import _Differentiation
import Foundation
public struct MyReproducer {
    func compute() {
        @differentiable(reverse)
        func assignF(_ x: Double) -> Double {
            var localStruct = TestStruct(); localStruct.f(x); return localStruct.g
        }
        
        @differentiable(reverse)
        func assignG(_ x: Double) -> Double {
            var localStruct = TestStruct(); localStruct.g = x; return localStruct.g
        }
    }
}

File 2:

public struct TestStruct: Differentiable {
    private var _g: Double = 0
    @differentiable(reverse)
    var g: Double {
        get {self._g}
        set(newValue) {self._g = 3.0*newValue*newValue}
    }
    @differentiable(reverse)
    mutating func f(_ x: Double) {
        self._g = 3.0*x*x
    }
}

Place the above code into two separate files, and compile in Debug mode.

Note: Placing TestStruct inside File 1, albeit outside MyReproducer, will cause the compilation to succeed.

Expected behavior
The project containing the two files should compile successfully, even when TestStruct and MyReproducer are in different files.

  • Swift compiler version info: Fails with (seemingly) everything from 2022-02-03a to 2023-01-19a.
  • Xcode version info: 13.3 (13E113)
  • Deployment target: iOS 12.3.1, ARM64.

Additional context
Similar to: #55170

Metadata

Metadata

Assignees

Labels

AutoDiffaccessorsFeature → declarations: Variable (property) accessorsbugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfmultiple filesFlag: An issue whose reproduction requires multiple filestype checkerArea → compiler: Semantic analysisunexpected errorBug: Unexpected error

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions