2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[Inst]{The @Inst@ type: dictionaries or method instances}
8 LIE, emptyLIE, unitLIE, plusLIE, consLIE, zonkLIE,
9 plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
12 pprInst, pprInsts, pprInstsInFull, tidyInsts, tidyMoreInsts,
14 newDictsFromOld, newDicts, cloneDict,
15 newMethod, newMethodWithGivenTy, newMethodAtLoc,
16 newOverloadedLit, newIPDict, tcInstCall,
18 tyVarsOfInst, tyVarsOfInsts, tyVarsOfLIE,
19 ipNamesOfInst, ipNamesOfInsts, predsOfInst, predsOfInsts,
20 instLoc, getDictClassTys, dictPred,
22 lookupInst, lookupSimpleInst, LookupInstResult(..),
24 isDict, isClassDict, isMethod,
25 isLinearInst, linearInstType,
26 isTyVarDict, isStdClassTyVarDict, isMethodFor,
27 instBindingRequired, instCanBeGeneralised,
32 InstOrigin(..), InstLoc, pprInstLoc
35 #include "HsVersions.h"
37 import HsSyn ( HsLit(..), HsOverLit(..), HsExpr(..) )
38 import TcHsSyn ( TcExpr, TcId, TypecheckedHsExpr,
39 mkHsTyApp, mkHsDictApp, mkHsConApp, zonkId
42 import TcEnv ( TcIdSet, tcGetInstEnv, tcLookupId )
43 import InstEnv ( InstLookupResult(..), lookupInstEnv )
44 import TcMType ( zonkTcType, zonkTcTypes, zonkTcPredType, zapToType,
45 zonkTcThetaType, tcInstTyVar, tcInstType,
47 import TcType ( Type, TcType, TcThetaType, TcPredType, TcTauType, TcTyVarSet,
48 SourceType(..), PredType, ThetaType, TyVarDetails(VanillaTv),
49 tcSplitForAllTys, tcSplitForAllTys,
50 tcSplitMethodTy, tcSplitPhiTy, tcFunArgTy,
51 isIntTy,isFloatTy, isIntegerTy, isDoubleTy,
52 tcIsTyVarTy, mkPredTy, mkTyVarTy, mkTyVarTys,
53 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tidyPred,
54 isClassPred, isTyVarClassPred, isLinearPred,
55 getClassPredTys, getClassPredTys_maybe, mkPredName,
56 tidyType, tidyTypes, tidyFreeTyVars,
57 tcCmpType, tcCmpTypes, tcCmpPred
59 import CoreFVs ( idFreeTyVars )
60 import Class ( Class )
61 import Id ( Id, idName, idType, mkUserLocal, mkSysLocal, mkLocalId, setIdUnique )
62 import PrelInfo ( isStandardClass, isCcallishClass, isNoDictClass )
63 import Name ( Name, mkMethodOcc, getOccName )
64 import PprType ( pprPred, pprParendType )
65 import Subst ( emptyInScopeSet, mkSubst,
66 substTy, substTyWith, substTheta, mkTyVarSubst, mkTopTyVarSubst
68 import Literal ( inIntRange )
69 import VarEnv ( TidyEnv, lookupSubstEnv, SubstResult(..) )
70 import VarSet ( elemVarSet, emptyVarSet, unionVarSet )
71 import TysWiredIn ( floatDataCon, doubleDataCon )
72 import PrelNames( fromIntegerName, fromRationalName )
73 import Util ( thenCmp, equalLength )
74 import BasicTypes( IPName(..), mapIPName, ipNameName )
80 %************************************************************************
82 \subsection[Inst-collections]{LIE: a collection of Insts}
84 %************************************************************************
89 isEmptyLIE = isEmptyBag
91 unitLIE inst = unitBag inst
92 mkLIE insts = listToBag insts
93 plusLIE lie1 lie2 = lie1 `unionBags` lie2
94 consLIE inst lie = inst `consBag` lie
95 plusLIEs lies = unionManyBags lies
99 zonkLIE :: LIE -> NF_TcM LIE
100 zonkLIE lie = mapBagNF_Tc zonkInst lie
102 pprInsts :: [Inst] -> SDoc
103 pprInsts insts = parens (sep (punctuate comma (map pprInst insts)))
107 = vcat (map go insts)
109 go inst = quotes (ppr inst) <+> pprInstLoc (instLoc inst)
112 %************************************************************************
114 \subsection[Inst-types]{@Inst@ types}
116 %************************************************************************
118 An @Inst@ is either a dictionary, an instance of an overloaded
119 literal, or an instance of an overloaded value. We call the latter a
120 ``method'' even though it may not correspond to a class operation.
121 For example, we might have an instance of the @double@ function at
122 type Int, represented by
124 Method 34 doubleId [Int] origin
136 TcId -- The overloaded function
137 -- This function will be a global, local, or ClassOpId;
138 -- inside instance decls (only) it can also be an InstId!
139 -- The id needn't be completely polymorphic.
140 -- You'll probably find its name (for documentation purposes)
141 -- inside the InstOrigin
143 [TcType] -- The types to which its polymorphic tyvars
144 -- should be instantiated.
145 -- These types must saturate the Id's foralls.
147 TcThetaType -- The (types of the) dictionaries to which the function
148 -- must be applied to get the method
150 TcTauType -- The type of the method
154 -- INVARIANT: in (Method u f tys theta tau loc)
155 -- type of (f tys dicts(from theta)) = tau
159 HsOverLit -- The literal from the occurrence site
160 TcType -- The type at which the literal is used
166 @Insts@ are ordered by their class/type info, rather than by their
167 unique. This allows the context-reduction mechanism to use standard finite
168 maps to do their stuff.
171 instance Ord Inst where
174 instance Eq Inst where
175 (==) i1 i2 = case i1 `cmpInst` i2 of
179 cmpInst (Dict _ pred1 _) (Dict _ pred2 _) = pred1 `tcCmpPred` pred2
180 cmpInst (Dict _ _ _) other = LT
182 cmpInst (Method _ _ _ _ _ _) (Dict _ _ _) = GT
183 cmpInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
184 cmpInst (Method _ _ _ _ _ _) other = LT
186 cmpInst (LitInst _ lit1 ty1 _) (LitInst _ lit2 ty2 _) = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
187 cmpInst (LitInst _ _ _ _) other = GT
189 -- and they can only have HsInt or HsFracs in them.
196 instName :: Inst -> Name
197 instName inst = idName (instToId inst)
199 instToId :: Inst -> TcId
200 instToId (Dict id _ _) = id
201 instToId (Method id _ _ _ _ _) = id
202 instToId (LitInst id _ _ _) = id
204 instLoc (Dict _ _ loc) = loc
205 instLoc (Method _ _ _ _ _ loc) = loc
206 instLoc (LitInst _ _ _ loc) = loc
208 dictPred (Dict _ pred _ ) = pred
209 dictPred inst = pprPanic "dictPred" (ppr inst)
211 getDictClassTys (Dict _ pred _) = getClassPredTys pred
213 predsOfInsts :: [Inst] -> [PredType]
214 predsOfInsts insts = concatMap predsOfInst insts
216 predsOfInst (Dict _ pred _) = [pred]
217 predsOfInst (Method _ _ _ theta _ _) = theta
218 predsOfInst (LitInst _ _ _ _) = []
219 -- The last case is is really a big cheat
220 -- LitInsts to give rise to a (Num a) or (Fractional a) predicate
221 -- But Num and Fractional have only one parameter and no functional
222 -- dependencies, so I think no caller of predsOfInst will care.
224 ipNamesOfInsts :: [Inst] -> [Name]
225 ipNamesOfInst :: Inst -> [Name]
226 -- Get the implicit parameters mentioned by these Insts
227 -- NB: ?x and %x get different Names
229 ipNamesOfInsts insts = [n | inst <- insts, n <- ipNamesOfInst inst]
231 ipNamesOfInst (Dict _ (IParam n _) _) = [ipNameName n]
232 ipNamesOfInst (Method _ _ _ theta _ _) = [ipNameName n | IParam n _ <- theta]
233 ipNamesOfInst other = []
235 tyVarsOfInst :: Inst -> TcTyVarSet
236 tyVarsOfInst (LitInst _ _ ty _) = tyVarsOfType ty
237 tyVarsOfInst (Dict _ pred _) = tyVarsOfPred pred
238 tyVarsOfInst (Method _ id tys _ _ _) = tyVarsOfTypes tys `unionVarSet` idFreeTyVars id
239 -- The id might have free type variables; in the case of
240 -- locally-overloaded class methods, for example
242 tyVarsOfInsts insts = foldr (unionVarSet . tyVarsOfInst) emptyVarSet insts
243 tyVarsOfLIE lie = tyVarsOfInsts (lieToList lie)
249 isDict :: Inst -> Bool
250 isDict (Dict _ _ _) = True
253 isClassDict :: Inst -> Bool
254 isClassDict (Dict _ pred _) = isClassPred pred
255 isClassDict other = False
257 isTyVarDict :: Inst -> Bool
258 isTyVarDict (Dict _ pred _) = isTyVarClassPred pred
259 isTyVarDict other = False
261 isMethod :: Inst -> Bool
262 isMethod (Method _ _ _ _ _ _) = True
263 isMethod other = False
265 isMethodFor :: TcIdSet -> Inst -> Bool
266 isMethodFor ids (Method uniq id tys _ _ loc) = id `elemVarSet` ids
267 isMethodFor ids inst = False
269 isLinearInst :: Inst -> Bool
270 isLinearInst (Dict _ pred _) = isLinearPred pred
271 isLinearInst other = False
272 -- We never build Method Insts that have
273 -- linear implicit paramters in them.
274 -- Hence no need to look for Methods
277 linearInstType :: Inst -> TcType -- %x::t --> t
278 linearInstType (Dict _ (IParam _ ty) _) = ty
281 isStdClassTyVarDict (Dict _ pred _) = case getClassPredTys_maybe pred of
282 Just (clas, [ty]) -> isStandardClass clas && tcIsTyVarTy ty
286 Two predicates which deal with the case where class constraints don't
287 necessarily result in bindings. The first tells whether an @Inst@
288 must be witnessed by an actual binding; the second tells whether an
289 @Inst@ can be generalised over.
292 instBindingRequired :: Inst -> Bool
293 instBindingRequired (Dict _ (ClassP clas _) _) = not (isNoDictClass clas)
294 instBindingRequired other = True
296 instCanBeGeneralised :: Inst -> Bool
297 instCanBeGeneralised (Dict _ (ClassP clas _) _) = not (isCcallishClass clas)
298 instCanBeGeneralised other = True
302 %************************************************************************
304 \subsection{Building dictionaries}
306 %************************************************************************
309 newDicts :: InstOrigin
313 = tcGetInstLoc orig `thenNF_Tc` \ loc ->
314 newDictsAtLoc loc theta
316 cloneDict :: Inst -> NF_TcM Inst
317 cloneDict (Dict id ty loc) = tcGetUnique `thenNF_Tc` \ uniq ->
318 returnNF_Tc (Dict (setIdUnique id uniq) ty loc)
320 newDictsFromOld :: Inst -> TcThetaType -> NF_TcM [Inst]
321 newDictsFromOld (Dict _ _ loc) theta = newDictsAtLoc loc theta
323 -- Local function, similar to newDicts,
324 -- but with slightly different interface
325 newDictsAtLoc :: InstLoc
328 newDictsAtLoc inst_loc@(_,loc,_) theta
329 = tcGetUniques `thenNF_Tc` \ new_uniqs ->
330 returnNF_Tc (zipWith mk_dict new_uniqs theta)
332 mk_dict uniq pred = Dict (mkLocalId (mkPredName uniq loc pred) (mkPredTy pred)) pred inst_loc
334 -- For vanilla implicit parameters, there is only one in scope
335 -- at any time, so we used to use the name of the implicit parameter itself
336 -- But with splittable implicit parameters there may be many in
337 -- scope, so we make up a new name.
338 newIPDict :: InstOrigin -> IPName Name -> Type
339 -> NF_TcM (IPName Id, Inst)
340 newIPDict orig ip_name ty
341 = tcGetInstLoc orig `thenNF_Tc` \ inst_loc@(_,loc,_) ->
342 tcGetUnique `thenNF_Tc` \ uniq ->
344 pred = IParam ip_name ty
345 id = mkLocalId (mkPredName uniq loc pred) (mkPredTy pred)
347 returnNF_Tc (mapIPName (\n -> id) ip_name, Dict id pred inst_loc)
351 %************************************************************************
353 \subsection{Building methods (calls of overloaded functions)}
355 %************************************************************************
359 tcInstCall :: InstOrigin -> TcType -> NF_TcM (TypecheckedHsExpr -> TypecheckedHsExpr, LIE, TcType)
360 tcInstCall orig fun_ty -- fun_ty is usually a sigma-type
361 = tcInstType VanillaTv fun_ty `thenNF_Tc` \ (tyvars, theta, tau) ->
362 newDicts orig theta `thenNF_Tc` \ dicts ->
364 inst_fn e = mkHsDictApp (mkHsTyApp e (mkTyVarTys tyvars)) (map instToId dicts)
366 returnNF_Tc (inst_fn, mkLIE dicts, tau)
368 newMethod :: InstOrigin
372 newMethod orig id tys
373 = -- Get the Id type and instantiate it at the specified types
375 (tyvars, rho) = tcSplitForAllTys (idType id)
376 rho_ty = substTyWith tyvars tys rho
377 (pred, tau) = tcSplitMethodTy rho_ty
379 newMethodWithGivenTy orig id tys [pred] tau
381 newMethodWithGivenTy orig id tys theta tau
382 = tcGetInstLoc orig `thenNF_Tc` \ loc ->
383 newMethodWith loc id tys theta tau
385 newMethodWith inst_loc@(_,loc,_) id tys theta tau
386 = tcGetUnique `thenNF_Tc` \ new_uniq ->
388 meth_id = mkUserLocal (mkMethodOcc (getOccName id)) new_uniq tau loc
390 returnNF_Tc (Method meth_id id tys theta tau inst_loc)
392 newMethodAtLoc :: InstLoc
394 -> NF_TcM (Inst, TcId)
395 newMethodAtLoc inst_loc real_id tys
396 -- This actually builds the Inst
397 = -- Get the Id type and instantiate it at the specified types
399 (tyvars,rho) = tcSplitForAllTys (idType real_id)
400 rho_ty = ASSERT( equalLength tyvars tys )
401 substTy (mkTopTyVarSubst tyvars tys) rho
402 (theta, tau) = tcSplitPhiTy rho_ty
404 newMethodWith inst_loc real_id tys theta tau `thenNF_Tc` \ meth_inst ->
405 returnNF_Tc (meth_inst, instToId meth_inst)
408 In newOverloadedLit we convert directly to an Int or Integer if we
409 know that's what we want. This may save some time, by not
410 temporarily generating overloaded literals, but it won't catch all
411 cases (the rest are caught in lookupInst).
414 newOverloadedLit :: InstOrigin
417 -> NF_TcM (TcExpr, LIE)
418 newOverloadedLit orig lit expected_ty
419 | Just expr <- shortCutLit lit expected_ty
420 = returnNF_Tc (expr, emptyLIE)
423 = tcGetInstLoc orig `thenNF_Tc` \ loc ->
424 tcGetUnique `thenNF_Tc` \ new_uniq ->
425 zapToType expected_ty `thenNF_Tc_`
426 -- The expected type might be a 'hole' type variable,
427 -- in which case we must zap it to an ordinary type variable
429 lit_inst = LitInst lit_id lit expected_ty loc
430 lit_id = mkSysLocal FSLIT("lit") new_uniq expected_ty
432 returnNF_Tc (HsVar (instToId lit_inst), unitLIE lit_inst)
434 shortCutLit :: HsOverLit -> TcType -> Maybe TcExpr
435 shortCutLit (HsIntegral i fi) ty
436 | isIntTy ty && inIntRange i && fi == fromIntegerName -- Short cut for Int
437 = Just (HsLit (HsInt i))
438 | isIntegerTy ty && fi == fromIntegerName -- Short cut for Integer
439 = Just (HsLit (HsInteger i))
441 shortCutLit (HsFractional f fr) ty
442 | isFloatTy ty && fr == fromRationalName
443 = Just (mkHsConApp floatDataCon [] [HsLit (HsFloatPrim f)])
444 | isDoubleTy ty && fr == fromRationalName
445 = Just (mkHsConApp doubleDataCon [] [HsLit (HsDoublePrim f)])
452 %************************************************************************
456 %************************************************************************
458 Zonking makes sure that the instance types are fully zonked,
459 but doesn't do the same for any of the Ids in an Inst. There's no
460 need, and it's a lot of extra work.
463 zonkInst :: Inst -> NF_TcM Inst
464 zonkInst (Dict id pred loc)
465 = zonkTcPredType pred `thenNF_Tc` \ new_pred ->
466 returnNF_Tc (Dict id new_pred loc)
468 zonkInst (Method m id tys theta tau loc)
469 = zonkId id `thenNF_Tc` \ new_id ->
470 -- Essential to zonk the id in case it's a local variable
471 -- Can't use zonkIdOcc because the id might itself be
472 -- an InstId, in which case it won't be in scope
474 zonkTcTypes tys `thenNF_Tc` \ new_tys ->
475 zonkTcThetaType theta `thenNF_Tc` \ new_theta ->
476 zonkTcType tau `thenNF_Tc` \ new_tau ->
477 returnNF_Tc (Method m new_id new_tys new_theta new_tau loc)
479 zonkInst (LitInst id lit ty loc)
480 = zonkTcType ty `thenNF_Tc` \ new_ty ->
481 returnNF_Tc (LitInst id lit new_ty loc)
483 zonkInsts insts = mapNF_Tc zonkInst insts
487 %************************************************************************
489 \subsection{Printing}
491 %************************************************************************
493 ToDo: improve these pretty-printing things. The ``origin'' is really only
494 relevant in error messages.
497 instance Outputable Inst where
498 ppr inst = pprInst inst
500 pprInst (LitInst u lit ty loc)
501 = hsep [ppr lit, ptext SLIT("at"), ppr ty, show_uniq u]
503 pprInst (Dict u pred loc) = pprPred pred <+> show_uniq u
505 pprInst m@(Method u id tys theta tau loc)
506 = hsep [ppr id, ptext SLIT("at"),
507 brackets (sep (map pprParendType tys)) {- ,
508 ptext SLIT("theta"), ppr theta,
509 ptext SLIT("tau"), ppr tau
513 show_uniq u = ifPprDebug (text "{-" <> ppr u <> text "-}")
515 tidyInst :: TidyEnv -> Inst -> Inst
516 tidyInst env (LitInst u lit ty loc) = LitInst u lit (tidyType env ty) loc
517 tidyInst env (Dict u pred loc) = Dict u (tidyPred env pred) loc
518 tidyInst env (Method u id tys theta tau loc) = Method u id (tidyTypes env tys) theta tau loc
520 tidyMoreInsts :: TidyEnv -> [Inst] -> (TidyEnv, [Inst])
521 -- This function doesn't assume that the tyvars are in scope
522 -- so it works like tidyOpenType, returning a TidyEnv
523 tidyMoreInsts env insts
524 = (env', map (tidyInst env') insts)
526 env' = tidyFreeTyVars env (tyVarsOfInsts insts)
528 tidyInsts :: [Inst] -> (TidyEnv, [Inst])
529 tidyInsts insts = tidyMoreInsts emptyTidyEnv insts
533 %************************************************************************
535 \subsection{Looking up Insts}
537 %************************************************************************
540 data LookupInstResult s
542 | SimpleInst TcExpr -- Just a variable, type application, or literal
543 | GenInst [Inst] TcExpr -- The expression and its needed insts
546 -> NF_TcM (LookupInstResult s)
550 lookupInst dict@(Dict _ (ClassP clas tys) loc)
551 = getDOptsTc `thenNF_Tc` \ dflags ->
552 tcGetInstEnv `thenNF_Tc` \ inst_env ->
553 case lookupInstEnv dflags inst_env clas tys of
555 FoundInst tenv dfun_id
556 -> -- It's possible that not all the tyvars are in
557 -- the substitution, tenv. For example:
558 -- instance C X a => D X where ...
559 -- (presumably there's a functional dependency in class C)
560 -- Hence the mk_ty_arg to instantiate any un-substituted tyvars.
562 (tyvars, rho) = tcSplitForAllTys (idType dfun_id)
563 mk_ty_arg tv = case lookupSubstEnv tenv tv of
564 Just (DoneTy ty) -> returnNF_Tc ty
565 Nothing -> tcInstTyVar VanillaTv tv `thenNF_Tc` \ tc_tv ->
566 returnTc (mkTyVarTy tc_tv)
568 mapNF_Tc mk_ty_arg tyvars `thenNF_Tc` \ ty_args ->
570 dfun_rho = substTy (mkTyVarSubst tyvars ty_args) rho
571 (theta, _) = tcSplitPhiTy dfun_rho
572 ty_app = mkHsTyApp (HsVar dfun_id) ty_args
575 returnNF_Tc (SimpleInst ty_app)
577 newDictsAtLoc loc theta `thenNF_Tc` \ dicts ->
579 rhs = mkHsDictApp ty_app (map instToId dicts)
581 returnNF_Tc (GenInst dicts rhs)
583 other -> returnNF_Tc NoInstance
585 lookupInst dict@(Dict _ _ loc) = returnNF_Tc NoInstance
589 lookupInst inst@(Method _ id tys theta _ loc)
590 = newDictsAtLoc loc theta `thenNF_Tc` \ dicts ->
591 returnNF_Tc (GenInst dicts (mkHsDictApp (mkHsTyApp (HsVar id) tys) (map instToId dicts)))
595 -- Look for short cuts first: if the literal is *definitely* a
596 -- int, integer, float or a double, generate the real thing here.
597 -- This is essential (see nofib/spectral/nucleic).
598 -- [Same shortcut as in newOverloadedLit, but we
599 -- may have done some unification by now]
601 lookupInst inst@(LitInst u lit ty loc)
602 | Just expr <- shortCutLit lit ty
603 = returnNF_Tc (GenInst [] expr) -- GenInst, not SimpleInst, because
604 -- expr may be a constructor application
606 lookupInst inst@(LitInst u (HsIntegral i from_integer_name) ty loc)
607 = tcLookupId from_integer_name `thenNF_Tc` \ from_integer ->
608 newMethodAtLoc loc from_integer [ty] `thenNF_Tc` \ (method_inst, method_id) ->
609 returnNF_Tc (GenInst [method_inst]
610 (HsApp (HsVar method_id) (HsLit (HsInteger i))))
613 lookupInst inst@(LitInst u (HsFractional f from_rat_name) ty loc)
614 = tcLookupId from_rat_name `thenNF_Tc` \ from_rational ->
615 newMethodAtLoc loc from_rational [ty] `thenNF_Tc` \ (method_inst, method_id) ->
617 rational_ty = tcFunArgTy (idType method_id)
618 rational_lit = HsLit (HsRat f rational_ty)
620 returnNF_Tc (GenInst [method_inst] (HsApp (HsVar method_id) rational_lit))
623 There is a second, simpler interface, when you want an instance of a
624 class at a given nullary type constructor. It just returns the
625 appropriate dictionary if it exists. It is used only when resolving
626 ambiguous dictionaries.
629 lookupSimpleInst :: Class
630 -> [Type] -- Look up (c,t)
631 -> NF_TcM (Maybe ThetaType) -- Here are the needed (c,t)s
633 lookupSimpleInst clas tys
634 = getDOptsTc `thenNF_Tc` \ dflags ->
635 tcGetInstEnv `thenNF_Tc` \ inst_env ->
636 case lookupInstEnv dflags inst_env clas tys of
638 -> returnNF_Tc (Just (substTheta (mkSubst emptyInScopeSet tenv) theta))
640 (_, rho) = tcSplitForAllTys (idType dfun)
641 (theta,_) = tcSplitPhiTy rho
643 other -> returnNF_Tc Nothing