Support switch statements with nil pattern matching

This change adds support for highlighting `nil` when
it occurs inside of a `switch` statement’s `case`.
This commit is contained in:
John Sundell 2019-03-09 13:02:33 +01:00
parent d72e816cd8
commit d74074f409
2 changed files with 49 additions and 0 deletions

View File

@ -221,6 +221,15 @@ private extension SwiftGrammar {
func matches(_ segment: Segment) -> Bool {
if segment.tokens.next == ":" {
// Nil pattern matching inside of a switch statement case
if segment.tokens.current == "nil" {
guard let previousToken = segment.tokens.previous else {
return false
}
return previousToken.isAny(of: "case", ",")
}
guard segment.tokens.current == "default" else {
return false
}

View File

@ -202,6 +202,45 @@ final class StatementTests: SyntaxHighlighterTestCase {
])
}
func testSwitchStatementWithOptional() {
let components = highlighter.highlight("""
switch anOptional {
case nil: break
case "value"?: break
default: break
}
""")
XCTAssertEqual(components, [
.token("switch", .keyword),
.whitespace(" "),
.plainText("anOptional"),
.whitespace(" "),
.plainText("{"),
.whitespace("\n"),
.token("case", .keyword),
.whitespace(" "),
.token("nil", .keyword),
.plainText(":"),
.whitespace(" "),
.token("break", .keyword),
.whitespace("\n"),
.token("case", .keyword),
.whitespace(" "),
.token("\"value\"", .string),
.plainText("?:"),
.whitespace(" "),
.token("break", .keyword),
.whitespace("\n"),
.token("default", .keyword),
.plainText(":"),
.whitespace(" "),
.token("break", .keyword),
.whitespace("\n"),
.plainText("}")
])
}
func testForStatementWithStaticProperty() {
let components = highlighter.highlight("for value in Enum.allCases { }")
@ -306,6 +345,7 @@ extension StatementTests {
("testSwitchStatementWithAssociatedValues", testSwitchStatementWithAssociatedValues),
("testSwitchStatementWithFallthrough", testSwitchStatementWithFallthrough),
("testSwitchStatementWithTypePatternMatching", testSwitchStatementWithTypePatternMatching),
("testSwitchStatementWithOptional", testSwitchStatementWithOptional),
("testForStatementWithStaticProperty", testForStatementWithStaticProperty),
("testForStatementWithContinue", testForStatementWithContinue),
("testRepeatWhileStatement", testRepeatWhileStatement)