PageRenderTime 71ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/compiler/typecheck/TcRnTypes.lhs

https://github.com/crdueck/ghc
Haskell | 1669 lines | 1016 code | 295 blank | 358 comment | 30 complexity | 3f485a1899740f600aa5864bfe0c8452 MD5 | raw file

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

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