aboutsummaryrefslogtreecommitdiff
path: root/src/Lexer.hs
blob: 848a892b1398854c4995bc73765302c8429ae8b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
module Lexer where

import Data.Char (digitToInt)
import Text.Parsec
import Text.Parsec.Language (emptyDef)
import Text.Parsec.String (Parser)
import qualified Text.Parsec.Token as T

scanner :: T.TokenParser ()
scanner = T.makeTokenParser style
  where
    ops = ["+", "*", "-", ";"]
    names = ["module", "private", "def", "return", "->"]
    style =
      emptyDef
        { T.commentLine = "//",
          T.reservedOpNames = ops,
          T.reservedNames = names
        }

binNum :: Parser Integer
binNum = do
  _ <- char '0'
  _ <- oneOf "bB"
  digits <- many1 $ oneOf "01"
  let n = foldl (\x d -> 2 * x + toInteger (digitToInt d)) 0 digits
  seq n $ return n

integer :: Parser Integer
integer = binNum <|> T.integer scanner

parens :: Parser a -> Parser a
parens = T.parens scanner

braces :: Parser a -> Parser a
braces = T.braces scanner

commaSep :: Parser a -> Parser [a]
commaSep = T.commaSep scanner

colonSep :: Parser String
colonSep = T.colon scanner

identifier :: Parser String
identifier = T.identifier scanner

reserved :: String -> Parser ()
reserved = T.reserved scanner

reservedOp :: String -> Parser ()
reservedOp = T.reservedOp scanner

scan :: Parser a -> Parser a
scan p = do
  T.whiteSpace scanner
  r <- p
  eof
  return r