Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix an error message StartsWith parser throws #332

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Sources/Parsing/ParserPrinters/StartsWith.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
public struct StartsWith<Input: Collection>: Parser where Input.SubSequence == Input {
public let count: Int
public let possiblePrefix: AnyCollection<Input.Element>
public let originalPossiblePrefix: Any
public let startsWith: (Input) -> Bool

/// Initializes a parser that successfully returns `Void` when the initial elements of its input
Expand All @@ -57,13 +58,14 @@ public struct StartsWith<Input: Collection>: Parser where Input.SubSequence == I
where PossiblePrefix.Element == Input.Element {
self.count = possiblePrefix.count
self.possiblePrefix = AnyCollection(possiblePrefix)
self.originalPossiblePrefix = possiblePrefix
self.startsWith = { input in input.starts(with: possiblePrefix, by: areEquivalent) }
}

@inlinable
public func parse(_ input: inout Input) throws {
guard self.startsWith(input) else {
throw ParsingError.expectedInput(formatValue(self.possiblePrefix), at: input)
throw ParsingError.expectedInput(formatValue(self.originalPossiblePrefix), at: input)
}
input.removeFirst(self.count)
}
Expand Down
15 changes: 15 additions & 0 deletions Tests/ParsingTests/StartsWithTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,19 @@ final class StartsWithTests: XCTestCase {
XCTAssertNoThrow(try StartsWith("Hello".utf8).parse(&str))
XCTAssertEqual(", world!", Substring(str))
}

func testParseFailure() {
var input = "Goodnight, Blob!"[...].utf8
XCTAssertThrowsError(try StartsWith("Hello, ".utf8).parse(&input)) { error in
XCTAssertEqual(
"""
error: unexpected input
--> input:1:1
1 | Goodnight, Blob!
| ^ expected "Hello, "
""",
"\(error)"
)
}
}
}