Skip to content

Commit

Permalink
Merge pull request #115 from angelolloqui/fix/various
Browse files Browse the repository at this point in the history
Fix/various
  • Loading branch information
angelolloqui committed Mar 29, 2020
2 parents def9047 + 4a2c576 commit 530a4db
Show file tree
Hide file tree
Showing 11 changed files with 140 additions and 88 deletions.
10 changes: 0 additions & 10 deletions Assets/Tests/KotlinTokenizer/control_flow.kt
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,3 @@ val match = this.interactor.match
if (match == null || !(interactor.userIsOwner || interactor.userIsPlayer)) {
return
}
when (nb) {
in 0 .. 7, 8, 9 -> print("single digit")
10 -> print("double digits")
11 .. 99 -> print("double digits")
-1 -> {
print("negative digits")
print("Multiple statements")
}
else -> print("three or more digits")
}
12 changes: 0 additions & 12 deletions Assets/Tests/KotlinTokenizer/control_flow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,3 @@ guard let value = some.method() else {
guard let value = some.method() else { throw Exception() }
guard let match = self.interactor.match, (interactor.userIsOwner || interactor.userIsPlayer) else { return }

// Switch
switch nb {
case 0...7, 8, 9: print("single digit")
case 10: print("double digits")
case 11...99: print("double digits")
case -1:
print("negative digits")
print("Multiple statements")

default: print("three or more digits")
}

66 changes: 40 additions & 26 deletions Assets/Tests/KotlinTokenizer/enums.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,6 @@ sealed class Barcode {
data class qrCode(val named: String) : Barcode()
object empty : Barcode()
}
when (enumValue) {
.resetPasswordSendEmail -> return (category: "ResetPassword", name: "sendEmail", label: null)
.paymentSelectorOpen -> return (category: "PaymentSelector", name: "open", label: "${tenant.name} - ${option.duration}min")
}
when (exception) {
.qrCode -> {
val message = serverMessage
if (message != null) {
trackError(name = name, message = message)
} else {
trackError(name = name, message = R.string.localizable.network_error())
}
}
else -> trackError(name = "generic", message = R.string.localizable.generic_error())
}
public sealed class SDKException : Error {
object notFound : SDKException()
object unauthorized : SDKException()
Expand All @@ -47,34 +32,63 @@ public enum class PaymentMethodType (val rawValue: String) : Equatable {
}
}
enum class AnimationLength {
shot,
short,
long

val duration: Double
get() {
when (this) {
.shot -> return 2
.long -> return 5.0
AnimationLength.short -> return 2
long -> return 5.0
}
}

fun getDuration() : Double =
this.duration
}
sealed class AnimationLengthAdvanced {
object shot : AnimationLengthAdvanced()
object short : AnimationLengthAdvanced()
object long : AnimationLengthAdvanced()
data class custom(val v1: Double) : AnimationLengthAdvanced()

val duration: Double
get() {
when (this) {
.shot -> return 2
.long -> return 5.0
.custom -> return duration
short -> return 2
long -> return 5.0
is custom -> return duration
}
}

fun getDuration() : Double =
this.duration
}
when (enumValue) {
resetPasswordSendEmail -> return (category: "ResetPassword", name: "sendEmail", label: null)
is paymentSelectorOpen -> return (category: "PaymentSelector", name: "open", label: "${tenant.name} - ${option.duration}min")
}
when (exception) {
is qrCode -> {
val message = serverMessage
if (message != null) {
trackError(name = name, message = message)
} else {
trackError(name = name, message = R.string.localizable.network_error())
}
}
else -> trackError(name = "generic", message = R.string.localizable.generic_error())
}
when (planets) {
mars, earth, venus -> habitable = true
else -> habitable = false
}
val nb = 42
when (nb) {
0 -> print("zero")
1, 2, 3 -> print("low numbers")
in 4 .. 7, 8, 9 -> print("single digit")
10 -> print("double digits")
in 11 .. 99 -> print("double digits")
in 100 .. 999 -> print("triple digits")
else -> print("four or more digits")
}
67 changes: 43 additions & 24 deletions Assets/Tests/KotlinTokenizer/enums.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,6 @@ enum Barcode {
case empty
}

// Usage
switch enumValue {
case .resetPasswordSendEmail:
return (category: "ResetPassword", name: "sendEmail", label: nil)
case .paymentSelectorOpen(_, let tenant, _, let option):
return (category: "PaymentSelector", name: "open", label: "\(tenant.name) - \(option.duration)min")
}

switch exception {
case .qrCode(_):
if let message = serverMessage {
trackError(name: name, message: message)
} else {
trackError(name: name, message: R.string.localizable.network_error())
}
default:
trackError(name: "generic", message: R.string.localizable.generic_error())
}

public enum SDKException: Error {
case notFound
case unauthorized
Expand All @@ -47,11 +28,11 @@ public enum PaymentMethodType: String, Equatable {
}

enum AnimationLength {
case shot
case short
case long
var duration: Double {
switch self {
case .shot:
case AnimationLength.short:
return 2
case .long:
return 5.0
Expand All @@ -63,14 +44,14 @@ enum AnimationLength {
}
}

enum AnimationLengthAdvanced {
case shot
enum AnimationLengthAdvanced: Equatable {
case short
case long
case custom(Double)

var duration: Double {
switch self {
case .shot:
case .short:
return 2
case .long:
return 5.0
Expand All @@ -83,3 +64,41 @@ enum AnimationLengthAdvanced {
return self.duration
}
}

// Usage
switch enumValue {
case .resetPasswordSendEmail:
return (category: "ResetPassword", name: "sendEmail", label: nil)
case .paymentSelectorOpen(_, let tenant, _, let option):
return (category: "PaymentSelector", name: "open", label: "\(tenant.name) - \(option.duration)min")
}

switch exception {
case .qrCode(_):
if let message = serverMessage {
trackError(name: name, message: message)
} else {
trackError(name: name, message: R.string.localizable.network_error())
}
default:
trackError(name: "generic", message: R.string.localizable.generic_error())
}

switch planets {
case .mars, .earth, .venus:
habitable = true
default:
habitable = false

}

let nb = 42
switch nb {
case 0: print("zero")
case 1, 2, 3: print("low numbers")
case 4...7, 8, 9: print("single digit")
case 10: print("double digits")
case 11...99: print("double digits")
case 100...999: print("triple digits")
default: print("four or more digits")
}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
![](Assets/logo_small.png)

![status](https://travis-ci.org/angelolloqui/SwiftKotlin.svg?branch=develop)
![Swift 4.2](https://img.shields.io/badge/swift-4.2-brightgreen.svg)
![Swift 5](https://img.shields.io/badge/swift-5-brightgreen.svg)
![Swift Package Manager](https://img.shields.io/badge/SPM-ready-orange.svg)
[![License](https://img.shields.io/badge/license-MIT-lightgrey.svg?maxAge=2592000)](https://opensource.org/licenses/MIT)
[![Twitter](https://img.shields.io/badge/[email protected]?maxAge=2592000)](http://twitter.com/angelolloqui)
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftKotlinCommandLine/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ let kotlinTokenizer = KotlinTokenizer(
CommentsAdditionTransformPlugin()
]
)
let version = "0.2.3"
let version = "0.2.4"
let arguments = [
"output",
"help",
Expand Down
34 changes: 25 additions & 9 deletions Sources/SwiftKotlinFramework/KotlinTokenizer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,6 @@ public class KotlinTokenizer: SwiftTokenizer {
]
switch statement {
case let .case(itemList, stmts):
let prefix = itemList.count > 1 ? [statement.newToken(.keyword, "in", node), statement.newToken(.space, " ", node)] : []
let conditions = itemList.map { tokenize($0, node: node) }.joined(token: statement.newToken(.delimiter, ", ", node))
var statements = tokenize(stmts, node: node)
if stmts.count > 1 || statements.filter({ $0.kind == .linebreak }).count > 1 {
Expand All @@ -530,7 +529,7 @@ public class KotlinTokenizer: SwiftTokenizer {
indent(statements) +
[linebreak, statement.newToken(.endOfScope, "}", node)]
}
return prefix + conditions + separatorTokens + statements
return conditions + separatorTokens + statements

case .default(let stmts):
return
Expand All @@ -541,17 +540,34 @@ public class KotlinTokenizer: SwiftTokenizer {
}

open override func tokenize(_ statement: SwitchStatement.Case.Item, node: ASTNode) -> [Token] {
guard let enumCasePattern = statement.pattern as? EnumCasePattern else {
return super.tokenize(statement, node: node)
let prefix: [Token]
if let expression = (statement.pattern as? ExpressionPattern)?.expression {
prefix = !(expression is LiteralExpression) ? [statement.newToken(.keyword, "in", node)] : []
} else {
prefix = []
}
let patternWithoutTuple = EnumCasePattern(typeIdentifier: enumCasePattern.typeIdentifier, name: enumCasePattern.name, tuplePattern: nil)
return [
tokenize(patternWithoutTuple, node: node),
statement.whereExpression.map { _ in [statement.newToken(.keyword, "where", node)] } ?? [],
statement.whereExpression.map { tokenize($0) } ?? []
].joined(token: statement.newToken(.space, " ", node))
prefix,
super.tokenize(statement, node: node)
].joined(token: statement.newToken(.space, " ", node))
}

open override func tokenize(_ pattern: EnumCasePattern, node: ASTNode) -> [Token] {
let patternWithoutTuple: EnumCasePattern
let prefix: [Token]
if pattern.tuplePattern != nil {
patternWithoutTuple = EnumCasePattern(typeIdentifier: pattern.typeIdentifier, name: pattern.name, tuplePattern: nil)
prefix = [pattern.newToken(.keyword, "is", node), pattern.newToken(.space, " ", node)]
} else {
patternWithoutTuple = pattern
prefix = []
}
var tokens = super.tokenize(patternWithoutTuple, node: node)
if tokens.first?.value == "." {
tokens.remove(at: 0)
}
return prefix + tokens
}

open override func tokenize(_ statement: ForInStatement) -> [Token] {
var tokens = super.tokenize(statement)
Expand Down
10 changes: 10 additions & 0 deletions Sources/SwiftKotlinFramework/utils/AST+Operations.swift
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,16 @@ extension GuardStatement {
}
}

extension TypeInheritanceClause {
var nonEquatable: TypeInheritanceClause? {
let typeInheritanceList = self.typeInheritanceList.nonEquatable
if typeInheritanceList.isEmpty {
return nil
}
return TypeInheritanceClause(classRequirement: classRequirement, typeInheritanceList: typeInheritanceList)
}
}

extension Collection where Iterator.Element == TypeIdentifier {
var nonEquatable: [TypeIdentifier] {
return filter { $0.names.contains { $0.name.textDescription != "Equatable" } }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ extension KotlinTokenizer {
let lineBreak = declaration.newToken(.linebreak, "\n")
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 inheritanceTokens = declaration.typeInheritanceClause?.nonEquatable.map { tokenize($0, node: declaration) } ?? []
let headTokens = [
attrsTokens,
modifierTokens,
Expand Down
4 changes: 2 additions & 2 deletions SwiftKotlinApp.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@
INFOPLIST_FILE = "$(SRCROOT)/Sources/SwiftKotlinApp/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.12;
MARKETING_VERSION = 0.2.3;
MARKETING_VERSION = 0.2.4;
MTL_ENABLE_DEBUG_INFO = YES;
PRODUCT_BUNDLE_IDENTIFIER = com.angelolloqui.SwiftKotlinApp;
PRODUCT_NAME = SwiftKotlin;
Expand Down Expand Up @@ -352,7 +352,7 @@
INFOPLIST_FILE = "$(SRCROOT)/Sources/SwiftKotlinApp/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.12;
MARKETING_VERSION = 0.2.3;
MARKETING_VERSION = 0.2.4;
MTL_ENABLE_DEBUG_INFO = NO;
PRODUCT_BUNDLE_IDENTIFIER = com.angelolloqui.SwiftKotlinApp;
PRODUCT_NAME = SwiftKotlin;
Expand Down
19 changes: 17 additions & 2 deletions Tests/SwiftKotlinFrameworkTests/KotlinTokenizerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ extension KotlinTokenizerTests {
let swiftURL = URL(fileURLWithPath: "\(path)/\(file).swift")
let kotlinURL = URL(fileURLWithPath: "\(path)/\(file).kt")

let expected = try String(contentsOf: kotlinURL).trimmingCharacters(in: .whitespacesAndNewlines)
let expected = try String(contentsOf: kotlinURL).removingLineTrailingSpacing()
let translated = kotlinTokenizer.translate(path: swiftURL).tokens?
.joinedValues().trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
.joinedValues().removingLineTrailingSpacing() ?? ""

if translated != expected {
let difference = prettyFirstDifferenceBetweenStrings(translated, expected)
Expand All @@ -60,4 +60,19 @@ extension KotlinTokenizerTests {
}
}

private extension String {
func removingLineTrailingSpacing() -> String {
return components(separatedBy: "\n")
.map { $0.trimmingLastIndentSpacing() }
.joined(separator: "\n")
.trimmingCharacters(in: .whitespacesAndNewlines)
}

func trimmingLastIndentSpacing() -> String {
var view = self[...]
while view.last?.isWhitespace == true {
view = view.dropLast()
}
return String(view)
}
}

0 comments on commit 530a4db

Please sign in to comment.