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

/compiler/typecheck/TcRnDriver.lhs

https://bitbucket.org/carter/ghc
Haskell | 1895 lines | 1241 code | 281 blank | 373 comment | 39 complexity | fb42482014db1d55220cc1c3ac35552f 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 TypeRep
  26. import DynFlags
  27. import StaticFlags
  28. import HsSyn
  29. import PrelNames
  30. import RdrName
  31. import TcHsSyn
  32. import TcExpr
  33. import TcRnMonad
  34. import TcEvidence
  35. import Coercion( pprCoAxiom )
  36. import FamInst
  37. import InstEnv
  38. import FamInstEnv
  39. import TcAnnotations
  40. import TcBinds
  41. import HeaderInfo ( mkPrelImports )
  42. import TcType ( tidyTopType )
  43. import TcDefaults
  44. import TcEnv
  45. import TcRules
  46. import TcForeign
  47. import TcInstDcls
  48. import TcIface
  49. import TcMType
  50. import MkIface
  51. import IfaceSyn
  52. import TcSimplify
  53. import TcTyClsDecls
  54. import LoadIface
  55. import RnNames
  56. import RnEnv
  57. import RnSource
  58. import PprCore
  59. import CoreSyn
  60. import ErrUtils
  61. import Id
  62. import VarEnv
  63. import Module
  64. import UniqFM
  65. import Name
  66. import NameEnv
  67. import NameSet
  68. import Avail
  69. import TyCon
  70. import SrcLoc
  71. import HscTypes
  72. import ListSetOps
  73. import Outputable
  74. import DataCon
  75. import Type
  76. import Class
  77. import TcType ( orphNamesOfDFunHead )
  78. import Inst ( tcGetInstEnvs )
  79. import Data.List ( sortBy )
  80. import Data.IORef ( readIORef )
  81. import Data.Ord
  82. #ifdef GHCI
  83. import TcType ( isUnitTy, isTauTy )
  84. import TcHsType
  85. import TcMatches
  86. import RnTypes
  87. import RnExpr
  88. import MkId
  89. import BasicTypes
  90. import TidyPgm ( globaliseAndTidyId )
  91. import TysWiredIn ( unitTy, mkListTy )
  92. #endif
  93. import FastString
  94. import Maybes
  95. import Util
  96. import Bag
  97. import Control.Monad
  98. #include "HsVersions.h"
  99. \end{code}
  100. %************************************************************************
  101. %* *
  102. Typecheck and rename a module
  103. %* *
  104. %************************************************************************
  105. \begin{code}
  106. -- | Top level entry point for typechecker and renamer
  107. tcRnModule :: HscEnv
  108. -> HscSource
  109. -> Bool -- True <=> save renamed syntax
  110. -> HsParsedModule
  111. -> IO (Messages, Maybe TcGblEnv)
  112. tcRnModule hsc_env hsc_src save_rn_syntax
  113. HsParsedModule {
  114. hpm_module =
  115. (L loc (HsModule maybe_mod export_ies
  116. import_decls local_decls mod_deprec
  117. maybe_doc_hdr)),
  118. hpm_src_files =
  119. src_files
  120. }
  121. = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
  122. let { this_pkg = thisPackage (hsc_dflags hsc_env) ;
  123. (this_mod, prel_imp_loc)
  124. = case maybe_mod of
  125. Nothing -- 'module M where' is omitted
  126. -> (mAIN, srcLocSpan (srcSpanStart loc))
  127. Just (L mod_loc mod) -- The normal case
  128. -> (mkModule this_pkg mod, mod_loc) } ;
  129. initTc hsc_env hsc_src save_rn_syntax this_mod $
  130. setSrcSpan loc $
  131. do { -- Deal with imports; first add implicit prelude
  132. implicit_prelude <- xoptM Opt_ImplicitPrelude;
  133. let { prel_imports = mkPrelImports (moduleName this_mod) prel_imp_loc
  134. implicit_prelude import_decls } ;
  135. ifWOptM Opt_WarnImplicitPrelude $
  136. when (notNull prel_imports) $ addWarn (implicitPreludeWarn) ;
  137. tcg_env <- {-# SCC "tcRnImports" #-}
  138. tcRnImports hsc_env this_mod (prel_imports ++ import_decls) ;
  139. -- If the whole module is warned about or deprecated
  140. -- (via mod_deprec) record that in tcg_warns. If we do thereby add
  141. -- a WarnAll, it will override any subseqent depracations added to tcg_warns
  142. let { tcg_env1 = case mod_deprec of
  143. Just txt -> tcg_env { tcg_warns = WarnAll txt }
  144. Nothing -> tcg_env
  145. } ;
  146. setGblEnv tcg_env1 $ do {
  147. -- Load the hi-boot interface for this module, if any
  148. -- We do this now so that the boot_names can be passed
  149. -- to tcTyAndClassDecls, because the boot_names are
  150. -- automatically considered to be loop breakers
  151. --
  152. -- Do this *after* tcRnImports, so that we know whether
  153. -- a module that we import imports us; and hence whether to
  154. -- look for a hi-boot file
  155. boot_iface <- tcHiBootIface hsc_src this_mod ;
  156. -- Rename and type check the declarations
  157. traceRn (text "rn1a") ;
  158. tcg_env <- if isHsBoot hsc_src then
  159. tcRnHsBootDecls local_decls
  160. else
  161. {-# SCC "tcRnSrcDecls" #-}
  162. tcRnSrcDecls boot_iface local_decls ;
  163. setGblEnv tcg_env $ do {
  164. -- Process the export list
  165. traceRn (text "rn4a: before exports");
  166. tcg_env <- rnExports (isJust maybe_mod) export_ies tcg_env ;
  167. traceRn (text "rn4b: after exports") ;
  168. -- Check that main is exported (must be after rnExports)
  169. checkMainExported tcg_env ;
  170. -- Compare the hi-boot iface (if any) with the real thing
  171. -- Must be done after processing the exports
  172. tcg_env <- checkHiBootIface tcg_env boot_iface ;
  173. -- The new type env is already available to stuff slurped from
  174. -- interface files, via TcEnv.updateGlobalTypeEnv
  175. -- It's important that this includes the stuff in checkHiBootIface,
  176. -- because the latter might add new bindings for boot_dfuns,
  177. -- which may be mentioned in imported unfoldings
  178. -- Don't need to rename the Haddock documentation,
  179. -- it's not parsed by GHC anymore.
  180. tcg_env <- return (tcg_env { tcg_doc_hdr = maybe_doc_hdr }) ;
  181. -- Report unused names
  182. reportUnusedNames export_ies tcg_env ;
  183. -- add extra source files to tcg_dependent_files
  184. addDependentFiles src_files ;
  185. -- Dump output and return
  186. tcDump tcg_env ;
  187. return tcg_env
  188. }}}}
  189. implicitPreludeWarn :: SDoc
  190. implicitPreludeWarn
  191. = ptext (sLit "Module `Prelude' implicitly imported")
  192. \end{code}
  193. %************************************************************************
  194. %* *
  195. Import declarations
  196. %* *
  197. %************************************************************************
  198. \begin{code}
  199. tcRnImports :: HscEnv -> Module
  200. -> [LImportDecl RdrName] -> TcM TcGblEnv
  201. tcRnImports hsc_env this_mod import_decls
  202. = do { (rn_imports, rdr_env, imports,hpc_info) <- rnImports import_decls ;
  203. ; let { dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface)
  204. -- Make sure we record the dependencies from the DynFlags in the EPS or we
  205. -- end up hitting the sanity check in LoadIface.loadInterface that
  206. -- checks for unknown home-package modules being loaded. We put
  207. -- these dependencies on the left so their (non-source) imports
  208. -- take precedence over the (possibly-source) imports on the right.
  209. -- We don't add them to any other field (e.g. the imp_dep_mods of
  210. -- imports) because we don't want to load their instances etc.
  211. ; dep_mods = listToUFM [(mod_nm, (mod_nm, False)) | mod_nm <- dynFlagDependencies (hsc_dflags hsc_env)]
  212. `plusUFM` imp_dep_mods imports
  213. -- We want instance declarations from all home-package
  214. -- modules below this one, including boot modules, except
  215. -- ourselves. The 'except ourselves' is so that we don't
  216. -- get the instances from this module's hs-boot file
  217. ; want_instances :: ModuleName -> Bool
  218. ; want_instances mod = mod `elemUFM` dep_mods
  219. && mod /= moduleName this_mod
  220. ; (home_insts, home_fam_insts) = hptInstances hsc_env
  221. want_instances
  222. } ;
  223. -- Record boot-file info in the EPS, so that it's
  224. -- visible to loadHiBootInterface in tcRnSrcDecls,
  225. -- and any other incrementally-performed imports
  226. ; updateEps_ (\eps -> eps { eps_is_boot = dep_mods }) ;
  227. -- Update the gbl env
  228. ; updGblEnv ( \ gbl ->
  229. gbl {
  230. tcg_rdr_env = plusOccEnv (tcg_rdr_env gbl) rdr_env,
  231. tcg_imports = tcg_imports gbl `plusImportAvails` imports,
  232. tcg_rn_imports = rn_imports,
  233. tcg_inst_env = extendInstEnvList (tcg_inst_env gbl) home_insts,
  234. tcg_fam_inst_env = extendFamInstEnvList (tcg_fam_inst_env gbl)
  235. home_fam_insts,
  236. tcg_hpc = hpc_info
  237. }) $ do {
  238. ; traceRn (text "rn1" <+> ppr (imp_dep_mods imports))
  239. -- Fail if there are any errors so far
  240. -- The error printing (if needed) takes advantage
  241. -- of the tcg_env we have now set
  242. -- ; traceIf (text "rdr_env: " <+> ppr rdr_env)
  243. ; failIfErrsM
  244. -- Load any orphan-module and family instance-module
  245. -- interfaces, so that their rules and instance decls will be
  246. -- found.
  247. ; loadModuleInterfaces (ptext (sLit "Loading orphan modules"))
  248. (imp_orphs imports)
  249. -- Check type-family consistency
  250. ; traceRn (text "rn1: checking family instance consistency")
  251. ; let { dir_imp_mods = moduleEnvKeys
  252. . imp_mods
  253. $ imports }
  254. ; checkFamInstConsistency (imp_finsts imports) dir_imp_mods ;
  255. ; getGblEnv } }
  256. \end{code}
  257. %************************************************************************
  258. %* *
  259. Type-checking external-core modules
  260. %* *
  261. %************************************************************************
  262. \begin{code}
  263. tcRnExtCore :: HscEnv
  264. -> HsExtCore RdrName
  265. -> IO (Messages, Maybe ModGuts)
  266. -- Nothing => some error occurred
  267. tcRnExtCore hsc_env (HsExtCore this_mod decls src_binds)
  268. -- The decls are IfaceDecls; all names are original names
  269. = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
  270. initTc hsc_env ExtCoreFile False this_mod $ do {
  271. let { ldecls = map noLoc decls } ;
  272. -- Bring the type and class decls into scope
  273. -- ToDo: check that this doesn't need to extract the val binds.
  274. -- It seems that only the type and class decls need to be in scope below because
  275. -- (a) tcTyAndClassDecls doesn't need the val binds, and
  276. -- (b) tcExtCoreBindings doesn't need anything
  277. -- (in fact, it might not even need to be in the scope of
  278. -- this tcg_env at all)
  279. (tc_envs, _bndrs) <- getLocalNonValBinders emptyFsEnv {- no fixity decls -}
  280. (mkFakeGroup ldecls) ;
  281. setEnvs tc_envs $ do {
  282. (rn_decls, _fvs) <- checkNoErrs $ rnTyClDecls [] [ldecls] ;
  283. -- The empty list is for extra dependencies coming from .hs-boot files
  284. -- See Note [Extra dependencies from .hs-boot files] in RnSource
  285. -- Dump trace of renaming part
  286. rnDump (ppr rn_decls) ;
  287. -- Typecheck them all together so that
  288. -- any mutually recursive types are done right
  289. -- Just discard the auxiliary bindings; they are generated
  290. -- only for Haskell source code, and should already be in Core
  291. tcg_env <- tcTyAndClassDecls emptyModDetails rn_decls ;
  292. safe_mode <- liftIO $ finalSafeMode (hsc_dflags hsc_env) tcg_env ;
  293. dep_files <- liftIO $ readIORef (tcg_dependent_files tcg_env) ;
  294. setGblEnv tcg_env $ do {
  295. -- Make the new type env available to stuff slurped from interface files
  296. -- Now the core bindings
  297. core_binds <- initIfaceExtCore (tcExtCoreBindings src_binds) ;
  298. -- Wrap up
  299. let {
  300. bndrs = bindersOfBinds core_binds ;
  301. my_exports = map (Avail . idName) bndrs ;
  302. -- ToDo: export the data types also?
  303. mod_guts = ModGuts { mg_module = this_mod,
  304. mg_boot = False,
  305. mg_used_names = emptyNameSet, -- ToDo: compute usage
  306. mg_used_th = False,
  307. mg_dir_imps = emptyModuleEnv, -- ??
  308. mg_deps = noDependencies, -- ??
  309. mg_exports = my_exports,
  310. mg_tcs = tcg_tcs tcg_env,
  311. mg_insts = tcg_insts tcg_env,
  312. mg_fam_insts = tcg_fam_insts tcg_env,
  313. mg_inst_env = tcg_inst_env tcg_env,
  314. mg_fam_inst_env = tcg_fam_inst_env tcg_env,
  315. mg_rules = [],
  316. mg_vect_decls = [],
  317. mg_anns = [],
  318. mg_binds = core_binds,
  319. -- Stubs
  320. mg_rdr_env = emptyGlobalRdrEnv,
  321. mg_fix_env = emptyFixityEnv,
  322. mg_warns = NoWarnings,
  323. mg_foreign = NoStubs,
  324. mg_hpc_info = emptyHpcInfo False,
  325. mg_modBreaks = emptyModBreaks,
  326. mg_vect_info = noVectInfo,
  327. mg_safe_haskell = safe_mode,
  328. mg_trust_pkg = False,
  329. mg_dependent_files = dep_files
  330. } } ;
  331. tcCoreDump mod_guts ;
  332. return mod_guts
  333. }}}}
  334. mkFakeGroup :: [LTyClDecl a] -> HsGroup a
  335. mkFakeGroup decls -- Rather clumsy; lots of unused fields
  336. = emptyRdrGroup { hs_tyclds = [decls] }
  337. \end{code}
  338. %************************************************************************
  339. %* *
  340. Type-checking the top level of a module
  341. %* *
  342. %************************************************************************
  343. \begin{code}
  344. tcRnSrcDecls :: ModDetails -> [LHsDecl RdrName] -> TcM TcGblEnv
  345. -- Returns the variables free in the decls
  346. -- Reason: solely to report unused imports and bindings
  347. tcRnSrcDecls boot_iface decls
  348. = do { -- Do all the declarations
  349. ((tcg_env, tcl_env), lie) <- captureConstraints $ tc_rn_src_decls boot_iface decls ;
  350. ; traceTc "Tc8" empty ;
  351. ; setEnvs (tcg_env, tcl_env) $
  352. do {
  353. -- Finish simplifying class constraints
  354. --
  355. -- simplifyTop deals with constant or ambiguous InstIds.
  356. -- How could there be ambiguous ones? They can only arise if a
  357. -- top-level decl falls under the monomorphism restriction
  358. -- and no subsequent decl instantiates its type.
  359. --
  360. -- We do this after checkMain, so that we use the type info
  361. -- that checkMain adds
  362. --
  363. -- We do it with both global and local env in scope:
  364. -- * the global env exposes the instances to simplifyTop
  365. -- * the local env exposes the local Ids to simplifyTop,
  366. -- so that we get better error messages (monomorphism restriction)
  367. new_ev_binds <- {-# SCC "simplifyTop" #-}
  368. simplifyTop lie ;
  369. traceTc "Tc9" empty ;
  370. failIfErrsM ; -- Don't zonk if there have been errors
  371. -- It's a waste of time; and we may get debug warnings
  372. -- about strangely-typed TyCons!
  373. -- Zonk the final code. This must be done last.
  374. -- Even simplifyTop may do some unification.
  375. -- This pass also warns about missing type signatures
  376. let { TcGblEnv { tcg_type_env = type_env,
  377. tcg_binds = binds,
  378. tcg_sigs = sig_ns,
  379. tcg_ev_binds = cur_ev_binds,
  380. tcg_imp_specs = imp_specs,
  381. tcg_rules = rules,
  382. tcg_vects = vects,
  383. tcg_fords = fords } = tcg_env
  384. ; all_ev_binds = cur_ev_binds `unionBags` new_ev_binds } ;
  385. (bind_ids, ev_binds', binds', fords', imp_specs', rules', vects')
  386. <- {-# SCC "zonkTopDecls" #-}
  387. zonkTopDecls all_ev_binds binds sig_ns rules vects imp_specs fords ;
  388. let { final_type_env = extendTypeEnvWithIds type_env bind_ids
  389. ; tcg_env' = tcg_env { tcg_binds = binds',
  390. tcg_ev_binds = ev_binds',
  391. tcg_imp_specs = imp_specs',
  392. tcg_rules = rules',
  393. tcg_vects = vects',
  394. tcg_fords = fords' } } ;
  395. setGlobalTypeEnv tcg_env' final_type_env
  396. } }
  397. tc_rn_src_decls :: ModDetails
  398. -> [LHsDecl RdrName]
  399. -> TcM (TcGblEnv, TcLclEnv)
  400. -- Loops around dealing with each top level inter-splice group
  401. -- in turn, until it's dealt with the entire module
  402. tc_rn_src_decls boot_details ds
  403. = {-# SCC "tc_rn_src_decls" #-}
  404. do { (first_group, group_tail) <- findSplice ds ;
  405. -- If ds is [] we get ([], Nothing)
  406. -- The extra_deps are needed while renaming type and class declarations
  407. -- See Note [Extra dependencies from .hs-boot files] in RnSource
  408. let { extra_deps = map tyConName (typeEnvTyCons (md_types boot_details)) } ;
  409. -- Deal with decls up to, but not including, the first splice
  410. (tcg_env, rn_decls) <- rnTopSrcDecls extra_deps first_group ;
  411. -- rnTopSrcDecls fails if there are any errors
  412. (tcg_env, tcl_env) <- setGblEnv tcg_env $
  413. tcTopSrcDecls boot_details rn_decls ;
  414. -- If there is no splice, we're nearly done
  415. setEnvs (tcg_env, tcl_env) $
  416. case group_tail of {
  417. Nothing -> do { tcg_env <- checkMain ; -- Check for `main'
  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 (ATD tvs1 ty_pats1 ty1 _loc1) (ATD tvs2 ty_pats2 ty2 _loc2)
  636. | Just env <- eqTyVarBndrs emptyRnEnv2 tvs1 tvs2
  637. = eqListBy (eqTypeX env) ty_pats1 ty_pats2 &&
  638. eqTypeX env ty1 ty2
  639. | otherwise = False
  640. eqFD (as1,bs1) (as2,bs2) =
  641. eqListBy (eqTypeX env) (mkTyVarTys as1) (mkTyVarTys as2) &&
  642. eqListBy (eqTypeX env) (mkTyVarTys bs1) (mkTyVarTys bs2)
  643. in
  644. -- Checks kind of class
  645. eqListBy eqFD clas_fds1 clas_fds2 &&
  646. (null sc_theta1 && null op_stuff1 && null ats1
  647. || -- Above tests for an "abstract" class
  648. eqListBy (eqPredX env) sc_theta1 sc_theta2 &&
  649. eqListBy eqSig op_stuff1 op_stuff2 &&
  650. eqListBy eqAT ats1 ats2)
  651. | Just syn_rhs1 <- synTyConRhs_maybe tc1
  652. , Just syn_rhs2 <- synTyConRhs_maybe tc2
  653. , Just env <- eqTyVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
  654. = ASSERT(tc1 == tc2)
  655. let eqSynRhs (SynFamilyTyCon o1 i1) (SynFamilyTyCon o2 i2)
  656. = o1==o2 && i1==i2
  657. eqSynRhs (SynonymTyCon t1) (SynonymTyCon t2)
  658. = eqTypeX env t1 t2
  659. eqSynRhs _ _ = False
  660. in
  661. eqSynRhs syn_rhs1 syn_rhs2
  662. | isAlgTyCon tc1 && isAlgTyCon tc2
  663. , Just env <- eqTyVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
  664. = ASSERT(tc1 == tc2)
  665. eqListBy (eqPredX env) (tyConStupidTheta tc1) (tyConStupidTheta tc2) &&
  666. eqAlgRhs (algTyConRhs tc1) (algTyConRhs tc2)
  667. | isForeignTyCon tc1 && isForeignTyCon tc2
  668. = eqKind (tyConKind tc1) (tyConKind tc2) &&
  669. tyConExtName tc1 == tyConExtName tc2
  670. | otherwise = False
  671. where
  672. eqAlgRhs (AbstractTyCon dis1) rhs2
  673. | dis1 = isDistinctAlgRhs rhs2 --Check compatibility
  674. | otherwise = True
  675. eqAlgRhs DataFamilyTyCon{} DataFamilyTyCon{} = True
  676. eqAlgRhs tc1@DataTyCon{} tc2@DataTyCon{} =
  677. eqListBy eqCon (data_cons tc1) (data_cons tc2)
  678. eqAlgRhs tc1@NewTyCon{} tc2@NewTyCon{} =
  679. eqCon (data_con tc1) (data_con tc2)
  680. eqAlgRhs _ _ = False
  681. eqCon c1 c2
  682. = dataConName c1 == dataConName c2
  683. && dataConIsInfix c1 == dataConIsInfix c2
  684. && dataConStrictMarks c1 == dataConStrictMarks c2
  685. && dataConFieldLabels c1 == dataConFieldLabels c2
  686. && eqType (dataConUserType c1) (dataConUserType c2)
  687. emptyRnEnv2 :: RnEnv2
  688. emptyRnEnv2 = mkRnEnv2 emptyInScopeSet
  689. ----------------
  690. missingBootThing :: Name -> String -> SDoc
  691. missingBootThing name what
  692. = ppr name <+> ptext (sLit "is exported by the hs-boot file, but not")
  693. <+> text what <+> ptext (sLit "the module")
  694. bootMisMatch :: TyThing -> IfaceDecl -> IfaceDecl -> SDoc
  695. bootMisMatch thing boot_decl real_decl
  696. = vcat [ppr thing <+> ptext (sLit "has conflicting definitions in the module and its hs-boot file"),
  697. ptext (sLit "Main module:") <+> ppr real_decl,
  698. ptext (sLit "Boot file: ") <+> ppr boot_decl]
  699. instMisMatch :: ClsInst -> SDoc
  700. instMisMatch inst
  701. = hang (ppr inst)
  702. 2 (ptext (sLit "is defined in the hs-boot file, but not in the module itself"))
  703. \end{code}
  704. %************************************************************************
  705. %* *
  706. Type-checking the top level of a module
  707. %* *
  708. %************************************************************************
  709. tcRnGroup takes a bunch of top-level source-code declarations, and
  710. * renames them
  711. * gets supporting declarations from interface files
  712. * typechecks them
  713. * zonks them
  714. * and augments the TcGblEnv with the results
  715. In Template Haskell it may be called repeatedly for each group of
  716. declarations. It expects there to be an incoming TcGblEnv in the
  717. monad; it augments it and returns the new TcGblEnv.
  718. \begin{code}
  719. ------------------------------------------------
  720. rnTopSrcDecls :: [Name] -> HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name)
  721. -- Fails if there are any errors
  722. rnTopSrcDecls extra_deps group
  723. = do { -- Rename the source decls
  724. traceTc "rn12" empty ;
  725. (tcg_env, rn_decls) <- checkNoErrs $ rnSrcDecls extra_deps group ;
  726. traceTc "rn13" empty ;
  727. -- save the renamed syntax, if we want it
  728. let { tcg_env'
  729. | Just grp <- tcg_rn_decls tcg_env
  730. = tcg_env{ tcg_rn_decls = Just (appendGroups grp rn_decls) }
  731. | otherwise
  732. = tcg_env };
  733. -- Dump trace of renaming part
  734. rnDump (ppr rn_decls) ;
  735. return (tcg_env', rn_decls)
  736. }
  737. ------------------------------------------------
  738. tcTopSrcDecls :: ModDetails -> HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
  739. tcTopSrcDecls boot_details
  740. (HsGroup { hs_tyclds = tycl_decls,
  741. hs_instds = inst_decls,
  742. hs_derivds = deriv_decls,
  743. hs_fords = foreign_decls,
  744. hs_defds = default_decls,
  745. hs_annds = annotation_decls,
  746. hs_ruleds = rule_decls,
  747. hs_vects = vect_decls,
  748. hs_valds = val_binds })
  749. = do { -- Type-check the type and class decls, and all imported decls
  750. -- The latter come in via tycl_decls
  751. traceTc "Tc2 (src)" empty ;
  752. -- Source-language instances, including derivings,
  753. -- and import the supporting declarations
  754. traceTc "Tc3" empty ;
  755. (tcg_env, inst_infos, deriv_binds)
  756. <- tcTyClsInstDecls boot_details tycl_decls inst_decls deriv_decls ;
  757. setGblEnv tcg_env $ do {
  758. -- Foreign import declarations next.
  759. traceTc "Tc4" empty ;
  760. (fi_ids, fi_decls) <- tcForeignImports foreign_decls ;
  761. tcExtendGlobalValEnv fi_ids $ do {
  762. -- Default declarations
  763. traceTc "Tc4a" empty ;
  764. default_tys <- tcDefaults default_decls ;
  765. updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
  766. -- Now GHC-generated derived bindings, generics, and selectors
  767. -- Do not generate warnings from compiler-generated code;
  768. -- hence the use of discardWarnings
  769. tc_envs <- discardWarnings (tcTopBinds deriv_binds) ;
  770. setEnvs tc_envs $ do {
  771. -- Value declarations next
  772. traceTc "Tc5" empty ;
  773. tc_envs@(tcg_env, tcl_env) <- tcTopBinds val_binds;
  774. setEnvs tc_envs $ do { -- Environment doesn't change now
  775. -- Second pass over class and instance declarations,
  776. -- now using the kind-checked decls
  777. traceTc "Tc6" empty ;
  778. inst_binds <- tcInstDecls2 (concat tycl_decls) inst_infos ;
  779. -- Foreign exports
  780. traceTc "Tc7" empty ;
  781. (foe_binds, foe_decls) <- tcForeignExports foreign_decls ;
  782. -- Annotations
  783. annotations <- tcAnnotations annotation_decls ;
  784. -- Rules
  785. rules <- tcRules rule_decls ;
  786. -- Vectorisation declarations
  787. vects <- tcVectDecls vect_decls ;
  788. -- Wrap up
  789. traceTc "Tc7a" empty ;
  790. let { all_binds = inst_binds `unionBags`
  791. foe_binds
  792. ; sig_names = mkNameSet (collectHsValBinders val_binds)
  793. `minusNameSet` getTypeSigNames val_binds
  794. -- Extend the GblEnv with the (as yet un-zonked)
  795. -- bindings, rules, foreign decls
  796. ; tcg_env' = tcg_env { tcg_binds = tcg_binds tcg_env `unionBags` all_binds
  797. , tcg_sigs = tcg_sigs tcg_env `unionNameSets` sig_names
  798. , tcg_rules = tcg_rules tcg_env ++ rules
  799. , tcg_vects = tcg_vects tcg_env ++ vects
  800. , tcg_anns = tcg_anns tcg_env ++ annotations
  801. , tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls } } ;
  802. return (tcg_env', tcl_env)
  803. }}}}}}
  804. ---------------------------
  805. tcTyClsInstDecls :: ModDetails
  806. -> [TyClGroup Name]
  807. -> [LInstDecl Name]
  808. -> [LDerivDecl Name]
  809. -> TcM (TcGblEnv, -- The full inst env
  810. [InstInfo Name], -- Source-code instance decls to process;
  811. -- contains all dfuns for this module
  812. HsValBinds Name) -- Supporting bindings for derived instances
  813. tcTyClsInstDecls boot_details tycl_decls inst_decls deriv_decls
  814. = tcExtendTcTyThingEnv [(con, APromotionErr FamDataConPE)
  815. | lid <- inst_decls, con <- get_cons lid ] $
  816. -- Note [AFamDataCon: not promoting data family constructors]
  817. do { tcg_env <- tcTyAndClassDecls boot_details tycl_decls ;
  818. ; setGblEnv tcg_env $
  819. tcInstDecls1 (concat tycl_decls) inst_decls deriv_decls }
  820. where
  821. -- get_cons extracts the *constructor* bindings of the declaration
  822. get_cons :: LInstDecl Name -> [Name]
  823. get_cons (L _ (FamInstD { lid_inst = fid })) = get_fi_cons fid
  824. get_cons (L _ (ClsInstD { cid_fam_insts = fids })) = concatMap (get_fi_cons . unLoc) fids
  825. get_fi_cons :: FamInstDecl Name -> [Name]
  826. get_fi_cons (FamInstDecl { fid_defn = TyData { td_cons = cons } })
  827. = map (unLoc . con_name . unLoc) cons
  828. get_fi_cons (FamInstDecl {}) = []
  829. \end{code}
  830. Note [AFamDataCon: not promoting data family constructors]
  831. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  832. Consider
  833. data family T a
  834. data instance T Int = MkT
  835. data Proxy (a :: k)
  836. data S = MkS (Proxy 'MkT)
  837. Is it ok to use the promoted data family instance constructor 'MkT' in
  838. the data declaration for S? No, we don't allow this. It *might* make
  839. sense, but at least it would mean that we'd have to interleave
  840. typechecking instances and data types, whereas at present we do data
  841. types *then* instances.
  842. So to check for this we put in the TcLclEnv a binding for all the family
  843. constructors, bound to AFamDataCon, so that if we trip over 'MkT' when
  844. type checking 'S' we'll produce a decent error message.
  845. %************************************************************************
  846. %* *
  847. Checking for 'main'
  848. %* *
  849. %************************************************************************
  850. \begin{code}
  851. checkMain :: TcM TcGblEnv
  852. -- If we are in module Main, check that 'main' is defined.
  853. checkMain
  854. = do { tcg_env <- getGblEnv ;
  855. dflags <- getDynFlags ;
  856. check_main dflags tcg_env
  857. }
  858. check_main :: DynFlags -> TcGblEnv -> TcM TcGblEnv
  859. check_main dflags tcg_env
  860. | mod /= main_mod
  861. = traceTc "checkMain not" (ppr main_mod <+> ppr mod) >>
  862. return tcg_env
  863. | otherwise
  864. = do { mb_main <- lookupGlobalOccRn_maybe main_fn
  865. -- Check that 'main' is in scope
  866. -- It might be imported from another module!
  867. ; case mb_main of {
  868. Nothing -> do { traceTc "checkMain fail" (ppr main_mod <+> ppr main_fn)
  869. ; complain_no_main
  870. ; return tcg_env } ;
  871. Just main_name -> do
  872. { traceTc "checkMain found" (ppr main_mod <+> ppr main_fn)
  873. ; let loc = srcLocSpan (getSrcLoc main_name)
  874. ; ioTyCon <- tcLookupTyCon ioTyConName
  875. ; res_ty <- newFlexiTyVarTy liftedTypeKind
  876. ; main_expr
  877. <- addErrCtxt mainCtxt $
  878. tcMonoExpr (L loc (HsVar main_name)) (mkTyConApp ioTyCon [res_ty])
  879. -- See Note [Root-main Id]
  880. -- Construct the binding
  881. -- :Main.main :: IO res_ty = runMainIO res_ty main
  882. ; run_main_id <- tcLookupId runMainIOName
  883. ; let { root_main_name = mkExternalName rootMainKey rOOT_MAIN
  884. (mkVarOccFS (fsLit "main"))
  885. (getSrcSpan main_name)
  886. ; root_main_id = Id.mkExportedLocalId root_main_name
  887. (mkTyConApp ioTyCon [res_ty])
  888. ; co = mkWpTyApps [res_ty]
  889. ; rhs = nlHsApp (mkLHsWrap co (nlHsVar run_main_id)) main_expr
  890. ; main_bind = mkVarBind root_main_id rhs }
  891. ; return (tcg_env { tcg_main = Just main_name,
  892. tcg_binds = tcg_binds tcg_env
  893. `snocBag` main_bind,
  894. tcg_dus = tcg_dus tcg_env
  895. `plusDU` usesOnly (unitFV main_name)
  896. -- Record the use of 'main', so that we don't
  897. -- complain about it being defined but not used
  898. })
  899. }}}
  900. where
  901. mod = tcg_mod tcg_env
  902. main_mod = mainModIs dflags
  903. main_fn = getMainFun dflags
  904. complain_no_main | ghcLink dflags == LinkInMemory = return ()
  905. | otherwise = failWithTc noMainMsg
  906. -- In interactive mode, don't worry about the absence of 'main'
  907. -- In other modes, fail altogether, so that we don't go on
  908. -- and complain a second time when processing the export list.
  909. mainCtxt = ptext (sLit "When checking the type of the") <+> pp_main_fn
  910. noMainMsg = ptext (sLit "The") <+> pp_main_fn
  911. <+> ptext (sLit "is not defined in module") <+> quotes (ppr main_mod)
  912. pp_main_fn = ppMainFn main_fn
  913. ppMainFn :: RdrName -> SDoc
  914. ppMainFn main_fn
  915. | main_fn == main_RDR_Unqual
  916. = ptext (sLit "function") <+> quotes (ppr main_fn)
  917. | otherwise
  918. = ptext (sLit "main function") <+> quotes (ppr main_fn)
  919. -- | Get the unqualified name of the function to use as the \"main\" for the main module.
  920. -- Either returns the default name or the one configured on the command line with -main-is
  921. getMainFun :: DynFlags -> RdrName
  922. getMainFun dflags = case (mainFunIs dflags) of
  923. Just fn -> mkRdrUnqual (mkVarOccFS (mkFastString fn))
  924. Nothing -> main_RDR_Unqual
  925. checkMainExported :: TcGblEnv -> TcM ()
  926. checkMainExported tcg_env = do
  927. dflags <- getDynFlags
  928. case tcg_main tcg_env of
  929. Nothing -> return () -- not the main module
  930. Just main_name -> do
  931. let main_mod = mainModIs dflags
  932. checkTc (main_name `elem` concatMap availNames (tcg_exports tcg_env)) $
  933. ptext (sLit "The") <+> ppMainFn (nameRdrName main_name) <+>
  934. ptext (sLit "is not exported by module") <+> quotes (ppr main_mod)
  935. \end{code}
  936. Note [Root-main Id]
  937. ~~~~~~~~~~~~~~~~~~~
  938. The function that the RTS invokes is always :Main.main, which we call
  939. root_main_id. (Because GHC allows the user to have a module not
  940. called Main as the main module, we can't rely on the main function
  941. being called "Main.main". That's why root_main_id has a fixed module
  942. ":Main".)
  943. This is unusual: it's a LocalId whose Name has a Module from another
  944. module. Tiresomely, we must filter it out again in MkIface, les we
  945. get two defns for 'main' in the interface file!
  946. %*********************************************************
  947. %* *
  948. GHCi stuff
  949. %* *
  950. %*********************************************************
  951. \begin{code}
  952. setInteractiveContext :: HscEnv -> InteractiveContext -> TcRn a -> TcRn a
  953. setInteractiveContext hsc_env icxt thing_inside
  954. = let -- Initialise the tcg_inst_env with instances from all home modules.
  955. -- This mimics the more selective call to hptInstances in tcRnImports
  956. (home_insts, home_fam_insts) = hptInstances hsc_env (\_ -> True)
  957. (ic_insts, ic_finsts) = ic_instances icxt
  958. -- Note [GHCi temporary Ids]
  959. -- Ideally we would just make a type_env from ic_tythings
  960. -- and ic_sys_vars, adding in implicit things. However, Ids
  961. -- bound interactively might have some free type variables
  962. -- (RuntimeUnk things), and if we don't register these free
  963. -- TyVars as global TyVars then the typechecker will try to
  964. -- quantify over them and fall over in zonkQuantifiedTyVar.
  965. --
  966. -- So we must add any free TyVars to the typechecker's global
  967. -- TyVar set. This is what happens when the local environment
  968. -- is extended, so we use tcExtendGhciEnv below which extends
  969. -- the local environment with the Ids.
  970. --
  971. -- However, any Ids bound this way will shadow other Ids in
  972. -- the GlobalRdrEnv, so we have to be careful to only add Ids
  973. -- which are visible in the GlobalRdrEnv.
  974. --
  975. -- Perhaps it would be better to just extend the global TyVar
  976. -- list from the free tyvars in the Ids here? Anyway, at least
  977. -- this hack is localised.
  978. --
  979. -- Note [delete shadowed tcg_rdr_env entries]
  980. -- We also *delete* entries from tcg_rdr_env that we have
  981. -- shadowed in the local env (see above). This isn't strictly
  982. -- necessary, but in an out-of-scope error when GHC suggests
  983. -- names it can be confusing to see multiple identical
  984. -- entries. (#5564)
  985. --
  986. (tmp_ids, types_n_classes) = partitionWith sel_id (ic_tythings icxt)
  987. where sel_id (AnId id) = Left id
  988. sel_id other = Right other
  989. type_env = mkTypeEnvWithImplicits
  990. (map AnId (ic_sys_vars icxt) ++ types_n_classes)
  991. visible_tmp_ids = filter visible tmp_ids
  992. where visible id = not (null (lookupGRE_Name (ic_rn_gbl_env icxt)
  993. (idName id)))
  994. con_fields = [ (dataConName c, dataConFieldLabels c)
  995. | ATyCon t <- types_n_classes
  996. , c <- tyConDataCons t ]
  997. in
  998. updGblEnv (\env -> env {
  999. tcg_rdr_env = delListFromOccEnv (ic_rn_gbl_env icxt)
  1000. (map getOccName visible_tmp_ids)
  1001. -- Note [delete shadowed tcg_rdr_env entries]
  1002. , tcg_type_env = type_env
  1003. , tcg_insts = ic_insts
  1004. , tcg_inst_env = extendInstEnvList
  1005. (extendInstEnvList (tcg_inst_env env) ic_insts)
  1006. home_insts
  1007. , tcg_fam_insts = ic_finsts
  1008. , tcg_fam_inst_env = extendFamInstEnvList
  1009. (extendFamInstEnvList (tcg_fam_inst_env env)
  1010. ic_finsts)
  1011. home_fam_insts
  1012. , tcg_field_env = RecFields (mkNameEnv con_fields)
  1013. (mkNameSet (concatMap snd con_fields))
  1014. -- setting tcg_field_env is necessary to make RecordWildCards work
  1015. -- (test: ghci049)
  1016. , tcg_fix_env = ic_fix_env icxt
  1017. , tcg_default = ic_default icxt
  1018. }) $
  1019. tcExtendGhciEnv visible_tmp_ids $ -- Note [GHCi temporary Ids]
  1020. thing_inside
  1021. #ifdef GHCI
  1022. -- | The returned [Id] is the list of new Ids bound by this statement. It can
  1023. -- be used to extend the InteractiveContext via extendInteractiveContext.
  1024. --
  1025. -- The returned TypecheckedHsExpr is of type IO [ () ], a list of the bound
  1026. -- values, coerced to ().
  1027. tcRnStmt :: HscEnv -> InteractiveContext -> GhciLStmt RdrName
  1028. -> IO (Messages, Maybe ([Id], LHsExpr Id, FixityEnv))
  1029. tcRnStmt hsc_env ictxt rdr_stmt
  1030. = initTcPrintErrors hsc_env iNTERACTIVE $
  1031. setInteractiveContext hsc_env ictxt $ do {
  1032. -- The real work is done here
  1033. ((bound_ids, tc_expr), fix_env) <- tcUse…

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