Template Haskell support for TypeApplications
[ghc.git] / libraries / template-haskell / Language / Haskell / TH / Ppr.hs
1 -- | contains a prettyprinter for the
2 -- Template Haskell datatypes
3
4 module Language.Haskell.TH.Ppr where
5 -- All of the exports from this module should
6 -- be "public" functions. The main module TH
7 -- re-exports them all.
8
9 import Text.PrettyPrint (render)
10 import Language.Haskell.TH.PprLib
11 import Language.Haskell.TH.Syntax
12 import Data.Word ( Word8 )
13 import Data.Char ( toLower, chr, ord, isSymbol )
14 import GHC.Show ( showMultiLineString )
15 import Data.Ratio ( numerator, denominator )
16
17 nestDepth :: Int
18 nestDepth = 4
19
20 type Precedence = Int
21 appPrec, unopPrec, opPrec, noPrec :: Precedence
22 appPrec = 3 -- Argument of a function application
23 opPrec = 2 -- Argument of an infix operator
24 unopPrec = 1 -- Argument of an unresolved infix operator
25 noPrec = 0 -- Others
26
27 parensIf :: Bool -> Doc -> Doc
28 parensIf True d = parens d
29 parensIf False d = d
30
31 ------------------------------
32
33 pprint :: Ppr a => a -> String
34 pprint x = render $ to_HPJ_Doc $ ppr x
35
36 class Ppr a where
37 ppr :: a -> Doc
38 ppr_list :: [a] -> Doc
39 ppr_list = vcat . map ppr
40
41 instance Ppr a => Ppr [a] where
42 ppr x = ppr_list x
43
44 ------------------------------
45 instance Ppr Name where
46 ppr v = pprName v
47
48 ------------------------------
49 instance Ppr Info where
50 ppr (TyConI d) = ppr d
51 ppr (ClassI d is) = ppr d $$ vcat (map ppr is)
52 ppr (FamilyI d is) = ppr d $$ vcat (map ppr is)
53 ppr (PrimTyConI name arity is_unlifted)
54 = text "Primitive"
55 <+> (if is_unlifted then text "unlifted" else empty)
56 <+> text "type constructor" <+> quotes (ppr name)
57 <+> parens (text "arity" <+> int arity)
58 ppr (ClassOpI v ty cls)
59 = text "Class op from" <+> ppr cls <> colon <+> ppr_sig v ty
60 ppr (DataConI v ty tc)
61 = text "Constructor from" <+> ppr tc <> colon <+> ppr_sig v ty
62 ppr (PatSynI nm ty) = pprPatSynSig nm ty
63 ppr (TyVarI v ty)
64 = text "Type variable" <+> ppr v <+> equals <+> ppr ty
65 ppr (VarI v ty mb_d)
66 = vcat [ppr_sig v ty,
67 case mb_d of { Nothing -> empty; Just d -> ppr d }]
68
69 ppr_sig :: Name -> Type -> Doc
70 ppr_sig v ty = pprName' Applied v <+> dcolon <+> ppr ty
71
72 pprFixity :: Name -> Fixity -> Doc
73 pprFixity _ f | f == defaultFixity = empty
74 pprFixity v (Fixity i d) = ppr_fix d <+> int i <+> ppr v
75 where ppr_fix InfixR = text "infixr"
76 ppr_fix InfixL = text "infixl"
77 ppr_fix InfixN = text "infix"
78
79 -- | Pretty prints a pattern synonym type signature
80 pprPatSynSig :: Name -> PatSynType -> Doc
81 pprPatSynSig nm ty
82 = text "pattern" <+> pprPrefixOcc nm <+> dcolon <+> pprPatSynType ty
83
84 -- | Pretty prints a pattern synonym's type; follows the usual
85 -- conventions to print a pattern synonym type compactly, yet
86 -- unambiguously. See the note on 'PatSynType' and the section on
87 -- pattern synonyms in the GHC users guide for more information.
88 pprPatSynType :: PatSynType -> Doc
89 pprPatSynType ty@(ForallT uniTys reqs ty'@(ForallT exTys provs ty''))
90 | null exTys, null provs = ppr (ForallT uniTys reqs ty'')
91 | null uniTys, null reqs = noreqs <+> ppr ty'
92 | null reqs = forall uniTys <+> noreqs <+> ppr ty'
93 | otherwise = ppr ty
94 where noreqs = text "() =>"
95 forall tvs = text "forall" <+> (hsep (map ppr tvs)) <+> text "."
96 pprPatSynType ty = ppr ty
97
98 ------------------------------
99 instance Ppr Module where
100 ppr (Module pkg m) = text (pkgString pkg) <+> text (modString m)
101
102 instance Ppr ModuleInfo where
103 ppr (ModuleInfo imps) = text "Module" <+> vcat (map ppr imps)
104
105 ------------------------------
106 instance Ppr Exp where
107 ppr = pprExp noPrec
108
109 pprPrefixOcc :: Name -> Doc
110 -- Print operators with parens around them
111 pprPrefixOcc n = parensIf (isSymOcc n) (ppr n)
112
113 isSymOcc :: Name -> Bool
114 isSymOcc n
115 = case nameBase n of
116 [] -> True -- Empty name; weird
117 (c:_) -> isSymbolASCII c || (ord c > 0x7f && isSymbol c)
118 -- c.f. OccName.startsVarSym in GHC itself
119
120 isSymbolASCII :: Char -> Bool
121 isSymbolASCII c = c `elem` "!#$%&*+./<=>?@\\^|~-"
122
123 pprInfixExp :: Exp -> Doc
124 pprInfixExp (VarE v) = pprName' Infix v
125 pprInfixExp (ConE v) = pprName' Infix v
126 pprInfixExp _ = text "<<Non-variable/constructor in infix context>>"
127
128 pprExp :: Precedence -> Exp -> Doc
129 pprExp _ (VarE v) = pprName' Applied v
130 pprExp _ (ConE c) = pprName' Applied c
131 pprExp i (LitE l) = pprLit i l
132 pprExp i (AppE e1 e2) = parensIf (i >= appPrec) $ pprExp opPrec e1
133 <+> pprExp appPrec e2
134 pprExp i (AppTypeE e t)
135 = parensIf (i >= appPrec) $ pprExp opPrec e <+> char '@' <> pprParendType t
136 pprExp _ (ParensE e) = parens (pprExp noPrec e)
137 pprExp i (UInfixE e1 op e2)
138 = parensIf (i > unopPrec) $ pprExp unopPrec e1
139 <+> pprInfixExp op
140 <+> pprExp unopPrec e2
141 pprExp i (InfixE (Just e1) op (Just e2))
142 = parensIf (i >= opPrec) $ pprExp opPrec e1
143 <+> pprInfixExp op
144 <+> pprExp opPrec e2
145 pprExp _ (InfixE me1 op me2) = parens $ pprMaybeExp noPrec me1
146 <+> pprInfixExp op
147 <+> pprMaybeExp noPrec me2
148 pprExp i (LamE ps e) = parensIf (i > noPrec) $ char '\\' <> hsep (map (pprPat appPrec) ps)
149 <+> text "->" <+> ppr e
150 pprExp i (LamCaseE ms) = parensIf (i > noPrec)
151 $ text "\\case" $$ nest nestDepth (ppr ms)
152 pprExp _ (TupE es) = parens (commaSep es)
153 pprExp _ (UnboxedTupE es) = hashParens (commaSep es)
154 pprExp _ (UnboxedSumE e alt arity) = unboxedSumBars (ppr e) alt arity
155 -- Nesting in Cond is to avoid potential problems in do statments
156 pprExp i (CondE guard true false)
157 = parensIf (i > noPrec) $ sep [text "if" <+> ppr guard,
158 nest 1 $ text "then" <+> ppr true,
159 nest 1 $ text "else" <+> ppr false]
160 pprExp i (MultiIfE alts)
161 = parensIf (i > noPrec) $ vcat $
162 case alts of
163 [] -> [text "if {}"]
164 (alt : alts') -> text "if" <+> pprGuarded arrow alt
165 : map (nest 3 . pprGuarded arrow) alts'
166 pprExp i (LetE ds_ e) = parensIf (i > noPrec) $ text "let" <+> pprDecs ds_
167 $$ text " in" <+> ppr e
168 where
169 pprDecs [] = empty
170 pprDecs [d] = ppr d
171 pprDecs ds = braces (semiSep ds)
172
173 pprExp i (CaseE e ms)
174 = parensIf (i > noPrec) $ text "case" <+> ppr e <+> text "of"
175 $$ nest nestDepth (ppr ms)
176 pprExp i (DoE ss_) = parensIf (i > noPrec) $ text "do" <+> pprStms ss_
177 where
178 pprStms [] = empty
179 pprStms [s] = ppr s
180 pprStms ss = braces (semiSep ss)
181
182 pprExp _ (CompE []) = text "<<Empty CompExp>>"
183 -- This will probably break with fixity declarations - would need a ';'
184 pprExp _ (CompE ss) = text "[" <> ppr s
185 <+> bar
186 <+> commaSep ss'
187 <> text "]"
188 where s = last ss
189 ss' = init ss
190 pprExp _ (ArithSeqE d) = ppr d
191 pprExp _ (ListE es) = brackets (commaSep es)
192 pprExp i (SigE e t) = parensIf (i > noPrec) $ ppr e <+> dcolon <+> ppr t
193 pprExp _ (RecConE nm fs) = ppr nm <> braces (pprFields fs)
194 pprExp _ (RecUpdE e fs) = pprExp appPrec e <> braces (pprFields fs)
195 pprExp i (StaticE e) = parensIf (i >= appPrec) $
196 text "static"<+> pprExp appPrec e
197 pprExp _ (UnboundVarE v) = pprName' Applied v
198
199 pprFields :: [(Name,Exp)] -> Doc
200 pprFields = sep . punctuate comma . map (\(s,e) -> ppr s <+> equals <+> ppr e)
201
202 pprMaybeExp :: Precedence -> Maybe Exp -> Doc
203 pprMaybeExp _ Nothing = empty
204 pprMaybeExp i (Just e) = pprExp i e
205
206 ------------------------------
207 instance Ppr Stmt where
208 ppr (BindS p e) = ppr p <+> text "<-" <+> ppr e
209 ppr (LetS ds) = text "let" <+> (braces (semiSep ds))
210 ppr (NoBindS e) = ppr e
211 ppr (ParS sss) = sep $ punctuate bar
212 $ map commaSep sss
213
214 ------------------------------
215 instance Ppr Match where
216 ppr (Match p rhs ds) = ppr p <+> pprBody False rhs
217 $$ where_clause ds
218
219 ------------------------------
220 pprGuarded :: Doc -> (Guard, Exp) -> Doc
221 pprGuarded eqDoc (guard, expr) = case guard of
222 NormalG guardExpr -> bar <+> ppr guardExpr <+> eqDoc <+> ppr expr
223 PatG stmts -> bar <+> vcat (punctuate comma $ map ppr stmts) $$
224 nest nestDepth (eqDoc <+> ppr expr)
225
226 ------------------------------
227 pprBody :: Bool -> Body -> Doc
228 pprBody eq body = case body of
229 GuardedB xs -> nest nestDepth $ vcat $ map (pprGuarded eqDoc) xs
230 NormalB e -> eqDoc <+> ppr e
231 where eqDoc | eq = equals
232 | otherwise = arrow
233
234 ------------------------------
235 instance Ppr Lit where
236 ppr = pprLit noPrec
237
238 pprLit :: Precedence -> Lit -> Doc
239 pprLit i (IntPrimL x) = parensIf (i > noPrec && x < 0)
240 (integer x <> char '#')
241 pprLit _ (WordPrimL x) = integer x <> text "##"
242 pprLit i (FloatPrimL x) = parensIf (i > noPrec && x < 0)
243 (float (fromRational x) <> char '#')
244 pprLit i (DoublePrimL x) = parensIf (i > noPrec && x < 0)
245 (double (fromRational x) <> text "##")
246 pprLit i (IntegerL x) = parensIf (i > noPrec && x < 0) (integer x)
247 pprLit _ (CharL c) = text (show c)
248 pprLit _ (CharPrimL c) = text (show c) <> char '#'
249 pprLit _ (StringL s) = pprString s
250 pprLit _ (StringPrimL s) = pprString (bytesToString s) <> char '#'
251 pprLit i (RationalL rat) = parensIf (i > noPrec) $
252 integer (numerator rat) <+> char '/'
253 <+> integer (denominator rat)
254
255 bytesToString :: [Word8] -> String
256 bytesToString = map (chr . fromIntegral)
257
258 pprString :: String -> Doc
259 -- Print newlines as newlines with Haskell string escape notation,
260 -- not as '\n'. For other non-printables use regular escape notation.
261 pprString s = vcat (map text (showMultiLineString s))
262
263 ------------------------------
264 instance Ppr Pat where
265 ppr = pprPat noPrec
266
267 pprPat :: Precedence -> Pat -> Doc
268 pprPat i (LitP l) = pprLit i l
269 pprPat _ (VarP v) = pprName' Applied v
270 pprPat _ (TupP ps) = parens (commaSep ps)
271 pprPat _ (UnboxedTupP ps) = hashParens (commaSep ps)
272 pprPat _ (UnboxedSumP p alt arity) = unboxedSumBars (ppr p) alt arity
273 pprPat i (ConP s ps) = parensIf (i >= appPrec) $ pprName' Applied s
274 <+> sep (map (pprPat appPrec) ps)
275 pprPat _ (ParensP p) = parens $ pprPat noPrec p
276 pprPat i (UInfixP p1 n p2)
277 = parensIf (i > unopPrec) (pprPat unopPrec p1 <+>
278 pprName' Infix n <+>
279 pprPat unopPrec p2)
280 pprPat i (InfixP p1 n p2)
281 = parensIf (i >= opPrec) (pprPat opPrec p1 <+>
282 pprName' Infix n <+>
283 pprPat opPrec p2)
284 pprPat i (TildeP p) = parensIf (i > noPrec) $ char '~' <> pprPat appPrec p
285 pprPat i (BangP p) = parensIf (i > noPrec) $ char '!' <> pprPat appPrec p
286 pprPat i (AsP v p) = parensIf (i > noPrec) $ ppr v <> text "@"
287 <> pprPat appPrec p
288 pprPat _ WildP = text "_"
289 pprPat _ (RecP nm fs)
290 = parens $ ppr nm
291 <+> braces (sep $ punctuate comma $
292 map (\(s,p) -> ppr s <+> equals <+> ppr p) fs)
293 pprPat _ (ListP ps) = brackets (commaSep ps)
294 pprPat i (SigP p t) = parensIf (i > noPrec) $ ppr p <+> dcolon <+> ppr t
295 pprPat _ (ViewP e p) = parens $ pprExp noPrec e <+> text "->" <+> pprPat noPrec p
296
297 ------------------------------
298 instance Ppr Dec where
299 ppr = ppr_dec True
300
301 ppr_dec :: Bool -- declaration on the toplevel?
302 -> Dec
303 -> Doc
304 ppr_dec _ (FunD f cs) = vcat $ map (\c -> pprPrefixOcc f <+> ppr c) cs
305 ppr_dec _ (ValD p r ds) = ppr p <+> pprBody True r
306 $$ where_clause ds
307 ppr_dec _ (TySynD t xs rhs)
308 = ppr_tySyn empty t (hsep (map ppr xs)) rhs
309 ppr_dec _ (DataD ctxt t xs ksig cs decs)
310 = ppr_data empty ctxt t (hsep (map ppr xs)) ksig cs decs
311 ppr_dec _ (NewtypeD ctxt t xs ksig c decs)
312 = ppr_newtype empty ctxt t (sep (map ppr xs)) ksig c decs
313 ppr_dec _ (ClassD ctxt c xs fds ds)
314 = text "class" <+> pprCxt ctxt <+> ppr c <+> hsep (map ppr xs) <+> ppr fds
315 $$ where_clause ds
316 ppr_dec _ (InstanceD o ctxt i ds) =
317 text "instance" <+> maybe empty ppr_overlap o <+> pprCxt ctxt <+> ppr i
318 $$ where_clause ds
319 ppr_dec _ (SigD f t) = pprPrefixOcc f <+> dcolon <+> ppr t
320 ppr_dec _ (ForeignD f) = ppr f
321 ppr_dec _ (InfixD fx n) = pprFixity n fx
322 ppr_dec _ (PragmaD p) = ppr p
323 ppr_dec isTop (DataFamilyD tc tvs kind)
324 = text "data" <+> maybeFamily <+> ppr tc <+> hsep (map ppr tvs) <+> maybeKind
325 where
326 maybeFamily | isTop = text "family"
327 | otherwise = empty
328 maybeKind | (Just k') <- kind = dcolon <+> ppr k'
329 | otherwise = empty
330 ppr_dec isTop (DataInstD ctxt tc tys ksig cs decs)
331 = ppr_data maybeInst ctxt tc (sep (map pprParendType tys)) ksig cs decs
332 where
333 maybeInst | isTop = text "instance"
334 | otherwise = empty
335 ppr_dec isTop (NewtypeInstD ctxt tc tys ksig c decs)
336 = ppr_newtype maybeInst ctxt tc (sep (map pprParendType tys)) ksig c decs
337 where
338 maybeInst | isTop = text "instance"
339 | otherwise = empty
340 ppr_dec isTop (TySynInstD tc (TySynEqn tys rhs))
341 = ppr_tySyn maybeInst tc (sep (map pprParendType tys)) rhs
342 where
343 maybeInst | isTop = text "instance"
344 | otherwise = empty
345 ppr_dec isTop (OpenTypeFamilyD tfhead)
346 = text "type" <+> maybeFamily <+> ppr_tf_head tfhead
347 where
348 maybeFamily | isTop = text "family"
349 | otherwise = empty
350 ppr_dec _ (ClosedTypeFamilyD tfhead@(TypeFamilyHead tc _ _ _) eqns)
351 = hang (text "type family" <+> ppr_tf_head tfhead <+> text "where")
352 nestDepth (vcat (map ppr_eqn eqns))
353 where
354 ppr_eqn (TySynEqn lhs rhs)
355 = ppr tc <+> sep (map pprParendType lhs) <+> text "=" <+> ppr rhs
356 ppr_dec _ (RoleAnnotD name roles)
357 = hsep [ text "type role", ppr name ] <+> hsep (map ppr roles)
358 ppr_dec _ (StandaloneDerivD cxt ty)
359 = hsep [ text "deriving instance", pprCxt cxt, ppr ty ]
360 ppr_dec _ (DefaultSigD n ty)
361 = hsep [ text "default", pprPrefixOcc n, dcolon, ppr ty ]
362 ppr_dec _ (PatSynD name args dir pat)
363 = text "pattern" <+> pprNameArgs <+> ppr dir <+> pprPatRHS
364 where
365 pprNameArgs | InfixPatSyn a1 a2 <- args = ppr a1 <+> ppr name <+> ppr a2
366 | otherwise = ppr name <+> ppr args
367 pprPatRHS | ExplBidir cls <- dir = hang (ppr pat <+> text "where")
368 nestDepth (ppr name <+> ppr cls)
369 | otherwise = ppr pat
370 ppr_dec _ (PatSynSigD name ty)
371 = pprPatSynSig name ty
372
373
374 ppr_overlap :: Overlap -> Doc
375 ppr_overlap o = text $
376 case o of
377 Overlaps -> "{-# OVERLAPS #-}"
378 Overlappable -> "{-# OVERLAPPABLE #-}"
379 Overlapping -> "{-# OVERLAPPING #-}"
380 Incoherent -> "{-# INCOHERENT #-}"
381
382 ppr_data :: Doc -> Cxt -> Name -> Doc -> Maybe Kind -> [Con] -> Cxt -> Doc
383 ppr_data maybeInst ctxt t argsDoc ksig cs decs
384 = sep [text "data" <+> maybeInst
385 <+> pprCxt ctxt
386 <+> ppr t <+> argsDoc <+> ksigDoc <+> maybeWhere,
387 nest nestDepth (sep (pref $ map ppr cs)),
388 if null decs
389 then empty
390 else nest nestDepth
391 $ text "deriving" <+> ppr_cxt_preds decs]
392 where
393 pref :: [Doc] -> [Doc]
394 pref xs | isGadtDecl = xs
395 pref [] = [] -- No constructors; can't happen in H98
396 pref (d:ds) = (char '=' <+> d):map (bar <+>) ds
397
398 maybeWhere :: Doc
399 maybeWhere | isGadtDecl = text "where"
400 | otherwise = empty
401
402 isGadtDecl :: Bool
403 isGadtDecl = not (null cs) && all isGadtCon cs
404 where isGadtCon (GadtC _ _ _ ) = True
405 isGadtCon (RecGadtC _ _ _) = True
406 isGadtCon (ForallC _ _ x ) = isGadtCon x
407 isGadtCon _ = False
408
409 ksigDoc = case ksig of
410 Nothing -> empty
411 Just k -> dcolon <+> ppr k
412
413 ppr_newtype :: Doc -> Cxt -> Name -> Doc -> Maybe Kind -> Con -> Cxt -> Doc
414 ppr_newtype maybeInst ctxt t argsDoc ksig c decs
415 = sep [text "newtype" <+> maybeInst
416 <+> pprCxt ctxt
417 <+> ppr t <+> argsDoc <+> ksigDoc,
418 nest 2 (char '=' <+> ppr c),
419 if null decs
420 then empty
421 else nest nestDepth
422 $ text "deriving" <+> ppr_cxt_preds decs]
423 where
424 ksigDoc = case ksig of
425 Nothing -> empty
426 Just k -> dcolon <+> ppr k
427
428 ppr_tySyn :: Doc -> Name -> Doc -> Type -> Doc
429 ppr_tySyn maybeInst t argsDoc rhs
430 = text "type" <+> maybeInst <+> ppr t <+> argsDoc <+> text "=" <+> ppr rhs
431
432 ppr_tf_head :: TypeFamilyHead -> Doc
433 ppr_tf_head (TypeFamilyHead tc tvs res inj)
434 = ppr tc <+> hsep (map ppr tvs) <+> ppr res <+> maybeInj
435 where
436 maybeInj | (Just inj') <- inj = ppr inj'
437 | otherwise = empty
438
439 ------------------------------
440 instance Ppr FunDep where
441 ppr (FunDep xs ys) = hsep (map ppr xs) <+> text "->" <+> hsep (map ppr ys)
442 ppr_list [] = empty
443 ppr_list xs = bar <+> commaSep xs
444
445 ------------------------------
446 instance Ppr FamFlavour where
447 ppr DataFam = text "data"
448 ppr TypeFam = text "type"
449
450 ------------------------------
451 instance Ppr FamilyResultSig where
452 ppr NoSig = empty
453 ppr (KindSig k) = dcolon <+> ppr k
454 ppr (TyVarSig bndr) = text "=" <+> ppr bndr
455
456 ------------------------------
457 instance Ppr InjectivityAnn where
458 ppr (InjectivityAnn lhs rhs) =
459 bar <+> ppr lhs <+> text "->" <+> hsep (map ppr rhs)
460
461 ------------------------------
462 instance Ppr Foreign where
463 ppr (ImportF callconv safety impent as typ)
464 = text "foreign import"
465 <+> showtextl callconv
466 <+> showtextl safety
467 <+> text (show impent)
468 <+> ppr as
469 <+> dcolon <+> ppr typ
470 ppr (ExportF callconv expent as typ)
471 = text "foreign export"
472 <+> showtextl callconv
473 <+> text (show expent)
474 <+> ppr as
475 <+> dcolon <+> ppr typ
476
477 ------------------------------
478 instance Ppr Pragma where
479 ppr (InlineP n inline rm phases)
480 = text "{-#"
481 <+> ppr inline
482 <+> ppr rm
483 <+> ppr phases
484 <+> ppr n
485 <+> text "#-}"
486 ppr (SpecialiseP n ty inline phases)
487 = text "{-# SPECIALISE"
488 <+> maybe empty ppr inline
489 <+> ppr phases
490 <+> sep [ ppr n <+> dcolon
491 , nest 2 $ ppr ty ]
492 <+> text "#-}"
493 ppr (SpecialiseInstP inst)
494 = text "{-# SPECIALISE instance" <+> ppr inst <+> text "#-}"
495 ppr (RuleP n bndrs lhs rhs phases)
496 = sep [ text "{-# RULES" <+> pprString n <+> ppr phases
497 , nest 4 $ ppr_forall <+> ppr lhs
498 , nest 4 $ char '=' <+> ppr rhs <+> text "#-}" ]
499 where ppr_forall | null bndrs = empty
500 | otherwise = text "forall"
501 <+> fsep (map ppr bndrs)
502 <+> char '.'
503 ppr (AnnP tgt expr)
504 = text "{-# ANN" <+> target1 tgt <+> ppr expr <+> text "#-}"
505 where target1 ModuleAnnotation = text "module"
506 target1 (TypeAnnotation t) = text "type" <+> ppr t
507 target1 (ValueAnnotation v) = ppr v
508 ppr (LineP line file)
509 = text "{-# LINE" <+> int line <+> text (show file) <+> text "#-}"
510
511 ------------------------------
512 instance Ppr Inline where
513 ppr NoInline = text "NOINLINE"
514 ppr Inline = text "INLINE"
515 ppr Inlinable = text "INLINABLE"
516
517 ------------------------------
518 instance Ppr RuleMatch where
519 ppr ConLike = text "CONLIKE"
520 ppr FunLike = empty
521
522 ------------------------------
523 instance Ppr Phases where
524 ppr AllPhases = empty
525 ppr (FromPhase i) = brackets $ int i
526 ppr (BeforePhase i) = brackets $ char '~' <> int i
527
528 ------------------------------
529 instance Ppr RuleBndr where
530 ppr (RuleVar n) = ppr n
531 ppr (TypedRuleVar n ty) = parens $ ppr n <+> dcolon <+> ppr ty
532
533 ------------------------------
534 instance Ppr Clause where
535 ppr (Clause ps rhs ds) = hsep (map (pprPat appPrec) ps) <+> pprBody True rhs
536 $$ where_clause ds
537
538 ------------------------------
539 instance Ppr Con where
540 ppr (NormalC c sts) = ppr c <+> sep (map pprBangType sts)
541
542 ppr (RecC c vsts)
543 = ppr c <+> braces (sep (punctuate comma $ map pprVarBangType vsts))
544
545 ppr (InfixC st1 c st2) = pprBangType st1
546 <+> pprName' Infix c
547 <+> pprBangType st2
548
549 ppr (ForallC ns ctxt (GadtC c sts ty))
550 = commaSepApplied c <+> dcolon <+> pprForall ns ctxt
551 <+> pprGadtRHS sts ty
552
553 ppr (ForallC ns ctxt (RecGadtC c vsts ty))
554 = commaSepApplied c <+> dcolon <+> pprForall ns ctxt
555 <+> pprRecFields vsts ty
556
557 ppr (ForallC ns ctxt con)
558 = pprForall ns ctxt <+> ppr con
559
560 ppr (GadtC c sts ty)
561 = commaSepApplied c <+> dcolon <+> pprGadtRHS sts ty
562
563 ppr (RecGadtC c vsts ty)
564 = commaSepApplied c <+> dcolon <+> pprRecFields vsts ty
565
566 instance Ppr PatSynDir where
567 ppr Unidir = text "<-"
568 ppr ImplBidir = text "="
569 ppr (ExplBidir _) = text "<-"
570 -- the ExplBidir's clauses are pretty printed together with the
571 -- entire pattern synonym; so only print the direction here.
572
573 instance Ppr PatSynArgs where
574 ppr (PrefixPatSyn args) = sep $ map ppr args
575 ppr (InfixPatSyn a1 a2) = ppr a1 <+> ppr a2
576 ppr (RecordPatSyn sels) = braces $ sep (punctuate comma (map ppr sels))
577
578 commaSepApplied :: [Name] -> Doc
579 commaSepApplied = commaSepWith (pprName' Applied)
580
581 pprForall :: [TyVarBndr] -> Cxt -> Doc
582 pprForall tvs cxt
583 -- even in the case without any tvs, there could be a non-empty
584 -- context cxt (e.g., in the case of pattern synonyms, where there
585 -- are multiple forall binders and contexts).
586 | [] <- tvs = pprCxt cxt
587 | otherwise = text "forall" <+> hsep (map ppr tvs) <+> char '.' <+> pprCxt cxt
588
589 pprRecFields :: [(Name, Strict, Type)] -> Type -> Doc
590 pprRecFields vsts ty
591 = braces (sep (punctuate comma $ map pprVarBangType vsts))
592 <+> arrow <+> ppr ty
593
594 pprGadtRHS :: [(Strict, Type)] -> Type -> Doc
595 pprGadtRHS [] ty
596 = ppr ty
597 pprGadtRHS sts ty
598 = sep (punctuate (space <> arrow) (map pprBangType sts))
599 <+> arrow <+> ppr ty
600
601 ------------------------------
602 pprVarBangType :: VarBangType -> Doc
603 -- Slight infelicity: with print non-atomic type with parens
604 pprVarBangType (v, bang, t) = ppr v <+> dcolon <+> pprBangType (bang, t)
605
606 ------------------------------
607 pprBangType :: BangType -> Doc
608 -- Make sure we print
609 --
610 -- Con {-# UNPACK #-} a
611 --
612 -- rather than
613 --
614 -- Con {-# UNPACK #-}a
615 --
616 -- when there's no strictness annotation. If there is a strictness annotation,
617 -- it's okay to not put a space between it and the type.
618 pprBangType (bt@(Bang _ NoSourceStrictness), t) = ppr bt <+> pprParendType t
619 pprBangType (bt, t) = ppr bt <> pprParendType t
620
621 ------------------------------
622 instance Ppr Bang where
623 ppr (Bang su ss) = ppr su <+> ppr ss
624
625 ------------------------------
626 instance Ppr SourceUnpackedness where
627 ppr NoSourceUnpackedness = empty
628 ppr SourceNoUnpack = text "{-# NOUNPACK #-}"
629 ppr SourceUnpack = text "{-# UNPACK #-}"
630
631 ------------------------------
632 instance Ppr SourceStrictness where
633 ppr NoSourceStrictness = empty
634 ppr SourceLazy = char '~'
635 ppr SourceStrict = char '!'
636
637 ------------------------------
638 instance Ppr DecidedStrictness where
639 ppr DecidedLazy = empty
640 ppr DecidedStrict = char '!'
641 ppr DecidedUnpack = text "{-# UNPACK #-} !"
642
643 ------------------------------
644 {-# DEPRECATED pprVarStrictType
645 "As of @template-haskell-2.11.0.0@, 'VarStrictType' has been replaced by 'VarBangType'. Please use 'pprVarBangType' instead." #-}
646 pprVarStrictType :: (Name, Strict, Type) -> Doc
647 pprVarStrictType = pprVarBangType
648
649 ------------------------------
650 {-# DEPRECATED pprStrictType
651 "As of @template-haskell-2.11.0.0@, 'StrictType' has been replaced by 'BangType'. Please use 'pprBangType' instead." #-}
652 pprStrictType :: (Strict, Type) -> Doc
653 pprStrictType = pprBangType
654
655 ------------------------------
656 pprParendType :: Type -> Doc
657 pprParendType (VarT v) = ppr v
658 pprParendType (ConT c) = ppr c
659 pprParendType (TupleT 0) = text "()"
660 pprParendType (TupleT n) = parens (hcat (replicate (n-1) comma))
661 pprParendType (UnboxedTupleT n) = hashParens $ hcat $ replicate (n-1) comma
662 pprParendType (UnboxedSumT arity) = hashParens $ hcat $ replicate (arity-1) bar
663 pprParendType ArrowT = parens (text "->")
664 pprParendType ListT = text "[]"
665 pprParendType (LitT l) = pprTyLit l
666 pprParendType (PromotedT c) = text "'" <> ppr c
667 pprParendType (PromotedTupleT 0) = text "'()"
668 pprParendType (PromotedTupleT n) = quoteParens (hcat (replicate (n-1) comma))
669 pprParendType PromotedNilT = text "'[]"
670 pprParendType PromotedConsT = text "(':)"
671 pprParendType StarT = char '*'
672 pprParendType ConstraintT = text "Constraint"
673 pprParendType (SigT ty k) = parens (ppr ty <+> text "::" <+> ppr k)
674 pprParendType WildCardT = char '_'
675 pprParendType (InfixT x n y) = parens (ppr x <+> pprName' Infix n <+> ppr y)
676 pprParendType t@(UInfixT {}) = parens (pprUInfixT t)
677 pprParendType (ParensT t) = ppr t
678 pprParendType tuple | (TupleT n, args) <- split tuple
679 , length args == n
680 = parens (commaSep args)
681 pprParendType other = parens (ppr other)
682
683 pprUInfixT :: Type -> Doc
684 pprUInfixT (UInfixT x n y) = pprUInfixT x <+> pprName' Infix n <+> pprUInfixT y
685 pprUInfixT t = ppr t
686
687 instance Ppr Type where
688 ppr (ForallT tvars ctxt ty) = sep [pprForall tvars ctxt, ppr ty]
689 ppr ty = pprTyApp (split ty)
690 -- Works, in a degnerate way, for SigT, and puts parens round (ty :: kind)
691 -- See Note [Pretty-printing kind signatures]
692
693 {- Note [Pretty-printing kind signatures]
694 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
695 GHC's parser only recognises a kind signature in a type when there are
696 parens around it. E.g. the parens are required here:
697 f :: (Int :: *)
698 type instance F Int = (Bool :: *)
699 So we always print a SigT with parens (see Trac #10050). -}
700
701 pprTyApp :: (Type, [Type]) -> Doc
702 pprTyApp (ArrowT, [arg1,arg2]) = sep [pprFunArgType arg1 <+> text "->", ppr arg2]
703 pprTyApp (EqualityT, [arg1, arg2]) =
704 sep [pprFunArgType arg1 <+> text "~", ppr arg2]
705 pprTyApp (ListT, [arg]) = brackets (ppr arg)
706 pprTyApp (TupleT n, args)
707 | length args == n = parens (commaSep args)
708 pprTyApp (PromotedTupleT n, args)
709 | length args == n = quoteParens (commaSep args)
710 pprTyApp (fun, args) = pprParendType fun <+> sep (map pprParendType args)
711
712 pprFunArgType :: Type -> Doc -- Should really use a precedence argument
713 -- Everything except forall and (->) binds more tightly than (->)
714 pprFunArgType ty@(ForallT {}) = parens (ppr ty)
715 pprFunArgType ty@((ArrowT `AppT` _) `AppT` _) = parens (ppr ty)
716 pprFunArgType ty@(SigT _ _) = parens (ppr ty)
717 pprFunArgType ty = ppr ty
718
719 split :: Type -> (Type, [Type]) -- Split into function and args
720 split t = go t []
721 where go (AppT t1 t2) args = go t1 (t2:args)
722 go ty args = (ty, args)
723
724 pprTyLit :: TyLit -> Doc
725 pprTyLit (NumTyLit n) = integer n
726 pprTyLit (StrTyLit s) = text (show s)
727
728 instance Ppr TyLit where
729 ppr = pprTyLit
730
731 ------------------------------
732 instance Ppr TyVarBndr where
733 ppr (PlainTV nm) = ppr nm
734 ppr (KindedTV nm k) = parens (ppr nm <+> dcolon <+> ppr k)
735
736 instance Ppr Role where
737 ppr NominalR = text "nominal"
738 ppr RepresentationalR = text "representational"
739 ppr PhantomR = text "phantom"
740 ppr InferR = text "_"
741
742 ------------------------------
743 pprCxt :: Cxt -> Doc
744 pprCxt [] = empty
745 pprCxt ts = ppr_cxt_preds ts <+> text "=>"
746
747 ppr_cxt_preds :: Cxt -> Doc
748 ppr_cxt_preds [] = empty
749 ppr_cxt_preds [t] = ppr t
750 ppr_cxt_preds ts = parens (commaSep ts)
751
752 ------------------------------
753 instance Ppr Range where
754 ppr = brackets . pprRange
755 where pprRange :: Range -> Doc
756 pprRange (FromR e) = ppr e <> text ".."
757 pprRange (FromThenR e1 e2) = ppr e1 <> text ","
758 <> ppr e2 <> text ".."
759 pprRange (FromToR e1 e2) = ppr e1 <> text ".." <> ppr e2
760 pprRange (FromThenToR e1 e2 e3) = ppr e1 <> text ","
761 <> ppr e2 <> text ".."
762 <> ppr e3
763
764 ------------------------------
765 where_clause :: [Dec] -> Doc
766 where_clause [] = empty
767 where_clause ds = nest nestDepth $ text "where" <+> vcat (map (ppr_dec False) ds)
768
769 showtextl :: Show a => a -> Doc
770 showtextl = text . map toLower . show
771
772 hashParens :: Doc -> Doc
773 hashParens d = text "(# " <> d <> text " #)"
774
775 quoteParens :: Doc -> Doc
776 quoteParens d = text "'(" <> d <> text ")"
777
778 -----------------------------
779 instance Ppr Loc where
780 ppr (Loc { loc_module = md
781 , loc_package = pkg
782 , loc_start = (start_ln, start_col)
783 , loc_end = (end_ln, end_col) })
784 = hcat [ text pkg, colon, text md, colon
785 , parens $ int start_ln <> comma <> int start_col
786 , text "-"
787 , parens $ int end_ln <> comma <> int end_col ]
788
789 -- Takes a list of printable things and prints them separated by commas followed
790 -- by space.
791 commaSep :: Ppr a => [a] -> Doc
792 commaSep = commaSepWith ppr
793
794 -- Takes a list of things and prints them with the given pretty-printing
795 -- function, separated by commas followed by space.
796 commaSepWith :: (a -> Doc) -> [a] -> Doc
797 commaSepWith pprFun = sep . punctuate comma . map pprFun
798
799 -- Takes a list of printable things and prints them separated by semicolons
800 -- followed by space.
801 semiSep :: Ppr a => [a] -> Doc
802 semiSep = sep . punctuate semi . map ppr
803
804 -- Prints out the series of vertical bars that wraps an expression or pattern
805 -- used in an unboxed sum.
806 unboxedSumBars :: Doc -> SumAlt -> SumArity -> Doc
807 unboxedSumBars d alt arity = hashParens $
808 bars (alt-1) <> d <> bars (arity - alt)
809 where
810 bars i = hsep (replicate i bar)
811
812 -- Text containing the vertical bar character.
813 bar :: Doc
814 bar = char '|'