PageRenderTime 67ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/typecheck/TcRnTypes.lhs

http://github.com/ghc/ghc
Haskell | 1701 lines | 1034 code | 302 blank | 365 comment | 30 complexity | 9d3f720a446a632a7204263b7ca93115 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, GPL-3.0

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

  1. % (c) The University of Glasgow 2006-2012
  2. % (c) The GRASP Project, Glasgow University, 1992-2002
  3. %
  4. Various types used during typechecking, please see TcRnMonad as well for
  5. operations on these types. You probably want to import it, instead of this
  6. module.
  7. All the monads exported here are built on top of the same IOEnv monad. The
  8. monad functions like a Reader monad in the way it passes the environment
  9. around. This is done to allow the environment to be manipulated in a stack
  10. like fashion when entering expressions... ect.
  11. For state that is global and should be returned at the end (e.g not part
  12. of the stack mechanism), you should use an TcRef (= IORef) to store them.
  13. \begin{code}
  14. module TcRnTypes(
  15. TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
  16. TcRef,
  17. -- The environment types
  18. Env(..),
  19. TcGblEnv(..), TcLclEnv(..),
  20. IfGblEnv(..), IfLclEnv(..),
  21. -- Ranamer types
  22. ErrCtxt, RecFieldEnv(..),
  23. ImportAvails(..), emptyImportAvails, plusImportAvails,
  24. WhereFrom(..), mkModDeps,
  25. -- Typechecker types
  26. TcTypeEnv, TcIdBinder(..), TcTyThing(..), PromotionErr(..),
  27. pprTcTyThingCategory, pprPECategory,
  28. -- Template Haskell
  29. ThStage(..), topStage, topAnnStage, topSpliceStage,
  30. ThLevel, impLevel, outerLevel, thLevel,
  31. -- Arrows
  32. ArrowCtxt(NoArrowCtxt), newArrowScope, escapeArrowScope,
  33. -- Canonical constraints
  34. Xi, Ct(..), Cts, emptyCts, andCts, andManyCts, dropDerivedWC,
  35. singleCt, extendCts, isEmptyCts, isCTyEqCan, isCFunEqCan,
  36. isCDictCan_Maybe, isCFunEqCan_maybe,
  37. isCIrredEvCan, isCNonCanonical, isWantedCt, isDerivedCt,
  38. isGivenCt, isHoleCt,
  39. ctEvidence,
  40. SubGoalDepth, mkNonCanonical, mkNonCanonicalCt,
  41. ctPred, ctEvPred, ctEvTerm, ctEvId,
  42. WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
  43. andWC, unionsWC, addFlats, addImplics, mkFlatWC, addInsols,
  44. Implication(..),
  45. CtLoc(..), ctLocSpan, ctLocEnv, ctLocOrigin,
  46. ctLocDepth, bumpCtLocDepth,
  47. setCtLocOrigin, setCtLocEnv,
  48. CtOrigin(..),
  49. pushErrCtxt, pushErrCtxtSameOrigin,
  50. SkolemInfo(..),
  51. CtEvidence(..),
  52. mkGivenLoc,
  53. isWanted, isGiven,
  54. isDerived, canSolve, canRewrite,
  55. CtFlavour(..), ctEvFlavour, ctFlavour,
  56. -- Pretty printing
  57. pprEvVarTheta, pprWantedsWithLocs,
  58. pprEvVars, pprEvVarWithType,
  59. pprArising, pprArisingAt,
  60. -- Misc other types
  61. TcId, TcIdSet, TcTyVarBind(..), TcTyVarBinds
  62. ) where
  63. #include "HsVersions.h"
  64. import HsSyn
  65. import HscTypes
  66. import TcEvidence
  67. import Type
  68. import Class ( Class )
  69. import TyCon ( TyCon )
  70. import DataCon ( DataCon, dataConUserType )
  71. import TcType
  72. import Annotations
  73. import InstEnv
  74. import FamInstEnv
  75. import IOEnv
  76. import RdrName
  77. import Name
  78. import NameEnv
  79. import NameSet
  80. import Avail
  81. import Var
  82. import VarEnv
  83. import Module
  84. import SrcLoc
  85. import VarSet
  86. import ErrUtils
  87. import UniqFM
  88. import UniqSupply
  89. import BasicTypes
  90. import Bag
  91. import DynFlags
  92. import Outputable
  93. import ListSetOps
  94. import FastString
  95. import Data.Set (Set)
  96. #ifdef GHCI
  97. import Data.Map ( Map )
  98. import Data.Dynamic ( Dynamic )
  99. import Data.Typeable ( TypeRep )
  100. import qualified Language.Haskell.TH as TH
  101. #endif
  102. \end{code}
  103. %************************************************************************
  104. %* *
  105. Standard monad definition for TcRn
  106. All the combinators for the monad can be found in TcRnMonad
  107. %* *
  108. %************************************************************************
  109. The monad itself has to be defined here, because it is mentioned by ErrCtxt
  110. \begin{code}
  111. type TcRef a = IORef a
  112. type TcId = Id
  113. type TcIdSet = IdSet
  114. type TcRnIf a b c = IOEnv (Env a b) c
  115. type IfM lcl a = TcRnIf IfGblEnv lcl a -- Iface stuff
  116. type IfG a = IfM () a -- Top level
  117. type IfL a = IfM IfLclEnv a -- Nested
  118. type TcRn a = TcRnIf TcGblEnv TcLclEnv a
  119. type RnM a = TcRn a -- Historical
  120. type TcM a = TcRn a -- Historical
  121. \end{code}
  122. Representation of type bindings to uninstantiated meta variables used during
  123. constraint solving.
  124. \begin{code}
  125. data TcTyVarBind = TcTyVarBind TcTyVar TcType
  126. type TcTyVarBinds = Bag TcTyVarBind
  127. instance Outputable TcTyVarBind where
  128. ppr (TcTyVarBind tv ty) = ppr tv <+> text ":=" <+> ppr ty
  129. \end{code}
  130. %************************************************************************
  131. %* *
  132. The main environment types
  133. %* *
  134. %************************************************************************
  135. \begin{code}
  136. -- We 'stack' these envs through the Reader like monad infastructure
  137. -- as we move into an expression (although the change is focused in
  138. -- the lcl type).
  139. data Env gbl lcl
  140. = Env {
  141. env_top :: HscEnv, -- Top-level stuff that never changes
  142. -- Includes all info about imported things
  143. env_us :: {-# UNPACK #-} !(IORef UniqSupply),
  144. -- Unique supply for local varibles
  145. env_gbl :: gbl, -- Info about things defined at the top level
  146. -- of the module being compiled
  147. env_lcl :: lcl -- Nested stuff; changes as we go into
  148. }
  149. instance ContainsDynFlags (Env gbl lcl) where
  150. extractDynFlags env = hsc_dflags (env_top env)
  151. replaceDynFlags env dflags
  152. = env {env_top = replaceDynFlags (env_top env) dflags}
  153. instance ContainsModule gbl => ContainsModule (Env gbl lcl) where
  154. extractModule env = extractModule (env_gbl env)
  155. -- TcGblEnv describes the top-level of the module at the
  156. -- point at which the typechecker is finished work.
  157. -- It is this structure that is handed on to the desugarer
  158. -- For state that needs to be updated during the typechecking
  159. -- phase and returned at end, use a TcRef (= IORef).
  160. data TcGblEnv
  161. = TcGblEnv {
  162. tcg_mod :: Module, -- ^ Module being compiled
  163. tcg_src :: HscSource,
  164. -- ^ What kind of module (regular Haskell, hs-boot, ext-core)
  165. tcg_rdr_env :: GlobalRdrEnv, -- ^ Top level envt; used during renaming
  166. tcg_default :: Maybe [Type],
  167. -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
  168. tcg_fix_env :: FixityEnv, -- ^ Just for things in this module
  169. tcg_field_env :: RecFieldEnv, -- ^ Just for things in this module
  170. tcg_type_env :: TypeEnv,
  171. -- ^ Global type env for the module we are compiling now. All
  172. -- TyCons and Classes (for this module) end up in here right away,
  173. -- along with their derived constructors, selectors.
  174. --
  175. -- (Ids defined in this module start in the local envt, though they
  176. -- move to the global envt during zonking)
  177. tcg_type_env_var :: TcRef TypeEnv,
  178. -- Used only to initialise the interface-file
  179. -- typechecker in initIfaceTcRn, so that it can see stuff
  180. -- bound in this module when dealing with hi-boot recursions
  181. -- Updated at intervals (e.g. after dealing with types and classes)
  182. tcg_inst_env :: InstEnv,
  183. -- ^ Instance envt for all /home-package/ modules;
  184. -- Includes the dfuns in tcg_insts
  185. tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
  186. tcg_ann_env :: AnnEnv, -- ^ And for annotations
  187. -- Now a bunch of things about this module that are simply
  188. -- accumulated, but never consulted until the end.
  189. -- Nevertheless, it's convenient to accumulate them along
  190. -- with the rest of the info from this module.
  191. tcg_exports :: [AvailInfo], -- ^ What is exported
  192. tcg_imports :: ImportAvails,
  193. -- ^ Information about what was imported from where, including
  194. -- things bound in this module. Also store Safe Haskell info
  195. -- here about transative trusted packaage requirements.
  196. tcg_dus :: DefUses, -- ^ What is defined in this module and what is used.
  197. tcg_used_rdrnames :: TcRef (Set RdrName),
  198. -- See Note [Tracking unused binding and imports]
  199. tcg_keep :: TcRef NameSet,
  200. -- ^ Locally-defined top-level names to keep alive.
  201. --
  202. -- "Keep alive" means give them an Exported flag, so that the
  203. -- simplifier does not discard them as dead code, and so that they
  204. -- are exposed in the interface file (but not to export to the
  205. -- user).
  206. --
  207. -- Some things, like dict-fun Ids and default-method Ids are "born"
  208. -- with the Exported flag on, for exactly the above reason, but some
  209. -- we only discover as we go. Specifically:
  210. --
  211. -- * The to/from functions for generic data types
  212. --
  213. -- * Top-level variables appearing free in the RHS of an orphan
  214. -- rule
  215. --
  216. -- * Top-level variables appearing free in a TH bracket
  217. tcg_th_used :: TcRef Bool,
  218. -- ^ @True@ <=> Template Haskell syntax used.
  219. --
  220. -- We need this so that we can generate a dependency on the
  221. -- Template Haskell package, because the desugarer is going
  222. -- to emit loads of references to TH symbols. The reference
  223. -- is implicit rather than explicit, so we have to zap a
  224. -- mutable variable.
  225. tcg_th_splice_used :: TcRef Bool,
  226. -- ^ @True@ <=> A Template Haskell splice was used.
  227. --
  228. -- Splices disable recompilation avoidance (see #481)
  229. tcg_dfun_n :: TcRef OccSet,
  230. -- ^ Allows us to choose unique DFun names.
  231. -- The next fields accumulate the payload of the module
  232. -- The binds, rules and foreign-decl fiels are collected
  233. -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
  234. tcg_rn_exports :: Maybe [Located (IE Name)],
  235. tcg_rn_imports :: [LImportDecl Name],
  236. -- Keep the renamed imports regardless. They are not
  237. -- voluminous and are needed if you want to report unused imports
  238. tcg_rn_decls :: Maybe (HsGroup Name),
  239. -- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
  240. -- decls.
  241. tcg_dependent_files :: TcRef [FilePath], -- ^ dependencies from addDependentFile
  242. #ifdef GHCI
  243. tcg_th_topdecls :: TcRef [LHsDecl RdrName],
  244. -- ^ Top-level declarations from addTopDecls
  245. tcg_th_topnames :: TcRef NameSet,
  246. -- ^ Exact names bound in top-level declarations in tcg_th_topdecls
  247. tcg_th_modfinalizers :: TcRef [TH.Q ()],
  248. -- ^ Template Haskell module finalizers
  249. tcg_th_state :: TcRef (Map TypeRep Dynamic),
  250. -- ^ Template Haskell state
  251. #endif /* GHCI */
  252. tcg_ev_binds :: Bag EvBind, -- Top-level evidence bindings
  253. tcg_binds :: LHsBinds Id, -- Value bindings in this module
  254. tcg_sigs :: NameSet, -- ...Top-level names that *lack* a signature
  255. tcg_imp_specs :: [LTcSpecPrag], -- ...SPECIALISE prags for imported Ids
  256. tcg_warns :: Warnings, -- ...Warnings and deprecations
  257. tcg_anns :: [Annotation], -- ...Annotations
  258. tcg_tcs :: [TyCon], -- ...TyCons and Classes
  259. tcg_insts :: [ClsInst], -- ...Instances
  260. tcg_fam_insts :: [FamInst], -- ...Family instances
  261. tcg_rules :: [LRuleDecl Id], -- ...Rules
  262. tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
  263. tcg_vects :: [LVectDecl Id], -- ...Vectorisation declarations
  264. tcg_doc_hdr :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
  265. tcg_hpc :: AnyHpcUsage, -- ^ @True@ if any part of the
  266. -- prog uses hpc instrumentation.
  267. tcg_main :: Maybe Name, -- ^ The Name of the main
  268. -- function, if this module is
  269. -- the main module.
  270. tcg_safeInfer :: TcRef Bool -- Has the typechecker
  271. -- inferred this module
  272. -- as -XSafe (Safe Haskell)
  273. }
  274. instance ContainsModule TcGblEnv where
  275. extractModule env = tcg_mod env
  276. data RecFieldEnv
  277. = RecFields (NameEnv [Name]) -- Maps a constructor name *in this module*
  278. -- to the fields for that constructor
  279. NameSet -- Set of all fields declared *in this module*;
  280. -- used to suppress name-shadowing complaints
  281. -- when using record wild cards
  282. -- E.g. let fld = e in C {..}
  283. -- This is used when dealing with ".." notation in record
  284. -- construction and pattern matching.
  285. -- The FieldEnv deals *only* with constructors defined in *this*
  286. -- module. For imported modules, we get the same info from the
  287. -- TypeEnv
  288. \end{code}
  289. Note [Tracking unused binding and imports]
  290. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  291. We gather two sorts of usage information
  292. * tcg_dus (defs/uses)
  293. Records *defined* Names (local, top-level)
  294. and *used* Names (local or imported)
  295. Used (a) to report "defined but not used"
  296. (see RnNames.reportUnusedNames)
  297. (b) to generate version-tracking usage info in interface
  298. files (see MkIface.mkUsedNames)
  299. This usage info is mainly gathered by the renamer's
  300. gathering of free-variables
  301. * tcg_used_rdrnames
  302. Records used *imported* (not locally-defined) RdrNames
  303. Used only to report unused import declarations
  304. Notice that they are RdrNames, not Names, so we can
  305. tell whether the reference was qualified or unqualified, which
  306. is esssential in deciding whether a particular import decl
  307. is unnecessary. This info isn't present in Names.
  308. %************************************************************************
  309. %* *
  310. The interface environments
  311. Used when dealing with IfaceDecls
  312. %* *
  313. %************************************************************************
  314. \begin{code}
  315. data IfGblEnv
  316. = IfGblEnv {
  317. -- The type environment for the module being compiled,
  318. -- in case the interface refers back to it via a reference that
  319. -- was originally a hi-boot file.
  320. -- We need the module name so we can test when it's appropriate
  321. -- to look in this env.
  322. if_rec_types :: Maybe (Module, IfG TypeEnv)
  323. -- Allows a read effect, so it can be in a mutable
  324. -- variable; c.f. handling the external package type env
  325. -- Nothing => interactive stuff, no loops possible
  326. }
  327. data IfLclEnv
  328. = IfLclEnv {
  329. -- The module for the current IfaceDecl
  330. -- So if we see f = \x -> x
  331. -- it means M.f = \x -> x, where M is the if_mod
  332. if_mod :: Module,
  333. -- The field is used only for error reporting
  334. -- if (say) there's a Lint error in it
  335. if_loc :: SDoc,
  336. -- Where the interface came from:
  337. -- .hi file, or GHCi state, or ext core
  338. -- plus which bit is currently being examined
  339. if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
  340. -- (and coercions)
  341. if_id_env :: UniqFM Id -- Nested id binding
  342. }
  343. \end{code}
  344. %************************************************************************
  345. %* *
  346. The local typechecker environment
  347. %* *
  348. %************************************************************************
  349. The Global-Env/Local-Env story
  350. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  351. During type checking, we keep in the tcg_type_env
  352. * All types and classes
  353. * All Ids derived from types and classes (constructors, selectors)
  354. At the end of type checking, we zonk the local bindings,
  355. and as we do so we add to the tcg_type_env
  356. * Locally defined top-level Ids
  357. Why? Because they are now Ids not TcIds. This final GlobalEnv is
  358. a) fed back (via the knot) to typechecking the
  359. unfoldings of interface signatures
  360. b) used in the ModDetails of this module
  361. \begin{code}
  362. data TcLclEnv -- Changes as we move inside an expression
  363. -- Discarded after typecheck/rename; not passed on to desugarer
  364. = TcLclEnv {
  365. tcl_loc :: SrcSpan, -- Source span
  366. tcl_ctxt :: [ErrCtxt], -- Error context, innermost on top
  367. tcl_untch :: Untouchables, -- Birthplace for new unification variables
  368. tcl_th_ctxt :: ThStage, -- Template Haskell context
  369. tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
  370. tcl_rdr :: LocalRdrEnv, -- Local name envt
  371. -- Maintained during renaming, of course, but also during
  372. -- type checking, solely so that when renaming a Template-Haskell
  373. -- splice we have the right environment for the renamer.
  374. --
  375. -- Does *not* include global name envt; may shadow it
  376. -- Includes both ordinary variables and type variables;
  377. -- they are kept distinct because tyvar have a different
  378. -- occurrence contructor (Name.TvOcc)
  379. -- We still need the unsullied global name env so that
  380. -- we can look up record field names
  381. tcl_env :: TcTypeEnv, -- The local type environment:
  382. -- Ids and TyVars defined in this module
  383. tcl_bndrs :: [TcIdBinder], -- Stack of locally-bound Ids, innermost on top
  384. -- Used only for error reporting
  385. tcl_tidy :: TidyEnv, -- Used for tidying types; contains all
  386. -- in-scope type variables (but not term variables)
  387. tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
  388. -- Namely, the in-scope TyVars bound in tcl_env,
  389. -- plus the tyvars mentioned in the types of Ids bound
  390. -- in tcl_lenv.
  391. -- Why mutable? see notes with tcGetGlobalTyVars
  392. tcl_lie :: TcRef WantedConstraints, -- Place to accumulate type constraints
  393. tcl_errs :: TcRef Messages -- Place to accumulate errors
  394. }
  395. type TcTypeEnv = NameEnv TcTyThing
  396. data TcIdBinder
  397. = TcIdBndr
  398. TcId
  399. TopLevelFlag -- Tells whether the bindind is syntactically top-level
  400. -- (The monomorphic Ids for a recursive group count
  401. -- as not-top-level for this purpose.)
  402. {- Note [Given Insts]
  403. ~~~~~~~~~~~~~~~~~~
  404. Because of GADTs, we have to pass inwards the Insts provided by type signatures
  405. and existential contexts. Consider
  406. data T a where { T1 :: b -> b -> T [b] }
  407. f :: Eq a => T a -> Bool
  408. f (T1 x y) = [x]==[y]
  409. The constructor T1 binds an existential variable 'b', and we need Eq [b].
  410. Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
  411. pass it inwards.
  412. -}
  413. ---------------------------
  414. -- Template Haskell stages and levels
  415. ---------------------------
  416. data ThStage -- See Note [Template Haskell state diagram] in TcSplice
  417. = Splice -- Top-level splicing
  418. -- This code will be run *at compile time*;
  419. -- the result replaces the splice
  420. -- Binding level = 0
  421. Bool -- True if in a typed splice, False otherwise
  422. | Comp -- Ordinary Haskell code
  423. -- Binding level = 1
  424. | Brack -- Inside brackets
  425. Bool -- True if inside a typed bracket, False otherwise
  426. ThStage -- Binding level = level(stage) + 1
  427. (TcRef [PendingSplice]) -- Accumulate pending splices here
  428. (TcRef WantedConstraints) -- and type constraints here
  429. topStage, topAnnStage, topSpliceStage :: ThStage
  430. topStage = Comp
  431. topAnnStage = Splice False
  432. topSpliceStage = Splice False
  433. instance Outputable ThStage where
  434. ppr (Splice _) = text "Splice"
  435. ppr Comp = text "Comp"
  436. ppr (Brack _ s _ _) = text "Brack" <> parens (ppr s)
  437. type ThLevel = Int
  438. -- See Note [Template Haskell levels] in TcSplice
  439. -- Incremented when going inside a bracket,
  440. -- decremented when going inside a splice
  441. -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
  442. -- original "Template meta-programming for Haskell" paper
  443. impLevel, outerLevel :: ThLevel
  444. impLevel = 0 -- Imported things; they can be used inside a top level splice
  445. outerLevel = 1 -- Things defined outside brackets
  446. -- NB: Things at level 0 are not *necessarily* imported.
  447. -- eg $( \b -> ... ) here b is bound at level 0
  448. --
  449. -- For example:
  450. -- f = ...
  451. -- g1 = $(map ...) is OK
  452. -- g2 = $(f ...) is not OK; because we havn't compiled f yet
  453. thLevel :: ThStage -> ThLevel
  454. thLevel (Splice _) = 0
  455. thLevel Comp = 1
  456. thLevel (Brack _ s _ _) = thLevel s + 1
  457. ---------------------------
  458. -- Arrow-notation context
  459. ---------------------------
  460. {- Note [Escaping the arrow scope]
  461. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  462. In arrow notation, a variable bound by a proc (or enclosed let/kappa)
  463. is not in scope to the left of an arrow tail (-<) or the head of (|..|).
  464. For example
  465. proc x -> (e1 -< e2)
  466. Here, x is not in scope in e1, but it is in scope in e2. This can get
  467. a bit complicated:
  468. let x = 3 in
  469. proc y -> (proc z -> e1) -< e2
  470. Here, x and z are in scope in e1, but y is not.
  471. We implement this by
  472. recording the environment when passing a proc (using newArrowScope),
  473. and returning to that (using escapeArrowScope) on the left of -< and the
  474. head of (|..|).
  475. All this can be dealt with by the *renamer*; by the time we get to
  476. the *type checker* we have sorted out the scopes
  477. -}
  478. data ArrowCtxt
  479. = NoArrowCtxt
  480. | ArrowCtxt (Env TcGblEnv TcLclEnv)
  481. -- Record the current environment (outside a proc)
  482. newArrowScope :: TcM a -> TcM a
  483. newArrowScope
  484. = updEnv $ \env ->
  485. env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
  486. -- Return to the stored environment (from the enclosing proc)
  487. escapeArrowScope :: TcM a -> TcM a
  488. escapeArrowScope
  489. = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
  490. NoArrowCtxt -> env
  491. ArrowCtxt env' -> env'
  492. ---------------------------
  493. -- TcTyThing
  494. ---------------------------
  495. data TcTyThing
  496. = AGlobal TyThing -- Used only in the return type of a lookup
  497. | ATcId { -- Ids defined in this module; may not be fully zonked
  498. tct_id :: TcId,
  499. tct_closed :: TopLevelFlag, -- See Note [Bindings with closed types]
  500. tct_level :: ThLevel }
  501. | ATyVar Name TcTyVar -- The type variable to which the lexically scoped type
  502. -- variable is bound. We only need the Name
  503. -- for error-message purposes; it is the corresponding
  504. -- Name in the domain of the envt
  505. | AThing TcKind -- Used temporarily, during kind checking, for the
  506. -- tycons and clases in this recursive group
  507. -- Can be a mono-kind or a poly-kind; in TcTyClsDcls see
  508. -- Note [Type checking recursive type and class declarations]
  509. | APromotionErr PromotionErr
  510. data PromotionErr
  511. = TyConPE -- TyCon used in a kind before we are ready
  512. -- data T :: T -> * where ...
  513. | ClassPE -- Ditto Class
  514. | FamDataConPE -- Data constructor for a data family
  515. -- See Note [AFamDataCon: not promoting data family constructors] in TcRnDriver
  516. | RecDataConPE -- Data constructor in a reuursive loop
  517. -- See Note [ARecDataCon: recusion and promoting data constructors] in TcTyClsDecls
  518. | NoDataKinds -- -XDataKinds not enabled
  519. instance Outputable TcTyThing where -- Debugging only
  520. ppr (AGlobal g) = pprTyThing g
  521. ppr elt@(ATcId {}) = text "Identifier" <>
  522. brackets (ppr (tct_id elt) <> dcolon
  523. <> ppr (varType (tct_id elt)) <> comma
  524. <+> ppr (tct_closed elt) <> comma
  525. <+> ppr (tct_level elt))
  526. ppr (ATyVar n tv) = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv
  527. ppr (AThing k) = text "AThing" <+> ppr k
  528. ppr (APromotionErr err) = text "APromotionErr" <+> ppr err
  529. instance Outputable PromotionErr where
  530. ppr ClassPE = text "ClassPE"
  531. ppr TyConPE = text "TyConPE"
  532. ppr FamDataConPE = text "FamDataConPE"
  533. ppr RecDataConPE = text "RecDataConPE"
  534. ppr NoDataKinds = text "NoDataKinds"
  535. pprTcTyThingCategory :: TcTyThing -> SDoc
  536. pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
  537. pprTcTyThingCategory (ATyVar {}) = ptext (sLit "Type variable")
  538. pprTcTyThingCategory (ATcId {}) = ptext (sLit "Local identifier")
  539. pprTcTyThingCategory (AThing {}) = ptext (sLit "Kinded thing")
  540. pprTcTyThingCategory (APromotionErr pe) = pprPECategory pe
  541. pprPECategory :: PromotionErr -> SDoc
  542. pprPECategory ClassPE = ptext (sLit "Class")
  543. pprPECategory TyConPE = ptext (sLit "Type constructor")
  544. pprPECategory FamDataConPE = ptext (sLit "Data constructor")
  545. pprPECategory RecDataConPE = ptext (sLit "Data constructor")
  546. pprPECategory NoDataKinds = ptext (sLit "Data constructor")
  547. \end{code}
  548. Note [Bindings with closed types]
  549. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  550. Consider
  551. f x = let g ys = map not ys
  552. in ...
  553. Can we generalise 'g' under the OutsideIn algorithm? Yes,
  554. because all g's free variables are top-level; that is they themselves
  555. have no free type variables, and it is the type variables in the
  556. environment that makes things tricky for OutsideIn generalisation.
  557. Definition:
  558. A variable is "closed", and has tct_closed set to TopLevel,
  559. iff
  560. a) all its free variables are imported, or are themselves closed
  561. b) generalisation is not restricted by the monomorphism restriction
  562. Under OutsideIn we are free to generalise a closed let-binding.
  563. This is an extension compared to the JFP paper on OutsideIn, which
  564. used "top-level" as a proxy for "closed". (It's not a good proxy
  565. anyway -- the MR can make a top-level binding with a free type
  566. variable.)
  567. Note that:
  568. * A top-level binding may not be closed, if it suffer from the MR
  569. * A nested binding may be closed (eg 'g' in the example we started with)
  570. Indeed, that's the point; whether a function is defined at top level
  571. or nested is orthogonal to the question of whether or not it is closed
  572. * A binding may be non-closed because it mentions a lexically scoped
  573. *type variable* Eg
  574. f :: forall a. blah
  575. f x = let g y = ...(y::a)...
  576. \begin{code}
  577. type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, MsgDoc))
  578. -- Monadic so that we have a chance
  579. -- to deal with bound type variables just before error
  580. -- message construction
  581. -- Bool: True <=> this is a landmark context; do not
  582. -- discard it when trimming for display
  583. \end{code}
  584. %************************************************************************
  585. %* *
  586. Operations over ImportAvails
  587. %* *
  588. %************************************************************************
  589. \begin{code}
  590. -- | 'ImportAvails' summarises what was imported from where, irrespective of
  591. -- whether the imported things are actually used or not. It is used:
  592. --
  593. -- * when processing the export list,
  594. --
  595. -- * when constructing usage info for the interface file,
  596. --
  597. -- * to identify the list of directly imported modules for initialisation
  598. -- purposes and for optimised overlap checking of family instances,
  599. --
  600. -- * when figuring out what things are really unused
  601. --
  602. data ImportAvails
  603. = ImportAvails {
  604. imp_mods :: ImportedMods,
  605. -- = ModuleEnv [(ModuleName, Bool, SrcSpan, Bool)],
  606. -- ^ Domain is all directly-imported modules
  607. -- The 'ModuleName' is what the module was imported as, e.g. in
  608. -- @
  609. -- import Foo as Bar
  610. -- @
  611. -- it is @Bar@.
  612. --
  613. -- The 'Bool' means:
  614. --
  615. -- - @True@ => import was @import Foo ()@
  616. --
  617. -- - @False@ => import was some other form
  618. --
  619. -- Used
  620. --
  621. -- (a) to help construct the usage information in the interface
  622. -- file; if we import somethign we need to recompile if the
  623. -- export version changes
  624. --
  625. -- (b) to specify what child modules to initialise
  626. --
  627. -- We need a full ModuleEnv rather than a ModuleNameEnv here,
  628. -- because we might be importing modules of the same name from
  629. -- different packages. (currently not the case, but might be in the
  630. -- future).
  631. imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
  632. -- ^ Home-package modules needed by the module being compiled
  633. --
  634. -- It doesn't matter whether any of these dependencies
  635. -- are actually /used/ when compiling the module; they
  636. -- are listed if they are below it at all. For
  637. -- example, suppose M imports A which imports X. Then
  638. -- compiling M might not need to consult X.hi, but X
  639. -- is still listed in M's dependencies.
  640. imp_dep_pkgs :: [PackageId],
  641. -- ^ Packages needed by the module being compiled, whether directly,
  642. -- or via other modules in this package, or via modules imported
  643. -- from other packages.
  644. imp_trust_pkgs :: [PackageId],
  645. -- ^ This is strictly a subset of imp_dep_pkgs and records the
  646. -- packages the current module needs to trust for Safe Haskell
  647. -- compilation to succeed. A package is required to be trusted if
  648. -- we are dependent on a trustworthy module in that package.
  649. -- While perhaps making imp_dep_pkgs a tuple of (PackageId, Bool)
  650. -- where True for the bool indicates the package is required to be
  651. -- trusted is the more logical design, doing so complicates a lot
  652. -- of code not concerned with Safe Haskell.
  653. -- See Note [RnNames . Tracking Trust Transitively]
  654. imp_trust_own_pkg :: Bool,
  655. -- ^ Do we require that our own package is trusted?
  656. -- This is to handle efficiently the case where a Safe module imports
  657. -- a Trustworthy module that resides in the same package as it.
  658. -- See Note [RnNames . Trust Own Package]
  659. imp_orphs :: [Module],
  660. -- ^ Orphan modules below us in the import tree (and maybe including
  661. -- us for imported modules)
  662. imp_finsts :: [Module]
  663. -- ^ Family instance modules below us in the import tree (and maybe
  664. -- including us for imported modules)
  665. }
  666. mkModDeps :: [(ModuleName, IsBootInterface)]
  667. -> ModuleNameEnv (ModuleName, IsBootInterface)
  668. mkModDeps deps = foldl add emptyUFM deps
  669. where
  670. add env elt@(m,_) = addToUFM env m elt
  671. emptyImportAvails :: ImportAvails
  672. emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
  673. imp_dep_mods = emptyUFM,
  674. imp_dep_pkgs = [],
  675. imp_trust_pkgs = [],
  676. imp_trust_own_pkg = False,
  677. imp_orphs = [],
  678. imp_finsts = [] }
  679. -- | Union two ImportAvails
  680. --
  681. -- This function is a key part of Import handling, basically
  682. -- for each import we create a separate ImportAvails structure
  683. -- and then union them all together with this function.
  684. plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
  685. plusImportAvails
  686. (ImportAvails { imp_mods = mods1,
  687. imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
  688. imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1,
  689. imp_orphs = orphs1, imp_finsts = finsts1 })
  690. (ImportAvails { imp_mods = mods2,
  691. imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
  692. imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2,
  693. imp_orphs = orphs2, imp_finsts = finsts2 })
  694. = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
  695. imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
  696. imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
  697. imp_trust_pkgs = tpkgs1 `unionLists` tpkgs2,
  698. imp_trust_own_pkg = tself1 || tself2,
  699. imp_orphs = orphs1 `unionLists` orphs2,
  700. imp_finsts = finsts1 `unionLists` finsts2 }
  701. where
  702. plus_mod_dep (m1, boot1) (m2, boot2)
  703. = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
  704. -- Check mod-names match
  705. (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
  706. \end{code}
  707. %************************************************************************
  708. %* *
  709. \subsection{Where from}
  710. %* *
  711. %************************************************************************
  712. The @WhereFrom@ type controls where the renamer looks for an interface file
  713. \begin{code}
  714. data WhereFrom
  715. = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
  716. | ImportBySystem -- Non user import.
  717. | ImportByPlugin -- Importing a plugin;
  718. -- See Note [Care with plugin imports] in LoadIface
  719. instance Outputable WhereFrom where
  720. ppr (ImportByUser is_boot) | is_boot = ptext (sLit "{- SOURCE -}")
  721. | otherwise = empty
  722. ppr ImportBySystem = ptext (sLit "{- SYSTEM -}")
  723. ppr ImportByPlugin = ptext (sLit "{- PLUGIN -}")
  724. \end{code}
  725. %************************************************************************
  726. %* *
  727. %* Canonical constraints *
  728. %* *
  729. %* These are the constraints the low-level simplifier works with *
  730. %* *
  731. %************************************************************************
  732. \begin{code}
  733. -- The syntax of xi types:
  734. -- xi ::= a | T xis | xis -> xis | ... | forall a. tau
  735. -- Two important notes:
  736. -- (i) No type families, unless we are under a ForAll
  737. -- (ii) Note that xi types can contain unexpanded type synonyms;
  738. -- however, the (transitive) expansions of those type synonyms
  739. -- will not contain any type functions, unless we are under a ForAll.
  740. -- We enforce the structure of Xi types when we flatten (TcCanonical)
  741. type Xi = Type -- In many comments, "xi" ranges over Xi
  742. type Cts = Bag Ct
  743. data Ct
  744. -- Atomic canonical constraints
  745. = CDictCan { -- e.g. Num xi
  746. cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
  747. cc_class :: Class,
  748. cc_tyargs :: [Xi],
  749. cc_loc :: CtLoc
  750. }
  751. | CIrredEvCan { -- These stand for yet-unusable predicates
  752. cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
  753. -- The ctev_pred of the evidence is
  754. -- of form (tv xi1 xi2 ... xin)
  755. -- or (tv1 ~ ty2) where the CTyEqCan kind invariant fails
  756. -- or (F tys ~ ty) where the CFunEqCan kind invariant fails
  757. -- See Note [CIrredEvCan constraints]
  758. cc_loc :: CtLoc
  759. }
  760. | CTyEqCan { -- tv ~ xi (recall xi means function free)
  761. -- Invariant:
  762. -- * tv not in tvs(xi) (occurs check)
  763. -- * typeKind xi `subKind` typeKind tv
  764. -- See Note [Kind orientation for CTyEqCan]
  765. -- * We prefer unification variables on the left *JUST* for efficiency
  766. cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
  767. cc_tyvar :: TcTyVar,
  768. cc_rhs :: Xi,
  769. cc_loc :: CtLoc
  770. }
  771. | CFunEqCan { -- F xis ~ xi
  772. -- Invariant: * isSynFamilyTyCon cc_fun
  773. -- * typeKind (F xis) `subKind` typeKind xi
  774. -- See Note [Kind orientation for CFunEqCan]
  775. cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
  776. cc_fun :: TyCon, -- A type function
  777. cc_tyargs :: [Xi], -- Either under-saturated or exactly saturated
  778. cc_rhs :: Xi, -- *never* over-saturated (because if so
  779. -- we should have decomposed)
  780. cc_loc :: CtLoc
  781. }
  782. | CNonCanonical { -- See Note [NonCanonical Semantics]
  783. cc_ev :: CtEvidence,
  784. cc_loc :: CtLoc
  785. }
  786. | CHoleCan { -- Treated as an "insoluble" constraint
  787. -- See Note [Insoluble constraints]
  788. cc_ev :: CtEvidence,
  789. cc_loc :: CtLoc,
  790. cc_occ :: OccName -- The name of this hole
  791. }
  792. \end{code}
  793. Note [Kind orientation for CTyEqCan]
  794. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  795. Given an equality (t:* ~ s:Open), we absolutely want to re-orient it.
  796. We can't solve it by updating t:=s, ragardless of how touchable 't' is,
  797. because the kinds don't work. Indeed we don't want to leave it with
  798. the orientation (t ~ s), because if that gets into the inert set we'll
  799. start replacing t's by s's, and that too is the wrong way round.
  800. Hence in a CTyEqCan, (t:k1 ~ xi:k2) we require that k2 is a subkind of k1.
  801. If the two have incompatible kinds, we just don't use a CTyEqCan at all.
  802. See Note [Equalities with incompatible kinds] in TcCanonical
  803. We can't require *equal* kinds, because
  804. * wanted constraints don't necessarily have identical kinds
  805. eg alpha::? ~ Int
  806. * a solved wanted constraint becomes a given
  807. Note [Kind orientation for CFunEqCan]
  808. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  809. For (F xis ~ rhs) we require that kind(rhs) is a subkind of kind(lhs).
  810. This reallly only maters when rhs is an Open type variable (since only type
  811. variables have Open kinds):
  812. F ty ~ (a:Open)
  813. which can happen, say, from
  814. f :: F a b
  815. f = undefined -- The a:Open comes from instantiating 'undefined'
  816. Note that the kind invariant is maintained by rewriting.
  817. Eg wanted1 rewrites wanted2; if both were compatible kinds before,
  818. wanted2 will be afterwards. Similarly givens.
  819. Caveat:
  820. - Givens from higher-rank, such as:
  821. type family T b :: * -> * -> *
  822. type instance T Bool = (->)
  823. f :: forall a. ((T a ~ (->)) => ...) -> a -> ...
  824. flop = f (...) True
  825. Whereas we would be able to apply the type instance, we would not be able to
  826. use the given (T Bool ~ (->)) in the body of 'flop'
  827. Note [CIrredEvCan constraints]
  828. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  829. CIrredEvCan constraints are used for constraints that are "stuck"
  830. - we can't solve them (yet)
  831. - we can't use them to solve other constraints
  832. - but they may become soluble if we substitute for some
  833. of the type variables in the constraint
  834. Example 1: (c Int), where c :: * -> Constraint. We can't do anything
  835. with this yet, but if later c := Num, *then* we can solve it
  836. Example 2: a ~ b, where a :: *, b :: k, where k is a kind variable
  837. We don't want to use this to substitute 'b' for 'a', in case
  838. 'k' is subequently unifed with (say) *->*, because then
  839. we'd have ill-kinded types floating about. Rather we want
  840. to defer using the equality altogether until 'k' get resolved.
  841. Note [Ct/evidence invariant]
  842. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  843. If ct :: Ct, then extra fields of 'ct' cache precisely the ctev_pred field
  844. of (cc_ev ct), and is fully rewritten wrt the substitution. Eg for CDictCan,
  845. ctev_pred (cc_ev ct) = (cc_class ct) (cc_tyargs ct)
  846. This holds by construction; look at the unique place where CDictCan is
  847. built (in TcCanonical).
  848. In contrast, the type of the evidence *term* (ccev_evtm or ctev_evar) in
  849. the evidence may *not* be fully zonked; we are careful not to look at it
  850. during constraint solving. See Note [Evidence field of CtEvidence]
  851. \begin{code}
  852. mkNonCanonical :: CtLoc -> CtEvidence -> Ct
  853. mkNonCanonical loc ev = CNonCanonical { cc_ev = ev, cc_loc = loc }
  854. mkNonCanonicalCt :: Ct -> Ct
  855. mkNonCanonicalCt ct = CNonCanonical { cc_ev = cc_ev ct, cc_loc = cc_loc ct }
  856. ctEvidence :: Ct -> CtEvidence
  857. ctEvidence = cc_ev
  858. ctPred :: Ct -> PredType
  859. -- See Note [Ct/evidence invariant]
  860. ctPred ct = ctEvPred (cc_ev ct)
  861. dropDerivedWC :: WantedConstraints -> WantedConstraints
  862. -- See Note [Insoluble derived constraints]
  863. dropDerivedWC wc@(WC { wc_flat = flats, wc_insol = insols })
  864. = wc { wc_flat = filterBag isWantedCt flats
  865. , wc_insol = filterBag (not . isDerivedCt) insols }
  866. -- Keep Givens from insols because they indicate unreachable code
  867. -- The implications are (recursively) already filtered
  868. \end{code}
  869. Note [Insoluble derived constraints]
  870. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  871. In general we discard derived constraints at the end of constraint solving;
  872. see dropDerivedWC. For example,
  873. * If we have an unsolved (Ord a), we don't want to complain about
  874. an unsolved (Eq a) as well.
  875. * If we have kind-incompatible (a::* ~ Int#::#) equality, we
  876. don't want to complain about the kind error twice.
  877. Arguably, for *some* derived constraints we might want to report errors.
  878. Notably, functional dependencies. If we have
  879. class C a b | a -> b
  880. and we have
  881. [W] C a b, [W] C a c
  882. where a,b,c are all signature variables. Then we could reasonably
  883. report an error unifying (b ~ c). But it's probably not worth it;
  884. after all, we also get an error because we can't discharge the constraint.
  885. %************************************************************************
  886. %* *
  887. CtEvidence
  888. The "flavor" of a canonical constraint
  889. %* *
  890. %************************************************************************
  891. \begin{code}
  892. isWantedCt :: Ct -> Bool
  893. isWantedCt = isWanted . cc_ev
  894. isGivenCt :: Ct -> Bool
  895. isGivenCt = isGiven . cc_ev
  896. isDerivedCt :: Ct -> Bool
  897. isDerivedCt = isDerived . cc_ev
  898. isCTyEqCan :: Ct -> Bool
  899. isCTyEqCan (CTyEqCan {}) = True
  900. isCTyEqCan (CFunEqCan {}) = False
  901. isCTyEqCan _ = False
  902. isCDictCan_Maybe :: Ct -> Maybe Class
  903. isCDictCan_Maybe (CDictCan {cc_class = cls }) = Just cls
  904. isCDictCan_Maybe _ = Nothing
  905. isCIrredEvCan :: Ct -> Bool
  906. isCIrredEvCan (CIrredEvCan {}) = True
  907. isCIrredEvCan _ = False
  908. isCFunEqCan_maybe :: Ct -> Maybe (TyCon, [Type])
  909. isCFunEqCan_maybe (CFunEqCan { cc_fun = tc, cc_tyargs = xis }) = Just (tc, xis)
  910. isCFunEqCan_maybe _ = Nothing
  911. isCFunEqCan :: Ct -> Bool
  912. isCFunEqCan (CFunEqCan {}) = True
  913. isCFunEqCan _ = False
  914. isCNonCanonical :: Ct -> Bool
  915. isCNonCanonical (CNonCanonical {}) = True
  916. isCNonCanonical _ = False
  917. isHoleCt:: Ct -> Bool
  918. isHoleCt (CHoleCan {}) = True
  919. isHoleCt _ = False
  920. \end{code}
  921. \begin{code}
  922. instance Outputable Ct where
  923. ppr ct = ppr (cc_ev ct) <+> parens (text ct_sort)
  924. where ct_sort = case ct of
  925. CTyEqCan {} -> "CTyEqCan"
  926. CFunEqCan {} -> "CFunEqCan"
  927. CNonCanonical {} -> "CNonCanonical"
  928. CDictCan {} -> "CDictCan"
  929. CIrredEvCan {} -> "CIrredEvCan"
  930. CHoleCan {} -> "CHoleCan"
  931. \end{code}
  932. \begin{code}
  933. singleCt :: Ct -> Cts
  934. singleCt = unitBag
  935. andCts :: Cts -> Cts -> Cts
  936. andCts = unionBags
  937. extendCts :: Cts -> Ct -> Cts
  938. extendCts = snocBag
  939. andManyCts :: [Cts] -> Cts
  940. andManyCts = unionManyBags
  941. emptyCts :: Cts
  942. emptyCts = emptyBag
  943. isEmptyCts :: Cts -> Bool
  944. isEmptyCts = isEmptyBag
  945. \end{code}
  946. %************************************************************************
  947. %* *
  948. Wanted constraints
  949. These are forced to be in TcRnTypes because
  950. TcLclEnv mentions WantedConstraints
  951. WantedConstraint mentions CtLoc
  952. CtLoc mentions ErrCtxt
  953. ErrCtxt mentions TcM
  954. %* *
  955. v%************************************************************************
  956. \begin{code}
  957. data WantedConstraints
  958. = WC { wc_flat :: Cts -- Unsolved constraints, all wanted
  959. , wc_impl :: Bag Implication
  960. , wc_insol :: Cts -- Insoluble constraints, can be
  961. -- wanted, given, or derived
  962. -- See Note [Insoluble constraints]
  963. }
  964. emptyWC :: WantedConstraints
  965. emptyWC = WC { wc_flat = emptyBag, wc_impl = emptyBag, wc_insol = emptyBag }
  966. mkFlatWC :: [Ct] -> WantedConstraints
  967. mkFlatWC cts
  968. = WC { wc_flat = listToBag cts, wc_impl = emptyBag, wc_insol = emptyBag }
  969. isEmptyWC :: WantedConstraints -> Bool
  970. isEmptyWC (WC { wc_flat = f, wc_impl = i, wc_insol = n })
  971. = isEmptyBag f && isEmptyBag i && isEmptyBag n
  972. insolubleWC :: WantedConstraints -> Bool
  973. -- True if there are any insoluble constraints in the wanted bag
  974. insolubleWC wc = not (isEmptyBag (wc_insol wc))
  975. || anyBag ic_insol (wc_impl wc)
  976. andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
  977. andWC (WC { wc_flat = f1, wc_impl = i1, wc_insol = n1 })
  978. (WC { wc_flat = f2, wc_impl = i2, wc_insol = n2 })
  979. = WC { wc_flat = f1 `unionBags` f2
  980. , wc_impl = i1 `unionBags` i2
  981. , wc_insol = n1 `unionBags` n2 }
  982. unionsWC :: [WantedConstraints] -> WantedConstraints
  983. unionsWC = foldr andWC emptyWC
  984. addFlats :: WantedConstraints -> Bag Ct -> WantedConstraints
  985. addFlats wc cts
  986. = wc { wc_flat = wc_flat wc `unionBags` cts }
  987. addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
  988. addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
  989. addInsols :: WantedConstraints -> Bag Ct -> WantedConstraints
  990. addInsols wc cts
  991. = wc { wc_insol = wc_insol wc `unionBags` cts }
  992. instance Outputable WantedConstraints where
  993. ppr (WC {wc_flat = f, wc_impl = i, wc_insol = n})
  994. = ptext (sLit "WC") <+> braces (vcat
  995. [ if isEmptyBag f then empty else
  996. ptext (sLit "wc_flat =") <+> pprBag ppr f
  997. , if isEmptyBag i then empty else
  998. ptext (sLit "wc_impl =") <+> pprBag ppr i
  999. , if isEmptyBag n then empty else
  1000. ptext (sLit "wc_insol =") <+> pprBag ppr n ])
  1001. pprBag :: (a -> SDoc) -> Bag a -> SDoc
  1002. pprBag pp b = foldrBag (($$) . pp) empty b
  1003. \end{code}
  1004. %************************************************************************
  1005. %* *
  1006. Implication constraints
  1007. %* *
  1008. %************************************************************************
  1009. \begin{code}
  1010. data Implication
  1011. = Implic {
  1012. ic_untch :: Untouchables, -- Untouchables: unification variables
  1013. -- free in the environment
  1014. ic_skols :: [TcTyVar], -- Introduced skolems
  1015. ic_info :: SkolemInfo, -- See Note [Skolems in an implication]
  1016. -- See Note [Shadowing in a constraint]
  1017. ic_fsks :: [TcTyVar], -- Extra flatten-skolems introduced by the flattening
  1018. -- done by canonicalisation.
  1019. ic_given :: [EvVar], -- Given evidence variables
  1020. -- (order does not matter)
  1021. ic_env :: TcLclEnv, -- Gives the source location and error context
  1022. -- for the implicatdion, and hence for all the
  1023. -- given evidence variables
  1024. ic_wanted :: WantedConstraints, -- The wanted
  1025. ic_insol :: Bool, -- True iff insolubleWC ic_wanted is true
  1026. ic_binds :: EvBindsVar -- Points to the place to fill in the
  1027. -- abstraction and bindings
  1028. }
  1029. instance Outputable Implication where
  1030. ppr (Implic { ic_untch = untch, ic_skols = skols, ic_fsks = fsks
  1031. , ic_given = given
  1032. , ic_w

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