Fix startsVarSym and refactor operator predicates (fixes #4239)
[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) = text "[" <> ppr s
183 <+> bar
184 <+> commaSep ss'
185 <> text "]"
186 where s = last ss
187 ss' = init ss
188 pprExp _ (ArithSeqE d) = ppr d
189 pprExp _ (ListE es) = brackets (commaSep es)
190 pprExp i (SigE e t) = parensIf (i > noPrec) $ ppr e <+> dcolon <+> ppr t
191 pprExp _ (RecConE nm fs) = ppr nm <> braces (pprFields fs)
192 pprExp _ (RecUpdE e fs) = pprExp appPrec e <> braces (pprFields fs)
193 pprExp i (StaticE e) = parensIf (i >= appPrec) $
194 text "static"<+> pprExp appPrec e
195 pprExp _ (UnboundVarE v) = pprName' Applied v
196
197 pprFields :: [(Name,Exp)] -> Doc
198 pprFields = sep . punctuate comma . map (\(s,e) -> ppr s <+> equals <+> ppr e)
199
200 pprMaybeExp :: Precedence -> Maybe Exp -> Doc
201 pprMaybeExp _ Nothing = empty
202 pprMaybeExp i (Just e) = pprExp i e
203
204 ------------------------------
205 instance Ppr Stmt where
206 ppr (BindS p e) = ppr p <+> text "<-" <+> ppr e
207 ppr (LetS ds) = text "let" <+> (braces (semiSep ds))
208 ppr (NoBindS e) = ppr e
209 ppr (ParS sss) = sep $ punctuate bar
210 $ map commaSep sss
211
212 ------------------------------
213 instance Ppr Match where
214 ppr (Match p rhs ds) = ppr p <+> pprBody False rhs
215 $$ where_clause ds
216
217 ------------------------------
218 pprGuarded :: Doc -> (Guard, Exp) -> Doc
219 pprGuarded eqDoc (guard, expr) = case guard of
220 NormalG guardExpr -> bar <+> ppr guardExpr <+> eqDoc <+> ppr expr
221 PatG stmts -> bar <+> vcat (punctuate comma $ map ppr stmts) $$
222 nest nestDepth (eqDoc <+> ppr expr)
223
224 ------------------------------
225 pprBody :: Bool -> Body -> Doc
226 pprBody eq body = case body of
227 GuardedB xs -> nest nestDepth $ vcat $ map (pprGuarded eqDoc) xs
228 NormalB e -> eqDoc <+> ppr e
229 where eqDoc | eq = equals
230 | otherwise = arrow
231
232 ------------------------------
233 instance Ppr Lit where
234 ppr = pprLit noPrec
235
236 pprLit :: Precedence -> Lit -> Doc
237 pprLit i (IntPrimL x) = parensIf (i > noPrec && x < 0)
238 (integer x <> char '#')
239 pprLit _ (WordPrimL x) = integer x <> text "##"
240 pprLit i (FloatPrimL x) = parensIf (i > noPrec && x < 0)
241 (float (fromRational x) <> char '#')
242 pprLit i (DoublePrimL x) = parensIf (i > noPrec && x < 0)
243 (double (fromRational x) <> text "##")
244 pprLit i (IntegerL x) = parensIf (i > noPrec && x < 0) (integer x)
245 pprLit _ (CharL c) = text (show c)
246 pprLit _ (CharPrimL c) = text (show c) <> char '#'
247 pprLit _ (StringL s) = pprString s
248 pprLit _ (StringPrimL s) = pprString (bytesToString s) <> char '#'
249 pprLit i (RationalL rat) = parensIf (i > noPrec) $
250 integer (numerator rat) <+> char '/'
251 <+> integer (denominator rat)
252
253 bytesToString :: [Word8] -> String
254 bytesToString = map (chr . fromIntegral)
255
256 pprString :: String -> Doc
257 -- Print newlines as newlines with Haskell string escape notation,
258 -- not as '\n'. For other non-printables use regular escape notation.
259 pprString s = vcat (map text (showMultiLineString s))
260
261 ------------------------------
262 instance Ppr Pat where
263 ppr = pprPat noPrec
264
265 pprPat :: Precedence -> Pat -> Doc
266 pprPat i (LitP l) = pprLit i l
267 pprPat _ (VarP v) = pprName' Applied v
268 pprPat _ (TupP ps) = parens (commaSep ps)
269 pprPat _ (UnboxedTupP ps) = hashParens (commaSep ps)
270 pprPat _ (UnboxedSumP p alt arity) = unboxedSumBars (ppr p) alt arity
271 pprPat i (ConP s ps) = parensIf (i >= appPrec) $ pprName' Applied s
272 <+> sep (map (pprPat appPrec) ps)
273 pprPat _ (ParensP p) = parens $ pprPat noPrec p
274 pprPat i (UInfixP p1 n p2)
275 = parensIf (i > unopPrec) (pprPat unopPrec p1 <+>
276 pprName' Infix n <+>
277 pprPat unopPrec p2)
278 pprPat i (InfixP p1 n p2)
279 = parensIf (i >= opPrec) (pprPat opPrec p1 <+>
280 pprName' Infix n <+>
281 pprPat opPrec p2)
282 pprPat i (TildeP p) = parensIf (i > noPrec) $ char '~' <> pprPat appPrec p
283 pprPat i (BangP p) = parensIf (i > noPrec) $ char '!' <> pprPat appPrec p
284 pprPat i (AsP v p) = parensIf (i > noPrec) $ ppr v <> text "@"
285 <> pprPat appPrec p
286 pprPat _ WildP = text "_"
287 pprPat _ (RecP nm fs)
288 = parens $ ppr nm
289 <+> braces (sep $ punctuate comma $
290 map (\(s,p) -> ppr s <+> equals <+> ppr p) fs)
291 pprPat _ (ListP ps) = brackets (commaSep ps)
292 pprPat i (SigP p t) = parensIf (i > noPrec) $ ppr p <+> dcolon <+> ppr t
293 pprPat _ (ViewP e p) = parens $ pprExp noPrec e <+> text "->" <+> pprPat noPrec p
294
295 ------------------------------
296 instance Ppr Dec where
297 ppr = ppr_dec True
298
299 ppr_dec :: Bool -- declaration on the toplevel?
300 -> Dec
301 -> Doc
302 ppr_dec _ (FunD f cs) = vcat $ map (\c -> pprPrefixOcc f <+> ppr c) cs
303 ppr_dec _ (ValD p r ds) = ppr p <+> pprBody True r
304 $$ where_clause ds
305 ppr_dec _ (TySynD t xs rhs)
306 = ppr_tySyn empty t (hsep (map ppr xs)) rhs
307 ppr_dec _ (DataD ctxt t xs ksig cs decs)
308 = ppr_data empty ctxt t (hsep (map ppr xs)) ksig cs decs
309 ppr_dec _ (NewtypeD ctxt t xs ksig c decs)
310 = ppr_newtype empty ctxt t (sep (map ppr xs)) ksig c decs
311 ppr_dec _ (ClassD ctxt c xs fds ds)
312 = text "class" <+> pprCxt ctxt <+> ppr c <+> hsep (map ppr xs) <+> ppr fds
313 $$ where_clause ds
314 ppr_dec _ (InstanceD o ctxt i ds) =
315 text "instance" <+> maybe empty ppr_overlap o <+> pprCxt ctxt <+> ppr i
316 $$ where_clause ds
317 ppr_dec _ (SigD f t) = pprPrefixOcc f <+> dcolon <+> ppr t
318 ppr_dec _ (ForeignD f) = ppr f
319 ppr_dec _ (InfixD fx n) = pprFixity n fx
320 ppr_dec _ (PragmaD p) = ppr p
321 ppr_dec isTop (DataFamilyD tc tvs kind)
322 = text "data" <+> maybeFamily <+> ppr tc <+> hsep (map ppr tvs) <+> maybeKind
323 where
324 maybeFamily | isTop = text "family"
325 | otherwise = empty
326 maybeKind | (Just k') <- kind = dcolon <+> ppr k'
327 | otherwise = empty
328 ppr_dec isTop (DataInstD ctxt tc tys ksig cs decs)
329 = ppr_data maybeInst ctxt tc (sep (map pprParendType tys)) ksig cs decs
330 where
331 maybeInst | isTop = text "instance"
332 | otherwise = empty
333 ppr_dec isTop (NewtypeInstD ctxt tc tys ksig c decs)
334 = ppr_newtype maybeInst ctxt tc (sep (map pprParendType tys)) ksig c decs
335 where
336 maybeInst | isTop = text "instance"
337 | otherwise = empty
338 ppr_dec isTop (TySynInstD tc (TySynEqn tys rhs))
339 = ppr_tySyn maybeInst tc (sep (map pprParendType tys)) rhs
340 where
341 maybeInst | isTop = text "instance"
342 | otherwise = empty
343 ppr_dec isTop (OpenTypeFamilyD tfhead)
344 = text "type" <+> maybeFamily <+> ppr_tf_head tfhead
345 where
346 maybeFamily | isTop = text "family"
347 | otherwise = empty
348 ppr_dec _ (ClosedTypeFamilyD tfhead@(TypeFamilyHead tc _ _ _) eqns)
349 = hang (text "type family" <+> ppr_tf_head tfhead <+> text "where")
350 nestDepth (vcat (map ppr_eqn eqns))
351 where
352 ppr_eqn (TySynEqn lhs rhs)
353 = ppr tc <+> sep (map pprParendType lhs) <+> text "=" <+> ppr rhs
354 ppr_dec _ (RoleAnnotD name roles)
355 = hsep [ text "type role", ppr name ] <+> hsep (map ppr roles)
356 ppr_dec _ (StandaloneDerivD cxt ty)
357 = hsep [ text "deriving instance", pprCxt cxt, ppr ty ]
358 ppr_dec _ (DefaultSigD n ty)
359 = hsep [ text "default", pprPrefixOcc n, dcolon, ppr ty ]
360 ppr_dec _ (PatSynD name args dir pat)
361 = text "pattern" <+> pprNameArgs <+> ppr dir <+> pprPatRHS
362 where
363 pprNameArgs | InfixPatSyn a1 a2 <- args = ppr a1 <+> ppr name <+> ppr a2
364 | otherwise = ppr name <+> ppr args
365 pprPatRHS | ExplBidir cls <- dir = hang (ppr pat <+> text "where")
366 nestDepth (ppr name <+> ppr cls)
367 | otherwise = ppr pat
368 ppr_dec _ (PatSynSigD name ty)
369 = pprPatSynSig name ty
370
371
372 ppr_overlap :: Overlap -> Doc
373 ppr_overlap o = text $
374 case o of
375 Overlaps -> "{-# OVERLAPS #-}"
376 Overlappable -> "{-# OVERLAPPABLE #-}"
377 Overlapping -> "{-# OVERLAPPING #-}"
378 Incoherent -> "{-# INCOHERENT #-}"
379
380 ppr_data :: Doc -> Cxt -> Name -> Doc -> Maybe Kind -> [Con] -> Cxt -> Doc
381 ppr_data maybeInst ctxt t argsDoc ksig cs decs
382 = sep [text "data" <+> maybeInst
383 <+> pprCxt ctxt
384 <+> ppr t <+> argsDoc <+> ksigDoc <+> maybeWhere,
385 nest nestDepth (sep (pref $ map ppr cs)),
386 if null decs
387 then empty
388 else nest nestDepth
389 $ text "deriving" <+> ppr_cxt_preds decs]
390 where
391 pref :: [Doc] -> [Doc]
392 pref xs | isGadtDecl = xs
393 pref [] = [] -- No constructors; can't happen in H98
394 pref (d:ds) = (char '=' <+> d):map (bar <+>) ds
395
396 maybeWhere :: Doc
397 maybeWhere | isGadtDecl = text "where"
398 | otherwise = empty
399
400 isGadtDecl :: Bool
401 isGadtDecl = not (null cs) && all isGadtCon cs
402 where isGadtCon (GadtC _ _ _ ) = True
403 isGadtCon (RecGadtC _ _ _) = True
404 isGadtCon (ForallC _ _ x ) = isGadtCon x
405 isGadtCon _ = False
406
407 ksigDoc = case ksig of
408 Nothing -> empty
409 Just k -> dcolon <+> ppr k
410
411 ppr_newtype :: Doc -> Cxt -> Name -> Doc -> Maybe Kind -> Con -> Cxt -> Doc
412 ppr_newtype maybeInst ctxt t argsDoc ksig c decs
413 = sep [text "newtype" <+> maybeInst
414 <+> pprCxt ctxt
415 <+> ppr t <+> argsDoc <+> ksigDoc,
416 nest 2 (char '=' <+> ppr c),
417 if null decs
418 then empty
419 else nest nestDepth
420 $ text "deriving" <+> ppr_cxt_preds decs]
421 where
422 ksigDoc = case ksig of
423 Nothing -> empty
424 Just k -> dcolon <+> ppr k
425
426 ppr_tySyn :: Doc -> Name -> Doc -> Type -> Doc
427 ppr_tySyn maybeInst t argsDoc rhs
428 = text "type" <+> maybeInst <+> ppr t <+> argsDoc <+> text "=" <+> ppr rhs
429
430 ppr_tf_head :: TypeFamilyHead -> Doc
431 ppr_tf_head (TypeFamilyHead tc tvs res inj)
432 = ppr tc <+> hsep (map ppr tvs) <+> ppr res <+> maybeInj
433 where
434 maybeInj | (Just inj') <- inj = ppr inj'
435 | otherwise = empty
436
437 ------------------------------
438 instance Ppr FunDep where
439 ppr (FunDep xs ys) = hsep (map ppr xs) <+> text "->" <+> hsep (map ppr ys)
440 ppr_list [] = empty
441 ppr_list xs = bar <+> commaSep xs
442
443 ------------------------------
444 instance Ppr FamFlavour where
445 ppr DataFam = text "data"
446 ppr TypeFam = text "type"
447
448 ------------------------------
449 instance Ppr FamilyResultSig where
450 ppr NoSig = empty
451 ppr (KindSig k) = dcolon <+> ppr k
452 ppr (TyVarSig bndr) = text "=" <+> ppr bndr
453
454 ------------------------------
455 instance Ppr InjectivityAnn where
456 ppr (InjectivityAnn lhs rhs) =
457 bar <+> ppr lhs <+> text "->" <+> hsep (map ppr rhs)
458
459 ------------------------------
460 instance Ppr Foreign where
461 ppr (ImportF callconv safety impent as typ)
462 = text "foreign import"
463 <+> showtextl callconv
464 <+> showtextl safety
465 <+> text (show impent)
466 <+> ppr as
467 <+> dcolon <+> ppr typ
468 ppr (ExportF callconv expent as typ)
469 = text "foreign export"
470 <+> showtextl callconv
471 <+> text (show expent)
472 <+> ppr as
473 <+> dcolon <+> ppr typ
474
475 ------------------------------
476 instance Ppr Pragma where
477 ppr (InlineP n inline rm phases)
478 = text "{-#"
479 <+> ppr inline
480 <+> ppr rm
481 <+> ppr phases
482 <+> ppr n
483 <+> text "#-}"
484 ppr (SpecialiseP n ty inline phases)
485 = text "{-# SPECIALISE"
486 <+> maybe empty ppr inline
487 <+> ppr phases
488 <+> sep [ ppr n <+> dcolon
489 , nest 2 $ ppr ty ]
490 <+> text "#-}"
491 ppr (SpecialiseInstP inst)
492 = text "{-# SPECIALISE instance" <+> ppr inst <+> text "#-}"
493 ppr (RuleP n bndrs lhs rhs phases)
494 = sep [ text "{-# RULES" <+> pprString n <+> ppr phases
495 , nest 4 $ ppr_forall <+> ppr lhs
496 , nest 4 $ char '=' <+> ppr rhs <+> text "#-}" ]
497 where ppr_forall | null bndrs = empty
498 | otherwise = text "forall"
499 <+> fsep (map ppr bndrs)
500 <+> char '.'
501 ppr (AnnP tgt expr)
502 = text "{-# ANN" <+> target1 tgt <+> ppr expr <+> text "#-}"
503 where target1 ModuleAnnotation = text "module"
504 target1 (TypeAnnotation t) = text "type" <+> ppr t
505 target1 (ValueAnnotation v) = ppr v
506 ppr (LineP line file)
507 = text "{-# LINE" <+> int line <+> text (show file) <+> text "#-}"
508
509 ------------------------------
510 instance Ppr Inline where
511 ppr NoInline = text "NOINLINE"
512 ppr Inline = text "INLINE"
513 ppr Inlinable = text "INLINABLE"
514
515 ------------------------------
516 instance Ppr RuleMatch where
517 ppr ConLike = text "CONLIKE"
518 ppr FunLike = empty
519
520 ------------------------------
521 instance Ppr Phases where
522 ppr AllPhases = empty
523 ppr (FromPhase i) = brackets $ int i
524 ppr (BeforePhase i) = brackets $ char '~' <> int i
525
526 ------------------------------
527 instance Ppr RuleBndr where
528 ppr (RuleVar n) = ppr n
529 ppr (TypedRuleVar n ty) = parens $ ppr n <+> dcolon <+> ppr ty
530
531 ------------------------------
532 instance Ppr Clause where
533 ppr (Clause ps rhs ds) = hsep (map (pprPat appPrec) ps) <+> pprBody True rhs
534 $$ where_clause ds
535
536 ------------------------------
537 instance Ppr Con where
538 ppr (NormalC c sts) = ppr c <+> sep (map pprBangType sts)
539
540 ppr (RecC c vsts)
541 = ppr c <+> braces (sep (punctuate comma $ map pprVarBangType vsts))
542
543 ppr (InfixC st1 c st2) = pprBangType st1
544 <+> pprName' Infix c
545 <+> pprBangType st2
546
547 ppr (ForallC ns ctxt (GadtC c sts ty))
548 = commaSepApplied c <+> dcolon <+> pprForall ns ctxt
549 <+> pprGadtRHS sts ty
550
551 ppr (ForallC ns ctxt (RecGadtC c vsts ty))
552 = commaSepApplied c <+> dcolon <+> pprForall ns ctxt
553 <+> pprRecFields vsts ty
554
555 ppr (ForallC ns ctxt con)
556 = pprForall ns ctxt <+> ppr con
557
558 ppr (GadtC c sts ty)
559 = commaSepApplied c <+> dcolon <+> pprGadtRHS sts ty
560
561 ppr (RecGadtC c vsts ty)
562 = commaSepApplied c <+> dcolon <+> pprRecFields vsts ty
563
564 instance Ppr PatSynDir where
565 ppr Unidir = text "<-"
566 ppr ImplBidir = text "="
567 ppr (ExplBidir _) = text "<-"
568 -- the ExplBidir's clauses are pretty printed together with the
569 -- entire pattern synonym; so only print the direction here.
570
571 instance Ppr PatSynArgs where
572 ppr (PrefixPatSyn args) = sep $ map ppr args
573 ppr (InfixPatSyn a1 a2) = ppr a1 <+> ppr a2
574 ppr (RecordPatSyn sels) = braces $ sep (punctuate comma (map ppr sels))
575
576 commaSepApplied :: [Name] -> Doc
577 commaSepApplied = commaSepWith (pprName' Applied)
578
579 pprForall :: [TyVarBndr] -> Cxt -> Doc
580 pprForall tvs cxt
581 -- even in the case without any tvs, there could be a non-empty
582 -- context cxt (e.g., in the case of pattern synonyms, where there
583 -- are multiple forall binders and contexts).
584 | [] <- tvs = pprCxt cxt
585 | otherwise = text "forall" <+> hsep (map ppr tvs) <+> char '.' <+> pprCxt cxt
586
587 pprRecFields :: [(Name, Strict, Type)] -> Type -> Doc
588 pprRecFields vsts ty
589 = braces (sep (punctuate comma $ map pprVarBangType vsts))
590 <+> arrow <+> ppr ty
591
592 pprGadtRHS :: [(Strict, Type)] -> Type -> Doc
593 pprGadtRHS [] ty
594 = ppr ty
595 pprGadtRHS sts ty
596 = sep (punctuate (space <> arrow) (map pprBangType sts))
597 <+> arrow <+> ppr ty
598
599 ------------------------------
600 pprVarBangType :: VarBangType -> Doc
601 -- Slight infelicity: with print non-atomic type with parens
602 pprVarBangType (v, bang, t) = ppr v <+> dcolon <+> pprBangType (bang, t)
603
604 ------------------------------
605 pprBangType :: BangType -> Doc
606 -- Make sure we print
607 --
608 -- Con {-# UNPACK #-} a
609 --
610 -- rather than
611 --
612 -- Con {-# UNPACK #-}a
613 --
614 -- when there's no strictness annotation. If there is a strictness annotation,
615 -- it's okay to not put a space between it and the type.
616 pprBangType (bt@(Bang _ NoSourceStrictness), t) = ppr bt <+> pprParendType t
617 pprBangType (bt, t) = ppr bt <> pprParendType t
618
619 ------------------------------
620 instance Ppr Bang where
621 ppr (Bang su ss) = ppr su <+> ppr ss
622
623 ------------------------------
624 instance Ppr SourceUnpackedness where
625 ppr NoSourceUnpackedness = empty
626 ppr SourceNoUnpack = text "{-# NOUNPACK #-}"
627 ppr SourceUnpack = text "{-# UNPACK #-}"
628
629 ------------------------------
630 instance Ppr SourceStrictness where
631 ppr NoSourceStrictness = empty
632 ppr SourceLazy = char '~'
633 ppr SourceStrict = char '!'
634
635 ------------------------------
636 instance Ppr DecidedStrictness where
637 ppr DecidedLazy = empty
638 ppr DecidedStrict = char '!'
639 ppr DecidedUnpack = text "{-# UNPACK #-} !"
640
641 ------------------------------
642 {-# DEPRECATED pprVarStrictType
643 "As of @template-haskell-2.11.0.0@, 'VarStrictType' has been replaced by 'VarBangType'. Please use 'pprVarBangType' instead." #-}
644 pprVarStrictType :: (Name, Strict, Type) -> Doc
645 pprVarStrictType = pprVarBangType
646
647 ------------------------------
648 {-# DEPRECATED pprStrictType
649 "As of @template-haskell-2.11.0.0@, 'StrictType' has been replaced by 'BangType'. Please use 'pprBangType' instead." #-}
650 pprStrictType :: (Strict, Type) -> Doc
651 pprStrictType = pprBangType
652
653 ------------------------------
654 pprParendType :: Type -> Doc
655 pprParendType (VarT v) = ppr v
656 pprParendType (ConT c) = ppr c
657 pprParendType (TupleT 0) = text "()"
658 pprParendType (TupleT n) = parens (hcat (replicate (n-1) comma))
659 pprParendType (UnboxedTupleT n) = hashParens $ hcat $ replicate (n-1) comma
660 pprParendType (UnboxedSumT arity) = hashParens $ hcat $ replicate (arity-1) bar
661 pprParendType ArrowT = parens (text "->")
662 pprParendType ListT = text "[]"
663 pprParendType (LitT l) = pprTyLit l
664 pprParendType (PromotedT c) = text "'" <> ppr c
665 pprParendType (PromotedTupleT 0) = text "'()"
666 pprParendType (PromotedTupleT n) = quoteParens (hcat (replicate (n-1) comma))
667 pprParendType PromotedNilT = text "'[]"
668 pprParendType PromotedConsT = text "(':)"
669 pprParendType StarT = char '*'
670 pprParendType ConstraintT = text "Constraint"
671 pprParendType (SigT ty k) = parens (ppr ty <+> text "::" <+> ppr k)
672 pprParendType WildCardT = char '_'
673 pprParendType (InfixT x n y) = parens (ppr x <+> pprName' Infix n <+> ppr y)
674 pprParendType t@(UInfixT {}) = parens (pprUInfixT t)
675 pprParendType (ParensT t) = ppr t
676 pprParendType tuple | (TupleT n, args) <- split tuple
677 , length args == n
678 = parens (commaSep args)
679 pprParendType other = parens (ppr other)
680
681 pprUInfixT :: Type -> Doc
682 pprUInfixT (UInfixT x n y) = pprUInfixT x <+> pprName' Infix n <+> pprUInfixT y
683 pprUInfixT t = ppr t
684
685 instance Ppr Type where
686 ppr (ForallT tvars ctxt ty) = sep [pprForall tvars ctxt, ppr ty]
687 ppr ty = pprTyApp (split ty)
688 -- Works, in a degnerate way, for SigT, and puts parens round (ty :: kind)
689 -- See Note [Pretty-printing kind signatures]
690
691 {- Note [Pretty-printing kind signatures]
692 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
693 GHC's parser only recognises a kind signature in a type when there are
694 parens around it. E.g. the parens are required here:
695 f :: (Int :: *)
696 type instance F Int = (Bool :: *)
697 So we always print a SigT with parens (see Trac #10050). -}
698
699 pprTyApp :: (Type, [Type]) -> Doc
700 pprTyApp (ArrowT, [arg1,arg2]) = sep [pprFunArgType arg1 <+> text "->", ppr arg2]
701 pprTyApp (EqualityT, [arg1, arg2]) =
702 sep [pprFunArgType arg1 <+> text "~", ppr arg2]
703 pprTyApp (ListT, [arg]) = brackets (ppr arg)
704 pprTyApp (TupleT n, args)
705 | length args == n = parens (commaSep args)
706 pprTyApp (PromotedTupleT n, args)
707 | length args == n = quoteParens (commaSep args)
708 pprTyApp (fun, args) = pprParendType fun <+> sep (map pprParendType args)
709
710 pprFunArgType :: Type -> Doc -- Should really use a precedence argument
711 -- Everything except forall and (->) binds more tightly than (->)
712 pprFunArgType ty@(ForallT {}) = parens (ppr ty)
713 pprFunArgType ty@((ArrowT `AppT` _) `AppT` _) = parens (ppr ty)
714 pprFunArgType ty@(SigT _ _) = parens (ppr ty)
715 pprFunArgType ty = ppr ty
716
717 split :: Type -> (Type, [Type]) -- Split into function and args
718 split t = go t []
719 where go (AppT t1 t2) args = go t1 (t2:args)
720 go ty args = (ty, args)
721
722 pprTyLit :: TyLit -> Doc
723 pprTyLit (NumTyLit n) = integer n
724 pprTyLit (StrTyLit s) = text (show s)
725
726 instance Ppr TyLit where
727 ppr = pprTyLit
728
729 ------------------------------
730 instance Ppr TyVarBndr where
731 ppr (PlainTV nm) = ppr nm
732 ppr (KindedTV nm k) = parens (ppr nm <+> dcolon <+> ppr k)
733
734 instance Ppr Role where
735 ppr NominalR = text "nominal"
736 ppr RepresentationalR = text "representational"
737 ppr PhantomR = text "phantom"
738 ppr InferR = text "_"
739
740 ------------------------------
741 pprCxt :: Cxt -> Doc
742 pprCxt [] = empty
743 pprCxt ts = ppr_cxt_preds ts <+> text "=>"
744
745 ppr_cxt_preds :: Cxt -> Doc
746 ppr_cxt_preds [] = empty
747 ppr_cxt_preds [t] = ppr t
748 ppr_cxt_preds ts = parens (commaSep ts)
749
750 ------------------------------
751 instance Ppr Range where
752 ppr = brackets . pprRange
753 where pprRange :: Range -> Doc
754 pprRange (FromR e) = ppr e <> text ".."
755 pprRange (FromThenR e1 e2) = ppr e1 <> text ","
756 <> ppr e2 <> text ".."
757 pprRange (FromToR e1 e2) = ppr e1 <> text ".." <> ppr e2
758 pprRange (FromThenToR e1 e2 e3) = ppr e1 <> text ","
759 <> ppr e2 <> text ".."
760 <> ppr e3
761
762 ------------------------------
763 where_clause :: [Dec] -> Doc
764 where_clause [] = empty
765 where_clause ds = nest nestDepth $ text "where" <+> vcat (map (ppr_dec False) ds)
766
767 showtextl :: Show a => a -> Doc
768 showtextl = text . map toLower . show
769
770 hashParens :: Doc -> Doc
771 hashParens d = text "(# " <> d <> text " #)"
772
773 quoteParens :: Doc -> Doc
774 quoteParens d = text "'(" <> d <> text ")"
775
776 -----------------------------
777 instance Ppr Loc where
778 ppr (Loc { loc_module = md
779 , loc_package = pkg
780 , loc_start = (start_ln, start_col)
781 , loc_end = (end_ln, end_col) })
782 = hcat [ text pkg, colon, text md, colon
783 , parens $ int start_ln <> comma <> int start_col
784 , text "-"
785 , parens $ int end_ln <> comma <> int end_col ]
786
787 -- Takes a list of printable things and prints them separated by commas followed
788 -- by space.
789 commaSep :: Ppr a => [a] -> Doc
790 commaSep = commaSepWith ppr
791
792 -- Takes a list of things and prints them with the given pretty-printing
793 -- function, separated by commas followed by space.
794 commaSepWith :: (a -> Doc) -> [a] -> Doc
795 commaSepWith pprFun = sep . punctuate comma . map pprFun
796
797 -- Takes a list of printable things and prints them separated by semicolons
798 -- followed by space.
799 semiSep :: Ppr a => [a] -> Doc
800 semiSep = sep . punctuate semi . map ppr
801
802 -- Prints out the series of vertical bars that wraps an expression or pattern
803 -- used in an unboxed sum.
804 unboxedSumBars :: Doc -> SumAlt -> SumArity -> Doc
805 unboxedSumBars d alt arity = hashParens $
806 bars (alt-1) <> d <> bars (arity - alt)
807 where
808 bars i = hsep (replicate i bar)
809
810 -- Text containing the vertical bar character.
811 bar :: Doc
812 bar = char '|'