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 getDictClassTys, dictPred,
29 lookupSimpleInst, LookupInstResult(..), lookupPred,
30 tcExtendLocalInstEnv, tcGetInstEnvs, getOverlapFlag,
32 isDict, isClassDict, isMethod, isImplicInst,
33 isIPDict, isInheritableInst, isMethodOrLit,
34 isTyVarDict, isMethodFor, getDefaultableDicts,
37 instToId, instToVar, instName,
39 InstOrigin(..), InstLoc, pprInstLoc
42 #include "HsVersions.h"
44 import {-# SOURCE #-} TcExpr( tcPolyExpr )
45 import {-# SOURCE #-} TcUnify( unifyType )
67 import Var ( Var, TyVar )
85 instName :: Inst -> Name
86 instName inst = Var.varName (instToVar inst)
88 instToId :: Inst -> TcId
89 instToId inst = ASSERT2( isId id, ppr inst ) id
93 instToVar :: Inst -> Var
94 instToVar (LitInst {tci_name = nm, tci_ty = ty})
96 instToVar (Method {tci_id = id})
98 instToVar (Dict {tci_name = nm, tci_pred = pred})
99 | isEqPred pred = Var.mkCoVar nm (mkPredTy pred)
100 | otherwise = mkLocalId nm (mkPredTy pred)
101 instToVar (ImplicInst {tci_name = nm, tci_tyvars = tvs, tci_given = givens,
102 tci_wanted = wanteds})
103 = mkLocalId nm (mkImplicTy tvs givens wanteds)
105 instType :: Inst -> Type
106 instType (LitInst {tci_ty = ty}) = ty
107 instType (Method {tci_id = id}) = idType id
108 instType (Dict {tci_pred = pred}) = mkPredTy pred
109 instType imp@(ImplicInst {}) = mkImplicTy (tci_tyvars imp) (tci_given imp)
112 mkImplicTy tvs givens wanteds -- The type of an implication constraint
113 = ASSERT( all isDict givens )
114 -- pprTrace "mkImplicTy" (ppr givens) $
116 mkPhiTy (map dictPred givens) $
117 if isSingleton wanteds then
118 instType (head wanteds)
120 mkTupleTy Boxed (length wanteds) (map instType wanteds)
122 dictPred (Dict {tci_pred = pred}) = pred
123 dictPred inst = pprPanic "dictPred" (ppr inst)
125 getDictClassTys (Dict {tci_pred = pred}) = getClassPredTys pred
126 getDictClassTys inst = pprPanic "getDictClassTys" (ppr inst)
128 -- fdPredsOfInst is used to get predicates that contain functional
129 -- dependencies *or* might do so. The "might do" part is because
130 -- a constraint (C a b) might have a superclass with FDs
131 -- Leaving these in is really important for the call to fdPredsOfInsts
132 -- in TcSimplify.inferLoop, because the result is fed to 'grow',
133 -- which is supposed to be conservative
134 fdPredsOfInst (Dict {tci_pred = pred}) = [pred]
135 fdPredsOfInst (Method {tci_theta = theta}) = theta
136 fdPredsOfInst (ImplicInst {tci_given = gs,
137 tci_wanted = ws}) = fdPredsOfInsts (gs ++ ws)
138 fdPredsOfInst (LitInst {}) = []
140 fdPredsOfInsts :: [Inst] -> [PredType]
141 fdPredsOfInsts insts = concatMap fdPredsOfInst insts
143 isInheritableInst (Dict {tci_pred = pred}) = isInheritablePred pred
144 isInheritableInst (Method {tci_theta = theta}) = all isInheritablePred theta
145 isInheritableInst other = True
148 ---------------------------------
149 -- Get the implicit parameters mentioned by these Insts
150 -- NB: the results of these functions are insensitive to zonking
152 ipNamesOfInsts :: [Inst] -> [Name]
153 ipNamesOfInst :: Inst -> [Name]
154 ipNamesOfInsts insts = [n | inst <- insts, n <- ipNamesOfInst inst]
156 ipNamesOfInst (Dict {tci_pred = IParam n _}) = [ipNameName n]
157 ipNamesOfInst (Method {tci_theta = theta}) = [ipNameName n | IParam n _ <- theta]
158 ipNamesOfInst other = []
160 ---------------------------------
161 tyVarsOfInst :: Inst -> TcTyVarSet
162 tyVarsOfInst (LitInst {tci_ty = ty}) = tyVarsOfType ty
163 tyVarsOfInst (Dict {tci_pred = pred}) = tyVarsOfPred pred
164 tyVarsOfInst (Method {tci_oid = id, tci_tys = tys}) = tyVarsOfTypes tys `unionVarSet` idFreeTyVars id
165 -- The id might have free type variables; in the case of
166 -- locally-overloaded class methods, for example
167 tyVarsOfInst (ImplicInst {tci_tyvars = tvs, tci_given = givens, tci_wanted = wanteds})
168 = (tyVarsOfInsts givens `unionVarSet` tyVarsOfInsts wanteds) `minusVarSet` mkVarSet tvs
171 tyVarsOfInsts insts = foldr (unionVarSet . tyVarsOfInst) emptyVarSet insts
172 tyVarsOfLIE lie = tyVarsOfInsts (lieToList lie)
178 isDict :: Inst -> Bool
179 isDict (Dict {}) = True
182 isClassDict :: Inst -> Bool
183 isClassDict (Dict {tci_pred = pred}) = isClassPred pred
184 isClassDict other = False
186 isTyVarDict :: Inst -> Bool
187 isTyVarDict (Dict {tci_pred = pred}) = isTyVarClassPred pred
188 isTyVarDict other = False
190 isIPDict :: Inst -> Bool
191 isIPDict (Dict {tci_pred = pred}) = isIPPred pred
192 isIPDict other = False
194 isImplicInst (ImplicInst {}) = True
195 isImplicInst other = False
197 isMethod :: Inst -> Bool
198 isMethod (Method {}) = True
199 isMethod other = False
201 isMethodFor :: TcIdSet -> Inst -> Bool
202 isMethodFor ids (Method {tci_oid = id}) = id `elemVarSet` ids
203 isMethodFor ids inst = False
205 isMethodOrLit :: Inst -> Bool
206 isMethodOrLit (Method {}) = True
207 isMethodOrLit (LitInst {}) = True
208 isMethodOrLit other = False
212 getDefaultableDicts :: [Inst] -> ([(Inst, Class, TcTyVar)], TcTyVarSet)
213 -- Look for free dicts of the form (C tv), even inside implications
214 -- *and* the set of tyvars mentioned by all *other* constaints
215 -- This disgustingly ad-hoc function is solely to support defaulting
216 getDefaultableDicts insts
217 = (concat ps, unionVarSets tvs)
219 (ps, tvs) = mapAndUnzip get insts
220 get d@(Dict {tci_pred = ClassP cls [ty]})
221 | Just tv <- tcGetTyVar_maybe ty = ([(d,cls,tv)], emptyVarSet)
222 | otherwise = ([], tyVarsOfType ty)
223 get (ImplicInst {tci_tyvars = tvs, tci_wanted = wanteds})
224 = ([ up | up@(_,_,tv) <- ups, not (tv `elemVarSet` tv_set)],
225 ftvs `minusVarSet` tv_set)
227 tv_set = mkVarSet tvs
228 (ups, ftvs) = getDefaultableDicts wanteds
229 get inst = ([], tyVarsOfInst inst)
232 %************************************************************************
234 \subsection{Building dictionaries}
236 %************************************************************************
238 -- newDictBndrs makes a dictionary at a binding site
239 -- instCall makes a dictionary at an occurrence site
240 -- and throws it into the LIE
244 newDictBndrsO :: InstOrigin -> TcThetaType -> TcM [Inst]
245 newDictBndrsO orig theta = do { loc <- getInstLoc orig
246 ; newDictBndrs loc theta }
248 newDictBndrs :: InstLoc -> TcThetaType -> TcM [Inst]
249 newDictBndrs inst_loc theta = mapM (newDictBndr inst_loc) theta
251 newDictBndr :: InstLoc -> TcPredType -> TcM Inst
252 newDictBndr inst_loc pred
253 = do { uniq <- newUnique
254 ; let name = mkPredName uniq inst_loc pred
255 ; return (Dict {tci_name = name, tci_pred = pred, tci_loc = inst_loc}) }
258 instCall :: InstOrigin -> [TcType] -> TcThetaType -> TcM HsWrapper
259 -- Instantiate the constraints of a call
260 -- (instCall o tys theta)
261 -- (a) Makes fresh dictionaries as necessary for the constraints (theta)
262 -- (b) Throws these dictionaries into the LIE
263 -- (c) Eeturns an HsWrapper ([.] tys dicts)
265 instCall orig tys theta
266 = do { loc <- getInstLoc orig
267 ; (dicts, dict_app) <- instCallDicts loc theta
269 ; return (dict_app <.> mkWpTyApps tys) }
272 instStupidTheta :: InstOrigin -> TcThetaType -> TcM ()
273 -- Similar to instCall, but only emit the constraints in the LIE
274 -- Used exclusively for the 'stupid theta' of a data constructor
275 instStupidTheta orig theta
276 = do { loc <- getInstLoc orig
277 ; (dicts, _) <- instCallDicts loc theta
281 instCallDicts :: InstLoc -> TcThetaType -> TcM ([Inst], HsWrapper)
282 -- This is the key place where equality predicates
283 -- are unleashed into the world
284 instCallDicts loc [] = return ([], idHsWrapper)
286 instCallDicts loc (EqPred ty1 ty2 : preds)
287 = do { unifyType ty1 ty2 -- For now, we insist that they unify right away
288 -- Later on, when we do associated types,
289 -- unifyType :: Type -> Type -> TcM ([Inst], Coercion)
290 ; (dicts, co_fn) <- instCallDicts loc preds
291 ; return (dicts, co_fn <.> WpTyApp ty1) }
292 -- We use type application to apply the function to the
293 -- coercion; here ty1 *is* the appropriate identity coercion
295 instCallDicts loc (pred : preds)
296 = do { uniq <- newUnique
297 ; let name = mkPredName uniq loc pred
298 dict = Dict {tci_name = name, tci_pred = pred, tci_loc = loc}
299 ; (dicts, co_fn) <- instCallDicts loc preds
300 ; return (dict:dicts, co_fn <.> WpApp (instToId dict)) }
303 cloneDict :: Inst -> TcM Inst -- Only used for linear implicit params
304 cloneDict dict@(Dict nm ty loc) = do { uniq <- newUnique
305 ; return (dict {tci_name = setNameUnique nm uniq}) }
306 cloneDict other = pprPanic "cloneDict" (ppr other)
308 -- For vanilla implicit parameters, there is only one in scope
309 -- at any time, so we used to use the name of the implicit parameter itself
310 -- But with splittable implicit parameters there may be many in
311 -- scope, so we make up a new namea.
312 newIPDict :: InstOrigin -> IPName Name -> Type
313 -> TcM (IPName Id, Inst)
314 newIPDict orig ip_name ty
315 = getInstLoc orig `thenM` \ inst_loc ->
316 newUnique `thenM` \ uniq ->
318 pred = IParam ip_name ty
319 name = mkPredName uniq inst_loc pred
320 dict = Dict {tci_name = name, tci_pred = pred, tci_loc = inst_loc}
322 returnM (mapIPName (\n -> instToId dict) ip_name, dict)
327 mkPredName :: Unique -> InstLoc -> PredType -> Name
328 mkPredName uniq loc pred_ty
329 = mkInternalName uniq occ (srcSpanStart (instLocSpan loc))
331 occ = case pred_ty of
332 ClassP cls _ -> mkDictOcc (getOccName cls)
333 IParam ip _ -> getOccName (ipNameName ip)
334 EqPred ty _ -> mkEqPredCoOcc baseOcc
336 -- we use the outermost tycon of the lhs, which must be a type
337 -- function, as the base name for an equality
338 baseOcc = case splitTyConApp_maybe ty of
340 pprPanic "Inst.mkPredName:" (ppr ty)
341 Just (tc, _) -> getOccName tc
344 %************************************************************************
346 \subsection{Building methods (calls of overloaded functions)}
348 %************************************************************************
352 newMethodFromName :: InstOrigin -> BoxyRhoType -> Name -> TcM TcId
353 newMethodFromName origin ty name
354 = tcLookupId name `thenM` \ id ->
355 -- Use tcLookupId not tcLookupGlobalId; the method is almost
356 -- always a class op, but with -fno-implicit-prelude GHC is
357 -- meant to find whatever thing is in scope, and that may
358 -- be an ordinary function.
359 getInstLoc origin `thenM` \ loc ->
360 tcInstClassOp loc id [ty] `thenM` \ inst ->
361 extendLIE inst `thenM_`
362 returnM (instToId inst)
364 newMethodWithGivenTy orig id tys
365 = getInstLoc orig `thenM` \ loc ->
366 newMethod loc id tys `thenM` \ inst ->
367 extendLIE inst `thenM_`
368 returnM (instToId inst)
370 --------------------------------------------
371 -- tcInstClassOp, and newMethod do *not* drop the
372 -- Inst into the LIE; they just returns the Inst
373 -- This is important because they are used by TcSimplify
376 -- NB: the kind of the type variable to be instantiated
377 -- might be a sub-kind of the type to which it is applied,
378 -- notably when the latter is a type variable of kind ??
379 -- Hence the call to checkKind
380 -- A worry: is this needed anywhere else?
381 tcInstClassOp :: InstLoc -> Id -> [TcType] -> TcM Inst
382 tcInstClassOp inst_loc sel_id tys
384 (tyvars, _rho) = tcSplitForAllTys (idType sel_id)
386 zipWithM_ checkKind tyvars tys `thenM_`
387 newMethod inst_loc sel_id tys
389 checkKind :: TyVar -> TcType -> TcM ()
390 -- Ensure that the type has a sub-kind of the tyvar
393 -- ty1 <- zonkTcType ty
394 ; if typeKind ty1 `isSubKind` Var.tyVarKind tv
398 pprPanic "checkKind: adding kind constraint"
399 (vcat [ppr tv <+> ppr (Var.tyVarKind tv),
400 ppr ty <+> ppr ty1 <+> ppr (typeKind ty1)])
402 -- do { tv1 <- tcInstTyVar tv
403 -- ; unifyType ty1 (mkTyVarTy tv1) } }
406 ---------------------------
407 newMethod inst_loc id tys
408 = newUnique `thenM` \ new_uniq ->
410 (theta,tau) = tcSplitPhiTy (applyTys (idType id) tys)
411 meth_id = mkUserLocal (mkMethodOcc (getOccName id)) new_uniq tau loc
412 inst = Method {tci_id = meth_id, tci_oid = id, tci_tys = tys,
413 tci_theta = theta, tci_loc = inst_loc}
414 loc = srcSpanStart (instLocSpan inst_loc)
420 shortCutIntLit :: Integer -> TcType -> Maybe (HsExpr TcId)
422 | isIntTy ty && inIntRange i -- Short cut for Int
423 = Just (HsLit (HsInt i))
424 | isIntegerTy ty -- Short cut for Integer
425 = Just (HsLit (HsInteger i ty))
426 | otherwise = Nothing
428 shortCutFracLit :: Rational -> TcType -> Maybe (HsExpr TcId)
431 = Just (mk_lit floatDataCon (HsFloatPrim f))
433 = Just (mk_lit doubleDataCon (HsDoublePrim f))
434 | otherwise = Nothing
436 mk_lit con lit = HsApp (nlHsVar (dataConWrapId con)) (nlHsLit lit)
438 mkIntegerLit :: Integer -> TcM (LHsExpr TcId)
440 = tcMetaTy integerTyConName `thenM` \ integer_ty ->
441 getSrcSpanM `thenM` \ span ->
442 returnM (L span $ HsLit (HsInteger i integer_ty))
444 mkRatLit :: Rational -> TcM (LHsExpr TcId)
446 = tcMetaTy rationalTyConName `thenM` \ rat_ty ->
447 getSrcSpanM `thenM` \ span ->
448 returnM (L span $ HsLit (HsRat r rat_ty))
450 isHsVar :: HsExpr Name -> Name -> Bool
451 isHsVar (HsVar f) g = f==g
452 isHsVar other g = False
456 %************************************************************************
460 %************************************************************************
462 Zonking makes sure that the instance types are fully zonked.
465 zonkInst :: Inst -> TcM Inst
466 zonkInst dict@(Dict { tci_pred = pred})
467 = zonkTcPredType pred `thenM` \ new_pred ->
468 returnM (dict {tci_pred = new_pred})
470 zonkInst meth@(Method {tci_oid = id, tci_tys = tys, tci_theta = theta})
471 = zonkId id `thenM` \ new_id ->
472 -- Essential to zonk the id in case it's a local variable
473 -- Can't use zonkIdOcc because the id might itself be
474 -- an InstId, in which case it won't be in scope
476 zonkTcTypes tys `thenM` \ new_tys ->
477 zonkTcThetaType theta `thenM` \ new_theta ->
478 returnM (meth { tci_oid = new_id, tci_tys = new_tys, tci_theta = new_theta })
479 -- No need to zonk the tci_id
481 zonkInst lit@(LitInst {tci_ty = ty})
482 = zonkTcType ty `thenM` \ new_ty ->
483 returnM (lit {tci_ty = new_ty})
485 zonkInst implic@(ImplicInst {})
486 = ASSERT( all isImmutableTyVar (tci_tyvars implic) )
487 do { givens' <- zonkInsts (tci_given implic)
488 ; wanteds' <- zonkInsts (tci_wanted implic)
489 ; return (implic {tci_given = givens',tci_wanted = wanteds'}) }
491 zonkInsts insts = mappM zonkInst insts
495 %************************************************************************
497 \subsection{Printing}
499 %************************************************************************
501 ToDo: improve these pretty-printing things. The ``origin'' is really only
502 relevant in error messages.
505 instance Outputable Inst where
506 ppr inst = pprInst inst
508 pprDictsTheta :: [Inst] -> SDoc
509 -- Print in type-like fashion (Eq a, Show b)
510 -- The Inst can be an implication constraint, but not a Method or LitInst
511 pprDictsTheta insts = parens (sep (punctuate comma (map (ppr . instType) insts)))
513 pprDictsInFull :: [Inst] -> SDoc
514 -- Print in type-like fashion, but with source location
516 = vcat (map go dicts)
518 go dict = sep [quotes (ppr (instType dict)), nest 2 (pprInstArising dict)]
520 pprInsts :: [Inst] -> SDoc
521 -- Debugging: print the evidence :: type
522 pprInsts insts = brackets (interpp'SP insts)
524 pprInst, pprInstInFull :: Inst -> SDoc
525 -- Debugging: print the evidence :: type
526 pprInst inst = ppr (instName inst) <+> dcolon
527 <+> (braces (ppr (instType inst)) $$
528 ifPprDebug implic_stuff)
530 implic_stuff | isImplicInst inst = ppr (tci_reft inst)
533 pprInstInFull inst = sep [quotes (pprInst inst), nest 2 (pprInstArising inst)]
535 tidyInst :: TidyEnv -> Inst -> Inst
536 tidyInst env lit@(LitInst {tci_ty = ty}) = lit {tci_ty = tidyType env ty}
537 tidyInst env dict@(Dict {tci_pred = pred}) = dict {tci_pred = tidyPred env pred}
538 tidyInst env meth@(Method {tci_tys = tys}) = meth {tci_tys = tidyTypes env tys}
539 tidyInst env implic@(ImplicInst {})
540 = implic { tci_tyvars = tvs'
541 , tci_given = map (tidyInst env') (tci_given implic)
542 , tci_wanted = map (tidyInst env') (tci_wanted implic) }
544 (env', tvs') = mapAccumL tidyTyVarBndr env (tci_tyvars implic)
546 tidyMoreInsts :: TidyEnv -> [Inst] -> (TidyEnv, [Inst])
547 -- This function doesn't assume that the tyvars are in scope
548 -- so it works like tidyOpenType, returning a TidyEnv
549 tidyMoreInsts env insts
550 = (env', map (tidyInst env') insts)
552 env' = tidyFreeTyVars env (tyVarsOfInsts insts)
554 tidyInsts :: [Inst] -> (TidyEnv, [Inst])
555 tidyInsts insts = tidyMoreInsts emptyTidyEnv insts
557 showLIE :: SDoc -> TcM () -- Debugging
559 = do { lie_var <- getLIEVar ;
560 lie <- readMutVar lie_var ;
561 traceTc (str <+> vcat (map pprInstInFull (lieToList lie))) }
565 %************************************************************************
567 Extending the instance environment
569 %************************************************************************
572 tcExtendLocalInstEnv :: [Instance] -> TcM a -> TcM a
573 -- Add new locally-defined instances
574 tcExtendLocalInstEnv dfuns thing_inside
575 = do { traceDFuns dfuns
577 ; inst_env' <- foldlM addLocalInst (tcg_inst_env env) dfuns
578 ; let env' = env { tcg_insts = dfuns ++ tcg_insts env,
579 tcg_inst_env = inst_env' }
580 ; setGblEnv env' thing_inside }
582 addLocalInst :: InstEnv -> Instance -> TcM InstEnv
583 -- Check that the proposed new instance is OK,
584 -- and then add it to the home inst env
585 addLocalInst home_ie ispec
586 = do { -- Instantiate the dfun type so that we extend the instance
587 -- envt with completely fresh template variables
588 -- This is important because the template variables must
589 -- not overlap with anything in the things being looked up
590 -- (since we do unification).
591 -- We use tcInstSkolType because we don't want to allocate fresh
592 -- *meta* type variables.
593 let dfun = instanceDFunId ispec
594 ; (tvs', theta', tau') <- tcInstSkolType InstSkol (idType dfun)
595 ; let (cls, tys') = tcSplitDFunHead tau'
596 dfun' = setIdType dfun (mkSigmaTy tvs' theta' tau')
597 ispec' = setInstanceDFunId ispec dfun'
599 -- Load imported instances, so that we report
600 -- duplicates correctly
602 ; let inst_envs = (eps_inst_env eps, home_ie)
604 -- Check functional dependencies
605 ; case checkFunDeps inst_envs ispec' of
606 Just specs -> funDepErr ispec' specs
609 -- Check for duplicate instance decls
610 ; let { (matches, _) = lookupInstEnv inst_envs cls tys'
611 ; dup_ispecs = [ dup_ispec
612 | (_, dup_ispec) <- matches
613 , let (_,_,_,dup_tys) = instanceHead dup_ispec
614 , isJust (tcMatchTys (mkVarSet tvs') tys' dup_tys)] }
615 -- Find memebers of the match list which ispec itself matches.
616 -- If the match is 2-way, it's a duplicate
618 dup_ispec : _ -> dupInstErr ispec' dup_ispec
621 -- OK, now extend the envt
622 ; return (extendInstEnv home_ie ispec') }
624 getOverlapFlag :: TcM OverlapFlag
626 = do { dflags <- getDOpts
627 ; let overlap_ok = dopt Opt_AllowOverlappingInstances dflags
628 incoherent_ok = dopt Opt_AllowIncoherentInstances dflags
629 overlap_flag | incoherent_ok = Incoherent
630 | overlap_ok = OverlapOk
631 | otherwise = NoOverlap
633 ; return overlap_flag }
636 = traceTc (hang (text "Adding instances:") 2 (vcat (map pp ispecs)))
638 pp ispec = ppr (instanceDFunId ispec) <+> colon <+> ppr ispec
639 -- Print the dfun name itself too
641 funDepErr ispec ispecs
643 addErr (hang (ptext SLIT("Functional dependencies conflict between instance declarations:"))
644 2 (pprInstances (ispec:ispecs)))
645 dupInstErr ispec dup_ispec
647 addErr (hang (ptext SLIT("Duplicate instance declarations:"))
648 2 (pprInstances [ispec, dup_ispec]))
650 addDictLoc ispec thing_inside
651 = setSrcSpan (mkSrcSpan loc loc) thing_inside
653 loc = getSrcLoc ispec
657 %************************************************************************
659 \subsection{Looking up Insts}
661 %************************************************************************
664 data LookupInstResult
666 | GenInst [Inst] (LHsExpr TcId) -- The expression and its needed insts
668 lookupSimpleInst :: Inst -> TcM LookupInstResult
669 -- This is "simple" in tthat it returns NoInstance for implication constraints
671 -- It's important that lookupInst does not put any new stuff into
672 -- the LIE. Instead, any Insts needed by the lookup are returned in
673 -- the LookupInstResult, where they can be further processed by tcSimplify
675 --------------------- Implications ------------------------
676 lookupSimpleInst (ImplicInst {}) = return NoInstance
678 --------------------- Methods ------------------------
679 lookupSimpleInst (Method {tci_oid = id, tci_tys = tys, tci_theta = theta, tci_loc = loc})
680 = do { (dicts, dict_app) <- instCallDicts loc theta
681 ; let co_fn = dict_app <.> mkWpTyApps tys
682 ; return (GenInst dicts (L span $ HsWrap co_fn (HsVar id))) }
684 span = instLocSpan loc
686 --------------------- Literals ------------------------
687 -- Look for short cuts first: if the literal is *definitely* a
688 -- int, integer, float or a double, generate the real thing here.
689 -- This is essential (see nofib/spectral/nucleic).
690 -- [Same shortcut as in newOverloadedLit, but we
691 -- may have done some unification by now]
693 lookupSimpleInst (LitInst {tci_lit = HsIntegral i from_integer_name, tci_ty = ty, tci_loc = loc})
694 | Just expr <- shortCutIntLit i ty
695 = returnM (GenInst [] (noLoc expr))
697 = ASSERT( from_integer_name `isHsVar` fromIntegerName ) -- A LitInst invariant
698 tcLookupId fromIntegerName `thenM` \ from_integer ->
699 tcInstClassOp loc from_integer [ty] `thenM` \ method_inst ->
700 mkIntegerLit i `thenM` \ integer_lit ->
701 returnM (GenInst [method_inst]
702 (mkHsApp (L (instLocSpan loc)
703 (HsVar (instToId method_inst))) integer_lit))
705 lookupSimpleInst (LitInst {tci_lit = HsFractional f from_rat_name, tci_ty = ty, tci_loc = loc})
706 | Just expr <- shortCutFracLit f ty
707 = returnM (GenInst [] (noLoc expr))
710 = ASSERT( from_rat_name `isHsVar` fromRationalName ) -- A LitInst invariant
711 tcLookupId fromRationalName `thenM` \ from_rational ->
712 tcInstClassOp loc from_rational [ty] `thenM` \ method_inst ->
713 mkRatLit f `thenM` \ rat_lit ->
714 returnM (GenInst [method_inst] (mkHsApp (L (instLocSpan loc)
715 (HsVar (instToId method_inst))) rat_lit))
717 --------------------- Dictionaries ------------------------
718 lookupSimpleInst (Dict {tci_pred = pred, tci_loc = loc})
719 = do { mb_result <- lookupPred pred
720 ; case mb_result of {
721 Nothing -> return NoInstance ;
722 Just (tenv, dfun_id) -> do
724 -- tenv is a substitution that instantiates the dfun_id
725 -- to match the requested result type.
727 -- We ASSUME that the dfun is quantified over the very same tyvars
728 -- that are bound by the tenv.
731 -- might have some tyvars that *only* appear in arguments
732 -- dfun :: forall a b. C a b, Ord b => D [a]
733 -- We instantiate b to a flexi type variable -- it'll presumably
734 -- become fixed later via functional dependencies
735 { use_stage <- getStage
736 ; checkWellStaged (ptext SLIT("instance for") <+> quotes (ppr pred))
737 (topIdLvl dfun_id) use_stage
739 -- It's possible that not all the tyvars are in
740 -- the substitution, tenv. For example:
741 -- instance C X a => D X where ...
742 -- (presumably there's a functional dependency in class C)
743 -- Hence the open_tvs to instantiate any un-substituted tyvars.
744 ; let (tyvars, rho) = tcSplitForAllTys (idType dfun_id)
745 open_tvs = filter (`notElemTvSubst` tenv) tyvars
746 ; open_tvs' <- mappM tcInstTyVar open_tvs
748 tenv' = extendTvSubstList tenv open_tvs (mkTyVarTys open_tvs')
749 -- Since the open_tvs' are freshly made, they cannot possibly be captured by
750 -- any nested for-alls in rho. So the in-scope set is unchanged
751 dfun_rho = substTy tenv' rho
752 (theta, _) = tcSplitPhiTy dfun_rho
753 src_loc = instLocSpan loc
755 tys = map (substTyVar tenv') tyvars
757 returnM (GenInst [] (L src_loc $ HsWrap (mkWpTyApps tys) dfun))
759 { (dicts, dict_app) <- instCallDicts loc theta
760 ; let co_fn = dict_app <.> mkWpTyApps tys
761 ; returnM (GenInst dicts (L src_loc $ HsWrap co_fn dfun))
765 lookupPred :: TcPredType -> TcM (Maybe (TvSubst, DFunId))
766 -- Look up a class constraint in the instance environment
767 lookupPred pred@(ClassP clas tys)
769 ; tcg_env <- getGblEnv
770 ; let inst_envs = (eps_inst_env eps, tcg_inst_env tcg_env)
771 ; case lookupInstEnv inst_envs clas tys of {
772 ([(tenv, ispec)], [])
773 -> do { let dfun_id = is_dfun ispec
774 ; traceTc (text "lookupInst success" <+>
775 vcat [text "dict" <+> ppr pred,
776 text "witness" <+> ppr dfun_id
777 <+> ppr (idType dfun_id) ])
778 -- Record that this dfun is needed
779 ; record_dfun_usage dfun_id
780 ; return (Just (tenv, dfun_id)) } ;
783 -> do { traceTc (text "lookupInst fail" <+>
784 vcat [text "dict" <+> ppr pred,
785 text "matches" <+> ppr matches,
786 text "unifs" <+> ppr unifs])
787 -- In the case of overlap (multiple matches) we report
788 -- NoInstance here. That has the effect of making the
789 -- context-simplifier return the dict as an irreducible one.
790 -- Then it'll be given to addNoInstanceErrs, which will do another
791 -- lookupInstEnv to get the detailed info about what went wrong.
795 lookupPred ip_pred = return Nothing -- Implicit parameters
797 record_dfun_usage dfun_id
798 = do { hsc_env <- getTopEnv
799 ; let dfun_name = idName dfun_id
800 dfun_mod = nameModule dfun_name
801 ; if isInternalName dfun_name || -- Internal name => defined in this module
802 modulePackageId dfun_mod /= thisPackage (hsc_dflags hsc_env)
803 then return () -- internal, or in another package
804 else do { tcg_env <- getGblEnv
805 ; updMutVar (tcg_inst_uses tcg_env)
806 (`addOneToNameSet` idName dfun_id) }}
809 tcGetInstEnvs :: TcM (InstEnv, InstEnv)
810 -- Gets both the external-package inst-env
811 -- and the home-pkg inst env (includes module being compiled)
812 tcGetInstEnvs = do { eps <- getEps; env <- getGblEnv;
813 return (eps_inst_env eps, tcg_inst_env env) }
818 %************************************************************************
822 %************************************************************************
824 Suppose we are doing the -fno-implicit-prelude thing, and we encounter
825 a do-expression. We have to find (>>) in the current environment, which is
826 done by the rename. Then we have to check that it has the same type as
827 Control.Monad.(>>). Or, more precisely, a compatible type. One 'customer' had
830 (>>) :: HB m n mn => m a -> n b -> mn b
832 So the idea is to generate a local binding for (>>), thus:
834 let then72 :: forall a b. m a -> m b -> m b
835 then72 = ...something involving the user's (>>)...
837 ...the do-expression...
839 Now the do-expression can proceed using then72, which has exactly
842 In fact tcSyntaxName just generates the RHS for then72, because we only
843 want an actual binding in the do-expression case. For literals, we can
844 just use the expression inline.
847 tcSyntaxName :: InstOrigin
848 -> TcType -- Type to instantiate it at
849 -> (Name, HsExpr Name) -- (Standard name, user name)
850 -> TcM (Name, HsExpr TcId) -- (Standard name, suitable expression)
851 -- *** NOW USED ONLY FOR CmdTop (sigh) ***
852 -- NB: tcSyntaxName calls tcExpr, and hence can do unification.
853 -- So we do not call it from lookupInst, which is called from tcSimplify
855 tcSyntaxName orig ty (std_nm, HsVar user_nm)
857 = newMethodFromName orig ty std_nm `thenM` \ id ->
858 returnM (std_nm, HsVar id)
860 tcSyntaxName orig ty (std_nm, user_nm_expr)
861 = tcLookupId std_nm `thenM` \ std_id ->
863 -- C.f. newMethodAtLoc
864 ([tv], _, tau) = tcSplitSigmaTy (idType std_id)
865 sigma1 = substTyWith [tv] [ty] tau
866 -- Actually, the "tau-type" might be a sigma-type in the
867 -- case of locally-polymorphic methods.
869 addErrCtxtM (syntaxNameCtxt user_nm_expr orig sigma1) $
871 -- Check that the user-supplied thing has the
872 -- same type as the standard one.
873 -- Tiresome jiggling because tcCheckSigma takes a located expression
874 getSrcSpanM `thenM` \ span ->
875 tcPolyExpr (L span user_nm_expr) sigma1 `thenM` \ expr ->
876 returnM (std_nm, unLoc expr)
878 syntaxNameCtxt name orig ty tidy_env
879 = getInstLoc orig `thenM` \ inst_loc ->
881 msg = vcat [ptext SLIT("When checking that") <+> quotes (ppr name) <+>
882 ptext SLIT("(needed by a syntactic construct)"),
883 nest 2 (ptext SLIT("has the required type:") <+> ppr (tidyType tidy_env ty)),
884 nest 2 (ptext SLIT("arising from") <+> pprInstLoc inst_loc)]
886 returnM (tidy_env, msg)