Repository navigation
Expand file tree
/
Copy pathString+Extensions.swift
More file actions
61 lines (54 loc) · 1.79 KB
/
Copy pathString+Extensions.swift
File metadata and controls
61 lines (54 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
extension String {
/// For a String that's of the form java.util.Vector, return the "Vector" part.
package var defaultSwiftNameForJavaClass: String {
if let dotLoc = lastIndex(of: ".") {
let afterDot = index(after: dotLoc)
return String(self[afterDot...]).javaClassNameToCanonicalName.adjustedSwiftTypeName
}
return javaClassNameToCanonicalName.adjustedSwiftTypeName
}
}
extension String {
/// Convert a Java class name to its canonical name.
/// Replaces `$` with `.` for nested classes but preserves `$` at the start of identifiers.
package var javaClassNameToCanonicalName: String {
let regex = try! Regex(#"(\w)\$"#, as: (Substring, Substring).self)
return self.replacing(regex) { match in
"\(match.output.1)."
}
}
/// Whether this is the name of an anonymous class.
package var isLocalJavaClass: Bool {
for segment in split(separator: "$") {
if let firstChar = segment.first, firstChar.isNumber {
return true
}
}
return false
}
/// Adjust type name for "bad" type names that don't work well in Swift.
package var adjustedSwiftTypeName: String {
switch self {
case "Type": return "JavaType"
default: return self
}
}
}