Break up TcRnTypes, among other modules.
[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... etc.
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 a TcRef (= IORef) to store them.
17 -}
18
19 {-# LANGUAGE CPP, DeriveFunctor, ExistentialQuantification, GeneralizedNewtypeDeriving,
20 ViewPatterns #-}
21
22 module TcRnTypes(
23 TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
24 TcRef,
25
26 -- The environment types
27 Env(..),
28 TcGblEnv(..), TcLclEnv(..),
29 setLclEnvTcLevel, getLclEnvTcLevel,
30 setLclEnvLoc, getLclEnvLoc,
31 IfGblEnv(..), IfLclEnv(..),
32 tcVisibleOrphanMods,
33
34 -- Frontend types (shouldn't really be here)
35 FrontendResult(..),
36
37 -- Renamer types
38 ErrCtxt, RecFieldEnv, pushErrCtxt, pushErrCtxtSameOrigin,
39 ImportAvails(..), emptyImportAvails, plusImportAvails,
40 WhereFrom(..), mkModDeps, modDepsElts,
41
42 -- Typechecker types
43 TcTypeEnv, TcBinderStack, TcBinder(..),
44 TcTyThing(..), PromotionErr(..),
45 IdBindingInfo(..), ClosedTypeId, RhsNames,
46 IsGroupClosed(..),
47 SelfBootInfo(..),
48 pprTcTyThingCategory, pprPECategory, CompleteMatch(..),
49
50 -- Desugaring types
51 DsM, DsLclEnv(..), DsGblEnv(..),
52 DsMetaEnv, DsMetaVal(..), CompleteMatchMap,
53 mkCompleteMatchMap, extendCompleteMatchMap,
54
55 -- Template Haskell
56 ThStage(..), SpliceType(..), PendingStuff(..),
57 topStage, topAnnStage, topSpliceStage,
58 ThLevel, impLevel, outerLevel, thLevel,
59 ForeignSrcLang(..),
60
61 -- Arrows
62 ArrowCtxt(..),
63
64 -- TcSigInfo
65 TcSigFun, TcSigInfo(..), TcIdSigInfo(..),
66 TcIdSigInst(..), TcPatSynInfo(..),
67 isPartialSig, hasCompleteSig,
68
69 -- Misc other types
70 TcId, TcIdSet,
71 NameShape(..),
72 removeBindingShadowing,
73
74 -- Constraint solver plugins
75 TcPlugin(..), TcPluginResult(..), TcPluginSolver,
76 TcPluginM, runTcPluginM, unsafeTcPluginTcM,
77 getEvBindsTcPluginM,
78
79 -- Role annotations
80 RoleAnnotEnv, emptyRoleAnnotEnv, mkRoleAnnotEnv,
81 lookupRoleAnnot, getRoleAnnots
82 ) where
83
84 #include "HsVersions.h"
85
86 import GhcPrelude
87
88 import GHC.Hs
89 import HscTypes
90 import TcEvidence
91 import Type
92 import TyCon ( TyCon, tyConKind )
93 import PatSyn ( PatSyn )
94 import Id ( idType, idName )
95 import FieldLabel ( FieldLabel )
96 import TcType
97 import Constraint
98 import TcOrigin
99 import Annotations
100 import InstEnv
101 import FamInstEnv
102 import {-# SOURCE #-} GHC.HsToCore.PmCheck.Types (Delta)
103 import IOEnv
104 import RdrName
105 import Name
106 import NameEnv
107 import NameSet
108 import Avail
109 import Var
110 import VarEnv
111 import Module
112 import SrcLoc
113 import VarSet
114 import ErrUtils
115 import UniqFM
116 import UniqSupply
117 import BasicTypes
118 import Bag
119 import DynFlags
120 import Outputable
121 import ListSetOps
122 import Fingerprint
123 import Util
124 import PrelNames ( isUnboundName )
125 import CostCentreState
126
127 import Control.Monad (ap)
128 import qualified Control.Monad.Fail as MonadFail
129 import Data.Set ( Set )
130 import qualified Data.Set as S
131
132 import Data.List ( sort )
133 import Data.Map ( Map )
134 import Data.Dynamic ( Dynamic )
135 import Data.Typeable ( TypeRep )
136 import Data.Maybe ( mapMaybe )
137 import GHCi.Message
138 import GHCi.RemoteTypes
139
140 import {-# SOURCE #-} TcHoleFitTypes ( HoleFitPlugin )
141
142 import qualified Language.Haskell.TH as TH
143
144 -- | A 'NameShape' is a substitution on 'Name's that can be used
145 -- to refine the identities of a hole while we are renaming interfaces
146 -- (see 'RnModIface'). Specifically, a 'NameShape' for
147 -- 'ns_module_name' @A@, defines a mapping from @{A.T}@
148 -- (for some 'OccName' @T@) to some arbitrary other 'Name'.
149 --
150 -- The most intruiging thing about a 'NameShape', however, is
151 -- how it's constructed. A 'NameShape' is *implied* by the
152 -- exported 'AvailInfo's of the implementor of an interface:
153 -- if an implementor of signature @<H>@ exports @M.T@, you implicitly
154 -- define a substitution from @{H.T}@ to @M.T@. So a 'NameShape'
155 -- is computed from the list of 'AvailInfo's that are exported
156 -- by the implementation of a module, or successively merged
157 -- together by the export lists of signatures which are joining
158 -- together.
159 --
160 -- It's not the most obvious way to go about doing this, but it
161 -- does seem to work!
162 --
163 -- NB: Can't boot this and put it in NameShape because then we
164 -- start pulling in too many DynFlags things.
165 data NameShape = NameShape {
166 ns_mod_name :: ModuleName,
167 ns_exports :: [AvailInfo],
168 ns_map :: OccEnv Name
169 }
170
171
172 {-
173 ************************************************************************
174 * *
175 Standard monad definition for TcRn
176 All the combinators for the monad can be found in TcRnMonad
177 * *
178 ************************************************************************
179
180 The monad itself has to be defined here, because it is mentioned by ErrCtxt
181 -}
182
183 type TcRnIf a b = IOEnv (Env a b)
184 type TcRn = TcRnIf TcGblEnv TcLclEnv -- Type inference
185 type IfM lcl = TcRnIf IfGblEnv lcl -- Iface stuff
186 type IfG = IfM () -- Top level
187 type IfL = IfM IfLclEnv -- Nested
188 type DsM = TcRnIf DsGblEnv DsLclEnv -- Desugaring
189
190 -- TcRn is the type-checking and renaming monad: the main monad that
191 -- most type-checking takes place in. The global environment is
192 -- 'TcGblEnv', which tracks all of the top-level type-checking
193 -- information we've accumulated while checking a module, while the
194 -- local environment is 'TcLclEnv', which tracks local information as
195 -- we move inside expressions.
196
197 -- | Historical "renaming monad" (now it's just 'TcRn').
198 type RnM = TcRn
199
200 -- | Historical "type-checking monad" (now it's just 'TcRn').
201 type TcM = TcRn
202
203 -- We 'stack' these envs through the Reader like monad infrastructure
204 -- as we move into an expression (although the change is focused in
205 -- the lcl type).
206 data Env gbl lcl
207 = Env {
208 env_top :: !HscEnv, -- Top-level stuff that never changes
209 -- Includes all info about imported things
210 -- BangPattern is to fix leak, see #15111
211
212 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
213 -- Unique supply for local variables
214
215 env_gbl :: gbl, -- Info about things defined at the top level
216 -- of the module being compiled
217
218 env_lcl :: lcl -- Nested stuff; changes as we go into
219 }
220
221 instance ContainsDynFlags (Env gbl lcl) where
222 extractDynFlags env = hsc_dflags (env_top env)
223
224 instance ContainsModule gbl => ContainsModule (Env gbl lcl) where
225 extractModule env = extractModule (env_gbl env)
226
227
228 {-
229 ************************************************************************
230 * *
231 The interface environments
232 Used when dealing with IfaceDecls
233 * *
234 ************************************************************************
235 -}
236
237 data IfGblEnv
238 = IfGblEnv {
239 -- Some information about where this environment came from;
240 -- useful for debugging.
241 if_doc :: SDoc,
242 -- The type environment for the module being compiled,
243 -- in case the interface refers back to it via a reference that
244 -- was originally a hi-boot file.
245 -- We need the module name so we can test when it's appropriate
246 -- to look in this env.
247 -- See Note [Tying the knot] in TcIface
248 if_rec_types :: Maybe (Module, IfG TypeEnv)
249 -- Allows a read effect, so it can be in a mutable
250 -- variable; c.f. handling the external package type env
251 -- Nothing => interactive stuff, no loops possible
252 }
253
254 data IfLclEnv
255 = IfLclEnv {
256 -- The module for the current IfaceDecl
257 -- So if we see f = \x -> x
258 -- it means M.f = \x -> x, where M is the if_mod
259 -- NB: This is a semantic module, see
260 -- Note [Identity versus semantic module]
261 if_mod :: Module,
262
263 -- Whether or not the IfaceDecl came from a boot
264 -- file or not; we'll use this to choose between
265 -- NoUnfolding and BootUnfolding
266 if_boot :: Bool,
267
268 -- The field is used only for error reporting
269 -- if (say) there's a Lint error in it
270 if_loc :: SDoc,
271 -- Where the interface came from:
272 -- .hi file, or GHCi state, or ext core
273 -- plus which bit is currently being examined
274
275 if_nsubst :: Maybe NameShape,
276
277 -- This field is used to make sure "implicit" declarations
278 -- (anything that cannot be exported in mi_exports) get
279 -- wired up correctly in typecheckIfacesForMerging. Most
280 -- of the time it's @Nothing@. See Note [Resolving never-exported Names in TcIface]
281 -- in TcIface.
282 if_implicits_env :: Maybe TypeEnv,
283
284 if_tv_env :: FastStringEnv TyVar, -- Nested tyvar bindings
285 if_id_env :: FastStringEnv Id -- Nested id binding
286 }
287
288 {-
289 ************************************************************************
290 * *
291 Desugarer monad
292 * *
293 ************************************************************************
294
295 Now the mondo monad magic (yes, @DsM@ is a silly name)---carry around
296 a @UniqueSupply@ and some annotations, which
297 presumably include source-file location information:
298 -}
299
300 data DsGblEnv
301 = DsGblEnv
302 { ds_mod :: Module -- For SCC profiling
303 , ds_fam_inst_env :: FamInstEnv -- Like tcg_fam_inst_env
304 , ds_unqual :: PrintUnqualified
305 , ds_msgs :: IORef Messages -- Warning messages
306 , ds_if_env :: (IfGblEnv, IfLclEnv) -- Used for looking up global,
307 -- possibly-imported things
308 , ds_complete_matches :: CompleteMatchMap
309 -- Additional complete pattern matches
310 , ds_cc_st :: IORef CostCentreState
311 -- Tracking indices for cost centre annotations
312 }
313
314 instance ContainsModule DsGblEnv where
315 extractModule = ds_mod
316
317 data DsLclEnv = DsLclEnv {
318 dsl_meta :: DsMetaEnv, -- Template Haskell bindings
319 dsl_loc :: RealSrcSpan, -- To put in pattern-matching error msgs
320
321 -- See Note [Note [Type and Term Equality Propagation] in Check.hs
322 -- The oracle state Delta is augmented as we walk inwards,
323 -- through each pattern match in turn
324 dsl_delta :: Delta
325 }
326
327 -- Inside [| |] brackets, the desugarer looks
328 -- up variables in the DsMetaEnv
329 type DsMetaEnv = NameEnv DsMetaVal
330
331 data DsMetaVal
332 = DsBound Id -- Bound by a pattern inside the [| |].
333 -- Will be dynamically alpha renamed.
334 -- The Id has type THSyntax.Var
335
336 | DsSplice (HsExpr GhcTc) -- These bindings are introduced by
337 -- the PendingSplices on a HsBracketOut
338
339
340 {-
341 ************************************************************************
342 * *
343 Global typechecker environment
344 * *
345 ************************************************************************
346 -}
347
348 -- | 'FrontendResult' describes the result of running the
349 -- frontend of a Haskell module. Usually, you'll get
350 -- a 'FrontendTypecheck', since running the frontend involves
351 -- typechecking a program, but for an hs-boot merge you'll
352 -- just get a ModIface, since no actual typechecking occurred.
353 --
354 -- This data type really should be in HscTypes, but it needs
355 -- to have a TcGblEnv which is only defined here.
356 data FrontendResult
357 = FrontendTypecheck TcGblEnv
358
359 -- Note [Identity versus semantic module]
360 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
361 -- When typechecking an hsig file, it is convenient to keep track
362 -- of two different "this module" identifiers:
363 --
364 -- - The IDENTITY module is simply thisPackage + the module
365 -- name; i.e. it uniquely *identifies* the interface file
366 -- we're compiling. For example, p[A=<A>]:A is an
367 -- identity module identifying the requirement named A
368 -- from library p.
369 --
370 -- - The SEMANTIC module, which is the actual module that
371 -- this signature is intended to represent (e.g. if
372 -- we have a identity module p[A=base:Data.IORef]:A,
373 -- then the semantic module is base:Data.IORef)
374 --
375 -- Which one should you use?
376 --
377 -- - In the desugarer and later phases of compilation,
378 -- identity and semantic modules coincide, since we never compile
379 -- signatures (we just generate blank object files for
380 -- hsig files.)
381 --
382 -- A corrolary of this is that the following invariant holds at any point
383 -- past desugaring,
384 --
385 -- if I have a Module, this_mod, in hand representing the module
386 -- currently being compiled,
387 -- then moduleUnitId this_mod == thisPackage dflags
388 --
389 -- - For any code involving Names, we want semantic modules.
390 -- See lookupIfaceTop in IfaceEnv, mkIface and addFingerprints
391 -- in MkIface, and tcLookupGlobal in TcEnv
392 --
393 -- - When reading interfaces, we want the identity module to
394 -- identify the specific interface we want (such interfaces
395 -- should never be loaded into the EPS). However, if a
396 -- hole module <A> is requested, we look for A.hi
397 -- in the home library we are compiling. (See LoadIface.)
398 -- Similarly, in RnNames we check for self-imports using
399 -- identity modules, to allow signatures to import their implementor.
400 --
401 -- - For recompilation avoidance, you want the identity module,
402 -- since that will actually say the specific interface you
403 -- want to track (and recompile if it changes)
404
405 -- | 'TcGblEnv' describes the top-level of the module at the
406 -- point at which the typechecker is finished work.
407 -- It is this structure that is handed on to the desugarer
408 -- For state that needs to be updated during the typechecking
409 -- phase and returned at end, use a 'TcRef' (= 'IORef').
410 data TcGblEnv
411 = TcGblEnv {
412 tcg_mod :: Module, -- ^ Module being compiled
413 tcg_semantic_mod :: Module, -- ^ If a signature, the backing module
414 -- See also Note [Identity versus semantic module]
415 tcg_src :: HscSource,
416 -- ^ What kind of module (regular Haskell, hs-boot, hsig)
417
418 tcg_rdr_env :: GlobalRdrEnv, -- ^ Top level envt; used during renaming
419 tcg_default :: Maybe [Type],
420 -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
421
422 tcg_fix_env :: FixityEnv, -- ^ Just for things in this module
423 tcg_field_env :: RecFieldEnv, -- ^ Just for things in this module
424 -- See Note [The interactive package] in HscTypes
425
426 tcg_type_env :: TypeEnv,
427 -- ^ Global type env for the module we are compiling now. All
428 -- TyCons and Classes (for this module) end up in here right away,
429 -- along with their derived constructors, selectors.
430 --
431 -- (Ids defined in this module start in the local envt, though they
432 -- move to the global envt during zonking)
433 --
434 -- NB: for what "things in this module" means, see
435 -- Note [The interactive package] in HscTypes
436
437 tcg_type_env_var :: TcRef TypeEnv,
438 -- Used only to initialise the interface-file
439 -- typechecker in initIfaceTcRn, so that it can see stuff
440 -- bound in this module when dealing with hi-boot recursions
441 -- Updated at intervals (e.g. after dealing with types and classes)
442
443 tcg_inst_env :: !InstEnv,
444 -- ^ Instance envt for all /home-package/ modules;
445 -- Includes the dfuns in tcg_insts
446 -- NB. BangPattern is to fix a leak, see #15111
447 tcg_fam_inst_env :: !FamInstEnv, -- ^ Ditto for family instances
448 -- NB. BangPattern is to fix a leak, see #15111
449 tcg_ann_env :: AnnEnv, -- ^ And for annotations
450
451 -- Now a bunch of things about this module that are simply
452 -- accumulated, but never consulted until the end.
453 -- Nevertheless, it's convenient to accumulate them along
454 -- with the rest of the info from this module.
455 tcg_exports :: [AvailInfo], -- ^ What is exported
456 tcg_imports :: ImportAvails,
457 -- ^ Information about what was imported from where, including
458 -- things bound in this module. Also store Safe Haskell info
459 -- here about transitive trusted package requirements.
460 --
461 -- There are not many uses of this field, so you can grep for
462 -- all them.
463 --
464 -- The ImportAvails records information about the following
465 -- things:
466 --
467 -- 1. All of the modules you directly imported (tcRnImports)
468 -- 2. The orphans (only!) of all imported modules in a GHCi
469 -- session (runTcInteractive)
470 -- 3. The module that instantiated a signature
471 -- 4. Each of the signatures that merged in
472 --
473 -- It is used in the following ways:
474 -- - imp_orphs is used to determine what orphan modules should be
475 -- visible in the context (tcVisibleOrphanMods)
476 -- - imp_finsts is used to determine what family instances should
477 -- be visible (tcExtendLocalFamInstEnv)
478 -- - To resolve the meaning of the export list of a module
479 -- (tcRnExports)
480 -- - imp_mods is used to compute usage info (mkIfaceTc, deSugar)
481 -- - imp_trust_own_pkg is used for Safe Haskell in interfaces
482 -- (mkIfaceTc, as well as in HscMain)
483 -- - To create the Dependencies field in interface (mkDependencies)
484
485 -- These three fields track unused bindings and imports
486 -- See Note [Tracking unused binding and imports]
487 tcg_dus :: DefUses,
488 tcg_used_gres :: TcRef [GlobalRdrElt],
489 tcg_keep :: TcRef NameSet,
490
491 tcg_th_used :: TcRef Bool,
492 -- ^ @True@ <=> Template Haskell syntax used.
493 --
494 -- We need this so that we can generate a dependency on the
495 -- Template Haskell package, because the desugarer is going
496 -- to emit loads of references to TH symbols. The reference
497 -- is implicit rather than explicit, so we have to zap a
498 -- mutable variable.
499
500 tcg_th_splice_used :: TcRef Bool,
501 -- ^ @True@ <=> A Template Haskell splice was used.
502 --
503 -- Splices disable recompilation avoidance (see #481)
504
505 tcg_dfun_n :: TcRef OccSet,
506 -- ^ Allows us to choose unique DFun names.
507
508 tcg_merged :: [(Module, Fingerprint)],
509 -- ^ The requirements we merged with; we always have to recompile
510 -- if any of these changed.
511
512 -- The next fields accumulate the payload of the module
513 -- The binds, rules and foreign-decl fields are collected
514 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
515
516 tcg_rn_exports :: Maybe [(Located (IE GhcRn), Avails)],
517 -- Nothing <=> no explicit export list
518 -- Is always Nothing if we don't want to retain renamed
519 -- exports.
520 -- If present contains each renamed export list item
521 -- together with its exported names.
522
523 tcg_rn_imports :: [LImportDecl GhcRn],
524 -- Keep the renamed imports regardless. They are not
525 -- voluminous and are needed if you want to report unused imports
526
527 tcg_rn_decls :: Maybe (HsGroup GhcRn),
528 -- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
529 -- decls.
530
531 tcg_dependent_files :: TcRef [FilePath], -- ^ dependencies from addDependentFile
532
533 tcg_th_topdecls :: TcRef [LHsDecl GhcPs],
534 -- ^ Top-level declarations from addTopDecls
535
536 tcg_th_foreign_files :: TcRef [(ForeignSrcLang, FilePath)],
537 -- ^ Foreign files emitted from TH.
538
539 tcg_th_topnames :: TcRef NameSet,
540 -- ^ Exact names bound in top-level declarations in tcg_th_topdecls
541
542 tcg_th_modfinalizers :: TcRef [(TcLclEnv, ThModFinalizers)],
543 -- ^ Template Haskell module finalizers.
544 --
545 -- They can use particular local environments.
546
547 tcg_th_coreplugins :: TcRef [String],
548 -- ^ Core plugins added by Template Haskell code.
549
550 tcg_th_state :: TcRef (Map TypeRep Dynamic),
551 tcg_th_remote_state :: TcRef (Maybe (ForeignRef (IORef QState))),
552 -- ^ Template Haskell state
553
554 tcg_ev_binds :: Bag EvBind, -- Top-level evidence bindings
555
556 -- Things defined in this module, or (in GHCi)
557 -- in the declarations for a single GHCi command.
558 -- For the latter, see Note [The interactive package] in HscTypes
559 tcg_tr_module :: Maybe Id, -- Id for $trModule :: GHC.Types.Module
560 -- for which every module has a top-level defn
561 -- except in GHCi in which case we have Nothing
562 tcg_binds :: LHsBinds GhcTc, -- Value bindings in this module
563 tcg_sigs :: NameSet, -- ...Top-level names that *lack* a signature
564 tcg_imp_specs :: [LTcSpecPrag], -- ...SPECIALISE prags for imported Ids
565 tcg_warns :: Warnings, -- ...Warnings and deprecations
566 tcg_anns :: [Annotation], -- ...Annotations
567 tcg_tcs :: [TyCon], -- ...TyCons and Classes
568 tcg_insts :: [ClsInst], -- ...Instances
569 tcg_fam_insts :: [FamInst], -- ...Family instances
570 tcg_rules :: [LRuleDecl GhcTc], -- ...Rules
571 tcg_fords :: [LForeignDecl GhcTc], -- ...Foreign import & exports
572 tcg_patsyns :: [PatSyn], -- ...Pattern synonyms
573
574 tcg_doc_hdr :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
575 tcg_hpc :: !AnyHpcUsage, -- ^ @True@ if any part of the
576 -- prog uses hpc instrumentation.
577 -- NB. BangPattern is to fix a leak, see #15111
578
579 tcg_self_boot :: SelfBootInfo, -- ^ Whether this module has a
580 -- corresponding hi-boot file
581
582 tcg_main :: Maybe Name, -- ^ The Name of the main
583 -- function, if this module is
584 -- the main module.
585
586 tcg_safeInfer :: TcRef (Bool, WarningMessages),
587 -- ^ Has the typechecker inferred this module as -XSafe (Safe Haskell)
588 -- See Note [Safe Haskell Overlapping Instances Implementation],
589 -- although this is used for more than just that failure case.
590
591 tcg_tc_plugins :: [TcPluginSolver],
592 -- ^ A list of user-defined plugins for the constraint solver.
593 tcg_hf_plugins :: [HoleFitPlugin],
594 -- ^ A list of user-defined plugins for hole fit suggestions.
595
596 tcg_top_loc :: RealSrcSpan,
597 -- ^ The RealSrcSpan this module came from
598
599 tcg_static_wc :: TcRef WantedConstraints,
600 -- ^ Wanted constraints of static forms.
601 -- See Note [Constraints in static forms].
602 tcg_complete_matches :: [CompleteMatch],
603
604 -- ^ Tracking indices for cost centre annotations
605 tcg_cc_st :: TcRef CostCentreState
606 }
607
608 -- NB: topModIdentity, not topModSemantic!
609 -- Definition sites of orphan identities will be identity modules, not semantic
610 -- modules.
611
612 -- Note [Constraints in static forms]
613 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
614 --
615 -- When a static form produces constraints like
616 --
617 -- f :: StaticPtr (Bool -> String)
618 -- f = static show
619 --
620 -- we collect them in tcg_static_wc and resolve them at the end
621 -- of type checking. They need to be resolved separately because
622 -- we don't want to resolve them in the context of the enclosing
623 -- expression. Consider
624 --
625 -- g :: Show a => StaticPtr (a -> String)
626 -- g = static show
627 --
628 -- If the @Show a0@ constraint that the body of the static form produces was
629 -- resolved in the context of the enclosing expression, then the body of the
630 -- static form wouldn't be closed because the Show dictionary would come from
631 -- g's context instead of coming from the top level.
632
633 tcVisibleOrphanMods :: TcGblEnv -> ModuleSet
634 tcVisibleOrphanMods tcg_env
635 = mkModuleSet (tcg_mod tcg_env : imp_orphs (tcg_imports tcg_env))
636
637 instance ContainsModule TcGblEnv where
638 extractModule env = tcg_semantic_mod env
639
640 type RecFieldEnv = NameEnv [FieldLabel]
641 -- Maps a constructor name *in this module*
642 -- to the fields for that constructor.
643 -- This is used when dealing with ".." notation in record
644 -- construction and pattern matching.
645 -- The FieldEnv deals *only* with constructors defined in *this*
646 -- module. For imported modules, we get the same info from the
647 -- TypeEnv
648
649 data SelfBootInfo
650 = NoSelfBoot -- No corresponding hi-boot file
651 | SelfBoot
652 { sb_mds :: ModDetails -- There was a hi-boot file,
653 , sb_tcs :: NameSet } -- defining these TyCons,
654 -- What is sb_tcs used for? See Note [Extra dependencies from .hs-boot files]
655 -- in RnSource
656
657
658 {- Note [Tracking unused binding and imports]
659 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
660 We gather three sorts of usage information
661
662 * tcg_dus :: DefUses (defs/uses)
663 Records what is defined in this module and what is used.
664
665 Records *defined* Names (local, top-level)
666 and *used* Names (local or imported)
667
668 Used (a) to report "defined but not used"
669 (see RnNames.reportUnusedNames)
670 (b) to generate version-tracking usage info in interface
671 files (see MkIface.mkUsedNames)
672 This usage info is mainly gathered by the renamer's
673 gathering of free-variables
674
675 * tcg_used_gres :: TcRef [GlobalRdrElt]
676 Records occurrences of imported entities.
677
678 Used only to report unused import declarations
679
680 Records each *occurrence* an *imported* (not locally-defined) entity.
681 The occurrence is recorded by keeping a GlobalRdrElt for it.
682 These is not the GRE that is in the GlobalRdrEnv; rather it
683 is recorded *after* the filtering done by pickGREs. So it reflect
684 /how that occurrence is in scope/. See Note [GRE filtering] in
685 RdrName.
686
687 * tcg_keep :: TcRef NameSet
688 Records names of the type constructors, data constructors, and Ids that
689 are used by the constraint solver.
690
691 The typechecker may use find that some imported or
692 locally-defined things are used, even though they
693 do not appear to be mentioned in the source code:
694
695 (a) The to/from functions for generic data types
696
697 (b) Top-level variables appearing free in the RHS of an
698 orphan rule
699
700 (c) Top-level variables appearing free in a TH bracket
701 See Note [Keeping things alive for Template Haskell]
702 in RnSplice
703
704 (d) The data constructor of a newtype that is used
705 to solve a Coercible instance (e.g. #10347). Example
706 module T10347 (N, mkN) where
707 import Data.Coerce
708 newtype N a = MkN Int
709 mkN :: Int -> N a
710 mkN = coerce
711
712 Then we wish to record `MkN` as used, since it is (morally)
713 used to perform the coercion in `mkN`. To do so, the
714 Coercible solver updates tcg_keep's TcRef whenever it
715 encounters a use of `coerce` that crosses newtype boundaries.
716
717 The tcg_keep field is used in two distinct ways:
718
719 * Desugar.addExportFlagsAndRules. Where things like (a-c) are locally
720 defined, we should give them an an Exported flag, so that the
721 simplifier does not discard them as dead code, and so that they are
722 exposed in the interface file (but not to export to the user).
723
724 * RnNames.reportUnusedNames. Where newtype data constructors like (d)
725 are imported, we don't want to report them as unused.
726
727
728 ************************************************************************
729 * *
730 The local typechecker environment
731 * *
732 ************************************************************************
733
734 Note [The Global-Env/Local-Env story]
735 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
736 During type checking, we keep in the tcg_type_env
737 * All types and classes
738 * All Ids derived from types and classes (constructors, selectors)
739
740 At the end of type checking, we zonk the local bindings,
741 and as we do so we add to the tcg_type_env
742 * Locally defined top-level Ids
743
744 Why? Because they are now Ids not TcIds. This final GlobalEnv is
745 a) fed back (via the knot) to typechecking the
746 unfoldings of interface signatures
747 b) used in the ModDetails of this module
748 -}
749
750 data TcLclEnv -- Changes as we move inside an expression
751 -- Discarded after typecheck/rename; not passed on to desugarer
752 = TcLclEnv {
753 tcl_loc :: RealSrcSpan, -- Source span
754 tcl_ctxt :: [ErrCtxt], -- Error context, innermost on top
755 tcl_tclvl :: TcLevel, -- Birthplace for new unification variables
756
757 tcl_th_ctxt :: ThStage, -- Template Haskell context
758 tcl_th_bndrs :: ThBindEnv, -- and binder info
759 -- The ThBindEnv records the TH binding level of in-scope Names
760 -- defined in this module (not imported)
761 -- We can't put this info in the TypeEnv because it's needed
762 -- (and extended) in the renamer, for untyed splices
763
764 tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
765
766 tcl_rdr :: LocalRdrEnv, -- Local name envt
767 -- Maintained during renaming, of course, but also during
768 -- type checking, solely so that when renaming a Template-Haskell
769 -- splice we have the right environment for the renamer.
770 --
771 -- Does *not* include global name envt; may shadow it
772 -- Includes both ordinary variables and type variables;
773 -- they are kept distinct because tyvar have a different
774 -- occurrence constructor (Name.TvOcc)
775 -- We still need the unsullied global name env so that
776 -- we can look up record field names
777
778 tcl_env :: TcTypeEnv, -- The local type environment:
779 -- Ids and TyVars defined in this module
780
781 tcl_bndrs :: TcBinderStack, -- Used for reporting relevant bindings,
782 -- and for tidying types
783
784 tcl_lie :: TcRef WantedConstraints, -- Place to accumulate type constraints
785 tcl_errs :: TcRef Messages -- Place to accumulate errors
786 }
787
788 setLclEnvTcLevel :: TcLclEnv -> TcLevel -> TcLclEnv
789 setLclEnvTcLevel env lvl = env { tcl_tclvl = lvl }
790
791 getLclEnvTcLevel :: TcLclEnv -> TcLevel
792 getLclEnvTcLevel = tcl_tclvl
793
794 setLclEnvLoc :: TcLclEnv -> RealSrcSpan -> TcLclEnv
795 setLclEnvLoc env loc = env { tcl_loc = loc }
796
797 getLclEnvLoc :: TcLclEnv -> RealSrcSpan
798 getLclEnvLoc = tcl_loc
799
800 type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, MsgDoc))
801 -- Monadic so that we have a chance
802 -- to deal with bound type variables just before error
803 -- message construction
804
805 -- Bool: True <=> this is a landmark context; do not
806 -- discard it when trimming for display
807
808 -- These are here to avoid module loops: one might expect them
809 -- in Constraint, but they refer to ErrCtxt which refers to TcM.
810 -- Easier to just keep these definitions here, alongside TcM.
811 pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc
812 pushErrCtxt o err loc@(CtLoc { ctl_env = lcl })
813 = loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
814
815 pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc
816 -- Just add information w/o updating the origin!
817 pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl })
818 = loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
819
820 type TcTypeEnv = NameEnv TcTyThing
821
822 type ThBindEnv = NameEnv (TopLevelFlag, ThLevel)
823 -- Domain = all Ids bound in this module (ie not imported)
824 -- The TopLevelFlag tells if the binding is syntactically top level.
825 -- We need to know this, because the cross-stage persistence story allows
826 -- cross-stage at arbitrary types if the Id is bound at top level.
827 --
828 -- Nota bene: a ThLevel of 'outerLevel' is *not* the same as being
829 -- bound at top level! See Note [Template Haskell levels] in TcSplice
830
831 {- Note [Given Insts]
832 ~~~~~~~~~~~~~~~~~~
833 Because of GADTs, we have to pass inwards the Insts provided by type signatures
834 and existential contexts. Consider
835 data T a where { T1 :: b -> b -> T [b] }
836 f :: Eq a => T a -> Bool
837 f (T1 x y) = [x]==[y]
838
839 The constructor T1 binds an existential variable 'b', and we need Eq [b].
840 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
841 pass it inwards.
842
843 -}
844
845 -- | Type alias for 'IORef'; the convention is we'll use this for mutable
846 -- bits of data in 'TcGblEnv' which are updated during typechecking and
847 -- returned at the end.
848 type TcRef a = IORef a
849 -- ToDo: when should I refer to it as a 'TcId' instead of an 'Id'?
850 type TcId = Id
851 type TcIdSet = IdSet
852
853 ---------------------------
854 -- The TcBinderStack
855 ---------------------------
856
857 type TcBinderStack = [TcBinder]
858 -- This is a stack of locally-bound ids and tyvars,
859 -- innermost on top
860 -- Used only in error reporting (relevantBindings in TcError),
861 -- and in tidying
862 -- We can't use the tcl_env type environment, because it doesn't
863 -- keep track of the nesting order
864
865 data TcBinder
866 = TcIdBndr
867 TcId
868 TopLevelFlag -- Tells whether the binding is syntactically top-level
869 -- (The monomorphic Ids for a recursive group count
870 -- as not-top-level for this purpose.)
871
872 | TcIdBndr_ExpType -- Variant that allows the type to be specified as
873 -- an ExpType
874 Name
875 ExpType
876 TopLevelFlag
877
878 | TcTvBndr -- e.g. case x of P (y::a) -> blah
879 Name -- We bind the lexical name "a" to the type of y,
880 TyVar -- which might be an utterly different (perhaps
881 -- existential) tyvar
882
883 instance Outputable TcBinder where
884 ppr (TcIdBndr id top_lvl) = ppr id <> brackets (ppr top_lvl)
885 ppr (TcIdBndr_ExpType id _ top_lvl) = ppr id <> brackets (ppr top_lvl)
886 ppr (TcTvBndr name tv) = ppr name <+> ppr tv
887
888 instance HasOccName TcBinder where
889 occName (TcIdBndr id _) = occName (idName id)
890 occName (TcIdBndr_ExpType name _ _) = occName name
891 occName (TcTvBndr name _) = occName name
892
893 -- fixes #12177
894 -- Builds up a list of bindings whose OccName has not been seen before
895 -- i.e., If ys = removeBindingShadowing xs
896 -- then
897 -- - ys is obtained from xs by deleting some elements
898 -- - ys has no duplicate OccNames
899 -- - The first duplicated OccName in xs is retained in ys
900 -- Overloaded so that it can be used for both GlobalRdrElt in typed-hole
901 -- substitutions and TcBinder when looking for relevant bindings.
902 removeBindingShadowing :: HasOccName a => [a] -> [a]
903 removeBindingShadowing bindings = reverse $ fst $ foldl
904 (\(bindingAcc, seenNames) binding ->
905 if occName binding `elemOccSet` seenNames -- if we've seen it
906 then (bindingAcc, seenNames) -- skip it
907 else (binding:bindingAcc, extendOccSet seenNames (occName binding)))
908 ([], emptyOccSet) bindings
909
910 ---------------------------
911 -- Template Haskell stages and levels
912 ---------------------------
913
914 data SpliceType = Typed | Untyped
915
916 data ThStage -- See Note [Template Haskell state diagram] in TcSplice
917 = Splice SpliceType -- Inside a top-level splice
918 -- This code will be run *at compile time*;
919 -- the result replaces the splice
920 -- Binding level = 0
921
922 | RunSplice (TcRef [ForeignRef (TH.Q ())])
923 -- Set when running a splice, i.e. NOT when renaming or typechecking the
924 -- Haskell code for the splice. See Note [RunSplice ThLevel].
925 --
926 -- Contains a list of mod finalizers collected while executing the splice.
927 --
928 -- 'addModFinalizer' inserts finalizers here, and from here they are taken
929 -- to construct an @HsSpliced@ annotation for untyped splices. See Note
930 -- [Delaying modFinalizers in untyped splices] in "RnSplice".
931 --
932 -- For typed splices, the typechecker takes finalizers from here and
933 -- inserts them in the list of finalizers in the global environment.
934 --
935 -- See Note [Collecting modFinalizers in typed splices] in "TcSplice".
936
937 | Comp -- Ordinary Haskell code
938 -- Binding level = 1
939
940 | Brack -- Inside brackets
941 ThStage -- Enclosing stage
942 PendingStuff
943
944 data PendingStuff
945 = RnPendingUntyped -- Renaming the inside of an *untyped* bracket
946 (TcRef [PendingRnSplice]) -- Pending splices in here
947
948 | RnPendingTyped -- Renaming the inside of a *typed* bracket
949
950 | TcPending -- Typechecking the inside of a typed bracket
951 (TcRef [PendingTcSplice]) -- Accumulate pending splices here
952 (TcRef WantedConstraints) -- and type constraints here
953
954 topStage, topAnnStage, topSpliceStage :: ThStage
955 topStage = Comp
956 topAnnStage = Splice Untyped
957 topSpliceStage = Splice Untyped
958
959 instance Outputable ThStage where
960 ppr (Splice _) = text "Splice"
961 ppr (RunSplice _) = text "RunSplice"
962 ppr Comp = text "Comp"
963 ppr (Brack s _) = text "Brack" <> parens (ppr s)
964
965 type ThLevel = Int
966 -- NB: see Note [Template Haskell levels] in TcSplice
967 -- Incremented when going inside a bracket,
968 -- decremented when going inside a splice
969 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
970 -- original "Template meta-programming for Haskell" paper
971
972 impLevel, outerLevel :: ThLevel
973 impLevel = 0 -- Imported things; they can be used inside a top level splice
974 outerLevel = 1 -- Things defined outside brackets
975
976 thLevel :: ThStage -> ThLevel
977 thLevel (Splice _) = 0
978 thLevel (RunSplice _) =
979 -- See Note [RunSplice ThLevel].
980 panic "thLevel: called when running a splice"
981 thLevel Comp = 1
982 thLevel (Brack s _) = thLevel s + 1
983
984 {- Node [RunSplice ThLevel]
985 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
986 The 'RunSplice' stage is set when executing a splice, and only when running a
987 splice. In particular it is not set when the splice is renamed or typechecked.
988
989 'RunSplice' is needed to provide a reference where 'addModFinalizer' can insert
990 the finalizer (see Note [Delaying modFinalizers in untyped splices]), and
991 'addModFinalizer' runs when doing Q things. Therefore, It doesn't make sense to
992 set 'RunSplice' when renaming or typechecking the splice, where 'Splice',
993 'Brack' or 'Comp' are used instead.
994
995 -}
996
997 ---------------------------
998 -- Arrow-notation context
999 ---------------------------
1000
1001 {- Note [Escaping the arrow scope]
1002 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1003 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
1004 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
1005 For example
1006
1007 proc x -> (e1 -< e2)
1008
1009 Here, x is not in scope in e1, but it is in scope in e2. This can get
1010 a bit complicated:
1011
1012 let x = 3 in
1013 proc y -> (proc z -> e1) -< e2
1014
1015 Here, x and z are in scope in e1, but y is not.
1016
1017 We implement this by
1018 recording the environment when passing a proc (using newArrowScope),
1019 and returning to that (using escapeArrowScope) on the left of -< and the
1020 head of (|..|).
1021
1022 All this can be dealt with by the *renamer*. But the type checker needs
1023 to be involved too. Example (arrowfail001)
1024 class Foo a where foo :: a -> ()
1025 data Bar = forall a. Foo a => Bar a
1026 get :: Bar -> ()
1027 get = proc x -> case x of Bar a -> foo -< a
1028 Here the call of 'foo' gives rise to a (Foo a) constraint that should not
1029 be captured by the pattern match on 'Bar'. Rather it should join the
1030 constraints from further out. So we must capture the constraint bag
1031 from further out in the ArrowCtxt that we push inwards.
1032 -}
1033
1034 data ArrowCtxt -- Note [Escaping the arrow scope]
1035 = NoArrowCtxt
1036 | ArrowCtxt LocalRdrEnv (TcRef WantedConstraints)
1037
1038
1039 ---------------------------
1040 -- TcTyThing
1041 ---------------------------
1042
1043 -- | A typecheckable thing available in a local context. Could be
1044 -- 'AGlobal' 'TyThing', but also lexically scoped variables, etc.
1045 -- See 'TcEnv' for how to retrieve a 'TyThing' given a 'Name'.
1046 data TcTyThing
1047 = AGlobal TyThing -- Used only in the return type of a lookup
1048
1049 | ATcId -- Ids defined in this module; may not be fully zonked
1050 { tct_id :: TcId
1051 , tct_info :: IdBindingInfo -- See Note [Meaning of IdBindingInfo]
1052 }
1053
1054 | ATyVar Name TcTyVar -- See Note [Type variables in the type environment]
1055
1056 | ATcTyCon TyCon -- Used temporarily, during kind checking, for the
1057 -- tycons and clases in this recursive group
1058 -- The TyCon is always a TcTyCon. Its kind
1059 -- can be a mono-kind or a poly-kind; in TcTyClsDcls see
1060 -- Note [Type checking recursive type and class declarations]
1061
1062 | APromotionErr PromotionErr
1063
1064 data PromotionErr
1065 = TyConPE -- TyCon used in a kind before we are ready
1066 -- data T :: T -> * where ...
1067 | ClassPE -- Ditto Class
1068
1069 | FamDataConPE -- Data constructor for a data family
1070 -- See Note [AFamDataCon: not promoting data family constructors]
1071 -- in TcEnv.
1072 | ConstrainedDataConPE PredType
1073 -- Data constructor with a non-equality context
1074 -- See Note [Don't promote data constructors with
1075 -- non-equality contexts] in TcHsType
1076 | PatSynPE -- Pattern synonyms
1077 -- See Note [Don't promote pattern synonyms] in TcEnv
1078
1079 | RecDataConPE -- Data constructor in a recursive loop
1080 -- See Note [Recursion and promoting data constructors] in TcTyClsDecls
1081 | NoDataKindsTC -- -XDataKinds not enabled (for a tycon)
1082 | NoDataKindsDC -- -XDataKinds not enabled (for a datacon)
1083
1084 instance Outputable TcTyThing where -- Debugging only
1085 ppr (AGlobal g) = ppr g
1086 ppr elt@(ATcId {}) = text "Identifier" <>
1087 brackets (ppr (tct_id elt) <> dcolon
1088 <> ppr (varType (tct_id elt)) <> comma
1089 <+> ppr (tct_info elt))
1090 ppr (ATyVar n tv) = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv
1091 <+> dcolon <+> ppr (varType tv)
1092 ppr (ATcTyCon tc) = text "ATcTyCon" <+> ppr tc <+> dcolon <+> ppr (tyConKind tc)
1093 ppr (APromotionErr err) = text "APromotionErr" <+> ppr err
1094
1095 -- | IdBindingInfo describes how an Id is bound.
1096 --
1097 -- It is used for the following purposes:
1098 -- a) for static forms in TcExpr.checkClosedInStaticForm and
1099 -- b) to figure out when a nested binding can be generalised,
1100 -- in TcBinds.decideGeneralisationPlan.
1101 --
1102 data IdBindingInfo -- See Note [Meaning of IdBindingInfo and ClosedTypeId]
1103 = NotLetBound
1104 | ClosedLet
1105 | NonClosedLet
1106 RhsNames -- Used for (static e) checks only
1107 ClosedTypeId -- Used for generalisation checks
1108 -- and for (static e) checks
1109
1110 -- | IsGroupClosed describes a group of mutually-recursive bindings
1111 data IsGroupClosed
1112 = IsGroupClosed
1113 (NameEnv RhsNames) -- Free var info for the RHS of each binding in the goup
1114 -- Used only for (static e) checks
1115
1116 ClosedTypeId -- True <=> all the free vars of the group are
1117 -- imported or ClosedLet or
1118 -- NonClosedLet with ClosedTypeId=True.
1119 -- In particular, no tyvars, no NotLetBound
1120
1121 type RhsNames = NameSet -- Names of variables, mentioned on the RHS of
1122 -- a definition, that are not Global or ClosedLet
1123
1124 type ClosedTypeId = Bool
1125 -- See Note [Meaning of IdBindingInfo and ClosedTypeId]
1126
1127 {- Note [Meaning of IdBindingInfo]
1128 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1129 NotLetBound means that
1130 the Id is not let-bound (e.g. it is bound in a
1131 lambda-abstraction or in a case pattern)
1132
1133 ClosedLet means that
1134 - The Id is let-bound,
1135 - Any free term variables are also Global or ClosedLet
1136 - Its type has no free variables (NB: a top-level binding subject
1137 to the MR might have free vars in its type)
1138 These ClosedLets can definitely be floated to top level; and we
1139 may need to do so for static forms.
1140
1141 Property: ClosedLet
1142 is equivalent to
1143 NonClosedLet emptyNameSet True
1144
1145 (NonClosedLet (fvs::RhsNames) (cl::ClosedTypeId)) means that
1146 - The Id is let-bound
1147
1148 - The fvs::RhsNames contains the free names of the RHS,
1149 excluding Global and ClosedLet ones.
1150
1151 - For the ClosedTypeId field see Note [Bindings with closed types]
1152
1153 For (static e) to be valid, we need for every 'x' free in 'e',
1154 that x's binding is floatable to the top level. Specifically:
1155 * x's RhsNames must be empty
1156 * x's type has no free variables
1157 See Note [Grand plan for static forms] in StaticPtrTable.hs.
1158 This test is made in TcExpr.checkClosedInStaticForm.
1159 Actually knowing x's RhsNames (rather than just its emptiness
1160 or otherwise) is just so we can produce better error messages
1161
1162 Note [Bindings with closed types: ClosedTypeId]
1163 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1164 Consider
1165
1166 f x = let g ys = map not ys
1167 in ...
1168
1169 Can we generalise 'g' under the OutsideIn algorithm? Yes,
1170 because all g's free variables are top-level; that is they themselves
1171 have no free type variables, and it is the type variables in the
1172 environment that makes things tricky for OutsideIn generalisation.
1173
1174 Here's the invariant:
1175 If an Id has ClosedTypeId=True (in its IdBindingInfo), then
1176 the Id's type is /definitely/ closed (has no free type variables).
1177 Specifically,
1178 a) The Id's acutal type is closed (has no free tyvars)
1179 b) Either the Id has a (closed) user-supplied type signature
1180 or all its free variables are Global/ClosedLet
1181 or NonClosedLet with ClosedTypeId=True.
1182 In particular, none are NotLetBound.
1183
1184 Why is (b) needed? Consider
1185 \x. (x :: Int, let y = x+1 in ...)
1186 Initially x::alpha. If we happen to typecheck the 'let' before the
1187 (x::Int), y's type will have a free tyvar; but if the other way round
1188 it won't. So we treat any let-bound variable with a free
1189 non-let-bound variable as not ClosedTypeId, regardless of what the
1190 free vars of its type actually are.
1191
1192 But if it has a signature, all is well:
1193 \x. ...(let { y::Int; y = x+1 } in
1194 let { v = y+2 } in ...)...
1195 Here the signature on 'v' makes 'y' a ClosedTypeId, so we can
1196 generalise 'v'.
1197
1198 Note that:
1199
1200 * A top-level binding may not have ClosedTypeId=True, if it suffers
1201 from the MR
1202
1203 * A nested binding may be closed (eg 'g' in the example we started
1204 with). Indeed, that's the point; whether a function is defined at
1205 top level or nested is orthogonal to the question of whether or
1206 not it is closed.
1207
1208 * A binding may be non-closed because it mentions a lexically scoped
1209 *type variable* Eg
1210 f :: forall a. blah
1211 f x = let g y = ...(y::a)...
1212
1213 Under OutsideIn we are free to generalise an Id all of whose free
1214 variables have ClosedTypeId=True (or imported). This is an extension
1215 compared to the JFP paper on OutsideIn, which used "top-level" as a
1216 proxy for "closed". (It's not a good proxy anyway -- the MR can make
1217 a top-level binding with a free type variable.)
1218
1219 Note [Type variables in the type environment]
1220 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1221 The type environment has a binding for each lexically-scoped
1222 type variable that is in scope. For example
1223
1224 f :: forall a. a -> a
1225 f x = (x :: a)
1226
1227 g1 :: [a] -> a
1228 g1 (ys :: [b]) = head ys :: b
1229
1230 g2 :: [Int] -> Int
1231 g2 (ys :: [c]) = head ys :: c
1232
1233 * The forall'd variable 'a' in the signature scopes over f's RHS.
1234
1235 * The pattern-bound type variable 'b' in 'g1' scopes over g1's
1236 RHS; note that it is bound to a skolem 'a' which is not itself
1237 lexically in scope.
1238
1239 * The pattern-bound type variable 'c' in 'g2' is bound to
1240 Int; that is, pattern-bound type variables can stand for
1241 arbitrary types. (see
1242 GHC proposal #128 "Allow ScopedTypeVariables to refer to types"
1243 https://github.com/ghc-proposals/ghc-proposals/pull/128,
1244 and the paper
1245 "Type variables in patterns", Haskell Symposium 2018.
1246
1247
1248 This is implemented by the constructor
1249 ATyVar Name TcTyVar
1250 in the type environment.
1251
1252 * The Name is the name of the original, lexically scoped type
1253 variable
1254
1255 * The TcTyVar is sometimes a skolem (like in 'f'), and sometimes
1256 a unification variable (like in 'g1', 'g2'). We never zonk the
1257 type environment so in the latter case it always stays as a
1258 unification variable, although that variable may be later
1259 unified with a type (such as Int in 'g2').
1260 -}
1261
1262 instance Outputable IdBindingInfo where
1263 ppr NotLetBound = text "NotLetBound"
1264 ppr ClosedLet = text "TopLevelLet"
1265 ppr (NonClosedLet fvs closed_type) =
1266 text "TopLevelLet" <+> ppr fvs <+> ppr closed_type
1267
1268 instance Outputable PromotionErr where
1269 ppr ClassPE = text "ClassPE"
1270 ppr TyConPE = text "TyConPE"
1271 ppr PatSynPE = text "PatSynPE"
1272 ppr FamDataConPE = text "FamDataConPE"
1273 ppr (ConstrainedDataConPE pred) = text "ConstrainedDataConPE"
1274 <+> parens (ppr pred)
1275 ppr RecDataConPE = text "RecDataConPE"
1276 ppr NoDataKindsTC = text "NoDataKindsTC"
1277 ppr NoDataKindsDC = text "NoDataKindsDC"
1278
1279 pprTcTyThingCategory :: TcTyThing -> SDoc
1280 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
1281 pprTcTyThingCategory (ATyVar {}) = text "Type variable"
1282 pprTcTyThingCategory (ATcId {}) = text "Local identifier"
1283 pprTcTyThingCategory (ATcTyCon {}) = text "Local tycon"
1284 pprTcTyThingCategory (APromotionErr pe) = pprPECategory pe
1285
1286 pprPECategory :: PromotionErr -> SDoc
1287 pprPECategory ClassPE = text "Class"
1288 pprPECategory TyConPE = text "Type constructor"
1289 pprPECategory PatSynPE = text "Pattern synonym"
1290 pprPECategory FamDataConPE = text "Data constructor"
1291 pprPECategory ConstrainedDataConPE{} = text "Data constructor"
1292 pprPECategory RecDataConPE = text "Data constructor"
1293 pprPECategory NoDataKindsTC = text "Type constructor"
1294 pprPECategory NoDataKindsDC = text "Data constructor"
1295
1296 {-
1297 ************************************************************************
1298 * *
1299 Operations over ImportAvails
1300 * *
1301 ************************************************************************
1302 -}
1303
1304 -- | 'ImportAvails' summarises what was imported from where, irrespective of
1305 -- whether the imported things are actually used or not. It is used:
1306 --
1307 -- * when processing the export list,
1308 --
1309 -- * when constructing usage info for the interface file,
1310 --
1311 -- * to identify the list of directly imported modules for initialisation
1312 -- purposes and for optimised overlap checking of family instances,
1313 --
1314 -- * when figuring out what things are really unused
1315 --
1316 data ImportAvails
1317 = ImportAvails {
1318 imp_mods :: ImportedMods,
1319 -- = ModuleEnv [ImportedModsVal],
1320 -- ^ Domain is all directly-imported modules
1321 --
1322 -- See the documentation on ImportedModsVal in HscTypes for the
1323 -- meaning of the fields.
1324 --
1325 -- We need a full ModuleEnv rather than a ModuleNameEnv here,
1326 -- because we might be importing modules of the same name from
1327 -- different packages. (currently not the case, but might be in the
1328 -- future).
1329
1330 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
1331 -- ^ Home-package modules needed by the module being compiled
1332 --
1333 -- It doesn't matter whether any of these dependencies
1334 -- are actually /used/ when compiling the module; they
1335 -- are listed if they are below it at all. For
1336 -- example, suppose M imports A which imports X. Then
1337 -- compiling M might not need to consult X.hi, but X
1338 -- is still listed in M's dependencies.
1339
1340 imp_dep_pkgs :: Set InstalledUnitId,
1341 -- ^ Packages needed by the module being compiled, whether directly,
1342 -- or via other modules in this package, or via modules imported
1343 -- from other packages.
1344
1345 imp_trust_pkgs :: Set InstalledUnitId,
1346 -- ^ This is strictly a subset of imp_dep_pkgs and records the
1347 -- packages the current module needs to trust for Safe Haskell
1348 -- compilation to succeed. A package is required to be trusted if
1349 -- we are dependent on a trustworthy module in that package.
1350 -- While perhaps making imp_dep_pkgs a tuple of (UnitId, Bool)
1351 -- where True for the bool indicates the package is required to be
1352 -- trusted is the more logical design, doing so complicates a lot
1353 -- of code not concerned with Safe Haskell.
1354 -- See Note [RnNames . Tracking Trust Transitively]
1355
1356 imp_trust_own_pkg :: Bool,
1357 -- ^ Do we require that our own package is trusted?
1358 -- This is to handle efficiently the case where a Safe module imports
1359 -- a Trustworthy module that resides in the same package as it.
1360 -- See Note [RnNames . Trust Own Package]
1361
1362 imp_orphs :: [Module],
1363 -- ^ Orphan modules below us in the import tree (and maybe including
1364 -- us for imported modules)
1365
1366 imp_finsts :: [Module]
1367 -- ^ Family instance modules below us in the import tree (and maybe
1368 -- including us for imported modules)
1369 }
1370
1371 mkModDeps :: [(ModuleName, IsBootInterface)]
1372 -> ModuleNameEnv (ModuleName, IsBootInterface)
1373 mkModDeps deps = foldl' add emptyUFM deps
1374 where
1375 add env elt@(m,_) = addToUFM env m elt
1376
1377 modDepsElts
1378 :: ModuleNameEnv (ModuleName, IsBootInterface)
1379 -> [(ModuleName, IsBootInterface)]
1380 modDepsElts = sort . nonDetEltsUFM
1381 -- It's OK to use nonDetEltsUFM here because sorting by module names
1382 -- restores determinism
1383
1384 emptyImportAvails :: ImportAvails
1385 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
1386 imp_dep_mods = emptyUFM,
1387 imp_dep_pkgs = S.empty,
1388 imp_trust_pkgs = S.empty,
1389 imp_trust_own_pkg = False,
1390 imp_orphs = [],
1391 imp_finsts = [] }
1392
1393 -- | Union two ImportAvails
1394 --
1395 -- This function is a key part of Import handling, basically
1396 -- for each import we create a separate ImportAvails structure
1397 -- and then union them all together with this function.
1398 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
1399 plusImportAvails
1400 (ImportAvails { imp_mods = mods1,
1401 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
1402 imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1,
1403 imp_orphs = orphs1, imp_finsts = finsts1 })
1404 (ImportAvails { imp_mods = mods2,
1405 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
1406 imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2,
1407 imp_orphs = orphs2, imp_finsts = finsts2 })
1408 = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
1409 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
1410 imp_dep_pkgs = dpkgs1 `S.union` dpkgs2,
1411 imp_trust_pkgs = tpkgs1 `S.union` tpkgs2,
1412 imp_trust_own_pkg = tself1 || tself2,
1413 imp_orphs = orphs1 `unionLists` orphs2,
1414 imp_finsts = finsts1 `unionLists` finsts2 }
1415 where
1416 plus_mod_dep r1@(m1, boot1) r2@(m2, boot2)
1417 | ASSERT2( m1 == m2, (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
1418 boot1 = r2
1419 | otherwise = r1
1420 -- If either side can "see" a non-hi-boot interface, use that
1421 -- Reusing existing tuples saves 10% of allocations on test
1422 -- perf/compiler/MultiLayerModules
1423
1424 {-
1425 ************************************************************************
1426 * *
1427 \subsection{Where from}
1428 * *
1429 ************************************************************************
1430
1431 The @WhereFrom@ type controls where the renamer looks for an interface file
1432 -}
1433
1434 data WhereFrom
1435 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
1436 | ImportBySystem -- Non user import.
1437 | ImportByPlugin -- Importing a plugin;
1438 -- See Note [Care with plugin imports] in LoadIface
1439
1440 instance Outputable WhereFrom where
1441 ppr (ImportByUser is_boot) | is_boot = text "{- SOURCE -}"
1442 | otherwise = empty
1443 ppr ImportBySystem = text "{- SYSTEM -}"
1444 ppr ImportByPlugin = text "{- PLUGIN -}"
1445
1446
1447 {- *********************************************************************
1448 * *
1449 Type signatures
1450 * *
1451 ********************************************************************* -}
1452
1453 -- These data types need to be here only because
1454 -- TcSimplify uses them, and TcSimplify is fairly
1455 -- low down in the module hierarchy
1456
1457 type TcSigFun = Name -> Maybe TcSigInfo
1458
1459 data TcSigInfo = TcIdSig TcIdSigInfo
1460 | TcPatSynSig TcPatSynInfo
1461
1462 data TcIdSigInfo -- See Note [Complete and partial type signatures]
1463 = CompleteSig -- A complete signature with no wildcards,
1464 -- so the complete polymorphic type is known.
1465 { sig_bndr :: TcId -- The polymorphic Id with that type
1466
1467 , sig_ctxt :: UserTypeCtxt -- In the case of type-class default methods,
1468 -- the Name in the FunSigCtxt is not the same
1469 -- as the TcId; the former is 'op', while the
1470 -- latter is '$dmop' or some such
1471
1472 , sig_loc :: SrcSpan -- Location of the type signature
1473 }
1474
1475 | PartialSig -- A partial type signature (i.e. includes one or more
1476 -- wildcards). In this case it doesn't make sense to give
1477 -- the polymorphic Id, because we are going to /infer/ its
1478 -- type, so we can't make the polymorphic Id ab-initio
1479 { psig_name :: Name -- Name of the function; used when report wildcards
1480 , psig_hs_ty :: LHsSigWcType GhcRn -- The original partial signature in
1481 -- HsSyn form
1482 , sig_ctxt :: UserTypeCtxt
1483 , sig_loc :: SrcSpan -- Location of the type signature
1484 }
1485
1486
1487 {- Note [Complete and partial type signatures]
1488 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1489 A type signature is partial when it contains one or more wildcards
1490 (= type holes). The wildcard can either be:
1491 * A (type) wildcard occurring in sig_theta or sig_tau. These are
1492 stored in sig_wcs.
1493 f :: Bool -> _
1494 g :: Eq _a => _a -> _a -> Bool
1495 * Or an extra-constraints wildcard, stored in sig_cts:
1496 h :: (Num a, _) => a -> a
1497
1498 A type signature is a complete type signature when there are no
1499 wildcards in the type signature, i.e. iff sig_wcs is empty and
1500 sig_extra_cts is Nothing.
1501 -}
1502
1503 data TcIdSigInst
1504 = TISI { sig_inst_sig :: TcIdSigInfo
1505
1506 , sig_inst_skols :: [(Name, TcTyVar)]
1507 -- Instantiated type and kind variables, TyVarTvs
1508 -- The Name is the Name that the renamer chose;
1509 -- but the TcTyVar may come from instantiating
1510 -- the type and hence have a different unique.
1511 -- No need to keep track of whether they are truly lexically
1512 -- scoped because the renamer has named them uniquely
1513 -- See Note [Binding scoped type variables] in TcSigs
1514 --
1515 -- NB: The order of sig_inst_skols is irrelevant
1516 -- for a CompleteSig, but for a PartialSig see
1517 -- Note [Quantified varaibles in partial type signatures]
1518
1519 , sig_inst_theta :: TcThetaType
1520 -- Instantiated theta. In the case of a
1521 -- PartialSig, sig_theta does not include
1522 -- the extra-constraints wildcard
1523
1524 , sig_inst_tau :: TcSigmaType -- Instantiated tau
1525 -- See Note [sig_inst_tau may be polymorphic]
1526
1527 -- Relevant for partial signature only
1528 , sig_inst_wcs :: [(Name, TcTyVar)]
1529 -- Like sig_inst_skols, but for /named/ wildcards (_a etc).
1530 -- The named wildcards scope over the binding, and hence
1531 -- their Names may appear in type signatures in the binding
1532
1533 , sig_inst_wcx :: Maybe TcType
1534 -- Extra-constraints wildcard to fill in, if any
1535 -- If this exists, it is surely of the form (meta_tv |> co)
1536 -- (where the co might be reflexive). This is filled in
1537 -- only from the return value of TcHsType.tcAnonWildCardOcc
1538 }
1539
1540 {- Note [sig_inst_tau may be polymorphic]
1541 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1542 Note that "sig_inst_tau" might actually be a polymorphic type,
1543 if the original function had a signature like
1544 forall a. Eq a => forall b. Ord b => ....
1545 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
1546 It happens, too! See Note [Polymorphic methods] in TcClassDcl.
1547
1548 Note [Quantified varaibles in partial type signatures]
1549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1550 Consider
1551 f :: forall a b. _ -> a -> _ -> b
1552 f (x,y) p q = q
1553
1554 Then we expect f's final type to be
1555 f :: forall {x,y}. forall a b. (x,y) -> a -> b -> b
1556
1557 Note that x,y are Inferred, and can't be use for visible type
1558 application (VTA). But a,b are Specified, and remain Specified
1559 in the final type, so we can use VTA for them. (Exception: if
1560 it turns out that a's kind mentions b we need to reorder them
1561 with scopedSort.)
1562
1563 The sig_inst_skols of the TISI from a partial signature records
1564 that original order, and is used to get the variables of f's
1565 final type in the correct order.
1566
1567
1568 Note [Wildcards in partial signatures]
1569 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1570 The wildcards in psig_wcs may stand for a type mentioning
1571 the universally-quantified tyvars of psig_ty
1572
1573 E.g. f :: forall a. _ -> a
1574 f x = x
1575 We get sig_inst_skols = [a]
1576 sig_inst_tau = _22 -> a
1577 sig_inst_wcs = [_22]
1578 and _22 in the end is unified with the type 'a'
1579
1580 Moreover the kind of a wildcard in sig_inst_wcs may mention
1581 the universally-quantified tyvars sig_inst_skols
1582 e.g. f :: t a -> t _
1583 Here we get
1584 sig_inst_skols = [k:*, (t::k ->*), (a::k)]
1585 sig_inst_tau = t a -> t _22
1586 sig_inst_wcs = [ _22::k ]
1587 -}
1588
1589 data TcPatSynInfo
1590 = TPSI {
1591 patsig_name :: Name,
1592 patsig_implicit_bndrs :: [TyVarBinder], -- Implicitly-bound kind vars (Inferred) and
1593 -- implicitly-bound type vars (Specified)
1594 -- See Note [The pattern-synonym signature splitting rule] in TcPatSyn
1595 patsig_univ_bndrs :: [TyVar], -- Bound by explicit user forall
1596 patsig_req :: TcThetaType,
1597 patsig_ex_bndrs :: [TyVar], -- Bound by explicit user forall
1598 patsig_prov :: TcThetaType,
1599 patsig_body_ty :: TcSigmaType
1600 }
1601
1602 instance Outputable TcSigInfo where
1603 ppr (TcIdSig idsi) = ppr idsi
1604 ppr (TcPatSynSig tpsi) = text "TcPatSynInfo" <+> ppr tpsi
1605
1606 instance Outputable TcIdSigInfo where
1607 ppr (CompleteSig { sig_bndr = bndr })
1608 = ppr bndr <+> dcolon <+> ppr (idType bndr)
1609 ppr (PartialSig { psig_name = name, psig_hs_ty = hs_ty })
1610 = text "psig" <+> ppr name <+> dcolon <+> ppr hs_ty
1611
1612 instance Outputable TcIdSigInst where
1613 ppr (TISI { sig_inst_sig = sig, sig_inst_skols = skols
1614 , sig_inst_theta = theta, sig_inst_tau = tau })
1615 = hang (ppr sig) 2 (vcat [ ppr skols, ppr theta <+> darrow <+> ppr tau ])
1616
1617 instance Outputable TcPatSynInfo where
1618 ppr (TPSI{ patsig_name = name}) = ppr name
1619
1620 isPartialSig :: TcIdSigInst -> Bool
1621 isPartialSig (TISI { sig_inst_sig = PartialSig {} }) = True
1622 isPartialSig _ = False
1623
1624 -- | No signature or a partial signature
1625 hasCompleteSig :: TcSigFun -> Name -> Bool
1626 hasCompleteSig sig_fn name
1627 = case sig_fn name of
1628 Just (TcIdSig (CompleteSig {})) -> True
1629 _ -> False
1630
1631
1632 {-
1633 Constraint Solver Plugins
1634 -------------------------
1635 -}
1636
1637 type TcPluginSolver = [Ct] -- given
1638 -> [Ct] -- derived
1639 -> [Ct] -- wanted
1640 -> TcPluginM TcPluginResult
1641
1642 newtype TcPluginM a = TcPluginM (EvBindsVar -> TcM a) deriving (Functor)
1643
1644 instance Applicative TcPluginM where
1645 pure x = TcPluginM (const $ pure x)
1646 (<*>) = ap
1647
1648 instance Monad TcPluginM where
1649 #if !MIN_VERSION_base(4,13,0)
1650 fail = MonadFail.fail
1651 #endif
1652 TcPluginM m >>= k =
1653 TcPluginM (\ ev -> do a <- m ev
1654 runTcPluginM (k a) ev)
1655
1656 instance MonadFail.MonadFail TcPluginM where
1657 fail x = TcPluginM (const $ fail x)
1658
1659 runTcPluginM :: TcPluginM a -> EvBindsVar -> TcM a
1660 runTcPluginM (TcPluginM m) = m
1661
1662 -- | This function provides an escape for direct access to
1663 -- the 'TcM` monad. It should not be used lightly, and
1664 -- the provided 'TcPluginM' API should be favoured instead.
1665 unsafeTcPluginTcM :: TcM a -> TcPluginM a
1666 unsafeTcPluginTcM = TcPluginM . const
1667
1668 -- | Access the 'EvBindsVar' carried by the 'TcPluginM' during
1669 -- constraint solving. Returns 'Nothing' if invoked during
1670 -- 'tcPluginInit' or 'tcPluginStop'.
1671 getEvBindsTcPluginM :: TcPluginM EvBindsVar
1672 getEvBindsTcPluginM = TcPluginM return
1673
1674
1675 data TcPlugin = forall s. TcPlugin
1676 { tcPluginInit :: TcPluginM s
1677 -- ^ Initialize plugin, when entering type-checker.
1678
1679 , tcPluginSolve :: s -> TcPluginSolver
1680 -- ^ Solve some constraints.
1681 -- TODO: WRITE MORE DETAILS ON HOW THIS WORKS.
1682
1683 , tcPluginStop :: s -> TcPluginM ()
1684 -- ^ Clean up after the plugin, when exiting the type-checker.
1685 }
1686
1687 data TcPluginResult
1688 = TcPluginContradiction [Ct]
1689 -- ^ The plugin found a contradiction.
1690 -- The returned constraints are removed from the inert set,
1691 -- and recorded as insoluble.
1692
1693 | TcPluginOk [(EvTerm,Ct)] [Ct]
1694 -- ^ The first field is for constraints that were solved.
1695 -- These are removed from the inert set,
1696 -- and the evidence for them is recorded.
1697 -- The second field contains new work, that should be processed by
1698 -- the constraint solver.
1699
1700 {- *********************************************************************
1701 * *
1702 Role annotations
1703 * *
1704 ********************************************************************* -}
1705
1706 type RoleAnnotEnv = NameEnv (LRoleAnnotDecl GhcRn)
1707
1708 mkRoleAnnotEnv :: [LRoleAnnotDecl GhcRn] -> RoleAnnotEnv
1709 mkRoleAnnotEnv role_annot_decls
1710 = mkNameEnv [ (name, ra_decl)
1711 | ra_decl <- role_annot_decls
1712 , let name = roleAnnotDeclName (unLoc ra_decl)
1713 , not (isUnboundName name) ]
1714 -- Some of the role annots will be unbound;
1715 -- we don't wish to include these
1716
1717 emptyRoleAnnotEnv :: RoleAnnotEnv
1718 emptyRoleAnnotEnv = emptyNameEnv
1719
1720 lookupRoleAnnot :: RoleAnnotEnv -> Name -> Maybe (LRoleAnnotDecl GhcRn)
1721 lookupRoleAnnot = lookupNameEnv
1722
1723 getRoleAnnots :: [Name] -> RoleAnnotEnv -> [LRoleAnnotDecl GhcRn]
1724 getRoleAnnots bndrs role_env
1725 = mapMaybe (lookupRoleAnnot role_env) bndrs