less prototype, less bad code implementation of CCHM type theory
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.5 KiB

  1. {
  2. module Presyntax.Lexer where
  3. import qualified Data.ByteString.Lazy as Lbs
  4. import qualified Data.Text.Encoding as T
  5. import Presyntax.Tokens
  6. }
  7. %wrapper "monadUserState-bytestring"
  8. $alpha = [a-zA-Z]
  9. $digit = [0-9]
  10. $white_nol = $white # \n
  11. tokens :-
  12. $white_nol+ ;
  13. -- zero state: normal lexing
  14. <0> $alpha [$alpha $digit \_ \']* { yield TokVar }
  15. <0> \= { always TokEqual }
  16. <0> \: { always TokColon }
  17. <0> \, { always TokComma }
  18. <0> \* { always TokStar }
  19. <0> ".1" { always TokPi1 }
  20. <0> ".2" { always TokPi2 }
  21. <0> \\ { always TokLambda }
  22. <0> "->" { always TokArrow }
  23. <0> \( { always TokOParen }
  24. <0> \{ { always TokOBrace }
  25. <0> \) { always TokCParen }
  26. <0> \} { always TokCBrace }
  27. <0> \; { always TokSemi }
  28. <0> \n { begin newline }
  29. -- newline: emit a semicolon when de-denting
  30. <newline> {
  31. \n ;
  32. () { offsideRule }
  33. }
  34. {
  35. alexEOF :: Alex Token
  36. alexEOF = do
  37. (AlexPn _ l c, _, _, _) <- alexGetInput
  38. pure $ Token TokEof l c
  39. yield k (AlexPn _ l c, _, s, _) i = pure (Token (k $! (T.decodeUtf8 (Lbs.toStrict (Lbs.take i s)))) l c)
  40. always k x i = yield (const k) x i
  41. data AlexUserState = AlexUserState { layoutColumns :: [Int], startCodes :: [Int] }
  42. alexInitUserState = AlexUserState [1] []
  43. just :: Alex a -> AlexAction Token
  44. just k _ _ = k *> alexMonadScan
  45. getUserState :: Alex AlexUserState
  46. getUserState = Alex $ \s -> Right (s, alex_ust s)
  47. mapUserState :: (AlexUserState -> AlexUserState) -> Alex ()
  48. mapUserState k = Alex $ \s -> Right (s { alex_ust = k $! alex_ust s }, ())
  49. pushStartCode :: Int -> Alex ()
  50. pushStartCode c = do
  51. sc <- alexGetStartCode
  52. mapUserState $ \s -> s { startCodes = sc:startCodes s }
  53. alexSetStartCode c
  54. popStartCode :: Alex ()
  55. popStartCode = do
  56. sc <- startCodes <$> getUserState
  57. case sc of
  58. [] -> alexSetStartCode 0
  59. (x:xs) -> do
  60. mapUserState $ \s -> s { startCodes = xs }
  61. alexSetStartCode x
  62. offsideRule :: AlexInput -> Int64 -> Alex Token
  63. offsideRule i@(AlexPn p line col, _, s, _) l = do
  64. ~(col':_) <- layoutColumns <$> getUserState
  65. case col `compare` col' of
  66. EQ -> do
  67. popStartCode
  68. pure (Token TokSemi line col)
  69. GT -> do
  70. popStartCode
  71. alexMonadScan
  72. LT -> alexError "wrong ass indentation"
  73. }