diff --git a/Samples/SwiftJavaExtractJNISampleApp/Sources/MySwiftLibrary/DefaultArguments.swift b/Samples/SwiftJavaExtractJNISampleApp/Sources/MySwiftLibrary/DefaultArguments.swift new file mode 100644 index 000000000..21b794fe8 --- /dev/null +++ b/Samples/SwiftJavaExtractJNISampleApp/Sources/MySwiftLibrary/DefaultArguments.swift @@ -0,0 +1,18 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 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 +// +//===----------------------------------------------------------------------===// + +/// Trailing default arguments are Java overloads; Swift fills in the values left out. +public func greeting(name: String = "world", excited: Bool = false) -> String { + "Hello, \(name)\(excited ? "!" : ".")" +} diff --git a/Samples/SwiftJavaExtractJNISampleApp/src/test/java/com/example/swift/DefaultArgumentsTest.java b/Samples/SwiftJavaExtractJNISampleApp/src/test/java/com/example/swift/DefaultArgumentsTest.java new file mode 100644 index 000000000..00c6c01a7 --- /dev/null +++ b/Samples/SwiftJavaExtractJNISampleApp/src/test/java/com/example/swift/DefaultArgumentsTest.java @@ -0,0 +1,28 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 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 +// +//===----------------------------------------------------------------------===// + +package com.example.swift; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class DefaultArgumentsTest { + @Test + void overloadsUseSwiftDefaults() { + assertEquals("Hello, world.", MySwiftLibrary.greeting()); + assertEquals("Hello, Ana.", MySwiftLibrary.greeting("Ana")); + assertEquals("Hello, Ana!", MySwiftLibrary.greeting("Ana", true)); + } +} diff --git a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+DefaultArguments.swift b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+DefaultArguments.swift new file mode 100644 index 000000000..d21171faf --- /dev/null +++ b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+DefaultArguments.swift @@ -0,0 +1,161 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 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 +// +//===----------------------------------------------------------------------===// + +import SwiftExtract +import SwiftSyntax + +// Java has no default arguments, so the JNI output gives a function one overload per trailing +// defaulted parameter a caller may leave out. The overload's thunk calls the function without +// those arguments, and Swift fills in its own defaults: no default expression is translated. + +extension AnalysisResult { + /// Adds an overload for each trailing defaulted parameter a function can be called without, unless + /// a declared function already has that name and parameter types. Protocol requirements can't have + /// default arguments, so protocols are left as they are. + package mutating func expandDefaultArgumentOverloads() { + self.extractedGlobalFuncs = Self.withDefaultArgumentOverloads(self.extractedGlobalFuncs) + + for type in self.extractedTypes.values where type.swiftNominal.kind != .protocol { + type.methods = Self.withDefaultArgumentOverloads(type.methods) + type.initializers = Self.withDefaultArgumentOverloads(type.initializers) + } + } + + private static func withDefaultArgumentOverloads(_ funcs: [ExtractedFunc]) -> [ExtractedFunc] { + var declared = Set(funcs.map(\.overloadKey)) + return funcs.flatMap { function in + let others = sameNameDeclarations(as: function, extracted: funcs) + return [function] + + function.defaultArgumentOverloads().filter { overload in + // The thunk calls the original with only these arguments, which mustn't be ambiguous. + let labels = overload.functionSignature.parameters.map { $0.argumentLabel ?? "_" } + return declared.insert(overload.overloadKey).inserted + && !others.contains { callableLabelLists(of: $0).contains(labels) } + } + } + } + + /// The other declarations a call to `function` could resolve to: those with its name, exported or not, + /// in the same declaration list, and the extracted ones elsewhere (such as in other extensions). + private static func sameNameDeclarations(as function: ExtractedFunc, extracted: [ExtractedFunc]) -> [DeclSyntax] { + var declarations = extracted.filter { $0 !== function }.map { DeclSyntax(fromProtocol: $0.swiftDecl) } + if let list = function.swiftDecl.parent?.parent?.as(MemberBlockItemListSyntax.self) { + declarations += list.map(\.decl) + } else if let list = function.swiftDecl.parent?.parent?.as(CodeBlockItemListSyntax.self) { + declarations += list.compactMap { $0.item.as(DeclSyntax.self) } + } + let isStatic = isStaticDeclaration(DeclSyntax(fromProtocol: function.swiftDecl)) + var seen: Set = [function.swiftDecl.id] + return declarations.filter { declaration in + declarationName(declaration) == function.name && isStaticDeclaration(declaration) == isStatic + && seen.insert(declaration.id).inserted + } + } +} + +extension ExtractedFunc { + /// Overloads that leave out this function's trailing defaulted parameters, longest first. + /// + /// A method whose result may need a `SwiftArena` also gets an overload ending in one, which a + /// Kotlin lambda converts to. So an overload is left out when the parameter after its last one is + /// a closure and the overload with that closure exists: `f(a, SwiftArena)` would be ambiguous with + /// `f(a, closure)`. + func defaultArgumentOverloads() -> [ExtractedFunc] { + let parameters = functionSignature.parameters + let mayTakeArena = apiKind == .initializer || Self.resultMayNeedArena(functionSignature.result.type) + var overloads: [ExtractedFunc] = [] + var count = parameters.count + var longerOverloadExists = true + while count > 0, parameters[count - 1].hasDefaultValue { + count -= 1 + if mayTakeArena, longerOverloadExists, case .function = parameters[count].type { + longerOverloadExists = false + continue + } + longerOverloadExists = true + var signature = functionSignature + signature.parameters = Array(parameters.prefix(count)) + overloads.append( + ExtractedFunc( + module: module, + swiftDecl: swiftDecl, + name: name, + apiKind: apiKind, + functionSignature: signature, + sourceFilePath: sourceFilePath + ) + ) + } + return overloads + } + + /// Whether a result may be returned through a `SwiftArena`: anything but primitives, strings and + /// `Void`, or optionals and arrays of them. + private static func resultMayNeedArena(_ type: SwiftType) -> Bool { + switch type { + case .nominal(let nominal): + switch nominal.asKnownType { + case .bool, .int, .uint, .int8, .uint8, .int16, .uint16, .int32, .uint32, .int64, .uint64, .float, .double, + .string: + return false + case .optional(let wrapped), .array(let wrapped): + return resultMayNeedArena(wrapped) + default: + return true + } + case .tuple(let elements): + return elements.contains { resultMayNeedArena($0.type) } + default: + return true + } + } + + /// Identifies an overload by name and parameter types, as Java does. + fileprivate var overloadKey: String { + "\(name)(\(functionSignature.parameters.map { "\($0.type)" }.joined(separator: ",")))" + } +} + +private func declarationName(_ declaration: DeclSyntax) -> String? { + if let function = declaration.as(FunctionDeclSyntax.self) { + return function.name.text + } + return declaration.is(InitializerDeclSyntax.self) ? "init" : nil +} + +private func isStaticDeclaration(_ declaration: DeclSyntax) -> Bool { + declaration.as(FunctionDeclSyntax.self)?.modifiers.contains { + $0.name.tokenKind == .keyword(.static) || $0.name.tokenKind == .keyword(.class) + } ?? false +} + +/// The argument label lists a call to a function or initializer can use: any parameter with a default +/// value may be left out. +private func callableLabelLists(of declaration: DeclSyntax) -> Set<[String]> { + let parameters: FunctionParameterListSyntax + if let function = declaration.as(FunctionDeclSyntax.self) { + parameters = function.signature.parameterClause.parameters + } else if let initializer = declaration.as(InitializerDeclSyntax.self) { + parameters = initializer.signature.parameterClause.parameters + } else { + return [] + } + var lists: Set<[String]> = [[]] + for parameter in parameters { + let label = parameter.firstName.tokenKind == .wildcard ? "_" : parameter.firstName.text + let withParameter = Set(lists.map { $0 + [label] }) + lists = parameter.defaultValue == nil ? withParameter : lists.union(withParameter) + } + return lists +} diff --git a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+EscapingClosureWrapJava.swift b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+EscapingClosureWrapJava.swift index 3132b8d37..0ffa75810 100644 --- a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+EscapingClosureWrapJava.swift +++ b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+EscapingClosureWrapJava.swift @@ -40,6 +40,9 @@ extension JNISwift2JavaGenerator { _ printer: inout SwiftPrinter, _ closureTy: SyntheticEscapingClosureFunctionType, ) { + guard printedEscapingClosureWrappers.insert(closureTy.javaInterfaceName).inserted else { + return + } printer.printBraceBlock( """ @JavaInterface("\(closureTy.javaBinaryName)") diff --git a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift index f956d0882..f786e9dff 100644 --- a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift +++ b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift @@ -811,12 +811,19 @@ extension JNISwift2JavaGenerator { { return } + // Overloads of a method share its helper class; the first, with every parameter, prints it. + guard printedJavaClosureHelperClasses.insert("\(translated.parentName).\(translated.name)").inserted else { + return + } printer.printBraceBlock( """ public static class \(translated.name) """ ) { printer in + // Only holds interfaces. Without a public constructor, Kotlin's `Type.method()` can't also mean + // `Type.method` constructed, when the method takes no arguments. + printer.print("private \(translated.name)() {}") for functionType in translated.functionTypes { if KnownJavaFunctionalInterface.find(functionType) != nil { continue diff --git a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator.swift b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator.swift index 9f9cee0b1..a555e4fc8 100644 --- a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator.swift +++ b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator.swift @@ -44,6 +44,10 @@ package class JNISwift2JavaGenerator: Swift2JavaGenerator { var thunkNameRegistry = ThunkNameRegistry() + /// Overloads for default arguments share their closure parameters' wrappers and Java interfaces. + var printedEscapingClosureWrappers: Set = [] + var printedJavaClosureHelperClasses: Set = [] + /// Accumulates every ``@_cdecl`` symbol name emitted during thunk printing. /// Written to a linker version script after generation when /// ``Configuration/linkerExportListOutput`` is set. @@ -132,6 +136,8 @@ package class JNISwift2JavaGenerator: Swift2JavaGenerator { // Expand variadic functions into N overloads var expandedAnalysis = analysis expandedAnalysis.expandVariadicOverloads(maxOverloads: config.effectiveMaxVariadicOverloads) + // Default arguments become overloads without the trailing defaulted parameters + expandedAnalysis.expandDefaultArgumentOverloads() self.analysis = expandedAnalysis // Every extracted protocol that also gets a plain Java `interface` diff --git a/Sources/SwiftJavaDocumentation/Documentation.docc/FeaturesJextract.md b/Sources/SwiftJavaDocumentation/Documentation.docc/FeaturesJextract.md index f0dded6c8..ec0d82905 100644 --- a/Sources/SwiftJavaDocumentation/Documentation.docc/FeaturesJextract.md +++ b/Sources/SwiftJavaDocumentation/Documentation.docc/FeaturesJextract.md @@ -136,6 +136,27 @@ generated Java wrapper type. } } +### Default arguments + +In JNI mode, a function or initializer with trailing default arguments gets one +Java overload for each argument a caller can leave out. Swift fills in the +default value, so the default expression is never translated to Java: + +```swift +public func greeting(name: String = "world", excited: Bool = false) -> String +``` + +```java +MySwiftLibrary.greeting(); // "Hello, world." +MySwiftLibrary.greeting("Ana"); // "Hello, Ana." +MySwiftLibrary.greeting("Ana", true); // "Hello, Ana!" +``` + +An overload is left out when a declared function already has the same Java +signature, or when calling the Swift function with those arguments would be +ambiguous. A defaulted parameter that isn't trailing (`f(a: Int = 0, b: Int)`) +must still be passed. + ### Throwing functions Throwing Swift functions are imported as Java methods that throw exceptions. diff --git a/Tests/JExtractSwiftTests/JNI/JNIClosureTests.swift b/Tests/JExtractSwiftTests/JNI/JNIClosureTests.swift index a75317afd..d5f93be2e 100644 --- a/Tests/JExtractSwiftTests/JNI/JNIClosureTests.swift +++ b/Tests/JExtractSwiftTests/JNI/JNIClosureTests.swift @@ -1213,6 +1213,7 @@ struct JNIClosureTests { expectedChunks: [ """ public static class closureWithArgumentsAndReturn { + private closureWithArgumentsAndReturn() {} /** Corresponds to the Swift closure parameter of type {@code (Int64, Bool) -> Int64}. */ @FunctionalInterface public interface closure { diff --git a/Tests/JExtractSwiftTests/JNI/JNIDefaultArgumentsTests.swift b/Tests/JExtractSwiftTests/JNI/JNIDefaultArgumentsTests.swift new file mode 100644 index 000000000..f2c497e78 --- /dev/null +++ b/Tests/JExtractSwiftTests/JNI/JNIDefaultArgumentsTests.swift @@ -0,0 +1,182 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 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 +// +//===----------------------------------------------------------------------===// + +import CodePrinting +import JExtractSwiftLib +import SwiftExtract +import SwiftJavaConfigurationShared +import Testing + +/// Trailing default arguments become Java overloads that leave them out; Swift fills them in. +@Suite +struct JNIDefaultArgumentsTests { + let source = "public func greet(name: String, excited: Bool = false, times: Int32 = 1) -> String {}" + + @Test + func javaOverloads() throws { + try assertOutput( + input: source, + .jni, + .java, + detectChunkByInitialLines: 1, + expectedChunks: [ + "public static java.lang.String greet(java.lang.String name, boolean excited, int times) {", + "public static java.lang.String greet(java.lang.String name, boolean excited) {", + "public static java.lang.String greet(java.lang.String name) {", + "private static native java.lang.String $greet(java.lang.String name);", + ] + ) + } + + @Test + func swiftCallsLeaveTheArgumentsOut() throws { + try assertOutput( + input: source, + .jni, + .swift, + detectChunkByInitialLines: 1, + expectedChunks: [ + "return SwiftModule.greet(name: String(fromJNI: name, in: environment), excited: Bool(fromJNI: excited, in: environment)).getJNILocalRefValue(in: environment)", + "return SwiftModule.greet(name: String(fromJNI: name, in: environment)).getJNILocalRefValue(in: environment)", + ] + ) + } + + @Test + func initializers() throws { + try assertOutput( + input: """ + public struct Point { + public init(x: Int64 = 0, y: Int64 = 0) {} + } + """, + .jni, + .java, + detectChunkByInitialLines: 1, + expectedChunks: [ + "public static Point init(long x, SwiftArena swiftArena) {", + "public static Point init(SwiftArena swiftArena) {", + ] + ) + } + + @Test + func declaredOverloadsWin() throws { + var config = Configuration() + config.swiftModule = "SwiftModule" + let translator = makeSwiftJavaAnalyzer(config: config) + try translator.analyze( + path: "/fake/Fake.swiftinterface", + text: """ + public func f(a: Int64 = 0) {} + public func f() {} + """ + ) + var analysis = translator.result + analysis.expandDefaultArgumentOverloads() + // `f()` is declared, so `f(a:)` adds no overload without `a`. + #expect(analysis.extractedGlobalFuncs.map(\.functionSignature.parameters.count) == [1, 0]) + } + + @Test + func onlyTrailingDefaults() throws { + try assertOutput( + input: "public func f(a: Int64 = 0, b: Int64) {}", + .jni, + .java, + detectChunkByInitialLines: 1, + expectedChunks: ["public static void f(long a, long b) {"], + notExpectedChunks: ["public static void f(long a) {", "public static void f() {"] + ) + } + + let callbacks = """ + public struct Callbacks { + public init(onOpen: @escaping (Int64) -> Void = { _ in }, onClose: @escaping () -> Void = {}) {} + } + public func run(times: Int64, onDone: @escaping () -> Void = {}) {} + """ + + /// An initializer's result may take a `SwiftArena`, which a Kotlin lambda converts to, so + /// `init(onOpen, SwiftArena)` would be ambiguous with `init(onOpen, onClose)`. + @Test + func closureOverloadsThatWouldBeAmbiguousWithAnArena() throws { + var config = Configuration() + config.swiftModule = "SwiftModule" + let translator = makeSwiftJavaAnalyzer(config: config) + try translator.analyze(path: "/fake/Fake.swiftinterface", text: callbacks) + var analysis = translator.result + analysis.expandDefaultArgumentOverloads() + let initializers = try #require(analysis.extractedTypes.values.first?.initializers) + #expect(initializers.map(\.functionSignature.parameters.count) == [2, 0]) + // No arena for a `Void` result, so every overload is kept. + #expect(analysis.extractedGlobalFuncs.map(\.functionSignature.parameters.count) == [2, 1]) + } + + @Test + func overloadsShareClosureWrappers() throws { + try assertOutput( + input: callbacks, + .jni, + .swift, + detectChunkByInitialLines: 1, + expectedChunks: ["public struct JavaSwiftModule_run_onDone"] + ) + var config = Configuration() + config.swiftModule = "SwiftModule" + let translator = makeSwiftJavaAnalyzer(config: config) + try translator.analyze(path: "/fake/Fake.swiftinterface", text: callbacks) + let generator = JNISwift2JavaGenerator( + config: config, + translator: translator, + javaPackage: "com.example.swift", + swiftOutputDirectory: "/fake", + javaOutputDirectory: "/fake", + javaClassLookupTable: [:], + moduleJavaPackages: [:] + ) + var swiftPrinter = SwiftPrinter(mode: .accumulateAll) + try generator.writeSwiftThunkSources(&swiftPrinter) + var javaPrinter = JavaPrinter(mode: .accumulateAll) + try generator.writeExportedJavaSources(&javaPrinter) + #expect(swiftPrinter.contents.components(separatedBy: "public struct JavaSwiftModule_run_onDone").count == 2) + #expect(javaPrinter.contents.components(separatedBy: "public static class run").count == 2) + } + + /// `Quantity.init()` would be ambiguous: the internal `init(value:)` can be called that way too. + @Test + func overloadAmbiguousWithAnotherDeclarationIsSkipped() throws { + try assertOutput( + input: """ + public struct Quantity { + init(value: Int64 = 0) {} + public init(amount: Double = 0) {} + } + + public struct Count { + public init(count: Int64 = 1) {} + } + """, + .jni, + .swift, + expectedChunks: [ + "Quantity.init(amount: Double(fromJNI: amount, in: environment))", + "Count.init()", + ], + notExpectedChunks: [ + "Quantity.init()" + ] + ) + } +} diff --git a/Tests/JExtractSwiftTests/JNI/JNIEscapingClosureTests.swift b/Tests/JExtractSwiftTests/JNI/JNIEscapingClosureTests.swift index d691da948..526f81e29 100644 --- a/Tests/JExtractSwiftTests/JNI/JNIEscapingClosureTests.swift +++ b/Tests/JExtractSwiftTests/JNI/JNIEscapingClosureTests.swift @@ -57,6 +57,7 @@ struct JNIEscapingClosureTests { expectedChunks: [ """ public static class setCallback { + private setCallback() {} /** Corresponds to the Swift closure parameter of type {@code @escaping () -> Void}. */ @FunctionalInterface public interface callback { @@ -97,6 +98,7 @@ struct JNIEscapingClosureTests { expectedChunks: [ """ public static class delayedExecution { + private delayedExecution() {} /** Corresponds to the Swift closure parameter of type {@code @escaping (Int64) -> Int64}. */ @FunctionalInterface public interface closure { @@ -154,6 +156,7 @@ struct JNIEscapingClosureTests { expectedChunks: [ """ public static class setCallback { + private setCallback() {} /** Corresponds to the Swift closure parameter of type {@code @escaping () -> Void}. */ @FunctionalInterface public interface callback {