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