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

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

http://picorec.googlecode.com/
Haskell | 1659 lines | 1084 code | 260 blank | 315 comment | 38 complexity | a78c754c36441489fd110568e6353596 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause

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

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

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