zevv / npeg

PEGs for Nim, another take
MIT License
329 stars 22 forks source link

Captures only work when input is consumed #17

Closed sealmove closed 4 years ago

sealmove commented 4 years ago

I think this behavior is somewhat surprising.

let p = peg o:
  o <- >&1:
    echo len($1)

doAssert p.match("a").ok
0

Possible solutions:

zevv commented 4 years ago

True, will document. Try instead:

let p = peg o:
  o <- &>1:
    echo len($1)

-- :wq ^X^Cy^K^X^C^C^C^C

sealmove commented 4 years ago

Unfortunately you snippet fails with:

Error: unhandled exception: Capture out of range, 1 is not in [0..0] [NPegException]
zevv commented 4 years ago

Sure, it needs this instead:

let p = peg o:
  o <- &p   
  p <- >1:
    echo len($1)

The reason is that & can have no side effects and internally restores the match state and all its captures to the state it was before. I'll add this to the documentation, thanks for reporting!