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