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

Add Indexed parser #366

Open
wants to merge 1 commit 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
31 changes: 31 additions & 0 deletions Sources/Parsing/ParserPrinters/Indexed.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
extension Parsers {
/// A parser of a collection that returns a base parser's output as well as the index range of the
/// parsed input.
public struct Indexed<Base>: Parser
where Base: Parser, Base.Input: Collection {
public let base: Base

@inlinable
init(_ base: Base) {
self.base = base
}

@inlinable
public func parse(
_ input: inout Base.Input
) throws -> (output: Base.Output, indices: Range<Base.Input.Index>) {
let startIndex = input.startIndex
let output = try base.parse(&input)
return (output, startIndex..<input.startIndex)
}
}
}

extension Parser where Input: Collection {
/// A parser of a collection that returns a base parser's output as well as the index range of the
/// parsed input.
@inlinable
public func indexed() -> Parsers.Indexed<Self> {
Parsers.Indexed(self)
}
}
46 changes: 46 additions & 0 deletions Tests/ParsingTests/IndexedTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import Parsing
import XCTest

private struct Output: Equatable {
var username: Substring
var range: Range<String.Index>
}

final class IndexedTests: XCTestCase {
func testStringHappyPath() throws {
let input = "Hi @BlobJr; please call @BlobSr when you get a chance. Thanks."
let parser: some Parser<Substring.UTF8View, [Output]> = Many {
Skip {
PrefixUpTo("@".utf8)
}

From(.substring) {
Parse {
"@"

Prefix(while: { $0.isLetter || $0.isNumber })
}
.indexed()
}
.map(Output.init)
} terminator: {
Rest()
}
let usernames = try parser.parse(input)
XCTAssertEqual(
usernames,
[
Output(
username: "BlobJr",
range: input
.index(input.startIndex, offsetBy: 3)..<input.index(input.startIndex, offsetBy: 10)
),
Output(
username: "BlobSr",
range: input
.index(input.startIndex, offsetBy: 24)..<input.index(input.startIndex, offsetBy: 31)
)
]
)
}
}