Skip to content

jextract import optional types #139

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

Closed
wants to merge 4 commits into from
Closed
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 @@ -20,6 +20,8 @@
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;

import java.util.OptionalLong;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

Expand Down Expand Up @@ -56,4 +58,11 @@ void test_MySwiftClass_property_len() {
assertEquals(12, got);
}

@Test
void test_MySwiftClass_optionalInt() {
MySwiftClass o = new MySwiftClass(12, 42);
OptionalLong got = o.getOptionalInt(); // FIXME: we need to get the Swift optional as memory region, map it to the Java Optional
assertEquals(12, got);
}

}
4 changes: 4 additions & 0 deletions Sources/ExampleSwiftLibrary/MySwiftLibrary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ public class MySwiftClass {
p("make int -> 12")
return 12
}

public func getOptionalInt() -> Int? {
return 12
}
}

@_silgen_name("swift_getTypeByMangledNameInEnvironment")
Expand Down
48 changes: 48 additions & 0 deletions Sources/JExtractSwift/JavaTypes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,51 @@ extension JavaType {
.class(package: "java.lang", name: "Runnable")
}
}

// ==== ------------------------------------------------------------------------
// Optionals

extension JavaType {

static var javaUtilOptionalInt: JavaType {
.class(package: "java.util", name: "OptionalInt")
}

static var javaUtilOptionalLong: JavaType {
.class(package: "java.util", name: "OptionalLong")
}

static var javaUtilOptionalDouble: JavaType {
.class(package: "java.util", name: "OptionalDouble")
}

// FIXME: general generics?
static func javaUtilOptionalT(_ javaType: JavaType) -> JavaType {
if let className = javaType.className {
return .class(package: "java.util", name: "Optional<\(className)>")
}

if javaType.isPrimitive {
switch javaType {
case .int, .long:
return .javaUtilOptionalLong
case .float, .double:
return .javaUtilOptionalDouble
case .boolean:
return .class(package: "java.util", name: "Optional<Boolean>")
case .byte:
return .class(package: "java.util", name: "Optional<Byte>")
case .char:
return .class(package: "java.util", name: "Optional<Character>")
case .short:
return .class(package: "java.util", name: "Optional<Short>")
case .void:
return .class(package: "java.util", name: "Optional<Void>")
default:
fatalError("Impossible type to map to Optional: \(javaType)")
}
}

fatalError("Impossible type to map to Optional: \(javaType)")
}
}
8 changes: 4 additions & 4 deletions Sources/JExtractSwift/Swift2JavaTranslator+Printing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ extension Swift2JavaTranslator {
for (_, ty) in importedTypes.sorted(by: { (lhs, rhs) in lhs.key < rhs.key }) {
let filename = "\(ty.javaClassName).java"
log.info("Printing contents: \(filename)")
printImportedClass(&printer, ty)
printImportedNominalType(&printer, ty)

try writeContents(
printer.finalize(),
Expand Down Expand Up @@ -110,7 +110,7 @@ extension Swift2JavaTranslator {
}
}

public func printImportedClass(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
public func printImportedNominalType(_ printer: inout CodePrinter, _ decl: ImportedNominalType) {
printHeader(&printer)
printPackage(&printer)
printImports(&printer)
Expand Down Expand Up @@ -152,7 +152,6 @@ extension Swift2JavaTranslator {
}

public func printHeader(_ printer: inout CodePrinter) {
assert(printer.isEmpty)
printer.print(
"""
// Generated by jextract-swift
Expand Down Expand Up @@ -457,7 +456,8 @@ extension Swift2JavaTranslator {
printer.print(
"""
static {
System.loadLibrary("swiftCore");
System.loadLibrary(SwiftKit.STDLIB_DYLIB_NAME);
System.loadLibrary(SwiftKit.SWIFTKIT_DYLIB_NAME);
System.loadLibrary(LIB_NAME);
}
"""
Expand Down
1 change: 1 addition & 0 deletions Sources/JExtractSwift/Swift2JavaVisitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ final class Swift2JavaVisitor: SyntaxVisitor {
}

javaResultType = try cCompatibleType(for: returnTy)
log.trace("Mapped return type type: \(returnTy) -> \(javaResultType)")
} catch {
self.log.info("Unable to import function \(node.name) - \(error)")
return .skipChildren
Expand Down
22 changes: 21 additions & 1 deletion Sources/JExtractSwift/TranslatedType.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,30 @@ extension Swift2JavaVisitor {
case .arrayType, .attributedType, .classRestrictionType, .compositionType,
.dictionaryType, .implicitlyUnwrappedOptionalType, .metatypeType,
.missingType, .namedOpaqueReturnType,
.optionalType, .packElementType, .packExpansionType, .someOrAnyType,
.packElementType, .packExpansionType, .someOrAnyType,
.suppressedType, .tupleType:
throw TypeTranslationError.unimplementedType(type)

case .optionalType(let optionalType):
if optionalType.wrappedType.trimmedDescription == "Int" {
return TranslatedType(
cCompatibleConvention: .direct,
originalSwiftType: optionalType.wrappedType, // FIXME: just optionalType?
cCompatibleSwiftType: "OptionalLong",
cCompatibleJavaMemoryLayout: .heapObject,
javaType: .javaUtilOptionalLong
)
} else if let translatedWrappedType = try? cCompatibleType(for: optionalType.wrappedType) {
return TranslatedType(
cCompatibleConvention: .direct,
originalSwiftType: optionalType.wrappedType, // FIXME: just optionalType?
cCompatibleSwiftType: "Optional<TODO>",
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

FIXME

cCompatibleJavaMemoryLayout: .heapObject,
javaType: .javaUtilOptionalT(translatedWrappedType.javaType)
)
} else {
throw TypeTranslationError.unimplementedType(type)
}
case .functionType(let functionType):
// FIXME: Temporary hack to keep existing code paths working.
if functionType.trimmedDescription == "() -> ()" {
Expand Down
10 changes: 6 additions & 4 deletions SwiftKit/src/main/java/org/swift/swiftkit/SwiftKit.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,17 @@

public class SwiftKit {

private static final String STDLIB_DYLIB_NAME = "swiftCore";
private static final String STDLIB_MACOS_DYLIB_PATH = "/usr/lib/swift/libswiftCore.dylib";
public static final String STDLIB_DYLIB_NAME = "swiftCore";
public static final String SWIFTKIT_DYLIB_NAME = "SwiftKitSwift";

private static final Arena LIBRARY_ARENA = Arena.ofAuto();
static final String STDLIB_MACOS_DYLIB_PATH = "/usr/lib/swift/libswiftCore.dylib";

static final Arena LIBRARY_ARENA = Arena.ofAuto();
static final boolean TRACE_DOWNCALLS = Boolean.getBoolean("jextract.trace.downcalls");

static {
System.loadLibrary(STDLIB_DYLIB_NAME);
System.loadLibrary("SwiftKitSwift");
System.loadLibrary(SWIFTKIT_DYLIB_NAME);
}

static final SymbolLookup SYMBOL_LOOKUP = getSymbolLookup();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 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 org.swift.swiftkit.stdlib;

import org.swift.swiftkit.*;
import org.swift.swiftkit.util.TypeToken;

import java.lang.foreign.*;

public class SwiftOptional<Wrapped extends SwiftInstance> implements SwiftValue {

// Pointer to the referred to class instance's "self".
private final MemorySegment selfMemorySegment;

static final String LIB_NAME = SwiftKit.STDLIB_DYLIB_NAME;

public SwiftOptional(MemorySegment selfMemorySegment) {
this.selfMemorySegment = selfMemorySegment;
}

public final MemorySegment $memorySegment() {
return this.selfMemorySegment;
}

public static final AddressLayout SWIFT_POINTER = ValueLayout.ADDRESS;

private static final GroupLayout $LAYOUT = MemoryLayout.structLayout(
SWIFT_POINTER
).withName("Swift.Optional<T>");

@Override
public GroupLayout $layout() {
return $LAYOUT;
}

@Override
public SwiftAnyType $swiftType() {
var ty = new TypeToken<Wrapped>() {}.getType();
if (ty == Integer.class || ty == Long.class) {
return SwiftKit.getTypeByMangledNameInEnvironment("SiSg").get();
} else {
throw new RuntimeException("Other Optional type mappings not implemented yet");
}
}
}
35 changes: 35 additions & 0 deletions SwiftKit/src/main/java/org/swift/swiftkit/util/TypeToken.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 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 org.swift.swiftkit.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
* Type token to obtain the underlying {@link Type} of a generic type {@code T}.
* @param <T>
*/
public abstract class TypeToken<T> {
private Type type;

protected TypeToken(){
Type superClass = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}

public Type getType() {
return type;
}
}
30 changes: 30 additions & 0 deletions SwiftKit/src/test/java/org/swift/swiftkit/util/TypeTokenTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 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 org.swift.swiftkit.util;

import org.junit.jupiter.api.Test;

import java.lang.reflect.Type;

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

class TypeTokenTest {
@Test
void token() {
var token = new TypeToken<String>() {};
Type type = token.getType();
assertEquals(String.class, type);
}
}
Loading
Loading