Basic.hs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. {-# LANGUAGE OverloadedStrings #-}
  2. module Data.SCargot.Language.Basic
  3. ( -- * Spec
  4. -- $descr
  5. basicParser
  6. , basicPrinter
  7. ) where
  8. import Control.Applicative ((<$>))
  9. import Data.Char (isAlphaNum)
  10. import Text.Parsec (many1, satisfy)
  11. import Data.Text (Text, pack)
  12. import Data.SCargot.Repr.Basic (SExpr)
  13. import Data.SCargot ( SExprParser
  14. , SExprPrinter
  15. , mkParser
  16. , flatPrint
  17. )
  18. isAtomChar :: Char -> Bool
  19. isAtomChar c = isAlphaNum c
  20. || c == '-' || c == '*' || c == '/'
  21. || c == '+' || c == '<' || c == '>'
  22. || c == '=' || c == '!' || c == '?'
  23. -- $descr
  24. -- The 'basicSpec' describes S-expressions whose atoms are simply
  25. -- text strings that contain alphanumeric characters and a small
  26. -- set of punctuation. It does no parsing of numbers or other data
  27. -- types, and will accept tokens that typical Lisp implementations
  28. -- would find nonsensical (like @77foo@).
  29. --
  30. -- Atoms recognized by the 'basicSpec' are any string matching the
  31. -- regular expression @[A-Za-z0-9+*<>/=!?-]+@.
  32. -- | A 'SExprParser' that understands atoms to be sequences of
  33. -- alphanumeric characters as well as the punctuation
  34. -- characters @[-*/+<>=!?]@, and does no processing of them.
  35. --
  36. -- >>> decode basicParser "(1 elephant)"
  37. -- Right [SCons (SAtom "1") (SCons (SAtom "elephant") SNil)]
  38. basicParser :: SExprParser Text (SExpr Text)
  39. basicParser = mkParser pToken
  40. where pToken = pack <$> many1 (satisfy isAtomChar)
  41. -- | A 'SExprPrinter' that prints textual atoms directly (without quoting
  42. -- or any other processing) onto a single line.
  43. --
  44. -- >>> encode basicPrinter [L [A "1", A "elephant"]]
  45. -- "(1 elephant)"
  46. basicPrinter :: SExprPrinter Text (SExpr Text)
  47. basicPrinter = flatPrint id