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