Skip to content

Commit

Permalink
Merge pull request #61 from angelolloqui/feature/0.1.3
Browse files Browse the repository at this point in the history
Feature/0.1.3
  • Loading branch information
angelolloqui committed Feb 3, 2018
2 parents f115fce + 6e6015c commit dbeb813
Show file tree
Hide file tree
Showing 13 changed files with 120 additions and 47 deletions.
2 changes: 1 addition & 1 deletion Sources/SwiftKotlinApp/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<string>0.1.3</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftKotlinCommandLine/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ let kotlinTokenizer = KotlinTokenizer(
FoundationMethodsTransformPlugin()
]
)
let version = "0.1.0"
let version = "0.1.3"
let arguments = [
"output",
"help",
Expand Down
69 changes: 61 additions & 8 deletions Sources/SwiftKotlinFramework/KotlinTokenizer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,27 @@ public class KotlinTokenizer: SwiftTokenizer {
}

open override func tokenize(_ declaration: FunctionDeclaration) -> [Token] {
return super.tokenize(declaration)
.replacing({ $0.value == "func"},
with: [declaration.newToken(.keyword, "fun")])
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = declaration.modifiers.map { tokenize($0, node: declaration) }
.joined(token: declaration.newToken(.space, " "))
let genericParameterClauseTokens = declaration.genericParameterClause.map { tokenize($0, node: declaration) } ?? []

let headTokens = [
attrsTokens,
modifierTokens,
[declaration.newToken(.keyword, "fun")],
genericParameterClauseTokens
].joined(token: declaration.newToken(.space, " "))

let signatureTokens = tokenize(declaration.signature, node: declaration)
let bodyTokens = declaration.body.map(tokenize) ?? []

return [
headTokens,
[declaration.newToken(.identifier, declaration.name)] + signatureTokens,
bodyTokens
].joined(token: declaration.newToken(.space, " "))
.prefix(with: declaration.newToken(.linebreak, "\n"))
}

open override func tokenize(_ parameter: FunctionSignature.Parameter, node: ASTNode) -> [Token] {
Expand Down Expand Up @@ -323,14 +341,13 @@ public class KotlinTokenizer: SwiftTokenizer {

guard unionCases.count == declaration.members.count &&
declaration.genericParameterClause == nil &&
declaration.genericWhereClause == nil &&
declaration.typeInheritanceClause == nil else {
declaration.genericWhereClause == nil else {
return self.unsupportedTokens(message: "Complex enums not supported yet", element: declaration, node: declaration).suffix(with: lineBreak) +
super.tokenize(declaration)
}

// Simple enums (no tuples)
if !simpleCases.contains(where: { $0.tuple != nil }) {
if !simpleCases.contains(where: { $0.tuple != nil }) && declaration.typeInheritanceClause == nil {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = declaration.accessLevelModifier.map { tokenize($0, node: declaration) } ?? []
let headTokens = [
Expand All @@ -353,16 +370,18 @@ public class KotlinTokenizer: SwiftTokenizer {
indent(membersTokens) +
[lineBreak, declaration.newToken(.endOfScope, "}")]
}
// Tuples required sealed classes
// Tuples or inhertance required sealed classes
else {
let attrsTokens = tokenize(declaration.attributes, node: declaration)
let modifierTokens = declaration.accessLevelModifier.map { tokenize($0, node: declaration) } ?? []
let inheritanceTokens = declaration.typeInheritanceClause.map { tokenize($0, node: declaration) } ?? []
let headTokens = [
attrsTokens,
modifierTokens,
[declaration.newToken(.keyword, "sealed")],
[declaration.newToken(.keyword, "class")],
[declaration.newToken(.identifier, declaration.name)],
inheritanceTokens
].joined(token: space)

let membersTokens = simpleCases.map { c in
Expand Down Expand Up @@ -394,6 +413,21 @@ public class KotlinTokenizer: SwiftTokenizer {

}

open override func tokenize(_ codeBlock: CodeBlock) -> [Token] {
guard codeBlock.statements.count == 1,
let returnStatement = codeBlock.statements.first as? ReturnStatement,
let parent = codeBlock.lexicalParent as? Declaration else {
return super.tokenize(codeBlock)
}
let sameLine = parent is VariableDeclaration
let separator = sameLine ? codeBlock.newToken(.space, " ") : codeBlock.newToken(.linebreak, "\n")
let tokens = Array(tokenize(returnStatement).dropFirst(2))
return [
[codeBlock.newToken(.symbol, "=")],
sameLine ? tokens : indent(tokens)
].joined(token: separator)
}

// MARK: - Statements

open override func tokenize(_ statement: GuardStatement) -> [Token] {
Expand Down Expand Up @@ -574,6 +608,18 @@ public class KotlinTokenizer: SwiftTokenizer {
with: [expression.newToken(.symbol, binaryOperator)])
}

open override func tokenize(_ expression: FunctionCallExpression) -> [Token] {
var tokens = super.tokenize(expression)
if (expression.postfixExpression is OptionalChainingExpression || expression.postfixExpression is ForcedValueExpression),
let startIndex = tokens.indexOf(kind: .startOfScope, after: 0) {
tokens.insert(contentsOf: [
expression.newToken(.symbol, "."),
expression.newToken(.keyword, "invoke")
], at: startIndex)
}
return tokens
}

open override func tokenize(_ expression: FunctionCallExpression.Argument, node: ASTNode) -> [Token] {
return super.tokenize(expression, node: node)
.replacing({ $0.value == ": " && $0.kind == .delimiter },
Expand Down Expand Up @@ -692,7 +738,14 @@ public class KotlinTokenizer: SwiftTokenizer {
}
}


open override func tokenize(_ expression: OptionalChainingExpression) -> [Token] {
var tokens = tokenize(expression.postfixExpression)
if tokens.last?.value != "this" {
tokens.append(expression.newToken(.symbol, "?"))
}
return tokens
}

// MARK: - Types
open override func tokenize(_ type: ArrayType, node: ASTNode) -> [Token] {
return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,5 @@ fun collectCustomerProviders(customerProvider: () -> String) {
customerProviders.append(customerProvider)
}

fun foo(code: (() -> String)) : String {
return "foo ${bar(code)}"
}
fun foo(code: (() -> String)) : String =
"foo ${bar(code)}"
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,8 @@ when (exception) {
}
else -> trackError(name = "generic", message = R.string.localizable.generic_error())
}
public sealed class SDKException : Error {
object notFound : SDKException()
object unauthorized : SDKException()
data class network(val v1: HttpResponse, val v2: Error?) : SDKException()
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,9 @@ case .qrCode(_):
default:
trackError(name: "generic", message: R.string.localizable.generic_error())
}

public enum SDKException: Error {
case notFound
case unauthorized
case network(HttpResponse, Error?)
}
Original file line number Diff line number Diff line change
@@ -1,24 +1,15 @@
val Double.km: Double
get() {
return this * 1000.0
}
get() = this * 1000.0
val Double.m: Double
get() {
return this
}
get() = this

open fun Double.toKm() : Double {
return this * 1000.0
}
open fun Double.toKm() : Double =
this * 1000.0

fun Double.toMeter() : Double {
return this
}
fun Double.toMeter() : Double =
this

public fun Double.Companion.toKm() : Double {
return this * 1000.0
}
public fun Double.Companion.toKm() : Double =
this * 1000.0
public val Double.Companion.m: Double
get() {
return this
}
get() = this
13 changes: 10 additions & 3 deletions Tests/SwiftKotlinFrameworkTests/Tests/KotlinTokenizer/functions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@ fun method(param: String) : String {}

fun method(param: (Int) -> Unit) {}

fun findRestaurant(restaurantId: Int) : ServiceTask<Restaurant> {
return NetworkRequestServiceTask<Restaurant>(networkSession = networkSession, endpoint = "restaurants/")
}
fun findRestaurant(restaurantId: Int) : ServiceTask<Restaurant> =
NetworkRequestServiceTask<Restaurant>(networkSession = networkSession, endpoint = "restaurants/")
restaurantService.findRestaurant(restaurantId = restaurant.id, param = param)

fun tokenize(codeBlock: String?) : List<String> {
val statement = codeBlock ?: return listOf()
return someOtherMethod(statement = statement)
}

public fun <T> whenAll(promises: List<Promise<T>>) : Promise<List<T>> =
Promise<T>()
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,14 @@ func findRestaurant(restaurantId: Int) -> ServiceTask<Restaurant> {
}

restaurantService.findRestaurant(restaurantId: restaurant.id, param: param)

func tokenize(_ codeBlock: String?) -> [String] {
guard let statement = codeBlock else {
return []
}
return someOtherMethod(statement: statement)
}

public func whenAll<T>(promises: [Promise<T>]) -> Promise<[T]> {
return Promise<T>()
}
10 changes: 6 additions & 4 deletions Tests/SwiftKotlinFrameworkTests/Tests/KotlinTokenizer/lambdas.kt
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
userService.updateUser(picture = picture).always {
this?.hasPhoto = true
this.hasPhoto = true
}
userService.autoLinkTenant(tenantId = tenant.id).then { _ ->
this?.startPayment(paymentMethod, true)
this.startPayment(paymentMethod, true)
}.catchError { _ ->
val intent = this?.coordinator?.autoRegisterIntent(tenant = tenant, onComplete = { this?.startPayment(paymentMethod, true) })
this?.navigationManager?.show(intent, animation = .push)
val intent = this.coordinator.autoRegisterIntent(tenant = tenant, onComplete = { this.startPayment(paymentMethod, true) })
this.navigationManager.show(intent, animation = .push)
}
item.selectCallback = { option ->
presenter.selectPaymentMethod(option)
}
item.selectCallback?.invoke(option)
item.selectCallback!!.invoke(option)
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ userService.autoLinkTenant(tenantId: tenant.id).then { [weak self] _ in
item.selectCallback = { option in
presenter.selectPaymentMethod(option)
}

item.selectCallback?(option)
item.selectCallback!(option)
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ interface Hello {

class A {
val stateObservable1: Observable<RestaurantsListState>
get() {
return state.asObservable()
}
get() = state.asObservable()
val stateObservable2: Observable<RestaurantsListState>
get() {
return state.asObservable()
Expand Down
10 changes: 4 additions & 6 deletions Tests/SwiftKotlinFrameworkTests/Tests/KotlinTokenizer/statics.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,11 @@ class A {

fun method() {}

fun create() : A? {
return null
}
fun create() : A? =
null

fun withParams(param: Int) : A? {
return null
}
fun withParams(param: Int) : A? =
null
}
}

Expand Down

0 comments on commit dbeb813

Please sign in to comment.