Skip to content

Instantly share code, notes, and snippets.

@cs
Last active October 6, 2015 21:58
Show Gist options
  • Save cs/3059280 to your computer and use it in GitHub Desktop.
Save cs/3059280 to your computer and use it in GitHub Desktop.
module Text.Parsec.Custom (many1Till) where
import Control.Monad
import Text.Parsec.Prim
import Text.Parsec.Combinator
many1Till :: (Stream s m t, Show end) => ParsecT s u m a -> ParsecT s u m end -> ParsecT s u m [a]
many1Till p end = do
notFollowedBy end
first <- p
rest <- manyTill p end
return (first:rest)
module Text.Parsec.CustomTest (allParsecCustomTests) where
import Text.Parsec
import Text.Parsec.Error
import Text.Parsec.Char
import Text.Parsec.Prim
import Text.Parsec.Combinator
import Text.Parsec.Custom
import Test.HUnit
-- modify the parser to ensure that the entire input string has been processed:
quickParse p input = let p' = do { r <- p ; eof ; return r } in
parse p' "<< anonymous >>" input
getRight :: Either a b -> Maybe b
getRight (Right b) = Just b
getRight (Left _) = Nothing
allParsecCustomTests = TestList [
TestLabel "empty" emptyTest,
simpleCharWithNoMatch,
simpleCharWithOneMatch,
simpleCharWithTwoMatches,
complexWithTry,
complexWithTryAndLookAhead
]
emptyTest = expected ~=? actual
where
expected = Nothing
actual = let p = many1Till anyChar (char '.') in
getRight $ quickParse p ""
simpleCharWithNoMatch = expected ~=? actual
where
expected = Nothing
actual = let p = many1Till (char 'a') (char 'b') in
getRight $ quickParse p "b"
simpleCharWithOneMatch = expected ~=? actual
where
expected = Just "a"
actual = let p = many1Till (char 'a') (char 'b') in
getRight $ quickParse p "ab"
simpleCharWithTwoMatches = expected ~=? actual
where
expected = Just "aa"
actual = let p = many1Till (char 'a') (char 'b') in
getRight $ quickParse p "aab"
complexWithTry = expected ~=? actual
where
expected = Just "foo"
actual = let p = do { f <- many1Till (anyChar) (try $ string "end") ; return f } in
getRight $ quickParse p "fooend"
complexWithTryAndLookAhead = expected ~=? actual
where
expected = Just "foo"
actual = let p = do { f <- many1Till (anyChar) (lookAhead $ try $ string "end") ; string "end" ; return f } in
getRight $ quickParse p "fooend"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment