PageRenderTime 71ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/types/FamInstEnv.lhs

http://github.com/ghc/ghc
Haskell | 1035 lines | 729 code | 184 blank | 122 comment | 33 complexity | 687310d6424dc941d63a83b89a7eab01 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, GPL-3.0
  1. %
  2. % (c) The University of Glasgow 2006
  3. %
  4. FamInstEnv: Type checked family instance declarations
  5. \begin{code}
  6. {-# LANGUAGE GADTs #-}
  7. module FamInstEnv (
  8. FamInst(..), FamFlavor(..), famInstAxiom, famInstTyCon, famInstRHS,
  9. famInstsRepTyCons, famInstRepTyCon_maybe, dataFamInstRepTyCon,
  10. pprFamInst, pprFamInstHdr, pprFamInsts,
  11. mkImportedFamInst,
  12. FamInstEnvs, FamInstEnv, emptyFamInstEnv, emptyFamInstEnvs,
  13. extendFamInstEnv, deleteFromFamInstEnv, extendFamInstEnvList,
  14. identicalFamInst, famInstEnvElts, familyInstances, orphNamesOfFamInst,
  15. -- * CoAxioms
  16. mkCoAxBranch, mkBranchedCoAxiom, mkUnbranchedCoAxiom, mkSingleCoAxiom,
  17. computeAxiomIncomps,
  18. FamInstMatch(..),
  19. lookupFamInstEnv, lookupFamInstEnvConflicts,
  20. isDominatedBy,
  21. -- Normalisation
  22. chooseBranch, topNormaliseType, normaliseType, normaliseTcApp,
  23. -- Flattening
  24. flattenTys
  25. ) where
  26. #include "HsVersions.h"
  27. import InstEnv
  28. import Unify
  29. import Type
  30. import TcType ( orphNamesOfTypes )
  31. import TypeRep
  32. import TyCon
  33. import Coercion
  34. import CoAxiom
  35. import VarSet
  36. import VarEnv
  37. import Name
  38. import UniqFM
  39. import Outputable
  40. import Maybes
  41. import TrieMap
  42. import Unique
  43. import Util
  44. import Var
  45. import Pair
  46. import SrcLoc
  47. import NameSet
  48. import FastString
  49. \end{code}
  50. %************************************************************************
  51. %* *
  52. Type checked family instance heads
  53. %* *
  54. %************************************************************************
  55. Note [FamInsts and CoAxioms]
  56. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  57. * CoAxioms and FamInsts are just like
  58. DFunIds and ClsInsts
  59. * A CoAxiom is a System-FC thing: it can relate any two types
  60. * A FamInst is a Haskell source-language thing, corresponding
  61. to a type/data family instance declaration.
  62. - The FamInst contains a CoAxiom, which is the evidence
  63. for the instance
  64. - The LHS of the CoAxiom is always of form F ty1 .. tyn
  65. where F is a type family
  66. \begin{code}
  67. data FamInst -- See Note [FamInsts and CoAxioms]
  68. = FamInst { fi_axiom :: CoAxiom Unbranched -- The new coercion axiom introduced
  69. -- by this family instance
  70. , fi_flavor :: FamFlavor
  71. -- Everything below here is a redundant,
  72. -- cached version of the two things above
  73. -- except that the TyVars are freshened
  74. , fi_fam :: Name -- Family name
  75. -- Used for "rough matching"; same idea as for class instances
  76. -- See Note [Rough-match field] in InstEnv
  77. , fi_tcs :: [Maybe Name] -- Top of type args
  78. -- INVARIANT: fi_tcs = roughMatchTcs fi_tys
  79. -- Used for "proper matching"; ditto
  80. , fi_tvs :: [TyVar] -- Template tyvars for full match
  81. -- Like ClsInsts, these variables are always
  82. -- fresh. See Note [Template tyvars are fresh]
  83. -- in InstEnv
  84. , fi_tys :: [Type] -- and its arg types
  85. -- INVARIANT: fi_tvs = coAxiomTyVars fi_axiom
  86. , fi_rhs :: Type -- the RHS, with its freshened vars
  87. }
  88. data FamFlavor
  89. = SynFamilyInst -- A synonym family
  90. | DataFamilyInst TyCon -- A data family, with its representation TyCon
  91. \end{code}
  92. \begin{code}
  93. -- Obtain the axiom of a family instance
  94. famInstAxiom :: FamInst -> CoAxiom Unbranched
  95. famInstAxiom = fi_axiom
  96. -- Split the left-hand side of the FamInst
  97. famInstSplitLHS :: FamInst -> (TyCon, [Type])
  98. famInstSplitLHS (FamInst { fi_axiom = axiom, fi_tys = lhs })
  99. = (coAxiomTyCon axiom, lhs)
  100. -- Get the RHS of the FamInst
  101. famInstRHS :: FamInst -> Type
  102. famInstRHS = fi_rhs
  103. -- Get the family TyCon of the FamInst
  104. famInstTyCon :: FamInst -> TyCon
  105. famInstTyCon = coAxiomTyCon . famInstAxiom
  106. -- Return the representation TyCons introduced by data family instances, if any
  107. famInstsRepTyCons :: [FamInst] -> [TyCon]
  108. famInstsRepTyCons fis = [tc | FamInst { fi_flavor = DataFamilyInst tc } <- fis]
  109. -- Extracts the TyCon for this *data* (or newtype) instance
  110. famInstRepTyCon_maybe :: FamInst -> Maybe TyCon
  111. famInstRepTyCon_maybe fi
  112. = case fi_flavor fi of
  113. DataFamilyInst tycon -> Just tycon
  114. SynFamilyInst -> Nothing
  115. dataFamInstRepTyCon :: FamInst -> TyCon
  116. dataFamInstRepTyCon fi
  117. = case fi_flavor fi of
  118. DataFamilyInst tycon -> tycon
  119. SynFamilyInst -> pprPanic "dataFamInstRepTyCon" (ppr fi)
  120. \end{code}
  121. %************************************************************************
  122. %* *
  123. Pretty printing
  124. %* *
  125. %************************************************************************
  126. \begin{code}
  127. instance NamedThing FamInst where
  128. getName = coAxiomName . fi_axiom
  129. instance Outputable FamInst where
  130. ppr = pprFamInst
  131. -- Prints the FamInst as a family instance declaration
  132. pprFamInst :: FamInst -> SDoc
  133. pprFamInst famInst
  134. = hang (pprFamInstHdr famInst)
  135. 2 (vcat [ ifPprDebug (ptext (sLit "Coercion axiom:") <+> ppr ax)
  136. , ifPprDebug (ptext (sLit "RHS:") <+> ppr (famInstRHS famInst))
  137. , ptext (sLit "--") <+> pprDefinedAt (getName famInst)])
  138. where
  139. ax = fi_axiom famInst
  140. pprFamInstHdr :: FamInst -> SDoc
  141. pprFamInstHdr fi@(FamInst {fi_flavor = flavor})
  142. = pprTyConSort <+> pp_instance <+> pprHead
  143. where
  144. (fam_tc, tys) = famInstSplitLHS fi
  145. -- For *associated* types, say "type T Int = blah"
  146. -- For *top level* type instances, say "type instance T Int = blah"
  147. pp_instance
  148. | isTyConAssoc fam_tc = empty
  149. | otherwise = ptext (sLit "instance")
  150. pprHead = pprTypeApp fam_tc tys
  151. pprTyConSort = case flavor of
  152. SynFamilyInst -> ptext (sLit "type")
  153. DataFamilyInst tycon
  154. | isDataTyCon tycon -> ptext (sLit "data")
  155. | isNewTyCon tycon -> ptext (sLit "newtype")
  156. | isAbstractTyCon tycon -> ptext (sLit "data")
  157. | otherwise -> ptext (sLit "WEIRD") <+> ppr tycon
  158. pprFamInsts :: [FamInst] -> SDoc
  159. pprFamInsts finsts = vcat (map pprFamInst finsts)
  160. \end{code}
  161. Note [Lazy axiom match]
  162. ~~~~~~~~~~~~~~~~~~~~~~~
  163. It is Vitally Important that mkImportedFamInst is *lazy* in its axiom
  164. parameter. The axiom is loaded lazily, via a forkM, in TcIface. Sometime
  165. later, mkImportedFamInst is called using that axiom. However, the axiom
  166. may itself depend on entities which are not yet loaded as of the time
  167. of the mkImportedFamInst. Thus, if mkImportedFamInst eagerly looks at the
  168. axiom, a dependency loop spontaneously appears and GHC hangs. The solution
  169. is simply for mkImportedFamInst never, ever to look inside of the axiom
  170. until everything else is good and ready to do so. We can assume that this
  171. readiness has been achieved when some other code pulls on the axiom in the
  172. FamInst. Thus, we pattern match on the axiom lazily (in the where clause,
  173. not in the parameter list) and we assert the consistency of names there
  174. also.
  175. \begin{code}
  176. -- Make a family instance representation from the information found in an
  177. -- interface file. In particular, we get the rough match info from the iface
  178. -- (instead of computing it here).
  179. mkImportedFamInst :: Name -- Name of the family
  180. -> [Maybe Name] -- Rough match info
  181. -> CoAxiom Unbranched -- Axiom introduced
  182. -> FamInst -- Resulting family instance
  183. mkImportedFamInst fam mb_tcs axiom
  184. = FamInst {
  185. fi_fam = fam,
  186. fi_tcs = mb_tcs,
  187. fi_tvs = tvs,
  188. fi_tys = tys,
  189. fi_rhs = rhs,
  190. fi_axiom = axiom,
  191. fi_flavor = flavor }
  192. where
  193. -- See Note [Lazy axiom match]
  194. ~(CoAxiom { co_ax_branches =
  195. ~(FirstBranch ~(CoAxBranch { cab_lhs = tys
  196. , cab_tvs = tvs
  197. , cab_rhs = rhs })) }) = axiom
  198. -- Derive the flavor for an imported FamInst rather disgustingly
  199. -- Maybe we should store it in the IfaceFamInst?
  200. flavor = case splitTyConApp_maybe rhs of
  201. Just (tc, _)
  202. | Just ax' <- tyConFamilyCoercion_maybe tc
  203. , ax' == axiom
  204. -> DataFamilyInst tc
  205. _ -> SynFamilyInst
  206. \end{code}
  207. %************************************************************************
  208. %* *
  209. FamInstEnv
  210. %* *
  211. %************************************************************************
  212. Note [FamInstEnv]
  213. ~~~~~~~~~~~~~~~~~
  214. A FamInstEnv maps a family name to the list of known instances for that family.
  215. The same FamInstEnv includes both 'data family' and 'type family' instances.
  216. Type families are reduced during type inference, but not data families;
  217. the user explains when to use a data family instance by using contructors
  218. and pattern matching.
  219. Neverthless it is still useful to have data families in the FamInstEnv:
  220. - For finding overlaps and conflicts
  221. - For finding the representation type...see FamInstEnv.topNormaliseType
  222. and its call site in Simplify
  223. - In standalone deriving instance Eq (T [Int]) we need to find the
  224. representation type for T [Int]
  225. Note [Varying number of patterns for data family axioms]
  226. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  227. For data families, the number of patterns may vary between instances.
  228. For example
  229. data family T a b
  230. data instance T Int a = T1 a | T2
  231. data instance T Bool [a] = T3 a
  232. Then we get a data type for each instance, and an axiom:
  233. data TInt a = T1 a | T2
  234. data TBoolList a = T3 a
  235. axiom ax7 :: T Int ~ TInt -- Eta-reduced
  236. axiom ax8 a :: T Bool [a] ~ TBoolList a
  237. These two axioms for T, one with one pattern, one with two. The reason
  238. for this eta-reduction is decribed in TcInstDcls
  239. Note [Eta reduction for data family axioms]
  240. \begin{code}
  241. type FamInstEnv = UniqFM FamilyInstEnv -- Maps a family to its instances
  242. -- See Note [FamInstEnv]
  243. type FamInstEnvs = (FamInstEnv, FamInstEnv)
  244. -- External package inst-env, Home-package inst-env
  245. newtype FamilyInstEnv
  246. = FamIE [FamInst] -- The instances for a particular family, in any order
  247. instance Outputable FamilyInstEnv where
  248. ppr (FamIE fs) = ptext (sLit "FamIE") <+> vcat (map ppr fs)
  249. -- INVARIANTS:
  250. -- * The fs_tvs are distinct in each FamInst
  251. -- of a range value of the map (so we can safely unify them)
  252. emptyFamInstEnvs :: (FamInstEnv, FamInstEnv)
  253. emptyFamInstEnvs = (emptyFamInstEnv, emptyFamInstEnv)
  254. emptyFamInstEnv :: FamInstEnv
  255. emptyFamInstEnv = emptyUFM
  256. famInstEnvElts :: FamInstEnv -> [FamInst]
  257. famInstEnvElts fi = [elt | FamIE elts <- eltsUFM fi, elt <- elts]
  258. familyInstances :: (FamInstEnv, FamInstEnv) -> TyCon -> [FamInst]
  259. familyInstances (pkg_fie, home_fie) fam
  260. = get home_fie ++ get pkg_fie
  261. where
  262. get env = case lookupUFM env fam of
  263. Just (FamIE insts) -> insts
  264. Nothing -> []
  265. -- | Collects the names of the concrete types and type constructors that
  266. -- make up the LHS of a type family instance. For instance,
  267. -- given `type family Foo a b`:
  268. --
  269. -- `type instance Foo (F (G (H a))) b = ...` would yield [F,G,H]
  270. --
  271. -- Used in the implementation of ":info" in GHCi.
  272. orphNamesOfFamInst :: FamInst -> NameSet
  273. orphNamesOfFamInst
  274. = orphNamesOfTypes . concat . brListMap cab_lhs . coAxiomBranches . fi_axiom
  275. extendFamInstEnvList :: FamInstEnv -> [FamInst] -> FamInstEnv
  276. extendFamInstEnvList inst_env fis = foldl extendFamInstEnv inst_env fis
  277. extendFamInstEnv :: FamInstEnv -> FamInst -> FamInstEnv
  278. extendFamInstEnv inst_env ins_item@(FamInst {fi_fam = cls_nm})
  279. = addToUFM_C add inst_env cls_nm (FamIE [ins_item])
  280. where
  281. add (FamIE items) _ = FamIE (ins_item:items)
  282. deleteFromFamInstEnv :: FamInstEnv -> FamInst -> FamInstEnv
  283. deleteFromFamInstEnv inst_env fam_inst@(FamInst {fi_fam = fam_nm})
  284. = adjustUFM adjust inst_env fam_nm
  285. where
  286. adjust :: FamilyInstEnv -> FamilyInstEnv
  287. adjust (FamIE items)
  288. = FamIE (filterOut (identicalFamInst fam_inst) items)
  289. identicalFamInst :: FamInst -> FamInst -> Bool
  290. -- Same LHS, *and* the instance is defined in the same module
  291. -- Used for overriding in GHCi
  292. identicalFamInst (FamInst { fi_axiom = ax1 }) (FamInst { fi_axiom = ax2 })
  293. = nameModule (coAxiomName ax1) == nameModule (coAxiomName ax2)
  294. && coAxiomTyCon ax1 == coAxiomTyCon ax2
  295. && brListLength brs1 == brListLength brs2
  296. && and (brListZipWith identical_ax_branch brs1 brs2)
  297. where brs1 = coAxiomBranches ax1
  298. brs2 = coAxiomBranches ax2
  299. identical_ax_branch br1 br2
  300. = length tvs1 == length tvs2
  301. && length lhs1 == length lhs2
  302. && and (zipWith (eqTypeX rn_env) lhs1 lhs2)
  303. where
  304. tvs1 = coAxBranchTyVars br1
  305. tvs2 = coAxBranchTyVars br2
  306. lhs1 = coAxBranchLHS br1
  307. lhs2 = coAxBranchLHS br2
  308. rn_env = rnBndrs2 (mkRnEnv2 emptyInScopeSet) tvs1 tvs2
  309. \end{code}
  310. %************************************************************************
  311. %* *
  312. Compatibility
  313. %* *
  314. %************************************************************************
  315. Note [Apartness]
  316. ~~~~~~~~~~~~~~~~
  317. In dealing with closed type families, we must be able to check that one type
  318. will never reduce to another. This check is called /apartness/. The check
  319. is always between a target (which may be an arbitrary type) and a pattern.
  320. Here is how we do it:
  321. apart(target, pattern) = not (unify(flatten(target), pattern))
  322. where flatten (implemented in flattenTys, below) converts all type-family
  323. applications into fresh variables. (See Note [Flattening].)
  324. Note [Compatibility]
  325. ~~~~~~~~~~~~~~~~~~~~
  326. Two patterns are /compatible/ if either of the following conditions hold:
  327. 1) The patterns are apart.
  328. 2) The patterns unify with a substitution S, and their right hand sides
  329. equal under that substitution.
  330. For open type families, only compatible instances are allowed. For closed
  331. type families, the story is slightly more complicated. Consider the following:
  332. type family F a where
  333. F Int = Bool
  334. F a = Int
  335. g :: Show a => a -> F a
  336. g x = length (show x)
  337. Should that type-check? No. We need to allow for the possibility that 'a'
  338. might be Int and therefore 'F a' should be Bool. We can simplify 'F a' to Int
  339. only when we can be sure that 'a' is not Int.
  340. To achieve this, after finding a possible match within the equations, we have to
  341. go back to all previous equations and check that, under the
  342. substitution induced by the match, other branches are surely apart. (See
  343. [Apartness].) This is similar to what happens with class
  344. instance selection, when we need to guarantee that there is only a match and
  345. no unifiers. The exact algorithm is different here because the the
  346. potentially-overlapping group is closed.
  347. As another example, consider this:
  348. type family G x
  349. type instance where
  350. G Int = Bool
  351. G a = Double
  352. type family H y
  353. -- no instances
  354. Now, we want to simplify (G (H Char)). We can't, because (H Char) might later
  355. simplify to be Int. So, (G (H Char)) is stuck, for now.
  356. While everything above is quite sound, it isn't as expressive as we'd like.
  357. Consider this:
  358. type family J a where
  359. J Int = Int
  360. J a = a
  361. Can we simplify (J b) to b? Sure we can. Yes, the first equation matches if
  362. b is instantiated with Int, but the RHSs coincide there, so it's all OK.
  363. So, the rule is this: when looking up a branch in a closed type family, we
  364. find a branch that matches the target, but then we make sure that the target
  365. is apart from every previous *incompatible* branch. We don't check the
  366. branches that are compatible with the matching branch, because they are either
  367. irrelevant (clause 1 of compatible) or benign (clause 2 of compatible).
  368. \begin{code}
  369. compatibleBranches :: CoAxBranch -> CoAxBranch -> Bool
  370. compatibleBranches (CoAxBranch { cab_lhs = lhs1, cab_rhs = rhs1 })
  371. (CoAxBranch { cab_lhs = lhs2, cab_rhs = rhs2 })
  372. = case tcUnifyTysFG instanceBindFun lhs1 lhs2 of
  373. SurelyApart -> True
  374. Unifiable subst
  375. | Type.substTy subst rhs1 `eqType` Type.substTy subst rhs2
  376. -> True
  377. _ -> False
  378. -- takes a CoAxiom with unknown branch incompatibilities and computes
  379. -- the compatibilities
  380. computeAxiomIncomps :: CoAxiom br -> CoAxiom br
  381. computeAxiomIncomps ax@(CoAxiom { co_ax_branches = branches })
  382. = ax { co_ax_branches = go [] branches }
  383. where
  384. go :: [CoAxBranch] -> BranchList CoAxBranch br -> BranchList CoAxBranch br
  385. go prev_branches (FirstBranch br)
  386. = FirstBranch (br { cab_incomps = mk_incomps br prev_branches })
  387. go prev_branches (NextBranch br tail)
  388. = let br' = br { cab_incomps = mk_incomps br prev_branches } in
  389. NextBranch br' (go (br' : prev_branches) tail)
  390. mk_incomps :: CoAxBranch -> [CoAxBranch] -> [CoAxBranch]
  391. mk_incomps br = filter (not . compatibleBranches br)
  392. \end{code}
  393. %************************************************************************
  394. %* *
  395. Constructing axioms
  396. These functions are here because tidyType / tcUnifyTysFG
  397. are not available in CoAxiom
  398. %* *
  399. %************************************************************************
  400. Note [Tidy axioms when we build them]
  401. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  402. We print out axioms and don't want to print stuff like
  403. F k k a b = ...
  404. Instead we must tidy those kind variables. See Trac #7524.
  405. \begin{code}
  406. -- all axiom roles are Nominal, as this is only used with type families
  407. mkCoAxBranch :: [TyVar] -- original, possibly stale, tyvars
  408. -> [Type] -- LHS patterns
  409. -> Type -- RHS
  410. -> SrcSpan
  411. -> CoAxBranch
  412. mkCoAxBranch tvs lhs rhs loc
  413. = CoAxBranch { cab_tvs = tvs1
  414. , cab_lhs = tidyTypes env lhs
  415. , cab_roles = map (const Nominal) tvs1
  416. , cab_rhs = tidyType env rhs
  417. , cab_loc = loc
  418. , cab_incomps = placeHolderIncomps }
  419. where
  420. (env, tvs1) = tidyTyVarBndrs emptyTidyEnv tvs
  421. -- See Note [Tidy axioms when we build them]
  422. -- all of the following code is here to avoid mutual dependencies with
  423. -- Coercion
  424. mkBranchedCoAxiom :: Name -> TyCon -> [CoAxBranch] -> CoAxiom Branched
  425. mkBranchedCoAxiom ax_name fam_tc branches
  426. = computeAxiomIncomps $
  427. CoAxiom { co_ax_unique = nameUnique ax_name
  428. , co_ax_name = ax_name
  429. , co_ax_tc = fam_tc
  430. , co_ax_role = Nominal
  431. , co_ax_implicit = False
  432. , co_ax_branches = toBranchList branches }
  433. mkUnbranchedCoAxiom :: Name -> TyCon -> CoAxBranch -> CoAxiom Unbranched
  434. mkUnbranchedCoAxiom ax_name fam_tc branch
  435. = CoAxiom { co_ax_unique = nameUnique ax_name
  436. , co_ax_name = ax_name
  437. , co_ax_tc = fam_tc
  438. , co_ax_role = Nominal
  439. , co_ax_implicit = False
  440. , co_ax_branches = FirstBranch (branch { cab_incomps = [] }) }
  441. mkSingleCoAxiom :: Name -> [TyVar] -> TyCon -> [Type] -> Type -> CoAxiom Unbranched
  442. mkSingleCoAxiom ax_name tvs fam_tc lhs_tys rhs_ty
  443. = CoAxiom { co_ax_unique = nameUnique ax_name
  444. , co_ax_name = ax_name
  445. , co_ax_tc = fam_tc
  446. , co_ax_role = Nominal
  447. , co_ax_implicit = False
  448. , co_ax_branches = FirstBranch (branch { cab_incomps = [] }) }
  449. where
  450. branch = mkCoAxBranch tvs lhs_tys rhs_ty (getSrcSpan ax_name)
  451. \end{code}
  452. %************************************************************************
  453. %* *
  454. Looking up a family instance
  455. %* *
  456. %************************************************************************
  457. @lookupFamInstEnv@ looks up in a @FamInstEnv@, using a one-way match.
  458. Multiple matches are only possible in case of type families (not data
  459. families), and then, it doesn't matter which match we choose (as the
  460. instances are guaranteed confluent).
  461. We return the matching family instances and the type instance at which it
  462. matches. For example, if we lookup 'T [Int]' and have a family instance
  463. data instance T [a] = ..
  464. desugared to
  465. data :R42T a = ..
  466. coe :Co:R42T a :: T [a] ~ :R42T a
  467. we return the matching instance '(FamInst{.., fi_tycon = :R42T}, Int)'.
  468. \begin{code}
  469. -- when matching a type family application, we get a FamInst,
  470. -- and the list of types the axiom should be applied to
  471. data FamInstMatch = FamInstMatch { fim_instance :: FamInst
  472. , fim_tys :: [Type]
  473. }
  474. -- See Note [Over-saturated matches]
  475. instance Outputable FamInstMatch where
  476. ppr (FamInstMatch { fim_instance = inst
  477. , fim_tys = tys })
  478. = ptext (sLit "match with") <+> parens (ppr inst) <+> ppr tys
  479. lookupFamInstEnv
  480. :: FamInstEnvs
  481. -> TyCon -> [Type] -- What we are looking for
  482. -> [FamInstMatch] -- Successful matches
  483. -- Precondition: the tycon is saturated (or over-saturated)
  484. lookupFamInstEnv
  485. = lookup_fam_inst_env match
  486. where
  487. match _ tpl_tvs tpl_tys tys = tcMatchTys tpl_tvs tpl_tys tys
  488. lookupFamInstEnvConflicts
  489. :: FamInstEnvs
  490. -> FamInst -- Putative new instance
  491. -> [FamInstMatch] -- Conflicting matches (don't look at the fim_tys field)
  492. -- E.g. when we are about to add
  493. -- f : type instance F [a] = a->a
  494. -- we do (lookupFamInstConflicts f [b])
  495. -- to find conflicting matches
  496. --
  497. -- Precondition: the tycon is saturated (or over-saturated)
  498. lookupFamInstEnvConflicts envs fam_inst@(FamInst { fi_axiom = new_axiom })
  499. = lookup_fam_inst_env my_unify envs fam tys
  500. where
  501. (fam, tys) = famInstSplitLHS fam_inst
  502. -- In example above, fam tys' = F [b]
  503. my_unify (FamInst { fi_axiom = old_axiom }) tpl_tvs tpl_tys _
  504. = ASSERT2( tyVarsOfTypes tys `disjointVarSet` tpl_tvs,
  505. (ppr fam <+> ppr tys) $$
  506. (ppr tpl_tvs <+> ppr tpl_tys) )
  507. -- Unification will break badly if the variables overlap
  508. -- They shouldn't because we allocate separate uniques for them
  509. if compatibleBranches (coAxiomSingleBranch old_axiom) (new_branch)
  510. then Nothing
  511. else Just noSubst
  512. -- Note [Family instance overlap conflicts]
  513. noSubst = panic "lookupFamInstEnvConflicts noSubst"
  514. new_branch = coAxiomSingleBranch new_axiom
  515. \end{code}
  516. Note [Family instance overlap conflicts]
  517. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  518. - In the case of data family instances, any overlap is fundamentally a
  519. conflict (as these instances imply injective type mappings).
  520. - In the case of type family instances, overlap is admitted as long as
  521. the right-hand sides of the overlapping rules coincide under the
  522. overlap substitution. eg
  523. type instance F a Int = a
  524. type instance F Int b = b
  525. These two overlap on (F Int Int) but then both RHSs are Int,
  526. so all is well. We require that they are syntactically equal;
  527. anything else would be difficult to test for at this stage.
  528. \begin{code}
  529. ------------------------------------------------------------
  530. -- Might be a one-way match or a unifier
  531. type MatchFun = FamInst -- The FamInst template
  532. -> TyVarSet -> [Type] -- fi_tvs, fi_tys of that FamInst
  533. -> [Type] -- Target to match against
  534. -> Maybe TvSubst
  535. lookup_fam_inst_env' -- The worker, local to this module
  536. :: MatchFun
  537. -> FamInstEnv
  538. -> TyCon -> [Type] -- What we are looking for
  539. -> [FamInstMatch]
  540. lookup_fam_inst_env' match_fun ie fam match_tys
  541. | isOpenFamilyTyCon fam
  542. , Just (FamIE insts) <- lookupUFM ie fam
  543. = find insts -- The common case
  544. | otherwise = []
  545. where
  546. find [] = []
  547. find (item@(FamInst { fi_tcs = mb_tcs, fi_tvs = tpl_tvs,
  548. fi_tys = tpl_tys }) : rest)
  549. -- Fast check for no match, uses the "rough match" fields
  550. | instanceCantMatch rough_tcs mb_tcs
  551. = find rest
  552. -- Proper check
  553. | Just subst <- match_fun item (mkVarSet tpl_tvs) tpl_tys match_tys1
  554. = (FamInstMatch { fim_instance = item
  555. , fim_tys = substTyVars subst tpl_tvs `chkAppend` match_tys2 })
  556. : find rest
  557. -- No match => try next
  558. | otherwise
  559. = find rest
  560. where
  561. (rough_tcs, match_tys1, match_tys2) = split_tys tpl_tys
  562. -- Precondition: the tycon is saturated (or over-saturated)
  563. -- Deal with over-saturation
  564. -- See Note [Over-saturated matches]
  565. split_tys tpl_tys
  566. | isSynFamilyTyCon fam
  567. = pre_rough_split_tys
  568. | otherwise
  569. = let (match_tys1, match_tys2) = splitAtList tpl_tys match_tys
  570. rough_tcs = roughMatchTcs match_tys1
  571. in (rough_tcs, match_tys1, match_tys2)
  572. (pre_match_tys1, pre_match_tys2) = splitAt (tyConArity fam) match_tys
  573. pre_rough_split_tys
  574. = (roughMatchTcs pre_match_tys1, pre_match_tys1, pre_match_tys2)
  575. lookup_fam_inst_env -- The worker, local to this module
  576. :: MatchFun
  577. -> FamInstEnvs
  578. -> TyCon -> [Type] -- What we are looking for
  579. -> [FamInstMatch] -- Successful matches
  580. -- Precondition: the tycon is saturated (or over-saturated)
  581. lookup_fam_inst_env match_fun (pkg_ie, home_ie) fam tys =
  582. lookup_fam_inst_env' match_fun home_ie fam tys ++
  583. lookup_fam_inst_env' match_fun pkg_ie fam tys
  584. \end{code}
  585. Note [Over-saturated matches]
  586. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  587. It's ok to look up an over-saturated type constructor. E.g.
  588. type family F a :: * -> *
  589. type instance F (a,b) = Either (a->b)
  590. The type instance gives rise to a newtype TyCon (at a higher kind
  591. which you can't do in Haskell!):
  592. newtype FPair a b = FP (Either (a->b))
  593. Then looking up (F (Int,Bool) Char) will return a FamInstMatch
  594. (FPair, [Int,Bool,Char])
  595. The "extra" type argument [Char] just stays on the end.
  596. Because of eta-reduction of data family instances (see
  597. Note [Eta reduction for data family axioms] in TcInstDecls), we must
  598. handle data families and type families separately here. All instances
  599. of a type family must have the same arity, so we can precompute the split
  600. between the match_tys and the overflow tys. This is done in pre_rough_split_tys.
  601. For data instances, though, we need to re-split for each instance, because
  602. the breakdown might be different.
  603. \begin{code}
  604. -- checks if one LHS is dominated by a list of other branches
  605. -- in other words, if an application would match the first LHS, it is guaranteed
  606. -- to match at least one of the others. The RHSs are ignored.
  607. -- This algorithm is conservative:
  608. -- True -> the LHS is definitely covered by the others
  609. -- False -> no information
  610. -- It is currently (Oct 2012) used only for generating errors for
  611. -- inaccessible branches. If these errors go unreported, no harm done.
  612. -- This is defined here to avoid a dependency from CoAxiom to Unify
  613. isDominatedBy :: CoAxBranch -> [CoAxBranch] -> Bool
  614. isDominatedBy branch branches
  615. = or $ map match branches
  616. where
  617. lhs = coAxBranchLHS branch
  618. match (CoAxBranch { cab_tvs = tvs, cab_lhs = tys })
  619. = isJust $ tcMatchTys (mkVarSet tvs) tys lhs
  620. \end{code}
  621. %************************************************************************
  622. %* *
  623. Choosing an axiom application
  624. %* *
  625. %************************************************************************
  626. The lookupFamInstEnv function does a nice job for *open* type families,
  627. but we also need to handle closed ones when normalising a type:
  628. \begin{code}
  629. -- The TyCon can be oversaturated. This works on both open and closed families
  630. chooseAxiom :: FamInstEnvs -> Role -> TyCon -> [Type] -> Maybe (Coercion, Type)
  631. chooseAxiom envs role tc tys
  632. | isOpenFamilyTyCon tc
  633. , [FamInstMatch { fim_instance = fam_inst
  634. , fim_tys = inst_tys }] <- lookupFamInstEnv envs tc tys
  635. = let ax = famInstAxiom fam_inst
  636. co = mkUnbranchedAxInstCo role ax inst_tys
  637. ty = pSnd (coercionKind co)
  638. in Just (co, ty)
  639. | Just ax <- isClosedSynFamilyTyCon_maybe tc
  640. , Just (ind, inst_tys) <- chooseBranch ax tys
  641. = let co = mkAxInstCo role ax ind inst_tys
  642. ty = pSnd (coercionKind co)
  643. in Just (co, ty)
  644. | otherwise
  645. = Nothing
  646. -- The axiom can be oversaturated. (Closed families only.)
  647. chooseBranch :: CoAxiom Branched -> [Type] -> Maybe (BranchIndex, [Type])
  648. chooseBranch axiom tys
  649. = do { let num_pats = coAxiomNumPats axiom
  650. (target_tys, extra_tys) = splitAt num_pats tys
  651. branches = coAxiomBranches axiom
  652. ; (ind, inst_tys) <- findBranch (fromBranchList branches) 0 target_tys
  653. ; return (ind, inst_tys ++ extra_tys) }
  654. -- The axiom must *not* be oversaturated
  655. findBranch :: [CoAxBranch] -- branches to check
  656. -> BranchIndex -- index of current branch
  657. -> [Type] -- target types
  658. -> Maybe (BranchIndex, [Type])
  659. findBranch (CoAxBranch { cab_tvs = tpl_tvs, cab_lhs = tpl_lhs, cab_incomps = incomps }
  660. : rest) ind target_tys
  661. = case tcMatchTys (mkVarSet tpl_tvs) tpl_lhs target_tys of
  662. Just subst -- matching worked. now, check for apartness.
  663. | all (isSurelyApart
  664. . tcUnifyTysFG instanceBindFun flattened_target
  665. . coAxBranchLHS) incomps
  666. -> -- matching worked & we're apart from all incompatible branches. success
  667. Just (ind, substTyVars subst tpl_tvs)
  668. -- failure. keep looking
  669. _ -> findBranch rest (ind+1) target_tys
  670. where isSurelyApart SurelyApart = True
  671. isSurelyApart _ = False
  672. flattened_target = flattenTys in_scope target_tys
  673. in_scope = mkInScopeSet (unionVarSets $
  674. map (tyVarsOfTypes . coAxBranchLHS) incomps)
  675. -- fail if no branches left
  676. findBranch [] _ _ = Nothing
  677. \end{code}
  678. %************************************************************************
  679. %* *
  680. Looking up a family instance
  681. %* *
  682. %************************************************************************
  683. \begin{code}
  684. topNormaliseType :: FamInstEnvs
  685. -> Type
  686. -> Maybe (Coercion, Type)
  687. -- Get rid of *outermost* (or toplevel)
  688. -- * type functions
  689. -- * newtypes
  690. -- using appropriate coercions.
  691. -- By "outer" we mean that toplevelNormaliseType guarantees to return
  692. -- a type that does not have a reducible redex (F ty1 .. tyn) as its
  693. -- outermost form. It *can* return something like (Maybe (F ty)), where
  694. -- (F ty) is a redex.
  695. -- Its a bit like Type.repType, but handles type families too
  696. -- The coercion returned is always an R coercion
  697. topNormaliseType env ty
  698. = go initRecTc ty
  699. where
  700. go :: RecTcChecker -> Type -> Maybe (Coercion, Type)
  701. go rec_nts ty
  702. | Just ty' <- coreView ty -- Expand synonyms
  703. = go rec_nts ty'
  704. | Just (rec_nts', nt_co, nt_rhs) <- topNormaliseNewTypeX rec_nts ty
  705. = add_co nt_co rec_nts' nt_rhs
  706. go rec_nts (TyConApp tc tys)
  707. | isFamilyTyCon tc -- Expand family tycons
  708. , (co, ty) <- normaliseTcApp env Representational tc tys
  709. -- Note that normaliseType fully normalises 'tys',
  710. -- wrt type functions but *not* newtypes
  711. -- It has do to so to be sure that nested calls like
  712. -- F (G Int)
  713. -- are correctly top-normalised
  714. , not (isReflCo co)
  715. = add_co co rec_nts ty
  716. go _ _ = Nothing
  717. add_co co rec_nts ty
  718. = case go rec_nts ty of
  719. Nothing -> Just (co, ty)
  720. Just (co', ty') -> Just (mkTransCo co co', ty')
  721. ---------------
  722. normaliseTcApp :: FamInstEnvs -> Role -> TyCon -> [Type] -> (Coercion, Type)
  723. normaliseTcApp env role tc tys
  724. | isFamilyTyCon tc
  725. , Just (co, rhs) <- chooseAxiom env role tc ntys
  726. = let -- A reduction is possible
  727. first_coi = mkTransCo tycon_coi co
  728. (rest_coi,nty) = normaliseType env role rhs
  729. fix_coi = mkTransCo first_coi rest_coi
  730. in
  731. (fix_coi, nty)
  732. | otherwise -- No unique matching family instance exists;
  733. -- we do not do anything
  734. = (tycon_coi, TyConApp tc ntys)
  735. where
  736. -- Normalise the arg types so that they'll match
  737. -- when we lookup in in the instance envt
  738. (cois, ntys) = zipWithAndUnzip (normaliseType env) (tyConRolesX role tc) tys
  739. tycon_coi = mkTyConAppCo role tc cois
  740. ---------------
  741. normaliseType :: FamInstEnvs -- environment with family instances
  742. -> Role -- desired role of output coercion
  743. -> Type -- old type
  744. -> (Coercion, Type) -- (coercion,new type), where
  745. -- co :: old-type ~ new_type
  746. -- Normalise the input type, by eliminating *all* type-function redexes
  747. -- Returns with Refl if nothing happens
  748. normaliseType env role ty
  749. | Just ty' <- coreView ty = normaliseType env role ty'
  750. normaliseType env role (TyConApp tc tys)
  751. = normaliseTcApp env role tc tys
  752. normaliseType _env role ty@(LitTy {}) = (Refl role ty, ty)
  753. normaliseType env role (AppTy ty1 ty2)
  754. = let (coi1,nty1) = normaliseType env role ty1
  755. (coi2,nty2) = normaliseType env Nominal ty2
  756. in (mkAppCo coi1 coi2, mkAppTy nty1 nty2)
  757. normaliseType env role (FunTy ty1 ty2)
  758. = let (coi1,nty1) = normaliseType env role ty1
  759. (coi2,nty2) = normaliseType env role ty2
  760. in (mkFunCo role coi1 coi2, mkFunTy nty1 nty2)
  761. normaliseType env role (ForAllTy tyvar ty1)
  762. = let (coi,nty1) = normaliseType env role ty1
  763. in (mkForAllCo tyvar coi, ForAllTy tyvar nty1)
  764. normaliseType _ role ty@(TyVarTy _)
  765. = (Refl role ty,ty)
  766. \end{code}
  767. %************************************************************************
  768. %* *
  769. Flattening
  770. %* *
  771. %************************************************************************
  772. Note [Flattening]
  773. ~~~~~~~~~~~~~~~~~
  774. As described in
  775. http://research.microsoft.com/en-us/um/people/simonpj/papers/ext-f/axioms-extended.pdf
  776. we sometimes need to flatten core types before unifying them. Flattening
  777. means replacing all top-level uses of type functions with fresh variables,
  778. taking care to preserve sharing. That is, the type (Either (F a b) (F a b)) should
  779. flatten to (Either c c), never (Either c d).
  780. Defined here because of module dependencies.
  781. \begin{code}
  782. type FlattenMap = TypeMap TyVar
  783. -- See Note [Flattening]
  784. flattenTys :: InScopeSet -> [Type] -> [Type]
  785. flattenTys in_scope tys = snd $ coreFlattenTys all_in_scope emptyTypeMap tys
  786. where
  787. -- when we hit a type function, we replace it with a fresh variable
  788. -- but, we need to make sure that this fresh variable isn't mentioned
  789. -- *anywhere* in the types we're flattening, even if locally-bound in
  790. -- a forall. That way, we can ensure consistency both within and outside
  791. -- of that forall.
  792. all_in_scope = in_scope `extendInScopeSetSet` allTyVarsInTys tys
  793. coreFlattenTys :: InScopeSet -> FlattenMap -> [Type] -> (FlattenMap, [Type])
  794. coreFlattenTys in_scope = go []
  795. where
  796. go rtys m [] = (m, reverse rtys)
  797. go rtys m (ty : tys)
  798. = let (m', ty') = coreFlattenTy in_scope m ty in
  799. go (ty' : rtys) m' tys
  800. coreFlattenTy :: InScopeSet -> FlattenMap -> Type -> (FlattenMap, Type)
  801. coreFlattenTy in_scope = go
  802. where
  803. go m ty@(TyVarTy {}) = (m, ty)
  804. go m (AppTy ty1 ty2) = let (m1, ty1') = go m ty1
  805. (m2, ty2') = go m1 ty2 in
  806. (m2, AppTy ty1' ty2')
  807. go m (TyConApp tc tys)
  808. | isFamilyTyCon tc
  809. = let (m', tv) = coreFlattenTyFamApp in_scope m tc tys in
  810. (m', mkTyVarTy tv)
  811. | otherwise
  812. = let (m', tys') = coreFlattenTys in_scope m tys in
  813. (m', mkTyConApp tc tys')
  814. go m (FunTy ty1 ty2) = let (m1, ty1') = go m ty1
  815. (m2, ty2') = go m1 ty2 in
  816. (m2, FunTy ty1' ty2')
  817. -- Note to RAE: this will have to be changed with kind families
  818. go m (ForAllTy tv ty) = let (m', ty') = go m ty in
  819. (m', ForAllTy tv ty')
  820. go m ty@(LitTy {}) = (m, ty)
  821. coreFlattenTyFamApp :: InScopeSet -> FlattenMap
  822. -> TyCon -- type family tycon
  823. -> [Type] -- args
  824. -> (FlattenMap, TyVar)
  825. coreFlattenTyFamApp in_scope m fam_tc fam_args
  826. = case lookupTypeMap m fam_ty of
  827. Just tv -> (m, tv)
  828. -- we need fresh variables here, but this is called far from
  829. -- any good source of uniques. So, we generate one from thin
  830. -- air, using the arbitrary prime number 71 as a seed
  831. Nothing -> let tyvar_unique = deriveUnique (getUnique fam_tc) 71
  832. tyvar_name = mkSysTvName tyvar_unique (fsLit "fl")
  833. tv = uniqAway in_scope $ mkTyVar tyvar_name (typeKind fam_ty)
  834. m' = extendTypeMap m fam_ty tv in
  835. (m', tv)
  836. where fam_ty = TyConApp fam_tc fam_args
  837. allTyVarsInTys :: [Type] -> VarSet
  838. allTyVarsInTys [] = emptyVarSet
  839. allTyVarsInTys (ty:tys) = allTyVarsInTy ty `unionVarSet` allTyVarsInTys tys
  840. allTyVarsInTy :: Type -> VarSet
  841. allTyVarsInTy = go
  842. where
  843. go (TyVarTy tv) = unitVarSet tv
  844. go (AppTy ty1 ty2) = (go ty1) `unionVarSet` (go ty2)
  845. go (TyConApp _ tys) = allTyVarsInTys tys
  846. go (FunTy ty1 ty2) = (go ty1) `unionVarSet` (go ty2)
  847. go (ForAllTy tv ty) = (go (tyVarKind tv)) `unionVarSet`
  848. unitVarSet tv `unionVarSet`
  849. (go ty) -- don't remove tv
  850. go (LitTy {}) = emptyVarSet
  851. \end{code}