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