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