[project @ 2000-12-11 14:42:21 by sewardj]
[ghc-hetmet.git] / ghc / compiler / main / DriverUtil.hs
1 -----------------------------------------------------------------------------
2 -- $Id: DriverUtil.hs,v 1.13 2000/12/11 14:42:21 sewardj Exp $
3 --
4 -- Utils for the driver
5 --
6 -- (c) The University of Glasgow 2000
7 --
8 -----------------------------------------------------------------------------
9
10 module DriverUtil where
11
12 #include "../includes/config.h"
13 #include "HsVersions.h"
14
15 import Util
16
17 import IOExts
18 import Exception
19 import Dynamic
20 import RegexString
21
22 import IO
23 import System
24 import Directory ( removeFile )
25 import List
26 import Char
27 import Monad
28
29 -----------------------------------------------------------------------------
30 -- Errors
31
32 short_usage = "Usage: For basic information, try the `--help' option."
33    
34 GLOBAL_VAR(v_Path_usage,  "",  String)
35
36 long_usage = do
37   usage_path <- readIORef v_Path_usage
38   usage <- readFile usage_path
39   dump usage
40   exitWith ExitSuccess
41   where
42      dump "" = return ()
43      dump ('$':'$':s) = hPutStr stderr prog_name >> dump s
44      dump (c:s) = hPutChar stderr c >> dump s
45
46 data BarfKind
47   = PhaseFailed String ExitCode
48   | Interrupted
49   | UsageError String                   -- prints the short usage msg after the error
50   | OtherError String                   -- just prints the error message
51   deriving Eq
52
53 prog_name = unsafePerformIO (getProgName)
54 {-# NOINLINE prog_name #-}
55
56 instance Show BarfKind where
57   showsPrec _ e = showString prog_name . showString ": " . showBarf e
58
59 showBarf (UsageError str)
60    = showString str . showChar '\n' . showString short_usage
61 showBarf (OtherError str)
62    = showString str
63 showBarf (PhaseFailed phase code)
64    = showString phase . showString " failed, code = " . shows code
65 showBarf (Interrupted)
66    = showString "interrupted"
67
68 unknownFlagErr f = throwDyn (UsageError ("unrecognised flag: " ++ f))
69
70 barfKindTc = mkTyCon "BarfKind"
71 {-# NOINLINE barfKindTc #-}
72 instance Typeable BarfKind where
73   typeOf _ = mkAppTy barfKindTc []
74
75 -----------------------------------------------------------------------------
76 -- Reading OPTIONS pragmas
77
78 getOptionsFromSource 
79         :: String               -- input file
80         -> IO [String]          -- options, if any
81 getOptionsFromSource file
82   = do h <- openFile file ReadMode
83        catchJust ioErrors (look h)
84           (\e -> if isEOFError e then return [] else ioError e)
85   where
86         look h = do
87             l <- hGetLine h
88             case () of
89                 () | null l -> look h
90                    | prefixMatch "#" l -> look h
91                    | prefixMatch "{-# LINE" l -> look h   -- -}
92                    | Just (opts:_) <- matchRegex optionRegex l
93                         -> return (words opts)
94                    | otherwise -> return []
95
96 optionRegex = mkRegex "\\{-#[ \t]+OPTIONS[ \t]+(.*)#-\\}"   -- -}
97
98 -----------------------------------------------------------------------------
99 -- Utils
100
101 my_partition :: (a -> Maybe b) -> [a] -> ([(a,b)],[a])
102 my_partition _ [] = ([],[])
103 my_partition p (a:as)
104   = let (bs,cs) = my_partition p as in
105     case p a of
106         Nothing -> (bs,a:cs)
107         Just b  -> ((a,b):bs,cs)
108
109 my_prefix_match :: String -> String -> Maybe String
110 my_prefix_match [] rest = Just rest
111 my_prefix_match (_:_) [] = Nothing
112 my_prefix_match (p:pat) (r:rest)
113   | p == r    = my_prefix_match pat rest
114   | otherwise = Nothing
115
116 later = flip finally
117
118 handleDyn :: Typeable ex => (ex -> IO a) -> IO a -> IO a
119 handleDyn = flip catchDyn
120
121 split :: Char -> String -> [String]
122 split c s = case rest of
123                 []     -> [chunk] 
124                 _:rest -> chunk : split c rest
125   where (chunk, rest) = break (==c) s
126
127 add :: IORef [a] -> a -> IO ()
128 add var x = do
129   xs <- readIORef var
130   writeIORef var (x:xs)
131
132 addNoDups :: Eq a => IORef [a] -> a -> IO ()
133 addNoDups var x = do
134   xs <- readIORef var
135   unless (x `elem` xs) $ writeIORef var (x:xs)
136
137 splitFilename :: String -> (String,String)
138 splitFilename f = split_longest_prefix f '.'
139
140 -- "foo/bar/xyzzy.ext" -> ("foo/bar", "xyzzy", ".ext")
141 splitFilename3 :: String -> (String,String,String)
142 splitFilename3 str
143    = let (dir, rest) = split_longest_prefix str '/'
144          (name, ext) = splitFilename rest
145          real_dir | null dir  = "."
146                   | otherwise = dir
147      in  (real_dir, name, ext)
148
149 remove_suffix :: Char -> String -> String
150 remove_suffix c s
151   | null pre  = reverse suf
152   | otherwise = reverse pre
153   where (suf,pre) = break (==c) (reverse s)
154
155 drop_longest_prefix :: String -> Char -> String
156 drop_longest_prefix s c = reverse suf
157   where (suf,_pre) = break (==c) (reverse s)
158
159 take_longest_prefix :: String -> Char -> String
160 take_longest_prefix s c = reverse pre
161   where (_suf,pre) = break (==c) (reverse s)
162
163 -- split a string at the last occurence of 'c', returning the two
164 -- parts of the string with the 'c' removed.  If the string contains
165 -- no 'c's, the entire string is returned in the second component.
166 split_longest_prefix :: String -> Char -> (String,String)
167 split_longest_prefix s c
168   = case pre of
169         []      -> ([], reverse suf)
170         (_:pre) -> (reverse pre, reverse suf)
171   where (suf,pre) = break (==c) (reverse s)
172
173 newsuf :: String -> String -> String
174 newsuf suf s = remove_suffix '.' s ++ suf
175
176 -- getdir strips the filename off the input string, returning the directory.
177 getdir :: String -> String
178 getdir s = if null dir then "." else init dir
179   where dir = take_longest_prefix s '/'
180
181 newdir :: String -> String -> String
182 newdir dir s = dir ++ '/':drop_longest_prefix s '/'
183
184 remove_spaces :: String -> String
185 remove_spaces = reverse . dropWhile isSpace . reverse . dropWhile isSpace
186
187
188 -- system that works feasibly under Windows (i.e. passes the command line to sh,
189 -- because system() under Windows doesn't look at SHELL, and always uses CMD.EXE)
190 kludgedSystem cmd phase_name
191  = do
192 #ifndef mingw32_TARGET_OS
193    exit_code <- system cmd `catchAllIO` 
194                    (\_ -> throwDyn (PhaseFailed phase_name (ExitFailure 1)))
195 #else
196    pid <- myGetProcessID
197    let tmp = "/tmp/sh" ++ show pid
198    h <- openFile tmp WriteMode
199    hPutStrLn h cmd
200    hClose h
201    exit_code <- system ("sh - " ++ tmp) `catchAllIO` 
202                    (\_ -> removeFile tmp >>
203                           throwDyn (PhaseFailed phase_name (ExitFailure 1)))
204    removeFile tmp
205 #endif
206    return exit_code