Skip to content

Commit 59c49c0

Browse files
committed
Add distinct error type for invalid escape sequences
1 parent 0ab9a8b commit 59c49c0

2 files changed

Lines changed: 10 additions & 2 deletions

File tree

ShapeScript/Lexer.swift

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ public enum LexerErrorType: Equatable {
8888
case invalidColor(String)
8989
case unexpectedToken(String)
9090
case unterminatedString
91+
case invalidEscapeSequence(String)
9192
}
9293

9394
public struct LexerError: Error, Equatable {
@@ -107,6 +108,11 @@ public struct LexerError: Error, Equatable {
107108
return "Unexpected token '\(token)'"
108109
case .unterminatedString:
109110
return "Unterminated string literal"
111+
case let .invalidEscapeSequence(sequence):
112+
let sequence = sequence.unicodeScalars.contains {
113+
CharacterSet.whitespaces.contains($0)
114+
} ? "'\(sequence)'" : sequence
115+
return "Invalid escape sequence \(sequence)"
110116
}
111117
}
112118

@@ -123,6 +129,8 @@ public struct LexerError: Error, Equatable {
123129
return nil
124130
case .unterminatedString:
125131
return "Try adding a closing \" (double quote) at the end of the line."
132+
case .invalidEscapeSequence:
133+
return "Supported sequences are \\\", \\n and \\\\."
126134
}
127135
}
128136

@@ -337,7 +345,7 @@ private extension Substring {
337345
break loop
338346
default:
339347
let range = start.index(before: startIndex) ..< index(after: startIndex)
340-
throw LexerError(.unexpectedToken(String(start[range])), at: range)
348+
throw LexerError(.invalidEscapeSequence(String(start[range])), at: range)
341349
}
342350
removeFirst()
343351
escaped = false

ShapeScriptTests/LexerTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ class LexerTests: XCTestCase {
184184
let range = input.range(of: "\\'")!
185185
XCTAssertThrowsError(try tokenize(input)) { error in
186186
let error = try? XCTUnwrap(error as? LexerError)
187-
XCTAssertEqual(error, LexerError(.unexpectedToken("\\'"), at: range))
187+
XCTAssertEqual(error, LexerError(.invalidEscapeSequence("\\'"), at: range))
188188
}
189189
}
190190

0 commit comments

Comments
 (0)