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

/compiler/typecheck/FamInst.lhs

https://bitbucket.org/carter/ghc
Haskell | 331 lines | 236 code | 52 blank | 43 comment | 13 complexity | f99d78bc7abdd169adc0297b6d44caf6 MD5 | raw file
  1. The @FamInst@ type: family instance heads
  2. \begin{code}
  3. {-# OPTIONS -fno-warn-tabs #-}
  4. -- The above warning supression flag is a temporary kludge.
  5. -- While working on this module you are encouraged to remove it and
  6. -- detab the module (please do the detabbing in a separate patch). See
  7. -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
  8. -- for details
  9. module FamInst (
  10. checkFamInstConsistency, tcExtendLocalFamInstEnv,
  11. tcLookupFamInst, tcLookupDataFamInst,
  12. tcGetFamInstEnvs
  13. ) where
  14. import HscTypes
  15. import FamInstEnv
  16. import LoadIface
  17. import TypeRep
  18. import TcMType
  19. import TcRnMonad
  20. import TyCon
  21. import DynFlags
  22. import Name
  23. import Module
  24. import Outputable
  25. import UniqFM
  26. import FastString
  27. import Util
  28. import Maybes
  29. import Control.Monad
  30. import Data.Map (Map)
  31. import qualified Data.Map as Map
  32. #include "HsVersions.h"
  33. \end{code}
  34. %************************************************************************
  35. %* *
  36. Optimised overlap checking for family instances
  37. %* *
  38. %************************************************************************
  39. For any two family instance modules that we import directly or indirectly, we
  40. check whether the instances in the two modules are consistent, *unless* we can
  41. be certain that the instances of the two modules have already been checked for
  42. consistency during the compilation of modules that we import.
  43. Why do we need to check? Consider
  44. module X1 where module X2 where
  45. data T1 data T2
  46. type instance F T1 b = Int type instance F a T2 = Char
  47. f1 :: F T1 a -> Int f2 :: Char -> F a T2
  48. f1 x = x f2 x = x
  49. Now if we import both X1 and X2 we could make (f2 . f1) :: Int -> Char.
  50. Notice that neither instance is an orphan.
  51. How do we know which pairs of modules have already been checked? Any pair of
  52. modules where both modules occur in the `HscTypes.dep_finsts' set (of the
  53. `HscTypes.Dependencies') of one of our directly imported modules must have
  54. already been checked. Everything else, we check now. (So that we can be
  55. certain that the modules in our `HscTypes.dep_finsts' are consistent.)
  56. \begin{code}
  57. -- The optimisation of overlap tests is based on determining pairs of modules
  58. -- whose family instances need to be checked for consistency.
  59. --
  60. data ModulePair = ModulePair Module Module
  61. -- canonical order of the components of a module pair
  62. --
  63. canon :: ModulePair -> (Module, Module)
  64. canon (ModulePair m1 m2) | m1 < m2 = (m1, m2)
  65. | otherwise = (m2, m1)
  66. instance Eq ModulePair where
  67. mp1 == mp2 = canon mp1 == canon mp2
  68. instance Ord ModulePair where
  69. mp1 `compare` mp2 = canon mp1 `compare` canon mp2
  70. instance Outputable ModulePair where
  71. ppr (ModulePair m1 m2) = angleBrackets (ppr m1 <> comma <+> ppr m2)
  72. -- Sets of module pairs
  73. --
  74. type ModulePairSet = Map ModulePair ()
  75. listToSet :: [ModulePair] -> ModulePairSet
  76. listToSet l = Map.fromList (zip l (repeat ()))
  77. checkFamInstConsistency :: [Module] -> [Module] -> TcM ()
  78. checkFamInstConsistency famInstMods directlyImpMods
  79. = do { dflags <- getDynFlags
  80. ; (eps, hpt) <- getEpsAndHpt
  81. ; let { -- Fetch the iface of a given module. Must succeed as
  82. -- all directly imported modules must already have been loaded.
  83. modIface mod =
  84. case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of
  85. Nothing -> panic "FamInst.checkFamInstConsistency"
  86. Just iface -> iface
  87. ; hmiModule = mi_module . hm_iface
  88. ; hmiFamInstEnv = extendFamInstEnvList emptyFamInstEnv
  89. . md_fam_insts . hm_details
  90. ; hpt_fam_insts = mkModuleEnv [ (hmiModule hmi, hmiFamInstEnv hmi)
  91. | hmi <- eltsUFM hpt]
  92. ; groups = map (dep_finsts . mi_deps . modIface)
  93. directlyImpMods
  94. ; okPairs = listToSet $ concatMap allPairs groups
  95. -- instances of okPairs are consistent
  96. ; criticalPairs = listToSet $ allPairs famInstMods
  97. -- all pairs that we need to consider
  98. ; toCheckPairs = Map.keys $ criticalPairs `Map.difference` okPairs
  99. -- the difference gives us the pairs we need to check now
  100. }
  101. ; mapM_ (check hpt_fam_insts) toCheckPairs
  102. }
  103. where
  104. allPairs [] = []
  105. allPairs (m:ms) = map (ModulePair m) ms ++ allPairs ms
  106. check hpt_fam_insts (ModulePair m1 m2)
  107. = do { env1 <- getFamInsts hpt_fam_insts m1
  108. ; env2 <- getFamInsts hpt_fam_insts m2
  109. ; mapM_ (checkForConflicts (emptyFamInstEnv, env2))
  110. (famInstEnvElts env1) }
  111. getFamInsts :: ModuleEnv FamInstEnv -> Module -> TcM FamInstEnv
  112. getFamInsts hpt_fam_insts mod
  113. | Just env <- lookupModuleEnv hpt_fam_insts mod = return env
  114. | otherwise = do { _ <- initIfaceTcRn (loadSysInterface doc mod)
  115. ; eps <- getEps
  116. ; return (expectJust "checkFamInstConsistency" $
  117. lookupModuleEnv (eps_mod_fam_inst_env eps) mod) }
  118. where
  119. doc = ppr mod <+> ptext (sLit "is a family-instance module")
  120. \end{code}
  121. %************************************************************************
  122. %* *
  123. Lookup
  124. %* *
  125. %************************************************************************
  126. Look up the instance tycon of a family instance.
  127. The match may be ambiguous (as we know that overlapping instances have
  128. identical right-hand sides under overlapping substitutions - see
  129. 'FamInstEnv.lookupFamInstEnvConflicts'). However, the type arguments used
  130. for matching must be equal to or be more specific than those of the family
  131. instance declaration. We pick one of the matches in case of ambiguity; as
  132. the right-hand sides are identical under the match substitution, the choice
  133. does not matter.
  134. Return the instance tycon and its type instance. For example, if we have
  135. tcLookupFamInst 'T' '[Int]' yields (':R42T', 'Int')
  136. then we have a coercion (ie, type instance of family instance coercion)
  137. :Co:R42T Int :: T [Int] ~ :R42T Int
  138. which implies that :R42T was declared as 'data instance T [a]'.
  139. \begin{code}
  140. tcLookupFamInst :: TyCon -> [Type] -> TcM (Maybe (FamInst, [Type]))
  141. tcLookupFamInst tycon tys
  142. | not (isFamilyTyCon tycon)
  143. = return Nothing
  144. | otherwise
  145. = do { instEnv <- tcGetFamInstEnvs
  146. ; let mb_match = lookupFamInstEnv instEnv tycon tys
  147. -- ; traceTc "lookupFamInst" ((ppr tycon <+> ppr tys) $$
  148. -- pprTvBndrs (varSetElems (tyVarsOfTypes tys)) $$
  149. -- ppr mb_match $$ ppr instEnv)
  150. ; case mb_match of
  151. [] -> return Nothing
  152. ((fam_inst, rep_tys):_)
  153. -> return $ Just (fam_inst, rep_tys)
  154. }
  155. tcLookupDataFamInst :: TyCon -> [Type] -> TcM (TyCon, [Type])
  156. -- Find the instance of a data family
  157. -- Note [Looking up family instances for deriving]
  158. tcLookupDataFamInst tycon tys
  159. | not (isFamilyTyCon tycon)
  160. = return (tycon, tys)
  161. | otherwise
  162. = ASSERT( isAlgTyCon tycon )
  163. do { maybeFamInst <- tcLookupFamInst tycon tys
  164. ; case maybeFamInst of
  165. Nothing -> famInstNotFound tycon tys
  166. Just (famInst, tys) -> let tycon' = dataFamInstRepTyCon famInst
  167. in return (tycon', tys) }
  168. famInstNotFound :: TyCon -> [Type] -> TcM a
  169. famInstNotFound tycon tys
  170. = failWithTc (ptext (sLit "No family instance for")
  171. <+> quotes (pprTypeApp tycon tys))
  172. \end{code}
  173. Note [Looking up family instances for deriving]
  174. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  175. tcLookupFamInstExact is an auxiliary lookup wrapper which requires
  176. that looked-up family instances exist. If called with a vanilla
  177. tycon, the old type application is simply returned.
  178. If we have
  179. data instance F () = ... deriving Eq
  180. data instance F () = ... deriving Eq
  181. then tcLookupFamInstExact will be confused by the two matches;
  182. but that can't happen because tcInstDecls1 doesn't call tcDeriving
  183. if there are any overlaps.
  184. There are two other things that might go wrong with the lookup.
  185. First, we might see a standalone deriving clause
  186. deriving Eq (F ())
  187. when there is no data instance F () in scope.
  188. Note that it's OK to have
  189. data instance F [a] = ...
  190. deriving Eq (F [(a,b)])
  191. where the match is not exact; the same holds for ordinary data types
  192. with standalone deriving declrations.
  193. %************************************************************************
  194. %* *
  195. Extending the family instance environment
  196. %* *
  197. %************************************************************************
  198. \begin{code}
  199. -- Add new locally-defined family instances
  200. tcExtendLocalFamInstEnv :: [FamInst] -> TcM a -> TcM a
  201. tcExtendLocalFamInstEnv fam_insts thing_inside
  202. = do { env <- getGblEnv
  203. ; (inst_env', fam_insts') <- foldlM addLocalFamInst
  204. (tcg_fam_inst_env env, tcg_fam_insts env)
  205. fam_insts
  206. ; let env' = env { tcg_fam_insts = fam_insts'
  207. , tcg_fam_inst_env = inst_env' }
  208. ; setGblEnv env' thing_inside
  209. }
  210. -- Check that the proposed new instance is OK,
  211. -- and then add it to the home inst env
  212. addLocalFamInst :: (FamInstEnv,[FamInst]) -> FamInst -> TcM (FamInstEnv, [FamInst])
  213. addLocalFamInst (home_fie, my_fis) fam_inst
  214. -- home_fie includes home package and this module
  215. -- my_fies is just the ones from this module
  216. = do { traceTc "addLocalFamInst" (ppr fam_inst)
  217. ; isGHCi <- getIsGHCi
  218. -- In GHCi, we *override* any identical instances
  219. -- that are also defined in the interactive context
  220. ; let (home_fie', my_fis')
  221. | isGHCi = ( deleteFromFamInstEnv home_fie fam_inst
  222. , filterOut (identicalFamInst fam_inst) my_fis)
  223. | otherwise = (home_fie, my_fis)
  224. -- Load imported instances, so that we report
  225. -- overlaps correctly
  226. ; eps <- getEps
  227. ; let inst_envs = (eps_fam_inst_env eps, home_fie')
  228. home_fie'' = extendFamInstEnv home_fie fam_inst
  229. -- Check for conflicting instance decls
  230. ; no_conflict <- checkForConflicts inst_envs fam_inst
  231. ; if no_conflict then
  232. return (home_fie'', fam_inst : my_fis')
  233. else
  234. return (home_fie, my_fis) }
  235. \end{code}
  236. %************************************************************************
  237. %* *
  238. Checking an instance against conflicts with an instance env
  239. %* *
  240. %************************************************************************
  241. Check whether a single family instance conflicts with those in two instance
  242. environments (one for the EPS and one for the HPT).
  243. \begin{code}
  244. checkForConflicts :: FamInstEnvs -> FamInst -> TcM Bool
  245. checkForConflicts inst_envs fam_inst
  246. = do { -- To instantiate the family instance type, extend the instance
  247. -- envt with completely fresh template variables
  248. -- This is important because the template variables must
  249. -- not overlap with anything in the things being looked up
  250. -- (since we do unification).
  251. -- We use tcInstSkolType because we don't want to allocate
  252. -- fresh *meta* type variables.
  253. ; (_, skol_tvs) <- tcInstSkolTyVars (coAxiomTyVars (famInstAxiom fam_inst))
  254. ; let conflicts = lookupFamInstEnvConflicts inst_envs fam_inst skol_tvs
  255. no_conflicts = null conflicts
  256. ; traceTc "checkForConflicts" (ppr conflicts $$ ppr fam_inst $$ ppr inst_envs)
  257. ; unless no_conflicts $
  258. conflictInstErr fam_inst (fst (head conflicts))
  259. ; return no_conflicts }
  260. conflictInstErr :: FamInst -> FamInst -> TcRn ()
  261. conflictInstErr famInst conflictingFamInst
  262. = addFamInstsErr (ptext (sLit "Conflicting family instance declarations:"))
  263. [famInst, conflictingFamInst]
  264. addFamInstsErr :: SDoc -> [FamInst] -> TcRn ()
  265. addFamInstsErr herald insts
  266. = setSrcSpan (getSrcSpan (head sorted)) $
  267. addErr (hang herald 2 (pprFamInsts sorted))
  268. where
  269. sorted = sortWith getSrcLoc insts
  270. -- The sortWith just arranges that instances are dislayed in order
  271. -- of source location, which reduced wobbling in error messages,
  272. -- and is better for users
  273. tcGetFamInstEnvs :: TcM FamInstEnvs
  274. -- Gets both the external-package inst-env
  275. -- and the home-pkg inst env (includes module being compiled)
  276. tcGetFamInstEnvs
  277. = do { eps <- getEps; env <- getGblEnv
  278. ; return (eps_fam_inst_env eps, tcg_fam_inst_env env) }
  279. \end{code}