Merge remote-tracking branch 'origin/master' into type-nats
[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 <+> (if inline then text "INLINE" else text "NOINLINE")
330 <+> (if conlike then text "CONLIKE" else empty)
331 <+> ppr_activation activation
332 <+> ppr n
333 <+> text "#-}"
334 ppr (SpecialiseP n ty Nothing)
335 = sep [ text "{-# SPECIALISE"
336 , ppr n <+> text "::"
337 , ppr ty
338 , text "#-}"
339 ]
340 ppr (SpecialiseP n ty (Just (InlineSpec inline _conlike activation)))
341 = sep [ text "{-# SPECIALISE" <+>
342 (if inline then text "INLINE" else text "NOINLINE") <+>
343 ppr_activation activation
344 , ppr n <+> text "::"
345 , ppr ty
346 , text "#-}"
347 ]
348 where
349
350 ppr_activation :: Maybe (Bool, Int) -> Doc
351 ppr_activation (Just (beforeFrom, i))
352 = brackets $ (if beforeFrom then empty else char '~') <+> int i
353 ppr_activation Nothing = empty
354
355 ------------------------------
356 instance Ppr Clause where
357 ppr (Clause ps rhs ds) = hsep (map (pprPat appPrec) ps) <+> pprBody True rhs
358 $$ where_clause ds
359
360 ------------------------------
361 instance Ppr Con where
362 ppr (NormalC c sts) = ppr c <+> sep (map pprStrictType sts)
363 ppr (RecC c vsts)
364 = ppr c <+> braces (sep (punctuate comma $ map pprVarStrictType vsts))
365 ppr (InfixC st1 c st2) = pprStrictType st1
366 <+> pprName' Infix c
367 <+> pprStrictType st2
368 ppr (ForallC ns ctxt con) = text "forall" <+> hsep (map ppr ns)
369 <+> char '.' <+> sep [pprCxt ctxt, ppr con]
370
371 ------------------------------
372 pprVarStrictType :: (Name, Strict, Type) -> Doc
373 -- Slight infelicity: with print non-atomic type with parens
374 pprVarStrictType (v, str, t) = ppr v <+> text "::" <+> pprStrictType (str, t)
375
376 ------------------------------
377 pprStrictType :: (Strict, Type) -> Doc
378 -- Prints with parens if not already atomic
379 pprStrictType (IsStrict, t) = char '!' <> pprParendType t
380 pprStrictType (NotStrict, t) = pprParendType t
381 pprStrictType (Unpacked, t) = text "{-# UNPACK #-} !" <> pprParendType t
382
383 ------------------------------
384 pprParendType :: Type -> Doc
385 pprParendType (VarT v) = ppr v
386 pprParendType (ConT c) = ppr c
387 pprParendType (TupleT 0) = text "()"
388 pprParendType (TupleT n) = parens (hcat (replicate (n-1) comma))
389 pprParendType (UnboxedTupleT n) = hashParens $ hcat $ replicate (n-1) comma
390 pprParendType ArrowT = parens (text "->")
391 pprParendType ListT = text "[]"
392 pprParendType (LitT l) = pprTyLit l
393 pprParendType other = parens (ppr other)
394
395 instance Ppr Type where
396 ppr (ForallT tvars ctxt ty)
397 = text "forall" <+> hsep (map ppr tvars) <+> text "."
398 <+> sep [pprCxt ctxt, ppr ty]
399 ppr (SigT ty k) = ppr ty <+> text "::" <+> ppr k
400 ppr ty = pprTyApp (split ty)
401
402 pprTyApp :: (Type, [Type]) -> Doc
403 pprTyApp (ArrowT, [arg1,arg2]) = sep [pprFunArgType arg1 <+> text "->", ppr arg2]
404 pprTyApp (ListT, [arg]) = brackets (ppr arg)
405 pprTyApp (TupleT n, args)
406 | length args == n = parens (sep (punctuate comma (map ppr args)))
407 pprTyApp (fun, args) = pprParendType fun <+> sep (map pprParendType args)
408
409 pprFunArgType :: Type -> Doc -- Should really use a precedence argument
410 -- Everything except forall and (->) binds more tightly than (->)
411 pprFunArgType ty@(ForallT {}) = parens (ppr ty)
412 pprFunArgType ty@((ArrowT `AppT` _) `AppT` _) = parens (ppr ty)
413 pprFunArgType ty@(SigT _ _) = parens (ppr ty)
414 pprFunArgType ty = ppr ty
415
416 split :: Type -> (Type, [Type]) -- Split into function and args
417 split t = go t []
418 where go (AppT t1 t2) args = go t1 (t2:args)
419 go ty args = (ty, args)
420
421 pprTyLit :: TyLit -> Doc
422 pprTyLit (NumTyLit n) = integer n
423 pprTyLit (StrTyLit s) = text (show s)
424
425 instance Ppr TyLit where
426 ppr = pprTyLit
427
428 ------------------------------
429 instance Ppr TyVarBndr where
430 ppr (PlainTV nm) = ppr nm
431 ppr (KindedTV nm k) = parens (ppr nm <+> text "::" <+> ppr k)
432
433 instance Ppr Kind where
434 ppr StarK = char '*'
435 ppr (ArrowK k1 k2) = pprArrowArgKind k1 <+> text "->" <+> ppr k2
436
437 pprArrowArgKind :: Kind -> Doc
438 pprArrowArgKind k@(ArrowK _ _) = parens (ppr k)
439 pprArrowArgKind k = ppr k
440
441 ------------------------------
442 pprCxt :: Cxt -> Doc
443 pprCxt [] = empty
444 pprCxt [t] = ppr t <+> text "=>"
445 pprCxt ts = parens (sep $ punctuate comma $ map ppr ts) <+> text "=>"
446
447 ------------------------------
448 instance Ppr Pred where
449 ppr (ClassP cla tys) = ppr cla <+> sep (map pprParendType tys)
450 ppr (EqualP ty1 ty2) = pprFunArgType ty1 <+> char '~' <+> pprFunArgType ty2
451
452 ------------------------------
453 instance Ppr Range where
454 ppr = brackets . pprRange
455 where pprRange :: Range -> Doc
456 pprRange (FromR e) = ppr e <> text ".."
457 pprRange (FromThenR e1 e2) = ppr e1 <> text ","
458 <> ppr e2 <> text ".."
459 pprRange (FromToR e1 e2) = ppr e1 <> text ".." <> ppr e2
460 pprRange (FromThenToR e1 e2 e3) = ppr e1 <> text ","
461 <> ppr e2 <> text ".."
462 <> ppr e3
463
464 ------------------------------
465 where_clause :: [Dec] -> Doc
466 where_clause [] = empty
467 where_clause ds = nest nestDepth $ text "where" <+> vcat (map (ppr_dec False) ds)
468
469 showtextl :: Show a => a -> Doc
470 showtextl = text . map toLower . show
471
472 hashParens :: Doc -> Doc
473 hashParens d = text "(# " <> d <> text " #)"
474