Make TH capable of quoting GADT declarations (Trac #5217)
[ghc-hetmet.git] / compiler / hsSyn / HsTypes.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 HsTypes: Abstract syntax: user-defined types
7
8 \begin{code}
9 {-# LANGUAGE DeriveDataTypeable #-}
10
11 module HsTypes (
12         HsType(..), LHsType, 
13         HsTyVarBndr(..), LHsTyVarBndr,
14         HsExplicitFlag(..),
15         HsContext, LHsContext,
16         HsPred(..), LHsPred,
17         HsQuasiQuote(..),
18
19         LBangType, BangType, HsBang(..), 
20         getBangType, getBangStrictness, 
21
22         ConDeclField(..), pprConDeclFields,
23         
24         mkExplicitHsForAllTy, mkImplicitHsForAllTy, hsExplicitTvs,
25         hsTyVarName, hsTyVarNames, replaceTyVarName,
26         hsTyVarKind, hsTyVarNameKind,
27         hsLTyVarName, hsLTyVarNames, hsLTyVarLocName, hsLTyVarLocNames,
28         splitHsInstDeclTy, splitHsFunType,
29         splitHsAppTys, mkHsAppTys,
30         
31         -- Type place holder
32         PostTcType, placeHolderType, PostTcKind, placeHolderKind,
33
34         -- Printing
35         pprParendHsType, pprHsForAll, pprHsContext, ppr_hs_context,
36     ) where
37
38 import {-# SOURCE #-} HsExpr ( HsSplice, pprSplice )
39
40 import NameSet( FreeVars )
41 import Type
42 import HsDoc
43 import BasicTypes
44 import SrcLoc
45 import StaticFlags
46 import Outputable
47 import FastString
48
49 import Data.Data
50 \end{code}
51
52
53 %************************************************************************
54 %*                                                                      *
55 \subsection{Annotating the syntax}
56 %*                                                                      *
57 %************************************************************************
58
59 \begin{code}
60 type PostTcKind = Kind
61 type PostTcType = Type          -- Used for slots in the abstract syntax
62                                 -- where we want to keep slot for a type
63                                 -- to be added by the type checker...but
64                                 -- before typechecking it's just bogus
65
66 placeHolderType :: PostTcType   -- Used before typechecking
67 placeHolderType  = panic "Evaluated the place holder for a PostTcType"
68
69 placeHolderKind :: PostTcKind   -- Used before typechecking
70 placeHolderKind  = panic "Evaluated the place holder for a PostTcKind"
71 \end{code}
72
73 %************************************************************************
74 %*                                                                      *
75         Quasi quotes; used in types and elsewhere
76 %*                                                                      *
77 %************************************************************************
78
79 \begin{code}
80 data HsQuasiQuote id = HsQuasiQuote 
81                            id           -- The quasi-quoter
82                            SrcSpan      -- The span of the enclosed string
83                            FastString   -- The enclosed string
84   deriving (Data, Typeable)
85
86 instance OutputableBndr id => Outputable (HsQuasiQuote id) where
87     ppr = ppr_qq
88
89 ppr_qq :: OutputableBndr id => HsQuasiQuote id -> SDoc
90 ppr_qq (HsQuasiQuote quoter _ quote) =
91     char '[' <> ppr quoter <> ptext (sLit "|") <>
92     ppr quote <> ptext (sLit "|]")
93 \end{code}
94
95
96 %************************************************************************
97 %*                                                                      *
98 \subsection{Bang annotations}
99 %*                                                                      *
100 %************************************************************************
101
102 \begin{code}
103 type LBangType name = Located (BangType name)
104 type BangType name  = HsType name       -- Bangs are in the HsType data type
105
106 getBangType :: LHsType a -> LHsType a
107 getBangType (L _ (HsBangTy _ ty)) = ty
108 getBangType ty                    = ty
109
110 getBangStrictness :: LHsType a -> HsBang
111 getBangStrictness (L _ (HsBangTy s _)) = s
112 getBangStrictness _                    = HsNoBang
113 \end{code}
114
115
116 %************************************************************************
117 %*                                                                      *
118 \subsection{Data types}
119 %*                                                                      *
120 %************************************************************************
121
122 This is the syntax for types as seen in type signatures.
123
124 \begin{code}
125 type LHsContext name = Located (HsContext name)
126
127 type HsContext name = [LHsPred name]
128
129 type LHsPred name = Located (HsPred name)
130
131 data HsPred name = HsClassP name [LHsType name]          -- class constraint
132                  | HsEqualP (LHsType name) (LHsType name)-- equality constraint
133                  | HsIParam (IPName name) (LHsType name)
134                  deriving (Data, Typeable)
135
136 type LHsType name = Located (HsType name)
137
138 data HsType name
139   = HsForAllTy  HsExplicitFlag          -- Renamer leaves this flag unchanged, to record the way
140                                         -- the user wrote it originally, so that the printer can
141                                         -- print it as the user wrote it
142                 [LHsTyVarBndr name]     -- With ImplicitForAll, this is the empty list
143                                         -- until the renamer fills in the variables
144                 (LHsContext name)
145                 (LHsType name)
146
147   | HsTyVar             name            -- Type variable or type constructor
148
149   | HsAppTy             (LHsType name)
150                         (LHsType name)
151
152   | HsFunTy             (LHsType name)   -- function type
153                         (LHsType name)
154
155   | HsListTy            (LHsType name)  -- Element type
156
157   | HsPArrTy            (LHsType name)  -- Elem. type of parallel array: [:t:]
158
159   | HsTupleTy           Boxity
160                         [LHsType name]  -- Element types (length gives arity)
161
162   | HsOpTy              (LHsType name) (Located name) (LHsType name)
163
164   | HsParTy             (LHsType name)   
165         -- Parenthesis preserved for the precedence re-arrangement in RnTypes
166         -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c!
167         -- 
168         -- However, NB that toHsType doesn't add HsParTys (in an effort to keep
169         -- interface files smaller), so when printing a HsType we may need to
170         -- add parens.  
171
172   | HsPredTy            (HsPred name)   -- Only used in the type of an instance
173                                         -- declaration, eg.  Eq [a] -> Eq a
174                                         --                             ^^^^
175                                         --                            HsPredTy
176                                         -- Note no need for location info on the
177                                         -- Enclosed HsPred; the one on the type will do
178
179   | HsKindSig           (LHsType name)  -- (ty :: kind)
180                         Kind            -- A type with a kind signature
181
182   | HsQuasiQuoteTy      (HsQuasiQuote name)
183
184   | HsSpliceTy          (HsSplice name) 
185                         FreeVars        -- Variables free in the splice (filled in by renamer)
186                         PostTcKind
187
188   | HsDocTy             (LHsType name) LHsDocString -- A documented type
189
190   | HsBangTy    HsBang (LHsType name)   -- Bang-style type annotations 
191   | HsRecTy [ConDeclField name]         -- Only in data type declarations
192
193   | HsCoreTy Type       -- An escape hatch for tunnelling a *closed* 
194                         -- Core Type through HsSyn.  
195                                          
196   deriving (Data, Typeable)
197
198 data HsExplicitFlag = Explicit | Implicit deriving (Data, Typeable)
199
200 data ConDeclField name  -- Record fields have Haddoc docs on them
201   = ConDeclField { cd_fld_name :: Located name,
202                    cd_fld_type :: LBangType name, 
203                    cd_fld_doc  :: Maybe LHsDocString }
204   deriving (Data, Typeable)
205
206 -----------------------
207 -- Combine adjacent for-alls. 
208 -- The following awkward situation can happen otherwise:
209 --      f :: forall a. ((Num a) => Int)
210 -- might generate HsForAll (Just [a]) [] (HsForAll Nothing [Num a] t)
211 -- Then a isn't discovered as ambiguous, and we abstract the AbsBinds wrt []
212 -- but the export list abstracts f wrt [a].  Disaster.
213 --
214 -- A valid type must have one for-all at the top of the type, or of the fn arg types
215
216 mkImplicitHsForAllTy ::                        LHsContext name -> LHsType name -> HsType name
217 mkExplicitHsForAllTy :: [LHsTyVarBndr name] -> LHsContext name -> LHsType name -> HsType name
218 mkImplicitHsForAllTy     ctxt ty = mkHsForAllTy Implicit [] ctxt ty
219 mkExplicitHsForAllTy tvs ctxt ty = mkHsForAllTy Explicit tvs ctxt ty
220
221 mkHsForAllTy :: HsExplicitFlag -> [LHsTyVarBndr name] -> LHsContext name -> LHsType name -> HsType name
222 -- Smart constructor for HsForAllTy
223 mkHsForAllTy exp tvs (L _ []) ty = mk_forall_ty exp tvs ty
224 mkHsForAllTy exp tvs ctxt ty = HsForAllTy exp tvs ctxt ty
225
226 -- mk_forall_ty makes a pure for-all type (no context)
227 mk_forall_ty :: HsExplicitFlag -> [LHsTyVarBndr name] -> LHsType name -> HsType name
228 mk_forall_ty exp  tvs  (L _ (HsParTy ty))                   = mk_forall_ty exp tvs ty
229 mk_forall_ty exp1 tvs1 (L _ (HsForAllTy exp2 tvs2 ctxt ty)) = mkHsForAllTy (exp1 `plus` exp2) (tvs1 ++ tvs2) ctxt ty
230 mk_forall_ty exp  tvs  ty                                   = HsForAllTy exp tvs (L noSrcSpan []) ty
231         -- Even if tvs is empty, we still make a HsForAll!
232         -- In the Implicit case, this signals the place to do implicit quantification
233         -- In the Explicit case, it prevents implicit quantification    
234         --      (see the sigtype production in Parser.y.pp)
235         --      so that (forall. ty) isn't implicitly quantified
236
237 plus :: HsExplicitFlag -> HsExplicitFlag -> HsExplicitFlag
238 Implicit `plus` Implicit = Implicit
239 _        `plus` _        = Explicit
240
241 hsExplicitTvs :: LHsType name -> [name]
242 -- The explicitly-given forall'd type variables of a HsType
243 hsExplicitTvs (L _ (HsForAllTy Explicit tvs _ _)) = hsLTyVarNames tvs
244 hsExplicitTvs _                                   = []
245
246 ---------------------
247 type LHsTyVarBndr name = Located (HsTyVarBndr name)
248
249 data HsTyVarBndr name
250   = UserTyVar           -- No explicit kinding
251          name           -- See Note [Printing KindedTyVars]
252          PostTcKind
253
254   | KindedTyVar 
255          name 
256          Kind 
257       --  *** NOTA BENE *** A "monotype" in a pragma can have
258       -- for-alls in it, (mostly to do with dictionaries).  These
259       -- must be explicitly Kinded.
260   deriving (Data, Typeable)
261
262 hsTyVarName :: HsTyVarBndr name -> name
263 hsTyVarName (UserTyVar n _)   = n
264 hsTyVarName (KindedTyVar n _) = n
265
266 hsTyVarKind :: HsTyVarBndr name -> Kind
267 hsTyVarKind (UserTyVar _ k)   = k
268 hsTyVarKind (KindedTyVar _ k) = k
269
270 hsTyVarNameKind :: HsTyVarBndr name -> (name, Kind)
271 hsTyVarNameKind (UserTyVar n k)   = (n,k)
272 hsTyVarNameKind (KindedTyVar n k) = (n,k)
273
274 hsLTyVarName :: LHsTyVarBndr name -> name
275 hsLTyVarName = hsTyVarName . unLoc
276
277 hsTyVarNames :: [HsTyVarBndr name] -> [name]
278 hsTyVarNames tvs = map hsTyVarName tvs
279
280 hsLTyVarNames :: [LHsTyVarBndr name] -> [name]
281 hsLTyVarNames = map hsLTyVarName
282
283 hsLTyVarLocName :: LHsTyVarBndr name -> Located name
284 hsLTyVarLocName = fmap hsTyVarName
285
286 hsLTyVarLocNames :: [LHsTyVarBndr name] -> [Located name]
287 hsLTyVarLocNames = map hsLTyVarLocName
288
289 replaceTyVarName :: HsTyVarBndr name1 -> name2 -> HsTyVarBndr name2
290 replaceTyVarName (UserTyVar _ k)   n' = UserTyVar n' k
291 replaceTyVarName (KindedTyVar _ k) n' = KindedTyVar n' k
292 \end{code}
293
294
295 \begin{code}
296 splitHsAppTys :: LHsType n -> [LHsType n] -> (LHsType n, [LHsType n])
297 splitHsAppTys (L _ (HsAppTy f a)) as = splitHsAppTys f (a:as)
298 splitHsAppTys f                   as = (f,as)
299
300 mkHsAppTys :: OutputableBndr n => LHsType n -> [LHsType n] -> HsType n
301 mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
302 mkHsAppTys fun_ty (arg_ty:arg_tys)
303   = foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
304   where
305     mk_app fun arg = HsAppTy (noLoc fun) arg    
306        -- Add noLocs for inner nodes of the application; 
307        -- they are never used 
308
309 splitHsInstDeclTy 
310     :: OutputableBndr name
311     => HsType name 
312     -> ([LHsTyVarBndr name], HsContext name, name, [LHsType name])
313         -- Split up an instance decl type, returning the pieces
314
315 splitHsInstDeclTy inst_ty
316   = case inst_ty of
317         HsParTy (L _ ty)              -> splitHsInstDeclTy ty
318         HsForAllTy _ tvs cxt (L _ ty) -> split_tau tvs (unLoc cxt) ty
319         other                         -> split_tau []  []          other
320     -- The type vars should have been computed by now, even if they were implicit
321   where
322     split_tau tvs cxt (HsPredTy (HsClassP cls tys)) = (tvs, cxt, cls, tys)
323     split_tau tvs cxt (HsParTy (L _ ty))            = split_tau tvs cxt ty
324     split_tau _ _ _ = pprPanic "splitHsInstDeclTy" (ppr inst_ty)
325
326 -- Splits HsType into the (init, last) parts
327 -- Breaks up any parens in the result type: 
328 --      splitHsFunType (a -> (b -> c)) = ([a,b], c)
329 splitHsFunType :: LHsType name -> ([LHsType name], LHsType name)
330 splitHsFunType (L _ (HsFunTy x y)) = (x:args, res)
331   where
332   (args, res) = splitHsFunType y
333 splitHsFunType (L _ (HsParTy ty))  = splitHsFunType ty
334 splitHsFunType other               = ([], other)
335 \end{code}
336
337
338 %************************************************************************
339 %*                                                                      *
340 \subsection{Pretty printing}
341 %*                                                                      *
342 %************************************************************************
343
344 \begin{code}
345 instance (OutputableBndr name) => Outputable (HsType name) where
346     ppr ty = pprHsType ty
347
348 instance (Outputable name) => Outputable (HsTyVarBndr name) where
349     ppr (UserTyVar name _)      = ppr name
350     ppr (KindedTyVar name kind) = hsep [ppr name, dcolon, pprParendKind kind]
351
352 instance OutputableBndr name => Outputable (HsPred name) where
353     ppr (HsClassP clas tys) = ppr clas <+> hsep (map pprLHsType tys)
354     ppr (HsEqualP t1 t2)    = hsep [pprLHsType t1, ptext (sLit "~"), 
355                                     pprLHsType t2]
356     ppr (HsIParam n ty)     = hsep [ppr n, dcolon, ppr ty]
357
358 pprLHsType :: OutputableBndr name => LHsType name -> SDoc
359 pprLHsType = pprParendHsType . unLoc
360
361 pprHsForAll :: OutputableBndr name => HsExplicitFlag -> [LHsTyVarBndr name] ->  LHsContext name -> SDoc
362 pprHsForAll exp tvs cxt 
363   | show_forall = forall_part <+> pprHsContext (unLoc cxt)
364   | otherwise   = pprHsContext (unLoc cxt)
365   where
366     show_forall =  opt_PprStyle_Debug
367                 || (not (null tvs) && is_explicit)
368     is_explicit = case exp of {Explicit -> True; Implicit -> False}
369     forall_part = ptext (sLit "forall") <+> interppSP tvs <> dot
370
371 pprHsContext :: (OutputableBndr name) => HsContext name -> SDoc
372 pprHsContext []         = empty
373 pprHsContext [L _ pred] 
374    | noParenHsPred pred = ppr pred <+> darrow
375 pprHsContext cxt        = ppr_hs_context cxt <+> darrow
376
377 noParenHsPred :: HsPred name -> Bool
378 -- c.f. TypeRep.noParenPred
379 noParenHsPred (HsClassP {}) = True
380 noParenHsPred (HsEqualP {}) = True
381 noParenHsPred (HsIParam {}) = False
382
383 ppr_hs_context :: (OutputableBndr name) => HsContext name -> SDoc
384 ppr_hs_context []  = empty
385 ppr_hs_context cxt = parens (interpp'SP cxt)
386
387 pprConDeclFields :: OutputableBndr name => [ConDeclField name] -> SDoc
388 pprConDeclFields fields = braces (sep (punctuate comma (map ppr_fld fields)))
389   where
390     ppr_fld (ConDeclField { cd_fld_name = n, cd_fld_type = ty, 
391                             cd_fld_doc = doc })
392         = ppr n <+> dcolon <+> ppr ty <+> ppr_mbDoc doc
393 \end{code}
394
395 Note [Printing KindedTyVars]
396 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
397 Trac #3830 reminded me that we should really only print the kind
398 signature on a KindedTyVar if the kind signature was put there by the
399 programmer.  During kind inference GHC now adds a PostTcKind to UserTyVars,
400 rather than converting to KindedTyVars as before.
401
402 (As it happens, the message in #3830 comes out a different way now,
403 and the problem doesn't show up; but having the flag on a KindedTyVar
404 seems like the Right Thing anyway.)
405
406 \begin{code}
407 pREC_TOP, pREC_FUN, pREC_OP, pREC_CON :: Int
408 pREC_TOP = 0  -- type   in ParseIface.y
409 pREC_FUN = 1  -- btype  in ParseIface.y
410               -- Used for LH arg of (->)
411 pREC_OP  = 2  -- Used for arg of any infix operator
412               -- (we don't keep their fixities around)
413 pREC_CON = 3  -- Used for arg of type applicn:
414               -- always parenthesise unless atomic
415
416 maybeParen :: Int       -- Precedence of context
417            -> Int       -- Precedence of top-level operator
418            -> SDoc -> SDoc      -- Wrap in parens if (ctxt >= op)
419 maybeParen ctxt_prec op_prec p | ctxt_prec >= op_prec = parens p
420                                | otherwise            = p
421         
422 -- printing works more-or-less as for Types
423
424 pprHsType, pprParendHsType :: (OutputableBndr name) => HsType name -> SDoc
425
426 pprHsType ty       = getPprStyle $ \sty -> ppr_mono_ty pREC_TOP (prepare sty ty)
427 pprParendHsType ty = ppr_mono_ty pREC_CON ty
428
429 -- Before printing a type
430 -- (a) Remove outermost HsParTy parens
431 -- (b) Drop top-level for-all type variables in user style
432 --     since they are implicit in Haskell
433 prepare :: PprStyle -> HsType name -> HsType name
434 prepare sty (HsParTy ty)          = prepare sty (unLoc ty)
435 prepare _   ty                    = ty
436
437 ppr_mono_lty :: (OutputableBndr name) => Int -> LHsType name -> SDoc
438 ppr_mono_lty ctxt_prec ty = ppr_mono_ty ctxt_prec (unLoc ty)
439
440 ppr_mono_ty :: (OutputableBndr name) => Int -> HsType name -> SDoc
441 ppr_mono_ty ctxt_prec (HsForAllTy exp tvs ctxt ty)
442   = maybeParen ctxt_prec pREC_FUN $
443     sep [pprHsForAll exp tvs ctxt, ppr_mono_lty pREC_TOP ty]
444
445 ppr_mono_ty _    (HsBangTy b ty)     = ppr b <> ppr ty
446 ppr_mono_ty _    (HsQuasiQuoteTy qq) = ppr qq
447 ppr_mono_ty _    (HsRecTy flds)      = pprConDeclFields flds
448 ppr_mono_ty _    (HsTyVar name)      = ppr name
449 ppr_mono_ty prec (HsFunTy ty1 ty2)   = ppr_fun_ty prec ty1 ty2
450 ppr_mono_ty _    (HsTupleTy con tys) = tupleParens con (interpp'SP tys)
451 ppr_mono_ty _    (HsKindSig ty kind) = parens (ppr_mono_lty pREC_TOP ty <+> dcolon <+> pprKind kind)
452 ppr_mono_ty _    (HsListTy ty)       = brackets (ppr_mono_lty pREC_TOP ty)
453 ppr_mono_ty _    (HsPArrTy ty)       = pabrackets (ppr_mono_lty pREC_TOP ty)
454 ppr_mono_ty _    (HsPredTy pred)     = ppr pred
455 ppr_mono_ty _    (HsSpliceTy s _ _)  = pprSplice s
456 ppr_mono_ty _    (HsCoreTy ty)       = ppr ty
457
458 ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty)
459   = maybeParen ctxt_prec pREC_CON $
460     hsep [ppr_mono_lty pREC_FUN fun_ty, ppr_mono_lty pREC_CON arg_ty]
461
462 ppr_mono_ty ctxt_prec (HsOpTy ty1 op ty2)  
463   = maybeParen ctxt_prec pREC_OP $
464     ppr_mono_lty pREC_OP ty1 <+> ppr op <+> ppr_mono_lty pREC_OP ty2
465
466 ppr_mono_ty _         (HsParTy ty)
467   = parens (ppr_mono_lty pREC_TOP ty)
468   -- Put the parens in where the user did
469   -- But we still use the precedence stuff to add parens because
470   --    toHsType doesn't put in any HsParTys, so we may still need them
471
472 ppr_mono_ty ctxt_prec (HsDocTy ty doc) 
473   = maybeParen ctxt_prec pREC_OP $
474     ppr_mono_lty pREC_OP ty <+> ppr (unLoc doc)
475   -- we pretty print Haddock comments on types as if they were
476   -- postfix operators
477
478 --------------------------
479 ppr_fun_ty :: (OutputableBndr name) => Int -> LHsType name -> LHsType name -> SDoc
480 ppr_fun_ty ctxt_prec ty1 ty2
481   = let p1 = ppr_mono_lty pREC_FUN ty1
482         p2 = ppr_mono_lty pREC_TOP ty2
483     in
484     maybeParen ctxt_prec pREC_FUN $
485     sep [p1, ptext (sLit "->") <+> p2]
486
487 --------------------------
488 pabrackets :: SDoc -> SDoc
489 pabrackets p = ptext (sLit "[:") <> p <> ptext (sLit ":]")
490 \end{code}
491
492