summaryrefslogtreecommitdiff
path: root/src/Brainfuck/Parser.hs
blob: 1ea046a5aed5df4fcc26c2f0433cd22e1c6502bf (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
module Brainfuck.Parser (
    BrainfuckProgram,
    BrainCom(..),

	parseBrainfuck
    ) where

import Control.Applicative( some )
import Text.ParserCombinators.Parsec



type BrainfuckProgram = [BrainCom]


data BrainCom = R | L | Inc | Dec | Out | In | OpenLoop | CloseLoop
    deriving (Show, Eq)




parseBrainfuck :: String -> Either ParseError BrainfuckProgram
parseBrainfuck = parse brainfuck "error"




brainfuck = do
	many commentChar
	bs <- many fuck
	eof
	return . concat $ bs


fuck =  (brainCommand >>= return . (:[]))
    <|> loop
    <?> "brainfuck command"


loop = do
	char '['
	many commentChar
	bs <- many brainCommand
	char ']'
	many commentChar
	return . concat $ [[OpenLoop],bs,[CloseLoop]]


brainCommand = do { b <- brainCom; many commentChar; return b }


brainCom =  (char '>' >> return R)
        <|> (char '<' >> return L)
        <|> (char '+' >> return Inc)
        <|> (char '-' >> return Dec)
        <|> (char '.' >> return Out)
        <|> (char ',' >> return In)
        <?> "brainfuck command"


commentChar = noneOf "><+-.,[]"