Deferred type errors now throw TypeError (#10284)
[ghc.git] / libraries / base / Control / Exception / Base.hs
1 {-# LANGUAGE Trustworthy #-}
2 {-# LANGUAGE NoImplicitPrelude, MagicHash #-}
3 {-# LANGUAGE StandaloneDeriving #-}
4
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module : Control.Exception.Base
8 -- Copyright : (c) The University of Glasgow 2001
9 -- License : BSD-style (see the file libraries/base/LICENSE)
10 --
11 -- Maintainer : libraries@haskell.org
12 -- Stability : experimental
13 -- Portability : non-portable (extended exceptions)
14 --
15 -- Extensible exceptions, except for multiple handlers.
16 --
17 -----------------------------------------------------------------------------
18
19 module Control.Exception.Base (
20
21 -- * The Exception type
22 SomeException(..),
23 Exception(..),
24 IOException,
25 ArithException(..),
26 ArrayException(..),
27 AssertionFailed(..),
28 SomeAsyncException(..), AsyncException(..),
29 asyncExceptionToException, asyncExceptionFromException,
30 NonTermination(..),
31 NestedAtomically(..),
32 BlockedIndefinitelyOnMVar(..),
33 BlockedIndefinitelyOnSTM(..),
34 AllocationLimitExceeded(..),
35 Deadlock(..),
36 NoMethodError(..),
37 PatternMatchFail(..),
38 RecConError(..),
39 RecSelError(..),
40 RecUpdError(..),
41 ErrorCall(..),
42 TypeError(..), -- #10284, custom error type for deferred type errors
43
44 -- * Throwing exceptions
45 throwIO,
46 throw,
47 ioError,
48 throwTo,
49
50 -- * Catching Exceptions
51
52 -- ** The @catch@ functions
53 catch,
54 catchJust,
55
56 -- ** The @handle@ functions
57 handle,
58 handleJust,
59
60 -- ** The @try@ functions
61 try,
62 tryJust,
63 onException,
64
65 -- ** The @evaluate@ function
66 evaluate,
67
68 -- ** The @mapException@ function
69 mapException,
70
71 -- * Asynchronous Exceptions
72
73 -- ** Asynchronous exception control
74 mask,
75 mask_,
76 uninterruptibleMask,
77 uninterruptibleMask_,
78 MaskingState(..),
79 getMaskingState,
80
81 -- * Assertions
82
83 assert,
84
85 -- * Utilities
86
87 bracket,
88 bracket_,
89 bracketOnError,
90
91 finally,
92
93 -- * Calls for GHC runtime
94 recSelError, recConError, irrefutPatError, runtimeError,
95 nonExhaustiveGuardsError, patError, noMethodBindingError,
96 absentError, typeError,
97 nonTermination, nestedAtomically,
98 ) where
99
100 import GHC.Base
101 import GHC.IO hiding (bracket,finally,onException)
102 import GHC.IO.Exception
103 import GHC.Exception
104 import GHC.Show
105 -- import GHC.Exception hiding ( Exception )
106 import GHC.Conc.Sync
107
108 import Data.Either
109
110 -----------------------------------------------------------------------------
111 -- Catching exceptions
112
113 -- |This is the simplest of the exception-catching functions. It
114 -- takes a single argument, runs it, and if an exception is raised
115 -- the \"handler\" is executed, with the value of the exception passed as an
116 -- argument. Otherwise, the result is returned as normal. For example:
117 --
118 -- > catch (readFile f)
119 -- > (\e -> do let err = show (e :: IOException)
120 -- > hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
121 -- > return "")
122 --
123 -- Note that we have to give a type signature to @e@, or the program
124 -- will not typecheck as the type is ambiguous. While it is possible
125 -- to catch exceptions of any type, see the section \"Catching all
126 -- exceptions\" (in "Control.Exception") for an explanation of the problems with doing so.
127 --
128 -- For catching exceptions in pure (non-'IO') expressions, see the
129 -- function 'evaluate'.
130 --
131 -- Note that due to Haskell\'s unspecified evaluation order, an
132 -- expression may throw one of several possible exceptions: consider
133 -- the expression @(error \"urk\") + (1 \`div\` 0)@. Does
134 -- the expression throw
135 -- @ErrorCall \"urk\"@, or @DivideByZero@?
136 --
137 -- The answer is \"it might throw either\"; the choice is
138 -- non-deterministic. If you are catching any type of exception then you
139 -- might catch either. If you are calling @catch@ with type
140 -- @IO Int -> (ArithException -> IO Int) -> IO Int@ then the handler may
141 -- get run with @DivideByZero@ as an argument, or an @ErrorCall \"urk\"@
142 -- exception may be propogated further up. If you call it again, you
143 -- might get a the opposite behaviour. This is ok, because 'catch' is an
144 -- 'IO' computation.
145 --
146 catch :: Exception e
147 => IO a -- ^ The computation to run
148 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
149 -> IO a
150 catch = catchException
151
152 -- | The function 'catchJust' is like 'catch', but it takes an extra
153 -- argument which is an /exception predicate/, a function which
154 -- selects which type of exceptions we\'re interested in.
155 --
156 -- > catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
157 -- > (readFile f)
158 -- > (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
159 -- > return "")
160 --
161 -- Any other exceptions which are not matched by the predicate
162 -- are re-raised, and may be caught by an enclosing
163 -- 'catch', 'catchJust', etc.
164 catchJust
165 :: Exception e
166 => (e -> Maybe b) -- ^ Predicate to select exceptions
167 -> IO a -- ^ Computation to run
168 -> (b -> IO a) -- ^ Handler
169 -> IO a
170 catchJust p a handler = catch a handler'
171 where handler' e = case p e of
172 Nothing -> throwIO e
173 Just b -> handler b
174
175 -- | A version of 'catch' with the arguments swapped around; useful in
176 -- situations where the code for the handler is shorter. For example:
177 --
178 -- > do handle (\NonTermination -> exitWith (ExitFailure 1)) $
179 -- > ...
180 handle :: Exception e => (e -> IO a) -> IO a -> IO a
181 handle = flip catch
182
183 -- | A version of 'catchJust' with the arguments swapped around (see
184 -- 'handle').
185 handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
186 handleJust p = flip (catchJust p)
187
188 -----------------------------------------------------------------------------
189 -- 'mapException'
190
191 -- | This function maps one exception into another as proposed in the
192 -- paper \"A semantics for imprecise exceptions\".
193
194 -- Notice that the usage of 'unsafePerformIO' is safe here.
195
196 mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
197 mapException f v = unsafePerformIO (catch (evaluate v)
198 (\x -> throwIO (f x)))
199
200 -----------------------------------------------------------------------------
201 -- 'try' and variations.
202
203 -- | Similar to 'catch', but returns an 'Either' result which is
204 -- @('Right' a)@ if no exception of type @e@ was raised, or @('Left' ex)@
205 -- if an exception of type @e@ was raised and its value is @ex@.
206 -- If any other type of exception is raised than it will be propogated
207 -- up to the next enclosing exception handler.
208 --
209 -- > try a = catch (Right `liftM` a) (return . Left)
210
211 try :: Exception e => IO a -> IO (Either e a)
212 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
213
214 -- | A variant of 'try' that takes an exception predicate to select
215 -- which exceptions are caught (c.f. 'catchJust'). If the exception
216 -- does not match the predicate, it is re-thrown.
217 tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
218 tryJust p a = do
219 r <- try a
220 case r of
221 Right v -> return (Right v)
222 Left e -> case p e of
223 Nothing -> throwIO e
224 Just b -> return (Left b)
225
226 -- | Like 'finally', but only performs the final action if there was an
227 -- exception raised by the computation.
228 onException :: IO a -> IO b -> IO a
229 onException io what = io `catch` \e -> do _ <- what
230 throwIO (e :: SomeException)
231
232 -----------------------------------------------------------------------------
233 -- Some Useful Functions
234
235 -- | When you want to acquire a resource, do some work with it, and
236 -- then release the resource, it is a good idea to use 'bracket',
237 -- because 'bracket' will install the necessary exception handler to
238 -- release the resource in the event that an exception is raised
239 -- during the computation. If an exception is raised, then 'bracket' will
240 -- re-raise the exception (after performing the release).
241 --
242 -- A common example is opening a file:
243 --
244 -- > bracket
245 -- > (openFile "filename" ReadMode)
246 -- > (hClose)
247 -- > (\fileHandle -> do { ... })
248 --
249 -- The arguments to 'bracket' are in this order so that we can partially apply
250 -- it, e.g.:
251 --
252 -- > withFile name mode = bracket (openFile name mode) hClose
253 --
254 bracket
255 :: IO a -- ^ computation to run first (\"acquire resource\")
256 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
257 -> (a -> IO c) -- ^ computation to run in-between
258 -> IO c -- returns the value from the in-between computation
259 bracket before after thing =
260 mask $ \restore -> do
261 a <- before
262 r <- restore (thing a) `onException` after a
263 _ <- after a
264 return r
265
266 -- | A specialised variant of 'bracket' with just a computation to run
267 -- afterward.
268 --
269 finally :: IO a -- ^ computation to run first
270 -> IO b -- ^ computation to run afterward (even if an exception
271 -- was raised)
272 -> IO a -- returns the value from the first computation
273 a `finally` sequel =
274 mask $ \restore -> do
275 r <- restore a `onException` sequel
276 _ <- sequel
277 return r
278
279 -- | A variant of 'bracket' where the return value from the first computation
280 -- is not required.
281 bracket_ :: IO a -> IO b -> IO c -> IO c
282 bracket_ before after thing = bracket before (const after) (const thing)
283
284 -- | Like 'bracket', but only performs the final action if there was an
285 -- exception raised by the in-between computation.
286 bracketOnError
287 :: IO a -- ^ computation to run first (\"acquire resource\")
288 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
289 -> (a -> IO c) -- ^ computation to run in-between
290 -> IO c -- returns the value from the in-between computation
291 bracketOnError before after thing =
292 mask $ \restore -> do
293 a <- before
294 restore (thing a) `onException` after a
295
296 -----
297
298 -- |A pattern match failed. The @String@ gives information about the
299 -- source location of the pattern.
300 data PatternMatchFail = PatternMatchFail String
301
302 instance Show PatternMatchFail where
303 showsPrec _ (PatternMatchFail err) = showString err
304
305 instance Exception PatternMatchFail
306
307 -----
308
309 -- |A record selector was applied to a constructor without the
310 -- appropriate field. This can only happen with a datatype with
311 -- multiple constructors, where some fields are in one constructor
312 -- but not another. The @String@ gives information about the source
313 -- location of the record selector.
314 data RecSelError = RecSelError String
315
316 instance Show RecSelError where
317 showsPrec _ (RecSelError err) = showString err
318
319 instance Exception RecSelError
320
321 -----
322
323 -- |An uninitialised record field was used. The @String@ gives
324 -- information about the source location where the record was
325 -- constructed.
326 data RecConError = RecConError String
327
328 instance Show RecConError where
329 showsPrec _ (RecConError err) = showString err
330
331 instance Exception RecConError
332
333 -----
334
335 -- |A record update was performed on a constructor without the
336 -- appropriate field. This can only happen with a datatype with
337 -- multiple constructors, where some fields are in one constructor
338 -- but not another. The @String@ gives information about the source
339 -- location of the record update.
340 data RecUpdError = RecUpdError String
341
342 instance Show RecUpdError where
343 showsPrec _ (RecUpdError err) = showString err
344
345 instance Exception RecUpdError
346
347 -----
348
349 -- |A class method without a definition (neither a default definition,
350 -- nor a definition in the appropriate instance) was called. The
351 -- @String@ gives information about which method it was.
352 data NoMethodError = NoMethodError String
353
354 instance Show NoMethodError where
355 showsPrec _ (NoMethodError err) = showString err
356
357 instance Exception NoMethodError
358
359 -----
360
361 -- |An expression that didn't typecheck during compile time was called.
362 -- This is only possible with -fdefer-type-errors. The @String@ gives
363 -- details about the failed type check.
364 data TypeError = TypeError String
365
366 instance Show TypeError where
367 showsPrec _ (TypeError err) = showString err
368
369 instance Exception TypeError
370
371 -----
372
373 -- |Thrown when the runtime system detects that the computation is
374 -- guaranteed not to terminate. Note that there is no guarantee that
375 -- the runtime system will notice whether any given computation is
376 -- guaranteed to terminate or not.
377 data NonTermination = NonTermination
378
379 instance Show NonTermination where
380 showsPrec _ NonTermination = showString "<<loop>>"
381
382 instance Exception NonTermination
383
384 -----
385
386 -- |Thrown when the program attempts to call @atomically@, from the @stm@
387 -- package, inside another call to @atomically@.
388 data NestedAtomically = NestedAtomically
389
390 instance Show NestedAtomically where
391 showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
392
393 instance Exception NestedAtomically
394
395 -----
396
397 recSelError, recConError, irrefutPatError, runtimeError,
398 nonExhaustiveGuardsError, patError, noMethodBindingError,
399 absentError, typeError
400 :: Addr# -> a -- All take a UTF8-encoded C string
401
402 recSelError s = throw (RecSelError ("No match in record selector "
403 ++ unpackCStringUtf8# s)) -- No location info unfortunately
404 runtimeError s = error (unpackCStringUtf8# s) -- No location info unfortunately
405 absentError s = error ("Oops! Entered absent arg " ++ unpackCStringUtf8# s)
406
407 nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
408 irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
409 recConError s = throw (RecConError (untangle s "Missing field in record construction"))
410 noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
411 patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
412 typeError s = throw (TypeError (unpackCStringUtf8# s))
413
414 -- GHC's RTS calls this
415 nonTermination :: SomeException
416 nonTermination = toException NonTermination
417
418 -- GHC's RTS calls this
419 nestedAtomically :: SomeException
420 nestedAtomically = toException NestedAtomically