2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[TcInstDecls]{Typechecking instance declarations}
7 #include "HsVersions.h"
19 import HsSyn ( InstDecl(..), FixityDecl, Sig(..),
20 SpecInstSig(..), HsBinds(..), Bind(..),
21 MonoBinds(..), GRHSsAndBinds, Match,
22 InPat(..), OutPat(..), HsExpr(..), HsLit(..),
23 Stmt, Qualifier, ArithSeqInfo, Fake,
24 PolyType(..), MonoType )
25 import RnHsSyn ( RenamedHsBinds(..), RenamedMonoBinds(..),
26 RenamedInstDecl(..), RenamedFixityDecl(..),
27 RenamedSig(..), RenamedSpecInstSig(..),
28 RnName(..){-incl instance Outputable-}
30 import TcHsSyn ( TcIdOcc(..), TcHsBinds(..),
31 TcMonoBinds(..), TcExpr(..), tcIdType,
33 mkHsDictLam, mkHsDictApp )
36 import TcMonad hiding ( rnMtoTcM )
37 import GenSpecEtc ( checkSigTyVarsGivenGlobals )
38 import Inst ( Inst, InstOrigin(..), InstanceMapper(..),
39 newDicts, newMethod, LIE(..), emptyLIE, plusLIE )
40 import TcBinds ( tcPragmaSigs )
41 import TcDeriv ( tcDeriving )
42 import TcEnv ( tcLookupClass, tcTyVarScope, newLocalId )
43 import TcGRHSs ( tcGRHSsAndBinds )
44 import TcInstUtil ( InstInfo(..), mkInstanceRelatedIds, buildInstanceEnvs )
45 import TcKind ( TcKind, unifyKind )
46 import TcMatches ( tcMatchesFun )
47 import TcMonoType ( tcContext, tcMonoTypeKind )
48 import TcSimplify ( tcSimplifyAndCheck )
49 import TcType ( TcType(..), TcTyVar(..),
50 tcInstSigTyVars, tcInstType, tcInstTheta, tcInstTcType
52 import Unify ( unifyTauTy, unifyTauTyLists )
55 import Bag ( emptyBag, unitBag, unionBags, unionManyBags,
56 concatBag, foldBag, bagToList )
57 import CmdLineOpts ( opt_GlasgowExts,
58 opt_OmitDefaultInstanceMethods,
59 opt_SpecialiseOverloaded
61 import Class ( GenClass, GenClassOp,
62 isCcallishClass, classBigSig,
63 classOps, classOpLocalType,
66 import Id ( GenId, idType, isDefaultMethodId_maybe )
67 import ListSetOps ( minusList )
68 import Maybes ( maybeToBool, expectJust )
69 import Name ( getLocalName, origName, nameOf, Name{--O only-} )
70 import PrelVals ( nO_EXPLICIT_METHOD_ERROR_ID )
71 import PrelMods ( pRELUDE )
72 import PprType ( GenType, GenTyVar, GenClass, GenClassOp, TyCon,
77 import RnUtils ( RnEnv(..) )
78 import TyCon ( isSynTyCon, derivedFor )
79 import Type ( GenType(..), ThetaType(..), mkTyVarTys,
80 splitSigmaTy, splitAppTy, isTyVarTy, matchTy, mkSigmaTy,
81 getTyCon_maybe, maybeBoxedPrimType, splitRhoTy
83 import TyVar ( GenTyVar, mkTyVarSet, unionTyVarSets )
84 import TysWiredIn ( stringTy )
85 import Unique ( Unique )
86 import Util ( zipEqual, panic )
89 Typechecking instance declarations is done in two passes. The first
90 pass, made by @tcInstDecls1@, collects information to be used in the
93 This pre-processed info includes the as-yet-unprocessed bindings
94 inside the instance declaration. These are type-checked in the second
95 pass, when the class-instance envs and GVE contain all the info from
96 all the instance and value decls. Indeed that's the reason we need
97 two passes over the instance decls.
100 Here is the overall algorithm.
101 Assume that we have an instance declaration
103 instance c => k (t tvs) where b
107 $LIE_c$ is the LIE for the context of class $c$
109 $betas_bar$ is the free variables in the class method type, excluding the
112 $LIE_cop$ is the LIE constraining a particular class method
114 $tau_cop$ is the tau type of a class method
116 $LIE_i$ is the LIE for the context of instance $i$
118 $X$ is the instance constructor tycon
120 $gammas_bar$ is the set of type variables of the instance
122 $LIE_iop$ is the LIE for a particular class method instance
124 $tau_iop$ is the tau type for this instance of a class method
126 $alpha$ is the class variable
128 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
130 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
133 ToDo: Update the list above with names actually in the code.
137 First, make the LIEs for the class and instance contexts, which means
138 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
139 and make LIElistI and LIEI.
141 Then process each method in turn.
143 order the instance methods according to the ordering of the class methods
145 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
147 Create final dictionary function from bindings generated already
149 df = lambda inst_tyvars
156 in <op1,op2,...,opn,sd1,...,sdm>
158 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
159 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
163 tcInstDecls1 :: Bag RenamedInstDecl
164 -> [RenamedSpecInstSig]
165 -> Module -- module name for deriving
166 -> RnEnv -- for renaming derivings
167 -> [RenamedFixityDecl] -- fixities for deriving
168 -> TcM s (Bag InstInfo,
172 tcInstDecls1 inst_decls specinst_sigs mod_name rn_env fixities
173 = -- Do the ordinary instance declarations
174 mapBagNF_Tc (tcInstDecl1 mod_name) inst_decls
175 `thenNF_Tc` \ inst_info_bags ->
177 decl_inst_info = concatBag inst_info_bags
179 -- Handle "derived" instances; note that we only do derivings
180 -- for things in this module; we ignore deriving decls from
181 -- interfaces! We pass fixities, because they may be used
182 -- in deriving Read and Show.
183 tcDeriving mod_name rn_env decl_inst_info fixities
184 `thenTc` \ (deriv_inst_info, deriv_binds, ddump_deriv) ->
187 inst_info = deriv_inst_info `unionBags` decl_inst_info
190 -- Handle specialise instance pragmas
191 tcSpecInstSigs inst_info specinst_sigs
192 `thenTc` \ spec_inst_info ->
195 spec_inst_info = emptyBag -- For now
197 full_inst_info = inst_info `unionBags` spec_inst_info
199 returnTc (full_inst_info, deriv_binds, ddump_deriv)
202 tcInstDecl1 :: FAST_STRING -> RenamedInstDecl -> NF_TcM s (Bag InstInfo)
206 poly_ty@(HsForAllTy tyvar_names context inst_ty)
208 from_here inst_mod uprags pragmas src_loc)
209 = -- Prime error recovery, set source location
210 recoverNF_Tc (returnNF_Tc emptyBag) $
211 tcAddSrcLoc src_loc $
214 tcLookupClass class_name `thenNF_Tc` \ (clas_kind, clas) ->
219 -- Typecheck the context and instance type
220 tcTyVarScope (map de_rn tyvar_names) (\ tyvars ->
221 tcContext context `thenTc` \ theta ->
222 tcMonoTypeKind inst_ty `thenTc` \ (tau_kind, tau) ->
223 unifyKind clas_kind tau_kind `thenTc_`
224 returnTc (tyvars, theta, tau)
225 ) `thenTc` \ (inst_tyvars, inst_theta, inst_tau) ->
227 -- Check for respectable instance type
228 scrutiniseInstanceType from_here clas inst_tau
229 `thenTc` \ (inst_tycon,arg_tys) ->
231 -- Deal with the case where we are deriving
232 -- and importing the same instance
233 if (not from_here && (clas `derivedFor` inst_tycon)
234 && all isTyVarTy arg_tys)
236 if mod_name == inst_mod
238 -- Imported instance came from this module;
239 -- discard and derive fresh instance
242 -- Imported instance declared in another module;
243 -- report duplicate instance error
244 failTc (derivingWhenInstanceImportedErr inst_mod clas inst_tycon)
247 -- Make the dfun id and constant-method ids
248 mkInstanceRelatedIds from_here src_loc inst_mod pragmas
249 clas inst_tyvars inst_tau inst_theta uprags
250 `thenTc` \ (dfun_id, dfun_theta, const_meth_ids) ->
252 returnTc (unitBag (InstInfo clas inst_tyvars inst_tau inst_theta
253 dfun_theta dfun_id const_meth_ids
254 binds from_here inst_mod src_loc uprags))
258 %************************************************************************
260 \subsection{Type-checking instance declarations, pass 2}
262 %************************************************************************
265 tcInstDecls2 :: Bag InstInfo
266 -> NF_TcM s (LIE s, TcHsBinds s)
268 tcInstDecls2 inst_decls
269 = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyBinds)) inst_decls
271 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
272 tc2 `thenNF_Tc` \ (lie2, binds2) ->
273 returnNF_Tc (lie1 `plusLIE` lie2,
274 binds1 `ThenBinds` binds2)
278 ======= New documentation starts here (Sept 92) ==============
280 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
281 the dictionary function for this instance declaration. For example
283 instance Foo a => Foo [a] where
287 might generate something like
289 dfun.Foo.List dFoo_a = let op1 x = ...
295 HOWEVER, if the instance decl has no context, then it returns a
296 bigger @HsBinds@ with declarations for each method. For example
298 instance Foo [a] where
304 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
305 const.Foo.op1.List a x = ...
306 const.Foo.op2.List a y = ...
308 This group may be mutually recursive, because (for example) there may
309 be no method supplied for op2 in which case we'll get
311 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
313 that is, the default method applied to the dictionary at this type.
315 What we actually produce in either case is:
317 AbsBinds [a] [dfun_theta_dicts]
318 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
319 { d = (sd1,sd2, ..., op1, op2, ...)
324 The "maybe" says that we only ask AbsBinds to make global constant methods
325 if the dfun_theta is empty.
328 For an instance declaration, say,
330 instance (C1 a, C2 b) => C (T a b) where
333 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
334 function whose type is
336 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
338 Notice that we pass it the superclass dictionaries at the instance type; this
339 is the ``Mark Jones optimisation''. The stuff before the "=>" here
340 is the @dfun_theta@ below.
342 First comes the easy case of a non-local instance decl.
345 tcInstDecl2 :: InstInfo
346 -> NF_TcM s (LIE s, TcHsBinds s)
348 tcInstDecl2 (InstInfo _ _ _ _ _ _ _ _ False{-import-} _ _ _)
349 = returnNF_Tc (emptyLIE, EmptyBinds)
351 tcInstDecl2 (InstInfo clas inst_tyvars inst_ty
352 inst_decl_theta dfun_theta
353 dfun_id const_meth_ids monobinds
354 True{-here-} inst_mod locn uprags)
355 = -- Prime error recovery
356 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyBinds)) $
359 -- Get the class signature
360 tcInstSigTyVars inst_tyvars `thenNF_Tc` \ (inst_tyvars', _, tenv) ->
363 super_classes, sc_sel_ids,
364 class_ops, op_sel_ids, defm_ids) = classBigSig clas
366 tcInstType tenv inst_ty `thenNF_Tc` \ inst_ty' ->
367 tcInstTheta tenv dfun_theta `thenNF_Tc` \ dfun_theta' ->
368 tcInstTheta tenv inst_decl_theta `thenNF_Tc` \ inst_decl_theta' ->
370 sc_theta' = super_classes `zip` repeat inst_ty'
371 origin = InstanceDeclOrigin
372 mk_method sel_id = newMethodId sel_id inst_ty' origin
374 -- Create dictionary Ids from the specified instance contexts.
375 newDicts origin sc_theta' `thenNF_Tc` \ (sc_dicts, sc_dict_ids) ->
376 newDicts origin dfun_theta' `thenNF_Tc` \ (dfun_arg_dicts, dfun_arg_dicts_ids) ->
377 newDicts origin inst_decl_theta' `thenNF_Tc` \ (inst_decl_dicts, _) ->
378 newDicts origin [(clas,inst_ty')] `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
380 -- Create method variables
381 mapAndUnzipNF_Tc mk_method op_sel_ids `thenNF_Tc` \ (meth_insts_s, meth_ids) ->
383 -- Collect available Insts
385 avail_insts -- These insts are in scope; quite a few, eh?
386 = unionManyBags (this_dict : dfun_arg_dicts : meth_insts_s)
389 = if opt_OmitDefaultInstanceMethods then
390 makeInstanceDeclNoDefaultExpr origin meth_ids defm_ids inst_ty' clas inst_mod
392 makeInstanceDeclDefaultMethodExpr origin meth_ids defm_ids inst_ty' this_dict_id
394 processInstBinds clas mk_method_expr inst_tyvars' avail_insts meth_ids monobinds
395 `thenTc` \ (insts_needed, method_mbinds) ->
397 -- Create the dict and method binds
399 = VarMonoBind this_dict_id (Dictionary sc_dict_ids meth_ids)
401 dict_and_method_binds
402 = dict_bind `AndMonoBinds` method_mbinds
404 inst_tyvars_set' = mkTyVarSet inst_tyvars'
406 -- Check the overloading constraints of the methods and superclasses
407 tcAddErrCtxt (bindSigCtxt meth_ids) (
409 inst_tyvars_set' -- Local tyvars
411 (sc_dicts `unionBags` insts_needed) -- Need to get defns for all these
412 ) `thenTc` \ (const_lie, super_binds) ->
414 -- Check that we *could* construct the superclass dictionaries,
415 -- even though we are *actually* going to pass the superclass dicts in;
416 -- the check ensures that the caller will never have a problem building
418 tcAddErrCtxt superClassSigCtxt (
420 inst_tyvars_set' -- Local tyvars
421 inst_decl_dicts -- The instance dictionaries available
422 sc_dicts -- The superclass dicationaries reqd
424 -- Ignore the result; we're only doing
425 -- this to make sure it can be done.
427 -- Now process any SPECIALIZE pragmas for the methods
429 spec_sigs = [ s | s@(SpecSig _ _ _ _) <- uprags ]
431 tcPragmaSigs spec_sigs `thenTc` \ (_, spec_binds, spec_lie) ->
433 -- Complete the binding group, adding any spec_binds
438 ((this_dict_id, RealId dfun_id)
439 : (meth_ids `zip` map RealId const_meth_ids))
440 -- NB: const_meth_ids will often be empty
442 (RecBind dict_and_method_binds)
448 returnTc (const_lie `plusLIE` spec_lie, inst_binds)
451 ============= OLD ================
453 @mkMethodId@ manufactures an id for a local method.
454 It's rather turgid stuff, because there are two cases:
456 (a) For methods with no local polymorphism, we can make an Inst of the
457 class-op selector function and a corresp InstId;
458 which is good because then other methods which call
459 this one will do so directly.
461 (b) For methods with local polymorphism, we can't do this. For example,
464 op :: (Num b) => a -> b -> a
466 Here the type of the class-op-selector is
468 forall a b. (Foo a, Num b) => a -> b -> a
470 The locally defined method at (say) type Float will have type
472 forall b. (Num b) => Float -> b -> Float
474 and the one is not an instance of the other.
476 So for these we just make a local (non-Inst) id with a suitable type.
479 =============== END OF OLD ===================
482 newMethodId sel_id inst_ty origin
483 = newMethod origin (RealId sel_id) [inst_ty]
486 {- REMOVE SOON: (this was pre-split-poly selector types)
487 let (sel_tyvars,sel_theta,sel_tau) = splitSigmaTy (idType sel_id)
488 (_:meth_theta) = sel_theta -- The local theta is all except the
489 -- first element of the context
492 -- Ah! a selector for a class op with no local polymorphism
493 -- Build an Inst for this
494 [clas_tyvar] -> newMethod origin (RealId sel_id) [inst_ty]
496 -- Ho! a selector for a class op with local polymorphism.
497 -- Just make a suitably typed local id for this
498 (clas_tyvar:local_tyvars) ->
499 tcInstType [(clas_tyvar,inst_ty)]
500 (mkSigmaTy local_tyvars meth_theta sel_tau)
501 `thenNF_Tc` \ method_ty ->
502 newLocalId (getLocalName sel_id) method_ty `thenNF_Tc` \ meth_id ->
503 returnNF_Tc (emptyLIE, meth_id)
507 The next function makes a default method which calls the global default method, at
508 the appropriate instance type.
510 See the notes under default decls in TcClassDcl.lhs.
513 makeInstanceDeclDefaultMethodExpr
520 -> NF_TcM s (TcExpr s)
522 makeInstanceDeclDefaultMethodExpr origin meth_ids defm_ids inst_ty this_dict tag
524 -- def_op_id = defm_id inst_ty this_dict
525 returnNF_Tc (mkHsDictApp (mkHsTyApp (HsVar (RealId defm_id)) [inst_ty]) [this_dict])
528 meth_id = meth_ids !! idx
529 defm_id = defm_ids !! idx
531 makeInstanceDeclNoDefaultExpr
539 -> NF_TcM s (TcExpr s)
541 makeInstanceDeclNoDefaultExpr origin meth_ids defm_ids inst_ty clas inst_mod tag
543 -- Produce a warning if the default instance method
544 -- has been omitted when one exists in the class
545 warnTc (not err_defm_ok)
546 (omitDefaultMethodWarn clas_op clas_name inst_ty)
548 returnNF_Tc (HsApp (mkHsTyApp (HsVar (RealId nO_EXPLICIT_METHOD_ERROR_ID)) [tcIdType meth_id])
549 (HsLitOut (HsString (_PK_ error_msg)) stringTy))
552 meth_id = meth_ids !! idx
553 clas_op = (classOps clas) !! idx
554 defm_id = defm_ids !! idx
556 Just (_, _, err_defm_ok) = isDefaultMethodId_maybe defm_id
558 error_msg = _UNPK_ inst_mod ++ "." ++ _UNPK_ clas_name ++ "."
559 ++ (ppShow 80 (ppr PprForUser inst_ty)) ++ "."
560 ++ (ppShow 80 (ppr PprForUser clas_op)) ++ "\""
562 clas_name = nameOf (origName "makeInstanceDeclNoDefaultExpr" clas)
566 %************************************************************************
568 \subsection{Processing each method}
570 %************************************************************************
572 @processInstBinds@ returns a @MonoBinds@ which binds
573 all the method ids (which are passed in). It is used
574 - both for instance decls,
575 - and to compile the default-method declarations in a class decl.
577 Any method ids which don't have a binding have a suitable default
578 binding created for them. The actual right-hand side used is
579 created using a function which is passed in, because the right thing to
580 do differs between instance and class decls.
585 -> (Int -> NF_TcM s (TcExpr s)) -- Function to make default method
586 -> [TcTyVar s] -- Tyvars for this instance decl
587 -> LIE s -- available Insts
588 -> [TcIdOcc s] -- Local method ids in tag order
589 -- (instance tyvars are free in their types)
591 -> TcM s (LIE s, -- These are required
594 processInstBinds clas mk_default_method_rhs inst_tyvars avail_insts method_ids monobinds
596 -- Process the explicitly-given method bindings
597 processInstBinds1 clas inst_tyvars avail_insts method_ids monobinds
598 `thenTc` \ (tags, insts_needed_in_methods, method_binds) ->
600 -- Find the methods not handled, and make default method bindings for them.
602 unmentioned_tags = [1.. length method_ids] `minusList` tags
604 mapNF_Tc mk_default_method unmentioned_tags
605 `thenNF_Tc` \ default_bind_list ->
607 returnTc (insts_needed_in_methods,
608 foldr AndMonoBinds method_binds default_bind_list)
610 -- From a tag construct us the passed-in function to construct
611 -- the binding for the default method
612 mk_default_method tag = mk_default_method_rhs tag `thenNF_Tc` \ rhs ->
613 returnNF_Tc (VarMonoBind (method_ids !! (tag-1)) rhs)
619 -> [TcTyVar s] -- Tyvars for this instance decl
620 -> LIE s -- available Insts
621 -> [TcIdOcc s] -- Local method ids in tag order (instance tyvars are free),
623 -> TcM s ([Int], -- Class-op tags accounted for
624 LIE s, -- These are required
627 processInstBinds1 clas inst_tyvars avail_insts method_ids EmptyMonoBinds
628 = returnTc ([], emptyLIE, EmptyMonoBinds)
630 processInstBinds1 clas inst_tyvars avail_insts method_ids (AndMonoBinds mb1 mb2)
631 = processInstBinds1 clas inst_tyvars avail_insts method_ids mb1
632 `thenTc` \ (op_tags1,dicts1,method_binds1) ->
633 processInstBinds1 clas inst_tyvars avail_insts method_ids mb2
634 `thenTc` \ (op_tags2,dicts2,method_binds2) ->
635 returnTc (op_tags1 ++ op_tags2,
636 dicts1 `unionBags` dicts2,
637 AndMonoBinds method_binds1 method_binds2)
641 processInstBinds1 clas inst_tyvars avail_insts method_ids mbind
643 -- Find what class op is being defined here. The complication is
644 -- that we could have a PatMonoBind or a FunMonoBind. If the
645 -- former, it should only bind a single variable, or else we're in
646 -- trouble (I'm not sure what the static semantics of methods
647 -- defined in a pattern binding with multiple patterns is!)
648 -- Renamer has reduced us to these two cases.
650 (op,locn) = case mbind of
651 FunMonoBind op _ _ locn -> (op, locn)
652 PatMonoBind (VarPatIn op) _ locn -> (op, locn)
654 occ = getLocalName op
655 origin = InstanceDeclOrigin
659 -- Make a method id for the method
661 tag = classOpTagByString clas occ
662 method_id = method_ids !! (tag-1)
663 method_ty = tcIdType method_id
666 tcInstTcType method_ty `thenNF_Tc` \ (method_tyvars, method_rho) ->
668 (method_theta, method_tau) = splitRhoTy method_rho
670 newDicts origin method_theta `thenNF_Tc` \ (method_dicts,method_dict_ids) ->
672 case (method_tyvars, method_dict_ids) of
674 ([],[]) -> -- The simple case; no local polymorphism or overloading in the method
676 -- Type check the method itself
677 tcMethodBind method_id method_tau mbind `thenTc` \ (mbind', lieIop) ->
678 returnTc ([tag], lieIop, mbind')
680 other -> -- It's a locally-polymorphic and/or overloaded method; UGH!
682 -- Make a new id for (a) the local, non-overloaded method
683 -- and (b) the locally-overloaded method
684 -- The latter is needed just so we can return an AbsBinds wrapped
685 -- up inside a MonoBinds.
688 -- Make the method_tyvars into signature tyvars so they
689 -- won't get unified with anything.
690 tcInstSigTyVars method_tyvars `thenNF_Tc` \ (sig_tyvars, sig_tyvar_tys, _) ->
691 unifyTauTyLists (mkTyVarTys method_tyvars) sig_tyvar_tys `thenTc_`
693 newLocalId occ method_tau `thenNF_Tc` \ local_id ->
694 newLocalId occ method_ty `thenNF_Tc` \ copy_id ->
696 inst_tyvar_set = mkTyVarSet inst_tyvars
697 inst_method_tyvar_set = inst_tyvar_set `unionTyVarSets` (mkTyVarSet sig_tyvars)
699 -- Typecheck the method
700 tcMethodBind local_id method_tau mbind `thenTc` \ (mbind', lieIop) ->
702 -- Check the overloading part of the signature.
703 -- Simplify everything fully, even though some
704 -- constraints could "really" be left to the next
705 -- level out. The case which forces this is
707 -- class Foo a where { op :: Bar a => a -> a }
709 -- Here we must simplify constraints on "a" to catch all
710 -- the Bar-ish things.
711 tcAddErrCtxt (methodSigCtxt op method_ty) (
712 checkSigTyVarsGivenGlobals
714 sig_tyvars method_tau `thenTc_`
717 inst_method_tyvar_set
718 (method_dicts `plusLIE` avail_insts)
720 ) `thenTc` \ (f_dicts, dict_binds) ->
725 VarMonoBind method_id
730 [(local_id, copy_id)]
737 tcMethodBind :: TcIdOcc s -> TcType s -> RenamedMonoBinds
738 -> TcM s (TcMonoBinds s, LIE s)
740 tcMethodBind meth_id meth_ty (FunMonoBind name inf matches locn)
741 = tcMatchesFun name meth_ty matches `thenTc` \ (rhs', lie) ->
742 returnTc (FunMonoBind meth_id inf rhs' locn, lie)
744 tcMethodBind meth_id meth_ty pbind@(PatMonoBind pat grhss_and_binds locn)
745 -- pat is sure to be a (VarPatIn op)
746 = tcAddErrCtxt (patMonoBindsCtxt pbind) $
747 tcGRHSsAndBinds grhss_and_binds `thenTc` \ (grhss_and_binds', lie, rhs_ty) ->
748 unifyTauTy meth_ty rhs_ty `thenTc_`
749 returnTc (PatMonoBind (VarPat meth_id) grhss_and_binds' locn, lie)
753 %************************************************************************
755 \subsection{Type-checking specialise instance pragmas}
757 %************************************************************************
761 tcSpecInstSigs :: E -> CE -> TCE
762 -> Bag InstInfo -- inst decls seen (declared and derived)
763 -> [RenamedSpecInstSig] -- specialise instance upragmas
764 -> TcM (Bag InstInfo) -- new, overlapped, inst decls
766 tcSpecInstSigs e ce tce inst_infos []
769 tcSpecInstSigs e ce tce inst_infos sigs
770 = buildInstanceEnvs inst_infos `thenTc` \ inst_mapper ->
771 tc_inst_spec_sigs inst_mapper sigs `thenNF_Tc` \ spec_inst_infos ->
772 returnTc spec_inst_infos
774 tc_inst_spec_sigs inst_mapper []
775 = returnNF_Tc emptyBag
776 tc_inst_spec_sigs inst_mapper (sig:sigs)
777 = tcSpecInstSig e ce tce inst_infos inst_mapper sig `thenNF_Tc` \ info_sig ->
778 tc_inst_spec_sigs inst_mapper sigs `thenNF_Tc` \ info_sigs ->
779 returnNF_Tc (info_sig `unionBags` info_sigs)
781 tcSpecInstSig :: E -> CE -> TCE
784 -> RenamedSpecInstSig
785 -> NF_TcM (Bag InstInfo)
787 tcSpecInstSig e ce tce inst_infos inst_mapper (SpecInstSig class_name ty src_loc)
788 = recoverTc emptyBag (
789 tcAddSrcLoc src_loc (
791 clas = lookupCE ce class_name -- Renamer ensures this can't fail
793 -- Make some new type variables, named as in the specialised instance type
794 ty_names = extractMonoTyNames ???is_tyvarish_name??? ty
795 (tmpl_e,inst_tmpls,inst_tmpl_tys) = mkTVE ty_names
797 babyTcMtoTcM (tcInstanceType ce tce tmpl_e True src_loc ty)
798 `thenTc` \ inst_ty ->
800 maybe_tycon = case maybeAppDataTyCon inst_ty of
801 Just (tc,_,_) -> Just tc
804 maybe_unspec_inst = lookup_unspec_inst clas maybe_tycon inst_infos
806 -- Check that we have a local instance declaration to specialise
807 checkMaybeTc maybe_unspec_inst
808 (specInstUnspecInstNotFoundErr clas inst_ty src_loc) `thenTc_`
810 -- Create tvs to substitute for tmpls while simplifying the context
811 copyTyVars inst_tmpls `thenNF_Tc` \ (tv_e, inst_tvs, inst_tv_tys) ->
813 Just (InstInfo _ unspec_tyvars unspec_inst_ty unspec_theta
814 _ _ _ binds True{-from here-} mod _ uprag) = maybe_unspec_inst
816 subst = case matchTy unspec_inst_ty inst_ty of
818 Nothing -> panic "tcSpecInstSig:matchTy"
820 subst_theta = instantiateThetaTy subst unspec_theta
821 subst_tv_theta = instantiateThetaTy tv_e subst_theta
823 mk_spec_origin clas ty
824 = InstanceSpecOrigin inst_mapper clas ty src_loc
825 -- I'm VERY SUSPICIOUS ABOUT THIS
826 -- the inst-mapper is in a knot at this point so it's no good
827 -- looking at it in tcSimplify...
829 tcSimplifyThetas mk_spec_origin subst_tv_theta
830 `thenTc` \ simpl_tv_theta ->
832 simpl_theta = [ (clas, tv_to_tmpl tv) | (clas, tv) <- simpl_tv_theta ]
834 tv_tmpl_map = zipEqual "tcSpecInstSig" inst_tv_tys inst_tmpl_tys
835 tv_to_tmpl tv = assoc "tcSpecInstSig" tv_tmpl_map tv
837 mkInstanceRelatedIds e True{-from here-} src_loc mod NoInstancePragmas
838 clas inst_tmpls inst_ty simpl_theta uprag
839 `thenTc` \ (dfun_id, dfun_theta, const_meth_ids) ->
841 getSwitchCheckerTc `thenNF_Tc` \ sw_chkr ->
842 (if sw_chkr SpecialiseTrace then
843 pprTrace "Specialised Instance: "
844 (ppAboves [ppCat [if null simpl_theta then ppNil else ppr PprDebug simpl_theta,
845 if null simpl_theta then ppNil else ppStr "=>",
847 pprParendGenType PprDebug inst_ty],
848 ppCat [ppStr " derived from:",
849 if null unspec_theta then ppNil else ppr PprDebug unspec_theta,
850 if null unspec_theta then ppNil else ppStr "=>",
852 pprParendGenType PprDebug unspec_inst_ty]])
855 returnTc (unitBag (InstInfo clas inst_tmpls inst_ty simpl_theta
856 dfun_theta dfun_id const_meth_ids
857 binds True{-from here-} mod src_loc uprag))
861 lookup_unspec_inst clas maybe_tycon inst_infos
862 = case filter (match_info match_inst_ty) (bagToList inst_infos) of
864 (info:_) -> Just info
866 match_info match_ty (InstInfo inst_clas _ inst_ty _ _ _ _ _ from_here _ _ _)
867 = from_here && clas == inst_clas &&
868 match_ty inst_ty && is_plain_instance inst_ty
870 match_inst_ty = case maybe_tycon of
871 Just tycon -> match_tycon tycon
874 match_tycon tycon inst_ty = case (maybeAppDataTyCon inst_ty) of
875 Just (inst_tc,_,_) -> tycon == inst_tc
878 match_fun inst_ty = isFunType inst_ty
881 is_plain_instance inst_ty
882 = case (maybeAppDataTyCon inst_ty) of
883 Just (_,tys,_) -> all isTyVarTemplateTy tys
884 Nothing -> case maybeUnpackFunTy inst_ty of
885 Just (arg, res) -> isTyVarTemplateTy arg && isTyVarTemplateTy res
886 Nothing -> error "TcInstDecls:is_plain_instance"
891 Checking for a decent instance type
892 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
893 @scrutiniseInstanceType@ checks the type {\em and} its syntactic constraints:
894 it must normally look like: @instance Foo (Tycon a b c ...) ...@
896 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
897 flag is on, or (2)~the instance is imported (they must have been
898 compiled elsewhere). In these cases, we let them go through anyway.
900 We can also have instances for functions: @instance Foo (a -> b) ...@.
903 scrutiniseInstanceType from_here clas inst_tau
905 | not (maybeToBool inst_tycon_maybe) || isSynTyCon inst_tycon
906 = failTc (instTypeErr inst_tau)
908 -- IMPORTED INSTANCES ARE OK (but see tcInstDecl1)
910 = returnTc (inst_tycon,arg_tys)
913 | not (all isTyVarTy arg_tys ||
916 = failTc (instTypeErr inst_tau)
919 -- It is obviously illegal to have an explicit instance
920 -- for something that we are also planning to `derive'
921 -- Though we can have an explicit instance which is more
922 -- specific than the derived instance
923 | clas `derivedFor` inst_tycon
924 && all isTyVarTy arg_tys
925 = failTc (derivingWhenInstanceExistsErr clas inst_tycon)
928 -- A user declaration of a CCallable/CReturnable instance
929 -- must be for a "boxed primitive" type.
931 && not (maybeToBool (maybeBoxedPrimType inst_tau))
932 = failTc (nonBoxedPrimCCallErr clas inst_tau)
935 = returnTc (inst_tycon,arg_tys)
938 (possible_tycon, arg_tys) = splitAppTy inst_tau
939 inst_tycon_maybe = getTyCon_maybe possible_tycon
940 inst_tycon = expectJust "tcInstDecls1:inst_tycon" inst_tycon_maybe
947 SynTy tc _ _ -> ppBesides [ppStr "The type synonym `", ppr sty tc, rest_of_msg]
948 TyVarTy tv -> ppBesides [ppStr "The type variable `", ppr sty tv, rest_of_msg]
949 other -> ppBesides [ppStr "The type `", ppr sty ty, rest_of_msg]
951 rest_of_msg = ppStr "' cannot be used as an instance type."
953 derivingWhenInstanceExistsErr clas tycon sty
954 = ppHang (ppBesides [ppStr "Deriving class `", ppr sty clas, ppStr "' type `", ppr sty tycon, ppStr "'"])
955 4 (ppStr "when an explicit instance exists")
957 derivingWhenInstanceImportedErr inst_mod clas tycon sty
958 = ppHang (ppBesides [ppStr "Deriving class `", ppr sty clas, ppStr "' type `", ppr sty tycon, ppStr "'"])
959 4 (ppBesides [ppStr "when an instance declared in module `", pp_mod, ppStr "' has been imported"])
961 pp_mod = ppBesides [ppStr "module `", ppPStr inst_mod, ppStr "'"]
963 nonBoxedPrimCCallErr clas inst_ty sty
964 = ppHang (ppStr "Instance isn't for a `boxed-primitive' type")
965 4 (ppBesides [ ppStr "class `", ppr sty clas, ppStr "' type `",
966 ppr sty inst_ty, ppStr "'"])
968 omitDefaultMethodWarn clas_op clas_name inst_ty sty
969 = ppCat [ppStr "Warning: Omitted default method for",
970 ppr sty clas_op, ppStr "in instance",
971 ppPStr clas_name, pprParendGenType sty inst_ty]
974 patMonoBindsCtxt pbind sty
975 = ppHang (ppStr "In a pattern binding:")
978 methodSigCtxt name ty sty
979 = ppHang (ppBesides [ppStr "When matching the definition of class method `",
980 ppr sty name, ppStr "' to its signature :" ])
983 bindSigCtxt method_ids sty
984 = ppHang (ppStr "When checking type signatures for: ")
985 4 (ppInterleave (ppStr ", ") (map (ppr sty) method_ids))
987 superClassSigCtxt sty
988 = ppStr "When checking superclass constraints on instance declaration"