Fix GHCi/GHC-API tidying and modules (Trac #9424, #9426)
[ghc.git] / compiler / typecheck / TcRnTypes.hs
1 {-
2 (c) The University of Glasgow 2006-2012
3 (c) The GRASP Project, Glasgow University, 1992-2002
4
5
6 Various types used during typechecking, please see TcRnMonad as well for
7 operations on these types. You probably want to import it, instead of this
8 module.
9
10 All the monads exported here are built on top of the same IOEnv monad. The
11 monad functions like a Reader monad in the way it passes the environment
12 around. This is done to allow the environment to be manipulated in a stack
13 like fashion when entering expressions... ect.
14
15 For state that is global and should be returned at the end (e.g not part
16 of the stack mechanism), you should use an TcRef (= IORef) to store them.
17 -}
18
19 {-# LANGUAGE CPP, ExistentialQuantification #-}
20
21 module TcRnTypes(
22 TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
23 TcRef,
24
25 -- The environment types
26 Env(..),
27 TcGblEnv(..), TcLclEnv(..),
28 IfGblEnv(..), IfLclEnv(..),
29
30 -- Ranamer types
31 ErrCtxt, RecFieldEnv(..),
32 ImportAvails(..), emptyImportAvails, plusImportAvails,
33 WhereFrom(..), mkModDeps,
34
35 -- Typechecker types
36 TcTypeEnv, TcIdBinder(..), TcTyThing(..), PromotionErr(..),
37 pprTcTyThingCategory, pprPECategory,
38
39 -- Desugaring types
40 DsM, DsLclEnv(..), DsGblEnv(..), PArrBuiltin(..),
41 DsMetaEnv, DsMetaVal(..),
42
43 -- Template Haskell
44 ThStage(..), PendingStuff(..), topStage, topAnnStage, topSpliceStage,
45 ThLevel, impLevel, outerLevel, thLevel,
46
47 -- Arrows
48 ArrowCtxt(..),
49
50 -- Canonical constraints
51 Xi, Ct(..), Cts, emptyCts, andCts, andManyCts, pprCts,
52 singleCt, listToCts, ctsElts, consCts, snocCts, extendCtsList,
53 isEmptyCts, isCTyEqCan, isCFunEqCan,
54 isCDictCan_Maybe, isCFunEqCan_maybe,
55 isCIrredEvCan, isCNonCanonical, isWantedCt, isDerivedCt,
56 isGivenCt, isHoleCt, isTypedHoleCt, isPartialTypeSigCt,
57 ctEvidence, ctLoc, ctPred, ctFlavour, ctEqRel,
58 mkNonCanonical, mkNonCanonicalCt,
59 ctEvPred, ctEvLoc, ctEvEqRel,
60 ctEvTerm, ctEvCoercion, ctEvId, ctEvCheckDepth,
61
62 WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
63 andWC, unionsWC, addSimples, addImplics, mkSimpleWC, addInsols,
64 dropDerivedWC,
65
66 Implication(..),
67 SubGoalCounter(..),
68 SubGoalDepth, initialSubGoalDepth, maxSubGoalDepth,
69 bumpSubGoalDepth, subGoalCounterValue, subGoalDepthExceeded,
70 CtLoc(..), ctLocSpan, ctLocEnv, ctLocOrigin,
71 ctLocDepth, bumpCtLocDepth,
72 setCtLocOrigin, setCtLocEnv, setCtLocSpan,
73 CtOrigin(..), pprCtOrigin,
74 pushErrCtxt, pushErrCtxtSameOrigin,
75
76 SkolemInfo(..),
77
78 CtEvidence(..),
79 mkGivenLoc,
80 isWanted, isGiven, isDerived,
81 ctEvRole,
82
83 -- Constraint solver plugins
84 TcPlugin(..), TcPluginResult(..), TcPluginSolver,
85 TcPluginM, runTcPluginM, unsafeTcPluginTcM,
86
87 CtFlavour(..), ctEvFlavour,
88
89 -- Pretty printing
90 pprEvVarTheta,
91 pprEvVars, pprEvVarWithType,
92 pprArising, pprArisingAt,
93
94 -- Misc other types
95 TcId, TcIdSet, HoleSort(..)
96
97 ) where
98
99 #include "HsVersions.h"
100
101 import HsSyn
102 import CoreSyn
103 import HscTypes
104 import TcEvidence
105 import Type
106 import CoAxiom ( Role )
107 import Class ( Class )
108 import TyCon ( TyCon )
109 import ConLike ( ConLike(..) )
110 import DataCon ( DataCon, dataConUserType, dataConOrigArgTys )
111 import PatSyn ( PatSyn, patSynType )
112 import TysWiredIn ( coercibleClass )
113 import TcType
114 import Annotations
115 import InstEnv
116 import FamInstEnv
117 import IOEnv
118 import RdrName
119 import Name
120 import NameEnv
121 import NameSet
122 import Avail
123 import Var
124 import VarEnv
125 import Module
126 import SrcLoc
127 import VarSet
128 import ErrUtils
129 import UniqFM
130 import UniqSupply
131 import BasicTypes
132 import Bag
133 import DynFlags
134 import Outputable
135 import ListSetOps
136 import FastString
137 import GHC.Fingerprint
138
139 import Data.Set (Set)
140 import Control.Monad (ap, liftM)
141
142 #ifdef GHCI
143 import Data.Map ( Map )
144 import Data.Dynamic ( Dynamic )
145 import Data.Typeable ( TypeRep )
146
147 import qualified Language.Haskell.TH as TH
148 #endif
149
150 {-
151 ************************************************************************
152 * *
153 Standard monad definition for TcRn
154 All the combinators for the monad can be found in TcRnMonad
155 * *
156 ************************************************************************
157
158 The monad itself has to be defined here, because it is mentioned by ErrCtxt
159 -}
160
161 type TcRnIf a b = IOEnv (Env a b)
162 type TcRn = TcRnIf TcGblEnv TcLclEnv -- Type inference
163 type IfM lcl = TcRnIf IfGblEnv lcl -- Iface stuff
164 type IfG = IfM () -- Top level
165 type IfL = IfM IfLclEnv -- Nested
166 type DsM = TcRnIf DsGblEnv DsLclEnv -- Desugaring
167
168 -- TcRn is the type-checking and renaming monad: the main monad that
169 -- most type-checking takes place in. The global environment is
170 -- 'TcGblEnv', which tracks all of the top-level type-checking
171 -- information we've accumulated while checking a module, while the
172 -- local environment is 'TcLclEnv', which tracks local information as
173 -- we move inside expressions.
174
175 -- | Historical "renaming monad" (now it's just 'TcRn').
176 type RnM = TcRn
177
178 -- | Historical "type-checking monad" (now it's just 'TcRn').
179 type TcM = TcRn
180
181 -- We 'stack' these envs through the Reader like monad infastructure
182 -- as we move into an expression (although the change is focused in
183 -- the lcl type).
184 data Env gbl lcl
185 = Env {
186 env_top :: HscEnv, -- Top-level stuff that never changes
187 -- Includes all info about imported things
188
189 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
190 -- Unique supply for local varibles
191
192 env_gbl :: gbl, -- Info about things defined at the top level
193 -- of the module being compiled
194
195 env_lcl :: lcl -- Nested stuff; changes as we go into
196 }
197
198 instance ContainsDynFlags (Env gbl lcl) where
199 extractDynFlags env = hsc_dflags (env_top env)
200 replaceDynFlags env dflags
201 = env {env_top = replaceDynFlags (env_top env) dflags}
202
203 instance ContainsModule gbl => ContainsModule (Env gbl lcl) where
204 extractModule env = extractModule (env_gbl env)
205
206
207 {-
208 ************************************************************************
209 * *
210 The interface environments
211 Used when dealing with IfaceDecls
212 * *
213 ************************************************************************
214 -}
215
216 data IfGblEnv
217 = IfGblEnv {
218 -- The type environment for the module being compiled,
219 -- in case the interface refers back to it via a reference that
220 -- was originally a hi-boot file.
221 -- We need the module name so we can test when it's appropriate
222 -- to look in this env.
223 if_rec_types :: Maybe (Module, IfG TypeEnv)
224 -- Allows a read effect, so it can be in a mutable
225 -- variable; c.f. handling the external package type env
226 -- Nothing => interactive stuff, no loops possible
227 }
228
229 data IfLclEnv
230 = IfLclEnv {
231 -- The module for the current IfaceDecl
232 -- So if we see f = \x -> x
233 -- it means M.f = \x -> x, where M is the if_mod
234 if_mod :: Module,
235
236 -- The field is used only for error reporting
237 -- if (say) there's a Lint error in it
238 if_loc :: SDoc,
239 -- Where the interface came from:
240 -- .hi file, or GHCi state, or ext core
241 -- plus which bit is currently being examined
242
243 if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
244 -- (and coercions)
245 if_id_env :: UniqFM Id -- Nested id binding
246 }
247
248 {-
249 ************************************************************************
250 * *
251 Desugarer monad
252 * *
253 ************************************************************************
254
255 Now the mondo monad magic (yes, @DsM@ is a silly name)---carry around
256 a @UniqueSupply@ and some annotations, which
257 presumably include source-file location information:
258 -}
259
260 -- If '-XParallelArrays' is given, the desugarer populates this table with the corresponding
261 -- variables found in 'Data.Array.Parallel'.
262 --
263 data PArrBuiltin
264 = PArrBuiltin
265 { lengthPVar :: Var -- ^ lengthP
266 , replicatePVar :: Var -- ^ replicateP
267 , singletonPVar :: Var -- ^ singletonP
268 , mapPVar :: Var -- ^ mapP
269 , filterPVar :: Var -- ^ filterP
270 , zipPVar :: Var -- ^ zipP
271 , crossMapPVar :: Var -- ^ crossMapP
272 , indexPVar :: Var -- ^ (!:)
273 , emptyPVar :: Var -- ^ emptyP
274 , appPVar :: Var -- ^ (+:+)
275 , enumFromToPVar :: Var -- ^ enumFromToP
276 , enumFromThenToPVar :: Var -- ^ enumFromThenToP
277 }
278
279 data DsGblEnv
280 = DsGblEnv
281 { ds_mod :: Module -- For SCC profiling
282 , ds_fam_inst_env :: FamInstEnv -- Like tcg_fam_inst_env
283 , ds_unqual :: PrintUnqualified
284 , ds_msgs :: IORef Messages -- Warning messages
285 , ds_if_env :: (IfGblEnv, IfLclEnv) -- Used for looking up global,
286 -- possibly-imported things
287 , ds_dph_env :: GlobalRdrEnv -- exported entities of 'Data.Array.Parallel.Prim'
288 -- iff '-fvectorise' flag was given as well as
289 -- exported entities of 'Data.Array.Parallel' iff
290 -- '-XParallelArrays' was given; otherwise, empty
291 , ds_parr_bi :: PArrBuiltin -- desugarar names for '-XParallelArrays'
292 , ds_static_binds :: IORef [(Fingerprint, (Id,CoreExpr))]
293 -- ^ Bindings resulted from floating static forms
294 }
295
296 instance ContainsModule DsGblEnv where
297 extractModule = ds_mod
298
299 data DsLclEnv = DsLclEnv {
300 dsl_meta :: DsMetaEnv, -- Template Haskell bindings
301 dsl_loc :: SrcSpan -- to put in pattern-matching error msgs
302 }
303
304 -- Inside [| |] brackets, the desugarer looks
305 -- up variables in the DsMetaEnv
306 type DsMetaEnv = NameEnv DsMetaVal
307
308 data DsMetaVal
309 = DsBound Id -- Bound by a pattern inside the [| |].
310 -- Will be dynamically alpha renamed.
311 -- The Id has type THSyntax.Var
312
313 | DsSplice (HsExpr Id) -- These bindings are introduced by
314 -- the PendingSplices on a HsBracketOut
315
316
317 {-
318 ************************************************************************
319 * *
320 Global typechecker environment
321 * *
322 ************************************************************************
323 -}
324
325 -- | 'TcGblEnv' describes the top-level of the module at the
326 -- point at which the typechecker is finished work.
327 -- It is this structure that is handed on to the desugarer
328 -- For state that needs to be updated during the typechecking
329 -- phase and returned at end, use a 'TcRef' (= 'IORef').
330 data TcGblEnv
331 = TcGblEnv {
332 tcg_mod :: Module, -- ^ Module being compiled
333 tcg_src :: HscSource,
334 -- ^ What kind of module (regular Haskell, hs-boot, ext-core)
335 tcg_sig_of :: Maybe Module,
336 -- ^ Are we being compiled as a signature of an implementation?
337 tcg_impl_rdr_env :: Maybe GlobalRdrEnv,
338 -- ^ Environment used only during -sig-of for resolving top level
339 -- bindings. See Note [Signature parameters in TcGblEnv and DynFlags]
340
341 tcg_rdr_env :: GlobalRdrEnv, -- ^ Top level envt; used during renaming
342 tcg_default :: Maybe [Type],
343 -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
344
345 tcg_fix_env :: FixityEnv, -- ^ Just for things in this module
346 tcg_field_env :: RecFieldEnv, -- ^ Just for things in this module
347 -- See Note [The interactive package] in HscTypes
348
349 tcg_type_env :: TypeEnv,
350 -- ^ Global type env for the module we are compiling now. All
351 -- TyCons and Classes (for this module) end up in here right away,
352 -- along with their derived constructors, selectors.
353 --
354 -- (Ids defined in this module start in the local envt, though they
355 -- move to the global envt during zonking)
356 --
357 -- NB: for what "things in this module" means, see
358 -- Note [The interactive package] in HscTypes
359
360 tcg_type_env_var :: TcRef TypeEnv,
361 -- Used only to initialise the interface-file
362 -- typechecker in initIfaceTcRn, so that it can see stuff
363 -- bound in this module when dealing with hi-boot recursions
364 -- Updated at intervals (e.g. after dealing with types and classes)
365
366 tcg_inst_env :: InstEnv,
367 -- ^ Instance envt for all /home-package/ modules;
368 -- Includes the dfuns in tcg_insts
369 tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
370 tcg_ann_env :: AnnEnv, -- ^ And for annotations
371
372 tcg_visible_orphan_mods :: ModuleSet,
373 -- ^ The set of orphan modules which transitively reachable from
374 -- direct imports. We use this to figure out if an orphan instance
375 -- in the global InstEnv should be considered visible.
376 -- See Note [Instance lookup and orphan instances] in InstEnv
377
378 -- Now a bunch of things about this module that are simply
379 -- accumulated, but never consulted until the end.
380 -- Nevertheless, it's convenient to accumulate them along
381 -- with the rest of the info from this module.
382 tcg_exports :: [AvailInfo], -- ^ What is exported
383 tcg_imports :: ImportAvails,
384 -- ^ Information about what was imported from where, including
385 -- things bound in this module. Also store Safe Haskell info
386 -- here about transative trusted packaage requirements.
387
388 tcg_dus :: DefUses, -- ^ What is defined in this module and what is used.
389 tcg_used_rdrnames :: TcRef (Set RdrName),
390 -- See Note [Tracking unused binding and imports]
391
392 tcg_keep :: TcRef NameSet,
393 -- ^ Locally-defined top-level names to keep alive.
394 --
395 -- "Keep alive" means give them an Exported flag, so that the
396 -- simplifier does not discard them as dead code, and so that they
397 -- are exposed in the interface file (but not to export to the
398 -- user).
399 --
400 -- Some things, like dict-fun Ids and default-method Ids are "born"
401 -- with the Exported flag on, for exactly the above reason, but some
402 -- we only discover as we go. Specifically:
403 --
404 -- * The to/from functions for generic data types
405 --
406 -- * Top-level variables appearing free in the RHS of an orphan
407 -- rule
408 --
409 -- * Top-level variables appearing free in a TH bracket
410
411 tcg_th_used :: TcRef Bool,
412 -- ^ @True@ <=> Template Haskell syntax used.
413 --
414 -- We need this so that we can generate a dependency on the
415 -- Template Haskell package, because the desugarer is going
416 -- to emit loads of references to TH symbols. The reference
417 -- is implicit rather than explicit, so we have to zap a
418 -- mutable variable.
419
420 tcg_th_splice_used :: TcRef Bool,
421 -- ^ @True@ <=> A Template Haskell splice was used.
422 --
423 -- Splices disable recompilation avoidance (see #481)
424
425 tcg_dfun_n :: TcRef OccSet,
426 -- ^ Allows us to choose unique DFun names.
427
428 -- The next fields accumulate the payload of the module
429 -- The binds, rules and foreign-decl fields are collected
430 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
431
432 tcg_rn_exports :: Maybe [Located (IE Name)],
433 tcg_rn_imports :: [LImportDecl Name],
434 -- Keep the renamed imports regardless. They are not
435 -- voluminous and are needed if you want to report unused imports
436
437 tcg_rn_decls :: Maybe (HsGroup Name),
438 -- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
439 -- decls.
440
441 tcg_dependent_files :: TcRef [FilePath], -- ^ dependencies from addDependentFile
442
443 #ifdef GHCI
444 tcg_th_topdecls :: TcRef [LHsDecl RdrName],
445 -- ^ Top-level declarations from addTopDecls
446
447 tcg_th_topnames :: TcRef NameSet,
448 -- ^ Exact names bound in top-level declarations in tcg_th_topdecls
449
450 tcg_th_modfinalizers :: TcRef [TH.Q ()],
451 -- ^ Template Haskell module finalizers
452
453 tcg_th_state :: TcRef (Map TypeRep Dynamic),
454 -- ^ Template Haskell state
455 #endif /* GHCI */
456
457 tcg_ev_binds :: Bag EvBind, -- Top-level evidence bindings
458
459 -- Things defined in this module, or (in GHCi)
460 -- in the declarations for a single GHCi command.
461 -- For the latter, see Note [The interactive package] in HscTypes
462 tcg_binds :: LHsBinds Id, -- Value bindings in this module
463 tcg_sigs :: NameSet, -- ...Top-level names that *lack* a signature
464 tcg_imp_specs :: [LTcSpecPrag], -- ...SPECIALISE prags for imported Ids
465 tcg_warns :: Warnings, -- ...Warnings and deprecations
466 tcg_anns :: [Annotation], -- ...Annotations
467 tcg_tcs :: [TyCon], -- ...TyCons and Classes
468 tcg_insts :: [ClsInst], -- ...Instances
469 tcg_fam_insts :: [FamInst], -- ...Family instances
470 tcg_rules :: [LRuleDecl Id], -- ...Rules
471 tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
472 tcg_vects :: [LVectDecl Id], -- ...Vectorisation declarations
473 tcg_patsyns :: [PatSyn], -- ...Pattern synonyms
474
475 tcg_doc_hdr :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
476 tcg_hpc :: AnyHpcUsage, -- ^ @True@ if any part of the
477 -- prog uses hpc instrumentation.
478
479 tcg_main :: Maybe Name, -- ^ The Name of the main
480 -- function, if this module is
481 -- the main module.
482 tcg_safeInfer :: TcRef Bool, -- Has the typechecker
483 -- inferred this module
484 -- as -XSafe (Safe Haskell)
485
486 -- | A list of user-defined plugins for the constraint solver.
487 tcg_tc_plugins :: [TcPluginSolver],
488
489 tcg_static_wc :: TcRef WantedConstraints
490 -- ^ Wanted constraints of static forms.
491 }
492
493 -- Note [Signature parameters in TcGblEnv and DynFlags]
494 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
495 -- When compiling signature files, we need to know which implementation
496 -- we've actually linked against the signature. There are three seemingly
497 -- redundant places where this information is stored: in DynFlags, there
498 -- is sigOf, and in TcGblEnv, there is tcg_sig_of and tcg_impl_rdr_env.
499 -- Here's the difference between each of them:
500 --
501 -- * DynFlags.sigOf is global per invocation of GHC. If we are compiling
502 -- with --make, there may be multiple signature files being compiled; in
503 -- which case this parameter is a map from local module name to implementing
504 -- Module.
505 --
506 -- * HscEnv.tcg_sig_of is global per the compilation of a single file, so
507 -- it is simply the result of looking up tcg_mod in the DynFlags.sigOf
508 -- parameter. It's setup in TcRnMonad.initTc. This prevents us
509 -- from having to repeatedly do a lookup in DynFlags.sigOf.
510 --
511 -- * HscEnv.tcg_impl_rdr_env is a RdrEnv that lets us look up names
512 -- according to the sig-of module. It's setup in TcRnDriver.tcRnSignature.
513 -- Here is an example showing why we need this map:
514 --
515 -- module A where
516 -- a = True
517 --
518 -- module ASig where
519 -- import B
520 -- a :: Bool
521 --
522 -- module B where
523 -- b = False
524 --
525 -- When we compile ASig --sig-of main:A, the default
526 -- global RdrEnv (tcg_rdr_env) has an entry for b, but not for a
527 -- (we never imported A). So we have to look in a different environment
528 -- to actually get the original name.
529 --
530 -- By the way, why do we need to do the lookup; can't we just use A:a
531 -- as the name directly? Well, if A is reexporting the entity from another
532 -- module, then the original name needs to be the real original name:
533 --
534 -- module C where
535 -- a = True
536 --
537 -- module A(a) where
538 -- import C
539
540 instance ContainsModule TcGblEnv where
541 extractModule env = tcg_mod env
542
543 data RecFieldEnv
544 = RecFields (NameEnv [Name]) -- Maps a constructor name *in this module*
545 -- to the fields for that constructor
546 NameSet -- Set of all fields declared *in this module*;
547 -- used to suppress name-shadowing complaints
548 -- when using record wild cards
549 -- E.g. let fld = e in C {..}
550 -- This is used when dealing with ".." notation in record
551 -- construction and pattern matching.
552 -- The FieldEnv deals *only* with constructors defined in *this*
553 -- module. For imported modules, we get the same info from the
554 -- TypeEnv
555
556 {-
557 Note [Tracking unused binding and imports]
558 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
559 We gather two sorts of usage information
560 * tcg_dus (defs/uses)
561 Records *defined* Names (local, top-level)
562 and *used* Names (local or imported)
563
564 Used (a) to report "defined but not used"
565 (see RnNames.reportUnusedNames)
566 (b) to generate version-tracking usage info in interface
567 files (see MkIface.mkUsedNames)
568 This usage info is mainly gathered by the renamer's
569 gathering of free-variables
570
571 * tcg_used_rdrnames
572 Records used *imported* (not locally-defined) RdrNames
573 Used only to report unused import declarations
574 Notice that they are RdrNames, not Names, so we can
575 tell whether the reference was qualified or unqualified, which
576 is esssential in deciding whether a particular import decl
577 is unnecessary. This info isn't present in Names.
578
579
580 ************************************************************************
581 * *
582 The local typechecker environment
583 * *
584 ************************************************************************
585
586 Note [The Global-Env/Local-Env story]
587 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
588 During type checking, we keep in the tcg_type_env
589 * All types and classes
590 * All Ids derived from types and classes (constructors, selectors)
591
592 At the end of type checking, we zonk the local bindings,
593 and as we do so we add to the tcg_type_env
594 * Locally defined top-level Ids
595
596 Why? Because they are now Ids not TcIds. This final GlobalEnv is
597 a) fed back (via the knot) to typechecking the
598 unfoldings of interface signatures
599 b) used in the ModDetails of this module
600 -}
601
602 data TcLclEnv -- Changes as we move inside an expression
603 -- Discarded after typecheck/rename; not passed on to desugarer
604 = TcLclEnv {
605 tcl_loc :: SrcSpan, -- Source span
606 tcl_ctxt :: [ErrCtxt], -- Error context, innermost on top
607 tcl_tclvl :: TcLevel, -- Birthplace for new unification variables
608
609 tcl_th_ctxt :: ThStage, -- Template Haskell context
610 tcl_th_bndrs :: ThBindEnv, -- Binding level of in-scope Names
611 -- defined in this module (not imported)
612
613 tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
614
615 tcl_rdr :: LocalRdrEnv, -- Local name envt
616 -- Maintained during renaming, of course, but also during
617 -- type checking, solely so that when renaming a Template-Haskell
618 -- splice we have the right environment for the renamer.
619 --
620 -- Does *not* include global name envt; may shadow it
621 -- Includes both ordinary variables and type variables;
622 -- they are kept distinct because tyvar have a different
623 -- occurrence contructor (Name.TvOcc)
624 -- We still need the unsullied global name env so that
625 -- we can look up record field names
626
627 tcl_env :: TcTypeEnv, -- The local type environment:
628 -- Ids and TyVars defined in this module
629
630 tcl_bndrs :: [TcIdBinder], -- Stack of locally-bound Ids, innermost on top
631 -- Used only for error reporting
632
633 tcl_tidy :: TidyEnv, -- Used for tidying types; contains all
634 -- in-scope type variables (but not term variables)
635
636 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
637 -- Namely, the in-scope TyVars bound in tcl_env,
638 -- plus the tyvars mentioned in the types of Ids bound
639 -- in tcl_lenv.
640 -- Why mutable? see notes with tcGetGlobalTyVars
641
642 tcl_lie :: TcRef WantedConstraints, -- Place to accumulate type constraints
643 tcl_errs :: TcRef Messages -- Place to accumulate errors
644 }
645
646 type TcTypeEnv = NameEnv TcTyThing
647
648 type ThBindEnv = NameEnv (TopLevelFlag, ThLevel)
649 -- Domain = all Ids bound in this module (ie not imported)
650 -- The TopLevelFlag tells if the binding is syntactically top level.
651 -- We need to know this, because the cross-stage persistence story allows
652 -- cross-stage at arbitrary types if the Id is bound at top level.
653 --
654 -- Nota bene: a ThLevel of 'outerLevel' is *not* the same as being
655 -- bound at top level! See Note [Template Haskell levels] in TcSplice
656
657 data TcIdBinder
658 = TcIdBndr
659 TcId
660 TopLevelFlag -- Tells whether the bindind is syntactically top-level
661 -- (The monomorphic Ids for a recursive group count
662 -- as not-top-level for this purpose.)
663
664 {- Note [Given Insts]
665 ~~~~~~~~~~~~~~~~~~
666 Because of GADTs, we have to pass inwards the Insts provided by type signatures
667 and existential contexts. Consider
668 data T a where { T1 :: b -> b -> T [b] }
669 f :: Eq a => T a -> Bool
670 f (T1 x y) = [x]==[y]
671
672 The constructor T1 binds an existential variable 'b', and we need Eq [b].
673 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
674 pass it inwards.
675
676 -}
677
678 -- | Type alias for 'IORef'; the convention is we'll use this for mutable
679 -- bits of data in 'TcGblEnv' which are updated during typechecking and
680 -- returned at the end.
681 type TcRef a = IORef a
682 -- ToDo: when should I refer to it as a 'TcId' instead of an 'Id'?
683 type TcId = Id
684 type TcIdSet = IdSet
685
686 ---------------------------
687 -- Template Haskell stages and levels
688 ---------------------------
689
690 data ThStage -- See Note [Template Haskell state diagram] in TcSplice
691 = Splice -- Inside a top-level splice splice
692 -- This code will be run *at compile time*;
693 -- the result replaces the splice
694 -- Binding level = 0
695 Bool -- True if in a typed splice, False otherwise
696
697 | Comp -- Ordinary Haskell code
698 -- Binding level = 1
699
700 | Brack -- Inside brackets
701 ThStage -- Enclosing stage
702 PendingStuff
703
704 data PendingStuff
705 = RnPendingUntyped -- Renaming the inside of an *untyped* bracket
706 (TcRef [PendingRnSplice]) -- Pending splices in here
707
708 | RnPendingTyped -- Renaming the inside of a *typed* bracket
709
710 | TcPending -- Typechecking the inside of a typed bracket
711 (TcRef [PendingTcSplice]) -- Accumulate pending splices here
712 (TcRef WantedConstraints) -- and type constraints here
713
714 topStage, topAnnStage, topSpliceStage :: ThStage
715 topStage = Comp
716 topAnnStage = Splice False
717 topSpliceStage = Splice False
718
719 instance Outputable ThStage where
720 ppr (Splice _) = text "Splice"
721 ppr Comp = text "Comp"
722 ppr (Brack s _) = text "Brack" <> parens (ppr s)
723
724 type ThLevel = Int
725 -- NB: see Note [Template Haskell levels] in TcSplice
726 -- Incremented when going inside a bracket,
727 -- decremented when going inside a splice
728 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
729 -- original "Template meta-programming for Haskell" paper
730
731 impLevel, outerLevel :: ThLevel
732 impLevel = 0 -- Imported things; they can be used inside a top level splice
733 outerLevel = 1 -- Things defined outside brackets
734
735 thLevel :: ThStage -> ThLevel
736 thLevel (Splice _) = 0
737 thLevel Comp = 1
738 thLevel (Brack s _) = thLevel s + 1
739
740 ---------------------------
741 -- Arrow-notation context
742 ---------------------------
743
744 {- Note [Escaping the arrow scope]
745 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
746 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
747 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
748 For example
749
750 proc x -> (e1 -< e2)
751
752 Here, x is not in scope in e1, but it is in scope in e2. This can get
753 a bit complicated:
754
755 let x = 3 in
756 proc y -> (proc z -> e1) -< e2
757
758 Here, x and z are in scope in e1, but y is not.
759
760 We implement this by
761 recording the environment when passing a proc (using newArrowScope),
762 and returning to that (using escapeArrowScope) on the left of -< and the
763 head of (|..|).
764
765 All this can be dealt with by the *renamer*. But the type checker needs
766 to be involved too. Example (arrowfail001)
767 class Foo a where foo :: a -> ()
768 data Bar = forall a. Foo a => Bar a
769 get :: Bar -> ()
770 get = proc x -> case x of Bar a -> foo -< a
771 Here the call of 'foo' gives rise to a (Foo a) constraint that should not
772 be captured by the pattern match on 'Bar'. Rather it should join the
773 constraints from further out. So we must capture the constraint bag
774 from further out in the ArrowCtxt that we push inwards.
775 -}
776
777 data ArrowCtxt -- Note [Escaping the arrow scope]
778 = NoArrowCtxt
779 | ArrowCtxt LocalRdrEnv (TcRef WantedConstraints)
780
781
782 ---------------------------
783 -- TcTyThing
784 ---------------------------
785
786 data TcTyThing
787 = AGlobal TyThing -- Used only in the return type of a lookup
788
789 | ATcId { -- Ids defined in this module; may not be fully zonked
790 tct_id :: TcId,
791 tct_closed :: TopLevelFlag } -- See Note [Bindings with closed types]
792
793 | ATyVar Name TcTyVar -- The type variable to which the lexically scoped type
794 -- variable is bound. We only need the Name
795 -- for error-message purposes; it is the corresponding
796 -- Name in the domain of the envt
797
798 | AThing TcKind -- Used temporarily, during kind checking, for the
799 -- tycons and clases in this recursive group
800 -- Can be a mono-kind or a poly-kind; in TcTyClsDcls see
801 -- Note [Type checking recursive type and class declarations]
802
803 | APromotionErr PromotionErr
804
805 data PromotionErr
806 = TyConPE -- TyCon used in a kind before we are ready
807 -- data T :: T -> * where ...
808 | ClassPE -- Ditto Class
809
810 | FamDataConPE -- Data constructor for a data family
811 -- See Note [AFamDataCon: not promoting data family constructors] in TcRnDriver
812
813 | RecDataConPE -- Data constructor in a recursive loop
814 -- See Note [ARecDataCon: recusion and promoting data constructors] in TcTyClsDecls
815 | NoDataKinds -- -XDataKinds not enabled
816
817 instance Outputable TcTyThing where -- Debugging only
818 ppr (AGlobal g) = pprTyThing g
819 ppr elt@(ATcId {}) = text "Identifier" <>
820 brackets (ppr (tct_id elt) <> dcolon
821 <> ppr (varType (tct_id elt)) <> comma
822 <+> ppr (tct_closed elt))
823 ppr (ATyVar n tv) = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv
824 ppr (AThing k) = text "AThing" <+> ppr k
825 ppr (APromotionErr err) = text "APromotionErr" <+> ppr err
826
827 instance Outputable PromotionErr where
828 ppr ClassPE = text "ClassPE"
829 ppr TyConPE = text "TyConPE"
830 ppr FamDataConPE = text "FamDataConPE"
831 ppr RecDataConPE = text "RecDataConPE"
832 ppr NoDataKinds = text "NoDataKinds"
833
834 pprTcTyThingCategory :: TcTyThing -> SDoc
835 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
836 pprTcTyThingCategory (ATyVar {}) = ptext (sLit "Type variable")
837 pprTcTyThingCategory (ATcId {}) = ptext (sLit "Local identifier")
838 pprTcTyThingCategory (AThing {}) = ptext (sLit "Kinded thing")
839 pprTcTyThingCategory (APromotionErr pe) = pprPECategory pe
840
841 pprPECategory :: PromotionErr -> SDoc
842 pprPECategory ClassPE = ptext (sLit "Class")
843 pprPECategory TyConPE = ptext (sLit "Type constructor")
844 pprPECategory FamDataConPE = ptext (sLit "Data constructor")
845 pprPECategory RecDataConPE = ptext (sLit "Data constructor")
846 pprPECategory NoDataKinds = ptext (sLit "Data constructor")
847
848 {-
849 Note [Bindings with closed types]
850 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
851 Consider
852
853 f x = let g ys = map not ys
854 in ...
855
856 Can we generalise 'g' under the OutsideIn algorithm? Yes,
857 because all g's free variables are top-level; that is they themselves
858 have no free type variables, and it is the type variables in the
859 environment that makes things tricky for OutsideIn generalisation.
860
861 Definition:
862
863 A variable is "closed", and has tct_closed set to TopLevel,
864 iff
865 a) all its free variables are imported, or are themselves closed
866 b) generalisation is not restricted by the monomorphism restriction
867
868 Under OutsideIn we are free to generalise a closed let-binding.
869 This is an extension compared to the JFP paper on OutsideIn, which
870 used "top-level" as a proxy for "closed". (It's not a good proxy
871 anyway -- the MR can make a top-level binding with a free type
872 variable.)
873
874 Note that:
875 * A top-level binding may not be closed, if it suffer from the MR
876
877 * A nested binding may be closed (eg 'g' in the example we started with)
878 Indeed, that's the point; whether a function is defined at top level
879 or nested is orthogonal to the question of whether or not it is closed
880
881 * A binding may be non-closed because it mentions a lexically scoped
882 *type variable* Eg
883 f :: forall a. blah
884 f x = let g y = ...(y::a)...
885 -}
886
887 type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, MsgDoc))
888 -- Monadic so that we have a chance
889 -- to deal with bound type variables just before error
890 -- message construction
891
892 -- Bool: True <=> this is a landmark context; do not
893 -- discard it when trimming for display
894
895 {-
896 ************************************************************************
897 * *
898 Operations over ImportAvails
899 * *
900 ************************************************************************
901 -}
902
903 -- | 'ImportAvails' summarises what was imported from where, irrespective of
904 -- whether the imported things are actually used or not. It is used:
905 --
906 -- * when processing the export list,
907 --
908 -- * when constructing usage info for the interface file,
909 --
910 -- * to identify the list of directly imported modules for initialisation
911 -- purposes and for optimised overlap checking of family instances,
912 --
913 -- * when figuring out what things are really unused
914 --
915 data ImportAvails
916 = ImportAvails {
917 imp_mods :: ImportedMods,
918 -- = ModuleEnv [(ModuleName, Bool, SrcSpan, Bool)],
919 -- ^ Domain is all directly-imported modules
920 -- The 'ModuleName' is what the module was imported as, e.g. in
921 -- @
922 -- import Foo as Bar
923 -- @
924 -- it is @Bar@.
925 --
926 -- The 'Bool' means:
927 --
928 -- - @True@ => import was @import Foo ()@
929 --
930 -- - @False@ => import was some other form
931 --
932 -- Used
933 --
934 -- (a) to help construct the usage information in the interface
935 -- file; if we import something we need to recompile if the
936 -- export version changes
937 --
938 -- (b) to specify what child modules to initialise
939 --
940 -- We need a full ModuleEnv rather than a ModuleNameEnv here,
941 -- because we might be importing modules of the same name from
942 -- different packages. (currently not the case, but might be in the
943 -- future).
944
945 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
946 -- ^ Home-package modules needed by the module being compiled
947 --
948 -- It doesn't matter whether any of these dependencies
949 -- are actually /used/ when compiling the module; they
950 -- are listed if they are below it at all. For
951 -- example, suppose M imports A which imports X. Then
952 -- compiling M might not need to consult X.hi, but X
953 -- is still listed in M's dependencies.
954
955 imp_dep_pkgs :: [PackageKey],
956 -- ^ Packages needed by the module being compiled, whether directly,
957 -- or via other modules in this package, or via modules imported
958 -- from other packages.
959
960 imp_trust_pkgs :: [PackageKey],
961 -- ^ This is strictly a subset of imp_dep_pkgs and records the
962 -- packages the current module needs to trust for Safe Haskell
963 -- compilation to succeed. A package is required to be trusted if
964 -- we are dependent on a trustworthy module in that package.
965 -- While perhaps making imp_dep_pkgs a tuple of (PackageKey, Bool)
966 -- where True for the bool indicates the package is required to be
967 -- trusted is the more logical design, doing so complicates a lot
968 -- of code not concerned with Safe Haskell.
969 -- See Note [RnNames . Tracking Trust Transitively]
970
971 imp_trust_own_pkg :: Bool,
972 -- ^ Do we require that our own package is trusted?
973 -- This is to handle efficiently the case where a Safe module imports
974 -- a Trustworthy module that resides in the same package as it.
975 -- See Note [RnNames . Trust Own Package]
976
977 imp_orphs :: [Module],
978 -- ^ Orphan modules below us in the import tree (and maybe including
979 -- us for imported modules)
980
981 imp_finsts :: [Module]
982 -- ^ Family instance modules below us in the import tree (and maybe
983 -- including us for imported modules)
984 }
985
986 mkModDeps :: [(ModuleName, IsBootInterface)]
987 -> ModuleNameEnv (ModuleName, IsBootInterface)
988 mkModDeps deps = foldl add emptyUFM deps
989 where
990 add env elt@(m,_) = addToUFM env m elt
991
992 emptyImportAvails :: ImportAvails
993 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
994 imp_dep_mods = emptyUFM,
995 imp_dep_pkgs = [],
996 imp_trust_pkgs = [],
997 imp_trust_own_pkg = False,
998 imp_orphs = [],
999 imp_finsts = [] }
1000
1001 -- | Union two ImportAvails
1002 --
1003 -- This function is a key part of Import handling, basically
1004 -- for each import we create a separate ImportAvails structure
1005 -- and then union them all together with this function.
1006 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
1007 plusImportAvails
1008 (ImportAvails { imp_mods = mods1,
1009 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
1010 imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1,
1011 imp_orphs = orphs1, imp_finsts = finsts1 })
1012 (ImportAvails { imp_mods = mods2,
1013 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
1014 imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2,
1015 imp_orphs = orphs2, imp_finsts = finsts2 })
1016 = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
1017 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
1018 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
1019 imp_trust_pkgs = tpkgs1 `unionLists` tpkgs2,
1020 imp_trust_own_pkg = tself1 || tself2,
1021 imp_orphs = orphs1 `unionLists` orphs2,
1022 imp_finsts = finsts1 `unionLists` finsts2 }
1023 where
1024 plus_mod_dep (m1, boot1) (m2, boot2)
1025 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
1026 -- Check mod-names match
1027 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
1028
1029 {-
1030 ************************************************************************
1031 * *
1032 \subsection{Where from}
1033 * *
1034 ************************************************************************
1035
1036 The @WhereFrom@ type controls where the renamer looks for an interface file
1037 -}
1038
1039 data WhereFrom
1040 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
1041 | ImportBySystem -- Non user import.
1042 | ImportByPlugin -- Importing a plugin;
1043 -- See Note [Care with plugin imports] in LoadIface
1044
1045 instance Outputable WhereFrom where
1046 ppr (ImportByUser is_boot) | is_boot = ptext (sLit "{- SOURCE -}")
1047 | otherwise = empty
1048 ppr ImportBySystem = ptext (sLit "{- SYSTEM -}")
1049 ppr ImportByPlugin = ptext (sLit "{- PLUGIN -}")
1050
1051 {-
1052 ************************************************************************
1053 * *
1054 * Canonical constraints *
1055 * *
1056 * These are the constraints the low-level simplifier works with *
1057 * *
1058 ************************************************************************
1059 -}
1060
1061 -- The syntax of xi types:
1062 -- xi ::= a | T xis | xis -> xis | ... | forall a. tau
1063 -- Two important notes:
1064 -- (i) No type families, unless we are under a ForAll
1065 -- (ii) Note that xi types can contain unexpanded type synonyms;
1066 -- however, the (transitive) expansions of those type synonyms
1067 -- will not contain any type functions, unless we are under a ForAll.
1068 -- We enforce the structure of Xi types when we flatten (TcCanonical)
1069
1070 type Xi = Type -- In many comments, "xi" ranges over Xi
1071
1072 type Cts = Bag Ct
1073
1074 data Ct
1075 -- Atomic canonical constraints
1076 = CDictCan { -- e.g. Num xi
1077 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1078 cc_class :: Class,
1079 cc_tyargs :: [Xi] -- cc_tyargs are function-free, hence Xi
1080 }
1081
1082 | CIrredEvCan { -- These stand for yet-unusable predicates
1083 cc_ev :: CtEvidence -- See Note [Ct/evidence invariant]
1084 -- The ctev_pred of the evidence is
1085 -- of form (tv xi1 xi2 ... xin)
1086 -- or (tv1 ~ ty2) where the CTyEqCan kind invariant fails
1087 -- or (F tys ~ ty) where the CFunEqCan kind invariant fails
1088 -- See Note [CIrredEvCan constraints]
1089 }
1090
1091 | CTyEqCan { -- tv ~ rhs
1092 -- Invariants:
1093 -- * See Note [Applying the inert substitution] in TcFlatten
1094 -- * tv not in tvs(rhs) (occurs check)
1095 -- * If tv is a TauTv, then rhs has no foralls
1096 -- (this avoids substituting a forall for the tyvar in other types)
1097 -- * typeKind ty `subKind` typeKind tv
1098 -- See Note [Kind orientation for CTyEqCan]
1099 -- * rhs is not necessarily function-free,
1100 -- but it has no top-level function.
1101 -- E.g. a ~ [F b] is fine
1102 -- but a ~ F b is not
1103 -- * If the equality is representational, rhs has no top-level newtype
1104 -- See Note [No top-level newtypes on RHS of representational
1105 -- equalities] in TcCanonical
1106 -- * If rhs is also a tv, then it is oriented to give best chance of
1107 -- unification happening; eg if rhs is touchable then lhs is too
1108 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1109 cc_tyvar :: TcTyVar,
1110 cc_rhs :: TcType, -- Not necessarily function-free (hence not Xi)
1111 -- See invariants above
1112 cc_eq_rel :: EqRel
1113 }
1114
1115 | CFunEqCan { -- F xis ~ fsk
1116 -- Invariants:
1117 -- * isTypeFamilyTyCon cc_fun
1118 -- * typeKind (F xis) = tyVarKind fsk
1119 -- * always Nominal role
1120 -- * always Given or Wanted, never Derived
1121 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1122 cc_fun :: TyCon, -- A type function
1123
1124 cc_tyargs :: [Xi], -- cc_tyargs are function-free (hence Xi)
1125 -- Either under-saturated or exactly saturated
1126 -- *never* over-saturated (because if so
1127 -- we should have decomposed)
1128
1129 cc_fsk :: TcTyVar -- [Given] always a FlatSkol skolem
1130 -- [Wanted] always a FlatMetaTv unification variable
1131 -- See Note [The flattening story] in TcFlatten
1132 }
1133
1134 | CNonCanonical { -- See Note [NonCanonical Semantics]
1135 cc_ev :: CtEvidence
1136 }
1137
1138 | CHoleCan { -- Treated as an "insoluble" constraint
1139 -- See Note [Insoluble constraints]
1140 cc_ev :: CtEvidence,
1141 cc_occ :: OccName, -- The name of this hole
1142 cc_hole :: HoleSort -- The sort of this hole (expr, type, ...)
1143 }
1144
1145 -- | Used to indicate which sort of hole we have.
1146 data HoleSort = ExprHole -- ^ A hole in an expression (TypedHoles)
1147 | TypeHole -- ^ A hole in a type (PartialTypeSignatures)
1148
1149 {-
1150 Note [Kind orientation for CTyEqCan]
1151 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1152 Given an equality (t:* ~ s:Open), we can't solve it by updating t:=s,
1153 ragardless of how touchable 't' is, because the kinds don't work.
1154
1155 Instead we absolutely must re-orient it. Reason: if that gets into the
1156 inert set we'll start replacing t's by s's, and that might make a
1157 kind-correct type into a kind error. After re-orienting,
1158 we may be able to solve by updating s:=t.
1159
1160 Hence in a CTyEqCan, (t:k1 ~ xi:k2) we require that k2 is a subkind of k1.
1161
1162 If the two have incompatible kinds, we just don't use a CTyEqCan at all.
1163 See Note [Equalities with incompatible kinds] in TcCanonical
1164
1165 We can't require *equal* kinds, because
1166 * wanted constraints don't necessarily have identical kinds
1167 eg alpha::? ~ Int
1168 * a solved wanted constraint becomes a given
1169
1170 Note [Kind orientation for CFunEqCan]
1171 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1172 For (F xis ~ rhs) we require that kind(lhs) is a subkind of kind(rhs).
1173 This really only maters when rhs is an Open type variable (since only type
1174 variables have Open kinds):
1175 F ty ~ (a:Open)
1176 which can happen, say, from
1177 f :: F a b
1178 f = undefined -- The a:Open comes from instantiating 'undefined'
1179
1180 Note that the kind invariant is maintained by rewriting.
1181 Eg wanted1 rewrites wanted2; if both were compatible kinds before,
1182 wanted2 will be afterwards. Similarly givens.
1183
1184 Caveat:
1185 - Givens from higher-rank, such as:
1186 type family T b :: * -> * -> *
1187 type instance T Bool = (->)
1188
1189 f :: forall a. ((T a ~ (->)) => ...) -> a -> ...
1190 flop = f (...) True
1191 Whereas we would be able to apply the type instance, we would not be able to
1192 use the given (T Bool ~ (->)) in the body of 'flop'
1193
1194
1195 Note [CIrredEvCan constraints]
1196 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1197 CIrredEvCan constraints are used for constraints that are "stuck"
1198 - we can't solve them (yet)
1199 - we can't use them to solve other constraints
1200 - but they may become soluble if we substitute for some
1201 of the type variables in the constraint
1202
1203 Example 1: (c Int), where c :: * -> Constraint. We can't do anything
1204 with this yet, but if later c := Num, *then* we can solve it
1205
1206 Example 2: a ~ b, where a :: *, b :: k, where k is a kind variable
1207 We don't want to use this to substitute 'b' for 'a', in case
1208 'k' is subequently unifed with (say) *->*, because then
1209 we'd have ill-kinded types floating about. Rather we want
1210 to defer using the equality altogether until 'k' get resolved.
1211
1212 Note [Ct/evidence invariant]
1213 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1214 If ct :: Ct, then extra fields of 'ct' cache precisely the ctev_pred field
1215 of (cc_ev ct), and is fully rewritten wrt the substitution. Eg for CDictCan,
1216 ctev_pred (cc_ev ct) = (cc_class ct) (cc_tyargs ct)
1217 This holds by construction; look at the unique place where CDictCan is
1218 built (in TcCanonical).
1219
1220 In contrast, the type of the evidence *term* (ccev_evtm or ctev_evar) in
1221 the evidence may *not* be fully zonked; we are careful not to look at it
1222 during constraint solving. See Note [Evidence field of CtEvidence]
1223 -}
1224
1225 mkNonCanonical :: CtEvidence -> Ct
1226 mkNonCanonical ev = CNonCanonical { cc_ev = ev }
1227
1228 mkNonCanonicalCt :: Ct -> Ct
1229 mkNonCanonicalCt ct = CNonCanonical { cc_ev = cc_ev ct }
1230
1231 ctEvidence :: Ct -> CtEvidence
1232 ctEvidence = cc_ev
1233
1234 ctLoc :: Ct -> CtLoc
1235 ctLoc = ctEvLoc . ctEvidence
1236
1237 ctPred :: Ct -> PredType
1238 -- See Note [Ct/evidence invariant]
1239 ctPred ct = ctEvPred (cc_ev ct)
1240
1241 -- | Get the flavour of the given 'Ct'
1242 ctFlavour :: Ct -> CtFlavour
1243 ctFlavour = ctEvFlavour . ctEvidence
1244
1245 -- | Get the equality relation for the given 'Ct'
1246 ctEqRel :: Ct -> EqRel
1247 ctEqRel = ctEvEqRel . ctEvidence
1248
1249 dropDerivedWC :: WantedConstraints -> WantedConstraints
1250 -- See Note [Dropping derived constraints]
1251 dropDerivedWC wc@(WC { wc_simple = simples })
1252 = wc { wc_simple = filterBag isWantedCt simples }
1253 -- The wc_impl implications are already (recursively) filtered
1254
1255 {-
1256 Note [Dropping derived constraints]
1257 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1258 In general we discard derived constraints at the end of constraint solving;
1259 see dropDerivedWC. For example
1260 * If we have an unsolved (Ord a), we don't want to complain about
1261 an unsolved (Eq a) as well.
1262
1263 But we keep Derived *insoluble* constraints because they indicate a solid,
1264 comprehensible error. Particularly:
1265
1266 * Insolubles Givens indicate unreachable code
1267
1268 * Insoluble kind equalities (e.g. [D] * ~ (* -> *)) may arise from
1269 a type equality a ~ Int#, say
1270
1271 * Insoluble derived wanted equalities (e.g. [D] Int ~ Bool) may
1272 arise from functional dependency interactions. We are careful
1273 to keep a good CtOrigin on such constraints (FunDepOrigin1, FunDepOrigin2)
1274 so that we can produce a good error message (Trac #9612)
1275
1276 Since we leave these Derived constraints in the residual WantedConstraints,
1277 we must filter them out when we re-process the WantedConstraint,
1278 in TcSimplify.solve_wanteds.
1279
1280
1281 ************************************************************************
1282 * *
1283 CtEvidence
1284 The "flavor" of a canonical constraint
1285 * *
1286 ************************************************************************
1287 -}
1288
1289 isWantedCt :: Ct -> Bool
1290 isWantedCt = isWanted . cc_ev
1291
1292 isGivenCt :: Ct -> Bool
1293 isGivenCt = isGiven . cc_ev
1294
1295 isDerivedCt :: Ct -> Bool
1296 isDerivedCt = isDerived . cc_ev
1297
1298 isCTyEqCan :: Ct -> Bool
1299 isCTyEqCan (CTyEqCan {}) = True
1300 isCTyEqCan (CFunEqCan {}) = False
1301 isCTyEqCan _ = False
1302
1303 isCDictCan_Maybe :: Ct -> Maybe Class
1304 isCDictCan_Maybe (CDictCan {cc_class = cls }) = Just cls
1305 isCDictCan_Maybe _ = Nothing
1306
1307 isCIrredEvCan :: Ct -> Bool
1308 isCIrredEvCan (CIrredEvCan {}) = True
1309 isCIrredEvCan _ = False
1310
1311 isCFunEqCan_maybe :: Ct -> Maybe (TyCon, [Type])
1312 isCFunEqCan_maybe (CFunEqCan { cc_fun = tc, cc_tyargs = xis }) = Just (tc, xis)
1313 isCFunEqCan_maybe _ = Nothing
1314
1315 isCFunEqCan :: Ct -> Bool
1316 isCFunEqCan (CFunEqCan {}) = True
1317 isCFunEqCan _ = False
1318
1319 isCNonCanonical :: Ct -> Bool
1320 isCNonCanonical (CNonCanonical {}) = True
1321 isCNonCanonical _ = False
1322
1323 isHoleCt:: Ct -> Bool
1324 isHoleCt (CHoleCan {}) = True
1325 isHoleCt _ = False
1326
1327 isTypedHoleCt :: Ct -> Bool
1328 isTypedHoleCt (CHoleCan { cc_hole = ExprHole }) = True
1329 isTypedHoleCt _ = False
1330
1331 isPartialTypeSigCt :: Ct -> Bool
1332 isPartialTypeSigCt (CHoleCan { cc_hole = TypeHole }) = True
1333 isPartialTypeSigCt _ = False
1334
1335 instance Outputable Ct where
1336 ppr ct = ppr (cc_ev ct) <+> parens (text ct_sort)
1337 where ct_sort = case ct of
1338 CTyEqCan {} -> "CTyEqCan"
1339 CFunEqCan {} -> "CFunEqCan"
1340 CNonCanonical {} -> "CNonCanonical"
1341 CDictCan {} -> "CDictCan"
1342 CIrredEvCan {} -> "CIrredEvCan"
1343 CHoleCan {} -> "CHoleCan"
1344
1345 singleCt :: Ct -> Cts
1346 singleCt = unitBag
1347
1348 andCts :: Cts -> Cts -> Cts
1349 andCts = unionBags
1350
1351 listToCts :: [Ct] -> Cts
1352 listToCts = listToBag
1353
1354 ctsElts :: Cts -> [Ct]
1355 ctsElts = bagToList
1356
1357 consCts :: Ct -> Cts -> Cts
1358 consCts = consBag
1359
1360 snocCts :: Cts -> Ct -> Cts
1361 snocCts = snocBag
1362
1363 extendCtsList :: Cts -> [Ct] -> Cts
1364 extendCtsList cts xs | null xs = cts
1365 | otherwise = cts `unionBags` listToBag xs
1366
1367 andManyCts :: [Cts] -> Cts
1368 andManyCts = unionManyBags
1369
1370 emptyCts :: Cts
1371 emptyCts = emptyBag
1372
1373 isEmptyCts :: Cts -> Bool
1374 isEmptyCts = isEmptyBag
1375
1376 pprCts :: Cts -> SDoc
1377 pprCts cts = vcat (map ppr (bagToList cts))
1378
1379 {-
1380 ************************************************************************
1381 * *
1382 Wanted constraints
1383 These are forced to be in TcRnTypes because
1384 TcLclEnv mentions WantedConstraints
1385 WantedConstraint mentions CtLoc
1386 CtLoc mentions ErrCtxt
1387 ErrCtxt mentions TcM
1388 * *
1389 v%************************************************************************
1390 -}
1391
1392 data WantedConstraints
1393 = WC { wc_simple :: Cts -- Unsolved constraints, all wanted
1394 , wc_impl :: Bag Implication
1395 , wc_insol :: Cts -- Insoluble constraints, can be
1396 -- wanted, given, or derived
1397 -- See Note [Insoluble constraints]
1398 }
1399
1400 emptyWC :: WantedConstraints
1401 emptyWC = WC { wc_simple = emptyBag, wc_impl = emptyBag, wc_insol = emptyBag }
1402
1403 mkSimpleWC :: [Ct] -> WantedConstraints
1404 mkSimpleWC cts
1405 = WC { wc_simple = listToBag cts, wc_impl = emptyBag, wc_insol = emptyBag }
1406
1407 isEmptyWC :: WantedConstraints -> Bool
1408 isEmptyWC (WC { wc_simple = f, wc_impl = i, wc_insol = n })
1409 = isEmptyBag f && isEmptyBag i && isEmptyBag n
1410
1411 insolubleWC :: WantedConstraints -> Bool
1412 -- True if there are any insoluble constraints in the wanted bag. Ignore
1413 -- constraints arising from PartialTypeSignatures to solve as much of the
1414 -- constraints as possible before reporting the holes.
1415 insolubleWC wc = not (isEmptyBag (filterBag (not . isPartialTypeSigCt)
1416 (wc_insol wc)))
1417 || anyBag ic_insol (wc_impl wc)
1418
1419 andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
1420 andWC (WC { wc_simple = f1, wc_impl = i1, wc_insol = n1 })
1421 (WC { wc_simple = f2, wc_impl = i2, wc_insol = n2 })
1422 = WC { wc_simple = f1 `unionBags` f2
1423 , wc_impl = i1 `unionBags` i2
1424 , wc_insol = n1 `unionBags` n2 }
1425
1426 unionsWC :: [WantedConstraints] -> WantedConstraints
1427 unionsWC = foldr andWC emptyWC
1428
1429 addSimples :: WantedConstraints -> Bag Ct -> WantedConstraints
1430 addSimples wc cts
1431 = wc { wc_simple = wc_simple wc `unionBags` cts }
1432
1433 addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
1434 addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
1435
1436 addInsols :: WantedConstraints -> Bag Ct -> WantedConstraints
1437 addInsols wc cts
1438 = wc { wc_insol = wc_insol wc `unionBags` cts }
1439
1440 instance Outputable WantedConstraints where
1441 ppr (WC {wc_simple = s, wc_impl = i, wc_insol = n})
1442 = ptext (sLit "WC") <+> braces (vcat
1443 [ ppr_bag (ptext (sLit "wc_simple")) s
1444 , ppr_bag (ptext (sLit "wc_insol")) n
1445 , ppr_bag (ptext (sLit "wc_impl")) i ])
1446
1447 ppr_bag :: Outputable a => SDoc -> Bag a -> SDoc
1448 ppr_bag doc bag
1449 | isEmptyBag bag = empty
1450 | otherwise = hang (doc <+> equals)
1451 2 (foldrBag (($$) . ppr) empty bag)
1452
1453 {-
1454 ************************************************************************
1455 * *
1456 Implication constraints
1457 * *
1458 ************************************************************************
1459 -}
1460
1461 data Implication
1462 = Implic {
1463 ic_tclvl :: TcLevel, -- TcLevel: unification variables
1464 -- free in the environment
1465
1466 ic_skols :: [TcTyVar], -- Introduced skolems
1467 ic_info :: SkolemInfo, -- See Note [Skolems in an implication]
1468 -- See Note [Shadowing in a constraint]
1469
1470 ic_given :: [EvVar], -- Given evidence variables
1471 -- (order does not matter)
1472 -- See Invariant (GivenInv) in TcType
1473
1474 ic_no_eqs :: Bool, -- True <=> ic_givens have no equalities, for sure
1475 -- False <=> ic_givens might have equalities
1476
1477 ic_env :: TcLclEnv, -- Gives the source location and error context
1478 -- for the implicatdion, and hence for all the
1479 -- given evidence variables
1480
1481 ic_wanted :: WantedConstraints, -- The wanted
1482 ic_insol :: Bool, -- True iff insolubleWC ic_wanted is true
1483
1484 ic_binds :: EvBindsVar -- Points to the place to fill in the
1485 -- abstraction and bindings
1486 }
1487
1488 instance Outputable Implication where
1489 ppr (Implic { ic_tclvl = tclvl, ic_skols = skols
1490 , ic_given = given, ic_no_eqs = no_eqs
1491 , ic_wanted = wanted, ic_insol = insol
1492 , ic_binds = binds, ic_info = info })
1493 = hang (ptext (sLit "Implic") <+> lbrace)
1494 2 (sep [ ptext (sLit "TcLevel =") <+> ppr tclvl
1495 , ptext (sLit "Skolems =") <+> pprTvBndrs skols
1496 , ptext (sLit "No-eqs =") <+> ppr no_eqs
1497 , ptext (sLit "Insol =") <+> ppr insol
1498 , hang (ptext (sLit "Given =")) 2 (pprEvVars given)
1499 , hang (ptext (sLit "Wanted =")) 2 (ppr wanted)
1500 , ptext (sLit "Binds =") <+> ppr binds
1501 , pprSkolInfo info ] <+> rbrace)
1502
1503 {-
1504 Note [Shadowing in a constraint]
1505 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1506 We assume NO SHADOWING in a constraint. Specifically
1507 * The unification variables are all implicitly quantified at top
1508 level, and are all unique
1509 * The skolem varibles bound in ic_skols are all freah when the
1510 implication is created.
1511 So we can safely substitute. For example, if we have
1512 forall a. a~Int => ...(forall b. ...a...)...
1513 we can push the (a~Int) constraint inwards in the "givens" without
1514 worrying that 'b' might clash.
1515
1516 Note [Skolems in an implication]
1517 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1518 The skolems in an implication are not there to perform a skolem escape
1519 check. That happens because all the environment variables are in the
1520 untouchables, and therefore cannot be unified with anything at all,
1521 let alone the skolems.
1522
1523 Instead, ic_skols is used only when considering floating a constraint
1524 outside the implication in TcSimplify.floatEqualities or
1525 TcSimplify.approximateImplications
1526
1527 Note [Insoluble constraints]
1528 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1529 Some of the errors that we get during canonicalization are best
1530 reported when all constraints have been simplified as much as
1531 possible. For instance, assume that during simplification the
1532 following constraints arise:
1533
1534 [Wanted] F alpha ~ uf1
1535 [Wanted] beta ~ uf1 beta
1536
1537 When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
1538 we will simply see a message:
1539 'Can't construct the infinite type beta ~ uf1 beta'
1540 and the user has no idea what the uf1 variable is.
1541
1542 Instead our plan is that we will NOT fail immediately, but:
1543 (1) Record the "frozen" error in the ic_insols field
1544 (2) Isolate the offending constraint from the rest of the inerts
1545 (3) Keep on simplifying/canonicalizing
1546
1547 At the end, we will hopefully have substituted uf1 := F alpha, and we
1548 will be able to report a more informative error:
1549 'Can't construct the infinite type beta ~ F alpha beta'
1550
1551 Insoluble constraints *do* include Derived constraints. For example,
1552 a functional dependency might give rise to [D] Int ~ Bool, and we must
1553 report that. If insolubles did not contain Deriveds, reportErrors would
1554 never see it.
1555
1556
1557 ************************************************************************
1558 * *
1559 Pretty printing
1560 * *
1561 ************************************************************************
1562 -}
1563
1564 pprEvVars :: [EvVar] -> SDoc -- Print with their types
1565 pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
1566
1567 pprEvVarTheta :: [EvVar] -> SDoc
1568 pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
1569
1570 pprEvVarWithType :: EvVar -> SDoc
1571 pprEvVarWithType v = ppr v <+> dcolon <+> pprType (evVarPred v)
1572
1573 {-
1574 ************************************************************************
1575 * *
1576 CtEvidence
1577 * *
1578 ************************************************************************
1579
1580 Note [Evidence field of CtEvidence]
1581 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1582 During constraint solving we never look at the type of ctev_evtm, or
1583 ctev_evar; instead we look at the cte_pred field. The evtm/evar field
1584 may be un-zonked.
1585 -}
1586
1587 data CtEvidence
1588 = CtGiven { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
1589 , ctev_evtm :: EvTerm -- See Note [Evidence field of CtEvidence]
1590 , ctev_loc :: CtLoc }
1591 -- Truly given, not depending on subgoals
1592 -- NB: Spontaneous unifications belong here
1593
1594 | CtWanted { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
1595 , ctev_evar :: EvVar -- See Note [Evidence field of CtEvidence]
1596 , ctev_loc :: CtLoc }
1597 -- Wanted goal
1598
1599 | CtDerived { ctev_pred :: TcPredType
1600 , ctev_loc :: CtLoc }
1601 -- A goal that we don't really have to solve and can't immediately
1602 -- rewrite anything other than a derived (there's no evidence!)
1603 -- but if we do manage to solve it may help in solving other goals.
1604
1605 ctEvPred :: CtEvidence -> TcPredType
1606 -- The predicate of a flavor
1607 ctEvPred = ctev_pred
1608
1609 ctEvLoc :: CtEvidence -> CtLoc
1610 ctEvLoc = ctev_loc
1611
1612 -- | Get the equality relation relevant for a 'CtEvidence'
1613 ctEvEqRel :: CtEvidence -> EqRel
1614 ctEvEqRel = predTypeEqRel . ctEvPred
1615
1616 -- | Get the role relevant for a 'CtEvidence'
1617 ctEvRole :: CtEvidence -> Role
1618 ctEvRole = eqRelRole . ctEvEqRel
1619
1620 ctEvTerm :: CtEvidence -> EvTerm
1621 ctEvTerm (CtGiven { ctev_evtm = tm }) = tm
1622 ctEvTerm (CtWanted { ctev_evar = ev }) = EvId ev
1623 ctEvTerm ctev@(CtDerived {}) = pprPanic "ctEvTerm: derived constraint cannot have id"
1624 (ppr ctev)
1625
1626 ctEvCoercion :: CtEvidence -> TcCoercion
1627 -- ctEvCoercion ev = evTermCoercion (ctEvTerm ev)
1628 ctEvCoercion (CtGiven { ctev_evtm = tm }) = evTermCoercion tm
1629 ctEvCoercion (CtWanted { ctev_evar = v }) = mkTcCoVarCo v
1630 ctEvCoercion ctev@(CtDerived {}) = pprPanic "ctEvCoercion: derived constraint cannot have id"
1631 (ppr ctev)
1632
1633 ctEvId :: CtEvidence -> TcId
1634 ctEvId (CtWanted { ctev_evar = ev }) = ev
1635 ctEvId ctev = pprPanic "ctEvId:" (ppr ctev)
1636
1637 instance Outputable CtEvidence where
1638 ppr fl = case fl of
1639 CtGiven {} -> ptext (sLit "[G]") <+> ppr (ctev_evtm fl) <+> ppr_pty
1640 CtWanted {} -> ptext (sLit "[W]") <+> ppr (ctev_evar fl) <+> ppr_pty
1641 CtDerived {} -> ptext (sLit "[D]") <+> text "_" <+> ppr_pty
1642 where ppr_pty = dcolon <+> ppr (ctEvPred fl)
1643
1644 isWanted :: CtEvidence -> Bool
1645 isWanted (CtWanted {}) = True
1646 isWanted _ = False
1647
1648 isGiven :: CtEvidence -> Bool
1649 isGiven (CtGiven {}) = True
1650 isGiven _ = False
1651
1652 isDerived :: CtEvidence -> Bool
1653 isDerived (CtDerived {}) = True
1654 isDerived _ = False
1655
1656 {-
1657 %************************************************************************
1658 %* *
1659 CtFlavour
1660 %* *
1661 %************************************************************************
1662
1663 Just an enum type that tracks whether a constraint is wanted, derived,
1664 or given, when we need to separate that info from the constraint itself.
1665
1666 -}
1667
1668 data CtFlavour = Given | Wanted | Derived
1669 deriving Eq
1670
1671 instance Outputable CtFlavour where
1672 ppr Given = text "[G]"
1673 ppr Wanted = text "[W]"
1674 ppr Derived = text "[D]"
1675
1676 ctEvFlavour :: CtEvidence -> CtFlavour
1677 ctEvFlavour (CtWanted {}) = Wanted
1678 ctEvFlavour (CtGiven {}) = Given
1679 ctEvFlavour (CtDerived {}) = Derived
1680
1681 {-
1682 ************************************************************************
1683 * *
1684 SubGoalDepth
1685 * *
1686 ************************************************************************
1687
1688 Note [SubGoalDepth]
1689 ~~~~~~~~~~~~~~~~~~~
1690 The 'SubGoalCounter' takes care of stopping the constraint solver from looping.
1691 Because of the different use-cases of regular constaints and type function
1692 applications, there are two independent counters. Therefore, this datatype is
1693 abstract. See Note [WorkList]
1694
1695 Each counter starts at zero and increases.
1696
1697 * The "dictionary constraint counter" counts the depth of type class
1698 instance declarations. Example:
1699 [W] d{7} : Eq [Int]
1700 That is d's dictionary-constraint depth is 7. If we use the instance
1701 $dfEqList :: Eq a => Eq [a]
1702 to simplify it, we get
1703 d{7} = $dfEqList d'{8}
1704 where d'{8} : Eq Int, and d' has dictionary-constraint depth 8.
1705
1706 For civilised (decidable) instance declarations, each increase of
1707 depth removes a type constructor from the type, so the depth never
1708 gets big; i.e. is bounded by the structural depth of the type.
1709
1710 The flag -fcontext-stack=n (not very well named!) fixes the maximium
1711 level.
1712
1713 * The "type function reduction counter" does the same thing when resolving
1714 * qualities involving type functions. Example:
1715 Assume we have a wanted at depth 7:
1716 [W] d{7} : F () ~ a
1717 If thre is an type function equation "F () = Int", this would be rewritten to
1718 [W] d{8} : Int ~ a
1719 and remembered as having depth 8.
1720
1721 Again, without UndecidableInstances, this counter is bounded, but without it
1722 can resolve things ad infinitum. Hence there is a maximum level. But we use a
1723 different maximum, as we expect possibly many more type function reductions
1724 in sensible programs than type class constraints.
1725
1726 The flag -ftype-function-depth=n fixes the maximium level.
1727 -}
1728
1729 data SubGoalCounter = CountConstraints | CountTyFunApps
1730
1731 data SubGoalDepth -- See Note [SubGoalDepth]
1732 = SubGoalDepth
1733 {-# UNPACK #-} !Int -- Dictionary constraints
1734 {-# UNPACK #-} !Int -- Type function reductions
1735 deriving (Eq, Ord)
1736
1737 instance Outputable SubGoalDepth where
1738 ppr (SubGoalDepth c f) = angleBrackets $
1739 char 'C' <> colon <> int c <> comma <>
1740 char 'F' <> colon <> int f
1741
1742 initialSubGoalDepth :: SubGoalDepth
1743 initialSubGoalDepth = SubGoalDepth 0 0
1744
1745 maxSubGoalDepth :: DynFlags -> SubGoalDepth
1746 maxSubGoalDepth dflags = SubGoalDepth (ctxtStkDepth dflags) (tyFunStkDepth dflags)
1747
1748 bumpSubGoalDepth :: SubGoalCounter -> SubGoalDepth -> SubGoalDepth
1749 bumpSubGoalDepth CountConstraints (SubGoalDepth c f) = SubGoalDepth (c+1) f
1750 bumpSubGoalDepth CountTyFunApps (SubGoalDepth c f) = SubGoalDepth c (f+1)
1751
1752 subGoalCounterValue :: SubGoalCounter -> SubGoalDepth -> Int
1753 subGoalCounterValue CountConstraints (SubGoalDepth c _) = c
1754 subGoalCounterValue CountTyFunApps (SubGoalDepth _ f) = f
1755
1756 subGoalDepthExceeded :: SubGoalDepth -> SubGoalDepth -> Maybe SubGoalCounter
1757 subGoalDepthExceeded (SubGoalDepth mc mf) (SubGoalDepth c f)
1758 | c > mc = Just CountConstraints
1759 | f > mf = Just CountTyFunApps
1760 | otherwise = Nothing
1761
1762 -- | Checks whether the evidence can be used to solve a goal with the given minimum depth
1763 -- See Note [Preventing recursive dictionaries]
1764 ctEvCheckDepth :: Class -> CtLoc -> CtEvidence -> Bool
1765 ctEvCheckDepth cls target ev
1766 | isWanted ev
1767 , cls == coercibleClass -- The restriction applies only to Coercible
1768 = ctLocDepth target <= ctLocDepth (ctEvLoc ev)
1769 | otherwise = True
1770
1771 {-
1772 Note [Preventing recursive dictionaries]
1773 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1774 NB: this will go away when we start treating Coercible as an equality.
1775
1776 We have some classes where it is not very useful to build recursive
1777 dictionaries (Coercible, at the moment). So we need the constraint solver to
1778 prevent that. We conservatively ensure this property using the subgoal depth of
1779 the constraints: When solving a Coercible constraint at depth d, we do not
1780 consider evidence from a depth <= d as suitable.
1781
1782 Therefore we need to record the minimum depth allowed to solve a CtWanted. This
1783 is done in the SubGoalDepth field of CtWanted. Most code now uses mkCtWanted,
1784 which initializes it to initialSubGoalDepth (i.e. 0); but when requesting a
1785 Coercible instance (requestCoercible in TcInteract), we bump the current depth
1786 by one and use that.
1787
1788 There are two spots where wanted contraints attempted to be solved
1789 using existing constraints: lookupInertDict and lookupSolvedDict in
1790 TcSMonad. Both use ctEvCheckDepth to make the check. That function
1791 ensures that a Given constraint can always be used to solve a goal
1792 (i.e. they are at depth infinity, for our purposes)
1793
1794
1795 ************************************************************************
1796 * *
1797 CtLoc
1798 * *
1799 ************************************************************************
1800
1801 The 'CtLoc' gives information about where a constraint came from.
1802 This is important for decent error message reporting because
1803 dictionaries don't appear in the original source code.
1804 type will evolve...
1805 -}
1806
1807 data CtLoc = CtLoc { ctl_origin :: CtOrigin
1808 , ctl_env :: TcLclEnv
1809 , ctl_depth :: !SubGoalDepth }
1810 -- The TcLclEnv includes particularly
1811 -- source location: tcl_loc :: SrcSpan
1812 -- context: tcl_ctxt :: [ErrCtxt]
1813 -- binder stack: tcl_bndrs :: [TcIdBinders]
1814 -- level: tcl_tclvl :: TcLevel
1815
1816 mkGivenLoc :: TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
1817 mkGivenLoc tclvl skol_info env
1818 = CtLoc { ctl_origin = GivenOrigin skol_info
1819 , ctl_env = env { tcl_tclvl = tclvl }
1820 , ctl_depth = initialSubGoalDepth }
1821
1822 ctLocEnv :: CtLoc -> TcLclEnv
1823 ctLocEnv = ctl_env
1824
1825 ctLocDepth :: CtLoc -> SubGoalDepth
1826 ctLocDepth = ctl_depth
1827
1828 ctLocOrigin :: CtLoc -> CtOrigin
1829 ctLocOrigin = ctl_origin
1830
1831 ctLocSpan :: CtLoc -> SrcSpan
1832 ctLocSpan (CtLoc { ctl_env = lcl}) = tcl_loc lcl
1833
1834 setCtLocSpan :: CtLoc -> SrcSpan -> CtLoc
1835 setCtLocSpan ctl@(CtLoc { ctl_env = lcl }) loc = setCtLocEnv ctl (lcl { tcl_loc = loc })
1836
1837 bumpCtLocDepth :: SubGoalCounter -> CtLoc -> CtLoc
1838 bumpCtLocDepth cnt loc@(CtLoc { ctl_depth = d }) = loc { ctl_depth = bumpSubGoalDepth cnt d }
1839
1840 setCtLocOrigin :: CtLoc -> CtOrigin -> CtLoc
1841 setCtLocOrigin ctl orig = ctl { ctl_origin = orig }
1842
1843 setCtLocEnv :: CtLoc -> TcLclEnv -> CtLoc
1844 setCtLocEnv ctl env = ctl { ctl_env = env }
1845
1846 pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc
1847 pushErrCtxt o err loc@(CtLoc { ctl_env = lcl })
1848 = loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
1849
1850 pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc
1851 -- Just add information w/o updating the origin!
1852 pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl })
1853 = loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
1854
1855 pprArising :: CtOrigin -> SDoc
1856 -- Used for the main, top-level error message
1857 -- We've done special processing for TypeEq and FunDep origins
1858 pprArising (TypeEqOrigin {}) = empty
1859 pprArising orig = pprCtOrigin orig
1860
1861 pprArisingAt :: CtLoc -> SDoc
1862 pprArisingAt (CtLoc { ctl_origin = o, ctl_env = lcl})
1863 = sep [ pprCtOrigin o
1864 , text "at" <+> ppr (tcl_loc lcl)]
1865
1866 {-
1867 ************************************************************************
1868 * *
1869 SkolemInfo
1870 * *
1871 ************************************************************************
1872 -}
1873
1874 -- SkolemInfo gives the origin of *given* constraints
1875 -- a) type variables are skolemised
1876 -- b) an implication constraint is generated
1877 data SkolemInfo
1878 = SigSkol UserTypeCtxt -- A skolem that is created by instantiating
1879 Type -- a programmer-supplied type signature
1880 -- Location of the binding site is on the TyVar
1881
1882 -- The rest are for non-scoped skolems
1883 | ClsSkol Class -- Bound at a class decl
1884 | InstSkol -- Bound at an instance decl
1885 | DataSkol -- Bound at a data type declaration
1886 | FamInstSkol -- Bound at a family instance decl
1887 | PatSkol -- An existential type variable bound by a pattern for
1888 ConLike -- a data constructor with an existential type.
1889 (HsMatchContext Name)
1890 -- e.g. data T = forall a. Eq a => MkT a
1891 -- f (MkT x) = ...
1892 -- The pattern MkT x will allocate an existential type
1893 -- variable for 'a'.
1894
1895 | ArrowSkol -- An arrow form (see TcArrows)
1896
1897 | IPSkol [HsIPName] -- Binding site of an implicit parameter
1898
1899 | RuleSkol RuleName -- The LHS of a RULE
1900
1901 | InferSkol [(Name,TcType)]
1902 -- We have inferred a type for these (mutually-recursivive)
1903 -- polymorphic Ids, and are now checking that their RHS
1904 -- constraints are satisfied.
1905
1906 | BracketSkol -- Template Haskell bracket
1907
1908 | UnifyForAllSkol -- We are unifying two for-all types
1909 [TcTyVar] -- The instantiated skolem variables
1910 TcType -- The instantiated type *inside* the forall
1911
1912 | UnkSkol -- Unhelpful info (until I improve it)
1913
1914 instance Outputable SkolemInfo where
1915 ppr = pprSkolInfo
1916
1917 pprSkolInfo :: SkolemInfo -> SDoc
1918 -- Complete the sentence "is a rigid type variable bound by..."
1919 pprSkolInfo (SigSkol (FunSigCtxt f) ty)
1920 = hang (ptext (sLit "the type signature for"))
1921 2 (pprPrefixOcc f <+> dcolon <+> ppr ty)
1922 pprSkolInfo (SigSkol cx ty) = hang (pprUserTypeCtxt cx <> colon)
1923 2 (ppr ty)
1924 pprSkolInfo (IPSkol ips) = ptext (sLit "the implicit-parameter binding") <> plural ips <+> ptext (sLit "for")
1925 <+> pprWithCommas ppr ips
1926 pprSkolInfo (ClsSkol cls) = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
1927 pprSkolInfo InstSkol = ptext (sLit "the instance declaration")
1928 pprSkolInfo DataSkol = ptext (sLit "the data type declaration")
1929 pprSkolInfo FamInstSkol = ptext (sLit "the family instance declaration")
1930 pprSkolInfo BracketSkol = ptext (sLit "a Template Haskell bracket")
1931 pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
1932 pprSkolInfo ArrowSkol = ptext (sLit "the arrow form")
1933 pprSkolInfo (PatSkol cl mc) = case cl of
1934 RealDataCon dc -> sep [ ptext (sLit "a pattern with constructor")
1935 , nest 2 $ ppr dc <+> dcolon
1936 <+> pprType (dataConUserType dc) <> comma
1937 -- pprType prints forall's regardless of -fprint-explict-foralls
1938 -- which is what we want here, since we might be saying
1939 -- type variable 't' is bound by ...
1940 , ptext (sLit "in") <+> pprMatchContext mc ]
1941 PatSynCon ps -> sep [ ptext (sLit "a pattern with pattern synonym")
1942 , nest 2 $ ppr ps <+> dcolon
1943 <+> pprType (patSynType ps) <> comma
1944 , ptext (sLit "in") <+> pprMatchContext mc ]
1945 pprSkolInfo (InferSkol ids) = sep [ ptext (sLit "the inferred type of")
1946 , vcat [ ppr name <+> dcolon <+> ppr ty
1947 | (name,ty) <- ids ]]
1948 pprSkolInfo (UnifyForAllSkol tvs ty) = ptext (sLit "the type") <+> ppr (mkForAllTys tvs ty)
1949
1950 -- UnkSkol
1951 -- For type variables the others are dealt with by pprSkolTvBinding.
1952 -- For Insts, these cases should not happen
1953 pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
1954
1955 {-
1956 ************************************************************************
1957 * *
1958 CtOrigin
1959 * *
1960 ************************************************************************
1961 -}
1962
1963 data CtOrigin
1964 = GivenOrigin SkolemInfo
1965
1966 -- All the others are for *wanted* constraints
1967 | OccurrenceOf Name -- Occurrence of an overloaded identifier
1968 | AppOrigin -- An application of some kind
1969
1970 | SpecPragOrigin Name -- Specialisation pragma for identifier
1971
1972 | TypeEqOrigin { uo_actual :: TcType
1973 , uo_expected :: TcType }
1974 | KindEqOrigin
1975 TcType TcType -- A kind equality arising from unifying these two types
1976 CtOrigin -- originally arising from this
1977 | CoercibleOrigin TcType TcType -- a Coercible constraint
1978
1979 | IPOccOrigin HsIPName -- Occurrence of an implicit parameter
1980
1981 | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
1982 | NegateOrigin -- Occurrence of syntactic negation
1983
1984 | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
1985 | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
1986 | SectionOrigin
1987 | TupleOrigin -- (..,..)
1988 | ExprSigOrigin -- e :: ty
1989 | PatSigOrigin -- p :: ty
1990 | PatOrigin -- Instantiating a polytyped pattern at a constructor
1991 | RecordUpdOrigin
1992 | ViewPatOrigin
1993
1994 | ScOrigin -- Typechecking superclasses of an instance declaration
1995 | DerivOrigin -- Typechecking deriving
1996 | DerivOriginDC DataCon Int
1997 -- Checking constraints arising from this data con and field index
1998 | DerivOriginCoerce Id Type Type
1999 -- DerivOriginCoerce id ty1 ty2: Trying to coerce class method `id` from
2000 -- `ty1` to `ty2`.
2001 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
2002 | DefaultOrigin -- Typechecking a default decl
2003 | DoOrigin -- Arising from a do expression
2004 | MCompOrigin -- Arising from a monad comprehension
2005 | IfOrigin -- Arising from an if statement
2006 | ProcOrigin -- Arising from a proc expression
2007 | AnnOrigin -- An annotation
2008
2009 | FunDepOrigin1 -- A functional dependency from combining
2010 PredType CtLoc -- This constraint arising from ...
2011 PredType CtLoc -- and this constraint arising from ...
2012
2013 | FunDepOrigin2 -- A functional dependency from combining
2014 PredType CtOrigin -- This constraint arising from ...
2015 PredType SrcSpan -- and this instance
2016 -- We only need a CtOrigin on the first, because the location
2017 -- is pinned on the entire error message
2018
2019 | HoleOrigin
2020 | UnboundOccurrenceOf RdrName
2021 | ListOrigin -- An overloaded list
2022 | StaticOrigin -- A static form
2023
2024 ctoHerald :: SDoc
2025 ctoHerald = ptext (sLit "arising from")
2026
2027 pprCtOrigin :: CtOrigin -> SDoc
2028
2029 pprCtOrigin (GivenOrigin sk) = ctoHerald <+> ppr sk
2030
2031 pprCtOrigin (FunDepOrigin1 pred1 loc1 pred2 loc2)
2032 = hang (ctoHerald <+> ptext (sLit "a functional dependency between constraints:"))
2033 2 (vcat [ hang (quotes (ppr pred1)) 2 (pprArisingAt loc1)
2034 , hang (quotes (ppr pred2)) 2 (pprArisingAt loc2) ])
2035
2036 pprCtOrigin (FunDepOrigin2 pred1 orig1 pred2 loc2)
2037 = hang (ctoHerald <+> ptext (sLit "a functional dependency between:"))
2038 2 (vcat [ hang (ptext (sLit "constraint") <+> quotes (ppr pred1))
2039 2 (pprArising orig1 )
2040 , hang (ptext (sLit "instance") <+> quotes (ppr pred2))
2041 2 (ptext (sLit "at") <+> ppr loc2) ])
2042
2043 pprCtOrigin (KindEqOrigin t1 t2 _)
2044 = hang (ctoHerald <+> ptext (sLit "a kind equality arising from"))
2045 2 (sep [ppr t1, char '~', ppr t2])
2046
2047 pprCtOrigin (UnboundOccurrenceOf name)
2048 = ctoHerald <+> ptext (sLit "an undeclared identifier") <+> quotes (ppr name)
2049
2050 pprCtOrigin (DerivOriginDC dc n)
2051 = hang (ctoHerald <+> ptext (sLit "the") <+> speakNth n
2052 <+> ptext (sLit "field of") <+> quotes (ppr dc))
2053 2 (parens (ptext (sLit "type") <+> quotes (ppr ty)))
2054 where
2055 ty = dataConOrigArgTys dc !! (n-1)
2056
2057 pprCtOrigin (DerivOriginCoerce meth ty1 ty2)
2058 = hang (ctoHerald <+> ptext (sLit "the coercion of the method") <+> quotes (ppr meth))
2059 2 (sep [ text "from type" <+> quotes (ppr ty1)
2060 , nest 2 $ text "to type" <+> quotes (ppr ty2) ])
2061
2062 pprCtOrigin (CoercibleOrigin ty1 ty2)
2063 = hang (ctoHerald <+> text "trying to show that the representations of")
2064 2 (quotes (ppr ty1) <+> text "and" $$
2065 quotes (ppr ty2) <+> text "are the same")
2066
2067 pprCtOrigin simple_origin
2068 = ctoHerald <+> pprCtO simple_origin
2069
2070 ----------------
2071 pprCtO :: CtOrigin -> SDoc -- Ones that are short one-liners
2072 pprCtO (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
2073 pprCtO AppOrigin = ptext (sLit "an application")
2074 pprCtO (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
2075 pprCtO (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
2076 pprCtO RecordUpdOrigin = ptext (sLit "a record update")
2077 pprCtO ExprSigOrigin = ptext (sLit "an expression type signature")
2078 pprCtO PatSigOrigin = ptext (sLit "a pattern type signature")
2079 pprCtO PatOrigin = ptext (sLit "a pattern")
2080 pprCtO ViewPatOrigin = ptext (sLit "a view pattern")
2081 pprCtO IfOrigin = ptext (sLit "an if statement")
2082 pprCtO (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
2083 pprCtO (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
2084 pprCtO (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
2085 pprCtO SectionOrigin = ptext (sLit "an operator section")
2086 pprCtO TupleOrigin = ptext (sLit "a tuple")
2087 pprCtO NegateOrigin = ptext (sLit "a use of syntactic negation")
2088 pprCtO ScOrigin = ptext (sLit "the superclasses of an instance declaration")
2089 pprCtO DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
2090 pprCtO StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
2091 pprCtO DefaultOrigin = ptext (sLit "a 'default' declaration")
2092 pprCtO DoOrigin = ptext (sLit "a do statement")
2093 pprCtO MCompOrigin = ptext (sLit "a statement in a monad comprehension")
2094 pprCtO ProcOrigin = ptext (sLit "a proc expression")
2095 pprCtO (TypeEqOrigin t1 t2) = ptext (sLit "a type equality") <+> sep [ppr t1, char '~', ppr t2]
2096 pprCtO AnnOrigin = ptext (sLit "an annotation")
2097 pprCtO HoleOrigin = ptext (sLit "a use of") <+> quotes (ptext $ sLit "_")
2098 pprCtO ListOrigin = ptext (sLit "an overloaded list")
2099 pprCtO StaticOrigin = ptext (sLit "a static form")
2100 pprCtO _ = panic "pprCtOrigin"
2101
2102 {-
2103 Constraint Solver Plugins
2104 -------------------------
2105 -}
2106
2107 type TcPluginSolver = [Ct] -- given
2108 -> [Ct] -- derived
2109 -> [Ct] -- wanted
2110 -> TcPluginM TcPluginResult
2111
2112 newtype TcPluginM a = TcPluginM (TcM a)
2113
2114 instance Functor TcPluginM where
2115 fmap = liftM
2116
2117 instance Applicative TcPluginM where
2118 pure = return
2119 (<*>) = ap
2120
2121 instance Monad TcPluginM where
2122 return x = TcPluginM (return x)
2123 fail x = TcPluginM (fail x)
2124 TcPluginM m >>= k =
2125 TcPluginM (do a <- m
2126 let TcPluginM m1 = k a
2127 m1)
2128
2129 runTcPluginM :: TcPluginM a -> TcM a
2130 runTcPluginM (TcPluginM m) = m
2131
2132 -- | This function provides an escape for direct access to
2133 -- the 'TcM` monad. It should not be used lightly, and
2134 -- the provided 'TcPluginM' API should be favoured instead.
2135 unsafeTcPluginTcM :: TcM a -> TcPluginM a
2136 unsafeTcPluginTcM = TcPluginM
2137
2138 data TcPlugin = forall s. TcPlugin
2139 { tcPluginInit :: TcPluginM s
2140 -- ^ Initialize plugin, when entering type-checker.
2141
2142 , tcPluginSolve :: s -> TcPluginSolver
2143 -- ^ Solve some constraints.
2144 -- TODO: WRITE MORE DETAILS ON HOW THIS WORKS.
2145
2146 , tcPluginStop :: s -> TcPluginM ()
2147 -- ^ Clean up after the plugin, when exiting the type-checker.
2148 }
2149
2150 data TcPluginResult
2151 = TcPluginContradiction [Ct]
2152 -- ^ The plugin found a contradiction.
2153 -- The returned constraints are removed from the inert set,
2154 -- and recorded as insoluable.
2155
2156 | TcPluginOk [(EvTerm,Ct)] [Ct]
2157 -- ^ The first field is for constraints that were solved.
2158 -- These are removed from the inert set,
2159 -- and the evidence for them is recorded.
2160 -- The second field contains new work, that should be processed by
2161 -- the constraint solver.