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