PageRenderTime 53ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/types/FamInstEnv.lhs

https://bitbucket.org/carter/ghc
Haskell | 670 lines | 457 code | 114 blank | 99 comment | 16 complexity | ae7b8fb81361b69679dee1d6840f346b MD5 | raw file
  1. %
  2. % (c) The University of Glasgow 2006
  3. %
  4. FamInstEnv: Type checked family instance declarations
  5. \begin{code}
  6. {-# OPTIONS -fno-warn-tabs #-}
  7. -- The above warning supression flag is a temporary kludge.
  8. -- While working on this module you are encouraged to remove it and
  9. -- detab the module (please do the detabbing in a separate patch). See
  10. -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
  11. -- for details
  12. module FamInstEnv (
  13. FamInst(..), FamFlavor(..), famInstAxiom,
  14. famInstsRepTyCons, famInstRepTyCon_maybe, dataFamInstRepTyCon,
  15. famInstLHS,
  16. pprFamInst, pprFamInstHdr, pprFamInsts,
  17. mkSynFamInst, mkDataFamInst, mkImportedFamInst,
  18. FamInstEnvs, FamInstEnv, emptyFamInstEnv, emptyFamInstEnvs,
  19. extendFamInstEnv, deleteFromFamInstEnv, extendFamInstEnvList,
  20. identicalFamInst, famInstEnvElts, familyInstances,
  21. lookupFamInstEnv, lookupFamInstEnvConflicts, lookupFamInstEnvConflicts',
  22. -- Normalisation
  23. topNormaliseType, normaliseType, normaliseTcApp
  24. ) where
  25. #include "HsVersions.h"
  26. import InstEnv
  27. import Unify
  28. import Type
  29. import TypeRep
  30. import TyCon
  31. import Coercion
  32. import VarSet
  33. import VarEnv
  34. import Name
  35. import UniqFM
  36. import Outputable
  37. import Maybes
  38. import Util
  39. import FastString
  40. \end{code}
  41. %************************************************************************
  42. %* *
  43. \subsection{Type checked family instance heads}
  44. %* *
  45. %************************************************************************
  46. Note [FamInsts and CoAxioms]
  47. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  48. * CoAxioms and FamInsts are just like
  49. DFunIds and ClsInsts
  50. * A CoAxiom is a System-FC thing: it can relate any two types
  51. * A FamInst is a Haskell source-language thing, corresponding
  52. to a type/data family instance declaration.
  53. - The FamInst contains a CoAxiom, which is the evidence
  54. for the instance
  55. - The LHS of the CoAxiom is always of form F ty1 .. tyn
  56. where F is a type family
  57. \begin{code}
  58. data FamInst -- See Note [FamInsts and CoAxioms]
  59. = FamInst { fi_axiom :: CoAxiom -- The new coercion axiom introduced
  60. -- by this family instance
  61. , fi_flavor :: FamFlavor
  62. -- Everything below here is a redundant,
  63. -- cached version of the two things above
  64. , fi_fam :: Name -- Family name
  65. -- INVARIANT: fi_fam = name of fi_fam_tc
  66. -- Used for "rough matching"; same idea as for class instances
  67. -- See Note [Rough-match field] in InstEnv
  68. , fi_tcs :: [Maybe Name] -- Top of type args
  69. -- INVARIANT: fi_tcs = roughMatchTcs fi_tys
  70. -- Used for "proper matching"; ditto
  71. , fi_tvs :: TyVarSet -- Template tyvars for full match
  72. , fi_fam_tc :: TyCon -- Family tycon
  73. , fi_tys :: [Type] -- and its arg types
  74. -- INVARIANT: fi_tvs = coAxiomTyVars fi_axiom
  75. -- (fi_fam_tc, fi_tys) = coAxiomSplitLHS fi_axiom
  76. }
  77. data FamFlavor
  78. = SynFamilyInst -- A synonym family
  79. | DataFamilyInst TyCon -- A data family, with its representation TyCon
  80. \end{code}
  81. \begin{code}
  82. -- Obtain the axiom of a family instance
  83. famInstAxiom :: FamInst -> CoAxiom
  84. famInstAxiom = fi_axiom
  85. famInstLHS :: FamInst -> (TyCon, [Type])
  86. famInstLHS (FamInst { fi_fam_tc = tc, fi_tys = tys }) = (tc, tys)
  87. -- Return the representation TyCons introduced by data family instances, if any
  88. famInstsRepTyCons :: [FamInst] -> [TyCon]
  89. famInstsRepTyCons fis = [tc | FamInst { fi_flavor = DataFamilyInst tc } <- fis]
  90. -- Extracts the TyCon for this *data* (or newtype) instance
  91. famInstRepTyCon_maybe :: FamInst -> Maybe TyCon
  92. famInstRepTyCon_maybe fi
  93. = case fi_flavor fi of
  94. DataFamilyInst tycon -> Just tycon
  95. SynFamilyInst -> Nothing
  96. dataFamInstRepTyCon :: FamInst -> TyCon
  97. dataFamInstRepTyCon fi
  98. = case fi_flavor fi of
  99. DataFamilyInst tycon -> tycon
  100. SynFamilyInst -> pprPanic "dataFamInstRepTyCon" (ppr fi)
  101. \end{code}
  102. \begin{code}
  103. instance NamedThing FamInst where
  104. getName = coAxiomName . fi_axiom
  105. instance Outputable FamInst where
  106. ppr = pprFamInst
  107. -- Prints the FamInst as a family instance declaration
  108. pprFamInst :: FamInst -> SDoc
  109. pprFamInst famInst
  110. = hang (pprFamInstHdr famInst)
  111. 2 (vcat [ ifPprDebug (ptext (sLit "Coercion axiom:") <+> ppr ax)
  112. , ifPprDebug (ptext (sLit "RHS:") <+> ppr (coAxiomRHS ax))
  113. , ptext (sLit "--") <+> pprDefinedAt (getName famInst)])
  114. where
  115. ax = fi_axiom famInst
  116. pprFamInstHdr :: FamInst -> SDoc
  117. pprFamInstHdr (FamInst {fi_axiom = axiom, fi_flavor = flavor})
  118. = pprTyConSort <+> pp_instance <+> pprHead
  119. where
  120. (fam_tc, tys) = coAxiomSplitLHS axiom
  121. -- For *associated* types, say "type T Int = blah"
  122. -- For *top level* type instances, say "type instance T Int = blah"
  123. pp_instance
  124. | isTyConAssoc fam_tc = empty
  125. | otherwise = ptext (sLit "instance")
  126. pprHead = sep [ ifPprDebug (ptext (sLit "forall")
  127. <+> pprTvBndrs (coAxiomTyVars axiom))
  128. , pprTypeApp fam_tc tys ]
  129. pprTyConSort = case flavor of
  130. SynFamilyInst -> ptext (sLit "type")
  131. DataFamilyInst tycon
  132. | isDataTyCon tycon -> ptext (sLit "data")
  133. | isNewTyCon tycon -> ptext (sLit "newtype")
  134. | isAbstractTyCon tycon -> ptext (sLit "data")
  135. | otherwise -> ptext (sLit "WEIRD") <+> ppr tycon
  136. pprFamInsts :: [FamInst] -> SDoc
  137. pprFamInsts finsts = vcat (map pprFamInst finsts)
  138. -- | Create a coercion identifying a @type@ family instance.
  139. -- It has the form @Co tvs :: F ts ~ R@, where @Co@ is
  140. -- the coercion constructor built here, @F@ the family tycon and @R@ the
  141. -- right-hand side of the type family instance.
  142. mkSynFamInst :: Name -- ^ Unique name for the coercion tycon
  143. -> [TyVar] -- ^ Type parameters of the coercion (@tvs@)
  144. -> TyCon -- ^ Family tycon (@F@)
  145. -> [Type] -- ^ Type instance (@ts@)
  146. -> Type -- ^ Representation tycon (@R@)
  147. -> FamInst
  148. mkSynFamInst name tvs fam_tc inst_tys rep_ty
  149. = FamInst { fi_fam = tyConName fam_tc,
  150. fi_fam_tc = fam_tc,
  151. fi_tcs = roughMatchTcs inst_tys,
  152. fi_tvs = mkVarSet tvs,
  153. fi_tys = inst_tys,
  154. fi_flavor = SynFamilyInst,
  155. fi_axiom = axiom }
  156. where
  157. axiom = CoAxiom { co_ax_unique = nameUnique name
  158. , co_ax_name = name
  159. , co_ax_implicit = False
  160. , co_ax_tvs = tvs
  161. , co_ax_lhs = mkTyConApp fam_tc inst_tys
  162. , co_ax_rhs = rep_ty }
  163. -- | Create a coercion identifying a @data@ or @newtype@ representation type
  164. -- and its family instance. It has the form @Co tvs :: F ts ~ R tvs@,
  165. -- where @Co@ is the coercion constructor built here, @F@ the family tycon
  166. -- and @R@ the (derived) representation tycon.
  167. mkDataFamInst :: Name -- ^ Unique name for the coercion tycon
  168. -> [TyVar] -- ^ Type parameters of the coercion (@tvs@)
  169. -> TyCon -- ^ Family tycon (@F@)
  170. -> [Type] -- ^ Type instance (@ts@)
  171. -> TyCon -- ^ Representation tycon (@R@)
  172. -> FamInst
  173. mkDataFamInst name tvs fam_tc inst_tys rep_tc
  174. = FamInst { fi_fam = tyConName fam_tc,
  175. fi_fam_tc = fam_tc,
  176. fi_tcs = roughMatchTcs inst_tys,
  177. fi_tvs = mkVarSet tvs,
  178. fi_tys = inst_tys,
  179. fi_flavor = DataFamilyInst rep_tc,
  180. fi_axiom = axiom }
  181. where
  182. axiom = CoAxiom { co_ax_unique = nameUnique name
  183. , co_ax_name = name
  184. , co_ax_implicit = False
  185. , co_ax_tvs = tvs
  186. , co_ax_lhs = mkTyConApp fam_tc inst_tys
  187. , co_ax_rhs = mkTyConApp rep_tc (mkTyVarTys tvs) }
  188. -- Make a family instance representation from the information found in an
  189. -- interface file. In particular, we get the rough match info from the iface
  190. -- (instead of computing it here).
  191. mkImportedFamInst :: Name -- Name of the family
  192. -> [Maybe Name] -- Rough match info
  193. -> CoAxiom -- Axiom introduced
  194. -> FamInst -- Resulting family instance
  195. mkImportedFamInst fam mb_tcs axiom
  196. = FamInst {
  197. fi_fam = fam,
  198. fi_fam_tc = fam_tc,
  199. fi_tcs = mb_tcs,
  200. fi_tvs = mkVarSet . coAxiomTyVars $ axiom,
  201. fi_tys = tys,
  202. fi_axiom = axiom,
  203. fi_flavor = flavor }
  204. where
  205. (fam_tc, tys) = coAxiomSplitLHS axiom
  206. -- Derive the flavor for an imported FamInst rather disgustingly
  207. -- Maybe we should store it in the IfaceFamInst?
  208. flavor = case splitTyConApp_maybe (coAxiomRHS axiom) of
  209. Just (tc, _)
  210. | Just ax' <- tyConFamilyCoercion_maybe tc
  211. , ax' == axiom
  212. -> DataFamilyInst tc
  213. _ -> SynFamilyInst
  214. \end{code}
  215. %************************************************************************
  216. %* *
  217. FamInstEnv
  218. %* *
  219. %************************************************************************
  220. Note [FamInstEnv]
  221. ~~~~~~~~~~~~~~~~~~~~~
  222. A FamInstEnv maps a family name to the list of known instances for that family.
  223. The same FamInstEnv includes both 'data family' and 'type family' instances.
  224. Type families are reduced during type inference, but not data families;
  225. the user explains when to use a data family instance by using contructors
  226. and pattern matching.
  227. Neverthless it is still useful to have data families in the FamInstEnv:
  228. - For finding overlaps and conflicts
  229. - For finding the representation type...see FamInstEnv.topNormaliseType
  230. and its call site in Simplify
  231. - In standalone deriving instance Eq (T [Int]) we need to find the
  232. representation type for T [Int]
  233. \begin{code}
  234. type FamInstEnv = UniqFM FamilyInstEnv -- Maps a family to its instances
  235. -- See Note [FamInstEnv]
  236. type FamInstEnvs = (FamInstEnv, FamInstEnv)
  237. -- External package inst-env, Home-package inst-env
  238. data FamilyInstEnv
  239. = FamIE [FamInst] -- The instances for a particular family, in any order
  240. Bool -- True <=> there is an instance of form T a b c
  241. -- If *not* then the common case of looking up
  242. -- (T a b c) can fail immediately
  243. instance Outputable FamilyInstEnv where
  244. ppr (FamIE fs b) = ptext (sLit "FamIE") <+> ppr b <+> vcat (map ppr fs)
  245. -- INVARIANTS:
  246. -- * The fs_tvs are distinct in each FamInst
  247. -- of a range value of the map (so we can safely unify them)
  248. emptyFamInstEnvs :: (FamInstEnv, FamInstEnv)
  249. emptyFamInstEnvs = (emptyFamInstEnv, emptyFamInstEnv)
  250. emptyFamInstEnv :: FamInstEnv
  251. emptyFamInstEnv = emptyUFM
  252. famInstEnvElts :: FamInstEnv -> [FamInst]
  253. famInstEnvElts fi = [elt | FamIE elts _ <- eltsUFM fi, elt <- elts]
  254. familyInstances :: (FamInstEnv, FamInstEnv) -> TyCon -> [FamInst]
  255. familyInstances (pkg_fie, home_fie) fam
  256. = get home_fie ++ get pkg_fie
  257. where
  258. get env = case lookupUFM env fam of
  259. Just (FamIE insts _) -> insts
  260. Nothing -> []
  261. extendFamInstEnvList :: FamInstEnv -> [FamInst] -> FamInstEnv
  262. extendFamInstEnvList inst_env fis = foldl extendFamInstEnv inst_env fis
  263. extendFamInstEnv :: FamInstEnv -> FamInst -> FamInstEnv
  264. extendFamInstEnv inst_env ins_item@(FamInst {fi_fam = cls_nm, fi_tcs = mb_tcs})
  265. = addToUFM_C add inst_env cls_nm (FamIE [ins_item] ins_tyvar)
  266. where
  267. add (FamIE items tyvar) _ = FamIE (ins_item:items)
  268. (ins_tyvar || tyvar)
  269. ins_tyvar = not (any isJust mb_tcs)
  270. deleteFromFamInstEnv :: FamInstEnv -> FamInst -> FamInstEnv
  271. deleteFromFamInstEnv inst_env fam_inst@(FamInst {fi_fam = fam_nm})
  272. = adjustUFM adjust inst_env fam_nm
  273. where
  274. adjust :: FamilyInstEnv -> FamilyInstEnv
  275. adjust (FamIE items tyvars)
  276. = FamIE (filterOut (identicalFamInst fam_inst) items) tyvars
  277. identicalFamInst :: FamInst -> FamInst -> Bool
  278. -- Same LHS, *and* the instance is defined in the same module
  279. -- Used for overriding in GHCi
  280. identicalFamInst (FamInst { fi_axiom = ax1 }) (FamInst { fi_axiom = ax2 })
  281. = nameModule (coAxiomName ax1) == nameModule (coAxiomName ax2)
  282. && eqTypeX rn_env (coAxiomLHS ax1) (coAxiomLHS ax2)
  283. where
  284. tvs1 = coAxiomTyVars ax1
  285. tvs2 = coAxiomTyVars ax2
  286. rn_env = ASSERT( equalLength tvs1 tvs2 )
  287. rnBndrs2 (mkRnEnv2 emptyInScopeSet) tvs1 tvs2
  288. \end{code}
  289. %************************************************************************
  290. %* *
  291. Looking up a family instance
  292. %* *
  293. %************************************************************************
  294. @lookupFamInstEnv@ looks up in a @FamInstEnv@, using a one-way match.
  295. Multiple matches are only possible in case of type families (not data
  296. families), and then, it doesn't matter which match we choose (as the
  297. instances are guaranteed confluent).
  298. We return the matching family instances and the type instance at which it
  299. matches. For example, if we lookup 'T [Int]' and have a family instance
  300. data instance T [a] = ..
  301. desugared to
  302. data :R42T a = ..
  303. coe :Co:R42T a :: T [a] ~ :R42T a
  304. we return the matching instance '(FamInst{.., fi_tycon = :R42T}, Int)'.
  305. \begin{code}
  306. type FamInstMatch = (FamInst, [Type]) -- Matching type instance
  307. -- See Note [Over-saturated matches]
  308. lookupFamInstEnv
  309. :: FamInstEnvs
  310. -> TyCon -> [Type] -- What we are looking for
  311. -> [FamInstMatch] -- Successful matches
  312. -- Precondition: the tycon is saturated (or over-saturated)
  313. lookupFamInstEnv
  314. = lookup_fam_inst_env match True
  315. where
  316. match _ tpl_tvs tpl_tys tys = tcMatchTys tpl_tvs tpl_tys tys
  317. lookupFamInstEnvConflicts
  318. :: FamInstEnvs
  319. -> FamInst -- Putative new instance
  320. -> [TyVar] -- Unique tyvars, matching arity of FamInst
  321. -> [FamInstMatch] -- Conflicting matches
  322. -- E.g. when we are about to add
  323. -- f : type instance F [a] = a->a
  324. -- we do (lookupFamInstConflicts f [b])
  325. -- to find conflicting matches
  326. -- The skolem tyvars are needed because we don't have a
  327. -- unique supply to hand
  328. --
  329. -- Precondition: the tycon is saturated (or over-saturated)
  330. lookupFamInstEnvConflicts envs fam_inst skol_tvs
  331. = lookup_fam_inst_env my_unify False envs fam tys1
  332. where
  333. inst_axiom = famInstAxiom fam_inst
  334. (fam, tys) = famInstLHS fam_inst
  335. skol_tys = mkTyVarTys skol_tvs
  336. tys1 = substTys (zipTopTvSubst (coAxiomTyVars inst_axiom) skol_tys) tys
  337. -- In example above, fam tys' = F [b]
  338. my_unify old_fam_inst tpl_tvs tpl_tys match_tys
  339. = ASSERT2( tyVarsOfTypes tys1 `disjointVarSet` tpl_tvs,
  340. (ppr fam <+> ppr tys1) $$
  341. (ppr tpl_tvs <+> ppr tpl_tys) )
  342. -- Unification will break badly if the variables overlap
  343. -- They shouldn't because we allocate separate uniques for them
  344. case tcUnifyTys instanceBindFun tpl_tys match_tys of
  345. Just subst | conflicting old_fam_inst subst -> Just subst
  346. _other -> Nothing
  347. -- Note [Family instance overlap conflicts]
  348. conflicting old_fam_inst subst
  349. | isAlgTyCon fam = True
  350. | otherwise = not (old_rhs `eqType` new_rhs)
  351. where
  352. old_axiom = famInstAxiom old_fam_inst
  353. old_tvs = coAxiomTyVars old_axiom
  354. old_rhs = mkAxInstRHS old_axiom (substTyVars subst old_tvs)
  355. new_rhs = mkAxInstRHS inst_axiom (substTyVars subst skol_tvs)
  356. -- This variant is called when we want to check if the conflict is only in the
  357. -- home environment (see FamInst.addLocalFamInst)
  358. lookupFamInstEnvConflicts' :: FamInstEnv -> FamInst -> [TyVar] -> [FamInstMatch]
  359. lookupFamInstEnvConflicts' env fam_inst skol_tvs
  360. = lookupFamInstEnvConflicts (emptyFamInstEnv, env) fam_inst skol_tvs
  361. \end{code}
  362. Note [Family instance overlap conflicts]
  363. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  364. - In the case of data family instances, any overlap is fundamentally a
  365. conflict (as these instances imply injective type mappings).
  366. - In the case of type family instances, overlap is admitted as long as
  367. the right-hand sides of the overlapping rules coincide under the
  368. overlap substitution. eg
  369. type instance F a Int = a
  370. type instance F Int b = b
  371. These two overlap on (F Int Int) but then both RHSs are Int,
  372. so all is well. We require that they are syntactically equal;
  373. anything else would be difficult to test for at this stage.
  374. While @lookupFamInstEnv@ uses a one-way match, the next function
  375. @lookupFamInstEnvConflicts@ uses two-way matching (ie, unification). This is
  376. needed to check for overlapping instances.
  377. For class instances, these two variants of lookup are combined into one
  378. function (cf, @InstEnv@). We don't do that for family instances as the
  379. results of matching and unification are used in two different contexts.
  380. Moreover, matching is the wildly more frequently used operation in the case of
  381. indexed synonyms and we don't want to slow that down by needless unification.
  382. \begin{code}
  383. ------------------------------------------------------------
  384. -- Might be a one-way match or a unifier
  385. type MatchFun = FamInst -- The FamInst template
  386. -> TyVarSet -> [Type] -- fi_tvs, fi_tys of that FamInst
  387. -> [Type] -- Target to match against
  388. -> Maybe TvSubst
  389. type OneSidedMatch = Bool -- Are optimisations that are only valid for
  390. -- one sided matches allowed?
  391. lookup_fam_inst_env' -- The worker, local to this module
  392. :: MatchFun
  393. -> OneSidedMatch
  394. -> FamInstEnv
  395. -> TyCon -> [Type] -- What we are looking for
  396. -> [FamInstMatch] -- Successful matches
  397. lookup_fam_inst_env' match_fun one_sided ie fam tys
  398. | not (isFamilyTyCon fam)
  399. = []
  400. | otherwise
  401. = ASSERT2( n_tys >= arity, ppr fam <+> ppr tys ) -- Family type applications must be saturated
  402. lookup ie
  403. where
  404. -- See Note [Over-saturated matches]
  405. arity = tyConArity fam
  406. n_tys = length tys
  407. extra_tys = drop arity tys
  408. (match_tys, add_extra_tys)
  409. | arity < n_tys = (take arity tys, \res_tys -> res_tys ++ extra_tys)
  410. | otherwise = (tys, \res_tys -> res_tys)
  411. -- The second case is the common one, hence functional representation
  412. --------------
  413. rough_tcs = roughMatchTcs match_tys
  414. all_tvs = all isNothing rough_tcs && one_sided
  415. --------------
  416. lookup env = case lookupUFM env fam of
  417. Nothing -> [] -- No instances for this class
  418. Just (FamIE insts has_tv_insts)
  419. -- Short cut for common case:
  420. -- The thing we are looking up is of form (C a
  421. -- b c), and the FamIE has no instances of
  422. -- that form, so don't bother to search
  423. | all_tvs && not has_tv_insts -> []
  424. | otherwise -> find insts
  425. --------------
  426. find [] = []
  427. find (item@(FamInst { fi_tcs = mb_tcs, fi_tvs = tpl_tvs,
  428. fi_tys = tpl_tys, fi_axiom = axiom }) : rest)
  429. -- Fast check for no match, uses the "rough match" fields
  430. | instanceCantMatch rough_tcs mb_tcs
  431. = find rest
  432. -- Proper check
  433. | Just subst <- match_fun item tpl_tvs tpl_tys match_tys
  434. = (item, add_extra_tys $ substTyVars subst (coAxiomTyVars axiom)) : find rest
  435. -- No match => try next
  436. | otherwise
  437. = find rest
  438. -- Precondition: the tycon is saturated (or over-saturated)
  439. lookup_fam_inst_env -- The worker, local to this module
  440. :: MatchFun
  441. -> OneSidedMatch
  442. -> FamInstEnvs
  443. -> TyCon -> [Type] -- What we are looking for
  444. -> [FamInstMatch] -- Successful matches
  445. -- Precondition: the tycon is saturated (or over-saturated)
  446. lookup_fam_inst_env match_fun one_sided (pkg_ie, home_ie) fam tys =
  447. lookup_fam_inst_env' match_fun one_sided home_ie fam tys ++
  448. lookup_fam_inst_env' match_fun one_sided pkg_ie fam tys
  449. \end{code}
  450. Note [Over-saturated matches]
  451. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  452. It's ok to look up an over-saturated type constructor. E.g.
  453. type family F a :: * -> *
  454. type instance F (a,b) = Either (a->b)
  455. The type instance gives rise to a newtype TyCon (at a higher kind
  456. which you can't do in Haskell!):
  457. newtype FPair a b = FP (Either (a->b))
  458. Then looking up (F (Int,Bool) Char) will return a FamInstMatch
  459. (FPair, [Int,Bool,Char])
  460. The "extra" type argument [Char] just stays on the end.
  461. %************************************************************************
  462. %* *
  463. Looking up a family instance
  464. %* *
  465. %************************************************************************
  466. \begin{code}
  467. topNormaliseType :: FamInstEnvs
  468. -> Type
  469. -> Maybe (Coercion, Type)
  470. -- Get rid of *outermost* (or toplevel)
  471. -- * type functions
  472. -- * newtypes
  473. -- using appropriate coercions.
  474. -- By "outer" we mean that toplevelNormaliseType guarantees to return
  475. -- a type that does not have a reducible redex (F ty1 .. tyn) as its
  476. -- outermost form. It *can* return something like (Maybe (F ty)), where
  477. -- (F ty) is a redex.
  478. -- Its a bit like Type.repType, but handles type families too
  479. topNormaliseType env ty
  480. = go [] ty
  481. where
  482. go :: [TyCon] -> Type -> Maybe (Coercion, Type)
  483. go rec_nts ty | Just ty' <- coreView ty -- Expand synonyms
  484. = go rec_nts ty'
  485. go rec_nts (TyConApp tc tys)
  486. | isNewTyCon tc -- Expand newtypes
  487. = if tc `elem` rec_nts -- See Note [Expanding newtypes] in Type.lhs
  488. then Nothing
  489. else let nt_co = mkAxInstCo (newTyConCo tc) tys
  490. in add_co nt_co rec_nts' nt_rhs
  491. | isFamilyTyCon tc -- Expand open tycons
  492. , (co, ty) <- normaliseTcApp env tc tys
  493. -- Note that normaliseType fully normalises 'tys',
  494. -- It has do to so to be sure that nested calls like
  495. -- F (G Int)
  496. -- are correctly top-normalised
  497. , not (isReflCo co)
  498. = add_co co rec_nts ty
  499. where
  500. nt_rhs = newTyConInstRhs tc tys
  501. rec_nts' | isRecursiveTyCon tc = tc:rec_nts
  502. | otherwise = rec_nts
  503. go _ _ = Nothing
  504. add_co co rec_nts ty
  505. = case go rec_nts ty of
  506. Nothing -> Just (co, ty)
  507. Just (co', ty') -> Just (mkTransCo co co', ty')
  508. ---------------
  509. normaliseTcApp :: FamInstEnvs -> TyCon -> [Type] -> (Coercion, Type)
  510. normaliseTcApp env tc tys
  511. | isFamilyTyCon tc
  512. , tyConArity tc <= length tys -- Unsaturated data families are possible
  513. , [(fam_inst, inst_tys)] <- lookupFamInstEnv env tc ntys
  514. = let -- A matching family instance exists
  515. ax = famInstAxiom fam_inst
  516. co = mkAxInstCo ax inst_tys
  517. rhs = mkAxInstRHS ax inst_tys
  518. first_coi = mkTransCo tycon_coi co
  519. (rest_coi,nty) = normaliseType env rhs
  520. fix_coi = mkTransCo first_coi rest_coi
  521. in
  522. (fix_coi, nty)
  523. | otherwise -- No unique matching family instance exists;
  524. -- we do not do anything
  525. = (tycon_coi, TyConApp tc ntys)
  526. where
  527. -- Normalise the arg types so that they'll match
  528. -- when we lookup in in the instance envt
  529. (cois, ntys) = mapAndUnzip (normaliseType env) tys
  530. tycon_coi = mkTyConAppCo tc cois
  531. ---------------
  532. normaliseType :: FamInstEnvs -- environment with family instances
  533. -> Type -- old type
  534. -> (Coercion, Type) -- (coercion,new type), where
  535. -- co :: old-type ~ new_type
  536. -- Normalise the input type, by eliminating *all* type-function redexes
  537. -- Returns with Refl if nothing happens
  538. normaliseType env ty
  539. | Just ty' <- coreView ty = normaliseType env ty'
  540. normaliseType env (TyConApp tc tys)
  541. = normaliseTcApp env tc tys
  542. normaliseType _env ty@(LitTy {}) = (Refl ty, ty)
  543. normaliseType env (AppTy ty1 ty2)
  544. = let (coi1,nty1) = normaliseType env ty1
  545. (coi2,nty2) = normaliseType env ty2
  546. in (mkAppCo coi1 coi2, mkAppTy nty1 nty2)
  547. normaliseType env (FunTy ty1 ty2)
  548. = let (coi1,nty1) = normaliseType env ty1
  549. (coi2,nty2) = normaliseType env ty2
  550. in (mkFunCo coi1 coi2, mkFunTy nty1 nty2)
  551. normaliseType env (ForAllTy tyvar ty1)
  552. = let (coi,nty1) = normaliseType env ty1
  553. in (mkForAllCo tyvar coi, ForAllTy tyvar nty1)
  554. normaliseType _ ty@(TyVarTy _)
  555. = (Refl ty,ty)
  556. \end{code}