diff --git a/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/SwiftKotlinFramework.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/SwiftKotlinFramework.xcscheme new file mode 100644 index 0000000..61ae3be --- /dev/null +++ b/.swiftpm/xcode/xcshareddata/xcschemes/SwiftKotlinFramework.xcscheme @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Assets/Tests/KotlinTokenizer/access_control.kt b/Assets/Tests/KotlinTokenizer/access_control.kt new file mode 100644 index 0000000..b1e01c3 --- /dev/null +++ b/Assets/Tests/KotlinTokenizer/access_control.kt @@ -0,0 +1,80 @@ +internal class ImplicitInternalClass { + private val privateVar: Int = 1 + internal val implicitInternalVar: Int = 1 + internal val explicitInternalVar: Int = 1 + + private class PrivateClass { + private var privateVar: Int = 1 + var implicitPrivateVar: Int = 1 + + class InheritedAccess { + private var privateVar: Int = 1 + var implicitPrivateVar: Int = 1 + + fun inheritedAccessFunc() {} + } + + fun inheritedAccessFunc() {} + } + + internal fun implicitInternalFunc() {} + + internal fun internalFunc() {} + + private fun privateFunc() {} +} + +class PublicClass { + private val privateVar: Int = 1 + internal val implicitInternalVar: Int = 1 + internal val explicitInternalVar: Int = 1 + val publicVar: Int = 1 + + internal class InheritedAccess {} + + internal fun implicitInternalFunc() {} + + internal fun internalFunc() {} + + private fun privateFunc() {} + + fun publicFunc() {} +} + +private class PrivateClass { + + class InheritedAccess {} +} + +data class publicStruct( + var publicVar: String, + internal var internalVar: String, + private var privateVar: String) {} + +internal data class internalStruct( + internal var internalVar: String, + private var privateVar: String) {} + +interface publicProtocol {} +enum class publicEnum { + a +} +internal enum class internalEnum { + a +} + +internal fun implicitInternalFunc() { + val internalVariable = 1 +} + +internal fun internalFunc() { + val internalVariable = 1 +} + +private fun privateFunc() { + val internalVariable = 1 +} + +fun publicFunc() { + val internalVariable = 1 +} diff --git a/Assets/Tests/KotlinTokenizer/access_control.swift b/Assets/Tests/KotlinTokenizer/access_control.swift new file mode 100644 index 0000000..6423fcf --- /dev/null +++ b/Assets/Tests/KotlinTokenizer/access_control.swift @@ -0,0 +1,80 @@ + +class ImplicitInternalClass { + private let privateVar: Int = 1 + let implicitInternalVar: Int = 1 + internal let explicitInternalVar: Int = 1 + + private class PrivateClass { + private var privateVar: Int = 1 + var implicitPrivateVar: Int = 1 + + class InheritedAccess { + private var privateVar: Int = 1 + var implicitPrivateVar: Int = 1 + + func inheritedAccessFunc() {} + } + + func inheritedAccessFunc() {} + } + + func implicitInternalFunc() {} + internal func internalFunc() {} + private func privateFunc() {} +} + +public class PublicClass { + private let privateVar: Int = 1 + let implicitInternalVar: Int = 1 + internal let explicitInternalVar: Int = 1 + public let publicVar: Int = 1 + + class InheritedAccess { + + } + + func implicitInternalFunc() {} + internal func internalFunc() {} + private func privateFunc() {} + public func publicFunc() {} +} + +private class PrivateClass { + class InheritedAccess { + + } +} + +public struct publicStruct { + public var publicVar: String + var internalVar: String + private var privateVar: String +} + +struct internalStruct { + var internalVar: String + private var privateVar: String +} + +public protocol publicProtocol { +} + +public enum publicEnum { + case a +} +enum internalEnum { + case a +} + +func implicitInternalFunc() { + let internalVariable = 1 +} +internal func internalFunc() { + let internalVariable = 1 +} +private func privateFunc() { + let internalVariable = 1 +} +public func publicFunc() { + let internalVariable = 1 +} diff --git a/Assets/Tests/KotlinTokenizer/annotations.kt b/Assets/Tests/KotlinTokenizer/annotations.kt index 25096fe..33f47dc 100644 --- a/Assets/Tests/KotlinTokenizer/annotations.kt +++ b/Assets/Tests/KotlinTokenizer/annotations.kt @@ -1,16 +1,16 @@ -var completionHandlers: List<() -> Unit> = listOf() +internal var completionHandlers: List<() -> Unit> = listOf() -fun someFunctionWithEscapingClosure(completionHandler: () -> Unit) { +internal fun someFunctionWithEscapingClosure(completionHandler: () -> Unit) { completionHandlers.append(completionHandler) } -fun serve(customerProvider: () -> String) { +internal fun serve(customerProvider: () -> String) { print("Now serving ${customerProvider()}!") } -fun collectCustomerProviders(customerProvider: () -> String) { +internal fun collectCustomerProviders(customerProvider: () -> String) { customerProviders.append(customerProvider) } -fun foo(code: (() -> String)) : String = +internal fun foo(code: (() -> String)) : String = "foo ${bar(code)}" diff --git a/Assets/Tests/KotlinTokenizer/constructors.kt b/Assets/Tests/KotlinTokenizer/constructors.kt index 7dd1b87..7e8b0e0 100644 --- a/Assets/Tests/KotlinTokenizer/constructors.kt +++ b/Assets/Tests/KotlinTokenizer/constructors.kt @@ -1,26 +1,33 @@ - open class ClassA { - - public constructor() {} + + constructor() {} } open class ClassB: ClassA { val message: String - val cause: String - - public constructor(message: String, cause: String) : super() { + private val cause: String + + constructor(message: String, cause: String) : super() { this.message = message this.cause = cause } - - public constructor(cause: String) : this(message = "", cuase = cause) {} + + constructor(cause: String) : this(message = "", cuase = cause) {} + + private fun privateMethod() {} + + internal fun internalMethod() {} + + fun implicitInternalMethod() + + fun publicMethod() {} } open class ClassC: ClassB { - - public constructor() : super(message = "message", cause = "cause") {} + + constructor() : super(message = "message", cause = "cause") {} } -val obj1 = ClassA() -val obj2 = ClassB(message = "message", cause = "a cause") -val obj3 = ClassB("a cause") -val obj4 = ClassC() +internal val obj1 = ClassA() +internal val obj2 = ClassB(message = "message", cause = "a cause") +internal val obj3 = ClassB("a cause") +internal val obj4 = ClassC() diff --git a/Assets/Tests/KotlinTokenizer/constructors.swift b/Assets/Tests/KotlinTokenizer/constructors.swift index 8a62684..a43b3d5 100644 --- a/Assets/Tests/KotlinTokenizer/constructors.swift +++ b/Assets/Tests/KotlinTokenizer/constructors.swift @@ -4,8 +4,8 @@ open class ClassA { } open class ClassB: ClassA { - let message: String - let cause: String + public let message: String + private let cause: String public init(message: String, cause: String) { self.message = message @@ -16,6 +16,11 @@ open class ClassB: ClassA { public convenience init(_ cause: String) { self.init(message: "", cuase: cause) } + + private func privateMethod() {} + internal func internalMethod() {} + func implicitInternalMethod() + public func publicMethod() {} } open class ClassC: ClassB { diff --git a/Assets/Tests/KotlinTokenizer/enums.kt b/Assets/Tests/KotlinTokenizer/enums.kt index b52966b..8e21543 100644 --- a/Assets/Tests/KotlinTokenizer/enums.kt +++ b/Assets/Tests/KotlinTokenizer/enums.kt @@ -1,4 +1,4 @@ -enum class CompassPoint { +internal enum class CompassPoint { north, south, east, @@ -14,28 +14,28 @@ private enum class Planet { uranus, neptune } -sealed class Barcode { +internal sealed class Barcode { data class upc(val v1: Int, val v2: Int, val v3: Int, val v4: Int) : Barcode() data class qrCode(val named: String) : Barcode() object empty : Barcode() } -public sealed class SDKException : Error { +sealed class SDKException : Error { object notFound : SDKException() object unauthorized : SDKException() data class network(val v1: HttpResponse, val v2: Error?) : SDKException() } -public enum class PaymentMethodType (val rawValue: String) : Equatable { +enum class PaymentMethodType (val rawValue: String) : Equatable { direct("DIRECT"), creditCard("CREDIT_CARD"); companion object { operator fun invoke(rawValue: String) = PaymentMethodType.values().firstOrNull { it.rawValue == rawValue } } } -enum class AnimationLength { +internal enum class AnimationLength { short, long - val duration: Double + internal val duration: Double get() { when (this) { AnimationLength.short -> return 2 @@ -43,15 +43,15 @@ enum class AnimationLength { } } - fun getDuration() : Double = + internal fun getDuration() : Double = this.duration } -sealed class AnimationLengthAdvanced { +internal sealed class AnimationLengthAdvanced { object short : AnimationLengthAdvanced() object long : AnimationLengthAdvanced() data class custom(val v1: Double) : AnimationLengthAdvanced() - val duration: Double + internal val duration: Double get() { when (this) { short -> return 2 @@ -60,7 +60,7 @@ sealed class AnimationLengthAdvanced { } } - fun getDuration() : Double = + internal fun getDuration() : Double = this.duration } when (enumValue) { @@ -82,7 +82,7 @@ when (planets) { mars, earth, venus -> habitable = true else -> habitable = false } -val nb = 42 +internal val nb = 42 when (nb) { 0 -> print("zero") 1, 2, 3 -> print("low numbers") diff --git a/Assets/Tests/KotlinTokenizer/exceptions.kt b/Assets/Tests/KotlinTokenizer/exceptions.kt index 178faf1..ba46731 100644 --- a/Assets/Tests/KotlinTokenizer/exceptions.kt +++ b/Assets/Tests/KotlinTokenizer/exceptions.kt @@ -1,7 +1,7 @@ -val optA = try { obj.methodThrows() } catch (e: Throwable) { null } -val forceA = obj.methodThrows() +internal val optA = try { obj.methodThrows() } catch (e: Throwable) { null } +internal val forceA = obj.methodThrows() -fun method() { +internal fun method() { obj.methodThrows() } diff --git a/Assets/Tests/KotlinTokenizer/expressions.kt b/Assets/Tests/KotlinTokenizer/expressions.kt index f3bee3b..96cbe34 100644 --- a/Assets/Tests/KotlinTokenizer/expressions.kt +++ b/Assets/Tests/KotlinTokenizer/expressions.kt @@ -1,8 +1,8 @@ -val value = if (isTrue) "yes" else "no" -val label = if (x > 0) "Positive" else "negative" +internal val value = if (isTrue) "yes" else "no" +internal val label = if (x > 0) "Positive" else "negative" button.color = if (item.deleted) red else green -val text = label ?: "default" +internal val text = label ?: "default" service.deleteObject() this.service.fetchData()?.user?.name?.size this.data.filter { it.item?.value == 1 }.map { it.key }.firstOrNull()?.name?.size diff --git a/Assets/Tests/KotlinTokenizer/extensions.kt b/Assets/Tests/KotlinTokenizer/extensions.kt index e21c5ac..3db98ea 100644 --- a/Assets/Tests/KotlinTokenizer/extensions.kt +++ b/Assets/Tests/KotlinTokenizer/extensions.kt @@ -1,15 +1,15 @@ -val Double.km: Double +internal val Double.km: Double get() = this * 1000.0 -val Double.m: Double +internal val Double.m: Double get() = this -open fun Double.toKm() : Double = +private fun Double.toKm() : Double = this * 1000.0 -fun Double.toMeter() : Double = +internal fun Double.toMeter() : Double = this -public fun Double.Companion.toKm() : Double = +fun Double.Companion.toKm() : Double = this * 1000.0 -public val Double.Companion.m: Double +val Double.Companion.m: Double get() = this diff --git a/Assets/Tests/KotlinTokenizer/extensions.swift b/Assets/Tests/KotlinTokenizer/extensions.swift index 9baca1d..8fe853c 100644 --- a/Assets/Tests/KotlinTokenizer/extensions.swift +++ b/Assets/Tests/KotlinTokenizer/extensions.swift @@ -3,7 +3,7 @@ extension Double { var m: Double { return self } } extension Double { - open func toKm() -> Double { return self * 1000.0 } + private func toKm() -> Double { return self * 1000.0 } func toMeter() -> Double { return self } } public extension Double { diff --git a/Assets/Tests/KotlinTokenizer/foundation_types.kt b/Assets/Tests/KotlinTokenizer/foundation_types.kt index c249deb..98697ba 100644 --- a/Assets/Tests/KotlinTokenizer/foundation_types.kt +++ b/Assets/Tests/KotlinTokenizer/foundation_types.kt @@ -1,15 +1,15 @@ -var boolean: Boolean -var anyObject: Any? = null -var any: Any? = null -var array: List? = null -var array: Promise>? = null -var array: List>> -var strings1 = listOf() -var strings2 = listOf("value1", "value2") -var strings3: List = listOf("value3", "value4") -var map: Map? = null -var map: Promise>? = null -var map: Map>> -var map = mapOf(1 to "a", 2 to "b") -var map = mapOf() +internal var boolean: Boolean +internal var anyObject: Any? = null +internal var any: Any? = null +internal var array: List? = null +internal var array: Promise>? = null +internal var array: List>> +internal var strings1 = listOf() +internal var strings2 = listOf("value1", "value2") +internal var strings3: List = listOf("value3", "value4") +internal var map: Map? = null +internal var map: Promise>? = null +internal var map: Map>> +internal var map = mapOf(1 to "a", 2 to "b") +internal var map = mapOf() method(value = listOf("value1", "value")) diff --git a/Assets/Tests/KotlinTokenizer/functions.kt b/Assets/Tests/KotlinTokenizer/functions.kt index f79beef..8cc2444 100644 --- a/Assets/Tests/KotlinTokenizer/functions.kt +++ b/Assets/Tests/KotlinTokenizer/functions.kt @@ -1,28 +1,28 @@ -fun greet(name: String, day: String) {} +internal fun greet(name: String, day: String) {} -fun greet(name: String = "value", day: String, value: Int?) {} +internal fun greet(name: String = "value", day: String, value: Int?) {} -fun method(param: String) : String {} +internal fun method(param: String) : String {} -fun method(param: (Int) -> Unit) {} +internal fun method(param: (Int) -> Unit) {} -fun findRestaurant(restaurantId: Int) : ServiceTask = +internal fun findRestaurant(restaurantId: Int) : ServiceTask = NetworkRequestServiceTask(networkSession = networkSession, endpoint = "restaurants/") restaurantService.findRestaurant(restaurantId = restaurant.id, param = param) -fun tokenize(codeBlock: String?) : List { +internal fun tokenize(codeBlock: String?) : List { val statement = codeBlock ?: return listOf() return someOtherMethod(statement = statement) } -public fun whenAll(promises: List>) : Promise> = +fun whenAll(promises: List>) : Promise> = Promise() -public fun whenAny(promises: List>) : Promise> = +fun whenAny(promises: List>) : Promise> = Promise() -fun sumOf(vararg numbers: Int) : Int { +internal fun sumOf(vararg numbers: Int) : Int { var sum = 0 for (number in numbers) { sum += number diff --git a/Assets/Tests/KotlinTokenizer/keywords.kt b/Assets/Tests/KotlinTokenizer/keywords.kt index b602048..6324751 100644 --- a/Assets/Tests/KotlinTokenizer/keywords.kt +++ b/Assets/Tests/KotlinTokenizer/keywords.kt @@ -1,16 +1,16 @@ -val variable = "string" -var variable: Int? = null +internal val variable = "string" +internal var variable: Int? = null -fun test() {} +internal fun test() {} private fun funcTest() {} -override fun afunc() {} +internal override fun afunc() {} this.method() -var strongSelf = this +internal var strongSelf = this numbers.map { 3 * it.value } -interface Nameable {} -var nextPage = (stateValue.lastPage ?: 0) + 1 +internal interface Nameable {} +internal var nextPage = (stateValue.lastPage ?: 0) + 1 private var number = 3 diff --git a/Assets/Tests/KotlinTokenizer/overrideargs.kt b/Assets/Tests/KotlinTokenizer/overrideargs.kt index 14dd0d6..ffc6436 100644 --- a/Assets/Tests/KotlinTokenizer/overrideargs.kt +++ b/Assets/Tests/KotlinTokenizer/overrideargs.kt @@ -1,7 +1,7 @@ -class Test { +internal class Test { - override fun dostuff(x: Int) {} + internal override fun dostuff(x: Int) {} - fun otherMethod(x: Int = 5) {} + internal fun otherMethod(x: Int = 5) {} } diff --git a/Assets/Tests/KotlinTokenizer/properties.kt b/Assets/Tests/KotlinTokenizer/properties.kt index edae9a9..03d11b3 100644 --- a/Assets/Tests/KotlinTokenizer/properties.kt +++ b/Assets/Tests/KotlinTokenizer/properties.kt @@ -1,35 +1,35 @@ -interface Hello { +internal interface Hello { val foo: String var bar: String } -class A { - var myVar: String? = null - val stateObservable1: Observable +internal class A { + internal var myVar: String? = null + internal val stateObservable1: Observable get() = state.asObservable() - val stateObservable2: Observable + internal val stateObservable2: Observable get() = state.asObservable() - val stateObservable3: Observable + internal val stateObservable3: Observable get() = state.asObservable() - val stateObservable4: Observable + internal val stateObservable4: Observable get() { NSLog("Multiple statements") return state.asObservable() } - var center: Point + internal var center: Point get() = Point(x = centerX, y = centerY) set(newValue) { origin.x = newValue.x - 100 } - var top: Point + internal var top: Point get() = Point(x = topX, y = topY) set(val) { origin.y = 0 origin.x = val.x } - lateinit var subject: TestSubject - val players: List by lazy { + lateinit internal var subject: TestSubject + internal val players: List by lazy { var temporaryPlayers = listOf() temporaryPlayers.append("John Doe") temporaryPlayers @@ -37,7 +37,7 @@ class A { private val name: String by lazy { -> "abc" } - var isLocating = false + internal var isLocating = false set(newValue) { val oldValue = field field = newValue @@ -49,7 +49,7 @@ class A { private set(newValue) { field = newValue } - val myVar: String + internal val myVar: String get() { if (a == 5) { return "test" @@ -59,10 +59,10 @@ class A { } } -data class Rect( - var origin = Point(), - var size = Size()) { - var center: Point +internal data class Rect( + internal var origin = Point(), + internal var size = Size()) { + internal var center: Point get() { val centerX = origin.x + (size.width / 2) val centerY = origin.y + (size.height / 2) @@ -74,8 +74,8 @@ data class Rect( } } -class StepCounter { - var totalSteps: Int = 0 +internal class StepCounter { + internal var totalSteps: Int = 0 set(newTotalSteps) { val oldValue = field print("About to set totalSteps to ${newTotalSteps}") diff --git a/Assets/Tests/KotlinTokenizer/statics.kt b/Assets/Tests/KotlinTokenizer/statics.kt index 3e57a3a..a96840f 100644 --- a/Assets/Tests/KotlinTokenizer/statics.kt +++ b/Assets/Tests/KotlinTokenizer/statics.kt @@ -1,57 +1,57 @@ -class A { +internal class A { companion object { - public var myBool = true + var myBool = true } } -class A { +internal class A { companion object { private var myBool = true var myNum = 3 - var myString = "string" + internal var myString = "string" } } -class A { +internal class A { companion object { - fun method() {} + internal fun method() {} } } -class A { +internal class A { companion object { - fun method() {} + internal fun method() {} - fun create() : A? = + internal fun create() : A? = null - fun withParams(param: Int) : A? = + internal fun withParams(param: Int) : A? = null } } -class A { +internal class A { companion object { - var myBool = true + internal var myBool = true - fun method() {} + internal fun method() {} } - var name = "string" + internal var name = "string" - fun test() {} + internal fun test() {} } -data class A(var name = "string") { +internal data class A(internal var name = "string") { companion object { - var myBool = true + internal var myBool = true - fun method() {} + internal fun method() {} } - fun test() {} + internal fun test() {} } diff --git a/Assets/Tests/KotlinTokenizer/statics.swift b/Assets/Tests/KotlinTokenizer/statics.swift index d8dca0f..d87402f 100644 --- a/Assets/Tests/KotlinTokenizer/statics.swift +++ b/Assets/Tests/KotlinTokenizer/statics.swift @@ -5,7 +5,7 @@ class A { class A { static private var myBool = true - static var myNum = 3 + static public var myNum = 3 static var myString = "string" } diff --git a/Assets/Tests/KotlinTokenizer/string_interpolator.kt b/Assets/Tests/KotlinTokenizer/string_interpolator.kt index 0a77f5b..c3737a8 100644 --- a/Assets/Tests/KotlinTokenizer/string_interpolator.kt +++ b/Assets/Tests/KotlinTokenizer/string_interpolator.kt @@ -1,6 +1,6 @@ -var string1 = "name: ${name}" -var string2 = "full name: ${name} ${lastName}" -var string3 = "name: ${name ?: lastName}" -var string4 = "name: ${user?.name ?: ("-" + lastName)}" -var string5 = "name: ${list.map({ it.name }) ?: "empty"} \tactive: ${active}" -var unicode = "A special \u016C char and interpolator ${name}" +internal var string1 = "name: ${name}" +internal var string2 = "full name: ${name} ${lastName}" +internal var string3 = "name: ${name ?: lastName}" +internal var string4 = "name: ${user?.name ?: ("-" + lastName)}" +internal var string5 = "name: ${list.map({ it.name }) ?: "empty"} \tactive: ${active}" +internal var unicode = "A special \u016C char and interpolator ${name}" diff --git a/Assets/Tests/KotlinTokenizer/structs.kt b/Assets/Tests/KotlinTokenizer/structs.kt index 130045b..71bd864 100644 --- a/Assets/Tests/KotlinTokenizer/structs.kt +++ b/Assets/Tests/KotlinTokenizer/structs.kt @@ -1,15 +1,17 @@ -data class Data(var text: String) {} +internal data class Data(internal var text: String) {} data class Person( - val name: String, - val surname: String, - var age: Int) { + internal val name: String, + internal val surname: String, + internal var age: Int) { - fun eat() {} + internal fun eat() {} + + private fun incrementAge() {} } -data class User( +internal data class User( var id: Int? = 0, var name: String? = null, var content: Content): Codable { diff --git a/Assets/Tests/KotlinTokenizer/structs.swift b/Assets/Tests/KotlinTokenizer/structs.swift index 9c48c54..1280229 100644 --- a/Assets/Tests/KotlinTokenizer/structs.swift +++ b/Assets/Tests/KotlinTokenizer/structs.swift @@ -2,15 +2,16 @@ struct Data { var text: String } -struct Person: Equatable { +public struct Person: Equatable { let name: String let surname: String var age: Int - func eat() {} + internal func eat() {} + private func incrementAge() {} } -struct User: Codable { +internal struct User: Codable { struct Content { let text: String } diff --git a/Assets/Tests/KotlinTokenizer/unwrapping.kt b/Assets/Tests/KotlinTokenizer/unwrapping.kt index 72a5de7..f98b73f 100644 --- a/Assets/Tests/KotlinTokenizer/unwrapping.kt +++ b/Assets/Tests/KotlinTokenizer/unwrapping.kt @@ -1,7 +1,7 @@ -class A { - lateinit var unwrapped: Object - var opt: Object? = null +internal class A { + lateinit internal var unwrapped: Object + internal var opt: Object? = null } -val a = A() +internal val a = A() a.unwrapped.action() a.opt!!.action() diff --git a/Assets/Tests/plugins/CommentsAdditionTransformPlugin.kt b/Assets/Tests/plugins/CommentsAdditionTransformPlugin.kt index 6ca526e..98c22ca 100644 --- a/Assets/Tests/plugins/CommentsAdditionTransformPlugin.kt +++ b/Assets/Tests/plugins/CommentsAdditionTransformPlugin.kt @@ -4,23 +4,24 @@ // // Created by Angel Garcia on 14/10/2017. // -class MyClass { + +internal class MyClass { //Public properties - var a: Int? = null - var b: String? = null - + internal var a: Int? = null + internal var b: String? = null + //Public method - fun aMethod() { + internal fun aMethod() { // A comment inside aMethod b = "method run" b = b + "more" } - + /* Multiline comments are also supported */ - fun anotherMethod() { + internal fun anotherMethod() { val a = this.a if (a != null) { // Inside if @@ -33,5 +34,5 @@ class MyClass { } // Other comments before structs -data class MyStruct {} +internal data class MyStruct {} diff --git a/Assets/Tests/plugins/FoundationMethodsTransformPlugin.kt b/Assets/Tests/plugins/FoundationMethodsTransformPlugin.kt index 77c70d8..2bda9f2 100644 --- a/Assets/Tests/plugins/FoundationMethodsTransformPlugin.kt +++ b/Assets/Tests/plugins/FoundationMethodsTransformPlugin.kt @@ -1,4 +1,4 @@ -val list = listOf(1, 2, 3) +internal val list = listOf(1, 2, 3) list.firstOrNull() list.lastOrNull() list.size diff --git a/Assets/Tests/plugins/UIKitTransformPlugin.kt b/Assets/Tests/plugins/UIKitTransformPlugin.kt index cf293be..76ea08f 100644 --- a/Assets/Tests/plugins/UIKitTransformPlugin.kt +++ b/Assets/Tests/plugins/UIKitTransformPlugin.kt @@ -1,20 +1,20 @@ -class ViewController: UIViewController { - @BindView() lateinit var view: View - @BindView() lateinit var label: TextView - @BindView() lateinit var textField: EditText - @BindView() lateinit var imageView: ImageView - @BindView() lateinit var button: Button - @BindView() lateinit var tableView: RecyclerView - @BindView() lateinit var stackView: LinearLayout - @BindView() lateinit var scrollView: ScrollView - @BindView() lateinit var aSwitch: Switch +internal class ViewController: UIViewController { + @BindView() lateinit internal var view: View + @BindView() lateinit internal var label: TextView + @BindView() lateinit internal var textField: EditText + @BindView() lateinit internal var imageView: ImageView + @BindView() lateinit internal var button: Button + @BindView() lateinit internal var tableView: RecyclerView + @BindView() lateinit internal var stackView: LinearLayout + @BindView() lateinit internal var scrollView: ScrollView + @BindView() lateinit internal var aSwitch: Switch - fun method(label: TextView) : View { + internal fun method(label: TextView) : View { val view = View() view.addSubview(view) return view } - @OnClick() fun onTap() {} + @OnClick() internal fun onTap() {} } diff --git a/Assets/Tests/plugins/XCTTestToJUnitTokenTransformPlugin.kt b/Assets/Tests/plugins/XCTTestToJUnitTokenTransformPlugin.kt index bcb3783..cfd0be9 100644 --- a/Assets/Tests/plugins/XCTTestToJUnitTokenTransformPlugin.kt +++ b/Assets/Tests/plugins/XCTTestToJUnitTokenTransformPlugin.kt @@ -1,53 +1,53 @@ import org.junit.* import org.junit.Assert.* -class AvailabilityServiceTests { - lateinit var service: AvailabilityService - lateinit var mockHttpClient: MockHttpClient +internal class AvailabilityServiceTests { + lateinit internal var service: AvailabilityService + lateinit internal var mockHttpClient: MockHttpClient @Before - fun setUp() { + internal fun setUp() { mockHttpClient = MockHttpClient() service = AvailabilityService(httpClient = mockHttpClient) } @After - fun tearDown() { + internal fun tearDown() { mockHttpClient.clear() } @Test - fun testAssertEqual() { + internal fun testAssertEqual() { assertEquals(1, 1) assertEquals("Not equal", 1, 1) } @Test - fun testAssertTrue() { + internal fun testAssertTrue() { assertTrue(true) assertTrue("Not true", true) } @Test - fun testAssertFalse() { + internal fun testAssertFalse() { assertFalse(false) assertFalse("Should not be true", false) } @Test - fun testAssertNil() { + internal fun testAssertNil() { assertNull(null) assertNull("Should be nil", null) } @Test - fun testAssertNotNil() { + internal fun testAssertNotNil() { assertNotNull("") assertNotNull("Should not be nil", "") } @Test - fun testMultipleStatements() { + internal fun testMultipleStatements() { mockHttpClient.fileResponse = "empty" val result = service.search() val params = mockHttpClient.parameters @@ -58,33 +58,33 @@ class AvailabilityServiceTests { assertNotNull(result) } - fun noTestMethod() { + internal fun noTestMethod() { assertTrue(true) } } -class TestWithInheritance: SomeProtocol { +internal class TestWithInheritance: SomeProtocol { @Test - fun testMethodNotUnderXCTest() { + internal fun testMethodNotUnderXCTest() { assertTrue(true) } } -class ClassWithNoTest: Other { +internal class ClassWithNoTest: Other { - override fun setUp() { + internal override fun setUp() { super.setUp() mockHttpClient = MockHttpClient() service = AvailabilityService(httpClient = mockHttpClient) } - override fun tearDown() { + internal override fun tearDown() { mockHttpClient.clear() super.tearDown() } - fun testMethodNotUnderXCTest() { + internal fun testMethodNotUnderXCTest() { assertTrue(true) } } diff --git a/Sources/SwiftKotlinFramework/KotlinTokenizer.swift b/Sources/SwiftKotlinFramework/KotlinTokenizer.swift index 9abc590..2400f30 100644 --- a/Sources/SwiftKotlinFramework/KotlinTokenizer.swift +++ b/Sources/SwiftKotlinFramework/KotlinTokenizer.swift @@ -15,6 +15,9 @@ import Parser public class KotlinTokenizer: SwiftTokenizer { // MARK: - Declarations + open override func tokenize(_ declaration: Declaration) -> [Token] { + return super.tokenize(changeAccessLevelModifier(declaration)) + } open override func tokenize(_ constant: ConstantDeclaration) -> [Token] { return super.tokenize(constant) @@ -95,6 +98,7 @@ public class KotlinTokenizer: SwiftTokenizer { typeInheritanceClause: declaration.typeInheritanceClause, genericWhereClause: declaration.genericWhereClause, members: declaration.members.filter({ !$0.isStatic })) + declaration.lexicalParent.map(newClass.setLexicalParent) newClass.setSourceRange(declaration.sourceRange) var tokens = super.tokenize(newClass) if !staticMembers.isEmpty, let bodyStart = tokens.firstIndex(where: { $0.value == "{"}) { @@ -256,14 +260,17 @@ public class KotlinTokenizer: SwiftTokenizer { let whereTokens = declaration.genericWhereClause.map { self.unsupportedTokens(message: "Kotlin does not support where clauses in extensions: \($0)", element: $0, node: declaration) } ?? [] - let modifierTokens = declaration.accessLevelModifier.map { tokenize($0, node: declaration) }? - .suffix(with: declaration.newToken(.space, " ")) ?? [] let typeTokens = tokenize(declaration.type, node: declaration) + let accessLevelExtension = declaration.accessLevelModifier let memberTokens = declaration.members.map { member in var tokens = tokenize(member) let firstToken = tokens.firstIndex(where: { $0.kind != .linebreak }) ?? 0 - tokens.insert(contentsOf: modifierTokens, at: firstToken) + let accessLevelMemeber = tokens.compactMap { $0.origin as? AccessLevelModifier }.first + if accessLevelMemeber == nil && accessLevelExtension != nil { + let modifierTokens = tokenize(accessLevelExtension!, node: declaration).suffix(with: declaration.newToken(.space, " ")) + tokens.insert(contentsOf: modifierTokens, at: firstToken) + } if let index = tokens.firstIndex(where: { $0.kind == .identifier }) { if member.isStatic { tokens.insert(contentsOf: [declaration.newToken(.keyword, "Companion"), declaration.newToken(.delimiter, ".")], at: index) diff --git a/Sources/SwiftKotlinFramework/plugins/CommentsAdditionTransformPlugin.swift b/Sources/SwiftKotlinFramework/plugins/CommentsAdditionTransformPlugin.swift index 8f986fd..2fc7541 100644 --- a/Sources/SwiftKotlinFramework/plugins/CommentsAdditionTransformPlugin.swift +++ b/Sources/SwiftKotlinFramework/plugins/CommentsAdditionTransformPlugin.swift @@ -24,14 +24,14 @@ public class CommentsAdditionTransformPlugin: TokenTransformPlugin { public func transform(tokens: [Token], topDeclaration: TopLevelDeclaration) throws -> [Token] { var newTokens = [Token]() var sortedComments = topDeclaration.comments.sorted { $0.location.line < $1.location.line } - + var position = 0 - while position < tokens.count && !sortedComments.isEmpty { + while position < tokens.count && (!sortedComments.isEmpty || tokens[position].kind == .linebreak) { let token = tokens[position] - let comment = sortedComments[0] + let comment = sortedComments.first var consumeComment = false - if let tokenRange = token.sourceRange, + if let comment = comment, let tokenRange = token.sourceRange, tokenRange.isValid { if tokenRange.start.isAfter(location: comment.location) { @@ -39,12 +39,7 @@ public class CommentsAdditionTransformPlugin: TokenTransformPlugin { } } - if consumeComment, let node = token.node { - // Consume linbreaks - if token.kind == .linebreak { - newTokens.append(token) - position += 1 - } + if consumeComment, let comment = comment, let node = token.node { // Consume indentations while position < tokens.count && tokens[position].kind == .indentation { newTokens.append(tokens[position]) @@ -54,7 +49,12 @@ public class CommentsAdditionTransformPlugin: TokenTransformPlugin { sortedComments.removeFirst() tokens.lineIndentationToken(at: position).map { newTokens.append($0) } } else { - newTokens.append(token) + if token.kind == .linebreak, newTokens.last?.kind == .comment, + let previousNoCommentIndex = newTokens.lastIndex(where: { $0.kind != .comment && $0.kind != .indentation }) { + newTokens.insert(token, at: previousNoCommentIndex) + } else { + newTokens.append(token) + } position += 1 } } diff --git a/Sources/SwiftKotlinFramework/plugins/XCTTestToJUnitTokenTransformPlugin.swift b/Sources/SwiftKotlinFramework/plugins/XCTTestToJUnitTokenTransformPlugin.swift index 6abd50a..d04aa22 100644 --- a/Sources/SwiftKotlinFramework/plugins/XCTTestToJUnitTokenTransformPlugin.swift +++ b/Sources/SwiftKotlinFramework/plugins/XCTTestToJUnitTokenTransformPlugin.swift @@ -76,7 +76,7 @@ public class XCTTestToJUnitTokenTransformPlugin: TokenTransformPlugin { var newTokens = tokens for method in testMethods { - if let firstTokenIndex = newTokens.firstIndex(where: { $0.node === method && $0.kind != .linebreak && $0.kind != .indentation }), + if let firstTokenIndex = newTokens.firstIndex(where: { $0.isFrom(method) && $0.kind != .linebreak && $0.kind != .indentation }), let lineBreakIndex = newTokens.indexOf(kind: .linebreak, before: firstTokenIndex) { let indentation = newTokens.lineIndentationToken(at: firstTokenIndex) newTokens.insert(method.newToken(.identifier, annotation), at: lineBreakIndex) @@ -92,7 +92,7 @@ public class XCTTestToJUnitTokenTransformPlugin: TokenTransformPlugin { private func removeSuperCall(_ tokens: [Token], node: FunctionDeclaration) -> [Token] { guard node.modifiers.contains(.override) else { return tokens } var newTokens = tokens - if let overrideIndex = newTokens.firstIndex(where: { $0.node === node && $0.value == "override" }) { + if let overrideIndex = newTokens.firstIndex(where: { $0.isFrom(node) && $0.value == "override" }) { newTokens.remove(at: overrideIndex) newTokens.remove(at: overrideIndex) // Remove the spacing } @@ -160,3 +160,9 @@ public class XCTTestToJUnitTokenTransformPlugin: TokenTransformPlugin { return newTokens } } + +private extension Token { + func isFrom(_ function: FunctionDeclaration) -> Bool { + return (node as? FunctionDeclaration)?.name.textDescription == function.name.textDescription + } +} diff --git a/Sources/SwiftKotlinFramework/utils/Declaration+AccessLevelModifier.swift b/Sources/SwiftKotlinFramework/utils/Declaration+AccessLevelModifier.swift new file mode 100644 index 0000000..0f6989f --- /dev/null +++ b/Sources/SwiftKotlinFramework/utils/Declaration+AccessLevelModifier.swift @@ -0,0 +1,216 @@ +// +// Declaration+AccessLevelModifier.swift +// AST +// +// Created by Angel Luis Garcia on 19/06/2020. +// + +import Transform +import AST + +extension KotlinTokenizer { + func changeAccessLevelModifier(_ declaration: Declaration) -> Declaration { + // If explicit, use it otherwise check parent's + if let accessLevel = declaration.accessLevelModifier { + return declaration.copyWith(accessLevelModifier: accessLevel.toKotlin()) + } + //Extension and protocol members get automatic access level from parent + if declaration.lexicalParent is ExtensionDeclaration || declaration.lexicalParent is ProtocolDeclaration { + return declaration.copyWith(accessLevelModifier: declaration.lexicalParentAccessLevelModifier?.toKotlin()) + } + if declaration.lexicalParentAccessLevelModifier?.toKotlin() != nil { + return declaration + } + return declaration.copyWith(accessLevelModifier: .internal) + } +} + +private extension AccessLevelModifier { + func toKotlin() -> AccessLevelModifier? { + switch self { + case .private, .fileprivate: + return .private + case .internal: + return .internal + case .public: + return nil + case .open: + return .open + default: + return self + } + } +} + +private extension Declaration { + func copyWith(accessLevelModifier: AccessLevelModifier?) -> Declaration { + guard accessLevelModifier != self.accessLevelModifier else { return self } + guard let parent = (self as? ASTNode)?.lexicalParent, parent is CodeBlock != true, parent is ClosureExpression != true else { return self } + let copy: Declaration + switch self { + case let decl as ClassDeclaration: + copy = ClassDeclaration( + attributes: decl.attributes, + accessLevelModifier: accessLevelModifier, + isFinal: decl.isFinal, + name: decl.name, + genericParameterClause: decl.genericParameterClause, + typeInheritanceClause: decl.typeInheritanceClause, + genericWhereClause: decl.genericWhereClause, + members: decl.members + ) + case let decl as ConstantDeclaration: + copy = ConstantDeclaration( + attributes: decl.attributes, + modifiers: decl.modifiers.replacing(accessLevelModifier: accessLevelModifier), + initializerList: decl.initializerList + ) + case let decl as EnumDeclaration: + copy = EnumDeclaration( + attributes: decl.attributes, + accessLevelModifier: accessLevelModifier, + isIndirect: decl.isIndirect, + name: decl.name, + genericParameterClause: decl.genericParameterClause, + typeInheritanceClause: decl.typeInheritanceClause, + genericWhereClause: decl.genericWhereClause, + members: decl.members + ) + case let decl as ExtensionDeclaration: + copy = ExtensionDeclaration( + attributes: decl.attributes, + accessLevelModifier: accessLevelModifier, + type: decl.type, + genericWhereClause: decl.genericWhereClause, + members: decl.members + ) + case let decl as FunctionDeclaration: + copy = FunctionDeclaration( + attributes: decl.attributes, + modifiers: decl.modifiers.replacing(accessLevelModifier: accessLevelModifier), + name: decl.name, + genericParameterClause: decl.genericParameterClause, + signature: decl.signature, + genericWhereClause: decl.genericWhereClause, + body: decl.body + ) + case let decl as InitializerDeclaration: + copy = InitializerDeclaration( + attributes: decl.attributes, + modifiers: decl.modifiers.replacing(accessLevelModifier: accessLevelModifier), + kind: decl.kind, + genericParameterClause: decl.genericParameterClause, + parameterList: decl.parameterList, + throwsKind: decl.throwsKind, + genericWhereClause: decl.genericWhereClause, + body: decl.body + ) + case let decl as ProtocolDeclaration: + copy = ProtocolDeclaration( + attributes: decl.attributes, + accessLevelModifier: accessLevelModifier, + name: decl.name, + typeInheritanceClause: decl.typeInheritanceClause, + members: decl.members + ) + case let decl as StructDeclaration: + copy = StructDeclaration( + attributes: decl.attributes, + accessLevelModifier: accessLevelModifier, + name: decl.name, + genericParameterClause: decl.genericParameterClause, + typeInheritanceClause: decl.typeInheritanceClause, + genericWhereClause: decl.genericWhereClause, + members: decl.members + ) + case let decl as TypealiasDeclaration: + copy = TypealiasDeclaration( + attributes: decl.attributes, + accessLevelModifier: accessLevelModifier, + name: decl.name, + generic: decl.generic, + assignment: decl.assignment + ) + case let decl as VariableDeclaration: + copy = VariableDeclaration( + attributes: decl.attributes, + modifiers: decl.modifiers.replacing(accessLevelModifier: accessLevelModifier), + initializerList: [] + ) + (copy as? VariableDeclaration)?.replaceBody(with: decl.body) + default: + copy = self + } + if let copy = copy as? ASTNode { + lexicalParent.map(copy.setLexicalParent) + copy.setSourceRange(sourceRange) + } + return copy + } +} + +extension Declaration { + var accessLevelModifier: AccessLevelModifier? { + switch self { + case let decl as ClassDeclaration: + return decl.accessLevelModifier + case let decl as ConstantDeclaration: + return decl.modifiers.accessLevelModifier + case let decl as EnumDeclaration: + return decl.accessLevelModifier + case let decl as ExtensionDeclaration: + return decl.accessLevelModifier + case let decl as FunctionDeclaration: + return decl.modifiers.accessLevelModifier + case let decl as InitializerDeclaration: + return decl.modifiers.accessLevelModifier + case let decl as ProtocolDeclaration: + return decl.accessLevelModifier + case let decl as StructDeclaration: + return decl.accessLevelModifier + case let decl as SubscriptDeclaration: + return decl.modifiers.accessLevelModifier + case let decl as TypealiasDeclaration: + return decl.accessLevelModifier + case let decl as VariableDeclaration: + return decl.modifiers.accessLevelModifier + default: + return nil + } + } + + var lexicalParentAccessLevelModifier: AccessLevelModifier? { + var parent = lexicalParent + while parent != nil { + if let declaration = parent as? Declaration, let accessLevelModifier = declaration.accessLevelModifier { + return accessLevelModifier + } + parent = parent?.lexicalParent + } + return nil + } +} + +private extension Collection where Iterator.Element == DeclarationModifier { + var accessLevelModifier: AccessLevelModifier? { + return self.compactMap { $0.accessLevelModifier }.first + } + func replacing(accessLevelModifier: AccessLevelModifier?) -> [DeclarationModifier] { + var modifiers = self.filter { $0.accessLevelModifier == nil } + if let accessLevelModifier = accessLevelModifier { + modifiers.insert(DeclarationModifier.accessLevel(accessLevelModifier), at: 0) + } + return modifiers + } +} + +private extension DeclarationModifier { + var accessLevelModifier: AccessLevelModifier? { + switch self { + case .accessLevel(let accessLevel): + return accessLevel + default: + return nil + } + } +} diff --git a/Sources/SwiftKotlinFramework/utils/Token+Operations.swift b/Sources/SwiftKotlinFramework/utils/Token+Operations.swift index 4800557..43ffaff 100644 --- a/Sources/SwiftKotlinFramework/utils/Token+Operations.swift +++ b/Sources/SwiftKotlinFramework/utils/Token+Operations.swift @@ -53,7 +53,7 @@ extension Array where Iterator.Element == Token { func lineIndentationToken(at index: Int) -> Token? { var indentation: Token? - var position = index + var position = Swift.min(index, self.count - 1) while position >= 0 { let token = self[position] if token.kind == .indentation, let node = token.node {