-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHListPP.hs
executable file
·86 lines (73 loc) · 2.35 KB
/
HListPP.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
{-# LANGUAGE QuasiQuotes, ViewPatterns, ApplicativeDo #-}
module Main where
import Data.Char
import Data.List
import Data.Monoid
import System.Environment
import Text.Regex.Applicative
import Control.Exception
import System.Exit
import System.IO
-- "ModuleName."
modNameDot = do
m <- psym isUpper
odName <- many (psym isAlpha <|> psym isDigit)
dot <- sym '.'
pure $ m:odName ++ [dot]
-- "M.Od.Ule.Name.something"
qualIdent = do
modNames <- many modNameDot
end <- identSym <|> identAlpha
pure $ concat (modNames ++ [end])
identSym = some (psym isSymbol)
identAlpha = do
i <- psym isAlpha
dent <- many (psym isAlpha <|> psym isDigit <|> sym '\'')
pure $ i:dent
takeQual x = case findLongestPrefix qualIdent x of
Just (a , '`' : rest) -> ('`' : a ++ "`", rest) -- `infix`
Just (a, rest) -> (addLabel a,rest) -- `ident
Nothing -> ("``", x) -- unlikely
addLabel xu = "(hLens' (Label :: Label \""++xu++"\"))"
main = do
args <- getArgs
operate args
`catch` \ (SomeException e) -> do
hPutStrLn stderr (show e)
hPutStrLn stderr ("in: HListPP " ++ unwords args)
exitFailure
{-# INLINE operate #-}
operate [originalFileName, inputFile, outputFile] = do
input <- readFile inputFile
let linePragma = "{-# LINE 1 \"" <> originalFileName <> "\" #-}\n"
writeFile outputFile (linePragma <> s input)
operate args = error $ "usage: HListPP originalFileName inputFile outputFile\
\ also: \
\ {-# OPTIONS_GHC -F -pgmF HListPP #-}\
\ called with arguments: " ++ show args
-- | applies takeQual outside of characters, strings, comments
{-# INLINE s #-}
s (stripPrefix "'\"'" -> Just xs) = "'\"'" ++ s xs
s (stripPrefix "'`'" -> Just xs) = "'`'" ++ s xs
s (stripPrefix "{-" -> Just xs) = "{-" ++ cl xs
s (stripPrefix "--" -> Just xs)
| x1 : _ <- xs, isSymbol x1 = "--" ++ s xs
| otherwise = "-- " ++ cs xs
s ('"': xs) = '"' : t xs
s ('`': (takeQual -> (a,xs))) = a ++ s xs
s (x:xs) = x : s xs
s [] = []
-- | inside string
{-# INLINE t #-}
t (stripPrefix "\\\"" -> Just xs) = "\\\"" ++ t xs
t ('"' : xs) = '"' : s xs
t (x:xs) = x : t xs
t [] = error "expected \""
-- | inside multiline comment
cl (stripPrefix "-}" -> Just xs) = "-}" ++ s xs
cl (x:xs) = x:cl xs
cl [] = error "expected -}"
-- | inside single line comment
cs ('\n':xs) = '\n' : s xs
cs (x:xs) = x : cs xs
cs "" = ""