PageRenderTime 29ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/typecheck/TcRnDriver.lhs

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