Skip to content

Get range of parsed input #69

Answered by stephencelis
dehlen asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @dehlen,

One way to capture the range of a parsed result is by introducing a new operator that captures it. Here's something @mbrandonw and I sketched out:

extension Parser where Input: Collection {
  func withRange() -> AnyParser<Input, (output: Output, range: Range<Input.Index>)> {
    .init { input in
      let startIndex = input.startIndex
      guard let output = self.parse(&input)
      else { return nil }
      let endIndex = input.startIndex
      return (output, startIndex ..< endIndex)
    }
  }
}

With that defined, you can get the range from Int.parser() by tacking on withRange():

let parser = Int.parser().withRange()
let input = "123 Hello"[...].utf8
let (output, range) = p…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@dehlen
Comment options

Answer selected by dehlen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #68 on November 29, 2021 14:50.