[Haskell-cafe] parsec: how to get end location

Roman Cheplyaka roma at ro-che.info
Sun Jun 13 18:10:59 EDT 2010

* Antoine Latter <aslatter at gmail.com> [2010-06-13 16:47:28-0500]
> On Sun, Jun 13, 2010 at 4:17 PM, Roman Cheplyaka <roma at ro-che.info> wrote:
> > Suppose I have some parser 'p'. I want to parse it as well as get its
> > span in the text. So I could write
> >
> > \begin{code]
> > pWithLocation = do
> >  loc_start <- getPosition
> >  pval <- p
> >  loc_end <- getPosition
> >  return (pval,loc_start,loc_end)
> > \end{code}
> >
> > except that loc_end gives me the location _after_ 'p'. In case when 'p'
> > has consumed trailing newline I see no way to recover the end location
> > of 'p' (it is the last column of the previous line).
> >
> > So, can I do anything with this without patching parsec?
> >
> > I use parsec3 if it matters.
> >
> Can you use a parser which doesn't consume leading/trailing whitespace?
> Or somehow layer the parsers so that the whitepsace munching happens
> outside of parseWithLocation.

Of course most parsers don't consume trailing newlines. But I was
writing general function to use in many places in the code which would
recover the end location. In most cases it just subtracts 1 from the
column number, but what if it just happened so that column number is 1?

So I got an impression that this way of obtaining the end location is at
least ugly. It would be better if there was a function

  parseWithLocation :: Parser a -> Parser (a, SourcePos, SourcePos)

which, I guess, is easy to implement within Parsec without any such

Roman I. Cheplyaka :: http://ro-che.info/
"Don't let school get in the way of your education." - Mark Twain

More information about the Haskell-Cafe mailing list