Monadify typecheck/Inst: use do, return and standard monad functions
[ghc-hetmet.git] / compiler / typecheck / Inst.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 The @Inst@ type: dictionaries or method instances
7
8 \begin{code}
9 {-# OPTIONS -w #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 module Inst ( 
17         Inst, 
18
19         pprInstances, pprDictsTheta, pprDictsInFull,    -- User error messages
20         showLIE, pprInst, pprInsts, pprInstInFull,      -- Debugging messages
21
22         tidyInsts, tidyMoreInsts,
23
24         newDictBndr, newDictBndrs, newDictBndrsO,
25         instCall, instStupidTheta,
26         cloneDict, 
27         shortCutFracLit, shortCutIntLit, shortCutStringLit, newIPDict, 
28         newMethod, newMethodFromName, newMethodWithGivenTy, 
29         tcInstClassOp, 
30         tcSyntaxName, isHsVar,
31
32         tyVarsOfInst, tyVarsOfInsts, tyVarsOfLIE, 
33         ipNamesOfInst, ipNamesOfInsts, fdPredsOfInst, fdPredsOfInsts,
34         getDictClassTys, dictPred,
35
36         lookupSimpleInst, LookupInstResult(..), 
37         tcExtendLocalInstEnv, tcGetInstEnvs, getOverlapFlag,
38
39         isAbstractableInst, isEqInst,
40         isDict, isClassDict, isMethod, isImplicInst,
41         isIPDict, isInheritableInst, isMethodOrLit,
42         isTyVarDict, isMethodFor, 
43
44         zonkInst, zonkInsts,
45         instToId, instToVar, instType, instName, instToDictBind,
46         addInstToDictBind,
47
48         InstOrigin(..), InstLoc, pprInstLoc,
49
50         mkWantedCo, mkGivenCo,
51         fromWantedCo, fromGivenCo,
52         eitherEqInst, mkEqInst, mkEqInsts, mkWantedEqInst,
53         finalizeEqInst, writeWantedCoercion,
54         eqInstType, updateEqInstCoercion,
55         eqInstCoercion, eqInstTys
56     ) where
57
58 #include "HsVersions.h"
59
60 import {-# SOURCE #-}   TcExpr( tcPolyExpr )
61 import {-# SOURCE #-}   TcUnify( boxyUnify, unifyType )
62
63 import FastString(FastString)
64 import HsSyn
65 import TcHsSyn
66 import TcRnMonad
67 import TcEnv
68 import InstEnv
69 import FunDeps
70 import TcMType
71 import TcType
72 import Type
73 import TypeRep
74 import Class
75 import Unify
76 import Module
77 import Coercion
78 import HscTypes
79 import CoreFVs
80 import DataCon
81 import Id
82 import Name
83 import NameSet
84 import Literal
85 import Var      ( Var, TyVar )
86 import qualified Var
87 import VarEnv
88 import VarSet
89 import TysWiredIn
90 import PrelNames
91 import BasicTypes
92 import SrcLoc
93 import DynFlags
94 import Bag
95 import Maybes
96 import Util
97 import Unique
98 import Outputable
99 import Data.List
100 import TypeRep
101 import Class
102
103 import Control.Monad
104 \end{code}
105
106
107 Selection
108 ~~~~~~~~~
109 \begin{code}
110 instName :: Inst -> Name
111 instName (EqInst {tci_name = name}) = name
112 instName inst = Var.varName (instToVar inst)
113
114 instToId :: Inst -> TcId
115 instToId inst = WARN( not (isId id), ppr inst ) 
116               id 
117               where
118                 id = instToVar inst
119
120 instToVar :: Inst -> Var
121 instToVar (LitInst {tci_name = nm, tci_ty = ty})
122   = mkLocalId nm ty
123 instToVar (Method {tci_id = id}) 
124   = id
125 instToVar (Dict {tci_name = nm, tci_pred = pred})    
126   | isEqPred pred = Var.mkCoVar nm (mkPredTy pred)
127   | otherwise     = mkLocalId nm (mkPredTy pred)
128 instToVar (ImplicInst {tci_name = nm, tci_tyvars = tvs, tci_given = givens,
129                        tci_wanted = wanteds})
130   = mkLocalId nm (mkImplicTy tvs givens wanteds)
131 instToVar i@(EqInst {})
132   = eitherEqInst i id (\(TyVarTy covar) -> covar)
133
134 instType :: Inst -> Type
135 instType (LitInst {tci_ty = ty})  = ty
136 instType (Method {tci_id = id})   = idType id
137 instType (Dict {tci_pred = pred}) = mkPredTy pred
138 instType imp@(ImplicInst {})      = mkImplicTy (tci_tyvars imp) (tci_given imp) 
139                                                (tci_wanted imp)
140 -- instType i@(EqInst {tci_co = co}) = eitherEqInst i TyVarTy id
141 instType (EqInst {tci_left = ty1, tci_right = ty2}) = mkPredTy (EqPred ty1 ty2)
142
143 mkImplicTy tvs givens wanteds   -- The type of an implication constraint
144   = ASSERT( all isAbstractableInst givens )
145     -- pprTrace "mkImplicTy" (ppr givens) $
146     -- See [Equational Constraints in Implication Constraints]
147     let dict_wanteds = filter (not . isEqInst) wanteds
148     in 
149       mkForAllTys tvs $ 
150       mkPhiTy (map dictPred givens) $
151       if isSingleton dict_wanteds then
152         instType (head dict_wanteds) 
153       else
154         mkTupleTy Boxed (length dict_wanteds) (map instType dict_wanteds)
155
156 dictPred (Dict {tci_pred = pred}) = pred
157 dictPred (EqInst {tci_left=ty1,tci_right=ty2}) = EqPred ty1 ty2
158 dictPred inst                     = pprPanic "dictPred" (ppr inst)
159
160 getDictClassTys (Dict {tci_pred = pred}) = getClassPredTys pred
161 getDictClassTys inst                     = pprPanic "getDictClassTys" (ppr inst)
162
163 -- fdPredsOfInst is used to get predicates that contain functional 
164 -- dependencies *or* might do so.  The "might do" part is because
165 -- a constraint (C a b) might have a superclass with FDs
166 -- Leaving these in is really important for the call to fdPredsOfInsts
167 -- in TcSimplify.inferLoop, because the result is fed to 'grow',
168 -- which is supposed to be conservative
169 fdPredsOfInst (Dict {tci_pred = pred})       = [pred]
170 fdPredsOfInst (Method {tci_theta = theta})   = theta
171 fdPredsOfInst (ImplicInst {tci_given = gs, 
172                            tci_wanted = ws}) = fdPredsOfInsts (gs ++ ws)
173 fdPredsOfInst (LitInst {})                   = []
174 fdPredsOfInst (EqInst {})                    = []
175
176 fdPredsOfInsts :: [Inst] -> [PredType]
177 fdPredsOfInsts insts = concatMap fdPredsOfInst insts
178
179 isInheritableInst (Dict {tci_pred = pred})     = isInheritablePred pred
180 isInheritableInst (Method {tci_theta = theta}) = all isInheritablePred theta
181 isInheritableInst other                        = True
182
183
184 ---------------------------------
185 -- Get the implicit parameters mentioned by these Insts
186 -- NB: the results of these functions are insensitive to zonking
187
188 ipNamesOfInsts :: [Inst] -> [Name]
189 ipNamesOfInst  :: Inst   -> [Name]
190 ipNamesOfInsts insts = [n | inst <- insts, n <- ipNamesOfInst inst]
191
192 ipNamesOfInst (Dict {tci_pred = IParam n _}) = [ipNameName n]
193 ipNamesOfInst (Method {tci_theta = theta})   = [ipNameName n | IParam n _ <- theta]
194 ipNamesOfInst other                          = []
195
196 ---------------------------------
197 tyVarsOfInst :: Inst -> TcTyVarSet
198 tyVarsOfInst (LitInst {tci_ty = ty})  = tyVarsOfType  ty
199 tyVarsOfInst (Dict {tci_pred = pred}) = tyVarsOfPred pred
200 tyVarsOfInst (Method {tci_oid = id, tci_tys = tys}) = tyVarsOfTypes tys `unionVarSet` varTypeTyVars id
201                                  -- The id might have free type variables; in the case of
202                                  -- locally-overloaded class methods, for example
203 tyVarsOfInst (ImplicInst {tci_tyvars = tvs, tci_given = givens, tci_wanted = wanteds})
204   = (tyVarsOfInsts givens `unionVarSet` tyVarsOfInsts wanteds) 
205     `minusVarSet` mkVarSet tvs
206     `unionVarSet` unionVarSets (map varTypeTyVars tvs)
207                 -- Remember the free tyvars of a coercion
208 tyVarsOfInst (EqInst {tci_left = ty1, tci_right = ty2}) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
209
210 tyVarsOfInsts insts = foldr (unionVarSet . tyVarsOfInst) emptyVarSet insts
211 tyVarsOfLIE   lie   = tyVarsOfInsts (lieToList lie)
212
213
214 --------------------------
215 instToDictBind :: Inst -> LHsExpr TcId -> TcDictBinds
216 instToDictBind inst rhs 
217   = unitBag (L (instSpan inst) (VarBind (instToId inst) rhs))
218
219 addInstToDictBind :: TcDictBinds -> Inst -> LHsExpr TcId -> TcDictBinds
220 addInstToDictBind binds inst rhs = binds `unionBags` instToDictBind inst rhs
221 \end{code}
222
223 Predicates
224 ~~~~~~~~~~
225 \begin{code}
226
227 isAbstractableInst :: Inst -> Bool
228 isAbstractableInst inst = isDict inst || isEqInst inst
229
230 isEqInst :: Inst -> Bool
231 isEqInst (EqInst {}) = True
232 isEqInst other       = False
233
234 isDict :: Inst -> Bool
235 isDict (Dict {}) = True
236 isDict other     = False
237
238 isClassDict :: Inst -> Bool
239 isClassDict (Dict {tci_pred = pred}) = isClassPred pred
240 isClassDict other                    = False
241
242 isTyVarDict :: Inst -> Bool
243 isTyVarDict (Dict {tci_pred = pred}) = isTyVarClassPred pred
244 isTyVarDict other                    = False
245
246 isIPDict :: Inst -> Bool
247 isIPDict (Dict {tci_pred = pred}) = isIPPred pred
248 isIPDict other                    = False
249
250 isImplicInst (ImplicInst {}) = True
251 isImplicInst other           = False
252
253 isMethod :: Inst -> Bool
254 isMethod (Method {}) = True
255 isMethod other       = False
256
257 isMethodFor :: TcIdSet -> Inst -> Bool
258 isMethodFor ids (Method {tci_oid = id}) = id `elemVarSet` ids
259 isMethodFor ids inst                    = False
260
261 isMethodOrLit :: Inst -> Bool
262 isMethodOrLit (Method {})  = True
263 isMethodOrLit (LitInst {}) = True
264 isMethodOrLit other        = False
265 \end{code}
266
267
268 %************************************************************************
269 %*                                                                      *
270 \subsection{Building dictionaries}
271 %*                                                                      *
272 %************************************************************************
273
274 -- newDictBndrs makes a dictionary at a binding site
275 -- instCall makes a dictionary at an occurrence site
276 --      and throws it into the LIE
277
278 \begin{code}
279 ----------------
280 newDictBndrsO :: InstOrigin -> TcThetaType -> TcM [Inst]
281 newDictBndrsO orig theta = do { loc <- getInstLoc orig
282                               ; newDictBndrs loc theta }
283
284 newDictBndrs :: InstLoc -> TcThetaType -> TcM [Inst]
285 newDictBndrs inst_loc theta = mapM (newDictBndr inst_loc) theta
286
287 newDictBndr :: InstLoc -> TcPredType -> TcM Inst
288 newDictBndr inst_loc pred@(EqPred ty1 ty2)
289   = do { uniq <- newUnique 
290         ; let name = mkPredName uniq inst_loc pred 
291         ; return (EqInst {tci_name  = name, 
292                           tci_loc   = inst_loc, 
293                           tci_left  = ty1, 
294                           tci_right = ty2, 
295                           tci_co    = mkGivenCo $ TyVarTy (Var.mkCoVar name (PredTy pred))})
296        }
297 newDictBndr inst_loc pred
298   = do  { uniq <- newUnique 
299         ; let name = mkPredName uniq inst_loc pred 
300         ; return (Dict {tci_name = name, tci_pred = pred, tci_loc = inst_loc}) }
301
302 ----------------
303 instCall :: InstOrigin -> [TcType] -> TcThetaType -> TcM HsWrapper
304 -- Instantiate the constraints of a call
305 --      (instCall o tys theta)
306 -- (a) Makes fresh dictionaries as necessary for the constraints (theta)
307 -- (b) Throws these dictionaries into the LIE
308 -- (c) Returns an HsWrapper ([.] tys dicts)
309
310 instCall orig tys theta 
311   = do  { loc <- getInstLoc orig
312         ; dict_app <- instCallDicts loc theta
313         ; return (dict_app <.> mkWpTyApps tys) }
314
315 ----------------
316 instStupidTheta :: InstOrigin -> TcThetaType -> TcM ()
317 -- Similar to instCall, but only emit the constraints in the LIE
318 -- Used exclusively for the 'stupid theta' of a data constructor
319 instStupidTheta orig theta
320   = do  { loc <- getInstLoc orig
321         ; _co <- instCallDicts loc theta        -- Discard the coercion
322         ; return () }
323
324 ----------------
325 instCallDicts :: InstLoc -> TcThetaType -> TcM HsWrapper
326 -- Instantiates the TcTheta, puts all constraints thereby generated
327 -- into the LIE, and returns a HsWrapper to enclose the call site.
328 -- This is the key place where equality predicates 
329 -- are unleashed into the world
330 instCallDicts loc [] = return idHsWrapper
331
332 -- instCallDicts loc (EqPred ty1 ty2 : preds)
333 --   = do  { unifyType ty1 ty2  -- For now, we insist that they unify right away 
334 --                              -- Later on, when we do associated types, 
335 --                              -- unifyType :: Type -> Type -> TcM ([Inst], Coercion)
336 --      ; (dicts, co_fn) <- instCallDicts loc preds
337 --      ; return (dicts, co_fn <.> WpTyApp ty1) }
338 --      -- We use type application to apply the function to the 
339 --      -- coercion; here ty1 *is* the appropriate identity coercion
340
341 instCallDicts loc (EqPred ty1 ty2 : preds)
342   = do  { traceTc (text "instCallDicts" <+> ppr (EqPred ty1 ty2))
343         ; coi <- boxyUnify ty1 ty2
344 --      ; coi <- unifyType ty1 ty2
345         ; let co = fromCoI coi ty1
346         ; co_fn <- instCallDicts loc preds
347         ; return (co_fn <.> WpTyApp co) }
348
349 instCallDicts loc (pred : preds)
350   = do  { uniq <- newUnique
351         ; let name = mkPredName uniq loc pred 
352               dict = Dict {tci_name = name, tci_pred = pred, tci_loc = loc}
353         ; extendLIE dict
354         ; co_fn <- instCallDicts loc preds
355         ; return (co_fn <.> WpApp (instToId dict)) }
356
357 -------------
358 cloneDict :: Inst -> TcM Inst
359 cloneDict dict@(Dict nm ty loc) = do { uniq <- newUnique
360                                      ; return (dict {tci_name = setNameUnique nm uniq}) }
361 cloneDict eq@(EqInst {})        = return eq
362 cloneDict other = pprPanic "cloneDict" (ppr other)
363
364 -- For vanilla implicit parameters, there is only one in scope
365 -- at any time, so we used to use the name of the implicit parameter itself
366 -- But with splittable implicit parameters there may be many in 
367 -- scope, so we make up a new namea.
368 newIPDict :: InstOrigin -> IPName Name -> Type 
369           -> TcM (IPName Id, Inst)
370 newIPDict orig ip_name ty = do
371     inst_loc <- getInstLoc orig
372     uniq <- newUnique
373     let
374         pred = IParam ip_name ty
375         name = mkPredName uniq inst_loc pred 
376         dict = Dict {tci_name = name, tci_pred = pred, tci_loc = inst_loc}
377     
378     return (mapIPName (\n -> instToId dict) ip_name, dict)
379 \end{code}
380
381
382 \begin{code}
383 mkPredName :: Unique -> InstLoc -> PredType -> Name
384 mkPredName uniq loc pred_ty
385   = mkInternalName uniq occ (instLocSpan loc)
386   where
387     occ = case pred_ty of
388             ClassP cls _ -> mkDictOcc (getOccName cls)
389             IParam ip  _ -> getOccName (ipNameName ip)
390             EqPred ty  _ -> mkEqPredCoOcc baseOcc
391               where
392                 -- we use the outermost tycon of the lhs, if there is one, to
393                 -- improve readability of Core code
394                 baseOcc = case splitTyConApp_maybe ty of
395                             Nothing      -> mkOccName tcName "$"
396                             Just (tc, _) -> getOccName tc
397 \end{code}
398
399 %************************************************************************
400 %*                                                                      *
401 \subsection{Building methods (calls of overloaded functions)}
402 %*                                                                      *
403 %************************************************************************
404
405
406 \begin{code}
407 newMethodFromName :: InstOrigin -> BoxyRhoType -> Name -> TcM TcId
408 newMethodFromName origin ty name = do
409     id <- tcLookupId name
410         -- Use tcLookupId not tcLookupGlobalId; the method is almost
411         -- always a class op, but with -fno-implicit-prelude GHC is
412         -- meant to find whatever thing is in scope, and that may
413         -- be an ordinary function. 
414     loc <- getInstLoc origin
415     inst <- tcInstClassOp loc id [ty]
416     extendLIE inst
417     return (instToId inst)
418
419 newMethodWithGivenTy orig id tys = do
420     loc <- getInstLoc orig
421     inst <- newMethod loc id tys
422     extendLIE inst
423     return (instToId inst)
424
425 --------------------------------------------
426 -- tcInstClassOp, and newMethod do *not* drop the 
427 -- Inst into the LIE; they just returns the Inst
428 -- This is important because they are used by TcSimplify
429 -- to simplify Insts
430
431 -- NB: the kind of the type variable to be instantiated
432 --     might be a sub-kind of the type to which it is applied,
433 --     notably when the latter is a type variable of kind ??
434 --     Hence the call to checkKind
435 -- A worry: is this needed anywhere else?
436 tcInstClassOp :: InstLoc -> Id -> [TcType] -> TcM Inst
437 tcInstClassOp inst_loc sel_id tys = do
438     let
439         (tyvars, _rho) = tcSplitForAllTys (idType sel_id)
440     zipWithM_ checkKind tyvars tys
441     newMethod inst_loc sel_id tys
442
443 checkKind :: TyVar -> TcType -> TcM ()
444 -- Ensure that the type has a sub-kind of the tyvar
445 checkKind tv ty
446   = do  { let ty1 = ty 
447                 -- ty1 <- zonkTcType ty
448         ; if typeKind ty1 `isSubKind` Var.tyVarKind tv
449           then return ()
450           else 
451
452     pprPanic "checkKind: adding kind constraint" 
453              (vcat [ppr tv <+> ppr (Var.tyVarKind tv), 
454                     ppr ty <+> ppr ty1 <+> ppr (typeKind ty1)])
455         }
456 --    do        { tv1 <- tcInstTyVar tv
457 --      ; unifyType ty1 (mkTyVarTy tv1) } }
458
459
460 ---------------------------
461 newMethod inst_loc id tys = do
462     new_uniq <- newUnique
463     let
464         (theta,tau) = tcSplitPhiTy (applyTys (idType id) tys)
465         meth_id     = mkUserLocal (mkMethodOcc (getOccName id)) new_uniq tau loc
466         inst        = Method {tci_id = meth_id, tci_oid = id, tci_tys = tys,
467                               tci_theta = theta, tci_loc = inst_loc}
468         loc         = instLocSpan inst_loc
469     
470     return inst
471 \end{code}
472
473 \begin{code}
474 shortCutIntLit :: Integer -> TcType -> Maybe (HsExpr TcId)
475 shortCutIntLit i ty
476   | isIntTy ty && inIntRange i          -- Short cut for Int
477   = Just (HsLit (HsInt i))
478   | isIntegerTy ty                      -- Short cut for Integer
479   = Just (HsLit (HsInteger i ty))
480   | otherwise = Nothing
481
482 shortCutFracLit :: Rational -> TcType -> Maybe (HsExpr TcId)
483 shortCutFracLit f ty
484   | isFloatTy ty 
485   = Just (mk_lit floatDataCon (HsFloatPrim f))
486   | isDoubleTy ty
487   = Just (mk_lit doubleDataCon (HsDoublePrim f))
488   | otherwise = Nothing
489   where
490     mk_lit con lit = HsApp (nlHsVar (dataConWrapId con)) (nlHsLit lit)
491
492 shortCutStringLit :: FastString -> TcType -> Maybe (HsExpr TcId)
493 shortCutStringLit s ty
494   | isStringTy ty                       -- Short cut for String
495   = Just (HsLit (HsString s))
496   | otherwise = Nothing
497
498 mkIntegerLit :: Integer -> TcM (LHsExpr TcId)
499 mkIntegerLit i = do
500     integer_ty <- tcMetaTy integerTyConName
501     span <- getSrcSpanM
502     return (L span $ HsLit (HsInteger i integer_ty))
503
504 mkRatLit :: Rational -> TcM (LHsExpr TcId)
505 mkRatLit r = do
506     rat_ty <- tcMetaTy rationalTyConName
507     span <- getSrcSpanM
508     return (L span $ HsLit (HsRat r rat_ty))
509
510 mkStrLit :: FastString -> TcM (LHsExpr TcId)
511 mkStrLit s = do
512     --string_ty <- tcMetaTy stringTyConName
513     span <- getSrcSpanM
514     return (L span $ HsLit (HsString s))
515
516 isHsVar :: HsExpr Name -> Name -> Bool
517 isHsVar (HsVar f) g = f==g
518 isHsVar other     g = False
519 \end{code}
520
521
522 %************************************************************************
523 %*                                                                      *
524 \subsection{Zonking}
525 %*                                                                      *
526 %************************************************************************
527
528 Zonking makes sure that the instance types are fully zonked.
529
530 \begin{code}
531 zonkInst :: Inst -> TcM Inst
532 zonkInst dict@(Dict { tci_pred = pred}) = do
533     new_pred <- zonkTcPredType pred
534     return (dict {tci_pred = new_pred})
535
536 zonkInst meth@(Method {tci_oid = id, tci_tys = tys, tci_theta = theta}) = do
537     new_id <- zonkId id
538         -- Essential to zonk the id in case it's a local variable
539         -- Can't use zonkIdOcc because the id might itself be
540         -- an InstId, in which case it won't be in scope
541
542     new_tys <- zonkTcTypes tys
543     new_theta <- zonkTcThetaType theta
544     return (meth { tci_oid = new_id, tci_tys = new_tys, tci_theta = new_theta })
545         -- No need to zonk the tci_id
546
547 zonkInst lit@(LitInst {tci_ty = ty}) = do
548     new_ty <- zonkTcType ty
549     return (lit {tci_ty = new_ty})
550
551 zonkInst implic@(ImplicInst {})
552   = ASSERT( all isImmutableTyVar (tci_tyvars implic) )
553     do  { givens'  <- zonkInsts (tci_given  implic)
554         ; wanteds' <- zonkInsts (tci_wanted implic)
555         ; return (implic {tci_given = givens',tci_wanted = wanteds'}) }
556
557 zonkInst eqinst@(EqInst {tci_left = ty1, tci_right = ty2})
558   = do { co' <- eitherEqInst eqinst 
559                   (\covar -> return (mkWantedCo covar)) 
560                   (\co    -> liftM mkGivenCo $ zonkTcType co)
561        ; ty1' <- zonkTcType ty1
562        ; ty2' <- zonkTcType ty2
563        ; return (eqinst {tci_co = co', tci_left= ty1', tci_right = ty2' })
564        }
565
566 zonkInsts insts = mapM zonkInst insts
567 \end{code}
568
569
570 %************************************************************************
571 %*                                                                      *
572 \subsection{Printing}
573 %*                                                                      *
574 %************************************************************************
575
576 ToDo: improve these pretty-printing things.  The ``origin'' is really only
577 relevant in error messages.
578
579 \begin{code}
580 instance Outputable Inst where
581     ppr inst = pprInst inst
582
583 pprDictsTheta :: [Inst] -> SDoc
584 -- Print in type-like fashion (Eq a, Show b)
585 -- The Inst can be an implication constraint, but not a Method or LitInst
586 pprDictsTheta insts = parens (sep (punctuate comma (map (ppr . instType) insts)))
587
588 pprDictsInFull :: [Inst] -> SDoc
589 -- Print in type-like fashion, but with source location
590 pprDictsInFull dicts 
591   = vcat (map go dicts)
592   where
593     go dict = sep [quotes (ppr (instType dict)), nest 2 (pprInstArising dict)]
594
595 pprInsts :: [Inst] -> SDoc
596 -- Debugging: print the evidence :: type
597 pprInsts insts = brackets (interpp'SP insts)
598
599 pprInst, pprInstInFull :: Inst -> SDoc
600 -- Debugging: print the evidence :: type
601 pprInst i@(EqInst {tci_left = ty1, tci_right = ty2, tci_co = co}) 
602         = eitherEqInst i
603                 (\covar -> text "Wanted" <+> ppr (TyVarTy covar) <+> dcolon <+> ppr (EqPred ty1 ty2))
604                 (\co    -> text "Given"  <+> ppr co              <+> dcolon <+> ppr (EqPred ty1 ty2))
605 pprInst inst = ppr name <> braces (pprUnique (getUnique name)) <+> dcolon 
606                 <+> (braces (ppr (instType inst) <> implicWantedEqs) $$
607                      ifPprDebug implic_stuff)
608   where
609     name = instName inst
610     (implic_stuff, implicWantedEqs) 
611       | isImplicInst inst = (ppr (tci_reft inst),
612                             text " &" <+> 
613                             ppr (filter isEqInst (tci_wanted inst)))
614       | otherwise         = (empty, empty)
615
616 pprInstInFull inst@(EqInst {}) = pprInst inst
617 pprInstInFull inst = sep [quotes (pprInst inst), nest 2 (pprInstArising inst)]
618
619 tidyInst :: TidyEnv -> Inst -> Inst
620 tidyInst env eq@(EqInst {tci_left = lty, tci_right = rty, tci_co = co}) =
621   eq { tci_left  = tidyType env lty
622      , tci_right = tidyType env rty
623      , tci_co    = either Left (Right . tidyType env) co
624      }
625 tidyInst env lit@(LitInst {tci_ty = ty})   = lit {tci_ty = tidyType env ty}
626 tidyInst env dict@(Dict {tci_pred = pred}) = dict {tci_pred = tidyPred env pred}
627 tidyInst env meth@(Method {tci_tys = tys}) = meth {tci_tys = tidyTypes env tys}
628 tidyInst env implic@(ImplicInst {})
629   = implic { tci_tyvars = tvs' 
630            , tci_given  = map (tidyInst env') (tci_given  implic)
631            , tci_wanted = map (tidyInst env') (tci_wanted implic) }
632   where
633     (env', tvs') = mapAccumL tidyTyVarBndr env (tci_tyvars implic)
634
635 tidyMoreInsts :: TidyEnv -> [Inst] -> (TidyEnv, [Inst])
636 -- This function doesn't assume that the tyvars are in scope
637 -- so it works like tidyOpenType, returning a TidyEnv
638 tidyMoreInsts env insts
639   = (env', map (tidyInst env') insts)
640   where
641     env' = tidyFreeTyVars env (tyVarsOfInsts insts)
642
643 tidyInsts :: [Inst] -> (TidyEnv, [Inst])
644 tidyInsts insts = tidyMoreInsts emptyTidyEnv insts
645
646 showLIE :: SDoc -> TcM ()       -- Debugging
647 showLIE str
648   = do { lie_var <- getLIEVar ;
649          lie <- readMutVar lie_var ;
650          traceTc (str <+> vcat (map pprInstInFull (lieToList lie))) }
651 \end{code}
652
653
654 %************************************************************************
655 %*                                                                      *
656         Extending the instance environment
657 %*                                                                      *
658 %************************************************************************
659
660 \begin{code}
661 tcExtendLocalInstEnv :: [Instance] -> TcM a -> TcM a
662   -- Add new locally-defined instances
663 tcExtendLocalInstEnv dfuns thing_inside
664  = do { traceDFuns dfuns
665       ; env <- getGblEnv
666       ; inst_env' <- foldlM addLocalInst (tcg_inst_env env) dfuns
667       ; let env' = env { tcg_insts = dfuns ++ tcg_insts env,
668                          tcg_inst_env = inst_env' }
669       ; setGblEnv env' thing_inside }
670
671 addLocalInst :: InstEnv -> Instance -> TcM InstEnv
672 -- Check that the proposed new instance is OK, 
673 -- and then add it to the home inst env
674 addLocalInst home_ie ispec
675   = do  {       -- Instantiate the dfun type so that we extend the instance
676                 -- envt with completely fresh template variables
677                 -- This is important because the template variables must
678                 -- not overlap with anything in the things being looked up
679                 -- (since we do unification).  
680                 -- We use tcInstSkolType because we don't want to allocate fresh
681                 --  *meta* type variables.  
682           let dfun = instanceDFunId ispec
683         ; (tvs', theta', tau') <- tcInstSkolType InstSkol (idType dfun)
684         ; let   (cls, tys') = tcSplitDFunHead tau'
685                 dfun'       = setIdType dfun (mkSigmaTy tvs' theta' tau')           
686                 ispec'      = setInstanceDFunId ispec dfun'
687
688                 -- Load imported instances, so that we report
689                 -- duplicates correctly
690         ; eps <- getEps
691         ; let inst_envs = (eps_inst_env eps, home_ie)
692
693                 -- Check functional dependencies
694         ; case checkFunDeps inst_envs ispec' of
695                 Just specs -> funDepErr ispec' specs
696                 Nothing    -> return ()
697
698                 -- Check for duplicate instance decls
699         ; let { (matches, _) = lookupInstEnv inst_envs cls tys'
700               ; dup_ispecs = [ dup_ispec 
701                              | (dup_ispec, _) <- matches
702                              , let (_,_,_,dup_tys) = instanceHead dup_ispec
703                              , isJust (tcMatchTys (mkVarSet tvs') tys' dup_tys)] }
704                 -- Find memebers of the match list which ispec itself matches.
705                 -- If the match is 2-way, it's a duplicate
706         ; case dup_ispecs of
707             dup_ispec : _ -> dupInstErr ispec' dup_ispec
708             []            -> return ()
709
710                 -- OK, now extend the envt
711         ; return (extendInstEnv home_ie ispec') }
712
713 getOverlapFlag :: TcM OverlapFlag
714 getOverlapFlag 
715   = do  { dflags <- getDOpts
716         ; let overlap_ok    = dopt Opt_OverlappingInstances dflags
717               incoherent_ok = dopt Opt_IncoherentInstances  dflags
718               overlap_flag | incoherent_ok = Incoherent
719                            | overlap_ok    = OverlapOk
720                            | otherwise     = NoOverlap
721                            
722         ; return overlap_flag }
723
724 traceDFuns ispecs
725   = traceTc (hang (text "Adding instances:") 2 (vcat (map pp ispecs)))
726   where
727     pp ispec = ppr (instanceDFunId ispec) <+> colon <+> ppr ispec
728         -- Print the dfun name itself too
729
730 funDepErr ispec ispecs
731   = addDictLoc ispec $
732     addErr (hang (ptext SLIT("Functional dependencies conflict between instance declarations:"))
733                2 (pprInstances (ispec:ispecs)))
734 dupInstErr ispec dup_ispec
735   = addDictLoc ispec $
736     addErr (hang (ptext SLIT("Duplicate instance declarations:"))
737                2 (pprInstances [ispec, dup_ispec]))
738
739 addDictLoc ispec thing_inside
740   = setSrcSpan (mkSrcSpan loc loc) thing_inside
741   where
742    loc = getSrcLoc ispec
743 \end{code}
744     
745
746 %************************************************************************
747 %*                                                                      *
748 \subsection{Looking up Insts}
749 %*                                                                      *
750 %************************************************************************
751
752 \begin{code}
753 data LookupInstResult
754   = NoInstance
755   | GenInst [Inst] (LHsExpr TcId)       -- The expression and its needed insts
756
757 lookupSimpleInst :: Inst -> TcM LookupInstResult
758 -- This is "simple" in that it returns NoInstance for implication constraints
759
760 -- It's important that lookupInst does not put any new stuff into
761 -- the LIE.  Instead, any Insts needed by the lookup are returned in
762 -- the LookupInstResult, where they can be further processed by tcSimplify
763
764 lookupSimpleInst (EqInst {}) = return NoInstance
765
766 --------------------- Implications ------------------------
767 lookupSimpleInst (ImplicInst {}) = return NoInstance
768
769 --------------------- Methods ------------------------
770 lookupSimpleInst (Method {tci_oid = id, tci_tys = tys, tci_theta = theta, tci_loc = loc})
771   = do  { (dict_app, dicts) <- getLIE $ instCallDicts loc theta
772         ; let co_fn = dict_app <.> mkWpTyApps tys
773         ; return (GenInst dicts (L span $ HsWrap co_fn (HsVar id))) }
774   where
775     span = instLocSpan loc
776
777 --------------------- Literals ------------------------
778 -- Look for short cuts first: if the literal is *definitely* a 
779 -- int, integer, float or a double, generate the real thing here.
780 -- This is essential (see nofib/spectral/nucleic).
781 -- [Same shortcut as in newOverloadedLit, but we
782 --  may have done some unification by now]              
783
784 lookupSimpleInst (LitInst {tci_lit = HsIntegral i from_integer_name _, tci_ty = ty, tci_loc = loc})
785   | Just expr <- shortCutIntLit i ty
786   = return (GenInst [] (noLoc expr))
787   | otherwise
788   = ASSERT( from_integer_name `isHsVar` fromIntegerName ) do    -- A LitInst invariant
789     from_integer <- tcLookupId fromIntegerName
790     method_inst <- tcInstClassOp loc from_integer [ty]
791     integer_lit <- mkIntegerLit i
792     return (GenInst [method_inst]
793                      (mkHsApp (L (instLocSpan loc)
794                                  (HsVar (instToId method_inst))) integer_lit))
795
796 lookupSimpleInst (LitInst {tci_lit = HsFractional f from_rat_name _, tci_ty = ty, tci_loc = loc})
797   | Just expr <- shortCutFracLit f ty
798   = return (GenInst [] (noLoc expr))
799
800   | otherwise
801   = ASSERT( from_rat_name `isHsVar` fromRationalName ) do       -- A LitInst invariant
802     from_rational <- tcLookupId fromRationalName
803     method_inst <- tcInstClassOp loc from_rational [ty]
804     rat_lit <- mkRatLit f
805     return (GenInst [method_inst] (mkHsApp (L (instLocSpan loc) 
806                                                (HsVar (instToId method_inst))) rat_lit))
807
808 lookupSimpleInst (LitInst {tci_lit = HsIsString s from_string_name _, tci_ty = ty, tci_loc = loc})
809   | Just expr <- shortCutStringLit s ty
810   = return (GenInst [] (noLoc expr))
811   | otherwise
812   = ASSERT( from_string_name `isHsVar` fromStringName ) do      -- A LitInst invariant
813     from_string <- tcLookupId fromStringName
814     method_inst <- tcInstClassOp loc from_string [ty]
815     string_lit <- mkStrLit s
816     return (GenInst [method_inst]
817                      (mkHsApp (L (instLocSpan loc)
818                                  (HsVar (instToId method_inst))) string_lit))
819
820 --------------------- Dictionaries ------------------------
821 lookupSimpleInst (Dict {tci_pred = pred, tci_loc = loc})
822   = do  { mb_result <- lookupPred pred
823         ; case mb_result of {
824             Nothing -> return NoInstance ;
825             Just (dfun_id, mb_inst_tys) -> do
826
827     { use_stage <- getStage
828     ; checkWellStaged (ptext SLIT("instance for") <+> quotes (ppr pred))
829                       (topIdLvl dfun_id) use_stage
830
831         -- It's possible that not all the tyvars are in
832         -- the substitution, tenv. For example:
833         --      instance C X a => D X where ...
834         -- (presumably there's a functional dependency in class C)
835         -- Hence mb_inst_tys :: Either TyVar TcType 
836
837     ; let inst_tv (Left tv)  = do { tv' <- tcInstTyVar tv; return (mkTyVarTy tv') }
838           inst_tv (Right ty) = return ty
839     ; tys <- mapM inst_tv mb_inst_tys
840     ; let
841         (theta, _) = tcSplitPhiTy (applyTys (idType dfun_id) tys)
842         src_loc    = instLocSpan loc
843         dfun       = HsVar dfun_id
844     ; if null theta then
845         return (GenInst [] (L src_loc $ HsWrap (mkWpTyApps tys) dfun))
846       else do
847     { (dict_app, dicts) <- getLIE $ instCallDicts loc theta -- !!!
848     ; let co_fn = dict_app <.> mkWpTyApps tys
849     ; return (GenInst dicts (L src_loc $ HsWrap co_fn dfun))
850     }}}}
851
852 ---------------
853 lookupPred :: TcPredType -> TcM (Maybe (DFunId, [Either TyVar TcType]))
854 -- Look up a class constraint in the instance environment
855 lookupPred pred@(ClassP clas tys)
856   = do  { eps     <- getEps
857         ; tcg_env <- getGblEnv
858         ; let inst_envs = (eps_inst_env eps, tcg_inst_env tcg_env)
859         ; case lookupInstEnv inst_envs clas tys of {
860             ([(ispec, inst_tys)], []) 
861                 -> do   { let dfun_id = is_dfun ispec
862                         ; traceTc (text "lookupInst success" <+> 
863                                    vcat [text "dict" <+> ppr pred, 
864                                          text "witness" <+> ppr dfun_id
865                                          <+> ppr (idType dfun_id) ])
866                                 -- Record that this dfun is needed
867                         ; record_dfun_usage dfun_id
868                         ; return (Just (dfun_id, inst_tys)) } ;
869
870             (matches, unifs)
871                 -> do   { traceTc (text "lookupInst fail" <+> 
872                                    vcat [text "dict" <+> ppr pred,
873                                          text "matches" <+> ppr matches,
874                                          text "unifs" <+> ppr unifs])
875                 -- In the case of overlap (multiple matches) we report
876                 -- NoInstance here.  That has the effect of making the 
877                 -- context-simplifier return the dict as an irreducible one.
878                 -- Then it'll be given to addNoInstanceErrs, which will do another
879                 -- lookupInstEnv to get the detailed info about what went wrong.
880                         ; return Nothing }
881         }}
882
883 lookupPred ip_pred = return Nothing     -- Implicit parameters
884
885 record_dfun_usage dfun_id 
886   = do  { hsc_env <- getTopEnv
887         ; let  dfun_name = idName dfun_id
888                dfun_mod  = nameModule dfun_name
889         ; if isInternalName dfun_name ||    -- Internal name => defined in this module
890              modulePackageId dfun_mod /= thisPackage (hsc_dflags hsc_env)
891           then return () -- internal, or in another package
892            else do { tcg_env <- getGblEnv
893                    ; updMutVar (tcg_inst_uses tcg_env)
894                                (`addOneToNameSet` idName dfun_id) }}
895
896
897 tcGetInstEnvs :: TcM (InstEnv, InstEnv)
898 -- Gets both the external-package inst-env
899 -- and the home-pkg inst env (includes module being compiled)
900 tcGetInstEnvs = do { eps <- getEps; env <- getGblEnv;
901                      return (eps_inst_env eps, tcg_inst_env env) }
902 \end{code}
903
904
905
906 %************************************************************************
907 %*                                                                      *
908                 Re-mappable syntax
909 %*                                                                      *
910 %************************************************************************
911
912 Suppose we are doing the -fno-implicit-prelude thing, and we encounter
913 a do-expression.  We have to find (>>) in the current environment, which is
914 done by the rename. Then we have to check that it has the same type as
915 Control.Monad.(>>).  Or, more precisely, a compatible type. One 'customer' had
916 this:
917
918   (>>) :: HB m n mn => m a -> n b -> mn b
919
920 So the idea is to generate a local binding for (>>), thus:
921
922         let then72 :: forall a b. m a -> m b -> m b
923             then72 = ...something involving the user's (>>)...
924         in
925         ...the do-expression...
926
927 Now the do-expression can proceed using then72, which has exactly
928 the expected type.
929
930 In fact tcSyntaxName just generates the RHS for then72, because we only
931 want an actual binding in the do-expression case. For literals, we can 
932 just use the expression inline.
933
934 \begin{code}
935 tcSyntaxName :: InstOrigin
936              -> TcType                  -- Type to instantiate it at
937              -> (Name, HsExpr Name)     -- (Standard name, user name)
938              -> TcM (Name, HsExpr TcId) -- (Standard name, suitable expression)
939 --      *** NOW USED ONLY FOR CmdTop (sigh) ***
940 -- NB: tcSyntaxName calls tcExpr, and hence can do unification.
941 -- So we do not call it from lookupInst, which is called from tcSimplify
942
943 tcSyntaxName orig ty (std_nm, HsVar user_nm)
944   | std_nm == user_nm
945   = do id <- newMethodFromName orig ty std_nm
946        return (std_nm, HsVar id)
947
948 tcSyntaxName orig ty (std_nm, user_nm_expr) = do
949     std_id <- tcLookupId std_nm
950     let 
951         -- C.f. newMethodAtLoc
952         ([tv], _, tau)  = tcSplitSigmaTy (idType std_id)
953         sigma1          = substTyWith [tv] [ty] tau
954         -- Actually, the "tau-type" might be a sigma-type in the
955         -- case of locally-polymorphic methods.
956
957     addErrCtxtM (syntaxNameCtxt user_nm_expr orig sigma1) $ do
958
959         -- Check that the user-supplied thing has the
960         -- same type as the standard one.  
961         -- Tiresome jiggling because tcCheckSigma takes a located expression
962      span <- getSrcSpanM
963      expr <- tcPolyExpr (L span user_nm_expr) sigma1
964      return (std_nm, unLoc expr)
965
966 syntaxNameCtxt name orig ty tidy_env = do
967     inst_loc <- getInstLoc orig
968     let
969         msg = vcat [ptext SLIT("When checking that") <+> quotes (ppr name) <+> 
970                                 ptext SLIT("(needed by a syntactic construct)"),
971                     nest 2 (ptext SLIT("has the required type:") <+> ppr (tidyType tidy_env ty)),
972                     nest 2 (ptext SLIT("arising from") <+> pprInstLoc inst_loc)]
973     
974     return (tidy_env, msg)
975 \end{code}
976
977 %************************************************************************
978 %*                                                                      *
979                 EqInsts
980 %*                                                                      *
981 %************************************************************************
982
983 \begin{code}
984 mkGivenCo   :: Coercion -> Either TcTyVar Coercion
985 mkGivenCo   =  Right
986
987 mkWantedCo  :: TcTyVar  -> Either TcTyVar Coercion
988 mkWantedCo  =  Left
989
990 fromGivenCo :: Either TcTyVar Coercion -> Coercion
991 fromGivenCo (Right co)   = co
992 fromGivenCo _            = panic "fromGivenCo: not a wanted coercion"
993
994 fromWantedCo :: String -> Either TcTyVar Coercion -> TcTyVar
995 fromWantedCo _ (Left covar) = covar
996 fromWantedCo msg _          = panic ("fromWantedCo: not a wanted coercion: " ++ msg)
997
998 eitherEqInst :: Inst                -- given or wanted EqInst
999              -> (TcTyVar  -> a)     --  result if wanted
1000              -> (Coercion -> a)     --  result if given
1001              -> a               
1002 eitherEqInst (EqInst {tci_co = either_co}) withWanted withGiven
1003         = case either_co of
1004                 Left  covar -> withWanted covar
1005                 Right co    -> withGiven  co
1006
1007 mkEqInsts :: [PredType] -> [Either TcTyVar Coercion] -> TcM [Inst]
1008 mkEqInsts preds cos = zipWithM mkEqInst preds cos
1009
1010 mkEqInst :: PredType -> Either TcTyVar Coercion -> TcM Inst
1011 mkEqInst (EqPred ty1 ty2) co
1012         = do { uniq <- newUnique
1013              ; src_span <- getSrcSpanM
1014              ; err_ctxt <- getErrCtxt
1015              ; let loc  = InstLoc EqOrigin src_span err_ctxt
1016                    name = mkName uniq src_span
1017                    inst = EqInst {tci_left = ty1, tci_right = ty2, tci_co = co, tci_loc = loc, tci_name = name} 
1018              ; return inst
1019              }
1020         where mkName uniq src_span = mkInternalName uniq (mkVarOcc "co") src_span
1021
1022 mkWantedEqInst :: PredType -> TcM Inst
1023 mkWantedEqInst pred@(EqPred ty1 ty2)
1024   = do { cotv <- newMetaCoVar ty1 ty2
1025        ; mkEqInst pred (Left cotv)
1026        }
1027
1028 -- type inference:
1029 --      We want to promote the wanted EqInst to a given EqInst
1030 --      in the signature context.
1031 --      This means we have to give the coercion a name
1032 --      and fill it in as its own name.
1033 finalizeEqInst 
1034         :: Inst                 -- wanted
1035         -> TcM Inst             -- given
1036 finalizeEqInst wanted@(EqInst {tci_left = ty1, tci_right = ty2, tci_name = name})
1037         = do { let var = Var.mkCoVar name (PredTy $ EqPred ty1 ty2)
1038              ; writeWantedCoercion wanted (TyVarTy var)
1039              ; let given = wanted { tci_co = mkGivenCo $ TyVarTy var }
1040              ; return given
1041              }
1042
1043 writeWantedCoercion 
1044         :: Inst         -- wanted EqInst
1045         -> Coercion     -- coercion to fill the hole with
1046         -> TcM ()       
1047 writeWantedCoercion wanted co
1048         = do { let cotv = fromWantedCo "writeWantedCoercion" $ tci_co wanted
1049              ; writeMetaTyVar cotv co
1050              }
1051
1052 eqInstType :: Inst -> TcType
1053 eqInstType inst = eitherEqInst inst mkTyVarTy id
1054
1055 eqInstCoercion :: Inst -> Either TcTyVar Coercion
1056 eqInstCoercion = tci_co
1057
1058 eqInstTys :: Inst -> (TcType, TcType)
1059 eqInstTys inst = (tci_left inst, tci_right inst)
1060
1061 updateEqInstCoercion :: (Either TcTyVar Coercion -> Either TcTyVar Coercion) -> Inst -> Inst
1062 updateEqInstCoercion f inst = inst {tci_co = f $ tci_co inst}
1063 \end{code}