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