-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParse.hs
114 lines (102 loc) · 2.32 KB
/
Parse.hs
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
{-# LANGUAGE OverloadedStrings #-}
module Parse where
import Data.Void
import Data.Text (Text)
import qualified Data.Text as T
import Text.Megaparsec hiding (Label, label)
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as L
import Control.Monad
import Structs
type Parser = Parsec Void Text
space' :: Parser ()
space' = skipMany $ choice [void spaceChar, void $ char ',']
register :: Parser Register
register = choice
[ ACC <$ string "ACC"
, Dir LEFT <$ string "LEFT"
, Dir RIGHT <$ string "RIGHT"
, Dir UP <$ string "UP"
, Dir DOWN <$ string "DOWN" ]
operand :: Parser Operand
operand = choice
[ Imm <$> L.lexeme space L.decimal
, do
char '-'
int <- L.lexeme space L.decimal
return $ Imm (-int)
, Reg <$> register ]
instruction :: Parser Instruction
instruction = choice
[ NOP <$ string "NOP"
, do
string "MOV"
space'
src <- operand
space'
dst <- operand
return $ MOV src dst
, SWP <$ string "SWP"
, SAV <$ string "SAV"
, do
string "ADD"
space'
src <- operand
return $ ADD src
, do
string "SUB"
space'
src <- operand
return $ SUB src
, NEG <$ string "NEG"
, do
string "JMP"
space'
lbl <- label
return $ JMP lbl
, do
string "JEZ"
space'
lbl <- label
return $ JEZ lbl
, do
string "JNZ"
space'
lbl <- label
return $ JNZ lbl
, do
string "JLZ"
space'
lbl <- label
return $ JLZ lbl
, do
string "JGZ"
space'
lbl <- label
return $ JGZ lbl
, do
string "JRO"
space'
src <- operand
return $ JRO src ]
<?> "instruction"
comment :: Parser Comment
comment = do
char '#'
text <- manyTill printChar $ choice [eof, void eol]
return $ Comment (T.pack text)
label :: Parser Label
label = do
name <- some alphaNumChar
return $ Label (T.pack name)
line :: Parser Line
line = do
label <- optional $ do
lbl <- label
char ':'
return lbl
space'
instruction <- optional instruction
space'
comment <- optional comment
return $ Line label instruction comment