1 implementation module lex
6 import System.CommandLine
9 from StdFunc import id, const
11 import Control.Applicative
13 import Control.Monad.State
14 from Data.Func import $
16 // Misschien moeten we hier continuation style van maken
17 instance toString lexerOutput where
18 toString l = "dit is een lexer output, danwel error\n"
20 lexer :: [Char] -> LexerOutput [Token]
21 lexer _ = Left "Not Implemented"
23 Start :: *World -> *World
25 # (args, w) = getCommandLine w // We lezen nu nog standaard van stdin
27 # (toparse, out) = readEntireFile out
28 # out = out <<< toString (lexer toparse)
29 # (b, w) = fclose out w
30 | not b = setReturnCode 1 w
33 readEntireFile :: *File -> *([Char], *File)
35 # (b, c, f) = freadc f
37 # (cs, f) = readEntireFile f
42 // Clean adaption of Yard, a parsec like parser combinator
43 :: Parser a = Parser ([Char] -> (LexerOutput a, [Char]))
45 runParser :: (Parser a) [Char] -> (LexerOutput a, [Char])
46 runParser (Parser p) s = p s
48 instance Functor Parser where
51 instance Applicative Parser where
52 pure a = Parser $ \s -> (Right a, s)
55 instance Monad Parser where
56 bind p f = Parser $ \s -> let (out, rest) = runParser p s in case out of
57 Left e = (Left e, rest)
58 Right t = runParser (f t) rest
60 //gives us some, many and optional
61 instance Alternative Parser where
63 (<|>) p1 p2 = parserAlternative p1 p2
64 parserAlternative p1 p2 = Parser $ \s -> let (out, rest) = runParser p1 s in case out of
65 Left e = runParser p2 s
66 Right t = (Right t, rest)
68 //parser that fails with error
69 fail :: String -> Parser a
70 fail e = Parser $ \s -> (Left e, s)
72 //parser that always fails
74 zero = fail "Zero parser"
76 //matches exactly one Char
78 item = Parser $ \s -> case s of
79 [] = (Left "Unexpected empty input", s)
80 [x:xs] = (Right x, xs)
82 //matches any char which satisfies f
83 satisfy :: (Char -> Bool) -> Parser Char
84 satisfy f = item >>= (\r -> if (f r) (return r) zero)
86 //tries a parser, if it fails returns a default value
87 optionalDef :: a (Parser a) -> Parser a
88 optionalDef def p = parserAlternative p (return def)
91 char :: Char -> Parser Char
92 char c = satisfy (\i -> c==i) //I hate that we can't do: satisfy (==c)
95 alpha = satisfy isAlpha
98 digit = satisfy isDigit
100 //matches a given String
101 string :: [Char] -> Parser [Char]
102 string s = mapM_ char s >>| return s