2 % (c) The University of Glasgow 2006
3 % (c) The GRASP Project, Glasgow University, 1992-1998
6 Outputable: defines classes for pretty-printing and forcing, both
12 Outputable(..), OutputableBndr(..), -- Class
16 PprStyle, CodeStyle(..), PrintUnqualified, alwaysQualify,
17 getPprStyle, withPprStyle, withPprStyleDoc, pprDeeper, pprSetDepth,
18 codeStyle, userStyle, debugStyle, dumpStyle, asmStyle,
19 ifPprDebug, qualName, qualModule,
20 mkErrStyle, defaultErrStyle, defaultDumpStyle, defaultUserStyle,
24 interppSP, interpp'SP, pprQuotedList, pprWithCommas,
26 text, char, ftext, ptext,
27 int, integer, float, double, rational,
28 parens, cparen, brackets, braces, quotes, doubleQuotes, angleBrackets,
29 semi, comma, colon, dcolon, space, equals, dot, arrow,
30 lparen, rparen, lbrack, rbrack, lbrace, rbrace, underscore,
31 (<>), (<+>), hcat, hsep,
36 speakNth, speakNTimes, speakN, speakNOf, plural,
38 printSDoc, printErrs, printDump,
39 printForC, printForAsm, printForUser,
41 showSDoc, showSDocForUser, showSDocDebug, showSDocDump,
42 showSDocUnqual, showsPrecSDoc,
43 pprHsChar, pprHsString,
46 pprPanic, assertPprPanic, pprPanic#, pprPgmError,
47 pprTrace, warnPprTrace,
48 trace, pgmError, panic, panic#, assertPanic
51 #include "HsVersions.h"
54 import {-# SOURCE #-} Module( Module, modulePackageId,
55 ModuleName, moduleName )
56 import {-# SOURCE #-} OccName( OccName )
58 import StaticFlags ( opt_PprStyle_Debug, opt_PprUserLength )
59 import PackageConfig ( PackageId, packageIdString )
61 import qualified Pretty
62 import Pretty ( Doc, Mode(..) )
65 import Data.Word ( Word32 )
66 import System.IO ( Handle, stderr, stdout, hFlush )
67 import Data.Char ( ord )
71 %************************************************************************
73 \subsection{The @PprStyle@ data type}
75 %************************************************************************
80 = PprUser PrintUnqualified Depth
81 -- Pretty-print in a way that will make sense to the
82 -- ordinary user; must be very close to Haskell
84 -- Assumes printing tidied code: non-system names are
85 -- printed without uniques.
88 -- Print code; either C or assembler
90 | PprDump -- For -ddump-foo; less verbose than PprDebug.
91 -- Does not assume tidied code: non-external names
92 -- are printed with uniques.
94 | PprDebug -- Full debugging output
96 data CodeStyle = CStyle -- The format of labels differs for C and assembler
99 data Depth = AllTheWay
100 | PartWay Int -- 0 => stop
103 -- -----------------------------------------------------------------------------
104 -- Printing original names
106 -- When printing code that contains original names, we need to map the
107 -- original names back to something the user understands. This is the
108 -- purpose of the pair of functions that gets passed around
109 -- when rendering 'SDoc'.
111 -- | given an /original/ name, this function tells you which module
112 -- name it should be qualified with when printing for the user, if
113 -- any. For example, given @Control.Exception.catch@, which is in scope
114 -- as @Exception.catch@, this fuction will return @Just "Exception"@.
115 -- Note that the return value is a ModuleName, not a Module, because
116 -- in source code, names are qualified by ModuleNames.
117 type QualifyName = Module -> OccName -> Maybe ModuleName
119 -- | For a given module, we need to know whether to print it with
120 -- a package name to disambiguate it, and if so which package name should
122 type QualifyModule = Module -> Maybe PackageId
124 type PrintUnqualified = (QualifyName, QualifyModule)
126 alwaysQualifyNames :: QualifyName
127 alwaysQualifyNames m n = Just (moduleName m)
129 neverQualifyNames :: QualifyName
130 neverQualifyNames m n = Nothing
132 alwaysQualifyModules :: QualifyModule
133 alwaysQualifyModules m = Just (modulePackageId m)
135 neverQualifyModules :: QualifyModule
136 neverQualifyModules m = Nothing
138 alwaysQualify = (alwaysQualifyNames, alwaysQualifyModules)
139 neverQualify = (neverQualifyNames, neverQualifyModules)
141 defaultUserStyle = mkUserStyle alwaysQualify AllTheWay
143 defaultDumpStyle | opt_PprStyle_Debug = PprDebug
144 | otherwise = PprDump
146 -- | Style for printing error messages
147 mkErrStyle :: PrintUnqualified -> PprStyle
148 mkErrStyle qual = mkUserStyle qual (PartWay opt_PprUserLength)
150 defaultErrStyle :: PprStyle
151 -- Default style for error messages
152 -- It's a bit of a hack because it doesn't take into account what's in scope
153 -- Only used for desugarer warnings, and typechecker errors in interface sigs
155 | opt_PprStyle_Debug = mkUserStyle alwaysQualify AllTheWay
156 | otherwise = mkUserStyle alwaysQualify (PartWay opt_PprUserLength)
158 mkUserStyle unqual depth
159 | opt_PprStyle_Debug = PprDebug
160 | otherwise = PprUser unqual depth
163 Orthogonal to the above printing styles are (possibly) some
164 command-line flags that affect printing (often carried with the
165 style). The most likely ones are variations on how much type info is
168 The following test decides whether or not we are actually generating
169 code (either C or assembly), or generating interface files.
171 %************************************************************************
173 \subsection{The @SDoc@ data type}
175 %************************************************************************
178 type SDoc = PprStyle -> Doc
180 withPprStyle :: PprStyle -> SDoc -> SDoc
181 withPprStyle sty d sty' = d sty
183 withPprStyleDoc :: PprStyle -> SDoc -> Doc
184 withPprStyleDoc sty d = d sty
186 pprDeeper :: SDoc -> SDoc
187 pprDeeper d (PprUser q (PartWay 0)) = Pretty.text "..."
188 pprDeeper d (PprUser q (PartWay n)) = d (PprUser q (PartWay (n-1)))
189 pprDeeper d other_sty = d other_sty
191 pprSetDepth :: Int -> SDoc -> SDoc
192 pprSetDepth n d (PprUser q _) = d (PprUser q (PartWay n))
193 pprSetDepth n d other_sty = d other_sty
195 getPprStyle :: (PprStyle -> SDoc) -> SDoc
196 getPprStyle df sty = df sty sty
200 qualName :: PprStyle -> QualifyName
201 qualName (PprUser (qual_name,_) _) m n = qual_name m n
202 qualName other m n = Just (moduleName m)
204 qualModule :: PprStyle -> QualifyModule
205 qualModule (PprUser (_,qual_mod) _) m = qual_mod m
206 qualModule other m = Just (modulePackageId m)
208 codeStyle :: PprStyle -> Bool
209 codeStyle (PprCode _) = True
212 asmStyle :: PprStyle -> Bool
213 asmStyle (PprCode AsmStyle) = True
214 asmStyle other = False
216 dumpStyle :: PprStyle -> Bool
217 dumpStyle PprDump = True
218 dumpStyle other = False
220 debugStyle :: PprStyle -> Bool
221 debugStyle PprDebug = True
222 debugStyle other = False
224 userStyle :: PprStyle -> Bool
225 userStyle (PprUser _ _) = True
226 userStyle other = False
228 ifPprDebug :: SDoc -> SDoc -- Empty for non-debug style
229 ifPprDebug d sty@PprDebug = d sty
230 ifPprDebug d sty = Pretty.empty
235 printSDoc :: SDoc -> PprStyle -> IO ()
237 Pretty.printDoc PageMode stdout (d sty)
240 -- I'm not sure whether the direct-IO approach of Pretty.printDoc
241 -- above is better or worse than the put-big-string approach here
242 printErrs :: Doc -> IO ()
243 printErrs doc = do Pretty.printDoc PageMode stderr doc
246 printDump :: SDoc -> IO ()
248 Pretty.printDoc PageMode stdout (better_doc defaultDumpStyle)
251 better_doc = doc $$ text ""
253 printForUser :: Handle -> PrintUnqualified -> SDoc -> IO ()
254 printForUser handle unqual doc
255 = Pretty.printDoc PageMode handle (doc (mkUserStyle unqual AllTheWay))
257 -- printForC, printForAsm do what they sound like
258 printForC :: Handle -> SDoc -> IO ()
259 printForC handle doc = Pretty.printDoc LeftMode handle (doc (PprCode CStyle))
261 printForAsm :: Handle -> SDoc -> IO ()
262 printForAsm handle doc = Pretty.printDoc LeftMode handle (doc (PprCode AsmStyle))
264 pprCode :: CodeStyle -> SDoc -> SDoc
265 pprCode cs d = withPprStyle (PprCode cs) d
267 mkCodeStyle :: CodeStyle -> PprStyle
268 mkCodeStyle = PprCode
270 -- Can't make SDoc an instance of Show because SDoc is just a function type
271 -- However, Doc *is* an instance of Show
272 -- showSDoc just blasts it out as a string
273 showSDoc :: SDoc -> String
274 showSDoc d = show (d defaultUserStyle)
276 showSDocForUser :: PrintUnqualified -> SDoc -> String
277 showSDocForUser unqual doc = show (doc (mkUserStyle unqual AllTheWay))
279 showSDocUnqual :: SDoc -> String
280 -- Only used in the gruesome HsExpr.isOperator
281 showSDocUnqual d = show (d (mkUserStyle neverQualify AllTheWay))
283 showsPrecSDoc :: Int -> SDoc -> ShowS
284 showsPrecSDoc p d = showsPrec p (d defaultUserStyle)
286 showSDocDump :: SDoc -> String
287 showSDocDump d = show (d PprDump)
289 showSDocDebug :: SDoc -> String
290 showSDocDebug d = show (d PprDebug)
294 docToSDoc :: Doc -> SDoc
295 docToSDoc d = \_ -> d
297 empty sty = Pretty.empty
298 text s sty = Pretty.text s
299 char c sty = Pretty.char c
300 ftext s sty = Pretty.ftext s
301 ptext s sty = Pretty.ptext s
302 int n sty = Pretty.int n
303 integer n sty = Pretty.integer n
304 float n sty = Pretty.float n
305 double n sty = Pretty.double n
306 rational n sty = Pretty.rational n
308 parens d sty = Pretty.parens (d sty)
309 braces d sty = Pretty.braces (d sty)
310 brackets d sty = Pretty.brackets (d sty)
311 doubleQuotes d sty = Pretty.doubleQuotes (d sty)
312 angleBrackets d = char '<' <> d <> char '>'
314 cparen b d sty = Pretty.cparen b (d sty)
316 -- quotes encloses something in single quotes...
317 -- but it omits them if the thing ends in a single quote
318 -- so that we don't get `foo''. Instead we just have foo'.
319 quotes d sty = case show pp_d of
321 other -> Pretty.quotes pp_d
325 semi sty = Pretty.semi
326 comma sty = Pretty.comma
327 colon sty = Pretty.colon
328 equals sty = Pretty.equals
329 space sty = Pretty.space
330 lparen sty = Pretty.lparen
331 rparen sty = Pretty.rparen
332 lbrack sty = Pretty.lbrack
333 rbrack sty = Pretty.rbrack
334 lbrace sty = Pretty.lbrace
335 rbrace sty = Pretty.rbrace
336 dcolon sty = Pretty.ptext SLIT("::")
337 arrow sty = Pretty.ptext SLIT("->")
338 underscore = char '_'
341 nest n d sty = Pretty.nest n (d sty)
342 (<>) d1 d2 sty = (Pretty.<>) (d1 sty) (d2 sty)
343 (<+>) d1 d2 sty = (Pretty.<+>) (d1 sty) (d2 sty)
344 ($$) d1 d2 sty = (Pretty.$$) (d1 sty) (d2 sty)
345 ($+$) d1 d2 sty = (Pretty.$+$) (d1 sty) (d2 sty)
347 hcat ds sty = Pretty.hcat [d sty | d <- ds]
348 hsep ds sty = Pretty.hsep [d sty | d <- ds]
349 vcat ds sty = Pretty.vcat [d sty | d <- ds]
350 sep ds sty = Pretty.sep [d sty | d <- ds]
351 cat ds sty = Pretty.cat [d sty | d <- ds]
352 fsep ds sty = Pretty.fsep [d sty | d <- ds]
353 fcat ds sty = Pretty.fcat [d sty | d <- ds]
355 hang d1 n d2 sty = Pretty.hang (d1 sty) n (d2 sty)
357 punctuate :: SDoc -> [SDoc] -> [SDoc]
359 punctuate p (d:ds) = go d ds
362 go d (e:es) = (d <> p) : go e es
366 %************************************************************************
368 \subsection[Outputable-class]{The @Outputable@ class}
370 %************************************************************************
373 class Outputable a where
378 instance Outputable Bool where
379 ppr True = ptext SLIT("True")
380 ppr False = ptext SLIT("False")
382 instance Outputable Int where
385 instance Outputable () where
388 instance (Outputable a) => Outputable [a] where
389 ppr xs = brackets (fsep (punctuate comma (map ppr xs)))
391 instance (Outputable a, Outputable b) => Outputable (a, b) where
392 ppr (x,y) = parens (sep [ppr x <> comma, ppr y])
394 instance Outputable a => Outputable (Maybe a) where
395 ppr Nothing = ptext SLIT("Nothing")
396 ppr (Just x) = ptext SLIT("Just") <+> ppr x
398 -- ToDo: may not be used
399 instance (Outputable a, Outputable b, Outputable c) => Outputable (a, b, c) where
401 parens (sep [ppr x <> comma,
405 instance (Outputable a, Outputable b, Outputable c, Outputable d) =>
406 Outputable (a, b, c, d) where
408 parens (sep [ppr x <> comma,
413 instance Outputable FastString where
414 ppr fs = ftext fs -- Prints an unadorned string,
415 -- no double quotes or anything
417 instance Outputable PackageId where
418 ppr pid = text (packageIdString pid)
422 %************************************************************************
424 \subsection{The @OutputableBndr@ class}
426 %************************************************************************
428 When we print a binder, we often want to print its type too.
429 The @OutputableBndr@ class encapsulates this idea.
431 @BindingSite@ is used to tell the thing that prints binder what
432 language construct is binding the identifier. This can be used
433 to decide how much info to print.
436 data BindingSite = LambdaBind | CaseBind | LetBind
438 class Outputable a => OutputableBndr a where
439 pprBndr :: BindingSite -> a -> SDoc
445 %************************************************************************
447 \subsection{Random printing helpers}
449 %************************************************************************
452 -- We have 31-bit Chars and will simply use Show instances
453 -- of Char and String.
455 pprHsChar :: Char -> SDoc
456 pprHsChar c | c > '\x10ffff' = char '\\' <> text (show (fromIntegral (ord c) :: Word32))
457 | otherwise = text (show c)
459 pprHsString :: FastString -> SDoc
460 pprHsString fs = text (show (unpackFS fs))
464 %************************************************************************
466 \subsection{Other helper functions}
468 %************************************************************************
471 pprWithCommas :: (a -> SDoc) -> [a] -> SDoc
472 pprWithCommas pp xs = fsep (punctuate comma (map pp xs))
474 interppSP :: Outputable a => [a] -> SDoc
475 interppSP xs = sep (map ppr xs)
477 interpp'SP :: Outputable a => [a] -> SDoc
478 interpp'SP xs = sep (punctuate comma (map ppr xs))
480 pprQuotedList :: Outputable a => [a] -> SDoc
481 -- [x,y,z] ==> `x', `y', `z'
482 pprQuotedList xs = hsep (punctuate comma (map (quotes . ppr) xs))
486 %************************************************************************
488 \subsection{Printing numbers verbally}
490 %************************************************************************
492 @speakNth@ converts an integer to a verbal index; eg 1 maps to
496 speakNth :: Int -> SDoc
497 speakNth 1 = ptext SLIT("first")
498 speakNth 2 = ptext SLIT("second")
499 speakNth 3 = ptext SLIT("third")
500 speakNth 4 = ptext SLIT("fourth")
501 speakNth 5 = ptext SLIT("fifth")
502 speakNth 6 = ptext SLIT("sixth")
503 speakNth n = hcat [ int n, text suffix ]
505 suffix | n <= 20 = "th" -- 11,12,13 are non-std
506 | last_dig == 1 = "st"
507 | last_dig == 2 = "nd"
508 | last_dig == 3 = "rd"
511 last_dig = n `rem` 10
513 speakN :: Int -> SDoc
514 speakN 0 = ptext SLIT("none") -- E.g. "he has none"
515 speakN 1 = ptext SLIT("one") -- E.g. "he has one"
516 speakN 2 = ptext SLIT("two")
517 speakN 3 = ptext SLIT("three")
518 speakN 4 = ptext SLIT("four")
519 speakN 5 = ptext SLIT("five")
520 speakN 6 = ptext SLIT("six")
523 speakNOf :: Int -> SDoc -> SDoc
524 speakNOf 0 d = ptext SLIT("no") <+> d <> char 's' -- E.g. "no arguments"
525 speakNOf 1 d = ptext SLIT("one") <+> d -- E.g. "one argument"
526 speakNOf n d = speakN n <+> d <> char 's' -- E.g. "three arguments"
528 speakNTimes :: Int {- >=1 -} -> SDoc
529 speakNTimes t | t == 1 = ptext SLIT("once")
530 | t == 2 = ptext SLIT("twice")
531 | otherwise = speakN t <+> ptext SLIT("times")
538 %************************************************************************
540 \subsection{Error handling}
542 %************************************************************************
545 pprPanic, pprPgmError :: String -> SDoc -> a
546 pprTrace :: String -> SDoc -> a -> a
547 pprPanic = pprAndThen panic -- Throw an exn saying "bug in GHC"
549 pprPgmError = pprAndThen pgmError -- Throw an exn saying "bug in pgm being compiled"
550 -- (used for unusual pgm errors)
551 pprTrace = pprAndThen trace
553 pprPanic# heading pretty_msg = panic# (show (doc PprDebug))
555 doc = text heading <+> pretty_msg
557 pprAndThen :: (String -> a) -> String -> SDoc -> a
558 pprAndThen cont heading pretty_msg = cont (show (doc PprDebug))
560 doc = sep [text heading, nest 4 pretty_msg]
562 assertPprPanic :: String -> Int -> SDoc -> a
563 assertPprPanic file line msg
564 = panic (show (doc PprDebug))
566 doc = sep [hsep[text "ASSERT failed! file",
568 text "line", int line],
571 warnPprTrace :: Bool -> String -> Int -> SDoc -> a -> a
572 warnPprTrace False file line msg x = x
573 warnPprTrace True file line msg x
574 = trace (show (doc PprDebug)) x
576 doc = sep [hsep [text "WARNING: file", text file, text "line", int line],