72d0e930bcb347de0c015a0b0cc2988beb892a69
[ghc-hetmet.git] / compiler / main / ErrUtils.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1998
3 %
4 \section[ErrsUtils]{Utilities for error reporting}
5
6 \begin{code}
7 module ErrUtils (
8         Message, mkLocMessage, printError,
9         Severity(..),
10
11         ErrMsg, WarnMsg,
12         errMsgSpans, errMsgContext, errMsgShortDoc, errMsgExtraInfo,
13         Messages, errorsFound, emptyMessages,
14         mkErrMsg, mkWarnMsg, mkPlainErrMsg, mkLongErrMsg,
15         printErrorsAndWarnings, printBagOfErrors, printBagOfWarnings,
16
17         ghcExit,
18         doIfSet, doIfSet_dyn, 
19         dumpIfSet, dumpIf_core, dumpIfSet_core, dumpIfSet_dyn, dumpIfSet_dyn_or,
20         mkDumpDoc, dumpSDoc,
21
22         --  * Messages during compilation
23         putMsg,
24         errorMsg,
25         fatalErrorMsg,
26         compilationProgressMsg,
27         showPass,
28         debugTraceMsg,  
29     ) where
30
31 -- XXX This define is a bit of a hack, and should be done more nicely
32 #define FAST_STRING_NOT_NEEDED 1
33 #include "HsVersions.h"
34
35 import Bag              ( Bag, bagToList, isEmptyBag, emptyBag )
36 import SrcLoc           ( SrcSpan )
37 import Util             ( sortLe )
38 import Outputable
39 import SrcLoc           ( srcSpanStart, noSrcSpan )
40 import DynFlags         ( DynFlags(..), DynFlag(..), dopt )
41 import StaticFlags      ( opt_ErrorSpans )
42
43 import System.Exit      ( ExitCode(..), exitWith )
44 import Data.Dynamic
45 import Data.List
46 import System.IO
47
48 -- -----------------------------------------------------------------------------
49 -- Basic error messages: just render a message with a source location.
50
51 type Message = SDoc
52
53 data Severity
54   = SevInfo
55   | SevWarning
56   | SevError
57   | SevFatal
58
59 mkLocMessage :: SrcSpan -> Message -> Message
60 mkLocMessage locn msg
61   | opt_ErrorSpans = hang (ppr locn <> colon) 4 msg
62   | otherwise      = hang (ppr (srcSpanStart locn) <> colon) 4 msg
63   -- always print the location, even if it is unhelpful.  Error messages
64   -- are supposed to be in a standard format, and one without a location
65   -- would look strange.  Better to say explicitly "<no location info>".
66
67 printError :: SrcSpan -> Message -> IO ()
68 printError span msg = printErrs (mkLocMessage span msg $ defaultErrStyle)
69
70
71 -- -----------------------------------------------------------------------------
72 -- Collecting up messages for later ordering and printing.
73
74 data ErrMsg = ErrMsg { 
75         errMsgSpans     :: [SrcSpan],
76         errMsgContext   :: PrintUnqualified,
77         errMsgShortDoc  :: Message,
78         errMsgExtraInfo :: Message
79         }
80         -- The SrcSpan is used for sorting errors into line-number order
81         -- NB  Pretty.Doc not SDoc: we deal with the printing style (in ptic 
82         -- whether to qualify an External Name) at the error occurrence
83
84 -- So we can throw these things as exceptions
85 errMsgTc :: TyCon
86 errMsgTc = mkTyCon "ErrMsg"
87 {-# NOINLINE errMsgTc #-}
88 instance Typeable ErrMsg where
89 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 603
90   typeOf _ = mkAppTy errMsgTc []
91 #else
92   typeOf _ = mkTyConApp errMsgTc []
93 #endif
94
95 type WarnMsg = ErrMsg
96
97 -- A short (one-line) error message, with context to tell us whether
98 -- to qualify names in the message or not.
99 mkErrMsg :: SrcSpan -> PrintUnqualified -> Message -> ErrMsg
100 mkErrMsg locn print_unqual msg
101   = ErrMsg [locn] print_unqual msg empty
102
103 -- Variant that doesn't care about qualified/unqualified names
104 mkPlainErrMsg :: SrcSpan -> Message -> ErrMsg
105 mkPlainErrMsg locn msg
106   = ErrMsg [locn] alwaysQualify msg empty
107
108 -- A long (multi-line) error message, with context to tell us whether
109 -- to qualify names in the message or not.
110 mkLongErrMsg :: SrcSpan -> PrintUnqualified -> Message -> Message -> ErrMsg
111 mkLongErrMsg locn print_unqual msg extra 
112  = ErrMsg [locn] print_unqual msg extra
113
114 mkWarnMsg :: SrcSpan -> PrintUnqualified -> Message -> WarnMsg
115 mkWarnMsg = mkErrMsg
116
117 type Messages = (Bag WarnMsg, Bag ErrMsg)
118
119 emptyMessages :: Messages
120 emptyMessages = (emptyBag, emptyBag)
121
122 errorsFound :: DynFlags -> Messages -> Bool
123 -- The dyn-flags are used to see if the user has specified
124 -- -Werorr, which says that warnings should be fatal
125 errorsFound dflags (warns, errs) 
126   | dopt Opt_WarnIsError dflags = not (isEmptyBag errs) || not (isEmptyBag warns)
127   | otherwise                   = not (isEmptyBag errs)
128
129 printErrorsAndWarnings :: DynFlags -> Messages -> IO ()
130 printErrorsAndWarnings dflags (warns, errs)
131   | no_errs && no_warns  = return ()
132   | no_errs              = printBagOfWarnings dflags warns
133                             -- Don't print any warnings if there are errors
134   | otherwise            = printBagOfErrors   dflags errs
135   where
136     no_warns = isEmptyBag warns
137     no_errs  = isEmptyBag errs
138
139 printBagOfErrors :: DynFlags -> Bag ErrMsg -> IO ()
140 printBagOfErrors dflags bag_of_errors
141   = sequence_   [ let style = mkErrStyle unqual
142                   in log_action dflags SevError s style (d $$ e)
143                 | ErrMsg { errMsgSpans = s:_,
144                            errMsgShortDoc = d,
145                            errMsgExtraInfo = e,
146                            errMsgContext = unqual } <- sorted_errs ]
147     where
148       bag_ls      = bagToList bag_of_errors
149       sorted_errs = sortLe occ'ed_before bag_ls
150
151       occ'ed_before err1 err2 = 
152          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
153                 LT -> True
154                 EQ -> True
155                 GT -> False
156
157 printBagOfWarnings :: DynFlags -> Bag ErrMsg -> IO ()
158 printBagOfWarnings dflags bag_of_warns
159   = sequence_   [ let style = mkErrStyle unqual
160                   in log_action dflags SevWarning s style (d $$ e)
161                 | ErrMsg { errMsgSpans = s:_,
162                            errMsgShortDoc = d,
163                            errMsgExtraInfo = e,
164                            errMsgContext = unqual } <- sorted_errs ]
165     where
166       bag_ls      = bagToList bag_of_warns
167       sorted_errs = sortLe occ'ed_before bag_ls
168
169       occ'ed_before err1 err2 = 
170          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
171                 LT -> True
172                 EQ -> True
173                 GT -> False
174
175
176
177 ghcExit :: DynFlags -> Int -> IO ()
178 ghcExit dflags val
179   | val == 0  = exitWith ExitSuccess
180   | otherwise = do errorMsg dflags (text "\nCompilation had errors\n\n")
181                    exitWith (ExitFailure val)
182
183 doIfSet :: Bool -> IO () -> IO ()
184 doIfSet flag action | flag      = action
185                     | otherwise = return ()
186
187 doIfSet_dyn :: DynFlags -> DynFlag -> IO () -> IO()
188 doIfSet_dyn dflags flag action | dopt flag dflags = action
189                                | otherwise        = return ()
190
191 -- -----------------------------------------------------------------------------
192 -- Dumping
193
194 dumpIfSet :: Bool -> String -> SDoc -> IO ()
195 dumpIfSet flag hdr doc
196   | not flag   = return ()
197   | otherwise  = printDump (mkDumpDoc hdr doc)
198
199 dumpIf_core :: Bool -> DynFlags -> DynFlag -> String -> SDoc -> IO ()
200 dumpIf_core cond dflags dflag hdr doc
201   | cond
202     || verbosity dflags >= 4
203     || dopt Opt_D_verbose_core2core dflags
204   = dumpSDoc dflags dflag hdr doc
205
206   | otherwise = return ()
207
208 dumpIfSet_core :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
209 dumpIfSet_core dflags flag hdr doc
210   = dumpIf_core (dopt flag dflags) dflags flag hdr doc
211
212 dumpIfSet_dyn :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
213 dumpIfSet_dyn dflags flag hdr doc
214   | dopt flag dflags || verbosity dflags >= 4 
215   = dumpSDoc dflags flag hdr doc
216   | otherwise
217   = return ()
218
219 dumpIfSet_dyn_or :: DynFlags -> [DynFlag] -> String -> SDoc -> IO ()
220 dumpIfSet_dyn_or dflags flags hdr doc
221   | or [dopt flag dflags | flag <- flags]
222   || verbosity dflags >= 4 
223   = printDump (mkDumpDoc hdr doc)
224   | otherwise = return ()
225
226 mkDumpDoc :: String -> SDoc -> SDoc
227 mkDumpDoc hdr doc 
228    = vcat [text "", 
229            line <+> text hdr <+> line,
230            doc,
231            text ""]
232      where 
233         line = text (replicate 20 '=')
234
235
236 -- | Write out a dump.
237 --      If --dump-to-file is set then this goes to a file.
238 --      otherwise emit to stdout.
239 dumpSDoc :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
240 dumpSDoc dflags dflag hdr doc
241  = do   let mFile       = chooseDumpFile dflags dflag
242         case mFile of
243                 -- write the dump to a file
244                 --      don't add the header in this case, we can see what kind
245                 --      of dump it is from the filename.
246                 Just fileName
247                  -> do  handle  <- openFile fileName AppendMode
248                         hPrintDump handle doc
249                         hClose handle
250
251                 -- write the dump to stdout
252                 Nothing
253                  -> do  printDump (mkDumpDoc hdr doc)
254
255
256 -- | Choose where to put a dump file based on DynFlags
257 --
258 chooseDumpFile :: DynFlags -> DynFlag -> Maybe String
259 chooseDumpFile dflags dflag
260
261         -- dump file location is being forced
262         --      by the --ddump-file-prefix flag.
263         | dumpToFile
264         , Just prefix   <- dumpPrefixForce dflags
265         = Just $ prefix ++ (beautifyDumpName dflag)
266
267         -- dump file location chosen by DriverPipeline.runPipeline
268         | dumpToFile
269         , Just prefix   <- dumpPrefix dflags
270         = Just $ prefix ++ (beautifyDumpName dflag)
271
272         -- we haven't got a place to put a dump file.
273         | otherwise
274         = Nothing
275
276         where   dumpToFile = dopt Opt_DumpToFile dflags
277
278
279 -- | Build a nice file name from name of a DynFlag constructor
280 beautifyDumpName :: DynFlag -> String
281 beautifyDumpName dflag
282  = let  str     = show dflag
283         cut     = if isPrefixOf "Opt_D_" str
284                          then drop 6 str
285                          else str
286         dash    = map   (\c -> case c of
287                                 '_'     -> '-'
288                                 _       -> c)
289                         cut
290    in   dash
291
292
293 -- -----------------------------------------------------------------------------
294 -- Outputting messages from the compiler
295
296 -- We want all messages to go through one place, so that we can
297 -- redirect them if necessary.  For example, when GHC is used as a
298 -- library we might want to catch all messages that GHC tries to
299 -- output and do something else with them.
300
301 ifVerbose :: DynFlags -> Int -> IO () -> IO ()
302 ifVerbose dflags val act
303   | verbosity dflags >= val = act
304   | otherwise               = return ()
305
306 putMsg :: DynFlags -> Message -> IO ()
307 putMsg dflags msg = log_action dflags SevInfo noSrcSpan defaultUserStyle msg
308
309 errorMsg :: DynFlags -> Message -> IO ()
310 errorMsg dflags msg = log_action dflags SevError noSrcSpan defaultErrStyle msg
311
312 fatalErrorMsg :: DynFlags -> Message -> IO ()
313 fatalErrorMsg dflags msg = log_action dflags SevFatal noSrcSpan defaultErrStyle msg
314
315 compilationProgressMsg :: DynFlags -> String -> IO ()
316 compilationProgressMsg dflags msg
317   = ifVerbose dflags 1 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text msg))
318
319 showPass :: DynFlags -> String -> IO ()
320 showPass dflags what 
321   = ifVerbose dflags 2 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text "***" <+> text what <> colon))
322
323 debugTraceMsg :: DynFlags -> Int -> Message -> IO ()
324 debugTraceMsg dflags val msg
325   = ifVerbose dflags val (log_action dflags SevInfo noSrcSpan defaultDumpStyle msg)
326
327 \end{code}