Change TH syntax to allow promoted kinds and kind polymorphism
[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.Char ( toLower )
13 import GHC.Show ( showMultiLineString )
14
15 nestDepth :: Int
16 nestDepth = 4
17
18 type Precedence = Int
19 appPrec, unopPrec, opPrec, noPrec :: Precedence
20 appPrec = 3 -- Argument of a function application
21 opPrec = 2 -- Argument of an infix operator
22 unopPrec = 1 -- Argument of an unresolved infix operator
23 noPrec = 0 -- Others
24
25 parensIf :: Bool -> Doc -> Doc
26 parensIf True d = parens d
27 parensIf False d = d
28
29 ------------------------------
30
31 pprint :: Ppr a => a -> String
32 pprint x = render $ to_HPJ_Doc $ ppr x
33
34 class Ppr a where
35 ppr :: a -> Doc
36 ppr_list :: [a] -> Doc
37 ppr_list = vcat . map ppr
38
39 instance Ppr a => Ppr [a] where
40 ppr x = ppr_list x
41
42 ------------------------------
43 instance Ppr Name where
44 ppr v = pprName v
45
46 ------------------------------
47 instance Ppr Info where
48 ppr (TyConI d) = ppr d
49 ppr (ClassI d is) = ppr d $$ vcat (map ppr is)
50 ppr (FamilyI d is) = ppr d $$ vcat (map ppr is)
51 ppr (PrimTyConI name arity is_unlifted)
52 = text "Primitive"
53 <+> (if is_unlifted then text "unlifted" else empty)
54 <+> text "type construtor" <+> quotes (ppr name)
55 <+> parens (text "arity" <+> int arity)
56 ppr (ClassOpI v ty cls fix)
57 = text "Class op from" <+> ppr cls <> colon <+>
58 vcat [ppr_sig v ty, pprFixity v fix]
59 ppr (DataConI v ty tc fix)
60 = text "Constructor from" <+> ppr tc <> colon <+>
61 vcat [ppr_sig v ty, pprFixity v fix]
62 ppr (TyVarI v ty)
63 = text "Type variable" <+> ppr v <+> equals <+> ppr ty
64 ppr (VarI v ty mb_d fix)
65 = vcat [ppr_sig v ty, pprFixity v fix,
66 case mb_d of { Nothing -> empty; Just d -> ppr d }]
67
68 ppr_sig :: Name -> Type -> Doc
69 ppr_sig v ty = ppr v <+> text "::" <+> ppr ty
70
71 pprFixity :: Name -> Fixity -> Doc
72 pprFixity _ f | f == defaultFixity = empty
73 pprFixity v (Fixity i d) = ppr_fix d <+> int i <+> ppr v
74 where ppr_fix InfixR = text "infixr"
75 ppr_fix InfixL = text "infixl"
76 ppr_fix InfixN = text "infix"
77
78
79 ------------------------------
80 instance Ppr Exp where
81 ppr = pprExp noPrec
82
83 pprInfixExp :: Exp -> Doc
84 pprInfixExp (VarE v) = pprName' Infix v
85 pprInfixExp (ConE v) = pprName' Infix v
86 pprInfixExp _ = error "Attempt to pretty-print non-variable or constructor in infix context!"
87
88 pprExp :: Precedence -> Exp -> Doc
89 pprExp _ (VarE v) = pprName' Applied v
90 pprExp _ (ConE c) = pprName' Applied c
91 pprExp i (LitE l) = pprLit i l
92 pprExp i (AppE e1 e2) = parensIf (i >= appPrec) $ pprExp opPrec e1
93 <+> pprExp appPrec e2
94 pprExp _ (ParensE e) = parens (pprExp noPrec e)
95 pprExp i (UInfixE e1 op e2)
96 = parensIf (i > unopPrec) $ pprExp unopPrec e1
97 <+> pprInfixExp op
98 <+> pprExp unopPrec e2
99 pprExp i (InfixE (Just e1) op (Just e2))
100 = parensIf (i >= opPrec) $ pprExp opPrec e1
101 <+> pprInfixExp op
102 <+> pprExp opPrec e2
103 pprExp _ (InfixE me1 op me2) = parens $ pprMaybeExp noPrec me1
104 <+> pprInfixExp op
105 <+> pprMaybeExp noPrec me2
106 pprExp i (LamE ps e) = parensIf (i > noPrec) $ char '\\' <> hsep (map (pprPat appPrec) ps)
107 <+> text "->" <+> ppr e
108 pprExp _ (TupE es) = parens $ sep $ punctuate comma $ map ppr es
109 pprExp _ (UnboxedTupE es) = hashParens $ sep $ punctuate comma $ map ppr es
110 -- Nesting in Cond is to avoid potential problems in do statments
111 pprExp i (CondE guard true false)
112 = parensIf (i > noPrec) $ sep [text "if" <+> ppr guard,
113 nest 1 $ text "then" <+> ppr true,
114 nest 1 $ text "else" <+> ppr false]
115 pprExp i (LetE ds e) = parensIf (i > noPrec) $ text "let" <+> ppr ds
116 $$ text " in" <+> ppr e
117 pprExp i (CaseE e ms)
118 = parensIf (i > noPrec) $ text "case" <+> ppr e <+> text "of"
119 $$ nest nestDepth (ppr ms)
120 pprExp i (DoE ss) = parensIf (i > noPrec) $ text "do" <+> ppr ss
121 pprExp _ (CompE []) = error "Can't happen: pprExp (CompExp [])"
122 -- This will probably break with fixity declarations - would need a ';'
123 pprExp _ (CompE ss) = text "[" <> ppr s
124 <+> text "|"
125 <+> (sep $ punctuate comma $ map ppr ss')
126 <> text "]"
127 where s = last ss
128 ss' = init ss
129 pprExp _ (ArithSeqE d) = ppr d
130 pprExp _ (ListE es) = brackets $ sep $ punctuate comma $ map ppr es
131 pprExp i (SigE e t) = parensIf (i > noPrec) $ ppr e <+> text "::" <+> ppr t
132 pprExp _ (RecConE nm fs) = ppr nm <> braces (pprFields fs)
133 pprExp _ (RecUpdE e fs) = pprExp appPrec e <> braces (pprFields fs)
134
135 pprFields :: [(Name,Exp)] -> Doc
136 pprFields = sep . punctuate comma . map (\(s,e) -> ppr s <+> equals <+> ppr e)
137
138 pprMaybeExp :: Precedence -> Maybe Exp -> Doc
139 pprMaybeExp _ Nothing = empty
140 pprMaybeExp i (Just e) = pprExp i e
141
142 ------------------------------
143 instance Ppr Stmt where
144 ppr (BindS p e) = ppr p <+> text "<-" <+> ppr e
145 ppr (LetS ds) = text "let" <+> ppr ds
146 ppr (NoBindS e) = ppr e
147 ppr (ParS sss) = sep $ punctuate (text "|")
148 $ map (sep . punctuate comma . map ppr) sss
149
150 ------------------------------
151 instance Ppr Match where
152 ppr (Match p rhs ds) = ppr p <+> pprBody False rhs
153 $$ where_clause ds
154
155 ------------------------------
156 pprBody :: Bool -> Body -> Doc
157 pprBody eq (GuardedB xs) = nest nestDepth $ vcat $ map do_guard xs
158 where eqd = if eq then text "=" else text "->"
159 do_guard (NormalG g, e) = text "|" <+> ppr g <+> eqd <+> ppr e
160 do_guard (PatG ss, e) = text "|" <+> vcat (map ppr ss)
161 $$ nest nestDepth (eqd <+> ppr e)
162 pprBody eq (NormalB e) = (if eq then text "=" else text "->") <+> ppr e
163
164 ------------------------------
165 pprLit :: Precedence -> Lit -> Doc
166 pprLit i (IntPrimL x) = parensIf (i > noPrec && x < 0)
167 (integer x <> char '#')
168 pprLit _ (WordPrimL x) = integer x <> text "##"
169 pprLit i (FloatPrimL x) = parensIf (i > noPrec && x < 0)
170 (float (fromRational x) <> char '#')
171 pprLit i (DoublePrimL x) = parensIf (i > noPrec && x < 0)
172 (double (fromRational x) <> text "##")
173 pprLit i (IntegerL x) = parensIf (i > noPrec && x < 0) (integer x)
174 pprLit _ (CharL c) = text (show c)
175 pprLit _ (StringL s) = pprString s
176 pprLit _ (StringPrimL s) = pprString s <> char '#'
177 pprLit i (RationalL rat) = parensIf (i > noPrec) $ rational rat
178
179 pprString :: String -> Doc
180 -- Print newlines as newlines with Haskell string escape notation,
181 -- not as '\n'. For other non-printables use regular escape notation.
182 pprString s = vcat (map text (showMultiLineString s))
183
184 ------------------------------
185 instance Ppr Pat where
186 ppr = pprPat noPrec
187
188 pprPat :: Precedence -> Pat -> Doc
189 pprPat i (LitP l) = pprLit i l
190 pprPat _ (VarP v) = pprName' Applied v
191 pprPat _ (TupP ps) = parens $ sep $ punctuate comma $ map ppr ps
192 pprPat _ (UnboxedTupP ps) = hashParens $ sep $ punctuate comma $ map ppr ps
193 pprPat i (ConP s ps) = parensIf (i >= appPrec) $ pprName' Applied s
194 <+> sep (map (pprPat appPrec) ps)
195 pprPat _ (ParensP p) = parens $ pprPat noPrec p
196 pprPat i (UInfixP p1 n p2)
197 = parensIf (i > unopPrec) (pprPat unopPrec p1 <+>
198 pprName' Infix n <+>
199 pprPat unopPrec p2)
200 pprPat i (InfixP p1 n p2)
201 = parensIf (i >= opPrec) (pprPat opPrec p1 <+>
202 pprName' Infix n <+>
203 pprPat opPrec p2)
204 pprPat i (TildeP p) = parensIf (i > noPrec) $ char '~' <> pprPat appPrec p
205 pprPat i (BangP p) = parensIf (i > noPrec) $ char '!' <> pprPat appPrec p
206 pprPat i (AsP v p) = parensIf (i > noPrec) $ ppr v <> text "@"
207 <> pprPat appPrec p
208 pprPat _ WildP = text "_"
209 pprPat _ (RecP nm fs)
210 = parens $ ppr nm
211 <+> braces (sep $ punctuate comma $
212 map (\(s,p) -> ppr s <+> equals <+> ppr p) fs)
213 pprPat _ (ListP ps) = brackets $ sep $ punctuate comma $ map ppr ps
214 pprPat i (SigP p t) = parensIf (i > noPrec) $ ppr p <+> text "::" <+> ppr t
215 pprPat _ (ViewP e p) = parens $ pprExp noPrec e <+> text "->" <+> pprPat noPrec p
216
217 ------------------------------
218 instance Ppr Dec where
219 ppr = ppr_dec True
220
221 ppr_dec :: Bool -- declaration on the toplevel?
222 -> Dec
223 -> Doc
224 ppr_dec _ (FunD f cs) = vcat $ map (\c -> ppr f <+> ppr c) cs
225 ppr_dec _ (ValD p r ds) = ppr p <+> pprBody True r
226 $$ where_clause ds
227 ppr_dec _ (TySynD t xs rhs)
228 = ppr_tySyn empty t (hsep (map ppr xs)) rhs
229 ppr_dec _ (DataD ctxt t xs cs decs)
230 = ppr_data empty ctxt t (hsep (map ppr xs)) cs decs
231 ppr_dec _ (NewtypeD ctxt t xs c decs)
232 = ppr_newtype empty ctxt t (sep (map ppr xs)) c decs
233 ppr_dec _ (ClassD ctxt c xs fds ds)
234 = text "class" <+> pprCxt ctxt <+> ppr c <+> hsep (map ppr xs) <+> ppr fds
235 $$ where_clause ds
236 ppr_dec _ (InstanceD ctxt i ds) = text "instance" <+> pprCxt ctxt <+> ppr i
237 $$ where_clause ds
238 ppr_dec _ (SigD f t) = ppr f <+> text "::" <+> ppr t
239 ppr_dec _ (ForeignD f) = ppr f
240 ppr_dec _ (InfixD fx n) = pprFixity n fx
241 ppr_dec _ (PragmaD p) = ppr p
242 ppr_dec isTop (FamilyD flav tc tvs k)
243 = ppr flav <+> maybeFamily <+> ppr tc <+> hsep (map ppr tvs) <+> maybeKind
244 where
245 maybeFamily | isTop = text "family"
246 | otherwise = empty
247
248 maybeKind | (Just k') <- k = text "::" <+> ppr k'
249 | otherwise = empty
250 ppr_dec isTop (DataInstD ctxt tc tys cs decs)
251 = ppr_data maybeInst ctxt tc (sep (map pprParendType tys)) cs decs
252 where
253 maybeInst | isTop = text "instance"
254 | otherwise = empty
255 ppr_dec isTop (NewtypeInstD ctxt tc tys c decs)
256 = ppr_newtype maybeInst ctxt tc (sep (map pprParendType tys)) c decs
257 where
258 maybeInst | isTop = text "instance"
259 | otherwise = empty
260 ppr_dec isTop (TySynInstD tc tys rhs)
261 = ppr_tySyn maybeInst tc (sep (map pprParendType tys)) rhs
262 where
263 maybeInst | isTop = text "instance"
264 | otherwise = empty
265
266 ppr_data :: Doc -> Cxt -> Name -> Doc -> [Con] -> [Name] -> Doc
267 ppr_data maybeInst ctxt t argsDoc cs decs
268 = sep [text "data" <+> maybeInst
269 <+> pprCxt ctxt
270 <+> ppr t <+> argsDoc,
271 nest nestDepth (sep (pref $ map ppr cs)),
272 if null decs
273 then empty
274 else nest nestDepth
275 $ text "deriving"
276 <+> parens (hsep $ punctuate comma $ map ppr decs)]
277 where
278 pref :: [Doc] -> [Doc]
279 pref [] = [] -- No constructors; can't happen in H98
280 pref (d:ds) = (char '=' <+> d):map (char '|' <+>) ds
281
282 ppr_newtype :: Doc -> Cxt -> Name -> Doc -> Con -> [Name] -> Doc
283 ppr_newtype maybeInst ctxt t argsDoc c decs
284 = sep [text "newtype" <+> maybeInst
285 <+> pprCxt ctxt
286 <+> ppr t <+> argsDoc,
287 nest 2 (char '=' <+> ppr c),
288 if null decs
289 then empty
290 else nest nestDepth
291 $ text "deriving"
292 <+> parens (hsep $ punctuate comma $ map ppr decs)]
293
294 ppr_tySyn :: Doc -> Name -> Doc -> Type -> Doc
295 ppr_tySyn maybeInst t argsDoc rhs
296 = text "type" <+> maybeInst <+> ppr t <+> argsDoc <+> text "=" <+> ppr rhs
297
298 ------------------------------
299 instance Ppr FunDep where
300 ppr (FunDep xs ys) = hsep (map ppr xs) <+> text "->" <+> hsep (map ppr ys)
301 ppr_list [] = empty
302 ppr_list xs = char '|' <+> sep (punctuate (text ", ") (map ppr xs))
303
304 ------------------------------
305 instance Ppr FamFlavour where
306 ppr DataFam = text "data"
307 ppr TypeFam = text "type"
308
309 ------------------------------
310 instance Ppr Foreign where
311 ppr (ImportF callconv safety impent as typ)
312 = text "foreign import"
313 <+> showtextl callconv
314 <+> showtextl safety
315 <+> text (show impent)
316 <+> ppr as
317 <+> text "::" <+> ppr typ
318 ppr (ExportF callconv expent as typ)
319 = text "foreign export"
320 <+> showtextl callconv
321 <+> text (show expent)
322 <+> ppr as
323 <+> text "::" <+> ppr typ
324
325 ------------------------------
326 instance Ppr Pragma where
327 ppr (InlineP n (InlineSpec inline conlike activation))
328 = text "{-#"
329 <+> text (case inline of
330 NoInline -> "NOINLINE"
331 Inline -> "INLINE"
332 Inlinable -> "INLINABLE")
333 <+> (if conlike then text "CONLIKE" else empty)
334 <+> ppr_activation activation
335 <+> ppr n
336 <+> text "#-}"
337 ppr (SpecialiseP n ty Nothing)
338 = sep [ text "{-# SPECIALISE"
339 , ppr n <+> text "::"
340 , ppr ty
341 , text "#-}"
342 ]
343 ppr (SpecialiseP n ty (Just (InlineSpec inline _conlike activation)))
344 = sep [ text "{-# SPECIALISE" <+>
345 text (case inline of
346 NoInline -> "NOINLINE"
347 Inline -> "INLINE"
348 Inlinable -> "INLINABLE") <+>
349 ppr_activation activation
350 , ppr n <+> text "::"
351 , ppr ty
352 , text "#-}"
353 ]
354 where
355
356 ppr_activation :: Maybe (Bool, Int) -> Doc
357 ppr_activation (Just (beforeFrom, i))
358 = brackets $ (if beforeFrom then empty else char '~') <+> int i
359 ppr_activation Nothing = empty
360
361 ------------------------------
362 instance Ppr Clause where
363 ppr (Clause ps rhs ds) = hsep (map (pprPat appPrec) ps) <+> pprBody True rhs
364 $$ where_clause ds
365
366 ------------------------------
367 instance Ppr Con where
368 ppr (NormalC c sts) = ppr c <+> sep (map pprStrictType sts)
369 ppr (RecC c vsts)
370 = ppr c <+> braces (sep (punctuate comma $ map pprVarStrictType vsts))
371 ppr (InfixC st1 c st2) = pprStrictType st1
372 <+> pprName' Infix c
373 <+> pprStrictType st2
374 ppr (ForallC ns ctxt con) = text "forall" <+> hsep (map ppr ns)
375 <+> char '.' <+> sep [pprCxt ctxt, ppr con]
376
377 ------------------------------
378 pprVarStrictType :: (Name, Strict, Type) -> Doc
379 -- Slight infelicity: with print non-atomic type with parens
380 pprVarStrictType (v, str, t) = ppr v <+> text "::" <+> pprStrictType (str, t)
381
382 ------------------------------
383 pprStrictType :: (Strict, Type) -> Doc
384 -- Prints with parens if not already atomic
385 pprStrictType (IsStrict, t) = char '!' <> pprParendType t
386 pprStrictType (NotStrict, t) = pprParendType t
387 pprStrictType (Unpacked, t) = text "{-# UNPACK #-} !" <> pprParendType t
388
389 ------------------------------
390 pprParendType :: Type -> Doc
391 pprParendType (VarT v) = ppr v
392 pprParendType (ConT c) = ppr c
393 pprParendType (TupleT 0) = text "()"
394 pprParendType (TupleT n) = parens (hcat (replicate (n-1) comma))
395 pprParendType (UnboxedTupleT n) = hashParens $ hcat $ replicate (n-1) comma
396 pprParendType ArrowT = parens (text "->")
397 pprParendType ListT = text "[]"
398 pprParendType (LitT l) = pprTyLit l
399 pprParendType (PromotedT c) = text "'" <> ppr c
400 pprParendType (PromotedTupleT 0) = text "'()"
401 pprParendType (PromotedTupleT n) = quoteParens (hcat (replicate (n-1) comma))
402 pprParendType PromotedNilT = text "'[]"
403 pprParendType PromotedConsT = text "(':)"
404 pprParendType StarT = char '*'
405 pprParendType ConstraintT = text "Constraint"
406 pprParendType other = parens (ppr other)
407
408 instance Ppr Type where
409 ppr (ForallT tvars ctxt ty)
410 = text "forall" <+> hsep (map ppr tvars) <+> text "."
411 <+> sep [pprCxt ctxt, ppr ty]
412 ppr (SigT ty k) = ppr ty <+> text "::" <+> ppr k
413 ppr ty = pprTyApp (split ty)
414
415 pprTyApp :: (Type, [Type]) -> Doc
416 pprTyApp (ArrowT, [arg1,arg2]) = sep [pprFunArgType arg1 <+> text "->", ppr arg2]
417 pprTyApp (ListT, [arg]) = brackets (ppr arg)
418 pprTyApp (TupleT n, args)
419 | length args == n = parens (sep (punctuate comma (map ppr args)))
420 pprTyApp (PromotedTupleT n, args)
421 | length args == n = quoteParens (sep (punctuate comma (map ppr args)))
422 pprTyApp (fun, args) = pprParendType fun <+> sep (map pprParendType args)
423
424 pprFunArgType :: Type -> Doc -- Should really use a precedence argument
425 -- Everything except forall and (->) binds more tightly than (->)
426 pprFunArgType ty@(ForallT {}) = parens (ppr ty)
427 pprFunArgType ty@((ArrowT `AppT` _) `AppT` _) = parens (ppr ty)
428 pprFunArgType ty@(SigT _ _) = parens (ppr ty)
429 pprFunArgType ty = ppr ty
430
431 split :: Type -> (Type, [Type]) -- Split into function and args
432 split t = go t []
433 where go (AppT t1 t2) args = go t1 (t2:args)
434 go ty args = (ty, args)
435
436 pprTyLit :: TyLit -> Doc
437 pprTyLit (NumTyLit n) = integer n
438 pprTyLit (StrTyLit s) = text (show s)
439
440 instance Ppr TyLit where
441 ppr = pprTyLit
442
443 ------------------------------
444 instance Ppr TyVarBndr where
445 ppr (PlainTV nm) = ppr nm
446 ppr (KindedTV nm k) = parens (ppr nm <+> text "::" <+> ppr k)
447
448 ------------------------------
449 pprCxt :: Cxt -> Doc
450 pprCxt [] = empty
451 pprCxt [t] = ppr t <+> text "=>"
452 pprCxt ts = parens (sep $ punctuate comma $ map ppr ts) <+> text "=>"
453
454 ------------------------------
455 instance Ppr Pred where
456 ppr (ClassP cla tys) = ppr cla <+> sep (map pprParendType tys)
457 ppr (EqualP ty1 ty2) = pprFunArgType ty1 <+> char '~' <+> pprFunArgType ty2
458
459 ------------------------------
460 instance Ppr Range where
461 ppr = brackets . pprRange
462 where pprRange :: Range -> Doc
463 pprRange (FromR e) = ppr e <> text ".."
464 pprRange (FromThenR e1 e2) = ppr e1 <> text ","
465 <> ppr e2 <> text ".."
466 pprRange (FromToR e1 e2) = ppr e1 <> text ".." <> ppr e2
467 pprRange (FromThenToR e1 e2 e3) = ppr e1 <> text ","
468 <> ppr e2 <> text ".."
469 <> ppr e3
470
471 ------------------------------
472 where_clause :: [Dec] -> Doc
473 where_clause [] = empty
474 where_clause ds = nest nestDepth $ text "where" <+> vcat (map (ppr_dec False) ds)
475
476 showtextl :: Show a => a -> Doc
477 showtextl = text . map toLower . show
478
479 hashParens :: Doc -> Doc
480 hashParens d = text "(# " <> d <> text " #)"
481
482 quoteParens :: Doc -> Doc
483 quoteParens d = text "'(" <> d <> text ")"
484