Fix TH ppr output for list comprehensions with only one Stmt
[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 cxt ty)
362 = hsep [ text "deriving instance", pprCxt cxt, ppr ty ]
363 ppr_dec _ (DefaultSigD n ty)
364 = hsep [ text "default", pprPrefixOcc n, dcolon, ppr ty ]
365 ppr_dec _ (PatSynD name args dir pat)
366 = text "pattern" <+> pprNameArgs <+> ppr dir <+> pprPatRHS
367 where
368 pprNameArgs | InfixPatSyn a1 a2 <- args = ppr a1 <+> ppr name <+> ppr a2
369 | otherwise = ppr name <+> ppr args
370 pprPatRHS | ExplBidir cls <- dir = hang (ppr pat <+> text "where")
371 nestDepth (ppr name <+> ppr cls)
372 | otherwise = ppr pat
373 ppr_dec _ (PatSynSigD name ty)
374 = pprPatSynSig name ty
375
376
377 ppr_overlap :: Overlap -> Doc
378 ppr_overlap o = text $
379 case o of
380 Overlaps -> "{-# OVERLAPS #-}"
381 Overlappable -> "{-# OVERLAPPABLE #-}"
382 Overlapping -> "{-# OVERLAPPING #-}"
383 Incoherent -> "{-# INCOHERENT #-}"
384
385 ppr_data :: Doc -> Cxt -> Name -> Doc -> Maybe Kind -> [Con] -> Cxt -> Doc
386 ppr_data maybeInst ctxt t argsDoc ksig cs decs
387 = sep [text "data" <+> maybeInst
388 <+> pprCxt ctxt
389 <+> ppr t <+> argsDoc <+> ksigDoc <+> maybeWhere,
390 nest nestDepth (sep (pref $ map ppr cs)),
391 if null decs
392 then empty
393 else nest nestDepth
394 $ text "deriving" <+> ppr_cxt_preds decs]
395 where
396 pref :: [Doc] -> [Doc]
397 pref xs | isGadtDecl = xs
398 pref [] = [] -- No constructors; can't happen in H98
399 pref (d:ds) = (char '=' <+> d):map (bar <+>) ds
400
401 maybeWhere :: Doc
402 maybeWhere | isGadtDecl = text "where"
403 | otherwise = empty
404
405 isGadtDecl :: Bool
406 isGadtDecl = not (null cs) && all isGadtCon cs
407 where isGadtCon (GadtC _ _ _ ) = True
408 isGadtCon (RecGadtC _ _ _) = True
409 isGadtCon (ForallC _ _ x ) = isGadtCon x
410 isGadtCon _ = False
411
412 ksigDoc = case ksig of
413 Nothing -> empty
414 Just k -> dcolon <+> ppr k
415
416 ppr_newtype :: Doc -> Cxt -> Name -> Doc -> Maybe Kind -> Con -> Cxt -> Doc
417 ppr_newtype maybeInst ctxt t argsDoc ksig c decs
418 = sep [text "newtype" <+> maybeInst
419 <+> pprCxt ctxt
420 <+> ppr t <+> argsDoc <+> ksigDoc,
421 nest 2 (char '=' <+> ppr c),
422 if null decs
423 then empty
424 else nest nestDepth
425 $ text "deriving" <+> ppr_cxt_preds decs]
426 where
427 ksigDoc = case ksig of
428 Nothing -> empty
429 Just k -> dcolon <+> ppr k
430
431 ppr_tySyn :: Doc -> Name -> Doc -> Type -> Doc
432 ppr_tySyn maybeInst t argsDoc rhs
433 = text "type" <+> maybeInst <+> ppr t <+> argsDoc <+> text "=" <+> ppr rhs
434
435 ppr_tf_head :: TypeFamilyHead -> Doc
436 ppr_tf_head (TypeFamilyHead tc tvs res inj)
437 = ppr tc <+> hsep (map ppr tvs) <+> ppr res <+> maybeInj
438 where
439 maybeInj | (Just inj') <- inj = ppr inj'
440 | otherwise = empty
441
442 ------------------------------
443 instance Ppr FunDep where
444 ppr (FunDep xs ys) = hsep (map ppr xs) <+> text "->" <+> hsep (map ppr ys)
445 ppr_list [] = empty
446 ppr_list xs = bar <+> commaSep xs
447
448 ------------------------------
449 instance Ppr FamFlavour where
450 ppr DataFam = text "data"
451 ppr TypeFam = text "type"
452
453 ------------------------------
454 instance Ppr FamilyResultSig where
455 ppr NoSig = empty
456 ppr (KindSig k) = dcolon <+> ppr k
457 ppr (TyVarSig bndr) = text "=" <+> ppr bndr
458
459 ------------------------------
460 instance Ppr InjectivityAnn where
461 ppr (InjectivityAnn lhs rhs) =
462 bar <+> ppr lhs <+> text "->" <+> hsep (map ppr rhs)
463
464 ------------------------------
465 instance Ppr Foreign where
466 ppr (ImportF callconv safety impent as typ)
467 = text "foreign import"
468 <+> showtextl callconv
469 <+> showtextl safety
470 <+> text (show impent)
471 <+> ppr as
472 <+> dcolon <+> ppr typ
473 ppr (ExportF callconv expent as typ)
474 = text "foreign export"
475 <+> showtextl callconv
476 <+> text (show expent)
477 <+> ppr as
478 <+> dcolon <+> ppr typ
479
480 ------------------------------
481 instance Ppr Pragma where
482 ppr (InlineP n inline rm phases)
483 = text "{-#"
484 <+> ppr inline
485 <+> ppr rm
486 <+> ppr phases
487 <+> ppr n
488 <+> text "#-}"
489 ppr (SpecialiseP n ty inline phases)
490 = text "{-# SPECIALISE"
491 <+> maybe empty ppr inline
492 <+> ppr phases
493 <+> sep [ ppr n <+> dcolon
494 , nest 2 $ ppr ty ]
495 <+> text "#-}"
496 ppr (SpecialiseInstP inst)
497 = text "{-# SPECIALISE instance" <+> ppr inst <+> text "#-}"
498 ppr (RuleP n bndrs lhs rhs phases)
499 = sep [ text "{-# RULES" <+> pprString n <+> ppr phases
500 , nest 4 $ ppr_forall <+> ppr lhs
501 , nest 4 $ char '=' <+> ppr rhs <+> text "#-}" ]
502 where ppr_forall | null bndrs = empty
503 | otherwise = text "forall"
504 <+> fsep (map ppr bndrs)
505 <+> char '.'
506 ppr (AnnP tgt expr)
507 = text "{-# ANN" <+> target1 tgt <+> ppr expr <+> text "#-}"
508 where target1 ModuleAnnotation = text "module"
509 target1 (TypeAnnotation t) = text "type" <+> ppr t
510 target1 (ValueAnnotation v) = ppr v
511 ppr (LineP line file)
512 = text "{-# LINE" <+> int line <+> text (show file) <+> text "#-}"
513
514 ------------------------------
515 instance Ppr Inline where
516 ppr NoInline = text "NOINLINE"
517 ppr Inline = text "INLINE"
518 ppr Inlinable = text "INLINABLE"
519
520 ------------------------------
521 instance Ppr RuleMatch where
522 ppr ConLike = text "CONLIKE"
523 ppr FunLike = empty
524
525 ------------------------------
526 instance Ppr Phases where
527 ppr AllPhases = empty
528 ppr (FromPhase i) = brackets $ int i
529 ppr (BeforePhase i) = brackets $ char '~' <> int i
530
531 ------------------------------
532 instance Ppr RuleBndr where
533 ppr (RuleVar n) = ppr n
534 ppr (TypedRuleVar n ty) = parens $ ppr n <+> dcolon <+> ppr ty
535
536 ------------------------------
537 instance Ppr Clause where
538 ppr (Clause ps rhs ds) = hsep (map (pprPat appPrec) ps) <+> pprBody True rhs
539 $$ where_clause ds
540
541 ------------------------------
542 instance Ppr Con where
543 ppr (NormalC c sts) = ppr c <+> sep (map pprBangType sts)
544
545 ppr (RecC c vsts)
546 = ppr c <+> braces (sep (punctuate comma $ map pprVarBangType vsts))
547
548 ppr (InfixC st1 c st2) = pprBangType st1
549 <+> pprName' Infix c
550 <+> pprBangType st2
551
552 ppr (ForallC ns ctxt (GadtC c sts ty))
553 = commaSepApplied c <+> dcolon <+> pprForall ns ctxt
554 <+> pprGadtRHS sts ty
555
556 ppr (ForallC ns ctxt (RecGadtC c vsts ty))
557 = commaSepApplied c <+> dcolon <+> pprForall ns ctxt
558 <+> pprRecFields vsts ty
559
560 ppr (ForallC ns ctxt con)
561 = pprForall ns ctxt <+> ppr con
562
563 ppr (GadtC c sts ty)
564 = commaSepApplied c <+> dcolon <+> pprGadtRHS sts ty
565
566 ppr (RecGadtC c vsts ty)
567 = commaSepApplied c <+> dcolon <+> pprRecFields vsts ty
568
569 instance Ppr PatSynDir where
570 ppr Unidir = text "<-"
571 ppr ImplBidir = text "="
572 ppr (ExplBidir _) = text "<-"
573 -- the ExplBidir's clauses are pretty printed together with the
574 -- entire pattern synonym; so only print the direction here.
575
576 instance Ppr PatSynArgs where
577 ppr (PrefixPatSyn args) = sep $ map ppr args
578 ppr (InfixPatSyn a1 a2) = ppr a1 <+> ppr a2
579 ppr (RecordPatSyn sels) = braces $ sep (punctuate comma (map ppr sels))
580
581 commaSepApplied :: [Name] -> Doc
582 commaSepApplied = commaSepWith (pprName' Applied)
583
584 pprForall :: [TyVarBndr] -> Cxt -> Doc
585 pprForall tvs cxt
586 -- even in the case without any tvs, there could be a non-empty
587 -- context cxt (e.g., in the case of pattern synonyms, where there
588 -- are multiple forall binders and contexts).
589 | [] <- tvs = pprCxt cxt
590 | otherwise = text "forall" <+> hsep (map ppr tvs) <+> char '.' <+> pprCxt cxt
591
592 pprRecFields :: [(Name, Strict, Type)] -> Type -> Doc
593 pprRecFields vsts ty
594 = braces (sep (punctuate comma $ map pprVarBangType vsts))
595 <+> arrow <+> ppr ty
596
597 pprGadtRHS :: [(Strict, Type)] -> Type -> Doc
598 pprGadtRHS [] ty
599 = ppr ty
600 pprGadtRHS sts ty
601 = sep (punctuate (space <> arrow) (map pprBangType sts))
602 <+> arrow <+> ppr ty
603
604 ------------------------------
605 pprVarBangType :: VarBangType -> Doc
606 -- Slight infelicity: with print non-atomic type with parens
607 pprVarBangType (v, bang, t) = ppr v <+> dcolon <+> pprBangType (bang, t)
608
609 ------------------------------
610 pprBangType :: BangType -> Doc
611 -- Make sure we print
612 --
613 -- Con {-# UNPACK #-} a
614 --
615 -- rather than
616 --
617 -- Con {-# UNPACK #-}a
618 --
619 -- when there's no strictness annotation. If there is a strictness annotation,
620 -- it's okay to not put a space between it and the type.
621 pprBangType (bt@(Bang _ NoSourceStrictness), t) = ppr bt <+> pprParendType t
622 pprBangType (bt, t) = ppr bt <> pprParendType t
623
624 ------------------------------
625 instance Ppr Bang where
626 ppr (Bang su ss) = ppr su <+> ppr ss
627
628 ------------------------------
629 instance Ppr SourceUnpackedness where
630 ppr NoSourceUnpackedness = empty
631 ppr SourceNoUnpack = text "{-# NOUNPACK #-}"
632 ppr SourceUnpack = text "{-# UNPACK #-}"
633
634 ------------------------------
635 instance Ppr SourceStrictness where
636 ppr NoSourceStrictness = empty
637 ppr SourceLazy = char '~'
638 ppr SourceStrict = char '!'
639
640 ------------------------------
641 instance Ppr DecidedStrictness where
642 ppr DecidedLazy = empty
643 ppr DecidedStrict = char '!'
644 ppr DecidedUnpack = text "{-# UNPACK #-} !"
645
646 ------------------------------
647 {-# DEPRECATED pprVarStrictType
648 "As of @template-haskell-2.11.0.0@, 'VarStrictType' has been replaced by 'VarBangType'. Please use 'pprVarBangType' instead." #-}
649 pprVarStrictType :: (Name, Strict, Type) -> Doc
650 pprVarStrictType = pprVarBangType
651
652 ------------------------------
653 {-# DEPRECATED pprStrictType
654 "As of @template-haskell-2.11.0.0@, 'StrictType' has been replaced by 'BangType'. Please use 'pprBangType' instead." #-}
655 pprStrictType :: (Strict, Type) -> Doc
656 pprStrictType = pprBangType
657
658 ------------------------------
659 pprParendType :: Type -> Doc
660 pprParendType (VarT v) = ppr v
661 pprParendType (ConT c) = ppr c
662 pprParendType (TupleT 0) = text "()"
663 pprParendType (TupleT n) = parens (hcat (replicate (n-1) comma))
664 pprParendType (UnboxedTupleT n) = hashParens $ hcat $ replicate (n-1) comma
665 pprParendType (UnboxedSumT arity) = hashParens $ hcat $ replicate (arity-1) bar
666 pprParendType ArrowT = parens (text "->")
667 pprParendType ListT = text "[]"
668 pprParendType (LitT l) = pprTyLit l
669 pprParendType (PromotedT c) = text "'" <> ppr c
670 pprParendType (PromotedTupleT 0) = text "'()"
671 pprParendType (PromotedTupleT n) = quoteParens (hcat (replicate (n-1) comma))
672 pprParendType PromotedNilT = text "'[]"
673 pprParendType PromotedConsT = text "(':)"
674 pprParendType StarT = char '*'
675 pprParendType ConstraintT = text "Constraint"
676 pprParendType (SigT ty k) = parens (ppr ty <+> text "::" <+> ppr k)
677 pprParendType WildCardT = char '_'
678 pprParendType (InfixT x n y) = parens (ppr x <+> pprName' Infix n <+> ppr y)
679 pprParendType t@(UInfixT {}) = parens (pprUInfixT t)
680 pprParendType (ParensT t) = ppr t
681 pprParendType tuple | (TupleT n, args) <- split tuple
682 , length args == n
683 = parens (commaSep args)
684 pprParendType other = parens (ppr other)
685
686 pprUInfixT :: Type -> Doc
687 pprUInfixT (UInfixT x n y) = pprUInfixT x <+> pprName' Infix n <+> pprUInfixT y
688 pprUInfixT t = ppr t
689
690 instance Ppr Type where
691 ppr (ForallT tvars ctxt ty) = sep [pprForall tvars ctxt, ppr ty]
692 ppr ty = pprTyApp (split ty)
693 -- Works, in a degnerate way, for SigT, and puts parens round (ty :: kind)
694 -- See Note [Pretty-printing kind signatures]
695
696 {- Note [Pretty-printing kind signatures]
697 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
698 GHC's parser only recognises a kind signature in a type when there are
699 parens around it. E.g. the parens are required here:
700 f :: (Int :: *)
701 type instance F Int = (Bool :: *)
702 So we always print a SigT with parens (see Trac #10050). -}
703
704 pprTyApp :: (Type, [Type]) -> Doc
705 pprTyApp (ArrowT, [arg1,arg2]) = sep [pprFunArgType arg1 <+> text "->", ppr arg2]
706 pprTyApp (EqualityT, [arg1, arg2]) =
707 sep [pprFunArgType arg1 <+> text "~", ppr arg2]
708 pprTyApp (ListT, [arg]) = brackets (ppr arg)
709 pprTyApp (TupleT n, args)
710 | length args == n = parens (commaSep args)
711 pprTyApp (PromotedTupleT n, args)
712 | length args == n = quoteParens (commaSep args)
713 pprTyApp (fun, args) = pprParendType fun <+> sep (map pprParendType args)
714
715 pprFunArgType :: Type -> Doc -- Should really use a precedence argument
716 -- Everything except forall and (->) binds more tightly than (->)
717 pprFunArgType ty@(ForallT {}) = parens (ppr ty)
718 pprFunArgType ty@((ArrowT `AppT` _) `AppT` _) = parens (ppr ty)
719 pprFunArgType ty@(SigT _ _) = parens (ppr ty)
720 pprFunArgType ty = ppr ty
721
722 split :: Type -> (Type, [Type]) -- Split into function and args
723 split t = go t []
724 where go (AppT t1 t2) args = go t1 (t2:args)
725 go ty args = (ty, args)
726
727 pprTyLit :: TyLit -> Doc
728 pprTyLit (NumTyLit n) = integer n
729 pprTyLit (StrTyLit s) = text (show s)
730
731 instance Ppr TyLit where
732 ppr = pprTyLit
733
734 ------------------------------
735 instance Ppr TyVarBndr where
736 ppr (PlainTV nm) = ppr nm
737 ppr (KindedTV nm k) = parens (ppr nm <+> dcolon <+> ppr k)
738
739 instance Ppr Role where
740 ppr NominalR = text "nominal"
741 ppr RepresentationalR = text "representational"
742 ppr PhantomR = text "phantom"
743 ppr InferR = text "_"
744
745 ------------------------------
746 pprCxt :: Cxt -> Doc
747 pprCxt [] = empty
748 pprCxt ts = ppr_cxt_preds ts <+> text "=>"
749
750 ppr_cxt_preds :: Cxt -> Doc
751 ppr_cxt_preds [] = empty
752 ppr_cxt_preds [t] = ppr t
753 ppr_cxt_preds ts = parens (commaSep ts)
754
755 ------------------------------
756 instance Ppr Range where
757 ppr = brackets . pprRange
758 where pprRange :: Range -> Doc
759 pprRange (FromR e) = ppr e <> text ".."
760 pprRange (FromThenR e1 e2) = ppr e1 <> text ","
761 <> ppr e2 <> text ".."
762 pprRange (FromToR e1 e2) = ppr e1 <> text ".." <> ppr e2
763 pprRange (FromThenToR e1 e2 e3) = ppr e1 <> text ","
764 <> ppr e2 <> text ".."
765 <> ppr e3
766
767 ------------------------------
768 where_clause :: [Dec] -> Doc
769 where_clause [] = empty
770 where_clause ds = nest nestDepth $ text "where" <+> vcat (map (ppr_dec False) ds)
771
772 showtextl :: Show a => a -> Doc
773 showtextl = text . map toLower . show
774
775 hashParens :: Doc -> Doc
776 hashParens d = text "(# " <> d <> text " #)"
777
778 quoteParens :: Doc -> Doc
779 quoteParens d = text "'(" <> d <> text ")"
780
781 -----------------------------
782 instance Ppr Loc where
783 ppr (Loc { loc_module = md
784 , loc_package = pkg
785 , loc_start = (start_ln, start_col)
786 , loc_end = (end_ln, end_col) })
787 = hcat [ text pkg, colon, text md, colon
788 , parens $ int start_ln <> comma <> int start_col
789 , text "-"
790 , parens $ int end_ln <> comma <> int end_col ]
791
792 -- Takes a list of printable things and prints them separated by commas followed
793 -- by space.
794 commaSep :: Ppr a => [a] -> Doc
795 commaSep = commaSepWith ppr
796
797 -- Takes a list of things and prints them with the given pretty-printing
798 -- function, separated by commas followed by space.
799 commaSepWith :: (a -> Doc) -> [a] -> Doc
800 commaSepWith pprFun = sep . punctuate comma . map pprFun
801
802 -- Takes a list of printable things and prints them separated by semicolons
803 -- followed by space.
804 semiSep :: Ppr a => [a] -> Doc
805 semiSep = sep . punctuate semi . map ppr
806
807 -- Prints out the series of vertical bars that wraps an expression or pattern
808 -- used in an unboxed sum.
809 unboxedSumBars :: Doc -> SumAlt -> SumArity -> Doc
810 unboxedSumBars d alt arity = hashParens $
811 bars (alt-1) <> d <> bars (arity - alt)
812 where
813 bars i = hsep (replicate i bar)
814
815 -- Text containing the vertical bar character.
816 bar :: Doc
817 bar = char '|'