Skip to content

Commit 892e27e

Browse files
committed
Java2Swift: Back-tick escaping for Java method/field names that are Swift keywords
1 parent 1ef3a87 commit 892e27e

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

Sources/Java2SwiftLib/JavaTranslator.swift

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -429,20 +429,21 @@ extension JavaTranslator {
429429
}
430430

431431
let throwsStr = javaMethod.throwsCheckedException ? "throws" : ""
432-
432+
let swiftMethodName = javaMethod.getName().escapedSwiftName
433433
let methodAttribute: AttributeSyntax = javaMethod.isStatic ? "@JavaStaticMethod" : "@JavaMethod";
434434
return """
435435
\(methodAttribute)
436-
public func \(raw: javaMethod.getName())\(raw: genericParameterClause)(\(raw: parametersStr))\(raw: throwsStr)\(raw: resultTypeStr)\(raw: whereClause)
436+
public func \(raw: swiftMethodName)\(raw: genericParameterClause)(\(raw: parametersStr))\(raw: throwsStr)\(raw: resultTypeStr)\(raw: whereClause)
437437
"""
438438
}
439439

440440
package func translateField(_ javaField: Field) throws -> DeclSyntax {
441441
let typeName = try getSwiftTypeNameAsString(javaField.getGenericType()!, outerOptional: true)
442442
let fieldAttribute: AttributeSyntax = javaField.isStatic ? "@JavaStaticField" : "@JavaField";
443+
let swiftFieldName = javaField.getName().escapedSwiftName
443444
return """
444445
\(fieldAttribute)
445-
public var \(raw: javaField.getName()): \(raw: typeName)
446+
public var \(raw: swiftFieldName): \(raw: typeName)
446447
"""
447448
}
448449

Sources/Java2SwiftLib/StringExtras.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
// SPDX-License-Identifier: Apache-2.0
1212
//
1313
//===----------------------------------------------------------------------===//
14+
import SwiftParser
1415

1516
extension String {
1617
/// Split the Swift type name into parent type + innermost type name.
@@ -24,4 +25,13 @@ extension String {
2425
name: String(suffix(from: index(after: lastDot)))
2526
)
2627
}
28+
29+
/// Escape a name with backticks if it's a Swift keyword.
30+
var escapedSwiftName: String {
31+
if isValidSwiftIdentifier(for: .variableName) {
32+
return self
33+
}
34+
35+
return "`\(self)`"
36+
}
2737
}

0 commit comments

Comments
 (0)