[project @ 2000-10-12 13:44:59 by simonpj]
[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 :: PersistentRenamerState
167              -> TcEnv                   -- Contains IdInfo for dfun ids
168              -> [RenamedHsDecl]
169              -> Module                  -- Module for deriving
170              -> FixityEnv               -- For derivings
171              -> RnNameSupply            -- For renaming derivings
172              -> TcM (Bag InstInfo,
173                        RenamedHsBinds)
174
175 tcInstDecls1 prs unf_env decls mod 
176   =     -- (1) Do the ordinary instance declarations
177     mapNF_Tc (tcInstDecl1 mod unf_env) 
178              [inst_decl | InstD inst_decl <- decls]     `thenNF_Tc` \ inst_info_bags ->
179     let
180         decl_inst_info = unionManyBags inst_info_bags
181     in
182         -- (2) Instances from "deriving" clauses; note that we only do derivings
183         -- for things in this module; we ignore deriving decls from
184         -- interfaces!
185     tcDeriving prs mod decl_inst_info                   `thenTc` \ (deriv_inst_info, deriv_binds) ->
186
187         -- (3) Instances from generic class declarations
188     mapTc (getGenericInstances mod) 
189           [cl_decl | TyClD cl_decl <- decls, isClassDecl cl_decl]       `thenTc` \ cls_inst_info ->
190
191     let
192         generic_insts  = concat cls_inst_info
193         full_inst_info = deriv_inst_info `unionBags` 
194                          unionManyBags inst_info_bags `unionBags` 
195                          (listToBag generic_insts)
196     in
197     ioToTc (dumpIfSet opt_D_dump_deriv "Generic instances" 
198                       (vcat (map pprInstInfo generic_insts)))   `thenNF_Tc_`
199
200     (returnTc (full_inst_info, deriv_binds)) 
201 \end{code} 
202
203 \begin{code}
204 tcInstDecl1 :: Module -> ValueEnv -> RenamedInstDecl -> NF_TcM (Bag InstInfo)
205 -- Deal with a single instance declaration
206 tcInstDecl1 mod unf_env (InstDecl poly_ty binds uprags maybe_dfun_name src_loc)
207   =     -- Prime error recovery, set source location
208     recoverNF_Tc (returnNF_Tc emptyBag) $
209     tcAddSrcLoc src_loc                 $
210
211         -- Type-check all the stuff before the "where"
212     tcHsSigType poly_ty                 `thenTc` \ poly_ty' ->
213     let
214         (tyvars, theta, dict_ty) = splitSigmaTy poly_ty'
215         (clas, inst_tys)         = case splitDictTy_maybe dict_ty of
216                                      Just ct -> ct
217                                      Nothing -> pprPanic "tcInstDecl1" (ppr poly_ty)
218     in
219
220     (case maybe_dfun_name of
221         Nothing ->      -- A source-file instance declaration
222
223                 -- Check for respectable instance type, and context
224                 -- but only do this for non-imported instance decls.
225                 -- Imported ones should have been checked already, and may indeed
226                 -- contain something illegal in normal Haskell, notably
227                 --      instance CCallable [Char] 
228             scrutiniseInstanceHead clas inst_tys                `thenNF_Tc_`
229             mapNF_Tc scrutiniseInstanceConstraint theta         `thenNF_Tc_`
230
231                 -- Make the dfun id and return it
232             newDFunName mod clas inst_tys src_loc               `thenNF_Tc` \ dfun_name ->
233             returnNF_Tc (mkDictFunId dfun_name clas tyvars inst_tys theta)
234
235         Just dfun_name ->       -- An interface-file instance declaration
236                 -- Make the dfun id and add info from interface file
237             let
238                 dfun_id = mkDictFunId dfun_name clas tyvars inst_tys theta
239             in
240             returnNF_Tc (tcAddImportedIdInfo unf_env dfun_id)
241     )                                           `thenNF_Tc` \ dfun_id ->
242
243     returnTc (unitBag (InstInfo clas tyvars inst_tys theta dfun_id binds src_loc uprags))
244 \end{code}
245
246
247 %************************************************************************
248 %*                                                                      *
249 \subsection{Extracting generic instance declaration from class declarations}
250 %*                                                                      *
251 %************************************************************************
252
253 @getGenericInstances@ extracts the generic instance declarations from a class
254 declaration.  For exmaple
255
256         class C a where
257           op :: a -> a
258         
259           op{ x+y } (Inl v)   = ...
260           op{ x+y } (Inr v)   = ...
261           op{ x*y } (v :*: w) = ...
262           op{ 1   } Unit      = ...
263
264 gives rise to the instance declarations
265
266         instance C (x+y) where
267           op (Inl v)   = ...
268           op (Inr v)   = ...
269         
270         instance C (x*y) where
271           op (v :*: w) = ...
272
273         instance C 1 where
274           op Unit      = ...
275
276
277 \begin{code}
278 getGenericInstances :: Module -> RenamedTyClDecl -> TcM [InstInfo] 
279 getGenericInstances mod decl@(ClassDecl context class_name tyvar_names 
280                                         fundeps class_sigs def_methods pragmas 
281                                         name_list loc)
282   | null groups         
283   = returnTc []         -- The comon case
284
285   | otherwise
286   = recoverNF_Tc (returnNF_Tc [])                               $
287     tcAddDeclCtxt decl                                          $
288     tcLookupClass class_name                                    `thenTc` \ clas ->
289
290         -- Make an InstInfo out of each group
291     mapTc (mkGenericInstance mod clas loc) groups               `thenTc` \ inst_infos ->
292
293         -- Check that there is only one InstInfo for each type constructor
294         -- The main way this can fail is if you write
295         --      f {| a+b |} ... = ...
296         --      f {| x+y |} ... = ...
297         -- Then at this point we'll have an InstInfo for each
298     let
299         bad_groups = [group | group <- equivClassesByUniq get_uniq inst_infos,
300                               length group > 1]
301         get_uniq inst = getUnique (simpleInstInfoTyCon inst)
302     in
303     mapTc (addErrTc . dupGenericInsts) bad_groups       `thenTc_`
304
305         -- Check that there is an InstInfo for each generic type constructor
306     let
307         missing = genericTyCons `minusList` map simpleInstInfoTyCon inst_infos
308     in
309     checkTc (null missing) (missingGenericInstances missing)    `thenTc_`
310
311     returnTc inst_infos
312
313   where
314         -- Group the declarations by type pattern
315         groups :: [(RenamedHsType, RenamedMonoBinds)]
316         groups = assocElts (getGenericBinds def_methods)
317
318
319 ---------------------------------
320 getGenericBinds :: RenamedMonoBinds -> Assoc RenamedHsType RenamedMonoBinds
321   -- Takes a group of method bindings, finds the generic ones, and returns
322   -- them in finite map indexed by the type parameter in the definition.
323
324 getGenericBinds EmptyMonoBinds    = emptyAssoc
325 getGenericBinds (AndMonoBinds m1 m2) 
326   = plusAssoc_C AndMonoBinds (getGenericBinds m1) (getGenericBinds m2)
327
328 getGenericBinds (FunMonoBind id infixop matches loc)
329   = mapAssoc wrap (foldr add emptyAssoc matches)
330   where
331     add match env = case maybeGenericMatch match of
332                       Nothing           -> env
333                       Just (ty, match') -> extendAssoc_C (++) env (ty, [match'])
334
335     wrap ms = FunMonoBind id infixop ms loc
336
337 ---------------------------------
338 mkGenericInstance :: Module -> Class -> SrcLoc
339                   -> (RenamedHsType, RenamedMonoBinds)
340                   -> TcM InstInfo
341
342 mkGenericInstance mod clas loc (hs_ty, binds)
343   -- Make a generic instance declaration
344   -- For example:       instance (C a, C b) => C (a+b) where { binds }
345
346   =     -- Extract the universally quantified type variables
347     tcTyVars (nameSetToList (extractHsTyVars hs_ty)) 
348              (kcHsSigType hs_ty)                `thenTc` \ tyvars ->
349     tcExtendTyVarEnv tyvars                                     $
350
351         -- Type-check the instance type, and check its form
352     tcHsSigType hs_ty                           `thenTc` \ inst_ty ->
353     checkTc (validGenericInstanceType inst_ty)
354             (badGenericInstanceType binds)      `thenTc_`
355
356         -- Make the dictionary function.
357     newDFunName mod clas [inst_ty] loc          `thenNF_Tc` \ dfun_name ->
358     let
359         inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
360         inst_tys   = [inst_ty]
361         dfun_id    = mkDictFunId dfun_name clas tyvars inst_tys inst_theta
362     in
363
364     returnTc (InstInfo clas tyvars inst_tys inst_theta dfun_id binds loc [])
365         -- The "[]" means "no pragmas"
366 \end{code}
367
368
369 %************************************************************************
370 %*                                                                      *
371 \subsection{Type-checking instance declarations, pass 2}
372 %*                                                                      *
373 %************************************************************************
374
375 \begin{code}
376 tcInstDecls2 :: Bag InstInfo
377              -> NF_TcM (LIE, TcMonoBinds)
378
379 tcInstDecls2 inst_decls
380   = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
381   where
382     combine tc1 tc2 = tc1       `thenNF_Tc` \ (lie1, binds1) ->
383                       tc2       `thenNF_Tc` \ (lie2, binds2) ->
384                       returnNF_Tc (lie1 `plusLIE` lie2,
385                                    binds1 `AndMonoBinds` binds2)
386 \end{code}
387
388 ======= New documentation starts here (Sept 92)  ==============
389
390 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
391 the dictionary function for this instance declaration.  For example
392 \begin{verbatim}
393         instance Foo a => Foo [a] where
394                 op1 x = ...
395                 op2 y = ...
396 \end{verbatim}
397 might generate something like
398 \begin{verbatim}
399         dfun.Foo.List dFoo_a = let op1 x = ...
400                                    op2 y = ...
401                                in
402                                    Dict [op1, op2]
403 \end{verbatim}
404
405 HOWEVER, if the instance decl has no context, then it returns a
406 bigger @HsBinds@ with declarations for each method.  For example
407 \begin{verbatim}
408         instance Foo [a] where
409                 op1 x = ...
410                 op2 y = ...
411 \end{verbatim}
412 might produce
413 \begin{verbatim}
414         dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
415         const.Foo.op1.List a x = ...
416         const.Foo.op2.List a y = ...
417 \end{verbatim}
418 This group may be mutually recursive, because (for example) there may
419 be no method supplied for op2 in which case we'll get
420 \begin{verbatim}
421         const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
422 \end{verbatim}
423 that is, the default method applied to the dictionary at this type.
424
425 What we actually produce in either case is:
426
427         AbsBinds [a] [dfun_theta_dicts]
428                  [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
429                  { d = (sd1,sd2, ..., op1, op2, ...)
430                    op1 = ...
431                    op2 = ...
432                  }
433
434 The "maybe" says that we only ask AbsBinds to make global constant methods
435 if the dfun_theta is empty.
436
437                 
438 For an instance declaration, say,
439
440         instance (C1 a, C2 b) => C (T a b) where
441                 ...
442
443 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
444 function whose type is
445
446         (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
447
448 Notice that we pass it the superclass dictionaries at the instance type; this
449 is the ``Mark Jones optimisation''.  The stuff before the "=>" here
450 is the @dfun_theta@ below.
451
452 First comes the easy case of a non-local instance decl.
453
454 \begin{code}
455 tcInstDecl2 :: InstInfo -> NF_TcM (LIE, TcMonoBinds)
456
457 tcInstDecl2 (InstInfo clas inst_tyvars inst_tys
458                       inst_decl_theta
459                       dfun_id monobinds
460                       locn uprags)
461   | not (isLocallyDefined dfun_id)
462   = returnNF_Tc (emptyLIE, EmptyMonoBinds)
463
464   | otherwise
465   =      -- Prime error recovery
466     recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds))  $
467     tcAddSrcLoc locn                                       $
468
469         -- Instantiate the instance decl with tc-style type variables
470     tcInstId dfun_id            `thenNF_Tc` \ (inst_tyvars', dfun_theta', dict_ty') ->
471     let
472         (clas, inst_tys') = expectJust "tcInstDecl2" (splitDictTy_maybe dict_ty')
473         origin            = InstanceDeclOrigin
474
475         (class_tyvars, sc_theta, _, op_items) = classBigSig clas
476
477         dm_ids    = [dm_id | (_, DefMeth dm_id) <- op_items]
478         sel_names = [idName sel_id | (sel_id, _) <- op_items]
479
480         -- Instantiate the theta found in the original instance decl
481         inst_decl_theta' = substTheta (mkTopTyVarSubst inst_tyvars (mkTyVarTys inst_tyvars'))
482                                       inst_decl_theta
483
484         -- Instantiate the super-class context with inst_tys
485         sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
486
487         -- Find any definitions in monobinds that aren't from the class
488         bad_bndrs = collectMonoBinders monobinds `minusList` sel_names
489     in
490          -- Check that all the method bindings come from this class
491     mapTc (addErrTc . badMethodErr clas) bad_bndrs              `thenNF_Tc_`
492
493          -- Create dictionary Ids from the specified instance contexts.
494     newClassDicts origin sc_theta'              `thenNF_Tc` \ (sc_dicts,        sc_dict_ids) ->
495     newDicts origin dfun_theta'                 `thenNF_Tc` \ (dfun_arg_dicts,  dfun_arg_dicts_ids)  ->
496     newDicts origin inst_decl_theta'            `thenNF_Tc` \ (inst_decl_dicts, _) ->
497     newClassDicts origin [(clas,inst_tys')]     `thenNF_Tc` \ (this_dict,       [this_dict_id]) ->
498
499     tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
500         tcExtendGlobalValEnv dm_ids (
501                 -- Default-method Ids may be mentioned in synthesised RHSs 
502
503         mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
504                                      inst_decl_theta'
505                                      monobinds uprags True)
506                        op_items
507     ))                  `thenTc` \ (method_binds_s, insts_needed_s, meth_lies_w_ids) ->
508
509         -- Deal with SPECIALISE instance pragmas by making them
510         -- look like SPECIALISE pragmas for the dfun
511     let
512         dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
513     in
514     tcExtendGlobalValEnv [dfun_id] (
515         tcSpecSigs dfun_prags
516     )                                   `thenTc` \ (prag_binds, prag_lie) ->
517
518         -- Check the overloading constraints of the methods and superclasses
519
520         -- tcMethodBind has checked that the class_tyvars havn't
521         -- been unified with each other or another type, but we must
522         -- still zonk them before passing them to tcSimplifyAndCheck
523     zonkTcSigTyVars inst_tyvars'        `thenNF_Tc` \ zonked_inst_tyvars ->
524     let
525         inst_tyvars_set = mkVarSet zonked_inst_tyvars
526
527         (meth_lies, meth_ids) = unzip meth_lies_w_ids
528
529                  -- These insts are in scope; quite a few, eh?
530         avail_insts = this_dict                 `plusLIE` 
531                       dfun_arg_dicts            `plusLIE`
532                       sc_dicts                  `plusLIE`
533                       unionManyBags meth_lies
534
535         methods_lie = plusLIEs insts_needed_s
536     in
537
538         -- Ditto method bindings
539     tcAddErrCtxt methodCtxt (
540       tcSimplifyAndCheck
541                  (ptext SLIT("instance declaration context"))
542                  inst_tyvars_set                        -- Local tyvars
543                  avail_insts
544                  methods_lie
545     )                                            `thenTc` \ (const_lie1, lie_binds1) ->
546     
547         -- Check that we *could* construct the superclass dictionaries,
548         -- even though we are *actually* going to pass the superclass dicts in;
549         -- the check ensures that the caller will never have 
550         --a problem building them.
551     tcAddErrCtxt superClassCtxt (
552       tcSimplifyAndCheck
553                  (ptext SLIT("instance declaration context"))
554                  inst_tyvars_set                -- Local tyvars
555                  inst_decl_dicts                -- The instance dictionaries available
556                  sc_dicts                       -- The superclass dicationaries reqd
557     )                                   `thenTc` \ _ -> 
558                                                 -- Ignore the result; we're only doing
559                                                 -- this to make sure it can be done.
560
561         -- Now do the simplification again, this time to get the
562         -- bindings; this time we use an enhanced "avails"
563         -- Ignore errors because they come from the *previous* tcSimplify
564     discardErrsTc (
565         tcSimplifyAndCheck
566                  (ptext SLIT("instance declaration context"))
567                  inst_tyvars_set
568                  dfun_arg_dicts         -- NB! Don't include this_dict here, else the sc_dicts
569                                         -- get bound by just selecting from this_dict!!
570                  sc_dicts
571     )                                            `thenTc` \ (const_lie2, lie_binds2) ->
572         
573
574         -- Create the result bindings
575     let
576         dict_constr   = classDataCon clas
577         scs_and_meths = sc_dict_ids ++ meth_ids
578
579         dict_rhs
580           | null scs_and_meths
581           =     -- Blatant special case for CCallable, CReturnable
582                 -- If the dictionary is empty then we should never
583                 -- select anything from it, so we make its RHS just
584                 -- emit an error message.  This in turn means that we don't
585                 -- mention the constructor, which doesn't exist for CCallable, CReturnable
586                 -- Hardly beautiful, but only three extra lines.
587             HsApp (TyApp (HsVar eRROR_ID) [(unUsgTy . idType) this_dict_id])
588                   (HsLit (HsString msg))
589
590           | otherwise   -- The common case
591           = mkHsConApp dict_constr inst_tys' (map HsVar (sc_dict_ids ++ meth_ids))
592                 -- We don't produce a binding for the dict_constr; instead we
593                 -- rely on the simplifier to unfold this saturated application
594                 -- We do this rather than generate an HsCon directly, because
595                 -- it means that the special cases (e.g. dictionary with only one
596                 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
597                 -- than needing to be repeated here.
598
599           where
600             msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
601
602         dict_bind    = VarMonoBind this_dict_id dict_rhs
603         method_binds = andMonoBindList method_binds_s
604
605         main_bind
606           = AbsBinds
607                  zonked_inst_tyvars
608                  dfun_arg_dicts_ids
609                  [(inst_tyvars', dfun_id, this_dict_id)] 
610                  emptyNameSet           -- No inlines (yet)
611                  (lie_binds1    `AndMonoBinds` 
612                   lie_binds2    `AndMonoBinds`
613                   method_binds  `AndMonoBinds`
614                   dict_bind)
615     in
616     returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
617               main_bind `AndMonoBinds` prag_binds)
618 \end{code}
619
620
621 %************************************************************************
622 %*                                                                      *
623 \subsection{Checking for a decent instance type}
624 %*                                                                      *
625 %************************************************************************
626
627 @scrutiniseInstanceHead@ checks the type {\em and} its syntactic constraints:
628 it must normally look like: @instance Foo (Tycon a b c ...) ...@
629
630 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
631 flag is on, or (2)~the instance is imported (they must have been
632 compiled elsewhere). In these cases, we let them go through anyway.
633
634 We can also have instances for functions: @instance Foo (a -> b) ...@.
635
636 \begin{code}
637 scrutiniseInstanceConstraint pred
638   | opt_AllowUndecidableInstances
639   = returnNF_Tc ()
640
641   | Just (clas,tys) <- getClassTys_maybe pred,
642     all isTyVarTy tys
643   = returnNF_Tc ()
644
645   | otherwise
646   = addErrTc (instConstraintErr pred)
647
648 scrutiniseInstanceHead clas inst_taus
649   |     -- CCALL CHECK
650         -- A user declaration of a CCallable/CReturnable instance
651         -- must be for a "boxed primitive" type.
652     (clas `hasKey` cCallableClassKey   && not (ccallable_type   first_inst_tau)) ||
653     (clas `hasKey` cReturnableClassKey && not (creturnable_type first_inst_tau))
654   = addErrTc (nonBoxedPrimCCallErr clas first_inst_tau)
655
656         -- DERIVING CHECK
657         -- It is obviously illegal to have an explicit instance
658         -- for something that we are also planning to `derive'
659   | maybeToBool alg_tycon_app_maybe && clas `elem` (tyConDerivings alg_tycon)
660   = addErrTc (derivingWhenInstanceExistsErr clas first_inst_tau)
661            -- Kind check will have ensured inst_taus is of length 1
662
663         -- Allow anything for AllowUndecidableInstances
664   | opt_AllowUndecidableInstances
665   = returnNF_Tc ()
666
667         -- If GlasgowExts then check at least one isn't a type variable
668   | opt_GlasgowExts 
669   = if all isTyVarTy inst_taus then
670         addErrTc (instTypeErr clas inst_taus (text "There must be at least one non-type-variable in the instance head"))
671     else
672         returnNF_Tc ()
673
674         -- WITH HASKELL 1.4, MUST HAVE C (T a b c)
675   |  not (length inst_taus == 1 &&
676           maybeToBool maybe_tycon_app &&        -- Yes, there's a type constuctor
677           not (isSynTyCon tycon) &&             -- ...but not a synonym
678           all isTyVarTy arg_tys &&              -- Applied to type variables
679           length (varSetElems (tyVarsOfTypes arg_tys)) == length arg_tys
680                  -- This last condition checks that all the type variables are distinct
681      )
682   = addErrTc (instTypeErr clas inst_taus
683                         (text "the instance type must be of form (T a b c)" $$
684                          text "where T is not a synonym, and a,b,c are distinct type variables")
685     )
686
687   | otherwise
688   = returnNF_Tc ()
689
690   where
691     (first_inst_tau : _)       = inst_taus
692
693         -- Stuff for algebraic or -> type
694     maybe_tycon_app       = splitTyConApp_maybe first_inst_tau
695     Just (tycon, arg_tys) = maybe_tycon_app
696
697         -- Stuff for an *algebraic* data type
698     alg_tycon_app_maybe    = splitAlgTyConApp_maybe first_inst_tau
699                                 -- The "Alg" part looks through synonyms
700     Just (alg_tycon, _, _) = alg_tycon_app_maybe
701  
702 ccallable_type   ty = isFFIArgumentTy False {- Not safe call -} ty
703 creturnable_type ty = isFFIResultTy ty
704 \end{code}
705
706
707 %************************************************************************
708 %*                                                                      *
709 \subsection{Error messages}
710 %*                                                                      *
711 %************************************************************************
712
713 \begin{code}
714 tcAddDeclCtxt decl thing_inside
715   = tcAddSrcLoc loc     $
716     tcAddErrCtxt ctxt   $
717     thing_inside
718   where
719      (name, loc, thing)
720         = case decl of
721             (ClassDecl _ name _ _ _ _ _ _ loc)         -> (name, loc, "class")
722             (TySynonym name _ _ loc)                   -> (name, loc, "type synonym")
723             (TyData NewType  _ name _ _ _ _ _ loc _ _) -> (name, loc, "newtype")
724             (TyData DataType _ name _ _ _ _ _ loc _ _) -> (name, loc, "data type")
725
726      ctxt = hsep [ptext SLIT("In the"), text thing, 
727                   ptext SLIT("declaration for"), quotes (ppr name)]
728 \end{code}
729
730 \begin{code}
731 instConstraintErr pred
732   = hang (ptext SLIT("Illegal constraint") <+> 
733           quotes (pprPred pred) <+> 
734           ptext SLIT("in instance context"))
735          4 (ptext SLIT("(Instance contexts must constrain only type variables)"))
736         
737 badGenericInstanceType binds
738   = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
739           nest 4 (ppr binds)]
740
741 missingGenericInstances missing
742   = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
743           
744
745
746 dupGenericInsts inst_infos
747   = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
748           nest 4 (vcat (map (ppr . simpleInstInfoTy) inst_infos)),
749           ptext SLIT("All the type patterns for a generic type constructor must be identical")
750     ]
751
752 instTypeErr clas tys msg
753   = sep [ptext SLIT("Illegal instance declaration for") <+> quotes (pprConstraint clas tys),
754          nest 4 (parens msg)
755     ]
756
757 derivingWhenInstanceExistsErr clas tycon
758   = hang (hsep [ptext SLIT("Deriving class"), 
759                        quotes (ppr clas), 
760                        ptext SLIT("type"), quotes (ppr tycon)])
761          4 (ptext SLIT("when an explicit instance exists"))
762
763 nonBoxedPrimCCallErr clas inst_ty
764   = hang (ptext SLIT("Unacceptable instance type for ccall-ish class"))
765          4 (hsep [ ptext SLIT("class"), ppr clas, ptext SLIT("type"),
766                         ppr inst_ty])
767
768 methodCtxt     = ptext SLIT("When checking the methods of an instance declaration")
769 superClassCtxt = ptext SLIT("When checking the superclasses of an instance declaration")
770 \end{code}