Parse.hs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. {-# LANGUAGE OverloadedStrings #-}
  2. module Data.Adnot.Parse (decodeValue) where
  3. import Control.Applicative((<|>))
  4. import Data.Attoparsec.ByteString.Char8
  5. import Data.ByteString (ByteString)
  6. import qualified Data.ByteString.Char8 as BS
  7. import qualified Data.Map as M
  8. import qualified Data.Text as T
  9. import qualified Data.Text.Encoding as T
  10. import qualified Data.Vector as V
  11. import Data.Adnot.Type
  12. decodeValue :: ByteString -> Either String Value
  13. decodeValue = parseOnly pVal
  14. where pVal = ws *> (pSum <|> pProd <|> pList <|> pLit)
  15. pSum = Sum <$> (char '(' *> ws *> pIdent)
  16. <*> (pValueList <* ws <* char ')')
  17. pProd = Product . M.fromList
  18. <$> (char '{' *> pProdBody <* ws <* char '}')
  19. pProdBody = many' pPair
  20. pPair = (,) <$> (ws *> pIdent) <*> pVal
  21. pList = List <$> (char '[' *> pValueList <* ws <* char ']')
  22. pLit = Symbol <$> pIdent
  23. <|> String <$> pString
  24. <|> Double <$> double
  25. <|> Integer <$> decimal
  26. pValueList = V.fromList <$> many' pVal
  27. pIdent = T.pack <$>
  28. ((:) <$> (letter_ascii <|> char '_')
  29. <*> many' (letter_ascii <|> digit <|> char '_'))
  30. pString = T.decodeUtf8 . BS.pack <$> (char '"' *> manyTill pStrChar (char '"'))
  31. pStrChar = '\n' <$ string "\\n"
  32. <|> '\t' <$ string "\\t"
  33. <|> '\r' <$ string "\\r"
  34. <|> '\b' <$ string "\\b"
  35. <|> '\f' <$ string "\\f"
  36. <|> '\'' <$ string "\\'"
  37. <|> '\"' <$ string "\\\""
  38. <|> '\\' <$ string "\\\\"
  39. <|> anyChar
  40. ws = skipSpace *> ((comment *> ws) <|> return ())
  41. comment = char '#' *> manyTill anyChar (char '\n')