50db73c3b4c13ef806de30631e08ae635f6011d8
[ghc-hetmet.git] / ghc / 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
10         ErrMsg, WarnMsg,
11         errMsgSpans, errMsgContext, errMsgShortDoc, errMsgExtraInfo,
12         Messages, errorsFound, emptyMessages,
13         mkErrMsg, mkWarnMsg, mkPlainErrMsg, mkLongErrMsg,
14         printErrorsAndWarnings, pprBagOfErrors, pprBagOfWarnings,
15
16         ghcExit,
17         doIfSet, doIfSet_dyn, 
18         dumpIfSet, dumpIfSet_core, dumpIfSet_dyn, dumpIfSet_dyn_or, mkDumpDoc,
19         showPass,
20
21         --  * Messages during compilation
22         setMsgHandler,
23         putMsg,
24         compilationProgressMsg,
25         debugTraceMsg,
26         errorMsg,
27     ) where
28
29 #include "HsVersions.h"
30
31 import Bag              ( Bag, bagToList, isEmptyBag, emptyBag )
32 import SrcLoc           ( SrcSpan )
33 import Util             ( sortLe, global )
34 import Outputable
35 import qualified Pretty
36 import SrcLoc           ( srcSpanStart )
37 import DynFlags         ( DynFlags(..), DynFlag(..), dopt )
38 import StaticFlags      ( opt_ErrorSpans )
39 import System           ( ExitCode(..), exitWith )
40 import DATA_IOREF
41 import IO               ( hPutStrLn, stderr )
42 import DYNAMIC
43
44
45 -- -----------------------------------------------------------------------------
46 -- Basic error messages: just render a message with a source location.
47
48 type Message = SDoc
49
50 mkLocMessage :: SrcSpan -> Message -> Message
51 mkLocMessage locn msg
52   | opt_ErrorSpans = hang (ppr locn <> colon) 4 msg
53   | otherwise      = hang (ppr (srcSpanStart locn) <> colon) 4 msg
54   -- always print the location, even if it is unhelpful.  Error messages
55   -- are supposed to be in a standard format, and one without a location
56   -- would look strange.  Better to say explicitly "<no location info>".
57
58 printError :: SrcSpan -> Message -> IO ()
59 printError span msg = printErrs (mkLocMessage span msg $ defaultErrStyle)
60
61
62 -- -----------------------------------------------------------------------------
63 -- Collecting up messages for later ordering and printing.
64
65 data ErrMsg = ErrMsg { 
66         errMsgSpans     :: [SrcSpan],
67         errMsgContext   :: PrintUnqualified,
68         errMsgShortDoc  :: Message,
69         errMsgExtraInfo :: Message
70         }
71         -- The SrcSpan is used for sorting errors into line-number order
72         -- NB  Pretty.Doc not SDoc: we deal with the printing style (in ptic 
73         -- whether to qualify an External Name) at the error occurrence
74
75 -- So we can throw these things as exceptions
76 errMsgTc :: TyCon
77 errMsgTc = mkTyCon "ErrMsg"
78 {-# NOINLINE errMsgTc #-}
79 instance Typeable ErrMsg where
80 #if __GLASGOW_HASKELL__ < 603
81   typeOf _ = mkAppTy errMsgTc []
82 #else
83   typeOf _ = mkTyConApp errMsgTc []
84 #endif
85
86 type WarnMsg = ErrMsg
87
88 -- A short (one-line) error message, with context to tell us whether
89 -- to qualify names in the message or not.
90 mkErrMsg :: SrcSpan -> PrintUnqualified -> Message -> ErrMsg
91 mkErrMsg locn print_unqual msg
92   = ErrMsg [locn] print_unqual msg empty
93
94 -- Variant that doesn't care about qualified/unqualified names
95 mkPlainErrMsg :: SrcSpan -> Message -> ErrMsg
96 mkPlainErrMsg locn msg
97   = ErrMsg [locn] alwaysQualify msg empty
98
99 -- A long (multi-line) error message, with context to tell us whether
100 -- to qualify names in the message or not.
101 mkLongErrMsg :: SrcSpan -> PrintUnqualified -> Message -> Message -> ErrMsg
102 mkLongErrMsg locn print_unqual msg extra 
103  = ErrMsg [locn] print_unqual msg extra
104
105 mkWarnMsg :: SrcSpan -> PrintUnqualified -> Message -> WarnMsg
106 mkWarnMsg = mkErrMsg
107
108 type Messages = (Bag WarnMsg, Bag ErrMsg)
109
110 emptyMessages :: Messages
111 emptyMessages = (emptyBag, emptyBag)
112
113 errorsFound :: DynFlags -> Messages -> Bool
114 -- The dyn-flags are used to see if the user has specified
115 -- -Werorr, which says that warnings should be fatal
116 errorsFound dflags (warns, errs) 
117   | dopt Opt_WarnIsError dflags = not (isEmptyBag errs) || not (isEmptyBag warns)
118   | otherwise                   = not (isEmptyBag errs)
119
120 printErrorsAndWarnings :: Messages -> IO ()
121 printErrorsAndWarnings (warns, errs)
122   | no_errs && no_warns  = return ()
123   | no_errs              = printErrs (pprBagOfWarnings warns)
124                             -- Don't print any warnings if there are errors
125   | otherwise            = printErrs (pprBagOfErrors   errs)
126   where
127     no_warns = isEmptyBag warns
128     no_errs  = isEmptyBag errs
129
130 pprBagOfErrors :: Bag ErrMsg -> Pretty.Doc
131 pprBagOfErrors bag_of_errors
132   = Pretty.vcat [ let style = mkErrStyle unqual
133                       doc = mkLocMessage s (d $$ e)
134                   in
135                   Pretty.text "" Pretty.$$ doc style
136                 | ErrMsg { errMsgSpans = s:ss,
137                            errMsgShortDoc = d,
138                            errMsgExtraInfo = e,
139                            errMsgContext = unqual } <- sorted_errs ]
140     where
141       bag_ls      = bagToList bag_of_errors
142       sorted_errs = sortLe occ'ed_before bag_ls
143
144       occ'ed_before err1 err2 = 
145          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
146                 LT -> True
147                 EQ -> True
148                 GT -> False
149
150 pprBagOfWarnings :: Bag WarnMsg -> Pretty.Doc
151 pprBagOfWarnings bag_of_warns = pprBagOfErrors bag_of_warns
152 \end{code}
153
154 \begin{code}
155 ghcExit :: Int -> IO ()
156 ghcExit val
157   | val == 0  = exitWith ExitSuccess
158   | otherwise = do errorMsg "\nCompilation had errors\n\n"
159                    exitWith (ExitFailure val)
160 \end{code}
161
162 \begin{code}
163 doIfSet :: Bool -> IO () -> IO ()
164 doIfSet flag action | flag      = action
165                     | otherwise = return ()
166
167 doIfSet_dyn :: DynFlags -> DynFlag -> IO () -> IO()
168 doIfSet_dyn dflags flag action | dopt flag dflags = action
169                                | otherwise        = return ()
170 \end{code}
171
172 \begin{code}
173 showPass :: DynFlags -> String -> IO ()
174 showPass dflags what = compilationPassMsg dflags ("*** "++what++":")
175
176 dumpIfSet :: Bool -> String -> SDoc -> IO ()
177 dumpIfSet flag hdr doc
178   | not flag   = return ()
179   | otherwise  = printDump (mkDumpDoc hdr doc)
180
181 dumpIfSet_core :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
182 dumpIfSet_core dflags flag hdr doc
183   | dopt flag dflags
184         || verbosity dflags >= 4
185         || dopt Opt_D_verbose_core2core dflags  = printDump (mkDumpDoc hdr doc)
186   | otherwise                                   = return ()
187
188 dumpIfSet_dyn :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
189 dumpIfSet_dyn dflags flag hdr doc
190   | dopt flag dflags || verbosity dflags >= 4 
191   = printDump (mkDumpDoc hdr doc)
192   | otherwise
193   = return ()
194
195 dumpIfSet_dyn_or :: DynFlags -> [DynFlag] -> String -> SDoc -> IO ()
196 dumpIfSet_dyn_or dflags flags hdr doc
197   | or [dopt flag dflags | flag <- flags]
198   || verbosity dflags >= 4 
199   = printDump (mkDumpDoc hdr doc)
200   | otherwise = return ()
201
202 mkDumpDoc hdr doc 
203    = vcat [text "", 
204            line <+> text hdr <+> line,
205            doc,
206            text ""]
207      where 
208         line = text (replicate 20 '=')
209
210 -- -----------------------------------------------------------------------------
211 -- Outputting messages from the compiler
212
213 -- We want all messages to go through one place, so that we can
214 -- redirect them if necessary.  For example, when GHC is used as a
215 -- library we might want to catch all messages that GHC tries to
216 -- output and do something else with them.
217
218 ifVerbose :: DynFlags -> Int -> IO () -> IO ()
219 ifVerbose dflags val act
220   | verbosity dflags >= val = act
221   | otherwise               = return ()
222
223 errorMsg :: String -> IO ()
224 errorMsg = putMsg
225
226 compilationProgressMsg :: DynFlags -> String -> IO ()
227 compilationProgressMsg dflags msg
228   = ifVerbose dflags 1 (putMsg msg)
229
230 compilationPassMsg :: DynFlags -> String -> IO ()
231 compilationPassMsg dflags msg
232   = ifVerbose dflags 2 (putMsg msg)
233
234 debugTraceMsg :: DynFlags -> Int -> String -> IO ()
235 debugTraceMsg dflags val msg
236   = ifVerbose dflags val (putMsg msg)
237
238 GLOBAL_VAR(msgHandler, hPutStrLn stderr, (String -> IO ()))
239
240 setMsgHandler :: (String -> IO ()) -> IO ()
241 setMsgHandler handle_msg = writeIORef msgHandler handle_msg
242
243 putMsg :: String -> IO ()
244 putMsg msg = do h <- readIORef msgHandler; h msg
245 \end{code}