aboutsummaryrefslogtreecommitdiff
path: root/ProgramParser.hs
blob: a25de6ebc5bae0006d9c3764ca2ce2752f149aa0 (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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
{-# LANGUAGE TupleSections #-}

module ProgramParser(parseProgram) where

import Control.Monad
import Data.Char
import Data.Maybe
import Text.Parsec
import qualified Text.Parsec.Expr as E

import AST
import Defs


type Parser = Parsec String ()


parseProgram :: String -> Either String Program
parseProgram s = case parse pProgram "" s of
    Left err -> Left $ show err
    Right p -> Right p

pProgram :: Parser Program
pProgram = between pWhiteComment eof go
  where
    go :: Parser Program
    go = (pDTypedef >>= \d -> addTypedef d <$> go) <|>
         (pDFunc >>= \d -> addFunc d <$> go) <|>
         (pDVar >>= \d -> addVar d <$> go) <|>
         return (Program [] [] [])

    addTypedef d (Program a b c) = Program (d:a) b c
    addVar d (Program a b c) = Program a (d:b) c
    addFunc d (Program a b c) = Program a b (d:c)

pDTypedef :: Parser DTypedef
pDTypedef = do
    symbol "type"
    n <- pName
    symbol ":="
    t <- pType
    symbol ";"
    return $ DTypedef n t

pDFunc :: Parser DFunc
pDFunc = do
    symbol "func"
    (rt,n) <- (try $ pType >>= \t -> (Just t,) <$> pName) <|>
              ((Nothing,) <$> pName)
    symbol "("
    args <- sepBy pTypeAndName (symbol ",")
    symbol ")"
    body <- pBlock
    return $ DFunc rt n args body

pDVar :: Parser DVar
pDVar = do
    (t,n) <- try pTypeAndName
    symbol ":="
    e <- pExpression
    symbol ";"
    return $ DVar t n e

pTypeAndName :: Parser (Type, Name)
pTypeAndName = (,) <$> pType <*> pName

pType :: Parser Type
pType = (flip label "type") $
    pStruct <|> do
        t <- pBasicType
        (do
            symbol "["
            msz <- optionMaybe pInteger
            symbol "]"
            return $ TArr t msz) <|> return t

pStruct :: Parser Type
pStruct = do
    symbol "struct"
    symbol "{"
    ms <- many $ pTypeAndName <* symbol ";"
    symbol "}"
    return $ TStruct ms

pBasicType :: Parser Type
pBasicType = (symbol "int" >> return TInt) <|>
             (symbol "char" >> return TChar) <|>
             (TName <$> pName)

pBlock :: Parser Block
pBlock = do
    symbol "{"
    body <- many pStatement
    symbol "}"
    return $ Block body

pStatement :: Parser Statement
pStatement = pSIf <|> pSWhile <|> pSReturn <|> pSBreak <|> pSDebugger <|> pSDecl <|> pSAs <|> pSExpr

pSDecl :: Parser Statement
pSDecl = do
    (t, n) <- try $ do
        t <- pType
        n <- pName
        symbol ":="
        return (t, n)
    e <- pExpression
    symbol ";"
    return $ SDecl t n e

pSAs :: Parser Statement
pSAs = do
    n <- try $ pAsExpression <* symbol "="
    e <- pExpression
    symbol ";"
    return $ SAs n e

pSIf :: Parser Statement
pSIf = do
    symbol "if"
    symbol "("
    cond <- pExpression
    symbol ")"
    bl1 <- pBlock
    bl2 <- try (symbol "else" >> pBlock) <|> return (Block [])
    return $ SIf cond bl1 bl2

pSWhile :: Parser Statement
pSWhile = do
    symbol "while"
    symbol "("
    cond <- pExpression
    symbol ")"
    bl <- pBlock
    return $ SWhile cond bl

pSReturn :: Parser Statement
pSReturn = do
    symbol "return"
    m <- optionMaybe pExpression
    symbol ";"
    return $ SReturn m

pSBreak :: Parser Statement
pSBreak = do
    symbol "break"
    m <- optionMaybe pIntegerInt
    symbol ";"
    return $ SBreak (fromMaybe 0 m)

pSDebugger :: Parser Statement
pSDebugger = symbol "debugger" >> symbol ";" >> return SDebugger

pSExpr :: Parser Statement
pSExpr = do
    e <- pExpression
    symbol ";"
    return $ SExpr e

pExpression :: Parser Expression
pExpression = E.buildExpressionParser optable litparser <?> "expression"
  where
    optable =
        [[E.Infix (symbol "**" >> return (mkEBin BOPow)) E.AssocRight],
         [E.Infix (symbol "*" >> return (mkEBin BOMul)) E.AssocLeft,
          E.Infix (symbol "/" >> return (mkEBin BODiv)) E.AssocLeft,
          E.Infix (symbol "%" >> return (mkEBin BOMod)) E.AssocLeft],
         [E.Infix (symbol "^" >> return (mkEBin BOBitXor)) E.AssocLeft],
         [E.Infix (symbol "&" >> return (mkEBin BOBitAnd)) E.AssocLeft],
         [E.Infix (symbol "|" >> return (mkEBin BOBitOr)) E.AssocLeft],
         [E.Infix (symbol "+" >> return (mkEBin BOAdd)) E.AssocLeft,
          E.Infix (symbol "-" >> return (mkEBin BOSub)) E.AssocLeft],
         [E.Infix (symbol ">=" >> return (mkEBin BOGeq)) E.AssocNone,
          E.Infix (symbol "<=" >> return (mkEBin BOLeq)) E.AssocNone,
          E.Infix (symbol ">" >> return (mkEBin BOGt)) E.AssocNone,
          E.Infix (symbol "<" >> return (mkEBin BOLt)) E.AssocNone,
          E.Infix (symbol "==" >> return (mkEBin BOEq)) E.AssocNone,
          E.Infix (symbol "!=" >> return (mkEBin BONeq)) E.AssocNone],
         [E.Infix (symbol "&&" >> return (mkEBin BOAnd)) E.AssocLeft],
         [E.Infix (symbol "||" >> return (mkEBin BOOr)) E.AssocLeft]]

    mkEBin :: BinaryOp -> Expression -> Expression -> Expression
    mkEBin bo a b = EBin bo a b Nothing

    mkELit :: Literal -> Expression
    mkELit l = ELit l Nothing

    litparser :: Parser Expression
    litparser = do
        preops <- many pPrefixOp
        e <- pParenExpr <|> pENew <|> (mkELit <$> pLiteral)
        postops <- many pPostfixOp
        return $ foldl (flip ($)) e (postops ++ preops)

pAsExpression :: Parser AsExpression
pAsExpression = do
    n <- pName
    postops <- many pPostfixAsOp
    return $ foldl (flip ($)) (AEVar n Nothing) postops

pPrefixOp :: Parser (Expression -> Expression)
pPrefixOp = (symbol "!" >> return (\e -> EUn UONot e Nothing)) <|>
            (symbol "-" >> return (\e -> EUn UONeg e Nothing))

pPostfixOp :: Parser (Expression -> Expression)
pPostfixOp =
    (do
        expr <- between (symbol "[") (symbol "]") pExpression
        return $ \e -> ESubscript e expr Nothing) <|>
    (do
        symbol "."
        n <- pName
        return $ \e -> EGet e n Nothing)

pPostfixAsOp :: Parser (AsExpression -> AsExpression)
pPostfixAsOp =
    (do
        expr <- between (symbol "[") (symbol "]") pExpression
        return $ \ae -> AESubscript ae expr Nothing) <|>
    (do
        symbol "."
        n <- pName
        return $ \ae -> AEGet ae n Nothing)

pParenExpr :: Parser Expression
pParenExpr = do
    symbol "("
    e <- pExpression
    symbol ")"
    return e

pENew :: Parser Expression
pENew = do
    symbol "new"
    t <- pBasicType
    symbol "["
    e <- pExpression
    symbol "]"
    return $ ENew t e

pLiteral :: Parser Literal
pLiteral =
    (LInt <$> pInteger) <|> (LChar <$> pCharLit) <|> (LStr <$> pString) <|>
    pLStruct <|> pLCall <|> (LVar <$> pName)

pCharLit :: Parser Char
pCharLit = do
    void $ char '\''
    c <- pStringChar (const False)
    void $ char '\''
    pWhiteComment
    return c

pStringChar :: (Char -> Bool) -> Parser Char
pStringChar avoid =
    (char '\\' >> ((char 'n' >> return '\n') <|>
                   (char 'r' >> return '\r') <|>
                   (char 't' >> return '\t') <|>
                   (char '0' >> return '\0') <|>
                   (char 'x' >> pHexDigit >>= \a -> pHexDigit >>= \b -> return (chr $ 16 * a + b)))) <|>
    satisfy (not . avoid)
  where
    pHexDigit :: Parser Int
    pHexDigit = (subtract 48 . fromEnum <$> digit)
                    <|> ((+ (10 - 97)) . ord <$> oneOf "abcdef")
                    <|> ((+ (10 - 65)) . ord <$> oneOf "ABCDEF")

pString :: Parser String
pString = do
    void $ char '"'
    s <- many (pStringChar (== '"'))
    void $ char '"'
    return s

pLStruct :: Parser Literal
pLStruct = do
    symbol "{"
    ms <- sepBy (pName >>= \n -> symbol "=" >> pExpression >>= \e -> return (n,e)) (symbol ",")
    symbol "}"
    return $ LStruct ms

pLCall :: Parser Literal
pLCall = do
    n <- try $ pName <* symbol "("
    al <- sepBy pExpression (symbol ",")
    symbol ")"
    return $ LCall n al


pName :: Parser Name
pName = do
    c0 <- satisfy (\c -> isAlpha c || c == '_')
    cr <- many $ satisfy (\c -> isAlpha c || isDigit c || c == '_')
    pWhiteComment
    return $ c0 : cr

pInteger :: Parser Integer
pInteger = bareint <* pWhiteComment
  where
    bareint =
        (try (string "0x") >> many1 (satisfy isHexDigit) >>= return . read . ("0x" ++)) <|>
        (try (string "0b") >> many1 (oneOf "01") >>= return . bin2int) <|>
        (many1 (satisfy isDigit) >>= return . read)

    bin2int :: String -> Integer
    bin2int s = go (reverse s)
      where
        go "" = 0
        go ('0':s') = 2 * go s'
        go ('1':s') = 2 * go s' + 1
        go (_:_) = undefined

pIntegerInt :: Parser Int
pIntegerInt = do
    i <- pInteger
    when (i > (fromIntegral (maxBound :: Int) :: Integer) ||
          i < (fromIntegral (minBound :: Int) :: Integer)) $
        unexpected $ "Integer literal " ++ show i ++ " does not fit in an Int"
    return $ fromIntegral i


symbol :: String -> Parser ()
symbol "" = error "symbol \"\""
symbol s = try $ do
    void $ string s
    when (isAlpha (last s)) $ void $ notFollowedBy (satisfy isAlpha)
    when (isDigit (last s)) $ void $ notFollowedBy (satisfy isDigit)
    when (isOperatorChar (last s)) $ void $ notFollowedBy (satisfy isOperatorChar)
    pWhiteComment

isOperatorChar :: Char -> Bool
isOperatorChar = (`elem` "*/%^&|+-><=!")

pWhiteComment :: Parser ()
pWhiteComment = void $ pWhite >> endBy pComment pWhite

pWhite :: Parser ()
pWhite = void $ many (oneOf " \t\n")

pComment :: Parser ()
pComment = pLineComment <|> pBlockComment

pLineComment :: Parser ()
pLineComment = do
    void $ try $ string "//"
    void $ many (satisfy (/= '\n'))
    eof <|> void (char '\n')

pBlockComment :: Parser ()
pBlockComment = do
    void $ try $ string "/*"
    void $ sepEndBy (manyTill anyToken (lookAhead $ try (string "/*") <|> try (string "*/")))
                    pBlockComment
    void $ string "*/"