6412
|
1 |
module PascalPreprocessor where
|
|
2 |
|
|
3 |
import Text.Parsec
|
|
4 |
import Control.Monad.IO.Class
|
|
5 |
import System.IO
|
|
6 |
import qualified Data.Map as Map
|
|
7 |
|
6413
|
8 |
|
|
9 |
-- comments are removed
|
|
10 |
comment = choice [
|
|
11 |
char '{' >> notFollowedBy (char '$') >> manyTill anyChar (try $ char '}') >> return ""
|
|
12 |
, (try $ string "(*") >> manyTill anyChar (try $ string "*)") >> return ""
|
|
13 |
, (try $ string "//") >> manyTill anyChar (try newline) >> return "\n"
|
|
14 |
]
|
|
15 |
|
6412
|
16 |
preprocess :: String -> IO String
|
|
17 |
preprocess fn = do
|
|
18 |
r <- runParserT (preprocessFile fn) Map.empty "" ""
|
|
19 |
case r of
|
|
20 |
(Left a) -> do
|
|
21 |
hPutStrLn stderr (show a)
|
|
22 |
return ""
|
|
23 |
(Right a) -> return a
|
|
24 |
|
|
25 |
where
|
|
26 |
preprocessFile :: String -> ParsecT String (Map.Map String String) IO String
|
|
27 |
preprocessFile fn = do
|
|
28 |
f <- liftIO (readFile fn)
|
|
29 |
setInput f
|
|
30 |
preprocessor
|
6413
|
31 |
|
6412
|
32 |
preprocessor, codeBlock, switch :: ParsecT String (Map.Map String String) IO String
|
6413
|
33 |
|
6412
|
34 |
preprocessor = chainl codeBlock (return (++)) ""
|
6413
|
35 |
|
6412
|
36 |
codeBlock = choice [
|
|
37 |
switch
|
6413
|
38 |
, comment
|
6412
|
39 |
, char '\'' >> many (noneOf "'") >>= \s -> char '\'' >> return ('\'' : s ++ "'")
|
6413
|
40 |
, many1 $ noneOf "{'/("
|
|
41 |
, char '/' >> notFollowedBy (char '/') >> return "/"
|
|
42 |
, char '(' >> notFollowedBy (char '*') >> return "("
|
6412
|
43 |
]
|
6413
|
44 |
|
6412
|
45 |
switch = do
|
|
46 |
try $ string "{$"
|
|
47 |
s <- choice [
|
|
48 |
include
|
|
49 |
, unknown
|
|
50 |
]
|
|
51 |
return s
|
6413
|
52 |
|
6412
|
53 |
include = do
|
|
54 |
try $ string "INCLUDE"
|
|
55 |
spaces
|
|
56 |
(char '"')
|
|
57 |
fn <- many1 $ noneOf "\"\n"
|
|
58 |
char '"'
|
|
59 |
spaces
|
|
60 |
char '}'
|
|
61 |
f <- liftIO (readFile fn)
|
|
62 |
c <- getInput
|
|
63 |
setInput $ f ++ c
|
|
64 |
return ""
|
|
65 |
|
|
66 |
unknown = do
|
|
67 |
fn <- many1 $ noneOf "}\n"
|
|
68 |
char '}'
|
|
69 |
return ""
|
|
70 |
|