Parse.hs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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.Map as M
  7. import qualified Data.Text as T
  8. import qualified Data.Vector as V
  9. import Data.Adnot.Type
  10. decodeValue :: ByteString -> Either String Value
  11. decodeValue = parseOnly pVal
  12. where pVal = ws *> (pSum <|> pProd <|> pList <|> pLit)
  13. pSum = Sum <$> (char '(' *> ws *> (pIdent <|> pString))
  14. <*> (pValueList <* (ws *> char ')'))
  15. pProd = Product . M.fromList
  16. <$> (char '{' *> pProdBody <* ws <* char '}')
  17. pProdBody = many' pPair
  18. pPair = (,) <$> (ws *> (pIdent <|> pString)) <*> pVal
  19. pList = List <$> (char '[' *> pValueList <* ws <* char ']')
  20. pLit = String <$> pIdent
  21. <|> String <$> pString
  22. <|> Integer <$> decimal
  23. pStr = String <$> (pIdent <|> pString)
  24. pValueList = V.fromList <$> many' pVal
  25. pIdent = T.pack <$>
  26. ((:) <$> (letter_ascii <|> char '_')
  27. <*> many' (letter_ascii <|> digit <|> char '_'))
  28. pString = T.pack <$> (char '"' *> manyTill pStrChar (char '"'))
  29. pStrChar = '\n' <$ string "\\n"
  30. <|> '\t' <$ string "\\t"
  31. <|> '\r' <$ string "\\r"
  32. <|> '\b' <$ string "\\b"
  33. <|> '\f' <$ string "\\f"
  34. <|> '\'' <$ string "\\'"
  35. <|> '\"' <$ string "\\\""
  36. <|> '\\' <$ string "\\\\"
  37. <|> anyChar
  38. ws = skipSpace *> ((comment *> ws) <|> return ())
  39. comment = char '#' *> manyTill anyChar (char '\n')