[project @ 2000-10-16 13:29:13 by sewardj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcInstDcls.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcInstDecls]{Typechecking instance declarations}
5
6 \begin{code}
7 module TcInstDcls ( tcInstDecls1, tcInstDecls2, tcAddDeclCtxt ) where
8
9 #include "HsVersions.h"
10
11
12 import CmdLineOpts      ( opt_GlasgowExts, opt_AllowUndecidableInstances, opt_D_dump_deriv )
13
14 import HsSyn            ( HsDecl(..), InstDecl(..), TyClDecl(..),
15                           MonoBinds(..), HsExpr(..),  HsLit(..), Sig(..),
16                           andMonoBindList, collectMonoBinders, isClassDecl
17                         )
18 import HsTypes          ( HsType (..), HsTyVarBndr(..), toHsTyVar )
19 import HsPat            ( InPat (..) )
20 import HsMatches        ( Match (..) )
21 import RnHsSyn          ( RenamedHsBinds, RenamedInstDecl, RenamedHsDecl, extractHsTyVars )
22 import TcHsSyn          ( TcMonoBinds, mkHsConApp )
23 import TcBinds          ( tcSpecSigs )
24 import TcClassDcl       ( tcMethodBind, badMethodErr )
25 import TcMonad       
26 import RnMonad          ( RnNameSupply, FixityEnv )
27 import Inst             ( InstOrigin(..),
28                           newDicts, newClassDicts,
29                           LIE, emptyLIE, plusLIE, plusLIEs )
30 import TcDeriv          ( tcDeriving )
31 import TcEnv            ( ValueEnv, tcExtendGlobalValEnv, 
32                           tcExtendTyVarEnvForMeths, TyThing (..),
33                           tcAddImportedIdInfo, tcInstId, tcLookupClass,
34                           newDFunName, tcExtendTyVarEnv
35                         )
36 import TcInstUtil       ( InstInfo(..), pprInstInfo, classDataCon, simpleInstInfoTyCon, simpleInstInfoTy )
37 import TcMonoType       ( tcTyVars, tcHsSigType, tcHsType, kcHsSigType )
38 import TcSimplify       ( tcSimplifyAndCheck )
39 import TcType           ( zonkTcSigTyVars )
40
41 import Bag              ( emptyBag, unitBag, unionBags, unionManyBags,
42                           foldBag, Bag, listToBag
43                         )
44 import Class            ( Class, DefMeth(..), classBigSig )
45 import Var              ( idName, idType )
46 import Maybes           ( maybeToBool, expectJust )
47 import MkId             ( mkDictFunId )
48 import Generics         ( validGenericInstanceType )
49 import Module           ( Module )
50 import Name             ( isLocallyDefined )
51 import NameSet          ( emptyNameSet, nameSetToList )
52 import PrelInfo         ( eRROR_ID )
53 import PprType          ( pprConstraint, pprPred )
54 import TyCon            ( isSynTyCon, tyConDerivings )
55 import Type             ( mkTyVarTys, splitSigmaTy, isTyVarTy,
56                           splitTyConApp_maybe, splitDictTy_maybe,
57                           splitAlgTyConApp_maybe, classesToPreds, classesOfPreds,
58                           unUsgTy, tyVarsOfTypes, mkClassPred, mkTyVarTy,
59                           getClassTys_maybe
60                         )
61 import Subst            ( mkTopTyVarSubst, substClasses, substTheta )
62 import VarSet           ( mkVarSet, varSetElems )
63 import TysWiredIn       ( genericTyCons, isFFIArgumentTy, isFFIResultTy )
64 import PrelNames        ( cCallableClassKey, cReturnableClassKey, hasKey )
65 import Name             ( Name, NameEnv, extendNameEnv_C, emptyNameEnv, 
66                           plusNameEnv_C, nameEnvElts )
67 import FiniteMap        ( mapFM )
68 import SrcLoc           ( SrcLoc )
69 import RnHsSyn          -- ( RenamedMonoBinds )
70 import VarSet           ( varSetElems )
71 import UniqFM           ( mapUFM )
72 import Unique           ( Uniquable(..) )
73 import BasicTypes       ( NewOrData(..) )
74 import ErrUtils         ( dumpIfSet )
75 import ListSetOps       ( Assoc, emptyAssoc, plusAssoc_C, mapAssoc, 
76                           assocElts, extendAssoc_C,
77                           equivClassesByUniq, minusList
78                         )
79 import List             ( intersect, (\\) )
80 import Outputable
81 \end{code}
82
83 Typechecking instance declarations is done in two passes. The first
84 pass, made by @tcInstDecls1@, collects information to be used in the
85 second pass.
86
87 This pre-processed info includes the as-yet-unprocessed bindings
88 inside the instance declaration.  These are type-checked in the second
89 pass, when the class-instance envs and GVE contain all the info from
90 all the instance and value decls.  Indeed that's the reason we need
91 two passes over the instance decls.
92
93
94 Here is the overall algorithm.
95 Assume that we have an instance declaration
96
97     instance c => k (t tvs) where b
98
99 \begin{enumerate}
100 \item
101 $LIE_c$ is the LIE for the context of class $c$
102 \item
103 $betas_bar$ is the free variables in the class method type, excluding the
104    class variable
105 \item
106 $LIE_cop$ is the LIE constraining a particular class method
107 \item
108 $tau_cop$ is the tau type of a class method
109 \item
110 $LIE_i$ is the LIE for the context of instance $i$
111 \item
112 $X$ is the instance constructor tycon
113 \item
114 $gammas_bar$ is the set of type variables of the instance
115 \item
116 $LIE_iop$ is the LIE for a particular class method instance
117 \item
118 $tau_iop$ is the tau type for this instance of a class method
119 \item
120 $alpha$ is the class variable
121 \item
122 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
123 \item
124 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
125 \end{enumerate}
126
127 ToDo: Update the list above with names actually in the code.
128
129 \begin{enumerate}
130 \item
131 First, make the LIEs for the class and instance contexts, which means
132 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
133 and make LIElistI and LIEI.
134 \item
135 Then process each method in turn.
136 \item
137 order the instance methods according to the ordering of the class methods
138 \item
139 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
140 \item
141 Create final dictionary function from bindings generated already
142 \begin{pseudocode}
143 df = lambda inst_tyvars
144        lambda LIEI
145          let Bop1
146              Bop2
147              ...
148              Bopn
149          and dbinds_super
150               in <op1,op2,...,opn,sd1,...,sdm>
151 \end{pseudocode}
152 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
153 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
154 \end{enumerate}
155
156
157 %************************************************************************
158 %*                                                                      *
159 \subsection{Extracting instance decls}
160 %*                                                                      *
161 %************************************************************************
162
163 Gather up the instance declarations from their various sources
164
165 \begin{code}
166 tcInstDecls1 :: PersistentCompilerState
167              -> HomeSymbolTable         -- Contains instances
168              -> TcEnv                   -- Contains IdInfo for dfun ids
169              -> Module                  -- Module for deriving
170              -> [RenamedHsDecl]
171              -> TcM (PersistentCompilerState, InstEnv, [InstInfo], RenamedHsBinds)
172
173 tcInstDecls1 pcs hst unf_env this_mod decls mod
174   = let
175         inst_decls = [inst_decl | InstD inst_decl <- decls]
176         clas_decls = [clas_decl | TyClD clas_decl <- decls, isClassDecl cl_decl]
177     in
178         -- (1) Do the ordinary instance declarations
179     mapNF_Tc (tcInstDecl1 mod) inst_decls               `thenNF_Tc` \ inst_infos ->
180
181         -- (2) Instances from generic class declarations
182     getGenericInstances mod clas_decls                  `thenTc` \ generic_inst_info -> 
183
184         -- Next, consruct the instance environment so far, consisting of
185         --      a) cached non-home-package InstEnv (gotten from pcs)    pcs_insts pcs
186         --      b) imported instance decls (not in the home package)    inst_env1
187         --      c) other modules in this package (gotten from hst)      inst_env2
188         --      d) local instance decls                                 inst_env3
189         --      e) generic instances                                    inst_env4
190         -- The result of (b) replaces the cached InstEnv in the PCS
191     let
192         (local_inst_info, imported_inst_info) = partition isLocalInst (concat inst_infos)
193         generic_inst_info = concat generic_inst_infos   -- All local
194
195         imported_dfuns   = map (tcAddImportedIdInfo unf_env . instInfoDFun) imported_inst_info
196         hst_dfuns        = foldModuleEnv ((++) . md_insts) [] hst
197     in
198     addInstDFuns (pcs_insts pcs) imported_dfuns `thenNF_Tc` \ inst_env1 ->
199     addInstDFuns inst_env1 hst_dfuns            `thenNF_Tc` \ inst_env2 ->
200     addInstInfos inst_env2 local_inst_info      `thenNF_Tc` \ inst_env3 ->
201     addInstInfos inst_env3 generic_inst_info    `thenNF_Tc` \ inst_env4 ->
202     in
203
204         -- (3) Compute instances from "deriving" clauses; 
205         --     note that we only do derivings for things in this module; 
206         --     we ignore deriving decls from interfaces!
207         -- This stuff computes a context for the derived instance decl, so it
208         -- needs to know about all the instances possible; hecne inst_env4
209     tcDeriving (pcs_PRS pcs) this_mod inst_env4 local_tycons    `thenTc` \ (deriv_inst_info, deriv_binds) ->
210     addInstInfos inst_env4 deriv_inst_info                      `thenNF_Tc` \ final_inst_env ->
211
212     returnTc (pcs { pcs_insts = inst_env1 }, 
213               final_inst_env, 
214               generic_inst_info ++ deriv_inst_info ++ local_inst_info,
215               deriv_binds)
216
217 addInstInfos :: InstEnv -> [InstInfo] -> NF_TcM InstEnv
218 addInstInfos inst_env infos = addInstDfuns inst_env (map iDFun infos)
219
220 addInstDFuns :: InstEnv -> [DFunId] -> NF_TcM InstEnv
221 addInstDFuns dfuns infos
222   = addErrsTc errs      `thenNF_Tc_` 
223     returnTc inst_env'
224   where
225     (inst_env', errs) = extendInstEnv env dfuns
226 \end{code} 
227
228 \begin{code}
229 tcInstDecl1 :: Module -> ValueEnv -> RenamedInstDecl -> NF_TcM [InstInfo]
230 -- Deal with a single instance declaration
231 tcInstDecl1 mod unf_env (InstDecl poly_ty binds uprags maybe_dfun_name src_loc)
232   =     -- Prime error recovery, set source location
233     recoverNF_Tc (returnNF_Tc [])       $
234     tcAddSrcLoc src_loc                 $
235
236         -- Type-check all the stuff before the "where"
237     tcHsSigType poly_ty                 `thenTc` \ poly_ty' ->
238     let
239         (tyvars, theta, dict_ty) = splitSigmaTy poly_ty'
240         (clas, inst_tys)         = case splitDictTy_maybe dict_ty of
241                                      Just ct -> ct
242                                      Nothing -> pprPanic "tcInstDecl1" (ppr poly_ty)
243     in
244
245     (case maybe_dfun_name of
246         Nothing ->      -- A source-file instance declaration
247
248                 -- Check for respectable instance type, and context
249                 -- but only do this for non-imported instance decls.
250                 -- Imported ones should have been checked already, and may indeed
251                 -- contain something illegal in normal Haskell, notably
252                 --      instance CCallable [Char] 
253             scrutiniseInstanceHead clas inst_tys                `thenNF_Tc_`
254             mapNF_Tc scrutiniseInstanceConstraint theta         `thenNF_Tc_`
255
256                 -- Make the dfun id and return it
257             newDFunName mod clas inst_tys src_loc               `thenNF_Tc` \ dfun_name ->
258             returnNF_Tc (True, mkDictFunId dfun_name clas tyvars inst_tys theta)
259
260         Just dfun_name ->       -- An interface-file instance declaration
261                 -- Make the dfun id
262             returnNF_Tc (False, mkDictFunId dfun_name clas tyvars inst_tys theta)
263     )                                           `thenNF_Tc` \ (is_local, dfun_id) ->
264
265     returnTc [InstInfo { iLocal = is_local,
266                          iClass = clas, iTyVars = tyvars, iTys = inst_tys,
267                          iTheta = theta, iDFunId = dfun_id, 
268                          iBinds = binds, iLoc = src_loc, iPrags = uprags }]
269 \end{code}
270
271
272 %************************************************************************
273 %*                                                                      *
274 \subsection{Extracting generic instance declaration from class declarations}
275 %*                                                                      *
276 %************************************************************************
277
278 @getGenericInstances@ extracts the generic instance declarations from a class
279 declaration.  For exmaple
280
281         class C a where
282           op :: a -> a
283         
284           op{ x+y } (Inl v)   = ...
285           op{ x+y } (Inr v)   = ...
286           op{ x*y } (v :*: w) = ...
287           op{ 1   } Unit      = ...
288
289 gives rise to the instance declarations
290
291         instance C (x+y) where
292           op (Inl v)   = ...
293           op (Inr v)   = ...
294         
295         instance C (x*y) where
296           op (v :*: w) = ...
297
298         instance C 1 where
299           op Unit      = ...
300
301
302 \begin{code}
303 getGenericInstances :: Module -> [RenamedTyClDecl] -> TcM [InstInfo] 
304 getGenericInstances mod class_decls
305   = mapTc (get_generics mod) class_decls                        `thenTc` \ gen_inst_infos ->
306     let
307         gen_inst_info = concat gen_inst_infos
308     in
309     ioToTc (dumpIfSet opt_D_dump_deriv "Generic instances" 
310                       (vcat (map pprInstInfo gen_inst_info)))   `thenNF_Tc_`
311     returnTc gen_inst_info
312
313 get_generics mod decl@(ClassDecl context class_name tyvar_names 
314                                  fundeps class_sigs def_methods pragmas 
315                                  name_list loc)
316   | null groups         
317   = returnTc [] -- The comon case: 
318                 --      no generic default methods, or
319                 --      its an imported class decl (=> has no methods at all)
320
321   | otherwise   -- A local class decl with generic default methods
322   = recoverNF_Tc (returnNF_Tc [])                               $
323     tcAddDeclCtxt decl                                          $
324     tcLookupClass class_name                                    `thenTc` \ clas ->
325
326         -- Make an InstInfo out of each group
327     mapTc (mkGenericInstance mod clas loc) groups               `thenTc` \ inst_infos ->
328
329         -- Check that there is only one InstInfo for each type constructor
330         -- The main way this can fail is if you write
331         --      f {| a+b |} ... = ...
332         --      f {| x+y |} ... = ...
333         -- Then at this point we'll have an InstInfo for each
334     let
335         bad_groups = [group | group <- equivClassesByUniq get_uniq inst_infos,
336                               length group > 1]
337         get_uniq inst = getUnique (simpleInstInfoTyCon inst)
338     in
339     mapTc (addErrTc . dupGenericInsts) bad_groups       `thenTc_`
340
341         -- Check that there is an InstInfo for each generic type constructor
342     let
343         missing = genericTyCons `minusList` map simpleInstInfoTyCon inst_infos
344     in
345     checkTc (null missing) (missingGenericInstances missing)    `thenTc_`
346
347     returnTc inst_infos
348
349   where
350         -- Group the declarations by type pattern
351         groups :: [(RenamedHsType, RenamedMonoBinds)]
352         groups = assocElts (getGenericBinds def_methods)
353
354
355 ---------------------------------
356 getGenericBinds :: RenamedMonoBinds -> Assoc RenamedHsType RenamedMonoBinds
357   -- Takes a group of method bindings, finds the generic ones, and returns
358   -- them in finite map indexed by the type parameter in the definition.
359
360 getGenericBinds EmptyMonoBinds    = emptyAssoc
361 getGenericBinds (AndMonoBinds m1 m2) 
362   = plusAssoc_C AndMonoBinds (getGenericBinds m1) (getGenericBinds m2)
363
364 getGenericBinds (FunMonoBind id infixop matches loc)
365   = mapAssoc wrap (foldr add emptyAssoc matches)
366   where
367     add match env = case maybeGenericMatch match of
368                       Nothing           -> env
369                       Just (ty, match') -> extendAssoc_C (++) env (ty, [match'])
370
371     wrap ms = FunMonoBind id infixop ms loc
372
373 ---------------------------------
374 mkGenericInstance :: Module -> Class -> SrcLoc
375                   -> (RenamedHsType, RenamedMonoBinds)
376                   -> TcM InstInfo
377
378 mkGenericInstance mod clas loc (hs_ty, binds)
379   -- Make a generic instance declaration
380   -- For example:       instance (C a, C b) => C (a+b) where { binds }
381
382   =     -- Extract the universally quantified type variables
383     tcTyVars (nameSetToList (extractHsTyVars hs_ty)) 
384              (kcHsSigType hs_ty)                `thenTc` \ tyvars ->
385     tcExtendTyVarEnv tyvars                                     $
386
387         -- Type-check the instance type, and check its form
388     tcHsSigType hs_ty                           `thenTc` \ inst_ty ->
389     checkTc (validGenericInstanceType inst_ty)
390             (badGenericInstanceType binds)      `thenTc_`
391
392         -- Make the dictionary function.
393     newDFunName mod clas [inst_ty] loc          `thenNF_Tc` \ dfun_name ->
394     let
395         inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
396         inst_tys   = [inst_ty]
397         dfun_id    = mkDictFunId dfun_name clas tyvars inst_tys inst_theta
398     in
399
400     returnTc (InstInfo { iLocal = True,
401                          iClass = clas, iTyVars = tyvars, iTys = inst_tys, 
402                          iTheta = inst_theta, iDFunId = dfun_id, iBinds = binds,
403                          iLoc = loc, iPrags = [] })
404 \end{code}
405
406
407 %************************************************************************
408 %*                                                                      *
409 \subsection{Type-checking instance declarations, pass 2}
410 %*                                                                      *
411 %************************************************************************
412
413 \begin{code}
414 tcInstDecls2 :: Bag InstInfo
415              -> NF_TcM (LIE, TcMonoBinds)
416
417 tcInstDecls2 inst_decls
418   = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
419   where
420     combine tc1 tc2 = tc1       `thenNF_Tc` \ (lie1, binds1) ->
421                       tc2       `thenNF_Tc` \ (lie2, binds2) ->
422                       returnNF_Tc (lie1 `plusLIE` lie2,
423                                    binds1 `AndMonoBinds` binds2)
424 \end{code}
425
426 ======= New documentation starts here (Sept 92)  ==============
427
428 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
429 the dictionary function for this instance declaration.  For example
430 \begin{verbatim}
431         instance Foo a => Foo [a] where
432                 op1 x = ...
433                 op2 y = ...
434 \end{verbatim}
435 might generate something like
436 \begin{verbatim}
437         dfun.Foo.List dFoo_a = let op1 x = ...
438                                    op2 y = ...
439                                in
440                                    Dict [op1, op2]
441 \end{verbatim}
442
443 HOWEVER, if the instance decl has no context, then it returns a
444 bigger @HsBinds@ with declarations for each method.  For example
445 \begin{verbatim}
446         instance Foo [a] where
447                 op1 x = ...
448                 op2 y = ...
449 \end{verbatim}
450 might produce
451 \begin{verbatim}
452         dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
453         const.Foo.op1.List a x = ...
454         const.Foo.op2.List a y = ...
455 \end{verbatim}
456 This group may be mutually recursive, because (for example) there may
457 be no method supplied for op2 in which case we'll get
458 \begin{verbatim}
459         const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
460 \end{verbatim}
461 that is, the default method applied to the dictionary at this type.
462
463 What we actually produce in either case is:
464
465         AbsBinds [a] [dfun_theta_dicts]
466                  [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
467                  { d = (sd1,sd2, ..., op1, op2, ...)
468                    op1 = ...
469                    op2 = ...
470                  }
471
472 The "maybe" says that we only ask AbsBinds to make global constant methods
473 if the dfun_theta is empty.
474
475                 
476 For an instance declaration, say,
477
478         instance (C1 a, C2 b) => C (T a b) where
479                 ...
480
481 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
482 function whose type is
483
484         (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
485
486 Notice that we pass it the superclass dictionaries at the instance type; this
487 is the ``Mark Jones optimisation''.  The stuff before the "=>" here
488 is the @dfun_theta@ below.
489
490 First comes the easy case of a non-local instance decl.
491
492 \begin{code}
493 tcInstDecl2 :: InstInfo -> NF_TcM (LIE, TcMonoBinds)
494
495 tcInstDecl2 (InstInfo { iClass = clas, iTyVars = inst_tyvars, iTys = inst_tys,
496                         iTheta = inst_decl_theta, iDFunId = dfun_id,
497                         iBinds = monobinds, iLoc = locn, iPrags = uprags })
498   | not (isLocallyDefined dfun_id)
499   = returnNF_Tc (emptyLIE, EmptyMonoBinds)
500
501   | otherwise
502   =      -- Prime error recovery
503     recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds))  $
504     tcAddSrcLoc locn                                       $
505
506         -- Instantiate the instance decl with tc-style type variables
507     tcInstId dfun_id            `thenNF_Tc` \ (inst_tyvars', dfun_theta', dict_ty') ->
508     let
509         (clas, inst_tys') = expectJust "tcInstDecl2" (splitDictTy_maybe dict_ty')
510         origin            = InstanceDeclOrigin
511
512         (class_tyvars, sc_theta, _, op_items) = classBigSig clas
513
514         dm_ids    = [dm_id | (_, DefMeth dm_id) <- op_items]
515         sel_names = [idName sel_id | (sel_id, _) <- op_items]
516
517         -- Instantiate the theta found in the original instance decl
518         inst_decl_theta' = substTheta (mkTopTyVarSubst inst_tyvars (mkTyVarTys inst_tyvars'))
519                                       inst_decl_theta
520
521         -- Instantiate the super-class context with inst_tys
522         sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
523
524         -- Find any definitions in monobinds that aren't from the class
525         bad_bndrs = collectMonoBinders monobinds `minusList` sel_names
526     in
527          -- Check that all the method bindings come from this class
528     mapTc (addErrTc . badMethodErr clas) bad_bndrs              `thenNF_Tc_`
529
530          -- Create dictionary Ids from the specified instance contexts.
531     newClassDicts origin sc_theta'              `thenNF_Tc` \ (sc_dicts,        sc_dict_ids) ->
532     newDicts origin dfun_theta'                 `thenNF_Tc` \ (dfun_arg_dicts,  dfun_arg_dicts_ids)  ->
533     newDicts origin inst_decl_theta'            `thenNF_Tc` \ (inst_decl_dicts, _) ->
534     newClassDicts origin [(clas,inst_tys')]     `thenNF_Tc` \ (this_dict,       [this_dict_id]) ->
535
536     tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
537         tcExtendGlobalValEnv dm_ids (
538                 -- Default-method Ids may be mentioned in synthesised RHSs 
539
540         mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
541                                      inst_decl_theta'
542                                      monobinds uprags True)
543                        op_items
544     ))                  `thenTc` \ (method_binds_s, insts_needed_s, meth_lies_w_ids) ->
545
546         -- Deal with SPECIALISE instance pragmas by making them
547         -- look like SPECIALISE pragmas for the dfun
548     let
549         dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
550     in
551     tcExtendGlobalValEnv [dfun_id] (
552         tcSpecSigs dfun_prags
553     )                                   `thenTc` \ (prag_binds, prag_lie) ->
554
555         -- Check the overloading constraints of the methods and superclasses
556
557         -- tcMethodBind has checked that the class_tyvars havn't
558         -- been unified with each other or another type, but we must
559         -- still zonk them before passing them to tcSimplifyAndCheck
560     zonkTcSigTyVars inst_tyvars'        `thenNF_Tc` \ zonked_inst_tyvars ->
561     let
562         inst_tyvars_set = mkVarSet zonked_inst_tyvars
563
564         (meth_lies, meth_ids) = unzip meth_lies_w_ids
565
566                  -- These insts are in scope; quite a few, eh?
567         avail_insts = this_dict                 `plusLIE` 
568                       dfun_arg_dicts            `plusLIE`
569                       sc_dicts                  `plusLIE`
570                       unionManyBags meth_lies
571
572         methods_lie = plusLIEs insts_needed_s
573     in
574
575         -- Ditto method bindings
576     tcAddErrCtxt methodCtxt (
577       tcSimplifyAndCheck
578                  (ptext SLIT("instance declaration context"))
579                  inst_tyvars_set                        -- Local tyvars
580                  avail_insts
581                  methods_lie
582     )                                            `thenTc` \ (const_lie1, lie_binds1) ->
583     
584         -- Check that we *could* construct the superclass dictionaries,
585         -- even though we are *actually* going to pass the superclass dicts in;
586         -- the check ensures that the caller will never have 
587         --a problem building them.
588     tcAddErrCtxt superClassCtxt (
589       tcSimplifyAndCheck
590                  (ptext SLIT("instance declaration context"))
591                  inst_tyvars_set                -- Local tyvars
592                  inst_decl_dicts                -- The instance dictionaries available
593                  sc_dicts                       -- The superclass dicationaries reqd
594     )                                   `thenTc` \ _ -> 
595                                                 -- Ignore the result; we're only doing
596                                                 -- this to make sure it can be done.
597
598         -- Now do the simplification again, this time to get the
599         -- bindings; this time we use an enhanced "avails"
600         -- Ignore errors because they come from the *previous* tcSimplify
601     discardErrsTc (
602         tcSimplifyAndCheck
603                  (ptext SLIT("instance declaration context"))
604                  inst_tyvars_set
605                  dfun_arg_dicts         -- NB! Don't include this_dict here, else the sc_dicts
606                                         -- get bound by just selecting from this_dict!!
607                  sc_dicts
608     )                                            `thenTc` \ (const_lie2, lie_binds2) ->
609         
610
611         -- Create the result bindings
612     let
613         dict_constr   = classDataCon clas
614         scs_and_meths = sc_dict_ids ++ meth_ids
615
616         dict_rhs
617           | null scs_and_meths
618           =     -- Blatant special case for CCallable, CReturnable
619                 -- If the dictionary is empty then we should never
620                 -- select anything from it, so we make its RHS just
621                 -- emit an error message.  This in turn means that we don't
622                 -- mention the constructor, which doesn't exist for CCallable, CReturnable
623                 -- Hardly beautiful, but only three extra lines.
624             HsApp (TyApp (HsVar eRROR_ID) [(unUsgTy . idType) this_dict_id])
625                   (HsLit (HsString msg))
626
627           | otherwise   -- The common case
628           = mkHsConApp dict_constr inst_tys' (map HsVar (sc_dict_ids ++ meth_ids))
629                 -- We don't produce a binding for the dict_constr; instead we
630                 -- rely on the simplifier to unfold this saturated application
631                 -- We do this rather than generate an HsCon directly, because
632                 -- it means that the special cases (e.g. dictionary with only one
633                 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
634                 -- than needing to be repeated here.
635
636           where
637             msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
638
639         dict_bind    = VarMonoBind this_dict_id dict_rhs
640         method_binds = andMonoBindList method_binds_s
641
642         main_bind
643           = AbsBinds
644                  zonked_inst_tyvars
645                  dfun_arg_dicts_ids
646                  [(inst_tyvars', dfun_id, this_dict_id)] 
647                  emptyNameSet           -- No inlines (yet)
648                  (lie_binds1    `AndMonoBinds` 
649                   lie_binds2    `AndMonoBinds`
650                   method_binds  `AndMonoBinds`
651                   dict_bind)
652     in
653     returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
654               main_bind `AndMonoBinds` prag_binds)
655 \end{code}
656
657
658 %************************************************************************
659 %*                                                                      *
660 \subsection{Checking for a decent instance type}
661 %*                                                                      *
662 %************************************************************************
663
664 @scrutiniseInstanceHead@ checks the type {\em and} its syntactic constraints:
665 it must normally look like: @instance Foo (Tycon a b c ...) ...@
666
667 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
668 flag is on, or (2)~the instance is imported (they must have been
669 compiled elsewhere). In these cases, we let them go through anyway.
670
671 We can also have instances for functions: @instance Foo (a -> b) ...@.
672
673 \begin{code}
674 scrutiniseInstanceConstraint pred
675   | opt_AllowUndecidableInstances
676   = returnNF_Tc ()
677
678   | Just (clas,tys) <- getClassTys_maybe pred,
679     all isTyVarTy tys
680   = returnNF_Tc ()
681
682   | otherwise
683   = addErrTc (instConstraintErr pred)
684
685 scrutiniseInstanceHead clas inst_taus
686   |     -- CCALL CHECK
687         -- A user declaration of a CCallable/CReturnable instance
688         -- must be for a "boxed primitive" type.
689     (clas `hasKey` cCallableClassKey   && not (ccallable_type   first_inst_tau)) ||
690     (clas `hasKey` cReturnableClassKey && not (creturnable_type first_inst_tau))
691   = addErrTc (nonBoxedPrimCCallErr clas first_inst_tau)
692
693         -- DERIVING CHECK
694         -- It is obviously illegal to have an explicit instance
695         -- for something that we are also planning to `derive'
696   | maybeToBool alg_tycon_app_maybe && clas `elem` (tyConDerivings alg_tycon)
697   = addErrTc (derivingWhenInstanceExistsErr clas first_inst_tau)
698            -- Kind check will have ensured inst_taus is of length 1
699
700         -- Allow anything for AllowUndecidableInstances
701   | opt_AllowUndecidableInstances
702   = returnNF_Tc ()
703
704         -- If GlasgowExts then check at least one isn't a type variable
705   | opt_GlasgowExts 
706   = if all isTyVarTy inst_taus then
707         addErrTc (instTypeErr clas inst_taus (text "There must be at least one non-type-variable in the instance head"))
708     else
709         returnNF_Tc ()
710
711         -- WITH HASKELL 1.4, MUST HAVE C (T a b c)
712   |  not (length inst_taus == 1 &&
713           maybeToBool maybe_tycon_app &&        -- Yes, there's a type constuctor
714           not (isSynTyCon tycon) &&             -- ...but not a synonym
715           all isTyVarTy arg_tys &&              -- Applied to type variables
716           length (varSetElems (tyVarsOfTypes arg_tys)) == length arg_tys
717                  -- This last condition checks that all the type variables are distinct
718      )
719   = addErrTc (instTypeErr clas inst_taus
720                         (text "the instance type must be of form (T a b c)" $$
721                          text "where T is not a synonym, and a,b,c are distinct type variables")
722     )
723
724   | otherwise
725   = returnNF_Tc ()
726
727   where
728     (first_inst_tau : _)       = inst_taus
729
730         -- Stuff for algebraic or -> type
731     maybe_tycon_app       = splitTyConApp_maybe first_inst_tau
732     Just (tycon, arg_tys) = maybe_tycon_app
733
734         -- Stuff for an *algebraic* data type
735     alg_tycon_app_maybe    = splitAlgTyConApp_maybe first_inst_tau
736                                 -- The "Alg" part looks through synonyms
737     Just (alg_tycon, _, _) = alg_tycon_app_maybe
738  
739 ccallable_type   ty = isFFIArgumentTy False {- Not safe call -} ty
740 creturnable_type ty = isFFIResultTy ty
741 \end{code}
742
743
744 %************************************************************************
745 %*                                                                      *
746 \subsection{Error messages}
747 %*                                                                      *
748 %************************************************************************
749
750 \begin{code}
751 tcAddDeclCtxt decl thing_inside
752   = tcAddSrcLoc loc     $
753     tcAddErrCtxt ctxt   $
754     thing_inside
755   where
756      (name, loc, thing)
757         = case decl of
758             (ClassDecl _ name _ _ _ _ _ _ loc)         -> (name, loc, "class")
759             (TySynonym name _ _ loc)                   -> (name, loc, "type synonym")
760             (TyData NewType  _ name _ _ _ _ _ loc _ _) -> (name, loc, "newtype")
761             (TyData DataType _ name _ _ _ _ _ loc _ _) -> (name, loc, "data type")
762
763      ctxt = hsep [ptext SLIT("In the"), text thing, 
764                   ptext SLIT("declaration for"), quotes (ppr name)]
765 \end{code}
766
767 \begin{code}
768 instConstraintErr pred
769   = hang (ptext SLIT("Illegal constraint") <+> 
770           quotes (pprPred pred) <+> 
771           ptext SLIT("in instance context"))
772          4 (ptext SLIT("(Instance contexts must constrain only type variables)"))
773         
774 badGenericInstanceType binds
775   = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
776           nest 4 (ppr binds)]
777
778 missingGenericInstances missing
779   = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
780           
781
782
783 dupGenericInsts inst_infos
784   = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
785           nest 4 (vcat (map (ppr . simpleInstInfoTy) inst_infos)),
786           ptext SLIT("All the type patterns for a generic type constructor must be identical")
787     ]
788
789 instTypeErr clas tys msg
790   = sep [ptext SLIT("Illegal instance declaration for") <+> quotes (pprConstraint clas tys),
791          nest 4 (parens msg)
792     ]
793
794 derivingWhenInstanceExistsErr clas tycon
795   = hang (hsep [ptext SLIT("Deriving class"), 
796                        quotes (ppr clas), 
797                        ptext SLIT("type"), quotes (ppr tycon)])
798          4 (ptext SLIT("when an explicit instance exists"))
799
800 nonBoxedPrimCCallErr clas inst_ty
801   = hang (ptext SLIT("Unacceptable instance type for ccall-ish class"))
802          4 (hsep [ ptext SLIT("class"), ppr clas, ptext SLIT("type"),
803                         ppr inst_ty])
804
805 methodCtxt     = ptext SLIT("When checking the methods of an instance declaration")
806 superClassCtxt = ptext SLIT("When checking the superclasses of an instance declaration")
807 \end{code}