blob: 1669bcd72bf05e7977cf7de198c90b210fa637d7 (
plain) (
blame)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
module Parser where
import Data.Functor.Identity
import Helper
import Text.Parsec
import Text.Parsec.Language
import qualified Text.Parsec.Token as Token
languageDef :: GenLanguageDef String u Identity
languageDef = emptyDef { Token.commentLine = "#"
, Token.identStart = letter
, Token.identLetter = alphaNum <|> char '?'
, Token.reservedOpNames = ["[", "]", "="]
}
type Parser = Parsec String ()
lexer :: Token.GenTokenParser String u Identity
lexer = Token.makeTokenParser languageDef
identifier :: Parser String
identifier = Token.identifier lexer
reservedOp :: String -> Parser ()
reservedOp = Token.reservedOp lexer
parens :: Parser a -> Parser a
parens = Token.parens lexer
almostAnything :: Parser String
almostAnything =
many1 $ oneOf ".`#~@$%^&*_+-=|;',/?[]<>(){} " <|> letter <|> digit
parseAbstraction :: Parser Expression
parseAbstraction = do
reservedOp "["
exp <- parseExpression
reservedOp "]"
pure $ Abstraction exp
parseApplication :: Parser Expression
parseApplication = do
s <- sepBy1 parseSingleton spaces
pure $ foldl1 Application s
parseBruijn :: Parser Expression
parseBruijn = do
idx <- digit
spaces
pure $ Bruijn $ (read . pure) idx
parseVariable :: Parser Expression
parseVariable = do
var <- identifier
spaces
pure $ Variable var
parseSingleton :: Parser Expression
parseSingleton =
parseBruijn <|> parseAbstraction <|> parens parseApplication <|> parseVariable
parseExpression :: Parser Expression
parseExpression = do
spaces
expr <- parseApplication <|> parseSingleton
spaces
pure expr
parseEvaluate :: Parser Instruction
parseEvaluate = Evaluate <$> parseExpression
parseDefine :: Parser Instruction
parseDefine = do
var <- identifier
spaces
Define var <$> parseExpression
parseReplDefine :: Parser Instruction
parseReplDefine = do
var <- identifier
spaces
reservedOp "="
spaces
Define var <$> parseExpression
parseComment :: Parser Instruction
parseComment = string "#" >> Comment <$> almostAnything
parseLoad :: Parser Instruction
parseLoad = string ":load " >> Load <$> almostAnything
parseLine :: Parser Instruction
parseLine = try parseDefine <|> parseComment
parseReplLine :: Parser Instruction
parseReplLine =
try parseReplDefine <|> parseComment <|> parseEvaluate <|> parseLoad
|