Common.hs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. module Data.SCargot.Common ( -- $intro
  2. -- * Identifier Syntaxes
  3. parseR5RSIdent
  4. , parseR6RSIdent
  5. , parseR7RSIdent
  6. , parseXIDIdentStrict
  7. , parseXIDIdentGeneral
  8. , parseHaskellIdent
  9. , parseHaskellVariable
  10. , parseHaskellConstructor
  11. -- * Numeric Literal Parsers
  12. , signed
  13. , prefixedNumber
  14. , signedPrefixedNumber
  15. , binNumber
  16. , signedBinNumber
  17. , octNumber
  18. , signedOctNumber
  19. , decNumber
  20. , signedDecNumber
  21. , dozNumber
  22. , signedDozNumber
  23. , hexNumber
  24. , signedHexNumber
  25. -- ** Numeric Literals for Arbitrary Bases
  26. , commonLispNumberAnyBase
  27. , gnuM4NumberAnyBase
  28. ) where
  29. #if !MIN_VERSION_base(4,8,0)
  30. import Control.Applicative hiding ((<|>), many)
  31. #endif
  32. import Control.Monad (guard)
  33. import Data.Char
  34. import Data.Text (Text)
  35. import qualified Data.Text as T
  36. import Text.Parsec
  37. import Text.Parsec.Text (Parser)
  38. -- | Parse an identifier according to the R5RS Scheme standard. This
  39. -- will not normalize case, even though the R5RS standard specifies
  40. -- that all identifiers be normalized to lower case first.
  41. --
  42. -- An R5RS identifier is, broadly speaking, alphabetic or numeric
  43. -- and may include various symbols, but no escapes.
  44. parseR5RSIdent :: Parser Text
  45. parseR5RSIdent =
  46. T.pack <$> ((:) <$> initial <*> many subsequent <|> peculiar)
  47. where initial = letter <|> oneOf "!$%&*/:<=>?^_~"
  48. subsequent = initial <|> digit <|> oneOf "+-.@"
  49. peculiar = string "+" <|> string "-" <|> string "..."
  50. hasCategory :: Char -> [GeneralCategory] -> Bool
  51. hasCategory c cs = generalCategory c `elem` cs
  52. -- | Parse an identifier according to the R6RS Scheme standard. An
  53. -- R6RS identifier may include inline hexadecimal escape sequences
  54. -- so that, for example, @foo@ is equivalent to @f\\x6f;o@, and is
  55. -- more liberal than R5RS as to which Unicode characters it may
  56. -- accept.
  57. parseR6RSIdent :: Parser Text
  58. parseR6RSIdent =
  59. T.pack <$> ((:) <$> initial <*> many subsequent <|> peculiar)
  60. where initial = constituent <|> oneOf "!$%&*/:<=>?^_~" <|> inlineHex
  61. constituent = letter
  62. <|> uniClass (\ c -> isLetter c ||
  63. isSymbol c ||
  64. hasCategory c
  65. [ NonSpacingMark
  66. , LetterNumber
  67. , OtherNumber
  68. , DashPunctuation
  69. , ConnectorPunctuation
  70. , OtherPunctuation
  71. , PrivateUse
  72. ])
  73. inlineHex = (chr . fromIntegral) <$> (string "\\x" *> hexNumber <* char ';')
  74. subsequent = initial <|> digit <|> oneOf "+-.@"
  75. <|> uniClass (\ c -> hasCategory c
  76. [ DecimalNumber
  77. , SpacingCombiningMark
  78. , EnclosingMark
  79. ])
  80. peculiar = string "+" <|> string "-" <|> string "..." <|>
  81. ((++) <$> string "->" <*> many subsequent)
  82. uniClass :: (Char -> Bool) -> Parser Char
  83. uniClass sp = satisfy (\ c -> c > '\x7f' && sp c)
  84. -- | Parse an identifier according to the R7RS Scheme standard. An
  85. -- R7RS identifier, in addition to a typical identifier format,
  86. -- can also be a chunk of text surrounded by vertical bars that
  87. -- can contain spaces and other characters. Unlike R6RS, it does
  88. -- not allow escapes to be included in identifiers unless those
  89. -- identifiers are surrounded by vertical bars.
  90. parseR7RSIdent :: Parser Text
  91. parseR7RSIdent = T.pack <$>
  92. ( (:) <$> initial <*> many subsequent
  93. <|> char '|' *> many1 symbolElement <* char '|'
  94. <|> peculiar
  95. )
  96. where initial = letter <|> specInit
  97. specInit = oneOf "!$%&*/:<=>?^_~"
  98. subsequent = initial <|> digit <|> specSubsequent
  99. specSubsequent = expSign <|> oneOf ".@"
  100. expSign = oneOf "+-"
  101. symbolElement = noneOf "\\|"
  102. <|> hexEscape
  103. <|> mnemEscape
  104. <|> ('|' <$ string "\\|")
  105. hexEscape = chr . fromIntegral <$> (string "\\x" *> hexNumber <* char ';')
  106. mnemEscape = '\a' <$ string "\\a"
  107. <|> '\b' <$ string "\\b"
  108. <|> '\t' <$ string "\\t"
  109. <|> '\n' <$ string "\\n"
  110. <|> '\r' <$ string "\\r"
  111. peculiar = (:[]) <$> expSign
  112. <|> cons2 <$> expSign <*> signSub <*> many subsequent
  113. <|> cons3 <$> expSign
  114. <*> char '.'
  115. <*> dotSub
  116. <*> many subsequent
  117. <|> cons2 <$> char '.' <*> dotSub <*> many subsequent
  118. dotSub = signSub <|> char '.'
  119. signSub = initial <|> expSign <|> char '@'
  120. cons2 a b cs = a : b : cs
  121. cons3 a b c ds = a : b : c : ds
  122. -- | Parse a Haskell variable identifier: a sequence of alphanumeric
  123. -- characters, underscores, or single quote that begins with a
  124. -- lower-case letter.
  125. parseHaskellVariable :: Parser Text
  126. parseHaskellVariable =
  127. T.pack <$> ((:) <$> small <*> many (small <|>
  128. large <|>
  129. digit' <|>
  130. char '\'' <|>
  131. char '_'))
  132. where small = satisfy isLower
  133. large = satisfy isUpper
  134. digit' = satisfy isDigit
  135. -- | Parse a Haskell constructor: a sequence of alphanumeric
  136. -- characters, underscores, or single quote that begins with an
  137. -- upper-case letter.
  138. parseHaskellConstructor :: Parser Text
  139. parseHaskellConstructor =
  140. T.pack <$> ((:) <$> large <*> many (small <|>
  141. large <|>
  142. digit' <|>
  143. char '\'' <|>
  144. char '_'))
  145. where small = satisfy isLower
  146. large = satisfy isUpper
  147. digit' = satisfy isDigit
  148. -- | Parse a Haskell identifer: a sequence of alphanumeric
  149. -- characters, underscores, or a single quote. This matches both
  150. -- variable and constructor names.
  151. parseHaskellIdent :: Parser Text
  152. parseHaskellIdent =
  153. T.pack <$> ((:) <$> (large <|> small)
  154. <*> many (small <|>
  155. large <|>
  156. digit' <|>
  157. char '\'' <|>
  158. char '_'))
  159. where small = satisfy isLower
  160. large = satisfy isUpper
  161. digit' = satisfy isDigit
  162. -- Ensure that a given character has the given Unicode category
  163. hasCat :: [GeneralCategory] -> Parser Char
  164. hasCat cats = satisfy (flip hasCategory cats)
  165. xidStart :: [GeneralCategory]
  166. xidStart = [ UppercaseLetter
  167. , LowercaseLetter
  168. , TitlecaseLetter
  169. , ModifierLetter
  170. , OtherLetter
  171. , LetterNumber
  172. ]
  173. xidContinue :: [GeneralCategory]
  174. xidContinue = xidStart ++ [ NonSpacingMark
  175. , SpacingCombiningMark
  176. , DecimalNumber
  177. , ConnectorPunctuation
  178. ]
  179. -- | Parse an identifier of unicode characters of the form
  180. -- @<XID_Start> <XID_Continue>*@, which corresponds strongly
  181. -- to the identifiers found in most C-like languages. Note that
  182. -- the @XID_Start@ category does not include the underscore,
  183. -- so @__foo@ is not a valid XID identifier. To parse
  184. -- identifiers that may include leading underscores, use
  185. -- 'parseXIDIdentGeneral'.
  186. parseXIDIdentStrict :: Parser Text
  187. parseXIDIdentStrict = T.pack <$> ((:) <$> hasCat xidStart
  188. <*> many (hasCat xidContinue))
  189. -- | Parse an identifier of unicode characters of the form
  190. -- @(<XID_Start> | '_') <XID_Continue>*@, which corresponds
  191. -- strongly to the identifiers found in most C-like languages.
  192. -- Unlike 'parseXIDIdentStrict', this will also accept an
  193. -- underscore as leading character, which corresponds more
  194. -- closely to programming languages like C and Java, but
  195. -- deviates somewhat from the
  196. -- <http://unicode.org/reports/tr31/ Unicode Identifier and
  197. -- Pattern Syntax standard>.
  198. parseXIDIdentGeneral :: Parser Text
  199. parseXIDIdentGeneral = T.pack <$> ((:) <$> (hasCat xidStart <|> char '_')
  200. <*> many (hasCat xidContinue))
  201. -- | A helper function for defining parsers for arbitrary-base integers.
  202. -- The first argument will be the base, and the second will be the
  203. -- parser for the individual digits.
  204. number :: Integer -> Parser Char -> Parser Integer
  205. number base digits = foldl go 0 <$> many1 digits
  206. where go x d = base * x + toInteger (value d)
  207. value c
  208. | c >= 'a' && c <= 'z' = 0xa + (fromEnum c - fromEnum 'a')
  209. | c >= 'A' && c <= 'Z' = 0xa + (fromEnum c - fromEnum 'A')
  210. | c >= '0' && c <= '9' = fromEnum c - fromEnum '0'
  211. | c == '\x218a' = 0xa
  212. | c == '\x218b' = 0xb
  213. | otherwise = error ("Unknown letter in number: " ++ show c)
  214. digitsFor :: Int -> [Char]
  215. digitsFor n
  216. | n <= 10 = take n ['0'..'9']
  217. | n <= 36 = take (n-10) ['A'..'Z'] ++ take (n-10) ['a'..'z'] ++ ['0'..'9']
  218. | otherwise = error ("Invalid base for parser: " ++ show n)
  219. anyBase :: Integer -> Parser Integer
  220. anyBase n = number n (oneOf (digitsFor (fromIntegral n)))
  221. -- | A parser for Common Lisp's arbitrary-base number syntax, of
  222. -- the form @#[base]r[number]@, where the base is given in
  223. -- decimal. Note that this syntax begins with a @#@, which
  224. -- means it might conflict with defined reader macros.
  225. commonLispNumberAnyBase :: Parser Integer
  226. commonLispNumberAnyBase = do
  227. _ <- char '#'
  228. n <- decNumber
  229. guard (n >= 2 && n <= 36)
  230. _ <- char 'r'
  231. signed (anyBase n)
  232. -- | A parser for GNU m4's arbitrary-base number syntax, of
  233. -- the form @0r[base]:[number]@, where the base is given in
  234. -- decimal.
  235. gnuM4NumberAnyBase :: Parser Integer
  236. gnuM4NumberAnyBase = do
  237. _ <- string "0r"
  238. n <- decNumber
  239. guard (n >= 2 && n <= 36)
  240. _ <- char ':'
  241. signed (anyBase n)
  242. sign :: Num a => Parser (a -> a)
  243. sign = (pure id <* char '+')
  244. <|> (pure negate <* char '-')
  245. <|> pure id
  246. -- | Given a parser for some kind of numeric literal, this will attempt to
  247. -- parse a leading @+@ or a leading @-@ followed by the numeric literal,
  248. -- and if a @-@ is found, negate that literal.
  249. signed :: Num a => Parser a -> Parser a
  250. signed p = ($) <$> sign <*> p
  251. -- | Parses a number in the same way as 'prefixedNumber', with an optional
  252. -- leading @+@ or @-@.
  253. signedPrefixedNumber :: Parser Integer
  254. signedPrefixedNumber = signed prefixedNumber
  255. -- | Parses a number, determining which numeric base to use by examining
  256. -- the literal's prefix: @0x@ for a hexadecimal number, @0z@ for a
  257. -- dozenal number, @0o@ for an octal number, and @0b@ for a binary
  258. -- number (as well as the upper-case versions of the same.) If the
  259. -- base is omitted entirely, then it is treated as a decimal number.
  260. prefixedNumber :: Parser Integer
  261. prefixedNumber = (string "0x" <|> string "0X") *> hexNumber
  262. <|> (string "0o" <|> string "0O") *> octNumber
  263. <|> (string "0z" <|> string "0Z") *> dozNumber
  264. <|> (string "0b" <|> string "0B") *> binNumber
  265. <|> decNumber
  266. -- | A parser for non-signed binary numbers
  267. binNumber :: Parser Integer
  268. binNumber = number 2 (char '0' <|> char '1')
  269. -- | A parser for signed binary numbers, with an optional leading @+@ or @-@.
  270. signedBinNumber :: Parser Integer
  271. signedBinNumber = signed binNumber
  272. -- | A parser for non-signed octal numbers
  273. octNumber :: Parser Integer
  274. octNumber = number 8 (oneOf "01234567")
  275. -- | A parser for signed octal numbers, with an optional leading @+@ or @-@.
  276. signedOctNumber :: Parser Integer
  277. signedOctNumber = ($) <$> sign <*> octNumber
  278. -- | A parser for non-signed decimal numbers
  279. decNumber :: Parser Integer
  280. decNumber = number 10 digit
  281. -- | A parser for signed decimal numbers, with an optional leading @+@ or @-@.
  282. signedDecNumber :: Parser Integer
  283. signedDecNumber = ($) <$> sign <*> decNumber
  284. dozDigit :: Parser Char
  285. dozDigit = digit <|> oneOf "AaBb\x218a\x218b"
  286. -- | A parser for non-signed duodecimal (dozenal) numbers. This understands both
  287. -- the ASCII characters @'a'@ and @'b'@ and the Unicode characters @'\x218a'@ (↊)
  288. -- and @'\x218b'@ (↋) as digits with the decimal values @10@ and @11@
  289. -- respectively.
  290. dozNumber :: Parser Integer
  291. dozNumber = number 12 dozDigit
  292. -- | A parser for signed duodecimal (dozenal) numbers, with an optional leading @+@ or @-@.
  293. signedDozNumber :: Parser Integer
  294. signedDozNumber = ($) <$> sign <*> dozNumber
  295. -- | A parser for non-signed hexadecimal numbers
  296. hexNumber :: Parser Integer
  297. hexNumber = number 16 hexDigit
  298. -- | A parser for signed hexadecimal numbers, with an optional leading @+@ or @-@.
  299. signedHexNumber :: Parser Integer
  300. signedHexNumber = ($) <$> sign <*> hexNumber
  301. {- $intro
  302. This module contains a selection of parsers for different kinds of
  303. identifiers and literals, from which more elaborate parsers can be
  304. assembled. These can afford the user a quick way of building parsers
  305. for different atom types.
  306. -}