Common.hs 14 KB

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