2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[TcInstDecls]{Typechecking instance declarations}
7 #include "HsVersions.h"
18 import HsSyn ( InstDecl(..), FixityDecl, Sig(..),
19 SpecInstSig(..), HsBinds(..), Bind(..),
20 MonoBinds(..), GRHSsAndBinds, Match,
21 InPat(..), OutPat(..), HsExpr(..), HsLit(..),
22 Stmt, Qual, ArithSeqInfo, Fake,
23 PolyType(..), MonoType )
24 import RnHsSyn ( RenamedHsBinds(..), RenamedMonoBinds(..),
25 RenamedInstDecl(..), RenamedFixityDecl(..),
26 RenamedSig(..), RenamedSpecInstSig(..) )
27 import TcHsSyn ( TcIdOcc(..), TcHsBinds(..),
28 TcMonoBinds(..), TcExpr(..),
30 mkHsDictLam, mkHsDictApp )
34 import GenSpecEtc ( checkSigTyVars, specTy )
35 import Inst ( Inst, InstOrigin(..), InstanceMapper(..),
36 newDicts, newMethod, LIE(..), emptyLIE, plusLIE )
37 import TcBinds ( tcPragmaSigs )
38 import TcDeriv ( tcDeriving )
39 import TcEnv ( tcLookupClass, tcTyVarScope, newLocalIds )
40 import TcGRHSs ( tcGRHSsAndBinds )
41 import TcInstUtil ( InstInfo(..), mkInstanceRelatedIds, buildInstanceEnvs )
42 import TcKind ( TcKind, unifyKind )
43 import TcMatches ( tcMatchesFun )
44 import TcMonoType ( tcContext, tcMonoTypeKind )
45 import TcSimplify ( tcSimplifyAndCheck, tcSimplifyThetas )
46 import TcType ( TcType(..), TcTyVar(..),
47 tcInstTyVar, tcInstType, tcInstTheta )
48 import Unify ( unifyTauTy )
51 import Bag ( emptyBag, unitBag, unionBags, unionManyBags,
52 concatBag, foldBag, bagToList )
53 import CmdLineOpts ( opt_GlasgowExts, opt_CompilingPrelude,
54 opt_OmitDefaultInstanceMethods,
55 opt_SpecialiseOverloaded )
56 import Class ( GenClass, GenClassOp,
57 isCcallishClass, getClassBigSig,
58 getClassOps, getClassOpLocalType )
59 import CoreUtils ( escErrorMsg )
60 import Id ( idType, isDefaultMethodId_maybe )
61 import ListSetOps ( minusList )
62 import Maybes ( maybeToBool, expectJust )
63 import Name ( Name, getTagFromClassOpName )
65 import PrelInfo ( pAT_ERROR_ID )
66 import PprType ( GenType, GenTyVar, GenClass, GenClassOp, TyCon,
70 import RnUtils ( GlobalNameMappers(..), GlobalNameMapper(..) )
71 import TyCon ( derivedFor )
72 import Type ( GenType(..), ThetaType(..), mkTyVarTy,
73 splitSigmaTy, splitAppTy, isTyVarTy, matchTy,
74 getTyCon_maybe, maybeBoxedPrimType )
75 import TyVar ( GenTyVar, tyVarListToSet )
76 import TysWiredIn ( stringTy )
77 import Unique ( Unique )
82 Typechecking instance declarations is done in two passes. The first
83 pass, made by @tcInstDecls1@, collects information to be used in the
86 This pre-processed info includes the as-yet-unprocessed bindings
87 inside the instance declaration. These are type-checked in the second
88 pass, when the class-instance envs and GVE contain all the info from
89 all the instance and value decls. Indeed that's the reason we need
90 two passes over the instance decls.
93 Here is the overall algorithm.
94 Assume that we have an instance declaration
96 instance c => k (t tvs) where b
100 $LIE_c$ is the LIE for the context of class $c$
102 $betas_bar$ is the free variables in the class method type, excluding the
105 $LIE_cop$ is the LIE constraining a particular class method
107 $tau_cop$ is the tau type of a class method
109 $LIE_i$ is the LIE for the context of instance $i$
111 $X$ is the instance constructor tycon
113 $gammas_bar$ is the set of type variables of the instance
115 $LIE_iop$ is the LIE for a particular class method instance
117 $tau_iop$ is the tau type for this instance of a class method
119 $alpha$ is the class variable
121 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
123 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
126 ToDo: Update the list above with names actually in the code.
130 First, make the LIEs for the class and instance contexts, which means
131 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
132 and make LIElistI and LIEI.
134 Then process each method in turn.
136 order the instance methods according to the ordering of the class methods
138 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
140 Create final dictionary function from bindings generated already
142 df = lambda inst_tyvars
149 in <op1,op2,...,opn,sd1,...,sdm>
151 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
152 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
156 tcInstDecls1 :: Bag RenamedInstDecl
157 -> [RenamedSpecInstSig]
158 -> FAST_STRING -- module name for deriving
159 -> GlobalNameMappers -- renamer fns for deriving
160 -> [RenamedFixityDecl] -- fixities for deriving
161 -> TcM s (Bag InstInfo,
165 tcInstDecls1 inst_decls specinst_sigs mod_name renamer_name_funs fixities
166 = -- Do the ordinary instance declarations
167 mapBagNF_Tc (tcInstDecl1 mod_name) inst_decls
168 `thenNF_Tc` \ inst_info_bags ->
170 decl_inst_info = concatBag inst_info_bags
172 -- Handle "derived" instances; note that we only do derivings
173 -- for things in this module; we ignore deriving decls from
174 -- interfaces! We pass fixities, because they may be used
175 -- in deriving Read and Show.
176 tcDeriving mod_name renamer_name_funs decl_inst_info fixities
177 `thenTc` \ (deriv_inst_info, deriv_binds, ddump_deriv) ->
180 inst_info = deriv_inst_info `unionBags` decl_inst_info
183 -- Handle specialise instance pragmas
184 tcSpecInstSigs inst_info specinst_sigs
185 `thenTc` \ spec_inst_info ->
188 spec_inst_info = emptyBag -- For now
190 full_inst_info = inst_info `unionBags` spec_inst_info
192 returnTc (full_inst_info, deriv_binds, ddump_deriv)
195 tcInstDecl1 :: FAST_STRING -> RenamedInstDecl -> NF_TcM s (Bag InstInfo)
199 poly_ty@(HsForAllTy tyvar_names context inst_ty)
201 from_here inst_mod uprags pragmas src_loc)
202 = -- Prime error recovery, set source location
203 recoverNF_Tc (returnNF_Tc emptyBag) $
204 tcAddSrcLoc src_loc $
207 tcLookupClass class_name `thenNF_Tc` \ (clas_kind, clas) ->
209 -- Typecheck the context and instance type
210 tcTyVarScope tyvar_names (\ tyvars ->
211 tcContext context `thenTc` \ theta ->
212 tcMonoTypeKind inst_ty `thenTc` \ (tau_kind, tau) ->
213 unifyKind clas_kind tau_kind `thenTc_`
214 returnTc (tyvars, theta, tau)
215 ) `thenTc` \ (inst_tyvars, inst_theta, inst_tau) ->
217 -- Check for respectable instance type
218 scrutiniseInstanceType from_here clas inst_tau
219 `thenTc` \ (inst_tycon,arg_tys) ->
221 -- Deal with the case where we are deriving
222 -- and importing the same instance
223 if (not from_here && (clas `derivedFor` inst_tycon)
224 && all isTyVarTy arg_tys)
226 if mod_name == inst_mod then
227 -- Imported instance came from this module;
228 -- discard and derive fresh instance
231 -- Imported instance declared in another module;
232 -- report duplicate instance error
233 failTc (derivingWhenInstanceImportedErr inst_mod clas inst_tycon)
236 -- Make the dfun id and constant-method ids
237 mkInstanceRelatedIds from_here inst_mod pragmas
238 clas inst_tyvars inst_tau inst_theta uprags
239 `thenTc` \ (dfun_id, dfun_theta, const_meth_ids) ->
241 returnTc (unitBag (InstInfo clas inst_tyvars inst_tau inst_theta
242 dfun_theta dfun_id const_meth_ids
243 binds from_here inst_mod src_loc uprags))
247 %************************************************************************
249 \subsection{Type-checking instance declarations, pass 2}
251 %************************************************************************
254 tcInstDecls2 :: Bag InstInfo
255 -> NF_TcM s (LIE s, TcHsBinds s)
257 tcInstDecls2 inst_decls
258 = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyBinds)) inst_decls
260 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
261 tc2 `thenNF_Tc` \ (lie2, binds2) ->
262 returnNF_Tc (lie1 `plusLIE` lie2,
263 binds1 `ThenBinds` binds2)
267 ======= New documentation starts here (Sept 92) ==============
269 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
270 the dictionary function for this instance declaration. For example
272 instance Foo a => Foo [a] where
276 might generate something like
278 dfun.Foo.List dFoo_a = let op1 x = ...
284 HOWEVER, if the instance decl has no context, then it returns a
285 bigger @HsBinds@ with declarations for each method. For example
287 instance Foo [a] where
293 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
294 const.Foo.op1.List a x = ...
295 const.Foo.op2.List a y = ...
297 This group may be mutually recursive, because (for example) there may
298 be no method supplied for op2 in which case we'll get
300 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
302 that is, the default method applied to the dictionary at this type.
304 What we actually produce in either case is:
306 AbsBinds [a] [dfun_theta_dicts]
307 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
308 { d = (sd1,sd2, ..., op1, op2, ...)
313 The "maybe" says that we only ask AbsBinds to make global constant methods
314 if the dfun_theta is empty.
317 For an instance declaration, say,
319 instance (C1 a, C2 b) => C (T a b) where
322 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
323 function whose type is
325 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
327 Notice that we pass it the superclass dictionaries at the instance type; this
328 is the ``Mark Jones optimisation''. The stuff before the "=>" here
329 is the @dfun_theta@ below.
331 First comes the easy case of a non-local instance decl.
334 tcInstDecl2 :: InstInfo
335 -> NF_TcM s (LIE s, TcHsBinds s)
337 tcInstDecl2 (InstInfo _ _ _ _ _ _ _ _ False{-import-} _ _ _)
338 = returnNF_Tc (emptyLIE, EmptyBinds)
340 tcInstDecl2 (InstInfo clas inst_tyvars inst_ty
341 inst_decl_theta dfun_theta
342 dfun_id const_meth_ids monobinds
343 True{-here-} inst_mod locn uprags)
344 = -- Prime error recovery
345 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyBinds)) $
348 -- Get the class signature
349 mapNF_Tc tcInstTyVar inst_tyvars `thenNF_Tc` \ inst_tyvars' ->
351 tenv = inst_tyvars `zip` (map mkTyVarTy inst_tyvars')
354 super_classes, sc_sel_ids,
355 class_ops, op_sel_ids, defm_ids) = getClassBigSig clas
357 tcInstType tenv inst_ty `thenNF_Tc` \ inst_ty' ->
358 tcInstTheta tenv dfun_theta `thenNF_Tc` \ dfun_theta' ->
359 tcInstTheta tenv inst_decl_theta `thenNF_Tc` \ inst_decl_theta' ->
361 sc_theta' = super_classes `zip` (repeat inst_ty')
362 origin = InstanceDeclOrigin
363 mk_method sel_id = newMethod origin (RealId sel_id) [inst_ty']
365 -- Create dictionary Ids from the specified instance contexts.
366 newDicts origin sc_theta' `thenNF_Tc` \ (sc_dicts, sc_dict_ids) ->
367 newDicts origin dfun_theta' `thenNF_Tc` \ (dfun_arg_dicts, dfun_arg_dicts_ids) ->
368 newDicts origin inst_decl_theta' `thenNF_Tc` \ (inst_decl_dicts, _) ->
369 newDicts origin [(clas,inst_ty')] `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
371 -- Create method variables
372 mapAndUnzipNF_Tc mk_method op_sel_ids `thenNF_Tc` \ (meth_insts_s, meth_ids) ->
374 -- Collect available Insts
376 avail_insts -- These insts are in scope; quite a few, eh?
377 = unionManyBags (this_dict : dfun_arg_dicts : meth_insts_s)
380 = if opt_OmitDefaultInstanceMethods then
381 makeInstanceDeclNoDefaultExpr origin clas meth_ids defm_ids inst_mod inst_ty'
383 makeInstanceDeclDefaultMethodExpr origin this_dict_id class_ops defm_ids inst_ty'
385 processInstBinds mk_method_expr inst_tyvars' avail_insts meth_ids monobinds
386 `thenTc` \ (insts_needed, method_mbinds) ->
388 -- Create the dict and method binds
390 = VarMonoBind this_dict_id (Dictionary sc_dict_ids meth_ids)
392 dict_and_method_binds
393 = dict_bind `AndMonoBinds` method_mbinds
395 inst_tyvars_set' = tyVarListToSet inst_tyvars'
397 -- Check the overloading constraints of the methods and superclasses
398 tcAddErrCtxt (bindSigCtxt meth_ids) (
400 inst_tyvars_set' -- Local tyvars
402 (sc_dicts `unionBags` insts_needed) -- Need to get defns for all these
403 ) `thenTc` \ (const_lie, super_binds) ->
405 -- Check that we *could* construct the superclass dictionaries,
406 -- even though we are *actually* going to pass the superclass dicts in;
407 -- the check ensures that the caller will never have a problem building
409 tcAddErrCtxt superClassSigCtxt (
411 inst_tyvars_set' -- Local tyvars
412 inst_decl_dicts -- The instance dictionaries available
413 sc_dicts -- The superclass dicationaries reqd
415 -- Ignore the result; we're only doing
416 -- this to make sure it can be done.
418 -- Now process any SPECIALIZE pragmas for the methods
420 spec_sigs = [ s | s@(SpecSig _ _ _ _) <- uprags ]
422 tcPragmaSigs spec_sigs `thenTc` \ (_, spec_binds, spec_lie) ->
424 -- Complete the binding group, adding any spec_binds
429 ((this_dict_id, RealId dfun_id)
430 : (meth_ids `zip` (map RealId const_meth_ids)))
431 -- const_meth_ids will often be empty
433 (RecBind dict_and_method_binds)
439 returnTc (const_lie `plusLIE` spec_lie, inst_binds)
442 This function makes a default method which calls the global default method, at
443 the appropriate instance type.
445 See the notes under default decls in TcClassDcl.lhs.
448 makeInstanceDeclDefaultMethodExpr
455 -> NF_TcM s (TcExpr s)
457 makeInstanceDeclDefaultMethodExpr origin this_dict class_ops defm_ids inst_ty tag
458 = specTy origin (getClassOpLocalType class_op)
459 `thenNF_Tc` \ (op_tyvars, op_lie, op_tau, op_dicts) ->
461 -- def_op_id = /\ op_tyvars -> \ op_dicts ->
462 -- defm_id inst_ty op_tyvars this_dict op_dicts
465 mkHsTyLam op_tyvars (
466 mkHsDictLam op_dicts (
467 mkHsDictApp (mkHsTyApp (HsVar (RealId defm_id))
468 (inst_ty : map mkTyVarTy op_tyvars))
469 (this_dict : op_dicts)
473 class_op = class_ops !! idx
474 defm_id = defm_ids !! idx
476 makeInstanceDeclNoDefaultExpr
484 -> NF_TcM s (TcExpr s)
486 makeInstanceDeclNoDefaultExpr origin clas method_occs defm_ids inst_mod inst_ty tag
488 (op_tyvars,op_theta,op_tau) = splitSigmaTy (idType method_id)
490 newDicts origin op_theta `thenNF_Tc` \ (op_lie,op_dicts) ->
492 -- Produce a warning if the default instance method
493 -- has been omitted when one exists in the class
494 warnTc (not err_defm_ok)
495 (omitDefaultMethodWarn clas_op clas_name inst_ty)
497 returnNF_Tc (mkHsTyLam op_tyvars (
498 mkHsDictLam op_dicts (
499 HsApp (mkHsTyApp (HsVar (RealId pAT_ERROR_ID)) [op_tau])
500 (HsLitOut (HsString (_PK_ error_msg)) stringTy))))
503 method_occ = method_occs !! idx
504 clas_op = (getClassOps clas) !! idx
505 defm_id = defm_ids !! idx
507 TcId method_id = method_occ
508 Just (_, _, err_defm_ok) = isDefaultMethodId_maybe defm_id
510 error_msg = "%E" -- => No explicit method for \"
511 ++ escErrorMsg error_str
513 error_str = _UNPK_ inst_mod ++ "." ++ _UNPK_ clas_name ++ "."
514 ++ (ppShow 80 (ppr PprForUser inst_ty)) ++ "."
515 ++ (ppShow 80 (ppr PprForUser clas_op)) ++ "\""
517 (_, clas_name) = getOrigName clas
521 %************************************************************************
523 \subsection{Processing each method}
525 %************************************************************************
527 @processInstBinds@ returns a @MonoBinds@ which binds
528 all the method ids (which are passed in). It is used
529 - both for instance decls,
530 - and to compile the default-method declarations in a class decl.
532 Any method ids which don't have a binding have a suitable default
533 binding created for them. The actual right-hand side used is
534 created using a function which is passed in, because the right thing to
535 do differs between instance and class decls.
539 :: (Int -> NF_TcM s (TcExpr s)) -- Function to make default method
540 -> [TcTyVar s] -- Tyvars for this instance decl
541 -> LIE s -- available Insts
542 -> [TcIdOcc s] -- Local method ids in tag order
543 -- (instance tyvars are free in their types)
545 -> TcM s (LIE s, -- These are required
548 processInstBinds mk_default_method_rhs inst_tyvars avail_insts method_ids monobinds
550 -- Process the explicitly-given method bindings
551 processInstBinds1 inst_tyvars avail_insts method_ids monobinds
552 `thenTc` \ (tags, insts_needed_in_methods, method_binds) ->
554 -- Find the methods not handled, and make default method bindings for them.
556 unmentioned_tags = [1.. length method_ids] `minusList` tags
558 mapNF_Tc mk_default_method unmentioned_tags
559 `thenNF_Tc` \ default_bind_list ->
561 returnTc (insts_needed_in_methods,
562 foldr AndMonoBinds method_binds default_bind_list)
564 -- From a tag construct us the passed-in function to construct
565 -- the binding for the default method
566 mk_default_method tag = mk_default_method_rhs tag `thenNF_Tc` \ rhs ->
567 returnNF_Tc (VarMonoBind (method_ids !! (tag-1)) rhs)
572 :: [TcTyVar s] -- Tyvars for this instance decl
573 -> LIE s -- available Insts
574 -> [TcIdOcc s] -- Local method ids in tag order (instance tyvars are free),
576 -> TcM s ([Int], -- Class-op tags accounted for
577 LIE s, -- These are required
580 processInstBinds1 inst_tyvars avail_insts method_ids EmptyMonoBinds
581 = returnTc ([], emptyLIE, EmptyMonoBinds)
583 processInstBinds1 inst_tyvars avail_insts method_ids (AndMonoBinds mb1 mb2)
584 = processInstBinds1 inst_tyvars avail_insts method_ids mb1
585 `thenTc` \ (op_tags1,dicts1,method_binds1) ->
586 processInstBinds1 inst_tyvars avail_insts method_ids mb2
587 `thenTc` \ (op_tags2,dicts2,method_binds2) ->
588 returnTc (op_tags1 ++ op_tags2,
589 dicts1 `unionBags` dicts2,
590 AndMonoBinds method_binds1 method_binds2)
594 processInstBinds1 inst_tyvars avail_insts method_ids mbind
596 -- Find what class op is being defined here. The complication is
597 -- that we could have a PatMonoBind or a FunMonoBind. If the
598 -- former, it should only bind a single variable, or else we're in
599 -- trouble (I'm not sure what the static semantics of methods
600 -- defined in a pattern binding with multiple patterns is!)
601 -- Renamer has reduced us to these two cases.
603 (op,locn) = case mbind of
604 FunMonoBind op _ locn -> (op, locn)
605 PatMonoBind (VarPatIn op) _ locn -> (op, locn)
607 occ = getOccurrenceName op
608 origin = InstanceDeclOrigin
612 -- Make a method id for the method
613 let tag = getTagFromClassOpName op
614 method_id = method_ids !! (tag-1)
616 TcId method_bndr = method_id
617 method_ty = idType method_bndr
618 (method_tyvars, method_theta, method_tau) = splitSigmaTy method_ty
620 newDicts origin method_theta `thenNF_Tc` \ (method_dicts,method_dict_ids) ->
622 case (method_tyvars, method_dict_ids) of
624 ([],[]) -> -- The simple case; no local polymorphism or overloading in the method
626 -- Type check the method itself
627 tcMethodBind method_id method_tau mbind `thenTc` \ (mbind', lieIop) ->
629 -- Make sure that the instance tyvars havn't been
630 -- unified with each other or with the method tyvars.
631 tcSetErrCtxt (methodSigCtxt op method_tau) (
632 checkSigTyVars inst_tyvars method_tau method_tau
634 returnTc ([tag], lieIop, mbind')
636 other -> -- It's a locally-polymorphic and/or overloaded method; UGH!
638 -- Make a new id for (a) the local, non-overloaded method
639 -- and (b) the locally-overloaded method
640 -- The latter is needed just so we can return an AbsBinds wrapped
641 -- up inside a MonoBinds.
643 newLocalIds [occ,occ] [method_tau,method_ty] `thenNF_Tc` \ new_ids ->
645 [local_id, copy_id] = map TcId new_ids
646 inst_method_tyvars = inst_tyvars ++ method_tyvars
648 -- Typecheck the method
649 tcMethodBind local_id method_tau mbind `thenTc` \ (mbind', lieIop) ->
651 -- Make sure that the instance tyvars haven't been
652 -- unified with each other or with the method tyvars.
653 tcAddErrCtxt (methodSigCtxt op method_tau) (
654 checkSigTyVars inst_method_tyvars method_tau method_tau
657 -- Check the overloading part of the signature.
658 -- Simplify everything fully, even though some
659 -- constraints could "really" be left to the next
660 -- level out. The case which forces this is
662 -- class Foo a where { op :: Bar a => a -> a }
664 -- Here we must simplify constraints on "a" to catch all
665 -- the Bar-ish things.
666 tcAddErrCtxt (methodSigCtxt op method_ty) (
668 (tyVarListToSet inst_method_tyvars)
669 (method_dicts `plusLIE` avail_insts)
671 ) `thenTc` \ (f_dicts, dict_binds) ->
675 VarMonoBind method_id
680 [(local_id, copy_id)]
687 tcMethodBind :: TcIdOcc s -> TcType s -> RenamedMonoBinds
688 -> TcM s (TcMonoBinds s, LIE s)
690 tcMethodBind meth_id meth_ty (FunMonoBind name matches locn)
691 = tcMatchesFun name meth_ty matches `thenTc` \ (rhs', lie) ->
692 returnTc (FunMonoBind meth_id rhs' locn, lie)
694 tcMethodBind meth_id meth_ty pbind@(PatMonoBind pat grhss_and_binds locn)
695 -- pat is sure to be a (VarPatIn op)
696 = tcAddErrCtxt (patMonoBindsCtxt pbind) $
697 tcGRHSsAndBinds grhss_and_binds `thenTc` \ (grhss_and_binds', lie, rhs_ty) ->
698 unifyTauTy meth_ty rhs_ty `thenTc_`
699 returnTc (PatMonoBind (VarPat meth_id) grhss_and_binds' locn, lie)
703 %************************************************************************
705 \subsection{Type-checking specialise instance pragmas}
707 %************************************************************************
711 tcSpecInstSigs :: E -> CE -> TCE
712 -> Bag InstInfo -- inst decls seen (declared and derived)
713 -> [RenamedSpecInstSig] -- specialise instance upragmas
714 -> TcM (Bag InstInfo) -- new, overlapped, inst decls
716 tcSpecInstSigs e ce tce inst_infos []
719 tcSpecInstSigs e ce tce inst_infos sigs
720 = buildInstanceEnvs inst_infos `thenTc` \ inst_mapper ->
721 tc_inst_spec_sigs inst_mapper sigs `thenNF_Tc` \ spec_inst_infos ->
722 returnTc spec_inst_infos
724 tc_inst_spec_sigs inst_mapper []
725 = returnNF_Tc emptyBag
726 tc_inst_spec_sigs inst_mapper (sig:sigs)
727 = tcSpecInstSig e ce tce inst_infos inst_mapper sig `thenNF_Tc` \ info_sig ->
728 tc_inst_spec_sigs inst_mapper sigs `thenNF_Tc` \ info_sigs ->
729 returnNF_Tc (info_sig `unionBags` info_sigs)
731 tcSpecInstSig :: E -> CE -> TCE
734 -> RenamedSpecInstSig
735 -> NF_TcM (Bag InstInfo)
737 tcSpecInstSig e ce tce inst_infos inst_mapper (SpecInstSig class_name ty src_loc)
738 = recoverTc emptyBag (
739 tcAddSrcLoc src_loc (
741 clas = lookupCE ce class_name -- Renamer ensures this can't fail
743 -- Make some new type variables, named as in the specialised instance type
744 ty_names = extractMonoTyNames (==) ty
745 (tmpl_e,inst_tmpls,inst_tmpl_tys) = mkTVE ty_names
747 babyTcMtoTcM (tcInstanceType ce tce tmpl_e True src_loc ty)
748 `thenTc` \ inst_ty ->
750 maybe_tycon = case maybeDataTyCon inst_ty of
751 Just (tc,_,_) -> Just tc
754 maybe_unspec_inst = lookup_unspec_inst clas maybe_tycon inst_infos
756 -- Check that we have a local instance declaration to specialise
757 checkMaybeTc maybe_unspec_inst
758 (specInstUnspecInstNotFoundErr clas inst_ty src_loc) `thenTc_`
760 -- Create tvs to substitute for tmpls while simplifying the context
761 copyTyVars inst_tmpls `thenNF_Tc` \ (tv_e, inst_tvs, inst_tv_tys) ->
763 Just (InstInfo _ unspec_tyvars unspec_inst_ty unspec_theta
764 _ _ _ binds True{-from here-} mod _ uprag) = maybe_unspec_inst
766 subst = case matchTy unspec_inst_ty inst_ty of
768 Nothing -> panic "tcSpecInstSig:matchTy"
770 subst_theta = instantiateThetaTy subst unspec_theta
771 subst_tv_theta = instantiateThetaTy tv_e subst_theta
773 mk_spec_origin clas ty
774 = InstanceSpecOrigin inst_mapper clas ty src_loc
776 tcSimplifyThetas mk_spec_origin subst_tv_theta
777 `thenTc` \ simpl_tv_theta ->
779 simpl_theta = [ (clas, tv_to_tmpl tv) | (clas, tv) <- simpl_tv_theta ]
781 tv_tmpl_map = inst_tv_tys `zipEqual` inst_tmpl_tys
782 tv_to_tmpl tv = assoc "tcSpecInstSig" tv_tmpl_map tv
784 mkInstanceRelatedIds e True{-from here-} mod NoInstancePragmas src_loc
785 clas inst_tmpls inst_ty simpl_theta uprag
786 `thenTc` \ (dfun_id, dfun_theta, const_meth_ids) ->
788 getSwitchCheckerTc `thenNF_Tc` \ sw_chkr ->
789 (if sw_chkr SpecialiseTrace then
790 pprTrace "Specialised Instance: "
791 (ppAboves [ppCat [if null simpl_theta then ppNil else ppr PprDebug simpl_theta,
792 if null simpl_theta then ppNil else ppStr "=>",
794 pprParendType PprDebug inst_ty],
795 ppCat [ppStr " derived from:",
796 if null unspec_theta then ppNil else ppr PprDebug unspec_theta,
797 if null unspec_theta then ppNil else ppStr "=>",
799 pprParendType PprDebug unspec_inst_ty]])
802 returnTc (unitBag (InstInfo clas inst_tmpls inst_ty simpl_theta
803 dfun_theta dfun_id const_meth_ids
804 binds True{-from here-} mod src_loc uprag))
808 lookup_unspec_inst clas maybe_tycon inst_infos
809 = case filter (match_info match_inst_ty) (bagToList inst_infos) of
811 (info:_) -> Just info
813 match_info match_ty (InstInfo inst_clas _ inst_ty _ _ _ _ _ from_here _ _ _)
814 = from_here && clas == inst_clas &&
815 match_ty inst_ty && is_plain_instance inst_ty
817 match_inst_ty = case maybe_tycon of
818 Just tycon -> match_tycon tycon
821 match_tycon tycon inst_ty = case (maybeDataTyCon inst_ty) of
822 Just (inst_tc,_,_) -> tycon == inst_tc
825 match_fun inst_ty = isFunType inst_ty
828 is_plain_instance inst_ty
829 = case (maybeDataTyCon inst_ty) of
830 Just (_,tys,_) -> all isTyVarTemplateTy tys
831 Nothing -> case maybeUnpackFunTy inst_ty of
832 Just (arg, res) -> isTyVarTemplateTy arg && isTyVarTemplateTy res
833 Nothing -> error "TcInstDecls:is_plain_instance"
838 Checking for a decent instance type
839 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
840 @scrutiniseInstanceType@ checks the type {\em and} its syntactic constraints:
841 it must normally look like: @instance Foo (Tycon a b c ...) ...@
843 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
844 flag is on, or (2)~the instance is imported (they must have been
845 compiled elsewhere). In these cases, we let them go through anyway.
847 We can also have instances for functions: @instance Foo (a -> b) ...@.
850 scrutiniseInstanceType from_here clas inst_tau
852 | not (maybeToBool inst_tycon_maybe)
853 = failTc (instTypeErr inst_tau)
855 -- IMPORTED INSTANCES ARE OK (but see tcInstDecl1)
857 = returnTc (inst_tycon,arg_tys)
860 | not (all isTyVarTy arg_tys ||
863 = failTc (instTypeErr inst_tau)
866 -- It is obviously illegal to have an explicit instance
867 -- for something that we are also planning to `derive'
868 -- Though we can have an explicit instance which is more
869 -- specific than the derived instance
870 | clas `derivedFor` inst_tycon
871 && all isTyVarTy arg_tys
872 = failTc (derivingWhenInstanceExistsErr clas inst_tycon)
875 -- A user declaration of a _CCallable/_CReturnable instance
876 -- must be for a "boxed primitive" type.
878 && not opt_CompilingPrelude -- which allows anything
879 && maybeToBool (maybeBoxedPrimType inst_tau)
880 = failTc (nonBoxedPrimCCallErr clas inst_tau)
883 = returnTc (inst_tycon,arg_tys)
886 (possible_tycon, arg_tys) = splitAppTy inst_tau
887 inst_tycon_maybe = getTyCon_maybe possible_tycon
888 inst_tycon = expectJust "tcInstDecls1:inst_tycon" inst_tycon_maybe
895 SynTy tc _ _ -> ppBesides [ppStr "The type synonym `", ppr sty tc, rest_of_msg]
896 TyVarTy tv -> ppBesides [ppStr "The type variable `", ppr sty tv, rest_of_msg]
897 other -> ppBesides [ppStr "The type `", ppr sty ty, rest_of_msg]
899 rest_of_msg = ppStr "' cannot be used as an instance type."
901 derivingWhenInstanceExistsErr clas tycon sty
902 = ppHang (ppBesides [ppStr "Deriving class `", ppr sty clas, ppStr "' type `", ppr sty tycon, ppStr "'"])
903 4 (ppStr "when an explicit instance exists")
905 derivingWhenInstanceImportedErr inst_mod clas tycon sty
906 = ppHang (ppBesides [ppStr "Deriving class `", ppr sty clas, ppStr "' type `", ppr sty tycon, ppStr "'"])
907 4 (ppBesides [ppStr "when an instance declared in module `", ppPStr inst_mod, ppStr "' has been imported"])
909 nonBoxedPrimCCallErr clas inst_ty sty
910 = ppHang (ppStr "Instance isn't for a `boxed-primitive' type")
911 4 (ppBesides [ ppStr "class `", ppr sty clas, ppStr "' type `",
912 ppr sty inst_ty, ppStr "'"])
914 omitDefaultMethodWarn clas_op clas_name inst_ty sty
915 = ppCat [ppStr "Warning: Omitted default method for",
916 ppr sty clas_op, ppStr "in instance",
917 ppPStr clas_name, pprParendType sty inst_ty]
920 patMonoBindsCtxt pbind sty
921 = ppHang (ppStr "In a pattern binding:")
924 methodSigCtxt name ty sty
925 = ppHang (ppBesides [ppStr "When matching the definition of class method `",
926 ppr sty name, ppStr "' to its signature :" ])
929 bindSigCtxt method_ids sty
930 = ppHang (ppStr "When checking type signatures for: ")
931 4 (ppInterleave (ppStr ", ") (map (ppr sty) method_ids))
933 superClassSigCtxt sty
934 = ppStr "When checking superclass constraints on instance declaration"