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

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

http://picorec.googlecode.com/
Haskell | 1160 lines | 660 code | 205 blank | 295 comment | 15 complexity | 5b32758fa127641dc3ca9b71281134e3 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause
  1. % (c) The University of Glasgow 2006
  2. % (c) The GRASP Project, Glasgow University, 1992-2002
  3. %
  4. \begin{code}
  5. module TcRnTypes(
  6. TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
  7. TcRef,
  8. -- The environment types
  9. Env(..),
  10. TcGblEnv(..), TcLclEnv(..),
  11. IfGblEnv(..), IfLclEnv(..),
  12. -- Ranamer types
  13. ErrCtxt, RecFieldEnv(..),
  14. ImportAvails(..), emptyImportAvails, plusImportAvails,
  15. WhereFrom(..), mkModDeps,
  16. -- Typechecker types
  17. TcTypeEnv, TcTyThing(..), pprTcTyThingCategory,
  18. -- Template Haskell
  19. ThStage(..), topStage, topAnnStage, topSpliceStage,
  20. ThLevel, impLevel, outerLevel, thLevel,
  21. -- Arrows
  22. ArrowCtxt(NoArrowCtxt), newArrowScope, escapeArrowScope,
  23. -- Constraints
  24. Untouchables(..), inTouchableRange, isNoUntouchables,
  25. WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
  26. andWC, addFlats, addImplics, mkFlatWC,
  27. EvVarX(..), mkEvVarX, evVarOf, evVarX, evVarOfPred,
  28. WantedEvVar, wantedToFlavored,
  29. keepWanted,
  30. Implication(..),
  31. CtLoc(..), ctLocSpan, ctLocOrigin, setCtLocOrigin,
  32. CtOrigin(..), EqOrigin(..),
  33. WantedLoc, GivenLoc, pushErrCtxt,
  34. SkolemInfo(..),
  35. CtFlavor(..), pprFlavorArising, isWanted, isGiven, isDerived,
  36. FlavoredEvVar,
  37. -- Pretty printing
  38. pprEvVarTheta, pprWantedEvVar, pprWantedsWithLocs,
  39. pprEvVars, pprEvVarWithType,
  40. pprArising, pprArisingAt,
  41. -- Misc other types
  42. TcId, TcIdSet, TcTyVarBind(..), TcTyVarBinds
  43. ) where
  44. #include "HsVersions.h"
  45. import HsSyn
  46. import HscTypes
  47. import Type
  48. import Class ( Class )
  49. import DataCon ( DataCon, dataConUserType )
  50. import TcType
  51. import Annotations
  52. import InstEnv
  53. import FamInstEnv
  54. import IOEnv
  55. import RdrName
  56. import Name
  57. import NameEnv
  58. import NameSet
  59. import Var
  60. import VarEnv
  61. import Module
  62. import SrcLoc
  63. import VarSet
  64. import ErrUtils
  65. import UniqFM
  66. import UniqSupply
  67. import Unique
  68. import BasicTypes
  69. import Bag
  70. import Outputable
  71. import ListSetOps
  72. import FastString
  73. import Data.Set (Set)
  74. \end{code}
  75. %************************************************************************
  76. %* *
  77. Standard monad definition for TcRn
  78. All the combinators for the monad can be found in TcRnMonad
  79. %* *
  80. %************************************************************************
  81. The monad itself has to be defined here, because it is mentioned by ErrCtxt
  82. \begin{code}
  83. type TcRef a = IORef a
  84. type TcId = Id -- Type may be a TcType DV: WHAT??????????
  85. type TcIdSet = IdSet
  86. type TcRnIf a b c = IOEnv (Env a b) c
  87. type IfM lcl a = TcRnIf IfGblEnv lcl a -- Iface stuff
  88. type IfG a = IfM () a -- Top level
  89. type IfL a = IfM IfLclEnv a -- Nested
  90. type TcRn a = TcRnIf TcGblEnv TcLclEnv a
  91. type RnM a = TcRn a -- Historical
  92. type TcM a = TcRn a -- Historical
  93. \end{code}
  94. Representation of type bindings to uninstantiated meta variables used during
  95. constraint solving.
  96. \begin{code}
  97. data TcTyVarBind = TcTyVarBind TcTyVar TcType
  98. type TcTyVarBinds = Bag TcTyVarBind
  99. instance Outputable TcTyVarBind where
  100. ppr (TcTyVarBind tv ty) = ppr tv <+> text ":=" <+> ppr ty
  101. \end{code}
  102. %************************************************************************
  103. %* *
  104. The main environment types
  105. %* *
  106. %************************************************************************
  107. \begin{code}
  108. data Env gbl lcl -- Changes as we move into an expression
  109. = Env {
  110. env_top :: HscEnv, -- Top-level stuff that never changes
  111. -- Includes all info about imported things
  112. env_us :: {-# UNPACK #-} !(IORef UniqSupply),
  113. -- Unique supply for local varibles
  114. env_gbl :: gbl, -- Info about things defined at the top level
  115. -- of the module being compiled
  116. env_lcl :: lcl -- Nested stuff; changes as we go into
  117. }
  118. -- TcGblEnv describes the top-level of the module at the
  119. -- point at which the typechecker is finished work.
  120. -- It is this structure that is handed on to the desugarer
  121. data TcGblEnv
  122. = TcGblEnv {
  123. tcg_mod :: Module, -- ^ Module being compiled
  124. tcg_src :: HscSource,
  125. -- ^ What kind of module (regular Haskell, hs-boot, ext-core)
  126. tcg_rdr_env :: GlobalRdrEnv, -- ^ Top level envt; used during renaming
  127. tcg_default :: Maybe [Type],
  128. -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
  129. tcg_fix_env :: FixityEnv, -- ^ Just for things in this module
  130. tcg_field_env :: RecFieldEnv, -- ^ Just for things in this module
  131. tcg_type_env :: TypeEnv,
  132. -- ^ Global type env for the module we are compiling now. All
  133. -- TyCons and Classes (for this module) end up in here right away,
  134. -- along with their derived constructors, selectors.
  135. --
  136. -- (Ids defined in this module start in the local envt, though they
  137. -- move to the global envt during zonking)
  138. tcg_type_env_var :: TcRef TypeEnv,
  139. -- Used only to initialise the interface-file
  140. -- typechecker in initIfaceTcRn, so that it can see stuff
  141. -- bound in this module when dealing with hi-boot recursions
  142. -- Updated at intervals (e.g. after dealing with types and classes)
  143. tcg_inst_env :: InstEnv,
  144. -- ^ Instance envt for /home-package/ modules; Includes the dfuns in
  145. -- tcg_insts
  146. tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
  147. -- Now a bunch of things about this module that are simply
  148. -- accumulated, but never consulted until the end.
  149. -- Nevertheless, it's convenient to accumulate them along
  150. -- with the rest of the info from this module.
  151. tcg_exports :: [AvailInfo], -- ^ What is exported
  152. tcg_imports :: ImportAvails,
  153. -- ^ Information about what was imported from where, including
  154. -- things bound in this module.
  155. tcg_dus :: DefUses,
  156. -- ^ What is defined in this module and what is used.
  157. -- The latter is used to generate
  158. --
  159. -- (a) version tracking; no need to recompile if these things have
  160. -- not changed version stamp
  161. --
  162. -- (b) unused-import info
  163. tcg_keep :: TcRef NameSet,
  164. -- ^ Locally-defined top-level names to keep alive.
  165. --
  166. -- "Keep alive" means give them an Exported flag, so that the
  167. -- simplifier does not discard them as dead code, and so that they
  168. -- are exposed in the interface file (but not to export to the
  169. -- user).
  170. --
  171. -- Some things, like dict-fun Ids and default-method Ids are "born"
  172. -- with the Exported flag on, for exactly the above reason, but some
  173. -- we only discover as we go. Specifically:
  174. --
  175. -- * The to/from functions for generic data types
  176. --
  177. -- * Top-level variables appearing free in the RHS of an orphan
  178. -- rule
  179. --
  180. -- * Top-level variables appearing free in a TH bracket
  181. tcg_th_used :: TcRef Bool,
  182. -- ^ @True@ <=> Template Haskell syntax used.
  183. --
  184. -- We need this so that we can generate a dependency on the
  185. -- Template Haskell package, becuase the desugarer is going
  186. -- to emit loads of references to TH symbols. The reference
  187. -- is implicit rather than explicit, so we have to zap a
  188. -- mutable variable.
  189. tcg_dfun_n :: TcRef OccSet,
  190. -- ^ Allows us to choose unique DFun names.
  191. -- The next fields accumulate the payload of the module
  192. -- The binds, rules and foreign-decl fiels are collected
  193. -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
  194. tcg_rn_exports :: Maybe [Located (IE Name)],
  195. tcg_rn_imports :: [LImportDecl Name],
  196. -- Keep the renamed imports regardless. They are not
  197. -- voluminous and are needed if you want to report unused imports
  198. tcg_used_rdrnames :: TcRef (Set RdrName),
  199. -- The set of used *imported* (not locally-defined) RdrNames
  200. -- Used only to report unused import declarations
  201. tcg_rn_decls :: Maybe (HsGroup Name),
  202. -- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
  203. -- decls.
  204. tcg_ev_binds :: Bag EvBind, -- Top-level evidence bindings
  205. tcg_binds :: LHsBinds Id, -- Value bindings in this module
  206. tcg_sigs :: NameSet, -- ...Top-level names that *lack* a signature
  207. tcg_imp_specs :: [LTcSpecPrag], -- ...SPECIALISE prags for imported Ids
  208. tcg_warns :: Warnings, -- ...Warnings and deprecations
  209. tcg_anns :: [Annotation], -- ...Annotations
  210. tcg_insts :: [Instance], -- ...Instances
  211. tcg_fam_insts :: [FamInst], -- ...Family instances
  212. tcg_rules :: [LRuleDecl Id], -- ...Rules
  213. tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
  214. tcg_doc_hdr :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
  215. tcg_hpc :: AnyHpcUsage, -- ^ @True@ if any part of the
  216. -- prog uses hpc instrumentation.
  217. tcg_main :: Maybe Name -- ^ The Name of the main
  218. -- function, if this module is
  219. -- the main module.
  220. }
  221. data RecFieldEnv
  222. = RecFields (NameEnv [Name]) -- Maps a constructor name *in this module*
  223. -- to the fields for that constructor
  224. NameSet -- Set of all fields declared *in this module*;
  225. -- used to suppress name-shadowing complaints
  226. -- when using record wild cards
  227. -- E.g. let fld = e in C {..}
  228. -- This is used when dealing with ".." notation in record
  229. -- construction and pattern matching.
  230. -- The FieldEnv deals *only* with constructors defined in *this*
  231. -- module. For imported modules, we get the same info from the
  232. -- TypeEnv
  233. \end{code}
  234. %************************************************************************
  235. %* *
  236. The interface environments
  237. Used when dealing with IfaceDecls
  238. %* *
  239. %************************************************************************
  240. \begin{code}
  241. data IfGblEnv
  242. = IfGblEnv {
  243. -- The type environment for the module being compiled,
  244. -- in case the interface refers back to it via a reference that
  245. -- was originally a hi-boot file.
  246. -- We need the module name so we can test when it's appropriate
  247. -- to look in this env.
  248. if_rec_types :: Maybe (Module, IfG TypeEnv)
  249. -- Allows a read effect, so it can be in a mutable
  250. -- variable; c.f. handling the external package type env
  251. -- Nothing => interactive stuff, no loops possible
  252. }
  253. data IfLclEnv
  254. = IfLclEnv {
  255. -- The module for the current IfaceDecl
  256. -- So if we see f = \x -> x
  257. -- it means M.f = \x -> x, where M is the if_mod
  258. if_mod :: Module,
  259. -- The field is used only for error reporting
  260. -- if (say) there's a Lint error in it
  261. if_loc :: SDoc,
  262. -- Where the interface came from:
  263. -- .hi file, or GHCi state, or ext core
  264. -- plus which bit is currently being examined
  265. if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
  266. if_id_env :: UniqFM Id -- Nested id binding
  267. }
  268. \end{code}
  269. %************************************************************************
  270. %* *
  271. The local typechecker environment
  272. %* *
  273. %************************************************************************
  274. The Global-Env/Local-Env story
  275. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  276. During type checking, we keep in the tcg_type_env
  277. * All types and classes
  278. * All Ids derived from types and classes (constructors, selectors)
  279. At the end of type checking, we zonk the local bindings,
  280. and as we do so we add to the tcg_type_env
  281. * Locally defined top-level Ids
  282. Why? Because they are now Ids not TcIds. This final GlobalEnv is
  283. a) fed back (via the knot) to typechecking the
  284. unfoldings of interface signatures
  285. b) used in the ModDetails of this module
  286. \begin{code}
  287. data TcLclEnv -- Changes as we move inside an expression
  288. -- Discarded after typecheck/rename; not passed on to desugarer
  289. = TcLclEnv {
  290. tcl_loc :: SrcSpan, -- Source span
  291. tcl_ctxt :: [ErrCtxt], -- Error context, innermost on top
  292. tcl_errs :: TcRef Messages, -- Place to accumulate errors
  293. tcl_th_ctxt :: ThStage, -- Template Haskell context
  294. tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
  295. tcl_rdr :: LocalRdrEnv, -- Local name envt
  296. -- Maintained during renaming, of course, but also during
  297. -- type checking, solely so that when renaming a Template-Haskell
  298. -- splice we have the right environment for the renamer.
  299. --
  300. -- Does *not* include global name envt; may shadow it
  301. -- Includes both ordinary variables and type variables;
  302. -- they are kept distinct because tyvar have a different
  303. -- occurrence contructor (Name.TvOcc)
  304. -- We still need the unsullied global name env so that
  305. -- we can look up record field names
  306. tcl_env :: TcTypeEnv, -- The local type environment: Ids and
  307. -- TyVars defined in this module
  308. tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
  309. -- Namely, the in-scope TyVars bound in tcl_env,
  310. -- plus the tyvars mentioned in the types of Ids bound
  311. -- in tcl_lenv.
  312. -- Why mutable? see notes with tcGetGlobalTyVars
  313. tcl_lie :: TcRef WantedConstraints, -- Place to accumulate type constraints
  314. -- TcMetaTyVars have
  315. tcl_meta :: TcRef Unique, -- The next free unique for TcMetaTyVars
  316. -- Guaranteed to be allocated linearly
  317. tcl_untch :: Unique -- Any TcMetaTyVar with
  318. -- unique >= tcl_untch is touchable
  319. -- unique < tcl_untch is untouchable
  320. }
  321. type TcTypeEnv = NameEnv TcTyThing
  322. {- Note [Given Insts]
  323. ~~~~~~~~~~~~~~~~~~
  324. Because of GADTs, we have to pass inwards the Insts provided by type signatures
  325. and existential contexts. Consider
  326. data T a where { T1 :: b -> b -> T [b] }
  327. f :: Eq a => T a -> Bool
  328. f (T1 x y) = [x]==[y]
  329. The constructor T1 binds an existential variable 'b', and we need Eq [b].
  330. Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
  331. pass it inwards.
  332. -}
  333. ---------------------------
  334. -- Template Haskell stages and levels
  335. ---------------------------
  336. data ThStage -- See Note [Template Haskell state diagram] in TcSplice
  337. = Splice -- Top-level splicing
  338. -- This code will be run *at compile time*;
  339. -- the result replaces the splice
  340. -- Binding level = 0
  341. | Comp -- Ordinary Haskell code
  342. -- Binding level = 1
  343. | Brack -- Inside brackets
  344. ThStage -- Binding level = level(stage) + 1
  345. (TcRef [PendingSplice]) -- Accumulate pending splices here
  346. (TcRef WantedConstraints) -- and type constraints here
  347. topStage, topAnnStage, topSpliceStage :: ThStage
  348. topStage = Comp
  349. topAnnStage = Splice
  350. topSpliceStage = Splice
  351. instance Outputable ThStage where
  352. ppr Splice = text "Splice"
  353. ppr Comp = text "Comp"
  354. ppr (Brack s _ _) = text "Brack" <> parens (ppr s)
  355. type ThLevel = Int
  356. -- See Note [Template Haskell levels] in TcSplice
  357. -- Incremented when going inside a bracket,
  358. -- decremented when going inside a splice
  359. -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
  360. -- original "Template meta-programming for Haskell" paper
  361. impLevel, outerLevel :: ThLevel
  362. impLevel = 0 -- Imported things; they can be used inside a top level splice
  363. outerLevel = 1 -- Things defined outside brackets
  364. -- NB: Things at level 0 are not *necessarily* imported.
  365. -- eg $( \b -> ... ) here b is bound at level 0
  366. --
  367. -- For example:
  368. -- f = ...
  369. -- g1 = $(map ...) is OK
  370. -- g2 = $(f ...) is not OK; because we havn't compiled f yet
  371. thLevel :: ThStage -> ThLevel
  372. thLevel Splice = 0
  373. thLevel Comp = 1
  374. thLevel (Brack s _ _) = thLevel s + 1
  375. ---------------------------
  376. -- Arrow-notation context
  377. ---------------------------
  378. {-
  379. In arrow notation, a variable bound by a proc (or enclosed let/kappa)
  380. is not in scope to the left of an arrow tail (-<) or the head of (|..|).
  381. For example
  382. proc x -> (e1 -< e2)
  383. Here, x is not in scope in e1, but it is in scope in e2. This can get
  384. a bit complicated:
  385. let x = 3 in
  386. proc y -> (proc z -> e1) -< e2
  387. Here, x and z are in scope in e1, but y is not. We implement this by
  388. recording the environment when passing a proc (using newArrowScope),
  389. and returning to that (using escapeArrowScope) on the left of -< and the
  390. head of (|..|).
  391. -}
  392. data ArrowCtxt
  393. = NoArrowCtxt
  394. | ArrowCtxt (Env TcGblEnv TcLclEnv)
  395. -- Record the current environment (outside a proc)
  396. newArrowScope :: TcM a -> TcM a
  397. newArrowScope
  398. = updEnv $ \env ->
  399. env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
  400. -- Return to the stored environment (from the enclosing proc)
  401. escapeArrowScope :: TcM a -> TcM a
  402. escapeArrowScope
  403. = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
  404. NoArrowCtxt -> env
  405. ArrowCtxt env' -> env'
  406. ---------------------------
  407. -- TcTyThing
  408. ---------------------------
  409. data TcTyThing
  410. = AGlobal TyThing -- Used only in the return type of a lookup
  411. | ATcId { -- Ids defined in this module; may not be fully zonked
  412. tct_id :: TcId,
  413. tct_level :: ThLevel }
  414. | ATyVar Name TcType -- The type to which the lexically scoped type vaiable
  415. -- is currently refined. We only need the Name
  416. -- for error-message purposes; it is the corresponding
  417. -- Name in the domain of the envt
  418. | AThing TcKind -- Used temporarily, during kind checking, for the
  419. -- tycons and clases in this recursive group
  420. instance Outputable TcTyThing where -- Debugging only
  421. ppr (AGlobal g) = pprTyThing g
  422. ppr elt@(ATcId {}) = text "Identifier" <>
  423. brackets (ppr (tct_id elt) <> dcolon
  424. <> ppr (varType (tct_id elt)) <> comma
  425. <+> ppr (tct_level elt))
  426. ppr (ATyVar tv _) = text "Type variable" <+> quotes (ppr tv)
  427. ppr (AThing k) = text "AThing" <+> ppr k
  428. pprTcTyThingCategory :: TcTyThing -> SDoc
  429. pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
  430. pprTcTyThingCategory (ATyVar {}) = ptext (sLit "Type variable")
  431. pprTcTyThingCategory (ATcId {}) = ptext (sLit "Local identifier")
  432. pprTcTyThingCategory (AThing {}) = ptext (sLit "Kinded thing")
  433. \end{code}
  434. \begin{code}
  435. type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, Message))
  436. -- Monadic so that we have a chance
  437. -- to deal with bound type variables just before error
  438. -- message construction
  439. -- Bool: True <=> this is a landmark context; do not
  440. -- discard it when trimming for display
  441. \end{code}
  442. %************************************************************************
  443. %* *
  444. Operations over ImportAvails
  445. %* *
  446. %************************************************************************
  447. \begin{code}
  448. -- | 'ImportAvails' summarises what was imported from where, irrespective of
  449. -- whether the imported things are actually used or not. It is used:
  450. --
  451. -- * when processing the export list,
  452. --
  453. -- * when constructing usage info for the interface file,
  454. --
  455. -- * to identify the list of directly imported modules for initialisation
  456. -- purposes and for optimised overlap checking of family instances,
  457. --
  458. -- * when figuring out what things are really unused
  459. --
  460. data ImportAvails
  461. = ImportAvails {
  462. imp_mods :: ModuleEnv [(ModuleName, Bool, SrcSpan)],
  463. -- ^ Domain is all directly-imported modules
  464. -- The 'ModuleName' is what the module was imported as, e.g. in
  465. -- @
  466. -- import Foo as Bar
  467. -- @
  468. -- it is @Bar@.
  469. --
  470. -- The 'Bool' means:
  471. --
  472. -- - @True@ => import was @import Foo ()@
  473. --
  474. -- - @False@ => import was some other form
  475. --
  476. -- Used
  477. --
  478. -- (a) to help construct the usage information in the interface
  479. -- file; if we import somethign we need to recompile if the
  480. -- export version changes
  481. --
  482. -- (b) to specify what child modules to initialise
  483. --
  484. -- We need a full ModuleEnv rather than a ModuleNameEnv here,
  485. -- because we might be importing modules of the same name from
  486. -- different packages. (currently not the case, but might be in the
  487. -- future).
  488. imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
  489. -- ^ Home-package modules needed by the module being compiled
  490. --
  491. -- It doesn't matter whether any of these dependencies
  492. -- are actually /used/ when compiling the module; they
  493. -- are listed if they are below it at all. For
  494. -- example, suppose M imports A which imports X. Then
  495. -- compiling M might not need to consult X.hi, but X
  496. -- is still listed in M's dependencies.
  497. imp_dep_pkgs :: [PackageId],
  498. -- ^ Packages needed by the module being compiled, whether directly,
  499. -- or via other modules in this package, or via modules imported
  500. -- from other packages.
  501. imp_orphs :: [Module],
  502. -- ^ Orphan modules below us in the import tree (and maybe including
  503. -- us for imported modules)
  504. imp_finsts :: [Module]
  505. -- ^ Family instance modules below us in the import tree (and maybe
  506. -- including us for imported modules)
  507. }
  508. mkModDeps :: [(ModuleName, IsBootInterface)]
  509. -> ModuleNameEnv (ModuleName, IsBootInterface)
  510. mkModDeps deps = foldl add emptyUFM deps
  511. where
  512. add env elt@(m,_) = addToUFM env m elt
  513. emptyImportAvails :: ImportAvails
  514. emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
  515. imp_dep_mods = emptyUFM,
  516. imp_dep_pkgs = [],
  517. imp_orphs = [],
  518. imp_finsts = [] }
  519. plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
  520. plusImportAvails
  521. (ImportAvails { imp_mods = mods1,
  522. imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
  523. imp_orphs = orphs1, imp_finsts = finsts1 })
  524. (ImportAvails { imp_mods = mods2,
  525. imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
  526. imp_orphs = orphs2, imp_finsts = finsts2 })
  527. = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
  528. imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
  529. imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
  530. imp_orphs = orphs1 `unionLists` orphs2,
  531. imp_finsts = finsts1 `unionLists` finsts2 }
  532. where
  533. plus_mod_dep (m1, boot1) (m2, boot2)
  534. = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
  535. -- Check mod-names match
  536. (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
  537. \end{code}
  538. %************************************************************************
  539. %* *
  540. \subsection{Where from}
  541. %* *
  542. %************************************************************************
  543. The @WhereFrom@ type controls where the renamer looks for an interface file
  544. \begin{code}
  545. data WhereFrom
  546. = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
  547. | ImportBySystem -- Non user import.
  548. instance Outputable WhereFrom where
  549. ppr (ImportByUser is_boot) | is_boot = ptext (sLit "{- SOURCE -}")
  550. | otherwise = empty
  551. ppr ImportBySystem = ptext (sLit "{- SYSTEM -}")
  552. \end{code}
  553. %************************************************************************
  554. %* *
  555. Wanted constraints
  556. These are forced to be in TcRnTypes because
  557. TcLclEnv mentions WantedConstraints
  558. WantedConstraint mentions CtLoc
  559. CtLoc mentions ErrCtxt
  560. ErrCtxt mentions TcM
  561. %* *
  562. v%************************************************************************
  563. \begin{code}
  564. data WantedConstraints
  565. = WC { wc_flat :: Bag WantedEvVar -- Unsolved constraints, all wanted
  566. , wc_impl :: Bag Implication
  567. , wc_insol :: Bag FlavoredEvVar -- Insoluble constraints, can be
  568. -- wanted, given, or derived
  569. -- See Note [Insoluble constraints]
  570. }
  571. emptyWC :: WantedConstraints
  572. emptyWC = WC { wc_flat = emptyBag, wc_impl = emptyBag, wc_insol = emptyBag }
  573. mkFlatWC :: Bag WantedEvVar -> WantedConstraints
  574. mkFlatWC wevs = WC { wc_flat = wevs, wc_impl = emptyBag, wc_insol = emptyBag }
  575. isEmptyWC :: WantedConstraints -> Bool
  576. isEmptyWC (WC { wc_flat = f, wc_impl = i, wc_insol = n })
  577. = isEmptyBag f && isEmptyBag i && isEmptyBag n
  578. insolubleWC :: WantedConstraints -> Bool
  579. -- True if there are any insoluble constraints in the wanted bag
  580. insolubleWC wc = not (isEmptyBag (wc_insol wc))
  581. || anyBag ic_insol (wc_impl wc)
  582. andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
  583. andWC (WC { wc_flat = f1, wc_impl = i1, wc_insol = n1 })
  584. (WC { wc_flat = f2, wc_impl = i2, wc_insol = n2 })
  585. = WC { wc_flat = f1 `unionBags` f2
  586. , wc_impl = i1 `unionBags` i2
  587. , wc_insol = n1 `unionBags` n2 }
  588. addFlats :: WantedConstraints -> Bag WantedEvVar -> WantedConstraints
  589. addFlats wc wevs = wc { wc_flat = wevs `unionBags` wc_flat wc }
  590. addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
  591. addImplics wc implic = wc { wc_impl = implic `unionBags` wc_impl wc }
  592. instance Outputable WantedConstraints where
  593. ppr (WC {wc_flat = f, wc_impl = i, wc_insol = n})
  594. = ptext (sLit "WC") <+> braces (vcat
  595. [ if isEmptyBag f then empty else
  596. ptext (sLit "wc_flat =") <+> pprBag pprWantedEvVar f
  597. , if isEmptyBag i then empty else
  598. ptext (sLit "wc_impl =") <+> pprBag ppr i
  599. , if isEmptyBag n then empty else
  600. ptext (sLit "wc_insol =") <+> pprBag ppr n ])
  601. pprBag :: (a -> SDoc) -> Bag a -> SDoc
  602. pprBag pp b = foldrBag (($$) . pp) empty b
  603. \end{code}
  604. \begin{code}
  605. data Untouchables = NoUntouchables
  606. | TouchableRange
  607. Unique -- Low end
  608. Unique -- High end
  609. -- A TcMetaTyvar is *touchable* iff its unique u satisfies
  610. -- u >= low
  611. -- u < high
  612. instance Outputable Untouchables where
  613. ppr NoUntouchables = ptext (sLit "No untouchables")
  614. ppr (TouchableRange low high) = ptext (sLit "Touchable range:") <+>
  615. ppr low <+> char '-' <+> ppr high
  616. isNoUntouchables :: Untouchables -> Bool
  617. isNoUntouchables NoUntouchables = True
  618. isNoUntouchables (TouchableRange {}) = False
  619. inTouchableRange :: Untouchables -> TcTyVar -> Bool
  620. inTouchableRange NoUntouchables _ = True
  621. inTouchableRange (TouchableRange low high) tv
  622. = uniq >= low && uniq < high
  623. where
  624. uniq = varUnique tv
  625. -- EvVar defined in module Var.lhs:
  626. -- Evidence variables include all *quantifiable* constraints
  627. -- dictionaries
  628. -- implicit parameters
  629. -- coercion variables
  630. \end{code}
  631. %************************************************************************
  632. %* *
  633. Implication constraints
  634. %* *
  635. %************************************************************************
  636. \begin{code}
  637. data Implication
  638. = Implic {
  639. ic_untch :: Untouchables, -- Untouchables: unification variables
  640. -- free in the environment
  641. ic_env :: TcTypeEnv, -- The type environment
  642. -- Used only when generating error messages
  643. -- Generally, ic_untch is a superset of tvsof(ic_env)
  644. -- However, we don't zonk ic_env when zonking the Implication
  645. -- Instead we do that when generating a skolem-escape error message
  646. ic_skols :: TcTyVarSet, -- Introduced skolems
  647. -- See Note [Skolems in an implication]
  648. ic_given :: [EvVar], -- Given evidence variables
  649. -- (order does not matter)
  650. ic_loc :: GivenLoc, -- Binding location of the implication,
  651. -- which is also the location of all the
  652. -- given evidence variables
  653. ic_wanted :: WantedConstraints, -- The wanted
  654. ic_insol :: Bool, -- True iff insolubleWC ic_wantted is true
  655. ic_binds :: EvBindsVar -- Points to the place to fill in the
  656. -- abstraction and bindings
  657. }
  658. instance Outputable Implication where
  659. ppr (Implic { ic_untch = untch, ic_skols = skols, ic_given = given
  660. , ic_wanted = wanted
  661. , ic_binds = binds, ic_loc = loc })
  662. = ptext (sLit "Implic") <+> braces
  663. (sep [ ptext (sLit "Untouchables = ") <+> ppr untch
  664. , ptext (sLit "Skolems = ") <+> ppr skols
  665. , ptext (sLit "Given = ") <+> pprEvVars given
  666. , ptext (sLit "Wanted = ") <+> ppr wanted
  667. , ptext (sLit "Binds = ") <+> ppr binds
  668. , pprSkolInfo (ctLocOrigin loc)
  669. , ppr (ctLocSpan loc) ])
  670. \end{code}
  671. Note [Skolems in an implication]
  672. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  673. The skolems in an implication are not there to perform a skolem escape
  674. check. That happens because all the environment variables are in the
  675. untouchables, and therefore cannot be unified with anything at all,
  676. let alone the skolems.
  677. Instead, ic_skols is used only when considering floating a constraint
  678. outside the implication in TcSimplify.floatEqualities or
  679. TcSimplify.approximateImplications
  680. Note [Insoluble constraints]
  681. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  682. Some of the errors that we get during canonicalization are best
  683. reported when all constraints have been simplified as much as
  684. possible. For instance, assume that during simplification the
  685. following constraints arise:
  686. [Wanted] F alpha ~ uf1
  687. [Wanted] beta ~ uf1 beta
  688. When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
  689. we will simply see a message:
  690. 'Can't construct the infinite type beta ~ uf1 beta'
  691. and the user has no idea what the uf1 variable is.
  692. Instead our plan is that we will NOT fail immediately, but:
  693. (1) Record the "frozen" error in the ic_insols field
  694. (2) Isolate the offending constraint from the rest of the inerts
  695. (3) Keep on simplifying/canonicalizing
  696. At the end, we will hopefully have substituted uf1 := F alpha, and we
  697. will be able to report a more informative error:
  698. 'Can't construct the infinite type beta ~ F alpha beta'
  699. %************************************************************************
  700. %* *
  701. EvVarX, WantedEvVar, FlavoredEvVar
  702. %* *
  703. %************************************************************************
  704. \begin{code}
  705. data EvVarX a = EvVarX EvVar a
  706. -- An evidence variable with accompanying info
  707. type WantedEvVar = EvVarX WantedLoc -- The location where it arose
  708. type FlavoredEvVar = EvVarX CtFlavor
  709. instance Outputable (EvVarX a) where
  710. ppr (EvVarX ev _) = pprEvVarWithType ev
  711. -- If you want to see the associated info,
  712. -- use a more specific printing function
  713. mkEvVarX :: EvVar -> a -> EvVarX a
  714. mkEvVarX = EvVarX
  715. evVarOf :: EvVarX a -> EvVar
  716. evVarOf (EvVarX ev _) = ev
  717. evVarX :: EvVarX a -> a
  718. evVarX (EvVarX _ a) = a
  719. evVarOfPred :: EvVarX a -> PredType
  720. evVarOfPred wev = evVarPred (evVarOf wev)
  721. wantedToFlavored :: WantedEvVar -> FlavoredEvVar
  722. wantedToFlavored (EvVarX v wl) = EvVarX v (Wanted wl)
  723. keepWanted :: Bag FlavoredEvVar -> Bag WantedEvVar
  724. keepWanted flevs
  725. = foldlBag keep_wanted emptyBag flevs
  726. where
  727. keep_wanted :: Bag WantedEvVar -> FlavoredEvVar -> Bag WantedEvVar
  728. keep_wanted r (EvVarX ev (Wanted wloc)) = consBag (EvVarX ev wloc) r
  729. keep_wanted r _ = r
  730. \end{code}
  731. \begin{code}
  732. pprEvVars :: [EvVar] -> SDoc -- Print with their types
  733. pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
  734. pprEvVarTheta :: [EvVar] -> SDoc
  735. pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
  736. pprEvVarWithType :: EvVar -> SDoc
  737. pprEvVarWithType v = ppr v <+> dcolon <+> pprPred (evVarPred v)
  738. pprWantedsWithLocs :: WantedConstraints -> SDoc
  739. pprWantedsWithLocs wcs
  740. = vcat [ pprBag pprWantedEvVarWithLoc (wc_flat wcs)
  741. , pprBag ppr (wc_impl wcs)
  742. , pprBag ppr (wc_insol wcs) ]
  743. pprWantedEvVarWithLoc, pprWantedEvVar :: WantedEvVar -> SDoc
  744. pprWantedEvVarWithLoc (EvVarX v loc) = hang (pprEvVarWithType v)
  745. 2 (pprArisingAt loc)
  746. pprWantedEvVar (EvVarX v _) = pprEvVarWithType v
  747. \end{code}
  748. %************************************************************************
  749. %* *
  750. CtLoc
  751. %* *
  752. %************************************************************************
  753. \begin{code}
  754. data CtFlavor
  755. = Given GivenLoc -- We have evidence for this constraint in TcEvBinds
  756. | Derived WantedLoc
  757. -- We have evidence for this constraint in TcEvBinds;
  758. -- *however* this evidence can contain wanteds, so
  759. -- it's valid only provisionally to the solution of
  760. -- these wanteds
  761. | Wanted WantedLoc -- We have no evidence bindings for this constraint.
  762. -- data DerivedOrig = DerSC | DerInst | DerSelf
  763. -- Deriveds are either superclasses of other wanteds or deriveds, or partially
  764. -- solved wanteds from instances, or 'self' dictionaries containing yet wanted
  765. -- superclasses.
  766. instance Outputable CtFlavor where
  767. ppr (Given {}) = ptext (sLit "[G]")
  768. ppr (Wanted {}) = ptext (sLit "[W]")
  769. ppr (Derived {}) = ptext (sLit "[D]")
  770. pprFlavorArising :: CtFlavor -> SDoc
  771. pprFlavorArising (Derived wl ) = pprArisingAt wl
  772. pprFlavorArising (Wanted wl) = pprArisingAt wl
  773. pprFlavorArising (Given gl) = pprArisingAt gl
  774. isWanted :: CtFlavor -> Bool
  775. isWanted (Wanted {}) = True
  776. isWanted _ = False
  777. isGiven :: CtFlavor -> Bool
  778. isGiven (Given {}) = True
  779. isGiven _ = False
  780. isDerived :: CtFlavor -> Bool
  781. isDerived (Derived {}) = True
  782. isDerived _ = False
  783. \end{code}
  784. %************************************************************************
  785. %* *
  786. CtLoc
  787. %* *
  788. %************************************************************************
  789. The 'CtLoc' gives information about where a constraint came from.
  790. This is important for decent error message reporting because
  791. dictionaries don't appear in the original source code.
  792. type will evolve...
  793. \begin{code}
  794. data CtLoc orig = CtLoc orig SrcSpan [ErrCtxt]
  795. type WantedLoc = CtLoc CtOrigin -- Instantiation for wanted constraints
  796. type GivenLoc = CtLoc SkolemInfo -- Instantiation for given constraints
  797. ctLocSpan :: CtLoc o -> SrcSpan
  798. ctLocSpan (CtLoc _ s _) = s
  799. ctLocOrigin :: CtLoc o -> o
  800. ctLocOrigin (CtLoc o _ _) = o
  801. setCtLocOrigin :: CtLoc o -> o' -> CtLoc o'
  802. setCtLocOrigin (CtLoc _ s c) o = CtLoc o s c
  803. pushErrCtxt :: orig -> ErrCtxt -> CtLoc orig -> CtLoc orig
  804. pushErrCtxt o err (CtLoc _ s errs) = CtLoc o s (err:errs)
  805. pprArising :: CtOrigin -> SDoc
  806. -- Used for the main, top-level error message
  807. -- We've done special processing for TypeEq and FunDep origins
  808. pprArising (TypeEqOrigin {}) = empty
  809. pprArising FunDepOrigin = empty
  810. pprArising orig = text "arising from" <+> ppr orig
  811. pprArisingAt :: Outputable o => CtLoc o -> SDoc
  812. pprArisingAt (CtLoc o s _) = sep [ text "arising from" <+> ppr o
  813. , text "at" <+> ppr s]
  814. \end{code}
  815. %************************************************************************
  816. %* *
  817. SkolemInfo
  818. %* *
  819. %************************************************************************
  820. \begin{code}
  821. -- SkolemInfo gives the origin of *given* constraints
  822. -- a) type variables are skolemised
  823. -- b) an implication constraint is generated
  824. data SkolemInfo
  825. = SigSkol UserTypeCtxt -- A skolem that is created by instantiating
  826. Type -- a programmer-supplied type signature
  827. -- Location of the binding site is on the TyVar
  828. -- The rest are for non-scoped skolems
  829. | ClsSkol Class -- Bound at a class decl
  830. | InstSkol -- Bound at an instance decl
  831. | DataSkol -- Bound at a data type declaration
  832. | FamInstSkol -- Bound at a family instance decl
  833. | PatSkol -- An existential type variable bound by a pattern for
  834. DataCon -- a data constructor with an existential type.
  835. (HsMatchContext Name)
  836. -- e.g. data T = forall a. Eq a => MkT a
  837. -- f (MkT x) = ...
  838. -- The pattern MkT x will allocate an existential type
  839. -- variable for 'a'.
  840. | ArrowSkol -- An arrow form (see TcArrows)
  841. | IPSkol [IPName Name] -- Binding site of an implicit parameter
  842. | RuleSkol RuleName -- The LHS of a RULE
  843. | InferSkol [(Name,TcType)]
  844. -- We have inferred a type for these (mutually-recursivive)
  845. -- polymorphic Ids, and are now checking that their RHS
  846. -- constraints are satisfied.
  847. | RuntimeUnkSkol -- a type variable used to represent an unknown
  848. -- runtime type (used in the GHCi debugger)
  849. | BracketSkol -- Template Haskell bracket
  850. | UnkSkol -- Unhelpful info (until I improve it)
  851. instance Outputable SkolemInfo where
  852. ppr = pprSkolInfo
  853. pprSkolInfo :: SkolemInfo -> SDoc
  854. -- Complete the sentence "is a rigid type variable bound by..."
  855. pprSkolInfo (SigSkol (FunSigCtxt f) ty)
  856. = hang (ptext (sLit "the type signature for"))
  857. 2 (ppr f <+> dcolon <+> ppr ty)
  858. pprSkolInfo (SigSkol cx ty) = hang (pprUserTypeCtxt cx <> colon)
  859. 2 (ppr ty)
  860. pprSkolInfo (IPSkol ips) = ptext (sLit "the implicit-parameter bindings for")
  861. <+> pprWithCommas ppr ips
  862. pprSkolInfo (ClsSkol cls) = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
  863. pprSkolInfo InstSkol = ptext (sLit "the instance declaration")
  864. pprSkolInfo DataSkol = ptext (sLit "the data type declaration")
  865. pprSkolInfo FamInstSkol = ptext (sLit "the family instance declaration")
  866. pprSkolInfo BracketSkol = ptext (sLit "a Template Haskell bracket")
  867. pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
  868. pprSkolInfo ArrowSkol = ptext (sLit "the arrow form")
  869. pprSkolInfo (PatSkol dc mc) = sep [ ptext (sLit "a pattern with constructor")
  870. , nest 2 $ ppr dc <+> dcolon
  871. <+> ppr (dataConUserType dc) <> comma
  872. , ptext (sLit "in") <+> pprMatchContext mc ]
  873. pprSkolInfo (InferSkol ids) = sep [ ptext (sLit "the inferred type of")
  874. , vcat [ ppr name <+> dcolon <+> ppr ty
  875. | (name,ty) <- ids ]]
  876. -- UnkSkol
  877. -- For type variables the others are dealt with by pprSkolTvBinding.
  878. -- For Insts, these cases should not happen
  879. pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
  880. pprSkolInfo RuntimeUnkSkol = WARN( True, text "pprSkolInfo: RuntimeUnkSkol" ) ptext (sLit "RuntimeUnkSkol")
  881. \end{code}
  882. %************************************************************************
  883. %* *
  884. CtOrigin
  885. %* *
  886. %************************************************************************
  887. \begin{code}
  888. -- CtOrigin gives the origin of *wanted* constraints
  889. data CtOrigin
  890. = OccurrenceOf Name -- Occurrence of an overloaded identifier
  891. | AppOrigin -- An application of some kind
  892. | SpecPragOrigin Name -- Specialisation pragma for identifier
  893. | TypeEqOrigin EqOrigin
  894. | IPOccOrigin (IPName Name) -- Occurrence of an implicit parameter
  895. | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
  896. | NegateOrigin -- Occurrence of syntactic negation
  897. | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
  898. | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
  899. | SectionOrigin
  900. | TupleOrigin -- (..,..)
  901. | ExprSigOrigin -- e :: ty
  902. | PatSigOrigin -- p :: ty
  903. | PatOrigin -- Instantiating a polytyped pattern at a constructor
  904. | RecordUpdOrigin
  905. | ViewPatOrigin
  906. | ScOrigin -- Typechecking superclasses of an instance declaration
  907. | DerivOrigin -- Typechecking deriving
  908. | StandAloneDerivOrigin -- Typechecking stand-alone deriving
  909. | DefaultOrigin -- Typechecking a default decl
  910. | DoOrigin -- Arising from a do expression
  911. | IfOrigin -- Arising from an if statement
  912. | ProcOrigin -- Arising from a proc expression
  913. | AnnOrigin -- An annotation
  914. | FunDepOrigin
  915. data EqOrigin
  916. = UnifyOrigin
  917. { uo_actual :: TcType
  918. , uo_expected :: TcType }
  919. instance Outputable CtOrigin where
  920. ppr orig = pprO orig
  921. pprO :: CtOrigin -> SDoc
  922. pprO (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
  923. pprO AppOrigin = ptext (sLit "an application")
  924. pprO (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
  925. pprO (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
  926. pprO RecordUpdOrigin = ptext (sLit "a record update")
  927. pprO ExprSigOrigin = ptext (sLit "an expression type signature")
  928. pprO PatSigOrigin = ptext (sLit "a pattern type signature")
  929. pprO PatOrigin = ptext (sLit "a pattern")
  930. pprO ViewPatOrigin = ptext (sLit "a view pattern")
  931. pprO IfOrigin = ptext (sLit "an if statement")
  932. pprO (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
  933. pprO (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
  934. pprO (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
  935. pprO SectionOrigin = ptext (sLit "an operator section")
  936. pprO TupleOrigin = ptext (sLit "a tuple")
  937. pprO NegateOrigin = ptext (sLit "a use of syntactic negation")
  938. pprO ScOrigin = ptext (sLit "the superclasses of an instance declaration")
  939. pprO DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
  940. pprO StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
  941. pprO DefaultOrigin = ptext (sLit "a 'default' declaration")
  942. pprO DoOrigin = ptext (sLit "a do statement")
  943. pprO ProcOrigin = ptext (sLit "a proc expression")
  944. pprO (TypeEqOrigin eq) = ptext (sLit "an equality") <+> ppr eq
  945. pprO AnnOrigin = ptext (sLit "an annotation")
  946. pprO FunDepOrigin = ptext (sLit "a functional dependency")
  947. instance Outputable EqOrigin where
  948. ppr (UnifyOrigin t1 t2) = ppr t1 <+> char '~' <+> ppr t2
  949. \end{code}