Advertisement
Guest User

Untitled

a guest
Feb 14th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. {-# Language TemplateHaskell, QuasiQuotes, FlexibleContexts #-}
  2.  
  3. module Parse (LVal, grammar) where
  4.  
  5. import Text.ParserCombinators.Parsec hiding (many)
  6. import Control.Applicative hiding (optional, (<|>))
  7.  
  8. data LVal =
  9. Var (LVal, LVal)
  10. | Varname String
  11. | Pair (LVal, LVal)
  12. | Lambda (String, LVal)
  13. | Number Integer
  14. | Apply (LVal, LVal)
  15. | Comment
  16. deriving (Show)
  17.  
  18. grammar = stat
  19.  
  20. stat :: Parser LVal
  21. stat =
  22. comment <//>
  23. var <//>
  24. apply
  25.  
  26. comment :: Parser LVal
  27. comment = (\_ -> Comment) <$>
  28. (string "--" *> (many (noneOf ['\n'])))
  29.  
  30. -- foo = bar
  31. -- [[name]] = (apply | expr)
  32. var :: Parser LVal
  33. var = (\v e -> Var (v, e)) <$>
  34. name <*>
  35. (spaceP *> char '=' *> spaceP *> (apply <//> expr))
  36.  
  37. -- fn expr
  38. -- [[name]] (name | expr)+
  39. apply :: Parser LVal
  40. apply = (\s e -> Apply (s, e)) <$>
  41. fun <*> (spaceP *> (apply <//> fun <//> expr))
  42.  
  43. -- [[number]], pair, lambda, name
  44. expr :: Parser LVal
  45. expr = nums <//>
  46. pair <//>
  47. lambda <//>
  48. name
  49.  
  50. -- \x x
  51. -- '\'[[name]] (apply | expr)
  52. lambda :: Parser LVal
  53. lambda = (\a e -> Lambda (a, e)) <$>
  54. ((char '\\' *> spaceP) *> strP) <*> (spaceP *> (expr <//> apply) <* spaceP)
  55.  
  56. -- <3, 5>
  57. -- '<' expr ',' expr '>'
  58. pair :: Parser LVal
  59. pair = (\e1 e2 -> Pair (e1, e2)) <$>
  60. ((char '<' *> spaceP) *> (expr <//> apply)) <*> ((spaceP *> char ',' *> spaceP) *> (expr <//> apply) <* (spaceP <* char '>' <* spaceP))
  61.  
  62. -- [[name]]
  63. name :: Parser LVal
  64. name = sToLv strP
  65.  
  66. fun :: Parser LVal
  67. fun = (brac lambda) <//>
  68. name <//>
  69. (sToLv arithP) <//>
  70. (brac apply)
  71.  
  72. -- [[number]]
  73. nums :: Parser LVal
  74. nums = (\n -> Number $
  75. read n) <$> (many1 $ oneOf ['0' .. '9'])
  76.  
  77. strP :: Parser String
  78. strP = many1 $ oneOf $ ('_':['a' .. 'z']) ++ ['A' .. 'Z']
  79.  
  80. arithP :: Parser String
  81. arithP = many1 $ oneOf "+-*/"
  82.  
  83. spaceP :: Parser String
  84. spaceP = many $ oneOf " \t\n"
  85.  
  86. sToLv e = (\s -> Varname s) <$>
  87. (spaceP *> e <* spaceP)
  88.  
  89. brac e = char '(' *> spaceP *> e <* spaceP <* char ')'
  90.  
  91. p <//> q = (try p) <|> q
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement