PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

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

http://picorec.googlecode.com/
Haskell | 534 lines | 358 code | 94 blank | 82 comment | 10 complexity | 1346d75e4a38a94cc5af011eef8efe48 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause
  1. %
  2. % (c) The University of Glasgow 2006
  3. %
  4. FamInstEnv: Type checked family instance declarations
  5. \begin{code}
  6. module FamInstEnv (
  7. FamInst(..), famInstTyCon, famInstTyVars,
  8. pprFamInst, pprFamInstHdr, pprFamInsts,
  9. famInstHead, mkLocalFamInst, mkImportedFamInst,
  10. FamInstEnvs, FamInstEnv, emptyFamInstEnv, emptyFamInstEnvs,
  11. extendFamInstEnv, extendFamInstEnvList,
  12. famInstEnvElts, familyInstances,
  13. lookupFamInstEnv, lookupFamInstEnvConflicts,
  14. -- Normalisation
  15. topNormaliseType
  16. ) where
  17. #include "HsVersions.h"
  18. import InstEnv
  19. import Unify
  20. import Type
  21. import TypeRep
  22. import TyCon
  23. import Coercion
  24. import VarSet
  25. import Var
  26. import Name
  27. import UniqFM
  28. import Outputable
  29. import Maybes
  30. import Util
  31. import FastString
  32. \end{code}
  33. %************************************************************************
  34. %* *
  35. \subsection{Type checked family instance heads}
  36. %* *
  37. %************************************************************************
  38. \begin{code}
  39. data FamInst
  40. = FamInst { fi_fam :: Name -- Family name
  41. -- INVARIANT: fi_fam = case tyConFamInst_maybe fi_tycon of
  42. -- Just (tc, tys) -> tc
  43. -- Used for "rough matching"; same idea as for class instances
  44. , fi_tcs :: [Maybe Name] -- Top of type args
  45. -- INVARIANT: fi_tcs = roughMatchTcs fi_tys
  46. -- Used for "proper matching"; ditto
  47. , fi_tvs :: TyVarSet -- Template tyvars for full match
  48. , fi_tys :: [Type] -- Full arg types
  49. -- INVARIANT: fi_tvs = tyConTyVars fi_tycon
  50. -- fi_tys = case tyConFamInst_maybe fi_tycon of
  51. -- Just (_, tys) -> tys
  52. , fi_tycon :: TyCon -- Representation tycon
  53. }
  54. -- Obtain the representation tycon of a family instance.
  55. --
  56. famInstTyCon :: FamInst -> TyCon
  57. famInstTyCon = fi_tycon
  58. famInstTyVars :: FamInst -> TyVarSet
  59. famInstTyVars = fi_tvs
  60. \end{code}
  61. \begin{code}
  62. instance NamedThing FamInst where
  63. getName = getName . fi_tycon
  64. instance Outputable FamInst where
  65. ppr = pprFamInst
  66. -- Prints the FamInst as a family instance declaration
  67. pprFamInst :: FamInst -> SDoc
  68. pprFamInst famInst
  69. = hang (pprFamInstHdr famInst)
  70. 2 (ptext (sLit "--") <+> pprNameLoc (getName famInst))
  71. pprFamInstHdr :: FamInst -> SDoc
  72. pprFamInstHdr (FamInst {fi_tycon = rep_tc})
  73. = pprTyConSort <+> pp_instance <+> pprHead
  74. where
  75. Just (fam_tc, tys) = tyConFamInst_maybe rep_tc
  76. -- For *associated* types, say "type T Int = blah"
  77. -- For *top level* type instances, say "type instance T Int = blah"
  78. pp_instance
  79. | isTyConAssoc fam_tc = empty
  80. | otherwise = ptext (sLit "instance")
  81. pprHead = pprTypeApp fam_tc tys
  82. pprTyConSort | isDataTyCon rep_tc = ptext (sLit "data")
  83. | isNewTyCon rep_tc = ptext (sLit "newtype")
  84. | isSynTyCon rep_tc = ptext (sLit "type")
  85. | isAbstractTyCon rep_tc = ptext (sLit "data")
  86. | otherwise = panic "FamInstEnv.pprFamInstHdr"
  87. pprFamInsts :: [FamInst] -> SDoc
  88. pprFamInsts finsts = vcat (map pprFamInst finsts)
  89. famInstHead :: FamInst -> ([TyVar], TyCon, [Type])
  90. famInstHead (FamInst {fi_tycon = tycon})
  91. = case tyConFamInst_maybe tycon of
  92. Nothing -> panic "FamInstEnv.famInstHead"
  93. Just (fam, tys) -> (tyConTyVars tycon, fam, tys)
  94. -- Make a family instance representation from a tycon. This is used for local
  95. -- instances, where we can safely pull on the tycon.
  96. --
  97. mkLocalFamInst :: TyCon -> FamInst
  98. mkLocalFamInst tycon
  99. = case tyConFamInst_maybe tycon of
  100. Nothing -> panic "FamInstEnv.mkLocalFamInst"
  101. Just (fam, tys) ->
  102. FamInst {
  103. fi_fam = tyConName fam,
  104. fi_tcs = roughMatchTcs tys,
  105. fi_tvs = mkVarSet . tyConTyVars $ tycon,
  106. fi_tys = tys,
  107. fi_tycon = tycon
  108. }
  109. -- Make a family instance representation from the information found in an
  110. -- unterface file. In particular, we get the rough match info from the iface
  111. -- (instead of computing it here).
  112. --
  113. mkImportedFamInst :: Name -> [Maybe Name] -> TyCon -> FamInst
  114. mkImportedFamInst fam mb_tcs tycon
  115. = FamInst {
  116. fi_fam = fam,
  117. fi_tcs = mb_tcs,
  118. fi_tvs = mkVarSet . tyConTyVars $ tycon,
  119. fi_tys = case tyConFamInst_maybe tycon of
  120. Nothing -> panic "FamInstEnv.mkImportedFamInst"
  121. Just (_, tys) -> tys,
  122. fi_tycon = tycon
  123. }
  124. \end{code}
  125. %************************************************************************
  126. %* *
  127. FamInstEnv
  128. %* *
  129. %************************************************************************
  130. Note [FamInstEnv]
  131. ~~~~~~~~~~~~~~~~~~~~~
  132. A FamInstEnv maps a family name to the list of known instances for that family.
  133. The same FamInstEnv includes both 'data family' and 'type family' instances.
  134. Type families are reduced during type inference, but not data families;
  135. the user explains when to use a data family instance by using contructors
  136. and pattern matching.
  137. Neverthless it is still useful to have data families in the FamInstEnv:
  138. - For finding overlaps and conflicts
  139. - For finding the representation type...see FamInstEnv.topNormaliseType
  140. and its call site in Simplify
  141. - In standalone deriving instance Eq (T [Int]) we need to find the
  142. representation type for T [Int]
  143. \begin{code}
  144. type FamInstEnv = UniqFM FamilyInstEnv -- Maps a family to its instances
  145. -- See Note [FamInstEnv]
  146. type FamInstEnvs = (FamInstEnv, FamInstEnv)
  147. -- External package inst-env, Home-package inst-env
  148. data FamilyInstEnv
  149. = FamIE [FamInst] -- The instances for a particular family, in any order
  150. Bool -- True <=> there is an instance of form T a b c
  151. -- If *not* then the common case of looking up
  152. -- (T a b c) can fail immediately
  153. instance Outputable FamilyInstEnv where
  154. ppr (FamIE fs b) = ptext (sLit "FamIE") <+> ppr b <+> vcat (map ppr fs)
  155. -- INVARIANTS:
  156. -- * The fs_tvs are distinct in each FamInst
  157. -- of a range value of the map (so we can safely unify them)
  158. emptyFamInstEnvs :: (FamInstEnv, FamInstEnv)
  159. emptyFamInstEnvs = (emptyFamInstEnv, emptyFamInstEnv)
  160. emptyFamInstEnv :: FamInstEnv
  161. emptyFamInstEnv = emptyUFM
  162. famInstEnvElts :: FamInstEnv -> [FamInst]
  163. famInstEnvElts fi = [elt | FamIE elts _ <- eltsUFM fi, elt <- elts]
  164. familyInstances :: (FamInstEnv, FamInstEnv) -> TyCon -> [FamInst]
  165. familyInstances (pkg_fie, home_fie) fam
  166. = get home_fie ++ get pkg_fie
  167. where
  168. get env = case lookupUFM env fam of
  169. Just (FamIE insts _) -> insts
  170. Nothing -> []
  171. extendFamInstEnvList :: FamInstEnv -> [FamInst] -> FamInstEnv
  172. extendFamInstEnvList inst_env fis = foldl extendFamInstEnv inst_env fis
  173. extendFamInstEnv :: FamInstEnv -> FamInst -> FamInstEnv
  174. extendFamInstEnv inst_env ins_item@(FamInst {fi_fam = cls_nm, fi_tcs = mb_tcs})
  175. = addToUFM_C add inst_env cls_nm (FamIE [ins_item] ins_tyvar)
  176. where
  177. add (FamIE items tyvar) _ = FamIE (ins_item:items)
  178. (ins_tyvar || tyvar)
  179. ins_tyvar = not (any isJust mb_tcs)
  180. \end{code}
  181. %************************************************************************
  182. %* *
  183. Looking up a family instance
  184. %* *
  185. %************************************************************************
  186. @lookupFamInstEnv@ looks up in a @FamInstEnv@, using a one-way match.
  187. Multiple matches are only possible in case of type families (not data
  188. families), and then, it doesn't matter which match we choose (as the
  189. instances are guaranteed confluent).
  190. We return the matching family instances and the type instance at which it
  191. matches. For example, if we lookup 'T [Int]' and have a family instance
  192. data instance T [a] = ..
  193. desugared to
  194. data :R42T a = ..
  195. coe :Co:R42T a :: T [a] ~ :R42T a
  196. we return the matching instance '(FamInst{.., fi_tycon = :R42T}, Int)'.
  197. \begin{code}
  198. type FamInstMatch = (FamInst, [Type]) -- Matching type instance
  199. -- See Note [Over-saturated matches]
  200. lookupFamInstEnv
  201. :: FamInstEnvs
  202. -> TyCon -> [Type] -- What we are looking for
  203. -> [FamInstMatch] -- Successful matches
  204. -- Precondition: the tycon is saturated (or over-saturated)
  205. lookupFamInstEnv
  206. = lookup_fam_inst_env match True
  207. where
  208. match _ tpl_tvs tpl_tys tys = tcMatchTys tpl_tvs tpl_tys tys
  209. lookupFamInstEnvConflicts
  210. :: FamInstEnvs
  211. -> FamInst -- Putative new instance
  212. -> [TyVar] -- Unique tyvars, matching arity of FamInst
  213. -> [FamInstMatch] -- Conflicting matches
  214. -- E.g. when we are about to add
  215. -- f : type instance F [a] = a->a
  216. -- we do (lookupFamInstConflicts f [b])
  217. -- to find conflicting matches
  218. -- The skolem tyvars are needed because we don't have a
  219. -- unique supply to hand
  220. --
  221. -- Precondition: the tycon is saturated (or over-saturated)
  222. lookupFamInstEnvConflicts envs fam_inst skol_tvs
  223. = lookup_fam_inst_env my_unify False envs fam tys'
  224. where
  225. inst_tycon = famInstTyCon fam_inst
  226. (fam, tys) = expectJust "FamInstEnv.lookuFamInstEnvConflicts"
  227. (tyConFamInst_maybe inst_tycon)
  228. skol_tys = mkTyVarTys skol_tvs
  229. tys' = substTys (zipTopTvSubst (tyConTyVars inst_tycon) skol_tys) tys
  230. -- In example above, fam tys' = F [b]
  231. my_unify old_fam_inst tpl_tvs tpl_tys match_tys
  232. = ASSERT2( tyVarsOfTypes tys `disjointVarSet` tpl_tvs,
  233. (ppr fam <+> ppr tys) $$
  234. (ppr tpl_tvs <+> ppr tpl_tys) )
  235. -- Unification will break badly if the variables overlap
  236. -- They shouldn't because we allocate separate uniques for them
  237. case tcUnifyTys instanceBindFun tpl_tys match_tys of
  238. Just subst | conflicting old_fam_inst subst -> Just subst
  239. _other -> Nothing
  240. -- - In the case of data family instances, any overlap is fundamentally a
  241. -- conflict (as these instances imply injective type mappings).
  242. -- - In the case of type family instances, overlap is admitted as long as
  243. -- the right-hand sides of the overlapping rules coincide under the
  244. -- overlap substitution. We require that they are syntactically equal;
  245. -- anything else would be difficult to test for at this stage.
  246. conflicting old_fam_inst subst
  247. | isAlgTyCon fam = True
  248. | otherwise = not (old_rhs `tcEqType` new_rhs)
  249. where
  250. old_tycon = famInstTyCon old_fam_inst
  251. old_tvs = tyConTyVars old_tycon
  252. old_rhs = mkTyConApp old_tycon (substTyVars subst old_tvs)
  253. new_rhs = mkTyConApp inst_tycon (substTyVars subst skol_tvs)
  254. \end{code}
  255. While @lookupFamInstEnv@ uses a one-way match, the next function
  256. @lookupFamInstEnvConflicts@ uses two-way matching (ie, unification). This is
  257. needed to check for overlapping instances.
  258. For class instances, these two variants of lookup are combined into one
  259. function (cf, @InstEnv@). We don't do that for family instances as the
  260. results of matching and unification are used in two different contexts.
  261. Moreover, matching is the wildly more frequently used operation in the case of
  262. indexed synonyms and we don't want to slow that down by needless unification.
  263. \begin{code}
  264. ------------------------------------------------------------
  265. -- Might be a one-way match or a unifier
  266. type MatchFun = FamInst -- The FamInst template
  267. -> TyVarSet -> [Type] -- fi_tvs, fi_tys of that FamInst
  268. -> [Type] -- Target to match against
  269. -> Maybe TvSubst
  270. type OneSidedMatch = Bool -- Are optimisations that are only valid for
  271. -- one sided matches allowed?
  272. lookup_fam_inst_env -- The worker, local to this module
  273. :: MatchFun
  274. -> OneSidedMatch
  275. -> FamInstEnvs
  276. -> TyCon -> [Type] -- What we are looking for
  277. -> [FamInstMatch] -- Successful matches
  278. -- Precondition: the tycon is saturated (or over-saturated)
  279. lookup_fam_inst_env match_fun one_sided (pkg_ie, home_ie) fam tys
  280. | not (isFamilyTyCon fam)
  281. = []
  282. | otherwise
  283. = ASSERT2( n_tys >= arity, ppr fam <+> ppr tys ) -- Family type applications must be saturated
  284. home_matches ++ pkg_matches
  285. where
  286. home_matches = lookup home_ie
  287. pkg_matches = lookup pkg_ie
  288. -- See Note [Over-saturated matches]
  289. arity = tyConArity fam
  290. n_tys = length tys
  291. extra_tys = drop arity tys
  292. (match_tys, add_extra_tys)
  293. | arity > n_tys = (take arity tys, \res_tys -> res_tys ++ extra_tys)
  294. | otherwise = (tys, \res_tys -> res_tys)
  295. -- The second case is the common one, hence functional representation
  296. --------------
  297. rough_tcs = roughMatchTcs match_tys
  298. all_tvs = all isNothing rough_tcs && one_sided
  299. --------------
  300. lookup env = case lookupUFM env fam of
  301. Nothing -> [] -- No instances for this class
  302. Just (FamIE insts has_tv_insts)
  303. -- Short cut for common case:
  304. -- The thing we are looking up is of form (C a
  305. -- b c), and the FamIE has no instances of
  306. -- that form, so don't bother to search
  307. | all_tvs && not has_tv_insts -> []
  308. | otherwise -> find insts
  309. --------------
  310. find [] = []
  311. find (item@(FamInst { fi_tcs = mb_tcs, fi_tvs = tpl_tvs,
  312. fi_tys = tpl_tys, fi_tycon = tycon }) : rest)
  313. -- Fast check for no match, uses the "rough match" fields
  314. | instanceCantMatch rough_tcs mb_tcs
  315. = find rest
  316. -- Proper check
  317. | Just subst <- match_fun item tpl_tvs tpl_tys match_tys
  318. = (item, add_extra_tys $ substTyVars subst (tyConTyVars tycon)) : find rest
  319. -- No match => try next
  320. | otherwise
  321. = find rest
  322. \end{code}
  323. Note [Over-saturated matches]
  324. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  325. It's ok to look up an over-saturated type constructor. E.g.
  326. type family F a :: * -> *
  327. type instance F (a,b) = Either (a->b)
  328. The type instance gives rise to a newtype TyCon (at a higher kind
  329. which you can't do in Haskell!):
  330. newtype FPair a b = FP (Either (a->b))
  331. Then looking up (F (Int,Bool) Char) will return a FamInstMatch
  332. (FPair, [Int,Bool,Char])
  333. The "extra" type argument [Char] just stays on the end.
  334. %************************************************************************
  335. %* *
  336. Looking up a family instance
  337. %* *
  338. %************************************************************************
  339. \begin{code}
  340. topNormaliseType :: FamInstEnvs
  341. -> Type
  342. -> Maybe (Coercion, Type)
  343. -- Get rid of *outermost* (or toplevel)
  344. -- * type functions
  345. -- * newtypes
  346. -- using appropriate coercions.
  347. -- By "outer" we mean that toplevelNormaliseType guarantees to return
  348. -- a type that does not have a reducible redex (F ty1 .. tyn) as its
  349. -- outermost form. It *can* return something like (Maybe (F ty)), where
  350. -- (F ty) is a redex.
  351. -- Its a bit like Type.repType, but handles type families too
  352. topNormaliseType env ty
  353. = go [] ty
  354. where
  355. go :: [TyCon] -> Type -> Maybe (Coercion, Type)
  356. go rec_nts ty | Just ty' <- coreView ty -- Expand synonyms
  357. = go rec_nts ty'
  358. go rec_nts (TyConApp tc tys) -- Expand newtypes
  359. | Just co_con <- newTyConCo_maybe tc -- See Note [Expanding newtypes]
  360. = if tc `elem` rec_nts -- in Type.lhs
  361. then Nothing
  362. else let nt_co = mkTyConApp co_con tys
  363. in add_co nt_co rec_nts' nt_rhs
  364. where
  365. nt_rhs = newTyConInstRhs tc tys
  366. rec_nts' | isRecursiveTyCon tc = tc:rec_nts
  367. | otherwise = rec_nts
  368. go rec_nts (TyConApp tc tys) -- Expand open tycons
  369. | isFamilyTyCon tc
  370. , (ACo co, ty) <- normaliseTcApp env tc tys
  371. = -- The ACo says "something happened"
  372. -- Note that normaliseType fully normalises, but it has do to so
  373. -- to be sure that
  374. add_co co rec_nts ty
  375. go _ _ = Nothing
  376. add_co co rec_nts ty
  377. = case go rec_nts ty of
  378. Nothing -> Just (co, ty)
  379. Just (co', ty') -> Just (mkTransCoercion co co', ty')
  380. ---------------
  381. normaliseTcApp :: FamInstEnvs -> TyCon -> [Type] -> (CoercionI, Type)
  382. normaliseTcApp env tc tys
  383. | isFamilyTyCon tc
  384. , tyConArity tc <= length tys -- Unsaturated data families are possible
  385. , [(fam_inst, inst_tys)] <- lookupFamInstEnv env tc ntys
  386. = let -- A matching family instance exists
  387. rep_tc = famInstTyCon fam_inst
  388. co_tycon = expectJust "lookupFamInst" (tyConFamilyCoercion_maybe rep_tc)
  389. co = mkTyConApp co_tycon inst_tys
  390. first_coi = mkTransCoI tycon_coi (ACo co)
  391. (rest_coi, nty) = normaliseType env (mkTyConApp rep_tc inst_tys)
  392. fix_coi = mkTransCoI first_coi rest_coi
  393. in
  394. (fix_coi, nty)
  395. | otherwise
  396. = (tycon_coi, TyConApp tc ntys)
  397. where
  398. -- Normalise the arg types so that they'll match
  399. -- when we lookup in in the instance envt
  400. (cois, ntys) = mapAndUnzip (normaliseType env) tys
  401. tycon_coi = mkTyConAppCoI tc cois
  402. ---------------
  403. normaliseType :: FamInstEnvs -- environment with family instances
  404. -> Type -- old type
  405. -> (CoercionI, Type) -- (coercion,new type), where
  406. -- co :: old-type ~ new_type
  407. -- Normalise the input type, by eliminating *all* type-function redexes
  408. -- Returns with IdCo if nothing happens
  409. normaliseType env ty
  410. | Just ty' <- coreView ty = normaliseType env ty'
  411. normaliseType env (TyConApp tc tys)
  412. = normaliseTcApp env tc tys
  413. normaliseType env (AppTy ty1 ty2)
  414. = let (coi1,nty1) = normaliseType env ty1
  415. (coi2,nty2) = normaliseType env ty2
  416. in (mkAppTyCoI coi1 coi2, mkAppTy nty1 nty2)
  417. normaliseType env (FunTy ty1 ty2)
  418. = let (coi1,nty1) = normaliseType env ty1
  419. (coi2,nty2) = normaliseType env ty2
  420. in (mkFunTyCoI coi1 coi2, mkFunTy nty1 nty2)
  421. normaliseType env (ForAllTy tyvar ty1)
  422. = let (coi,nty1) = normaliseType env ty1
  423. in (mkForAllTyCoI tyvar coi, ForAllTy tyvar nty1)
  424. normaliseType _ ty@(TyVarTy _)
  425. = (IdCo ty,ty)
  426. normaliseType env (PredTy predty)
  427. = normalisePred env predty
  428. ---------------
  429. normalisePred :: FamInstEnvs -> PredType -> (CoercionI,Type)
  430. normalisePred env (ClassP cls tys)
  431. = let (cois,tys') = mapAndUnzip (normaliseType env) tys
  432. in (mkClassPPredCoI cls cois, PredTy $ ClassP cls tys')
  433. normalisePred env (IParam ipn ty)
  434. = let (coi,ty') = normaliseType env ty
  435. in (mkIParamPredCoI ipn coi, PredTy $ IParam ipn ty')
  436. normalisePred env (EqPred ty1 ty2)
  437. = let (coi1,ty1') = normaliseType env ty1
  438. (coi2,ty2') = normaliseType env ty2
  439. in (mkEqPredCoI coi1 coi2, PredTy $ EqPred ty1' ty2')
  440. \end{code}