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

/compiler/typecheck/TcRnDriver.lhs

https://github.com/luite/ghc
Haskell | 1948 lines | 1281 code | 287 blank | 380 comment | 43 complexity | c0a582260af4f74b310c8d9de9b6e698 MD5 | raw file
  1. %
  2. % (c) The University of Glasgow 2006
  3. % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
  4. %
  5. \section[TcMovectle]{Typechecking a whole module}
  6. \begin{code}
  7. module TcRnDriver (
  8. #ifdef GHCI
  9. tcRnStmt, tcRnExpr, tcRnType,
  10. tcRnImportDecls,
  11. tcRnLookupRdrName,
  12. getModuleInterface,
  13. tcRnDeclsi,
  14. isGHCiMonad,
  15. #endif
  16. tcRnLookupName,
  17. tcRnGetInfo,
  18. tcRnModule,
  19. tcTopSrcDecls,
  20. tcRnExtCore
  21. ) where
  22. #ifdef GHCI
  23. import {-# SOURCE #-} TcSplice ( tcSpliceDecls )
  24. #endif
  25. import DynFlags
  26. import StaticFlags
  27. import HsSyn
  28. import PrelNames
  29. import RdrName
  30. import TcHsSyn
  31. import TcExpr
  32. import TcRnMonad
  33. import TcEvidence
  34. import Coercion( pprCoAxiom )
  35. import FamInst
  36. import InstEnv
  37. import FamInstEnv
  38. import TcAnnotations
  39. import TcBinds
  40. import HeaderInfo ( mkPrelImports )
  41. import TcDefaults
  42. import TcEnv
  43. import TcRules
  44. import TcForeign
  45. import TcInstDcls
  46. import TcIface
  47. import TcMType
  48. import MkIface
  49. import IfaceSyn
  50. import TcSimplify
  51. import TcTyClsDecls
  52. import LoadIface
  53. import RnNames
  54. import RnEnv
  55. import RnSource
  56. import PprCore
  57. import CoreSyn
  58. import ErrUtils
  59. import Id
  60. import VarEnv
  61. import Module
  62. import UniqFM
  63. import Name
  64. import NameEnv
  65. import NameSet
  66. import Avail
  67. import TyCon
  68. import SrcLoc
  69. import HscTypes
  70. import ListSetOps
  71. import Outputable
  72. import DataCon
  73. import Type
  74. import Class
  75. import CoAxiom ( CoAxBranch(..) )
  76. import Inst ( tcGetInstEnvs )
  77. import Data.List ( sortBy )
  78. import Data.IORef ( readIORef )
  79. import Data.Ord
  80. #ifdef GHCI
  81. import TcType ( isUnitTy, isTauTy )
  82. import TcHsType
  83. import TcMatches
  84. import RnTypes
  85. import RnExpr
  86. import MkId
  87. import BasicTypes
  88. import TidyPgm ( globaliseAndTidyId )
  89. import TysWiredIn ( unitTy, mkListTy )
  90. #endif
  91. import FastString
  92. import Maybes
  93. import Util
  94. import Bag
  95. import Control.Monad
  96. #include "HsVersions.h"
  97. \end{code}
  98. %************************************************************************
  99. %* *
  100. Typecheck and rename a module
  101. %* *
  102. %************************************************************************
  103. \begin{code}
  104. -- | Top level entry point for typechecker and renamer
  105. tcRnModule :: HscEnv
  106. -> HscSource
  107. -> Bool -- True <=> save renamed syntax
  108. -> HsParsedModule
  109. -> IO (Messages, Maybe TcGblEnv)
  110. tcRnModule hsc_env hsc_src save_rn_syntax
  111. HsParsedModule {
  112. hpm_module =
  113. (L loc (HsModule maybe_mod export_ies
  114. import_decls local_decls mod_deprec
  115. maybe_doc_hdr)),
  116. hpm_src_files =
  117. src_files
  118. }
  119. = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
  120. let { this_pkg = thisPackage (hsc_dflags hsc_env) ;
  121. (this_mod, prel_imp_loc)
  122. = case maybe_mod of
  123. Nothing -- 'module M where' is omitted
  124. -> (mAIN, srcLocSpan (srcSpanStart loc))
  125. Just (L mod_loc mod) -- The normal case
  126. -> (mkModule this_pkg mod, mod_loc) } ;
  127. initTc hsc_env hsc_src save_rn_syntax this_mod $
  128. setSrcSpan loc $
  129. do { -- Deal with imports; first add implicit prelude
  130. implicit_prelude <- xoptM Opt_ImplicitPrelude;
  131. let { prel_imports = mkPrelImports (moduleName this_mod) prel_imp_loc
  132. implicit_prelude import_decls } ;
  133. whenWOptM Opt_WarnImplicitPrelude $
  134. when (notNull prel_imports) $ addWarn (implicitPreludeWarn) ;
  135. tcg_env <- {-# SCC "tcRnImports" #-}
  136. tcRnImports hsc_env this_mod (prel_imports ++ import_decls) ;
  137. -- If the whole module is warned about or deprecated
  138. -- (via mod_deprec) record that in tcg_warns. If we do thereby add
  139. -- a WarnAll, it will override any subseqent depracations added to tcg_warns
  140. let { tcg_env1 = case mod_deprec of
  141. Just txt -> tcg_env { tcg_warns = WarnAll txt }
  142. Nothing -> tcg_env
  143. } ;
  144. setGblEnv tcg_env1 $ do {
  145. -- Load the hi-boot interface for this module, if any
  146. -- We do this now so that the boot_names can be passed
  147. -- to tcTyAndClassDecls, because the boot_names are
  148. -- automatically considered to be loop breakers
  149. --
  150. -- Do this *after* tcRnImports, so that we know whether
  151. -- a module that we import imports us; and hence whether to
  152. -- look for a hi-boot file
  153. boot_iface <- tcHiBootIface hsc_src this_mod ;
  154. -- Rename and type check the declarations
  155. traceRn (text "rn1a") ;
  156. tcg_env <- if isHsBoot hsc_src then
  157. tcRnHsBootDecls local_decls
  158. else
  159. {-# SCC "tcRnSrcDecls" #-}
  160. tcRnSrcDecls boot_iface local_decls ;
  161. setGblEnv tcg_env $ do {
  162. -- Process the export list
  163. traceRn (text "rn4a: before exports");
  164. tcg_env <- rnExports (isJust maybe_mod) export_ies tcg_env ;
  165. traceRn (text "rn4b: after exports") ;
  166. -- Check that main is exported (must be after rnExports)
  167. checkMainExported tcg_env ;
  168. -- Compare the hi-boot iface (if any) with the real thing
  169. -- Must be done after processing the exports
  170. tcg_env <- checkHiBootIface tcg_env boot_iface ;
  171. -- The new type env is already available to stuff slurped from
  172. -- interface files, via TcEnv.updateGlobalTypeEnv
  173. -- It's important that this includes the stuff in checkHiBootIface,
  174. -- because the latter might add new bindings for boot_dfuns,
  175. -- which may be mentioned in imported unfoldings
  176. -- Don't need to rename the Haddock documentation,
  177. -- it's not parsed by GHC anymore.
  178. tcg_env <- return (tcg_env { tcg_doc_hdr = maybe_doc_hdr }) ;
  179. -- Report unused names
  180. reportUnusedNames export_ies tcg_env ;
  181. -- add extra source files to tcg_dependent_files
  182. addDependentFiles src_files ;
  183. -- Dump output and return
  184. tcDump tcg_env ;
  185. return tcg_env
  186. }}}}
  187. implicitPreludeWarn :: SDoc
  188. implicitPreludeWarn
  189. = ptext (sLit "Module `Prelude' implicitly imported")
  190. \end{code}
  191. %************************************************************************
  192. %* *
  193. Import declarations
  194. %* *
  195. %************************************************************************
  196. \begin{code}
  197. tcRnImports :: HscEnv -> Module
  198. -> [LImportDecl RdrName] -> TcM TcGblEnv
  199. tcRnImports hsc_env this_mod import_decls
  200. = do { (rn_imports, rdr_env, imports,hpc_info) <- rnImports import_decls ;
  201. ; let { dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface)
  202. -- Make sure we record the dependencies from the DynFlags in the EPS or we
  203. -- end up hitting the sanity check in LoadIface.loadInterface that
  204. -- checks for unknown home-package modules being loaded. We put
  205. -- these dependencies on the left so their (non-source) imports
  206. -- take precedence over the (possibly-source) imports on the right.
  207. -- We don't add them to any other field (e.g. the imp_dep_mods of
  208. -- imports) because we don't want to load their instances etc.
  209. ; dep_mods = listToUFM [(mod_nm, (mod_nm, False)) | mod_nm <- dynFlagDependencies (hsc_dflags hsc_env)]
  210. `plusUFM` imp_dep_mods imports
  211. -- We want instance declarations from all home-package
  212. -- modules below this one, including boot modules, except
  213. -- ourselves. The 'except ourselves' is so that we don't
  214. -- get the instances from this module's hs-boot file
  215. ; want_instances :: ModuleName -> Bool
  216. ; want_instances mod = mod `elemUFM` dep_mods
  217. && mod /= moduleName this_mod
  218. ; (home_insts, home_fam_insts) = hptInstances hsc_env
  219. want_instances
  220. } ;
  221. -- Record boot-file info in the EPS, so that it's
  222. -- visible to loadHiBootInterface in tcRnSrcDecls,
  223. -- and any other incrementally-performed imports
  224. ; updateEps_ (\eps -> eps { eps_is_boot = dep_mods }) ;
  225. -- Update the gbl env
  226. ; updGblEnv ( \ gbl ->
  227. gbl {
  228. tcg_rdr_env = plusOccEnv (tcg_rdr_env gbl) rdr_env,
  229. tcg_imports = tcg_imports gbl `plusImportAvails` imports,
  230. tcg_rn_imports = rn_imports,
  231. tcg_inst_env = extendInstEnvList (tcg_inst_env gbl) home_insts,
  232. tcg_fam_inst_env = extendFamInstEnvList (tcg_fam_inst_env gbl)
  233. home_fam_insts,
  234. tcg_hpc = hpc_info
  235. }) $ do {
  236. ; traceRn (text "rn1" <+> ppr (imp_dep_mods imports))
  237. -- Fail if there are any errors so far
  238. -- The error printing (if needed) takes advantage
  239. -- of the tcg_env we have now set
  240. -- ; traceIf (text "rdr_env: " <+> ppr rdr_env)
  241. ; failIfErrsM
  242. -- Load any orphan-module and family instance-module
  243. -- interfaces, so that their rules and instance decls will be
  244. -- found.
  245. ; loadModuleInterfaces (ptext (sLit "Loading orphan modules"))
  246. (imp_orphs imports)
  247. -- Check type-family consistency
  248. ; traceRn (text "rn1: checking family instance consistency")
  249. ; let { dir_imp_mods = moduleEnvKeys
  250. . imp_mods
  251. $ imports }
  252. ; checkFamInstConsistency (imp_finsts imports) dir_imp_mods ;
  253. ; getGblEnv } }
  254. \end{code}
  255. %************************************************************************
  256. %* *
  257. Type-checking external-core modules
  258. %* *
  259. %************************************************************************
  260. \begin{code}
  261. tcRnExtCore :: HscEnv
  262. -> HsExtCore RdrName
  263. -> IO (Messages, Maybe ModGuts)
  264. -- Nothing => some error occurred
  265. tcRnExtCore hsc_env (HsExtCore this_mod decls src_binds)
  266. -- The decls are IfaceDecls; all names are original names
  267. = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
  268. initTc hsc_env ExtCoreFile False this_mod $ do {
  269. let { ldecls = map noLoc decls } ;
  270. -- Bring the type and class decls into scope
  271. -- ToDo: check that this doesn't need to extract the val binds.
  272. -- It seems that only the type and class decls need to be in scope below because
  273. -- (a) tcTyAndClassDecls doesn't need the val binds, and
  274. -- (b) tcExtCoreBindings doesn't need anything
  275. -- (in fact, it might not even need to be in the scope of
  276. -- this tcg_env at all)
  277. (tc_envs, _bndrs) <- getLocalNonValBinders emptyFsEnv {- no fixity decls -}
  278. (mkFakeGroup ldecls) ;
  279. setEnvs tc_envs $ do {
  280. (rn_decls, _fvs) <- checkNoErrs $ rnTyClDecls [] [ldecls] ;
  281. -- The empty list is for extra dependencies coming from .hs-boot files
  282. -- See Note [Extra dependencies from .hs-boot files] in RnSource
  283. -- Dump trace of renaming part
  284. rnDump (ppr rn_decls) ;
  285. -- Typecheck them all together so that
  286. -- any mutually recursive types are done right
  287. -- Just discard the auxiliary bindings; they are generated
  288. -- only for Haskell source code, and should already be in Core
  289. tcg_env <- tcTyAndClassDecls emptyModDetails rn_decls ;
  290. safe_mode <- liftIO $ finalSafeMode (hsc_dflags hsc_env) tcg_env ;
  291. dep_files <- liftIO $ readIORef (tcg_dependent_files tcg_env) ;
  292. setGblEnv tcg_env $ do {
  293. -- Make the new type env available to stuff slurped from interface files
  294. -- Now the core bindings
  295. core_binds <- initIfaceExtCore (tcExtCoreBindings src_binds) ;
  296. -- Wrap up
  297. let {
  298. bndrs = bindersOfBinds core_binds ;
  299. my_exports = map (Avail . idName) bndrs ;
  300. -- ToDo: export the data types also?
  301. mod_guts = ModGuts { mg_module = this_mod,
  302. mg_boot = False,
  303. mg_used_names = emptyNameSet, -- ToDo: compute usage
  304. mg_used_th = False,
  305. mg_dir_imps = emptyModuleEnv, -- ??
  306. mg_deps = noDependencies, -- ??
  307. mg_exports = my_exports,
  308. mg_tcs = tcg_tcs tcg_env,
  309. mg_insts = tcg_insts tcg_env,
  310. mg_fam_insts = tcg_fam_insts tcg_env,
  311. mg_inst_env = tcg_inst_env tcg_env,
  312. mg_fam_inst_env = tcg_fam_inst_env tcg_env,
  313. mg_rules = [],
  314. mg_vect_decls = [],
  315. mg_anns = [],
  316. mg_binds = core_binds,
  317. -- Stubs
  318. mg_rdr_env = emptyGlobalRdrEnv,
  319. mg_fix_env = emptyFixityEnv,
  320. mg_warns = NoWarnings,
  321. mg_foreign = NoStubs,
  322. mg_hpc_info = emptyHpcInfo False,
  323. mg_modBreaks = emptyModBreaks,
  324. mg_vect_info = noVectInfo,
  325. mg_safe_haskell = safe_mode,
  326. mg_trust_pkg = False,
  327. mg_dependent_files = dep_files
  328. } } ;
  329. tcCoreDump mod_guts ;
  330. return mod_guts
  331. }}}}
  332. mkFakeGroup :: [LTyClDecl a] -> HsGroup a
  333. mkFakeGroup decls -- Rather clumsy; lots of unused fields
  334. = emptyRdrGroup { hs_tyclds = [decls] }
  335. \end{code}
  336. %************************************************************************
  337. %* *
  338. Type-checking the top level of a module
  339. %* *
  340. %************************************************************************
  341. \begin{code}
  342. tcRnSrcDecls :: ModDetails -> [LHsDecl RdrName] -> TcM TcGblEnv
  343. -- Returns the variables free in the decls
  344. -- Reason: solely to report unused imports and bindings
  345. tcRnSrcDecls boot_iface decls
  346. = do { -- Do all the declarations
  347. ((tcg_env, tcl_env), lie) <- captureConstraints $ tc_rn_src_decls boot_iface decls ;
  348. ; traceTc "Tc8" empty ;
  349. ; setEnvs (tcg_env, tcl_env) $
  350. do {
  351. -- Finish simplifying class constraints
  352. --
  353. -- simplifyTop deals with constant or ambiguous InstIds.
  354. -- How could there be ambiguous ones? They can only arise if a
  355. -- top-level decl falls under the monomorphism restriction
  356. -- and no subsequent decl instantiates its type.
  357. --
  358. -- We do this after checkMain, so that we use the type info
  359. -- that checkMain adds
  360. --
  361. -- We do it with both global and local env in scope:
  362. -- * the global env exposes the instances to simplifyTop
  363. -- * the local env exposes the local Ids to simplifyTop,
  364. -- so that we get better error messages (monomorphism restriction)
  365. new_ev_binds <- {-# SCC "simplifyTop" #-}
  366. simplifyTop lie ;
  367. traceTc "Tc9" empty ;
  368. failIfErrsM ; -- Don't zonk if there have been errors
  369. -- It's a waste of time; and we may get debug warnings
  370. -- about strangely-typed TyCons!
  371. -- Zonk the final code. This must be done last.
  372. -- Even simplifyTop may do some unification.
  373. -- This pass also warns about missing type signatures
  374. let { TcGblEnv { tcg_type_env = type_env,
  375. tcg_binds = binds,
  376. tcg_sigs = sig_ns,
  377. tcg_ev_binds = cur_ev_binds,
  378. tcg_imp_specs = imp_specs,
  379. tcg_rules = rules,
  380. tcg_vects = vects,
  381. tcg_fords = fords } = tcg_env
  382. ; all_ev_binds = cur_ev_binds `unionBags` new_ev_binds } ;
  383. (bind_ids, ev_binds', binds', fords', imp_specs', rules', vects')
  384. <- {-# SCC "zonkTopDecls" #-}
  385. zonkTopDecls all_ev_binds binds sig_ns rules vects imp_specs fords ;
  386. let { final_type_env = extendTypeEnvWithIds type_env bind_ids
  387. ; tcg_env' = tcg_env { tcg_binds = binds',
  388. tcg_ev_binds = ev_binds',
  389. tcg_imp_specs = imp_specs',
  390. tcg_rules = rules',
  391. tcg_vects = vects',
  392. tcg_fords = fords' } } ;
  393. setGlobalTypeEnv tcg_env' final_type_env
  394. } }
  395. tc_rn_src_decls :: ModDetails
  396. -> [LHsDecl RdrName]
  397. -> TcM (TcGblEnv, TcLclEnv)
  398. -- Loops around dealing with each top level inter-splice group
  399. -- in turn, until it's dealt with the entire module
  400. tc_rn_src_decls boot_details ds
  401. = {-# SCC "tc_rn_src_decls" #-}
  402. do { (first_group, group_tail) <- findSplice ds ;
  403. -- If ds is [] we get ([], Nothing)
  404. -- The extra_deps are needed while renaming type and class declarations
  405. -- See Note [Extra dependencies from .hs-boot files] in RnSource
  406. let { extra_deps = map tyConName (typeEnvTyCons (md_types boot_details)) } ;
  407. -- Deal with decls up to, but not including, the first splice
  408. (tcg_env, rn_decls) <- rnTopSrcDecls extra_deps first_group ;
  409. -- rnTopSrcDecls fails if there are any errors
  410. (tcg_env, tcl_env) <- setGblEnv tcg_env $
  411. tcTopSrcDecls boot_details rn_decls ;
  412. -- If there is no splice, we're nearly done
  413. setEnvs (tcg_env, tcl_env) $
  414. case group_tail of {
  415. Nothing -> do { tcg_env <- checkMain ; -- Check for `main'
  416. traceTc "returning from tc_rn_src_decls: " $
  417. ppr $ nameEnvElts $ tcg_type_env tcg_env ; -- RAE
  418. return (tcg_env, tcl_env)
  419. } ;
  420. #ifndef GHCI
  421. -- There shouldn't be a splice
  422. Just (SpliceDecl {}, _) -> do {
  423. failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
  424. #else
  425. -- If there's a splice, we must carry on
  426. Just (SpliceDecl splice_expr _, rest_ds) -> do {
  427. -- Rename the splice expression, and get its supporting decls
  428. (rn_splice_expr, splice_fvs) <- checkNoErrs (rnLExpr splice_expr) ;
  429. -- checkNoErrs: don't typecheck if renaming failed
  430. rnDump (ppr rn_splice_expr) ;
  431. -- Execute the splice
  432. spliced_decls <- tcSpliceDecls rn_splice_expr ;
  433. -- Glue them on the front of the remaining decls and loop
  434. setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
  435. tc_rn_src_decls boot_details (spliced_decls ++ rest_ds)
  436. #endif /* GHCI */
  437. } } }
  438. \end{code}
  439. %************************************************************************
  440. %* *
  441. Compiling hs-boot source files, and
  442. comparing the hi-boot interface with the real thing
  443. %* *
  444. %************************************************************************
  445. \begin{code}
  446. tcRnHsBootDecls :: [LHsDecl RdrName] -> TcM TcGblEnv
  447. tcRnHsBootDecls decls
  448. = do { (first_group, group_tail) <- findSplice decls
  449. -- Rename the declarations
  450. ; (tcg_env, HsGroup {
  451. hs_tyclds = tycl_decls,
  452. hs_instds = inst_decls,
  453. hs_derivds = deriv_decls,
  454. hs_fords = for_decls,
  455. hs_defds = def_decls,
  456. hs_ruleds = rule_decls,
  457. hs_vects = vect_decls,
  458. hs_annds = _,
  459. hs_valds = val_binds }) <- rnTopSrcDecls [] first_group
  460. -- The empty list is for extra dependencies coming from .hs-boot files
  461. -- See Note [Extra dependencies from .hs-boot files] in RnSource
  462. ; (gbl_env, lie) <- captureConstraints $ setGblEnv tcg_env $ do {
  463. -- Check for illegal declarations
  464. ; case group_tail of
  465. Just (SpliceDecl d _, _) -> badBootDecl "splice" d
  466. Nothing -> return ()
  467. ; mapM_ (badBootDecl "foreign") for_decls
  468. ; mapM_ (badBootDecl "default") def_decls
  469. ; mapM_ (badBootDecl "rule") rule_decls
  470. ; mapM_ (badBootDecl "vect") vect_decls
  471. -- Typecheck type/class/isntance decls
  472. ; traceTc "Tc2 (boot)" empty
  473. ; (tcg_env, inst_infos, _deriv_binds)
  474. <- tcTyClsInstDecls emptyModDetails tycl_decls inst_decls deriv_decls
  475. ; setGblEnv tcg_env $ do {
  476. -- Typecheck value declarations
  477. ; traceTc "Tc5" empty
  478. ; val_ids <- tcHsBootSigs val_binds
  479. -- Wrap up
  480. -- No simplification or zonking to do
  481. ; traceTc "Tc7a" empty
  482. ; gbl_env <- getGblEnv
  483. -- Make the final type-env
  484. -- Include the dfun_ids so that their type sigs
  485. -- are written into the interface file.
  486. ; let { type_env0 = tcg_type_env gbl_env
  487. ; type_env1 = extendTypeEnvWithIds type_env0 val_ids
  488. ; type_env2 = extendTypeEnvWithIds type_env1 dfun_ids
  489. ; dfun_ids = map iDFunId inst_infos
  490. }
  491. ; setGlobalTypeEnv gbl_env type_env2
  492. }}
  493. ; traceTc "boot" (ppr lie); return gbl_env }
  494. badBootDecl :: String -> Located decl -> TcM ()
  495. badBootDecl what (L loc _)
  496. = addErrAt loc (char 'A' <+> text what
  497. <+> ptext (sLit "declaration is not (currently) allowed in a hs-boot file"))
  498. \end{code}
  499. Once we've typechecked the body of the module, we want to compare what
  500. we've found (gathered in a TypeEnv) with the hi-boot details (if any).
  501. \begin{code}
  502. checkHiBootIface :: TcGblEnv -> ModDetails -> TcM TcGblEnv
  503. -- Compare the hi-boot file for this module (if there is one)
  504. -- with the type environment we've just come up with
  505. -- In the common case where there is no hi-boot file, the list
  506. -- of boot_names is empty.
  507. --
  508. -- The bindings we return give bindings for the dfuns defined in the
  509. -- hs-boot file, such as $fbEqT = $fEqT
  510. checkHiBootIface
  511. tcg_env@(TcGblEnv { tcg_src = hs_src, tcg_binds = binds,
  512. tcg_insts = local_insts,
  513. tcg_type_env = local_type_env, tcg_exports = local_exports })
  514. (ModDetails { md_insts = boot_insts, md_fam_insts = boot_fam_insts,
  515. md_types = boot_type_env, md_exports = boot_exports })
  516. | isHsBoot hs_src -- Current module is already a hs-boot file!
  517. = return tcg_env
  518. | otherwise
  519. = do { traceTc "checkHiBootIface" $ vcat
  520. [ ppr boot_type_env, ppr boot_insts, ppr boot_exports]
  521. -- Check the exports of the boot module, one by one
  522. ; mapM_ check_export boot_exports
  523. -- Check for no family instances
  524. ; unless (null boot_fam_insts) $
  525. panic ("TcRnDriver.checkHiBootIface: Cannot handle family " ++
  526. "instances in boot files yet...")
  527. -- FIXME: Why? The actual comparison is not hard, but what would
  528. -- be the equivalent to the dfun bindings returned for class
  529. -- instances? We can't easily equate tycons...
  530. -- Check instance declarations
  531. ; mb_dfun_prs <- mapM check_inst boot_insts
  532. ; let dfun_prs = catMaybes mb_dfun_prs
  533. boot_dfuns = map fst dfun_prs
  534. dfun_binds = listToBag [ mkVarBind boot_dfun (nlHsVar dfun)
  535. | (boot_dfun, dfun) <- dfun_prs ]
  536. type_env' = extendTypeEnvWithIds local_type_env boot_dfuns
  537. tcg_env' = tcg_env { tcg_binds = binds `unionBags` dfun_binds }
  538. ; failIfErrsM
  539. ; setGlobalTypeEnv tcg_env' type_env' }
  540. -- Update the global type env *including* the knot-tied one
  541. -- so that if the source module reads in an interface unfolding
  542. -- mentioning one of the dfuns from the boot module, then it
  543. -- can "see" that boot dfun. See Trac #4003
  544. where
  545. check_export boot_avail -- boot_avail is exported by the boot iface
  546. | name `elem` dfun_names = return ()
  547. | isWiredInName name = return () -- No checking for wired-in names. In particular,
  548. -- 'error' is handled by a rather gross hack
  549. -- (see comments in GHC.Err.hs-boot)
  550. -- Check that the actual module exports the same thing
  551. | not (null missing_names)
  552. = addErrAt (nameSrcSpan (head missing_names))
  553. (missingBootThing (head missing_names) "exported by")
  554. -- If the boot module does not *define* the thing, we are done
  555. -- (it simply re-exports it, and names match, so nothing further to do)
  556. | isNothing mb_boot_thing = return ()
  557. -- Check that the actual module also defines the thing, and
  558. -- then compare the definitions
  559. | Just real_thing <- lookupTypeEnv local_type_env name,
  560. Just boot_thing <- mb_boot_thing
  561. = when (not (checkBootDecl boot_thing real_thing))
  562. $ addErrAt (nameSrcSpan (getName boot_thing))
  563. (let boot_decl = tyThingToIfaceDecl
  564. (fromJust mb_boot_thing)
  565. real_decl = tyThingToIfaceDecl real_thing
  566. in bootMisMatch real_thing boot_decl real_decl)
  567. | otherwise
  568. = addErrTc (missingBootThing name "defined in")
  569. where
  570. name = availName boot_avail
  571. mb_boot_thing = lookupTypeEnv boot_type_env name
  572. missing_names = case lookupNameEnv local_export_env name of
  573. Nothing -> [name]
  574. Just avail -> availNames boot_avail `minusList` availNames avail
  575. dfun_names = map getName boot_insts
  576. local_export_env :: NameEnv AvailInfo
  577. local_export_env = availsToNameEnv local_exports
  578. check_inst :: ClsInst -> TcM (Maybe (Id, Id))
  579. -- Returns a pair of the boot dfun in terms of the equivalent real dfun
  580. check_inst boot_inst
  581. = case [dfun | inst <- local_insts,
  582. let dfun = instanceDFunId inst,
  583. idType dfun `eqType` boot_inst_ty ] of
  584. [] -> do { traceTc "check_inst" (vcat [ text "local_insts" <+> vcat (map (ppr . idType . instanceDFunId) local_insts)
  585. , text "boot_inst" <+> ppr boot_inst
  586. , text "boot_inst_ty" <+> ppr boot_inst_ty
  587. ])
  588. ; addErrTc (instMisMatch boot_inst); return Nothing }
  589. (dfun:_) -> return (Just (local_boot_dfun, dfun))
  590. where
  591. boot_dfun = instanceDFunId boot_inst
  592. boot_inst_ty = idType boot_dfun
  593. local_boot_dfun = Id.mkExportedLocalId (idName boot_dfun) boot_inst_ty
  594. -- This has to compare the TyThing from the .hi-boot file to the TyThing
  595. -- in the current source file. We must be careful to allow alpha-renaming
  596. -- where appropriate, and also the boot declaration is allowed to omit
  597. -- constructors and class methods.
  598. --
  599. -- See rnfail055 for a good test of this stuff.
  600. checkBootDecl :: TyThing -> TyThing -> Bool
  601. checkBootDecl (AnId id1) (AnId id2)
  602. = ASSERT(id1 == id2)
  603. (idType id1 `eqType` idType id2)
  604. checkBootDecl (ATyCon tc1) (ATyCon tc2)
  605. = checkBootTyCon tc1 tc2
  606. checkBootDecl (ADataCon dc1) (ADataCon _)
  607. = pprPanic "checkBootDecl" (ppr dc1)
  608. checkBootDecl _ _ = False -- probably shouldn't happen
  609. ----------------
  610. checkBootTyCon :: TyCon -> TyCon -> Bool
  611. checkBootTyCon tc1 tc2
  612. | not (eqKind (tyConKind tc1) (tyConKind tc2))
  613. = False -- First off, check the kind
  614. | Just c1 <- tyConClass_maybe tc1
  615. , Just c2 <- tyConClass_maybe tc2
  616. , let (clas_tvs1, clas_fds1, sc_theta1, _, ats1, op_stuff1)
  617. = classExtraBigSig c1
  618. (clas_tvs2, clas_fds2, sc_theta2, _, ats2, op_stuff2)
  619. = classExtraBigSig c2
  620. , Just env <- eqTyVarBndrs emptyRnEnv2 clas_tvs1 clas_tvs2
  621. = let
  622. eqSig (id1, def_meth1) (id2, def_meth2)
  623. = idName id1 == idName id2 &&
  624. eqTypeX env op_ty1 op_ty2 &&
  625. def_meth1 == def_meth2
  626. where
  627. (_, rho_ty1) = splitForAllTys (idType id1)
  628. op_ty1 = funResultTy rho_ty1
  629. (_, rho_ty2) = splitForAllTys (idType id2)
  630. op_ty2 = funResultTy rho_ty2
  631. eqAT (tc1, def_ats1) (tc2, def_ats2)
  632. = checkBootTyCon tc1 tc2 &&
  633. eqListBy eqATDef def_ats1 def_ats2
  634. -- Ignore the location of the defaults
  635. eqATDef (CoAxBranch { cab_tvs = tvs1, cab_lhs = ty_pats1, cab_rhs = ty1 })
  636. (CoAxBranch { cab_tvs = tvs2, cab_lhs = ty_pats2, cab_rhs = ty2 })
  637. | Just env <- eqTyVarBndrs emptyRnEnv2 tvs1 tvs2
  638. = eqListBy (eqTypeX env) ty_pats1 ty_pats2 &&
  639. eqTypeX env ty1 ty2
  640. | otherwise = False
  641. eqFD (as1,bs1) (as2,bs2) =
  642. eqListBy (eqTypeX env) (mkTyVarTys as1) (mkTyVarTys as2) &&
  643. eqListBy (eqTypeX env) (mkTyVarTys bs1) (mkTyVarTys bs2)
  644. in
  645. -- Checks kind of class
  646. eqListBy eqFD clas_fds1 clas_fds2 &&
  647. (null sc_theta1 && null op_stuff1 && null ats1
  648. || -- Above tests for an "abstract" class
  649. eqListBy (eqPredX env) sc_theta1 sc_theta2 &&
  650. eqListBy eqSig op_stuff1 op_stuff2 &&
  651. eqListBy eqAT ats1 ats2)
  652. | Just syn_rhs1 <- synTyConRhs_maybe tc1
  653. , Just syn_rhs2 <- synTyConRhs_maybe tc2
  654. , Just env <- eqTyVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
  655. = ASSERT(tc1 == tc2)
  656. let eqSynRhs (SynFamilyTyCon o1 i1) (SynFamilyTyCon o2 i2)
  657. = o1==o2 && i1==i2
  658. eqSynRhs (SynonymTyCon t1) (SynonymTyCon t2)
  659. = eqTypeX env t1 t2
  660. eqSynRhs _ _ = False
  661. in
  662. eqSynRhs syn_rhs1 syn_rhs2
  663. | isAlgTyCon tc1 && isAlgTyCon tc2
  664. , Just env <- eqTyVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
  665. = ASSERT(tc1 == tc2)
  666. eqListBy (eqPredX env) (tyConStupidTheta tc1) (tyConStupidTheta tc2) &&
  667. eqAlgRhs (algTyConRhs tc1) (algTyConRhs tc2)
  668. | isForeignTyCon tc1 && isForeignTyCon tc2
  669. = eqKind (tyConKind tc1) (tyConKind tc2) &&
  670. tyConExtName tc1 == tyConExtName tc2
  671. | otherwise = False
  672. where
  673. eqAlgRhs (AbstractTyCon dis1) rhs2
  674. | dis1 = isDistinctAlgRhs rhs2 --Check compatibility
  675. | otherwise = True
  676. eqAlgRhs DataFamilyTyCon{} DataFamilyTyCon{} = True
  677. eqAlgRhs tc1@DataTyCon{} tc2@DataTyCon{} =
  678. eqListBy eqCon (data_cons tc1) (data_cons tc2)
  679. eqAlgRhs tc1@NewTyCon{} tc2@NewTyCon{} =
  680. eqCon (data_con tc1) (data_con tc2)
  681. eqAlgRhs _ _ = False
  682. eqCon c1 c2
  683. = dataConName c1 == dataConName c2
  684. && dataConIsInfix c1 == dataConIsInfix c2
  685. && eqListBy eqHsBang (dataConStrictMarks c1) (dataConStrictMarks c2)
  686. && dataConFieldLabels c1 == dataConFieldLabels c2
  687. && eqType (dataConUserType c1) (dataConUserType c2)
  688. emptyRnEnv2 :: RnEnv2
  689. emptyRnEnv2 = mkRnEnv2 emptyInScopeSet
  690. ----------------
  691. missingBootThing :: Name -> String -> SDoc
  692. missingBootThing name what
  693. = ppr name <+> ptext (sLit "is exported by the hs-boot file, but not")
  694. <+> text what <+> ptext (sLit "the module")
  695. bootMisMatch :: TyThing -> IfaceDecl -> IfaceDecl -> SDoc
  696. bootMisMatch thing boot_decl real_decl
  697. = vcat [ppr thing <+> ptext (sLit "has conflicting definitions in the module and its hs-boot file"),
  698. ptext (sLit "Main module:") <+> ppr real_decl,
  699. ptext (sLit "Boot file: ") <+> ppr boot_decl]
  700. instMisMatch :: ClsInst -> SDoc
  701. instMisMatch inst
  702. = hang (ppr inst)
  703. 2 (ptext (sLit "is defined in the hs-boot file, but not in the module itself"))
  704. \end{code}
  705. %************************************************************************
  706. %* *
  707. Type-checking the top level of a module
  708. %* *
  709. %************************************************************************
  710. tcRnGroup takes a bunch of top-level source-code declarations, and
  711. * renames them
  712. * gets supporting declarations from interface files
  713. * typechecks them
  714. * zonks them
  715. * and augments the TcGblEnv with the results
  716. In Template Haskell it may be called repeatedly for each group of
  717. declarations. It expects there to be an incoming TcGblEnv in the
  718. monad; it augments it and returns the new TcGblEnv.
  719. \begin{code}
  720. ------------------------------------------------
  721. rnTopSrcDecls :: [Name] -> HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name)
  722. -- Fails if there are any errors
  723. rnTopSrcDecls extra_deps group
  724. = do { -- Rename the source decls
  725. traceTc "rn12" empty ;
  726. (tcg_env, rn_decls) <- checkNoErrs $ rnSrcDecls extra_deps group ;
  727. traceTc "rn13" empty ;
  728. -- save the renamed syntax, if we want it
  729. let { tcg_env'
  730. | Just grp <- tcg_rn_decls tcg_env
  731. = tcg_env{ tcg_rn_decls = Just (appendGroups grp rn_decls) }
  732. | otherwise
  733. = tcg_env };
  734. -- Dump trace of renaming part
  735. rnDump (ppr rn_decls) ;
  736. return (tcg_env', rn_decls)
  737. }
  738. ------------------------------------------------
  739. tcTopSrcDecls :: ModDetails -> HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
  740. tcTopSrcDecls boot_details
  741. (HsGroup { hs_tyclds = tycl_decls,
  742. hs_instds = inst_decls,
  743. hs_derivds = deriv_decls,
  744. hs_fords = foreign_decls,
  745. hs_defds = default_decls,
  746. hs_annds = annotation_decls,
  747. hs_ruleds = rule_decls,
  748. hs_vects = vect_decls,
  749. hs_valds = val_binds })
  750. = do { -- Type-check the type and class decls, and all imported decls
  751. -- The latter come in via tycl_decls
  752. traceTc "Tc2 (src)" empty ;
  753. -- Source-language instances, including derivings,
  754. -- and import the supporting declarations
  755. traceTc "Tc3" empty ;
  756. (tcg_env, inst_infos, deriv_binds)
  757. <- tcTyClsInstDecls boot_details tycl_decls inst_decls deriv_decls ;
  758. setGblEnv tcg_env $ do {
  759. -- Foreign import declarations next.
  760. traceTc "Tc4" empty ;
  761. (fi_ids, fi_decls, fi_gres) <- tcForeignImports foreign_decls ;
  762. tcExtendGlobalValEnv fi_ids $ do {
  763. -- Default declarations
  764. traceTc "Tc4a" empty ;
  765. default_tys <- tcDefaults default_decls ;
  766. updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
  767. -- Now GHC-generated derived bindings, generics, and selectors
  768. -- Do not generate warnings from compiler-generated code;
  769. -- hence the use of discardWarnings
  770. tc_envs <- discardWarnings (tcTopBinds deriv_binds) ;
  771. setEnvs tc_envs $ do {
  772. -- Value declarations next
  773. traceTc "Tc5" empty ;
  774. tc_envs@(tcg_env, tcl_env) <- tcTopBinds val_binds;
  775. setEnvs tc_envs $ do { -- Environment doesn't change now
  776. -- Second pass over class and instance declarations,
  777. -- now using the kind-checked decls
  778. traceTc "Tc6" empty ;
  779. inst_binds <- tcInstDecls2 (concat tycl_decls) inst_infos ;
  780. -- Foreign exports
  781. traceTc "Tc7" empty ;
  782. (foe_binds, foe_decls, foe_gres) <- tcForeignExports foreign_decls ;
  783. -- Annotations
  784. annotations <- tcAnnotations annotation_decls ;
  785. -- Rules
  786. rules <- tcRules rule_decls ;
  787. -- Vectorisation declarations
  788. vects <- tcVectDecls vect_decls ;
  789. -- Wrap up
  790. traceTc "Tc7a" empty ;
  791. let { all_binds = inst_binds `unionBags`
  792. foe_binds
  793. ; fo_gres = fi_gres `unionBags` foe_gres
  794. ; fo_fvs = foldrBag (\gre fvs -> fvs `addOneFV` gre_name gre)
  795. emptyFVs fo_gres
  796. ; fo_rdr_names :: [RdrName]
  797. ; fo_rdr_names = foldrBag gre_to_rdr_name [] fo_gres
  798. ; sig_names = mkNameSet (collectHsValBinders val_binds)
  799. `minusNameSet` getTypeSigNames val_binds
  800. -- Extend the GblEnv with the (as yet un-zonked)
  801. -- bindings, rules, foreign decls
  802. ; tcg_env' = tcg_env { tcg_binds = tcg_binds tcg_env `unionBags` all_binds
  803. , tcg_sigs = tcg_sigs tcg_env `unionNameSets` sig_names
  804. , tcg_rules = tcg_rules tcg_env ++ rules
  805. , tcg_vects = tcg_vects tcg_env ++ vects
  806. , tcg_anns = tcg_anns tcg_env ++ annotations
  807. , tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls
  808. , tcg_dus = tcg_dus tcg_env `plusDU` usesOnly fo_fvs } } ;
  809. -- tcg_dus: see Note [Newtype constructor usage in foreign declarations]
  810. addUsedRdrNames fo_rdr_names ;
  811. traceTc "Tc8: type_env: " (ppr $ nameEnvElts $ tcg_type_env tcg_env') ; -- RAE
  812. return (tcg_env', tcl_env)
  813. }}}}}}
  814. where
  815. gre_to_rdr_name :: GlobalRdrElt -> [RdrName] -> [RdrName]
  816. -- For *imported* newtype data constructors, we want to
  817. -- make sure that at least one of the imports for them is used
  818. -- See Note [Newtype constructor usage in foreign declarations]
  819. gre_to_rdr_name gre rdrs
  820. = case gre_prov gre of
  821. LocalDef -> rdrs
  822. Imported [] -> panic "gre_to_rdr_name: Imported []"
  823. Imported (is : _) -> mkRdrQual modName occName : rdrs
  824. where
  825. modName = is_as (is_decl is)
  826. occName = nameOccName (gre_name gre)
  827. ---------------------------
  828. tcTyClsInstDecls :: ModDetails
  829. -> [TyClGroup Name]
  830. -> [LInstDecl Name]
  831. -> [LDerivDecl Name]
  832. -> TcM (TcGblEnv, -- The full inst env
  833. [InstInfo Name], -- Source-code instance decls to process;
  834. -- contains all dfuns for this module
  835. HsValBinds Name) -- Supporting bindings for derived instances
  836. tcTyClsInstDecls boot_details tycl_decls inst_decls deriv_decls
  837. = tcExtendTcTyThingEnv [(con, APromotionErr FamDataConPE)
  838. | lid <- inst_decls, con <- get_cons lid ] $
  839. -- Note [AFamDataCon: not promoting data family constructors]
  840. do { tcg_env <- tcTyAndClassDecls boot_details tycl_decls ;
  841. ; setGblEnv tcg_env $
  842. tcInstDecls1 (concat tycl_decls) inst_decls deriv_decls }
  843. where
  844. -- get_cons extracts the *constructor* bindings of the declaration
  845. get_cons :: LInstDecl Name -> [Name]
  846. get_cons (L _ (TyFamInstD {})) = []
  847. get_cons (L _ (DataFamInstD { dfid_inst = fid })) = get_fi_cons fid
  848. get_cons (L _ (ClsInstD { cid_inst = ClsInstDecl { cid_datafam_insts = fids } }))
  849. = concatMap (get_fi_cons . unLoc) fids
  850. get_fi_cons :: DataFamInstDecl Name -> [Name]
  851. get_fi_cons (DataFamInstDecl { dfid_defn = HsDataDefn { dd_cons = cons } })
  852. = map (unLoc . con_name . unLoc) cons
  853. \end{code}
  854. Note [AFamDataCon: not promoting data family constructors]
  855. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  856. Consider
  857. data family T a
  858. data instance T Int = MkT
  859. data Proxy (a :: k)
  860. data S = MkS (Proxy 'MkT)
  861. Is it ok to use the promoted data family instance constructor 'MkT' in
  862. the data declaration for S? No, we don't allow this. It *might* make
  863. sense, but at least it would mean that we'd have to interleave
  864. typechecking instances and data types, whereas at present we do data
  865. types *then* instances.
  866. So to check for this we put in the TcLclEnv a binding for all the family
  867. constructors, bound to AFamDataCon, so that if we trip over 'MkT' when
  868. type checking 'S' we'll produce a decent error message.
  869. %************************************************************************
  870. %* *
  871. Checking for 'main'
  872. %* *
  873. %************************************************************************
  874. \begin{code}
  875. checkMain :: TcM TcGblEnv
  876. -- If we are in module Main, check that 'main' is defined.
  877. checkMain
  878. = do { tcg_env <- getGblEnv ;
  879. dflags <- getDynFlags ;
  880. check_main dflags tcg_env
  881. }
  882. check_main :: DynFlags -> TcGblEnv -> TcM TcGblEnv
  883. check_main dflags tcg_env
  884. | mod /= main_mod
  885. = traceTc "checkMain not" (ppr main_mod <+> ppr mod) >>
  886. return tcg_env
  887. | otherwise
  888. = do { mb_main <- lookupGlobalOccRn_maybe main_fn
  889. -- Check that 'main' is in scope
  890. -- It might be imported from another module!
  891. ; case mb_main of {
  892. Nothing -> do { traceTc "checkMain fail" (ppr main_mod <+> ppr main_fn)
  893. ; complain_no_main
  894. ; return tcg_env } ;
  895. Just main_name -> do
  896. { traceTc "checkMain found" (ppr main_mod <+> ppr main_fn)
  897. ; let loc = srcLocSpan (getSrcLoc main_name)
  898. ; ioTyCon <- tcLookupTyCon ioTyConName
  899. ; res_ty <- newFlexiTyVarTy liftedTypeKind
  900. ; main_expr
  901. <- addErrCtxt mainCtxt $
  902. tcMonoExpr (L loc (HsVar main_name)) (mkTyConApp ioTyCon [res_ty])
  903. -- See Note [Root-main Id]
  904. -- Construct the binding
  905. -- :Main.main :: IO res_ty = runMainIO res_ty main
  906. ; run_main_id <- tcLookupId runMainIOName
  907. ; let { root_main_name = mkExternalName rootMainKey rOOT_MAIN
  908. (mkVarOccFS (fsLit "main"))
  909. (getSrcSpan main_name)
  910. ; root_main_id = Id.mkExportedLocalId root_main_name
  911. (mkTyConApp ioTyCon [res_ty])
  912. ; co = mkWpTyApps [res_ty]
  913. ; rhs = nlHsApp (mkLHsWrap co (nlHsVar run_main_id)) main_expr
  914. ; main_bind = mkVarBind root_main_id rhs }
  915. ; return (tcg_env { tcg_main = Just main_name,
  916. tcg_binds = tcg_binds tcg_env
  917. `snocBag` main_bind,
  918. tcg_dus = tcg_dus tcg_env
  919. `plusDU` usesOnly (unitFV main_name)
  920. -- Record the use of 'main', so that we don't
  921. -- complain about it being defined but not used
  922. })
  923. }}}
  924. where
  925. mod = tcg_mod tcg_env
  926. main_mod = mainModIs dflags
  927. main_fn = getMainFun dflags
  928. complain_no_main | ghcLink dflags == LinkInMemory = return ()
  929. | otherwise = failWithTc noMainMsg
  930. -- In interactive mode, don't worry about the absence of 'main'
  931. -- In other modes, fail altogether, so that we don't go on
  932. -- and complain a second time when processing the export list.
  933. mainCtxt = ptext (sLit "When checking the type of the") <+> pp_main_fn
  934. noMainMsg = ptext (sLit "The") <+> pp_main_fn
  935. <+> ptext (sLit "is not defined in module") <+> quotes (ppr main_mod)
  936. pp_main_fn = ppMainFn main_fn
  937. -- | Get the unqualified name of the function to use as the \"main\" for the main module.
  938. -- Either returns the default name or the one configured on the command line with -main-is
  939. getMainFun :: DynFlags -> RdrName
  940. getMainFun dflags = case mainFunIs dflags of
  941. Just fn -> mkRdrUnqual (mkVarOccFS (mkFastString fn))
  942. Nothing -> main_RDR_Unqual
  943. checkMainExported :: TcGblEnv -> TcM ()
  944. checkMainExported tcg_env
  945. = case tcg_main tcg_env of
  946. Nothing -> return () -- not the main module
  947. Just main_name ->
  948. do { dflags <- getDynFlags
  949. ; let main_mod = mainModIs dflags
  950. ; checkTc (main_name `elem` concatMap availNames (tcg_exports tcg_env)) $
  951. ptext (sLit "The") <+> ppMainFn (nameRdrName main_name) <+>
  952. ptext (sLit "is not exported by module") <+> quotes (ppr main_mod) }
  953. ppMainFn :: RdrName -> SDoc
  954. ppMainFn main_fn
  955. | rdrNameOcc main_fn == mainOcc
  956. = ptext (sLit "IO action") <+> quotes (ppr main_fn)
  957. | otherwise
  958. = ptext (sLit "main IO action") <+> quotes (ppr main_fn)
  959. mainOcc :: OccName
  960. mainOcc = mkVarOccFS (fsLit "main")
  961. \end{code}
  962. Note [Root-main Id]
  963. ~~~~~~~~~~~~~~~~~~~
  964. The function that the RTS invokes is always :Main.main, which we call
  965. root_main_id. (Because GHC allows the user to have a module not
  966. called Main as the main module, we can't rely on the main function
  967. being called "Main.main". That's why root_main_id has a fixed module
  968. ":Main".)
  969. This is unusual: it's a LocalId whose Name has a Module from another
  970. module. Tiresomely, we must filter it out again in MkIface, les we
  971. get two defns for 'main' in the interface file!
  972. %*********************************************************
  973. %* *
  974. GHCi stuff
  975. %* *
  976. %*********************************************************
  977. \begin{code}
  978. setInteractiveContext :: HscEnv -> InteractiveContext -> TcRn a -> TcRn a
  979. setInteractiveContext hsc_env icxt thing_inside
  980. = let -- Initialise the tcg_inst_env with instances from all home modules.
  981. -- This mimics the more selective call to hptInstances in tcRnImports
  982. (home_insts, home_fam_insts) = hptInstances hsc_env (\_ -> True)
  983. (ic_insts, ic_finsts) = ic_instances icxt
  984. -- Note [GHCi temporary Ids]
  985. -- Ideally we would just make a type_env from ic_tythings
  986. -- and ic_sys_vars, adding in implicit things. However, Ids
  987. -- bound interactively might have some free type variables
  988. -- (RuntimeUnk things), and if we don't register these free
  989. -- TyVars as global TyVars then the typechecker will try to
  990. -- quantify over them and fall over in zonkQuantifiedTyVar.
  991. --
  992. -- So we must add any free TyVars to the typechecker's global
  993. -- TyVar set. This is what happens when the local environment
  994. -- is extended, so we use tcExtendGhciEnv below which extends
  995. -- the local environment with the Ids.
  996. --
  997. -- However, any Ids bound this way will shadow other Ids in
  998. -- the GlobalRdrEnv, so we have to be careful to only add Ids
  999. -- which are visible in the GlobalRdrEnv.
  1000. --
  1001. -- Perhaps it would be better to just extend the global TyVar
  1002. -- list from the free tyvars in the Ids here? Anyway, at least
  1003. -- this hack is localised.
  1004. --
  1005. -- Note [delete shadowed tcg_rdr_env entries]
  1006. -- We also *delete* entries from tcg_rdr_env that we have
  1007. -- shadowed in the local env (see above). This isn't strictly
  1008. -- necessary, but in an out-of-scope error when GHC suggests
  1009. -- names it can be confusing to see multiple identical
  1010. -- entries. (#5564)
  1011. --
  1012. (tmp_ids, types_n_classes) = partitionWith sel_id (ic_tythings icxt)
  1013. where sel_id (AnId id) = Left id
  1014. sel_id other = Right other
  1015. type_env = mkTypeEnvWithImplicits
  1016. (map AnId (ic_sys_vars icxt) ++ types_n_classes)
  1017. visible_tmp_ids = filter visible tmp_ids
  1018. where visible id = not (null (lookupGRE_Name (ic_rn_gbl_env icxt)
  1019. (idName id)))
  1020. con_fields = [ (dataConName c, dataConFieldLabels c)
  1021. | ATyCon t <- types_n_classes
  1022. , c <- tyConDataCons t ]
  1023. in
  1024. updGblEnv (\env -> env {
  1025. tcg_rdr_env = delListFromOccEnv (ic_rn_gbl_env icxt)
  1026. (map getOccName visible_tmp_ids)
  1027. -- Note [delete shadowed tcg_rdr_env entries]
  1028. , tcg_type_env = type_env
  1029. , tcg_insts = ic_insts
  1030. , tcg_inst_env = extendInstEnvList
  1031. (extendInstEnvList (tcg_inst_env env) ic_insts)
  1032. home_insts
  1033. , tcg_fam_insts = ic_finsts
  1034. , tcg_fam_inst_env = extendFamInstEnvList
  1035. (extendFamInstEnvList (tcg_fam_inst_env env)
  1036. ic_finsts)
  1037. home_fam_insts
  1038. , tcg_field_env = RecFields (mkNameEnv con_fields)
  1039. (mkNameSet (concatMap snd con_fields))
  1040. -- setting tcg_field_env is necessary to make RecordWildCards work
  1041. -- (test: ghci049)
  1042. , tcg_fix_env = ic_fix_env icxt
  1043. , tcg_default = ic_default icxt
  1044. }) $
  1045. tcExtendGhciEnv visible_tmp_ids $ -- Note [GHCi temporary Ids]
  1046. thing_inside
  1047. #ifdef GHCI
  1048. -- | The returned [Id] is the list of new Ids bound by this statement. It can
  1049. -- be used to extend the InteractiveContext via extendInteractiveContext.
  1050. --
  1051. -- The returned TypecheckedHsExpr is of type IO [ () ], a list of the bound
  1052. -- values, coerced to ().
  1053. tcRnStmt :: HscEnv -> InteractiveContext -> GhciLStmt RdrName
  1054. -> IO (Messages, Maybe ([Id], LHsExpr Id, FixityEnv))
  1055. tcRnStmt hsc_env ictxt rdr_stmt
  1056. = initTcPrintErrors hsc_env iNTERACTIVE $
  1057. setInteractiveContext hsc_env ictxt $ do {
  1058. -- The real work is done here
  1059. ((bound_ids, tc_expr), fix_env) <- tcUserStmt rdr_stmt ;
  1060. zonked_expr <- zonkTopLExpr tc_expr ;
  1061. zonked_ids <- zonkTopBndrs bound_ids ;
  1062. -- None of the Ids should be of unboxed type, because we
  1063. -- cast them all to HValues in the end!
  1064. mapM_ bad_unboxed (filter (isUnLiftedType . idType) zonked_ids) ;
  1065. traceTc "tcs 1" empty ;
  1066. let { global_ids = map globaliseAndTidyId zonked_ids } ;
  1067. -- Note [Interactively-bound Ids in GHCi]
  1068. {- ---------------------------------------------
  1069. At one stage I removed any shadowed bindings from the type_env;
  1070. they are inaccessible but might, I suppose, cause a space leak if we leave them there.
  1071. However, with Template Haskell they aren't necessarily inaccessible. Consider this
  1072. GHCi session
  1073. Prelude> let f n = n * 2 :: Int
  1074. Prelude> fName <- runQ [| f |]
  1075. Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
  1076. 14
  1077. Prelude> let f n = n * 3 :: Int
  1078. Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
  1079. In the last line we use 'fName', which resolves to the *first* 'f'
  1080. in scope. If we delete it from the type env, GHCi crashes because
  1081. it doesn't expect that.
  1082. Hence this code is commented out
  1083. -------------------------------------------------- -}
  1084. dumpOptTcRn Opt_D_dump_tc
  1085. (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
  1086. text "Typechecked expr" <+> ppr zonked_expr]) ;
  1087. return (global_ids, zonked_expr, fix_env)
  1088. }
  1089. where
  1090. bad_unboxed id = addErr (sep [ptext (sLit "GHCi can't bind a variable of unlifted type:"),
  1091. nest 2 (ppr id <+> dcolon <+> ppr (idType id))])
  1092. \end{code}
  1093. Note [Interactively-bound Ids in GHCi]
  1094. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1095. The Ids bound by previous Stmts in GHCi are currently
  1096. a) GlobalIds
  1097. b) with an Internal Name (not External)
  1098. c) and a tidied type
  1099. (a) They must be GlobalIds (not LocalIds) otherwise when we come to
  1100. compile an expression using these ids later, the byte code
  1101. generator will consider the occurrences to be free rather than
  1102. global.
  1103. (b) They retain their Internal names because we don't have a suitable
  1104. Module to name them with. We could revisit this choice.
  1105. (c) Their types are tidied. This is important, because :info may ask
  1106. to look at them, and :info expects the things it looks up to have
  1107. tidy types
  1108. --------------------------------------------------------------------------
  1109. Typechecking Stmts in GHCi
  1110. Here is the grand plan, implemented in tcUserStmt
  1111. What you type The IO [HValue] that hscStmt returns
  1112. ------------- ------------------------------------
  1113. let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
  1114. bindings: [x,y,...]
  1115. pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
  1116. bindings: [x,y,...]
  1117. expr (of IO type) ==> expr >>= \ it -> return [coerce HVal it]
  1118. [NB: result not printed] bindings: [it]
  1119. expr (of non-IO type, ==> let it = expr in print it >> return [coerce HVal it]
  1120. result showable) bindings: [it]
  1121. expr (of non-IO type,
  1122. result not showable) ==> error
  1123. \begin{code}
  1124. -- | A plan is an attempt to lift some code into the IO monad.
  1125. type PlanResult = ([Id], LHsExpr Id)
  1126. type Plan = TcM PlanResult
  1127. -- | Try the plans in order. If one fails (by raising an exn), try the next.
  1128. -- If one succeeds, take it.
  1129. runPlans :: [Plan] -> TcM PlanResult
  1130. runPlans [] = panic "runPlans"
  1131. runPlans [p] = p
  1132. runPlans (p:ps) = tryTcLIE_ (runPlans ps) p
  1133. -- | Typecheck (and 'lift') a stmt entered by the user in GHCi into the
  1134. -- GHCi 'environemnt'.
  1135. --
  1136. -- By 'lift' and 'environment we mean that the code is changed to execute
  1137. -- properly in an IO monad. See Note [Interactively-bound Ids in GHCi] above
  1138. -- for more details. We do this lifting by trying different ways ('plans') of
  1139. -- lifting the code into the IO monad and type checking each plan until one
  1140. -- succeeds.
  1141. tcUserStmt :: GhciLStmt RdrName -> TcM (PlanResult, FixityEnv)
  1142. -- An expression typed at the prompt is treated very specially
  1143. tcUserStmt (L loc (BodyStmt expr _ _ _))
  1144. = do { (rn_expr, fvs) <- checkNoErrs (rnLExpr expr)
  1145. -- Don't try to typecheck if the renamer fails!
  1146. ; ghciStep <- getGhciStepIO
  1147. ; uniq <- newUnique
  1148. ; interPrintName <- getInteractivePrintName
  1149. ; let fresh_it = itName uniq loc
  1150. matches = [mkMatch [] rn_expr emptyLocalBinds]
  1151. -- [it = expr]
  1152. the_bind = L loc $ (mkTopFunBind (L loc fresh_it) matches) { bind_fvs = fvs }
  1153. -- Care here! In GHCi the expression might have
  1154. -- free variables, and they in turn may have free type variables
  1155. -- (if we are at a breakpoint, say). We must put those free vars
  1156. -- [let it = expr]
  1157. let_stmt = L loc $ LetStmt $ HsValBinds $
  1158. ValBindsOut [(NonRecursive,unitBag the_bind)] []
  1159. -- [it <- e]
  1160. bind_stmt = L loc $ BindStmt (L loc (VarPat fresh_it))
  1161. (nlHsApp ghciStep rn_expr)
  1162. (HsVar bindIOName) noSyntaxExpr
  1163. -- [; print it]
  1164. print_it = L loc $ BodyStmt (nlHsApp (nlHsVar interPrintName) (nlHsVar fresh_it))
  1165. (HsVar thenIOName) noSyntaxExpr placeHolderType
  1166. -- The plans are:
  1167. -- A. [it <- e; print it] but not if it::()
  1168. -- B. [it <- e]
  1169. -- C. [let it = e; print it]
  1170. --
  1171. -- Ensure that type errors don't get deferred when type checking the
  1172. -- naked expression. Deferring type errors here is unhelpful because the
  1173. -- expression gets evaluated right away anyway. It also would potentially
  1174. -- emit two redundant type-error warnings, one from each plan.
  1175. ; plan <- unsetGOptM Opt_DeferTypeErrors $ runPlans [
  1176. -- Plan A
  1177. do { stuff@([it_id], _) <- tcGhciStmts [bind_stmt, print_it]
  1178. ; it_ty <- zonkTcType (idType it_id)
  1179. ; when (isUnitTy $ it_ty) failM
  1180. ; return stuff },
  1181. -- Plan B; a naked bind statment
  1182. tcGhciStmts [bind_stmt],
  1183. -- Plan C; check that the let-binding is typeable all by itself.
  1184. -- If not, fail; if so, try to print it.
  1185. -- The two-step process avoids getting two errors: one from
  1186. -- the expression itself, and one from the 'print it' part
  1187. -- This two-step story is very clunky, alas
  1188. do { _ <- checkNoErrs (tcGhciStmts [let_stmt])
  1189. --- checkNoErrs defeats the error recovery of let-bindings
  1190. ; tcGhciStmts [let_stmt, print_it] } ]
  1191. ; fix_env <- getFixityEnv
  1192. ; return (plan, fix_env) }
  1193. tcUserStmt rdr_stmt@(L loc _)
  1194. = do { (([rn_stmt], fix_env), fvs) <- checkNoErrs $
  1195. rnStmts GhciStmtCtxt rnLExpr [rdr_stmt] $ \_ -> do
  1196. fix_env <- getFixityEnv
  1197. return (fix_env, emptyFVs)
  1198. -- Don't try to typecheck if the renamer fails!
  1199. ; traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs])
  1200. ; rnDump (ppr rn_stmt) ;
  1201. ; ghciStep <- getGhciStepIO
  1202. ; let gi_stmt
  1203. | (L loc (BindStmt pat expr op1 op2)) <- rn_stmt
  1204. = L loc $ BindStmt pat (nlHsApp ghciStep expr) op1 op2
  1205. | otherwise = rn_stmt
  1206. ; opt_pr_flag <- goptM Opt_PrintBindResult
  1207. ; let print_result_plan
  1208. | opt_pr_flag -- The flag says "print result"
  1209. , [v] <- collectLStmtBinders gi_stmt -- One binder
  1210. = [mk_print_result_plan gi_stmt v]
  1211. | otherwise = []
  1212. -- The plans are:
  1213. -- [stmt; print v] if one binder and not v::()
  1214. -- [stmt] otherwise
  1215. ; plan <- runPlans (print_result_plan ++ [tcGhciStmts [gi_stmt]])
  1216. ; return (plan, fix_env) }
  1217. where
  1218. mk_print_result_plan stmt v
  1219. = do { stuff@([v_id], _) <- tcGhciStmts [stmt, print_v]
  1220. ; v_ty <- zonkTcType (idType v_id)
  1221. ; when (isUnitTy v_ty || not (isTauTy v_ty)) failM
  1222. ; return stuff }
  1223. where
  1224. print_v = L loc $ BodyStmt (nlHsApp (nlHsVar printName) (nlHsVar v))
  1225. (HsVar thenIOName) noSyntaxExpr placeHolderType
  1226. -- | Typecheck the statements given and then return the results of the
  1227. -- statement in the form 'IO [()]'.
  1228. tcGhciStmts :: [GhciLStmt Name] -> TcM PlanResult
  1229. tcGhciStmts stmts
  1230. = do { ioTyCon <- tcLookupTyCon ioTyConName ;
  1231. ret_id <- tcLookupId returnIOName ; -- return @ IO
  1232. let {
  1233. ret_ty = mkListTy unitTy ;
  1234. io_ret_ty = mkTyConApp ioTyCon [ret_ty] ;
  1235. tc_io_stmts = tcStmtsAndThen GhciStmtCtxt tcDoStmt stmts io_ret_ty ;
  1236. names = collectLStmtsBinders stmts ;
  1237. } ;
  1238. -- OK, we're ready to typecheck the stmts
  1239. traceTc "TcRnDriver.tcGhciStmts: tc stmts" empty ;
  1240. ((tc_stmts, ids), lie) <- captureConstraints $
  1241. tc_io_stmts $ \ _ ->
  1242. mapM tcLookupId names ;
  1243. -- Look up the names right in the middle,
  1244. -- where they will all be in scope
  1245. -- Simplify the context
  1246. traceTc "TcRnDriver.tcGhciStmts: simplify ctxt" empty ;
  1247. const_binds <- checkNoErrs (simplifyInteractive lie) ;
  1248. -- checkNoErrs ensures that the plan fails if context redn fails
  1249. traceTc "TcRnDriver.tcGhciStmts: done" empty ;
  1250. let { -- mk_return builds the expression
  1251. -- returnIO @ [()] [coerce () x, .., coerce () z]
  1252. --
  1253. -- Despite the inconvenience of building the type applications etc,
  1254. -- this *has* to be done in type-annotated post-typecheck form
  1255. -- because we are going to return a list of *polymorphic* values
  1256. -- coerced to type (). If we built a *source* stmt
  1257. -- return [coerce x, ..., coerce z]
  1258. -- then the type checker would instantiate x..z, and we wouldn't
  1259. -- get their *polymorphic* values. (And we'd get ambiguity errs
  1260. -- if they were overloaded, since they aren't applied to anything.)
  1261. ret_expr = nlHsApp (nlHsTyApp ret_id [ret_ty])
  1262. (noLoc $ ExplicitList unitTy Nothing (map mk_item ids)) ;
  1263. mk_item id = nlHsApp (nlHsTyApp unsafeCoerceId [idType id, unitTy])
  1264. (nlHsVar id) ;
  1265. stmts = tc_stmts ++ [noLoc (mkLastStmt ret_expr)]
  1266. } ;
  1267. return (ids, mkHsDictLet (EvBinds const_binds) $
  1268. noLoc (HsDo GhciStmtCtxt stmts io_ret_ty))
  1269. }
  1270. -- | Generate a typed ghciStepIO expression (ghciStep :: Ty a -> IO a)
  1271. getGhciStepIO :: TcM (LHsExpr Name)
  1272. getGhciStepIO = do
  1273. ghciTy <- getGHCiMonad
  1274. fresh_a <- newUnique
  1275. let a_tv = mkTcTyVarName fresh_a (fsLit "a")
  1276. ghciM = nlHsAppTy (nlHsTyVar ghciTy) (nlHsTyVar a_tv)
  1277. ioM = nlHsAppTy (nlHsTyVar ioTyConName) (nlHsTyVar a_tv)
  1278. stepTy :: LHsType Name -- Renamed, so needs all binders in place
  1279. stepTy = noLoc $ HsForAllTy Implicit
  1280. (HsQTvs { hsq_tvs = [noLoc (UserTyVar a_tv)]
  1281. , hsq_kvs = [] })
  1282. (noLoc [])
  1283. (nlHsFunTy ghciM ioM)
  1284. step = noLoc $ ExprWithTySig (nlHsVar ghciStepIoMName) stepTy
  1285. return step
  1286. isGHCiMonad :: HscEnv -> InteractiveContext -> String -> IO (Messages, Maybe Name)
  1287. isGHCiMonad hsc_env ictxt ty
  1288. = initTcPrintErrors hsc_env iNTERACTIVE $
  1289. setInteractiveContext hsc_env ictxt $ do
  1290. rdrEnv <- getGlobalRdrEnv
  1291. let occIO = lookupOccEnv rdrEnv (mkOccName tcName ty)
  1292. case occIO of
  1293. Just [n] -> do
  1294. let name = gre_name n
  1295. ghciClass <- tcLookupClass ghciIoClassName
  1296. userTyCon <- tcLookupTyCon name
  1297. let userTy = mkTyConApp userTyCon []
  1298. _ <- tcLookupInstance ghciClass [userTy]
  1299. return name
  1300. Just _ -> failWithTc $ text "Ambigous type!"
  1301. Nothing -> failWithTc $ text ("Can't find type:" ++ ty)
  1302. \end{code}
  1303. tcRnExpr just finds the type of an expression
  1304. \begin{code}
  1305. tcRnExpr :: HscEnv
  1306. -> InteractiveContext
  1307. -> LHsExpr RdrName
  1308. -> IO (Messages, Maybe Type)
  1309. -- Type checks the expression and returns its most general type
  1310. tcRnExpr hsc_env ictxt rdr_expr
  1311. = initTcPrintErrors hsc_env iNTERACTIVE $
  1312. setInteractiveContext hsc_env ictxt $ do {
  1313. (rn_expr, _fvs) <- rnLExpr rdr_expr ;
  1314. failIfErrsM ;
  1315. -- Now typecheck the expression;
  1316. -- it might have a rank-2 type (e.g. :t runST)
  1317. uniq <- newUnique ;
  1318. let { fresh_it = itName uniq (getLoc rdr_expr) } ;
  1319. ((_tc_expr, res_ty), lie) <- captureConstraints $
  1320. tcInferRho rn_expr ;
  1321. ((qtvs, dicts, _, _), lie_top) <- captureConstraints $
  1322. {-# SCC "simplifyInfer" #-}
  1323. simplifyInfer True {- Free vars are closed -}
  1324. False {- No MR for now -}
  1325. [(fresh_it, res_ty)]
  1326. lie ;
  1327. _ <- simplifyInteractive lie_top ; -- Ignore the dicionary bindings
  1328. let { all_expr_ty = mkForAllTys qtvs (mkPiTypes dicts res_ty) } ;
  1329. zonkTcType all_expr_ty
  1330. }
  1331. --------------------------
  1332. tcRnImportDecls :: HscEnv
  1333. -> [LImportDecl RdrName]
  1334. -> IO (Messages, Maybe GlobalRdrEnv)
  1335. tcRnImportDecls hsc_env import_decls
  1336. = initTcPrintErrors hsc_env iNTERACTIVE $
  1337. do { gbl_env <- tcRnImports hsc_env iNTERACTIVE import_decls
  1338. ; return (tcg_rdr_env gbl_env) }
  1339. \end{code}
  1340. tcRnType just finds the kind of a type
  1341. \begin{code}
  1342. tcRnType :: HscEnv
  1343. -> InteractiveContext
  1344. -> Bool -- Normalise the returned type
  1345. -> LHsType RdrName
  1346. -> IO (Messages, Maybe (Type, Kind))
  1347. tcRnType hsc_env ictxt normalise rdr_type
  1348. = initTcPrintErrors hsc_env iNTERACTIVE $
  1349. setInteractiveContext hsc_env ictxt $
  1350. setXOptM Opt_PolyKinds $ -- See Note [Kind-generalise in tcRnType]
  1351. do { (rn_type, _fvs) <- rnLHsType GHCiCtx rdr_type
  1352. ; failIfErrsM
  1353. -- Now kind-check the type
  1354. -- It can have any rank or kind
  1355. ; ty <- tcHsSigType GhciCtxt rn_type ;
  1356. ; ty' <- if normalise
  1357. then do { fam_envs <- tcGetFamInstEnvs
  1358. ; return (snd (normaliseType fam_envs ty)) }
  1359. -- normaliseType returns a coercion
  1360. -- which we discard
  1361. else return ty ;
  1362. ; return (ty', typeKind ty) }
  1363. \end{code}
  1364. Note [Kind-generalise in tcRnType]
  1365. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1366. We switch on PolyKinds when kind-checking a user type, so that we will
  1367. kind-generalise the type. This gives the right default behaviour at
  1368. the GHCi prompt, where if you say ":k T", and T has a polymorphic
  1369. kind, you'd like to see that polymorphism. Of course. If T isn't
  1370. kind-polymorphic you won't get anything unexpected, but the apparent
  1371. *loss* of polymorphism, for types that you know are polymorphic, is
  1372. quite surprising. See Trac #7688 for a discussion.
  1373. %************************************************************************
  1374. %* *
  1375. tcRnDeclsi
  1376. %* *
  1377. %************************************************************************
  1378. tcRnDeclsi exists to allow class, data, and other declarations in GHCi.
  1379. \begin{code}
  1380. tcRnDeclsi :: HscEnv
  1381. -> InteractiveContext
  1382. -> [LHsDecl RdrName]
  1383. -> IO (Messages, Maybe TcGblEnv)
  1384. tcRnDeclsi hsc_env ictxt local_decls =
  1385. initTcPrintErrors hsc_env iNTERACTIVE $
  1386. setInteractiveContext hsc_env ictxt $ do
  1387. ((tcg_env, tclcl_env), lie) <-
  1388. captureConstraints $ tc_rn_src_decls emptyModDetails local_decls
  1389. setEnvs (tcg_env, tclcl_env) $ do
  1390. new_ev_binds <- simplifyTop lie
  1391. failIfErrsM
  1392. let TcGblEnv { tcg_type_env = type_env,
  1393. tcg_binds = binds,
  1394. tcg_sigs = sig_ns,
  1395. tcg_ev_binds = cur_ev_binds,
  1396. tcg_imp_specs = imp_specs,
  1397. tcg_rules = rules,
  1398. tcg_vects = vects,
  1399. tcg_fords = fords } = tcg_env
  1400. all_ev_binds = cur_ev_binds `unionBags` new_ev_binds
  1401. (bind_ids, ev_binds', binds', fords', imp_specs', rules', vects')
  1402. <- zonkTopDecls all_ev_binds binds sig_ns rules vects imp_specs fords
  1403. let --global_ids = map globaliseAndTidyId bind_ids
  1404. final_type_env = extendTypeEnvWithIds type_env bind_ids --global_ids
  1405. tcg_env' = tcg_env { tcg_binds = binds',
  1406. tcg_ev_binds = ev_binds',
  1407. tcg_imp_specs = imp_specs',
  1408. tcg_rules = rules',
  1409. tcg_vects = vects',
  1410. tcg_fords = fords' }
  1411. tcg_env'' <- setGlobalTypeEnv tcg_env' final_type_env
  1412. traceTc "returning from tcRnDeclsi: " $ ppr $ nameEnvElts $ tcg_type_env tcg_env'' -- RAE
  1413. return tcg_env''
  1414. #endif /* GHCi */
  1415. \end{code}
  1416. %************************************************************************
  1417. %* *
  1418. More GHCi stuff, to do with browsing and getting info
  1419. %* *
  1420. %************************************************************************
  1421. \begin{code}
  1422. #ifdef GHCI
  1423. -- | ASSUMES that the module is either in the 'HomePackageTable' or is
  1424. -- a package module with an interface on disk. If neither of these is
  1425. -- true, then the result will be an error indicating the interface
  1426. -- could not be found.
  1427. getModuleInterface :: HscEnv -> Module -> IO (Messages, Maybe ModIface)
  1428. getModuleInterface hsc_env mod
  1429. = initTc hsc_env HsSrcFile False iNTERACTIVE $
  1430. loadModuleInterface (ptext (sLit "getModuleInterface")) mod
  1431. tcRnLookupRdrName :: HscEnv -> RdrName -> IO (Messages, Maybe [Name])
  1432. tcRnLookupRdrName hsc_env rdr_name
  1433. = initTcPrintErrors hsc_env iNTERACTIVE $
  1434. setInteractiveContext hsc_env (hsc_IC hsc_env) $
  1435. lookup_rdr_name rdr_name
  1436. lookup_rdr_name :: RdrName -> TcM [Name]
  1437. lookup_rdr_name rdr_name = do
  1438. -- If the identifier is a constructor (begins with an
  1439. -- upper-case letter), then we need to consider both
  1440. -- constructor and type class identifiers.
  1441. let rdr_names = dataTcOccs rdr_name
  1442. -- results :: [Either Messages Name]
  1443. results <- mapM (tryTcErrs . lookupOccRn) rdr_names
  1444. traceRn (text "xx" <+> vcat [ppr rdr_names, ppr (map snd results)])
  1445. -- The successful lookups will be (Just name)
  1446. let (warns_s, good_names) = unzip [ (msgs, name)
  1447. | (msgs, Just name) <- results]
  1448. errs_s = [msgs | (msgs, Nothing) <- results]
  1449. -- Fail if nothing good happened, else add warnings
  1450. if null good_names
  1451. then addMessages (head errs_s) >> failM
  1452. -- No lookup succeeded, so
  1453. -- pick the first error message and report it
  1454. -- ToDo: If one of the errors is "could be Foo.X or Baz.X",
  1455. -- while the other is "X is not in scope",
  1456. -- we definitely want the former; but we might pick the latter
  1457. else mapM_ addMessages warns_s
  1458. -- Add deprecation warnings
  1459. return good_names
  1460. #endif
  1461. tcRnLookupName :: HscEnv -> Name -> IO (Messages, Maybe TyThing)
  1462. tcRnLookupName hsc_env name
  1463. = initTcPrintErrors hsc_env iNTERACTIVE $
  1464. setInteractiveContext hsc_env (hsc_IC hsc_env) $
  1465. tcRnLookupName' name
  1466. -- To look up a name we have to look in the local environment (tcl_lcl)
  1467. -- as well as the global environment, which is what tcLookup does.
  1468. -- But we also want a TyThing, so we have to convert:
  1469. tcRnLookupName' :: Name -> TcRn TyThing
  1470. tcRnLookupName' name = do
  1471. tcthing <- tcLookup name
  1472. case tcthing of
  1473. AGlobal thing -> return thing
  1474. ATcId{tct_id=id} -> return (AnId id)
  1475. _ -> panic "tcRnLookupName'"
  1476. tcRnGetInfo :: HscEnv
  1477. -> Name
  1478. -> IO (Messages, Maybe (TyThing, Fixity, [ClsInst], [FamInst Branched]))
  1479. -- Used to implement :info in GHCi
  1480. --
  1481. -- Look up a RdrName and return all the TyThings it might be
  1482. -- A capitalised RdrName is given to us in the DataName namespace,
  1483. -- but we want to treat it as *both* a data constructor
  1484. -- *and* as a type or class constructor;
  1485. -- hence the call to dataTcOccs, and we return up to two results
  1486. tcRnGetInfo hsc_env name
  1487. = let ictxt = hsc_IC hsc_env in
  1488. initTcPrintErrors hsc_env iNTERACTIVE $
  1489. setInteractiveContext hsc_env ictxt $ do
  1490. -- Load the interface for all unqualified types and classes
  1491. -- That way we will find all the instance declarations
  1492. -- (Packages have not orphan modules, and we assume that
  1493. -- in the home package all relevant modules are loaded.)
  1494. loadUnqualIfaces hsc_env ictxt
  1495. thing <- tcRnLookupName' name
  1496. fixity <- lookupFixityRn name
  1497. (cls_insts, fam_insts) <- lookupInsts thing
  1498. return (thing, fixity, cls_insts, fam_insts)
  1499. lookupInsts :: TyThing -> TcM ([ClsInst],[FamInst Branched])
  1500. lookupInsts (ATyCon tc)
  1501. | Just cls <- tyConClass_maybe tc
  1502. = do { inst_envs <- tcGetInstEnvs
  1503. ; return (classInstances inst_envs cls, []) }
  1504. | isFamilyTyCon tc || isTyConAssoc tc
  1505. = do { inst_envs <- tcGetFamInstEnvs
  1506. ; return ([], familyInstances inst_envs tc) }
  1507. | otherwise
  1508. = do { (pkg_ie, home_ie) <- tcGetInstEnvs
  1509. ; (pkg_fie, home_fie) <- tcGetFamInstEnvs
  1510. -- Load all instances for all classes that are
  1511. -- in the type environment (which are all the ones
  1512. -- we've seen in any interface file so far)
  1513. -- Return only the instances relevant to the given thing, i.e.
  1514. -- the instances whose head contains the thing's name.
  1515. ; let cls_insts =
  1516. [ ispec -- Search all
  1517. | ispec <- instEnvElts home_ie ++ instEnvElts pkg_ie
  1518. , tc_name `elemNameSet` orphNamesOfClsInst ispec ]
  1519. ; let fam_insts =
  1520. [ fispec
  1521. | fispec <- famInstEnvElts home_fie ++ famInstEnvElts pkg_fie
  1522. , tc_name `elemNameSet` orphNamesOfFamInst fispec ]
  1523. ; return (cls_insts, fam_insts) }
  1524. where
  1525. tc_name = tyConName tc
  1526. lookupInsts _ = return ([],[])
  1527. loadUnqualIfaces :: HscEnv -> InteractiveContext -> TcM ()
  1528. -- Load the interface for everything that is in scope unqualified
  1529. -- This is so that we can accurately report the instances for
  1530. -- something
  1531. loadUnqualIfaces hsc_env ictxt
  1532. = initIfaceTcRn $ do
  1533. mapM_ (loadSysInterface doc) (moduleSetElts (mkModuleSet unqual_mods))
  1534. where
  1535. this_pkg = thisPackage (hsc_dflags hsc_env)
  1536. unqual_mods = filter ((/= this_pkg) . modulePackageId)
  1537. [ nameModule name
  1538. | gre <- globalRdrEnvElts (ic_rn_gbl_env ictxt),
  1539. let name = gre_name gre,
  1540. not (isInternalName name),
  1541. isTcOcc (nameOccName name), -- Types and classes only
  1542. unQualOK gre ] -- In scope unqualified
  1543. doc = ptext (sLit "Need interface for module whose export(s) are in scope unqualified")
  1544. \end{code}
  1545. %************************************************************************
  1546. %* *
  1547. Degugging output
  1548. %* *
  1549. %************************************************************************
  1550. \begin{code}
  1551. rnDump :: SDoc -> TcRn ()
  1552. -- Dump, with a banner, if -ddump-rn
  1553. rnDump doc = do { dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc) }
  1554. tcDump :: TcGblEnv -> TcRn ()
  1555. tcDump env
  1556. = do { dflags <- getDynFlags ;
  1557. -- Dump short output if -ddump-types or -ddump-tc
  1558. when (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
  1559. (dumpTcRn short_dump) ;
  1560. -- Dump bindings if -ddump-tc
  1561. dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
  1562. }
  1563. where
  1564. short_dump = pprTcGblEnv env
  1565. full_dump = pprLHsBinds (tcg_binds env)
  1566. -- NB: foreign x-d's have undefined's in their types;
  1567. -- hence can't show the tc_fords
  1568. tcCoreDump :: ModGuts -> TcM ()
  1569. tcCoreDump mod_guts
  1570. = do { dflags <- getDynFlags ;
  1571. when (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
  1572. (dumpTcRn (pprModGuts mod_guts)) ;
  1573. -- Dump bindings if -ddump-tc
  1574. dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
  1575. where
  1576. full_dump = pprCoreBindings (mg_binds mod_guts)
  1577. -- It's unpleasant having both pprModGuts and pprModDetails here
  1578. pprTcGblEnv :: TcGblEnv -> SDoc
  1579. pprTcGblEnv (TcGblEnv { tcg_type_env = type_env,
  1580. tcg_insts = insts,
  1581. tcg_fam_insts = fam_insts,
  1582. tcg_rules = rules,
  1583. tcg_vects = vects,
  1584. tcg_imports = imports })
  1585. = vcat [ ppr_types insts type_env
  1586. , ppr_tycons fam_insts type_env
  1587. , ppr_insts insts
  1588. , ppr_fam_insts fam_insts
  1589. , vcat (map ppr rules)
  1590. , vcat (map ppr vects)
  1591. , ptext (sLit "Dependent modules:") <+>
  1592. ppr (sortBy cmp_mp $ eltsUFM (imp_dep_mods imports))
  1593. , ptext (sLit "Dependent packages:") <+>
  1594. ppr (sortBy stablePackageIdCmp $ imp_dep_pkgs imports)]
  1595. where -- The two uses of sortBy are just to reduce unnecessary
  1596. -- wobbling in testsuite output
  1597. cmp_mp (mod_name1, is_boot1) (mod_name2, is_boot2)
  1598. = (mod_name1 `stableModuleNameCmp` mod_name2)
  1599. `thenCmp`
  1600. (is_boot1 `compare` is_boot2)
  1601. pprModGuts :: ModGuts -> SDoc
  1602. pprModGuts (ModGuts { mg_tcs = tcs
  1603. , mg_rules = rules })
  1604. = vcat [ ppr_types [] (mkTypeEnv (map ATyCon tcs)),
  1605. ppr_rules rules ]
  1606. ppr_types :: [ClsInst] -> TypeEnv -> SDoc
  1607. ppr_types insts type_env
  1608. = text "TYPE SIGNATURES" $$ nest 2 (ppr_sigs ids)
  1609. where
  1610. dfun_ids = map instanceDFunId insts
  1611. ids = [id | id <- typeEnvIds type_env, want_sig id]
  1612. want_sig id | opt_PprStyle_Debug = True
  1613. | otherwise = isLocalId id &&
  1614. isExternalName (idName id) &&
  1615. not (id `elem` dfun_ids)
  1616. -- isLocalId ignores data constructors, records selectors etc.
  1617. -- The isExternalName ignores local dictionary and method bindings
  1618. -- that the type checker has invented. Top-level user-defined things
  1619. -- have External names.
  1620. ppr_tycons :: [FamInst br] -> TypeEnv -> SDoc
  1621. ppr_tycons fam_insts type_env
  1622. = vcat [ text "TYPE CONSTRUCTORS"
  1623. , nest 2 (ppr_tydecls tycons)
  1624. , text "COERCION AXIOMS"
  1625. , nest 2 (vcat (map pprCoAxiom (typeEnvCoAxioms type_env))) ]
  1626. where
  1627. fi_tycons = famInstsRepTyCons fam_insts
  1628. tycons = [tycon | tycon <- typeEnvTyCons type_env, want_tycon tycon]
  1629. want_tycon tycon | opt_PprStyle_Debug = True
  1630. | otherwise = not (isImplicitTyCon tycon) &&
  1631. isExternalName (tyConName tycon) &&
  1632. not (tycon `elem` fi_tycons)
  1633. ppr_insts :: [ClsInst] -> SDoc
  1634. ppr_insts [] = empty
  1635. ppr_insts ispecs = text "INSTANCES" $$ nest 2 (pprInstances ispecs)
  1636. ppr_fam_insts :: [FamInst br] -> SDoc
  1637. ppr_fam_insts [] = empty
  1638. ppr_fam_insts fam_insts =
  1639. text "FAMILY INSTANCES" $$ nest 2 (pprFamInsts fam_insts)
  1640. ppr_sigs :: [Var] -> SDoc
  1641. ppr_sigs ids
  1642. -- Print type signatures; sort by OccName
  1643. = vcat (map ppr_sig (sortBy (comparing getOccName) ids))
  1644. where
  1645. ppr_sig id = hang (ppr id <+> dcolon) 2 (ppr (tidyTopType (idType id)))
  1646. ppr_tydecls :: [TyCon] -> SDoc
  1647. ppr_tydecls tycons
  1648. -- Print type constructor info; sort by OccName
  1649. = vcat (map ppr_tycon (sortBy (comparing getOccName) tycons))
  1650. where
  1651. ppr_tycon tycon = vcat [ ppr (tyConName tycon) <+> dcolon <+> ppr (tyConKind tycon)
  1652. -- Temporarily print the kind signature too
  1653. , ppr (tyThingToIfaceDecl (ATyCon tycon)) ]
  1654. ppr_rules :: [CoreRule] -> SDoc
  1655. ppr_rules [] = empty
  1656. ppr_rules rs = vcat [ptext (sLit "{-# RULES"),
  1657. nest 2 (pprRules rs),
  1658. ptext (sLit "#-}")]
  1659. \end{code}