2 % (c) The GRASP Project, Glasgow University, 1992-1998
4 \section[Outputable]{Classes for pretty-printing}
6 Defines classes for pretty-printing and forcing, both forms of
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, 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 )
67 import IO ( Handle, stderr, stdout, hFlush )
72 %************************************************************************
74 \subsection{The @PprStyle@ data type}
76 %************************************************************************
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 -- quotes encloses something in single quotes...
315 -- but it omits them if the thing ends in a single quote
316 -- so that we don't get `foo''. Instead we just have foo'.
317 quotes d sty = case show pp_d of
319 other -> Pretty.quotes pp_d
323 semi sty = Pretty.semi
324 comma sty = Pretty.comma
325 colon sty = Pretty.colon
326 equals sty = Pretty.equals
327 space sty = Pretty.space
328 lparen sty = Pretty.lparen
329 rparen sty = Pretty.rparen
330 lbrack sty = Pretty.lbrack
331 rbrack sty = Pretty.rbrack
332 lbrace sty = Pretty.lbrace
333 rbrace sty = Pretty.rbrace
334 dcolon sty = Pretty.ptext SLIT("::")
335 arrow sty = Pretty.ptext SLIT("->")
336 underscore = char '_'
339 nest n d sty = Pretty.nest n (d sty)
340 (<>) d1 d2 sty = (Pretty.<>) (d1 sty) (d2 sty)
341 (<+>) d1 d2 sty = (Pretty.<+>) (d1 sty) (d2 sty)
342 ($$) d1 d2 sty = (Pretty.$$) (d1 sty) (d2 sty)
343 ($+$) d1 d2 sty = (Pretty.$+$) (d1 sty) (d2 sty)
345 hcat ds sty = Pretty.hcat [d sty | d <- ds]
346 hsep ds sty = Pretty.hsep [d sty | d <- ds]
347 vcat ds sty = Pretty.vcat [d sty | d <- ds]
348 sep ds sty = Pretty.sep [d sty | d <- ds]
349 cat ds sty = Pretty.cat [d sty | d <- ds]
350 fsep ds sty = Pretty.fsep [d sty | d <- ds]
351 fcat ds sty = Pretty.fcat [d sty | d <- ds]
353 hang d1 n d2 sty = Pretty.hang (d1 sty) n (d2 sty)
355 punctuate :: SDoc -> [SDoc] -> [SDoc]
357 punctuate p (d:ds) = go d ds
360 go d (e:es) = (d <> p) : go e es
364 %************************************************************************
366 \subsection[Outputable-class]{The @Outputable@ class}
368 %************************************************************************
371 class Outputable a where
376 instance Outputable Bool where
377 ppr True = ptext SLIT("True")
378 ppr False = ptext SLIT("False")
380 instance Outputable Int where
383 instance Outputable () where
386 instance (Outputable a) => Outputable [a] where
387 ppr xs = brackets (fsep (punctuate comma (map ppr xs)))
389 instance (Outputable a, Outputable b) => Outputable (a, b) where
390 ppr (x,y) = parens (sep [ppr x <> comma, ppr y])
392 instance Outputable a => Outputable (Maybe a) where
393 ppr Nothing = ptext SLIT("Nothing")
394 ppr (Just x) = ptext SLIT("Just") <+> ppr x
396 -- ToDo: may not be used
397 instance (Outputable a, Outputable b, Outputable c) => Outputable (a, b, c) where
399 parens (sep [ppr x <> comma,
403 instance (Outputable a, Outputable b, Outputable c, Outputable d) =>
404 Outputable (a, b, c, d) where
406 parens (sep [ppr x <> comma,
411 instance Outputable FastString where
412 ppr fs = ftext fs -- Prints an unadorned string,
413 -- no double quotes or anything
415 instance Outputable PackageId where
416 ppr pid = text (packageIdString pid)
420 %************************************************************************
422 \subsection{The @OutputableBndr@ class}
424 %************************************************************************
426 When we print a binder, we often want to print its type too.
427 The @OutputableBndr@ class encapsulates this idea.
429 @BindingSite@ is used to tell the thing that prints binder what
430 language construct is binding the identifier. This can be used
431 to decide how much info to print.
434 data BindingSite = LambdaBind | CaseBind | LetBind
436 class Outputable a => OutputableBndr a where
437 pprBndr :: BindingSite -> a -> SDoc
443 %************************************************************************
445 \subsection{Random printing helpers}
447 %************************************************************************
450 -- We have 31-bit Chars and will simply use Show instances
451 -- of Char and String.
453 pprHsChar :: Char -> SDoc
454 pprHsChar c | c > '\x10ffff' = char '\\' <> text (show (fromIntegral (ord c) :: Word32))
455 | otherwise = text (show c)
457 pprHsString :: FastString -> SDoc
458 pprHsString fs = text (show (unpackFS fs))
462 %************************************************************************
464 \subsection{Other helper functions}
466 %************************************************************************
469 pprWithCommas :: (a -> SDoc) -> [a] -> SDoc
470 pprWithCommas pp xs = fsep (punctuate comma (map pp xs))
472 interppSP :: Outputable a => [a] -> SDoc
473 interppSP xs = sep (map ppr xs)
475 interpp'SP :: Outputable a => [a] -> SDoc
476 interpp'SP xs = sep (punctuate comma (map ppr xs))
478 pprQuotedList :: Outputable a => [a] -> SDoc
479 -- [x,y,z] ==> `x', `y', `z'
480 pprQuotedList xs = hsep (punctuate comma (map (quotes . ppr) xs))
484 %************************************************************************
486 \subsection{Printing numbers verbally}
488 %************************************************************************
490 @speakNth@ converts an integer to a verbal index; eg 1 maps to
494 speakNth :: Int -> SDoc
495 speakNth 1 = ptext SLIT("first")
496 speakNth 2 = ptext SLIT("second")
497 speakNth 3 = ptext SLIT("third")
498 speakNth 4 = ptext SLIT("fourth")
499 speakNth 5 = ptext SLIT("fifth")
500 speakNth 6 = ptext SLIT("sixth")
501 speakNth n = hcat [ int n, text suffix ]
503 suffix | n <= 20 = "th" -- 11,12,13 are non-std
504 | last_dig == 1 = "st"
505 | last_dig == 2 = "nd"
506 | last_dig == 3 = "rd"
509 last_dig = n `rem` 10
511 speakN :: Int -> SDoc
512 speakN 0 = ptext SLIT("none") -- E.g. "he has none"
513 speakN 1 = ptext SLIT("one") -- E.g. "he has one"
514 speakN 2 = ptext SLIT("two")
515 speakN 3 = ptext SLIT("three")
516 speakN 4 = ptext SLIT("four")
517 speakN 5 = ptext SLIT("five")
518 speakN 6 = ptext SLIT("six")
521 speakNOf :: Int -> SDoc -> SDoc
522 speakNOf 0 d = ptext SLIT("no") <+> d <> char 's' -- E.g. "no arguments"
523 speakNOf 1 d = ptext SLIT("one") <+> d -- E.g. "one argument"
524 speakNOf n d = speakN n <+> d <> char 's' -- E.g. "three arguments"
526 speakNTimes :: Int {- >=1 -} -> SDoc
527 speakNTimes t | t == 1 = ptext SLIT("once")
528 | t == 2 = ptext SLIT("twice")
529 | otherwise = speakN t <+> ptext SLIT("times")
536 %************************************************************************
538 \subsection{Error handling}
540 %************************************************************************
543 pprPanic, pprPgmError :: String -> SDoc -> a
544 pprTrace :: String -> SDoc -> a -> a
545 pprPanic = pprAndThen panic -- Throw an exn saying "bug in GHC"
547 pprPgmError = pprAndThen pgmError -- Throw an exn saying "bug in pgm being compiled"
548 -- (used for unusual pgm errors)
549 pprTrace = pprAndThen trace
551 pprPanic# heading pretty_msg = panic# (show (doc PprDebug))
553 doc = text heading <+> pretty_msg
555 pprAndThen :: (String -> a) -> String -> SDoc -> a
556 pprAndThen cont heading pretty_msg = cont (show (doc PprDebug))
558 doc = sep [text heading, nest 4 pretty_msg]
560 assertPprPanic :: String -> Int -> SDoc -> a
561 assertPprPanic file line msg
562 = panic (show (doc PprDebug))
564 doc = sep [hsep[text "ASSERT failed! file",
566 text "line", int line],
569 warnPprTrace :: Bool -> String -> Int -> SDoc -> a -> a
570 warnPprTrace False file line msg x = x
571 warnPprTrace True file line msg x
572 = trace (show (doc PprDebug)) x
574 doc = sep [hsep [text "WARNING: file", text file, text "line", int line],