2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 The @Inst@ type: dictionaries or method instances
12 pprInstances, pprDictsTheta, pprDictsInFull, -- User error messages
13 showLIE, pprInst, pprInsts, pprInstInFull, -- Debugging messages
15 tidyInsts, tidyMoreInsts,
17 newDictBndr, newDictBndrs, newDictBndrsO,
18 instCall, instStupidTheta,
20 shortCutFracLit, shortCutIntLit, newIPDict,
21 newMethod, newMethodFromName, newMethodWithGivenTy,
23 tcSyntaxName, isHsVar,
25 tyVarsOfInst, tyVarsOfInsts, tyVarsOfLIE,
26 ipNamesOfInst, ipNamesOfInsts, fdPredsOfInst, fdPredsOfInsts,
27 instLoc, getDictClassTys, dictPred,
29 lookupInst, LookupInstResult(..), lookupPred,
30 tcExtendLocalInstEnv, tcGetInstEnvs, getOverlapFlag,
32 isDict, isClassDict, isMethod,
33 isIPDict, isInheritableInst,
34 isTyVarDict, isMethodFor,
37 instToId, instToVar, instName,
39 InstOrigin(..), InstLoc(..), pprInstLoc
42 #include "HsVersions.h"
44 import {-# SOURCE #-} TcExpr( tcPolyExpr )
45 import {-# SOURCE #-} TcUnify( unifyType )
66 import Var ( Var, TyVar )
83 instName :: Inst -> Name
84 instName inst = idName (instToId inst)
86 instToId :: Inst -> TcId
87 instToId inst = ASSERT2( isId id, ppr inst ) id
91 instToVar :: Inst -> Var
92 instToVar (LitInst nm _ ty _) = mkLocalId nm ty
93 instToVar (Method id _ _ _ _) = id
94 instToVar (Dict nm pred _)
95 | isEqPred pred = Var.mkTyVar nm (mkPredTy pred)
96 | otherwise = mkLocalId nm (mkPredTy pred)
98 instLoc (Dict _ _ loc) = loc
99 instLoc (Method _ _ _ _ loc) = loc
100 instLoc (LitInst _ _ _ loc) = loc
102 dictPred (Dict _ pred _ ) = pred
103 dictPred inst = pprPanic "dictPred" (ppr inst)
105 getDictClassTys (Dict _ pred _) = getClassPredTys pred
107 -- fdPredsOfInst is used to get predicates that contain functional
108 -- dependencies *or* might do so. The "might do" part is because
109 -- a constraint (C a b) might have a superclass with FDs
110 -- Leaving these in is really important for the call to fdPredsOfInsts
111 -- in TcSimplify.inferLoop, because the result is fed to 'grow',
112 -- which is supposed to be conservative
113 fdPredsOfInst (Dict _ pred _) = [pred]
114 fdPredsOfInst (Method _ _ _ theta _) = theta
115 fdPredsOfInst other = [] -- LitInsts etc
117 fdPredsOfInsts :: [Inst] -> [PredType]
118 fdPredsOfInsts insts = concatMap fdPredsOfInst insts
120 isInheritableInst (Dict _ pred _) = isInheritablePred pred
121 isInheritableInst (Method _ _ _ theta _) = all isInheritablePred theta
122 isInheritableInst other = True
125 ipNamesOfInsts :: [Inst] -> [Name]
126 ipNamesOfInst :: Inst -> [Name]
127 -- Get the implicit parameters mentioned by these Insts
128 -- NB: ?x and %x get different Names
129 ipNamesOfInsts insts = [n | inst <- insts, n <- ipNamesOfInst inst]
131 ipNamesOfInst (Dict _ (IParam n _) _) = [ipNameName n]
132 ipNamesOfInst (Method _ _ _ theta _) = [ipNameName n | IParam n _ <- theta]
133 ipNamesOfInst other = []
135 tyVarsOfInst :: Inst -> TcTyVarSet
136 tyVarsOfInst (LitInst _ _ ty _) = tyVarsOfType ty
137 tyVarsOfInst (Dict _ pred _) = tyVarsOfPred pred
138 tyVarsOfInst (Method _ id tys _ _) = tyVarsOfTypes tys `unionVarSet` idFreeTyVars id
139 -- The id might have free type variables; in the case of
140 -- locally-overloaded class methods, for example
143 tyVarsOfInsts insts = foldr (unionVarSet . tyVarsOfInst) emptyVarSet insts
144 tyVarsOfLIE lie = tyVarsOfInsts (lieToList lie)
150 isDict :: Inst -> Bool
151 isDict (Dict _ _ _) = True
154 isClassDict :: Inst -> Bool
155 isClassDict (Dict _ pred _) = isClassPred pred
156 isClassDict other = False
158 isTyVarDict :: Inst -> Bool
159 isTyVarDict (Dict _ pred _) = isTyVarClassPred pred
160 isTyVarDict other = False
162 isIPDict :: Inst -> Bool
163 isIPDict (Dict _ pred _) = isIPPred pred
164 isIPDict other = False
166 isMethod :: Inst -> Bool
167 isMethod (Method {}) = True
168 isMethod other = False
170 isMethodFor :: TcIdSet -> Inst -> Bool
171 isMethodFor ids (Method uniq id tys _ loc) = id `elemVarSet` ids
172 isMethodFor ids inst = False
177 %************************************************************************
179 \subsection{Building dictionaries}
181 %************************************************************************
183 -- newDictBndrs makes a dictionary at a binding site
184 -- instCall makes a dictionary at an occurrence site
185 -- and throws it into the LIE
189 newDictBndrsO :: InstOrigin -> TcThetaType -> TcM [Inst]
190 newDictBndrsO orig theta = do { loc <- getInstLoc orig
191 ; newDictBndrs loc theta }
193 newDictBndrs :: InstLoc -> TcThetaType -> TcM [Inst]
194 newDictBndrs inst_loc theta = mapM (newDictBndr inst_loc) theta
196 newDictBndr :: InstLoc -> TcPredType -> TcM Inst
197 newDictBndr inst_loc pred
198 = do { uniq <- newUnique
199 ; let name = mkPredName uniq (instLocSrcLoc inst_loc) pred
200 ; return (Dict name pred inst_loc) }
203 instCall :: InstOrigin -> [TcType] -> TcThetaType -> TcM HsWrapper
204 -- Instantiate the constraints of a call
205 -- (instCall o tys theta)
206 -- (a) Makes fresh dictionaries as necessary for the constraints (theta)
207 -- (b) Throws these dictionaries into the LIE
208 -- (c) Eeturns an HsWrapper ([.] tys dicts)
210 instCall orig tys theta
211 = do { loc <- getInstLoc orig
212 ; (dicts, dict_app) <- instCallDicts loc theta
214 ; return (dict_app <.> mkWpTyApps tys) }
217 instStupidTheta :: InstOrigin -> TcThetaType -> TcM ()
218 -- Similar to instCall, but only emit the constraints in the LIE
219 -- Used exclusively for the 'stupid theta' of a data constructor
220 instStupidTheta orig theta
221 = do { loc <- getInstLoc orig
222 ; (dicts, _) <- instCallDicts loc theta
226 instCallDicts :: InstLoc -> TcThetaType -> TcM ([Inst], HsWrapper)
227 -- This is the key place where equality predicates
228 -- are unleashed into the world
229 instCallDicts loc [] = return ([], idHsWrapper)
231 instCallDicts loc (EqPred ty1 ty2 : preds)
232 = do { unifyType ty1 ty2 -- For now, we insist that they unify right away
233 -- Later on, when we do associated types,
234 -- unifyType :: Type -> Type -> TcM ([Inst], Coercion)
235 ; (dicts, co_fn) <- instCallDicts loc preds
236 ; return (dicts, co_fn <.> WpTyApp ty1) }
237 -- We use type application to apply the function to the
238 -- coercion; here ty1 *is* the appropriate identity coercion
240 instCallDicts loc (pred : preds)
241 = do { uniq <- newUnique
242 ; let name = mkPredName uniq (instLocSrcLoc loc) pred
243 dict = Dict name pred loc
244 ; (dicts, co_fn) <- instCallDicts loc preds
245 ; return (dict:dicts, co_fn <.> WpApp (instToId dict)) }
248 cloneDict :: Inst -> TcM Inst -- Only used for linear implicit params
249 cloneDict (Dict nm ty loc) = newUnique `thenM` \ uniq ->
250 returnM (Dict (setNameUnique nm uniq) ty loc)
252 -- For vanilla implicit parameters, there is only one in scope
253 -- at any time, so we used to use the name of the implicit parameter itself
254 -- But with splittable implicit parameters there may be many in
255 -- scope, so we make up a new namea.
256 newIPDict :: InstOrigin -> IPName Name -> Type
257 -> TcM (IPName Id, Inst)
258 newIPDict orig ip_name ty
259 = getInstLoc orig `thenM` \ inst_loc ->
260 newUnique `thenM` \ uniq ->
262 pred = IParam ip_name ty
263 name = mkPredName uniq (instLocSrcLoc inst_loc) pred
264 dict = Dict name pred inst_loc
266 returnM (mapIPName (\n -> instToId dict) ip_name, dict)
271 %************************************************************************
273 \subsection{Building methods (calls of overloaded functions)}
275 %************************************************************************
279 newMethodFromName :: InstOrigin -> BoxyRhoType -> Name -> TcM TcId
280 newMethodFromName origin ty name
281 = tcLookupId name `thenM` \ id ->
282 -- Use tcLookupId not tcLookupGlobalId; the method is almost
283 -- always a class op, but with -fno-implicit-prelude GHC is
284 -- meant to find whatever thing is in scope, and that may
285 -- be an ordinary function.
286 getInstLoc origin `thenM` \ loc ->
287 tcInstClassOp loc id [ty] `thenM` \ inst ->
288 extendLIE inst `thenM_`
289 returnM (instToId inst)
291 newMethodWithGivenTy orig id tys
292 = getInstLoc orig `thenM` \ loc ->
293 newMethod loc id tys `thenM` \ inst ->
294 extendLIE inst `thenM_`
295 returnM (instToId inst)
297 --------------------------------------------
298 -- tcInstClassOp, and newMethod do *not* drop the
299 -- Inst into the LIE; they just returns the Inst
300 -- This is important because they are used by TcSimplify
303 -- NB: the kind of the type variable to be instantiated
304 -- might be a sub-kind of the type to which it is applied,
305 -- notably when the latter is a type variable of kind ??
306 -- Hence the call to checkKind
307 -- A worry: is this needed anywhere else?
308 tcInstClassOp :: InstLoc -> Id -> [TcType] -> TcM Inst
309 tcInstClassOp inst_loc sel_id tys
311 (tyvars, _rho) = tcSplitForAllTys (idType sel_id)
313 zipWithM_ checkKind tyvars tys `thenM_`
314 newMethod inst_loc sel_id tys
316 checkKind :: TyVar -> TcType -> TcM ()
317 -- Ensure that the type has a sub-kind of the tyvar
320 -- ty1 <- zonkTcType ty
321 ; if typeKind ty1 `isSubKind` Var.tyVarKind tv
325 pprPanic "checkKind: adding kind constraint"
326 (vcat [ppr tv <+> ppr (Var.tyVarKind tv),
327 ppr ty <+> ppr ty1 <+> ppr (typeKind ty1)])
329 -- do { tv1 <- tcInstTyVar tv
330 -- ; unifyType ty1 (mkTyVarTy tv1) } }
333 ---------------------------
334 newMethod inst_loc id tys
335 = newUnique `thenM` \ new_uniq ->
337 (theta,tau) = tcSplitPhiTy (applyTys (idType id) tys)
338 meth_id = mkUserLocal (mkMethodOcc (getOccName id)) new_uniq tau loc
339 inst = Method meth_id id tys theta inst_loc
340 loc = instLocSrcLoc inst_loc
346 shortCutIntLit :: Integer -> TcType -> Maybe (HsExpr TcId)
348 | isIntTy ty && inIntRange i -- Short cut for Int
349 = Just (HsLit (HsInt i))
350 | isIntegerTy ty -- Short cut for Integer
351 = Just (HsLit (HsInteger i ty))
352 | otherwise = Nothing
354 shortCutFracLit :: Rational -> TcType -> Maybe (HsExpr TcId)
357 = Just (mk_lit floatDataCon (HsFloatPrim f))
359 = Just (mk_lit doubleDataCon (HsDoublePrim f))
360 | otherwise = Nothing
362 mk_lit con lit = HsApp (nlHsVar (dataConWrapId con)) (nlHsLit lit)
364 mkIntegerLit :: Integer -> TcM (LHsExpr TcId)
366 = tcMetaTy integerTyConName `thenM` \ integer_ty ->
367 getSrcSpanM `thenM` \ span ->
368 returnM (L span $ HsLit (HsInteger i integer_ty))
370 mkRatLit :: Rational -> TcM (LHsExpr TcId)
372 = tcMetaTy rationalTyConName `thenM` \ rat_ty ->
373 getSrcSpanM `thenM` \ span ->
374 returnM (L span $ HsLit (HsRat r rat_ty))
376 isHsVar :: HsExpr Name -> Name -> Bool
377 isHsVar (HsVar f) g = f==g
378 isHsVar other g = False
382 %************************************************************************
386 %************************************************************************
388 Zonking makes sure that the instance types are fully zonked.
391 zonkInst :: Inst -> TcM Inst
392 zonkInst (Dict name pred loc)
393 = zonkTcPredType pred `thenM` \ new_pred ->
394 returnM (Dict name new_pred loc)
396 zonkInst (Method m id tys theta loc)
397 = zonkId id `thenM` \ new_id ->
398 -- Essential to zonk the id in case it's a local variable
399 -- Can't use zonkIdOcc because the id might itself be
400 -- an InstId, in which case it won't be in scope
402 zonkTcTypes tys `thenM` \ new_tys ->
403 zonkTcThetaType theta `thenM` \ new_theta ->
404 returnM (Method m new_id new_tys new_theta loc)
406 zonkInst (LitInst nm lit ty loc)
407 = zonkTcType ty `thenM` \ new_ty ->
408 returnM (LitInst nm lit new_ty loc)
410 zonkInsts insts = mappM zonkInst insts
414 %************************************************************************
416 \subsection{Printing}
418 %************************************************************************
420 ToDo: improve these pretty-printing things. The ``origin'' is really only
421 relevant in error messages.
424 instance Outputable Inst where
425 ppr inst = pprInst inst
427 pprDictsTheta :: [Inst] -> SDoc
428 -- Print in type-like fashion (Eq a, Show b)
429 pprDictsTheta dicts = pprTheta (map dictPred dicts)
431 pprDictsInFull :: [Inst] -> SDoc
432 -- Print in type-like fashion, but with source location
434 = vcat (map go dicts)
436 go dict = sep [quotes (ppr (dictPred dict)), nest 2 (pprInstLoc (instLoc dict))]
438 pprInsts :: [Inst] -> SDoc
439 -- Debugging: print the evidence :: type
440 pprInsts insts = brackets (interpp'SP insts)
442 pprInst, pprInstInFull :: Inst -> SDoc
443 -- Debugging: print the evidence :: type
444 pprInst (LitInst nm lit ty loc) = ppr nm <+> dcolon <+> ppr ty
445 pprInst (Dict nm pred loc) = ppr nm <+> dcolon <+> pprPred pred
447 pprInst m@(Method inst_id id tys theta loc)
448 = ppr inst_id <+> dcolon <+>
449 braces (sep [ppr id <+> ptext SLIT("at"),
450 brackets (sep (map pprParendType tys))])
453 = sep [quotes (pprInst inst), nest 2 (pprInstLoc (instLoc inst))]
455 tidyInst :: TidyEnv -> Inst -> Inst
456 tidyInst env (LitInst nm lit ty loc) = LitInst nm lit (tidyType env ty) loc
457 tidyInst env (Dict nm pred loc) = Dict nm (tidyPred env pred) loc
458 tidyInst env (Method u id tys theta loc) = Method u id (tidyTypes env tys) theta loc
460 tidyMoreInsts :: TidyEnv -> [Inst] -> (TidyEnv, [Inst])
461 -- This function doesn't assume that the tyvars are in scope
462 -- so it works like tidyOpenType, returning a TidyEnv
463 tidyMoreInsts env insts
464 = (env', map (tidyInst env') insts)
466 env' = tidyFreeTyVars env (tyVarsOfInsts insts)
468 tidyInsts :: [Inst] -> (TidyEnv, [Inst])
469 tidyInsts insts = tidyMoreInsts emptyTidyEnv insts
471 showLIE :: SDoc -> TcM () -- Debugging
473 = do { lie_var <- getLIEVar ;
474 lie <- readMutVar lie_var ;
475 traceTc (str <+> vcat (map pprInstInFull (lieToList lie))) }
479 %************************************************************************
481 Extending the instance environment
483 %************************************************************************
486 tcExtendLocalInstEnv :: [Instance] -> TcM a -> TcM a
487 -- Add new locally-defined instances
488 tcExtendLocalInstEnv dfuns thing_inside
489 = do { traceDFuns dfuns
491 ; inst_env' <- foldlM addLocalInst (tcg_inst_env env) dfuns
492 ; let env' = env { tcg_insts = dfuns ++ tcg_insts env,
493 tcg_inst_env = inst_env' }
494 ; setGblEnv env' thing_inside }
496 addLocalInst :: InstEnv -> Instance -> TcM InstEnv
497 -- Check that the proposed new instance is OK,
498 -- and then add it to the home inst env
499 addLocalInst home_ie ispec
500 = do { -- Instantiate the dfun type so that we extend the instance
501 -- envt with completely fresh template variables
502 -- This is important because the template variables must
503 -- not overlap with anything in the things being looked up
504 -- (since we do unification).
505 -- We use tcInstSkolType because we don't want to allocate fresh
506 -- *meta* type variables.
507 let dfun = instanceDFunId ispec
508 ; (tvs', theta', tau') <- tcInstSkolType (InstSkol dfun) (idType dfun)
509 ; let (cls, tys') = tcSplitDFunHead tau'
510 dfun' = setIdType dfun (mkSigmaTy tvs' theta' tau')
511 ispec' = setInstanceDFunId ispec dfun'
513 -- Load imported instances, so that we report
514 -- duplicates correctly
516 ; let inst_envs = (eps_inst_env eps, home_ie)
518 -- Check functional dependencies
519 ; case checkFunDeps inst_envs ispec' of
520 Just specs -> funDepErr ispec' specs
523 -- Check for duplicate instance decls
524 ; let { (matches, _) = lookupInstEnv inst_envs cls tys'
525 ; dup_ispecs = [ dup_ispec
526 | (_, dup_ispec) <- matches
527 , let (_,_,_,dup_tys) = instanceHead dup_ispec
528 , isJust (tcMatchTys (mkVarSet tvs') tys' dup_tys)] }
529 -- Find memebers of the match list which ispec itself matches.
530 -- If the match is 2-way, it's a duplicate
532 dup_ispec : _ -> dupInstErr ispec' dup_ispec
535 -- OK, now extend the envt
536 ; return (extendInstEnv home_ie ispec') }
538 getOverlapFlag :: TcM OverlapFlag
540 = do { dflags <- getDOpts
541 ; let overlap_ok = dopt Opt_AllowOverlappingInstances dflags
542 incoherent_ok = dopt Opt_AllowIncoherentInstances dflags
543 overlap_flag | incoherent_ok = Incoherent
544 | overlap_ok = OverlapOk
545 | otherwise = NoOverlap
547 ; return overlap_flag }
550 = traceTc (hang (text "Adding instances:") 2 (vcat (map pp ispecs)))
552 pp ispec = ppr (instanceDFunId ispec) <+> colon <+> ppr ispec
553 -- Print the dfun name itself too
555 funDepErr ispec ispecs
557 addErr (hang (ptext SLIT("Functional dependencies conflict between instance declarations:"))
558 2 (pprInstances (ispec:ispecs)))
559 dupInstErr ispec dup_ispec
561 addErr (hang (ptext SLIT("Duplicate instance declarations:"))
562 2 (pprInstances [ispec, dup_ispec]))
564 addDictLoc ispec thing_inside
565 = setSrcSpan (mkSrcSpan loc loc) thing_inside
567 loc = getSrcLoc ispec
571 %************************************************************************
573 \subsection{Looking up Insts}
575 %************************************************************************
578 data LookupInstResult
580 | SimpleInst (LHsExpr TcId) -- Just a variable, type application, or literal
581 | GenInst [Inst] (LHsExpr TcId) -- The expression and its needed insts
583 lookupInst :: Inst -> TcM LookupInstResult
584 -- It's important that lookupInst does not put any new stuff into
585 -- the LIE. Instead, any Insts needed by the lookup are returned in
586 -- the LookupInstResult, where they can be further processed by tcSimplify
591 lookupInst inst@(Method _ id tys theta loc)
592 = do { (dicts, dict_app) <- instCallDicts loc theta
593 ; let co_fn = dict_app <.> mkWpTyApps tys
594 ; return (GenInst dicts (L span $ HsWrap co_fn (HsVar id))) }
596 span = instLocSrcSpan loc
600 -- Look for short cuts first: if the literal is *definitely* a
601 -- int, integer, float or a double, generate the real thing here.
602 -- This is essential (see nofib/spectral/nucleic).
603 -- [Same shortcut as in newOverloadedLit, but we
604 -- may have done some unification by now]
606 lookupInst inst@(LitInst _nm (HsIntegral i from_integer_name) ty loc)
607 | Just expr <- shortCutIntLit i ty
608 = returnM (GenInst [] (noLoc expr)) -- GenInst, not SimpleInst, because
609 -- expr may be a constructor application
611 = ASSERT( from_integer_name `isHsVar` fromIntegerName ) -- A LitInst invariant
612 tcLookupId fromIntegerName `thenM` \ from_integer ->
613 tcInstClassOp loc from_integer [ty] `thenM` \ method_inst ->
614 mkIntegerLit i `thenM` \ integer_lit ->
615 returnM (GenInst [method_inst]
616 (mkHsApp (L (instLocSrcSpan loc)
617 (HsVar (instToId method_inst))) integer_lit))
619 lookupInst inst@(LitInst _nm (HsFractional f from_rat_name) ty loc)
620 | Just expr <- shortCutFracLit f ty
621 = returnM (GenInst [] (noLoc expr))
624 = ASSERT( from_rat_name `isHsVar` fromRationalName ) -- A LitInst invariant
625 tcLookupId fromRationalName `thenM` \ from_rational ->
626 tcInstClassOp loc from_rational [ty] `thenM` \ method_inst ->
627 mkRatLit f `thenM` \ rat_lit ->
628 returnM (GenInst [method_inst] (mkHsApp (L (instLocSrcSpan loc)
629 (HsVar (instToId method_inst))) rat_lit))
632 lookupInst (Dict _ pred loc)
633 = do { mb_result <- lookupPred pred
634 ; case mb_result of {
635 Nothing -> return NoInstance ;
636 Just (tenv, dfun_id) -> do
638 -- tenv is a substitution that instantiates the dfun_id
639 -- to match the requested result type.
641 -- We ASSUME that the dfun is quantified over the very same tyvars
642 -- that are bound by the tenv.
645 -- might have some tyvars that *only* appear in arguments
646 -- dfun :: forall a b. C a b, Ord b => D [a]
647 -- We instantiate b to a flexi type variable -- it'll presumably
648 -- become fixed later via functional dependencies
649 { use_stage <- getStage
650 ; checkWellStaged (ptext SLIT("instance for") <+> quotes (ppr pred))
651 (topIdLvl dfun_id) use_stage
653 -- It's possible that not all the tyvars are in
654 -- the substitution, tenv. For example:
655 -- instance C X a => D X where ...
656 -- (presumably there's a functional dependency in class C)
657 -- Hence the open_tvs to instantiate any un-substituted tyvars.
658 ; let (tyvars, rho) = tcSplitForAllTys (idType dfun_id)
659 open_tvs = filter (`notElemTvSubst` tenv) tyvars
660 ; open_tvs' <- mappM tcInstTyVar open_tvs
662 tenv' = extendTvSubstList tenv open_tvs (mkTyVarTys open_tvs')
663 -- Since the open_tvs' are freshly made, they cannot possibly be captured by
664 -- any nested for-alls in rho. So the in-scope set is unchanged
665 dfun_rho = substTy tenv' rho
666 (theta, _) = tcSplitPhiTy dfun_rho
667 src_loc = instLocSrcSpan loc
669 tys = map (substTyVar tenv') tyvars
671 returnM (SimpleInst (L src_loc $ HsWrap (mkWpTyApps tys) dfun))
673 { (dicts, dict_app) <- instCallDicts loc theta
674 ; let co_fn = dict_app <.> mkWpTyApps tys
675 ; returnM (GenInst dicts (L src_loc $ HsWrap co_fn dfun))
679 lookupPred :: TcPredType -> TcM (Maybe (TvSubst, DFunId))
680 -- Look up a class constraint in the instance environment
681 lookupPred pred@(ClassP clas tys)
683 ; tcg_env <- getGblEnv
684 ; let inst_envs = (eps_inst_env eps, tcg_inst_env tcg_env)
685 ; case lookupInstEnv inst_envs clas tys of {
686 ([(tenv, ispec)], [])
687 -> do { let dfun_id = is_dfun ispec
688 ; traceTc (text "lookupInst success" <+>
689 vcat [text "dict" <+> ppr pred,
690 text "witness" <+> ppr dfun_id
691 <+> ppr (idType dfun_id) ])
692 -- Record that this dfun is needed
693 ; record_dfun_usage dfun_id
694 ; return (Just (tenv, dfun_id)) } ;
697 -> do { traceTc (text "lookupInst fail" <+>
698 vcat [text "dict" <+> ppr pred,
699 text "matches" <+> ppr matches,
700 text "unifs" <+> ppr unifs])
701 -- In the case of overlap (multiple matches) we report
702 -- NoInstance here. That has the effect of making the
703 -- context-simplifier return the dict as an irreducible one.
704 -- Then it'll be given to addNoInstanceErrs, which will do another
705 -- lookupInstEnv to get the detailed info about what went wrong.
709 lookupPred ip_pred = return Nothing
711 record_dfun_usage dfun_id
712 = do { hsc_env <- getTopEnv
713 ; let dfun_name = idName dfun_id
714 dfun_mod = nameModule dfun_name
715 ; if isInternalName dfun_name || -- Internal name => defined in this module
716 modulePackageId dfun_mod /= thisPackage (hsc_dflags hsc_env)
717 then return () -- internal, or in another package
718 else do { tcg_env <- getGblEnv
719 ; updMutVar (tcg_inst_uses tcg_env)
720 (`addOneToNameSet` idName dfun_id) }}
723 tcGetInstEnvs :: TcM (InstEnv, InstEnv)
724 -- Gets both the external-package inst-env
725 -- and the home-pkg inst env (includes module being compiled)
726 tcGetInstEnvs = do { eps <- getEps; env <- getGblEnv;
727 return (eps_inst_env eps, tcg_inst_env env) }
732 %************************************************************************
736 %************************************************************************
738 Suppose we are doing the -fno-implicit-prelude thing, and we encounter
739 a do-expression. We have to find (>>) in the current environment, which is
740 done by the rename. Then we have to check that it has the same type as
741 Control.Monad.(>>). Or, more precisely, a compatible type. One 'customer' had
744 (>>) :: HB m n mn => m a -> n b -> mn b
746 So the idea is to generate a local binding for (>>), thus:
748 let then72 :: forall a b. m a -> m b -> m b
749 then72 = ...something involving the user's (>>)...
751 ...the do-expression...
753 Now the do-expression can proceed using then72, which has exactly
756 In fact tcSyntaxName just generates the RHS for then72, because we only
757 want an actual binding in the do-expression case. For literals, we can
758 just use the expression inline.
761 tcSyntaxName :: InstOrigin
762 -> TcType -- Type to instantiate it at
763 -> (Name, HsExpr Name) -- (Standard name, user name)
764 -> TcM (Name, HsExpr TcId) -- (Standard name, suitable expression)
765 -- *** NOW USED ONLY FOR CmdTop (sigh) ***
766 -- NB: tcSyntaxName calls tcExpr, and hence can do unification.
767 -- So we do not call it from lookupInst, which is called from tcSimplify
769 tcSyntaxName orig ty (std_nm, HsVar user_nm)
771 = newMethodFromName orig ty std_nm `thenM` \ id ->
772 returnM (std_nm, HsVar id)
774 tcSyntaxName orig ty (std_nm, user_nm_expr)
775 = tcLookupId std_nm `thenM` \ std_id ->
777 -- C.f. newMethodAtLoc
778 ([tv], _, tau) = tcSplitSigmaTy (idType std_id)
779 sigma1 = substTyWith [tv] [ty] tau
780 -- Actually, the "tau-type" might be a sigma-type in the
781 -- case of locally-polymorphic methods.
783 addErrCtxtM (syntaxNameCtxt user_nm_expr orig sigma1) $
785 -- Check that the user-supplied thing has the
786 -- same type as the standard one.
787 -- Tiresome jiggling because tcCheckSigma takes a located expression
788 getSrcSpanM `thenM` \ span ->
789 tcPolyExpr (L span user_nm_expr) sigma1 `thenM` \ expr ->
790 returnM (std_nm, unLoc expr)
792 syntaxNameCtxt name orig ty tidy_env
793 = getInstLoc orig `thenM` \ inst_loc ->
795 msg = vcat [ptext SLIT("When checking that") <+> quotes (ppr name) <+>
796 ptext SLIT("(needed by a syntactic construct)"),
797 nest 2 (ptext SLIT("has the required type:") <+> ppr (tidyType tidy_env ty)),
798 nest 2 (pprInstLoc inst_loc)]
800 returnM (tidy_env, msg)