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