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