PageRenderTime 406ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/ghc-7.0.4/compiler/types/InstEnv.lhs

http://picorec.googlecode.com/
Haskell | 582 lines | 407 code | 106 blank | 69 comment | 30 complexity | 51009d95b03139e9919fe0d286769cef MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause
  1. %
  2. % (c) The University of Glasgow 2006
  3. % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
  4. %
  5. \section[InstEnv]{Utilities for typechecking instance declarations}
  6. The bits common to TcInstDcls and TcDeriv.
  7. \begin{code}
  8. module InstEnv (
  9. DFunId, OverlapFlag(..),
  10. Instance(..), pprInstance, pprInstanceHdr, pprInstances,
  11. instanceHead, mkLocalInstance, mkImportedInstance,
  12. instanceDFunId, setInstanceDFunId, instanceRoughTcs,
  13. InstEnv, emptyInstEnv, extendInstEnv,
  14. extendInstEnvList, lookupInstEnv, instEnvElts,
  15. classInstances, instanceBindFun,
  16. instanceCantMatch, roughMatchTcs
  17. ) where
  18. #include "HsVersions.h"
  19. import Class
  20. import Var
  21. import VarSet
  22. import Name
  23. import TcType
  24. import TyCon
  25. import Unify
  26. import Outputable
  27. import BasicTypes
  28. import UniqFM
  29. import Id
  30. import FastString
  31. import Data.Maybe ( isJust, isNothing )
  32. \end{code}
  33. %************************************************************************
  34. %* *
  35. \subsection{The key types}
  36. %* *
  37. %************************************************************************
  38. \begin{code}
  39. data Instance
  40. = Instance { is_cls :: Name -- Class name
  41. -- Used for "rough matching"; see Note [Rough-match field]
  42. -- INVARIANT: is_tcs = roughMatchTcs is_tys
  43. , is_tcs :: [Maybe Name] -- Top of type args
  44. -- Used for "proper matching"; see Note [Proper-match fields]
  45. , is_tvs :: TyVarSet -- Template tyvars for full match
  46. , is_tys :: [Type] -- Full arg types
  47. -- INVARIANT: is_dfun Id has type
  48. -- forall is_tvs. (...) => is_cls is_tys
  49. , is_dfun :: DFunId -- See Note [Haddock assumptions]
  50. , is_flag :: OverlapFlag -- See detailed comments with
  51. -- the decl of BasicTypes.OverlapFlag
  52. }
  53. \end{code}
  54. Note [Rough-match field]
  55. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  56. The is_cls, is_tcs fields allow a "rough match" to be done
  57. without poking inside the DFunId. Poking the DFunId forces
  58. us to suck in all the type constructors etc it involves,
  59. which is a total waste of time if it has no chance of matching
  60. So the Name, [Maybe Name] fields allow us to say "definitely
  61. does not match", based only on the Name.
  62. In is_tcs,
  63. Nothing means that this type arg is a type variable
  64. (Just n) means that this type arg is a
  65. TyConApp with a type constructor of n.
  66. This is always a real tycon, never a synonym!
  67. (Two different synonyms might match, but two
  68. different real tycons can't.)
  69. NB: newtypes are not transparent, though!
  70. Note [Proper-match fields]
  71. ~~~~~~~~~~~~~~~~~~~~~~~~~
  72. The is_tvs, is_tys fields are simply cached values, pulled
  73. out (lazily) from the dfun id. They are cached here simply so
  74. that we don't need to decompose the DFunId each time we want
  75. to match it. The hope is that the fast-match fields mean
  76. that we often never poke th proper-match fields
  77. However, note that:
  78. * is_tvs must be a superset of the free vars of is_tys
  79. * The is_dfun must itself be quantified over exactly is_tvs
  80. (This is so that we can use the matching substitution to
  81. instantiate the dfun's context.)
  82. Note [Haddock assumptions]
  83. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  84. For normal user-written instances, Haddock relies on
  85. * the SrcSpan of
  86. * the Name of
  87. * the is_dfun of
  88. * an Instance
  89. being equal to
  90. * the SrcSpan of
  91. * the instance head type of
  92. * the InstDecl used to construct the Instance.
  93. \begin{code}
  94. instanceDFunId :: Instance -> DFunId
  95. instanceDFunId = is_dfun
  96. setInstanceDFunId :: Instance -> DFunId -> Instance
  97. setInstanceDFunId ispec dfun
  98. = ASSERT( idType dfun `tcEqType` idType (is_dfun ispec) )
  99. -- We need to create the cached fields afresh from
  100. -- the new dfun id. In particular, the is_tvs in
  101. -- the Instance must match those in the dfun!
  102. -- We assume that the only thing that changes is
  103. -- the quantified type variables, so the other fields
  104. -- are ok; hence the assert
  105. ispec { is_dfun = dfun, is_tvs = mkVarSet tvs, is_tys = tys }
  106. where
  107. (tvs, _, tys) = tcSplitDFunTy (idType dfun)
  108. instanceRoughTcs :: Instance -> [Maybe Name]
  109. instanceRoughTcs = is_tcs
  110. \end{code}
  111. \begin{code}
  112. instance NamedThing Instance where
  113. getName ispec = getName (is_dfun ispec)
  114. instance Outputable Instance where
  115. ppr = pprInstance
  116. pprInstance :: Instance -> SDoc
  117. -- Prints the Instance as an instance declaration
  118. pprInstance ispec
  119. = hang (pprInstanceHdr ispec)
  120. 2 (ptext (sLit "--") <+> pprNameLoc (getName ispec))
  121. -- * pprInstanceHdr is used in VStudio to populate the ClassView tree
  122. pprInstanceHdr :: Instance -> SDoc
  123. -- Prints the Instance as an instance declaration
  124. pprInstanceHdr ispec@(Instance { is_flag = flag })
  125. = getPprStyle $ \ sty ->
  126. let theta_to_print
  127. | debugStyle sty = theta
  128. | otherwise = drop (dfunNSilent dfun) theta
  129. in ptext (sLit "instance") <+> ppr flag
  130. <+> sep [pprThetaArrow theta_to_print, ppr res_ty]
  131. where
  132. dfun = is_dfun ispec
  133. (_, theta, res_ty) = tcSplitSigmaTy (idType dfun)
  134. -- Print without the for-all, which the programmer doesn't write
  135. pprInstances :: [Instance] -> SDoc
  136. pprInstances ispecs = vcat (map pprInstance ispecs)
  137. instanceHead :: Instance -> ([TyVar], ThetaType, Class, [Type])
  138. -- Returns the *source* theta, without the silent arguments
  139. instanceHead ispec
  140. = (tvs, drop n_silent theta, cls, tys)
  141. where
  142. (tvs, theta, tau) = tcSplitSigmaTy (idType dfun)
  143. (cls, tys) = tcSplitDFunHead tau
  144. dfun = is_dfun ispec
  145. n_silent = dfunNSilent dfun
  146. mkLocalInstance :: DFunId
  147. -> OverlapFlag
  148. -> Instance
  149. -- Used for local instances, where we can safely pull on the DFunId
  150. mkLocalInstance dfun oflag
  151. = Instance { is_flag = oflag, is_dfun = dfun,
  152. is_tvs = mkVarSet tvs, is_tys = tys,
  153. is_cls = className cls, is_tcs = roughMatchTcs tys }
  154. where
  155. (tvs, cls, tys) = tcSplitDFunTy (idType dfun)
  156. mkImportedInstance :: Name -> [Maybe Name]
  157. -> DFunId -> OverlapFlag -> Instance
  158. -- Used for imported instances, where we get the rough-match stuff
  159. -- from the interface file
  160. mkImportedInstance cls mb_tcs dfun oflag
  161. = Instance { is_flag = oflag, is_dfun = dfun,
  162. is_tvs = mkVarSet tvs, is_tys = tys,
  163. is_cls = cls, is_tcs = mb_tcs }
  164. where
  165. (tvs, _, tys) = tcSplitDFunTy (idType dfun)
  166. roughMatchTcs :: [Type] -> [Maybe Name]
  167. roughMatchTcs tys = map rough tys
  168. where
  169. rough ty = case tcSplitTyConApp_maybe ty of
  170. Just (tc,_) -> Just (tyConName tc)
  171. Nothing -> Nothing
  172. instanceCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
  173. -- (instanceCantMatch tcs1 tcs2) returns True if tcs1 cannot
  174. -- possibly be instantiated to actual, nor vice versa;
  175. -- False is non-committal
  176. instanceCantMatch (Just t : ts) (Just a : as) = t/=a || instanceCantMatch ts as
  177. instanceCantMatch _ _ = False -- Safe
  178. \end{code}
  179. Note [Overlapping instances]
  180. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  181. Overlap is permitted, but only in such a way that one can make
  182. a unique choice when looking up. That is, overlap is only permitted if
  183. one template matches the other, or vice versa. So this is ok:
  184. [a] [Int]
  185. but this is not
  186. (Int,a) (b,Int)
  187. If overlap is permitted, the list is kept most specific first, so that
  188. the first lookup is the right choice.
  189. For now we just use association lists.
  190. \subsection{Avoiding a problem with overlapping}
  191. Consider this little program:
  192. \begin{pseudocode}
  193. class C a where c :: a
  194. class C a => D a where d :: a
  195. instance C Int where c = 17
  196. instance D Int where d = 13
  197. instance C a => C [a] where c = [c]
  198. instance ({- C [a], -} D a) => D [a] where d = c
  199. instance C [Int] where c = [37]
  200. main = print (d :: [Int])
  201. \end{pseudocode}
  202. What do you think `main' prints (assuming we have overlapping instances, and
  203. all that turned on)? Well, the instance for `D' at type `[a]' is defined to
  204. be `c' at the same type, and we've got an instance of `C' at `[Int]', so the
  205. answer is `[37]', right? (the generic `C [a]' instance shouldn't apply because
  206. the `C [Int]' instance is more specific).
  207. Ghc-4.04 gives `[37]', while ghc-4.06 gives `[17]', so 4.06 is wrong. That
  208. was easy ;-) Let's just consult hugs for good measure. Wait - if I use old
  209. hugs (pre-September99), I get `[17]', and stranger yet, if I use hugs98, it
  210. doesn't even compile! What's going on!?
  211. What hugs complains about is the `D [a]' instance decl.
  212. \begin{pseudocode}
  213. ERROR "mj.hs" (line 10): Cannot build superclass instance
  214. *** Instance : D [a]
  215. *** Context supplied : D a
  216. *** Required superclass : C [a]
  217. \end{pseudocode}
  218. You might wonder what hugs is complaining about. It's saying that you
  219. need to add `C [a]' to the context of the `D [a]' instance (as appears
  220. in comments). But there's that `C [a]' instance decl one line above
  221. that says that I can reduce the need for a `C [a]' instance to the
  222. need for a `C a' instance, and in this case, I already have the
  223. necessary `C a' instance (since we have `D a' explicitly in the
  224. context, and `C' is a superclass of `D').
  225. Unfortunately, the above reasoning indicates a premature commitment to the
  226. generic `C [a]' instance. I.e., it prematurely rules out the more specific
  227. instance `C [Int]'. This is the mistake that ghc-4.06 makes. The fix is to
  228. add the context that hugs suggests (uncomment the `C [a]'), effectively
  229. deferring the decision about which instance to use.
  230. Now, interestingly enough, 4.04 has this same bug, but it's covered up
  231. in this case by a little known `optimization' that was disabled in
  232. 4.06. Ghc-4.04 silently inserts any missing superclass context into
  233. an instance declaration. In this case, it silently inserts the `C
  234. [a]', and everything happens to work out.
  235. (See `basicTypes/MkId:mkDictFunId' for the code in question. Search for
  236. `Mark Jones', although Mark claims no credit for the `optimization' in
  237. question, and would rather it stopped being called the `Mark Jones
  238. optimization' ;-)
  239. So, what's the fix? I think hugs has it right. Here's why. Let's try
  240. something else out with ghc-4.04. Let's add the following line:
  241. d' :: D a => [a]
  242. d' = c
  243. Everyone raise their hand who thinks that `d :: [Int]' should give a
  244. different answer from `d' :: [Int]'. Well, in ghc-4.04, it does. The
  245. `optimization' only applies to instance decls, not to regular
  246. bindings, giving inconsistent behavior.
  247. Old hugs had this same bug. Here's how we fixed it: like GHC, the
  248. list of instances for a given class is ordered, so that more specific
  249. instances come before more generic ones. For example, the instance
  250. list for C might contain:
  251. ..., C Int, ..., C a, ...
  252. When we go to look for a `C Int' instance we'll get that one first.
  253. But what if we go looking for a `C b' (`b' is unconstrained)? We'll
  254. pass the `C Int' instance, and keep going. But if `b' is
  255. unconstrained, then we don't know yet if the more specific instance
  256. will eventually apply. GHC keeps going, and matches on the generic `C
  257. a'. The fix is to, at each step, check to see if there's a reverse
  258. match, and if so, abort the search. This prevents hugs from
  259. prematurely chosing a generic instance when a more specific one
  260. exists.
  261. --Jeff
  262. BUT NOTE [Nov 2001]: we must actually *unify* not reverse-match in
  263. this test. Suppose the instance envt had
  264. ..., forall a b. C a a b, ..., forall a b c. C a b c, ...
  265. (still most specific first)
  266. Now suppose we are looking for (C x y Int), where x and y are unconstrained.
  267. C x y Int doesn't match the template {a,b} C a a b
  268. but neither does
  269. C a a b match the template {x,y} C x y Int
  270. But still x and y might subsequently be unified so they *do* match.
  271. Simple story: unify, don't match.
  272. %************************************************************************
  273. %* *
  274. InstEnv, ClsInstEnv
  275. %* *
  276. %************************************************************************
  277. A @ClsInstEnv@ all the instances of that class. The @Id@ inside a
  278. ClsInstEnv mapping is the dfun for that instance.
  279. If class C maps to a list containing the item ([a,b], [t1,t2,t3], dfun), then
  280. forall a b, C t1 t2 t3 can be constructed by dfun
  281. or, to put it another way, we have
  282. instance (...) => C t1 t2 t3, witnessed by dfun
  283. \begin{code}
  284. ---------------------------------------------------
  285. type InstEnv = UniqFM ClsInstEnv -- Maps Class to instances for that class
  286. data ClsInstEnv
  287. = ClsIE [Instance] -- The instances for a particular class, in any order
  288. Bool -- True <=> there is an instance of form C a b c
  289. -- If *not* then the common case of looking up
  290. -- (C a b c) can fail immediately
  291. instance Outputable ClsInstEnv where
  292. ppr (ClsIE is b) = ptext (sLit "ClsIE") <+> ppr b <+> pprInstances is
  293. -- INVARIANTS:
  294. -- * The is_tvs are distinct in each Instance
  295. -- of a ClsInstEnv (so we can safely unify them)
  296. -- Thus, the @ClassInstEnv@ for @Eq@ might contain the following entry:
  297. -- [a] ===> dfun_Eq_List :: forall a. Eq a => Eq [a]
  298. -- The "a" in the pattern must be one of the forall'd variables in
  299. -- the dfun type.
  300. emptyInstEnv :: InstEnv
  301. emptyInstEnv = emptyUFM
  302. instEnvElts :: InstEnv -> [Instance]
  303. instEnvElts ie = [elt | ClsIE elts _ <- eltsUFM ie, elt <- elts]
  304. classInstances :: (InstEnv,InstEnv) -> Class -> [Instance]
  305. classInstances (pkg_ie, home_ie) cls
  306. = get home_ie ++ get pkg_ie
  307. where
  308. get env = case lookupUFM env cls of
  309. Just (ClsIE insts _) -> insts
  310. Nothing -> []
  311. extendInstEnvList :: InstEnv -> [Instance] -> InstEnv
  312. extendInstEnvList inst_env ispecs = foldl extendInstEnv inst_env ispecs
  313. extendInstEnv :: InstEnv -> Instance -> InstEnv
  314. extendInstEnv inst_env ins_item@(Instance { is_cls = cls_nm, is_tcs = mb_tcs })
  315. = addToUFM_C add inst_env cls_nm (ClsIE [ins_item] ins_tyvar)
  316. where
  317. add (ClsIE cur_insts cur_tyvar) _ = ClsIE (ins_item : cur_insts)
  318. (ins_tyvar || cur_tyvar)
  319. ins_tyvar = not (any isJust mb_tcs)
  320. \end{code}
  321. %************************************************************************
  322. %* *
  323. Looking up an instance
  324. %* *
  325. %************************************************************************
  326. @lookupInstEnv@ looks up in a @InstEnv@, using a one-way match. Since
  327. the env is kept ordered, the first match must be the only one. The
  328. thing we are looking up can have an arbitrary "flexi" part.
  329. \begin{code}
  330. type InstTypes = [Either TyVar Type]
  331. -- Right ty => Instantiate with this type
  332. -- Left tv => Instantiate with any type of this tyvar's kind
  333. type InstMatch = (Instance, InstTypes)
  334. \end{code}
  335. Note [InstTypes: instantiating types]
  336. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  337. A successful match is an Instance, together with the types at which
  338. the dfun_id in the Instance should be instantiated
  339. The instantiating types are (Mabye Type)s because the dfun
  340. might have some tyvars that *only* appear in arguments
  341. dfun :: forall a b. C a b, Ord b => D [a]
  342. When we match this against D [ty], we return the instantiating types
  343. [Right ty, Left b]
  344. where the Nothing indicates that 'b' can be freely instantiated.
  345. (The caller instantiates it to a flexi type variable, which will presumably
  346. presumably later become fixed via functional dependencies.)
  347. \begin{code}
  348. lookupInstEnv :: (InstEnv, InstEnv) -- External and home package inst-env
  349. -> Class -> [Type] -- What we are looking for
  350. -> ([InstMatch], -- Successful matches
  351. [Instance]) -- These don't match but do unify
  352. -- The second component of the result pair happens when we look up
  353. -- Foo [a]
  354. -- in an InstEnv that has entries for
  355. -- Foo [Int]
  356. -- Foo [b]
  357. -- Then which we choose would depend on the way in which 'a'
  358. -- is instantiated. So we report that Foo [b] is a match (mapping b->a)
  359. -- but Foo [Int] is a unifier. This gives the caller a better chance of
  360. -- giving a suitable error messagen
  361. lookupInstEnv (pkg_ie, home_ie) cls tys
  362. = (pruned_matches, all_unifs)
  363. where
  364. rough_tcs = roughMatchTcs tys
  365. all_tvs = all isNothing rough_tcs
  366. (home_matches, home_unifs) = lookup home_ie
  367. (pkg_matches, pkg_unifs) = lookup pkg_ie
  368. all_matches = home_matches ++ pkg_matches
  369. all_unifs = home_unifs ++ pkg_unifs
  370. pruned_matches = foldr insert_overlapping [] all_matches
  371. -- Even if the unifs is non-empty (an error situation)
  372. -- we still prune the matches, so that the error message isn't
  373. -- misleading (complaining of multiple matches when some should be
  374. -- overlapped away)
  375. --------------
  376. lookup env = case lookupUFM env cls of
  377. Nothing -> ([],[]) -- No instances for this class
  378. Just (ClsIE insts has_tv_insts)
  379. | all_tvs && not has_tv_insts
  380. -> ([],[]) -- Short cut for common case
  381. -- The thing we are looking up is of form (C a b c), and
  382. -- the ClsIE has no instances of that form, so don't bother to search
  383. | otherwise
  384. -> find [] [] insts
  385. --------------
  386. lookup_tv :: TvSubst -> TyVar -> Either TyVar Type
  387. -- See Note [InstTypes: instantiating types]
  388. lookup_tv subst tv = case lookupTyVar subst tv of
  389. Just ty -> Right ty
  390. Nothing -> Left tv
  391. find ms us [] = (ms, us)
  392. find ms us (item@(Instance { is_tcs = mb_tcs, is_tvs = tpl_tvs,
  393. is_tys = tpl_tys, is_flag = oflag,
  394. is_dfun = dfun }) : rest)
  395. -- Fast check for no match, uses the "rough match" fields
  396. | instanceCantMatch rough_tcs mb_tcs
  397. = find ms us rest
  398. | Just subst <- tcMatchTys tpl_tvs tpl_tys tys
  399. = let
  400. (dfun_tvs, _) = tcSplitForAllTys (idType dfun)
  401. in
  402. ASSERT( all (`elemVarSet` tpl_tvs) dfun_tvs ) -- Check invariant
  403. find ((item, map (lookup_tv subst) dfun_tvs) : ms) us rest
  404. -- Does not match, so next check whether the things unify
  405. -- See Note [overlapping instances] above
  406. | Incoherent <- oflag
  407. = find ms us rest
  408. | otherwise
  409. = ASSERT2( tyVarsOfTypes tys `disjointVarSet` tpl_tvs,
  410. (ppr cls <+> ppr tys <+> ppr all_tvs) $$
  411. (ppr dfun <+> ppr tpl_tvs <+> ppr tpl_tys)
  412. )
  413. -- Unification will break badly if the variables overlap
  414. -- They shouldn't because we allocate separate uniques for them
  415. case tcUnifyTys instanceBindFun tpl_tys tys of
  416. Just _ -> find ms (item:us) rest
  417. Nothing -> find ms us rest
  418. ---------------
  419. ---------------
  420. insert_overlapping :: InstMatch -> [InstMatch] -> [InstMatch]
  421. -- Add a new solution, knocking out strictly less specific ones
  422. insert_overlapping new_item [] = [new_item]
  423. insert_overlapping new_item (item:items)
  424. | new_beats_old && old_beats_new = item : insert_overlapping new_item items
  425. -- Duplicate => keep both for error report
  426. | new_beats_old = insert_overlapping new_item items
  427. -- Keep new one
  428. | old_beats_new = item : items
  429. -- Keep old one
  430. | otherwise = item : insert_overlapping new_item items
  431. -- Keep both
  432. where
  433. new_beats_old = new_item `beats` item
  434. old_beats_new = item `beats` new_item
  435. (instA, _) `beats` (instB, _)
  436. = overlap_ok &&
  437. isJust (tcMatchTys (is_tvs instB) (is_tys instB) (is_tys instA))
  438. -- A beats B if A is more specific than B, and B admits overlap
  439. -- I.e. if B can be instantiated to match A
  440. where
  441. overlap_ok = case is_flag instB of
  442. NoOverlap -> False
  443. _ -> True
  444. \end{code}
  445. %************************************************************************
  446. %* *
  447. Binding decisions
  448. %* *
  449. %************************************************************************
  450. \begin{code}
  451. instanceBindFun :: TyVar -> BindFlag
  452. instanceBindFun tv | isTcTyVar tv && isOverlappableTyVar tv = Skolem
  453. | otherwise = BindMe
  454. -- Note [Binding when looking up instances]
  455. \end{code}
  456. Note [Binding when looking up instances]
  457. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  458. When looking up in the instance environment, or family-instance environment,
  459. we are careful about multiple matches, as described above in
  460. Note [Overlapping instances]
  461. The key_tys can contain skolem constants, and we can guarantee that those
  462. are never going to be instantiated to anything, so we should not involve
  463. them in the unification test. Example:
  464. class Foo a where { op :: a -> Int }
  465. instance Foo a => Foo [a] -- NB overlap
  466. instance Foo [Int] -- NB overlap
  467. data T = forall a. Foo a => MkT a
  468. f :: T -> Int
  469. f (MkT x) = op [x,x]
  470. The op [x,x] means we need (Foo [a]). Without the filterVarSet we'd
  471. complain, saying that the choice of instance depended on the instantiation
  472. of 'a'; but of course it isn't *going* to be instantiated.
  473. We do this only for isOverlappableTyVar skolems. For example we reject
  474. g :: forall a => [a] -> Int
  475. g x = op x
  476. on the grounds that the correct instance depends on the instantiation of 'a'