Other than in protocols, there is no way to declare a function without implementing its body in Swift, and the only way to do it is via (Objective-)C(++), right?
My (potential) use case for something like this is inserting marker function calls into source code to help with inspecting the IR and/or assembly. Are there better or more established approaches to inserting markers in Swift without using unimplemented functions?
3 Likes
Karl
(👑🦆)
2
You can use _silgen_name.
@_silgen_name("__MARKER_doIt")
func doIt(_ x: String) -> Int?
func test(_ x: [String]) -> [Int] {
x.compactMap { doIt($0) }
}
Obviously, one should not use underscored attributes in production. They may change or disappear, or their behaviour may change in any way, at any time.
With that disclaimer out of the way: I use this for exactly the same thing you're looking to do - to define a non-optimisable, easily recognisable stub for inspecting generated assembly. For instance, the Godbolt output for the above shows:
[...]
mov r15, qword ptr [r12 - 8]
mov rbx, qword ptr [r12]
mov rdi, rbx
call swift_bridgeObjectRetain@PLT
mov rdi, r15
mov rsi, rbx
call __MARKER_doIt@PLT
mov r15, rax
mov ebp, edx
mov rdi, rbx
call swift_bridgeObjectRelease@PLT
test bpl, 1
[...]
8 Likes
This is exactly the kind of solution I’m looking for. Thanks!