merge upstream
[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   | HsModalBoxType      name (LHsType name)     -- modal types; first argument is the environment classifier
160
161   | HsTupleTy           Boxity
162                         [LHsType name]  -- Element types (length gives arity)
163
164   | HsOpTy              (LHsType name) (Located name) (LHsType name)
165
166   | HsParTy             (LHsType name)   
167         -- Parenthesis preserved for the precedence re-arrangement in RnTypes
168         -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c!
169         -- 
170         -- However, NB that toHsType doesn't add HsParTys (in an effort to keep
171         -- interface files smaller), so when printing a HsType we may need to
172         -- add parens.  
173
174   | HsPredTy            (HsPred name)   -- Only used in the type of an instance
175                                         -- declaration, eg.  Eq [a] -> Eq a
176                                         --                             ^^^^
177                                         --                            HsPredTy
178                                         -- Note no need for location info on the
179                                         -- Enclosed HsPred; the one on the type will do
180
181   | HsKindSig           (LHsType name)  -- (ty :: kind)
182                         Kind            -- A type with a kind signature
183
184   | HsQuasiQuoteTy      (HsQuasiQuote name)
185
186   | HsSpliceTy          (HsSplice name) 
187                         FreeVars        -- Variables free in the splice (filled in by renamer)
188                         PostTcKind
189
190   | HsDocTy             (LHsType name) LHsDocString -- A documented type
191
192   | HsBangTy    HsBang (LHsType name)   -- Bang-style type annotations 
193   | HsRecTy [ConDeclField name]         -- Only in data type declarations
194
195   | HsCoreTy Type       -- An escape hatch for tunnelling a *closed* 
196                         -- Core Type through HsSyn.  
197                                          
198   deriving (Data, Typeable)
199
200 data HsExplicitFlag = Explicit | Implicit deriving (Data, Typeable)
201
202 data ConDeclField name  -- Record fields have Haddoc docs on them
203   = ConDeclField { cd_fld_name :: Located name,
204                    cd_fld_type :: LBangType name, 
205                    cd_fld_doc  :: Maybe LHsDocString }
206   deriving (Data, Typeable)
207
208 -----------------------
209 -- Combine adjacent for-alls. 
210 -- The following awkward situation can happen otherwise:
211 --      f :: forall a. ((Num a) => Int)
212 -- might generate HsForAll (Just [a]) [] (HsForAll Nothing [Num a] t)
213 -- Then a isn't discovered as ambiguous, and we abstract the AbsBinds wrt []
214 -- but the export list abstracts f wrt [a].  Disaster.
215 --
216 -- A valid type must have one for-all at the top of the type, or of the fn arg types
217
218 mkImplicitHsForAllTy ::                        LHsContext name -> LHsType name -> HsType name
219 mkExplicitHsForAllTy :: [LHsTyVarBndr name] -> LHsContext name -> LHsType name -> HsType name
220 mkImplicitHsForAllTy     ctxt ty = mkHsForAllTy Implicit [] ctxt ty
221 mkExplicitHsForAllTy tvs ctxt ty = mkHsForAllTy Explicit tvs ctxt ty
222
223 mkHsForAllTy :: HsExplicitFlag -> [LHsTyVarBndr name] -> LHsContext name -> LHsType name -> HsType name
224 -- Smart constructor for HsForAllTy
225 mkHsForAllTy exp tvs (L _ []) ty = mk_forall_ty exp tvs ty
226 mkHsForAllTy exp tvs ctxt ty = HsForAllTy exp tvs ctxt ty
227
228 -- mk_forall_ty makes a pure for-all type (no context)
229 mk_forall_ty :: HsExplicitFlag -> [LHsTyVarBndr name] -> LHsType name -> HsType name
230 mk_forall_ty exp  tvs  (L _ (HsParTy ty))                   = mk_forall_ty exp tvs ty
231 mk_forall_ty exp1 tvs1 (L _ (HsForAllTy exp2 tvs2 ctxt ty)) = mkHsForAllTy (exp1 `plus` exp2) (tvs1 ++ tvs2) ctxt ty
232 mk_forall_ty exp  tvs  ty                                   = HsForAllTy exp tvs (L noSrcSpan []) ty
233         -- Even if tvs is empty, we still make a HsForAll!
234         -- In the Implicit case, this signals the place to do implicit quantification
235         -- In the Explicit case, it prevents implicit quantification    
236         --      (see the sigtype production in Parser.y.pp)
237         --      so that (forall. ty) isn't implicitly quantified
238
239 plus :: HsExplicitFlag -> HsExplicitFlag -> HsExplicitFlag
240 Implicit `plus` Implicit = Implicit
241 _        `plus` _        = Explicit
242
243 hsExplicitTvs :: LHsType name -> [name]
244 -- The explicitly-given forall'd type variables of a HsType
245 hsExplicitTvs (L _ (HsForAllTy Explicit tvs _ _)) = hsLTyVarNames tvs
246 hsExplicitTvs _                                   = []
247
248 ---------------------
249 type LHsTyVarBndr name = Located (HsTyVarBndr name)
250
251 data HsTyVarBndr name
252   = UserTyVar           -- No explicit kinding
253          name           -- See Note [Printing KindedTyVars]
254          PostTcKind
255
256   | KindedTyVar 
257          name 
258          Kind 
259       --  *** NOTA BENE *** A "monotype" in a pragma can have
260       -- for-alls in it, (mostly to do with dictionaries).  These
261       -- must be explicitly Kinded.
262   deriving (Data, Typeable)
263
264 hsTyVarName :: HsTyVarBndr name -> name
265 hsTyVarName (UserTyVar n _)   = n
266 hsTyVarName (KindedTyVar n _) = n
267
268 hsTyVarKind :: HsTyVarBndr name -> Kind
269 hsTyVarKind (UserTyVar _ k)   = k
270 hsTyVarKind (KindedTyVar _ k) = k
271
272 hsTyVarNameKind :: HsTyVarBndr name -> (name, Kind)
273 hsTyVarNameKind (UserTyVar n k)   = (n,k)
274 hsTyVarNameKind (KindedTyVar n k) = (n,k)
275
276 hsLTyVarName :: LHsTyVarBndr name -> name
277 hsLTyVarName = hsTyVarName . unLoc
278
279 hsTyVarNames :: [HsTyVarBndr name] -> [name]
280 hsTyVarNames tvs = map hsTyVarName tvs
281
282 hsLTyVarNames :: [LHsTyVarBndr name] -> [name]
283 hsLTyVarNames = map hsLTyVarName
284
285 hsLTyVarLocName :: LHsTyVarBndr name -> Located name
286 hsLTyVarLocName = fmap hsTyVarName
287
288 hsLTyVarLocNames :: [LHsTyVarBndr name] -> [Located name]
289 hsLTyVarLocNames = map hsLTyVarLocName
290
291 replaceTyVarName :: HsTyVarBndr name1 -> name2 -> HsTyVarBndr name2
292 replaceTyVarName (UserTyVar _ k)   n' = UserTyVar n' k
293 replaceTyVarName (KindedTyVar _ k) n' = KindedTyVar n' k
294 \end{code}
295
296
297 \begin{code}
298 splitHsAppTys :: LHsType n -> [LHsType n] -> (LHsType n, [LHsType n])
299 splitHsAppTys (L _ (HsAppTy f a)) as = splitHsAppTys f (a:as)
300 splitHsAppTys f                   as = (f,as)
301
302 mkHsAppTys :: OutputableBndr n => LHsType n -> [LHsType n] -> HsType n
303 mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
304 mkHsAppTys fun_ty (arg_ty:arg_tys)
305   = foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
306   where
307     mk_app fun arg = HsAppTy (noLoc fun) arg    
308        -- Add noLocs for inner nodes of the application; 
309        -- they are never used 
310
311 splitHsInstDeclTy 
312     :: OutputableBndr name
313     => HsType name 
314     -> ([LHsTyVarBndr name], HsContext name, name, [LHsType name])
315         -- Split up an instance decl type, returning the pieces
316
317 splitHsInstDeclTy inst_ty
318   = case inst_ty of
319         HsParTy (L _ ty)              -> splitHsInstDeclTy ty
320         HsForAllTy _ tvs cxt (L _ ty) -> split_tau tvs (unLoc cxt) ty
321         other                         -> split_tau []  []          other
322     -- The type vars should have been computed by now, even if they were implicit
323   where
324     split_tau tvs cxt (HsPredTy (HsClassP cls tys)) = (tvs, cxt, cls, tys)
325     split_tau tvs cxt (HsParTy (L _ ty))            = split_tau tvs cxt ty
326     split_tau _ _ _ = pprPanic "splitHsInstDeclTy" (ppr inst_ty)
327
328 -- Splits HsType into the (init, last) parts
329 -- Breaks up any parens in the result type: 
330 --      splitHsFunType (a -> (b -> c)) = ([a,b], c)
331 splitHsFunType :: LHsType name -> ([LHsType name], LHsType name)
332 splitHsFunType (L _ (HsFunTy x y)) = (x:args, res)
333   where
334   (args, res) = splitHsFunType y
335 splitHsFunType (L _ (HsParTy ty))  = splitHsFunType ty
336 splitHsFunType other               = ([], other)
337 \end{code}
338
339
340 %************************************************************************
341 %*                                                                      *
342 \subsection{Pretty printing}
343 %*                                                                      *
344 %************************************************************************
345
346 \begin{code}
347 instance (OutputableBndr name) => Outputable (HsType name) where
348     ppr ty = pprHsType ty
349
350 instance (Outputable name) => Outputable (HsTyVarBndr name) where
351     ppr (UserTyVar name _)      = ppr name
352     ppr (KindedTyVar name kind) = hsep [ppr name, dcolon, pprParendKind kind]
353
354 instance OutputableBndr name => Outputable (HsPred name) where
355     ppr (HsClassP clas tys) = ppr clas <+> hsep (map pprLHsType tys)
356     ppr (HsEqualP t1 t2)    = hsep [pprLHsType t1, ptext (sLit "~"), 
357                                     pprLHsType t2]
358     ppr (HsIParam n ty)     = hsep [ppr n, dcolon, ppr ty]
359
360 pprLHsType :: OutputableBndr name => LHsType name -> SDoc
361 pprLHsType = pprParendHsType . unLoc
362
363 pprHsForAll :: OutputableBndr name => HsExplicitFlag -> [LHsTyVarBndr name] ->  LHsContext name -> SDoc
364 pprHsForAll exp tvs cxt 
365   | show_forall = forall_part <+> pprHsContext (unLoc cxt)
366   | otherwise   = pprHsContext (unLoc cxt)
367   where
368     show_forall =  opt_PprStyle_Debug
369                 || (not (null tvs) && is_explicit)
370     is_explicit = case exp of {Explicit -> True; Implicit -> False}
371     forall_part = ptext (sLit "forall") <+> interppSP tvs <> dot
372
373 pprHsContext :: (OutputableBndr name) => HsContext name -> SDoc
374 pprHsContext []         = empty
375 pprHsContext [L _ pred] 
376    | noParenHsPred pred = ppr pred <+> darrow
377 pprHsContext cxt        = ppr_hs_context cxt <+> darrow
378
379 noParenHsPred :: HsPred name -> Bool
380 -- c.f. TypeRep.noParenPred
381 noParenHsPred (HsClassP {}) = True
382 noParenHsPred (HsEqualP {}) = True
383 noParenHsPred (HsIParam {}) = False
384
385 ppr_hs_context :: (OutputableBndr name) => HsContext name -> SDoc
386 ppr_hs_context []  = empty
387 ppr_hs_context cxt = parens (interpp'SP cxt)
388
389 pprConDeclFields :: OutputableBndr name => [ConDeclField name] -> SDoc
390 pprConDeclFields fields = braces (sep (punctuate comma (map ppr_fld fields)))
391   where
392     ppr_fld (ConDeclField { cd_fld_name = n, cd_fld_type = ty, 
393                             cd_fld_doc = doc })
394         = ppr n <+> dcolon <+> ppr ty <+> ppr_mbDoc doc
395 \end{code}
396
397 Note [Printing KindedTyVars]
398 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
399 Trac #3830 reminded me that we should really only print the kind
400 signature on a KindedTyVar if the kind signature was put there by the
401 programmer.  During kind inference GHC now adds a PostTcKind to UserTyVars,
402 rather than converting to KindedTyVars as before.
403
404 (As it happens, the message in #3830 comes out a different way now,
405 and the problem doesn't show up; but having the flag on a KindedTyVar
406 seems like the Right Thing anyway.)
407
408 \begin{code}
409 pREC_TOP, pREC_FUN, pREC_OP, pREC_CON :: Int
410 pREC_TOP = 0  -- type   in ParseIface.y
411 pREC_FUN = 1  -- btype  in ParseIface.y
412               -- Used for LH arg of (->)
413 pREC_OP  = 2  -- Used for arg of any infix operator
414               -- (we don't keep their fixities around)
415 pREC_CON = 3  -- Used for arg of type applicn:
416               -- always parenthesise unless atomic
417
418 maybeParen :: Int       -- Precedence of context
419            -> Int       -- Precedence of top-level operator
420            -> SDoc -> SDoc      -- Wrap in parens if (ctxt >= op)
421 maybeParen ctxt_prec op_prec p | ctxt_prec >= op_prec = parens p
422                                | otherwise            = p
423         
424 -- printing works more-or-less as for Types
425
426 pprHsType, pprParendHsType :: (OutputableBndr name) => HsType name -> SDoc
427
428 pprHsType ty       = getPprStyle $ \sty -> ppr_mono_ty pREC_TOP (prepare sty ty)
429 pprParendHsType ty = ppr_mono_ty pREC_CON ty
430
431 -- Before printing a type
432 -- (a) Remove outermost HsParTy parens
433 -- (b) Drop top-level for-all type variables in user style
434 --     since they are implicit in Haskell
435 prepare :: PprStyle -> HsType name -> HsType name
436 prepare sty (HsParTy ty)          = prepare sty (unLoc ty)
437 prepare _   ty                    = ty
438
439 ppr_mono_lty :: (OutputableBndr name) => Int -> LHsType name -> SDoc
440 ppr_mono_lty ctxt_prec ty = ppr_mono_ty ctxt_prec (unLoc ty)
441
442 ppr_mono_ty :: (OutputableBndr name) => Int -> HsType name -> SDoc
443 ppr_mono_ty ctxt_prec (HsForAllTy exp tvs ctxt ty)
444   = maybeParen ctxt_prec pREC_FUN $
445     sep [pprHsForAll exp tvs ctxt, ppr_mono_lty pREC_TOP ty]
446
447 ppr_mono_ty _    (HsBangTy b ty)     = ppr b <> ppr ty
448 ppr_mono_ty _    (HsQuasiQuoteTy qq) = ppr qq
449 ppr_mono_ty _    (HsRecTy flds)      = pprConDeclFields flds
450 ppr_mono_ty _    (HsTyVar name)      = ppr name
451 ppr_mono_ty prec (HsFunTy ty1 ty2)   = ppr_fun_ty prec ty1 ty2
452 ppr_mono_ty _    (HsTupleTy con tys) = tupleParens con (interpp'SP tys)
453 ppr_mono_ty _    (HsKindSig ty kind) = parens (ppr_mono_lty pREC_TOP ty <+> dcolon <+> pprKind kind)
454 ppr_mono_ty _    (HsListTy ty)       = brackets (ppr_mono_lty pREC_TOP ty)
455 ppr_mono_ty _    (HsPArrTy ty)       = pabrackets (ppr_mono_lty pREC_TOP ty)
456 ppr_mono_ty _    (HsModalBoxType ecn ty) = ppr_modalBoxType (ppr ecn) (ppr_mono_lty pREC_TOP ty)
457 ppr_mono_ty _    (HsPredTy pred)     = ppr pred
458 ppr_mono_ty _    (HsSpliceTy s _ _)  = pprSplice s
459 ppr_mono_ty _    (HsCoreTy ty)       = ppr ty
460
461 ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty)
462   = maybeParen ctxt_prec pREC_CON $
463     hsep [ppr_mono_lty pREC_FUN fun_ty, ppr_mono_lty pREC_CON arg_ty]
464
465 ppr_mono_ty ctxt_prec (HsOpTy ty1 op ty2)  
466   = maybeParen ctxt_prec pREC_OP $
467     ppr_mono_lty pREC_OP ty1 <+> ppr op <+> ppr_mono_lty pREC_OP ty2
468
469 ppr_mono_ty _         (HsParTy ty)
470   = parens (ppr_mono_lty pREC_TOP ty)
471   -- Put the parens in where the user did
472   -- But we still use the precedence stuff to add parens because
473   --    toHsType doesn't put in any HsParTys, so we may still need them
474
475 ppr_mono_ty ctxt_prec (HsDocTy ty doc) 
476   = maybeParen ctxt_prec pREC_OP $
477     ppr_mono_lty pREC_OP ty <+> ppr (unLoc doc)
478   -- we pretty print Haddock comments on types as if they were
479   -- postfix operators
480
481 --------------------------
482 ppr_fun_ty :: (OutputableBndr name) => Int -> LHsType name -> LHsType name -> SDoc
483 ppr_fun_ty ctxt_prec ty1 ty2
484   = let p1 = ppr_mono_lty pREC_FUN ty1
485         p2 = ppr_mono_lty pREC_TOP ty2
486     in
487     maybeParen ctxt_prec pREC_FUN $
488     sep [p1, ptext (sLit "->") <+> p2]
489
490 --------------------------
491 pabrackets :: SDoc -> SDoc
492 pabrackets p = ptext (sLit "[:") <> p <> ptext (sLit ":]")
493
494 ppr_modalBoxType :: SDoc -> SDoc -> SDoc
495 ppr_modalBoxType ecn p = ptext (sLit "<[") <> p <> ptext (sLit "]>@") <> ecn 
496
497 \end{code}
498
499