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