/Comb

Comb is a parser combinator library for Haskell.

Primary LanguageHaskellGNU Affero General Public License v3.0AGPL-3.0

Comb

Comb

A parser combinator library.

See the Haddock documentation for information about the various parsers.

Example

The following program defines a parser (expr1) that parses arithmetic expressions, such as 1 + 2 * 3^4 / 3 - 5, and evaluates them to an Int.

import Comb

expr1 =
  chainl expr2
    (  (+) <$ symbol '+'
   <|> (-) <$ symbol '-')
expr2 =
  chainl expr3
    (  (*) <$ symbol '*'
   <|> div <$ symbol '/')
expr3 = chainr expr4 ((^) <$ symbol '^')
expr4 = many space *> (parenthesised expr1 <|> int) <* many space

result1 = runParser expr1 "9 + 5 * 3^2" :: Maybe (Int, String)
-- >>> Just (54, "")

To keep track of the current position in the file, you can use WithPosition:

result2 = runParser expr1 (Positioned positionBegin "9 + 5 * 3^2") :: Maybe (Int, Positioned String)
-- >>> Just (54, Positioned { position = Position { line = 1, column = 12, file = Nothing }, stream = "" })

When using a Functor different from Maybe, Positioned can be used to create better error messages.

Design improvements

To improve error handling, empty (of Alternative) could be replaced by more specialised error values. For example:

class Applicative f => ParserAlternative f where
  eof :: f a -- error value when the end of file is reached
  -- some function when there is no character match
  -- etc.

Licence

Copyright (C) 2019 Splinter Suidman

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

A copy of the GNU Affero General Public License is included in the file LICENSE.