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