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, newMethodFromName, newMethodWithGivenTy, newMethodAtLoc,
16 newOverloadedLit, newIPDict,
17 tcInstCall, tcInstDataCon, tcSyntaxName,
19 tyVarsOfInst, tyVarsOfInsts, tyVarsOfLIE,
20 ipNamesOfInst, ipNamesOfInsts, predsOfInst, predsOfInsts,
21 instLoc, getDictClassTys, dictPred,
23 lookupInst, lookupSimpleInst, LookupInstResult(..),
25 isDict, isClassDict, isMethod,
26 isLinearInst, linearInstType,
27 isTyVarDict, isStdClassTyVarDict, isMethodFor,
28 instBindingRequired, instCanBeGeneralised,
33 InstOrigin(..), InstLoc, pprInstLoc
36 #include "HsVersions.h"
38 import {-# SOURCE #-} TcExpr( tcExpr )
40 import HsSyn ( HsLit(..), HsOverLit(..), HsExpr(..) )
41 import TcHsSyn ( TcExpr, TcId, TypecheckedHsExpr,
42 mkHsTyApp, mkHsDictApp, mkHsConApp, zonkId
45 import TcEnv ( TcIdSet, tcGetInstEnv, tcLookupId, tcLookupGlobalId, tcLookupTyCon )
46 import InstEnv ( InstLookupResult(..), lookupInstEnv )
47 import TcMType ( zonkTcType, zonkTcTypes, zonkTcPredType, zapToType,
48 zonkTcThetaType, tcInstTyVar, tcInstType, tcInstTyVars
50 import TcType ( Type, TcType, TcThetaType, TcPredType, TcTauType, TcTyVarSet,
51 SourceType(..), PredType, ThetaType, TyVarDetails(VanillaTv),
52 tcSplitForAllTys, tcSplitForAllTys, mkTyConApp,
53 tcSplitMethodTy, tcSplitPhiTy, mkGenTyConApp,
54 isIntTy,isFloatTy, isIntegerTy, isDoubleTy,
55 tcIsTyVarTy, mkPredTy, mkTyVarTy, mkTyVarTys,
56 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tidyPred,
57 isClassPred, isTyVarClassPred, isLinearPred,
58 getClassPredTys, getClassPredTys_maybe, mkPredName,
59 tidyType, tidyTypes, tidyFreeTyVars,
60 tcCmpType, tcCmpTypes, tcCmpPred, tcSplitSigmaTy
62 import CoreFVs ( idFreeTyVars )
63 import Class ( Class )
64 import DataCon ( dataConSig )
65 import Id ( Id, idName, idType, mkUserLocal, mkSysLocal, mkLocalId, setIdUnique )
66 import PrelInfo ( isStandardClass, isCcallishClass, isNoDictClass )
67 import Name ( Name, mkMethodOcc, getOccName )
68 import PprType ( pprPred, pprParendType )
69 import Subst ( emptyInScopeSet, mkSubst,
70 substTy, substTyWith, substTheta, mkTyVarSubst, mkTopTyVarSubst
72 import Literal ( inIntRange )
73 import VarEnv ( TidyEnv, lookupSubstEnv, SubstResult(..) )
74 import VarSet ( elemVarSet, emptyVarSet, unionVarSet )
75 import TysWiredIn ( floatDataCon, doubleDataCon )
76 import PrelNames( fromIntegerName, fromRationalName, rationalTyConName )
77 import Util ( thenCmp, equalLength )
78 import BasicTypes( IPName(..), mapIPName, ipNameName )
84 %************************************************************************
86 \subsection[Inst-collections]{LIE: a collection of Insts}
88 %************************************************************************
93 isEmptyLIE = isEmptyBag
95 unitLIE inst = unitBag inst
96 mkLIE insts = listToBag insts
97 plusLIE lie1 lie2 = lie1 `unionBags` lie2
98 consLIE inst lie = inst `consBag` lie
99 plusLIEs lies = unionManyBags lies
100 lieToList = bagToList
101 listToLIE = listToBag
103 zonkLIE :: LIE -> NF_TcM LIE
104 zonkLIE lie = mapBagNF_Tc zonkInst lie
106 pprInsts :: [Inst] -> SDoc
107 pprInsts insts = parens (sep (punctuate comma (map pprInst insts)))
111 = vcat (map go insts)
113 go inst = quotes (ppr inst) <+> pprInstLoc (instLoc inst)
116 %************************************************************************
118 \subsection[Inst-types]{@Inst@ types}
120 %************************************************************************
122 An @Inst@ is either a dictionary, an instance of an overloaded
123 literal, or an instance of an overloaded value. We call the latter a
124 ``method'' even though it may not correspond to a class operation.
125 For example, we might have an instance of the @double@ function at
126 type Int, represented by
128 Method 34 doubleId [Int] origin
140 TcId -- The overloaded function
141 -- This function will be a global, local, or ClassOpId;
142 -- inside instance decls (only) it can also be an InstId!
143 -- The id needn't be completely polymorphic.
144 -- You'll probably find its name (for documentation purposes)
145 -- inside the InstOrigin
147 [TcType] -- The types to which its polymorphic tyvars
148 -- should be instantiated.
149 -- These types must saturate the Id's foralls.
151 TcThetaType -- The (types of the) dictionaries to which the function
152 -- must be applied to get the method
154 TcTauType -- The type of the method
158 -- INVARIANT: in (Method u f tys theta tau loc)
159 -- type of (f tys dicts(from theta)) = tau
163 HsOverLit -- The literal from the occurrence site
164 -- INVARIANT: never a rebindable-syntax literal
165 -- Reason: tcSyntaxName does unification, and we
166 -- don't want to deal with that during tcSimplify
167 TcType -- The type at which the literal is used
173 @Insts@ are ordered by their class/type info, rather than by their
174 unique. This allows the context-reduction mechanism to use standard finite
175 maps to do their stuff.
178 instance Ord Inst where
181 instance Eq Inst where
182 (==) i1 i2 = case i1 `cmpInst` i2 of
186 cmpInst (Dict _ pred1 _) (Dict _ pred2 _) = pred1 `tcCmpPred` pred2
187 cmpInst (Dict _ _ _) other = LT
189 cmpInst (Method _ _ _ _ _ _) (Dict _ _ _) = GT
190 cmpInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
191 cmpInst (Method _ _ _ _ _ _) other = LT
193 cmpInst (LitInst _ lit1 ty1 _) (LitInst _ lit2 ty2 _) = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
194 cmpInst (LitInst _ _ _ _) other = GT
196 -- and they can only have HsInt or HsFracs in them.
203 instName :: Inst -> Name
204 instName inst = idName (instToId inst)
206 instToId :: Inst -> TcId
207 instToId (Dict id _ _) = id
208 instToId (Method id _ _ _ _ _) = id
209 instToId (LitInst id _ _ _) = id
211 instLoc (Dict _ _ loc) = loc
212 instLoc (Method _ _ _ _ _ loc) = loc
213 instLoc (LitInst _ _ _ loc) = loc
215 dictPred (Dict _ pred _ ) = pred
216 dictPred inst = pprPanic "dictPred" (ppr inst)
218 getDictClassTys (Dict _ pred _) = getClassPredTys pred
220 predsOfInsts :: [Inst] -> [PredType]
221 predsOfInsts insts = concatMap predsOfInst insts
223 predsOfInst (Dict _ pred _) = [pred]
224 predsOfInst (Method _ _ _ theta _ _) = theta
225 predsOfInst (LitInst _ _ _ _) = []
226 -- The last case is is really a big cheat
227 -- LitInsts to give rise to a (Num a) or (Fractional a) predicate
228 -- But Num and Fractional have only one parameter and no functional
229 -- dependencies, so I think no caller of predsOfInst will care.
231 ipNamesOfInsts :: [Inst] -> [Name]
232 ipNamesOfInst :: Inst -> [Name]
233 -- Get the implicit parameters mentioned by these Insts
234 -- NB: ?x and %x get different Names
236 ipNamesOfInsts insts = [n | inst <- insts, n <- ipNamesOfInst inst]
238 ipNamesOfInst (Dict _ (IParam n _) _) = [ipNameName n]
239 ipNamesOfInst (Method _ _ _ theta _ _) = [ipNameName n | IParam n _ <- theta]
240 ipNamesOfInst other = []
242 tyVarsOfInst :: Inst -> TcTyVarSet
243 tyVarsOfInst (LitInst _ _ ty _) = tyVarsOfType ty
244 tyVarsOfInst (Dict _ pred _) = tyVarsOfPred pred
245 tyVarsOfInst (Method _ id tys _ _ _) = tyVarsOfTypes tys `unionVarSet` idFreeTyVars id
246 -- The id might have free type variables; in the case of
247 -- locally-overloaded class methods, for example
249 tyVarsOfInsts insts = foldr (unionVarSet . tyVarsOfInst) emptyVarSet insts
250 tyVarsOfLIE lie = tyVarsOfInsts (lieToList lie)
256 isDict :: Inst -> Bool
257 isDict (Dict _ _ _) = True
260 isClassDict :: Inst -> Bool
261 isClassDict (Dict _ pred _) = isClassPred pred
262 isClassDict other = False
264 isTyVarDict :: Inst -> Bool
265 isTyVarDict (Dict _ pred _) = isTyVarClassPred pred
266 isTyVarDict other = False
268 isMethod :: Inst -> Bool
269 isMethod (Method _ _ _ _ _ _) = True
270 isMethod other = False
272 isMethodFor :: TcIdSet -> Inst -> Bool
273 isMethodFor ids (Method uniq id tys _ _ loc) = id `elemVarSet` ids
274 isMethodFor ids inst = False
276 isLinearInst :: Inst -> Bool
277 isLinearInst (Dict _ pred _) = isLinearPred pred
278 isLinearInst other = False
279 -- We never build Method Insts that have
280 -- linear implicit paramters in them.
281 -- Hence no need to look for Methods
284 linearInstType :: Inst -> TcType -- %x::t --> t
285 linearInstType (Dict _ (IParam _ ty) _) = ty
288 isStdClassTyVarDict (Dict _ pred _) = case getClassPredTys_maybe pred of
289 Just (clas, [ty]) -> isStandardClass clas && tcIsTyVarTy ty
293 Two predicates which deal with the case where class constraints don't
294 necessarily result in bindings. The first tells whether an @Inst@
295 must be witnessed by an actual binding; the second tells whether an
296 @Inst@ can be generalised over.
299 instBindingRequired :: Inst -> Bool
300 instBindingRequired (Dict _ (ClassP clas _) _) = not (isNoDictClass clas)
301 instBindingRequired other = True
303 instCanBeGeneralised :: Inst -> Bool
304 instCanBeGeneralised (Dict _ (ClassP clas _) _) = not (isCcallishClass clas)
305 instCanBeGeneralised other = True
309 %************************************************************************
311 \subsection{Building dictionaries}
313 %************************************************************************
316 newDicts :: InstOrigin
320 = tcGetInstLoc orig `thenNF_Tc` \ loc ->
321 newDictsAtLoc loc theta
323 cloneDict :: Inst -> NF_TcM Inst
324 cloneDict (Dict id ty loc) = tcGetUnique `thenNF_Tc` \ uniq ->
325 returnNF_Tc (Dict (setIdUnique id uniq) ty loc)
327 newDictsFromOld :: Inst -> TcThetaType -> NF_TcM [Inst]
328 newDictsFromOld (Dict _ _ loc) theta = newDictsAtLoc loc theta
330 -- Local function, similar to newDicts,
331 -- but with slightly different interface
332 newDictsAtLoc :: InstLoc
335 newDictsAtLoc inst_loc@(_,loc,_) theta
336 = tcGetUniques `thenNF_Tc` \ new_uniqs ->
337 returnNF_Tc (zipWith mk_dict new_uniqs theta)
339 mk_dict uniq pred = Dict (mkLocalId (mkPredName uniq loc pred) (mkPredTy pred)) pred inst_loc
341 -- For vanilla implicit parameters, there is only one in scope
342 -- at any time, so we used to use the name of the implicit parameter itself
343 -- But with splittable implicit parameters there may be many in
344 -- scope, so we make up a new name.
345 newIPDict :: InstOrigin -> IPName Name -> Type
346 -> NF_TcM (IPName Id, Inst)
347 newIPDict orig ip_name ty
348 = tcGetInstLoc orig `thenNF_Tc` \ inst_loc@(_,loc,_) ->
349 tcGetUnique `thenNF_Tc` \ uniq ->
351 pred = IParam ip_name ty
352 id = mkLocalId (mkPredName uniq loc pred) (mkPredTy pred)
354 returnNF_Tc (mapIPName (\n -> id) ip_name, Dict id pred inst_loc)
358 %************************************************************************
360 \subsection{Building methods (calls of overloaded functions)}
362 %************************************************************************
366 tcInstCall :: InstOrigin -> TcType -> NF_TcM (TypecheckedHsExpr -> TypecheckedHsExpr, LIE, TcType)
367 tcInstCall orig fun_ty -- fun_ty is usually a sigma-type
368 = tcInstType VanillaTv fun_ty `thenNF_Tc` \ (tyvars, theta, tau) ->
369 newDicts orig theta `thenNF_Tc` \ dicts ->
371 inst_fn e = mkHsDictApp (mkHsTyApp e (mkTyVarTys tyvars)) (map instToId dicts)
373 returnNF_Tc (inst_fn, mkLIE dicts, tau)
375 tcInstDataCon orig data_con
377 (tvs, stupid_theta, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
378 -- We generate constraints for the stupid theta even when
379 -- pattern matching (as the Report requires)
381 tcInstTyVars VanillaTv (tvs ++ ex_tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
383 stupid_theta' = substTheta tenv stupid_theta
384 ex_theta' = substTheta tenv ex_theta
385 arg_tys' = map (substTy tenv) arg_tys
387 n_normal_tvs = length tvs
388 ex_tvs' = drop n_normal_tvs all_tvs'
389 result_ty = mkTyConApp tycon (take n_normal_tvs ty_args')
391 newDicts orig stupid_theta' `thenNF_Tc` \ stupid_dicts ->
392 newDicts orig ex_theta' `thenNF_Tc` \ ex_dicts ->
394 -- Note that we return the stupid theta *only* in the LIE;
395 -- we don't otherwise use it at all
396 returnNF_Tc (ty_args', map instToId ex_dicts, arg_tys', result_ty,
397 mkLIE stupid_dicts, mkLIE ex_dicts, ex_tvs')
400 newMethodFromName :: InstOrigin -> TcType -> Name -> NF_TcM Inst
401 newMethodFromName origin ty name
402 = tcLookupId name `thenNF_Tc` \ id ->
403 -- Use tcLookupId not tcLookupGlobalId; the method is almost
404 -- always a class op, but with -fno-implicit-prelude GHC is
405 -- meant to find whatever thing is in scope, and that may
406 -- be an ordinary function.
407 newMethod origin id [ty]
409 newMethod :: InstOrigin
413 newMethod orig id tys
414 = -- Get the Id type and instantiate it at the specified types
416 (tyvars, rho) = tcSplitForAllTys (idType id)
417 rho_ty = substTyWith tyvars tys rho
418 (pred, tau) = tcSplitMethodTy rho_ty
420 newMethodWithGivenTy orig id tys [pred] tau
422 newMethodWithGivenTy orig id tys theta tau
423 = tcGetInstLoc orig `thenNF_Tc` \ loc ->
424 newMethodWith loc id tys theta tau
426 newMethodWith inst_loc@(_,loc,_) id tys theta tau
427 = tcGetUnique `thenNF_Tc` \ new_uniq ->
429 meth_id = mkUserLocal (mkMethodOcc (getOccName id)) new_uniq tau loc
431 returnNF_Tc (Method meth_id id tys theta tau inst_loc)
433 newMethodAtLoc :: InstLoc
435 -> NF_TcM (Inst, TcId)
436 newMethodAtLoc inst_loc real_id tys
437 -- This actually builds the Inst
438 = -- Get the Id type and instantiate it at the specified types
440 (tyvars,rho) = tcSplitForAllTys (idType real_id)
441 rho_ty = ASSERT( equalLength tyvars tys )
442 substTy (mkTopTyVarSubst tyvars tys) rho
443 (theta, tau) = tcSplitPhiTy rho_ty
445 newMethodWith inst_loc real_id tys theta tau `thenNF_Tc` \ meth_inst ->
446 returnNF_Tc (meth_inst, instToId meth_inst)
449 In newOverloadedLit we convert directly to an Int or Integer if we
450 know that's what we want. This may save some time, by not
451 temporarily generating overloaded literals, but it won't catch all
452 cases (the rest are caught in lookupInst).
455 newOverloadedLit :: InstOrigin
458 -> NF_TcM (TcExpr, LIE)
459 newOverloadedLit orig lit@(HsIntegral i fi) expected_ty
460 | fi /= fromIntegerName -- Do not generate a LitInst for rebindable
461 -- syntax. Reason: tcSyntaxName does unification
462 -- which is very inconvenient in tcSimplify
463 = tcSyntaxName orig expected_ty fromIntegerName fi `thenTc` \ (expr, lie, _) ->
464 returnTc (HsApp expr (HsLit (HsInteger i)), lie)
466 | Just expr <- shortCutIntLit i expected_ty
467 = returnNF_Tc (expr, emptyLIE)
470 = newLitInst orig lit expected_ty
472 newOverloadedLit orig lit@(HsFractional r fr) expected_ty
473 | fr /= fromRationalName -- c.f. HsIntegral case
474 = tcSyntaxName orig expected_ty fromRationalName fr `thenTc` \ (expr, lie, _) ->
475 mkRatLit r `thenNF_Tc` \ rat_lit ->
476 returnTc (HsApp expr rat_lit, lie)
478 | Just expr <- shortCutFracLit r expected_ty
479 = returnNF_Tc (expr, emptyLIE)
482 = newLitInst orig lit expected_ty
484 newLitInst orig lit expected_ty
485 = tcGetInstLoc orig `thenNF_Tc` \ loc ->
486 tcGetUnique `thenNF_Tc` \ new_uniq ->
487 zapToType expected_ty `thenNF_Tc_`
488 -- The expected type might be a 'hole' type variable,
489 -- in which case we must zap it to an ordinary type variable
491 lit_inst = LitInst lit_id lit expected_ty loc
492 lit_id = mkSysLocal FSLIT("lit") new_uniq expected_ty
494 returnNF_Tc (HsVar (instToId lit_inst), unitLIE lit_inst)
496 shortCutIntLit :: Integer -> TcType -> Maybe TcExpr
498 | isIntTy ty && inIntRange i -- Short cut for Int
499 = Just (HsLit (HsInt i))
500 | isIntegerTy ty -- Short cut for Integer
501 = Just (HsLit (HsInteger i))
502 | otherwise = Nothing
504 shortCutFracLit :: Rational -> TcType -> Maybe TcExpr
507 = Just (mkHsConApp floatDataCon [] [HsLit (HsFloatPrim f)])
509 = Just (mkHsConApp doubleDataCon [] [HsLit (HsDoublePrim f)])
510 | otherwise = Nothing
512 mkRatLit :: Rational -> NF_TcM TcExpr
514 = tcLookupTyCon rationalTyConName `thenNF_Tc` \ rat_tc ->
516 rational_ty = mkGenTyConApp rat_tc []
518 returnNF_Tc (HsLit (HsRat r rational_ty))
522 %************************************************************************
526 %************************************************************************
528 Zonking makes sure that the instance types are fully zonked,
529 but doesn't do the same for any of the Ids in an Inst. There's no
530 need, and it's a lot of extra work.
533 zonkInst :: Inst -> NF_TcM Inst
534 zonkInst (Dict id pred loc)
535 = zonkTcPredType pred `thenNF_Tc` \ new_pred ->
536 returnNF_Tc (Dict id new_pred loc)
538 zonkInst (Method m id tys theta tau loc)
539 = zonkId id `thenNF_Tc` \ new_id ->
540 -- Essential to zonk the id in case it's a local variable
541 -- Can't use zonkIdOcc because the id might itself be
542 -- an InstId, in which case it won't be in scope
544 zonkTcTypes tys `thenNF_Tc` \ new_tys ->
545 zonkTcThetaType theta `thenNF_Tc` \ new_theta ->
546 zonkTcType tau `thenNF_Tc` \ new_tau ->
547 returnNF_Tc (Method m new_id new_tys new_theta new_tau loc)
549 zonkInst (LitInst id lit ty loc)
550 = zonkTcType ty `thenNF_Tc` \ new_ty ->
551 returnNF_Tc (LitInst id lit new_ty loc)
553 zonkInsts insts = mapNF_Tc zonkInst insts
557 %************************************************************************
559 \subsection{Printing}
561 %************************************************************************
563 ToDo: improve these pretty-printing things. The ``origin'' is really only
564 relevant in error messages.
567 instance Outputable Inst where
568 ppr inst = pprInst inst
570 pprInst (LitInst u lit ty loc)
571 = hsep [ppr lit, ptext SLIT("at"), ppr ty, show_uniq u]
573 pprInst (Dict u pred loc) = pprPred pred <+> show_uniq u
575 pprInst m@(Method u id tys theta tau loc)
576 = hsep [ppr id, ptext SLIT("at"),
577 brackets (sep (map pprParendType tys)) {- ,
578 ptext SLIT("theta"), ppr theta,
579 ptext SLIT("tau"), ppr tau
583 show_uniq u = ifPprDebug (text "{-" <> ppr u <> text "-}")
585 tidyInst :: TidyEnv -> Inst -> Inst
586 tidyInst env (LitInst u lit ty loc) = LitInst u lit (tidyType env ty) loc
587 tidyInst env (Dict u pred loc) = Dict u (tidyPred env pred) loc
588 tidyInst env (Method u id tys theta tau loc) = Method u id (tidyTypes env tys) theta tau loc
590 tidyMoreInsts :: TidyEnv -> [Inst] -> (TidyEnv, [Inst])
591 -- This function doesn't assume that the tyvars are in scope
592 -- so it works like tidyOpenType, returning a TidyEnv
593 tidyMoreInsts env insts
594 = (env', map (tidyInst env') insts)
596 env' = tidyFreeTyVars env (tyVarsOfInsts insts)
598 tidyInsts :: [Inst] -> (TidyEnv, [Inst])
599 tidyInsts insts = tidyMoreInsts emptyTidyEnv insts
603 %************************************************************************
605 \subsection{Looking up Insts}
607 %************************************************************************
610 data LookupInstResult s
612 | SimpleInst TcExpr -- Just a variable, type application, or literal
613 | GenInst [Inst] TcExpr -- The expression and its needed insts
616 -> NF_TcM (LookupInstResult s)
620 lookupInst dict@(Dict _ (ClassP clas tys) loc)
621 = getDOptsTc `thenNF_Tc` \ dflags ->
622 tcGetInstEnv `thenNF_Tc` \ inst_env ->
623 case lookupInstEnv dflags inst_env clas tys of
625 FoundInst tenv dfun_id
626 -> -- It's possible that not all the tyvars are in
627 -- the substitution, tenv. For example:
628 -- instance C X a => D X where ...
629 -- (presumably there's a functional dependency in class C)
630 -- Hence the mk_ty_arg to instantiate any un-substituted tyvars.
632 (tyvars, rho) = tcSplitForAllTys (idType dfun_id)
633 mk_ty_arg tv = case lookupSubstEnv tenv tv of
634 Just (DoneTy ty) -> returnNF_Tc ty
635 Nothing -> tcInstTyVar VanillaTv tv `thenNF_Tc` \ tc_tv ->
636 returnTc (mkTyVarTy tc_tv)
638 mapNF_Tc mk_ty_arg tyvars `thenNF_Tc` \ ty_args ->
640 dfun_rho = substTy (mkTyVarSubst tyvars ty_args) rho
641 (theta, _) = tcSplitPhiTy dfun_rho
642 ty_app = mkHsTyApp (HsVar dfun_id) ty_args
645 returnNF_Tc (SimpleInst ty_app)
647 newDictsAtLoc loc theta `thenNF_Tc` \ dicts ->
649 rhs = mkHsDictApp ty_app (map instToId dicts)
651 returnNF_Tc (GenInst dicts rhs)
653 other -> returnNF_Tc NoInstance
655 lookupInst dict@(Dict _ _ loc) = returnNF_Tc NoInstance
659 lookupInst inst@(Method _ id tys theta _ loc)
660 = newDictsAtLoc loc theta `thenNF_Tc` \ dicts ->
661 returnNF_Tc (GenInst dicts (mkHsDictApp (mkHsTyApp (HsVar id) tys) (map instToId dicts)))
665 -- Look for short cuts first: if the literal is *definitely* a
666 -- int, integer, float or a double, generate the real thing here.
667 -- This is essential (see nofib/spectral/nucleic).
668 -- [Same shortcut as in newOverloadedLit, but we
669 -- may have done some unification by now]
671 lookupInst inst@(LitInst u (HsIntegral i from_integer_name) ty loc)
672 | Just expr <- shortCutIntLit i ty
673 = returnNF_Tc (GenInst [] expr) -- GenInst, not SimpleInst, because
674 -- expr may be a constructor application
676 = ASSERT( from_integer_name == fromIntegerName ) -- A LitInst invariant
677 tcLookupGlobalId fromIntegerName `thenNF_Tc` \ from_integer ->
678 newMethodAtLoc loc from_integer [ty] `thenNF_Tc` \ (method_inst, method_id) ->
679 returnNF_Tc (GenInst [method_inst]
680 (HsApp (HsVar method_id) (HsLit (HsInteger i))))
683 lookupInst inst@(LitInst u (HsFractional f from_rat_name) ty loc)
684 | Just expr <- shortCutFracLit f ty
685 = returnNF_Tc (GenInst [] expr)
688 = ASSERT( from_rat_name == fromRationalName ) -- A LitInst invariant
689 tcLookupGlobalId fromRationalName `thenNF_Tc` \ from_rational ->
690 newMethodAtLoc loc from_rational [ty] `thenNF_Tc` \ (method_inst, method_id) ->
691 mkRatLit f `thenNF_Tc` \ rat_lit ->
692 returnNF_Tc (GenInst [method_inst] (HsApp (HsVar method_id) rat_lit))
695 There is a second, simpler interface, when you want an instance of a
696 class at a given nullary type constructor. It just returns the
697 appropriate dictionary if it exists. It is used only when resolving
698 ambiguous dictionaries.
701 lookupSimpleInst :: Class
702 -> [Type] -- Look up (c,t)
703 -> NF_TcM (Maybe ThetaType) -- Here are the needed (c,t)s
705 lookupSimpleInst clas tys
706 = getDOptsTc `thenNF_Tc` \ dflags ->
707 tcGetInstEnv `thenNF_Tc` \ inst_env ->
708 case lookupInstEnv dflags inst_env clas tys of
710 -> returnNF_Tc (Just (substTheta (mkSubst emptyInScopeSet tenv) theta))
712 (_, rho) = tcSplitForAllTys (idType dfun)
713 (theta,_) = tcSplitPhiTy rho
715 other -> returnNF_Tc Nothing
719 %************************************************************************
723 %************************************************************************
726 Suppose we are doing the -fno-implicit-prelude thing, and we encounter
727 a do-expression. We have to find (>>) in the current environment, which is
728 done by the rename. Then we have to check that it has the same type as
729 Control.Monad.(>>). Or, more precisely, a compatible type. One 'customer' had
732 (>>) :: HB m n mn => m a -> n b -> mn b
734 So the idea is to generate a local binding for (>>), thus:
736 let then72 :: forall a b. m a -> m b -> m b
737 then72 = ...something involving the user's (>>)...
739 ...the do-expression...
741 Now the do-expression can proceed using then72, which has exactly
744 In fact tcSyntaxName just generates the RHS for then72, because we only
745 want an actual binding in the do-expression case. For literals, we can
746 just use the expression inline.
749 tcSyntaxName :: InstOrigin
750 -> TcType -- Type to instantiate it at
751 -> Name -> Name -- (Standard name, user name)
752 -> TcM (TcExpr, LIE, TcType) -- Suitable expression with its type
754 -- NB: tcSyntaxName calls tcExpr, and hence can do unification.
755 -- So we do not call it from lookupInst, which is called from tcSimplify
757 tcSyntaxName orig ty std_nm user_nm
759 = newMethodFromName orig ty std_nm `thenNF_Tc` \ inst ->
763 returnTc (HsVar id, unitLIE inst, idType id)
766 = tcLookupGlobalId std_nm `thenNF_Tc` \ std_id ->
768 -- C.f. newMethodAtLoc
769 ([tv], _, tau) = tcSplitSigmaTy (idType std_id)
770 tau1 = substTy (mkTopTyVarSubst [tv] [ty]) tau
772 tcAddErrCtxtM (syntaxNameCtxt user_nm orig tau1) $
773 tcExpr (HsVar user_nm) tau1 `thenTc` \ (user_fn, lie) ->
774 returnTc (user_fn, lie, tau1)
776 syntaxNameCtxt name orig ty tidy_env
777 = tcGetInstLoc orig `thenNF_Tc` \ inst_loc ->
779 msg = vcat [ptext SLIT("When checking that") <+> quotes (ppr name) <+>
780 ptext SLIT("(needed by a syntactic construct)"),
781 nest 2 (ptext SLIT("has the required type:") <+> ppr (tidyType tidy_env ty)),
782 nest 2 (pprInstLoc inst_loc)]
784 returnNF_Tc (tidy_env, msg)