Make record selectors into ordinary functions
[ghc-hetmet.git] / compiler / typecheck / TcTyClsDecls.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1996-1998
4 %
5
6 TcTyClsDecls: Typecheck type and class declarations
7
8 \begin{code}
9 module TcTyClsDecls (
10         tcTyAndClassDecls, tcFamInstDecl, mkAuxBinds
11     ) where
12
13 #include "HsVersions.h"
14
15 import HsSyn
16 import HsTypes
17 import BasicTypes
18 import HscTypes
19 import BuildTyCl
20 import TcUnify
21 import TcRnMonad
22 import TcEnv
23 import TcTyDecls
24 import TcClassDcl
25 import TcHsType
26 import TcMType
27 import TcType
28 import TysWiredIn       ( unitTy )
29 import FunDeps
30 import Type
31 import Generics
32 import Class
33 import TyCon
34 import DataCon
35 import Id
36 import MkId             ( rEC_SEL_ERROR_ID )
37 import IdInfo
38 import Var
39 import VarSet
40 import Name
41 import OccName
42 import Outputable
43 import Maybes
44 import Monad
45 import Unify
46 import Util
47 import SrcLoc
48 import ListSetOps
49 import Digraph
50 import DynFlags
51 import FastString
52 import Unique           ( mkBuiltinUnique )
53 import BasicTypes
54
55 import Bag
56 import Data.List
57 import Control.Monad    ( mplus )
58 \end{code}
59
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection{Type checking for type and class declarations}
64 %*                                                                      *
65 %************************************************************************
66
67 Dealing with a group
68 ~~~~~~~~~~~~~~~~~~~~
69 Consider a mutually-recursive group, binding 
70 a type constructor T and a class C.
71
72 Step 1:         getInitialKind
73         Construct a KindEnv by binding T and C to a kind variable 
74
75 Step 2:         kcTyClDecl
76         In that environment, do a kind check
77
78 Step 3: Zonk the kinds
79
80 Step 4:         buildTyConOrClass
81         Construct an environment binding T to a TyCon and C to a Class.
82         a) Their kinds comes from zonking the relevant kind variable
83         b) Their arity (for synonyms) comes direct from the decl
84         c) The funcional dependencies come from the decl
85         d) The rest comes a knot-tied binding of T and C, returned from Step 4
86         e) The variances of the tycons in the group is calculated from 
87                 the knot-tied stuff
88
89 Step 5:         tcTyClDecl1
90         In this environment, walk over the decls, constructing the TyCons and Classes.
91         This uses in a strict way items (a)-(c) above, which is why they must
92         be constructed in Step 4. Feed the results back to Step 4.
93         For this step, pass the is-recursive flag as the wimp-out flag
94         to tcTyClDecl1.
95         
96
97 Step 6:         Extend environment
98         We extend the type environment with bindings not only for the TyCons and Classes,
99         but also for their "implicit Ids" like data constructors and class selectors
100
101 Step 7:         checkValidTyCl
102         For a recursive group only, check all the decls again, just
103         to check all the side conditions on validity.  We could not
104         do this before because we were in a mutually recursive knot.
105
106 Identification of recursive TyCons
107 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
108 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
109 @TyThing@s.
110
111 Identifying a TyCon as recursive serves two purposes
112
113 1.  Avoid infinite types.  Non-recursive newtypes are treated as
114 "transparent", like type synonyms, after the type checker.  If we did
115 this for all newtypes, we'd get infinite types.  So we figure out for
116 each newtype whether it is "recursive", and add a coercion if so.  In
117 effect, we are trying to "cut the loops" by identifying a loop-breaker.
118
119 2.  Avoid infinite unboxing.  This is nothing to do with newtypes.
120 Suppose we have
121         data T = MkT Int T
122         f (MkT x t) = f t
123 Well, this function diverges, but we don't want the strictness analyser
124 to diverge.  But the strictness analyser will diverge because it looks
125 deeper and deeper into the structure of T.   (I believe there are
126 examples where the function does something sane, and the strictness
127 analyser still diverges, but I can't see one now.)
128
129 Now, concerning (1), the FC2 branch currently adds a coercion for ALL
130 newtypes.  I did this as an experiment, to try to expose cases in which
131 the coercions got in the way of optimisations.  If it turns out that we
132 can indeed always use a coercion, then we don't risk recursive types,
133 and don't need to figure out what the loop breakers are.
134
135 For newtype *families* though, we will always have a coercion, so they
136 are always loop breakers!  So you can easily adjust the current
137 algorithm by simply treating all newtype families as loop breakers (and
138 indeed type families).  I think.
139
140 \begin{code}
141 tcTyAndClassDecls :: ModDetails -> [LTyClDecl Name]
142                    -> TcM (TcGblEnv,         -- Input env extended by types and classes 
143                                              -- and their implicit Ids,DataCons
144                            HsValBinds Name)  -- Renamed bindings for record selectors
145 -- Fails if there are any errors
146
147 tcTyAndClassDecls boot_details allDecls
148   = checkNoErrs $       -- The code recovers internally, but if anything gave rise to
149                         -- an error we'd better stop now, to avoid a cascade
150     do  {       -- Omit instances of type families; they are handled together
151                 -- with the *heads* of class instances
152         ; let decls = filter (not . isFamInstDecl . unLoc) allDecls
153
154                 -- First check for cyclic type synonysm or classes
155                 -- See notes with checkCycleErrs
156         ; checkCycleErrs decls
157         ; mod <- getModule
158         ; traceTc (text "tcTyAndCl" <+> ppr mod)
159         ; (syn_tycons, alg_tyclss) <- fixM (\ ~(_rec_syn_tycons, rec_alg_tyclss) ->
160           do    { let { -- Seperate ordinary synonyms from all other type and
161                         -- class declarations and add all associated type
162                         -- declarations from type classes.  The latter is
163                         -- required so that the temporary environment for the
164                         -- knot includes all associated family declarations.
165                       ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc)
166                                                    decls
167                       ; alg_at_decls           = concatMap addATs alg_decls
168                       }
169                         -- Extend the global env with the knot-tied results
170                         -- for data types and classes
171                         -- 
172                         -- We must populate the environment with the loop-tied
173                         -- T's right away, because the kind checker may "fault
174                         -- in" some type  constructors that recursively
175                         -- mention T
176                 ; let gbl_things = mkGlobalThings alg_at_decls rec_alg_tyclss
177                 ; tcExtendRecEnv gbl_things $ do
178
179                         -- Kind-check the declarations
180                 { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
181
182                 ; let { -- Calculate rec-flag
183                       ; calc_rec  = calcRecFlags boot_details rec_alg_tyclss
184                       ; tc_decl   = addLocM (tcTyClDecl calc_rec) }
185
186                         -- Type-check the type synonyms, and extend the envt
187                 ; syn_tycons <- tcSynDecls kc_syn_decls
188                 ; tcExtendGlobalEnv syn_tycons $ do
189
190                         -- Type-check the data types and classes
191                 { alg_tyclss <- mapM tc_decl kc_alg_decls
192                 ; return (syn_tycons, concat alg_tyclss)
193             }}})
194         -- Finished with knot-tying now
195         -- Extend the environment with the finished things
196         ; tcExtendGlobalEnv (syn_tycons ++ alg_tyclss) $ do
197
198         -- Perform the validity check
199         { traceTc (text "ready for validity check")
200         ; mapM_ (addLocM checkValidTyCl) decls
201         ; traceTc (text "done")
202    
203         -- Add the implicit things;
204         -- we want them in the environment because 
205         -- they may be mentioned in interface files
206         -- NB: All associated types and their implicit things will be added a
207         --     second time here.  This doesn't matter as the definitions are
208         --     the same.
209         ; let { implicit_things = concatMap implicitTyThings alg_tyclss
210               ; aux_binds       = mkAuxBinds alg_tyclss }
211         ; traceTc ((text "Adding" <+> ppr alg_tyclss) 
212                    $$ (text "and" <+> ppr implicit_things))
213         ; env <- tcExtendGlobalEnv implicit_things getGblEnv
214         ; return (env, aux_binds) }
215     }
216   where
217     -- Pull associated types out of class declarations, to tie them into the
218     -- knot above.  
219     -- NB: We put them in the same place in the list as `tcTyClDecl' will
220     --     eventually put the matching `TyThing's.  That's crucial; otherwise,
221     --     the two argument lists of `mkGlobalThings' don't match up.
222     addATs decl@(L _ (ClassDecl {tcdATs = ats})) = decl : ats
223     addATs decl                                  = [decl]
224
225 mkGlobalThings :: [LTyClDecl Name]      -- The decls
226                -> [TyThing]             -- Knot-tied, in 1-1 correspondence with the decls
227                -> [(Name,TyThing)]
228 -- Driven by the Decls, and treating the TyThings lazily
229 -- make a TypeEnv for the new things
230 mkGlobalThings decls things
231   = map mk_thing (decls `zipLazy` things)
232   where
233     mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
234          = (name, AClass cl)
235     mk_thing (L _ decl, ~(ATyCon tc))
236          = (tcdName decl, ATyCon tc)
237 \end{code}
238
239
240 %************************************************************************
241 %*                                                                      *
242                Type checking family instances
243 %*                                                                      *
244 %************************************************************************
245
246 Family instances are somewhat of a hybrid.  They are processed together with
247 class instance heads, but can contain data constructors and hence they share a
248 lot of kinding and type checking code with ordinary algebraic data types (and
249 GADTs).
250
251 \begin{code}
252 tcFamInstDecl :: LTyClDecl Name -> TcM TyThing
253 tcFamInstDecl (L loc decl)
254   =     -- Prime error recovery, set source location
255     setSrcSpan loc                              $
256     tcAddDeclCtxt decl                          $
257     do { -- type families require -XTypeFamilies and can't be in an
258          -- hs-boot file
259        ; type_families <- doptM Opt_TypeFamilies
260        ; is_boot  <- tcIsHsBoot   -- Are we compiling an hs-boot file?
261        ; checkTc type_families $ badFamInstDecl (tcdLName decl)
262        ; checkTc (not is_boot) $ badBootFamInstDeclErr
263
264          -- Perform kind and type checking
265        ; tc <- tcFamInstDecl1 decl
266        ; checkValidTyCon tc     -- Remember to check validity;
267                                 -- no recursion to worry about here
268        ; return (ATyCon tc) }
269
270 tcFamInstDecl1 :: TyClDecl Name -> TcM TyCon
271
272   -- "type instance"
273 tcFamInstDecl1 (decl@TySynonym {tcdLName = L loc tc_name})
274   = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
275     do { -- check that the family declaration is for a synonym
276          unless (isSynTyCon family) $
277            addErr (wrongKindOfFamily family)
278
279        ; -- (1) kind check the right-hand side of the type equation
280        ; k_rhs <- kcCheckHsType (tcdSynRhs decl) resKind
281
282          -- we need the exact same number of type parameters as the family
283          -- declaration 
284        ; let famArity = tyConArity family
285        ; checkTc (length k_typats == famArity) $ 
286            wrongNumberOfParmsErr famArity
287
288          -- (2) type check type equation
289        ; tcTyVarBndrs k_tvs $ \t_tvs -> do {  -- turn kinded into proper tyvars
290        ; t_typats <- mapM tcHsKindedType k_typats
291        ; t_rhs    <- tcHsKindedType k_rhs
292
293          -- (3) check the well-formedness of the instance
294        ; checkValidTypeInst t_typats t_rhs
295
296          -- (4) construct representation tycon
297        ; rep_tc_name <- newFamInstTyConName tc_name loc
298        ; buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs) 
299                        (typeKind t_rhs) (Just (family, t_typats))
300        }}
301
302   -- "newtype instance" and "data instance"
303 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
304                              tcdCons = cons})
305   = kcIdxTyPats decl $ \k_tvs k_typats resKind fam_tycon ->
306     do { -- check that the family declaration is for the right kind
307          unless (isAlgTyCon fam_tycon) $
308            addErr (wrongKindOfFamily fam_tycon)
309
310        ; -- (1) kind check the data declaration as usual
311        ; k_decl <- kcDataDecl decl k_tvs
312        ; let k_ctxt = tcdCtxt k_decl
313              k_cons = tcdCons k_decl
314
315          -- result kind must be '*' (otherwise, we have too few patterns)
316        ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity fam_tycon)
317
318          -- (2) type check indexed data type declaration
319        ; tcTyVarBndrs k_tvs $ \t_tvs -> do {  -- turn kinded into proper tyvars
320        ; unbox_strict <- doptM Opt_UnboxStrictFields
321
322          -- kind check the type indexes and the context
323        ; t_typats     <- mapM tcHsKindedType k_typats
324        ; stupid_theta <- tcHsKindedContext k_ctxt
325
326          -- (3) Check that
327          --     (a) left-hand side contains no type family applications
328          --         (vanilla synonyms are fine, though, and we checked for
329          --         foralls earlier)
330        ; mapM_ checkTyFamFreeness t_typats
331
332          --     (b) a newtype has exactly one constructor
333        ; checkTc (new_or_data == DataType || isSingleton k_cons) $
334                  newtypeConError tc_name (length k_cons)
335
336          -- (4) construct representation tycon
337        ; rep_tc_name <- newFamInstTyConName tc_name loc
338        ; let ex_ok = True       -- Existentials ok for type families!
339        ; fixM (\ rep_tycon -> do 
340              { let orig_res_ty = mkTyConApp fam_tycon t_typats
341              ; data_cons <- tcConDecls unbox_strict ex_ok rep_tycon
342                                        (t_tvs, orig_res_ty) k_cons
343              ; tc_rhs <-
344                  case new_or_data of
345                    DataType -> return (mkDataTyConRhs data_cons)
346                    NewType  -> ASSERT( not (null data_cons) )
347                                mkNewTyConRhs rep_tc_name rep_tycon (head data_cons)
348              ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
349                              False h98_syntax (Just (fam_tycon, t_typats))
350                  -- We always assume that indexed types are recursive.  Why?
351                  -- (1) Due to their open nature, we can never be sure that a
352                  -- further instance might not introduce a new recursive
353                  -- dependency.  (2) They are always valid loop breakers as
354                  -- they involve a coercion.
355              })
356        }}
357        where
358          h98_syntax = case cons of      -- All constructors have same shape
359                         L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
360                         _ -> True
361
362 tcFamInstDecl1 d = pprPanic "tcFamInstDecl1" (ppr d)
363
364 -- Kind checking of indexed types
365 -- -
366
367 -- Kind check type patterns and kind annotate the embedded type variables.
368 --
369 -- * Here we check that a type instance matches its kind signature, but we do
370 --   not check whether there is a pattern for each type index; the latter
371 --   check is only required for type synonym instances.
372
373 kcIdxTyPats :: TyClDecl Name
374             -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
375                -- ^^kinded tvs         ^^kinded ty pats  ^^res kind
376             -> TcM a
377 kcIdxTyPats decl thing_inside
378   = kcHsTyVars (tcdTyVars decl) $ \tvs -> 
379     do { fam_tycon <- tcLookupLocatedTyCon (tcdLName decl)
380        ; let { (kinds, resKind) = splitKindFunTys (tyConKind fam_tycon)
381              ; hs_typats        = fromJust $ tcdTyPats decl }
382
383          -- we may not have more parameters than the kind indicates
384        ; checkTc (length kinds >= length hs_typats) $
385            tooManyParmsErr (tcdLName decl)
386
387          -- type functions can have a higher-kinded result
388        ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
389        ; typats <- zipWithM kcCheckHsType hs_typats kinds
390        ; thing_inside tvs typats resultKind fam_tycon
391        }
392   where
393 \end{code}
394
395
396 %************************************************************************
397 %*                                                                      *
398                 Kind checking
399 %*                                                                      *
400 %************************************************************************
401
402 We need to kind check all types in the mutually recursive group
403 before we know the kind of the type variables.  For example:
404
405 class C a where
406    op :: D b => a -> b -> b
407
408 class D c where
409    bop :: (Monad c) => ...
410
411 Here, the kind of the locally-polymorphic type variable "b"
412 depends on *all the uses of class D*.  For example, the use of
413 Monad c in bop's type signature means that D must have kind Type->Type.
414
415 However type synonyms work differently.  They can have kinds which don't
416 just involve (->) and *:
417         type R = Int#           -- Kind #
418         type S a = Array# a     -- Kind * -> #
419         type T a b = (# a,b #)  -- Kind * -> * -> (# a,b #)
420 So we must infer their kinds from their right-hand sides *first* and then
421 use them, whereas for the mutually recursive data types D we bring into
422 scope kind bindings D -> k, where k is a kind variable, and do inference.
423
424 Type families
425 ~~~~~~~~~~~~~
426 This treatment of type synonyms only applies to Haskell 98-style synonyms.
427 General type functions can be recursive, and hence, appear in `alg_decls'.
428
429 The kind of a type family is solely determinded by its kind signature;
430 hence, only kind signatures participate in the construction of the initial
431 kind environment (as constructed by `getInitialKind').  In fact, we ignore
432 instances of families altogether in the following.  However, we need to
433 include the kinds of associated families into the construction of the
434 initial kind environment.  (This is handled by `allDecls').
435
436 \begin{code}
437 kcTyClDecls :: [LTyClDecl Name] -> [Located (TyClDecl Name)]
438             -> TcM ([LTyClDecl Name], [Located (TyClDecl Name)])
439 kcTyClDecls syn_decls alg_decls
440   = do  {       -- First extend the kind env with each data type, class, and
441                 -- indexed type, mapping them to a type variable
442           let initialKindDecls = concat [allDecls decl | L _ decl <- alg_decls]
443         ; alg_kinds <- mapM getInitialKind initialKindDecls
444         ; tcExtendKindEnv alg_kinds $ do
445
446                 -- Now kind-check the type synonyms, in dependency order
447                 -- We do these differently to data type and classes,
448                 -- because a type synonym can be an unboxed type
449                 --      type Foo = Int#
450                 -- and a kind variable can't unify with UnboxedTypeKind
451                 -- So we infer their kinds in dependency order
452         { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
453         ; tcExtendKindEnv syn_kinds $  do
454
455                 -- Now kind-check the data type, class, and kind signatures,
456                 -- returning kind-annotated decls; we don't kind-check
457                 -- instances of indexed types yet, but leave this to
458                 -- `tcInstDecls1'
459         { kc_alg_decls <- mapM (wrapLocM kcTyClDecl)
460                             (filter (not . isFamInstDecl . unLoc) alg_decls)
461
462         ; return (kc_syn_decls, kc_alg_decls) }}}
463   where
464     -- get all declarations relevant for determining the initial kind
465     -- environment
466     allDecls (decl@ClassDecl {tcdATs = ats}) = decl : [ at 
467                                                       | L _ at <- ats
468                                                       , isFamilyDecl at]
469     allDecls decl | isFamInstDecl decl = []
470                   | otherwise          = [decl]
471
472 ------------------------------------------------------------------------
473 getInitialKind :: TyClDecl Name -> TcM (Name, TcKind)
474 -- Only for data type, class, and indexed type declarations
475 -- Get as much info as possible from the data, class, or indexed type decl,
476 -- so as to maximise usefulness of error messages
477 getInitialKind decl
478   = do  { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
479         ; res_kind  <- mk_res_kind decl
480         ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
481   where
482     mk_arg_kind (UserTyVar _)        = newKindVar
483     mk_arg_kind (KindedTyVar _ kind) = return kind
484
485     mk_res_kind (TyFamily { tcdKind    = Just kind }) = return kind
486     mk_res_kind (TyData   { tcdKindSig = Just kind }) = return kind
487         -- On GADT-style declarations we allow a kind signature
488         --      data T :: *->* where { ... }
489     mk_res_kind _ = return liftedTypeKind
490
491
492 ----------------
493 kcSynDecls :: [SCC (LTyClDecl Name)] 
494            -> TcM ([LTyClDecl Name],    -- Kind-annotated decls
495                    [(Name,TcKind)])     -- Kind bindings
496 kcSynDecls []
497   = return ([], [])
498 kcSynDecls (group : groups)
499   = do  { (decl,  nk)  <- kcSynDecl group
500         ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
501         ; return (decl:decls, nk:nks) }
502                         
503 ----------------
504 kcSynDecl :: SCC (LTyClDecl Name) 
505            -> TcM (LTyClDecl Name,      -- Kind-annotated decls
506                    (Name,TcKind))       -- Kind bindings
507 kcSynDecl (AcyclicSCC (L loc decl))
508   = tcAddDeclCtxt decl  $
509     kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
510     do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl)) 
511                         <+> brackets (ppr k_tvs))
512        ; (k_rhs, rhs_kind) <- kcHsType (tcdSynRhs decl)
513        ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
514        ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
515        ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
516                  (unLoc (tcdLName decl), tc_kind)) })
517
518 kcSynDecl (CyclicSCC decls)
519   = do { recSynErr decls; failM }       -- Fail here to avoid error cascade
520                                         -- of out-of-scope tycons
521
522 kindedTyVarKind :: LHsTyVarBndr Name -> Kind
523 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
524 kindedTyVarKind x = pprPanic "kindedTyVarKind" (ppr x)
525
526 ------------------------------------------------------------------------
527 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
528         -- Not used for type synonyms (see kcSynDecl)
529
530 kcTyClDecl decl@(TyData {})
531   = ASSERT( not . isFamInstDecl $ decl )   -- must not be a family instance
532     kcTyClDeclBody decl $
533       kcDataDecl decl
534
535 kcTyClDecl decl@(TyFamily {})
536   = kcFamilyDecl [] decl      -- the empty list signals a toplevel decl      
537
538 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
539   = kcTyClDeclBody decl $ \ tvs' ->
540     do  { ctxt' <- kcHsContext ctxt     
541         ; ats'  <- mapM (wrapLocM (kcFamilyDecl tvs')) ats
542         ; sigs' <- mapM (wrapLocM kc_sig) sigs
543         ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
544                         tcdATs = ats'}) }
545   where
546     kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
547                                    ; return (TypeSig nm op_ty') }
548     kc_sig other_sig          = return other_sig
549
550 kcTyClDecl decl@(ForeignType {})
551   = return decl
552
553 kcTyClDecl (TySynonym {}) = panic "kcTyClDecl TySynonym"
554
555 kcTyClDeclBody :: TyClDecl Name
556                -> ([LHsTyVarBndr Name] -> TcM a)
557                -> TcM a
558 -- getInitialKind has made a suitably-shaped kind for the type or class
559 -- Unpack it, and attribute those kinds to the type variables
560 -- Extend the env with bindings for the tyvars, taken from
561 -- the kind of the tycon/class.  Give it to the thing inside, and 
562 -- check the result kind matches
563 kcTyClDeclBody decl thing_inside
564   = tcAddDeclCtxt decl          $
565     do  { tc_ty_thing <- tcLookupLocated (tcdLName decl)
566         ; let tc_kind    = case tc_ty_thing of
567                            AThing k -> k
568                            _ -> pprPanic "kcTyClDeclBody" (ppr tc_ty_thing)
569               (kinds, _) = splitKindFunTys tc_kind
570               hs_tvs     = tcdTyVars decl
571               kinded_tvs = ASSERT( length kinds >= length hs_tvs )
572                            [ L loc (KindedTyVar (hsTyVarName tv) k)
573                            | (L loc tv, k) <- zip hs_tvs kinds]
574         ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
575
576 -- Kind check a data declaration, assuming that we already extended the
577 -- kind environment with the type variables of the left-hand side (these
578 -- kinded type variables are also passed as the second parameter).
579 --
580 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
581 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
582            tvs
583   = do  { ctxt' <- kcHsContext ctxt     
584         ; cons' <- mapM (wrapLocM kc_con_decl) cons
585         ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
586   where
587     -- doc comments are typechecked to Nothing here
588     kc_con_decl (ConDecl name expl ex_tvs ex_ctxt details res _) = do
589       kcHsTyVars ex_tvs $ \ex_tvs' -> do
590         ex_ctxt' <- kcHsContext ex_ctxt
591         details' <- kc_con_details details 
592         res'     <- case res of
593           ResTyH98 -> return ResTyH98
594           ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
595         return (ConDecl name expl ex_tvs' ex_ctxt' details' res' Nothing)
596
597     kc_con_details (PrefixCon btys) 
598         = do { btys' <- mapM kc_larg_ty btys 
599              ; return (PrefixCon btys') }
600     kc_con_details (InfixCon bty1 bty2) 
601         = do { bty1' <- kc_larg_ty bty1
602              ; bty2' <- kc_larg_ty bty2
603              ; return (InfixCon bty1' bty2') }
604     kc_con_details (RecCon fields) 
605         = do { fields' <- mapM kc_field fields
606              ; return (RecCon fields') }
607
608     kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
609                                            ; return (ConDeclField fld bty' d) }
610
611     kc_larg_ty bty = case new_or_data of
612                         DataType -> kcHsSigType bty
613                         NewType  -> kcHsLiftedSigType bty
614         -- Can't allow an unlifted type for newtypes, because we're effectively
615         -- going to remove the constructor while coercing it to a lifted type.
616         -- And newtypes can't be bang'd
617 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
618
619 -- Kind check a family declaration or type family default declaration.
620 --
621 kcFamilyDecl :: [LHsTyVarBndr Name]  -- tyvars of enclosing class decl if any
622              -> TyClDecl Name -> TcM (TyClDecl Name)
623 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
624   = kcTyClDeclBody decl $ \tvs' ->
625     do { mapM_ unifyClassParmKinds tvs'
626        ; return (decl {tcdTyVars = tvs', 
627                        tcdKind = kind `mplus` Just liftedTypeKind})
628                        -- default result kind is '*'
629        }
630   where
631     unifyClassParmKinds (L _ (KindedTyVar n k))
632       | Just classParmKind <- lookup n classTyKinds = unifyKind k classParmKind
633       | otherwise                                   = return ()
634     unifyClassParmKinds x = pprPanic "kcFamilyDecl/unifyClassParmKinds" (ppr x)
635     classTyKinds = [(n, k) | L _ (KindedTyVar n k) <- classTvs]
636 kcFamilyDecl _ (TySynonym {})              -- type family defaults
637   = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
638 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
639 \end{code}
640
641
642 %************************************************************************
643 %*                                                                      *
644 \subsection{Type checking}
645 %*                                                                      *
646 %************************************************************************
647
648 \begin{code}
649 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
650 tcSynDecls [] = return []
651 tcSynDecls (decl : decls) 
652   = do { syn_tc <- addLocM tcSynDecl decl
653        ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
654        ; return (syn_tc : syn_tcs) }
655
656   -- "type"
657 tcSynDecl :: TyClDecl Name -> TcM TyThing
658 tcSynDecl
659   (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
660   = tcTyVarBndrs tvs            $ \ tvs' -> do 
661     { traceTc (text "tcd1" <+> ppr tc_name) 
662     ; rhs_ty' <- tcHsKindedType rhs_ty
663     ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty') 
664                              (typeKind rhs_ty') Nothing
665     ; return (ATyCon tycon) 
666     }
667 tcSynDecl d = pprPanic "tcSynDecl" (ppr d)
668
669 --------------------
670 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
671
672 tcTyClDecl calc_isrec decl
673   = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
674
675   -- "type family" declarations
676 tcTyClDecl1 :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
677 tcTyClDecl1 _calc_isrec 
678   (TyFamily {tcdFlavour = TypeFamily, 
679              tcdLName = L _ tc_name, tcdTyVars = tvs,
680              tcdKind = Just kind}) -- NB: kind at latest added during kind checking
681   = tcTyVarBndrs tvs  $ \ tvs' -> do 
682   { traceTc (text "type family: " <+> ppr tc_name) 
683
684         -- Check that we don't use families without -XTypeFamilies
685   ; idx_tys <- doptM Opt_TypeFamilies
686   ; checkTc idx_tys $ badFamInstDecl tc_name
687
688         -- Check for no type indices
689   ; checkTc (not (null tvs)) (noIndexTypes tc_name)
690
691   ; tycon <- buildSynTyCon tc_name tvs' (OpenSynTyCon kind Nothing) kind Nothing
692   ; return [ATyCon tycon]
693   }
694
695   -- "data family" declaration
696 tcTyClDecl1 _calc_isrec 
697   (TyFamily {tcdFlavour = DataFamily, 
698              tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
699   = tcTyVarBndrs tvs  $ \ tvs' -> do 
700   { traceTc (text "data family: " <+> ppr tc_name) 
701   ; extra_tvs <- tcDataKindSig mb_kind
702   ; let final_tvs = tvs' ++ extra_tvs    -- we may not need these
703
704
705         -- Check that we don't use families without -XTypeFamilies
706   ; idx_tys <- doptM Opt_TypeFamilies
707   ; checkTc idx_tys $ badFamInstDecl tc_name
708
709         -- Check for no type indices
710   ; checkTc (not (null tvs)) (noIndexTypes tc_name)
711
712   ; tycon <- buildAlgTyCon tc_name final_tvs [] 
713                mkOpenDataTyConRhs Recursive False True Nothing
714   ; return [ATyCon tycon]
715   }
716
717   -- "newtype" and "data"
718   -- NB: not used for newtype/data instances (whether associated or not)
719 tcTyClDecl1 calc_isrec
720   (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
721            tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
722   = tcTyVarBndrs tvs    $ \ tvs' -> do 
723   { extra_tvs <- tcDataKindSig mb_ksig
724   ; let final_tvs = tvs' ++ extra_tvs
725   ; stupid_theta <- tcHsKindedContext ctxt
726   ; want_generic <- doptM Opt_Generics
727   ; unbox_strict <- doptM Opt_UnboxStrictFields
728   ; empty_data_decls <- doptM Opt_EmptyDataDecls
729   ; kind_signatures <- doptM Opt_KindSignatures
730   ; existential_ok <- doptM Opt_ExistentialQuantification
731   ; gadt_ok      <- doptM Opt_GADTs
732   ; is_boot      <- tcIsHsBoot  -- Are we compiling an hs-boot file?
733   ; let ex_ok = existential_ok || gadt_ok       -- Data cons can have existential context
734
735         -- Check that we don't use GADT syntax in H98 world
736   ; checkTc (gadt_ok || h98_syntax) (badGadtDecl tc_name)
737
738         -- Check that we don't use kind signatures without Glasgow extensions
739   ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
740
741         -- Check that the stupid theta is empty for a GADT-style declaration
742   ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
743
744         -- Check that a newtype has exactly one constructor
745         -- Do this before checking for empty data decls, so that
746         -- we don't suggest -XEmptyDataDecls for newtypes
747   ; checkTc (new_or_data == DataType || isSingleton cons) 
748             (newtypeConError tc_name (length cons))
749
750         -- Check that there's at least one condecl,
751         -- or else we're reading an hs-boot file, or -XEmptyDataDecls
752   ; checkTc (not (null cons) || empty_data_decls || is_boot)
753             (emptyConDeclsErr tc_name)
754     
755   ; tycon <- fixM (\ tycon -> do 
756         { let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
757         ; data_cons <- tcConDecls unbox_strict ex_ok 
758                                   tycon (final_tvs, res_ty) cons
759         ; tc_rhs <-
760             if null cons && is_boot     -- In a hs-boot file, empty cons means
761             then return AbstractTyCon   -- "don't know"; hence Abstract
762             else case new_or_data of
763                    DataType -> return (mkDataTyConRhs data_cons)
764                    NewType  -> ASSERT( not (null data_cons) )
765                                mkNewTyConRhs tc_name tycon (head data_cons)
766         ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
767             (want_generic && canDoGenerics data_cons) h98_syntax Nothing
768         })
769   ; return [ATyCon tycon]
770   }
771   where
772     is_rec   = calc_isrec tc_name
773     h98_syntax = case cons of   -- All constructors have same shape
774                         L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
775                         _ -> True
776
777 tcTyClDecl1 calc_isrec 
778   (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs, 
779               tcdCtxt = ctxt, tcdMeths = meths,
780               tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
781   = tcTyVarBndrs tvs            $ \ tvs' -> do 
782   { ctxt' <- tcHsKindedContext ctxt
783   ; fds' <- mapM (addLocM tc_fundep) fundeps
784   ; atss <- mapM (addLocM (tcTyClDecl1 (const Recursive))) ats
785             -- NB: 'ats' only contains "type family" and "data family"
786             --     declarations as well as type family defaults
787   ; let ats' = map (setAssocFamilyPermutation tvs') (concat atss)
788   ; sig_stuff <- tcClassSigs class_name sigs meths
789   ; clas <- fixM (\ clas ->
790                 let     -- This little knot is just so we can get
791                         -- hold of the name of the class TyCon, which we
792                         -- need to look up its recursiveness
793                     tycon_name = tyConName (classTyCon clas)
794                     tc_isrec = calc_isrec tycon_name
795                 in
796                 buildClass False {- Must include unfoldings for selectors -}
797                            class_name tvs' ctxt' fds' ats'
798                            sig_stuff tc_isrec)
799   ; return (AClass clas : ats')
800       -- NB: Order is important due to the call to `mkGlobalThings' when
801       --     tying the the type and class declaration type checking knot.
802   }
803   where
804     tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM tcLookupTyVar tvs1 ;
805                                 ; tvs2' <- mapM tcLookupTyVar tvs2 ;
806                                 ; return (tvs1', tvs2') }
807
808 tcTyClDecl1 _
809   (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
810   = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
811
812 tcTyClDecl1 _ d = pprPanic "tcTyClDecl1" (ppr d)
813
814 -----------------------------------
815 tcConDecls :: Bool -> Bool -> TyCon -> ([TyVar], Type)
816            -> [LConDecl Name] -> TcM [DataCon]
817 tcConDecls unbox ex_ok rep_tycon res_tmpl cons
818   = mapM (addLocM (tcConDecl unbox ex_ok rep_tycon res_tmpl)) cons
819
820 tcConDecl :: Bool               -- True <=> -funbox-strict_fields
821           -> Bool               -- True <=> -XExistentialQuantificaton or -XGADTs
822           -> TyCon              -- Representation tycon
823           -> ([TyVar], Type)    -- Return type template (with its template tyvars)
824           -> ConDecl Name 
825           -> TcM DataCon
826
827 tcConDecl unbox_strict existential_ok rep_tycon res_tmpl        -- Data types
828           (ConDecl name _ tvs ctxt details res_ty _)
829   = addErrCtxt (dataConCtxt name)       $ 
830     tcTyVarBndrs tvs                    $ \ tvs' -> do 
831     { ctxt' <- tcHsKindedContext ctxt
832     ; checkTc (existential_ok || (null tvs && null (unLoc ctxt)))
833               (badExistential name)
834     ; (univ_tvs, ex_tvs, eq_preds, res_ty') <- tcResultType res_tmpl tvs' res_ty
835     ; let 
836         tc_datacon is_infix field_lbls btys
837           = do { (arg_tys, stricts) <- mapAndUnzipM (tcConArg unbox_strict) btys
838                ; buildDataCon (unLoc name) is_infix
839                     stricts field_lbls
840                     univ_tvs ex_tvs eq_preds ctxt' arg_tys
841                     res_ty' rep_tycon }
842                 -- NB:  we put data_tc, the type constructor gotten from the
843                 --      constructor type signature into the data constructor;
844                 --      that way checkValidDataCon can complain if it's wrong.
845
846     ; case details of
847         PrefixCon btys     -> tc_datacon False [] btys
848         InfixCon bty1 bty2 -> tc_datacon True  [] [bty1,bty2]
849         RecCon fields      -> tc_datacon False field_names btys
850                            where
851                               field_names = map (unLoc . cd_fld_name) fields
852                               btys        = map cd_fld_type fields
853     }
854
855 -- Example
856 --   data instance T (b,c) where 
857 --      TI :: forall e. e -> T (e,e)
858 --
859 -- The representation tycon looks like this:
860 --   data :R7T b c where 
861 --      TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
862 -- In this case orig_res_ty = T (e,e)
863
864 tcResultType :: ([TyVar], Type) -- Template for result type; e.g.
865                                 -- data instance T [a] b c = ...  
866                                 --      gives template ([a,b,c], T [a] b c)
867              -> [TyVar]         -- where MkT :: forall x y z. ...
868              -> ResType Name
869              -> TcM ([TyVar],           -- Universal
870                      [TyVar],           -- Existential (distinct OccNames from univs)
871                      [(TyVar,Type)],    -- Equality predicates
872                      Type)              -- Typechecked return type
873         -- We don't check that the TyCon given in the ResTy is
874         -- the same as the parent tycon, becuase we are in the middle
875         -- of a recursive knot; so it's postponed until checkValidDataCon
876
877 tcResultType (tmpl_tvs, res_ty) dc_tvs ResTyH98
878   = return (tmpl_tvs, dc_tvs, [], res_ty)
879         -- In H98 syntax the dc_tvs are the existential ones
880         --      data T a b c = forall d e. MkT ...
881         -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
882
883 tcResultType (tmpl_tvs, res_tmpl) dc_tvs (ResTyGADT res_ty)
884         -- E.g.  data T [a] b c where
885         --         MkT :: forall x y z. T [(x,y)] z z
886         -- Then we generate
887         --      Univ tyvars     Eq-spec
888         --          a              a~(x,y)
889         --          b              b~z
890         --          z              
891         -- Existentials are the leftover type vars: [x,y]
892         -- So we return ([a,b,z], [x,y], [a~(x,y),b~z], T [(x,y)] z z)
893   = do  { res_ty' <- tcHsKindedType res_ty
894         ; let Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty'
895
896                 -- /Lazily/ figure out the univ_tvs etc
897                 -- Each univ_tv is either a dc_tv or a tmpl_tv
898               (univ_tvs, eq_spec) = foldr choose ([], []) tidy_tmpl_tvs
899               choose tmpl (univs, eqs)
900                 | Just ty <- lookupTyVar subst tmpl 
901                 = case tcGetTyVar_maybe ty of
902                     Just tv | not (tv `elem` univs)
903                             -> (tv:univs,   eqs)
904                     _other  -> (tmpl:univs, (tmpl,ty):eqs)
905                 | otherwise = pprPanic "tcResultType" (ppr res_ty)
906               ex_tvs = dc_tvs `minusList` univ_tvs
907
908         ; return (univ_tvs, ex_tvs, eq_spec, res_ty') }
909   where
910         -- NB: tmpl_tvs and dc_tvs are distinct, but
911         -- we want them to be *visibly* distinct, both for
912         -- interface files and general confusion.  So rename
913         -- the tc_tvs, since they are not used yet (no 
914         -- consequential renaming needed)
915     (_, tidy_tmpl_tvs) = mapAccumL tidy_one init_occ_env tmpl_tvs
916     init_occ_env       = initTidyOccEnv (map getOccName dc_tvs)
917     tidy_one env tv    = (env', setTyVarName tv (tidyNameOcc name occ'))
918               where
919                  name = tyVarName tv
920                  (env', occ') = tidyOccName env (getOccName name) 
921
922 -------------------
923 tcConArg :: Bool                -- True <=> -funbox-strict_fields
924            -> LHsType Name
925            -> TcM (TcType, StrictnessMark)
926 tcConArg unbox_strict bty
927   = do  { arg_ty <- tcHsBangType bty
928         ; let bang = getBangStrictness bty
929         ; return (arg_ty, chooseBoxingStrategy unbox_strict arg_ty bang) }
930
931 -- We attempt to unbox/unpack a strict field when either:
932 --   (i)  The field is marked '!!', or
933 --   (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
934 --
935 -- We have turned off unboxing of newtypes because coercions make unboxing 
936 -- and reboxing more complicated
937 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> StrictnessMark
938 chooseBoxingStrategy unbox_strict_fields arg_ty bang
939   = case bang of
940         HsNoBang                                    -> NotMarkedStrict
941         HsStrict | unbox_strict_fields 
942                    && can_unbox arg_ty              -> MarkedUnboxed
943         HsUnbox  | can_unbox arg_ty                 -> MarkedUnboxed
944         _                                           -> MarkedStrict
945   where
946     -- we can unbox if the type is a chain of newtypes with a product tycon
947     -- at the end
948     can_unbox arg_ty = case splitTyConApp_maybe arg_ty of
949                    Nothing                      -> False
950                    Just (arg_tycon, tycon_args) -> 
951                        not (isRecursiveTyCon arg_tycon) &&      -- Note [Recusive unboxing]
952                        isProductTyCon arg_tycon &&
953                        (if isNewTyCon arg_tycon then 
954                             can_unbox (newTyConInstRhs arg_tycon tycon_args)
955                         else True)
956 \end{code}
957
958 Note [Recursive unboxing]
959 ~~~~~~~~~~~~~~~~~~~~~~~~~
960 Be careful not to try to unbox this!
961         data T = MkT !T Int
962 But it's the *argument* type that matters. This is fine:
963         data S = MkS S !Int
964 because Int is non-recursive.
965
966
967 %************************************************************************
968 %*                                                                      *
969                 Validity checking
970 %*                                                                      *
971 %************************************************************************
972
973 Validity checking is done once the mutually-recursive knot has been
974 tied, so we can look at things freely.
975
976 \begin{code}
977 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
978 checkCycleErrs tyclss
979   | null cls_cycles
980   = return ()
981   | otherwise
982   = do  { mapM_ recClsErr cls_cycles
983         ; failM }       -- Give up now, because later checkValidTyCl
984                         -- will loop if the synonym is recursive
985   where
986     cls_cycles = calcClassCycles tyclss
987
988 checkValidTyCl :: TyClDecl Name -> TcM ()
989 -- We do the validity check over declarations, rather than TyThings
990 -- only so that we can add a nice context with tcAddDeclCtxt
991 checkValidTyCl decl
992   = tcAddDeclCtxt decl $
993     do  { thing <- tcLookupLocatedGlobal (tcdLName decl)
994         ; traceTc (text "Validity of" <+> ppr thing)    
995         ; case thing of
996             ATyCon tc -> checkValidTyCon tc
997             AClass cl -> checkValidClass cl 
998             _ -> panic "checkValidTyCl"
999         ; traceTc (text "Done validity of" <+> ppr thing)       
1000         }
1001
1002 -------------------------
1003 -- For data types declared with record syntax, we require
1004 -- that each constructor that has a field 'f' 
1005 --      (a) has the same result type
1006 --      (b) has the same type for 'f'
1007 -- module alpha conversion of the quantified type variables
1008 -- of the constructor.
1009 --
1010 -- Note that we allow existentials to match becuase the
1011 -- fields can never meet. E.g
1012 --      data T where
1013 --        T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
1014 --        T2 { f1 :: c, f2 :: c, f3 ::Int } :: T  
1015 -- Here we do not complain about f1,f2 because they are existential
1016
1017 checkValidTyCon :: TyCon -> TcM ()
1018 checkValidTyCon tc 
1019   | isSynTyCon tc 
1020   = case synTyConRhs tc of
1021       OpenSynTyCon _ _ -> return ()
1022       SynonymTyCon ty  -> checkValidType syn_ctxt ty
1023   | otherwise
1024   = do  -- Check the context on the data decl
1025     checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
1026         
1027         -- Check arg types of data constructors
1028     mapM_ (checkValidDataCon tc) data_cons
1029
1030         -- Check that fields with the same name share a type
1031     mapM_ check_fields groups
1032
1033   where
1034     syn_ctxt  = TySynCtxt name
1035     name      = tyConName tc
1036     data_cons = tyConDataCons tc
1037
1038     groups = equivClasses cmp_fld (concatMap get_fields data_cons)
1039     cmp_fld (f1,_) (f2,_) = f1 `compare` f2
1040     get_fields con = dataConFieldLabels con `zip` repeat con
1041         -- dataConFieldLabels may return the empty list, which is fine
1042
1043     -- See Note [GADT record selectors] in MkId.lhs
1044     -- We must check (a) that the named field has the same 
1045     --                   type in each constructor
1046     --               (b) that those constructors have the same result type
1047     --
1048     -- However, the constructors may have differently named type variable
1049     -- and (worse) we don't know how the correspond to each other.  E.g.
1050     --     C1 :: forall a b. { f :: a, g :: b } -> T a b
1051     --     C2 :: forall d c. { f :: c, g :: c } -> T c d
1052     -- 
1053     -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1054     -- result type against other candidates' types BOTH WAYS ROUND.
1055     -- If they magically agrees, take the substitution and
1056     -- apply them to the latter ones, and see if they match perfectly.
1057     check_fields ((label, con1) : other_fields)
1058         -- These fields all have the same name, but are from
1059         -- different constructors in the data type
1060         = recoverM (return ()) $ mapM_ checkOne other_fields
1061                 -- Check that all the fields in the group have the same type
1062                 -- NB: this check assumes that all the constructors of a given
1063                 -- data type use the same type variables
1064         where
1065         (tvs1, _, _, res1) = dataConSig con1
1066         ts1 = mkVarSet tvs1
1067         fty1 = dataConFieldType con1 label
1068
1069         checkOne (_, con2)    -- Do it bothways to ensure they are structurally identical
1070             = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1071                  ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1072             where        
1073                 (tvs2, _, _, res2) = dataConSig con2
1074                 ts2 = mkVarSet tvs2
1075                 fty2 = dataConFieldType con2 label
1076     check_fields [] = panic "checkValidTyCon/check_fields []"
1077
1078 checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
1079                  -> Type -> Type -> Type -> Type -> TcM ()
1080 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1081   = do  { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1082         ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1083   where
1084     mb_subst1 = tcMatchTy tvs1 res1 res2
1085     mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1086
1087 -------------------------------
1088 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1089 checkValidDataCon tc con
1090   = setSrcSpan (srcLocSpan (getSrcLoc con))     $
1091     addErrCtxt (dataConCtxt con)                $ 
1092     do  { let tc_tvs = tyConTyVars tc
1093               res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
1094               actual_res_ty = dataConOrigResTy con
1095         ; checkTc (isJust (tcMatchTy (mkVarSet tc_tvs)
1096                                 res_ty_tmpl
1097                                 actual_res_ty))
1098                   (badDataConTyCon con res_ty_tmpl actual_res_ty)
1099         ; checkValidMonoType (dataConOrigResTy con)
1100                 -- Disallow MkT :: T (forall a. a->a)
1101                 -- Reason: it's really the argument of an equality constraint
1102         ; checkValidType ctxt (dataConUserType con)
1103         ; when (isNewTyCon tc) (checkNewDataCon con)
1104     }
1105   where
1106     ctxt = ConArgCtxt (dataConName con) 
1107
1108 -------------------------------
1109 checkNewDataCon :: DataCon -> TcM ()
1110 -- Checks for the data constructor of a newtype
1111 checkNewDataCon con
1112   = do  { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1113                 -- One argument
1114         ; checkTc (null eq_spec) (newtypePredError con)
1115                 -- Return type is (T a b c)
1116         ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1117                 -- No existentials
1118         ; checkTc (not (any isMarkedStrict (dataConStrictMarks con))) 
1119                   (newtypeStrictError con)
1120                 -- No strictness
1121     }
1122   where
1123     (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1124
1125 -------------------------------
1126 checkValidClass :: Class -> TcM ()
1127 checkValidClass cls
1128   = do  { constrained_class_methods <- doptM Opt_ConstrainedClassMethods
1129         ; multi_param_type_classes <- doptM Opt_MultiParamTypeClasses
1130         ; fundep_classes <- doptM Opt_FunctionalDependencies
1131
1132         -- Check that the class is unary, unless GlaExs
1133         ; checkTc (notNull tyvars) (nullaryClassErr cls)
1134         ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1135         ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1136
1137         -- Check the super-classes
1138         ; checkValidTheta (ClassSCCtxt (className cls)) theta
1139
1140         -- Check the class operations
1141         ; mapM_ (check_op constrained_class_methods) op_stuff
1142
1143         -- Check that if the class has generic methods, then the
1144         -- class has only one parameter.  We can't do generic
1145         -- multi-parameter type classes!
1146         ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1147         }
1148   where
1149     (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1150     unary       = isSingleton tyvars
1151     no_generics = null [() | (_, GenDefMeth) <- op_stuff]
1152
1153     check_op constrained_class_methods (sel_id, dm) 
1154       = addErrCtxt (classOpCtxt sel_id tau) $ do
1155         { checkValidTheta SigmaCtxt (tail theta)
1156                 -- The 'tail' removes the initial (C a) from the
1157                 -- class itself, leaving just the method type
1158
1159         ; traceTc (text "class op type" <+> ppr op_ty <+> ppr tau)
1160         ; checkValidType (FunSigCtxt op_name) tau
1161
1162                 -- Check that the type mentions at least one of
1163                 -- the class type variables...or at least one reachable
1164                 -- from one of the class variables.  Example: tc223
1165                 --   class Error e => Game b mv e | b -> mv e where
1166                 --      newBoard :: MonadState b m => m ()
1167                 -- Here, MonadState has a fundep m->b, so newBoard is fine
1168         ; let grown_tyvars = grow theta (mkVarSet tyvars)
1169         ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1170                   (noClassTyVarErr cls sel_id)
1171
1172                 -- Check that for a generic method, the type of 
1173                 -- the method is sufficiently simple
1174         ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1175                   (badGenericMethodType op_name op_ty)
1176         }
1177         where
1178           op_name = idName sel_id
1179           op_ty   = idType sel_id
1180           (_,theta1,tau1) = tcSplitSigmaTy op_ty
1181           (_,theta2,tau2)  = tcSplitSigmaTy tau1
1182           (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1183                       | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1184                 -- Ugh!  The function might have a type like
1185                 --      op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1186                 -- With -XConstrainedClassMethods, we want to allow this, even though the inner 
1187                 -- forall has an (Eq a) constraint.  Whereas in general, each constraint 
1188                 -- in the context of a for-all must mention at least one quantified
1189                 -- type variable.  What a mess!
1190 \end{code}
1191
1192
1193 %************************************************************************
1194 %*                                                                      *
1195                 Building record selectors
1196 %*                                                                      *
1197 %************************************************************************
1198
1199 \begin{code}
1200 mkAuxBinds :: [TyThing] -> HsValBinds Name
1201 mkAuxBinds ty_things
1202   = ValBindsOut [(NonRecursive, b) | b <- binds] sigs
1203   where
1204     (sigs, binds) = unzip rec_sels
1205     rec_sels = map mkRecSelBind [ (tc,fld) 
1206                                 | ATyCon tc <- ty_things 
1207                                 , fld <- tyConFields tc ]
1208
1209
1210 mkRecSelBind :: (TyCon, FieldLabel) -> (LSig Name, LHsBinds Name)
1211 mkRecSelBind (tycon, sel_name)
1212   = (L loc (IdSig sel_id), unitBag (L loc sel_bind))
1213   where
1214     loc = getSrcSpan tycon    
1215     sel_id = Var.mkLocalVar rec_details sel_name sel_ty vanillaIdInfo
1216     rec_details = RecSelId { sel_tycon = tycon, sel_naughty = is_naughty }
1217
1218     -- Find a representative constructor, con1
1219     all_cons = tyConDataCons tycon 
1220     cons_w_field = [ con | con <- all_cons
1221                    , sel_name `elem` dataConFieldLabels con ] 
1222     con1 = ASSERT( not (null cons_w_field) ) head cons_w_field
1223
1224     -- Selector type; Note [Polymorphic selectors]
1225     field_ty = dataConFieldType con1 sel_name
1226     (field_tvs, field_theta, field_tau) 
1227        | is_naughty = ([], [], unitTy)
1228        | otherwise  = tcSplitSigmaTy field_ty
1229     data_ty    = dataConOrigResTy con1
1230     data_tvs   = tyVarsOfType data_ty
1231     is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tvs)  
1232     sel_ty = mkForAllTys (varSetElems data_tvs ++ field_tvs) $ 
1233              mkPhiTy (dataConStupidTheta con1)  $       -- Urgh!
1234              mkPhiTy field_theta                $       -- Urgh!
1235              mkFunTy data_ty field_tau
1236
1237     -- Make the binding: sel (C2 { fld = x }) = x
1238     --                   sel (C7 { fld = x }) = x
1239     --    where cons_w_field = [C2,C7]
1240     sel_bind     = mkFunBind sel_lname (map mk_match cons_w_field ++ deflt)
1241     mk_match con = mkSimpleMatch [L loc (mk_sel_pat con)] 
1242                                  (L loc match_body)
1243     mk_sel_pat con = ConPatIn (L loc (getName con)) (RecCon rec_fields)
1244     rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }
1245     rec_field  = HsRecField { hsRecFieldId = sel_lname
1246                             , hsRecFieldArg = nlVarPat field_var
1247                             , hsRecPun = False }
1248     match_body | is_naughty = ExplicitTuple [] Boxed
1249                | otherwise  = HsVar field_var
1250     sel_lname = L loc sel_name
1251     field_var = mkInternalName (mkBuiltinUnique 1) (getOccName sel_name) loc
1252
1253     -- Add catch-all default case unless the case is exhaustive
1254     -- We do this explicitly so that we get a nice error message that
1255     -- mentions this particular record selector
1256     deflt | length cons_w_field == length all_cons = []
1257           | otherwise = [mkSimpleMatch [nlWildPat] 
1258                             (nlHsApp (nlHsVar (getName rEC_SEL_ERROR_ID))
1259                                      (nlHsLit msg_lit))]
1260     msg_lit = HsStringPrim $ mkFastString $ 
1261               occNameString (getOccName sel_name)
1262
1263 ---------------
1264 tyConFields :: TyCon -> [FieldLabel]
1265 tyConFields tc 
1266   | isAlgTyCon tc = nub (concatMap dataConFieldLabels (tyConDataCons tc))
1267   | otherwise     = []
1268 \end{code}
1269
1270 Note [Polymorphic selectors]
1271 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1272 When a record has a polymorphic field, we pull the foralls out to the front.
1273    data T = MkT { f :: forall a. [a] -> a }
1274 Then f :: forall a. T -> [a] -> a
1275 NOT  f :: T -> forall a. [a] -> a
1276
1277 This is horrid.  It's only needed in deeply obscure cases, which I hate.
1278 The only case I know is test tc163, which is worth looking at.  It's far
1279 from clear that this test should succeed at all!
1280
1281 Note [Naughty record selectors]
1282 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1283 A "naughty" field is one for which we can't define a record 
1284 selector, because an existential type variable would escape.  For example:
1285         data T = forall a. MkT { x,y::a }
1286 We obviously can't define       
1287         x (MkT v _) = v
1288 Nevertheless we *do* put a RecSelId into the type environment
1289 so that if the user tries to use 'x' as a selector we can bleat
1290 helpfully, rather than saying unhelpfully that 'x' is not in scope.
1291 Hence the sel_naughty flag, to identify record selectors that don't really exist.
1292
1293 In general, a field is naughty if its type mentions a type variable that
1294 isn't in the result type of the constructor.
1295
1296 We make a dummy binding for naughty selectors, so that they can be treated
1297 uniformly, apart from their sel_naughty field.  The function is never called.
1298
1299 Note [GADT record selectors]
1300 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1301 For GADTs, we require that all constructors with a common field 'f' have the same
1302 result type (modulo alpha conversion).  [Checked in TcTyClsDecls.checkValidTyCon]
1303 E.g. 
1304         data T where
1305           T1 { f :: Maybe a } :: T [a]
1306           T2 { f :: Maybe a, y :: b  } :: T [a]
1307
1308 and now the selector takes that result type as its argument:
1309    f :: forall a. T [a] -> Maybe a
1310
1311 Details: the "real" types of T1,T2 are:
1312    T1 :: forall r a.   (r~[a]) => a -> T r
1313    T2 :: forall r a b. (r~[a]) => a -> b -> T r
1314
1315 So the selector loooks like this:
1316    f :: forall a. T [a] -> Maybe a
1317    f (a:*) (t:T [a])
1318      = case t of
1319          T1 c   (g:[a]~[c]) (v:Maybe c)       -> v `cast` Maybe (right (sym g))
1320          T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
1321
1322 Note the forall'd tyvars of the selector are just the free tyvars
1323 of the result type; there may be other tyvars in the constructor's
1324 type (e.g. 'b' in T2).
1325
1326 Note the need for casts in the result!
1327
1328 Note [Selector running example]
1329 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1330 It's OK to combine GADTs and type families.  Here's a running example:
1331
1332         data instance T [a] where 
1333           T1 { fld :: b } :: T [Maybe b]
1334
1335 The representation type looks like this
1336         data :R7T a where
1337           T1 { fld :: b } :: :R7T (Maybe b)
1338
1339 and there's coercion from the family type to the representation type
1340         :CoR7T a :: T [a] ~ :R7T a
1341
1342 The selector we want for fld looks like this:
1343
1344         fld :: forall b. T [Maybe b] -> b
1345         fld = /\b. \(d::T [Maybe b]).
1346               case d `cast` :CoR7T (Maybe b) of 
1347                 T1 (x::b) -> x
1348
1349 The scrutinee of the case has type :R7T (Maybe b), which can be
1350 gotten by appying the eq_spec to the univ_tvs of the data con.
1351
1352 %************************************************************************
1353 %*                                                                      *
1354                 Error messages
1355 %*                                                                      *
1356 %************************************************************************
1357
1358 \begin{code}
1359 resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1360 resultTypeMisMatch field_name con1 con2
1361   = vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1362                 ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
1363           nest 2 $ ptext (sLit "but have different result types")]
1364
1365 fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1366 fieldTypeMisMatch field_name con1 con2
1367   = sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1368          ptext (sLit "give different types for field"), quotes (ppr field_name)]
1369
1370 dataConCtxt :: Outputable a => a -> SDoc
1371 dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
1372
1373 classOpCtxt :: Var -> Type -> SDoc
1374 classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
1375                               nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1376
1377 nullaryClassErr :: Class -> SDoc
1378 nullaryClassErr cls
1379   = ptext (sLit "No parameters for class")  <+> quotes (ppr cls)
1380
1381 classArityErr :: Class -> SDoc
1382 classArityErr cls
1383   = vcat [ptext (sLit "Too many parameters for class") <+> quotes (ppr cls),
1384           parens (ptext (sLit "Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1385
1386 classFunDepsErr :: Class -> SDoc
1387 classFunDepsErr cls
1388   = vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
1389           parens (ptext (sLit "Use -XFunctionalDependencies to allow fundeps"))]
1390
1391 noClassTyVarErr :: Class -> Var -> SDoc
1392 noClassTyVarErr clas op
1393   = sep [ptext (sLit "The class method") <+> quotes (ppr op),
1394          ptext (sLit "mentions none of the type variables of the class") <+> 
1395                 ppr clas <+> hsep (map ppr (classTyVars clas))]
1396
1397 genericMultiParamErr :: Class -> SDoc
1398 genericMultiParamErr clas
1399   = ptext (sLit "The multi-parameter class") <+> quotes (ppr clas) <+> 
1400     ptext (sLit "cannot have generic methods")
1401
1402 badGenericMethodType :: Name -> Kind -> SDoc
1403 badGenericMethodType op op_ty
1404   = hang (ptext (sLit "Generic method type is too complex"))
1405        4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1406                 ptext (sLit "You can only use type variables, arrows, lists, and tuples")])
1407
1408 recSynErr :: [LTyClDecl Name] -> TcRn ()
1409 recSynErr syn_decls
1410   = setSrcSpan (getLoc (head sorted_decls)) $
1411     addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
1412                  nest 2 (vcat (map ppr_decl sorted_decls))])
1413   where
1414     sorted_decls = sortLocated syn_decls
1415     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1416
1417 recClsErr :: [Located (TyClDecl Name)] -> TcRn ()
1418 recClsErr cls_decls
1419   = setSrcSpan (getLoc (head sorted_decls)) $
1420     addErr (sep [ptext (sLit "Cycle in class declarations (via superclasses):"),
1421                  nest 2 (vcat (map ppr_decl sorted_decls))])
1422   where
1423     sorted_decls = sortLocated cls_decls
1424     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1425
1426 sortLocated :: [Located a] -> [Located a]
1427 sortLocated things = sortLe le things
1428   where
1429     le (L l1 _) (L l2 _) = l1 <= l2
1430
1431 badDataConTyCon :: DataCon -> Type -> Type -> SDoc
1432 badDataConTyCon data_con res_ty_tmpl actual_res_ty
1433   = hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
1434                 ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
1435        2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
1436
1437 badGadtDecl :: Name -> SDoc
1438 badGadtDecl tc_name
1439   = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1440          , nest 2 (parens $ ptext (sLit "Use -XGADTs to allow GADTs")) ]
1441
1442 badExistential :: Located Name -> SDoc
1443 badExistential con_name
1444   = hang (ptext (sLit "Data constructor") <+> quotes (ppr con_name) <+>
1445                 ptext (sLit "has existential type variables, or a context"))
1446        2 (parens $ ptext (sLit "Use -XExistentialQuantification or -XGADTs to allow this"))
1447
1448 badStupidTheta :: Name -> SDoc
1449 badStupidTheta tc_name
1450   = ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1451
1452 newtypeConError :: Name -> Int -> SDoc
1453 newtypeConError tycon n
1454   = sep [ptext (sLit "A newtype must have exactly one constructor,"),
1455          nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
1456
1457 newtypeExError :: DataCon -> SDoc
1458 newtypeExError con
1459   = sep [ptext (sLit "A newtype constructor cannot have an existential context,"),
1460          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1461
1462 newtypeStrictError :: DataCon -> SDoc
1463 newtypeStrictError con
1464   = sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
1465          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1466
1467 newtypePredError :: DataCon -> SDoc
1468 newtypePredError con
1469   = sep [ptext (sLit "A newtype constructor must have a return type of form T a1 ... an"),
1470          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does not")]
1471
1472 newtypeFieldErr :: DataCon -> Int -> SDoc
1473 newtypeFieldErr con_name n_flds
1474   = sep [ptext (sLit "The constructor of a newtype must have exactly one field"), 
1475          nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
1476
1477 badSigTyDecl :: Name -> SDoc
1478 badSigTyDecl tc_name
1479   = vcat [ ptext (sLit "Illegal kind signature") <+>
1480            quotes (ppr tc_name)
1481          , nest 2 (parens $ ptext (sLit "Use -XKindSignatures to allow kind signatures")) ]
1482
1483 noIndexTypes :: Name -> SDoc
1484 noIndexTypes tc_name
1485   = ptext (sLit "Type family constructor") <+> quotes (ppr tc_name)
1486     <+> ptext (sLit "must have at least one type index parameter")
1487
1488 badFamInstDecl :: Outputable a => a -> SDoc
1489 badFamInstDecl tc_name
1490   = vcat [ ptext (sLit "Illegal family instance for") <+>
1491            quotes (ppr tc_name)
1492          , nest 2 (parens $ ptext (sLit "Use -XTypeFamilies to allow indexed type families")) ]
1493
1494 tooManyParmsErr :: Located Name -> SDoc
1495 tooManyParmsErr tc_name
1496   = ptext (sLit "Family instance has too many parameters:") <+> 
1497     quotes (ppr tc_name)
1498
1499 tooFewParmsErr :: Arity -> SDoc
1500 tooFewParmsErr arity
1501   = ptext (sLit "Family instance has too few parameters; expected") <+> 
1502     ppr arity
1503
1504 wrongNumberOfParmsErr :: Arity -> SDoc
1505 wrongNumberOfParmsErr exp_arity
1506   = ptext (sLit "Number of parameters must match family declaration; expected")
1507     <+> ppr exp_arity
1508
1509 badBootFamInstDeclErr :: SDoc
1510 badBootFamInstDeclErr = 
1511   ptext (sLit "Illegal family instance in hs-boot file")
1512
1513 wrongKindOfFamily :: TyCon -> SDoc
1514 wrongKindOfFamily family =
1515   ptext (sLit "Wrong category of family instance; declaration was for a") <+>
1516   kindOfFamily
1517   where
1518     kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1519                  | isAlgTyCon family = ptext (sLit "data type")
1520                  | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1521
1522 emptyConDeclsErr :: Name -> SDoc
1523 emptyConDeclsErr tycon
1524   = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1525          nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]
1526 \end{code}