PageRenderTime 57ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/iface/TcIface.lhs

https://bitbucket.org/carter/ghc
Haskell | 1479 lines | 1095 code | 193 blank | 191 comment | 26 complexity | 7caacf5dee3188091a0f88171af43e64 MD5 | raw file
  1. %
  2. % (c) The University of Glasgow 2006
  3. % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
  4. %
  5. Type checking of type signatures in interface files
  6. \begin{code}
  7. module TcIface (
  8. tcImportDecl, importDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
  9. tcIfaceDecl, tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
  10. tcIfaceVectInfo, tcIfaceAnnotations, tcIfaceGlobal, tcExtCoreBindings
  11. ) where
  12. #include "HsVersions.h"
  13. import IfaceSyn
  14. import LoadIface
  15. import IfaceEnv
  16. import BuildTyCl
  17. import TcRnMonad
  18. import TcType
  19. import Type
  20. import Coercion
  21. import TypeRep
  22. import HscTypes
  23. import Annotations
  24. import InstEnv
  25. import FamInstEnv
  26. import CoreSyn
  27. import CoreUtils
  28. import CoreUnfold
  29. import CoreLint
  30. import WorkWrap
  31. import MkCore( castBottomExpr )
  32. import Id
  33. import MkId
  34. import IdInfo
  35. import Class
  36. import TyCon
  37. import DataCon
  38. import PrelNames
  39. import TysWiredIn
  40. import TysPrim ( superKindTyConName )
  41. import BasicTypes ( Arity, strongLoopBreaker )
  42. import Literal
  43. import qualified Var
  44. import VarEnv
  45. import VarSet
  46. import Name
  47. import NameEnv
  48. import NameSet
  49. import OccurAnal ( occurAnalyseExpr )
  50. import Demand ( isBottomingSig )
  51. import Module
  52. import UniqFM
  53. import UniqSupply
  54. import Outputable
  55. import ErrUtils
  56. import Maybes
  57. import SrcLoc
  58. import DynFlags
  59. import Util
  60. import FastString
  61. import Control.Monad
  62. \end{code}
  63. This module takes
  64. IfaceDecl -> TyThing
  65. IfaceType -> Type
  66. etc
  67. An IfaceDecl is populated with RdrNames, and these are not renamed to
  68. Names before typechecking, because there should be no scope errors etc.
  69. -- For (b) consider: f = \$(...h....)
  70. -- where h is imported, and calls f via an hi-boot file.
  71. -- This is bad! But it is not seen as a staging error, because h
  72. -- is indeed imported. We don't want the type-checker to black-hole
  73. -- when simplifying and compiling the splice!
  74. --
  75. -- Simple solution: discard any unfolding that mentions a variable
  76. -- bound in this module (and hence not yet processed).
  77. -- The discarding happens when forkM finds a type error.
  78. %************************************************************************
  79. %* *
  80. %* tcImportDecl is the key function for "faulting in" *
  81. %* imported things
  82. %* *
  83. %************************************************************************
  84. The main idea is this. We are chugging along type-checking source code, and
  85. find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
  86. it in the EPS type envt. So it
  87. 1 loads GHC.Base.hi
  88. 2 gets the decl for GHC.Base.map
  89. 3 typechecks it via tcIfaceDecl
  90. 4 and adds it to the type env in the EPS
  91. Note that DURING STEP 4, we may find that map's type mentions a type
  92. constructor that also
  93. Notice that for imported things we read the current version from the EPS
  94. mutable variable. This is important in situations like
  95. ...$(e1)...$(e2)...
  96. where the code that e1 expands to might import some defns that
  97. also turn out to be needed by the code that e2 expands to.
  98. \begin{code}
  99. tcImportDecl :: Name -> TcM TyThing
  100. -- Entry point for *source-code* uses of importDecl
  101. tcImportDecl name
  102. | Just thing <- wiredInNameTyThing_maybe name
  103. = do { when (needWiredInHomeIface thing)
  104. (initIfaceTcRn (loadWiredInHomeIface name))
  105. -- See Note [Loading instances for wired-in things]
  106. ; return thing }
  107. | otherwise
  108. = do { traceIf (text "tcImportDecl" <+> ppr name)
  109. ; mb_thing <- initIfaceTcRn (importDecl name)
  110. ; case mb_thing of
  111. Succeeded thing -> return thing
  112. Failed err -> failWithTc err }
  113. importDecl :: Name -> IfM lcl (MaybeErr MsgDoc TyThing)
  114. -- Get the TyThing for this Name from an interface file
  115. -- It's not a wired-in thing -- the caller caught that
  116. importDecl name
  117. = ASSERT( not (isWiredInName name) )
  118. do { traceIf nd_doc
  119. -- Load the interface, which should populate the PTE
  120. ; mb_iface <- ASSERT2( isExternalName name, ppr name )
  121. loadInterface nd_doc (nameModule name) ImportBySystem
  122. ; case mb_iface of {
  123. Failed err_msg -> return (Failed err_msg) ;
  124. Succeeded _ -> do
  125. -- Now look it up again; this time we should find it
  126. { eps <- getEps
  127. ; case lookupTypeEnv (eps_PTE eps) name of
  128. Just thing -> return (Succeeded thing)
  129. Nothing -> return (Failed not_found_msg)
  130. }}}
  131. where
  132. nd_doc = ptext (sLit "Need decl for") <+> ppr name
  133. not_found_msg = hang (ptext (sLit "Can't find interface-file declaration for") <+>
  134. pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
  135. 2 (vcat [ptext (sLit "Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
  136. ptext (sLit "Use -ddump-if-trace to get an idea of which file caused the error")])
  137. \end{code}
  138. %************************************************************************
  139. %* *
  140. Checks for wired-in things
  141. %* *
  142. %************************************************************************
  143. Note [Loading instances for wired-in things]
  144. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  145. We need to make sure that we have at least *read* the interface files
  146. for any module with an instance decl or RULE that we might want.
  147. * If the instance decl is an orphan, we have a whole separate mechanism
  148. (loadOprhanModules)
  149. * If the instance decl not an orphan, then the act of looking at the
  150. TyCon or Class will force in the defining module for the
  151. TyCon/Class, and hence the instance decl
  152. * BUT, if the TyCon is a wired-in TyCon, we don't really need its interface;
  153. but we must make sure we read its interface in case it has instances or
  154. rules. That is what LoadIface.loadWiredInHomeInterface does. It's called
  155. from TcIface.{tcImportDecl, checkWiredInTyCon, ifCheckWiredInThing}
  156. * HOWEVER, only do this for TyCons. There are no wired-in Classes. There
  157. are some wired-in Ids, but we don't want to load their interfaces. For
  158. example, Control.Exception.Base.recSelError is wired in, but that module
  159. is compiled late in the base library, and we don't want to force it to
  160. load before it's been compiled!
  161. All of this is done by the type checker. The renamer plays no role.
  162. (It used to, but no longer.)
  163. \begin{code}
  164. checkWiredInTyCon :: TyCon -> TcM ()
  165. -- Ensure that the home module of the TyCon (and hence its instances)
  166. -- are loaded. See Note [Loading instances for wired-in things]
  167. -- It might not be a wired-in tycon (see the calls in TcUnify),
  168. -- in which case this is a no-op.
  169. checkWiredInTyCon tc
  170. | not (isWiredInName tc_name)
  171. = return ()
  172. | otherwise
  173. = do { mod <- getModule
  174. ; ASSERT( isExternalName tc_name )
  175. when (mod /= nameModule tc_name)
  176. (initIfaceTcRn (loadWiredInHomeIface tc_name))
  177. -- Don't look for (non-existent) Float.hi when
  178. -- compiling Float.lhs, which mentions Float of course
  179. -- A bit yukky to call initIfaceTcRn here
  180. }
  181. where
  182. tc_name = tyConName tc
  183. ifCheckWiredInThing :: TyThing -> IfL ()
  184. -- Even though we are in an interface file, we want to make
  185. -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
  186. -- Ditto want to ensure that RULES are loaded too
  187. -- See Note [Loading instances for wired-in things]
  188. ifCheckWiredInThing thing
  189. = do { mod <- getIfModule
  190. -- Check whether we are typechecking the interface for this
  191. -- very module. E.g when compiling the base library in --make mode
  192. -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
  193. -- the HPT, so without the test we'll demand-load it into the PIT!
  194. -- C.f. the same test in checkWiredInTyCon above
  195. ; let name = getName thing
  196. ; ASSERT2( isExternalName name, ppr name )
  197. when (needWiredInHomeIface thing && mod /= nameModule name)
  198. (loadWiredInHomeIface name) }
  199. needWiredInHomeIface :: TyThing -> Bool
  200. -- Only for TyCons; see Note [Loading instances for wired-in things]
  201. needWiredInHomeIface (ATyCon {}) = True
  202. needWiredInHomeIface _ = False
  203. \end{code}
  204. %************************************************************************
  205. %* *
  206. Type-checking a complete interface
  207. %* *
  208. %************************************************************************
  209. Suppose we discover we don't need to recompile. Then we must type
  210. check the old interface file. This is a bit different to the
  211. incremental type checking we do as we suck in interface files. Instead
  212. we do things similarly as when we are typechecking source decls: we
  213. bring into scope the type envt for the interface all at once, using a
  214. knot. Remember, the decls aren't necessarily in dependency order --
  215. and even if they were, the type decls might be mutually recursive.
  216. \begin{code}
  217. typecheckIface :: ModIface -- Get the decls from here
  218. -> TcRnIf gbl lcl ModDetails
  219. typecheckIface iface
  220. = initIfaceTc iface $ \ tc_env_var -> do
  221. -- The tc_env_var is freshly allocated, private to
  222. -- type-checking this particular interface
  223. { -- Get the right set of decls and rules. If we are compiling without -O
  224. -- we discard pragmas before typechecking, so that we don't "see"
  225. -- information that we shouldn't. From a versioning point of view
  226. -- It's not actually *wrong* to do so, but in fact GHCi is unable
  227. -- to handle unboxed tuples, so it must not see unfoldings.
  228. ignore_prags <- doptM Opt_IgnoreInterfacePragmas
  229. -- Typecheck the decls. This is done lazily, so that the knot-tying
  230. -- within this single module work out right. In the If monad there is
  231. -- no global envt for the current interface; instead, the knot is tied
  232. -- through the if_rec_types field of IfGblEnv
  233. ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
  234. ; let type_env = mkNameEnv names_w_things
  235. ; writeMutVar tc_env_var type_env
  236. -- Now do those rules, instances and annotations
  237. ; insts <- mapM tcIfaceInst (mi_insts iface)
  238. ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
  239. ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
  240. ; anns <- tcIfaceAnnotations (mi_anns iface)
  241. -- Vectorisation information
  242. ; vect_info <- tcIfaceVectInfo (mi_module iface) type_env (mi_vect_info iface)
  243. -- Exports
  244. ; exports <- ifaceExportNames (mi_exports iface)
  245. -- Finished
  246. ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
  247. text "Type envt:" <+> ppr type_env])
  248. ; return $ ModDetails { md_types = type_env
  249. , md_insts = insts
  250. , md_fam_insts = fam_insts
  251. , md_rules = rules
  252. , md_anns = anns
  253. , md_vect_info = vect_info
  254. , md_exports = exports
  255. }
  256. }
  257. \end{code}
  258. %************************************************************************
  259. %* *
  260. Type and class declarations
  261. %* *
  262. %************************************************************************
  263. \begin{code}
  264. tcHiBootIface :: HscSource -> Module -> TcRn ModDetails
  265. -- Load the hi-boot iface for the module being compiled,
  266. -- if it indeed exists in the transitive closure of imports
  267. -- Return the ModDetails, empty if no hi-boot iface
  268. tcHiBootIface hsc_src mod
  269. | isHsBoot hsc_src -- Already compiling a hs-boot file
  270. = return emptyModDetails
  271. | otherwise
  272. = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
  273. ; mode <- getGhcMode
  274. ; if not (isOneShot mode)
  275. -- In --make and interactive mode, if this module has an hs-boot file
  276. -- we'll have compiled it already, and it'll be in the HPT
  277. --
  278. -- We check wheher the interface is a *boot* interface.
  279. -- It can happen (when using GHC from Visual Studio) that we
  280. -- compile a module in TypecheckOnly mode, with a stable,
  281. -- fully-populated HPT. In that case the boot interface isn't there
  282. -- (it's been replaced by the mother module) so we can't check it.
  283. -- And that's fine, because if M's ModInfo is in the HPT, then
  284. -- it's been compiled once, and we don't need to check the boot iface
  285. then do { hpt <- getHpt
  286. ; case lookupUFM hpt (moduleName mod) of
  287. Just info | mi_boot (hm_iface info)
  288. -> return (hm_details info)
  289. _ -> return emptyModDetails }
  290. else do
  291. -- OK, so we're in one-shot mode.
  292. -- In that case, we're read all the direct imports by now,
  293. -- so eps_is_boot will record if any of our imports mention us by
  294. -- way of hi-boot file
  295. { eps <- getEps
  296. ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
  297. Nothing -> return emptyModDetails ; -- The typical case
  298. Just (_, False) -> failWithTc moduleLoop ;
  299. -- Someone below us imported us!
  300. -- This is a loop with no hi-boot in the way
  301. Just (_mod, True) -> -- There's a hi-boot interface below us
  302. do { read_result <- findAndReadIface
  303. need mod
  304. True -- Hi-boot file
  305. ; case read_result of
  306. Failed err -> failWithTc (elaborate err)
  307. Succeeded (iface, _path) -> typecheckIface iface
  308. }}}}
  309. where
  310. need = ptext (sLit "Need the hi-boot interface for") <+> ppr mod
  311. <+> ptext (sLit "to compare against the Real Thing")
  312. moduleLoop = ptext (sLit "Circular imports: module") <+> quotes (ppr mod)
  313. <+> ptext (sLit "depends on itself")
  314. elaborate err = hang (ptext (sLit "Could not find hi-boot interface for") <+>
  315. quotes (ppr mod) <> colon) 4 err
  316. \end{code}
  317. %************************************************************************
  318. %* *
  319. Type and class declarations
  320. %* *
  321. %************************************************************************
  322. When typechecking a data type decl, we *lazily* (via forkM) typecheck
  323. the constructor argument types. This is in the hope that we may never
  324. poke on those argument types, and hence may never need to load the
  325. interface files for types mentioned in the arg types.
  326. E.g.
  327. data Foo.S = MkS Baz.T
  328. Mabye we can get away without even loading the interface for Baz!
  329. This is not just a performance thing. Suppose we have
  330. data Foo.S = MkS Baz.T
  331. data Baz.T = MkT Foo.S
  332. (in different interface files, of course).
  333. Now, first we load and typecheck Foo.S, and add it to the type envt.
  334. If we do explore MkS's argument, we'll load and typecheck Baz.T.
  335. If we explore MkT's argument we'll find Foo.S already in the envt.
  336. If we typechecked constructor args eagerly, when loading Foo.S we'd try to
  337. typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
  338. which isn't done yet.
  339. All very cunning. However, there is a rather subtle gotcha which bit
  340. me when developing this stuff. When we typecheck the decl for S, we
  341. extend the type envt with S, MkS, and all its implicit Ids. Suppose
  342. (a bug, but it happened) that the list of implicit Ids depended in
  343. turn on the constructor arg types. Then the following sequence of
  344. events takes place:
  345. * we build a thunk <t> for the constructor arg tys
  346. * we build a thunk for the extended type environment (depends on <t>)
  347. * we write the extended type envt into the global EPS mutvar
  348. Now we look something up in the type envt
  349. * that pulls on <t>
  350. * which reads the global type envt out of the global EPS mutvar
  351. * but that depends in turn on <t>
  352. It's subtle, because, it'd work fine if we typechecked the constructor args
  353. eagerly -- they don't need the extended type envt. They just get the extended
  354. type envt by accident, because they look at it later.
  355. What this means is that the implicitTyThings MUST NOT DEPEND on any of
  356. the forkM stuff.
  357. \begin{code}
  358. tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
  359. -> IfaceDecl
  360. -> IfL TyThing
  361. tcIfaceDecl = tc_iface_decl NoParentTyCon
  362. tc_iface_decl :: TyConParent -- For nested declarations
  363. -> Bool -- True <=> discard IdInfo on IfaceId bindings
  364. -> IfaceDecl
  365. -> IfL TyThing
  366. tc_iface_decl _ ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type,
  367. ifIdDetails = details, ifIdInfo = info})
  368. = do { name <- lookupIfaceTop occ_name
  369. ; ty <- tcIfaceType iface_type
  370. ; details <- tcIdDetails ty details
  371. ; info <- tcIdInfo ignore_prags name ty info
  372. ; return (AnId (mkGlobalId details name ty info)) }
  373. tc_iface_decl parent _ (IfaceData {ifName = occ_name,
  374. ifCType = cType,
  375. ifTyVars = tv_bndrs,
  376. ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
  377. ifCons = rdr_cons,
  378. ifRec = is_rec,
  379. ifAxiom = mb_axiom_name })
  380. = bindIfaceTyVars_AT tv_bndrs $ \ tyvars -> do
  381. { tc_name <- lookupIfaceTop occ_name
  382. ; tycon <- fixM $ \ tycon -> do
  383. { stupid_theta <- tcIfaceCtxt ctxt
  384. ; parent' <- tc_parent tyvars mb_axiom_name
  385. ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
  386. ; return (buildAlgTyCon tc_name tyvars cType stupid_theta
  387. cons is_rec gadt_syn parent') }
  388. ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
  389. ; return (ATyCon tycon) }
  390. where
  391. tc_parent :: [TyVar] -> Maybe Name -> IfL TyConParent
  392. tc_parent _ Nothing = return parent
  393. tc_parent tyvars (Just ax_name)
  394. = ASSERT( isNoParent parent )
  395. do { ax <- tcIfaceCoAxiom ax_name
  396. ; let (fam_tc, fam_tys) = coAxiomSplitLHS ax
  397. subst = zipTopTvSubst (coAxiomTyVars ax) (mkTyVarTys tyvars)
  398. -- The subst matches the tyvar of the TyCon
  399. -- with those from the CoAxiom. They aren't
  400. -- necessarily the same, since the two may be
  401. -- gotten from separate interface-file declarations
  402. ; return (FamInstTyCon ax fam_tc (substTys subst fam_tys)) }
  403. tc_iface_decl parent _ (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
  404. ifSynRhs = mb_rhs_ty,
  405. ifSynKind = kind })
  406. = bindIfaceTyVars_AT tv_bndrs $ \ tyvars -> do
  407. { tc_name <- lookupIfaceTop occ_name
  408. ; rhs_kind <- tcIfaceKind kind -- Note [Synonym kind loop]
  409. ; rhs <- forkM (mk_doc tc_name) $
  410. tc_syn_rhs mb_rhs_ty
  411. ; tycon <- buildSynTyCon tc_name tyvars rhs rhs_kind parent
  412. ; return (ATyCon tycon) }
  413. where
  414. mk_doc n = ptext (sLit "Type syonym") <+> ppr n
  415. tc_syn_rhs (SynFamilyTyCon a b) = return (SynFamilyTyCon a b)
  416. tc_syn_rhs (SynonymTyCon ty) = do { rhs_ty <- tcIfaceType ty
  417. ; return (SynonymTyCon rhs_ty) }
  418. tc_iface_decl _parent ignore_prags
  419. (IfaceClass {ifCtxt = rdr_ctxt, ifName = tc_occ,
  420. ifTyVars = tv_bndrs, ifFDs = rdr_fds,
  421. ifATs = rdr_ats, ifSigs = rdr_sigs,
  422. ifRec = tc_isrec })
  423. -- ToDo: in hs-boot files we should really treat abstract classes specially,
  424. -- as we do abstract tycons
  425. = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
  426. { tc_name <- lookupIfaceTop tc_occ
  427. ; traceIf (text "tc-iface-class1" <+> ppr tc_occ)
  428. ; ctxt <- mapM tc_sc rdr_ctxt
  429. ; traceIf (text "tc-iface-class2" <+> ppr tc_occ)
  430. ; sigs <- mapM tc_sig rdr_sigs
  431. ; fds <- mapM tc_fd rdr_fds
  432. ; traceIf (text "tc-iface-class3" <+> ppr tc_occ)
  433. ; cls <- fixM $ \ cls -> do
  434. { ats <- mapM (tc_at cls) rdr_ats
  435. ; traceIf (text "tc-iface-class4" <+> ppr tc_occ)
  436. ; buildClass ignore_prags tc_name tyvars ctxt fds ats sigs tc_isrec }
  437. ; return (ATyCon (classTyCon cls)) }
  438. where
  439. tc_sc pred = forkM (mk_sc_doc pred) (tcIfaceType pred)
  440. -- The *length* of the superclasses is used by buildClass, and hence must
  441. -- not be inside the thunk. But the *content* maybe recursive and hence
  442. -- must be lazy (via forkM). Example:
  443. -- class C (T a) => D a where
  444. -- data T a
  445. -- Here the associated type T is knot-tied with the class, and
  446. -- so we must not pull on T too eagerly. See Trac #5970
  447. mk_sc_doc pred = ptext (sLit "Superclass") <+> ppr pred
  448. tc_sig (IfaceClassOp occ dm rdr_ty)
  449. = do { op_name <- lookupIfaceTop occ
  450. ; op_ty <- forkM (mk_op_doc op_name rdr_ty) (tcIfaceType rdr_ty)
  451. -- Must be done lazily for just the same reason as the
  452. -- type of a data con; to avoid sucking in types that
  453. -- it mentions unless it's necessary to do so
  454. ; return (op_name, dm, op_ty) }
  455. tc_at cls (IfaceAT tc_decl defs_decls)
  456. = do ATyCon tc <- tc_iface_decl (AssocFamilyTyCon cls) ignore_prags tc_decl
  457. defs <- mapM tc_iface_at_def defs_decls
  458. return (tc, defs)
  459. tc_iface_at_def (IfaceATD tvs pat_tys ty) =
  460. bindIfaceTyVars_AT tvs $
  461. \tvs' -> liftM2 (\pats tys -> ATD tvs' pats tys noSrcSpan)
  462. (mapM tcIfaceType pat_tys) (tcIfaceType ty)
  463. mk_op_doc op_name op_ty = ptext (sLit "Class op") <+> sep [ppr op_name, ppr op_ty]
  464. tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
  465. ; tvs2' <- mapM tcIfaceTyVar tvs2
  466. ; return (tvs1', tvs2') }
  467. tc_iface_decl _ _ (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
  468. = do { name <- lookupIfaceTop rdr_name
  469. ; return (ATyCon (mkForeignTyCon name ext_name
  470. liftedTypeKind 0)) }
  471. tc_iface_decl _ _ (IfaceAxiom {ifName = tc_occ, ifTyVars = tv_bndrs,
  472. ifLHS = lhs, ifRHS = rhs })
  473. = bindIfaceTyVars tv_bndrs $ \ tvs -> do
  474. { tc_name <- lookupIfaceTop tc_occ
  475. ; tc_lhs <- tcIfaceType lhs
  476. ; tc_rhs <- tcIfaceType rhs
  477. ; let axiom = CoAxiom { co_ax_unique = nameUnique tc_name
  478. , co_ax_name = tc_name
  479. , co_ax_implicit = False
  480. , co_ax_tvs = tvs
  481. , co_ax_lhs = tc_lhs
  482. , co_ax_rhs = tc_rhs }
  483. ; return (ACoAxiom axiom) }
  484. tcIfaceDataCons :: Name -> TyCon -> [TyVar] -> IfaceConDecls -> IfL AlgTyConRhs
  485. tcIfaceDataCons tycon_name tycon _ if_cons
  486. = case if_cons of
  487. IfAbstractTyCon dis -> return (AbstractTyCon dis)
  488. IfDataFamTyCon -> return DataFamilyTyCon
  489. IfDataTyCon cons -> do { data_cons <- mapM tc_con_decl cons
  490. ; return (mkDataTyConRhs data_cons) }
  491. IfNewTyCon con -> do { data_con <- tc_con_decl con
  492. ; mkNewTyConRhs tycon_name tycon data_con }
  493. where
  494. tc_con_decl (IfCon { ifConInfix = is_infix,
  495. ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
  496. ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
  497. ifConArgTys = args, ifConFields = field_lbls,
  498. ifConStricts = stricts})
  499. = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
  500. bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
  501. { name <- lookupIfaceTop occ
  502. ; eq_spec <- tcIfaceEqSpec spec
  503. ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
  504. -- At one stage I thought that this context checking *had*
  505. -- to be lazy, because of possible mutual recursion between the
  506. -- type and the classe:
  507. -- E.g.
  508. -- class Real a where { toRat :: a -> Ratio Integer }
  509. -- data (Real a) => Ratio a = ...
  510. -- But now I think that the laziness in checking class ops breaks
  511. -- the loop, so no laziness needed
  512. -- Read the argument types, but lazily to avoid faulting in
  513. -- the component types unless they are really needed
  514. ; arg_tys <- forkM (mk_doc name) (mapM tcIfaceType args)
  515. ; lbl_names <- mapM lookupIfaceTop field_lbls
  516. -- Remember, tycon is the representation tycon
  517. ; let orig_res_ty = mkFamilyTyConApp tycon
  518. (substTyVars (mkTopTvSubst eq_spec) univ_tyvars)
  519. ; buildDataCon name is_infix
  520. stricts lbl_names
  521. univ_tyvars ex_tyvars
  522. eq_spec theta
  523. arg_tys orig_res_ty tycon
  524. }
  525. mk_doc con_name = ptext (sLit "Constructor") <+> ppr con_name
  526. tcIfaceEqSpec :: [(OccName, IfaceType)] -> IfL [(TyVar, Type)]
  527. tcIfaceEqSpec spec
  528. = mapM do_item spec
  529. where
  530. do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
  531. ; ty <- tcIfaceType if_ty
  532. ; return (tv,ty) }
  533. \end{code}
  534. Note [Synonym kind loop]
  535. ~~~~~~~~~~~~~~~~~~~~~~~~
  536. Notice that we eagerly grab the *kind* from the interface file, but
  537. build a forkM thunk for the *rhs* (and family stuff). To see why,
  538. consider this (Trac #2412)
  539. M.hs: module M where { import X; data T = MkT S }
  540. X.hs: module X where { import {-# SOURCE #-} M; type S = T }
  541. M.hs-boot: module M where { data T }
  542. When kind-checking M.hs we need S's kind. But we do not want to
  543. find S's kind from (typeKind S-rhs), because we don't want to look at
  544. S-rhs yet! Since S is imported from X.hi, S gets just one chance to
  545. be defined, and we must not do that until we've finished with M.T.
  546. Solution: record S's kind in the interface file; now we can safely
  547. look at it.
  548. %************************************************************************
  549. %* *
  550. Instances
  551. %* *
  552. %************************************************************************
  553. \begin{code}
  554. tcIfaceInst :: IfaceClsInst -> IfL ClsInst
  555. tcIfaceInst (IfaceClsInst { ifDFun = dfun_occ, ifOFlag = oflag
  556. , ifInstCls = cls, ifInstTys = mb_tcs })
  557. = do { dfun <- forkM (ptext (sLit "Dict fun") <+> ppr dfun_occ) $
  558. tcIfaceExtId dfun_occ
  559. ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
  560. ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
  561. tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
  562. tcIfaceFamInst (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
  563. , ifFamInstAxiom = axiom_name } )
  564. = do { axiom' <- forkM (ptext (sLit "Axiom") <+> ppr axiom_name) $
  565. tcIfaceCoAxiom axiom_name
  566. ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
  567. ; return (mkImportedFamInst fam mb_tcs' axiom') }
  568. \end{code}
  569. %************************************************************************
  570. %* *
  571. Rules
  572. %* *
  573. %************************************************************************
  574. We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
  575. are in the type environment. However, remember that typechecking a Rule may
  576. (as a side effect) augment the type envt, and so we may need to iterate the process.
  577. \begin{code}
  578. tcIfaceRules :: Bool -- True <=> ignore rules
  579. -> [IfaceRule]
  580. -> IfL [CoreRule]
  581. tcIfaceRules ignore_prags if_rules
  582. | ignore_prags = return []
  583. | otherwise = mapM tcIfaceRule if_rules
  584. tcIfaceRule :: IfaceRule -> IfL CoreRule
  585. tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
  586. ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
  587. ifRuleAuto = auto })
  588. = do { ~(bndrs', args', rhs') <-
  589. -- Typecheck the payload lazily, in the hope it'll never be looked at
  590. forkM (ptext (sLit "Rule") <+> ftext name) $
  591. bindIfaceBndrs bndrs $ \ bndrs' ->
  592. do { args' <- mapM tcIfaceExpr args
  593. ; rhs' <- tcIfaceExpr rhs
  594. ; return (bndrs', args', rhs') }
  595. ; let mb_tcs = map ifTopFreeName args
  596. ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
  597. ru_bndrs = bndrs', ru_args = args',
  598. ru_rhs = occurAnalyseExpr rhs',
  599. ru_rough = mb_tcs,
  600. ru_auto = auto,
  601. ru_local = False }) } -- An imported RULE is never for a local Id
  602. -- or, even if it is (module loop, perhaps)
  603. -- we'll just leave it in the non-local set
  604. where
  605. -- This function *must* mirror exactly what Rules.topFreeName does
  606. -- We could have stored the ru_rough field in the iface file
  607. -- but that would be redundant, I think.
  608. -- The only wrinkle is that we must not be deceived by
  609. -- type syononyms at the top of a type arg. Since
  610. -- we can't tell at this point, we are careful not
  611. -- to write them out in coreRuleToIfaceRule
  612. ifTopFreeName :: IfaceExpr -> Maybe Name
  613. ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
  614. ifTopFreeName (IfaceApp f _) = ifTopFreeName f
  615. ifTopFreeName (IfaceExt n) = Just n
  616. ifTopFreeName _ = Nothing
  617. \end{code}
  618. %************************************************************************
  619. %* *
  620. Annotations
  621. %* *
  622. %************************************************************************
  623. \begin{code}
  624. tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
  625. tcIfaceAnnotations = mapM tcIfaceAnnotation
  626. tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
  627. tcIfaceAnnotation (IfaceAnnotation target serialized) = do
  628. target' <- tcIfaceAnnTarget target
  629. return $ Annotation {
  630. ann_target = target',
  631. ann_value = serialized
  632. }
  633. tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
  634. tcIfaceAnnTarget (NamedTarget occ) = do
  635. name <- lookupIfaceTop occ
  636. return $ NamedTarget name
  637. tcIfaceAnnTarget (ModuleTarget mod) = do
  638. return $ ModuleTarget mod
  639. \end{code}
  640. %************************************************************************
  641. %* *
  642. Vectorisation information
  643. %* *
  644. %************************************************************************
  645. \begin{code}
  646. -- We need access to the type environment as we need to look up information about type constructors
  647. -- (i.e., their data constructors and whether they are class type constructors). If a vectorised
  648. -- type constructor or class is defined in the same module as where it is vectorised, we cannot
  649. -- look that information up from the type constructor that we obtained via a 'forkM'ed
  650. -- 'tcIfaceTyCon' without recursively loading the interface that we are already type checking again
  651. -- and again and again...
  652. --
  653. tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
  654. tcIfaceVectInfo mod typeEnv (IfaceVectInfo
  655. { ifaceVectInfoVar = vars
  656. , ifaceVectInfoTyCon = tycons
  657. , ifaceVectInfoTyConReuse = tyconsReuse
  658. , ifaceVectInfoScalarVars = scalarVars
  659. , ifaceVectInfoScalarTyCons = scalarTyCons
  660. })
  661. = do { let scalarTyConsSet = mkNameSet scalarTyCons
  662. ; vVars <- mapM vectVarMapping vars
  663. ; let varsSet = mkVarSet (map fst vVars)
  664. ; tyConRes1 <- mapM (vectTyConVectMapping varsSet) tycons
  665. ; tyConRes2 <- mapM (vectTyConReuseMapping varsSet) tyconsReuse
  666. ; vScalarVars <- mapM vectVar scalarVars
  667. ; let (vTyCons, vDataCons, vScSels) = unzip3 (tyConRes1 ++ tyConRes2)
  668. ; return $ VectInfo
  669. { vectInfoVar = mkVarEnv vVars `extendVarEnvList` concat vScSels
  670. , vectInfoTyCon = mkNameEnv vTyCons
  671. , vectInfoDataCon = mkNameEnv (concat vDataCons)
  672. , vectInfoScalarVars = mkVarSet vScalarVars
  673. , vectInfoScalarTyCons = scalarTyConsSet
  674. }
  675. }
  676. where
  677. vectVarMapping name
  678. = do { vName <- lookupOrig mod (mkLocalisedOccName mod mkVectOcc name)
  679. ; var <- forkM (ptext (sLit "vect var") <+> ppr name) $
  680. tcIfaceExtId name
  681. ; vVar <- forkM (ptext (sLit "vect vVar [mod =") <+>
  682. ppr mod <> ptext (sLit "; nameModule =") <+>
  683. ppr (nameModule name) <> ptext (sLit "]") <+> ppr vName) $
  684. tcIfaceExtId vName
  685. ; return (var, (var, vVar))
  686. }
  687. -- where
  688. -- lookupLocalOrExternalId name
  689. -- = do { let mb_id = lookupTypeEnv typeEnv name
  690. -- ; case mb_id of
  691. -- -- id is local
  692. -- Just (AnId id) -> return id
  693. -- -- name is not an Id => internal inconsistency
  694. -- Just _ -> notAnIdErr
  695. -- -- Id is external
  696. -- Nothing -> tcIfaceExtId name
  697. -- }
  698. --
  699. -- notAnIdErr = pprPanic "TcIface.tcIfaceVectInfo: not an id" (ppr name)
  700. vectVar name
  701. = forkM (ptext (sLit "vect scalar var") <+> ppr name) $
  702. tcIfaceExtId name
  703. vectTyConVectMapping vars name
  704. = do { vName <- lookupOrig mod (mkLocalisedOccName mod mkVectTyConOcc name)
  705. ; vectTyConMapping vars name vName
  706. }
  707. vectTyConReuseMapping vars name
  708. = vectTyConMapping vars name name
  709. vectTyConMapping vars name vName
  710. = do { tycon <- lookupLocalOrExternalTyCon name
  711. ; vTycon <- forkM (ptext (sLit "vTycon of") <+> ppr vName) $
  712. lookupLocalOrExternalTyCon vName
  713. -- Map the data constructors of the original type constructor to those of the
  714. -- vectorised type constructor /unless/ the type constructor was vectorised
  715. -- abstractly; if it was vectorised abstractly, the workers of its data constructors
  716. -- do not appear in the set of vectorised variables.
  717. --
  718. -- NB: This is lazy! We don't pull at the type constructors before we actually use
  719. -- the data constructor mapping.
  720. ; let isAbstract | isClassTyCon tycon = False
  721. | datacon:_ <- tyConDataCons tycon
  722. = not $ dataConWrapId datacon `elemVarSet` vars
  723. | otherwise = True
  724. vDataCons | isAbstract = []
  725. | otherwise = [ (dataConName datacon, (datacon, vDatacon))
  726. | (datacon, vDatacon) <- zip (tyConDataCons tycon)
  727. (tyConDataCons vTycon)
  728. ]
  729. -- Map the (implicit) superclass and methods selectors as they don't occur in
  730. -- the var map.
  731. vScSels | Just cls <- tyConClass_maybe tycon
  732. , Just vCls <- tyConClass_maybe vTycon
  733. = [ (sel, (sel, vSel))
  734. | (sel, vSel) <- zip (classAllSelIds cls) (classAllSelIds vCls)
  735. ]
  736. | otherwise
  737. = []
  738. ; return ( (name, (tycon, vTycon)) -- (T, T_v)
  739. , vDataCons -- list of (Ci, Ci_v)
  740. , vScSels -- list of (seli, seli_v)
  741. )
  742. }
  743. where
  744. -- we need a fully defined version of the type constructor to be able to extract
  745. -- its data constructors etc.
  746. lookupLocalOrExternalTyCon name
  747. = do { let mb_tycon = lookupTypeEnv typeEnv name
  748. ; case mb_tycon of
  749. -- tycon is local
  750. Just (ATyCon tycon) -> return tycon
  751. -- name is not a tycon => internal inconsistency
  752. Just _ -> notATyConErr
  753. -- tycon is external
  754. Nothing -> tcIfaceTyCon (IfaceTc name)
  755. }
  756. notATyConErr = pprPanic "TcIface.tcIfaceVectInfo: not a tycon" (ppr name)
  757. \end{code}
  758. %************************************************************************
  759. %* *
  760. Types
  761. %* *
  762. %************************************************************************
  763. \begin{code}
  764. tcIfaceType :: IfaceType -> IfL Type
  765. tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
  766. tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
  767. tcIfaceType (IfaceLitTy l) = do { l1 <- tcIfaceTyLit l; return (LitTy l1) }
  768. tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
  769. tcIfaceType (IfaceTyConApp tc tks) = do { tc' <- tcIfaceTyCon tc
  770. ; tks' <- tcIfaceTcArgs (tyConKind tc') tks
  771. ; return (mkTyConApp tc' tks') }
  772. tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
  773. tcIfaceType t@(IfaceCoConApp {}) = pprPanic "tcIfaceType" (ppr t)
  774. tcIfaceTypes :: [IfaceType] -> IfL [Type]
  775. tcIfaceTypes tys = mapM tcIfaceType tys
  776. tcIfaceTcArgs :: Kind -> [IfaceType] -> IfL [Type]
  777. tcIfaceTcArgs _ []
  778. = return []
  779. tcIfaceTcArgs kind (tk:tks)
  780. = case splitForAllTy_maybe kind of
  781. Nothing -> tcIfaceTypes (tk:tks)
  782. Just (_, kind') -> do { k' <- tcIfaceKind tk
  783. ; tks' <- tcIfaceTcArgs kind' tks
  784. ; return (k':tks') }
  785. -----------------------------------------
  786. tcIfaceCtxt :: IfaceContext -> IfL ThetaType
  787. tcIfaceCtxt sts = mapM tcIfaceType sts
  788. -----------------------------------------
  789. tcIfaceTyLit :: IfaceTyLit -> IfL TyLit
  790. tcIfaceTyLit (IfaceNumTyLit n) = return (NumTyLit n)
  791. tcIfaceTyLit (IfaceStrTyLit n) = return (StrTyLit n)
  792. -----------------------------------------
  793. tcIfaceKind :: IfaceKind -> IfL Kind -- See Note [Checking IfaceTypes vs IfaceKinds]
  794. tcIfaceKind (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
  795. tcIfaceKind (IfaceAppTy t1 t2) = do { t1' <- tcIfaceKind t1; t2' <- tcIfaceKind t2; return (AppTy t1' t2') }
  796. tcIfaceKind (IfaceFunTy t1 t2) = do { t1' <- tcIfaceKind t1; t2' <- tcIfaceKind t2; return (FunTy t1' t2') }
  797. tcIfaceKind (IfaceTyConApp tc ts) = do { tc' <- tcIfaceKindCon tc; ts' <- tcIfaceKinds ts; return (mkTyConApp tc' ts') }
  798. tcIfaceKind (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceKind t; return (ForAllTy tv' t') }
  799. tcIfaceKind t = pprPanic "tcIfaceKind" (ppr t) -- IfaceCoApp, IfaceLitTy
  800. tcIfaceKinds :: [IfaceKind] -> IfL [Kind]
  801. tcIfaceKinds tys = mapM tcIfaceKind tys
  802. \end{code}
  803. Note [Checking IfaceTypes vs IfaceKinds]
  804. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  805. We need to know whether we are checking a *type* or a *kind*.
  806. Consider module M where
  807. Proxy :: forall k. k -> *
  808. data T = T
  809. and consider the two IfaceTypes
  810. M.Proxy * M.T{tc}
  811. M.Proxy 'M.T{tc} 'M.T(d}
  812. The first is conventional, but in the latter we use the promoted
  813. type constructor (as a kind) and data constructor (as a type). However,
  814. the Name of the promoted type constructor is just M.T; it's the *same name*
  815. as the ordinary type constructor.
  816. We could add a "promoted" flag to an IfaceTyCon, but that's a bit heavy.
  817. Instead we use context to distinguish, as in the source language.
  818. - When checking a kind, we look up M.T{tc} and promote it
  819. - When checking a type, we look up M.T{tc} and don't promote it
  820. and M.T{d} and promote it
  821. See tcIfaceKindCon and tcIfaceKTyCon respectively
  822. This context business is why we need tcIfaceTcArgs.
  823. %************************************************************************
  824. %* *
  825. Coercions
  826. %* *
  827. %************************************************************************
  828. \begin{code}
  829. tcIfaceCo :: IfaceType -> IfL Coercion
  830. tcIfaceCo (IfaceTyVar n) = mkCoVarCo <$> tcIfaceCoVar n
  831. tcIfaceCo (IfaceAppTy t1 t2) = mkAppCo <$> tcIfaceCo t1 <*> tcIfaceCo t2
  832. tcIfaceCo (IfaceFunTy t1 t2) = mkFunCo <$> tcIfaceCo t1 <*> tcIfaceCo t2
  833. tcIfaceCo (IfaceTyConApp tc ts) = mkTyConAppCo <$> tcIfaceTyCon tc <*> mapM tcIfaceCo ts
  834. tcIfaceCo t@(IfaceLitTy _) = mkReflCo <$> tcIfaceType t
  835. tcIfaceCo (IfaceCoConApp tc ts) = tcIfaceCoApp tc ts
  836. tcIfaceCo (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' ->
  837. mkForAllCo tv' <$> tcIfaceCo t
  838. tcIfaceCoApp :: IfaceCoCon -> [IfaceType] -> IfL Coercion
  839. tcIfaceCoApp IfaceReflCo [t] = Refl <$> tcIfaceType t
  840. tcIfaceCoApp (IfaceCoAx n) ts = AxiomInstCo <$> tcIfaceCoAxiom n <*> mapM tcIfaceCo ts
  841. tcIfaceCoApp IfaceUnsafeCo [t1,t2] = UnsafeCo <$> tcIfaceType t1 <*> tcIfaceType t2
  842. tcIfaceCoApp IfaceSymCo [t] = SymCo <$> tcIfaceCo t
  843. tcIfaceCoApp IfaceTransCo [t1,t2] = TransCo <$> tcIfaceCo t1 <*> tcIfaceCo t2
  844. tcIfaceCoApp IfaceInstCo [t1,t2] = InstCo <$> tcIfaceCo t1 <*> tcIfaceType t2
  845. tcIfaceCoApp (IfaceNthCo d) [t] = NthCo d <$> tcIfaceCo t
  846. tcIfaceCoApp (IfaceLRCo lr) [t] = LRCo lr <$> tcIfaceCo t
  847. tcIfaceCoApp cc ts = pprPanic "toIfaceCoApp" (ppr cc <+> ppr ts)
  848. tcIfaceCoVar :: FastString -> IfL CoVar
  849. tcIfaceCoVar = tcIfaceLclId
  850. \end{code}
  851. %************************************************************************
  852. %* *
  853. Core
  854. %* *
  855. %************************************************************************
  856. \begin{code}
  857. tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
  858. tcIfaceExpr (IfaceType ty)
  859. = Type <$> tcIfaceType ty
  860. tcIfaceExpr (IfaceCo co)
  861. = Coercion <$> tcIfaceCo co
  862. tcIfaceExpr (IfaceCast expr co)
  863. = Cast <$> tcIfaceExpr expr <*> tcIfaceCo co
  864. tcIfaceExpr (IfaceLcl name)
  865. = Var <$> tcIfaceLclId name
  866. tcIfaceExpr (IfaceExt gbl)
  867. = Var <$> tcIfaceExtId gbl
  868. tcIfaceExpr (IfaceLit lit)
  869. = do lit' <- tcIfaceLit lit
  870. return (Lit lit')
  871. tcIfaceExpr (IfaceFCall cc ty) = do
  872. ty' <- tcIfaceType ty
  873. u <- newUnique
  874. dflags <- getDynFlags
  875. return (Var (mkFCallId dflags u cc ty'))
  876. tcIfaceExpr (IfaceTuple boxity args) = do
  877. args' <- mapM tcIfaceExpr args
  878. -- Put the missing type arguments back in
  879. let con_args = map (Type . exprType) args' ++ args'
  880. return (mkApps (Var con_id) con_args)
  881. where
  882. arity = length args
  883. con_id = dataConWorkId (tupleCon boxity arity)
  884. tcIfaceExpr (IfaceLam bndr body)
  885. = bindIfaceBndr bndr $ \bndr' ->
  886. Lam bndr' <$> tcIfaceExpr body
  887. tcIfaceExpr (IfaceApp fun arg)
  888. = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
  889. tcIfaceExpr (IfaceECase scrut ty)
  890. = do { scrut' <- tcIfaceExpr scrut
  891. ; ty' <- tcIfaceType ty
  892. ; return (castBottomExpr scrut' ty') }
  893. tcIfaceExpr (IfaceCase scrut case_bndr alts) = do
  894. scrut' <- tcIfaceExpr scrut
  895. case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
  896. let
  897. scrut_ty = exprType scrut'
  898. case_bndr' = mkLocalId case_bndr_name scrut_ty
  899. tc_app = splitTyConApp scrut_ty
  900. -- NB: Won't always succeed (polymoprhic case)
  901. -- but won't be demanded in those cases
  902. -- NB: not tcSplitTyConApp; we are looking at Core here
  903. -- look through non-rec newtypes to find the tycon that
  904. -- corresponds to the datacon in this case alternative
  905. extendIfaceIdEnv [case_bndr'] $ do
  906. alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
  907. return (Case scrut' case_bndr' (coreAltsType alts') alts')
  908. tcIfaceExpr (IfaceLet (IfaceNonRec (IfLetBndr fs ty info) rhs) body)
  909. = do { name <- newIfaceName (mkVarOccFS fs)
  910. ; ty' <- tcIfaceType ty
  911. ; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
  912. name ty' info
  913. ; let id = mkLocalIdWithInfo name ty' id_info
  914. ; rhs' <- tcIfaceExpr rhs
  915. ; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
  916. ; return (Let (NonRec id rhs') body') }
  917. tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
  918. = do { ids <- mapM tc_rec_bndr (map fst pairs)
  919. ; extendIfaceIdEnv ids $ do
  920. { pairs' <- zipWithM tc_pair pairs ids
  921. ; body' <- tcIfaceExpr body
  922. ; return (Let (Rec pairs') body') } }
  923. where
  924. tc_rec_bndr (IfLetBndr fs ty _)
  925. = do { name <- newIfaceName (mkVarOccFS fs)
  926. ; ty' <- tcIfaceType ty
  927. ; return (mkLocalId name ty') }
  928. tc_pair (IfLetBndr _ _ info, rhs) id
  929. = do { rhs' <- tcIfaceExpr rhs
  930. ; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
  931. (idName id) (idType id) info
  932. ; return (setIdInfo id id_info, rhs') }
  933. tcIfaceExpr (IfaceTick tickish expr) = do
  934. expr' <- tcIfaceExpr expr
  935. tickish' <- tcIfaceTickish tickish
  936. return (Tick tickish' expr')
  937. -------------------------
  938. tcIfaceTickish :: IfaceTickish -> IfM lcl (Tickish Id)
  939. tcIfaceTickish (IfaceHpcTick modl ix) = return (HpcTick modl ix)
  940. tcIfaceTickish (IfaceSCC cc tick push) = return (ProfNote cc tick push)
  941. -------------------------
  942. tcIfaceLit :: Literal -> IfL Literal
  943. -- Integer literals deserialise to (LitInteger i <error thunk>)
  944. -- so tcIfaceLit just fills in the type.
  945. -- See Note [Integer literals] in Literal
  946. tcIfaceLit (LitInteger i _)
  947. = do t <- tcIfaceTyCon (IfaceTc integerTyConName)
  948. return (mkLitInteger i (mkTyConTy t))
  949. tcIfaceLit lit = return lit
  950. -------------------------
  951. tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
  952. -> (IfaceConAlt, [FastString], IfaceExpr)
  953. -> IfL (AltCon, [TyVar], CoreExpr)
  954. tcIfaceAlt _ _ (IfaceDefault, names, rhs)
  955. = ASSERT( null names ) do
  956. rhs' <- tcIfaceExpr rhs
  957. return (DEFAULT, [], rhs')
  958. tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
  959. = ASSERT( null names ) do
  960. lit' <- tcIfaceLit lit
  961. rhs' <- tcIfaceExpr rhs
  962. return (LitAlt lit', [], rhs')
  963. -- A case alternative is made quite a bit more complicated
  964. -- by the fact that we omit type annotations because we can
  965. -- work them out. True enough, but its not that easy!
  966. tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
  967. = do { con <- tcIfaceDataCon data_occ
  968. ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
  969. (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
  970. ; tcIfaceDataAlt con inst_tys arg_strs rhs }
  971. tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
  972. -> IfL (AltCon, [TyVar], CoreExpr)
  973. tcIfaceDataAlt con inst_tys arg_strs rhs
  974. = do { us <- newUniqueSupply
  975. ; let uniqs = uniqsFromSupply us
  976. ; let (ex_tvs, arg_ids)
  977. = dataConRepFSInstPat arg_strs uniqs con inst_tys
  978. ; rhs' <- extendIfaceTyVarEnv ex_tvs $
  979. extendIfaceIdEnv arg_ids $
  980. tcIfaceExpr rhs
  981. ; return (DataAlt con, ex_tvs ++ arg_ids, rhs') }
  982. \end{code}
  983. \begin{code}
  984. tcExtCoreBindings :: [IfaceBinding] -> IfL CoreProgram -- Used for external core
  985. tcExtCoreBindings [] = return []
  986. tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
  987. do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
  988. do_one (IfaceNonRec bndr rhs) thing_inside
  989. = do { rhs' <- tcIfaceExpr rhs
  990. ; bndr' <- newExtCoreBndr bndr
  991. ; extendIfaceIdEnv [bndr'] $ do
  992. { core_binds <- thing_inside
  993. ; return (NonRec bndr' rhs' : core_binds) }}
  994. do_one (IfaceRec pairs) thing_inside
  995. = do { bndrs' <- mapM newExtCoreBndr bndrs
  996. ; extendIfaceIdEnv bndrs' $ do
  997. { rhss' <- mapM tcIfaceExpr rhss
  998. ; core_binds <- thing_inside
  999. ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
  1000. where
  1001. (bndrs,rhss) = unzip pairs
  1002. \end{code}
  1003. %************************************************************************
  1004. %* *
  1005. IdInfo
  1006. %* *
  1007. %************************************************************************
  1008. \begin{code}
  1009. tcIdDetails :: Type -> IfaceIdDetails -> IfL IdDetails
  1010. tcIdDetails _ IfVanillaId = return VanillaId
  1011. tcIdDetails ty (IfDFunId ns)
  1012. = return (DFunId ns (isNewTyCon (classTyCon cls)))
  1013. where
  1014. (_, _, cls, _) = tcSplitDFunTy ty
  1015. tcIdDetails _ (IfRecSelId tc naughty)
  1016. = do { tc' <- tcIfaceTyCon tc
  1017. ; return (RecSelId { sel_tycon = tc', sel_naughty = naughty }) }
  1018. tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
  1019. tcIdInfo ignore_prags name ty info
  1020. | ignore_prags = return vanillaIdInfo
  1021. | otherwise = case info of
  1022. NoInfo -> return vanillaIdInfo
  1023. HasInfo info -> foldlM tcPrag init_info info
  1024. where
  1025. -- Set the CgInfo to something sensible but uninformative before
  1026. -- we start; default assumption is that it has CAFs
  1027. init_info = vanillaIdInfo
  1028. tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
  1029. tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
  1030. tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
  1031. tcPrag info (HsStrictness str) = return (info `setStrictnessInfo` Just str)
  1032. tcPrag info (HsInline prag) = return (info `setInlinePragInfo` prag)
  1033. -- The next two are lazy, so they don't transitively suck stuff in
  1034. tcPrag info (HsUnfold lb if_unf)
  1035. = do { unf <- tcUnfolding name ty info if_unf
  1036. ; let info1 | lb = info `setOccInfo` strongLoopBreaker
  1037. | otherwise = info
  1038. ; return (info1 `setUnfoldingInfoLazily` unf) }
  1039. \end{code}
  1040. \begin{code}
  1041. tcUnfolding :: Name -> Type -> IdInfo -> IfaceUnfolding -> IfL Unfolding
  1042. tcUnfolding name _ info (IfCoreUnfold stable if_expr)
  1043. = do { dflags <- getDynFlags
  1044. ; mb_expr <- tcPragExpr name if_expr
  1045. ; let unf_src = if stable then InlineStable else InlineRhs
  1046. ; return (case mb_expr of
  1047. Nothing -> NoUnfolding
  1048. Just expr -> mkUnfolding dflags unf_src
  1049. True {- Top level -}
  1050. is_bottoming expr) }
  1051. where
  1052. -- Strictness should occur before unfolding!
  1053. is_bottoming = case strictnessInfo info of
  1054. Just sig -> isBottomingSig sig
  1055. Nothing -> False
  1056. tcUnfolding name _ _ (IfCompulsory if_expr)
  1057. = do { mb_expr <- tcPragExpr name if_expr
  1058. ; return (case mb_expr of
  1059. Nothing -> NoUnfolding
  1060. Just expr -> mkCompulsoryUnfolding expr) }
  1061. tcUnfolding name _ _ (IfInlineRule arity unsat_ok boring_ok if_expr)
  1062. = do { mb_expr <- tcPragExpr name if_expr
  1063. ; return (case mb_expr of
  1064. Nothing -> NoUnfolding
  1065. Just expr -> mkCoreUnfolding InlineStable True expr arity
  1066. (UnfWhen unsat_ok boring_ok))
  1067. }
  1068. tcUnfolding name dfun_ty _ (IfDFunUnfold ops)
  1069. = do { mb_ops1 <- forkM_maybe doc $ mapM tc_arg ops
  1070. ; return (case mb_ops1 of
  1071. Nothing -> noUnfolding
  1072. Just ops1 -> mkDFunUnfolding dfun_ty ops1) }
  1073. where
  1074. doc = text "Class ops for dfun" <+> ppr name
  1075. tc_arg (DFunPolyArg e) = do { e' <- tcIfaceExpr e; return (DFunPolyArg e') }
  1076. tc_arg (DFunLamArg i) = return (DFunLamArg i)
  1077. tcUnfolding name ty info (IfExtWrapper arity wkr)
  1078. = tcIfaceWrapper name ty info arity (tcIfaceExtId wkr)
  1079. tcUnfolding name ty info (IfLclWrapper arity wkr)
  1080. = tcIfaceWrapper name ty info arity (tcIfaceLclId wkr)
  1081. -------------
  1082. tcIfaceWrapper :: Name -> Type -> IdInfo -> Arity -> IfL Id -> IfL Unfolding
  1083. tcIfaceWrapper name ty info arity get_worker
  1084. = do { mb_wkr_id <- forkM_maybe doc get_worker
  1085. ; us <- newUniqueSupply
  1086. ; dflags <- getDynFlags
  1087. ; return (case mb_wkr_id of
  1088. Nothing -> noUnfolding
  1089. Just wkr_id -> make_inline_rule dflags wkr_id us) }
  1090. where
  1091. doc = text "Worker for" <+> ppr name
  1092. make_inline_rule dflags wkr_id us
  1093. = mkWwInlineRule wkr_id
  1094. (initUs_ us (mkWrapper dflags ty strict_sig) wkr_id)
  1095. arity
  1096. -- Again we rely here on strictness info always appearing
  1097. -- before unfolding
  1098. strict_sig = case strictnessInfo info of
  1099. Just sig -> sig
  1100. Nothing -> pprPanic "Worker info but no strictness for" (ppr name)
  1101. \end{code}
  1102. For unfoldings we try to do the job lazily, so that we never type check
  1103. an unfolding that isn't going to be looked at.
  1104. \begin{code}
  1105. tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
  1106. tcPragExpr name expr
  1107. = forkM_maybe doc $ do
  1108. core_expr' <- tcIfaceExpr expr
  1109. -- Check for type consistency in the unfolding
  1110. ifDOptM Opt_DoCoreLinting $ do
  1111. in_scope <- get_in_scope
  1112. case lintUnfolding noSrcLoc in_scope core_expr' of
  1113. Nothing -> return ()
  1114. Just fail_msg -> do { mod <- getIfModule
  1115. ; pprPanic "Iface Lint failure"
  1116. (vcat [ ptext (sLit "In interface for") <+> ppr mod
  1117. , hang doc 2 fail_msg
  1118. , ppr name <+> equals <+> ppr core_expr'
  1119. , ptext (sLit "Iface expr =") <+> ppr expr ]) }
  1120. return core_expr'
  1121. where
  1122. doc = text "Unfolding of" <+> ppr name
  1123. get_in_scope :: IfL [Var] -- Totally disgusting; but just for linting
  1124. get_in_scope
  1125. = do { (gbl_env, lcl_env) <- getEnvs
  1126. ; rec_ids <- case if_rec_types gbl_env of
  1127. Nothing -> return []
  1128. Just (_, get_env) -> do
  1129. { type_env <- setLclEnv () get_env
  1130. ; return (typeEnvIds type_env) }
  1131. ; return (varEnvElts (if_tv_env lcl_env) ++
  1132. varEnvElts (if_id_env lcl_env) ++
  1133. rec_ids) }
  1134. \end{code}
  1135. %************************************************************************
  1136. %* *
  1137. Getting from Names to TyThings
  1138. %* *
  1139. %************************************************************************
  1140. \begin{code}
  1141. tcIfaceGlobal :: Name -> IfL TyThing
  1142. tcIfaceGlobal name
  1143. | Just thing <- wiredInNameTyThing_maybe name
  1144. -- Wired-in things include TyCons, DataCons, and Ids
  1145. -- Even though we are in an interface file, we want to make
  1146. -- sure the instances and RULES of this thing (particularly TyCon) are loaded
  1147. -- Imagine: f :: Double -> Double
  1148. = do { ifCheckWiredInThing thing; return thing }
  1149. | otherwise
  1150. = do { env <- getGblEnv
  1151. ; case if_rec_types env of { -- Note [Tying the knot]
  1152. Just (mod, get_type_env)
  1153. | nameIsLocalOrFrom mod name
  1154. -> do -- It's defined in the module being compiled
  1155. { type_env <- setLclEnv () get_type_env -- yuk
  1156. ; case lookupNameEnv type_env name of
  1157. Just thing -> return thing
  1158. Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
  1159. (ppr name $$ ppr type_env) }
  1160. ; _ -> do
  1161. { hsc_env <- getTopEnv
  1162. ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
  1163. ; case mb_thing of {
  1164. Just thing -> return thing ;
  1165. Nothing -> do
  1166. { mb_thing <- importDecl name -- It's imported; go get it
  1167. ; case mb_thing of
  1168. Failed err -> failIfM err
  1169. Succeeded thing -> return thing
  1170. }}}}}
  1171. -- Note [Tying the knot]
  1172. -- ~~~~~~~~~~~~~~~~~~~~~
  1173. -- The if_rec_types field is used in two situations:
  1174. --
  1175. -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
  1176. -- Then we look up M.T in M's type environment, which is splatted into if_rec_types
  1177. -- after we've built M's type envt.
  1178. --
  1179. -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
  1180. -- is up to date. So we call typecheckIface on M.hi. This splats M.T into
  1181. -- if_rec_types so that the (lazily typechecked) decls see all the other decls
  1182. --
  1183. -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
  1184. -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
  1185. -- emasculated form (e.g. lacking data constructors).
  1186. tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
  1187. tcIfaceTyCon (IfaceTc name)
  1188. = do { thing <- tcIfaceGlobal name
  1189. ; case thing of -- A "type constructor" can be a promoted data constructor
  1190. -- c.f. Trac #5881
  1191. ATyCon tc -> return tc
  1192. ADataCon dc -> return (buildPromotedDataCon dc)
  1193. _ -> pprPanic "tcIfaceTyCon" (ppr name $$ ppr thing) }
  1194. tcIfaceKindCon :: IfaceTyCon -> IfL TyCon
  1195. tcIfaceKindCon (IfaceTc name)
  1196. = do { thing <- tcIfaceGlobal name
  1197. ; case thing of -- A "type constructor" here is a promoted type constructor
  1198. -- c.f. Trac #5881
  1199. ATyCon tc
  1200. | isSuperKind (tyConKind tc) -> return tc -- Mainly just '*' or 'AnyK'
  1201. | otherwise -> return (buildPromotedTyCon tc)
  1202. _ -> pprPanic "tcIfaceKindCon" (ppr name $$ ppr thing) }
  1203. tcIfaceCoAxiom :: Name -> IfL CoAxiom
  1204. tcIfaceCoAxiom name = do { thing <- tcIfaceGlobal name
  1205. ; return (tyThingCoAxiom thing) }
  1206. tcIfaceDataCon :: Name -> IfL DataCon
  1207. tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
  1208. ; case thing of
  1209. ADataCon dc -> return dc
  1210. _ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
  1211. tcIfaceExtId :: Name -> IfL Id
  1212. tcIfaceExtId name = do { thing <- tcIfaceGlobal name
  1213. ; case thing of
  1214. AnId id -> return id
  1215. _ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
  1216. \end{code}
  1217. %************************************************************************
  1218. %* *
  1219. Bindings
  1220. %* *
  1221. %************************************************************************
  1222. \begin{code}
  1223. bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
  1224. bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
  1225. = do { name <- newIfaceName (mkVarOccFS fs)
  1226. ; ty' <- tcIfaceType ty
  1227. ; let id = mkLocalId name ty'
  1228. ; extendIfaceIdEnv [id] (thing_inside id) }
  1229. bindIfaceBndr (IfaceTvBndr bndr) thing_inside
  1230. = bindIfaceTyVar bndr thing_inside
  1231. bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
  1232. bindIfaceBndrs [] thing_inside = thing_inside []
  1233. bindIfaceBndrs (b:bs) thing_inside
  1234. = bindIfaceBndr b $ \ b' ->
  1235. bindIfaceBndrs bs $ \ bs' ->
  1236. thing_inside (b':bs')
  1237. -----------------------
  1238. newExtCoreBndr :: IfaceLetBndr -> IfL Id
  1239. newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
  1240. = do { mod <- getIfModule
  1241. ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
  1242. ; ty' <- tcIfaceType ty
  1243. ; return (mkLocalId name ty') }
  1244. -----------------------
  1245. bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
  1246. bindIfaceTyVar (occ,kind) thing_inside
  1247. = do { name <- newIfaceName (mkTyVarOccFS occ)
  1248. ; tyvar <- mk_iface_tyvar name kind
  1249. ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
  1250. bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
  1251. bindIfaceTyVars bndrs thing_inside
  1252. = do { names <- newIfaceNames (map mkTyVarOccFS occs)
  1253. ; let (kis_kind, tys_kind) = span isSuperIfaceKind kinds
  1254. (kis_name, tys_name) = splitAt (length kis_kind) names
  1255. -- We need to bring the kind variables in scope since type
  1256. -- variables may mention them.
  1257. ; kvs <- zipWithM mk_iface_tyvar kis_name kis_kind
  1258. ; extendIfaceTyVarEnv kvs $ do
  1259. { tvs <- zipWithM mk_iface_tyvar tys_name tys_kind
  1260. ; extendIfaceTyVarEnv tvs (thing_inside (kvs ++ tvs)) } }
  1261. where
  1262. (occs,kinds) = unzip bndrs
  1263. isSuperIfaceKind :: IfaceKind -> Bool
  1264. isSuperIfaceKind (IfaceTyConApp (IfaceTc n) []) = n == superKindTyConName
  1265. isSuperIfaceKind _ = False
  1266. mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
  1267. mk_iface_tyvar name ifKind
  1268. = do { kind <- tcIfaceKind ifKind
  1269. ; return (Var.mkTyVar name kind) }
  1270. bindIfaceTyVars_AT :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
  1271. -- Used for type variable in nested associated data/type declarations
  1272. -- where some of the type variables are already in scope
  1273. -- class C a where { data T a b }
  1274. -- Here 'a' is in scope when we look at the 'data T'
  1275. bindIfaceTyVars_AT [] thing_inside
  1276. = thing_inside []
  1277. bindIfaceTyVars_AT (b@(tv_occ,_) : bs) thing_inside
  1278. = do { mb_tv <- lookupIfaceTyVar tv_occ
  1279. ; let bind_b :: (TyVar -> IfL a) -> IfL a
  1280. bind_b = case mb_tv of
  1281. Just b' -> \k -> k b'
  1282. Nothing -> bindIfaceTyVar b
  1283. ; bind_b $ \b' ->
  1284. bindIfaceTyVars_AT bs $ \bs' ->
  1285. thing_inside (b':bs') }
  1286. \end{code}