PageRenderTime 69ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/typecheck/TcRnTypes.lhs

https://github.com/luite/ghc
Haskell | 1624 lines | 982 code | 286 blank | 356 comment | 26 complexity | 2c3f75fce313545f5c7f410f67f8429f MD5 | raw 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 Branched],-- ...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 (t1 ~ t2) where not (kind(t1) `compatKind` kind(t2)
  732. -- See Note [CIrredEvCan constraints]
  733. cc_loc :: CtLoc
  734. }
  735. | CTyEqCan { -- tv ~ xi (recall xi means function free)
  736. -- Invariant:
  737. -- * tv not in tvs(xi) (occurs check)
  738. -- * typeKind xi `compatKind` typeKind tv
  739. -- See Note [Spontaneous solving and kind compatibility]
  740. -- * We prefer unification variables on the left *JUST* for efficiency
  741. cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
  742. cc_tyvar :: TcTyVar,
  743. cc_rhs :: Xi,
  744. cc_loc :: CtLoc
  745. }
  746. | CFunEqCan { -- F xis ~ xi
  747. -- Invariant: * isSynFamilyTyCon cc_fun
  748. -- * typeKind (F xis) `compatKind` typeKind xi
  749. cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
  750. cc_fun :: TyCon, -- A type function
  751. cc_tyargs :: [Xi], -- Either under-saturated or exactly saturated
  752. cc_rhs :: Xi, -- *never* over-saturated (because if so
  753. -- we should have decomposed)
  754. cc_loc :: CtLoc
  755. }
  756. | CNonCanonical { -- See Note [NonCanonical Semantics]
  757. cc_ev :: CtEvidence,
  758. cc_loc :: CtLoc
  759. }
  760. | CHoleCan {
  761. cc_ev :: CtEvidence,
  762. cc_loc :: CtLoc,
  763. cc_occ :: OccName -- The name of this hole
  764. }
  765. \end{code}
  766. Note [CIrredEvCan constraints]
  767. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  768. CIrredEvCan constraints are used for constraints that are "stuck"
  769. - we can't solve them (yet)
  770. - we can't use them to solve other constraints
  771. - but they may become soluble if we substitute for some
  772. of the type variables in the constraint
  773. Example 1: (c Int), where c :: * -> Constraint. We can't do anything
  774. with this yet, but if later c := Num, *then* we can solve it
  775. Example 2: a ~ b, where a :: *, b :: k, where k is a kind variable
  776. We don't want to use this to substitute 'b' for 'a', in case
  777. 'k' is subequently unifed with (say) *->*, because then
  778. we'd have ill-kinded types floating about. Rather we want
  779. to defer using the equality altogether until 'k' get resolved.
  780. Note [Ct/evidence invariant]
  781. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  782. If ct :: Ct, then extra fields of 'ct' cache precisely the ctev_pred field
  783. of (cc_ev ct), and is fully rewritten wrt the substitution. Eg for CDictCan,
  784. ctev_pred (cc_ev ct) = (cc_class ct) (cc_tyargs ct)
  785. This holds by construction; look at the unique place where CDictCan is
  786. built (in TcCanonical).
  787. In contrast, the type of the evidence *term* (ccev_evtm or ctev_evar) in
  788. the evidence may *not* be fully zonked; we are careful not to look at it
  789. during constraint solving. See Note [Evidence field of CtEvidence]
  790. \begin{code}
  791. mkNonCanonical :: CtLoc -> CtEvidence -> Ct
  792. mkNonCanonical loc ev = CNonCanonical { cc_ev = ev, cc_loc = loc }
  793. mkNonCanonicalCt :: Ct -> Ct
  794. mkNonCanonicalCt ct = CNonCanonical { cc_ev = cc_ev ct, cc_loc = cc_loc ct }
  795. ctEvidence :: Ct -> CtEvidence
  796. ctEvidence = cc_ev
  797. ctPred :: Ct -> PredType
  798. -- See Note [Ct/evidence invariant]
  799. ctPred ct = ctEvPred (cc_ev ct)
  800. dropDerivedWC :: WantedConstraints -> WantedConstraints
  801. -- See Note [Insoluble derived constraints]
  802. dropDerivedWC wc@(WC { wc_flat = flats, wc_insol = insols })
  803. = wc { wc_flat = filterBag isWantedCt flats
  804. , wc_insol = filterBag (not . isDerivedCt) insols }
  805. -- Keep Givens from insols because they indicate unreachable code
  806. -- The implications are (recursively) already filtered
  807. \end{code}
  808. Note [Insoluble derived constraints]
  809. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  810. In general we discard derived constraints at the end of constraint solving;
  811. see dropDerivedWC. For example,
  812. * If we have an unsolved (Ord a), we don't want to complain about
  813. an unsolved (Eq a) as well.
  814. * If we have kind-incompatible (a::* ~ Int#::#) equality, we
  815. don't want to complain about the kind error twice.
  816. Arguably, for *some* derived constraints we might want to report errors.
  817. Notably, functional dependencies. If we have
  818. class C a b | a -> b
  819. and we have
  820. [W] C a b, [W] C a c
  821. where a,b,c are all signature variables. Then we could reasonably
  822. report an error unifying (b ~ c). But it's probably not worth it;
  823. after all, we also get an error because we can't discharge the constraint.
  824. %************************************************************************
  825. %* *
  826. CtEvidence
  827. The "flavor" of a canonical constraint
  828. %* *
  829. %************************************************************************
  830. \begin{code}
  831. isWantedCt :: Ct -> Bool
  832. isWantedCt = isWanted . cc_ev
  833. isGivenCt :: Ct -> Bool
  834. isGivenCt = isGiven . cc_ev
  835. isDerivedCt :: Ct -> Bool
  836. isDerivedCt = isDerived . cc_ev
  837. isCTyEqCan :: Ct -> Bool
  838. isCTyEqCan (CTyEqCan {}) = True
  839. isCTyEqCan (CFunEqCan {}) = False
  840. isCTyEqCan _ = False
  841. isCDictCan_Maybe :: Ct -> Maybe Class
  842. isCDictCan_Maybe (CDictCan {cc_class = cls }) = Just cls
  843. isCDictCan_Maybe _ = Nothing
  844. isCIrredEvCan :: Ct -> Bool
  845. isCIrredEvCan (CIrredEvCan {}) = True
  846. isCIrredEvCan _ = False
  847. isCFunEqCan_Maybe :: Ct -> Maybe TyCon
  848. isCFunEqCan_Maybe (CFunEqCan { cc_fun = tc }) = Just tc
  849. isCFunEqCan_Maybe _ = Nothing
  850. isCFunEqCan :: Ct -> Bool
  851. isCFunEqCan (CFunEqCan {}) = True
  852. isCFunEqCan _ = False
  853. isCNonCanonical :: Ct -> Bool
  854. isCNonCanonical (CNonCanonical {}) = True
  855. isCNonCanonical _ = False
  856. isHoleCt:: Ct -> Bool
  857. isHoleCt (CHoleCan {}) = True
  858. isHoleCt _ = False
  859. \end{code}
  860. \begin{code}
  861. instance Outputable Ct where
  862. ppr ct = ppr (cc_ev ct) <+> parens (text ct_sort)
  863. where ct_sort = case ct of
  864. CTyEqCan {} -> "CTyEqCan"
  865. CFunEqCan {} -> "CFunEqCan"
  866. CNonCanonical {} -> "CNonCanonical"
  867. CDictCan {} -> "CDictCan"
  868. CIrredEvCan {} -> "CIrredEvCan"
  869. CHoleCan {} -> "CHoleCan"
  870. \end{code}
  871. \begin{code}
  872. singleCt :: Ct -> Cts
  873. singleCt = unitBag
  874. andCts :: Cts -> Cts -> Cts
  875. andCts = unionBags
  876. extendCts :: Cts -> Ct -> Cts
  877. extendCts = snocBag
  878. andManyCts :: [Cts] -> Cts
  879. andManyCts = unionManyBags
  880. emptyCts :: Cts
  881. emptyCts = emptyBag
  882. isEmptyCts :: Cts -> Bool
  883. isEmptyCts = isEmptyBag
  884. \end{code}
  885. %************************************************************************
  886. %* *
  887. Wanted constraints
  888. These are forced to be in TcRnTypes because
  889. TcLclEnv mentions WantedConstraints
  890. WantedConstraint mentions CtLoc
  891. CtLoc mentions ErrCtxt
  892. ErrCtxt mentions TcM
  893. %* *
  894. v%************************************************************************
  895. \begin{code}
  896. data WantedConstraints
  897. = WC { wc_flat :: Cts -- Unsolved constraints, all wanted
  898. , wc_impl :: Bag Implication
  899. , wc_insol :: Cts -- Insoluble constraints, can be
  900. -- wanted, given, or derived
  901. -- See Note [Insoluble constraints]
  902. }
  903. emptyWC :: WantedConstraints
  904. emptyWC = WC { wc_flat = emptyBag, wc_impl = emptyBag, wc_insol = emptyBag }
  905. mkFlatWC :: [Ct] -> WantedConstraints
  906. mkFlatWC cts
  907. = WC { wc_flat = listToBag cts, wc_impl = emptyBag, wc_insol = emptyBag }
  908. isEmptyWC :: WantedConstraints -> Bool
  909. isEmptyWC (WC { wc_flat = f, wc_impl = i, wc_insol = n })
  910. = isEmptyBag f && isEmptyBag i && isEmptyBag n
  911. insolubleWC :: WantedConstraints -> Bool
  912. -- True if there are any insoluble constraints in the wanted bag
  913. insolubleWC wc = not (isEmptyBag (wc_insol wc))
  914. || anyBag ic_insol (wc_impl wc)
  915. andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
  916. andWC (WC { wc_flat = f1, wc_impl = i1, wc_insol = n1 })
  917. (WC { wc_flat = f2, wc_impl = i2, wc_insol = n2 })
  918. = WC { wc_flat = f1 `unionBags` f2
  919. , wc_impl = i1 `unionBags` i2
  920. , wc_insol = n1 `unionBags` n2 }
  921. unionsWC :: [WantedConstraints] -> WantedConstraints
  922. unionsWC = foldr andWC emptyWC
  923. addFlats :: WantedConstraints -> Bag Ct -> WantedConstraints
  924. addFlats wc cts
  925. = wc { wc_flat = wc_flat wc `unionBags` cts }
  926. addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
  927. addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
  928. addInsols :: WantedConstraints -> Bag Ct -> WantedConstraints
  929. addInsols wc cts
  930. = wc { wc_insol = wc_insol wc `unionBags` cts }
  931. instance Outputable WantedConstraints where
  932. ppr (WC {wc_flat = f, wc_impl = i, wc_insol = n})
  933. = ptext (sLit "WC") <+> braces (vcat
  934. [ if isEmptyBag f then empty else
  935. ptext (sLit "wc_flat =") <+> pprBag ppr f
  936. , if isEmptyBag i then empty else
  937. ptext (sLit "wc_impl =") <+> pprBag ppr i
  938. , if isEmptyBag n then empty else
  939. ptext (sLit "wc_insol =") <+> pprBag ppr n ])
  940. pprBag :: (a -> SDoc) -> Bag a -> SDoc
  941. pprBag pp b = foldrBag (($$) . pp) empty b
  942. \end{code}
  943. %************************************************************************
  944. %* *
  945. Implication constraints
  946. %* *
  947. %************************************************************************
  948. \begin{code}
  949. data Implication
  950. = Implic {
  951. ic_untch :: Untouchables, -- Untouchables: unification variables
  952. -- free in the environment
  953. ic_skols :: [TcTyVar], -- Introduced skolems
  954. ic_info :: SkolemInfo, -- See Note [Skolems in an implication]
  955. -- See Note [Shadowing in a constraint]
  956. ic_fsks :: [TcTyVar], -- Extra flatten-skolems introduced by the flattening
  957. -- done by canonicalisation.
  958. ic_given :: [EvVar], -- Given evidence variables
  959. -- (order does not matter)
  960. ic_env :: TcLclEnv, -- Gives the source location and error context
  961. -- for the implicatdion, and hence for all the
  962. -- given evidence variables
  963. ic_wanted :: WantedConstraints, -- The wanted
  964. ic_insol :: Bool, -- True iff insolubleWC ic_wanted is true
  965. ic_binds :: EvBindsVar -- Points to the place to fill in the
  966. -- abstraction and bindings
  967. }
  968. instance Outputable Implication where
  969. ppr (Implic { ic_untch = untch, ic_skols = skols, ic_fsks = fsks
  970. , ic_given = given
  971. , ic_wanted = wanted
  972. , ic_binds = binds, ic_info = info })
  973. = ptext (sLit "Implic") <+> braces
  974. (sep [ ptext (sLit "Untouchables =") <+> ppr untch
  975. , ptext (sLit "Skolems =") <+> ppr skols
  976. , ptext (sLit "Flatten-skolems =") <+> ppr fsks
  977. , ptext (sLit "Given =") <+> pprEvVars given
  978. , ptext (sLit "Wanted =") <+> ppr wanted
  979. , ptext (sLit "Binds =") <+> ppr binds
  980. , pprSkolInfo info ])
  981. \end{code}
  982. Note [Shadowing in a constraint]
  983. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  984. We assume NO SHADOWING in a constraint. Specifically
  985. * The unification variables are all implicitly quantified at top
  986. level, and are all unique
  987. * The skolem varibles bound in ic_skols are all freah when the
  988. implication is created.
  989. So we can safely substitute. For example, if we have
  990. forall a. a~Int => ...(forall b. ...a...)...
  991. we can push the (a~Int) constraint inwards in the "givens" without
  992. worrying that 'b' might clash.
  993. Note [Skolems in an implication]
  994. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  995. The skolems in an implication are not there to perform a skolem escape
  996. check. That happens because all the environment variables are in the
  997. untouchables, and therefore cannot be unified with anything at all,
  998. let alone the skolems.
  999. Instead, ic_skols is used only when considering floating a constraint
  1000. outside the implication in TcSimplify.floatEqualities or
  1001. TcSimplify.approximateImplications
  1002. Note [Insoluble constraints]
  1003. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1004. Some of the errors that we get during canonicalization are best
  1005. reported when all constraints have been simplified as much as
  1006. possible. For instance, assume that during simplification the
  1007. following constraints arise:
  1008. [Wanted] F alpha ~ uf1
  1009. [Wanted] beta ~ uf1 beta
  1010. When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
  1011. we will simply see a message:
  1012. 'Can't construct the infinite type beta ~ uf1 beta'
  1013. and the user has no idea what the uf1 variable is.
  1014. Instead our plan is that we will NOT fail immediately, but:
  1015. (1) Record the "frozen" error in the ic_insols field
  1016. (2) Isolate the offending constraint from the rest of the inerts
  1017. (3) Keep on simplifying/canonicalizing
  1018. At the end, we will hopefully have substituted uf1 := F alpha, and we
  1019. will be able to report a more informative error:
  1020. 'Can't construct the infinite type beta ~ F alpha beta'
  1021. Insoluble constraints *do* include Derived constraints. For example,
  1022. a functional dependency might give rise to [D] Int ~ Bool, and we must
  1023. report that. If insolubles did not contain Deriveds, reportErrors would
  1024. never see it.
  1025. %************************************************************************
  1026. %* *
  1027. Pretty printing
  1028. %* *
  1029. %************************************************************************
  1030. \begin{code}
  1031. pprEvVars :: [EvVar] -> SDoc -- Print with their types
  1032. pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
  1033. pprEvVarTheta :: [EvVar] -> SDoc
  1034. pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
  1035. pprEvVarWithType :: EvVar -> SDoc
  1036. pprEvVarWithType v = ppr v <+> dcolon <+> pprType (evVarPred v)
  1037. pprWantedsWithLocs :: WantedConstraints -> SDoc
  1038. pprWantedsWithLocs wcs
  1039. = vcat [ pprBag ppr (wc_flat wcs)
  1040. , pprBag ppr (wc_impl wcs)
  1041. , pprBag ppr (wc_insol wcs) ]
  1042. \end{code}
  1043. %************************************************************************
  1044. %* *
  1045. CtEvidence
  1046. %* *
  1047. %************************************************************************
  1048. Note [Evidence field of CtEvidence]
  1049. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1050. During constraint solving we never look at the type of ctev_evtm, or
  1051. ctev_evar; instead we look at the cte_pred field. The evtm/evar field
  1052. may be un-zonked.
  1053. \begin{code}
  1054. data CtEvidence
  1055. = CtGiven { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
  1056. , ctev_evtm :: EvTerm } -- See Note [Evidence field of CtEvidence]
  1057. -- Truly given, not depending on subgoals
  1058. -- NB: Spontaneous unifications belong here
  1059. | CtWanted { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
  1060. , ctev_evar :: EvVar } -- See Note [Evidence field of CtEvidence]
  1061. -- Wanted goal
  1062. | CtDerived { ctev_pred :: TcPredType }
  1063. -- A goal that we don't really have to solve and can't immediately
  1064. -- rewrite anything other than a derived (there's no evidence!)
  1065. -- but if we do manage to solve it may help in solving other goals.
  1066. data CtFlavour = Given | Wanted | Derived
  1067. ctFlavour :: Ct -> CtFlavour
  1068. ctFlavour ct = ctEvFlavour (cc_ev ct)
  1069. ctEvFlavour :: CtEvidence -> CtFlavour
  1070. ctEvFlavour (CtGiven {}) = Given
  1071. ctEvFlavour (CtWanted {}) = Wanted
  1072. ctEvFlavour (CtDerived {}) = Derived
  1073. ctEvPred :: CtEvidence -> TcPredType
  1074. -- The predicate of a flavor
  1075. ctEvPred = ctev_pred
  1076. ctEvTerm :: CtEvidence -> EvTerm
  1077. ctEvTerm (CtGiven { ctev_evtm = tm }) = tm
  1078. ctEvTerm (CtWanted { ctev_evar = ev }) = EvId ev
  1079. ctEvTerm ctev@(CtDerived {}) = pprPanic "ctEvTerm: derived constraint cannot have id"
  1080. (ppr ctev)
  1081. ctEvId :: CtEvidence -> TcId
  1082. ctEvId (CtWanted { ctev_evar = ev }) = ev
  1083. ctEvId ctev = pprPanic "ctEvId:" (ppr ctev)
  1084. instance Outputable CtFlavour where
  1085. ppr Given = ptext (sLit "[G]")
  1086. ppr Wanted = ptext (sLit "[W]")
  1087. ppr Derived = ptext (sLit "[D]")
  1088. instance Outputable CtEvidence where
  1089. ppr fl = case fl of
  1090. CtGiven {} -> ptext (sLit "[G]") <+> ppr (ctev_evtm fl) <+> ppr_pty
  1091. CtWanted {} -> ptext (sLit "[W]") <+> ppr (ctev_evar fl) <+> ppr_pty
  1092. CtDerived {} -> ptext (sLit "[D]") <+> text "_" <+> ppr_pty
  1093. where ppr_pty = dcolon <+> ppr (ctEvPred fl)
  1094. isWanted :: CtEvidence -> Bool
  1095. isWanted (CtWanted {}) = True
  1096. isWanted _ = False
  1097. isGiven :: CtEvidence -> Bool
  1098. isGiven (CtGiven {}) = True
  1099. isGiven _ = False
  1100. isDerived :: CtEvidence -> Bool
  1101. isDerived (CtDerived {}) = True
  1102. isDerived _ = False
  1103. canSolve :: CtFlavour -> CtFlavour -> Bool
  1104. -- canSolve ctid1 ctid2
  1105. -- The constraint ctid1 can be used to solve ctid2
  1106. -- "to solve" means a reaction where the active parts of the two constraints match.
  1107. -- active(F xis ~ xi) = F xis
  1108. -- active(tv ~ xi) = tv
  1109. -- active(D xis) = D xis
  1110. -- active(IP nm ty) = nm
  1111. --
  1112. -- NB: either (a `canSolve` b) or (b `canSolve` a) must hold
  1113. -----------------------------------------
  1114. canSolve Given _ = True
  1115. canSolve Wanted Derived = True
  1116. canSolve Wanted Wanted = True
  1117. canSolve Derived Derived = True -- Derived can't solve wanted/given
  1118. canSolve _ _ = False -- No evidence for a derived, anyway
  1119. canRewrite :: CtFlavour -> CtFlavour -> Bool
  1120. -- canRewrite ct1 ct2
  1121. -- The equality constraint ct1 can be used to rewrite inside ct2
  1122. canRewrite = canSolve
  1123. \end{code}
  1124. %************************************************************************
  1125. %* *
  1126. CtLoc
  1127. %* *
  1128. %************************************************************************
  1129. The 'CtLoc' gives information about where a constraint came from.
  1130. This is important for decent error message reporting because
  1131. dictionaries don't appear in the original source code.
  1132. type will evolve...
  1133. \begin{code}
  1134. data CtLoc = CtLoc { ctl_origin :: CtOrigin
  1135. , ctl_env :: TcLclEnv
  1136. , ctl_depth :: SubGoalDepth }
  1137. -- The TcLclEnv includes particularly
  1138. -- source location: tcl_loc :: SrcSpan
  1139. -- context: tcl_ctxt :: [ErrCtxt]
  1140. -- binder stack: tcl_bndrs :: [TcIdBinders]
  1141. type SubGoalDepth = Int -- An ever increasing number used to restrict
  1142. -- simplifier iterations. Bounded by -fcontext-stack.
  1143. -- See Note [WorkList]
  1144. mkGivenLoc :: SkolemInfo -> TcLclEnv -> CtLoc
  1145. mkGivenLoc skol_info env = CtLoc { ctl_origin = GivenOrigin skol_info
  1146. , ctl_env = env
  1147. , ctl_depth = 0 }
  1148. ctLocEnv :: CtLoc -> TcLclEnv
  1149. ctLocEnv = ctl_env
  1150. ctLocDepth :: CtLoc -> SubGoalDepth
  1151. ctLocDepth = ctl_depth
  1152. ctLocOrigin :: CtLoc -> CtOrigin
  1153. ctLocOrigin = ctl_origin
  1154. ctLocSpan :: CtLoc -> SrcSpan
  1155. ctLocSpan (CtLoc { ctl_env = lcl}) = tcl_loc lcl
  1156. bumpCtLocDepth :: CtLoc -> CtLoc
  1157. bumpCtLocDepth loc@(CtLoc { ctl_depth = d }) = loc { ctl_depth = d+1 }
  1158. setCtLocOrigin :: CtLoc -> CtOrigin -> CtLoc
  1159. setCtLocOrigin ctl orig = ctl { ctl_origin = orig }
  1160. setCtLocEnv :: CtLoc -> TcLclEnv -> CtLoc
  1161. setCtLocEnv ctl env = ctl { ctl_env = env }
  1162. pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc
  1163. pushErrCtxt o err loc@(CtLoc { ctl_env = lcl })
  1164. = loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
  1165. pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc
  1166. -- Just add information w/o updating the origin!
  1167. pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl })
  1168. = loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
  1169. pprArising :: CtOrigin -> SDoc
  1170. -- Used for the main, top-level error message
  1171. -- We've done special processing for TypeEq and FunDep origins
  1172. pprArising (TypeEqOrigin {}) = empty
  1173. pprArising FunDepOrigin = empty
  1174. pprArising orig = text "arising from" <+> ppr orig
  1175. pprArisingAt :: CtLoc -> SDoc
  1176. pprArisingAt (CtLoc { ctl_origin = o, ctl_env = lcl})
  1177. = sep [ text "arising from" <+> ppr o
  1178. , text "at" <+> ppr (tcl_loc lcl)]
  1179. \end{code}
  1180. %************************************************************************
  1181. %* *
  1182. SkolemInfo
  1183. %* *
  1184. %************************************************************************
  1185. \begin{code}
  1186. -- SkolemInfo gives the origin of *given* constraints
  1187. -- a) type variables are skolemised
  1188. -- b) an implication constraint is generated
  1189. data SkolemInfo
  1190. = SigSkol UserTypeCtxt -- A skolem that is created by instantiating
  1191. Type -- a programmer-supplied type signature
  1192. -- Location of the binding site is on the TyVar
  1193. -- The rest are for non-scoped skolems
  1194. | ClsSkol Class -- Bound at a class decl
  1195. | InstSkol -- Bound at an instance decl
  1196. | DataSkol -- Bound at a data type declaration
  1197. | FamInstSkol -- Bound at a family instance decl
  1198. | PatSkol -- An existential type variable bound by a pattern for
  1199. DataCon -- a data constructor with an existential type.
  1200. (HsMatchContext Name)
  1201. -- e.g. data T = forall a. Eq a => MkT a
  1202. -- f (MkT x) = ...
  1203. -- The pattern MkT x will allocate an existential type
  1204. -- variable for 'a'.
  1205. | ArrowSkol -- An arrow form (see TcArrows)
  1206. | IPSkol [HsIPName] -- Binding site of an implicit parameter
  1207. | RuleSkol RuleName -- The LHS of a RULE
  1208. | InferSkol [(Name,TcType)]
  1209. -- We have inferred a type for these (mutually-recursivive)
  1210. -- polymorphic Ids, and are now checking that their RHS
  1211. -- constraints are satisfied.
  1212. | BracketSkol -- Template Haskell bracket
  1213. | UnifyForAllSkol -- We are unifying two for-all types
  1214. [TcTyVar] -- The instantiated skolem variables
  1215. TcType -- The instantiated type *inside* the forall
  1216. | UnkSkol -- Unhelpful info (until I improve it)
  1217. instance Outputable SkolemInfo where
  1218. ppr = pprSkolInfo
  1219. pprSkolInfo :: SkolemInfo -> SDoc
  1220. -- Complete the sentence "is a rigid type variable bound by..."
  1221. pprSkolInfo (SigSkol (FunSigCtxt f) ty)
  1222. = hang (ptext (sLit "the type signature for"))
  1223. 2 (pprPrefixOcc f <+> dcolon <+> ppr ty)
  1224. pprSkolInfo (SigSkol cx ty) = hang (pprUserTypeCtxt cx <> colon)
  1225. 2 (ppr ty)
  1226. pprSkolInfo (IPSkol ips) = ptext (sLit "the implicit-parameter bindings for")
  1227. <+> pprWithCommas ppr ips
  1228. pprSkolInfo (ClsSkol cls) = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
  1229. pprSkolInfo InstSkol = ptext (sLit "the instance declaration")
  1230. pprSkolInfo DataSkol = ptext (sLit "the data type declaration")
  1231. pprSkolInfo FamInstSkol = ptext (sLit "the family instance declaration")
  1232. pprSkolInfo BracketSkol = ptext (sLit "a Template Haskell bracket")
  1233. pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
  1234. pprSkolInfo ArrowSkol = ptext (sLit "the arrow form")
  1235. pprSkolInfo (PatSkol dc mc) = sep [ ptext (sLit "a pattern with constructor")
  1236. , nest 2 $ ppr dc <+> dcolon
  1237. <+> ppr (dataConUserType dc) <> comma
  1238. , ptext (sLit "in") <+> pprMatchContext mc ]
  1239. pprSkolInfo (InferSkol ids) = sep [ ptext (sLit "the inferred type of")
  1240. , vcat [ ppr name <+> dcolon <+> ppr ty
  1241. | (name,ty) <- ids ]]
  1242. pprSkolInfo (UnifyForAllSkol tvs ty) = ptext (sLit "the type") <+> ppr (mkForAllTys tvs ty)
  1243. -- UnkSkol
  1244. -- For type variables the others are dealt with by pprSkolTvBinding.
  1245. -- For Insts, these cases should not happen
  1246. pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
  1247. \end{code}
  1248. %************************************************************************
  1249. %* *
  1250. CtOrigin
  1251. %* *
  1252. %************************************************************************
  1253. \begin{code}
  1254. data CtOrigin
  1255. = GivenOrigin SkolemInfo
  1256. -- All the others are for *wanted* constraints
  1257. | OccurrenceOf Name -- Occurrence of an overloaded identifier
  1258. | AppOrigin -- An application of some kind
  1259. | SpecPragOrigin Name -- Specialisation pragma for identifier
  1260. | TypeEqOrigin { uo_actual :: TcType
  1261. , uo_expected :: TcType }
  1262. | KindEqOrigin
  1263. TcType TcType -- A kind equality arising from unifying these two types
  1264. CtOrigin -- originally arising from this
  1265. | IPOccOrigin HsIPName -- Occurrence of an implicit parameter
  1266. | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
  1267. | NegateOrigin -- Occurrence of syntactic negation
  1268. | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
  1269. | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
  1270. | SectionOrigin
  1271. | TupleOrigin -- (..,..)
  1272. | AmbigOrigin UserTypeCtxt -- Will be FunSigCtxt, InstDeclCtxt, or SpecInstCtxt
  1273. | ExprSigOrigin -- e :: ty
  1274. | PatSigOrigin -- p :: ty
  1275. | PatOrigin -- Instantiating a polytyped pattern at a constructor
  1276. | RecordUpdOrigin
  1277. | ViewPatOrigin
  1278. | ScOrigin -- Typechecking superclasses of an instance declaration
  1279. | DerivOrigin -- Typechecking deriving
  1280. | StandAloneDerivOrigin -- Typechecking stand-alone deriving
  1281. | DefaultOrigin -- Typechecking a default decl
  1282. | DoOrigin -- Arising from a do expression
  1283. | MCompOrigin -- Arising from a monad comprehension
  1284. | IfOrigin -- Arising from an if statement
  1285. | ProcOrigin -- Arising from a proc expression
  1286. | AnnOrigin -- An annotation
  1287. | FunDepOrigin
  1288. | HoleOrigin
  1289. | UnboundOccurrenceOf RdrName
  1290. | ListOrigin -- An overloaded list
  1291. pprO :: CtOrigin -> SDoc
  1292. pprO (GivenOrigin sk) = ppr sk
  1293. pprO (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
  1294. pprO AppOrigin = ptext (sLit "an application")
  1295. pprO (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
  1296. pprO (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
  1297. pprO RecordUpdOrigin = ptext (sLit "a record update")
  1298. pprO (AmbigOrigin ctxt) = ptext (sLit "the ambiguity check for")
  1299. <+> case ctxt of
  1300. FunSigCtxt name -> quotes (ppr name)
  1301. InfSigCtxt name -> quotes (ppr name)
  1302. _ -> pprUserTypeCtxt ctxt
  1303. pprO ExprSigOrigin = ptext (sLit "an expression type signature")
  1304. pprO PatSigOrigin = ptext (sLit "a pattern type signature")
  1305. pprO PatOrigin = ptext (sLit "a pattern")
  1306. pprO ViewPatOrigin = ptext (sLit "a view pattern")
  1307. pprO IfOrigin = ptext (sLit "an if statement")
  1308. pprO (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
  1309. pprO (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
  1310. pprO (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
  1311. pprO SectionOrigin = ptext (sLit "an operator section")
  1312. pprO TupleOrigin = ptext (sLit "a tuple")
  1313. pprO NegateOrigin = ptext (sLit "a use of syntactic negation")
  1314. pprO ScOrigin = ptext (sLit "the superclasses of an instance declaration")
  1315. pprO DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
  1316. pprO StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
  1317. pprO DefaultOrigin = ptext (sLit "a 'default' declaration")
  1318. pprO DoOrigin = ptext (sLit "a do statement")
  1319. pprO MCompOrigin = ptext (sLit "a statement in a monad comprehension")
  1320. pprO ProcOrigin = ptext (sLit "a proc expression")
  1321. pprO (TypeEqOrigin t1 t2) = ptext (sLit "a type equality") <+> sep [ppr t1, char '~', ppr t2]
  1322. pprO (KindEqOrigin t1 t2 _) = ptext (sLit "a kind equality arising from") <+> sep [ppr t1, char '~', ppr t2]
  1323. pprO AnnOrigin = ptext (sLit "an annotation")
  1324. pprO FunDepOrigin = ptext (sLit "a functional dependency")
  1325. pprO HoleOrigin = ptext (sLit "a use of") <+> quotes (ptext $ sLit "_")
  1326. pprO (UnboundOccurrenceOf name) = hsep [ptext (sLit "an undeclared identifier"), quotes (ppr name)]
  1327. pprO ListOrigin = ptext (sLit "an overloaded list")
  1328. instance Outputable CtOrigin where
  1329. ppr = pprO
  1330. \end{code}