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, Qual, 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, opt_CompilingPrelude,
58 opt_OmitDefaultInstanceMethods,
59 opt_SpecialiseOverloaded )
60 import Class ( GenClass, GenClassOp,
61 isCcallishClass, classBigSig,
62 classOps, classOpLocalType,
65 import Id ( GenId, idType, isDefaultMethodId_maybe )
66 import ListSetOps ( minusList )
67 import Maybes ( maybeToBool, expectJust )
68 import Name ( getLocalName, origName, nameOf, Name{--O only-} )
69 import PrelVals ( nO_EXPLICIT_METHOD_ERROR_ID )
70 import PrelMods ( pRELUDE )
71 import PprType ( GenType, GenTyVar, GenClass, GenClassOp, TyCon,
76 import RnUtils ( RnEnv(..) )
77 import TyCon ( isSynTyCon, derivedFor )
78 import Type ( GenType(..), ThetaType(..), mkTyVarTys,
79 splitSigmaTy, splitAppTy, isTyVarTy, matchTy, mkSigmaTy,
80 getTyCon_maybe, maybeBoxedPrimType, splitRhoTy
82 import TyVar ( GenTyVar, mkTyVarSet, unionTyVarSets )
83 import TysWiredIn ( stringTy )
84 import Unique ( Unique )
85 import Util ( zipEqual, panic )
88 Typechecking instance declarations is done in two passes. The first
89 pass, made by @tcInstDecls1@, collects information to be used in the
92 This pre-processed info includes the as-yet-unprocessed bindings
93 inside the instance declaration. These are type-checked in the second
94 pass, when the class-instance envs and GVE contain all the info from
95 all the instance and value decls. Indeed that's the reason we need
96 two passes over the instance decls.
99 Here is the overall algorithm.
100 Assume that we have an instance declaration
102 instance c => k (t tvs) where b
106 $LIE_c$ is the LIE for the context of class $c$
108 $betas_bar$ is the free variables in the class method type, excluding the
111 $LIE_cop$ is the LIE constraining a particular class method
113 $tau_cop$ is the tau type of a class method
115 $LIE_i$ is the LIE for the context of instance $i$
117 $X$ is the instance constructor tycon
119 $gammas_bar$ is the set of type variables of the instance
121 $LIE_iop$ is the LIE for a particular class method instance
123 $tau_iop$ is the tau type for this instance of a class method
125 $alpha$ is the class variable
127 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
129 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
132 ToDo: Update the list above with names actually in the code.
136 First, make the LIEs for the class and instance contexts, which means
137 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
138 and make LIElistI and LIEI.
140 Then process each method in turn.
142 order the instance methods according to the ordering of the class methods
144 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
146 Create final dictionary function from bindings generated already
148 df = lambda inst_tyvars
155 in <op1,op2,...,opn,sd1,...,sdm>
157 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
158 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
162 tcInstDecls1 :: Bag RenamedInstDecl
163 -> [RenamedSpecInstSig]
164 -> Module -- module name for deriving
165 -> RnEnv -- for renaming derivings
166 -> [RenamedFixityDecl] -- fixities for deriving
167 -> TcM s (Bag InstInfo,
171 tcInstDecls1 inst_decls specinst_sigs mod_name rn_env fixities
172 = -- Do the ordinary instance declarations
173 mapBagNF_Tc (tcInstDecl1 mod_name) inst_decls
174 `thenNF_Tc` \ inst_info_bags ->
176 decl_inst_info = concatBag inst_info_bags
178 -- Handle "derived" instances; note that we only do derivings
179 -- for things in this module; we ignore deriving decls from
180 -- interfaces! We pass fixities, because they may be used
181 -- in deriving Read and Show.
182 tcDeriving mod_name rn_env decl_inst_info fixities
183 `thenTc` \ (deriv_inst_info, deriv_binds, ddump_deriv) ->
186 inst_info = deriv_inst_info `unionBags` decl_inst_info
189 -- Handle specialise instance pragmas
190 tcSpecInstSigs inst_info specinst_sigs
191 `thenTc` \ spec_inst_info ->
194 spec_inst_info = emptyBag -- For now
196 full_inst_info = inst_info `unionBags` spec_inst_info
198 returnTc (full_inst_info, deriv_binds, ddump_deriv)
201 tcInstDecl1 :: FAST_STRING -> RenamedInstDecl -> NF_TcM s (Bag InstInfo)
205 poly_ty@(HsForAllTy tyvar_names context inst_ty)
207 from_here inst_mod uprags pragmas src_loc)
208 = -- Prime error recovery, set source location
209 recoverNF_Tc (returnNF_Tc emptyBag) $
210 tcAddSrcLoc src_loc $
213 tcLookupClass class_name `thenNF_Tc` \ (clas_kind, clas) ->
218 -- Typecheck the context and instance type
219 tcTyVarScope (map de_rn tyvar_names) (\ tyvars ->
220 tcContext context `thenTc` \ theta ->
221 tcMonoTypeKind inst_ty `thenTc` \ (tau_kind, tau) ->
222 unifyKind clas_kind tau_kind `thenTc_`
223 returnTc (tyvars, theta, tau)
224 ) `thenTc` \ (inst_tyvars, inst_theta, inst_tau) ->
226 -- Check for respectable instance type
227 scrutiniseInstanceType from_here clas inst_tau
228 `thenTc` \ (inst_tycon,arg_tys) ->
230 -- Deal with the case where we are deriving
231 -- and importing the same instance
232 if (not from_here && (clas `derivedFor` inst_tycon)
233 && all isTyVarTy arg_tys)
235 if not opt_CompilingPrelude && maybeToBool inst_mod &&
236 mod_name == expectJust "inst_mod" 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 mod_str = case inst_mod of { Nothing -> pRELUDE; Just m -> m }
560 error_msg = _UNPK_ mod_str ++ "." ++ _UNPK_ clas_name ++ "."
561 ++ (ppShow 80 (ppr PprForUser inst_ty)) ++ "."
562 ++ (ppShow 80 (ppr PprForUser clas_op)) ++ "\""
564 clas_name = nameOf (origName clas)
568 %************************************************************************
570 \subsection{Processing each method}
572 %************************************************************************
574 @processInstBinds@ returns a @MonoBinds@ which binds
575 all the method ids (which are passed in). It is used
576 - both for instance decls,
577 - and to compile the default-method declarations in a class decl.
579 Any method ids which don't have a binding have a suitable default
580 binding created for them. The actual right-hand side used is
581 created using a function which is passed in, because the right thing to
582 do differs between instance and class decls.
587 -> (Int -> NF_TcM s (TcExpr s)) -- Function to make default method
588 -> [TcTyVar s] -- Tyvars for this instance decl
589 -> LIE s -- available Insts
590 -> [TcIdOcc s] -- Local method ids in tag order
591 -- (instance tyvars are free in their types)
593 -> TcM s (LIE s, -- These are required
596 processInstBinds clas mk_default_method_rhs inst_tyvars avail_insts method_ids monobinds
598 -- Process the explicitly-given method bindings
599 processInstBinds1 clas inst_tyvars avail_insts method_ids monobinds
600 `thenTc` \ (tags, insts_needed_in_methods, method_binds) ->
602 -- Find the methods not handled, and make default method bindings for them.
604 unmentioned_tags = [1.. length method_ids] `minusList` tags
606 mapNF_Tc mk_default_method unmentioned_tags
607 `thenNF_Tc` \ default_bind_list ->
609 returnTc (insts_needed_in_methods,
610 foldr AndMonoBinds method_binds default_bind_list)
612 -- From a tag construct us the passed-in function to construct
613 -- the binding for the default method
614 mk_default_method tag = mk_default_method_rhs tag `thenNF_Tc` \ rhs ->
615 returnNF_Tc (VarMonoBind (method_ids !! (tag-1)) rhs)
621 -> [TcTyVar s] -- Tyvars for this instance decl
622 -> LIE s -- available Insts
623 -> [TcIdOcc s] -- Local method ids in tag order (instance tyvars are free),
625 -> TcM s ([Int], -- Class-op tags accounted for
626 LIE s, -- These are required
629 processInstBinds1 clas inst_tyvars avail_insts method_ids EmptyMonoBinds
630 = returnTc ([], emptyLIE, EmptyMonoBinds)
632 processInstBinds1 clas inst_tyvars avail_insts method_ids (AndMonoBinds mb1 mb2)
633 = processInstBinds1 clas inst_tyvars avail_insts method_ids mb1
634 `thenTc` \ (op_tags1,dicts1,method_binds1) ->
635 processInstBinds1 clas inst_tyvars avail_insts method_ids mb2
636 `thenTc` \ (op_tags2,dicts2,method_binds2) ->
637 returnTc (op_tags1 ++ op_tags2,
638 dicts1 `unionBags` dicts2,
639 AndMonoBinds method_binds1 method_binds2)
643 processInstBinds1 clas inst_tyvars avail_insts method_ids mbind
645 -- Find what class op is being defined here. The complication is
646 -- that we could have a PatMonoBind or a FunMonoBind. If the
647 -- former, it should only bind a single variable, or else we're in
648 -- trouble (I'm not sure what the static semantics of methods
649 -- defined in a pattern binding with multiple patterns is!)
650 -- Renamer has reduced us to these two cases.
652 (op,locn) = case mbind of
653 FunMonoBind op _ _ locn -> (op, locn)
654 PatMonoBind (VarPatIn op) _ locn -> (op, locn)
656 occ = getLocalName op
657 origin = InstanceDeclOrigin
661 -- Make a method id for the method
663 tag = classOpTagByString clas occ
664 method_id = method_ids !! (tag-1)
665 method_ty = tcIdType method_id
668 tcInstTcType method_ty `thenNF_Tc` \ (method_tyvars, method_rho) ->
670 (method_theta, method_tau) = splitRhoTy method_rho
672 newDicts origin method_theta `thenNF_Tc` \ (method_dicts,method_dict_ids) ->
674 case (method_tyvars, method_dict_ids) of
676 ([],[]) -> -- The simple case; no local polymorphism or overloading in the method
678 -- Type check the method itself
679 tcMethodBind method_id method_tau mbind `thenTc` \ (mbind', lieIop) ->
680 returnTc ([tag], lieIop, mbind')
682 other -> -- It's a locally-polymorphic and/or overloaded method; UGH!
684 -- Make a new id for (a) the local, non-overloaded method
685 -- and (b) the locally-overloaded method
686 -- The latter is needed just so we can return an AbsBinds wrapped
687 -- up inside a MonoBinds.
690 -- Make the method_tyvars into signature tyvars so they
691 -- won't get unified with anything.
692 tcInstSigTyVars method_tyvars `thenNF_Tc` \ (sig_tyvars, sig_tyvar_tys, _) ->
693 unifyTauTyLists (mkTyVarTys method_tyvars) sig_tyvar_tys `thenTc_`
695 newLocalId occ method_tau `thenNF_Tc` \ local_id ->
696 newLocalId occ method_ty `thenNF_Tc` \ copy_id ->
698 inst_tyvar_set = mkTyVarSet inst_tyvars
699 inst_method_tyvar_set = inst_tyvar_set `unionTyVarSets` (mkTyVarSet sig_tyvars)
701 -- Typecheck the method
702 tcMethodBind local_id method_tau mbind `thenTc` \ (mbind', lieIop) ->
704 -- Check the overloading part of the signature.
705 -- Simplify everything fully, even though some
706 -- constraints could "really" be left to the next
707 -- level out. The case which forces this is
709 -- class Foo a where { op :: Bar a => a -> a }
711 -- Here we must simplify constraints on "a" to catch all
712 -- the Bar-ish things.
713 tcAddErrCtxt (methodSigCtxt op method_ty) (
714 checkSigTyVarsGivenGlobals
716 sig_tyvars method_tau `thenTc_`
719 inst_method_tyvar_set
720 (method_dicts `plusLIE` avail_insts)
722 ) `thenTc` \ (f_dicts, dict_binds) ->
727 VarMonoBind method_id
732 [(local_id, copy_id)]
739 tcMethodBind :: TcIdOcc s -> TcType s -> RenamedMonoBinds
740 -> TcM s (TcMonoBinds s, LIE s)
742 tcMethodBind meth_id meth_ty (FunMonoBind name inf matches locn)
743 = tcMatchesFun name meth_ty matches `thenTc` \ (rhs', lie) ->
744 returnTc (FunMonoBind meth_id inf rhs' locn, lie)
746 tcMethodBind meth_id meth_ty pbind@(PatMonoBind pat grhss_and_binds locn)
747 -- pat is sure to be a (VarPatIn op)
748 = tcAddErrCtxt (patMonoBindsCtxt pbind) $
749 tcGRHSsAndBinds grhss_and_binds `thenTc` \ (grhss_and_binds', lie, rhs_ty) ->
750 unifyTauTy meth_ty rhs_ty `thenTc_`
751 returnTc (PatMonoBind (VarPat meth_id) grhss_and_binds' locn, lie)
755 %************************************************************************
757 \subsection{Type-checking specialise instance pragmas}
759 %************************************************************************
763 tcSpecInstSigs :: E -> CE -> TCE
764 -> Bag InstInfo -- inst decls seen (declared and derived)
765 -> [RenamedSpecInstSig] -- specialise instance upragmas
766 -> TcM (Bag InstInfo) -- new, overlapped, inst decls
768 tcSpecInstSigs e ce tce inst_infos []
771 tcSpecInstSigs e ce tce inst_infos sigs
772 = buildInstanceEnvs inst_infos `thenTc` \ inst_mapper ->
773 tc_inst_spec_sigs inst_mapper sigs `thenNF_Tc` \ spec_inst_infos ->
774 returnTc spec_inst_infos
776 tc_inst_spec_sigs inst_mapper []
777 = returnNF_Tc emptyBag
778 tc_inst_spec_sigs inst_mapper (sig:sigs)
779 = tcSpecInstSig e ce tce inst_infos inst_mapper sig `thenNF_Tc` \ info_sig ->
780 tc_inst_spec_sigs inst_mapper sigs `thenNF_Tc` \ info_sigs ->
781 returnNF_Tc (info_sig `unionBags` info_sigs)
783 tcSpecInstSig :: E -> CE -> TCE
786 -> RenamedSpecInstSig
787 -> NF_TcM (Bag InstInfo)
789 tcSpecInstSig e ce tce inst_infos inst_mapper (SpecInstSig class_name ty src_loc)
790 = recoverTc emptyBag (
791 tcAddSrcLoc src_loc (
793 clas = lookupCE ce class_name -- Renamer ensures this can't fail
795 -- Make some new type variables, named as in the specialised instance type
796 ty_names = extractMonoTyNames ???is_tyvarish_name??? ty
797 (tmpl_e,inst_tmpls,inst_tmpl_tys) = mkTVE ty_names
799 babyTcMtoTcM (tcInstanceType ce tce tmpl_e True src_loc ty)
800 `thenTc` \ inst_ty ->
802 maybe_tycon = case maybeAppDataTyCon inst_ty of
803 Just (tc,_,_) -> Just tc
806 maybe_unspec_inst = lookup_unspec_inst clas maybe_tycon inst_infos
808 -- Check that we have a local instance declaration to specialise
809 checkMaybeTc maybe_unspec_inst
810 (specInstUnspecInstNotFoundErr clas inst_ty src_loc) `thenTc_`
812 -- Create tvs to substitute for tmpls while simplifying the context
813 copyTyVars inst_tmpls `thenNF_Tc` \ (tv_e, inst_tvs, inst_tv_tys) ->
815 Just (InstInfo _ unspec_tyvars unspec_inst_ty unspec_theta
816 _ _ _ binds True{-from here-} mod _ uprag) = maybe_unspec_inst
818 subst = case matchTy unspec_inst_ty inst_ty of
820 Nothing -> panic "tcSpecInstSig:matchTy"
822 subst_theta = instantiateThetaTy subst unspec_theta
823 subst_tv_theta = instantiateThetaTy tv_e subst_theta
825 mk_spec_origin clas ty
826 = InstanceSpecOrigin inst_mapper clas ty src_loc
827 -- I'm VERY SUSPICIOUS ABOUT THIS
828 -- the inst-mapper is in a knot at this point so it's no good
829 -- looking at it in tcSimplify...
831 tcSimplifyThetas mk_spec_origin subst_tv_theta
832 `thenTc` \ simpl_tv_theta ->
834 simpl_theta = [ (clas, tv_to_tmpl tv) | (clas, tv) <- simpl_tv_theta ]
836 tv_tmpl_map = zipEqual "tcSpecInstSig" inst_tv_tys inst_tmpl_tys
837 tv_to_tmpl tv = assoc "tcSpecInstSig" tv_tmpl_map tv
839 mkInstanceRelatedIds e True{-from here-} src_loc mod NoInstancePragmas
840 clas inst_tmpls inst_ty simpl_theta uprag
841 `thenTc` \ (dfun_id, dfun_theta, const_meth_ids) ->
843 getSwitchCheckerTc `thenNF_Tc` \ sw_chkr ->
844 (if sw_chkr SpecialiseTrace then
845 pprTrace "Specialised Instance: "
846 (ppAboves [ppCat [if null simpl_theta then ppNil else ppr PprDebug simpl_theta,
847 if null simpl_theta then ppNil else ppStr "=>",
849 pprParendGenType PprDebug inst_ty],
850 ppCat [ppStr " derived from:",
851 if null unspec_theta then ppNil else ppr PprDebug unspec_theta,
852 if null unspec_theta then ppNil else ppStr "=>",
854 pprParendGenType PprDebug unspec_inst_ty]])
857 returnTc (unitBag (InstInfo clas inst_tmpls inst_ty simpl_theta
858 dfun_theta dfun_id const_meth_ids
859 binds True{-from here-} mod src_loc uprag))
863 lookup_unspec_inst clas maybe_tycon inst_infos
864 = case filter (match_info match_inst_ty) (bagToList inst_infos) of
866 (info:_) -> Just info
868 match_info match_ty (InstInfo inst_clas _ inst_ty _ _ _ _ _ from_here _ _ _)
869 = from_here && clas == inst_clas &&
870 match_ty inst_ty && is_plain_instance inst_ty
872 match_inst_ty = case maybe_tycon of
873 Just tycon -> match_tycon tycon
876 match_tycon tycon inst_ty = case (maybeAppDataTyCon inst_ty) of
877 Just (inst_tc,_,_) -> tycon == inst_tc
880 match_fun inst_ty = isFunType inst_ty
883 is_plain_instance inst_ty
884 = case (maybeAppDataTyCon inst_ty) of
885 Just (_,tys,_) -> all isTyVarTemplateTy tys
886 Nothing -> case maybeUnpackFunTy inst_ty of
887 Just (arg, res) -> isTyVarTemplateTy arg && isTyVarTemplateTy res
888 Nothing -> error "TcInstDecls:is_plain_instance"
893 Checking for a decent instance type
894 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
895 @scrutiniseInstanceType@ checks the type {\em and} its syntactic constraints:
896 it must normally look like: @instance Foo (Tycon a b c ...) ...@
898 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
899 flag is on, or (2)~the instance is imported (they must have been
900 compiled elsewhere). In these cases, we let them go through anyway.
902 We can also have instances for functions: @instance Foo (a -> b) ...@.
905 scrutiniseInstanceType from_here clas inst_tau
907 | not (maybeToBool inst_tycon_maybe) || isSynTyCon inst_tycon
908 = failTc (instTypeErr inst_tau)
910 -- IMPORTED INSTANCES ARE OK (but see tcInstDecl1)
912 = returnTc (inst_tycon,arg_tys)
915 | not (all isTyVarTy arg_tys ||
918 = failTc (instTypeErr inst_tau)
921 -- It is obviously illegal to have an explicit instance
922 -- for something that we are also planning to `derive'
923 -- Though we can have an explicit instance which is more
924 -- specific than the derived instance
925 | clas `derivedFor` inst_tycon
926 && all isTyVarTy arg_tys
927 = failTc (derivingWhenInstanceExistsErr clas inst_tycon)
930 -- A user declaration of a CCallable/CReturnable instance
931 -- must be for a "boxed primitive" type.
933 -- && not opt_CompilingPrelude -- which allows anything
934 && not (maybeToBool (maybeBoxedPrimType inst_tau))
935 = failTc (nonBoxedPrimCCallErr clas inst_tau)
938 = returnTc (inst_tycon,arg_tys)
941 (possible_tycon, arg_tys) = splitAppTy inst_tau
942 inst_tycon_maybe = getTyCon_maybe possible_tycon
943 inst_tycon = expectJust "tcInstDecls1:inst_tycon" inst_tycon_maybe
950 SynTy tc _ _ -> ppBesides [ppStr "The type synonym `", ppr sty tc, rest_of_msg]
951 TyVarTy tv -> ppBesides [ppStr "The type variable `", ppr sty tv, rest_of_msg]
952 other -> ppBesides [ppStr "The type `", ppr sty ty, rest_of_msg]
954 rest_of_msg = ppStr "' cannot be used as an instance type."
956 derivingWhenInstanceExistsErr clas tycon sty
957 = ppHang (ppBesides [ppStr "Deriving class `", ppr sty clas, ppStr "' type `", ppr sty tycon, ppStr "'"])
958 4 (ppStr "when an explicit instance exists")
960 derivingWhenInstanceImportedErr inst_mod clas tycon sty
961 = ppHang (ppBesides [ppStr "Deriving class `", ppr sty clas, ppStr "' type `", ppr sty tycon, ppStr "'"])
962 4 (ppBesides [ppStr "when an instance declared in module `", pp_mod, ppStr "' has been imported"])
964 pp_mod = case inst_mod of
965 Nothing -> ppPStr SLIT("the standard Prelude")
966 Just m -> ppBesides [ppStr "module `", ppPStr m, ppStr "'"]
968 nonBoxedPrimCCallErr clas inst_ty sty
969 = ppHang (ppStr "Instance isn't for a `boxed-primitive' type")
970 4 (ppBesides [ ppStr "class `", ppr sty clas, ppStr "' type `",
971 ppr sty inst_ty, ppStr "'"])
973 omitDefaultMethodWarn clas_op clas_name inst_ty sty
974 = ppCat [ppStr "Warning: Omitted default method for",
975 ppr sty clas_op, ppStr "in instance",
976 ppPStr clas_name, pprParendGenType sty inst_ty]
979 patMonoBindsCtxt pbind sty
980 = ppHang (ppStr "In a pattern binding:")
983 methodSigCtxt name ty sty
984 = ppHang (ppBesides [ppStr "When matching the definition of class method `",
985 ppr sty name, ppStr "' to its signature :" ])
988 bindSigCtxt method_ids sty
989 = ppHang (ppStr "When checking type signatures for: ")
990 4 (ppInterleave (ppStr ", ") (map (ppr sty) method_ids))
992 superClassSigCtxt sty
993 = ppStr "When checking superclass constraints on instance declaration"