Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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 @@ -18,8 +18,8 @@

// Import javakit/swiftkit support libraries

import org.swift.swiftkit.core.SwiftArena;
import org.swift.swiftkit.core.SwiftLibraries;
import org.swift.swiftkit.core.ConfinedSwiftMemorySession;

public class HelloJava2SwiftJNI {

Expand All @@ -41,7 +41,7 @@ static void examples() {

MySwiftClass.method();

try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass myClass = MySwiftClass.init(10, 5, arena);
MySwiftClass myClass2 = MySwiftClass.init(arena);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
package com.example.swift;

import org.junit.jupiter.api.Test;
import org.swift.swiftkit.core.ConfinedSwiftMemorySession;
import org.swift.swiftkit.core.SwiftArena;

import java.util.Optional;
import java.util.OptionalInt;
Expand All @@ -26,39 +26,39 @@
public class MySwiftClassTest {
@Test
void init_noParameters() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(arena);
assertNotNull(c);
}
}

@Test
void init_withParameters() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(1337, 42, arena);
assertNotNull(c);
}
}

@Test
void sum() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(30, c.sum());
}
}

@Test
void xMultiplied() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(200, c.xMultiplied(10));
}
}

@Test
void throwingFunction() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
Exception exception = assertThrows(Exception.class, () -> c.throwingFunction());

Expand All @@ -68,15 +68,15 @@ void throwingFunction() {

@Test
void constant() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(100, c.getConstant());
}
}

@Test
void mutable() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(0, c.getMutable());
c.setMutable(42);
Expand All @@ -86,15 +86,15 @@ void mutable() {

@Test
void product() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(200, c.getProduct());
}
}

@Test
void throwingVariable() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);

Exception exception = assertThrows(Exception.class, () -> c.getThrowingVariable());
Expand All @@ -105,7 +105,7 @@ void throwingVariable() {

@Test
void mutableDividedByTwo() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(0, c.getMutableDividedByTwo());
c.setMutable(20);
Expand All @@ -117,15 +117,15 @@ void mutableDividedByTwo() {

@Test
void isWarm() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertFalse(c.isWarm());
}
}

@Test
void sumWithX() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c1 = MySwiftClass.init(20, 10, arena);
MySwiftClass c2 = MySwiftClass.init(50, 10, arena);
assertEquals(70, c1.sumX(c2));
Expand All @@ -134,7 +134,7 @@ void sumWithX() {

@Test
void copy() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c1 = MySwiftClass.init(20, 10, arena);
MySwiftClass c2 = c1.copy(arena);

Expand All @@ -146,7 +146,7 @@ void copy() {

@Test
void addXWithJavaLong() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c1 = MySwiftClass.init(20, 10, arena);
Long javaLong = 50L;
assertEquals(70, c1.addXWithJavaLong(javaLong));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@

import org.junit.jupiter.api.Test;
import org.swift.swiftkit.core.ConfinedSwiftMemorySession;
import org.swift.swiftkit.core.SwiftArena;

import static org.junit.jupiter.api.Assertions.*;

public class MySwiftStructTest {
@Test
void init() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftStruct s = MySwiftStruct.init(1337, 42, arena);
assertEquals(1337, s.getCapacity());
assertEquals(42, s.getLen());
Expand All @@ -31,7 +32,7 @@ void init() {

@Test
void getAndSetLen() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftStruct s = MySwiftStruct.init(1337, 42, arena);
s.setLen(100);
assertEquals(100, s.getLen());
Expand All @@ -40,7 +41,7 @@ void getAndSetLen() {

@Test
void increaseCap() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftStruct s = MySwiftStruct.init(1337, 42, arena);
long newCap = s.increaseCap(10);
assertEquals(1347, newCap);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
package com.example.swift;

import org.junit.jupiter.api.Test;
import org.swift.swiftkit.core.ConfinedSwiftMemorySession;
import org.swift.swiftkit.core.SwiftArena;

import java.util.Optional;
import java.util.OptionalDouble;
Expand Down Expand Up @@ -82,7 +82,7 @@ void optionalString() {

@Test
void optionalClass() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(arena);
assertEquals(Optional.empty(), MySwiftLibrary.optionalClass(Optional.empty(), arena));
Optional<MySwiftClass> optionalClass = MySwiftLibrary.optionalClass(Optional.of(c), arena);
Expand All @@ -99,7 +99,7 @@ void optionalJavaKitLong() {

@Test
void multipleOptionals() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(arena);
OptionalLong result = MySwiftLibrary.multipleOptionals(
Optional.of((byte) 1),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import JavaTypes

// MARK: Defaults

private let globalArenaName = "GLOBAL_ARENA"

extension JNISwift2JavaGenerator {
/// Default set Java imports for every generated file
static let defaultJavaImports: Array<String> = [
Expand Down Expand Up @@ -72,6 +74,11 @@ extension JNISwift2JavaGenerator {
printImports(&printer)

printModuleClass(&printer) { printer in
if config.effectiveMemoryManagementMode.requiresGlobalArena {
printer.print("static final SwiftArena \(globalArenaName) = SwiftArena.ofAuto();")
printer.println()
}

printer.print(
"""
static final String LIB_NAME = "\(swiftModuleName)";
Expand Down Expand Up @@ -247,29 +254,50 @@ extension JNISwift2JavaGenerator {
guard let translatedDecl = translatedDecl(for: decl) else {
fatalError("Decl was not translated, \(decl)")
}
let translatedSignature = translatedDecl.translatedFunctionSignature

var modifiers = ["public"]

if decl.isStatic || decl.isInitializer || !decl.hasParent {
modifiers.append("static")
}

let translatedSignature = translatedDecl.translatedFunctionSignature
let resultType = translatedSignature.resultType.javaType
var parameters = translatedDecl.translatedFunctionSignature.parameters.map({ $0.parameter.renderParameter() })
if translatedSignature.requiresSwiftArena {
parameters.append("SwiftArena swiftArena$")
}
var parameters = translatedDecl.translatedFunctionSignature.parameters.map { $0.parameter.renderParameter() }
let throwsClause = decl.isThrowing ? " throws Exception" : ""

var annotationsStr = translatedSignature.annotations.map({ $0.render() }).joined(separator: "\n")
if !annotationsStr.isEmpty { annotationsStr += "\n" }

let modifiersStr = modifiers.joined(separator: " ")
let parametersStr = parameters.joined(separator: ", ")

// Print default global arena variation
if config.effectiveMemoryManagementMode.requiresGlobalArena && translatedSignature.requiresSwiftArena {
printDeclDocumentation(&printer, decl)
printer.printBraceBlock(
"\(annotationsStr)\(modifiers.joined(separator: " ")) \(resultType) \(translatedDecl.name)(\(parametersStr))\(throwsClause)"
) { printer in
let arguments = translatedDecl.translatedFunctionSignature.parameters.map(\.parameter.name) + ["\(swiftModuleName).\(globalArenaName)"]
let call = "\(translatedDecl.name)(\(arguments.joined(separator: ", ")))"
if translatedDecl.translatedFunctionSignature.resultType.javaType.isVoid {
printer.print("\(call);")
} else {
printer.print("return \(call);")
}
}
printer.println()
}

// Make any function with explicit arena private if we force automatic.
if config.effectiveMemoryManagementMode == .forceAutomatic && translatedSignature.requiresSwiftArena {
modifiers[0] = "private"
}
if translatedSignature.requiresSwiftArena {
parameters.append("SwiftArena swiftArena$")
}
printDeclDocumentation(&printer, decl)
printer.printBraceBlock(
"\(annotationsStr)\(modifiersStr) \(resultType) \(translatedDecl.name)(\(parametersStr))\(throwsClause)"
"\(annotationsStr)\(modifiers.joined(separator: " ")) \(resultType) \(translatedDecl.name)(\(parameters.joined(separator: ", ")))\(throwsClause)"
) { printer in
printDowncall(&printer, decl)
}
Expand Down
5 changes: 5 additions & 0 deletions Sources/JavaKitConfigurationShared/Configuration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ public struct Configuration: Codable {
minimumInputAccessLevelMode ?? .default
}

public var memoryManagementMode: JExtractMemoryManagementMode?
public var effectiveMemoryManagementMode: JExtractMemoryManagementMode {
memoryManagementMode ?? .default
}

// ==== java 2 swift ---------------------------------------------------------

/// The Java class path that should be passed along to the swift-java tool.
Expand Down
26 changes: 26 additions & 0 deletions Sources/JavaKitConfigurationShared/GenerationMode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,29 @@ extension JExtractMinimumAccessLevelMode {
.public
}
}


/// Configures how memory should be managed by the user
public enum JExtractMemoryManagementMode: String, Codable {
/// Force users to provide an explicit `SwiftArena` to all calls that require them.
case forceExplicit

/// Provide both explicit `SwiftArena` support
/// and a default global automatic `SwiftArena` that will deallocate memory when the GC decides to.
case allowAutomatic

/// Force all memory management to a default global automatic `SwiftArena`
/// that will deallocate memory when the GC decides to.
case forceAutomatic

public static var `default`: Self {
.forceExplicit
}

public var requiresGlobalArena: Bool {
switch self {
case .forceExplicit: false
case .allowAutomatic, .forceAutomatic: true
}
}
}
9 changes: 9 additions & 0 deletions Sources/SwiftJavaTool/Commands/JExtractCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ extension SwiftJava {
@Option(help: "The lowest access level of Swift declarations that should be extracted, defaults to 'public'.")
var minimumInputAccessLevel: JExtractMinimumAccessLevelMode = .default

@Option(help: "The memory management mode to use for the generated code. By default, the user must explicitly provide `SwiftArena` to all calls that require it. By choosing `allow-automatic`, user can omit this parameter and a global GC-based arena will be used. `force-automatic` removes all explicit memory management.")
var memoryManagementMode: JExtractMemoryManagementMode = .default

@Option(
help: """
A swift-java configuration file for a given Swift module name on which this module depends,
Expand All @@ -89,6 +92,7 @@ extension SwiftJava.JExtractCommand {
config.writeEmptyFiles = writeEmptyFiles
config.unsignedNumbersMode = unsignedNumbers
config.minimumInputAccessLevelMode = minimumInputAccessLevel
config.memoryManagementMode = memoryManagementMode

try checkModeCompatibility()

Expand Down Expand Up @@ -117,6 +121,10 @@ extension SwiftJava.JExtractCommand {
case .wrapGuava:
() // OK
}
} else if self.mode == .ffm {
guard self.memoryManagementMode == .forceExplicit else {
throw IllegalModeCombinationError("FFM mode does not support '\(self.memoryManagementMode)' memory management mode! \(Self.helpMessage)")
}
}
}
}
Expand Down Expand Up @@ -148,3 +156,4 @@ struct IllegalModeCombinationError: Error {
extension JExtractGenerationMode: ExpressibleByArgument {}
extension JExtractUnsignedIntegerMode: ExpressibleByArgument {}
extension JExtractMinimumAccessLevelMode: ExpressibleByArgument {}
extension JExtractMemoryManagementMode: ExpressibleByArgument {}
Loading
Loading