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