Skip to content

[jextract] add support for throwing functions in JNI mode #277

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,8 @@ public struct LoweredFunctionSignature: Equatable {
SwiftFunctionSignature(
selfParameter: nil,
parameters: allLoweredParameters,
result: SwiftResult(convention: .direct, type: result.cdeclResultType)
result: SwiftResult(convention: .direct, type: result.cdeclResultType),
effectSpecifiers: []
)
}
}
Expand Down
4 changes: 4 additions & 0 deletions Sources/JExtractSwiftLib/ImportedDecls.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ public final class ImportedFunc: ImportedDecl, CustomStringConvertible {
return prefix + context + self.name
}

var isThrowing: Bool {
self.functionSignature.effectSpecifiers.contains(.throws)
}

init(
module: String,
swiftDecl: any DeclSyntaxProtocol,
Expand Down
29 changes: 22 additions & 7 deletions Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ extension JNISwift2JavaGenerator {
"thisClass: jclass"
] + translatedParameters.map { "\($0.0): \($0.1.jniTypeName)"}
let swiftReturnType = decl.functionSignature.result.type

let thunkReturnType = !swiftReturnType.isVoid ? " -> \(swiftReturnType.javaType.jniTypeName)" : ""

printer.printBraceBlock(
Expand All @@ -137,17 +136,32 @@ extension JNISwift2JavaGenerator {
let label = originalParam.argumentLabel.map { "\($0): "} ?? ""
return "\(label)\(originalParam.type)(fromJNI: \(translatedParam.0), in: environment!)"
}
let functionDowncall = "\(swiftModuleName).\(decl.name)(\(downcallParameters.joined(separator: ", ")))"
let tryClause: String = decl.isThrowing ? "try " : ""
let functionDowncall = "\(tryClause)\(swiftModuleName).\(decl.name)(\(downcallParameters.joined(separator: ", ")))"

if swiftReturnType.isVoid {
printer.print(functionDowncall)
let innerBody = if swiftReturnType.isVoid {
functionDowncall
} else {
"""
let result = \(functionDowncall)
return result.getJNIValue(in: environment)")
"""
}

if decl.isThrowing {
let dummyReturn = !swiftReturnType.isVoid ? "return \(swiftReturnType).jniPlaceholderValue" : ""
printer.print(
"""
let result = \(functionDowncall)
return result.getJNIValue(in: environment)")
do {
\(innerBody)
} catch {
environment.throwAsException(error)
\(dummyReturn)
}
"""
)
} else {
printer.print(innerBody)
}
}
}
Expand Down Expand Up @@ -197,6 +211,7 @@ extension JNISwift2JavaGenerator {
let params = decl.functionSignature.parameters.enumerated().map { idx, param in
"\(param.type.javaType) \(param.parameterName ?? "arg\(idx))")"
}
let throwsClause = decl.isThrowing ? " throws Exception" : ""

printer.print(
"""
Expand All @@ -208,7 +223,7 @@ extension JNISwift2JavaGenerator {
*/
"""
)
printer.print("public static native \(returnType) \(decl.name)(\(params.joined(separator: ", ")));")
printer.print("public static native \(returnType) \(decl.name)(\(params.joined(separator: ", ")))\(throwsClause);")
}
}

Expand Down
17 changes: 17 additions & 0 deletions Sources/JExtractSwiftLib/SwiftTypes/SwiftEffectSpecifier.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

enum SwiftEffectSpecifier: Equatable {
case `throws`
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that's okey, in swift-syntax they're just as a keyword afair -- any opinion about such enum @rintaro ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The enum look okay to me for now. We should support typed throw some day, but not now.

64 changes: 50 additions & 14 deletions Sources/JExtractSwiftLib/SwiftTypes/SwiftFunctionSignature.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,18 @@ public struct SwiftFunctionSignature: Equatable {
var selfParameter: SwiftSelfParameter?
var parameters: [SwiftParameter]
var result: SwiftResult
var effectSpecifiers: [SwiftEffectSpecifier]

init(selfParameter: SwiftSelfParameter? = nil, parameters: [SwiftParameter], result: SwiftResult) {
init(
selfParameter: SwiftSelfParameter? = nil,
parameters: [SwiftParameter],
result: SwiftResult,
effectSpecifiers: [SwiftEffectSpecifier]
) {
self.selfParameter = selfParameter
self.parameters = parameters
self.result = result
self.effectSpecifiers = effectSpecifiers
}
}

Expand Down Expand Up @@ -68,13 +75,16 @@ extension SwiftFunctionSignature {
throw SwiftFunctionTranslationError.generic(generics)
}

let (parameters, effectSpecifiers) = try Self.translateFunctionSignature(
node.signature,
symbolTable: symbolTable
)

self.init(
selfParameter: .initializer(enclosingType),
parameters: try Self.translateFunctionSignature(
node.signature,
symbolTable: symbolTable
),
result: SwiftResult(convention: .direct, type: enclosingType)
parameters: parameters,
result: SwiftResult(convention: .direct, type: enclosingType),
effectSpecifiers: effectSpecifiers
)
}

Expand Down Expand Up @@ -120,7 +130,7 @@ extension SwiftFunctionSignature {
}

// Translate the parameters.
let parameters = try Self.translateFunctionSignature(
let (parameters, effectSpecifiers) = try Self.translateFunctionSignature(
node.signature,
symbolTable: symbolTable
)
Expand All @@ -136,26 +146,28 @@ extension SwiftFunctionSignature {
result = .void
}

self.init(selfParameter: selfParameter, parameters: parameters, result: result)
self.init(selfParameter: selfParameter, parameters: parameters, result: result, effectSpecifiers: effectSpecifiers)
}

/// Translate the function signature, returning the list of translated
/// parameters.
/// parameters and effect specifiers.
static func translateFunctionSignature(
_ signature: FunctionSignatureSyntax,
symbolTable: SwiftSymbolTable
) throws -> [SwiftParameter] {
// FIXME: Prohibit effects for now.
if let throwsClause = signature.effectSpecifiers?.throwsClause {
throw SwiftFunctionTranslationError.throws(throwsClause)
) throws -> ([SwiftParameter], [SwiftEffectSpecifier]) {
var effectSpecifiers = [SwiftEffectSpecifier]()
if signature.effectSpecifiers?.throwsClause != nil {
effectSpecifiers.append(.throws)
}
if let asyncSpecifier = signature.effectSpecifiers?.asyncSpecifier {
throw SwiftFunctionTranslationError.async(asyncSpecifier)
}

return try signature.parameterClause.parameters.map { param in
let parameters = try signature.parameterClause.parameters.map { param in
try SwiftParameter(param, symbolTable: symbolTable)
}

return (parameters, effectSpecifiers)
}

init(_ varNode: VariableDeclSyntax, isSet: Bool, enclosingType: SwiftType?, symbolTable: SwiftSymbolTable) throws {
Expand Down Expand Up @@ -195,6 +207,22 @@ extension SwiftFunctionSignature {
}
let valueType = try SwiftType(varTypeNode, symbolTable: symbolTable)

var effectSpecifiers: [SwiftEffectSpecifier]? = nil
switch binding.accessorBlock?.accessors {
case .getter(let getter):
if let getter = getter.as(AccessorDeclSyntax.self) {
effectSpecifiers = Self.effectSpecifiers(from: getter)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AccessorBlockSyntax.Accessors.getter can only contain CodeBlockItemListSyntax so this should be unreachable.

}
case .accessors(let accessors):
if let getter = accessors.first(where: { $0.accessorSpecifier.tokenKind == .keyword(.get) }) {
effectSpecifiers = Self.effectSpecifiers(from: getter)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should do this only if isSet is false.

}
default:
break
}

self.effectSpecifiers = effectSpecifiers ?? []

if isSet {
self.parameters = [SwiftParameter(convention: .byValue, parameterName: "newValue", type: valueType)]
self.result = .void
Expand All @@ -203,6 +231,14 @@ extension SwiftFunctionSignature {
self.result = .init(convention: .direct, type: valueType)
}
}

private static func effectSpecifiers(from decl: AccessorDeclSyntax) -> [SwiftEffectSpecifier] {
var effectSpecifiers = [SwiftEffectSpecifier]()
if decl.effectSpecifiers?.throwsClause != nil {
effectSpecifiers.append(.throws)
}
return effectSpecifiers
}
}

extension VariableDeclSyntax {
Expand Down
68 changes: 68 additions & 0 deletions Tests/JExtractSwiftTests/JNI/JNIModuleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ struct JNIModuleTests {
public func copy(_ string: String) -> String
"""

let globalMethodThrowing = """
public func methodA() throws
public func methodB() throws -> Int64
"""

@Test
func generatesModuleJavaClass() throws {
let input = "public func helloWorld()"
Expand Down Expand Up @@ -150,4 +155,67 @@ struct JNIModuleTests {
]
)
}

@Test
func globalMethodThrowing_javaBindings() throws {
try assertOutput(
input: globalMethodThrowing,
.jni,
.java,
expectedChunks: [
"""
/**
* Downcall to Swift:
* {@snippet lang=swift :
* public func methodA() throws
* }
*/
public static native void methodA() throws Exception;
""",
"""
/**
* Downcall to Swift:
* {@snippet lang=swift :
* public func methodB() throws -> Int64
* }
*/
public static native long methodB() throws Exception;
""",
]
)
}

@Test
func globalMethodThrowing_swiftThunks() throws {
try assertOutput(
input: globalMethodThrowing,
.jni,
.swift,
detectChunkByInitialLines: 1,
expectedChunks: [
"""
@_cdecl("Java_com_example_swift_SwiftModule_methodA")
func swiftjava_SwiftModule_methodA(environment: UnsafeMutablePointer<JNIEnv?>!, thisClass: jclass) {
do {
try SwiftModule.methodA()
} catch {
environment.throwAsException(error)
}
}
""",
"""
@_cdecl("Java_com_example_swift_SwiftModule_methodB")
func swiftjava_SwiftModule_methodB(environment: UnsafeMutablePointer<JNIEnv?>!, thisClass: jclass) -> jlong {
do {
let result = try SwiftModule.methodB()
return result.getJNIValue(in: environment)
} catch {
environment.throwAsException(error)
return Int64.jniPlaceholderValue
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks ok 👍

}
""",
]
)
}
}