ac1bbf5e5863489e7deac397c702aeb542a56826
[packages/template-haskell.git] / 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
14 nestDepth :: Int
15 nestDepth = 4
16
17 type Precedence = Int
18 appPrec, opPrec, noPrec :: Precedence
19 appPrec = 2 -- Argument of a function application
20 opPrec = 1 -- Argument of an infix operator
21 noPrec = 0 -- Others
22
23 parensIf :: Bool -> Doc -> Doc
24 parensIf True d = parens d
25 parensIf False d = d
26
27 ------------------------------
28
29 pprint :: Ppr a => a -> String
30 pprint x = render $ to_HPJ_Doc $ ppr x
31
32 class Ppr a where
33 ppr :: a -> Doc
34 ppr_list :: [a] -> Doc
35 ppr_list = vcat . map ppr
36
37 instance Ppr a => Ppr [a] where
38 ppr x = ppr_list x
39
40 ------------------------------
41 instance Ppr Name where
42 ppr v = pprName v
43
44 ------------------------------
45 instance Ppr Info where
46 ppr (ClassI d is) = ppr d $$ vcat (map ppr is)
47 ppr (TyConI d) = ppr d
48 ppr (PrimTyConI name arity is_unlifted)
49 = text "Primitive"
50 <+> (if is_unlifted then text "unlifted" else empty)
51 <+> text "type construtor" <+> quotes (ppr name)
52 <+> parens (text "arity" <+> int arity)
53 ppr (ClassOpI v ty cls fix)
54 = text "Class op from" <+> ppr cls <> colon <+>
55 vcat [ppr_sig v ty, pprFixity v fix]
56 ppr (DataConI v ty tc fix)
57 = text "Constructor from" <+> ppr tc <> colon <+>
58 vcat [ppr_sig v ty, pprFixity v fix]
59 ppr (TyVarI v ty)
60 = text "Type variable" <+> ppr v <+> equals <+> ppr ty
61 ppr (VarI v ty mb_d fix)
62 = vcat [ppr_sig v ty, pprFixity v fix,
63 case mb_d of { Nothing -> empty; Just d -> ppr d }]
64
65 instance Ppr ClassInstance where
66 ppr (ClassInstance { ci_dfun = _dfun,
67 ci_tvs = _tvs,
68 ci_cxt = cxt,
69 ci_cls = cls,
70 ci_tys = tys })
71 = text "instance" <+> pprCxt cxt
72 <+> ppr cls <+> sep (map pprParendType tys)
73
74 ppr_sig :: Name -> Type -> Doc
75 ppr_sig v ty = ppr v <+> text "::" <+> ppr ty
76
77 pprFixity :: Name -> Fixity -> Doc
78 pprFixity _ f | f == defaultFixity = empty
79 pprFixity v (Fixity i d) = ppr_fix d <+> int i <+> ppr v
80 where ppr_fix InfixR = text "infixr"
81 ppr_fix InfixL = text "infixl"
82 ppr_fix InfixN = text "infix"
83
84
85 ------------------------------
86 instance Ppr Exp where
87 ppr = pprExp noPrec
88
89 pprInfixExp :: Exp -> Doc
90 pprInfixExp (VarE v) = pprName' Infix v
91 pprInfixExp (ConE v) = pprName' Infix v
92 pprInfixExp _ = error "Attempt to pretty-print non-variable or constructor in infix context!"
93
94 pprExp :: Precedence -> Exp -> Doc
95 pprExp _ (VarE v) = pprName' Applied v
96 pprExp _ (ConE c) = pprName' Applied c
97 pprExp i (LitE l) = pprLit i l
98 pprExp i (AppE e1 e2) = parensIf (i >= appPrec) $ pprExp opPrec e1
99 <+> pprExp appPrec e2
100 pprExp i (InfixE (Just e1) op (Just e2))
101 = parensIf (i >= opPrec) $ pprExp opPrec e1
102 <+> pprInfixExp op
103 <+> pprExp opPrec e2
104 pprExp _ (InfixE me1 op me2) = parens $ pprMaybeExp noPrec me1
105 <+> pprInfixExp op
106 <+> pprMaybeExp noPrec me2
107 pprExp i (LamE ps e) = parensIf (i > noPrec) $ char '\\' <> hsep (map (pprPat appPrec) ps)
108 <+> text "->" <+> ppr e
109 pprExp _ (TupE es) = parens $ 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) = text (show s)
176 pprLit _ (StringPrimL s) = text (show s) <> char '#'
177 pprLit i (RationalL rat) = parensIf (i > noPrec) $ rational rat
178
179 ------------------------------
180 instance Ppr Pat where
181 ppr = pprPat noPrec
182
183 pprPat :: Precedence -> Pat -> Doc
184 pprPat i (LitP l) = pprLit i l
185 pprPat _ (VarP v) = pprName' Applied v
186 pprPat _ (TupP ps) = parens $ sep $ punctuate comma $ map ppr ps
187 pprPat i (ConP s ps) = parensIf (i >= appPrec) $ pprName' Applied s
188 <+> sep (map (pprPat appPrec) ps)
189 pprPat i (InfixP p1 n p2)
190 = parensIf (i >= opPrec) (pprPat opPrec p1 <+>
191 pprName' Infix n <+>
192 pprPat opPrec p2)
193 pprPat i (TildeP p) = parensIf (i > noPrec) $ char '~' <> pprPat appPrec p
194 pprPat i (BangP p) = parensIf (i > noPrec) $ char '!' <> pprPat appPrec p
195 pprPat i (AsP v p) = parensIf (i > noPrec) $ ppr v <> text "@"
196 <> pprPat appPrec p
197 pprPat _ WildP = text "_"
198 pprPat _ (RecP nm fs)
199 = parens $ ppr nm
200 <+> braces (sep $ punctuate comma $
201 map (\(s,p) -> ppr s <+> equals <+> ppr p) fs)
202 pprPat _ (ListP ps) = brackets $ sep $ punctuate comma $ map ppr ps
203 pprPat i (SigP p t) = parensIf (i > noPrec) $ ppr p <+> text "::" <+> ppr t
204 pprPat _ (ViewP e p) = parens $ pprExp noPrec e <+> text "->" <+> pprPat noPrec p
205
206 ------------------------------
207 instance Ppr Dec where
208 ppr = ppr_dec True
209
210 ppr_dec :: Bool -- declaration on the toplevel?
211 -> Dec
212 -> Doc
213 ppr_dec _ (FunD f cs) = vcat $ map (\c -> ppr f <+> ppr c) cs
214 ppr_dec _ (ValD p r ds) = ppr p <+> pprBody True r
215 $$ where_clause ds
216 ppr_dec _ (TySynD t xs rhs)
217 = ppr_tySyn empty t (hsep (map ppr xs)) rhs
218 ppr_dec _ (DataD ctxt t xs cs decs)
219 = ppr_data empty ctxt t (hsep (map ppr xs)) cs decs
220 ppr_dec _ (NewtypeD ctxt t xs c decs)
221 = ppr_newtype empty ctxt t (sep (map ppr xs)) c decs
222 ppr_dec _ (ClassD ctxt c xs fds ds)
223 = text "class" <+> pprCxt ctxt <+> ppr c <+> hsep (map ppr xs) <+> ppr fds
224 $$ where_clause ds
225 ppr_dec _ (InstanceD ctxt i ds) = text "instance" <+> pprCxt ctxt <+> ppr i
226 $$ where_clause ds
227 ppr_dec _ (SigD f t) = ppr f <+> text "::" <+> ppr t
228 ppr_dec _ (ForeignD f) = ppr f
229 ppr_dec _ (PragmaD p) = ppr p
230 ppr_dec isTop (FamilyD flav tc tvs k)
231 = ppr flav <+> maybeFamily <+> ppr tc <+> hsep (map ppr tvs) <+> maybeKind
232 where
233 maybeFamily | isTop = text "family"
234 | otherwise = empty
235
236 maybeKind | (Just k') <- k = text "::" <+> ppr k'
237 | otherwise = empty
238 ppr_dec isTop (DataInstD ctxt tc tys cs decs)
239 = ppr_data maybeInst ctxt tc (sep (map pprParendType tys)) cs decs
240 where
241 maybeInst | isTop = text "instance"
242 | otherwise = empty
243 ppr_dec isTop (NewtypeInstD ctxt tc tys c decs)
244 = ppr_newtype maybeInst ctxt tc (sep (map pprParendType tys)) c decs
245 where
246 maybeInst | isTop = text "instance"
247 | otherwise = empty
248 ppr_dec isTop (TySynInstD tc tys rhs)
249 = ppr_tySyn maybeInst tc (sep (map pprParendType tys)) rhs
250 where
251 maybeInst | isTop = text "instance"
252 | otherwise = empty
253
254 ppr_data :: Doc -> Cxt -> Name -> Doc -> [Con] -> [Name] -> Doc
255 ppr_data maybeInst ctxt t argsDoc cs decs
256 = sep [text "data" <+> maybeInst
257 <+> pprCxt ctxt
258 <+> ppr t <+> argsDoc,
259 nest nestDepth (sep (pref $ map ppr cs)),
260 if null decs
261 then empty
262 else nest nestDepth
263 $ text "deriving"
264 <+> parens (hsep $ punctuate comma $ map ppr decs)]
265 where
266 pref :: [Doc] -> [Doc]
267 pref [] = [] -- No constructors; can't happen in H98
268 pref (d:ds) = (char '=' <+> d):map (char '|' <+>) ds
269
270 ppr_newtype :: Doc -> Cxt -> Name -> Doc -> Con -> [Name] -> Doc
271 ppr_newtype maybeInst ctxt t argsDoc c decs
272 = sep [text "newtype" <+> maybeInst
273 <+> pprCxt ctxt
274 <+> ppr t <+> argsDoc,
275 nest 2 (char '=' <+> ppr c),
276 if null decs
277 then empty
278 else nest nestDepth
279 $ text "deriving"
280 <+> parens (hsep $ punctuate comma $ map ppr decs)]
281
282 ppr_tySyn :: Doc -> Name -> Doc -> Type -> Doc
283 ppr_tySyn maybeInst t argsDoc rhs
284 = text "type" <+> maybeInst <+> ppr t <+> argsDoc <+> text "=" <+> ppr rhs
285
286 ------------------------------
287 instance Ppr FunDep where
288 ppr (FunDep xs ys) = hsep (map ppr xs) <+> text "->" <+> hsep (map ppr ys)
289 ppr_list [] = empty
290 ppr_list xs = char '|' <+> sep (punctuate (text ", ") (map ppr xs))
291
292 ------------------------------
293 instance Ppr FamFlavour where
294 ppr DataFam = text "data"
295 ppr TypeFam = text "type"
296
297 ------------------------------
298 instance Ppr Foreign where
299 ppr (ImportF callconv safety impent as typ)
300 = text "foreign import"
301 <+> showtextl callconv
302 <+> showtextl safety
303 <+> text (show impent)
304 <+> ppr as
305 <+> text "::" <+> ppr typ
306 ppr (ExportF callconv expent as typ)
307 = text "foreign export"
308 <+> showtextl callconv
309 <+> text (show expent)
310 <+> ppr as
311 <+> text "::" <+> ppr typ
312
313 ------------------------------
314 instance Ppr Pragma where
315 ppr (InlineP n (InlineSpec inline conlike activation))
316 = text "{-#"
317 <+> (if inline then text "INLINE" else text "NOINLINE")
318 <+> (if conlike then text "CONLIKE" else empty)
319 <+> ppr_activation activation
320 <+> ppr n
321 <+> text "#-}"
322 ppr (SpecialiseP n ty Nothing)
323 = sep [ text "{-# SPECIALISE"
324 , ppr n <+> text "::"
325 , ppr ty
326 , text "#-}"
327 ]
328 ppr (SpecialiseP n ty (Just (InlineSpec inline _conlike activation)))
329 = sep [ text "{-# SPECIALISE" <+>
330 (if inline then text "INLINE" else text "NOINLINE") <+>
331 ppr_activation activation
332 , ppr n <+> text "::"
333 , ppr ty
334 , text "#-}"
335 ]
336 where
337
338 ppr_activation :: Maybe (Bool, Int) -> Doc
339 ppr_activation (Just (beforeFrom, i))
340 = brackets $ (if beforeFrom then empty else char '~') <+> int i
341 ppr_activation Nothing = empty
342
343 ------------------------------
344 instance Ppr Clause where
345 ppr (Clause ps rhs ds) = hsep (map (pprPat appPrec) ps) <+> pprBody True rhs
346 $$ where_clause ds
347
348 ------------------------------
349 instance Ppr Con where
350 ppr (NormalC c sts) = ppr c <+> sep (map pprStrictType sts)
351 ppr (RecC c vsts)
352 = ppr c <+> braces (sep (punctuate comma $ map pprVarStrictType vsts))
353 ppr (InfixC st1 c st2) = pprStrictType st1
354 <+> pprName' Infix c
355 <+> pprStrictType st2
356 ppr (ForallC ns ctxt con) = text "forall" <+> hsep (map ppr ns)
357 <+> char '.' <+> sep [pprCxt ctxt, ppr con]
358
359 ------------------------------
360 pprVarStrictType :: (Name, Strict, Type) -> Doc
361 -- Slight infelicity: with print non-atomic type with parens
362 pprVarStrictType (v, str, t) = ppr v <+> text "::" <+> pprStrictType (str, t)
363
364 ------------------------------
365 pprStrictType :: (Strict, Type) -> Doc
366 -- Prints with parens if not already atomic
367 pprStrictType (IsStrict, t) = char '!' <> pprParendType t
368 pprStrictType (NotStrict, t) = pprParendType t
369
370 ------------------------------
371 pprParendType :: Type -> Doc
372 pprParendType (VarT v) = ppr v
373 pprParendType (ConT c) = ppr c
374 pprParendType (TupleT 0) = text "()"
375 pprParendType (TupleT n) = parens (hcat (replicate (n-1) comma))
376 pprParendType ArrowT = parens (text "->")
377 pprParendType ListT = text "[]"
378 pprParendType other = parens (ppr other)
379
380 instance Ppr Type where
381 ppr (ForallT tvars ctxt ty)
382 = text "forall" <+> hsep (map ppr tvars) <+> text "."
383 <+> sep [pprCxt ctxt, ppr ty]
384 ppr (SigT ty k) = ppr ty <+> text "::" <+> ppr k
385 ppr ty = pprTyApp (split ty)
386
387 pprTyApp :: (Type, [Type]) -> Doc
388 pprTyApp (ArrowT, [arg1,arg2]) = sep [pprFunArgType arg1 <+> text "->", ppr arg2]
389 pprTyApp (ListT, [arg]) = brackets (ppr arg)
390 pprTyApp (TupleT n, args)
391 | length args == n = parens (sep (punctuate comma (map ppr args)))
392 pprTyApp (fun, args) = pprParendType fun <+> sep (map pprParendType args)
393
394 pprFunArgType :: Type -> Doc -- Should really use a precedence argument
395 -- Everything except forall and (->) binds more tightly than (->)
396 pprFunArgType ty@(ForallT {}) = parens (ppr ty)
397 pprFunArgType ty@((ArrowT `AppT` _) `AppT` _) = parens (ppr ty)
398 pprFunArgType ty@(SigT _ _) = parens (ppr ty)
399 pprFunArgType ty = ppr ty
400
401 split :: Type -> (Type, [Type]) -- Split into function and args
402 split t = go t []
403 where go (AppT t1 t2) args = go t1 (t2:args)
404 go ty args = (ty, args)
405
406 ------------------------------
407 instance Ppr TyVarBndr where
408 ppr (PlainTV nm) = ppr nm
409 ppr (KindedTV nm k) = parens (ppr nm <+> text "::" <+> ppr k)
410
411 instance Ppr Kind where
412 ppr StarK = char '*'
413 ppr (ArrowK k1 k2) = pprArrowArgKind k1 <+> text "->" <+> ppr k2
414
415 pprArrowArgKind :: Kind -> Doc
416 pprArrowArgKind k@(ArrowK _ _) = parens (ppr k)
417 pprArrowArgKind k = ppr k
418
419 ------------------------------
420 pprCxt :: Cxt -> Doc
421 pprCxt [] = empty
422 pprCxt [t] = ppr t <+> text "=>"
423 pprCxt ts = parens (sep $ punctuate comma $ map ppr ts) <+> text "=>"
424
425 ------------------------------
426 instance Ppr Pred where
427 ppr (ClassP cla tys) = ppr cla <+> sep (map pprParendType tys)
428 ppr (EqualP ty1 ty2) = pprFunArgType ty1 <+> char '~' <+> pprFunArgType ty2
429
430 ------------------------------
431 instance Ppr Range where
432 ppr = brackets . pprRange
433 where pprRange :: Range -> Doc
434 pprRange (FromR e) = ppr e <> text ".."
435 pprRange (FromThenR e1 e2) = ppr e1 <> text ","
436 <> ppr e2 <> text ".."
437 pprRange (FromToR e1 e2) = ppr e1 <> text ".." <> ppr e2
438 pprRange (FromThenToR e1 e2 e3) = ppr e1 <> text ","
439 <> ppr e2 <> text ".."
440 <> ppr e3
441
442 ------------------------------
443 where_clause :: [Dec] -> Doc
444 where_clause [] = empty
445 where_clause ds = nest nestDepth $ text "where" <+> vcat (map (ppr_dec False) ds)
446
447 showtextl :: Show a => a -> Doc
448 showtextl = text . map toLower . show
449