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