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