[project @ 2005-02-02 15:28:49 by simonmar]
[ghc-base.git] / Debug / Trace.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Debug.Trace
4 -- Copyright   :  (c) The University of Glasgow 2001
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  provisional
9 -- Portability :  portable
10 --
11 -- The 'trace' function.
12 --
13 -----------------------------------------------------------------------------
14
15 module Debug.Trace (
16         -- * Tracing
17         putTraceMsg,      -- :: String -> IO ()
18         trace             -- :: String -> a -> a
19   ) where
20
21 import Prelude
22 import System.IO.Unsafe
23
24 #ifdef __GLASGOW_HASKELL__
25 import Foreign.C.String
26 #else
27 import System.IO (hPutStrLn,stderr)
28 #endif
29
30 -- | 'putTraceMsg' function outputs the trace message from IO monad.
31 -- Usually the output stream is 'System.IO.stderr' but if the function is called
32 -- from Windows GUI application then the output will be directed to the Windows
33 -- debug console.
34 putTraceMsg :: String -> IO ()
35 putTraceMsg msg = do
36 #ifndef __GLASGOW_HASKELL__
37     hPutStrLn stderr msg
38 #else
39     withCString "%s\n" $ \cfmt ->
40      withCString msg  $ \cmsg ->
41       debugBelch cfmt cmsg
42
43 foreign import ccall unsafe debugBelch :: CString -> CString -> IO ()
44 #endif
45
46 {-# NOINLINE trace #-}
47 {-|
48 When called, 'trace' outputs the string in its first argument, before 
49 returning the second argument as its result. The 'trace' function is not 
50 referentially transparent, and should only be used for debugging, or for 
51 monitoring execution. Some implementations of 'trace' may decorate the string 
52 that\'s output to indicate that you\'re tracing. The function is implemented on
53 top of 'putTraceMsg'.
54 -}
55 trace :: String -> a -> a
56 trace string expr = unsafePerformIO $ do
57     putTraceMsg string
58     return expr