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

/compiler/typecheck/TcRnDriver.lhs

https://github.com/luite/ghc
Haskell | 1948 lines | 1281 code | 287 blank | 380 comment | 43 complexity | c0a582260af4f74b310c8d9de9b6e698 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. %
  2. % (c) The University of Glasgow 2006
  3. % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
  4. %
  5. \section[TcMovectle]{Typechecking a whole module}
  6. \begin{code}
  7. module TcRnDriver (
  8. #ifdef GHCI
  9. tcRnStmt, tcRnExpr, tcRnType,
  10. tcRnImportDecls,
  11. tcRnLookupRdrName,
  12. getModuleInterface,
  13. tcRnDeclsi,
  14. isGHCiMonad,
  15. #endif
  16. tcRnLookupName,
  17. tcRnGetInfo,
  18. tcRnModule,
  19. tcTopSrcDecls,
  20. tcRnExtCore
  21. ) where
  22. #ifdef GHCI
  23. import {-# SOURCE #-} TcSplice ( tcSpliceDecls )
  24. #endif
  25. import DynFlags
  26. import StaticFlags
  27. import HsSyn
  28. import PrelNames
  29. import RdrName
  30. import TcHsSyn
  31. import TcExpr
  32. import TcRnMonad
  33. import TcEvidence
  34. import Coercion( pprCoAxiom )
  35. import FamInst
  36. import InstEnv
  37. import FamInstEnv
  38. import TcAnnotations
  39. import TcBinds
  40. import HeaderInfo ( mkPrelImports )
  41. import TcDefaults
  42. import TcEnv
  43. import TcRules
  44. import TcForeign
  45. import TcInstDcls
  46. import TcIface
  47. import TcMType
  48. import MkIface
  49. import IfaceSyn
  50. import TcSimplify
  51. import TcTyClsDecls
  52. import LoadIface
  53. import RnNames
  54. import RnEnv
  55. import RnSource
  56. import PprCore
  57. import CoreSyn
  58. import ErrUtils
  59. import Id
  60. import VarEnv
  61. import Module
  62. import UniqFM
  63. import Name
  64. import NameEnv
  65. import NameSet
  66. import Avail
  67. import TyCon
  68. import SrcLoc
  69. import HscTypes
  70. import ListSetOps
  71. import Outputable
  72. import DataCon
  73. import Type
  74. import Class
  75. import CoAxiom ( CoAxBranch(..) )
  76. import Inst ( tcGetInstEnvs )
  77. import Data.List ( sortBy )
  78. import Data.IORef ( readIORef )
  79. import Data.Ord
  80. #ifdef GHCI
  81. import TcType ( isUnitTy, isTauTy )
  82. import TcHsType
  83. import TcMatches
  84. import RnTypes
  85. import RnExpr
  86. import MkId
  87. import BasicTypes
  88. import TidyPgm ( globaliseAndTidyId )
  89. import TysWiredIn ( unitTy, mkListTy )
  90. #endif
  91. import FastString
  92. import Maybes
  93. import Util
  94. import Bag
  95. import Control.Monad
  96. #include "HsVersions.h"
  97. \end{code}
  98. %************************************************************************
  99. %* *
  100. Typecheck and rename a module
  101. %* *
  102. %************************************************************************
  103. \begin{code}
  104. -- | Top level entry point for typechecker and renamer
  105. tcRnModule :: HscEnv
  106. -> HscSource
  107. -> Bool -- True <=> save renamed syntax
  108. -> HsParsedModule
  109. -> IO (Messages, Maybe TcGblEnv)
  110. tcRnModule hsc_env hsc_src save_rn_syntax
  111. HsParsedModule {
  112. hpm_module =
  113. (L loc (HsModule maybe_mod export_ies
  114. import_decls local_decls mod_deprec
  115. maybe_doc_hdr)),
  116. hpm_src_files =
  117. src_files
  118. }
  119. = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
  120. let { this_pkg = thisPackage (hsc_dflags hsc_env) ;
  121. (this_mod, prel_imp_loc)
  122. = case maybe_mod of
  123. Nothing -- 'module M where' is omitted
  124. -> (mAIN, srcLocSpan (srcSpanStart loc))
  125. Just (L mod_loc mod) -- The normal case
  126. -> (mkModule this_pkg mod, mod_loc) } ;
  127. initTc hsc_env hsc_src save_rn_syntax this_mod $
  128. setSrcSpan loc $
  129. do { -- Deal with imports; first add implicit prelude
  130. implicit_prelude <- xoptM Opt_ImplicitPrelude;
  131. let { prel_imports = mkPrelImports (moduleName this_mod) prel_imp_loc
  132. implicit_prelude import_decls } ;
  133. whenWOptM Opt_WarnImplicitPrelude $
  134. when (notNull prel_imports) $ addWarn (implicitPreludeWarn) ;
  135. tcg_env <- {-# SCC "tcRnImports" #-}
  136. tcRnImports hsc_env this_mod (prel_imports ++ import_decls) ;
  137. -- If the whole module is warned about or deprecated
  138. -- (via mod_deprec) record that in tcg_warns. If we do thereby add
  139. -- a WarnAll, it will override any subseqent depracations added to tcg_warns
  140. let { tcg_env1 = case mod_deprec of
  141. Just txt -> tcg_env { tcg_warns = WarnAll txt }
  142. Nothing -> tcg_env
  143. } ;
  144. setGblEnv tcg_env1 $ do {
  145. -- Load the hi-boot interface for this module, if any
  146. -- We do this now so that the boot_names can be passed
  147. -- to tcTyAndClassDecls, because the boot_names are
  148. -- automatically considered to be loop breakers
  149. --
  150. -- Do this *after* tcRnImports, so that we know whether
  151. -- a module that we import imports us; and hence whether to
  152. -- look for a hi-boot file
  153. boot_iface <- tcHiBootIface hsc_src this_mod ;
  154. -- Rename and type check the declarations
  155. traceRn (text "rn1a") ;
  156. tcg_env <- if isHsBoot hsc_src then
  157. tcRnHsBootDecls local_decls
  158. else
  159. {-# SCC "tcRnSrcDecls" #-}
  160. tcRnSrcDecls boot_iface local_decls ;
  161. setGblEnv tcg_env $ do {
  162. -- Process the export list
  163. traceRn (text "rn4a: before exports");
  164. tcg_env <- rnExports (isJust maybe_mod) export_ies tcg_env ;
  165. traceRn (text "rn4b: after exports") ;
  166. -- Check that main is exported (must be after rnExports)
  167. checkMainExported tcg_env ;
  168. -- Compare the hi-boot iface (if any) with the real thing
  169. -- Must be done after processing the exports
  170. tcg_env <- checkHiBootIface tcg_env boot_iface ;
  171. -- The new type env is already available to stuff slurped from
  172. -- interface files, via TcEnv.updateGlobalTypeEnv
  173. -- It's important that this includes the stuff in checkHiBootIface,
  174. -- because the latter might add new bindings for boot_dfuns,
  175. -- which may be mentioned in imported unfoldings
  176. -- Don't need to rename the Haddock documentation,
  177. -- it's not parsed by GHC anymore.
  178. tcg_env <- return (tcg_env { tcg_doc_hdr = maybe_doc_hdr }) ;
  179. -- Report unused names
  180. reportUnusedNames export_ies tcg_env ;
  181. -- add extra source files to tcg_dependent_files
  182. addDependentFiles src_files ;
  183. -- Dump output and return
  184. tcDump tcg_env ;
  185. return tcg_env
  186. }}}}
  187. implicitPreludeWarn :: SDoc
  188. implicitPreludeWarn
  189. = ptext (sLit "Module `Prelude' implicitly imported")
  190. \end{code}
  191. %************************************************************************
  192. %* *
  193. Import declarations
  194. %* *
  195. %************************************************************************
  196. \begin{code}
  197. tcRnImports :: HscEnv -> Module
  198. -> [LImportDecl RdrName] -> TcM TcGblEnv
  199. tcRnImports hsc_env this_mod import_decls
  200. = do { (rn_imports, rdr_env, imports,hpc_info) <- rnImports import_decls ;
  201. ; let { dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface)
  202. -- Make sure we record the dependencies from the DynFlags in the EPS or we
  203. -- end up hitting the sanity check in LoadIface.loadInterface that
  204. -- checks for unknown home-package modules being loaded. We put
  205. -- these dependencies on the left so their (non-source) imports
  206. -- take precedence over the (possibly-source) imports on the right.
  207. -- We don't add them to any other field (e.g. the imp_dep_mods of
  208. -- imports) because we don't want to load their instances etc.
  209. ; dep_mods = listToUFM [(mod_nm, (mod_nm, False)) | mod_nm <- dynFlagDependencies (hsc_dflags hsc_env)]
  210. `plusUFM` imp_dep_mods imports
  211. -- We want instance declarations from all home-package
  212. -- modules below this one, including boot modules, except
  213. -- ourselves. The 'except ourselves' is so that we don't
  214. -- get the instances from this module's hs-boot file
  215. ; want_instances :: ModuleName -> Bool
  216. ; want_instances mod = mod `elemUFM` dep_mods
  217. && mod /= moduleName this_mod
  218. ; (home_insts, home_fam_insts) = hptInstances hsc_env
  219. want_instances
  220. } ;
  221. -- Record boot-file info in the EPS, so that it's
  222. -- visible to loadHiBootInterface in tcRnSrcDecls,
  223. -- and any other incrementally-performed imports
  224. ; updateEps_ (\eps -> eps { eps_is_boot = dep_mods }) ;
  225. -- Update the gbl env
  226. ; updGblEnv ( \ gbl ->
  227. gbl {
  228. tcg_rdr_env = plusOccEnv (tcg_rdr_env gbl) rdr_env,
  229. tcg_imports = tcg_imports gbl `plusImportAvails` imports,
  230. tcg_rn_imports = rn_imports,
  231. tcg_inst_env = extendInstEnvList (tcg_inst_env gbl) home_insts,
  232. tcg_fam_inst_env = extendFamInstEnvList (tcg_fam_inst_env gbl)
  233. home_fam_insts,
  234. tcg_hpc = hpc_info
  235. }) $ do {
  236. ; traceRn (text "rn1" <+> ppr (imp_dep_mods imports))
  237. -- Fail if there are any errors so far
  238. -- The error printing (if needed) takes advantage
  239. -- of the tcg_env we have now set
  240. -- ; traceIf (text "rdr_env: " <+> ppr rdr_env)
  241. ; failIfErrsM
  242. -- Load any orphan-module and family instance-module
  243. -- interfaces, so that their rules and instance decls will be
  244. -- found.
  245. ; loadModuleInterfaces (ptext (sLit "Loading orphan modules"))
  246. (imp_orphs imports)
  247. -- Check type-family consistency
  248. ; traceRn (text "rn1: checking family instance consistency")
  249. ; let { dir_imp_mods = moduleEnvKeys
  250. . imp_mods
  251. $ imports }
  252. ; checkFamInstConsistency (imp_finsts imports) dir_imp_mods ;
  253. ; getGblEnv } }
  254. \end{code}
  255. %************************************************************************
  256. %* *
  257. Type-checking external-core modules
  258. %* *
  259. %************************************************************************
  260. \begin{code}
  261. tcRnExtCore :: HscEnv
  262. -> HsExtCore RdrName
  263. -> IO (Messages, Maybe ModGuts)
  264. -- Nothing => some error occurred
  265. tcRnExtCore hsc_env (HsExtCore this_mod decls src_binds)
  266. -- The decls are IfaceDecls; all names are original names
  267. = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
  268. initTc hsc_env ExtCoreFile False this_mod $ do {
  269. let { ldecls = map noLoc decls } ;
  270. -- Bring the type and class decls into scope
  271. -- ToDo: check that this doesn't need to extract the val binds.
  272. -- It seems that only the type and class decls need to be in scope below because
  273. -- (a) tcTyAndClassDecls doesn't need the val binds, and
  274. -- (b) tcExtCoreBindings doesn't need anything
  275. -- (in fact, it might not even need to be in the scope of
  276. -- this tcg_env at all)
  277. (tc_envs, _bndrs) <- getLocalNonValBinders emptyFsEnv {- no fixity decls -}
  278. (mkFakeGroup ldecls) ;
  279. setEnvs tc_envs $ do {
  280. (rn_decls, _fvs) <- checkNoErrs $ rnTyClDecls [] [ldecls] ;
  281. -- The empty list is for extra dependencies coming from .hs-boot files
  282. -- See Note [Extra dependencies from .hs-boot files] in RnSource
  283. -- Dump trace of renaming part
  284. rnDump (ppr rn_decls) ;
  285. -- Typecheck them all together so that
  286. -- any mutually recursive types are done right
  287. -- Just discard the auxiliary bindings; they are generated
  288. -- only for Haskell source code, and should already be in Core
  289. tcg_env <- tcTyAndClassDecls emptyModDetails rn_decls ;
  290. safe_mode <- liftIO $ finalSafeMode (hsc_dflags hsc_env) tcg_env ;
  291. dep_files <- liftIO $ readIORef (tcg_dependent_files tcg_env) ;
  292. setGblEnv tcg_env $ do {
  293. -- Make the new type env available to stuff slurped from interface files
  294. -- Now the core bindings
  295. core_binds <- initIfaceExtCore (tcExtCoreBindings src_binds) ;
  296. -- Wrap up
  297. let {
  298. bndrs = bindersOfBinds core_binds ;
  299. my_exports = map (Avail . idName) bndrs ;
  300. -- ToDo: export the data types also?
  301. mod_guts = ModGuts { mg_module = this_mod,
  302. mg_boot = False,
  303. mg_used_names = emptyNameSet, -- ToDo: compute usage
  304. mg_used_th = False,
  305. mg_dir_imps = emptyModuleEnv, -- ??
  306. mg_deps = noDependencies, -- ??
  307. mg_exports = my_exports,
  308. mg_tcs = tcg_tcs tcg_env,
  309. mg_insts = tcg_insts tcg_env,
  310. mg_fam_insts = tcg_fam_insts tcg_env,
  311. mg_inst_env = tcg_inst_env tcg_env,
  312. mg_fam_inst_env = tcg_fam_inst_env tcg_env,
  313. mg_rules = [],
  314. mg_vect_decls = [],
  315. mg_anns = [],
  316. mg_binds = core_binds,
  317. -- Stubs
  318. mg_rdr_env = emptyGlobalRdrEnv,
  319. mg_fix_env = emptyFixityEnv,
  320. mg_warns = NoWarnings,
  321. mg_foreign = NoStubs,
  322. mg_hpc_info = emptyHpcInfo False,
  323. mg_modBreaks = emptyModBreaks,
  324. mg_vect_info = noVectInfo,
  325. mg_safe_haskell = safe_mode,
  326. mg_trust_pkg = False,
  327. mg_dependent_files = dep_files
  328. } } ;
  329. tcCoreDump mod_guts ;
  330. return mod_guts
  331. }}}}
  332. mkFakeGroup :: [LTyClDecl a] -> HsGroup a
  333. mkFakeGroup decls -- Rather clumsy; lots of unused fields
  334. = emptyRdrGroup { hs_tyclds = [decls] }
  335. \end{code}
  336. %************************************************************************
  337. %* *
  338. Type-checking the top level of a module
  339. %* *
  340. %************************************************************************
  341. \begin{code}
  342. tcRnSrcDecls :: ModDetails -> [LHsDecl RdrName] -> TcM TcGblEnv
  343. -- Returns the variables free in the decls
  344. -- Reason: solely to report unused imports and bindings
  345. tcRnSrcDecls boot_iface decls
  346. = do { -- Do all the declarations
  347. ((tcg_env, tcl_env), lie) <- captureConstraints $ tc_rn_src_decls boot_iface decls ;
  348. ; traceTc "Tc8" empty ;
  349. ; setEnvs (tcg_env, tcl_env) $
  350. do {
  351. -- Finish simplifying class constraints
  352. --
  353. -- simplifyTop deals with constant or ambiguous InstIds.
  354. -- How could there be ambiguous ones? They can only arise if a
  355. -- top-level decl falls under the monomorphism restriction
  356. -- and no subsequent decl instantiates its type.
  357. --
  358. -- We do this after checkMain, so that we use the type info
  359. -- that checkMain adds
  360. --
  361. -- We do it with both global and local env in scope:
  362. -- * the global env exposes the instances to simplifyTop
  363. -- * the local env exposes the local Ids to simplifyTop,
  364. -- so that we get better error messages (monomorphism restriction)
  365. new_ev_binds <- {-# SCC "simplifyTop" #-}
  366. simplifyTop lie ;
  367. traceTc "Tc9" empty ;
  368. failIfErrsM ; -- Don't zonk if there have been errors
  369. -- It's a waste of time; and we may get debug warnings
  370. -- about strangely-typed TyCons!
  371. -- Zonk the final code. This must be done last.
  372. -- Even simplifyTop may do some unification.
  373. -- This pass also warns about missing type signatures
  374. let { TcGblEnv { tcg_type_env = type_env,
  375. tcg_binds = binds,
  376. tcg_sigs = sig_ns,
  377. tcg_ev_binds = cur_ev_binds,
  378. tcg_imp_specs = imp_specs,
  379. tcg_rules = rules,
  380. tcg_vects = vects,
  381. tcg_fords = fords } = tcg_env
  382. ; all_ev_binds = cur_ev_binds `unionBags` new_ev_binds } ;
  383. (bind_ids, ev_binds', binds', fords', imp_specs', rules', vects')
  384. <- {-# SCC "zonkTopDecls" #-}
  385. zonkTopDecls all_ev_binds binds sig_ns rules vects imp_specs fords ;
  386. let { final_type_env = extendTypeEnvWithIds type_env bind_ids
  387. ; tcg_env' = tcg_env { tcg_binds = binds',
  388. tcg_ev_binds = ev_binds',
  389. tcg_imp_specs = imp_specs',
  390. tcg_rules = rules',
  391. tcg_vects = vects',
  392. tcg_fords = fords' } } ;
  393. setGlobalTypeEnv tcg_env' final_type_env
  394. } }
  395. tc_rn_src_decls :: ModDetails
  396. -> [LHsDecl RdrName]
  397. -> TcM (TcGblEnv, TcLclEnv)
  398. -- Loops around dealing with each top level inter-splice group
  399. -- in turn, until it's dealt with the entire module
  400. tc_rn_src_decls boot_details ds
  401. = {-# SCC "tc_rn_src_decls" #-}
  402. do { (first_group, group_tail) <- findSplice ds ;
  403. -- If ds is [] we get ([], Nothing)
  404. -- The extra_deps are needed while renaming type and class declarations
  405. -- See Note [Extra dependencies from .hs-boot files] in RnSource
  406. let { extra_deps = map tyConName (typeEnvTyCons (md_types boot_details)) } ;
  407. -- Deal with decls up to, but not including, the first splice
  408. (tcg_env, rn_decls) <- rnTopSrcDecls extra_deps first_group ;
  409. -- rnTopSrcDecls fails if there are any errors
  410. (tcg_env, tcl_env) <- setGblEnv tcg_env $
  411. tcTopSrcDecls boot_details rn_decls ;
  412. -- If there is no splice, we're nearly done
  413. setEnvs (tcg_env, tcl_env) $
  414. case group_tail of {
  415. Nothing -> do { tcg_env <- checkMain ; -- Check for `main'
  416. traceTc "returning from tc_rn_src_decls: " $
  417. ppr $ nameEnvElts $ tcg_type_env tcg_env ; -- RAE
  418. return (tcg_env, tcl_env)
  419. } ;
  420. #ifndef GHCI
  421. -- There shouldn't be a splice
  422. Just (SpliceDecl {}, _) -> do {
  423. failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
  424. #else
  425. -- If there's a splice, we must carry on
  426. Just (SpliceDecl splice_expr _, rest_ds) -> do {
  427. -- Rename the splice expression, and get its supporting decls
  428. (rn_splice_expr, splice_fvs) <- checkNoErrs (rnLExpr splice_expr) ;
  429. -- checkNoErrs: don't typecheck if renaming failed
  430. rnDump (ppr rn_splice_expr) ;
  431. -- Execute the splice
  432. spliced_decls <- tcSpliceDecls rn_splice_expr ;
  433. -- Glue them on the front of the remaining decls and loop
  434. setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
  435. tc_rn_src_decls boot_details (spliced_decls ++ rest_ds)
  436. #endif /* GHCI */
  437. } } }
  438. \end{code}
  439. %************************************************************************
  440. %* *
  441. Compiling hs-boot source files, and
  442. comparing the hi-boot interface with the real thing
  443. %* *
  444. %************************************************************************
  445. \begin{code}
  446. tcRnHsBootDecls :: [LHsDecl RdrName] -> TcM TcGblEnv
  447. tcRnHsBootDecls decls
  448. = do { (first_group, group_tail) <- findSplice decls
  449. -- Rename the declarations
  450. ; (tcg_env, HsGroup {
  451. hs_tyclds = tycl_decls,
  452. hs_instds = inst_decls,
  453. hs_derivds = deriv_decls,
  454. hs_fords = for_decls,
  455. hs_defds = def_decls,
  456. hs_ruleds = rule_decls,
  457. hs_vects = vect_decls,
  458. hs_annds = _,
  459. hs_valds = val_binds }) <- rnTopSrcDecls [] first_group
  460. -- The empty list is for extra dependencies coming from .hs-boot files
  461. -- See Note [Extra dependencies from .hs-boot files] in RnSource
  462. ; (gbl_env, lie) <- captureConstraints $ setGblEnv tcg_env $ do {
  463. -- Check for illegal declarations
  464. ; case group_tail of
  465. Just (SpliceDecl d _, _) -> badBootDecl "splice" d
  466. Nothing -> return ()
  467. ; mapM_ (badBootDecl "foreign") for_decls
  468. ; mapM_ (badBootDecl "default") def_decls
  469. ; mapM_ (badBootDecl "rule") rule_decls
  470. ; mapM_ (badBootDecl "vect") vect_decls
  471. -- Typecheck type/class/isntance decls
  472. ; traceTc "Tc2 (boot)" empty
  473. ; (tcg_env, inst_infos, _deriv_binds)
  474. <- tcTyClsInstDecls emptyModDetails tycl_decls inst_decls deriv_decls
  475. ; setGblEnv tcg_env $ do {
  476. -- Typecheck value declarations
  477. ; traceTc "Tc5" empty
  478. ; val_ids <- tcHsBootSigs val_binds
  479. -- Wrap up
  480. -- No simplification or zonking to do
  481. ; traceTc "Tc7a" empty
  482. ; gbl_env <- getGblEnv
  483. -- Make the final type-env
  484. -- Include the dfun_ids so that their type sigs
  485. -- are written into the interface file.
  486. ; let { type_env0 = tcg_type_env gbl_env
  487. ; type_env1 = extendTypeEnvWithIds type_env0 val_ids
  488. ; type_env2 = extendTypeEnvWithIds type_env1 dfun_ids
  489. ; dfun_ids = map iDFunId inst_infos
  490. }
  491. ; setGlobalTypeEnv gbl_env type_env2
  492. }}
  493. ; traceTc "boot" (ppr lie); return gbl_env }
  494. badBootDecl :: String -> Located decl -> TcM ()
  495. badBootDecl what (L loc _)
  496. = addErrAt loc (char 'A' <+> text what
  497. <+> ptext (sLit "declaration is not (currently) allowed in a hs-boot file"))
  498. \end{code}
  499. Once we've typechecked the body of the module, we want to compare what
  500. we've found (gathered in a TypeEnv) with the hi-boot details (if any).
  501. \begin{code}
  502. checkHiBootIface :: TcGblEnv -> ModDetails -> TcM TcGblEnv
  503. -- Compare the hi-boot file for this module (if there is one)
  504. -- with the type environment we've just come up with
  505. -- In the common case where there is no hi-boot file, the list
  506. -- of boot_names is empty.
  507. --
  508. -- The bindings we return give bindings for the dfuns defined in the
  509. -- hs-boot file, such as $fbEqT = $fEqT
  510. checkHiBootIface
  511. tcg_env@(TcGblEnv { tcg_src = hs_src, tcg_binds = binds,
  512. tcg_insts = local_insts,
  513. tcg_type_env = local_type_env, tcg_exports = local_exports })
  514. (ModDetails { md_insts = boot_insts, md_fam_insts = boot_fam_insts,
  515. md_types = boot_type_env, md_exports = boot_exports })
  516. | isHsBoot hs_src -- Current module is already a hs-boot file!
  517. = return tcg_env
  518. | otherwise
  519. = do { traceTc "checkHiBootIface" $ vcat
  520. [ ppr boot_type_env, ppr boot_insts, ppr boot_exports]
  521. -- Check the exports of the boot module, one by one
  522. ; mapM_ check_export boot_exports
  523. -- Check for no family instances
  524. ; unless (null boot_fam_insts) $
  525. panic ("TcRnDriver.checkHiBootIface: Cannot handle family " ++
  526. "instances in boot files yet...")
  527. -- FIXME: Why? The actual comparison is not hard, but what would
  528. -- be the equivalent to the dfun bindings returned for class
  529. -- instances? We can't easily equate tycons...
  530. -- Check instance declarations
  531. ; mb_dfun_prs <- mapM check_inst boot_insts
  532. ; let dfun_prs = catMaybes mb_dfun_prs
  533. boot_dfuns = map fst dfun_prs
  534. dfun_binds = listToBag [ mkVarBind boot_dfun (nlHsVar dfun)
  535. | (boot_dfun, dfun) <- dfun_prs ]
  536. type_env' = extendTypeEnvWithIds local_type_env boot_dfuns
  537. tcg_env' = tcg_env { tcg_binds = binds `unionBags` dfun_binds }
  538. ; failIfErrsM
  539. ; setGlobalTypeEnv tcg_env' type_env' }
  540. -- Update the global type env *including* the knot-tied one
  541. -- so that if the source module reads in an interface unfolding
  542. -- mentioning one of the dfuns from the boot module, then it
  543. -- can "see" that boot dfun. See Trac #4003
  544. where
  545. check_export boot_avail -- boot_avail is exported by the boot iface
  546. | name `elem` dfun_names = return ()
  547. | isWiredInName name = return () -- No checking for wired-in names. In particular,
  548. -- 'error' is handled by a rather gross hack
  549. -- (see comments in GHC.Err.hs-boot)
  550. -- Check that the actual module exports the same thing
  551. | not (null missing_names)
  552. = addErrAt (nameSrcSpan (head missing_names))
  553. (missingBootThing (head missing_names) "exported by")
  554. -- If the boot module does not *define* the thing, we are done
  555. -- (it simply re-exports it, and names match, so nothing further to do)
  556. | isNothing mb_boot_thing = return ()
  557. -- Check that the actual module also defines the thing, and
  558. -- then compare the definitions
  559. | Just real_thing <- lookupTypeEnv local_type_env name,
  560. Just boot_thing <- mb_boot_thing
  561. = when (not (checkBootDecl boot_thing real_thing))
  562. $ addErrAt (nameSrcSpan (getName boot_thing))
  563. (let boot_decl = tyThingToIfaceDecl
  564. (fromJust mb_boot_thing)
  565. real_decl = tyThingToIfaceDecl real_thing
  566. in bootMisMatch real_thing boot_decl real_decl)
  567. | otherwise
  568. = addErrTc (missingBootThing name "defined in")
  569. where
  570. name = availName boot_avail
  571. mb_boot_thing = lookupTypeEnv boot_type_env name
  572. missing_names = case lookupNameEnv local_export_env name of
  573. Nothing -> [name]
  574. Just avail -> availNames boot_avail `minusList` availNames avail
  575. dfun_names = map getName boot_insts
  576. local_export_env :: NameEnv AvailInfo
  577. local_export_env = availsToNameEnv local_exports
  578. check_inst :: ClsInst -> TcM (Maybe (Id, Id))
  579. -- Returns a pair of the boot dfun in terms of the equivalent real dfun
  580. check_inst boot_inst
  581. = case [dfun | inst <- local_insts,
  582. let dfun = instanceDFunId inst,
  583. idType dfun `eqType` boot_inst_ty ] of
  584. [] -> do { traceTc "check_inst" (vcat [ text "local_insts" <+> vcat (map (ppr . idType . instanceDFunId) local_insts)
  585. , text "boot_inst" <+> ppr boot_inst
  586. , text "boot_inst_ty" <+> ppr boot_inst_ty
  587. ])
  588. ; addErrTc (instMisMatch boot_inst); return Nothing }
  589. (dfun:_) -> return (Just (local_boot_dfun, dfun))
  590. where
  591. boot_dfun = instanceDFunId boot_inst
  592. boot_inst_ty = idType boot_dfun
  593. local_boot_dfun = Id.mkExportedLocalId (idName boot_dfun) boot_inst_ty
  594. -- This has to compare the TyThing from the .hi-boot file to the TyThing
  595. -- in the current source file. We must be careful to allow alpha-renaming
  596. -- where appropriate, and also the boot declaration is allowed to omit
  597. -- constructors and class methods.
  598. --
  599. -- See rnfail055 for a good test of this stuff.
  600. checkBootDecl :: TyThing -> TyThing -> Bool
  601. checkBootDecl (AnId id1) (AnId id2)
  602. = ASSERT(id1 == id2)
  603. (idType id1 `eqType` idType id2)
  604. checkBootDecl (ATyCon tc1) (ATyCon tc2)
  605. = checkBootTyCon tc1 tc2
  606. checkBootDecl (ADataCon dc1) (ADataCon _)
  607. = pprPanic "checkBootDecl" (ppr dc1)
  608. checkBootDecl _ _ = False -- probably shouldn't happen
  609. ----------------
  610. checkBootTyCon :: TyCon -> TyCon -> Bool
  611. checkBootTyCon tc1 tc2
  612. | not (eqKind (tyConKind tc1) (tyConKind tc2))
  613. = False -- First off, check the kind
  614. | Just c1 <- tyConClass_maybe tc1
  615. , Just c2 <- tyConClass_maybe tc2
  616. , let (clas_tvs1, clas_fds1, sc_theta1, _, ats1, op_stuff1)
  617. = classExtraBigSig c1
  618. (clas_tvs2, clas_fds2, sc_theta2, _, ats2, op_stuff2)
  619. = classExtraBigSig c2
  620. , Just env <- eqTyVarBndrs emptyRnEnv2 clas_tvs1 clas_tvs2
  621. = let
  622. eqSig (id1, def_meth1) (id2, def_meth2)
  623. = idName id1 == idName id2 &&
  624. eqTypeX env op_ty1 op_ty2 &&
  625. def_meth1 == def_meth2
  626. where
  627. (_, rho_ty1) = splitForAllTys (idType id1)
  628. op_ty1 = funResultTy rho_ty1
  629. (_, rho_ty2) = splitForAllTys (idType id2)
  630. op_ty2 = funResultTy rho_ty2
  631. eqAT (tc1, def_ats1) (tc2, def_ats2)
  632. = checkBootTyCon tc1 tc2 &&
  633. eqListBy eqATDef def_ats1 def_ats2
  634. -- Ignore the location of the defaults
  635. eqATDef (CoAxBranch { cab_tvs = tvs1, cab_lhs = ty_pats1, cab_rhs = ty1 })
  636. (CoAxBranch { cab_tvs = tvs2, cab_lhs = ty_pats2, cab_rhs = ty2 })
  637. | Just env <- eqTyVarBndrs emptyRnEnv2 tvs1 tvs2
  638. = eqListBy (eqTypeX env) ty_pats1 ty_pats2 &&
  639. eqTypeX env ty1 ty2
  640. | otherwise = False
  641. eqFD (as1,bs1) (as2,bs2) =
  642. eqListBy (eqTypeX env) (mkTyVarTys as1) (mkTyVarTys as2) &&
  643. eqListBy (eqTypeX env) (mkTyVarTys bs1) (mkTyVarTys bs2)
  644. in
  645. -- Checks kind of class
  646. eqListBy eqFD clas_fds1 clas_fds2 &&
  647. (null sc_theta1 && null op_stuff1 && null ats1
  648. || -- Above tests for an "abstract" class
  649. eqListBy (eqPredX env) sc_theta1 sc_theta2 &&
  650. eqListBy eqSig op_stuff1 op_stuff2 &&
  651. eqListBy eqAT ats1 ats2)
  652. | Just syn_rhs1 <- synTyConRhs_maybe tc1
  653. , Just syn_rhs2 <- synTyConRhs_maybe tc2
  654. , Just env <- eqTyVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
  655. = ASSERT(tc1 == tc2)
  656. let eqSynRhs (SynFamilyTyCon o1 i1) (SynFamilyTyCon o2 i2)
  657. = o1==o2 && i1==i2
  658. eqSynRhs (SynonymTyCon t1) (SynonymTyCon t2)
  659. = eqTypeX env t1 t2
  660. eqSynRhs _ _ = False
  661. in
  662. eqSynRhs syn_rhs1 syn_rhs2
  663. | isAlgTyCon tc1 && isAlgTyCon tc2
  664. , Just env <- eqTyVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
  665. = ASSERT(tc1 == tc2)
  666. eqListBy (eqPredX env) (tyConStupidTheta tc1) (tyConStupidTheta tc2) &&
  667. eqAlgRhs (algTyConRhs tc1) (algTyConRhs tc2)
  668. | isForeignTyCon tc1 && isForeignTyCon tc2
  669. = eqKind (tyConKind tc1) (tyConKind tc2) &&
  670. tyConExtName tc1 == tyConExtName tc2
  671. | otherwise = False
  672. where
  673. eqAlgRhs (AbstractTyCon dis1) rhs2
  674. | dis1 = isDistinctAlgRhs rhs2 --Check compatibility
  675. | otherwise = True
  676. eqAlgRhs DataFamilyTyCon{} DataFamilyTyCon{} = True
  677. eqAlgRhs tc1@DataTyCon{} tc2@DataTyCon{} =
  678. eqListBy eqCon (data_cons tc1) (data_cons tc2)
  679. eqAlgRhs tc1@NewTyCon{} tc2@NewTyCon{} =
  680. eqCon (data_con tc1) (data_con tc2)
  681. eqAlgRhs _ _ = False
  682. eqCon c1 c2
  683. = dataConName c1 == dataConName c2
  684. && dataConIsInfix c1 == dataConIsInfix c2
  685. && eqListBy eqHsBang (dataConStrictMarks c1) (dataConStrictMarks c2)
  686. && dataConFieldLabels c1 == dataConFieldLabels c2
  687. && eqType (dataConUserType c1) (dataConUserType c2)
  688. emptyRnEnv2 :: RnEnv2
  689. emptyRnEnv2 = mkRnEnv2 emptyInScopeSet
  690. ----------------
  691. missingBootThing :: Name -> String -> SDoc
  692. missingBootThing name what
  693. = ppr name <+> ptext (sLit "is exported by the hs-boot file, but not")
  694. <+> text what <+> ptext (sLit "the module")
  695. bootMisMatch :: TyThing -> IfaceDecl -> IfaceDecl -> SDoc
  696. bootMisMatch thing boot_decl real_decl
  697. = vcat [ppr thing <+> ptext (sLit "has conflicting definitions in the module and its hs-boot file"),
  698. ptext (sLit "Main module:") <+> ppr real_decl,
  699. ptext (sLit "Boot file: ") <+> ppr boot_decl]
  700. instMisMatch :: ClsInst -> SDoc
  701. instMisMatch inst
  702. = hang (ppr inst)
  703. 2 (ptext (sLit "is defined in the hs-boot file, but not in the module itself"))
  704. \end{code}
  705. %************************************************************************
  706. %* *
  707. Type-checking the top level of a module
  708. %* *
  709. %************************************************************************
  710. tcRnGroup takes a bunch of top-level source-code declarations, and
  711. * renames them
  712. * gets supporting declarations from interface files
  713. * typechecks them
  714. * zonks them
  715. * and augments the TcGblEnv with the results
  716. In Template Haskell it may be called repeatedly for each group of
  717. declarations. It expects there to be an incoming TcGblEnv in the
  718. monad; it augments it and returns the new TcGblEnv.
  719. \begin{code}
  720. ------------------------------------------------
  721. rnTopSrcDecls :: [Name] -> HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name)
  722. -- Fails if there are any errors
  723. rnTopSrcDecls extra_deps group
  724. = do { -- Rename the source decls
  725. traceTc "rn12" empty ;
  726. (tcg_env, rn_decls) <- checkNoErrs $ rnSrcDecls extra_deps group ;
  727. traceTc "rn13" empty ;
  728. -- save the renamed syntax, if we want it
  729. let { tcg_env'
  730. | Just grp <- tcg_rn_decls tcg_env
  731. = tcg_env{ tcg_rn_decls = Just (appendGroups grp rn_decls) }
  732. | otherwise
  733. = tcg_env };
  734. -- Dump trace of renaming part
  735. rnDump (ppr rn_decls) ;
  736. return (tcg_env', rn_decls)
  737. }
  738. ------------------------------------------------
  739. tcTopSrcDecls :: ModDetails -> HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
  740. tcTopSrcDecls boot_details
  741. (HsGroup { hs_tyclds = tycl_decls,
  742. hs_instds = inst_decls,
  743. hs_derivds = deriv_decls,
  744. hs_fords = foreign_decls,
  745. hs_defds = default_decls,
  746. hs_annds = annotation_decls,
  747. hs_ruleds = rule_decls,
  748. hs_vects = vect_decls,
  749. hs_valds = val_binds })
  750. = do { -- Type-check the type and class decls, and all imported decls
  751. -- The latter come in via tycl_decls
  752. traceTc "Tc2 (src)" empty ;
  753. -- Source-language instances, including derivings,
  754. -- and import the supporting declarations
  755. traceTc "Tc3" empty ;
  756. (tcg_env, inst_infos, deriv_binds)
  757. <- tcTyClsInstDecls boot_details tycl_decls inst_decls deriv_decls ;
  758. setGblEnv tcg_env $ do {
  759. -- Foreign import declarations next.
  760. traceTc "Tc4" empty ;
  761. (fi_ids, fi_decls, fi_gres) <- tcForeignImports foreign_decls ;
  762. tcExtendGlobalValEnv fi_ids $ do {
  763. -- Default declarations
  764. traceTc "Tc4a" empty ;
  765. default_tys <- tcDefaults default_decls ;
  766. updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
  767. -- Now GHC-generated derived bindings, generics, and selectors
  768. -- Do not generate warnings from compiler-generated code;
  769. -- hence the use of discardWarnings
  770. tc_envs <- discardWarnings (tcTopBinds deriv_binds) ;
  771. setEnvs tc_envs $ do {
  772. -- Value declarations next
  773. traceTc "Tc5" empty ;
  774. tc_envs@(tcg_env, tcl_env) <- tcTopBinds val_binds;
  775. setEnvs tc_envs $ do { -- Environment doesn't change now
  776. -- Second pass over class and instance declarations,
  777. -- now using the kind-checked decls
  778. traceTc "Tc6" empty ;
  779. inst_binds <- tcInstDecls2 (concat tycl_decls) inst_infos ;
  780. -- Foreign exports
  781. traceTc "Tc7" empty ;
  782. (foe_binds, foe_decls, foe_gres) <- tcForeignExports foreign_decls ;
  783. -- Annotations
  784. annotations <- tcAnnotations annotation_decls ;
  785. -- Rules
  786. rules <- tcRules rule_decls ;
  787. -- Vectorisation declarations
  788. vects <- tcVectDecls vect_decls ;
  789. -- Wrap up
  790. traceTc "Tc7a" empty ;
  791. let { all_binds = inst_binds `unionBags`
  792. foe_binds
  793. ; fo_gres = fi_gres `unionBags` foe_gres
  794. ; fo_fvs = foldrBag (\gre fvs -> fvs `addOneFV` gre_name gre)
  795. emptyFVs fo_gres
  796. ; fo_rdr_names :: [RdrName]
  797. ; fo_rdr_names = foldrBag gre_to_rdr_name [] fo_gres
  798. ; sig_names = mkNameSet (collectHsValBinders val_binds)
  799. `minusNameSet` getTypeSigNames val_binds
  800. -- Extend the GblEnv with the (as yet un-zonked)
  801. -- bindings, rules, foreign decls
  802. ; tcg_env' = tcg_env { tcg_binds = tcg_binds tcg_env `unionBags` all_binds
  803. , tcg_sigs = tcg_sigs tcg_env `unionNameSets` sig_names
  804. , tcg_rules = tcg_rules tcg_env ++ rules
  805. , tcg_vects = tcg_vects tcg_env ++ vects
  806. , tcg_anns = tcg_anns tcg_env ++ annotations
  807. , tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls
  808. , tcg_dus = tcg_dus tcg_env `plusDU` usesOnly fo_fvs } } ;
  809. -- tcg_dus: see Note [Newtype constructor usage in foreign declarations]
  810. addUsedRdrNames fo_rdr_names ;
  811. traceTc "Tc8: type_env: " (ppr $ nameEnvElts $ tcg_type_env tcg_env') ; -- RAE
  812. return (tcg_env', tcl_env)
  813. }}}}}}
  814. where
  815. gre_to_rdr_name :: GlobalRdrElt -> [RdrName] -> [RdrName]
  816. -- For *imported* newtype data constructors, we want to
  817. -- make sure that at least one of the imports for them is used
  818. -- See Note [Newtype constructor usage in foreign declarations]
  819. gre_to_rdr_name gre rdrs
  820. = case gre_prov gre of
  821. LocalDef -> rdrs
  822. Imported [] -> panic "gre_to_rdr_name: Imported []"
  823. Imported (is : _) -> mkRdrQual modName occName : rdrs
  824. where
  825. modName = is_as (is_decl is)
  826. occName = nameOccName (gre_name gre)
  827. ---------------------------
  828. tcTyClsInstDecls :: ModDetails
  829. -> [TyClGroup Name]
  830. -> [LInstDecl Name]
  831. -> [LDerivDecl Name]
  832. -> TcM (TcGblEnv, -- The full inst env
  833. [InstInfo Name], -- Source-code instance decls to process;
  834. -- contains all dfuns for this module
  835. HsValBinds Name) -- Supporting bindings for derived instances
  836. tcTyClsInstDecls boot_details tycl_decls inst_decls deriv_decls
  837. = tcExtendTcTyThingEnv [(con, APromotionErr FamDataConPE)
  838. | lid <- inst_decls, con <- get_cons lid ] $
  839. -- Note [AFamDataCon: not promoting data family constructors]
  840. do { tcg_env <- tcTyAndClassDecls boot_details tycl_decls ;
  841. ; setGblEnv tcg_env $
  842. tcInstDecls1 (concat tycl_decls) inst_decls deriv_decls }
  843. where
  844. -- get_cons extracts the *constructor* bindings of the declaration
  845. get_cons :: LInstDecl Name -> [Name]
  846. get_cons (L _ (TyFamInstD {})) = []
  847. get_cons (L _ (DataFamInstD { dfid_inst = fid })) = get_fi_cons fid
  848. get_cons (L _ (ClsInstD { cid_inst = ClsInstDecl { cid_datafam_insts = fids } }))
  849. = concatMap (get_fi_cons . unLoc) fids
  850. get_fi_cons :: DataFamInstDecl Name -> [Name]
  851. get_fi_cons (DataFamInstDecl { dfid_defn = HsDataDefn { dd_cons = cons } })
  852. = map (unLoc . con_name . unLoc) cons
  853. \end{code}
  854. Note [AFamDataCon: not promoting data family constructors]
  855. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  856. Consider
  857. data family T a
  858. data instance T Int = MkT
  859. data Proxy (a :: k)
  860. data S = MkS (Proxy 'MkT)
  861. Is it ok to use the promoted data family instance constructor 'MkT' in
  862. the data declaration for S? No, we don't allow this. It *might* make
  863. sense, but at least it would mean that we'd have to interleave
  864. typechecking instances and data types, whereas at present we do data
  865. types *then* instances.
  866. So to check for this we put in the TcLclEnv a binding for all the family
  867. constructors, bound to AFamDataCon, so that if we trip over 'MkT' when
  868. type checking 'S' we'll produce a decent error message.
  869. %************************************************************************
  870. %* *
  871. Checking for 'main'
  872. %* *
  873. %************************************************************************
  874. \begin{code}
  875. checkMain :: TcM TcGblEnv
  876. -- If we are in module Main, check that 'main' is defined.
  877. checkMain
  878. = do { tcg_env <- getGblEnv ;
  879. dflags <- getDynFlags ;
  880. check_main dflags tcg_env
  881. }
  882. check_main :: DynFlags -> TcGblEnv -> TcM TcGblEnv
  883. check_main dflags tcg_env
  884. | mod /= main_mod
  885. = traceTc "checkMain not" (ppr main_mod <+> ppr mod) >>
  886. return tcg_env
  887. | otherwise
  888. = do { mb_main <- lookupGlobalOccRn_maybe main_fn
  889. -- Check that 'main' is in scope
  890. -- It might be imported from another module!
  891. ; case mb_main of {
  892. Nothing -> do { traceTc "checkMain fail" (ppr main_mod <+> ppr main_fn)
  893. ; complain_no_main
  894. ; return tcg_env } ;
  895. Just main_name -> do
  896. { traceTc "checkMain found" (ppr main_mod <+> ppr main_fn)
  897. ; let loc = srcLocSpan (getSrcLoc main_name)
  898. ; ioTyCon <- tcLookupTyCon ioTyConName
  899. ; res_ty <- newFlexiTyVarTy liftedTypeKind
  900. ; main_expr
  901. <- addErrCtxt mainCtxt $
  902. tcMonoExpr (L loc (HsVar main_name)) (mkTyConApp ioTyCon [res_ty])
  903. -- See Note [Root-main Id]
  904. -- Construct the binding
  905. -- :Main.main :: IO res_ty = runMainIO res_ty main
  906. ; run_main_id <- tcLookupId runMainIOName
  907. ; let { root_main_name = mkExternalName rootMainKey rOOT_MAIN
  908. (mkVarOccFS (fsLit "main"))
  909. (getSrcSpan main_name)
  910. ; root_main_id = Id.mkExportedLocalId root_main_name
  911. (mkTyConApp ioTyCon [res_ty])
  912. ; co = mkWpTyApps [res_ty]
  913. ; rhs = nlHsApp (mkLHsWrap co (nlHsVar run_main_id)) main_expr
  914. ; main_bind = mkVarBind root_main_id rhs }
  915. ; return (tcg_env { tcg_main = Just main_name,
  916. tcg_binds = tcg_binds tcg_env
  917. `snocBag` main_bind,
  918. tcg_dus = tcg_dus tcg_env
  919. `plusDU` usesOnly (unitFV main_name)
  920. -- Record the use of 'main', so that we don't
  921. -- complain about it being defined but not used
  922. })
  923. }}}
  924. where
  925. mod = tcg_mod tcg_env
  926. main_mod = mainModIs dflags
  927. main_fn = getMainFun dflags
  928. complain_no_main | ghcLink dflags == LinkInMemory = return ()
  929. | otherwise = failWithTc noMainMsg
  930. -- In interactive mode, don't worry about the absence of 'main'
  931. -- In other modes, fail altogether, so that we don't go on
  932. -- and complain a second time when processing the export list.
  933. mainCtxt = ptext (sLit "When checking the type of the") <+> pp_main_fn
  934. noMainMsg = ptext (sLit "The") <+> pp_main_fn
  935. <+> ptext (sLit "is not defined in module") <+> quotes (ppr main_mod)
  936. pp_main_fn = ppMainFn main_fn
  937. -- | Get the unqualified name of the function to use as the \"main\" for the main module.
  938. -- Either returns the default name or the one configured on the command line with -main-is
  939. getMainFun :: DynFlags -> RdrName
  940. getMainFun dflags = case mainFunIs dflags of
  941. Just fn -> mkRdrUnqual (mkVarOccFS (mkFastString fn))
  942. Nothing -> main_RDR_Unqual
  943. checkMainExported :: TcGblEnv -> TcM ()
  944. checkMainExported tcg_env
  945. = case tcg_main tcg_env of
  946. Nothing -> return () -- not the main module
  947. Just main_name ->
  948. do { dflags <- getDynFlags
  949. ; let main_mod = mainModIs dflags
  950. ; checkTc (main_name `elem` concatMap availNames (tcg_exports tcg_env)) $
  951. ptext (sLit "The") <+> ppMainFn (nameRdrName main_name) <+>
  952. ptext (sLit "is not exported by module") <+> quotes (ppr main_mod) }
  953. ppMainFn :: RdrName -> SDoc
  954. ppMainFn main_fn
  955. | rdrNameOcc main_fn == mainOcc
  956. = ptext (sLit "IO action") <+> quotes (ppr main_fn)
  957. | otherwise
  958. = ptext (sLit "main IO action") <+> quotes (ppr main_fn)
  959. mainOcc :: OccName
  960. mainOcc = mkVarOccFS (fsLit "main")
  961. \end{code}
  962. Note [Root-main Id]
  963. ~~~~~~~~~~~~~~~~~~~
  964. The function that the RTS invokes is always :Main.main, which we call
  965. root_main_id. (Because GHC allows the user to have a module not
  966. called Main as the main module, we can't rely on the main function
  967. being called "Main.main". That's why root_main_id has a fixed module
  968. ":Main".)
  969. This is unusual: it's a LocalId whose Name has a Module from another
  970. module. Tiresomely, we must filter it out again in MkIface, les we
  971. get two defns for 'main' in the interface file!
  972. %*********************************************************
  973. %* *
  974. GHCi stuff
  975. %* *
  976. %*********************************************************
  977. \begin{code}
  978. setInteractiveContext :: HscEnv -> InteractiveContext -> TcRn a -> TcRn a
  979. setInteractiveContext hsc_env icxt thing_inside
  980. = let -- Initialise the tcg_inst_env with instances from all home modules.
  981. -- This mimics the more selective call to hptInstances in tcRnImports
  982. (home_insts, home_fam_insts) = hptInstances hsc_env (\_ -> True)
  983. (ic_insts, ic_finsts) = ic_instances icxt
  984. -- Note [GHCi temporary Ids]
  985. -- Ideally we would just make a type_env from ic_tythings
  986. -- and ic_sys_vars, adding in implicit things. However, Ids
  987. -- bound interactively might have some free type variables
  988. -- (RuntimeUnk things), and if we don't register these free
  989. -- TyVars as global TyVars then the typechecker will try to
  990. -- quantify over them and fall over in zonkQuantifiedTyVar.
  991. --
  992. -- So we must add any free TyVars to the typechecker's global
  993. -- TyVar set. This is what happens when the local environment
  994. -- is extended, so we use tcExtendGhciEnv below which extends
  995. -- the local environment with the Ids.
  996. --
  997. -- However, any Ids bound this way will shadow other Ids in
  998. -- the GlobalRdrEnv, so we have to be careful to only add Ids
  999. -- which are visible in the GlobalRdrEnv.
  1000. --
  1001. -- Perhaps it would be better to just extend the global TyVar
  1002. -- list from the free tyvars in the Ids here? Anyway, at least
  1003. -- this hack is localised.
  1004. --
  1005. -- Note [delete shadowed tcg_rdr_env entries]
  1006. -- We also *delete* entries from tcg_rdr_env that we have
  1007. -- shadowed in the local env (see above). This isn't strictly
  1008. -- necessary, but in an out-of-scope error when GHC suggests
  1009. -- names it can be confusing to see multiple identical
  1010. -- entries. (#5564)
  1011. --
  1012. (tmp_ids, types_n_classes) = partitionWith sel_id (ic_tythings icxt)
  1013. where sel_id (AnId id) = Left id
  1014. sel_id other = Right other
  1015. type_env = mkTypeEnvWithImplicits
  1016. (map AnId (ic_sys_vars icxt) ++ types_n_classes)
  1017. visible_tmp_ids = filter visible tmp_ids
  1018. where visible id = not (null (lookupGRE_Name (ic_rn_gbl_env icxt)
  1019. (idName id)))
  1020. con_fields = [ (dataConName c, dataConFieldLabels c)
  1021. | ATyCon t <- types_n_classes
  1022. , c <- tyConDataCons t ]
  1023. in
  1024. updGblEnv (\env -> env {
  1025. tcg_rdr_env = delListFromOccEnv (ic_rn_gbl_env icxt)
  1026. (map getOccName vi…

Large files files are truncated, but you can click here to view the full file