Skip to content

format all swift sources, enable format checks #109

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 2 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
2 changes: 0 additions & 2 deletions .github/workflows/pull_request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ jobs:
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
with:
api_breakage_check_enabled: false
# FIXME: Something is off with the format task and it gets "stuck", need to investigate
format_check_enabled: false
license_header_check_project_name: Swift.org

test-java:
Expand Down
6 changes: 3 additions & 3 deletions Samples/JavaKitSampleApp/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ let package = Package(
name: "JavaKitExample",
type: .dynamic,
targets: ["JavaKitExample"]
),
)
],

dependencies: [
Expand All @@ -71,12 +71,12 @@ let package = Package(
],
swiftSettings: [
.swiftLanguageMode(.v5),
.unsafeFlags(["-I\(javaIncludePath)", "-I\(javaPlatformIncludePath)"])
.unsafeFlags(["-I\(javaIncludePath)", "-I\(javaPlatformIncludePath)"]),
],
plugins: [
.plugin(name: "JavaCompilerPlugin", package: "swift-java"),
.plugin(name: "Java2SwiftPlugin", package: "swift-java"),
]
),
)
]
)
14 changes: 8 additions & 6 deletions Sources/ExampleSwiftLibrary/MySwiftLibrary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
// No annotations are necessary on the Swift side to perform the export.

#if os(Linux)
import Glibc
import Glibc
#else
import Darwin.C
import Darwin.C
#endif

public func helloWorld() {
Expand All @@ -35,7 +35,7 @@ public func globalTakeIntInt(i: Int, j: Int) {
p("i:\(i), j:\(j)")
}

public func globalCallMeRunnable(run: () -> ()) {
public func globalCallMeRunnable(run: () -> Void) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

c'mon, seriously swift-format? 🤪

(pretty sure that'll break some things since we checked the () -> () string 😅 )

run()
}

Expand Down Expand Up @@ -85,13 +85,15 @@ public func _getTypeByMangledNameInEnvironment(
_ name: UnsafePointer<UInt8>,
_ nameLength: UInt,
genericEnvironment: UnsafeRawPointer?,
genericArguments: UnsafeRawPointer?)
genericArguments: UnsafeRawPointer?
)
-> Any.Type?


// ==== Internal helpers

private func p(_ msg: String, file: String = #fileID, line: UInt = #line, function: String = #function) {
private func p(
_ msg: String, file: String = #fileID, line: UInt = #line, function: String = #function
) {
print("[swift][\(file):\(line)](\(function)) \(msg)")
fflush(stdout)
}
12 changes: 8 additions & 4 deletions Sources/JExtractSwift/CodePrinter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public struct CodePrinter {
}
public var indentationText: String = ""

public static func toString(_ block: (inout CodePrinter) -> ()) -> String {
public static func toString(_ block: (inout CodePrinter) -> Void) -> String {
var printer = CodePrinter()
block(&printer)
return printer.finalize()
Expand Down Expand Up @@ -66,7 +66,7 @@ public struct CodePrinter {
function: String = #function,
file: String = #fileID,
line: UInt = #line,
body: (inout CodePrinter) -> ()
body: (inout CodePrinter) -> Void
) {
indent()
print("\(text) {")
Expand Down Expand Up @@ -145,12 +145,16 @@ public struct CodePrinter {
return contents
}

public mutating func indent(file: String = #fileID, line: UInt = #line, function: String = #function) {
public mutating func indent(
file: String = #fileID, line: UInt = #line, function: String = #function
) {
indentationDepth += 1
log.trace("Indent => \(indentationDepth)", file: file, line: line, function: function)
}

public mutating func outdent(file: String = #fileID, line: UInt = #line, function: String = #function) {
public mutating func outdent(
file: String = #fileID, line: UInt = #line, function: String = #function
) {
indentationDepth -= 1
log.trace("Outdent => \(indentationDepth)", file: file, line: line, function: function)
assert(indentationDepth >= 0, "Outdent beyond zero at [\(file):\(line)](\(function))")
Expand Down
4 changes: 2 additions & 2 deletions Sources/JExtractSwift/Convenience/Collection+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
//
//===----------------------------------------------------------------------===//

public extension Dictionary {
extension Dictionary {
/// Same values, corresponding to mapped keys.
func mapKeys<Transformed>(
public func mapKeys<Transformed>(
_ transform: (Key) throws -> Transformed
) rethrows -> [Transformed: Value] {
.init(
Expand Down
2 changes: 1 addition & 1 deletion Sources/JExtractSwift/Convenience/String+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ extension String {

return "\(f.uppercased())\(String(dropFirst()))"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,8 @@ extension DeclSyntaxProtocol {
extension DeclModifierSyntax {
var isAccessControl: Bool {
switch self.name.tokenKind {
case .keyword(.private): fallthrough
case .keyword(.fileprivate): fallthrough
case .keyword(.internal): fallthrough
case .keyword(.package): fallthrough
case .keyword(.public):
case .keyword(.private), .keyword(.fileprivate), .keyword(.internal), .keyword(.package),
.keyword(.public):
return true
default:
return false
Expand Down
8 changes: 4 additions & 4 deletions Sources/JExtractSwift/ImportedDecls+Printing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@

import Foundation
import JavaTypes
import SwiftSyntax
import OrderedCollections
import SwiftSyntax

extension ImportedFunc {
/// Render a `@{@snippet ... }` comment section that can be put inside a JavaDoc comment
Expand All @@ -37,8 +37,8 @@ extension VariableAccessorKind {

public var fieldSuffix: String {
switch self {
case .get: "_GET"
case .set: "_SET"
case .get: "_GET"
case .set: "_SET"
}
}

Expand Down Expand Up @@ -99,4 +99,4 @@ extension Optional where Wrapped == VariableAccessorKind {
func renderMethodName(_ decl: ImportedFunc) -> String {
self?.renderMethodName(decl) ?? decl.baseIdentifier
}
}
}
27 changes: 17 additions & 10 deletions Sources/JExtractSwift/ImportedDecls.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@

import Foundation
import JavaTypes
import SwiftSyntax
import OrderedCollections
import SwiftSyntax

/// Any imported (Swift) declaration
protocol ImportedDecl {
Expand All @@ -36,7 +36,10 @@ public struct ImportedNominalType: ImportedDecl {
public var methods: [ImportedFunc] = []
public var variables: [ImportedVariable] = []

public init(swiftTypeName: String, javaType: JavaType, swiftMangledName: String? = nil, kind: NominalTypeKind) {
public init(
swiftTypeName: String, javaType: JavaType, swiftMangledName: String? = nil,
kind: NominalTypeKind
) {
self.swiftTypeName = swiftTypeName
self.javaType = javaType
self.swiftMangledName = swiftMangledName
Expand All @@ -56,7 +59,7 @@ public struct ImportedNominalType: ImportedDecl {
/// The Java class name without the package.
public var javaClassName: String {
switch javaType {
case .class(package: _, name: let name): name
case .class(package: _, let name): name
default: javaType.description
}
}
Expand Down Expand Up @@ -250,7 +253,7 @@ public struct ImportedVariable: ImportedDecl, CustomStringConvertible {
public var identifier: String

/// Which accessors are we able to expose.
///
///
/// Usually this will be all the accessors the variable declares,
/// however if the getter is async or throwing we may not be able to import it
/// (yet), and therefore would skip it from the supported set.
Expand Down Expand Up @@ -285,13 +288,14 @@ public struct ImportedVariable: ImportedDecl, CustomStringConvertible {

switch kind {
case .set:
let newValueParam: FunctionParameterSyntax = "_ newValue: \(self.returnType.cCompatibleSwiftType)"
let newValueParam: FunctionParameterSyntax =
"_ newValue: \(self.returnType.cCompatibleSwiftType)"
var funcDecl = ImportedFunc(
parentName: self.parentName,
identifier: self.identifier,
returnType: TranslatedType.void,
parameters: [.init(param: newValueParam, type: self.returnType)])
funcDecl.swiftMangledName = self.swiftMangledName + "s" // form mangled name of the getter by adding the suffix
funcDecl.swiftMangledName = self.swiftMangledName + "s" // form mangled name of the getter by adding the suffix
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

weird decision by swift-format here...

return funcDecl

case .get:
Expand All @@ -300,21 +304,24 @@ public struct ImportedVariable: ImportedDecl, CustomStringConvertible {
identifier: self.identifier,
returnType: self.returnType,
parameters: [])
funcDecl.swiftMangledName = self.swiftMangledName + "g" // form mangled name of the getter by adding the suffix
funcDecl.swiftMangledName = self.swiftMangledName + "g" // form mangled name of the getter by adding the suffix
return funcDecl
}
}

public func effectiveAccessorParameters(_ kind: VariableAccessorKind, selfVariant: SelfParameterVariant?) -> [ImportedParam] {
public func effectiveAccessorParameters(
_ kind: VariableAccessorKind, selfVariant: SelfParameterVariant?
) -> [ImportedParam] {
var params: [ImportedParam] = []

if kind == .set {
let newValueParam: FunctionParameterSyntax = "_ newValue: \(raw: self.returnType.swiftTypeName)"
let newValueParam: FunctionParameterSyntax =
"_ newValue: \(raw: self.returnType.swiftTypeName)"
params.append(
ImportedParam(
param: newValueParam,
type: self.returnType)
)
)
}

if let parentName {
Expand Down
5 changes: 3 additions & 2 deletions Sources/JExtractSwift/JavaType+Printing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
//===----------------------------------------------------------------------===//

import Foundation
import JavaTypes
import SwiftBasicFormat
import SwiftParser
import SwiftSyntax
import JavaTypes

extension JavaType {
/// Returns a 'handle' name to pass to the `invoke` call as well as the
Expand All @@ -42,6 +42,7 @@ extension JavaType {
"""
}

fatalError("Cannot render closure downcall handle for: \(self), in: \(decl), parameter: \(parameter)")
fatalError(
"Cannot render closure downcall handle for: \(self), in: \(decl), parameter: \(parameter)")
}
}
22 changes: 13 additions & 9 deletions Sources/JExtractSwift/NominalTypeResolution.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class NominalTypeResolution {
/// Mapping from qualified nominal type names to their syntax nodes.
private var topLevelNominalTypes: [String: NominalTypeDeclSyntaxNode] = [:]

@_spi(Testing) public init() { }
@_spi(Testing) public init() {}
}

/// A syntax node for a nominal type declaration.
Expand All @@ -59,13 +59,15 @@ extension NominalTypeResolution {
while true {
// If it's a nominal type, add its name.
if let nominal = currentNode.asProtocol(SyntaxProtocol.self) as? NominalTypeDeclSyntaxNode,
let nominalName = nominal.name.identifier?.name {
let nominalName = nominal.name.identifier?.name
{
nameComponents.append(nominalName)
}

// If it's an extension, add the full name of the extended type.
if let extensionDecl = currentNode.as(ExtensionDeclSyntax.self),
let extendedNominal = extendedType(of: extensionDecl) {
let extendedNominal = extendedType(of: extensionDecl)
{
let extendedNominalNameComponents = fullyQualifiedNameComponents(of: extendedNominal)
return extendedNominalNameComponents + nameComponents.reversed()
}
Expand All @@ -90,7 +92,9 @@ extension NominalTypeResolution {

/// Resolve a nominal type name to its syntax node, or nil if it cannot be
/// resolved for any reason.
private func resolveNominalType(_ nameComponents: some Sequence<some StringProtocol>) -> NominalTypeDeclSyntaxNode? {
private func resolveNominalType(_ nameComponents: some Sequence<some StringProtocol>)
-> NominalTypeDeclSyntaxNode?
{
// Resolve the name components in order.
var currentNode: NominalTypeDeclSyntaxNode? = nil
for nameComponentStr in nameComponents {
Expand Down Expand Up @@ -126,8 +130,8 @@ extension NominalTypeResolution {
// If we have a member with the given name that is a nominal type
// declaration, we found what we're looking for.
if let namedMemberDecl = memberDecl.asProtocol(NamedDeclSyntax.self),
namedMemberDecl.name.identifier?.name == name,
let nominalTypeDecl = memberDecl as? NominalTypeDeclSyntaxNode
namedMemberDecl.name.identifier?.name == name,
let nominalTypeDecl = memberDecl as? NominalTypeDeclSyntaxNode
{
return nominalTypeDecl
}
Expand Down Expand Up @@ -241,13 +245,13 @@ extension ExtensionDeclSyntax {
return ["Dictionary"]

case .implicitlyUnwrappedOptionalType, .optionalType:
return [ "Optional" ]
return ["Optional"]

// Types that never involve nominals.

case .classRestrictionType, .compositionType, .functionType, .metatypeType,
.missingType, .namedOpaqueReturnType, .packElementType,
.packExpansionType, .someOrAnyType, .suppressedType, .tupleType:
.missingType, .namedOpaqueReturnType, .packElementType,
.packExpansionType, .someOrAnyType, .suppressedType, .tupleType:
return []
}
}
Expand Down
16 changes: 12 additions & 4 deletions Sources/JExtractSwift/Swift2Java.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,14 @@ public struct SwiftToJava: ParsableCommand {
@Option(help: "The package the generated Java code should be emitted into.")
var packageName: String

@Option(name: .shortAndLong, help: "The directory in which to output the generated Swift files and manifest.")
@Option(
name: .shortAndLong,
help: "The directory in which to output the generated Swift files and manifest.")
var outputDirectory: String = ".build/jextract-swift/generated"

@Option(name: .long, help: "Name of the Swift module to import (and the swift interface files belong to)")
@Option(
name: .long,
help: "Name of the Swift module to import (and the swift interface files belong to)")
var swiftModule: String

// TODO: Once we ship this, make this `.warning` by default
Expand All @@ -53,13 +57,17 @@ public struct SwiftToJava: ParsableCommand {

var fileNo = 1
for interfaceFile in interfaceFiles {
print("[\(fileNo)/\(interfaceFiles.count)] Importing module '\(swiftModule)', interface file: \(interfaceFile)")
print(
"[\(fileNo)/\(interfaceFiles.count)] Importing module '\(swiftModule)', interface file: \(interfaceFile)"
)
defer { fileNo += 1 }

try translator.analyze(swiftInterfacePath: interfaceFile)
try translator.writeImportedTypesTo(outputDirectory: outputDirectory)

print("[\(fileNo)/\(interfaceFiles.count)] Imported interface file: \(interfaceFile) " + "done.".green)
print(
"[\(fileNo)/\(interfaceFiles.count)] Imported interface file: \(interfaceFile) "
+ "done.".green)
}

try translator.writeModuleTo(outputDirectory: outputDirectory)
Expand Down
Loading
Loading