PageRenderTime 59ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/ghc-7.4.1/compiler/typecheck/TcRnDriver.lhs

#
Haskell | 1796 lines | 1163 code | 277 blank | 356 comment | 38 complexity | 07bd2fd62ae24e16b12c17fc4f317ce9 MD5 | raw file
Possible License(s): LGPL-3.0, BSD-3-Clause, BSD-2-Clause

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

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