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