PageRenderTime 54ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/types/FamInstEnv.lhs

https://github.com/luite/ghc
Haskell | 905 lines | 652 code | 149 blank | 104 comment | 47 complexity | 356a0e56e0280ff9a060e3fd249b745b MD5 | raw file
  1. %
  2. % (c) The University of Glasgow 2006
  3. %
  4. FamInstEnv: Type checked family instance declarations
  5. \begin{code}
  6. module FamInstEnv (
  7. Branched, Unbranched,
  8. FamInst(..), FamFlavor(..), FamInstBranch(..),
  9. famInstAxiom, famInstBranchRoughMatch,
  10. famInstsRepTyCons, famInstNthBranch, famInstSingleBranch,
  11. famInstBranchLHS, famInstBranches,
  12. toBranchedFamInst, toUnbranchedFamInst,
  13. famInstTyCon, famInstRepTyCon_maybe, dataFamInstRepTyCon,
  14. pprFamInst, pprFamInsts,
  15. pprFamFlavor,
  16. mkImportedFamInst,
  17. FamInstEnv, FamInstEnvs,
  18. emptyFamInstEnvs, emptyFamInstEnv, famInstEnvElts, familyInstances,
  19. extendFamInstEnvList, extendFamInstEnv, deleteFromFamInstEnv,
  20. identicalFamInst, orphNamesOfFamInst,
  21. FamInstMatch(..),
  22. lookupFamInstEnv, lookupFamInstEnvConflicts, lookupFamInstEnvConflicts',
  23. isDominatedBy,
  24. -- Normalisation
  25. topNormaliseType, normaliseType, normaliseTcApp
  26. ) where
  27. #include "HsVersions.h"
  28. import TcType ( orphNamesOfTypes )
  29. import InstEnv
  30. import Unify
  31. import Type
  32. import Coercion hiding ( substTy )
  33. import TypeRep
  34. import TyCon
  35. import CoAxiom
  36. import VarSet
  37. import VarEnv
  38. import Name
  39. import NameSet
  40. import UniqFM
  41. import Outputable
  42. import Maybes
  43. import Util
  44. import FastString
  45. \end{code}
  46. %************************************************************************
  47. %* *
  48. Type checked family instance heads
  49. %* *
  50. %************************************************************************
  51. Note [FamInsts and CoAxioms]
  52. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  53. * CoAxioms and FamInsts are just like
  54. DFunIds and ClsInsts
  55. * A CoAxiom is a System-FC thing: it can relate any two types
  56. * A FamInst is a Haskell source-language thing, corresponding
  57. to a type/data family instance declaration.
  58. - The FamInst contains a CoAxiom, which is the evidence
  59. for the instance
  60. - The LHSs of the CoAxiom branches are always of form
  61. F ty1 .. tyn where F is a type family
  62. * A FamInstBranch corresponds to a CoAxBranch -- it represents
  63. one alternative in a branched family instance. We could theoretically
  64. not have FamInstBranches and just use the CoAxBranches within
  65. the CoAxiom stored in the FamInst, but for one problem: we want to
  66. cache the "rough match" top-level tycon names for quick matching.
  67. This data is not stored in a CoAxBranch, so we use FamInstBranches
  68. instead.
  69. Note [fi_branched field]
  70. ~~~~~~~~~~~~~~~~~~~~~~~~
  71. A FamInst stores whether or not it was declared with "type instance where"
  72. for two reasons:
  73. 1. for accurate pretty-printing; and
  74. 2. because confluent overlap is disallowed between branches
  75. declared in groups.
  76. Note that this "branched-ness" is properly associated with the FamInst,
  77. which thinks about overlap, and not in the CoAxiom, which blindly
  78. assumes that it is part of a consistent axiom set.
  79. A "branched" instance with fi_branched=True can have just one branch, however.
  80. Note [Why we need fib_rhs]
  81. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  82. It may at first seem unnecessary to store the right-hand side of an equation
  83. in a FamInstBranch. After all, FamInstBranches are used only for matching a
  84. family application; the underlying CoAxiom is used to perform the actual
  85. simplification.
  86. However, we do need to know the rhs field during conflict checking to support
  87. confluent overlap. When two unbranched instances have overlapping left-hand
  88. sides, we check if the right-hand sides are coincident in the region of overlap.
  89. This check requires fib_rhs. See lookupFamInstEnvConflicts.
  90. \begin{code}
  91. data FamInst br -- See Note [FamInsts and CoAxioms], Note [Branched axioms] in CoAxiom
  92. = FamInst { fi_axiom :: CoAxiom br -- The new coercion axiom introduced
  93. -- by this family instance
  94. , fi_flavor :: FamFlavor
  95. , fi_branched :: Bool -- True <=> declared with "type instance where"
  96. -- See Note [fi_branched field]
  97. -- Everything below here is a redundant,
  98. -- cached version of the two things above,
  99. -- except that the TyVars are freshened in the FamInstBranches
  100. , fi_branches :: BranchList FamInstBranch br
  101. -- Haskell-source-language view of
  102. -- a CoAxBranch
  103. , fi_fam :: Name -- Family name
  104. -- INVARIANT: fi_fam = name of fi_axiom.co_ax_tc
  105. }
  106. data FamInstBranch
  107. = FamInstBranch
  108. { fib_tvs :: [TyVar] -- Bound type variables
  109. -- Like ClsInsts, these variables are always
  110. -- fresh. See Note [Template tyvars are fresh]
  111. -- in InstEnv
  112. , fib_lhs :: [Type] -- type patterns
  113. , fib_rhs :: Type -- RHS of family instance
  114. -- See Note [Why we need fib_rhs]
  115. , fib_tcs :: [Maybe Name] -- used for "rough matching" during typechecking
  116. -- see Note [Rough-match field] in InstEnv
  117. }
  118. data FamFlavor
  119. = SynFamilyInst -- A synonym family
  120. | DataFamilyInst TyCon -- A data family, with its representation TyCon
  121. \end{code}
  122. \begin{code}
  123. -- Obtain the axiom of a family instance
  124. famInstAxiom :: FamInst br -> CoAxiom br
  125. famInstAxiom = fi_axiom
  126. famInstTyCon :: FamInst br -> TyCon
  127. famInstTyCon = co_ax_tc . fi_axiom
  128. famInstNthBranch :: FamInst br -> Int -> FamInstBranch
  129. famInstNthBranch (FamInst { fi_branches = branches }) index
  130. = ASSERT( 0 <= index && index < (length $ fromBranchList branches) )
  131. brListNth branches index
  132. famInstSingleBranch :: FamInst Unbranched -> FamInstBranch
  133. famInstSingleBranch (FamInst { fi_branches = FirstBranch branch }) = branch
  134. toBranchedFamInst :: FamInst br -> FamInst Branched
  135. toBranchedFamInst (FamInst ax flav grp branches fam)
  136. = FamInst (toBranchedAxiom ax) flav grp (toBranchedList branches) fam
  137. toUnbranchedFamInst :: FamInst br -> FamInst Unbranched
  138. toUnbranchedFamInst (FamInst ax flav grp branches fam)
  139. = FamInst (toUnbranchedAxiom ax) flav grp (toUnbranchedList branches) fam
  140. famInstBranches :: FamInst br -> BranchList FamInstBranch br
  141. famInstBranches = fi_branches
  142. famInstBranchLHS :: FamInstBranch -> [Type]
  143. famInstBranchLHS = fib_lhs
  144. famInstBranchRoughMatch :: FamInstBranch -> [Maybe Name]
  145. famInstBranchRoughMatch = fib_tcs
  146. -- Return the representation TyCons introduced by data family instances, if any
  147. famInstsRepTyCons :: [FamInst br] -> [TyCon]
  148. famInstsRepTyCons fis = [tc | FamInst { fi_flavor = DataFamilyInst tc } <- fis]
  149. -- Extracts the TyCon for this *data* (or newtype) instance
  150. famInstRepTyCon_maybe :: FamInst br -> Maybe TyCon
  151. famInstRepTyCon_maybe fi
  152. = case fi_flavor fi of
  153. DataFamilyInst tycon -> Just tycon
  154. SynFamilyInst -> Nothing
  155. dataFamInstRepTyCon :: FamInst br -> TyCon
  156. dataFamInstRepTyCon fi
  157. = case fi_flavor fi of
  158. DataFamilyInst tycon -> tycon
  159. SynFamilyInst -> pprPanic "dataFamInstRepTyCon" (ppr fi)
  160. \end{code}
  161. %************************************************************************
  162. %* *
  163. Pretty printing
  164. %* *
  165. %************************************************************************
  166. \begin{code}
  167. instance NamedThing (FamInst br) where
  168. getName = coAxiomName . fi_axiom
  169. instance Outputable (FamInst br) where
  170. ppr = pprFamInst
  171. -- Prints the FamInst as a family instance declaration
  172. pprFamInst :: FamInst br -> SDoc
  173. pprFamInst (FamInst { fi_branches = brs, fi_flavor = SynFamilyInst
  174. , fi_branched = True, fi_axiom = axiom })
  175. = hang (ptext (sLit "type instance where"))
  176. 2 (vcat [pprCoAxBranchHdr axiom i | i <- brListIndices brs])
  177. pprFamInst fi@(FamInst { fi_flavor = flavor
  178. , fi_branched = False, fi_axiom = ax })
  179. = pprFamFlavor flavor <+> pp_instance
  180. <+> pprCoAxBranchHdr ax 0
  181. where
  182. -- For *associated* types, say "type T Int = blah"
  183. -- For *top level* type instances, say "type instance T Int = blah"
  184. pp_instance
  185. | isTyConAssoc (famInstTyCon fi) = empty
  186. | otherwise = ptext (sLit "instance")
  187. pprFamInst _ = panic "pprFamInst"
  188. pprFamFlavor :: FamFlavor -> SDoc
  189. pprFamFlavor flavor
  190. = case flavor of
  191. SynFamilyInst -> ptext (sLit "type")
  192. DataFamilyInst tycon
  193. | isDataTyCon tycon -> ptext (sLit "data")
  194. | isNewTyCon tycon -> ptext (sLit "newtype")
  195. | isAbstractTyCon tycon -> ptext (sLit "data")
  196. | otherwise -> ptext (sLit "WEIRD") <+> ppr tycon
  197. pprFamInsts :: [FamInst br] -> SDoc
  198. pprFamInsts finsts = vcat (map pprFamInst finsts)
  199. \end{code}
  200. Note [Lazy axiom match]
  201. ~~~~~~~~~~~~~~~~~~~~~~~
  202. It is Vitally Important that mkImportedFamInst is *lazy* in its axiom
  203. parameter. The axiom is loaded lazily, via a forkM, in TcIface. Sometime
  204. later, mkImportedFamInst is called using that axiom. However, the axiom
  205. may itself depend on entities which are not yet loaded as of the time
  206. of the mkImportedFamInst. Thus, if mkImportedFamInst eagerly looks at the
  207. axiom, a dependency loop spontaneously appears and GHC hangs. The solution
  208. is simply for mkImportedFamInst never, ever to look inside of the axiom
  209. until everything else is good and ready to do so. We can assume that this
  210. readiness has been achieved when some other code pulls on the axiom in the
  211. FamInst. Thus, we pattern match on the axiom lazily (in the where clause,
  212. not in the parameter list) and we assert the consistency of names there
  213. also.
  214. \begin{code}
  215. -- Make a family instance representation from the information found in an
  216. -- interface file. In particular, we get the rough match info from the iface
  217. -- (instead of computing it here).
  218. mkImportedFamInst :: Name -- Name of the family
  219. -> Bool -- is this a branched instance?
  220. -> [[Maybe Name]] -- Rough match info, per branch
  221. -> CoAxiom Branched -- Axiom introduced
  222. -> FamInst Branched -- Resulting family instance
  223. mkImportedFamInst fam branched roughs axiom
  224. = FamInst {
  225. fi_fam = fam,
  226. fi_axiom = axiom,
  227. fi_flavor = flavor,
  228. fi_branched = branched,
  229. fi_branches = branches }
  230. where
  231. -- Lazy match (See note [Lazy axiom match])
  232. CoAxiom { co_ax_branches = axBranches }
  233. = ASSERT( fam == tyConName (coAxiomTyCon axiom) )
  234. axiom
  235. branches = toBranchList $ map mk_imp_fam_inst_branch $
  236. (roughs `zipLazy` fromBranchList axBranches)
  237. -- Lazy zip (See note [Lazy axiom match])
  238. mk_imp_fam_inst_branch (mb_tcs, ~(CoAxBranch { cab_tvs = tvs
  239. , cab_lhs = lhs
  240. , cab_rhs = rhs }))
  241. -- Lazy match (See note [Lazy axiom match])
  242. = FamInstBranch { fib_tvs = tvs
  243. , fib_lhs = lhs
  244. , fib_rhs = rhs
  245. , fib_tcs = mb_tcs }
  246. -- Derive the flavor for an imported FamInst rather disgustingly
  247. -- Maybe we should store it in the IfaceFamInst?
  248. flavor
  249. | FirstBranch (CoAxBranch { cab_rhs = rhs }) <- axBranches
  250. , Just (tc, _) <- splitTyConApp_maybe rhs
  251. , Just ax' <- tyConFamilyCoercion_maybe tc
  252. , (toBranchedAxiom ax') == axiom
  253. = DataFamilyInst tc
  254. | otherwise
  255. = SynFamilyInst
  256. \end{code}
  257. %************************************************************************
  258. %* *
  259. FamInstEnv
  260. %* *
  261. %************************************************************************
  262. Note [FamInstEnv]
  263. ~~~~~~~~~~~~~~~~~~~~~
  264. A FamInstEnv maps a family name to the list of known instances for that family.
  265. The same FamInstEnv includes both 'data family' and 'type family' instances.
  266. Type families are reduced during type inference, but not data families;
  267. the user explains when to use a data family instance by using contructors
  268. and pattern matching.
  269. Neverthless it is still useful to have data families in the FamInstEnv:
  270. - For finding overlaps and conflicts
  271. - For finding the representation type...see FamInstEnv.topNormaliseType
  272. and its call site in Simplify
  273. - In standalone deriving instance Eq (T [Int]) we need to find the
  274. representation type for T [Int]
  275. \begin{code}
  276. type FamInstEnv = UniqFM FamilyInstEnv -- Maps a family to its instances
  277. -- See Note [FamInstEnv]
  278. type FamInstEnvs = (FamInstEnv, FamInstEnv)
  279. -- External package inst-env, Home-package inst-env
  280. newtype FamilyInstEnv
  281. = FamIE [FamInst Branched] -- The instances for a particular family, in any order
  282. instance Outputable FamilyInstEnv where
  283. ppr (FamIE fs) = ptext (sLit "FamIE") <+> vcat (map ppr fs)
  284. -- INVARIANTS:
  285. -- * The fs_tvs are distinct in each FamInst
  286. -- of a range value of the map (so we can safely unify them)
  287. emptyFamInstEnvs :: (FamInstEnv, FamInstEnv)
  288. emptyFamInstEnvs = (emptyFamInstEnv, emptyFamInstEnv)
  289. emptyFamInstEnv :: FamInstEnv
  290. emptyFamInstEnv = emptyUFM
  291. famInstEnvElts :: FamInstEnv -> [FamInst Branched]
  292. famInstEnvElts fi = [elt | FamIE elts <- eltsUFM fi, elt <- elts]
  293. familyInstances :: (FamInstEnv, FamInstEnv) -> TyCon -> [FamInst Branched]
  294. familyInstances (pkg_fie, home_fie) fam
  295. = get home_fie ++ get pkg_fie
  296. where
  297. get env = case lookupUFM env fam of
  298. Just (FamIE insts) -> insts
  299. Nothing -> []
  300. -- | Collects the names of the concrete types and type constructors that
  301. -- make up the LHS of a type family instance. For instance,
  302. -- given `type family Foo a b`:
  303. --
  304. -- `type instance Foo (F (G (H a))) b = ...` would yield [F,G,H]
  305. --
  306. -- Used in the implementation of ":info" in GHCi.
  307. orphNamesOfFamInst :: FamInst Branched -> NameSet
  308. orphNamesOfFamInst
  309. = orphNamesOfTypes . concat . brListMap cab_lhs . coAxiomBranches . fi_axiom
  310. extendFamInstEnvList :: FamInstEnv -> [FamInst br] -> FamInstEnv
  311. extendFamInstEnvList inst_env fis = foldl extendFamInstEnv inst_env fis
  312. extendFamInstEnv :: FamInstEnv -> FamInst br -> FamInstEnv
  313. extendFamInstEnv inst_env ins_item@(FamInst {fi_fam = cls_nm})
  314. = addToUFM_C add inst_env cls_nm (FamIE [ins_item_br])
  315. where
  316. ins_item_br = toBranchedFamInst ins_item
  317. add (FamIE items) _ = FamIE (ins_item_br:items)
  318. deleteFromFamInstEnv :: FamInstEnv -> FamInst br -> FamInstEnv
  319. deleteFromFamInstEnv inst_env fam_inst@(FamInst {fi_fam = fam_nm})
  320. = adjustUFM adjust inst_env fam_nm
  321. where
  322. adjust :: FamilyInstEnv -> FamilyInstEnv
  323. adjust (FamIE items) = FamIE (filterOut (identicalFamInst fam_inst) items)
  324. identicalFamInst :: FamInst br1 -> FamInst br2 -> Bool
  325. -- Same LHS, *and* the instance is defined in the same module
  326. -- Used for overriding in GHCi
  327. identicalFamInst (FamInst { fi_axiom = ax1 }) (FamInst { fi_axiom = ax2 })
  328. = nameModule (coAxiomName ax1) == nameModule (coAxiomName ax2)
  329. && coAxiomTyCon ax1 == coAxiomTyCon ax2
  330. && brListLength brs1 == brListLength brs2
  331. && and (brListZipWith identical_ax_branch brs1 brs2)
  332. where brs1 = coAxiomBranches ax1
  333. brs2 = coAxiomBranches ax2
  334. identical_ax_branch br1 br2
  335. = length tvs1 == length tvs2
  336. && length lhs1 == length lhs2
  337. && and (zipWith (eqTypeX rn_env) lhs1 lhs2)
  338. where
  339. tvs1 = coAxBranchTyVars br1
  340. tvs2 = coAxBranchTyVars br2
  341. lhs1 = coAxBranchLHS br1
  342. lhs2 = coAxBranchLHS br2
  343. rn_env = rnBndrs2 (mkRnEnv2 emptyInScopeSet) tvs1 tvs2
  344. \end{code}
  345. %************************************************************************
  346. %* *
  347. Looking up a family instance
  348. %* *
  349. %************************************************************************
  350. @lookupFamInstEnv@ looks up in a @FamInstEnv@, using a one-way match.
  351. Multiple matches are only possible in case of type families (not data
  352. families), and then, it doesn't matter which match we choose (as the
  353. instances are guaranteed confluent).
  354. We return the matching family instances and the type instance at which it
  355. matches. For example, if we lookup 'T [Int]' and have a family instance
  356. data instance T [a] = ..
  357. desugared to
  358. data :R42T a = ..
  359. coe :Co:R42T a :: T [a] ~ :R42T a
  360. we return the matching instance '(FamInst{.., fi_tycon = :R42T}, Int)'.
  361. Note [Branched instance checking]
  362. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  363. Consider the following:
  364. type instance where
  365. F Int = Bool
  366. F a = Int
  367. g :: Show a => a -> F a
  368. g x = length (show x)
  369. Should that type-check? No. We need to allow for the possibility that 'a'
  370. might be Int and therefore 'F a' should be Bool. We can simplify 'F a' to Int
  371. only when we can be sure that 'a' is not Int.
  372. To achieve this, after finding a possible match within an instance, we have to
  373. go back to all previous FamInstBranchess and check that, under the
  374. substitution induced by the match, other branches are surely apart. (See
  375. [Apartness] in types/Unify.lhs.) This is similar to what happens with class
  376. instance selection, when we need to guarantee that there is only a match and
  377. no unifiers. The exact algorithm is different here because the the
  378. potentially-overlapping group is closed.
  379. As another example, consider this:
  380. type family G x
  381. type instance where
  382. G Int = Bool
  383. G a = Double
  384. type family H y
  385. -- no instances
  386. Now, we want to simplify (G (H Char)). We can't, because (H Char) might later
  387. simplify to be Int. So, (G (H Char)) is stuck, for now.
  388. ALTERNATE APPROACH: As we are processing the branches, we could check if a
  389. branch is not surely apart from an application but does not match that
  390. application. If this happens, there is no possible match and we can fail right
  391. away. This might be more efficient.
  392. Note [Early failure optimisation for branched instances]
  393. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  394. As we're searching through the instances for a match, it is possible that we
  395. find a branch within an instance that matches, but a previous branch is not
  396. surely apart from the target application. In this case, we can abort the
  397. search, because any other instance that matches will necessarily overlap with
  398. the instance we're currently searching. Because overlap among branched
  399. instances is disallowed, we know that that no such other instance exists.
  400. Note [Confluence checking within branched instances]
  401. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  402. GHC allows type family instances to have overlapping patterns as long as the
  403. right-hand sides are coincident in the region of overlap. Can we extend this
  404. notion of confluent overlap to branched instances? Not in any obvious way.
  405. Consider this:
  406. type instance where
  407. F Int = Int
  408. F a = a
  409. Without confluence checking (in other words, as implemented), we cannot now
  410. simplify an application of (F b) -- b might unify with Int later on, so this
  411. application is stuck. However, it would seem easy to just check that, in the
  412. region of overlap, (i.e. b |-> Int), the right-hand sides coincide, so we're
  413. OK. The problem happens when we are simplifying an application (F (G a)),
  414. where (G a) is stuck. What, now, is the region of overlap? We can't soundly
  415. simplify (F (G a)) without knowing that the right-hand sides are confluent
  416. in the region of overlap, but we also can't in any obvious way identify the
  417. region of overlap. We don't want to do analysis on the instances of G, because
  418. that is not sound in a world with open type families. (If G were known to be
  419. closed, there might be a way forward here.) To find the region of overlap,
  420. it is conceivable that we might convert (G a) to some fresh type variable and
  421. then unify, but we must be careful to convert every (G a) to the same fresh
  422. type variable. And then, what if there is an (H a) lying around? It all seems
  423. rather subtle, error-prone, confusing, and probably won't help anyone. So,
  424. we're not doing it.
  425. So, why is this not a problem with non-branched confluent overlap? Because
  426. we don't need to verify that an application is apart from anything. The
  427. non-branched confluent overlap check happens when we add the instance to the
  428. environment -- we're unifying among patterns, which cannot contain type family
  429. applications. So, we're safe there and can continue supporting that feature.
  430. \begin{code}
  431. -- when matching a type family application, we get a FamInst,
  432. -- a 0-based index of the branch that matched, and the list of types
  433. -- the axiom should be applied to
  434. data FamInstMatch = FamInstMatch { fim_instance :: FamInst Branched
  435. , fim_index :: BranchIndex
  436. , fim_tys :: [Type]
  437. }
  438. instance Outputable FamInstMatch where
  439. ppr (FamInstMatch { fim_instance = inst
  440. , fim_index = ind
  441. , fim_tys = tys })
  442. = ptext (sLit "match with") <+> parens (ppr inst)
  443. <> brackets (ppr ind) <+> ppr tys
  444. lookupFamInstEnv
  445. :: FamInstEnvs
  446. -> TyCon -> [Type] -- What we are looking for
  447. -> [FamInstMatch] -- Successful matches
  448. -- Precondition: the tycon is saturated (or over-saturated)
  449. lookupFamInstEnv
  450. = lookup_fam_inst_env match True
  451. where
  452. match :: MatchFun
  453. match seen (FamInstBranch { fib_tvs = tpl_tvs
  454. , fib_lhs = tpl_tys })
  455. _ match_tys
  456. = ASSERT( tyVarsOfTypes match_tys `disjointVarSet` tpl_tv_set )
  457. -- Unification will break badly if the variables overlap
  458. -- They shouldn't because we allocate separate uniques for them
  459. case tcMatchTys tpl_tv_set tpl_tys match_tys of
  460. -- success
  461. Just subst
  462. | checkConflict seen match_tys
  463. -> (Nothing, StopSearching) -- we found an incoherence, so stop searching
  464. -- see Note [Early failure optimisation for branched instances]
  465. | otherwise
  466. -> (Just subst, KeepSearching)
  467. -- failure; instance not relevant
  468. Nothing -> (Nothing, KeepSearching)
  469. where
  470. tpl_tv_set = mkVarSet tpl_tvs
  471. -- see Note [Branched instance checking]
  472. checkConflict :: [FamInstBranch] -- the previous branches in the instance that matched
  473. -> [Type] -- the types in the tyfam application we are matching
  474. -> Bool -- is there a conflict?
  475. checkConflict [] _ = False
  476. checkConflict ((FamInstBranch { fib_lhs = tpl_tys }) : rest) match_tys
  477. -- see Note [Confluence checking within branched instances]
  478. | SurelyApart <- tcApartTys instanceBindFun tpl_tys match_tys
  479. = checkConflict rest match_tys
  480. | otherwise
  481. = True
  482. lookupFamInstEnvConflicts
  483. :: FamInstEnvs
  484. -> Bool -- True <=> we are checking part of a group with other branches
  485. -> TyCon -- The TyCon of the family
  486. -> FamInstBranch -- the putative new instance branch
  487. -> [FamInstMatch] -- Conflicting branches
  488. -- E.g. when we are about to add
  489. -- f : type instance F [a] = a->a
  490. -- we do (lookupFamInstConflicts f [b])
  491. -- to find conflicting matches
  492. --
  493. -- Precondition: the tycon is saturated (or over-saturated)
  494. lookupFamInstEnvConflicts envs grp tc
  495. (FamInstBranch { fib_lhs = tys, fib_rhs = rhs })
  496. = lookup_fam_inst_env my_unify False envs tc tys
  497. where
  498. my_unify :: MatchFun
  499. my_unify _ (FamInstBranch { fib_tvs = tpl_tvs, fib_lhs = tpl_tys
  500. , fib_rhs = tpl_rhs }) old_grp match_tys
  501. = ASSERT( tyVarsOfTypes tys `disjointVarSet` mkVarSet tpl_tvs )
  502. -- Unification will break badly if the variables overlap
  503. -- They shouldn't because we allocate separate uniques for them
  504. case tcUnifyTys instanceBindFun tpl_tys match_tys of
  505. Just subst
  506. | isDataFamilyTyCon tc
  507. || grp
  508. || old_grp
  509. || rhs_conflict tpl_rhs rhs subst
  510. -> (Just subst, KeepSearching)
  511. | otherwise -- confluent overlap
  512. -> (Nothing, KeepSearching)
  513. -- irrelevant instance
  514. Nothing -> (Nothing, KeepSearching)
  515. -- checks whether two RHSs are distinct, under a unifying substitution
  516. -- Note [Family instance overlap conflicts]
  517. rhs_conflict :: Type -> Type -> TvSubst -> Bool
  518. rhs_conflict rhs1 rhs2 subst
  519. = not (rhs1' `eqType` rhs2')
  520. where
  521. rhs1' = substTy subst rhs1
  522. rhs2' = substTy subst rhs2
  523. -- This variant is called when we want to check if the conflict is only in the
  524. -- home environment (see FamInst.addLocalFamInst)
  525. lookupFamInstEnvConflicts' :: FamInstEnv -> Bool -> TyCon
  526. -> FamInstBranch -> [FamInstMatch]
  527. lookupFamInstEnvConflicts' env
  528. = lookupFamInstEnvConflicts (emptyFamInstEnv, env)
  529. \end{code}
  530. Note [lookup_fam_inst_env' implementation]
  531. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  532. To reduce code duplication, both lookups during simplification and conflict
  533. checking are routed through lookup_fam_inst_env', which looks for a
  534. matching/unifying branch compared to some target. In the simplification
  535. case, the search is for a match for a target application; in the conflict-
  536. checking case, the search is for a unifier for a putative new instance branch.
  537. The two uses are differentiated by different MatchFuns, which look at a given
  538. branch to see if it is relevant and whether the search should continue. The
  539. the branch is relevant (i.e. matches or unifies), Just subst is
  540. returned; if the instance is not relevant, Nothing is returned. The MatchFun
  541. also indicates what the search algorithm should do next: it could
  542. KeepSearching or StopSearching.
  543. When to StopSearching? See Note [Early failure optimisation for branched instances]
  544. For class instances, these two variants of lookup are combined into one
  545. function (cf, @InstEnv@). We don't do that for family instances as the
  546. results of matching and unification are used in two different contexts.
  547. Moreover, matching is the wildly more frequently used operation in the case of
  548. indexed synonyms and we don't want to slow that down by needless unification.
  549. Note [Family instance overlap conflicts]
  550. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  551. - In the case of data family instances, any overlap is fundamentally a
  552. conflict (as these instances imply injective type mappings).
  553. - In the case of type family instances, overlap is admitted as long as
  554. the neither instance declares an instance group and the right-hand
  555. sides of the overlapping rules coincide under the overlap substitution.
  556. For example:
  557. type instance F a Int = a
  558. type instance F Int b = b
  559. These two overlap on (F Int Int) but then both RHSs are Int,
  560. so all is well. We require that they are syntactically equal;
  561. anything else would be difficult to test for at this stage.
  562. \begin{code}
  563. ------------------------------------------------------------
  564. data ContSearch = KeepSearching
  565. | StopSearching
  566. -- Might be a one-way match or a unifier
  567. type MatchFun = [FamInstBranch] -- the previous branches in the instance
  568. -> FamInstBranch -- the individual branch to check
  569. -> Bool -- is this branch a part of a branched instance?
  570. -> [Type] -- the types to match against
  571. -> (Maybe TvSubst, ContSearch)
  572. type OneSidedMatch = Bool -- Are optimisations that are only valid for
  573. -- one sided matches allowed?
  574. lookup_fam_inst_env' -- The worker, local to this module
  575. :: MatchFun
  576. -> OneSidedMatch
  577. -> FamInstEnv
  578. -> TyCon -> [Type] -- What we are looking for
  579. -> [FamInstMatch]
  580. lookup_fam_inst_env' match_fun _one_sided ie fam tys
  581. | isFamilyTyCon fam
  582. , Just (FamIE insts) <- lookupUFM ie fam
  583. = ASSERT2( n_tys >= arity, ppr fam <+> ppr tys )
  584. if arity < n_tys then -- Family type applications must be saturated
  585. -- See Note [Over-saturated matches]
  586. map wrap_extra_tys (find match_fun (take arity tys) insts)
  587. else
  588. find match_fun tys insts -- The common case
  589. | otherwise = []
  590. where
  591. arity = tyConArity fam
  592. n_tys = length tys
  593. extra_tys = drop arity tys
  594. wrap_extra_tys fim@(FamInstMatch { fim_tys = match_tys })
  595. = fim { fim_tys = match_tys ++ extra_tys }
  596. find :: MatchFun -> [Type] -> [FamInst Branched] -> [FamInstMatch]
  597. find _ _ [] = []
  598. find match_fun match_tys (inst@(FamInst { fi_branches = branches, fi_branched = is_branched }) : rest)
  599. = case findBranch [] (fromBranchList branches) 0 of
  600. (Just match, StopSearching) -> [match]
  601. (Just match, KeepSearching) -> match : find match_fun match_tys rest
  602. (Nothing, StopSearching) -> []
  603. (Nothing, KeepSearching) -> find match_fun match_tys rest
  604. where
  605. rough_tcs = roughMatchTcs match_tys
  606. findBranch :: [FamInstBranch] -- the branches that have already been checked
  607. -> [FamInstBranch] -- still looking through these
  608. -> BranchIndex -- index of teh first of the "still looking" list
  609. -> (Maybe FamInstMatch, ContSearch)
  610. findBranch _ [] _ = (Nothing, KeepSearching)
  611. findBranch seen (branch@(FamInstBranch { fib_tvs = tvs, fib_tcs = mb_tcs }) : rest) ind
  612. | instanceCantMatch rough_tcs mb_tcs
  613. = findBranch seen rest (ind+1) -- branch won't unify later; no need to add to 'seen'
  614. | otherwise
  615. = case match_fun seen branch is_branched match_tys of
  616. (Nothing, KeepSearching) -> findBranch (branch : seen) rest (ind+1)
  617. (Nothing, StopSearching) -> (Nothing, StopSearching)
  618. (Just subst, cont) -> (Just match, cont)
  619. where
  620. match = FamInstMatch { fim_instance = inst
  621. , fim_index = ind
  622. , fim_tys = substTyVars subst tvs }
  623. lookup_fam_inst_env -- The worker, local to this module
  624. :: MatchFun
  625. -> OneSidedMatch
  626. -> FamInstEnvs
  627. -> TyCon -> [Type] -- What we are looking for
  628. -> [FamInstMatch] -- What was found
  629. -- Precondition: the tycon is saturated (or over-saturated)
  630. lookup_fam_inst_env match_fun one_sided (pkg_ie, home_ie) fam tys =
  631. lookup_fam_inst_env' match_fun one_sided home_ie fam tys ++
  632. lookup_fam_inst_env' match_fun one_sided pkg_ie fam tys
  633. \end{code}
  634. Note [Over-saturated matches]
  635. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  636. It's ok to look up an over-saturated type constructor. E.g.
  637. type family F a :: * -> *
  638. type instance F (a,b) = Either (a->b)
  639. The type instance gives rise to a newtype TyCon (at a higher kind
  640. which you can't do in Haskell!):
  641. newtype FPair a b = FP (Either (a->b))
  642. Then looking up (F (Int,Bool) Char) will return a FamInstMatch
  643. (FPair, [Int,Bool,Char])
  644. The "extra" type argument [Char] just stays on the end.
  645. \begin{code}
  646. -- checks if one LHS is dominated by a list of other branches
  647. -- in other words, if an application would match the first LHS, it is guaranteed
  648. -- to match at least one of the others. The RHSs are ignored.
  649. -- This algorithm is conservative:
  650. -- True -> the LHS is definitely covered by the others
  651. -- False -> no information
  652. -- It is currently (Oct 2012) used only for generating errors for
  653. -- inaccessible branches. If these errors go unreported, no harm done.
  654. -- This is defined here to avoid a dependency from CoAxiom to Unify
  655. isDominatedBy :: CoAxBranch -> [CoAxBranch] -> Bool
  656. isDominatedBy branch branches
  657. = or $ map match branches
  658. where
  659. lhs = coAxBranchLHS branch
  660. match (CoAxBranch { cab_tvs = tvs, cab_lhs = tys })
  661. = isJust $ tcMatchTys (mkVarSet tvs) tys lhs
  662. \end{code}
  663. %************************************************************************
  664. %* *
  665. Looking up a family instance
  666. %* *
  667. %************************************************************************
  668. \begin{code}
  669. topNormaliseType :: FamInstEnvs
  670. -> Type
  671. -> Maybe (Coercion, Type)
  672. -- Get rid of *outermost* (or toplevel)
  673. -- * type functions
  674. -- * newtypes
  675. -- using appropriate coercions.
  676. -- By "outer" we mean that toplevelNormaliseType guarantees to return
  677. -- a type that does not have a reducible redex (F ty1 .. tyn) as its
  678. -- outermost form. It *can* return something like (Maybe (F ty)), where
  679. -- (F ty) is a redex.
  680. -- Its a bit like Type.repType, but handles type families too
  681. topNormaliseType env ty
  682. = go emptyNameSet ty
  683. where
  684. go :: NameSet -> Type -> Maybe (Coercion, Type)
  685. go rec_nts ty
  686. | Just ty' <- coreView ty -- Expand synonyms
  687. = go rec_nts ty'
  688. | Just (rec_nts', nt_co, nt_rhs) <- topNormaliseNewTypeX rec_nts ty
  689. = add_co nt_co rec_nts' nt_rhs
  690. go rec_nts (TyConApp tc tys)
  691. | isFamilyTyCon tc -- Expand open tycons
  692. , (co, ty) <- normaliseTcApp env tc tys
  693. -- Note that normaliseType fully normalises 'tys',
  694. -- wrt type functions but *not* newtypes
  695. -- It has do to so to be sure that nested calls like
  696. -- F (G Int)
  697. -- are correctly top-normalised
  698. , not (isReflCo co)
  699. = add_co co rec_nts ty
  700. go _ _ = Nothing
  701. add_co co rec_nts ty
  702. = case go rec_nts ty of
  703. Nothing -> Just (co, ty)
  704. Just (co', ty') -> Just (mkTransCo co co', ty')
  705. ---------------
  706. normaliseTcApp :: FamInstEnvs -> TyCon -> [Type] -> (Coercion, Type)
  707. normaliseTcApp env tc tys
  708. | isFamilyTyCon tc
  709. , tyConArity tc <= length tys -- Unsaturated data families are possible
  710. , [FamInstMatch { fim_instance = fam_inst
  711. , fim_index = fam_ind
  712. , fim_tys = inst_tys }] <- lookupFamInstEnv env tc ntys
  713. = let -- A matching family instance exists
  714. ax = famInstAxiom fam_inst
  715. co = mkAxInstCo ax fam_ind inst_tys
  716. rhs = mkAxInstRHS ax fam_ind inst_tys
  717. first_coi = mkTransCo tycon_coi co
  718. (rest_coi,nty) = normaliseType env rhs
  719. fix_coi = mkTransCo first_coi rest_coi
  720. in
  721. (fix_coi, nty)
  722. | otherwise -- No unique matching family instance exists;
  723. -- we do not do anything (including for newtypes)
  724. = (tycon_coi, TyConApp tc ntys)
  725. where
  726. -- Normalise the arg types so that they'll match
  727. -- when we lookup in in the instance envt
  728. (cois, ntys) = mapAndUnzip (normaliseType env) tys
  729. tycon_coi = mkTyConAppCo tc cois
  730. ---------------
  731. normaliseType :: FamInstEnvs -- environment with family instances
  732. -> Type -- old type
  733. -> (Coercion, Type) -- (coercion,new type), where
  734. -- co :: old-type ~ new_type
  735. -- Normalise the input type, by eliminating *all* type-function redexes
  736. -- Returns with Refl if nothing happens
  737. -- Does nothing to newtypes
  738. normaliseType env ty
  739. | Just ty' <- coreView ty = normaliseType env ty'
  740. normaliseType env (TyConApp tc tys)
  741. = normaliseTcApp env tc tys
  742. normaliseType _env ty@(LitTy {}) = (Refl ty, ty)
  743. normaliseType env (AppTy ty1 ty2)
  744. = let (coi1,nty1) = normaliseType env ty1
  745. (coi2,nty2) = normaliseType env ty2
  746. in (mkAppCo coi1 coi2, mkAppTy nty1 nty2)
  747. normaliseType env (FunTy ty1 ty2)
  748. = let (coi1,nty1) = normaliseType env ty1
  749. (coi2,nty2) = normaliseType env ty2
  750. in (mkFunCo coi1 coi2, mkFunTy nty1 nty2)
  751. normaliseType env (ForAllTy tyvar ty1)
  752. = let (coi,nty1) = normaliseType env ty1
  753. in (mkForAllCo tyvar coi, ForAllTy tyvar nty1)
  754. normaliseType _ ty@(TyVarTy _)
  755. = (Refl ty,ty)
  756. \end{code}