PageRenderTime 75ms CodeModel.GetById 39ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/typecheck/TcRnDriver.lhs

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

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