{-# LANGUAGE DataKinds           #-}
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE MonadComprehensions #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE ViewPatterns        #-}
{-# LANGUAGE RecursiveDo        #-}

{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}

{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998

-}

-- | Typechecking user-specified @MonoTypes@
module GHC.Tc.Gen.HsType (
        -- Type signatures
        kcClassSigType, tcClassSigType,
        tcHsSigType, tcHsSigWcType,
        tcHsPartialSigType,
        tcStandaloneKindSig,
        funsSigCtxt, addSigCtxt, pprSigCtxt,

        tcHsClsInstType,
        tcHsDeriv, tcDerivStrategy,
        tcHsTypeApp,
        UserTypeCtxt(..),
        bindImplicitTKBndrs_Tv, bindImplicitTKBndrs_Skol,
            bindImplicitTKBndrs_Q_Tv, bindImplicitTKBndrs_Q_Skol,
        bindExplicitTKBndrs_Tv, bindExplicitTKBndrs_Skol,
            bindExplicitTKBndrs_Q_Tv, bindExplicitTKBndrs_Q_Skol,

        bindOuterFamEqnTKBndrs_Q_Tv, bindOuterFamEqnTKBndrs,
        tcOuterTKBndrs, scopedSortOuter, outerTyVars, outerTyVarBndrs,
        bindOuterSigTKBndrs_Tv,
        tcExplicitTKBndrs,
        bindNamedWildCardBinders,

        -- Type checking type and class decls, and instances thereof
        bindTyClTyVars, bindTyClTyVarsAndZonk,
        tcFamTyPats,
        etaExpandAlgTyCon, tcbVisibilities,

          -- tyvars
        zonkAndScopedSort,

        -- Kind-checking types
        -- No kind generalisation, no checkValidType
        InitialKindStrategy(..),
        SAKS_or_CUSK(..),
        ContextKind(..),
        kcDeclHeader, checkForDuplicateScopedTyVars,
        tcHsLiftedType,   tcHsOpenType,
        tcHsLiftedTypeNC, tcHsOpenTypeNC,
        tcInferLHsType, tcInferLHsTypeKind, tcInferLHsTypeUnsaturated,
        tcCheckLHsType,
        tcHsContext, tcLHsPredType,

        kindGeneralizeAll,

        -- Sort-checking kinds
        tcLHsKindSig, checkDataKindSig, DataSort(..),
        checkClassKindSig,

        -- Multiplicity
        tcMult,

        -- Pattern type signatures
        tcHsPatSigType,
        HoleMode(..),

        -- Error messages
        funAppCtxt, addTyConFlavCtxt
   ) where

import GHC.Prelude hiding ( head, init, last, tail )

import GHC.Hs
import GHC.Rename.Utils
import GHC.Tc.Errors.Types
import GHC.Tc.Utils.Monad
import GHC.Tc.Types.Origin
import GHC.Tc.Types.LclEnv
import GHC.Tc.Types.Constraint
import GHC.Tc.Utils.Env
import GHC.Tc.Utils.TcMType
import GHC.Tc.Validity
import GHC.Tc.Utils.Unify
import GHC.IfaceToCore
import GHC.Tc.Solver
import GHC.Tc.Zonk.Type
import GHC.Tc.Utils.TcType
import GHC.Tc.Utils.Instantiate ( tcInstInvisibleTyBinders, tcInstInvisibleTyBindersN,
                                  tcInstInvisibleTyBinder, tcSkolemiseInvisibleBndrs,
                                  tcInstTypeBndrs )
import GHC.Tc.Zonk.TcType

import GHC.Core.Type
import GHC.Core.Predicate
import GHC.Core.TyCo.Rep
import GHC.Core.TyCo.Ppr

import GHC.Builtin.Types.Prim
import GHC.Types.Error
import GHC.Types.Name.Env
import GHC.Types.Name.Reader( lookupLocalRdrOcc )
import GHC.Types.Var
import GHC.Types.Var.Set
import GHC.Core.TyCon
import GHC.Core.ConLike
import GHC.Core.DataCon
import GHC.Core.Class
import GHC.Types.Name
import GHC.Types.Var.Env
import GHC.Builtin.Types
import GHC.Types.Basic
import GHC.Types.SrcLoc
import GHC.Types.Unique
import GHC.Types.Unique.FM
import GHC.Utils.Misc
import GHC.Types.Unique.Supply
import GHC.Utils.Outputable
import GHC.Utils.Panic
import GHC.Utils.Panic.Plain
import GHC.Builtin.Names hiding ( wildCardName )
import GHC.Driver.DynFlags
import qualified GHC.LanguageExtensions as LangExt

import GHC.Data.FastString
import GHC.Data.List.Infinite ( Infinite (..) )
import qualified GHC.Data.List.Infinite as Inf
import GHC.Data.List.SetOps
import GHC.Data.Maybe
import GHC.Data.Bag( unitBag )

import Data.Function ( on )
import Data.List.NonEmpty ( NonEmpty(..), nonEmpty )
import qualified Data.List.NonEmpty as NE
import Data.List ( mapAccumL )
import Control.Monad
import Data.Tuple( swap )

{-
        ----------------------------
                General notes
        ----------------------------

Unlike with expressions, type-checking types both does some checking and
desugars at the same time. This is necessary because we often want to perform
equality checks on the types right away, and it would be incredibly painful
to do this on un-desugared types. Luckily, desugared types are close enough
to HsTypes to make the error messages sane.

During type-checking, we perform as little validity checking as possible.
Generally, after type-checking, you will want to do validity checking, say
with GHC.Tc.Validity.checkValidType.

Validity checking
~~~~~~~~~~~~~~~~~
Some of the validity check could in principle be done by the kind checker,
but not all:

- During desugaring, we normalise by expanding type synonyms.  Only
  after this step can we check things like type-synonym saturation
  e.g.  type T k = k Int
        type S a = a
  Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
  and then S is saturated.  This is a GHC extension.

- Similarly, also a GHC extension, we look through synonyms before complaining
  about the form of a class or instance declaration

- Ambiguity checks involve functional dependencies

Also, in a mutually recursive group of types, we can't look at the TyCon until we've
finished building the loop.  So to keep things simple, we postpone most validity
checking until step (3).

%************************************************************************
%*                                                                      *
              Check types AND do validity checking
*                                                                      *
************************************************************************

Note [Keeping implicitly quantified variables in order]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When the user implicitly quantifies over variables (say, in a type
signature), we need to come up with some ordering on these variables.
This is done by bumping the TcLevel, bringing the tyvars into scope,
and then type-checking the thing_inside. The constraints are all
wrapped in an implication, which is then solved. Finally, we can
zonk all the binders and then order them with scopedSort.

It's critical to solve before zonking and ordering in order to uncover
any unifications. You might worry that this eager solving could cause
trouble elsewhere. I don't think it will. Because it will solve only
in an increased TcLevel, it can't unify anything that was mentioned
elsewhere. Additionally, we require that the order of implicitly
quantified variables is manifest by the scope of these variables, so
we're not going to learn more information later that will help order
these variables.

Note [Recipe for checking a signature]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Kind-checking a user-written signature requires several steps:

 0. Bump the TcLevel
 1.   Bind any lexically-scoped type variables.
 2.   Generate constraints.
 3. Solve constraints.
 4. Sort any implicitly-bound variables into dependency order
 5. Promote tyvars and/or kind-generalize.
 6. Zonk.
 7. Check validity.

Very similar steps also apply when kind-checking a type or class
declaration.

The general pattern looks something like this.  (But NB every
specific instance varies in one way or another!)

    do { (tclvl, wanted, (spec_tkvs, ty))
              <- pushLevelAndSolveEqualitiesX "tc_top_lhs_type" $
                 bindImplicitTKBndrs_Skol sig_vars              $
                 <kind-check the type>

       ; spec_tkvs <- zonkAndScopedSort spec_tkvs

       ; reportUnsolvedEqualities skol_info spec_tkvs tclvl wanted

       ; let ty1 = mkSpecForAllTys spec_tkvs ty
       ; kvs <- kindGeneralizeAll ty1

       ; final_ty <- zonkTcTypeToType (mkInfForAllTys kvs ty1)

       ; checkValidType final_ty

This pattern is repeated many times in GHC.Tc.Gen.HsType,
GHC.Tc.Gen.Sig, and GHC.Tc.TyCl, with variations.  In more detail:

* pushLevelAndSolveEqualitiesX (Step 0, step 3) bumps the TcLevel,
  calls the thing inside to generate constraints, solves those
  constraints as much as possible, returning the residual unsolved
  constraints in 'wanted'.

* bindImplicitTKBndrs_Skol (Step 1) binds the user-specified type
  variables E.g.  when kind-checking f :: forall a. F a -> a we must
  bring 'a' into scope before kind-checking (F a -> a)

* zonkAndScopedSort (Step 4) puts those user-specified variables in
  the dependency order.  (For "implicit" variables the order is no
  user-specified.  E.g.  forall (a::k1) (b::k2). blah k1 and k2 are
  implicitly brought into scope.

* reportUnsolvedEqualities (Step 3 continued) reports any unsolved
  equalities, carefully wrapping them in an implication that binds the
  skolems.  We can't do that in pushLevelAndSolveEqualitiesX because
  that function doesn't have access to the skolems.

* kindGeneralize (Step 5). See Note [Kind generalisation]

* The final zonkTcTypeToType must happen after promoting/generalizing,
  because promoting and generalizing fill in metavariables.


Doing Step 3 (constraint solving) eagerly (rather than building an
implication constraint and solving later) is necessary for several
reasons:

* Exactly as for Solver.simplifyInfer: when generalising, we solve all
  the constraints we can so that we don't have to quantify over them
  or, since we don't quantify over constraints in kinds, float them
  and inhibit generalisation.

* Most signatures also bring implicitly quantified variables into
  scope, and solving is necessary to get these in the right order
  (Step 4) see Note [Keeping implicitly quantified variables in
  order]).

Note [Kind generalisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Step 5 of Note [Recipe for checking a signature], namely
kind-generalisation, is done by
    kindGeneraliseAll
    kindGeneraliseSome
    kindGeneraliseNone

Here, we have to deal with the fact that metatyvars generated in the
type will have a bumped TcLevel, because explicit foralls raise the
TcLevel. To avoid these variables from ever being visible in the
surrounding context, we must obey the following dictum:

  Every metavariable in a type must either be
    (A) generalized, or
    (B) promoted, or        See Note [Promotion in signatures]
    (C) a cause to error    See Note [Naughty quantification candidates]
                            in GHC.Tc.Utils.TcMType

There are three steps (look at kindGeneraliseSome):

1. candidateQTyVarsOfType finds the free variables of the type or kind,
   to generalise

2. filterConstrainedCandidates filters out candidates that appear
   in the unsolved 'wanteds', and promotes the ones that get filtered out
   thereby.

3. quantifyTyVars quantifies the remaining type variables

The kindGeneralize functions do not require pre-zonking; they zonk as they
go.

kindGeneraliseAll specialises for the case where step (2) is vacuous.
kindGeneraliseNone specialises for the case where we do no quantification,
but we must still promote.

If you are actually doing kind-generalization, you need to bump the
level before generating constraints, as we will only generalize
variables with a TcLevel higher than the ambient one.
Hence the "pushLevel" in pushLevelAndSolveEqualities.

Note [Promotion in signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If an unsolved metavariable in a signature is not generalized
(because we're not generalizing the construct -- e.g., pattern
sig -- or because the metavars are constrained -- see kindGeneralizeSome)
we need to promote to maintain (WantedInv) of Note [TcLevel invariants]
in GHC.Tc.Utils.TcType. Note that promotion is identical in effect to generalizing
and the reinstantiating with a fresh metavariable at the current level.
So in some sense, we generalize *all* variables, but then re-instantiate
some of them.

Here is an example of why we must promote:
  foo (x :: forall a. a -> Proxy b) = ...

In the pattern signature, `b` is unbound, and will thus be brought into
scope. We do not know its kind: it will be assigned kappa[2]. Note that
kappa is at TcLevel 2, because it is invented under a forall. (A priori,
the kind kappa might depend on `a`, so kappa rightly has a higher TcLevel
than the surrounding context.) This kappa cannot be solved for while checking
the pattern signature (which is not kind-generalized). When we are checking
the *body* of foo, though, we need to unify the type of x with the argument
type of bar. At this point, the ambient TcLevel is 1, and spotting a
metavariable with level 2 would violate the (WantedInv) invariant of
Note [TcLevel invariants]. So, instead of kind-generalizing,
we promote the metavariable to level 1. This is all done in kindGeneralizeNone.

-}

funsSigCtxt :: [LocatedN Name] -> UserTypeCtxt
-- Returns FunSigCtxt, with no redundant-context-reporting,
-- form a list of located names
funsSigCtxt :: [GenLocated SrcSpanAnnN Name] -> UserTypeCtxt
funsSigCtxt (L SrcSpanAnnN
_ Name
name1 : [GenLocated SrcSpanAnnN Name]
_) = Name -> ReportRedundantConstraints -> UserTypeCtxt
FunSigCtxt Name
name1 ReportRedundantConstraints
NoRRC
funsSigCtxt []              = String -> UserTypeCtxt
forall a. HasCallStack => String -> a
panic String
"funSigCtxt"

addSigCtxt :: Outputable hs_ty => UserTypeCtxt -> LocatedA hs_ty -> TcM a -> TcM a
addSigCtxt :: forall hs_ty a.
Outputable hs_ty =>
UserTypeCtxt -> LocatedA hs_ty -> TcM a -> TcM a
addSigCtxt UserTypeCtxt
ctxt LocatedA hs_ty
hs_ty TcM a
thing_inside
  = SrcSpan -> TcM a -> TcM a
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan (LocatedA hs_ty -> SrcSpan
forall a e. GenLocated (SrcSpanAnn' a) e -> SrcSpan
getLocA LocatedA hs_ty
hs_ty) (TcM a -> TcM a) -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$
    SDoc -> TcM a -> TcM a
forall a. SDoc -> TcM a -> TcM a
addErrCtxt (UserTypeCtxt -> LocatedA hs_ty -> SDoc
forall hs_ty.
Outputable hs_ty =>
UserTypeCtxt -> LocatedA hs_ty -> SDoc
pprSigCtxt UserTypeCtxt
ctxt LocatedA hs_ty
hs_ty) (TcM a -> TcM a) -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$
    TcM a
thing_inside

pprSigCtxt :: Outputable hs_ty => UserTypeCtxt -> LocatedA hs_ty -> SDoc
-- (pprSigCtxt ctxt <extra> <type>)
-- prints    In the type signature for 'f':
--              f :: <type>
-- The <extra> is either empty or "the ambiguity check for"
pprSigCtxt :: forall hs_ty.
Outputable hs_ty =>
UserTypeCtxt -> LocatedA hs_ty -> SDoc
pprSigCtxt UserTypeCtxt
ctxt LocatedA hs_ty
hs_ty
  | Just Name
n <- UserTypeCtxt -> Maybe Name
isSigMaybe UserTypeCtxt
ctxt
  = SDoc -> Int -> SDoc -> SDoc
hang (String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"In the type signature:")
       Int
2 (Name -> SDoc
forall a. OutputableBndr a => a -> SDoc
pprPrefixOcc Name
n SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> LocatedA hs_ty -> SDoc
forall a. Outputable a => a -> SDoc
ppr LocatedA hs_ty
hs_ty)

  | Bool
otherwise
  = SDoc -> Int -> SDoc -> SDoc
hang (String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"In" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> UserTypeCtxt -> SDoc
pprUserTypeCtxt UserTypeCtxt
ctxt SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> SDoc
forall doc. IsLine doc => doc
colon)
       Int
2 (LocatedA hs_ty -> SDoc
forall a. Outputable a => a -> SDoc
ppr LocatedA hs_ty
hs_ty)

tcHsSigWcType :: UserTypeCtxt -> LHsSigWcType GhcRn -> TcM Type
-- This one is used when we have a LHsSigWcType, but in
-- a place where wildcards aren't allowed. The renamer has
-- already checked this, so we can simply ignore it.
tcHsSigWcType :: UserTypeCtxt -> LHsSigWcType GhcRn -> TcM Type
tcHsSigWcType UserTypeCtxt
ctxt LHsSigWcType GhcRn
sig_ty = UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
tcHsSigType UserTypeCtxt
ctxt (LHsSigWcType GhcRn -> LHsSigType GhcRn
forall pass. LHsSigWcType pass -> LHsSigType pass
dropWildCards LHsSigWcType GhcRn
sig_ty)

kcClassSigType :: [LocatedN Name] -> LHsSigType GhcRn -> TcM ()
-- This is a special form of tcClassSigType that is used during the
-- kind-checking phase to infer the kind of class variables. Cf. tc_lhs_sig_type.
-- Importantly, this does *not* kind-generalize. Consider
--   class SC f where
--     meth :: forall a (x :: f a). Proxy x -> ()
-- When instantiating Proxy with kappa, we must unify kappa := f a. But we're
-- still working out the kind of f, and thus f a will have a coercion in it.
-- Coercions may block unification (Note [Equalities with incompatible kinds] in
-- GHC.Tc.Solver.Equality, wrinkle (EIK2)) and so we fail to unify. If we try to
-- kind-generalize, we'll end up promoting kappa to the top level (because
-- kind-generalization is normally done right before adding a binding to the context),
-- and then we can't set kappa := f a, because a is local.
kcClassSigType :: [GenLocated SrcSpanAnnN Name] -> LHsSigType GhcRn -> TcM ()
kcClassSigType [GenLocated SrcSpanAnnN Name]
names
    sig_ty :: LHsSigType GhcRn
sig_ty@(L SrcSpanAnnA
_ (HsSig { sig_bndrs :: forall pass. HsSigType pass -> HsOuterSigTyVarBndrs pass
sig_bndrs = HsOuterSigTyVarBndrs GhcRn
hs_outer_bndrs, sig_body :: forall pass. HsSigType pass -> LHsType pass
sig_body = LHsType GhcRn
hs_ty }))
  = UserTypeCtxt
-> GenLocated SrcSpanAnnA (HsSigType GhcRn) -> TcM () -> TcM ()
forall hs_ty a.
Outputable hs_ty =>
UserTypeCtxt -> LocatedA hs_ty -> TcM a -> TcM a
addSigCtxt ([GenLocated SrcSpanAnnN Name] -> UserTypeCtxt
funsSigCtxt [GenLocated SrcSpanAnnN Name]
names) LHsSigType GhcRn
GenLocated SrcSpanAnnA (HsSigType GhcRn)
sig_ty (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
    do { (HsOuterTyVarBndrs Specificity GhcTc, Type)
_ <- HsOuterSigTyVarBndrs GhcRn
-> TcM Type -> TcM (HsOuterTyVarBndrs Specificity GhcTc, Type)
forall a.
HsOuterSigTyVarBndrs GhcRn
-> TcM a -> TcM (HsOuterTyVarBndrs Specificity GhcTc, a)
bindOuterSigTKBndrs_Tv HsOuterSigTyVarBndrs GhcRn
hs_outer_bndrs    (TcM Type -> TcM (HsOuterTyVarBndrs Specificity GhcTc, Type))
-> TcM Type -> TcM (HsOuterTyVarBndrs Specificity GhcTc, Type)
forall a b. (a -> b) -> a -> b
$
              LHsType GhcRn -> Type -> TcM Type
tcLHsType LHsType GhcRn
hs_ty Type
liftedTypeKind
       ; () -> TcM ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return () }

tcClassSigType :: [LocatedN Name] -> LHsSigType GhcRn -> TcM Type
-- Does not do validity checking
tcClassSigType :: [GenLocated SrcSpanAnnN Name] -> LHsSigType GhcRn -> TcM Type
tcClassSigType [GenLocated SrcSpanAnnN Name]
names LHsSigType GhcRn
sig_ty
  = UserTypeCtxt
-> GenLocated SrcSpanAnnA (HsSigType GhcRn) -> TcM Type -> TcM Type
forall hs_ty a.
Outputable hs_ty =>
UserTypeCtxt -> LocatedA hs_ty -> TcM a -> TcM a
addSigCtxt UserTypeCtxt
sig_ctxt LHsSigType GhcRn
GenLocated SrcSpanAnnA (HsSigType GhcRn)
sig_ty (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
    do { SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo SkolemInfoAnon
skol_info_anon
       ; (Implication
implic, Type
ty) <- SkolemInfo
-> LHsSigType GhcRn -> ContextKind -> TcM (Implication, Type)
tc_lhs_sig_type SkolemInfo
skol_info LHsSigType GhcRn
sig_ty (Type -> ContextKind
TheKind Type
liftedTypeKind)
       ; Implication -> TcM ()
emitImplication Implication
implic
       ; Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Type
ty }
       -- Do not zonk-to-Type, nor perform a validity check
       -- We are in a knot with the class and associated types
       -- Zonking and validity checking is done by tcClassDecl
       --
       -- No need to fail here if the type has an error:
       --   If we're in the kind-checking phase, the solveEqualities
       --     in kcTyClGroup catches the error
       --   If we're in the type-checking phase, the solveEqualities
       --     in tcClassDecl1 gets it
       -- Failing fast here degrades the error message in, e.g., tcfail135:
       --   class Foo f where
       --     baa :: f a -> f
       -- If we fail fast, we're told that f has kind `k1` when we wanted `*`.
       -- It should be that f has kind `k2 -> *`, but we never get a chance
       -- to run the solver where the kind of f is touchable. This is
       -- painfully delicate.
  where
    sig_ctxt :: UserTypeCtxt
sig_ctxt = [GenLocated SrcSpanAnnN Name] -> UserTypeCtxt
funsSigCtxt [GenLocated SrcSpanAnnN Name]
names
    skol_info_anon :: SkolemInfoAnon
skol_info_anon = UserTypeCtxt -> SkolemInfoAnon
SigTypeSkol UserTypeCtxt
sig_ctxt

tcHsSigType :: UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
-- Does validity checking
-- See Note [Recipe for checking a signature]
tcHsSigType :: UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
tcHsSigType UserTypeCtxt
ctxt LHsSigType GhcRn
sig_ty
  = UserTypeCtxt
-> GenLocated SrcSpanAnnA (HsSigType GhcRn) -> TcM Type -> TcM Type
forall hs_ty a.
Outputable hs_ty =>
UserTypeCtxt -> LocatedA hs_ty -> TcM a -> TcM a
addSigCtxt UserTypeCtxt
ctxt LHsSigType GhcRn
GenLocated SrcSpanAnnA (HsSigType GhcRn)
sig_ty (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
    do { String -> SDoc -> TcM ()
traceTc String
"tcHsSigType {" (GenLocated SrcSpanAnnA (HsSigType GhcRn) -> SDoc
forall a. Outputable a => a -> SDoc
ppr LHsSigType GhcRn
GenLocated SrcSpanAnnA (HsSigType GhcRn)
sig_ty)
       ; SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo SkolemInfoAnon
skol_info
          -- Generalise here: see Note [Kind generalisation]
       ; (Implication
implic, Type
ty) <- SkolemInfo
-> LHsSigType GhcRn -> ContextKind -> TcM (Implication, Type)
tc_lhs_sig_type SkolemInfo
skol_info LHsSigType GhcRn
sig_ty  (UserTypeCtxt -> ContextKind
expectedKindInCtxt UserTypeCtxt
ctxt)

       -- Float out constraints, failing fast if not possible
       -- See Note [Failure in local type signatures] in GHC.Tc.Solver
       ; String -> SDoc -> TcM ()
traceTc String
"tcHsSigType 2" (Implication -> SDoc
forall a. Outputable a => a -> SDoc
ppr Implication
implic)
       ; WantedConstraints -> TcM ()
simplifyAndEmitFlatConstraints (Bag Implication -> WantedConstraints
mkImplicWC (Implication -> Bag Implication
forall a. a -> Bag a
unitBag Implication
implic))

       ; Type
ty <- ZonkM Type -> TcM Type
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM Type -> TcM Type) -> ZonkM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ Type -> ZonkM Type
zonkTcType Type
ty
       ; UserTypeCtxt -> Type -> TcM ()
checkValidType UserTypeCtxt
ctxt Type
ty
       ; String -> SDoc -> TcM ()
traceTc String
"end tcHsSigType }" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty)
       ; Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Type
ty }
  where
    skol_info :: SkolemInfoAnon
skol_info = UserTypeCtxt -> SkolemInfoAnon
SigTypeSkol UserTypeCtxt
ctxt

tc_lhs_sig_type :: SkolemInfo -> LHsSigType GhcRn
               -> ContextKind -> TcM (Implication, TcType)
-- Kind-checks/desugars an 'LHsSigType',
--   solve equalities,
--   and then kind-generalizes.
-- This will never emit constraints, as it uses solveEqualities internally.
-- No validity checking or zonking
-- Returns also an implication for the unsolved constraints
tc_lhs_sig_type :: SkolemInfo
-> LHsSigType GhcRn -> ContextKind -> TcM (Implication, Type)
tc_lhs_sig_type SkolemInfo
skol_info full_hs_ty :: LHsSigType GhcRn
full_hs_ty@(L SrcSpanAnnA
loc (HsSig { sig_bndrs :: forall pass. HsSigType pass -> HsOuterSigTyVarBndrs pass
sig_bndrs = HsOuterSigTyVarBndrs GhcRn
hs_outer_bndrs
                                                   , sig_body :: forall pass. HsSigType pass -> LHsType pass
sig_body = LHsType GhcRn
hs_ty })) ContextKind
ctxt_kind
  = SrcSpanAnnA -> TcM (Implication, Type) -> TcM (Implication, Type)
forall ann a. SrcSpanAnn' ann -> TcRn a -> TcRn a
setSrcSpanA SrcSpanAnnA
loc (TcM (Implication, Type) -> TcM (Implication, Type))
-> TcM (Implication, Type) -> TcM (Implication, Type)
forall a b. (a -> b) -> a -> b
$
    do { (TcLevel
tc_lvl, WantedConstraints
wanted, (Type
exp_kind, (HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs, Type
ty)))
              <- String
-> TcM (Type, (HsOuterTyVarBndrs Specificity GhcTc, Type))
-> TcM
     (TcLevel, WantedConstraints,
      (Type, (HsOuterTyVarBndrs Specificity GhcTc, Type)))
forall a. String -> TcM a -> TcM (TcLevel, WantedConstraints, a)
pushLevelAndSolveEqualitiesX String
"tc_lhs_sig_type" (TcM (Type, (HsOuterTyVarBndrs Specificity GhcTc, Type))
 -> TcM
      (TcLevel, WantedConstraints,
       (Type, (HsOuterTyVarBndrs Specificity GhcTc, Type))))
-> TcM (Type, (HsOuterTyVarBndrs Specificity GhcTc, Type))
-> TcM
     (TcLevel, WantedConstraints,
      (Type, (HsOuterTyVarBndrs Specificity GhcTc, Type)))
forall a b. (a -> b) -> a -> b
$
                 -- See Note [Failure in local type signatures]
                 do { Type
exp_kind <- ContextKind -> TcM Type
newExpectedKind ContextKind
ctxt_kind
                          -- See Note [Escaping kind in type signatures]
                    ; (HsOuterTyVarBndrs Specificity GhcTc, Type)
stuff <- SkolemInfo
-> HsOuterSigTyVarBndrs GhcRn
-> TcM Type
-> TcM (HsOuterTyVarBndrs Specificity GhcTc, Type)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemInfo
-> HsOuterTyVarBndrs flag GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
tcOuterTKBndrs SkolemInfo
skol_info HsOuterSigTyVarBndrs GhcRn
hs_outer_bndrs (TcM Type -> TcM (HsOuterTyVarBndrs Specificity GhcTc, Type))
-> TcM Type -> TcM (HsOuterTyVarBndrs Specificity GhcTc, Type)
forall a b. (a -> b) -> a -> b
$
                               LHsType GhcRn -> Type -> TcM Type
tcLHsType LHsType GhcRn
hs_ty Type
exp_kind
                    ; (Type, (HsOuterTyVarBndrs Specificity GhcTc, Type))
-> TcM (Type, (HsOuterTyVarBndrs Specificity GhcTc, Type))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
exp_kind, (HsOuterTyVarBndrs Specificity GhcTc, Type)
stuff) }

       -- Default any unconstrained variables free in the kind
       -- See Note [Escaping kind in type signatures]
       ; CandidatesQTvs
exp_kind_dvs <- Type -> TcM CandidatesQTvs
candidateQTyVarsOfType Type
exp_kind
       ; CandidatesQTvs
-> (TidyEnv -> ZonkM (TidyEnv, UninferrableTyVarCtx)) -> TcM ()
doNotQuantifyTyVars CandidatesQTvs
exp_kind_dvs (Type -> TidyEnv -> ZonkM (TidyEnv, UninferrableTyVarCtx)
err_ctx Type
exp_kind)

       ; String -> SDoc -> TcM ()
traceTc String
"tc_lhs_sig_type" (HsOuterSigTyVarBndrs GhcRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsOuterSigTyVarBndrs GhcRn
hs_outer_bndrs SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ HsOuterTyVarBndrs Specificity GhcTc -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs)
       ; HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs <- HsOuterTyVarBndrs Specificity GhcTc
-> TcM (HsOuterTyVarBndrs Specificity GhcTc)
forall flag.
HsOuterTyVarBndrs flag GhcTc -> TcM (HsOuterTyVarBndrs flag GhcTc)
scopedSortOuter HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs

       ; let [VarBndr TcTyVar Specificity]
outer_tv_bndrs :: [InvisTVBinder] = HsOuterTyVarBndrs Specificity GhcTc
-> [VarBndr TcTyVar Specificity]
outerTyVarBndrs HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs
             ty1 :: Type
ty1 = [VarBndr TcTyVar Specificity] -> Type -> Type
mkInvisForAllTys [VarBndr TcTyVar Specificity]
outer_tv_bndrs Type
ty
       ; [TcTyVar]
kvs <- SkolemInfo -> WantedConstraints -> Type -> TcM [TcTyVar]
kindGeneralizeSome SkolemInfo
skol_info WantedConstraints
wanted Type
ty1

       -- Build an implication for any as-yet-unsolved kind equalities
       -- See Note [Skolem escape in type signatures]
       ; Implication
implic <- SkolemInfoAnon
-> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM Implication
buildTvImplication (SkolemInfo -> SkolemInfoAnon
getSkolemInfo SkolemInfo
skol_info) [TcTyVar]
kvs TcLevel
tc_lvl WantedConstraints
wanted

       ; (Implication, Type) -> TcM (Implication, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Implication
implic, [TcTyVar] -> Type -> Type
mkInfForAllTys [TcTyVar]
kvs Type
ty1) }
  where
    err_ctx :: Type -> TidyEnv -> ZonkM (TidyEnv, UninferrableTyVarCtx)
err_ctx Type
exp_kind TidyEnv
tidy_env
      = do { (TidyEnv
tidy_env2, Type
exp_kind) <- TidyEnv -> Type -> ZonkM (TidyEnv, Type)
zonkTidyTcType TidyEnv
tidy_env Type
exp_kind
           ; (TidyEnv, UninferrableTyVarCtx)
-> ZonkM (TidyEnv, UninferrableTyVarCtx)
forall a. a -> ZonkM a
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
tidy_env2, Type -> LHsSigType GhcRn -> UninferrableTyVarCtx
UninfTyCtx_Sig Type
exp_kind LHsSigType GhcRn
full_hs_ty) }



{- Note [Escaping kind in type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider kind-checking the signature for `foo` (#19495):
  type family T (r :: RuntimeRep) :: TYPE r

  foo :: forall (r :: RuntimeRep). T r
  foo = ...

We kind-check the type with expected kind `TYPE delta` (see newExpectedKind),
where `delta :: RuntimeRep` is as-yet unknown. (We can't use `TYPE LiftedRep`
because we allow signatures like `foo :: Int#`.)

Suppose we are at level L currently.  We do this
  * pushLevelAndSolveEqualitiesX: moves to level L+1
  * newExpectedKind: allocates delta{L+1}
  * tcOuterTKBndrs: pushes the level again to L+2, binds skolem r{L+2}
  * kind-check the body (T r) :: TYPE delta{L+1}

Then
* We can't unify delta{L+1} with r{L+2}.
  And rightly so: skolem would escape.

* If delta{L+1} is unified with some-kind{L}, that is fine.
  This can happen
      \(x::a) -> let y :: a; y = x in ...(x :: Int#)...
  Here (x :: a :: TYPE gamma) is in the environment when we check
  the signature y::a.  We unify delta := gamma, and all is well.

* If delta{L+1} is unconstrained, we /must not/ quantify over it!
  E.g. Consider f :: Any   where Any :: forall k. k
  We kind-check this with expected kind TYPE kappa. We get
      Any @(TYPE kappa) :: TYPE kappa
  We don't want to generalise to     forall k. Any @k
  because that is ill-kinded: the kind of the body of the forall,
  (Any @k :: k) mentions the bound variable k.

  Instead we want to default it to LiftedRep.

  An alternative would be to promote it, similar to the monomorphism
  restriction, but the MR is pretty confusing.  Defaulting seems better

How does that defaulting happen?  Well, since we /currently/ default
RuntimeRep variables during generalisation, it'll happen in
kindGeneralize. But in principle we might allow generalisation over
RuntimeRep variables in future.  Moreover, what if we had
   kappa{L+1} := F alpha{L+1}
where F :: Type -> RuntimeRep.   Now it's alpha that is free in the kind
and it /won't/ be defaulted.

So we use doNotQuantifyTyVars to either default the free vars of
exp_kind (if possible), or error (if not).

Note [Skolem escape in type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tcHsSigType is tricky.  Consider (T11142)
  foo :: forall b. (forall k (a :: k). SameKind a b) -> ()
This is ill-kinded because of a nested skolem-escape.

That will show up as an un-solvable constraint in the implication
returned by buildTvImplication in tc_lhs_sig_type.  See Note [Skolem
escape prevention] in GHC.Tc.Utils.TcType for why it is unsolvable
(the unification variable for b's kind is untouchable).

Then, in GHC.Tc.Solver.simplifyAndEmitFlatConstraints (called from tcHsSigType)
we'll try to float out the constraint, be unable to do so, and fail.
See GHC.Tc.Solver Note [Failure in local type signatures] for more
detail on this.

The separation between tcHsSigType and tc_lhs_sig_type is because
tcClassSigType wants to use the latter, but *not* fail fast, because
there are skolems from the class decl which are in scope; but it's fine
not to because tcClassDecl1 has a solveEqualities wrapped around all
the tcClassSigType calls.

That's why tcHsSigType does simplifyAndEmitFlatConstraints (which
fails fast) but tcClassSigType just does emitImplication (which does
not).  Ugh.

c.f. see also Note [Skolem escape and forall-types]. The difference
is that we don't need to simplify at a forall type, only at the
top level of a signature.
-}

-- Does validity checking and zonking.
tcStandaloneKindSig :: LStandaloneKindSig GhcRn -> TcM (Name, Kind)
tcStandaloneKindSig :: LStandaloneKindSig GhcRn -> TcM (Name, Type)
tcStandaloneKindSig (L SrcSpanAnnA
_ (StandaloneKindSig XStandaloneKindSig GhcRn
_ (L SrcSpanAnnN
_ Name
name) LHsSigType GhcRn
ksig))
  = UserTypeCtxt
-> GenLocated SrcSpanAnnA (HsSigType GhcRn)
-> TcM (Name, Type)
-> TcM (Name, Type)
forall hs_ty a.
Outputable hs_ty =>
UserTypeCtxt -> LocatedA hs_ty -> TcM a -> TcM a
addSigCtxt UserTypeCtxt
ctxt LHsSigType GhcRn
GenLocated SrcSpanAnnA (HsSigType GhcRn)
ksig (TcM (Name, Type) -> TcM (Name, Type))
-> TcM (Name, Type) -> TcM (Name, Type)
forall a b. (a -> b) -> a -> b
$
    do { Type
kind <- TypeOrKind -> UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
tc_top_lhs_type TypeOrKind
KindLevel UserTypeCtxt
ctxt LHsSigType GhcRn
ksig
       ; UserTypeCtxt -> Type -> TcM ()
checkValidType UserTypeCtxt
ctxt Type
kind
       ; (Name, Type) -> TcM (Name, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Name
name, Type
kind) }
  where
   ctxt :: UserTypeCtxt
ctxt = Name -> UserTypeCtxt
StandaloneKindSigCtxt Name
name

tcTopLHsType :: UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
tcTopLHsType :: UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
tcTopLHsType UserTypeCtxt
ctxt LHsSigType GhcRn
lsig_ty
  = TcM Type -> TcM Type
forall r. TcM r -> TcM r
checkNoErrs (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$  -- Fail eagerly to avoid follow-on errors.  We are at
                   -- top level so these constraints will never be solved later.
    TypeOrKind -> UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
tc_top_lhs_type TypeOrKind
TypeLevel UserTypeCtxt
ctxt LHsSigType GhcRn
lsig_ty

tc_top_lhs_type :: TypeOrKind -> UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
-- tc_top_lhs_type is used for kind-checking top-level LHsSigTypes where
--   we want to fully solve /all/ equalities, and report errors
-- Does zonking, but not validity checking because it's used
--   for things (like deriving and instances) that aren't
--   ordinary types
-- Used for both types and kinds
tc_top_lhs_type :: TypeOrKind -> UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
tc_top_lhs_type TypeOrKind
tyki UserTypeCtxt
ctxt (L SrcSpanAnnA
loc sig_ty :: HsSigType GhcRn
sig_ty@(HsSig { sig_bndrs :: forall pass. HsSigType pass -> HsOuterSigTyVarBndrs pass
sig_bndrs = HsOuterSigTyVarBndrs GhcRn
hs_outer_bndrs
                                               , sig_body :: forall pass. HsSigType pass -> LHsType pass
sig_body = LHsType GhcRn
body }))
  = SrcSpanAnnA -> TcM Type -> TcM Type
forall ann a. SrcSpanAnn' ann -> TcRn a -> TcRn a
setSrcSpanA SrcSpanAnnA
loc (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
    do { String -> SDoc -> TcM ()
traceTc String
"tc_top_lhs_type {" (HsSigType GhcRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsSigType GhcRn
sig_ty)
       ; SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo SkolemInfoAnon
skol_info_anon
       ; (TcLevel
tclvl, WantedConstraints
wanted, (HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs, Type
ty))
              <- String
-> TcM (HsOuterTyVarBndrs Specificity GhcTc, Type)
-> TcM
     (TcLevel, WantedConstraints,
      (HsOuterTyVarBndrs Specificity GhcTc, Type))
forall a. String -> TcM a -> TcM (TcLevel, WantedConstraints, a)
pushLevelAndSolveEqualitiesX String
"tc_top_lhs_type"    (TcM (HsOuterTyVarBndrs Specificity GhcTc, Type)
 -> TcM
      (TcLevel, WantedConstraints,
       (HsOuterTyVarBndrs Specificity GhcTc, Type)))
-> TcM (HsOuterTyVarBndrs Specificity GhcTc, Type)
-> TcM
     (TcLevel, WantedConstraints,
      (HsOuterTyVarBndrs Specificity GhcTc, Type))
forall a b. (a -> b) -> a -> b
$
                 SkolemInfo
-> HsOuterSigTyVarBndrs GhcRn
-> TcM Type
-> TcM (HsOuterTyVarBndrs Specificity GhcTc, Type)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemInfo
-> HsOuterTyVarBndrs flag GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
tcOuterTKBndrs SkolemInfo
skol_info HsOuterSigTyVarBndrs GhcRn
hs_outer_bndrs (TcM Type -> TcM (HsOuterTyVarBndrs Specificity GhcTc, Type))
-> TcM Type -> TcM (HsOuterTyVarBndrs Specificity GhcTc, Type)
forall a b. (a -> b) -> a -> b
$
                 do { Type
kind <- ContextKind -> TcM Type
newExpectedKind (UserTypeCtxt -> ContextKind
expectedKindInCtxt UserTypeCtxt
ctxt)
                    ; TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type (TypeOrKind -> TcTyMode
mkMode TypeOrKind
tyki) LHsType GhcRn
body Type
kind }

       ; HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs <- HsOuterTyVarBndrs Specificity GhcTc
-> TcM (HsOuterTyVarBndrs Specificity GhcTc)
forall flag.
HsOuterTyVarBndrs flag GhcTc -> TcM (HsOuterTyVarBndrs flag GhcTc)
scopedSortOuter HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs
       ; let outer_tv_bndrs :: [VarBndr TcTyVar Specificity]
outer_tv_bndrs = HsOuterTyVarBndrs Specificity GhcTc
-> [VarBndr TcTyVar Specificity]
outerTyVarBndrs HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs
             ty1 :: Type
ty1 = [VarBndr TcTyVar Specificity] -> Type -> Type
mkInvisForAllTys [VarBndr TcTyVar Specificity]
outer_tv_bndrs Type
ty

       ; [TcTyVar]
kvs <- SkolemInfo -> Type -> TcM [TcTyVar]
kindGeneralizeAll SkolemInfo
skol_info Type
ty1  -- "All" because it's a top-level type
       ; SkolemInfo -> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM ()
reportUnsolvedEqualities SkolemInfo
skol_info [TcTyVar]
kvs TcLevel
tclvl WantedConstraints
wanted

       ; Type
final_ty <- ZonkFlexi -> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) Type -> TcM Type
forall (m :: * -> *) b. MonadIO m => ZonkFlexi -> ZonkT m b -> m b
initZonkEnv ZonkFlexi
DefaultFlexi
                   (ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) Type -> TcM Type)
-> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ Type -> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) Type
zonkTcTypeToTypeX ([TcTyVar] -> Type -> Type
mkInfForAllTys [TcTyVar]
kvs Type
ty1)
       ; String -> SDoc -> TcM ()
traceTc String
"tc_top_lhs_type }" ([SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [HsSigType GhcRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsSigType GhcRn
sig_ty, Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
final_ty])
       ; Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Type
final_ty }
  where
    skol_info_anon :: SkolemInfoAnon
skol_info_anon = UserTypeCtxt -> SkolemInfoAnon
SigTypeSkol UserTypeCtxt
ctxt

-----------------
tcHsDeriv :: LHsSigType GhcRn -> TcM ([TyVar], Class, [Type], [Kind])
-- Like tcHsSigType, but for the ...deriving( C t1 ty2 ) clause
-- Returns the C, [ty1, ty2, and the kinds of C's remaining arguments
-- E.g.    class C (a::*) (b::k->k)
--         data T a b = ... deriving( C Int )
--    returns ([k], C, [k, Int], [k->k])
-- Return values are fully zonked
tcHsDeriv :: LHsSigType GhcRn -> TcM ([TcTyVar], Class, [Type], [Type])
tcHsDeriv LHsSigType GhcRn
hs_ty
  = do { Type
ty <- UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
tcTopLHsType UserTypeCtxt
DerivClauseCtxt LHsSigType GhcRn
hs_ty
       ; let ([TcTyVar]
tvs, Type
pred)    = Type -> ([TcTyVar], Type)
splitForAllTyCoVars Type
ty
             ([Scaled Type]
kind_args, Type
_) = Type -> ([Scaled Type], Type)
splitFunTys (HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
pred)
       ; case Type -> Maybe (Class, [Type])
getClassPredTys_maybe Type
pred of
           Just (Class
cls, [Type]
tys) -> ([TcTyVar], Class, [Type], [Type])
-> TcM ([TcTyVar], Class, [Type], [Type])
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([TcTyVar]
tvs, Class
cls, [Type]
tys, (Scaled Type -> Type) -> [Scaled Type] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map Scaled Type -> Type
forall a. Scaled a -> a
scaledThing [Scaled Type]
kind_args)
           Maybe (Class, [Type])
Nothing -> TcRnMessage -> TcM ([TcTyVar], Class, [Type], [Type])
forall a. TcRnMessage -> TcM a
failWithTc (TcRnMessage -> TcM ([TcTyVar], Class, [Type], [Type]))
-> TcRnMessage -> TcM ([TcTyVar], Class, [Type], [Type])
forall a b. (a -> b) -> a -> b
$ LHsSigType GhcRn -> TcRnMessage
TcRnIllegalDerivingItem LHsSigType GhcRn
hs_ty }

-- | Typecheck a deriving strategy. For most deriving strategies, this is a
-- no-op, but for the @via@ strategy, this requires typechecking the @via@ type.
tcDerivStrategy :: Maybe (LDerivStrategy GhcRn)
                   -- ^ The deriving strategy
                -> TcM (Maybe (LDerivStrategy GhcTc), [TcTyVar])
                   -- ^ The typechecked deriving strategy and the tyvars that it binds
                   -- (if using 'ViaStrategy').
tcDerivStrategy :: Maybe (LDerivStrategy GhcRn)
-> TcM (Maybe (LDerivStrategy GhcTc), [TcTyVar])
tcDerivStrategy Maybe (LDerivStrategy GhcRn)
mb_lds
  = case Maybe (LDerivStrategy GhcRn)
mb_lds of
      Maybe (LDerivStrategy GhcRn)
Nothing -> Maybe (GenLocated (SrcAnn NoEpAnns) (DerivStrategy GhcTc))
-> TcM
     (Maybe (GenLocated (SrcAnn NoEpAnns) (DerivStrategy GhcTc)),
      [TcTyVar])
forall ds a. ds -> TcM (ds, [a])
boring_case Maybe (GenLocated (SrcAnn NoEpAnns) (DerivStrategy GhcTc))
forall a. Maybe a
Nothing
      Just (L SrcAnn NoEpAnns
loc DerivStrategy GhcRn
ds) ->
        SrcAnn NoEpAnns
-> TcM (Maybe (LDerivStrategy GhcTc), [TcTyVar])
-> TcM (Maybe (LDerivStrategy GhcTc), [TcTyVar])
forall ann a. SrcSpanAnn' ann -> TcRn a -> TcRn a
setSrcSpanA SrcAnn NoEpAnns
loc (TcM (Maybe (LDerivStrategy GhcTc), [TcTyVar])
 -> TcM (Maybe (LDerivStrategy GhcTc), [TcTyVar]))
-> TcM (Maybe (LDerivStrategy GhcTc), [TcTyVar])
-> TcM (Maybe (LDerivStrategy GhcTc), [TcTyVar])
forall a b. (a -> b) -> a -> b
$ do
          (DerivStrategy GhcTc
ds', [TcTyVar]
tvs) <- DerivStrategy GhcRn -> TcM (DerivStrategy GhcTc, [TcTyVar])
tc_deriv_strategy DerivStrategy GhcRn
ds
          (Maybe (GenLocated (SrcAnn NoEpAnns) (DerivStrategy GhcTc)),
 [TcTyVar])
-> TcM
     (Maybe (GenLocated (SrcAnn NoEpAnns) (DerivStrategy GhcTc)),
      [TcTyVar])
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (GenLocated (SrcAnn NoEpAnns) (DerivStrategy GhcTc)
-> Maybe (GenLocated (SrcAnn NoEpAnns) (DerivStrategy GhcTc))
forall a. a -> Maybe a
Just (SrcAnn NoEpAnns
-> DerivStrategy GhcTc
-> GenLocated (SrcAnn NoEpAnns) (DerivStrategy GhcTc)
forall l e. l -> e -> GenLocated l e
L SrcAnn NoEpAnns
loc DerivStrategy GhcTc
ds'), [TcTyVar]
tvs)
  where
    tc_deriv_strategy :: DerivStrategy GhcRn
                      -> TcM (DerivStrategy GhcTc, [TyVar])
    tc_deriv_strategy :: DerivStrategy GhcRn -> TcM (DerivStrategy GhcTc, [TcTyVar])
tc_deriv_strategy (StockStrategy    XStockStrategy GhcRn
_) = DerivStrategy GhcTc -> TcM (DerivStrategy GhcTc, [TcTyVar])
forall ds a. ds -> TcM (ds, [a])
boring_case (XStockStrategy GhcTc -> DerivStrategy GhcTc
forall pass. XStockStrategy pass -> DerivStrategy pass
StockStrategy    XStockStrategy GhcTc
NoExtField
noExtField)
    tc_deriv_strategy (AnyclassStrategy XAnyClassStrategy GhcRn
_) = DerivStrategy GhcTc -> TcM (DerivStrategy GhcTc, [TcTyVar])
forall ds a. ds -> TcM (ds, [a])
boring_case (XAnyClassStrategy GhcTc -> DerivStrategy GhcTc
forall pass. XAnyClassStrategy pass -> DerivStrategy pass
AnyclassStrategy XAnyClassStrategy GhcTc
NoExtField
noExtField)
    tc_deriv_strategy (NewtypeStrategy  XNewtypeStrategy GhcRn
_) = DerivStrategy GhcTc -> TcM (DerivStrategy GhcTc, [TcTyVar])
forall ds a. ds -> TcM (ds, [a])
boring_case (XNewtypeStrategy GhcTc -> DerivStrategy GhcTc
forall pass. XNewtypeStrategy pass -> DerivStrategy pass
NewtypeStrategy  XNewtypeStrategy GhcTc
NoExtField
noExtField)
    tc_deriv_strategy (ViaStrategy XViaStrategy GhcRn
hs_sig)
      = do { Type
ty <- UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
tcTopLHsType UserTypeCtxt
DerivClauseCtxt XViaStrategy GhcRn
LHsSigType GhcRn
hs_sig
             -- rec {..}: see Note [Keeping SkolemInfo inside a SkolemTv]
             --           in GHC.Tc.Utils.TcType
           ; rec { ([TcTyVar]
via_tvs, Type
via_pred) <- SkolemInfoAnon -> Type -> TcM ([TcTyVar], Type)
tcSkolemiseInvisibleBndrs (Type -> SkolemInfoAnon
DerivSkol Type
via_pred) Type
ty }
           ; (DerivStrategy GhcTc, [TcTyVar])
-> TcM (DerivStrategy GhcTc, [TcTyVar])
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (XViaStrategy GhcTc -> DerivStrategy GhcTc
forall pass. XViaStrategy pass -> DerivStrategy pass
ViaStrategy XViaStrategy GhcTc
Type
via_pred, [TcTyVar]
via_tvs) }

    boring_case :: ds -> TcM (ds, [a])
    boring_case :: forall ds a. ds -> TcM (ds, [a])
boring_case ds
ds = (ds, [a]) -> IOEnv (Env TcGblEnv TcLclEnv) (ds, [a])
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ds
ds, [])

tcHsClsInstType :: UserTypeCtxt    -- InstDeclCtxt or SpecInstCtxt
                -> LHsSigType GhcRn
                -> TcM Type
-- Like tcHsSigType, but for a class instance declaration
tcHsClsInstType :: UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
tcHsClsInstType UserTypeCtxt
user_ctxt LHsSigType GhcRn
hs_inst_ty
  = SrcSpan -> TcM Type -> TcM Type
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan (GenLocated SrcSpanAnnA (HsSigType GhcRn) -> SrcSpan
forall a e. GenLocated (SrcSpanAnn' a) e -> SrcSpan
getLocA LHsSigType GhcRn
GenLocated SrcSpanAnnA (HsSigType GhcRn)
hs_inst_ty) (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
    do { Type
inst_ty <- UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
tcTopLHsType UserTypeCtxt
user_ctxt LHsSigType GhcRn
hs_inst_ty
       ; UserTypeCtxt -> LHsSigType GhcRn -> Type -> TcM ()
checkValidInstance UserTypeCtxt
user_ctxt LHsSigType GhcRn
hs_inst_ty Type
inst_ty
       ; Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Type
inst_ty }

----------------------------------------------
-- | Type-check a visible type application
tcHsTypeApp :: LHsWcType GhcRn -> Kind -> TcM Type
-- See Note [Recipe for checking a signature] in GHC.Tc.Gen.HsType
tcHsTypeApp :: LHsWcType GhcRn -> Type -> TcM Type
tcHsTypeApp LHsWcType GhcRn
wc_ty Type
kind
  | HsWC { hswc_ext :: forall pass thing. HsWildCardBndrs pass thing -> XHsWC pass thing
hswc_ext = XHsWC GhcRn (LHsType GhcRn)
sig_wcs, hswc_body :: forall pass thing. HsWildCardBndrs pass thing -> thing
hswc_body = LHsType GhcRn
hs_ty } <- LHsWcType GhcRn
wc_ty
  = do { TcTyMode
mode <- TypeOrKind -> HoleMode -> TcM TcTyMode
mkHoleMode TypeOrKind
TypeLevel HoleMode
HM_VTA
                 -- HM_VTA: See Note [Wildcards in visible type application]
       ; Type
ty <- LHsType GhcRn -> TcM Type -> TcM Type
forall a. LHsType GhcRn -> TcM a -> TcM a
addTypeCtxt LHsType GhcRn
hs_ty                  (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
               String -> TcM Type -> TcM Type
forall a. String -> TcM a -> TcM a
solveEqualities String
"tcHsTypeApp" (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
               -- We are looking at a user-written type, very like a
               -- signature so we want to solve its equalities right now
               HsQTvsRn -> ([(Name, TcTyVar)] -> TcM Type) -> TcM Type
forall a. HsQTvsRn -> ([(Name, TcTyVar)] -> TcM a) -> TcM a
bindNamedWildCardBinders HsQTvsRn
XHsWC GhcRn (LHsType GhcRn)
sig_wcs (([(Name, TcTyVar)] -> TcM Type) -> TcM Type)
-> ([(Name, TcTyVar)] -> TcM Type) -> TcM Type
forall a b. (a -> b) -> a -> b
$ \ [(Name, TcTyVar)]
_ ->
               TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
hs_ty Type
kind

       -- We do not kind-generalize type applications: we just
       -- instantiate with exactly what the user says.
       -- See Note [No generalization in type application]
       -- We still must call kindGeneralizeNone, though, according
       -- to Note [Recipe for checking a signature]
       ; Type -> TcM ()
kindGeneralizeNone Type
ty
       ; Type
ty <- ZonkM Type -> TcM Type
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM Type -> TcM Type) -> ZonkM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ Type -> ZonkM Type
zonkTcType Type
ty
       ; UserTypeCtxt -> Type -> TcM ()
checkValidType UserTypeCtxt
TypeAppCtxt Type
ty
       ; Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Type
ty }

{- Note [Wildcards in visible type application]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A HsWildCardBndrs's hswc_ext now only includes /named/ wildcards, so
any unnamed wildcards stay unchanged in hswc_body.  When called in
tcHsTypeApp, tcCheckLHsType will call emitAnonTypeHole
on these anonymous wildcards. However, this would trigger
error/warning when an anonymous wildcard is passed in as a visible type
argument, which we do not want because users should be able to write
@_ to skip a instantiating a type variable variable without fuss. The
solution is to switch the PartialTypeSignatures flags here to let the
typechecker know that it's checking a '@_' and do not emit hole
constraints on it.  See related Note [Wildcards in visible kind
application] and Note [The wildcard story for types] in GHC.Hs.Type

Ugh!

Note [No generalization in type application]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We do not kind-generalize type applications. Imagine

  id @(Proxy Nothing)

If we kind-generalized, we would get

  id @(forall {k}. Proxy @(Maybe k) (Nothing @k))

which is very sneakily impredicative instantiation.

There is also the possibility of mentioning a wildcard
(`id @(Proxy _)`), which definitely should not be kind-generalized.

-}

tcFamTyPats :: TyCon
            -> HsTyPats GhcRn                -- Patterns
            -> TcM (TcType, TcKind)          -- (lhs_type, lhs_kind)
-- Check the LHS of a type/data family instance
-- e.g.   type instance F ty1 .. tyn = ...
-- Used for both type and data families
tcFamTyPats :: TyCon -> HsTyPats GhcRn -> TcM (Type, Type)
tcFamTyPats TyCon
fam_tc HsTyPats GhcRn
hs_pats
  = do { String -> SDoc -> TcM ()
traceTc String
"tcFamTyPats {" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
fam_tc, String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"arity:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Int -> SDoc
forall a. Outputable a => a -> SDoc
ppr Int
fam_arity ]

       ; TcTyMode
mode <- TypeOrKind -> HoleMode -> TcM TcTyMode
mkHoleMode TypeOrKind
TypeLevel HoleMode
HM_FamPat
                 -- HM_FamPat: See Note [Wildcards in family instances] in
                 -- GHC.Rename.Module
       ; let fun_ty :: Type
fun_ty = TyCon -> [Type] -> Type
mkTyConApp TyCon
fam_tc []
       ; (Type
fam_app, Type
res_kind) <- TcTyMode
-> LHsType GhcRn -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
tcInferTyApps TcTyMode
mode LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
lhs_fun Type
fun_ty HsTyPats GhcRn
hs_pats

       -- Hack alert: see Note [tcFamTyPats: zonking the result kind]
       ; Type
res_kind <- ZonkM Type -> TcM Type
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM Type -> TcM Type) -> ZonkM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ Type -> ZonkM Type
zonkTcType Type
res_kind

       ; String -> SDoc -> TcM ()
traceTc String
"End tcFamTyPats }" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
fam_tc, String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"res_kind:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
res_kind ]

       ; (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
fam_app, Type
res_kind) }
  where
    fam_name :: Name
fam_name  = TyCon -> Name
tyConName TyCon
fam_tc
    fam_arity :: Int
fam_arity = TyCon -> Int
tyConArity TyCon
fam_tc
    lhs_fun :: GenLocated SrcSpanAnnA (HsType GhcRn)
lhs_fun   = HsType GhcRn -> GenLocated SrcSpanAnnA (HsType GhcRn)
forall a an. a -> LocatedAn an a
noLocA (XTyVar GhcRn -> PromotionFlag -> LIdP GhcRn -> HsType GhcRn
forall pass.
XTyVar pass -> PromotionFlag -> LIdP pass -> HsType pass
HsTyVar XTyVar GhcRn
EpAnn [AddEpAnn]
forall a. EpAnn a
noAnn PromotionFlag
NotPromoted (Name -> GenLocated SrcSpanAnnN Name
forall a an. a -> LocatedAn an a
noLocA Name
fam_name))

{- Note [tcFamTyPats: zonking the result kind]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (#19250)
    F :: forall k. k -> k
    type instance F (x :: Constraint) = ()

The tricky point is this:
  is that () an empty type tuple (() :: Type), or
  an empty constraint tuple (() :: Constraint)?
We work this out in a hacky way, by looking at the expected kind:
see Note [Inferring tuple kinds].

In this case, we kind-check the RHS using the kind gotten from the LHS:
see the call to tcCheckLHsType in tcTyFamInstEqnGuts in GHC.Tc.Tycl.

But we want the kind from the LHS to be /zonked/, so that when
kind-checking the RHS (tcCheckLHsType) we can "see" what we learned
from kind-checking the LHS (tcFamTyPats).  In our example above, the
type of the LHS is just `kappa` (by instantiating the forall k), but
then we learn (from x::Constraint) that kappa ~ Constraint.  We want
that info when kind-checking the RHS.

Easy solution: just zonk that return kind.  Of course this won't help
if there is lots of type-family reduction to do, but it works fine in
common cases.
-}


{-
************************************************************************
*                                                                      *
            The main kind checker: no validity checks here
*                                                                      *
************************************************************************
-}

---------------------------
tcHsOpenType, tcHsLiftedType,
  tcHsOpenTypeNC, tcHsLiftedTypeNC :: LHsType GhcRn -> TcM TcType
-- Used for type signatures
-- Do not do validity checking
tcHsOpenType :: LHsType GhcRn -> TcM Type
tcHsOpenType   LHsType GhcRn
hs_ty = LHsType GhcRn -> TcM Type -> TcM Type
forall a. LHsType GhcRn -> TcM a -> TcM a
addTypeCtxt LHsType GhcRn
hs_ty (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ LHsType GhcRn -> TcM Type
tcHsOpenTypeNC LHsType GhcRn
hs_ty
tcHsLiftedType :: LHsType GhcRn -> TcM Type
tcHsLiftedType LHsType GhcRn
hs_ty = LHsType GhcRn -> TcM Type -> TcM Type
forall a. LHsType GhcRn -> TcM a -> TcM a
addTypeCtxt LHsType GhcRn
hs_ty (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ LHsType GhcRn -> TcM Type
tcHsLiftedTypeNC LHsType GhcRn
hs_ty

tcHsOpenTypeNC :: LHsType GhcRn -> TcM Type
tcHsOpenTypeNC   LHsType GhcRn
hs_ty = do { Type
ek <- TcM Type
newOpenTypeKind; LHsType GhcRn -> Type -> TcM Type
tcLHsType LHsType GhcRn
hs_ty Type
ek }
tcHsLiftedTypeNC :: LHsType GhcRn -> TcM Type
tcHsLiftedTypeNC LHsType GhcRn
hs_ty = LHsType GhcRn -> Type -> TcM Type
tcLHsType LHsType GhcRn
hs_ty Type
liftedTypeKind

-- Like tcHsType, but takes an expected kind
tcCheckLHsType :: LHsType GhcRn -> ContextKind -> TcM TcType
tcCheckLHsType :: LHsType GhcRn -> ContextKind -> TcM Type
tcCheckLHsType LHsType GhcRn
hs_ty ContextKind
exp_kind
  = LHsType GhcRn -> TcM Type -> TcM Type
forall a. LHsType GhcRn -> TcM a -> TcM a
addTypeCtxt LHsType GhcRn
hs_ty (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
    do { Type
ek <- ContextKind -> TcM Type
newExpectedKind ContextKind
exp_kind
       ; LHsType GhcRn -> Type -> TcM Type
tcLHsType LHsType GhcRn
hs_ty Type
ek }

tcInferLHsType :: LHsType GhcRn -> TcM TcType
tcInferLHsType :: LHsType GhcRn -> TcM Type
tcInferLHsType LHsType GhcRn
hs_ty
  = do { (Type
ty,Type
_kind) <- LHsType GhcRn -> TcM (Type, Type)
tcInferLHsTypeKind LHsType GhcRn
hs_ty
       ; Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Type
ty }

tcInferLHsTypeKind :: LHsType GhcRn -> TcM (TcType, TcKind)
-- Called from outside: set the context
-- Eagerly instantiate any trailing invisible binders
tcInferLHsTypeKind :: LHsType GhcRn -> TcM (Type, Type)
tcInferLHsTypeKind lhs_ty :: LHsType GhcRn
lhs_ty@(L SrcSpanAnnA
loc HsType GhcRn
hs_ty)
  = LHsType GhcRn -> TcM (Type, Type) -> TcM (Type, Type)
forall a. LHsType GhcRn -> TcM a -> TcM a
addTypeCtxt LHsType GhcRn
lhs_ty (TcM (Type, Type) -> TcM (Type, Type))
-> TcM (Type, Type) -> TcM (Type, Type)
forall a b. (a -> b) -> a -> b
$
    SrcSpanAnnA -> TcM (Type, Type) -> TcM (Type, Type)
forall ann a. SrcSpanAnn' ann -> TcRn a -> TcRn a
setSrcSpanA SrcSpanAnnA
loc    (TcM (Type, Type) -> TcM (Type, Type))
-> TcM (Type, Type) -> TcM (Type, Type)
forall a b. (a -> b) -> a -> b
$  -- Cover the tcInstInvisibleTyBinders
    do { (Type
res_ty, Type
res_kind) <- TcTyMode -> HsType GhcRn -> TcM (Type, Type)
tc_infer_hs_type TcTyMode
typeLevelMode HsType GhcRn
hs_ty
       ; Type -> Type -> TcM (Type, Type)
tcInstInvisibleTyBinders Type
res_ty Type
res_kind }
  -- See Note [Do not always instantiate eagerly in types]

-- Used to check the argument of GHCi :kind
-- Allow and report wildcards, e.g. :kind T _
-- Do not saturate family applications: see Note [Dealing with :kind]
-- Does not instantiate eagerly; See Note [Do not always instantiate eagerly in types]
tcInferLHsTypeUnsaturated :: LHsType GhcRn -> TcM (TcType, TcKind)
tcInferLHsTypeUnsaturated :: LHsType GhcRn -> TcM (Type, Type)
tcInferLHsTypeUnsaturated LHsType GhcRn
hs_ty
  = LHsType GhcRn -> TcM (Type, Type) -> TcM (Type, Type)
forall a. LHsType GhcRn -> TcM a -> TcM a
addTypeCtxt LHsType GhcRn
hs_ty (TcM (Type, Type) -> TcM (Type, Type))
-> TcM (Type, Type) -> TcM (Type, Type)
forall a b. (a -> b) -> a -> b
$
    do { TcTyMode
mode <- TypeOrKind -> HoleMode -> TcM TcTyMode
mkHoleMode TypeOrKind
TypeLevel HoleMode
HM_Sig  -- Allow and report holes
       ; case HsType GhcRn -> Maybe (LHsType GhcRn, HsTyPats GhcRn)
splitHsAppTys (GenLocated SrcSpanAnnA (HsType GhcRn) -> HsType GhcRn
forall l e. GenLocated l e -> e
unLoc LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
hs_ty) of
           Just (LHsType GhcRn
hs_fun_ty, HsTyPats GhcRn
hs_args)
              -> do { (Type
fun_ty, Type
_ki) <- TcTyMode -> LHsType GhcRn -> TcM (Type, Type)
tcInferTyAppHead TcTyMode
mode LHsType GhcRn
hs_fun_ty
                    ; TcTyMode
-> LHsType GhcRn -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
tcInferTyApps_nosat TcTyMode
mode LHsType GhcRn
hs_fun_ty Type
fun_ty HsTyPats GhcRn
hs_args }
                      -- Notice the 'nosat'; do not instantiate trailing
                      -- invisible arguments of a type family.
                      -- See Note [Dealing with :kind]
           Maybe (LHsType GhcRn, HsTyPats GhcRn)
Nothing -> TcTyMode -> LHsType GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode LHsType GhcRn
hs_ty }

{- Note [Dealing with :kind]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this GHCi command
  ghci> type family F :: Either j k
  ghci> :kind F
  F :: forall {j,k}. Either j k

We will only get the 'forall' if we /refrain/ from saturating those
invisible binders. But generally we /do/ saturate those invisible
binders (see tcInferTyApps), and we want to do so for nested application
even in GHCi.  Consider for example (#16287)
  ghci> type family F :: k
  ghci> data T :: (forall k. k) -> Type
  ghci> :kind T F
We want to reject this. It's just at the very top level that we want
to switch off saturation.

So tcInferLHsTypeUnsaturated does a little special case for top level
applications.  Actually the common case is a bare variable, as above.

Note [Do not always instantiate eagerly in types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Terms are eagerly instantiated. This means that if you say

  x = id

then `id` gets instantiated to have type alpha -> alpha. The variable
alpha is then unconstrained and regeneralized. But we cannot do this
in types, as we have no type-level lambda. So, when we are sure
that we will not want to regeneralize later -- because we are done
checking a type, for example -- we can instantiate. But we do not
instantiate at variables, nor do we in tcInferLHsTypeUnsaturated,
which is used by :kind in GHCi.

************************************************************************
*                                                                      *
      Type-checking modes
*                                                                      *
************************************************************************

The kind-checker is parameterised by a TcTyMode, which contains some
information about where we're checking a type.

The renamer issues errors about what it can. All errors issued here must
concern things that the renamer can't handle.

-}

tcMult :: HsArrow GhcRn -> TcM Mult
tcMult :: HsArrow GhcRn -> TcM Type
tcMult HsArrow GhcRn
hc = TcTyMode -> HsArrow GhcRn -> TcM Type
tc_mult TcTyMode
typeLevelMode HsArrow GhcRn
hc

-- | Info about the context in which we're checking a type. Currently,
-- differentiates only between types and kinds, but this will likely
-- grow, at least to include the distinction between patterns and
-- not-patterns.
--
-- To find out where the mode is used, search for 'mode_tyki'
--
-- This data type is purely local, not exported from this module
data TcTyMode
  = TcTyMode { TcTyMode -> TypeOrKind
mode_tyki :: TypeOrKind
             , TcTyMode -> HoleInfo
mode_holes :: HoleInfo   }

-- See Note [Levels for wildcards]
-- Nothing <=> no wildcards expected
type HoleInfo = Maybe (TcLevel, HoleMode)

-- HoleMode says how to treat the occurrences
-- of anonymous wildcards; see tcAnonWildCardOcc
data HoleMode = HM_Sig      -- Partial type signatures: f :: _ -> Int
              | HM_FamPat   -- Family instances: F _ Int = Bool
              | HM_VTA      -- Visible type and kind application:
                            --   f @(Maybe _)
                            --   Maybe @(_ -> _)
              | HM_TyAppPat -- Visible type applications in patterns:
                            --   foo (Con @_ @t x) = ...
                            --   case x of Con @_ @t v -> ...

mkMode :: TypeOrKind -> TcTyMode
mkMode :: TypeOrKind -> TcTyMode
mkMode TypeOrKind
tyki = TcTyMode { mode_tyki :: TypeOrKind
mode_tyki = TypeOrKind
tyki, mode_holes :: HoleInfo
mode_holes = HoleInfo
forall a. Maybe a
Nothing }

typeLevelMode, kindLevelMode :: TcTyMode
-- These modes expect no wildcards (holes) in the type
kindLevelMode :: TcTyMode
kindLevelMode = TypeOrKind -> TcTyMode
mkMode TypeOrKind
KindLevel
typeLevelMode :: TcTyMode
typeLevelMode = TypeOrKind -> TcTyMode
mkMode TypeOrKind
TypeLevel

mkHoleMode :: TypeOrKind -> HoleMode -> TcM TcTyMode
mkHoleMode :: TypeOrKind -> HoleMode -> TcM TcTyMode
mkHoleMode TypeOrKind
tyki HoleMode
hm
  = do { TcLevel
lvl <- TcM TcLevel
getTcLevel
       ; TcTyMode -> TcM TcTyMode
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TcTyMode { mode_tyki :: TypeOrKind
mode_tyki  = TypeOrKind
tyki
                          , mode_holes :: HoleInfo
mode_holes = (TcLevel, HoleMode) -> HoleInfo
forall a. a -> Maybe a
Just (TcLevel
lvl,HoleMode
hm) }) }

instance Outputable HoleMode where
  ppr :: HoleMode -> SDoc
ppr HoleMode
HM_Sig      = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"HM_Sig"
  ppr HoleMode
HM_FamPat   = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"HM_FamPat"
  ppr HoleMode
HM_VTA      = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"HM_VTA"
  ppr HoleMode
HM_TyAppPat = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"HM_TyAppPat"

instance Outputable TcTyMode where
  ppr :: TcTyMode -> SDoc
ppr (TcTyMode { mode_tyki :: TcTyMode -> TypeOrKind
mode_tyki = TypeOrKind
tyki, mode_holes :: TcTyMode -> HoleInfo
mode_holes = HoleInfo
hm })
    = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"TcTyMode" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc
braces ([SDoc] -> SDoc
forall doc. IsLine doc => [doc] -> doc
sep [ TypeOrKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr TypeOrKind
tyki SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> SDoc
forall doc. IsLine doc => doc
comma
                                      , HoleInfo -> SDoc
forall a. Outputable a => a -> SDoc
ppr HoleInfo
hm ])

{-
Note [Bidirectional type checking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In expressions, whenever we see a polymorphic identifier, say `id`, we are
free to instantiate it with metavariables, knowing that we can always
re-generalize with type-lambdas when necessary. For example:

  rank2 :: (forall a. a -> a) -> ()
  x = rank2 id

When checking the body of `x`, we can instantiate `id` with a metavariable.
Then, when we're checking the application of `rank2`, we notice that we really
need a polymorphic `id`, and then re-generalize over the unconstrained
metavariable.

In types, however, we're not so lucky, because *we cannot re-generalize*!
There is no lambda. So, we must be careful only to instantiate at the last
possible moment, when we're sure we're never going to want the lost polymorphism
again. This is done in calls to tcInstInvisibleTyBinders.

To implement this behavior, we use bidirectional type checking, where we
explicitly think about whether we know the kind of the type we're checking
or not. Note that there is a difference between not knowing a kind and
knowing a metavariable kind: the metavariables are TauTvs, and cannot become
forall-quantified kinds. Previously (before dependent types), there were
no higher-rank kinds, and so we could instantiate early and be sure that
no types would have polymorphic kinds, and so we could always assume that
the kind of a type was a fresh metavariable. Not so anymore, thus the
need for two algorithms.

For HsType forms that can never be kind-polymorphic, we implement only the
"down" direction, where we safely assume a metavariable kind. For HsType forms
that *can* be kind-polymorphic, we implement just the "up" (functions with
"infer" in their name) version, as we gain nothing by also implementing the
"down" version.

Note [Future-proofing the type checker]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As discussed in Note [Bidirectional type checking], each HsType form is
handled in *either* tc_infer_hs_type *or* tc_hs_type. These functions
are mutually recursive, so that either one can work for any type former.
But, we want to make sure that our pattern-matches are complete. So,
we have a bunch of repetitive code just so that we get warnings if we're
missing any patterns.

-}

------------------------------------------
-- | Check and desugar a type, returning the core type and its
-- possibly-polymorphic kind. Much like 'tcInferRho' at the expression
-- level.
tc_infer_lhs_type :: TcTyMode -> LHsType GhcRn -> TcM (TcType, TcKind)
tc_infer_lhs_type :: TcTyMode -> LHsType GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode (L SrcSpanAnnA
span HsType GhcRn
ty)
  = SrcSpanAnnA -> TcM (Type, Type) -> TcM (Type, Type)
forall ann a. SrcSpanAnn' ann -> TcRn a -> TcRn a
setSrcSpanA SrcSpanAnnA
span (TcM (Type, Type) -> TcM (Type, Type))
-> TcM (Type, Type) -> TcM (Type, Type)
forall a b. (a -> b) -> a -> b
$
    TcTyMode -> HsType GhcRn -> TcM (Type, Type)
tc_infer_hs_type TcTyMode
mode HsType GhcRn
ty

---------------------------
-- | Call 'tc_infer_hs_type' and check its result against an expected kind.
tc_infer_hs_type_ek :: HasDebugCallStack => TcTyMode -> HsType GhcRn -> TcKind -> TcM TcType
tc_infer_hs_type_ek :: HasDebugCallStack => TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_infer_hs_type_ek TcTyMode
mode HsType GhcRn
hs_ty Type
ek
  = do { (Type
ty, Type
k) <- TcTyMode -> HsType GhcRn -> TcM (Type, Type)
tc_infer_hs_type TcTyMode
mode HsType GhcRn
hs_ty
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
hs_ty Type
ty Type
k Type
ek }

---------------------------
-- | Infer the kind of a type and desugar. This is the "up" type-checker,
-- as described in Note [Bidirectional type checking]
tc_infer_hs_type :: TcTyMode -> HsType GhcRn -> TcM (TcType, TcKind)

tc_infer_hs_type :: TcTyMode -> HsType GhcRn -> TcM (Type, Type)
tc_infer_hs_type TcTyMode
mode (HsParTy XParTy GhcRn
_ LHsType GhcRn
t)
  = TcTyMode -> LHsType GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode LHsType GhcRn
t

tc_infer_hs_type TcTyMode
mode HsType GhcRn
ty
  | Just (LHsType GhcRn
hs_fun_ty, HsTyPats GhcRn
hs_args) <- HsType GhcRn -> Maybe (LHsType GhcRn, HsTyPats GhcRn)
splitHsAppTys HsType GhcRn
ty
  = do { (Type
fun_ty, Type
_ki) <- TcTyMode -> LHsType GhcRn -> TcM (Type, Type)
tcInferTyAppHead TcTyMode
mode LHsType GhcRn
hs_fun_ty
       ; TcTyMode
-> LHsType GhcRn -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
tcInferTyApps TcTyMode
mode LHsType GhcRn
hs_fun_ty Type
fun_ty HsTyPats GhcRn
hs_args }

tc_infer_hs_type TcTyMode
mode (HsKindSig XKindSig GhcRn
_ LHsType GhcRn
ty LHsType GhcRn
sig)
  = do { let mode' :: TcTyMode
mode' = TcTyMode
mode { mode_tyki = KindLevel }
       ; Type
sig' <- TcTyMode -> UserTypeCtxt -> LHsType GhcRn -> TcM Type
tc_lhs_kind_sig TcTyMode
mode' UserTypeCtxt
KindSigCtxt LHsType GhcRn
sig
                 -- We must typecheck the kind signature, and solve all
                 -- its equalities etc; from this point on we may do
                 -- things like instantiate its foralls, so it needs
                 -- to be fully determined (#14904)
       ; String -> SDoc -> TcM ()
traceTc String
"tc_infer_hs_type:sig" (GenLocated SrcSpanAnnA (HsType GhcRn) -> SDoc
forall a. Outputable a => a -> SDoc
ppr LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
ty SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
sig')
       ; Type
ty' <- LHsType GhcRn -> TcM Type -> TcM Type
forall a. LHsType GhcRn -> TcM a -> TcM a
tcAddKindSigPlaceholders LHsType GhcRn
sig (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
                TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
ty Type
sig'
       ; (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
ty', Type
sig') }

-- HsSpliced is an annotation produced by 'GHC.Rename.Splice.rnSpliceType' to communicate
-- the splice location to the typechecker. Here we skip over it in order to have
-- the same kind inferred for a given expression whether it was produced from
-- splices or not.
--
-- See Note [Delaying modFinalizers in untyped splices].
tc_infer_hs_type TcTyMode
mode (HsSpliceTy (HsUntypedSpliceTop ThModFinalizers
_ GenLocated SrcSpanAnnA (HsType GhcRn)
ty) HsUntypedSplice GhcRn
_)
  = TcTyMode -> LHsType GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
ty

tc_infer_hs_type TcTyMode
_ (HsSpliceTy (HsUntypedSpliceNested Name
n) HsUntypedSplice GhcRn
s) = String -> SDoc -> TcM (Type, Type)
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"tc_infer_hs_type: invalid nested splice" (Bool -> Maybe Name -> HsUntypedSplice GhcRn -> SDoc
forall (p :: Pass).
OutputableBndrId p =>
Bool -> Maybe Name -> HsUntypedSplice (GhcPass p) -> SDoc
pprUntypedSplice Bool
True (Name -> Maybe Name
forall a. a -> Maybe a
Just Name
n) HsUntypedSplice GhcRn
s)

tc_infer_hs_type TcTyMode
mode (HsDocTy XDocTy GhcRn
_ LHsType GhcRn
ty LHsDoc GhcRn
_) = TcTyMode -> LHsType GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode LHsType GhcRn
ty

-- See Note [Typechecking HsCoreTys]
tc_infer_hs_type TcTyMode
_ (XHsType XXType GhcRn
ty)
  = do TcLclEnv
env <- TcRnIf TcGblEnv TcLclEnv TcLclEnv
forall gbl lcl. TcRnIf gbl lcl lcl
getLclEnv
       -- Raw uniques since we go from NameEnv to TvSubstEnv.
       let subst_prs :: [(Unique, TcTyVar)]
           subst_prs :: [(Unique, TcTyVar)]
subst_prs = [ (Name -> Unique
forall a. Uniquable a => a -> Unique
getUnique Name
nm, TcTyVar
tv)
                       | ATyVar Name
nm TcTyVar
tv <- NameEnv TcTyThing -> [TcTyThing]
forall a. NameEnv a -> [a]
nonDetNameEnvElts (TcLclEnv -> NameEnv TcTyThing
getLclEnvTypeEnv TcLclEnv
env) ]
           subst :: Subst
subst = InScopeSet -> TvSubstEnv -> Subst
mkTvSubst
                     ([TcTyVar] -> InScopeSet
mkInScopeSetList ([TcTyVar] -> InScopeSet) -> [TcTyVar] -> InScopeSet
forall a b. (a -> b) -> a -> b
$ ((Unique, TcTyVar) -> TcTyVar) -> [(Unique, TcTyVar)] -> [TcTyVar]
forall a b. (a -> b) -> [a] -> [b]
map (Unique, TcTyVar) -> TcTyVar
forall a b. (a, b) -> b
snd [(Unique, TcTyVar)]
subst_prs)
                     ([(Unique, Type)] -> TvSubstEnv
forall elt key. [(Unique, elt)] -> UniqFM key elt
listToUFM_Directly ([(Unique, Type)] -> TvSubstEnv) -> [(Unique, Type)] -> TvSubstEnv
forall a b. (a -> b) -> a -> b
$ ((Unique, TcTyVar) -> (Unique, Type))
-> [(Unique, TcTyVar)] -> [(Unique, Type)]
forall a b. (a -> b) -> [a] -> [b]
map ((TcTyVar -> Type) -> (Unique, TcTyVar) -> (Unique, Type)
forall a b. (a -> b) -> (Unique, a) -> (Unique, b)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap TcTyVar -> Type
mkTyVarTy) [(Unique, TcTyVar)]
subst_prs)
           ty' :: Type
ty' = HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst XXType GhcRn
Type
ty
       (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
ty', HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
ty')

tc_infer_hs_type TcTyMode
_ (HsExplicitListTy XExplicitListTy GhcRn
_ PromotionFlag
_ [LHsType GhcRn]
tys)
  | [GenLocated SrcSpanAnnA (HsType GhcRn)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
tys  -- this is so that we can use visible kind application with '[]
              -- e.g ... '[] @Bool
  = (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TyCon -> Type
mkTyConTy TyCon
promotedNilDataCon,
            [TcTyVar] -> Type -> Type
mkSpecForAllTys [TcTyVar
alphaTyVar] (Type -> Type) -> Type -> Type
forall a b. (a -> b) -> a -> b
$ Type -> Type
mkListTy Type
alphaTy)

tc_infer_hs_type TcTyMode
mode HsType GhcRn
other_ty
  = do { Type
kv <- TcM Type
newMetaKindVar
       ; Type
ty' <- TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_hs_type TcTyMode
mode HsType GhcRn
other_ty Type
kv
       ; (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
ty', Type
kv) }

{-
Note [Typechecking HsCoreTys]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HsCoreTy is an escape hatch that allows embedding Core Types in HsTypes.
As such, there's not much to be done in order to typecheck an HsCoreTy,
since it's already been typechecked to some extent. There is one thing that
we must do, however: we must substitute the type variables from the tcl_env.
To see why, consider GeneralizedNewtypeDeriving, which is one of the main
clients of HsCoreTy (example adapted from #14579):

  newtype T a = MkT a deriving newtype Eq

This will produce an InstInfo GhcPs that looks roughly like this:

  instance forall a_1. Eq a_1 => Eq (T a_1) where
    (==) = coerce @(  a_1 ->   a_1 -> Bool) -- The type within @(...) is an HsCoreTy
                  @(T a_1 -> T a_1 -> Bool) -- So is this
                  (==)

This is then fed into the renamer. Since all of the type variables in this
InstInfo use Exact RdrNames, the resulting InstInfo GhcRn looks basically
identical. Things get more interesting when the InstInfo is fed into the
typechecker, however. GHC will first generate fresh skolems to instantiate
the instance-bound type variables with. In the example above, we might generate
the skolem a_2 and use that to instantiate a_1, which extends the local type
environment (tcl_env) with [a_1 :-> a_2]. This gives us:

  instance forall a_2. Eq a_2 => Eq (T a_2) where ...

To ensure that the body of this instance is well scoped, every occurrence of
the `a` type variable should refer to a_2, the new skolem. However, the
HsCoreTys mention a_1, not a_2. Luckily, the tcl_env provides exactly the
substitution we need ([a_1 :-> a_2]) to fix up the scoping. We apply this
substitution to each HsCoreTy and all is well:

  instance forall a_2. Eq a_2 => Eq (T a_2) where
    (==) = coerce @(  a_2 ->   a_2 -> Bool)
                  @(T a_2 -> T a_2 -> Bool)
                  (==)
-}

------------------------------------------
tcLHsType :: LHsType GhcRn -> TcKind -> TcM TcType
tcLHsType :: LHsType GhcRn -> Type -> TcM Type
tcLHsType LHsType GhcRn
hs_ty Type
exp_kind
  = TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
typeLevelMode LHsType GhcRn
hs_ty Type
exp_kind

tc_lhs_type :: TcTyMode -> LHsType GhcRn -> TcKind -> TcM TcType
tc_lhs_type :: TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode (L SrcSpanAnnA
span HsType GhcRn
ty) Type
exp_kind
  = SrcSpanAnnA -> TcM Type -> TcM Type
forall ann a. SrcSpanAnn' ann -> TcRn a -> TcRn a
setSrcSpanA SrcSpanAnnA
span (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
    TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_hs_type TcTyMode
mode HsType GhcRn
ty Type
exp_kind

tc_hs_type :: TcTyMode -> HsType GhcRn -> TcKind -> TcM TcType
-- See Note [Bidirectional type checking]

tc_hs_type :: TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_hs_type TcTyMode
mode (HsParTy XParTy GhcRn
_ LHsType GhcRn
ty)   Type
exp_kind = TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
ty Type
exp_kind
tc_hs_type TcTyMode
mode (HsDocTy XDocTy GhcRn
_ LHsType GhcRn
ty LHsDoc GhcRn
_) Type
exp_kind = TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
ty Type
exp_kind
tc_hs_type TcTyMode
_ ty :: HsType GhcRn
ty@(HsBangTy XBangTy GhcRn
_ HsSrcBang
bang LHsType GhcRn
_) Type
_
    -- While top-level bangs at this point are eliminated (eg !(Maybe Int)),
    -- other kinds of bangs are not (eg ((!Maybe) Int)). These kinds of
    -- bangs are invalid, so fail. (#7210, #14761)
    = TcRnMessage -> TcM Type
forall a. TcRnMessage -> TcM a
failWith (TcRnMessage -> TcM Type) -> TcRnMessage -> TcM Type
forall a b. (a -> b) -> a -> b
$ HsType GhcRn -> HsSrcBang -> TcRnMessage
TcRnUnexpectedAnnotation HsType GhcRn
ty HsSrcBang
bang
tc_hs_type TcTyMode
_ ty :: HsType GhcRn
ty@(HsRecTy {})      Type
_
      -- Record types (which only show up temporarily in constructor
      -- signatures) should have been removed by now
    = TcRnMessage -> TcM Type
forall a. TcRnMessage -> TcM a
failWithTc (TcRnMessage -> TcM Type) -> TcRnMessage -> TcM Type
forall a b. (a -> b) -> a -> b
$ Either (HsType GhcPs) (HsType GhcRn) -> TcRnMessage
TcRnIllegalRecordSyntax (HsType GhcRn -> Either (HsType GhcPs) (HsType GhcRn)
forall a b. b -> Either a b
Right HsType GhcRn
ty)

-- HsSpliced is an annotation produced by 'GHC.Rename.Splice.rnSpliceType'.
-- Here we get rid of it and add the finalizers to the global environment
-- while capturing the local environment.
--
-- See Note [Delaying modFinalizers in untyped splices].
tc_hs_type TcTyMode
mode (HsSpliceTy (HsUntypedSpliceTop ThModFinalizers
mod_finalizers GenLocated SrcSpanAnnA (HsType GhcRn)
ty) HsUntypedSplice GhcRn
_)
           Type
exp_kind
  = do ThModFinalizers -> TcM ()
addModFinalizersWithLclEnv ThModFinalizers
mod_finalizers
       TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
ty Type
exp_kind

tc_hs_type TcTyMode
_ (HsSpliceTy (HsUntypedSpliceNested Name
n) HsUntypedSplice GhcRn
s) Type
_ = String -> SDoc -> TcM Type
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"tc_hs_type: invalid nested splice" (Bool -> Maybe Name -> HsUntypedSplice GhcRn -> SDoc
forall (p :: Pass).
OutputableBndrId p =>
Bool -> Maybe Name -> HsUntypedSplice (GhcPass p) -> SDoc
pprUntypedSplice Bool
True (Name -> Maybe Name
forall a. a -> Maybe a
Just Name
n) HsUntypedSplice GhcRn
s)

---------- Functions and applications
tc_hs_type TcTyMode
mode (HsFunTy XFunTy GhcRn
_ HsArrow GhcRn
mult LHsType GhcRn
ty1 LHsType GhcRn
ty2) Type
exp_kind
  = TcTyMode
-> HsArrow GhcRn
-> LHsType GhcRn
-> LHsType GhcRn
-> Type
-> TcM Type
tc_fun_type TcTyMode
mode HsArrow GhcRn
mult LHsType GhcRn
ty1 LHsType GhcRn
ty2 Type
exp_kind

tc_hs_type TcTyMode
mode (HsOpTy XOpTy GhcRn
_ PromotionFlag
_ LHsType GhcRn
ty1 (L SrcSpanAnnN
_ Name
op) LHsType GhcRn
ty2) Type
exp_kind
  | Name
op Name -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
unrestrictedFunTyConKey
  = TcTyMode
-> HsArrow GhcRn
-> LHsType GhcRn
-> LHsType GhcRn
-> Type
-> TcM Type
tc_fun_type TcTyMode
mode (LHsUniToken "->" "\8594" GhcRn -> HsArrow GhcRn
forall pass. LHsUniToken "->" "\8594" pass -> HsArrow pass
HsUnrestrictedArrow LHsUniToken "->" "\8594" GhcRn
GenLocated TokenLocation (HsUniToken "->" "\8594")
forall (tok :: Symbol) (utok :: Symbol).
GenLocated TokenLocation (HsUniToken tok utok)
noHsUniTok) LHsType GhcRn
ty1 LHsType GhcRn
ty2 Type
exp_kind

--------- Foralls
tc_hs_type TcTyMode
mode (HsForAllTy { hst_tele :: forall pass. HsType pass -> HsForAllTelescope pass
hst_tele = HsForAllTelescope GhcRn
tele, hst_body :: forall pass. HsType pass -> LHsType pass
hst_body = LHsType GhcRn
ty }) Type
exp_kind
  = do { ([TcTyVarBinder]
tv_bndrs, Type
ty') <- TcTyMode
-> HsForAllTelescope GhcRn
-> TcM Type
-> TcM ([TcTyVarBinder], Type)
forall a.
TcTyMode
-> HsForAllTelescope GhcRn -> TcM a -> TcM ([TcTyVarBinder], a)
tcTKTelescope TcTyMode
mode HsForAllTelescope GhcRn
tele (TcM Type -> TcM ([TcTyVarBinder], Type))
-> TcM Type -> TcM ([TcTyVarBinder], Type)
forall a b. (a -> b) -> a -> b
$
                            TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
ty Type
exp_kind
                 -- Pass on the mode from the type, to any wildcards
                 -- in kind signatures on the forall'd variables
                 -- e.g.      f :: _ -> Int -> forall (a :: _). blah
                 -- Why exp_kind?  See Note [Body kind of a HsForAllTy]

       -- Do not kind-generalise here!  See Note [Kind generalisation]

       ; Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([TcTyVarBinder] -> Type -> Type
mkForAllTys [TcTyVarBinder]
tv_bndrs Type
ty') }

tc_hs_type TcTyMode
mode (HsQualTy { hst_ctxt :: forall pass. HsType pass -> LHsContext pass
hst_ctxt = LHsContext GhcRn
ctxt, hst_body :: forall pass. HsType pass -> LHsType pass
hst_body = LHsType GhcRn
rn_ty }) Type
exp_kind
  | [GenLocated SrcSpanAnnA (HsType GhcRn)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (GenLocated SrcSpanAnnC [GenLocated SrcSpanAnnA (HsType GhcRn)]
-> [GenLocated SrcSpanAnnA (HsType GhcRn)]
forall l e. GenLocated l e -> e
unLoc LHsContext GhcRn
GenLocated SrcSpanAnnC [GenLocated SrcSpanAnnA (HsType GhcRn)]
ctxt)
  = TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
rn_ty Type
exp_kind

  -- See Note [Body kind of a HsQualTy]
  | Type -> Bool
isConstraintLikeKind Type
exp_kind
  = do { [Type]
ctxt' <- TcTyMode -> LHsContext GhcRn -> TcM [Type]
tc_hs_context TcTyMode
mode LHsContext GhcRn
ctxt
       ; Type
ty'   <- TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
rn_ty Type
constraintKind
       ; Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([Type] -> Type -> Type
HasDebugCallStack => [Type] -> Type -> Type
tcMkDFunPhiTy [Type]
ctxt' Type
ty') }

  | Bool
otherwise
  = do { [Type]
ctxt' <- TcTyMode -> LHsContext GhcRn -> TcM [Type]
tc_hs_context TcTyMode
mode LHsContext GhcRn
ctxt

       ; Type
ek <- TcM Type
newOpenTypeKind  -- The body kind (result of the function) can
                                -- be TYPE r, for any r, hence newOpenTypeKind
       ; Type
ty' <- TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
rn_ty Type
ek
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind (GenLocated SrcSpanAnnA (HsType GhcRn) -> HsType GhcRn
forall l e. GenLocated l e -> e
unLoc LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
rn_ty) ([Type] -> Type -> Type
HasDebugCallStack => [Type] -> Type -> Type
tcMkPhiTy [Type]
ctxt' Type
ty')
                           Type
liftedTypeKind Type
exp_kind }

--------- Lists, arrays, and tuples
tc_hs_type TcTyMode
mode rn_ty :: HsType GhcRn
rn_ty@(HsListTy XListTy GhcRn
_ LHsType GhcRn
elt_ty) Type
exp_kind
  = do { Type
tau_ty <- TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
elt_ty Type
liftedTypeKind
       ; TyCon -> TcM ()
checkWiredInTyCon TyCon
listTyCon
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
rn_ty (Type -> Type
mkListTy Type
tau_ty) Type
liftedTypeKind Type
exp_kind }

-- See Note [Distinguishing tuple kinds] in GHC.Hs.Type
-- See Note [Inferring tuple kinds]
tc_hs_type TcTyMode
mode rn_ty :: HsType GhcRn
rn_ty@(HsTupleTy XTupleTy GhcRn
_ HsTupleSort
HsBoxedOrConstraintTuple [LHsType GhcRn]
hs_tys) Type
exp_kind
     -- (NB: not zonking before looking at exp_k, to avoid left-right bias)
  | Just TupleSort
tup_sort <- Type -> Maybe TupleSort
tupKindSort_maybe Type
exp_kind
  = String -> SDoc -> TcM ()
traceTc String
"tc_hs_type tuple" ([GenLocated SrcSpanAnnA (HsType GhcRn)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_tys) TcM () -> TcM Type -> TcM Type
forall a b.
IOEnv (Env TcGblEnv TcLclEnv) a
-> IOEnv (Env TcGblEnv TcLclEnv) b
-> IOEnv (Env TcGblEnv TcLclEnv) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
    HsType GhcRn
-> TcTyMode -> TupleSort -> [LHsType GhcRn] -> Type -> TcM Type
tc_tuple HsType GhcRn
rn_ty TcTyMode
mode TupleSort
tup_sort [LHsType GhcRn]
hs_tys Type
exp_kind
  | Bool
otherwise
  = do { String -> SDoc -> TcM ()
traceTc String
"tc_hs_type tuple 2" ([GenLocated SrcSpanAnnA (HsType GhcRn)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_tys)
       ; ([Type]
tys, [Type]
kinds) <- (GenLocated SrcSpanAnnA (HsType GhcRn) -> TcM (Type, Type))
-> [GenLocated SrcSpanAnnA (HsType GhcRn)]
-> IOEnv (Env TcGblEnv TcLclEnv) ([Type], [Type])
forall (m :: * -> *) a b c.
Applicative m =>
(a -> m (b, c)) -> [a] -> m ([b], [c])
mapAndUnzipM (TcTyMode -> LHsType GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode) [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_tys
       ; [Type]
kinds <- ZonkM [Type] -> TcM [Type]
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM [Type] -> TcM [Type]) -> ZonkM [Type] -> TcM [Type]
forall a b. (a -> b) -> a -> b
$ (Type -> ZonkM Type) -> [Type] -> ZonkM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM Type -> ZonkM Type
zonkTcType [Type]
kinds
           -- Infer each arg type separately, because errors can be
           -- confusing if we give them a shared kind.  Eg #7410
           -- (Either Int, Int), we do not want to get an error saying
           -- "the second argument of a tuple should have kind *->*"

       ; let (Type
arg_kind, TupleSort
tup_sort)
               = case [ (Type
k,TupleSort
s) | Type
k <- [Type]
kinds
                              , Just TupleSort
s <- [Type -> Maybe TupleSort
tupKindSort_maybe Type
k] ] of
                    ((Type
k,TupleSort
s) : [(Type, TupleSort)]
_) -> (Type
k,TupleSort
s)
                    [] -> (Type
liftedTypeKind, TupleSort
BoxedTuple)
         -- In the [] case, it's not clear what the kind is, so guess *

       ; [Type]
tys' <- [TcM Type] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a.
(Traversable t, Monad m) =>
t (m a) -> m (t a)
forall (m :: * -> *) a. Monad m => [m a] -> m [a]
sequence [ SrcSpanAnnA -> TcM Type -> TcM Type
forall ann a. SrcSpanAnn' ann -> TcRn a -> TcRn a
setSrcSpanA SrcSpanAnnA
loc (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
                            HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
hs_ty Type
ty Type
kind Type
arg_kind
                          | ((L SrcSpanAnnA
loc HsType GhcRn
hs_ty),Type
ty,Type
kind) <- [GenLocated SrcSpanAnnA (HsType GhcRn)]
-> [Type]
-> [Type]
-> [(GenLocated SrcSpanAnnA (HsType GhcRn), Type, Type)]
forall a b c. [a] -> [b] -> [c] -> [(a, b, c)]
zip3 [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_tys [Type]
tys [Type]
kinds ]

       ; HsType GhcRn -> TupleSort -> [Type] -> [Type] -> Type -> TcM Type
finish_tuple HsType GhcRn
rn_ty TupleSort
tup_sort [Type]
tys' ((Type -> Type) -> [Type] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map (Type -> Type -> Type
forall a b. a -> b -> a
const Type
arg_kind) [Type]
tys') Type
exp_kind }


tc_hs_type TcTyMode
mode rn_ty :: HsType GhcRn
rn_ty@(HsTupleTy XTupleTy GhcRn
_ HsTupleSort
HsUnboxedTuple [LHsType GhcRn]
tys) Type
exp_kind
  = HsType GhcRn
-> TcTyMode -> TupleSort -> [LHsType GhcRn] -> Type -> TcM Type
tc_tuple HsType GhcRn
rn_ty TcTyMode
mode TupleSort
UnboxedTuple [LHsType GhcRn]
tys Type
exp_kind

tc_hs_type TcTyMode
mode rn_ty :: HsType GhcRn
rn_ty@(HsSumTy XSumTy GhcRn
_ [LHsType GhcRn]
hs_tys) Type
exp_kind
  = do { let arity :: Int
arity = [GenLocated SrcSpanAnnA (HsType GhcRn)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_tys
       ; [Type]
arg_kinds <- (GenLocated SrcSpanAnnA (HsType GhcRn) -> TcM Type)
-> [GenLocated SrcSpanAnnA (HsType GhcRn)] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (\GenLocated SrcSpanAnnA (HsType GhcRn)
_ -> TcM Type
newOpenTypeKind) [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_tys
       ; [Type]
tau_tys   <- (GenLocated SrcSpanAnnA (HsType GhcRn) -> Type -> TcM Type)
-> [GenLocated SrcSpanAnnA (HsType GhcRn)] -> [Type] -> TcM [Type]
forall (m :: * -> *) a b c.
Applicative m =>
(a -> b -> m c) -> [a] -> [b] -> m [c]
zipWithM (TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode) [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_tys [Type]
arg_kinds
       ; let arg_reps :: [Type]
arg_reps = (Type -> Type) -> [Type] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map HasDebugCallStack => Type -> Type
Type -> Type
kindRep [Type]
arg_kinds
             arg_tys :: [Type]
arg_tys  = [Type]
arg_reps [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
tau_tys
             sum_ty :: Type
sum_ty   = TyCon -> [Type] -> Type
mkTyConApp (Int -> TyCon
sumTyCon Int
arity) [Type]
arg_tys
             sum_kind :: Type
sum_kind = [Type] -> Type
unboxedSumKind [Type]
arg_reps
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
rn_ty Type
sum_ty Type
sum_kind Type
exp_kind
       }

--------- Promoted lists and tuples
tc_hs_type TcTyMode
mode rn_ty :: HsType GhcRn
rn_ty@(HsExplicitListTy XExplicitListTy GhcRn
_ PromotionFlag
_ [LHsType GhcRn]
tys) Type
exp_kind
  -- The '[] case is handled in tc_infer_hs_type.
  -- See Note [Future-proofing the type checker].
  | [GenLocated SrcSpanAnnA (HsType GhcRn)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
tys
  = HasDebugCallStack => TcTyMode -> HsType GhcRn -> Type -> TcM Type
TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_infer_hs_type_ek TcTyMode
mode HsType GhcRn
rn_ty Type
exp_kind

  | Bool
otherwise
  = do { [(Type, Type)]
tks <- (GenLocated SrcSpanAnnA (HsType GhcRn) -> TcM (Type, Type))
-> [GenLocated SrcSpanAnnA (HsType GhcRn)]
-> IOEnv (Env TcGblEnv TcLclEnv) [(Type, Type)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (TcTyMode -> LHsType GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode) [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
tys
       ; ([Type]
taus', Type
kind) <- [LHsType GhcRn] -> [(Type, Type)] -> TcM ([Type], Type)
unifyKinds [LHsType GhcRn]
tys [(Type, Type)]
tks
       ; let ty :: Type
ty = ((Type -> Type -> Type) -> Type -> [Type] -> Type
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (Type -> Type -> Type -> Type
mk_cons Type
kind) (Type -> Type
mk_nil Type
kind) [Type]
taus')
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
rn_ty Type
ty (Type -> Type
mkListTy Type
kind) Type
exp_kind }
  where
    mk_cons :: Type -> Type -> Type -> Type
mk_cons Type
k Type
a Type
b = TyCon -> [Type] -> Type
mkTyConApp (DataCon -> TyCon
promoteDataCon DataCon
consDataCon) [Type
k, Type
a, Type
b]
    mk_nil :: Type -> Type
mk_nil  Type
k     = TyCon -> [Type] -> Type
mkTyConApp (DataCon -> TyCon
promoteDataCon DataCon
nilDataCon) [Type
k]

tc_hs_type TcTyMode
mode rn_ty :: HsType GhcRn
rn_ty@(HsExplicitTupleTy XExplicitTupleTy GhcRn
_ [LHsType GhcRn]
tys) Type
exp_kind
  -- using newMetaKindVar means that we force instantiations of any polykinded
  -- types. At first, I just used tc_infer_lhs_type, but that led to #11255.
  = do { [Type]
ks   <- Int -> TcM Type -> TcM [Type]
forall (m :: * -> *) a. Applicative m => Int -> m a -> m [a]
replicateM Int
arity TcM Type
newMetaKindVar
       ; [Type]
taus <- (GenLocated SrcSpanAnnA (HsType GhcRn) -> Type -> TcM Type)
-> [GenLocated SrcSpanAnnA (HsType GhcRn)] -> [Type] -> TcM [Type]
forall (m :: * -> *) a b c.
Applicative m =>
(a -> b -> m c) -> [a] -> [b] -> m [c]
zipWithM (TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode) [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
tys [Type]
ks
       ; let kind_con :: TyCon
kind_con   = Boxity -> Int -> TyCon
tupleTyCon           Boxity
Boxed Int
arity
             ty_con :: TyCon
ty_con     = Boxity -> Int -> TyCon
promotedTupleDataCon Boxity
Boxed Int
arity
             tup_k :: Type
tup_k      = TyCon -> [Type] -> Type
mkTyConApp TyCon
kind_con [Type]
ks
       ; Int -> TcM ()
checkTupSize Int
arity
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
rn_ty (TyCon -> [Type] -> Type
mkTyConApp TyCon
ty_con ([Type]
ks [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
taus)) Type
tup_k Type
exp_kind }
  where
    arity :: Int
arity = [GenLocated SrcSpanAnnA (HsType GhcRn)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
tys

--------- Constraint types
tc_hs_type TcTyMode
mode rn_ty :: HsType GhcRn
rn_ty@(HsIParamTy XIParamTy GhcRn
_ (L SrcAnn NoEpAnns
_ HsIPName
n) LHsType GhcRn
ty) Type
exp_kind
  = do { Bool -> TcM ()
forall (m :: * -> *). (HasCallStack, Applicative m) => Bool -> m ()
massert (TypeOrKind -> Bool
isTypeLevel (TcTyMode -> TypeOrKind
mode_tyki TcTyMode
mode))
       ; Type
ty' <- TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
ty Type
liftedTypeKind
       ; let n' :: Type
n' = FastString -> Type
mkStrLitTy (FastString -> Type) -> FastString -> Type
forall a b. (a -> b) -> a -> b
$ HsIPName -> FastString
hsIPNameFS HsIPName
n
       ; Class
ipClass <- Name -> TcM Class
tcLookupClass Name
ipClassName
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
rn_ty (Class -> [Type] -> Type
mkClassPred Class
ipClass [Type
n',Type
ty'])
                           Type
constraintKind Type
exp_kind }

tc_hs_type TcTyMode
_ rn_ty :: HsType GhcRn
rn_ty@(HsStarTy XStarTy GhcRn
_ Bool
_) Type
exp_kind
  -- Desugaring 'HsStarTy' to 'Data.Kind.Type' here means that we don't
  -- have to handle it in 'coreView'
  = HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
rn_ty Type
liftedTypeKind Type
liftedTypeKind Type
exp_kind

--------- Literals
tc_hs_type TcTyMode
_ rn_ty :: HsType GhcRn
rn_ty@(HsTyLit XTyLit GhcRn
_ (HsNumTy XNumTy GhcRn
_ Integer
n)) Type
exp_kind
  = do { TyCon -> TcM ()
checkWiredInTyCon TyCon
naturalTyCon
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
rn_ty (Integer -> Type
mkNumLitTy Integer
n) Type
naturalTy Type
exp_kind }

tc_hs_type TcTyMode
_ rn_ty :: HsType GhcRn
rn_ty@(HsTyLit XTyLit GhcRn
_ (HsStrTy XStrTy GhcRn
_ FastString
s)) Type
exp_kind
  = do { TyCon -> TcM ()
checkWiredInTyCon TyCon
typeSymbolKindCon
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
rn_ty (FastString -> Type
mkStrLitTy FastString
s) Type
typeSymbolKind Type
exp_kind }
tc_hs_type TcTyMode
_ rn_ty :: HsType GhcRn
rn_ty@(HsTyLit XTyLit GhcRn
_ (HsCharTy XCharTy GhcRn
_ Char
c)) Type
exp_kind
  = do { TyCon -> TcM ()
checkWiredInTyCon TyCon
charTyCon
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
rn_ty (Char -> Type
mkCharLitTy Char
c) Type
charTy Type
exp_kind }

--------- Wildcards

tc_hs_type TcTyMode
mode ty :: HsType GhcRn
ty@(HsWildCardTy XWildCardTy GhcRn
_)        Type
ek
  = IsExtraConstraint -> TcTyMode -> HsType GhcRn -> Type -> TcM Type
tcAnonWildCardOcc IsExtraConstraint
NoExtraConstraint TcTyMode
mode HsType GhcRn
ty Type
ek

--------- Potentially kind-polymorphic types: call the "up" checker
-- See Note [Future-proofing the type checker]
tc_hs_type TcTyMode
mode ty :: HsType GhcRn
ty@(HsTyVar {})            Type
ek = HasDebugCallStack => TcTyMode -> HsType GhcRn -> Type -> TcM Type
TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_infer_hs_type_ek TcTyMode
mode HsType GhcRn
ty Type
ek
tc_hs_type TcTyMode
mode ty :: HsType GhcRn
ty@(HsAppTy {})            Type
ek = HasDebugCallStack => TcTyMode -> HsType GhcRn -> Type -> TcM Type
TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_infer_hs_type_ek TcTyMode
mode HsType GhcRn
ty Type
ek
tc_hs_type TcTyMode
mode ty :: HsType GhcRn
ty@(HsAppKindTy{})         Type
ek = HasDebugCallStack => TcTyMode -> HsType GhcRn -> Type -> TcM Type
TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_infer_hs_type_ek TcTyMode
mode HsType GhcRn
ty Type
ek
tc_hs_type TcTyMode
mode ty :: HsType GhcRn
ty@(HsOpTy {})             Type
ek = HasDebugCallStack => TcTyMode -> HsType GhcRn -> Type -> TcM Type
TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_infer_hs_type_ek TcTyMode
mode HsType GhcRn
ty Type
ek
tc_hs_type TcTyMode
mode ty :: HsType GhcRn
ty@(HsKindSig {})          Type
ek = HasDebugCallStack => TcTyMode -> HsType GhcRn -> Type -> TcM Type
TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_infer_hs_type_ek TcTyMode
mode HsType GhcRn
ty Type
ek
tc_hs_type TcTyMode
mode ty :: HsType GhcRn
ty@(XHsType {})            Type
ek = HasDebugCallStack => TcTyMode -> HsType GhcRn -> Type -> TcM Type
TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_infer_hs_type_ek TcTyMode
mode HsType GhcRn
ty Type
ek

{-
Note [Variable Specificity and Forall Visibility]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A HsForAllTy contains an HsForAllTelescope to denote the visibility of the forall
binder. Furthermore, each invisible type variable binder also has a
Specificity. Together, these determine the variable binders (ForAllTyFlag) for each
variable in the generated ForAllTy type.

This table summarises this relation:
----------------------------------------------------------------------------
| User-written type         HsForAllTelescope   Specificity        ForAllTyFlag
|---------------------------------------------------------------------------
| f :: forall a. type       HsForAllInvis       SpecifiedSpec      Specified
| f :: forall {a}. type     HsForAllInvis       InferredSpec       Inferred
| f :: forall a -> type     HsForAllVis         SpecifiedSpec      Required
| f :: forall {a} -> type   HsForAllVis         InferredSpec       /
|   This last form is nonsensical and is thus rejected.
----------------------------------------------------------------------------

For more information regarding the interpretation of the resulting ForAllTyFlag, see
Note [VarBndrs, ForAllTyBinders, TyConBinders, and visibility] in "GHC.Core.TyCo.Rep".
-}

------------------------------------------
tc_mult :: TcTyMode -> HsArrow GhcRn -> TcM Mult
tc_mult :: TcTyMode -> HsArrow GhcRn -> TcM Type
tc_mult TcTyMode
mode HsArrow GhcRn
ty = TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode (HsArrow GhcRn -> LHsType GhcRn
arrowToHsType HsArrow GhcRn
ty) Type
multiplicityTy
------------------------------------------
tc_fun_type :: TcTyMode -> HsArrow GhcRn -> LHsType GhcRn -> LHsType GhcRn -> TcKind
            -> TcM TcType
tc_fun_type :: TcTyMode
-> HsArrow GhcRn
-> LHsType GhcRn
-> LHsType GhcRn
-> Type
-> TcM Type
tc_fun_type TcTyMode
mode HsArrow GhcRn
mult LHsType GhcRn
ty1 LHsType GhcRn
ty2 Type
exp_kind = case TcTyMode -> TypeOrKind
mode_tyki TcTyMode
mode of
  TypeOrKind
TypeLevel ->
    do { String -> SDoc -> TcM ()
traceTc String
"tc_fun_type" (GenLocated SrcSpanAnnA (HsType GhcRn) -> SDoc
forall a. Outputable a => a -> SDoc
ppr LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
ty1 SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ GenLocated SrcSpanAnnA (HsType GhcRn) -> SDoc
forall a. Outputable a => a -> SDoc
ppr LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
ty2)
       ; Type
arg_k <- TcM Type
newOpenTypeKind
       ; Type
res_k <- TcM Type
newOpenTypeKind
       ; Type
ty1'  <- TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
ty1 Type
arg_k
       ; Type
ty2'  <- TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
ty2 Type
res_k
       ; Type
mult' <- TcTyMode -> HsArrow GhcRn -> TcM Type
tc_mult TcTyMode
mode HsArrow GhcRn
mult
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind (XFunTy GhcRn
-> HsArrow GhcRn -> LHsType GhcRn -> LHsType GhcRn -> HsType GhcRn
forall pass.
XFunTy pass
-> HsArrow pass -> LHsType pass -> LHsType pass -> HsType pass
HsFunTy XFunTy GhcRn
EpAnn NoEpAnns
forall a. EpAnn a
noAnn HsArrow GhcRn
mult LHsType GhcRn
ty1 LHsType GhcRn
ty2)
                           (Type -> Type -> Type -> Type
tcMkVisFunTy Type
mult' Type
ty1' Type
ty2')
                           Type
liftedTypeKind Type
exp_kind }
  TypeOrKind
KindLevel ->  -- no representation polymorphism in kinds. yet.
    do { Type
ty1'  <- TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
ty1 Type
liftedTypeKind
       ; Type
ty2'  <- TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
ty2 Type
liftedTypeKind
       ; Type
mult' <- TcTyMode -> HsArrow GhcRn -> TcM Type
tc_mult TcTyMode
mode HsArrow GhcRn
mult
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind (XFunTy GhcRn
-> HsArrow GhcRn -> LHsType GhcRn -> LHsType GhcRn -> HsType GhcRn
forall pass.
XFunTy pass
-> HsArrow pass -> LHsType pass -> LHsType pass -> HsType pass
HsFunTy XFunTy GhcRn
EpAnn NoEpAnns
forall a. EpAnn a
noAnn HsArrow GhcRn
mult LHsType GhcRn
ty1 LHsType GhcRn
ty2)
                           (Type -> Type -> Type -> Type
tcMkVisFunTy Type
mult' Type
ty1' Type
ty2')
                           Type
liftedTypeKind Type
exp_kind }

{- Note [Skolem escape and forall-types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See also Note [Checking telescopes].

Consider
  f :: forall a. (forall kb (b :: kb). Proxy '[a, b]) -> ()

The Proxy '[a,b] forces a and b to have the same kind.  But a's
kind must be bound outside the 'forall a', and hence escapes.
We discover this by building an implication constraint for
each forall.  So the inner implication constraint will look like
    forall kb (b::kb).  kb ~ ka
where ka is a's kind.  We can't unify these two, /even/ if ka is
unification variable, because it would be untouchable inside
this inner implication.

That's what the pushLevelAndCaptureConstraints, plus subsequent
buildTvImplication/emitImplication is all about, when kind-checking
HsForAllTy.

Note that

* We don't need to /simplify/ the constraints here
  because we aren't generalising. We just capture them.

* We can't use emitResidualTvConstraint, because that has a fast-path
  for empty constraints.  We can't take that fast path here, because
  we must do the bad-telescope check even if there are no inner wanted
  constraints. See Note [Checking telescopes] in
  GHC.Tc.Types.Constraint.  Lacking this check led to #16247.
-}

{- *********************************************************************
*                                                                      *
                Tuples
*                                                                      *
********************************************************************* -}

---------------------------
tupKindSort_maybe :: TcKind -> Maybe TupleSort
tupKindSort_maybe :: Type -> Maybe TupleSort
tupKindSort_maybe Type
k
  | Just (Type
k', Coercion
_) <- Type -> Maybe (Type, Coercion)
splitCastTy_maybe Type
k = Type -> Maybe TupleSort
tupKindSort_maybe Type
k'
  | Just Type
k'      <- Type -> Maybe Type
coreView Type
k          = Type -> Maybe TupleSort
tupKindSort_maybe Type
k'
  | Type -> Bool
isConstraintKind Type
k                  = TupleSort -> Maybe TupleSort
forall a. a -> Maybe a
Just TupleSort
ConstraintTuple
  | Type -> Bool
tcIsLiftedTypeKind Type
k                = TupleSort -> Maybe TupleSort
forall a. a -> Maybe a
Just TupleSort
BoxedTuple
  | Bool
otherwise                           = Maybe TupleSort
forall a. Maybe a
Nothing

tc_tuple :: HsType GhcRn -> TcTyMode -> TupleSort -> [LHsType GhcRn] -> TcKind -> TcM TcType
tc_tuple :: HsType GhcRn
-> TcTyMode -> TupleSort -> [LHsType GhcRn] -> Type -> TcM Type
tc_tuple HsType GhcRn
rn_ty TcTyMode
mode TupleSort
tup_sort [LHsType GhcRn]
tys Type
exp_kind
  = do { [Type]
arg_kinds <- case TupleSort
tup_sort of
           TupleSort
BoxedTuple      -> [Type] -> TcM [Type]
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Int -> Type -> [Type]
forall a. Int -> a -> [a]
replicate Int
arity Type
liftedTypeKind)
           TupleSort
UnboxedTuple    -> Int -> TcM Type -> TcM [Type]
forall (m :: * -> *) a. Applicative m => Int -> m a -> m [a]
replicateM Int
arity TcM Type
newOpenTypeKind
           TupleSort
ConstraintTuple -> [Type] -> TcM [Type]
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Int -> Type -> [Type]
forall a. Int -> a -> [a]
replicate Int
arity Type
constraintKind)
       ; [Type]
tau_tys <- (GenLocated SrcSpanAnnA (HsType GhcRn) -> Type -> TcM Type)
-> [GenLocated SrcSpanAnnA (HsType GhcRn)] -> [Type] -> TcM [Type]
forall (m :: * -> *) a b c.
Applicative m =>
(a -> b -> m c) -> [a] -> [b] -> m [c]
zipWithM (TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode) [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
tys [Type]
arg_kinds
       ; HsType GhcRn -> TupleSort -> [Type] -> [Type] -> Type -> TcM Type
finish_tuple HsType GhcRn
rn_ty TupleSort
tup_sort [Type]
tau_tys [Type]
arg_kinds Type
exp_kind }
  where
    arity :: Int
arity   = [GenLocated SrcSpanAnnA (HsType GhcRn)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
tys

finish_tuple :: HsType GhcRn
             -> TupleSort
             -> [TcType]    -- ^ argument types
             -> [TcKind]    -- ^ of these kinds
             -> TcKind      -- ^ expected kind of the whole tuple
             -> TcM TcType
finish_tuple :: HsType GhcRn -> TupleSort -> [Type] -> [Type] -> Type -> TcM Type
finish_tuple HsType GhcRn
rn_ty TupleSort
tup_sort [Type]
tau_tys [Type]
tau_kinds Type
exp_kind = do
  String -> SDoc -> TcM ()
traceTc String
"finish_tuple" (TupleSort -> SDoc
forall a. Outputable a => a -> SDoc
ppr TupleSort
tup_sort SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
tau_kinds SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
exp_kind)
  case TupleSort
tup_sort of
    TupleSort
ConstraintTuple
      |  [Type
tau_ty] <- [Type]
tau_tys
         -- Drop any uses of 1-tuple constraints here.
         -- See Note [Ignore unary constraint tuples]
      -> Type -> Type -> TcM Type
check_expected_kind Type
tau_ty Type
constraintKind
      |  Bool
otherwise
      -> do let tycon :: TyCon
tycon = Int -> TyCon
cTupleTyCon Int
arity
            Int -> TcM ()
checkCTupSize Int
arity
            Type -> Type -> TcM Type
check_expected_kind (TyCon -> [Type] -> Type
mkTyConApp TyCon
tycon [Type]
tau_tys) Type
constraintKind
    TupleSort
BoxedTuple -> do
      let tycon :: TyCon
tycon = Boxity -> Int -> TyCon
tupleTyCon Boxity
Boxed Int
arity
      Int -> TcM ()
checkTupSize Int
arity
      TyCon -> TcM ()
checkWiredInTyCon TyCon
tycon
      Type -> Type -> TcM Type
check_expected_kind (TyCon -> [Type] -> Type
mkTyConApp TyCon
tycon [Type]
tau_tys) Type
liftedTypeKind
    TupleSort
UnboxedTuple -> do
      let tycon :: TyCon
tycon    = Boxity -> Int -> TyCon
tupleTyCon Boxity
Unboxed Int
arity
          tau_reps :: [Type]
tau_reps = (Type -> Type) -> [Type] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map HasDebugCallStack => Type -> Type
Type -> Type
kindRep [Type]
tau_kinds
          -- See also Note [Unboxed tuple RuntimeRep vars] in GHC.Core.TyCon
          arg_tys :: [Type]
arg_tys  = [Type]
tau_reps [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
tau_tys
          res_kind :: Type
res_kind = [Type] -> Type
unboxedTupleKind [Type]
tau_reps
      Int -> TcM ()
checkTupSize Int
arity
      Type -> Type -> TcM Type
check_expected_kind (TyCon -> [Type] -> Type
mkTyConApp TyCon
tycon [Type]
arg_tys) Type
res_kind
  where
    arity :: Int
arity = [Type] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Type]
tau_tys
    check_expected_kind :: Type -> Type -> TcM Type
check_expected_kind Type
ty Type
act_kind =
      HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
rn_ty Type
ty Type
act_kind Type
exp_kind

{-
Note [Ignore unary constraint tuples]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC provides unary tuples and unboxed tuples (see Note [One-tuples] in
GHC.Builtin.Types) but does *not* provide unary constraint tuples. Why? First,
recall the definition of a unary tuple data type:

  data Solo a = Solo a

Note that `Solo a` is *not* the same thing as `a`, since Solo is boxed and
lazy. Therefore, the presence of `Solo` matters semantically. On the other
hand, suppose we had a unary constraint tuple:

  class a => Solo% a

This compiles down a newtype (i.e., a cast) in Core, so `Solo% a` is
semantically equivalent to `a`. Therefore, a 1-tuple constraint would have
no user-visible impact, nor would it allow you to express anything that
you couldn't otherwise.

We could simply add Solo% for consistency with tuples (Solo) and unboxed
tuples (Solo#), but that would require even more magic to wire in another
magical class, so we opt not to do so. We must be careful, however, since
one can try to sneak in uses of unary constraint tuples through Template
Haskell, such as in this program (from #17511):

  f :: $(pure (ForallT [] [TupleT 1 `AppT` (ConT ''Show `AppT` ConT ''Int)]
                       (ConT ''String)))
  -- f :: Solo% (Show Int) => String
  f = "abc"

This use of `TupleT 1` will produce an HsBoxedOrConstraintTuple of arity 1,
and since it is used in a Constraint position, GHC will attempt to treat
it as thought it were a constraint tuple, which can potentially lead to
trouble if one attempts to look up the name of a constraint tuple of arity
1 (as it won't exist). To avoid this trouble, we simply take any unary
constraint tuples discovered when typechecking and drop them—i.e., treat
"Solo% a" as though the user had written "a". This is always safe to do
since the two constraints should be semantically equivalent.
-}

{- *********************************************************************
*                                                                      *
                Type applications
*                                                                      *
********************************************************************* -}

splitHsAppTys :: HsType GhcRn -> Maybe (LHsType GhcRn, [LHsTypeArg GhcRn])
splitHsAppTys :: HsType GhcRn -> Maybe (LHsType GhcRn, HsTyPats GhcRn)
splitHsAppTys HsType GhcRn
hs_ty
  | HsType GhcRn -> Bool
is_app HsType GhcRn
hs_ty = (GenLocated SrcSpanAnnA (HsType GhcRn),
 [HsArg
    GhcRn
    (GenLocated SrcSpanAnnA (HsType GhcRn))
    (GenLocated SrcSpanAnnA (HsType GhcRn))])
-> Maybe
     (GenLocated SrcSpanAnnA (HsType GhcRn),
      [HsArg
         GhcRn
         (GenLocated SrcSpanAnnA (HsType GhcRn))
         (GenLocated SrcSpanAnnA (HsType GhcRn))])
forall a. a -> Maybe a
Just (LHsType GhcRn -> HsTyPats GhcRn -> (LHsType GhcRn, HsTyPats GhcRn)
go (HsType GhcRn -> GenLocated SrcSpanAnnA (HsType GhcRn)
forall a an. a -> LocatedAn an a
noLocA HsType GhcRn
hs_ty) [])
  | Bool
otherwise    = Maybe (LHsType GhcRn, HsTyPats GhcRn)
Maybe
  (GenLocated SrcSpanAnnA (HsType GhcRn),
   [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))])
forall a. Maybe a
Nothing
  where
    is_app :: HsType GhcRn -> Bool
    is_app :: HsType GhcRn -> Bool
is_app (HsAppKindTy {})        = Bool
True
    is_app (HsAppTy {})            = Bool
True
    is_app (HsOpTy XOpTy GhcRn
_ PromotionFlag
_ LHsType GhcRn
_ (L SrcSpanAnnN
_ Name
op) LHsType GhcRn
_) = Bool -> Bool
not (Name
op Name -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
unrestrictedFunTyConKey)
      -- I'm not sure why this funTyConKey test is necessary
      -- Can it even happen?  Perhaps for   t1 `(->)` t2
      -- but then maybe it's ok to treat that like a normal
      -- application rather than using the special rule for HsFunTy
    is_app (HsTyVar {})            = Bool
True
    is_app (HsParTy XParTy GhcRn
_ (L SrcSpanAnnA
_ HsType GhcRn
ty))    = HsType GhcRn -> Bool
is_app HsType GhcRn
ty
    is_app HsType GhcRn
_                       = Bool
False

    go :: LHsType GhcRn
       -> [HsArg GhcRn (LHsType GhcRn) (LHsKind GhcRn)]
       -> (LHsType GhcRn,
           [HsArg GhcRn (LHsType GhcRn) (LHsKind GhcRn)]) -- AZ temp
    go :: LHsType GhcRn -> HsTyPats GhcRn -> (LHsType GhcRn, HsTyPats GhcRn)
go (L SrcSpanAnnA
_  (HsAppTy XAppTy GhcRn
_ LHsType GhcRn
f LHsType GhcRn
a))      HsTyPats GhcRn
as = LHsType GhcRn -> HsTyPats GhcRn -> (LHsType GhcRn, HsTyPats GhcRn)
go LHsType GhcRn
f (GenLocated SrcSpanAnnA (HsType GhcRn)
-> HsArg
     GhcRn
     (GenLocated SrcSpanAnnA (HsType GhcRn))
     (GenLocated SrcSpanAnnA (HsType GhcRn))
forall p tm ty. tm -> HsArg p tm ty
HsValArg LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
a HsArg
  GhcRn
  (GenLocated SrcSpanAnnA (HsType GhcRn))
  (GenLocated SrcSpanAnnA (HsType GhcRn))
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
forall a. a -> [a] -> [a]
: HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
as)
    go (L SrcSpanAnnA
_  (HsAppKindTy XAppKindTy GhcRn
_ LHsType GhcRn
ty LHsToken "@" GhcRn
at LHsType GhcRn
k)) HsTyPats GhcRn
as = LHsType GhcRn -> HsTyPats GhcRn -> (LHsType GhcRn, HsTyPats GhcRn)
go LHsType GhcRn
ty (LHsToken "@" GhcRn
-> GenLocated SrcSpanAnnA (HsType GhcRn)
-> HsArg
     GhcRn
     (GenLocated SrcSpanAnnA (HsType GhcRn))
     (GenLocated SrcSpanAnnA (HsType GhcRn))
forall p tm ty. LHsToken "@" p -> ty -> HsArg p tm ty
HsTypeArg LHsToken "@" GhcRn
at LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
k HsArg
  GhcRn
  (GenLocated SrcSpanAnnA (HsType GhcRn))
  (GenLocated SrcSpanAnnA (HsType GhcRn))
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
forall a. a -> [a] -> [a]
: HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
as)
    go (L SrcSpanAnnA
sp (HsParTy XParTy GhcRn
_ LHsType GhcRn
f))        HsTyPats GhcRn
as = LHsType GhcRn -> HsTyPats GhcRn -> (LHsType GhcRn, HsTyPats GhcRn)
go LHsType GhcRn
f (SrcSpan
-> HsArg
     GhcRn
     (GenLocated SrcSpanAnnA (HsType GhcRn))
     (GenLocated SrcSpanAnnA (HsType GhcRn))
forall p tm ty. SrcSpan -> HsArg p tm ty
HsArgPar (SrcSpanAnnA -> SrcSpan
forall a. SrcSpanAnn' a -> SrcSpan
locA SrcSpanAnnA
sp) HsArg
  GhcRn
  (GenLocated SrcSpanAnnA (HsType GhcRn))
  (GenLocated SrcSpanAnnA (HsType GhcRn))
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
forall a. a -> [a] -> [a]
: HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
as)
    go (L SrcSpanAnnA
_  (HsOpTy XOpTy GhcRn
_ PromotionFlag
prom LHsType GhcRn
l op :: LIdP GhcRn
op@(L SrcSpanAnnN
sp Name
_) LHsType GhcRn
r)) HsTyPats GhcRn
as
      = ( SrcSpanAnnA
-> HsType GhcRn -> GenLocated SrcSpanAnnA (HsType GhcRn)
forall l e. l -> e -> GenLocated l e
L (SrcSpanAnnN -> SrcSpanAnnA
forall a ann. SrcSpanAnn' a -> SrcAnn ann
na2la SrcSpanAnnN
sp) (XTyVar GhcRn -> PromotionFlag -> LIdP GhcRn -> HsType GhcRn
forall pass.
XTyVar pass -> PromotionFlag -> LIdP pass -> HsType pass
HsTyVar XTyVar GhcRn
EpAnn [AddEpAnn]
forall a. EpAnn a
noAnn PromotionFlag
prom LIdP GhcRn
op)
        , GenLocated SrcSpanAnnA (HsType GhcRn)
-> HsArg
     GhcRn
     (GenLocated SrcSpanAnnA (HsType GhcRn))
     (GenLocated SrcSpanAnnA (HsType GhcRn))
forall p tm ty. tm -> HsArg p tm ty
HsValArg LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
l HsArg
  GhcRn
  (GenLocated SrcSpanAnnA (HsType GhcRn))
  (GenLocated SrcSpanAnnA (HsType GhcRn))
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
forall a. a -> [a] -> [a]
: GenLocated SrcSpanAnnA (HsType GhcRn)
-> HsArg
     GhcRn
     (GenLocated SrcSpanAnnA (HsType GhcRn))
     (GenLocated SrcSpanAnnA (HsType GhcRn))
forall p tm ty. tm -> HsArg p tm ty
HsValArg LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
r HsArg
  GhcRn
  (GenLocated SrcSpanAnnA (HsType GhcRn))
  (GenLocated SrcSpanAnnA (HsType GhcRn))
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
forall a. a -> [a] -> [a]
: HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
as )
    go LHsType GhcRn
f HsTyPats GhcRn
as = (LHsType GhcRn
f, HsTyPats GhcRn
as)

---------------------------
tcInferTyAppHead :: TcTyMode -> LHsType GhcRn -> TcM (TcType, TcKind)
-- Version of tc_infer_lhs_type specialised for the head of an
-- application. In particular, for a HsTyVar (which includes type
-- constructors, it does not zoom off into tcInferTyApps and family
-- saturation
tcInferTyAppHead :: TcTyMode -> LHsType GhcRn -> TcM (Type, Type)
tcInferTyAppHead TcTyMode
_ (L SrcSpanAnnA
_ (HsTyVar XTyVar GhcRn
_ PromotionFlag
_ (L SrcSpanAnnN
_ Name
tv)))
  = Name -> TcM (Type, Type)
tcTyVar Name
tv
tcInferTyAppHead TcTyMode
mode LHsType GhcRn
ty
  = TcTyMode -> LHsType GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode LHsType GhcRn
ty

---------------------------
-- | Apply a type of a given kind to a list of arguments. This instantiates
-- invisible parameters as necessary. Always consumes all the arguments,
-- using matchExpectedFunKind as necessary.
-- This takes an optional @VarEnv Kind@ which maps kind variables to kinds.-
-- These kinds should be used to instantiate invisible kind variables;
-- they come from an enclosing class for an associated type/data family.
--
-- tcInferTyApps also arranges to saturate any trailing invisible arguments
--   of a type-family application, which is usually the right thing to do
-- tcInferTyApps_nosat does not do this saturation; it is used only
--   by ":kind" in GHCi
tcInferTyApps, tcInferTyApps_nosat
    :: TcTyMode
    -> LHsType GhcRn        -- ^ Function (for printing only)
    -> TcType               -- ^ Function
    -> [LHsTypeArg GhcRn]   -- ^ Args
    -> TcM (TcType, TcKind) -- ^ (f args, result kind)
tcInferTyApps :: TcTyMode
-> LHsType GhcRn -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
tcInferTyApps TcTyMode
mode LHsType GhcRn
hs_ty Type
fun HsTyPats GhcRn
hs_args
  = do { (Type
f_args, Type
res_k) <- TcTyMode
-> LHsType GhcRn -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
tcInferTyApps_nosat TcTyMode
mode LHsType GhcRn
hs_ty Type
fun HsTyPats GhcRn
hs_args
       ; Type -> Type -> TcM (Type, Type)
saturateFamApp Type
f_args Type
res_k }

tcInferTyApps_nosat :: TcTyMode
-> LHsType GhcRn -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
tcInferTyApps_nosat TcTyMode
mode LHsType GhcRn
orig_hs_ty Type
fun HsTyPats GhcRn
orig_hs_args
  = do { String -> SDoc -> TcM ()
traceTc String
"tcInferTyApps {" (GenLocated SrcSpanAnnA (HsType GhcRn) -> SDoc
forall a. Outputable a => a -> SDoc
ppr LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
orig_hs_ty SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
-> SDoc
forall a. Outputable a => a -> SDoc
ppr HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
orig_hs_args)
       ; (Type
f_args, Type
res_k) <- Int
-> Type
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
-> TcM (Type, Type)
go_init Int
1 Type
fun HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
orig_hs_args
       ; String -> SDoc -> TcM ()
traceTc String
"tcInferTyApps }" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
f_args SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
res_k)
       ; (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
f_args, Type
res_k) }
  where

    -- go_init just initialises the auxiliary
    -- arguments of the 'go' loop
    go_init :: Int
-> Type
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
-> TcM (Type, Type)
go_init Int
n Type
fun [HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
all_args
      = Int -> Type -> Subst -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
go Int
n Type
fun Subst
empty_subst Type
fun_ki HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
all_args
      where
        fun_ki :: Type
fun_ki = HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
fun
           -- We do (typeKind fun) here, even though the caller
           -- knows the function kind, to absolutely guarantee
           -- INVARIANT for 'go'
           -- Note that in a typical application (F t1 t2 t3),
           -- the 'fun' is just a TyCon, so typeKind is fast

        empty_subst :: Subst
empty_subst = InScopeSet -> Subst
mkEmptySubst (InScopeSet -> Subst) -> InScopeSet -> Subst
forall a b. (a -> b) -> a -> b
$ TyVarSet -> InScopeSet
mkInScopeSet (TyVarSet -> InScopeSet) -> TyVarSet -> InScopeSet
forall a b. (a -> b) -> a -> b
$
                      Type -> TyVarSet
tyCoVarsOfType Type
fun_ki

    go :: Int             -- The # of the next argument
       -> TcType          -- Function applied to some args
       -> Subst        -- Applies to function kind
       -> TcKind          -- Function kind
       -> [LHsTypeArg GhcRn]    -- Un-type-checked args
       -> TcM (TcType, TcKind)  -- Result type and its kind
    -- INVARIANT: in any call (go n fun subst fun_ki args)
    --               typeKind fun  =  subst(fun_ki)
    -- So the 'subst' and 'fun_ki' arguments are simply
    -- there to avoid repeatedly calling typeKind.
    --
    -- Reason for INVARIANT: to support the Purely Kinded Type Invariant
    -- it's important that if fun_ki has a forall, then so does
    -- (typeKind fun), because the next thing we are going to do
    -- is apply 'fun' to an argument type.

    -- Dispatch on all_args first, for performance reasons
    go :: Int -> Type -> Subst -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
go Int
n Type
fun Subst
subst Type
fun_ki HsTyPats GhcRn
all_args = case (HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
all_args, Type -> Maybe (PiTyVarBinder, Type)
tcSplitPiTy_maybe Type
fun_ki) of

      ---------------- No user-written args left. We're done!
      ([], Maybe (PiTyVarBinder, Type)
_) -> (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
fun, HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst Type
fun_ki)

      ---------------- HsArgPar: We don't care about parens here
      (HsArgPar SrcSpan
_ : [HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
args, Maybe (PiTyVarBinder, Type)
_) -> Int -> Type -> Subst -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
go Int
n Type
fun Subst
subst Type
fun_ki HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
args

      ---------------- HsTypeArg: a kind application (fun @ki)
      (HsTypeArg LHsToken "@" GhcRn
_ GenLocated SrcSpanAnnA (HsType GhcRn)
hs_ki_arg : [HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
hs_args, Just (PiTyVarBinder
ki_binder, Type
inner_ki)) ->
        case PiTyVarBinder
ki_binder of

        -- FunTy with PredTy on LHS, or ForAllTy with Inferred
        Named (Bndr TcTyVar
kv ForAllTyFlag
Inferred)         -> TcTyVar -> Type -> TcM (Type, Type)
instantiate TcTyVar
kv Type
inner_ki

        Named (Bndr TcTyVar
_ ForAllTyFlag
Specified) ->  -- Visible kind application
          do { String -> SDoc -> TcM ()
traceTc String
"tcInferTyApps (vis kind app)"
                       ([SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ PiTyVarBinder -> SDoc
forall a. Outputable a => a -> SDoc
ppr PiTyVarBinder
ki_binder, GenLocated SrcSpanAnnA (HsType GhcRn) -> SDoc
forall a. Outputable a => a -> SDoc
ppr GenLocated SrcSpanAnnA (HsType GhcRn)
hs_ki_arg
                             , Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr (PiTyVarBinder -> Type
piTyBinderType PiTyVarBinder
ki_binder)
                             , Subst -> SDoc
forall a. Outputable a => a -> SDoc
ppr Subst
subst ])

             ; let exp_kind :: Type
exp_kind = HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst (Type -> Type) -> Type -> Type
forall a b. (a -> b) -> a -> b
$ PiTyVarBinder -> Type
piTyBinderType PiTyVarBinder
ki_binder
             ; TcTyMode
arg_mode <- TypeOrKind -> HoleMode -> TcM TcTyMode
mkHoleMode TypeOrKind
KindLevel HoleMode
HM_VTA
                   -- HM_VKA: see Note [Wildcards in visible kind application]
             ; Type
ki_arg <- SDoc -> TcM Type -> TcM Type
forall a. SDoc -> TcM a -> TcM a
addErrCtxt (GenLocated SrcSpanAnnA (HsType GhcRn)
-> GenLocated SrcSpanAnnA (HsType GhcRn) -> Int -> SDoc
forall fun arg.
(Outputable fun, Outputable arg) =>
fun -> arg -> Int -> SDoc
funAppCtxt LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
orig_hs_ty GenLocated SrcSpanAnnA (HsType GhcRn)
hs_ki_arg Int
n) (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
                         TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
arg_mode LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
hs_ki_arg Type
exp_kind

             ; String -> SDoc -> TcM ()
traceTc String
"tcInferTyApps (vis kind app)" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
exp_kind)
             ; (Subst
subst', Type
fun') <- Subst -> Type -> PiTyVarBinder -> Type -> TcM (Subst, Type)
mkAppTyM Subst
subst Type
fun PiTyVarBinder
ki_binder Type
ki_arg
             ; Int -> Type -> Subst -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
go (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
1) Type
fun' Subst
subst' Type
inner_ki HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
hs_args }

        -- Attempted visible kind application (fun @ki), but fun_ki is
        --   forall k -> blah   or   k1 -> k2
        -- So we need a normal application.  Error.
        PiTyVarBinder
_ -> GenLocated SrcSpanAnnA (HsType GhcRn) -> Type -> TcM (Type, Type)
forall {a}. GenLocated SrcSpanAnnA (HsType GhcRn) -> Type -> TcRn a
ty_app_err GenLocated SrcSpanAnnA (HsType GhcRn)
hs_ki_arg (Type -> TcM (Type, Type)) -> Type -> TcM (Type, Type)
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst Type
fun_ki

      -- No binder; try applying the substitution, or fail if that's not possible
      (HsTypeArg LHsToken "@" GhcRn
_ GenLocated SrcSpanAnnA (HsType GhcRn)
ki_arg : [HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
_, Maybe (PiTyVarBinder, Type)
Nothing) -> TcM (Type, Type) -> TcM (Type, Type)
try_again_after_substing_or (TcM (Type, Type) -> TcM (Type, Type))
-> TcM (Type, Type) -> TcM (Type, Type)
forall a b. (a -> b) -> a -> b
$
                                           GenLocated SrcSpanAnnA (HsType GhcRn) -> Type -> TcM (Type, Type)
forall {a}. GenLocated SrcSpanAnnA (HsType GhcRn) -> Type -> TcRn a
ty_app_err GenLocated SrcSpanAnnA (HsType GhcRn)
ki_arg Type
substed_fun_ki

      ---------------- HsValArg: a normal argument (fun ty)
      (HsValArg GenLocated SrcSpanAnnA (HsType GhcRn)
arg : [HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
args, Just (PiTyVarBinder
ki_binder, Type
inner_ki))
        -- next binder is invisible; need to instantiate it
        | Named (Bndr TcTyVar
kv ForAllTyFlag
flag) <- PiTyVarBinder
ki_binder
        , ForAllTyFlag -> Bool
isInvisibleForAllTyFlag ForAllTyFlag
flag   -- ForAllTy with Inferred or Specified
         -> TcTyVar -> Type -> TcM (Type, Type)
instantiate TcTyVar
kv Type
inner_ki

        -- "normal" case
        | Bool
otherwise
         -> do { String -> SDoc -> TcM ()
traceTc String
"tcInferTyApps (vis normal app)"
                          ([SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ PiTyVarBinder -> SDoc
forall a. Outputable a => a -> SDoc
ppr PiTyVarBinder
ki_binder
                                , GenLocated SrcSpanAnnA (HsType GhcRn) -> SDoc
forall a. Outputable a => a -> SDoc
ppr GenLocated SrcSpanAnnA (HsType GhcRn)
arg
                                , Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr (PiTyVarBinder -> Type
piTyBinderType PiTyVarBinder
ki_binder)
                                , Subst -> SDoc
forall a. Outputable a => a -> SDoc
ppr Subst
subst ])
                ; let exp_kind :: Type
exp_kind = HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst (Type -> Type) -> Type -> Type
forall a b. (a -> b) -> a -> b
$ PiTyVarBinder -> Type
piTyBinderType PiTyVarBinder
ki_binder
                ; Type
arg' <- SDoc -> TcM Type -> TcM Type
forall a. SDoc -> TcM a -> TcM a
addErrCtxt (GenLocated SrcSpanAnnA (HsType GhcRn)
-> GenLocated SrcSpanAnnA (HsType GhcRn) -> Int -> SDoc
forall fun arg.
(Outputable fun, Outputable arg) =>
fun -> arg -> Int -> SDoc
funAppCtxt LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
orig_hs_ty GenLocated SrcSpanAnnA (HsType GhcRn)
arg Int
n) (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
                          TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
arg Type
exp_kind
                ; String -> SDoc -> TcM ()
traceTc String
"tcInferTyApps (vis normal app) 2" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
exp_kind)
                ; (Subst
subst', Type
fun') <- Subst -> Type -> PiTyVarBinder -> Type -> TcM (Subst, Type)
mkAppTyM Subst
subst Type
fun PiTyVarBinder
ki_binder Type
arg'
                ; Int -> Type -> Subst -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
go (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
1) Type
fun' Subst
subst' Type
inner_ki HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
args }

          -- no binder; try applying the substitution, or infer another arrow in fun kind
      (HsValArg GenLocated SrcSpanAnnA (HsType GhcRn)
_ : [HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
_, Maybe (PiTyVarBinder, Type)
Nothing)
        -> TcM (Type, Type) -> TcM (Type, Type)
try_again_after_substing_or (TcM (Type, Type) -> TcM (Type, Type))
-> TcM (Type, Type) -> TcM (Type, Type)
forall a b. (a -> b) -> a -> b
$
           do { let arrows_needed :: Int
arrows_needed = [HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
-> Int
forall p tm ty. [HsArg p tm ty] -> Int
n_initial_val_args HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
all_args
              ; Coercion
co <- TypedThing -> Int -> Type -> TcM Coercion
matchExpectedFunKind (HsType GhcRn -> TypedThing
HsTypeRnThing (HsType GhcRn -> TypedThing) -> HsType GhcRn -> TypedThing
forall a b. (a -> b) -> a -> b
$ GenLocated SrcSpanAnnA (HsType GhcRn) -> HsType GhcRn
forall l e. GenLocated l e -> e
unLoc LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
hs_ty) Int
arrows_needed Type
substed_fun_ki

              ; Type
fun' <- ZonkM Type -> TcM Type
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM Type -> TcM Type) -> ZonkM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ Type -> ZonkM Type
zonkTcType (Type
fun Type -> Coercion -> Type
`mkCastTy` Coercion
co)
                     -- This zonk is essential, to expose the fruits
                     -- of matchExpectedFunKind to the 'go' loop

              ; String -> SDoc -> TcM ()
traceTc String
"tcInferTyApps (no binder)" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
                   [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
fun SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
fun_ki
                        , Int -> SDoc
forall a. Outputable a => a -> SDoc
ppr Int
arrows_needed
                        , Coercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr Coercion
co
                        , Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
fun' SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr (HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
fun')]
              ; Int
-> Type
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
-> TcM (Type, Type)
go_init Int
n Type
fun' HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
all_args }
                -- Use go_init to establish go's INVARIANT
      where
        instantiate :: TcTyVar -> Type -> TcM (Type, Type)
instantiate TcTyVar
ki_binder Type
inner_ki
          = do { String -> SDoc -> TcM ()
traceTc String
"tcInferTyApps (need to instantiate)"
                         ([SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
ki_binder, Subst -> SDoc
forall a. Outputable a => a -> SDoc
ppr Subst
subst])
               ; (Subst
subst', Type
arg') <- Subst -> TcTyVar -> TcM (Subst, Type)
tcInstInvisibleTyBinder Subst
subst TcTyVar
ki_binder
               ; Int -> Type -> Subst -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
go Int
n (Type -> Type -> Type
mkAppTy Type
fun Type
arg') Subst
subst' Type
inner_ki HsTyPats GhcRn
all_args }
                 -- Because tcInvisibleTyBinder instantiate ki_binder,
                 -- the kind of arg' will have the same shape as the kind
                 -- of ki_binder.  So we don't need mkAppTyM here.

        try_again_after_substing_or :: TcM (Type, Type) -> TcM (Type, Type)
try_again_after_substing_or TcM (Type, Type)
fallthrough
          | Bool -> Bool
not (Subst -> Bool
isEmptyTCvSubst Subst
subst)
          = Int -> Type -> Subst -> Type -> HsTyPats GhcRn -> TcM (Type, Type)
go Int
n Type
fun Subst
zapped_subst Type
substed_fun_ki HsTyPats GhcRn
all_args
          | Bool
otherwise
          = TcM (Type, Type)
fallthrough

        zapped_subst :: Subst
zapped_subst   = Subst -> Subst
zapSubst Subst
subst
        substed_fun_ki :: Type
substed_fun_ki = HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst Type
fun_ki
        hs_ty :: LHsType GhcRn
hs_ty          = LHsType GhcRn -> HsTyPats GhcRn -> LHsType GhcRn
appTypeToArg LHsType GhcRn
orig_hs_ty (Int
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
-> [HsArg
      GhcRn
      (GenLocated SrcSpanAnnA (HsType GhcRn))
      (GenLocated SrcSpanAnnA (HsType GhcRn))]
forall a. Int -> [a] -> [a]
take (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1) HsTyPats GhcRn
[HsArg
   GhcRn
   (GenLocated SrcSpanAnnA (HsType GhcRn))
   (GenLocated SrcSpanAnnA (HsType GhcRn))]
orig_hs_args)

    n_initial_val_args :: [HsArg p tm ty] -> Arity
    -- Count how many leading HsValArgs we have
    n_initial_val_args :: forall p tm ty. [HsArg p tm ty] -> Int
n_initial_val_args (HsValArg {} : [HsArg p tm ty]
args) = Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ [HsArg p tm ty] -> Int
forall p tm ty. [HsArg p tm ty] -> Int
n_initial_val_args [HsArg p tm ty]
args
    n_initial_val_args (HsArgPar {} : [HsArg p tm ty]
args) = [HsArg p tm ty] -> Int
forall p tm ty. [HsArg p tm ty] -> Int
n_initial_val_args [HsArg p tm ty]
args
    n_initial_val_args [HsArg p tm ty]
_                    = Int
0

    ty_app_err :: GenLocated SrcSpanAnnA (HsType GhcRn) -> Type -> TcRn a
ty_app_err GenLocated SrcSpanAnnA (HsType GhcRn)
arg Type
ty
      = TcRnMessage -> TcRn a
forall a. TcRnMessage -> TcM a
failWith (TcRnMessage -> TcRn a) -> TcRnMessage -> TcRn a
forall a b. (a -> b) -> a -> b
$ LHsType GhcRn -> Type -> TcRnMessage
TcRnInvalidVisibleKindArgument LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
arg Type
ty

mkAppTyM :: Subst
         -> TcType -> PiTyBinder    -- fun, plus its top-level binder
         -> TcType                  -- arg
         -> TcM (Subst, TcType)  -- Extended subst, plus (fun arg)
-- Precondition: the application (fun arg) is well-kinded after zonking
--               That is, the application makes sense
--
-- Precondition: for (mkAppTyM subst fun bndr arg)
--       typeKind fun  =  Pi bndr. body
--  That is, fun always has a ForAllTy or FunTy at the top
--           and 'bndr' is fun's pi-binder
--
-- Postcondition: if fun and arg satisfy (PKTI), the purely-kinded type
--                invariant, then so does the result type (fun arg)
--
-- We do not require that
--    typeKind arg = tyVarKind (binderVar bndr)
-- This must be true after zonking (precondition 1), but it's not
-- required for the (PKTI).
mkAppTyM :: Subst -> Type -> PiTyVarBinder -> Type -> TcM (Subst, Type)
mkAppTyM Subst
subst Type
fun PiTyVarBinder
ki_binder Type
arg
  | -- See Note [mkAppTyM]: Nasty case 2
    TyConApp TyCon
tc [Type]
args <- Type
fun
  , TyCon -> Bool
isTypeSynonymTyCon TyCon
tc
  , [Type]
args [Type] -> Int -> Bool
forall a. [a] -> Int -> Bool
`lengthIs` (TyCon -> Int
tyConArity TyCon
tc Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1)
  , (TcTyVar -> Bool) -> [TcTyVar] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any TcTyVar -> Bool
isTrickyTvBinder (TyCon -> [TcTyVar]
tyConTyVars TyCon
tc) -- We could cache this in the synonym
  = do { (Type
arg':[Type]
args') <- ZonkM [Type] -> TcM [Type]
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM [Type] -> TcM [Type]) -> ZonkM [Type] -> TcM [Type]
forall a b. (a -> b) -> a -> b
$ [Type] -> ZonkM [Type]
zonkTcTypes (Type
argType -> [Type] -> [Type]
forall a. a -> [a] -> [a]
:[Type]
args)
       ; let subst' :: Subst
subst' = case PiTyVarBinder
ki_binder of
                        Anon {}           -> Subst
subst
                        Named (Bndr TcTyVar
tv ForAllTyFlag
_) -> Subst -> TcTyVar -> Type -> Subst
extendTvSubstAndInScope Subst
subst TcTyVar
tv Type
arg'
       ; (Subst, Type) -> TcM (Subst, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Subst
subst', TyCon -> [Type] -> Type
mkTyConApp TyCon
tc ([Type]
args' [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type
arg'])) }


mkAppTyM Subst
subst Type
fun (Anon {}) Type
arg
   = (Subst, Type) -> TcM (Subst, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Subst
subst, Type -> Type -> Type
mk_app_ty Type
fun Type
arg)

mkAppTyM Subst
subst Type
fun (Named (Bndr TcTyVar
tv ForAllTyFlag
_)) Type
arg
  = do { Type
arg' <- if TcTyVar -> Bool
isTrickyTvBinder TcTyVar
tv
                 then -- See Note [mkAppTyM]: Nasty case 1
                      ZonkM Type -> TcM Type
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM Type -> TcM Type) -> ZonkM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ Type -> ZonkM Type
zonkTcType Type
arg
                 else Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return     Type
arg
       ; (Subst, Type) -> TcM (Subst, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ( Subst -> TcTyVar -> Type -> Subst
extendTvSubstAndInScope Subst
subst TcTyVar
tv Type
arg'
                , Type -> Type -> Type
mk_app_ty Type
fun Type
arg' ) }

mk_app_ty :: TcType -> TcType -> TcType
-- This function just adds an ASSERT for mkAppTyM's precondition
mk_app_ty :: Type -> Type -> Type
mk_app_ty Type
fun Type
arg
  = Bool -> SDoc -> Type -> Type
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (Type -> Bool
isPiTy Type
fun_kind)
              (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
fun SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
fun_kind SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
arg) (Type -> Type) -> Type -> Type
forall a b. (a -> b) -> a -> b
$
    Type -> Type -> Type
mkAppTy Type
fun Type
arg
  where
    fun_kind :: Type
fun_kind = HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
fun

isTrickyTvBinder :: TcTyVar -> Bool
-- NB: isTrickyTvBinder is just an optimisation
-- It would be absolutely sound to return True always
isTrickyTvBinder :: TcTyVar -> Bool
isTrickyTvBinder TcTyVar
tv = Type -> Bool
isPiTy (TcTyVar -> Type
tyVarKind TcTyVar
tv)

{- Note [The Purely Kinded Type Invariant (PKTI)]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
During type inference, we maintain this invariant

 (PKTI) It is legal to call 'typeKind' on any Type ty,
        on any sub-term of ty, /without/ zonking ty

        Moreover, any such returned kind
        will itself satisfy (PKTI)

By "legal to call typeKind" we mean "typeKind will not crash".
The way in which typeKind can crash is in applications
    (a t1 t2 .. tn)
if 'a' is a type variable whose kind doesn't have enough arrows
or foralls.  (The crash is in piResultTys.)

The loop in tcInferTyApps has to be very careful to maintain the (PKTI).
For example, suppose
    kappa is a unification variable
    We have already unified kappa := Type
      yielding    co :: Refl (Type -> Type)
    a :: kappa
then consider the type
    (a Int)
If we call typeKind on that, we'll crash, because the (un-zonked)
kind of 'a' is just kappa, not an arrow kind.  So we must zonk first.

So the type inference engine is very careful when building applications.
This happens in tcInferTyApps. Suppose we are kind-checking the type (a Int),
where (a :: kappa).  Then in tcInferApps we'll run out of binders on
a's kind, so we'll call matchExpectedFunKind, and unify
   kappa := kappa1 -> kappa2,  with evidence co :: kappa ~ (kappa1 ~ kappa2)
At this point we must zonk the function type to expose the arrrow, so
that (a Int) will satisfy (PKTI).

The absence of this caused #14174 and #14520.

The calls to mkAppTyM is the other place we are very careful; see Note [mkAppTyM].

Wrinkle around FunTy:
Note that the PKTI does *not* guarantee anything about the shape of FunTys.
Specifically, when we have (FunTy vis mult arg res), it should be the case
that arg :: TYPE rr1 and res :: TYPE rr2, for some rr1 and rr2. However, we
might not have this. Example: if the user writes (a -> b), then we might
invent a :: kappa1 and b :: kappa2. We soon will check whether kappa1 ~ TYPE rho1
(for some rho1), and that will lead to kappa1 := TYPE rho1 (ditto for kappa2).
However, when we build the FunTy, we might not have zonked `a`, and so the
FunTy will be built without being able to purely extract the RuntimeReps.

Because the PKTI does not guarantee that the RuntimeReps are available in a FunTy,
we must be aware of this when splitting: splitTyConApp and splitAppTy will *not*
split a FunTy if the RuntimeReps are not available. See also Note [Decomposing FunTy]
in GHC.Tc.Solver.Equality.

Note [mkAppTyM]
~~~~~~~~~~~~~~~
mkAppTyM is trying to guarantee the Purely Kinded Type Invariant
(PKTI) for its result type (fun arg).  There are two ways it can go wrong:

* Nasty case 1: forall types (polykinds/T14174a)
    T :: forall (p :: *->*). p Int -> p Bool
  Now kind-check (T x), where x::kappa.
  Well, T and x both satisfy the PKTI, but
     T x :: x Int -> x Bool
  and (x Int) does /not/ satisfy the PKTI.

* Nasty case 2: type synonyms
    type S f a = f a
  Even though (S ff aa) would satisfy the (PKTI) if S was a data type
  (i.e. nasty case 1 is dealt with), it might still not satisfy (PKTI)
  if S is a type synonym, because the /expansion/ of (S ff aa) is
  (ff aa), and /that/ does not satisfy (PKTI).  E.g. perhaps
  (ff :: kappa), where 'kappa' has already been unified with (*->*).

  We check for nasty case 2 on the final argument of a type synonym.

Notice that in both cases the trickiness only happens if the
bound variable has a pi-type.  Hence isTrickyTvBinder.
-}


saturateFamApp :: TcType -> TcKind -> TcM (TcType, TcKind)
-- Precondition for (saturateFamApp ty kind):
--     typeKind ty = kind
--
-- If 'ty' is an unsaturated family application with trailing
-- invisible arguments, instantiate them.
-- See Note [saturateFamApp]

saturateFamApp :: Type -> Type -> TcM (Type, Type)
saturateFamApp Type
ty Type
kind
  | Just (TyCon
tc, [Type]
args) <- HasDebugCallStack => Type -> Maybe (TyCon, [Type])
Type -> Maybe (TyCon, [Type])
tcSplitTyConApp_maybe Type
ty
  , TyCon -> Bool
tyConMustBeSaturated TyCon
tc
  , let n_to_inst :: Int
n_to_inst = TyCon -> Int
tyConArity TyCon
tc Int -> Int -> Int
forall a. Num a => a -> a -> a
- [Type] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Type]
args
  = do { ([Type]
extra_args, Type
ki') <- Int -> Type -> TcM ([Type], Type)
tcInstInvisibleTyBindersN Int
n_to_inst Type
kind
       ; (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
ty Type -> [Type] -> Type
`mkAppTys` [Type]
extra_args, Type
ki') }
  | Bool
otherwise
  = (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
ty, Type
kind)

{- Note [saturateFamApp]
~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   type family F :: Either j k
   type instance F @Type = Right Maybe
   type instance F @Type = Right Either```

Then F :: forall {j,k}. Either j k

The two type instances do a visible kind application that instantiates
'j' but not 'k'.  But we want to end up with instances that look like
  type instance F @Type @(*->*) = Right @Type @(*->*) Maybe

so that F has arity 2.  We must instantiate that trailing invisible
binder. In general, Invisible binders precede Specified and Required,
so this is only going to bite for apparently-nullary families.

Note that
  type family F2 :: forall k. k -> *
is quite different and really does have arity 0.

It's not just type instances where we need to saturate those
unsaturated arguments: see #11246.  Hence doing this in tcInferApps.
-}

appTypeToArg :: LHsType GhcRn -> [LHsTypeArg GhcRn] -> LHsType GhcRn
appTypeToArg :: LHsType GhcRn -> HsTyPats GhcRn -> LHsType GhcRn
appTypeToArg LHsType GhcRn
f []                       = LHsType GhcRn
f
appTypeToArg LHsType GhcRn
f (HsValArg LHsType GhcRn
arg     : HsTyPats GhcRn
args) = LHsType GhcRn -> HsTyPats GhcRn -> LHsType GhcRn
appTypeToArg (LHsType GhcRn -> LHsType GhcRn -> LHsType GhcRn
forall (p :: Pass).
LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
mkHsAppTy LHsType GhcRn
f LHsType GhcRn
arg) HsTyPats GhcRn
args
appTypeToArg LHsType GhcRn
f (HsArgPar SrcSpan
_       : HsTyPats GhcRn
args) = LHsType GhcRn -> HsTyPats GhcRn -> LHsType GhcRn
appTypeToArg LHsType GhcRn
f                 HsTyPats GhcRn
args
appTypeToArg LHsType GhcRn
f (HsTypeArg LHsToken "@" GhcRn
at LHsType GhcRn
arg : HsTyPats GhcRn
args)
  = LHsType GhcRn -> HsTyPats GhcRn -> LHsType GhcRn
appTypeToArg (LHsType GhcRn
-> LHsToken "@" GhcRn -> LHsType GhcRn -> LHsType GhcRn
forall (p :: Pass).
LHsType (GhcPass p)
-> LHsToken "@" (GhcPass p)
-> LHsType (GhcPass p)
-> LHsType (GhcPass p)
mkHsAppKindTy LHsType GhcRn
f LHsToken "@" GhcRn
at LHsType GhcRn
arg) HsTyPats GhcRn
args


{- *********************************************************************
*                                                                      *
                checkExpectedKind
*                                                                      *
********************************************************************* -}

-- | This instantiates invisible arguments for the type being checked if it must
-- be saturated and is not yet saturated. It then calls and uses the result
-- from checkExpectedKindX to build the final type
checkExpectedKind :: HasDebugCallStack
                  => HsType GhcRn       -- ^ type we're checking (for printing)
                  -> TcType             -- ^ type we're checking
                  -> TcKind             -- ^ the known kind of that type
                  -> TcKind             -- ^ the expected kind
                  -> TcM TcType
-- Just a convenience wrapper to save calls to 'ppr'
checkExpectedKind :: HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
hs_ty Type
ty Type
act_kind Type
exp_kind
  = do { String -> SDoc -> TcM ()
traceTc String
"checkExpectedKind" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
act_kind)

       ; ([Type]
new_args, Type
act_kind') <- Int -> Type -> TcM ([Type], Type)
tcInstInvisibleTyBindersN Int
n_to_inst Type
act_kind

       ; let origin :: CtOrigin
origin = TypeEqOrigin { uo_actual :: Type
uo_actual   = Type
act_kind'
                                   , uo_expected :: Type
uo_expected = Type
exp_kind
                                   , uo_thing :: Maybe TypedThing
uo_thing    = TypedThing -> Maybe TypedThing
forall a. a -> Maybe a
Just (HsType GhcRn -> TypedThing
HsTypeRnThing HsType GhcRn
hs_ty)
                                   , uo_visible :: Bool
uo_visible  = Bool
True } -- the hs_ty is visible

       ; String -> SDoc -> TcM ()
traceTc String
"checkExpectedKindX" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ HsType GhcRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsType GhcRn
hs_ty
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"act_kind':" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
act_kind'
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"exp_kind:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
exp_kind ]

       ; let res_ty :: Type
res_ty = Type
ty Type -> [Type] -> Type
`mkAppTys` [Type]
new_args

       ; if Type
act_kind' HasDebugCallStack => Type -> Type -> Bool
Type -> Type -> Bool
`tcEqType` Type
exp_kind
         then Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Type
res_ty  -- This is very common
         else do { Coercion
co_k <- TypeOrKind -> CtOrigin -> Type -> Type -> TcM Coercion
unifyTypeAndEmit TypeOrKind
KindLevel CtOrigin
origin Type
act_kind' Type
exp_kind
                 ; String -> SDoc -> TcM ()
traceTc String
"checkExpectedKind" ([SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
act_kind
                                                     , Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
exp_kind
                                                     , Coercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr Coercion
co_k ])
                ; Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
res_ty Type -> Coercion -> Type
`mkCastTy` Coercion
co_k) } }
    where
      -- We need to make sure that both kinds have the same number of implicit
      -- foralls out front. If the actual kind has more, instantiate accordingly.
      -- Otherwise, just pass the type & kind through: the errors are caught
      -- in unifyType.
      n_exp_invis_bndrs :: Int
n_exp_invis_bndrs = Type -> Int
invisibleTyBndrCount Type
exp_kind
      n_act_invis_bndrs :: Int
n_act_invis_bndrs = Type -> Int
invisibleTyBndrCount Type
act_kind
      n_to_inst :: Int
n_to_inst         = Int
n_act_invis_bndrs Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
n_exp_invis_bndrs

---------------------------

tcHsContext :: Maybe (LHsContext GhcRn) -> TcM [PredType]
tcHsContext :: Maybe (LHsContext GhcRn) -> TcM [Type]
tcHsContext Maybe (LHsContext GhcRn)
Nothing    = [Type] -> TcM [Type]
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return []
tcHsContext (Just LHsContext GhcRn
cxt) = TcTyMode -> LHsContext GhcRn -> TcM [Type]
tc_hs_context TcTyMode
typeLevelMode LHsContext GhcRn
cxt

tcLHsPredType :: LHsType GhcRn -> TcM PredType
tcLHsPredType :: LHsType GhcRn -> TcM Type
tcLHsPredType LHsType GhcRn
pred = TcTyMode -> LHsType GhcRn -> TcM Type
tc_lhs_pred TcTyMode
typeLevelMode LHsType GhcRn
pred

tc_hs_context :: TcTyMode -> LHsContext GhcRn -> TcM [PredType]
tc_hs_context :: TcTyMode -> LHsContext GhcRn -> TcM [Type]
tc_hs_context TcTyMode
mode LHsContext GhcRn
ctxt = (GenLocated SrcSpanAnnA (HsType GhcRn) -> TcM Type)
-> [GenLocated SrcSpanAnnA (HsType GhcRn)] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (TcTyMode -> LHsType GhcRn -> TcM Type
tc_lhs_pred TcTyMode
mode) (GenLocated SrcSpanAnnC [GenLocated SrcSpanAnnA (HsType GhcRn)]
-> [GenLocated SrcSpanAnnA (HsType GhcRn)]
forall l e. GenLocated l e -> e
unLoc LHsContext GhcRn
GenLocated SrcSpanAnnC [GenLocated SrcSpanAnnA (HsType GhcRn)]
ctxt)

tc_lhs_pred :: TcTyMode -> LHsType GhcRn -> TcM PredType
tc_lhs_pred :: TcTyMode -> LHsType GhcRn -> TcM Type
tc_lhs_pred TcTyMode
mode LHsType GhcRn
pred = TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
pred Type
constraintKind

---------------------------
tcTyVar :: Name -> TcM (TcType, TcKind)
-- See Note [Type checking recursive type and class declarations]
-- in GHC.Tc.TyCl
-- This does not instantiate. See Note [Do not always instantiate eagerly in types]
tcTyVar :: Name -> TcM (Type, Type)
tcTyVar Name
name         -- Could be a tyvar, a tycon, or a datacon
  = do { String -> SDoc -> TcM ()
traceTc String
"lk1" (Name -> SDoc
forall a. Outputable a => a -> SDoc
ppr Name
name)
       ; TcTyThing
thing <- Name -> TcM TcTyThing
tcLookup Name
name
       ; case TcTyThing
thing of
           ATyVar Name
_ TcTyVar
tv -> (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TcTyVar -> Type
mkTyVarTy TcTyVar
tv, TcTyVar -> Type
tyVarKind TcTyVar
tv)

           -- See Note [Recursion through the kinds]
           (TcTyThing -> Maybe TyCon
tcTyThingTyCon_maybe -> Just TyCon
tc) -- TyCon or TcTyCon
             -> (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TyCon -> Type
mkTyConTy TyCon
tc, TyCon -> Type
tyConKind TyCon
tc)

           AGlobal (AConLike (RealDataCon DataCon
dc))
             -> do { Bool
data_kinds <- Extension -> TcRnIf TcGblEnv TcLclEnv Bool
forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
xoptM Extension
LangExt.DataKinds
                   ; Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Bool
data_kinds Bool -> Bool -> Bool
|| DataCon -> Bool
specialPromotedDc DataCon
dc) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
                       Name -> PromotionErr -> TcM ()
forall a. Name -> PromotionErr -> TcM a
promotionErr Name
name PromotionErr
NoDataKindsDC
                   ; Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (TyCon -> Bool
isFamInstTyCon (DataCon -> TyCon
dataConTyCon DataCon
dc)) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
                       -- see #15245
                       Name -> PromotionErr -> TcM ()
forall a. Name -> PromotionErr -> TcM a
promotionErr Name
name PromotionErr
FamDataConPE
                   ; let ([TcTyVar]
_, [TcTyVar]
_, [EqSpec]
_, [Type]
theta, [Scaled Type]
_, Type
_) = DataCon
-> ([TcTyVar], [TcTyVar], [EqSpec], [Type], [Scaled Type], Type)
dataConFullSig DataCon
dc
                   ; String -> SDoc -> TcM ()
traceTc String
"tcTyVar" (DataCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr DataCon
dc SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
theta)
                     -- promotionErr: Note [No constraints in kinds] in GHC.Tc.Validity
                   ; Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([Type] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Type]
theta) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
                     Name -> PromotionErr -> TcM ()
forall a. Name -> PromotionErr -> TcM a
promotionErr Name
name ([Type] -> PromotionErr
ConstrainedDataConPE [Type]
theta)
                   ; let tc :: TyCon
tc = DataCon -> TyCon
promoteDataCon DataCon
dc
                   ; (Type, Type) -> TcM (Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TyCon -> [Type] -> Type
mkTyConApp TyCon
tc [], TyCon -> Type
tyConKind TyCon
tc) }

           APromotionErr PromotionErr
err -> Name -> PromotionErr -> TcM (Type, Type)
forall a. Name -> PromotionErr -> TcM a
promotionErr Name
name PromotionErr
err

           TcTyThing
_  -> WrongThingSort -> TcTyThing -> Name -> TcM (Type, Type)
forall a. WrongThingSort -> TcTyThing -> Name -> TcM a
wrongThingErr WrongThingSort
WrongThingType TcTyThing
thing Name
name }

{-
Note [Recursion through the kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider these examples

Ticket #11554:
  data P (x :: k) = Q
  data A :: Type where
    MkA :: forall (a :: A). P a -> A

Ticket #12174
  data V a
  data T = forall (a :: T). MkT (V a)

The type is recursive (which is fine) but it is recursive /through the
kinds/.  In earlier versions of GHC this caused a loop in the compiler
(to do with knot-tying) but there is nothing fundamentally wrong with
the code (kinds are types, and the recursive declarations are OK). But
it's hard to distinguish "recursion through the kinds" from "recursion
through the types". Consider this (also #11554):

  data PB k (x :: k) = Q
  data B :: Type where
    MkB :: P B a -> B

Here the occurrence of B is not obviously in a kind position.

So now GHC allows all these programs.  #12081 and #15942 are other
examples.

Note [Body kind of a HsForAllTy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The body of a forall is usually a type, but in principle
there's no reason to prohibit *unlifted* types.
In fact, GHC can itself construct a function with an
unboxed tuple inside a for-all (via CPR analysis; see
typecheck/should_compile/tc170).

Moreover in instance heads we get forall-types with
kind Constraint.

It's tempting to check that the body kind is (TYPE _). But this is
wrong. For example:

  class C a b
  newtype N = Mk Foo deriving (C a)

We're doing newtype-deriving for C. But notice how `a` isn't in scope in
the predicate `C a`. So we quantify, yielding `forall a. C a` even though
`C a` has kind `* -> Constraint`. The `forall a. C a` is a bit cheeky, but
convenient. Bottom line: don't check for (TYPE _) here.

Note [Body kind of a HsQualTy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If ctxt is non-empty, the HsQualTy really is a /function/, so the
kind of the result really is '*', and in that case the kind of the
body-type can be lifted or unlifted.

However, consider
    instance Eq a => Eq [a] where ...
or
    f :: (Eq a => Eq [a]) => blah
Here both body-kind of the HsQualTy is Constraint rather than *.
Rather crudely we tell the difference by looking at exp_kind. It's
very convenient to typecheck instance types like any other HsSigType.

Admittedly the '(Eq a => Eq [a]) => blah' case is erroneous, but it's
better to reject in checkValidType.  If we say that the body kind
should be '*' we risk getting TWO error messages, one saying that Eq
[a] doesn't have kind '*', and one saying that we need a Constraint to
the left of the outer (=>).

How do we figure out the right body kind?  Well, it's a bit of a
kludge: I just look at the expected kind.  If it's Constraint, we
must be in this instance situation context. It's a kludge because it
wouldn't work if any unification was involved to compute that result
kind -- but it isn't.  (The true way might be to use the 'mode'
parameter, but that seemed like a sledgehammer to crack a nut.)

Note [Inferring tuple kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Give a tuple type (a,b,c), which the parser labels as HsBoxedOrConstraintTuple,
we try to figure out whether it's a tuple of kind * or Constraint.
  Step 1: look at the expected kind
  Step 2: infer argument kinds

If after Step 2 it's not clear from the arguments that it's
Constraint, then it must be *.  Once having decided that we re-check
the arguments to give good error messages in
  e.g.  (Maybe, Maybe)

Note that we will still fail to infer the correct kind in this case:

  type T a = ((a,a), D a)
  type family D :: Constraint -> Constraint

While kind checking T, we do not yet know the kind of D, so we will default the
kind of T to * -> *. It works if we annotate `a` with kind `Constraint`.

Note [Desugaring types]
~~~~~~~~~~~~~~~~~~~~~~~
The type desugarer is phase 2 of dealing with HsTypes.  Specifically:

  * It transforms from HsType to Type

  * It zonks any kinds.  The returned type should have no mutable kind
    or type variables (hence returning Type not TcType):
      - any unconstrained kind variables are defaulted to (Any *) just
        as in GHC.Tc.Zonk.Type.
      - there are no mutable type variables because we are
        kind-checking a type
    Reason: the returned type may be put in a TyCon or DataCon where
    it will never subsequently be zonked.

You might worry about nested scopes:
        ..a:kappa in scope..
            let f :: forall b. T '[a,b] -> Int
In this case, f's type could have a mutable kind variable kappa in it;
and we might then default it to (Any *) when dealing with f's type
signature.  But we don't expect this to happen because we can't get a
lexically scoped type variable with a mutable kind variable in it.  A
delicate point, this.  If it becomes an issue we might need to
distinguish top-level from nested uses.

Moreover
  * it cannot fail,
  * it does no unifications
  * it does no validity checking, except for structural matters, such as
        (a) spurious ! annotations.
        (b) a class used as a type

Note [Kind of a type splice]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider these terms, each with TH type splice inside:
     [| e1 :: Maybe $(..blah..) |]
     [| e2 :: $(..blah..) |]
When kind-checking the type signature, we'll kind-check the splice
$(..blah..); we want to give it a kind that can fit in any context,
as if $(..blah..) :: forall k. k.

In the e1 example, the context of the splice fixes kappa to *.  But
in the e2 example, we'll desugar the type, zonking the kind unification
variables as we go.  When we encounter the unconstrained kappa, we
want to default it to '*', not to (Any *).

-}

addTypeCtxt :: LHsType GhcRn -> TcM a -> TcM a
        -- Wrap a context around only if we want to show that contexts.
        -- Omit invisible ones and ones user's won't grok
addTypeCtxt :: forall a. LHsType GhcRn -> TcM a -> TcM a
addTypeCtxt (L SrcSpanAnnA
_ (HsWildCardTy XWildCardTy GhcRn
_)) TcM a
thing = TcM a
thing   -- "In the type '_'" just isn't helpful.
addTypeCtxt (L SrcSpanAnnA
_ HsType GhcRn
ty) TcM a
thing
  = SDoc -> TcM a -> TcM a
forall a. SDoc -> TcM a -> TcM a
addErrCtxt SDoc
doc TcM a
thing
  where
    doc :: SDoc
doc = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"In the type" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc -> SDoc
quotes (HsType GhcRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsType GhcRn
ty)


{- *********************************************************************
*                                                                      *
                Type-variable binders
*                                                                      *
********************************************************************* -}

bindNamedWildCardBinders :: [Name]
                         -> ([(Name, TcTyVar)] -> TcM a)
                         -> TcM a
-- Bring into scope the /named/ wildcard binders.  Remember that
-- plain wildcards _ are anonymous and dealt with by HsWildCardTy
-- Soe Note [The wildcard story for types] in GHC.Hs.Type
bindNamedWildCardBinders :: forall a. HsQTvsRn -> ([(Name, TcTyVar)] -> TcM a) -> TcM a
bindNamedWildCardBinders HsQTvsRn
wc_names [(Name, TcTyVar)] -> TcM a
thing_inside
  = do { [TcTyVar]
wcs <- (Name -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar)
-> HsQTvsRn -> TcM [TcTyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM Name -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newNamedWildTyVar HsQTvsRn
wc_names
       ; let wc_prs :: [(Name, TcTyVar)]
wc_prs = HsQTvsRn
wc_names HsQTvsRn -> [TcTyVar] -> [(Name, TcTyVar)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [TcTyVar]
wcs
       ; [(Name, TcTyVar)] -> TcM a -> TcM a
forall r. [(Name, TcTyVar)] -> TcM r -> TcM r
tcExtendNameTyVarEnv [(Name, TcTyVar)]
wc_prs (TcM a -> TcM a) -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$
         [(Name, TcTyVar)] -> TcM a
thing_inside [(Name, TcTyVar)]
wc_prs }

newNamedWildTyVar :: Name -> TcM TcTyVar
-- ^ New unification variable '_' for a wildcard
newNamedWildTyVar :: Name -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newNamedWildTyVar Name
_name   -- Currently ignoring the "_x" wildcard name used in the type
  = do { Type
kind <- TcM Type
newMetaKindVar
       ; TcTyVarDetails
details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
TauTv
       ; Name
wc_name <- FastString -> TcM Name
newMetaTyVarName (String -> FastString
fsLit String
"w")   -- See Note [Wildcard names]
       ; let tyvar :: TcTyVar
tyvar = Name -> Type -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
wc_name Type
kind TcTyVarDetails
details
       ; String -> SDoc -> TcM ()
traceTc String
"newWildTyVar" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tyvar)
       ; TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TcTyVar
tyvar }

---------------------------
tcAnonWildCardOcc :: IsExtraConstraint
                  -> TcTyMode -> HsType GhcRn -> Kind -> TcM TcType
tcAnonWildCardOcc :: IsExtraConstraint -> TcTyMode -> HsType GhcRn -> Type -> TcM Type
tcAnonWildCardOcc IsExtraConstraint
is_extra (TcTyMode { mode_holes :: TcTyMode -> HoleInfo
mode_holes = Just (TcLevel
hole_lvl, HoleMode
hole_mode) })
                  HsType GhcRn
ty Type
exp_kind
    -- hole_lvl: see Note [Checking partial type signatures]
    --           esp the bullet on nested forall types
  = do { TcTyVarDetails
kv_details <- TcLevel -> TcM TcTyVarDetails
newTauTvDetailsAtLevel TcLevel
hole_lvl
       ; Name
kv_name    <- FastString -> TcM Name
newMetaTyVarName (String -> FastString
fsLit String
"k")
       ; TcTyVarDetails
wc_details <- TcLevel -> TcM TcTyVarDetails
newTauTvDetailsAtLevel TcLevel
hole_lvl
       ; Name
wc_name    <- FastString -> TcM Name
newMetaTyVarName (String -> FastString
fsLit String
wc_nm)
       ; let kv :: TcTyVar
kv      = Name -> Type -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
kv_name Type
liftedTypeKind TcTyVarDetails
kv_details
             wc_kind :: Type
wc_kind = TcTyVar -> Type
mkTyVarTy TcTyVar
kv
             wc_tv :: TcTyVar
wc_tv   = Name -> Type -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
wc_name Type
wc_kind TcTyVarDetails
wc_details

       ; String -> SDoc -> TcM ()
traceTc String
"tcAnonWildCardOcc" (TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
hole_lvl SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bool
emit_holes)
       ; Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
emit_holes (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
         IsExtraConstraint -> TcTyVar -> TcM ()
emitAnonTypeHole IsExtraConstraint
is_extra TcTyVar
wc_tv
         -- Why the 'when' guard?
         -- See Note [Wildcards in visible kind application]

       -- You might think that this would always just unify
       -- wc_kind with exp_kind, so we could avoid even creating kv
       -- But the level numbers might not allow that unification,
       -- so we have to do it properly (T14140a)
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind HsType GhcRn
ty (TcTyVar -> Type
mkTyVarTy TcTyVar
wc_tv) Type
wc_kind Type
exp_kind }
  where
     -- See Note [Wildcard names]
     wc_nm :: String
wc_nm = case HoleMode
hole_mode of
               HoleMode
HM_Sig      -> String
"w"
               HoleMode
HM_FamPat   -> String
"_"
               HoleMode
HM_VTA      -> String
"w"
               HoleMode
HM_TyAppPat -> String
"_"

     emit_holes :: Bool
emit_holes = case HoleMode
hole_mode of
                     HoleMode
HM_Sig     -> Bool
True
                     HoleMode
HM_FamPat  -> Bool
False
                     HoleMode
HM_VTA     -> Bool
False
                     HoleMode
HM_TyAppPat -> Bool
False

tcAnonWildCardOcc IsExtraConstraint
is_extra TcTyMode
_ HsType GhcRn
_ Type
_
-- mode_holes is Nothing. This means we have an anonymous wildcard
-- in an unexpected place. The renamer rejects these wildcards in 'checkAnonWildcard',
-- but it is possible for a wildcard to be introduced by a Template Haskell splice,
-- as per #15433. To account for this, we throw a generic catch-all error message.
  = TcRnMessage -> TcM Type
forall a. TcRnMessage -> TcM a
failWith (TcRnMessage -> TcM Type) -> TcRnMessage -> TcM Type
forall a b. (a -> b) -> a -> b
$ Maybe Name -> BadAnonWildcardContext -> TcRnMessage
TcRnIllegalWildcardInType Maybe Name
forall a. Maybe a
Nothing BadAnonWildcardContext
reason
    where
      reason :: BadAnonWildcardContext
reason =
        case IsExtraConstraint
is_extra of
          IsExtraConstraint
YesExtraConstraint ->
            SoleExtraConstraintWildcardAllowed -> BadAnonWildcardContext
ExtraConstraintWildcardNotAllowed
              SoleExtraConstraintWildcardAllowed
SoleExtraConstraintWildcardNotAllowed
          IsExtraConstraint
NoExtraConstraint  ->
            BadAnonWildcardContext
WildcardsNotAllowedAtAll

{- Note [Wildcard names]
~~~~~~~~~~~~~~~~~~~~~~~~
So we hackily use the mode_holes flag to control the name used
for wildcards:

* For proper holes (whether in a visible type application (VTA) or no),
  we rename the '_' to 'w'. This is so that we see variables like 'w0'
  or 'w1' in error messages, a vast improvement upon '_0' and '_1'. For
  example, we prefer
       Found type wildcard ‘_’ standing for ‘w0’
  over
       Found type wildcard ‘_’ standing for ‘_1’

  Even in the VTA case, where we do not emit an error to be printed, we
  want to do the renaming, as the variables may appear in other,
  non-wildcard error messages.

* However, holes in the left-hand sides of type families ("type
  patterns") stand for type variables which we do not care to name --
  much like the use of an underscore in an ordinary term-level
  pattern. When we spot these, we neither wish to generate an error
  message nor to rename the variable.  We don't rename the variable so
  that we can pretty-print a type family LHS as, e.g.,
    F _ Int _ = ...
  and not
     F w1 Int w2 = ...

  See also Note [Wildcards in family instances] in
  GHC.Rename.Module. The choice of HM_FamPat is made in
  tcFamTyPats. There is also some unsavory magic, relying on that
  underscore, in GHC.Core.Coercion.tidyCoAxBndrsForUser.

Note [Wildcards in visible kind application]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are cases where users might want to pass in a wildcard as a visible kind
argument, for instance:

data T :: forall k1 k2. k1 → k2 → Type where
  MkT :: T a b
x :: T @_ @Nat False n
x = MkT

So we should allow '@_' without emitting any hole constraints, and
regardless of whether PartialTypeSignatures is enabled or not. But how
would the typechecker know which '_' is being used in VKA and which is
not when it calls emitNamedTypeHole in
tcHsPartialSigType on all HsWildCardBndrs?  The solution is to neither
rename nor include unnamed wildcards in HsWildCardBndrs, but instead
give every anonymous wildcard a fresh wild tyvar in tcAnonWildCardOcc.

And whenever we see a '@', we set mode_holes to HM_VKA, so that
we do not call emitAnonTypeHole in tcAnonWildCardOcc.
See related Note [Wildcards in visible type application] here and
Note [The wildcard story for types] in GHC.Hs.Type
-}

{- *********************************************************************
*                                                                      *
             Kind inference for type declarations
*                                                                      *
********************************************************************* -}

-- See Note [kcCheckDeclHeader vs kcInferDeclHeader]
data InitialKindStrategy
  = InitialKindCheck SAKS_or_CUSK
  | InitialKindInfer

-- Does the declaration have a standalone kind signature (SAKS) or a complete
-- user-supplied kind (CUSK)?
data SAKS_or_CUSK
  = SAKS Kind  -- Standalone kind signature, fully zonked! (zonkTcTypeToType)
  | CUSK       -- Complete user-supplied kind (CUSK)

instance Outputable SAKS_or_CUSK where
  ppr :: SAKS_or_CUSK -> SDoc
ppr (SAKS Type
k) = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"SAKS" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
k
  ppr SAKS_or_CUSK
CUSK = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"CUSK"

-- See Note [kcCheckDeclHeader vs kcInferDeclHeader]
kcDeclHeader
  :: InitialKindStrategy
  -> Name               -- ^ of the thing being checked
  -> TyConFlavour TyCon -- ^ What sort of 'TyCon' is being checked
  -> LHsQTyVars GhcRn   -- ^ Binders in the header
  -> TcM ContextKind    -- ^ The result kind
  -> TcM TcTyCon        -- ^ A suitably-kinded TcTyCon
kcDeclHeader :: InitialKindStrategy
-> Name
-> TyConFlavour TyCon
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcDeclHeader (InitialKindCheck SAKS_or_CUSK
msig) = SAKS_or_CUSK
-> Name
-> TyConFlavour TyCon
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcCheckDeclHeader SAKS_or_CUSK
msig
kcDeclHeader InitialKindStrategy
InitialKindInfer = Name
-> TyConFlavour TyCon
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcInferDeclHeader

{- Note [kcCheckDeclHeader vs kcInferDeclHeader]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
kcCheckDeclHeader and kcInferDeclHeader are responsible for getting the initial kind
of a type constructor.

* kcCheckDeclHeader: the TyCon has a standalone kind signature or a CUSK. In that
  case, find the full, final, poly-kinded kind of the TyCon.  It's very like a
  term-level binding where we have a complete type signature for the function.

* kcInferDeclHeader: the TyCon has neither a standalone kind signature nor a
  CUSK. Find a monomorphic kind, with unification variables in it; they will be
  generalised later.  It's very like a term-level binding where we do not have a
  type signature (or, more accurately, where we have a partial type signature),
  so we infer the type and generalise.
-}

------------------------------
kcCheckDeclHeader
  :: SAKS_or_CUSK
  -> Name               -- ^ of the thing being checked
  -> TyConFlavour TyCon -- ^ What sort of 'TyCon' is being checked
  -> LHsQTyVars GhcRn   -- ^ Binders in the header
  -> TcM ContextKind    -- ^ The result kind. AnyKind == no result signature
  -> TcM PolyTcTyCon    -- ^ A suitably-kinded generalized TcTyCon
kcCheckDeclHeader :: SAKS_or_CUSK
-> Name
-> TyConFlavour TyCon
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcCheckDeclHeader (SAKS Type
sig) = Type
-> Name
-> TyConFlavour TyCon
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcCheckDeclHeader_sig Type
sig
kcCheckDeclHeader SAKS_or_CUSK
CUSK       = Name
-> TyConFlavour TyCon
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcCheckDeclHeader_cusk

kcCheckDeclHeader_cusk
  :: Name               -- ^ of the thing being checked
  -> TyConFlavour TyCon -- ^ What sort of 'TyCon' is being checked
  -> LHsQTyVars GhcRn   -- ^ Binders in the header
  -> TcM ContextKind    -- ^ The result kind
  -> TcM PolyTcTyCon    -- ^ A suitably-kinded generalized TcTyCon
kcCheckDeclHeader_cusk :: Name
-> TyConFlavour TyCon
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcCheckDeclHeader_cusk Name
name TyConFlavour TyCon
flav
              (HsQTvs { hsq_ext :: forall pass. LHsQTyVars pass -> XHsQTvs pass
hsq_ext = XHsQTvs GhcRn
kv_ns
                      , hsq_explicit :: forall pass.
LHsQTyVars pass -> [LHsTyVarBndr (HsBndrVis pass) pass]
hsq_explicit = [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
hs_tvs }) TcM ContextKind
kc_res_ki
  -- CUSK case
  -- See Note [Required, Specified, and Inferred for types] in GHC.Tc.TyCl
  = Name -> TyConFlavour TyCon -> TcM TyCon -> TcM TyCon
forall tc a. Name -> TyConFlavour tc -> TcM a -> TcM a
addTyConFlavCtxt Name
name TyConFlavour TyCon
flav (TcM TyCon -> TcM TyCon) -> TcM TyCon -> TcM TyCon
forall a b. (a -> b) -> a -> b
$
    do { SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo SkolemInfoAnon
skol_info_anon
       ; (TcLevel
tclvl, WantedConstraints
wanted, ([TcTyVar]
scoped_kvs, ([VarBndr TcTyVar (HsBndrVis GhcRn)]
tc_bndrs, Type
res_kind)))
           <- String
-> TcM ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type))
-> TcM
     (TcLevel, WantedConstraints,
      ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)))
forall a. String -> TcM a -> TcM (TcLevel, WantedConstraints, a)
pushLevelAndSolveEqualitiesX String
"kcCheckDeclHeader_cusk" (TcM ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type))
 -> TcM
      (TcLevel, WantedConstraints,
       ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type))))
-> TcM ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type))
-> TcM
     (TcLevel, WantedConstraints,
      ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)))
forall a b. (a -> b) -> a -> b
$
              SkolemInfo
-> HsQTvsRn
-> TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
-> TcM ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type))
forall a. SkolemInfo -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrs_Q_Skol SkolemInfo
skol_info HsQTvsRn
XHsQTvs GhcRn
kv_ns                      (TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
 -> TcM ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)))
-> TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
-> TcM ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type))
forall a b. (a -> b) -> a -> b
$
              SkolemInfo
-> ContextKind
-> [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
-> TcM Type
-> TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemInfo
-> ContextKind
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrs_Q_Skol SkolemInfo
skol_info ContextKind
ctxt_kind [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
hs_tvs           (TcM Type -> TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type))
-> TcM Type -> TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
forall a b. (a -> b) -> a -> b
$
              ContextKind -> TcM Type
newExpectedKind (ContextKind -> TcM Type) -> TcM ContextKind -> TcM Type
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< TcM ContextKind
kc_res_ki

           -- Now, because we're in a CUSK,
           -- we quantify over the mentioned kind vars
       ; let spec_req_tkvs :: [TcTyVar]
spec_req_tkvs = [TcTyVar]
scoped_kvs [TcTyVar] -> [TcTyVar] -> [TcTyVar]
forall a. [a] -> [a] -> [a]
++ [VarBndr TcTyVar (HsBndrVis GhcRn)] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [VarBndr TcTyVar (HsBndrVis GhcRn)]
tc_bndrs
             all_kinds :: [Type]
all_kinds     = Type
res_kind Type -> [Type] -> [Type]
forall a. a -> [a] -> [a]
: (TcTyVar -> Type) -> [TcTyVar] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map TcTyVar -> Type
tyVarKind [TcTyVar]
spec_req_tkvs

       ; CandidatesQTvs
candidates <- [Type] -> TcM CandidatesQTvs
candidateQTyVarsOfKinds [Type]
all_kinds
             -- 'candidates' are all the variables that we are going to
             -- skolemise and then quantify over.  We do not include spec_req_tvs
             -- because they are /already/ skolems

       ; [TcTyVar]
inferred <- SkolemInfo
-> NonStandardDefaultingStrategy -> CandidatesQTvs -> TcM [TcTyVar]
quantifyTyVars SkolemInfo
skol_info NonStandardDefaultingStrategy
DefaultNonStandardTyVars (CandidatesQTvs -> TcM [TcTyVar])
-> CandidatesQTvs -> TcM [TcTyVar]
forall a b. (a -> b) -> a -> b
$
                     CandidatesQTvs
candidates CandidatesQTvs -> [TcTyVar] -> CandidatesQTvs
`delCandidates` [TcTyVar]
spec_req_tkvs
                     -- NB: 'inferred' comes back sorted in dependency order

       ; ([TcTyVar]
scoped_kvs, [VarBndr TcTyVar (HsBndrVis GhcRn)]
tc_bndrs, Type
res_kind) <- ZonkM ([TcTyVar], [VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
-> TcM ([TcTyVar], [VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM ([TcTyVar], [VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
 -> TcM ([TcTyVar], [VarBndr TcTyVar (HsBndrVis GhcRn)], Type))
-> ZonkM ([TcTyVar], [VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
-> TcM ([TcTyVar], [VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
forall a b. (a -> b) -> a -> b
$
          do { [TcTyVar]
scoped_kvs <- (TcTyVar -> ZonkM TcTyVar) -> [TcTyVar] -> ZonkM [TcTyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM TcTyVar -> ZonkM TcTyVar
zonkTyCoVarKind [TcTyVar]
scoped_kvs      -- scoped_kvs and tc_bndrs are skolems,
             ; [VarBndr TcTyVar (HsBndrVis GhcRn)]
tc_bndrs   <- (VarBndr TcTyVar (HsBndrVis GhcRn)
 -> ZonkM (VarBndr TcTyVar (HsBndrVis GhcRn)))
-> [VarBndr TcTyVar (HsBndrVis GhcRn)]
-> ZonkM [VarBndr TcTyVar (HsBndrVis GhcRn)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM VarBndr TcTyVar (HsBndrVis GhcRn)
-> ZonkM (VarBndr TcTyVar (HsBndrVis GhcRn))
forall flag. VarBndr TcTyVar flag -> ZonkM (VarBndr TcTyVar flag)
zonkTyCoVarBndrKind [VarBndr TcTyVar (HsBndrVis GhcRn)]
tc_bndrs    -- so zonkTyCoVarBndrKind suffices
             ; Type
res_kind   <- Type -> ZonkM Type
zonkTcType Type
res_kind
             ; ([TcTyVar], [VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
-> ZonkM ([TcTyVar], [VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
forall a. a -> ZonkM a
forall (m :: * -> *) a. Monad m => a -> m a
return ([TcTyVar]
scoped_kvs, [VarBndr TcTyVar (HsBndrVis GhcRn)]
tc_bndrs, Type
res_kind) }

       ; let mentioned_kv_set :: TyVarSet
mentioned_kv_set = CandidatesQTvs -> TyVarSet
candidateKindVars CandidatesQTvs
candidates
             specified :: [TcTyVar]
specified        = [TcTyVar] -> [TcTyVar]
scopedSort [TcTyVar]
scoped_kvs
                                -- NB: maintain the L-R order of scoped_kvs

             all_tcbs :: [TyConBinder]
all_tcbs =  ForAllTyFlag -> [TcTyVar] -> [TyConBinder]
mkNamedTyConBinders ForAllTyFlag
Inferred  [TcTyVar]
inferred
                      [TyConBinder] -> [TyConBinder] -> [TyConBinder]
forall a. [a] -> [a] -> [a]
++ ForAllTyFlag -> [TcTyVar] -> [TyConBinder]
mkNamedTyConBinders ForAllTyFlag
Specified [TcTyVar]
specified
                      [TyConBinder] -> [TyConBinder] -> [TyConBinder]
forall a. [a] -> [a] -> [a]
++ (VarBndr TcTyVar (HsBndrVis GhcRn) -> TyConBinder)
-> [VarBndr TcTyVar (HsBndrVis GhcRn)] -> [TyConBinder]
forall a b. (a -> b) -> [a] -> [b]
map (TyVarSet -> VarBndr TcTyVar (HsBndrVis GhcRn) -> TyConBinder
mkExplicitTyConBinder TyVarSet
mentioned_kv_set) [VarBndr TcTyVar (HsBndrVis GhcRn)]
tc_bndrs

       -- Eta expand if necessary; we are building a PolyTyCon
       ; ([TyConBinder]
eta_tcbs, Type
res_kind) <- TyConFlavour TyCon
-> SkolemInfo -> [TyConBinder] -> Type -> TcM ([TyConBinder], Type)
forall tc.
TyConFlavour tc
-> SkolemInfo -> [TyConBinder] -> Type -> TcM ([TyConBinder], Type)
etaExpandAlgTyCon TyConFlavour TyCon
flav SkolemInfo
skol_info [TyConBinder]
all_tcbs Type
res_kind

       ; let all_tv_prs :: [(Name, TcTyVar)]
all_tv_prs = [TcTyVar] -> [(Name, TcTyVar)]
mkTyVarNamePairs ([TcTyVar]
scoped_kvs [TcTyVar] -> [TcTyVar] -> [TcTyVar]
forall a. [a] -> [a] -> [a]
++ [VarBndr TcTyVar (HsBndrVis GhcRn)] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [VarBndr TcTyVar (HsBndrVis GhcRn)]
tc_bndrs)
             final_tcbs :: [TyConBinder]
final_tcbs = [TyConBinder]
all_tcbs [TyConBinder] -> [TyConBinder] -> [TyConBinder]
forall a. [a] -> [a] -> [a]
`chkAppend` [TyConBinder]
eta_tcbs
             tycon :: TyCon
tycon = Name
-> [TyConBinder]
-> Type
-> [(Name, TcTyVar)]
-> Bool
-> TyConFlavour TyCon
-> TyCon
mkTcTyCon Name
name [TyConBinder]
final_tcbs Type
res_kind [(Name, TcTyVar)]
all_tv_prs
                               Bool
True -- Make a PolyTcTyCon, fully generalised
                               TyConFlavour TyCon
flav

       ; SkolemInfo -> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM ()
reportUnsolvedEqualities SkolemInfo
skol_info ([TyConBinder] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [TyConBinder]
final_tcbs)
                                  TcLevel
tclvl WantedConstraints
wanted

         -- If the ordering from
         -- Note [Required, Specified, and Inferred for types] in GHC.Tc.TyCl
         -- doesn't work, we catch it here, before an error cascade
       ; TyCon -> TcM ()
checkTyConTelescope TyCon
tycon

       ; String -> SDoc -> TcM ()
traceTc String
"kcCheckDeclHeader_cusk " (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"name" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Name -> SDoc
forall a. Outputable a => a -> SDoc
ppr Name
name
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"candidates" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> CandidatesQTvs -> SDoc
forall a. Outputable a => a -> SDoc
ppr CandidatesQTvs
candidates
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"mentioned_kv_set" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> TyVarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVarSet
mentioned_kv_set
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"kv_ns" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> HsQTvsRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsQTvsRn
XHsQTvs GhcRn
kv_ns
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"hs_tvs" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
-> SDoc
forall a. Outputable a => a -> SDoc
ppr [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_tvs
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"scoped_kvs" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
scoped_kvs
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"spec_req_tvs" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [TcTyVar] -> SDoc
pprTyVars [TcTyVar]
spec_req_tkvs
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"all_kinds" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
all_kinds
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tc_tvs" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [TcTyVar] -> SDoc
pprTyVars ([VarBndr TcTyVar (HsBndrVis GhcRn)] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [VarBndr TcTyVar (HsBndrVis GhcRn)]
tc_bndrs)
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"res_kind" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
res_kind
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"inferred" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
inferred
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"specified" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
specified
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"final_tcbs" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [TyConBinder] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TyConBinder]
final_tcbs
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"mkTyConKind final_tc_bndrs res_kind"
                SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr ([TyConBinder] -> Type -> Type
mkTyConKind [TyConBinder]
final_tcbs Type
res_kind)
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"all_tv_prs" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [(Name, TcTyVar)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [(Name, TcTyVar)]
all_tv_prs ]

       ; TyCon -> TcM TyCon
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TyCon
tycon }
  where
    skol_info_anon :: SkolemInfoAnon
skol_info_anon = TyConFlavour TyCon -> Name -> SkolemInfoAnon
TyConSkol TyConFlavour TyCon
flav Name
name
    ctxt_kind :: ContextKind
ctxt_kind | TyConFlavour TyCon -> Bool
forall tc. TyConFlavour tc -> Bool
tcFlavourIsOpen TyConFlavour TyCon
flav = Type -> ContextKind
TheKind Type
liftedTypeKind
              | Bool
otherwise            = ContextKind
AnyKind

-- | Create a TyConBinder for a user-written type variable binder.
mkExplicitTyConBinder :: TyCoVarSet -- variables that are used dependently
                      -> VarBndr TyVar (HsBndrVis GhcRn)
                      -> TyConBinder
mkExplicitTyConBinder :: TyVarSet -> VarBndr TcTyVar (HsBndrVis GhcRn) -> TyConBinder
mkExplicitTyConBinder TyVarSet
dep_set (Bndr TcTyVar
tv HsBndrVis GhcRn
flag) =
  case HsBndrVis GhcRn
flag of
    HsBndrVis GhcRn
HsBndrRequired    -> TyVarSet -> TcTyVar -> TyConBinder
mkRequiredTyConBinder TyVarSet
dep_set TcTyVar
tv
    HsBndrInvisible{} -> ForAllTyFlag -> TcTyVar -> TyConBinder
mkNamedTyConBinder ForAllTyFlag
Specified TcTyVar
tv

-- | Kind-check a 'LHsQTyVars'. Used in 'inferInitialKind' (for tycon kinds and
-- other kinds).
--
-- This function does not do telescope checking.
kcInferDeclHeader
  :: Name               -- ^ of the thing being checked
  -> TyConFlavour TyCon -- ^ What sort of 'TyCon' is being checked
  -> LHsQTyVars GhcRn
  -> TcM ContextKind    -- ^ The result kind
  -> TcM MonoTcTyCon    -- ^ A suitably-kinded non-generalized TcTyCon
kcInferDeclHeader :: Name
-> TyConFlavour TyCon
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcInferDeclHeader Name
name TyConFlavour TyCon
flav
              (HsQTvs { hsq_ext :: forall pass. LHsQTyVars pass -> XHsQTvs pass
hsq_ext = XHsQTvs GhcRn
kv_ns
                      , hsq_explicit :: forall pass.
LHsQTyVars pass -> [LHsTyVarBndr (HsBndrVis pass) pass]
hsq_explicit = [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
hs_bndrs }) TcM ContextKind
kc_res_ki
  -- No standalone kind signature and no CUSK.
  -- See Note [Required, Specified, and Inferred for types] in GHC.Tc.TyCl
  = Name -> TyConFlavour TyCon -> TcM TyCon -> TcM TyCon
forall tc a. Name -> TyConFlavour tc -> TcM a -> TcM a
addTyConFlavCtxt Name
name TyConFlavour TyCon
flav (TcM TyCon -> TcM TyCon) -> TcM TyCon -> TcM TyCon
forall a b. (a -> b) -> a -> b
$
    do { Name -> [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn] -> TcM ()
rejectInvisibleBinders Name
name [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
hs_bndrs
       ; ([TcTyVar]
scoped_kvs, ([VarBndr TcTyVar (HsBndrVis GhcRn)]
tc_bndrs, Type
res_kind))
           -- Why bindImplicitTKBndrs_Q_Tv which uses newTyVarTyVar?
           -- See Note [Inferring kinds for type declarations] in GHC.Tc.TyCl
           <- HsQTvsRn
-> TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
-> TcM ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type))
forall a. HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrs_Q_Tv HsQTvsRn
XHsQTvs GhcRn
kv_ns              (TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
 -> TcM ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)))
-> TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
-> TcM ([TcTyVar], ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type))
forall a b. (a -> b) -> a -> b
$
              ContextKind
-> [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
-> TcM Type
-> TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
ContextKind
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrs_Q_Tv ContextKind
ctxt_kind [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
hs_bndrs (TcM Type -> TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type))
-> TcM Type -> TcM ([VarBndr TcTyVar (HsBndrVis GhcRn)], Type)
forall a b. (a -> b) -> a -> b
$
              ContextKind -> TcM Type
newExpectedKind (ContextKind -> TcM Type) -> TcM ContextKind -> TcM Type
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< TcM ContextKind
kc_res_ki
              -- Why "_Tv" not "_Skol"? See third wrinkle in
              -- Note [Inferring kinds for type declarations] in GHC.Tc.TyCl,

       ; let   -- NB: Don't add scoped_kvs to tyConTyVars, because they
               -- might unify with kind vars in other types in a mutually
               -- recursive group.
               -- See Note [Inferring kinds for type declarations] in GHC.Tc.TyCl

             tc_tvs :: [TcTyVar]
tc_tvs = [VarBndr TcTyVar (HsBndrVis GhcRn)] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [VarBndr TcTyVar (HsBndrVis GhcRn)]
tc_bndrs
               -- Discard visibility flags. We made sure all of them are HsBndrRequired
               -- by the call to rejectInvisibleBinders above.

             tc_binders :: [TyConBinder]
tc_binders = [TcTyVar] -> [TyConBinder]
mkAnonTyConBinders [TcTyVar]
tc_tvs
               -- This has to be mkAnonTyConBinder!
               -- See Note [No polymorphic recursion in type decls] in GHC.Tc.TyCl
               --
               -- Also, note that tc_binders has the tyvars from only the
               -- user-written type variable binders.
               -- See S1 Note [TcTyCon, MonoTcTyCon, and PolyTcTyCon] in GHC.Tc.TyCl

             all_tv_prs :: [(Name, TcTyVar)]
all_tv_prs = [TcTyVar] -> [(Name, TcTyVar)]
mkTyVarNamePairs ([TcTyVar]
scoped_kvs [TcTyVar] -> [TcTyVar] -> [TcTyVar]
forall a. [a] -> [a] -> [a]
++ [TcTyVar]
tc_tvs)
               -- NB: bindExplicitTKBndrs_Q_Tv does not clone;
               --     ditto Implicit
               -- See Note [Cloning for type variable binders]

             tycon :: TyCon
tycon = Name
-> [TyConBinder]
-> Type
-> [(Name, TcTyVar)]
-> Bool
-> TyConFlavour TyCon
-> TyCon
mkTcTyCon Name
name [TyConBinder]
tc_binders Type
res_kind [(Name, TcTyVar)]
all_tv_prs
                               Bool
False -- Make a MonoTcTyCon
                               TyConFlavour TyCon
flav

       ; String -> SDoc -> TcM ()
traceTc String
"kcInferDeclHeader: not-cusk" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ Name -> SDoc
forall a. Outputable a => a -> SDoc
ppr Name
name, HsQTvsRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsQTvsRn
XHsQTvs GhcRn
kv_ns, [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
-> SDoc
forall a. Outputable a => a -> SDoc
ppr [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_bndrs
              , [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
scoped_kvs
              , [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
tc_tvs, Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr ([TyConBinder] -> Type -> Type
mkTyConKind [TyConBinder]
tc_binders Type
res_kind) ]
       ; TyCon -> TcM TyCon
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TyCon
tycon }
  where
    ctxt_kind :: ContextKind
ctxt_kind | TyConFlavour TyCon -> Bool
forall tc. TyConFlavour tc -> Bool
tcFlavourIsOpen TyConFlavour TyCon
flav = Type -> ContextKind
TheKind Type
liftedTypeKind
              | Bool
otherwise            = ContextKind
AnyKind

-- rejectInvisibleBinders is called on on the inference code path; there is
-- no standalone kind signature, nor CUSK.
-- See Note [No inference for invisible binders in type decls] in GHC.Tc.TyCl
rejectInvisibleBinders :: Name -> [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn] -> TcM ()
rejectInvisibleBinders :: Name -> [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn] -> TcM ()
rejectInvisibleBinders Name
name = (GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
 -> TcM ())
-> [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
-> TcM ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ LHsTyVarBndr (HsBndrVis GhcRn) GhcRn -> TcM ()
GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
-> TcM ()
check_bndr_vis
  where
    check_bndr_vis :: LHsTyVarBndr (HsBndrVis GhcRn) GhcRn -> TcM ()
    check_bndr_vis :: LHsTyVarBndr (HsBndrVis GhcRn) GhcRn -> TcM ()
check_bndr_vis LHsTyVarBndr (HsBndrVis GhcRn) GhcRn
bndr =
      Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (HsBndrVis GhcRn -> Bool
forall pass. HsBndrVis pass -> Bool
isHsBndrInvisible (HsTyVarBndr (HsBndrVis GhcRn) GhcRn -> HsBndrVis GhcRn
forall flag (pass :: Pass). HsTyVarBndr flag (GhcPass pass) -> flag
hsTyVarBndrFlag (GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
-> HsTyVarBndr (HsBndrVis GhcRn) GhcRn
forall l e. GenLocated l e -> e
unLoc LHsTyVarBndr (HsBndrVis GhcRn) GhcRn
GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
bndr))) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
        TcRnMessage -> TcM ()
addErr (Name -> LHsTyVarBndr (HsBndrVis GhcRn) GhcRn -> TcRnMessage
TcRnInvisBndrWithoutSig Name
name LHsTyVarBndr (HsBndrVis GhcRn) GhcRn
bndr)

-- | Kind-check a declaration header against a standalone kind signature.
-- See Note [kcCheckDeclHeader_sig]
kcCheckDeclHeader_sig
  :: Kind               -- ^ Standalone kind signature, fully zonked! (zonkTcTypeToType)
  -> Name               -- ^ of the thing being checked
  -> TyConFlavour TyCon -- ^ What sort of 'TyCon' is being checked
  -> LHsQTyVars GhcRn   -- ^ Binders in the header
  -> TcM ContextKind    -- ^ The result kind. AnyKind == no result signature
  -> TcM PolyTcTyCon    -- ^ A suitably-kinded, fully generalised TcTyCon
-- Postcondition to (kcCheckDeclHeader_sig sig_kind n f hs_tvs kc_res_ki):
--   kind(returned PolyTcTyCon) = sig_kind
--
kcCheckDeclHeader_sig :: Type
-> Name
-> TyConFlavour TyCon
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcCheckDeclHeader_sig Type
sig_kind Name
name TyConFlavour TyCon
flav
          (HsQTvs { hsq_ext :: forall pass. LHsQTyVars pass -> XHsQTvs pass
hsq_ext      = XHsQTvs GhcRn
implicit_nms
                  , hsq_explicit :: forall pass.
LHsQTyVars pass -> [LHsTyVarBndr (HsBndrVis pass) pass]
hsq_explicit = [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
hs_tv_bndrs }) TcM ContextKind
kc_res_ki
  = Name -> TyConFlavour TyCon -> TcM TyCon -> TcM TyCon
forall tc a. Name -> TyConFlavour tc -> TcM a -> TcM a
addTyConFlavCtxt Name
name TyConFlavour TyCon
flav (TcM TyCon -> TcM TyCon) -> TcM TyCon -> TcM TyCon
forall a b. (a -> b) -> a -> b
$
    do { SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo (TyConFlavour TyCon -> Name -> SkolemInfoAnon
TyConSkol TyConFlavour TyCon
flav Name
name)
       ; ([TyConBinder]
sig_tcbs :: [TcTyConBinder], Type
sig_res_kind :: Kind)
             <- SkolemInfo
-> InScopeSet -> [OccName] -> Type -> TcM ([TyConBinder], Type)
splitTyConKind SkolemInfo
skol_info InScopeSet
emptyInScopeSet
                               ((GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
 -> OccName)
-> [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
-> [OccName]
forall a b. (a -> b) -> [a] -> [b]
map GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
-> OccName
forall a. NamedThing a => a -> OccName
getOccName [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_tv_bndrs) Type
sig_kind

       ; String -> SDoc -> TcM ()
traceTc String
"kcCheckDeclHeader_sig {" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
           [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"sig_kind:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
sig_kind
                , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"sig_tcbs:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [TyConBinder] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TyConBinder]
sig_tcbs
                , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"sig_res_kind:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
sig_res_kind
                , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"implict_nms:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> HsQTvsRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsQTvsRn
XHsQTvs GhcRn
implicit_nms
                , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"hs_tv_bndrs:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
-> SDoc
forall a. Outputable a => a -> SDoc
ppr [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_tv_bndrs ]

       ; (TcLevel
tclvl, WantedConstraints
wanted, ([TcTyVar]
implicit_tvs, ([TyConBinder]
skol_tcbs, [TcTyVar]
skol_scoped_tvs, ([TyConBinder]
extra_tcbs, Type
tycon_res_kind))))
           <- String
-> TcM
     ([TcTyVar], ([TyConBinder], [TcTyVar], ([TyConBinder], Type)))
-> TcM
     (TcLevel, WantedConstraints,
      ([TcTyVar], ([TyConBinder], [TcTyVar], ([TyConBinder], Type))))
forall a. String -> TcM a -> TcM (TcLevel, WantedConstraints, a)
pushLevelAndSolveEqualitiesX String
"kcCheckDeclHeader_sig" (TcM ([TcTyVar], ([TyConBinder], [TcTyVar], ([TyConBinder], Type)))
 -> TcM
      (TcLevel, WantedConstraints,
       ([TcTyVar], ([TyConBinder], [TcTyVar], ([TyConBinder], Type)))))
-> TcM
     ([TcTyVar], ([TyConBinder], [TcTyVar], ([TyConBinder], Type)))
-> TcM
     (TcLevel, WantedConstraints,
      ([TcTyVar], ([TyConBinder], [TcTyVar], ([TyConBinder], Type))))
forall a b. (a -> b) -> a -> b
$  -- #16687
              HsQTvsRn
-> TcM ([TyConBinder], [TcTyVar], ([TyConBinder], Type))
-> TcM
     ([TcTyVar], ([TyConBinder], [TcTyVar], ([TyConBinder], Type)))
forall a. HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrs_Q_Tv HsQTvsRn
XHsQTvs GhcRn
implicit_nms                (TcM ([TyConBinder], [TcTyVar], ([TyConBinder], Type))
 -> TcM
      ([TcTyVar], ([TyConBinder], [TcTyVar], ([TyConBinder], Type))))
-> TcM ([TyConBinder], [TcTyVar], ([TyConBinder], Type))
-> TcM
     ([TcTyVar], ([TyConBinder], [TcTyVar], ([TyConBinder], Type)))
forall a b. (a -> b) -> a -> b
$  -- Q means don't clone
              Name
-> [TyConBinder]
-> Type
-> [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
-> ([TyConBinder] -> Type -> TcM ([TyConBinder], Type))
-> TcM ([TyConBinder], [TcTyVar], ([TyConBinder], Type))
forall a.
Name
-> [TyConBinder]
-> Type
-> [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
-> ([TyConBinder] -> Type -> TcM a)
-> TcM ([TyConBinder], [TcTyVar], a)
matchUpSigWithDecl Name
name [TyConBinder]
sig_tcbs Type
sig_res_kind [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
hs_tv_bndrs (([TyConBinder] -> Type -> TcM ([TyConBinder], Type))
 -> TcM ([TyConBinder], [TcTyVar], ([TyConBinder], Type)))
-> ([TyConBinder] -> Type -> TcM ([TyConBinder], Type))
-> TcM ([TyConBinder], [TcTyVar], ([TyConBinder], Type))
forall a b. (a -> b) -> a -> b
$ \ [TyConBinder]
excess_sig_tcbs Type
sig_res_kind ->
              do { -- Kind-check the result kind annotation, if present:
                   --    data T a b :: res_ki where ...
                   --               ^^^^^^^^^
                   -- We do it here because at this point the environment has been
                   -- extended with both 'implicit_tcv_prs' and 'explicit_tv_prs'.
                 ; ContextKind
res_kind :: ContextKind <- TcM ContextKind
kc_res_ki


                 -- Work out extra_arity, the number of extra invisible binders from
                 -- the kind signature that should be part of the TyCon's arity.
                 -- See Note [Arity inference in kcCheckDeclHeader_sig]
                 ; let n_invis_tcbs :: Int
n_invis_tcbs = (TyConBinder -> Bool) -> [TyConBinder] -> Int
forall a. (a -> Bool) -> [a] -> Int
countWhile TyConBinder -> Bool
forall tv. VarBndr tv TyConBndrVis -> Bool
isInvisibleTyConBinder [TyConBinder]
excess_sig_tcbs
                       invis_arity :: Int
invis_arity = case ContextKind
res_kind of
                          ContextKind
AnyKind    -> Int
n_invis_tcbs -- No kind signature, so make all the invisible binders
                                                     -- the signature into part of the arity of the TyCon
                          ContextKind
OpenKind   -> Int
n_invis_tcbs -- Result kind is (TYPE rr), so again make all the
                                                     -- invisible binders part of the arity of the TyCon
                          TheKind Type
ki -> Int
0 Int -> Int -> Int
forall a. Ord a => a -> a -> a
`max` (Int
n_invis_tcbs Int -> Int -> Int
forall a. Num a => a -> a -> a
- Type -> Int
invisibleTyBndrCount Type
ki)

                 ; let ([TyConBinder]
invis_tcbs, [TyConBinder]
resid_tcbs) = Int -> [TyConBinder] -> ([TyConBinder], [TyConBinder])
forall a. Int -> [a] -> ([a], [a])
splitAt Int
invis_arity [TyConBinder]
excess_sig_tcbs
                 ; let sig_res_kind' :: Type
sig_res_kind' = [TyConBinder] -> Type -> Type
mkTyConKind [TyConBinder]
resid_tcbs Type
sig_res_kind

                 ; String -> SDoc -> TcM ()
traceTc String
"kcCheckDeclHeader_sig 2" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ [TyConBinder] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TyConBinder]
excess_sig_tcbs
                                                            , Int -> SDoc
forall a. Outputable a => a -> SDoc
ppr Int
invis_arity, [TyConBinder] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TyConBinder]
invis_tcbs
                                                            , Int -> SDoc
forall a. Outputable a => a -> SDoc
ppr Int
n_invis_tcbs ]

                 -- Unify res_ki (from the type declaration) with
                 -- sig_res_kind', the residual kind from the kind signature.
                 ; Type -> ContextKind -> TcM ()
checkExpectedResKind Type
sig_res_kind' ContextKind
res_kind

                 -- Add more binders for data/newtype, so the result kind has no arrows
                 -- See Note [Datatype return kinds]
                 ; if [TyConBinder] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TyConBinder]
resid_tcbs Bool -> Bool -> Bool
|| Bool -> Bool
not (TyConFlavour TyCon -> Bool
forall tc. TyConFlavour tc -> Bool
needsEtaExpansion TyConFlavour TyCon
flav)
                   then ([TyConBinder], Type) -> TcM ([TyConBinder], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([TyConBinder]
invis_tcbs,      Type
sig_res_kind')
                   else ([TyConBinder], Type) -> TcM ([TyConBinder], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([TyConBinder]
excess_sig_tcbs, Type
sig_res_kind)
          }


        -- Check that there are no unsolved equalities
        ; let all_tcbs :: [TyConBinder]
all_tcbs = [TyConBinder]
skol_tcbs [TyConBinder] -> [TyConBinder] -> [TyConBinder]
forall a. [a] -> [a] -> [a]
++ [TyConBinder]
extra_tcbs
        ; SkolemInfo -> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM ()
reportUnsolvedEqualities SkolemInfo
skol_info ([TyConBinder] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [TyConBinder]
all_tcbs) TcLevel
tclvl WantedConstraints
wanted

        -- Check that distinct binders map to distinct tyvars (see #20916). For example
        --    type T :: k -> k -> Type
        --    data T (a::p) (b::q) = ...
        -- Here p and q both map to the same kind variable k.  We don't allow this
        -- so we must check that they are distinct.  A similar thing happens
        -- in GHC.Tc.TyCl.swizzleTcTyConBinders during inference.
        --
        -- With visible dependent quantification, one of the binders involved
        -- may be explicit.  Consider #24604
        --    type UF :: forall zk -> zk -> Constraint
        --    class UF kk (xb :: k)
        -- Here `k` and `kk` both denote the same variable; but only `k` is implicit
        -- Hence we need to add skol_scoped_tvs
        ; [TcTyVar]
implicit_tvs <- ZonkM [TcTyVar] -> TcM [TcTyVar]
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM [TcTyVar] -> TcM [TcTyVar])
-> ZonkM [TcTyVar] -> TcM [TcTyVar]
forall a b. (a -> b) -> a -> b
$ [TcTyVar] -> ZonkM [TcTyVar]
HasDebugCallStack => [TcTyVar] -> ZonkM [TcTyVar]
zonkTcTyVarsToTcTyVars [TcTyVar]
implicit_tvs
        ; let implicit_prs :: [(Name, TcTyVar)]
implicit_prs = HsQTvsRn
XHsQTvs GhcRn
implicit_nms HsQTvsRn -> [TcTyVar] -> [(Name, TcTyVar)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [TcTyVar]
implicit_tvs
              dup_chk_prs :: [(Name, TcTyVar)]
dup_chk_prs  = [(Name, TcTyVar)]
implicit_prs [(Name, TcTyVar)] -> [(Name, TcTyVar)] -> [(Name, TcTyVar)]
forall a. [a] -> [a] -> [a]
++ [TcTyVar] -> [(Name, TcTyVar)]
mkTyVarNamePairs [TcTyVar]
skol_scoped_tvs
        ; Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (HsQTvsRn -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null HsQTvsRn
XHsQTvs GhcRn
implicit_nms) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$  -- No need if no implicit tyvars
          [(Name, TcTyVar)] -> TcM ()
checkForDuplicateScopedTyVars [(Name, TcTyVar)]
dup_chk_prs
        ; TyConFlavour TyCon -> [TyConBinder] -> [(Name, TcTyVar)] -> TcM ()
checkForDisconnectedScopedTyVars TyConFlavour TyCon
flav [TyConBinder]
all_tcbs [(Name, TcTyVar)]
implicit_prs

        -- Swizzle the Names so that the TyCon uses the user-declared implicit names
        -- E.g  type T :: k -> Type
        --      data T (a :: j) = ....
        -- We want the TyConBinders of T to be [j, a::j], not [k, a::k]
        -- Why? So that the TyConBinders of the TyCon will lexically scope over the
        -- associated types and methods of a class.
        ; let swizzle_env :: VarEnv Name
swizzle_env = [(TcTyVar, Name)] -> VarEnv Name
forall a. [(TcTyVar, a)] -> VarEnv a
mkVarEnv (((Name, TcTyVar) -> (TcTyVar, Name))
-> [(Name, TcTyVar)] -> [(TcTyVar, Name)]
forall a b. (a -> b) -> [a] -> [b]
map (Name, TcTyVar) -> (TcTyVar, Name)
forall a b. (a, b) -> (b, a)
swap [(Name, TcTyVar)]
implicit_prs)
              (Subst
subst, [TyConBinder]
swizzled_tcbs) = (Subst -> TyConBinder -> (Subst, TyConBinder))
-> Subst -> [TyConBinder] -> (Subst, [TyConBinder])
forall (t :: * -> *) s a b.
Traversable t =>
(s -> a -> (s, b)) -> s -> t a -> (s, t b)
mapAccumL (VarEnv Name -> Subst -> TyConBinder -> (Subst, TyConBinder)
swizzleTcb VarEnv Name
swizzle_env) Subst
emptySubst [TyConBinder]
all_tcbs
              swizzled_kind :: Type
swizzled_kind          = HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst Type
tycon_res_kind
              all_tv_prs :: [(Name, TcTyVar)]
all_tv_prs             = [TcTyVar] -> [(Name, TcTyVar)]
mkTyVarNamePairs ([TyConBinder] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [TyConBinder]
swizzled_tcbs)

        ; String -> SDoc -> TcM ()
traceTc String
"kcCheckDeclHeader swizzle" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat
          [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"sig_tcbs ="       SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [TyConBinder] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TyConBinder]
sig_tcbs
          , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"implicit_prs ="   SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [(Name, TcTyVar)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [(Name, TcTyVar)]
implicit_prs
          , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"hs_tv_bndrs ="    SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
-> SDoc
forall a. Outputable a => a -> SDoc
ppr [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_tv_bndrs
          , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"all_tcbs ="       SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [TcTyVar] -> SDoc
pprTyVars ([TyConBinder] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [TyConBinder]
all_tcbs)
          , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"swizzled_tcbs ="  SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [TcTyVar] -> SDoc
pprTyVars ([TyConBinder] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [TyConBinder]
swizzled_tcbs)
          , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tycon_res_kind =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
tycon_res_kind
          , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"swizzled_kind ="  SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
swizzled_kind ]

        -- Build the final, generalized PolyTcTyCon
        -- NB: all_tcbs must bind the tyvars in the range of all_tv_prs
        --     because the tv_prs is used when (say) typechecking the RHS of
        --     a type synonym.
        ; let tc :: TyCon
tc = Name
-> [TyConBinder]
-> Type
-> [(Name, TcTyVar)]
-> Bool
-> TyConFlavour TyCon
-> TyCon
mkTcTyCon Name
name [TyConBinder]
swizzled_tcbs Type
swizzled_kind [(Name, TcTyVar)]
all_tv_prs
                             Bool
True -- Make a PolyTcTyCon, fully generalised
                             TyConFlavour TyCon
flav

        ; String -> SDoc -> TcM ()
traceTc String
"kcCheckDeclHeader_sig }" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat
          [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tyConName = " SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Name -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TyCon -> Name
tyConName TyCon
tc)
          , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"sig_kind =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
debugPprType Type
sig_kind
          , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tyConKind =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
debugPprType (TyCon -> Type
tyConKind TyCon
tc)
          , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tyConBinders = " SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [TyConBinder] -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TyCon -> [TyConBinder]
tyConBinders TyCon
tc)
          , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tyConResKind" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
debugPprType (TyCon -> Type
tyConResKind TyCon
tc)
          ]
        ; TyCon -> TcM TyCon
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TyCon
tc }

-- | Check the result kind annotation on a type constructor against
-- the corresponding section of the standalone kind signature.
-- Drops invisible binders that interfere with unification.
checkExpectedResKind :: TcKind       -- ^ the result kind from the separate kind signature
                     -> ContextKind  -- ^ the result kind from the declaration header
                     -> TcM ()
checkExpectedResKind :: Type -> ContextKind -> TcM ()
checkExpectedResKind Type
_ ContextKind
AnyKind
  = () -> TcM ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()  -- No signature in the declaration header
checkExpectedResKind Type
sig_kind ContextKind
res_ki
  = do { Type
actual_res_ki <- ContextKind -> TcM Type
newExpectedKind ContextKind
res_ki

       ; let -- Drop invisible binders from sig_kind until they match up
             -- with res_ki.  By analogy with checkExpectedKind.
             n_res_invis_bndrs :: Int
n_res_invis_bndrs = Type -> Int
invisibleTyBndrCount Type
actual_res_ki
             n_sig_invis_bndrs :: Int
n_sig_invis_bndrs = Type -> Int
invisibleTyBndrCount Type
sig_kind
             n_to_inst :: Int
n_to_inst         = Int
n_sig_invis_bndrs Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
n_res_invis_bndrs

             ([PiTyVarBinder]
_, Type
sig_kind') = Int -> Type -> ([PiTyVarBinder], Type)
splitInvisPiTysN Int
n_to_inst Type
sig_kind

       ; TcM Coercion -> TcM ()
forall a. TcM a -> TcM ()
discardResult (TcM Coercion -> TcM ()) -> TcM Coercion -> TcM ()
forall a b. (a -> b) -> a -> b
$ Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyKind Maybe TypedThing
forall a. Maybe a
Nothing Type
sig_kind' Type
actual_res_ki }

matchUpSigWithDecl
  :: Name                        -- Name of the type constructor for error messages
  -> [TcTyConBinder]             -- TcTyConBinders (with skolem TcTyVars) from the separate kind signature
  -> TcKind                      -- The tail end of the kind signature
  -> [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]     -- User-written binders in decl
  -> ([TcTyConBinder] -> TcKind -> TcM a)  -- All user-written binders are in scope
                                           --   Argument is excess TyConBinders and tail kind
  -> TcM ( [TcTyConBinder]       -- Skolemised binders, with TcTyVars
         , [TcTyVar]             -- Skolem tyvars brought into lexical scope by this matching-up
         , a )
-- See Note [Matching a kind signature with a declaration]
-- Invariant: Length of returned TyConBinders + length of excess TyConBinders
--            = length of incoming TyConBinders
matchUpSigWithDecl :: forall a.
Name
-> [TyConBinder]
-> Type
-> [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
-> ([TyConBinder] -> Type -> TcM a)
-> TcM ([TyConBinder], [TcTyVar], a)
matchUpSigWithDecl Name
name [TyConBinder]
sig_tcbs Type
sig_res_kind [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
hs_bndrs [TyConBinder] -> Type -> TcM a
thing_inside
  = Subst
-> [TyConBinder]
-> [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
-> TcM ([TyConBinder], [TcTyVar], a)
go Subst
emptySubst [TyConBinder]
sig_tcbs [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_bndrs
  where
    go :: Subst
-> [TyConBinder]
-> [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
-> TcM ([TyConBinder], [TcTyVar], a)
go Subst
subst [TyConBinder]
tcbs []
      = do { let (Subst
subst', [TyConBinder]
tcbs') = Subst -> [TyConBinder] -> (Subst, [TyConBinder])
substTyConBindersX Subst
subst [TyConBinder]
tcbs
           ; a
res <- [TyConBinder] -> Type -> TcM a
thing_inside [TyConBinder]
tcbs' (HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst' Type
sig_res_kind)
           ; ([TyConBinder], [TcTyVar], a) -> TcM ([TyConBinder], [TcTyVar], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([], [], a
res) }

    go Subst
_ [] [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_bndrs
      = TcRnMessage -> TcM ([TyConBinder], [TcTyVar], a)
forall a. TcRnMessage -> TcM a
failWithTc (Type -> [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn] -> TcRnMessage
TcRnTooManyBinders Type
sig_res_kind [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_bndrs)

    go Subst
subst (TyConBinder
tcb : [TyConBinder]
tcbs') hs_bndrs :: [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_bndrs@(GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
hs_bndr : [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_bndrs')
      | TyConBndrVis -> HsBndrVis GhcRn -> Bool
zippable (TyConBinder -> TyConBndrVis
forall tv argf. VarBndr tv argf -> argf
binderFlag TyConBinder
tcb) (HsTyVarBndr (HsBndrVis GhcRn) GhcRn -> HsBndrVis GhcRn
forall flag (pass :: Pass). HsTyVarBndr flag (GhcPass pass) -> flag
hsTyVarBndrFlag (GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
-> HsTyVarBndr (HsBndrVis GhcRn) GhcRn
forall l e. GenLocated l e -> e
unLoc GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
hs_bndr))
      = -- Visible TyConBinder, so match up with the hs_bndrs
        do { let Bndr TcTyVar
tv TyConBndrVis
vis = TyConBinder
tcb
                 tv' :: TcTyVar
tv' = (Type -> Type) -> TcTyVar -> TcTyVar
updateTyVarKind (HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst) (TcTyVar -> TcTyVar) -> TcTyVar -> TcTyVar
forall a b. (a -> b) -> a -> b
$
                       TcTyVar -> Name -> TcTyVar
setTyVarName TcTyVar
tv (GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
-> Name
forall a. NamedThing a => a -> Name
getName GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
hs_bndr)
                   -- Give the skolem the Name of the HsTyVarBndr, so that if it
                   -- appears in an error message it has a name and binding site
                   -- that come from the type declaration, not the kind signature
                 subst' :: Subst
subst' = Subst -> TcTyVar -> TcTyVar -> Subst
extendTCvSubstWithClone Subst
subst TcTyVar
tv TcTyVar
tv'
           ; HsTyVarBndr (HsBndrVis GhcRn) GhcRn -> Type -> TcM ()
tc_hs_bndr (GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
-> HsTyVarBndr (HsBndrVis GhcRn) GhcRn
forall l e. GenLocated l e -> e
unLoc GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
hs_bndr) (TcTyVar -> Type
tyVarKind TcTyVar
tv')
           ; String -> SDoc -> TcM ()
traceTc String
"musd1" (TyConBinder -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyConBinder
tcb SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
-> SDoc
forall a. Outputable a => a -> SDoc
ppr GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
hs_bndr SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv')
           ; ([TyConBinder]
tcbs', [TcTyVar]
tvs, a
res) <- [TcTyVar]
-> TcM ([TyConBinder], [TcTyVar], a)
-> TcM ([TyConBinder], [TcTyVar], a)
forall r. [TcTyVar] -> TcM r -> TcM r
tcExtendTyVarEnv [TcTyVar
tv'] (TcM ([TyConBinder], [TcTyVar], a)
 -> TcM ([TyConBinder], [TcTyVar], a))
-> TcM ([TyConBinder], [TcTyVar], a)
-> TcM ([TyConBinder], [TcTyVar], a)
forall a b. (a -> b) -> a -> b
$
                                  Subst
-> [TyConBinder]
-> [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
-> TcM ([TyConBinder], [TcTyVar], a)
go Subst
subst' [TyConBinder]
tcbs' [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_bndrs'
           ; ([TyConBinder], [TcTyVar], a) -> TcM ([TyConBinder], [TcTyVar], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TcTyVar -> TyConBndrVis -> TyConBinder
forall var argf. var -> argf -> VarBndr var argf
Bndr TcTyVar
tv' TyConBndrVis
vis TyConBinder -> [TyConBinder] -> [TyConBinder]
forall a. a -> [a] -> [a]
: [TyConBinder]
tcbs', TcTyVar
tv'TcTyVar -> [TcTyVar] -> [TcTyVar]
forall a. a -> [a] -> [a]
:[TcTyVar]
tvs, a
res) }
             -- We do a tcExtendTyVarEnv [tv'], so we return tv' in
             -- the list of lexically-scoped skolem type variables

      | TyConBndrVis -> Bool
skippable (TyConBinder -> TyConBndrVis
forall tv argf. VarBndr tv argf -> argf
binderFlag TyConBinder
tcb)
      = -- Invisible TyConBinder, so do not consume one of the hs_bndrs
        do { let (Subst
subst', TyConBinder
tcb') = Subst -> TyConBinder -> (Subst, TyConBinder)
substTyConBinderX Subst
subst TyConBinder
tcb
           ; String -> SDoc -> TcM ()
traceTc String
"musd2" (TyConBinder -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyConBinder
tcb SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
-> SDoc
forall a. Outputable a => a -> SDoc
ppr GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
hs_bndr SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ TyConBinder -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyConBinder
tcb')
           ; ([TyConBinder]
tcbs', [TcTyVar]
tvs, a
res) <- Subst
-> [TyConBinder]
-> [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
-> TcM ([TyConBinder], [TcTyVar], a)
go Subst
subst' [TyConBinder]
tcbs' [GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)]
hs_bndrs
                   -- NB: pass on hs_bndrs unchanged; we do not consume a
                   --     HsTyVarBndr for an invisible TyConBinder
           ; ([TyConBinder], [TcTyVar], a) -> TcM ([TyConBinder], [TcTyVar], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TyConBinder
tcb' TyConBinder -> [TyConBinder] -> [TyConBinder]
forall a. a -> [a] -> [a]
: [TyConBinder]
tcbs', [TcTyVar]
tvs, a
res) }
                   -- Return `tvs`; no new lexically-scoped TyVars brought into scope

      | Bool
otherwise =
          -- At this point we conclude that:
          --   * the quantifier (tcb) is visible: (ty -> ...), (forall a -> ...)
          --   * the binder (hs_bndr) is invisible: @t, @(t :: k)
          -- Any other combination should have been handled by the zippable/skippable clauses.
          TcRnMessage -> TcM ([TyConBinder], [TcTyVar], a)
forall a. TcRnMessage -> TcM a
failWithTc (Name -> LHsTyVarBndr (HsBndrVis GhcRn) GhcRn -> TcRnMessage
TcRnInvalidInvisTyVarBndr Name
name LHsTyVarBndr (HsBndrVis GhcRn) GhcRn
GenLocated SrcSpanAnnA (HsTyVarBndr (HsBndrVis GhcRn) GhcRn)
hs_bndr)

    tc_hs_bndr :: HsTyVarBndr (HsBndrVis GhcRn) GhcRn -> TcKind -> TcM ()
    tc_hs_bndr :: HsTyVarBndr (HsBndrVis GhcRn) GhcRn -> Type -> TcM ()
tc_hs_bndr (UserTyVar XUserTyVar GhcRn
_ HsBndrVis GhcRn
_ LIdP GhcRn
_) Type
_
      = () -> TcM ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    tc_hs_bndr (KindedTyVar XKindedTyVar GhcRn
_ HsBndrVis GhcRn
_ (L SrcSpanAnnN
_ Name
hs_nm) LHsType GhcRn
lhs_kind) Type
expected_kind
      = do { Type
sig_kind <- UserTypeCtxt -> LHsType GhcRn -> TcM Type
tcLHsKindSig (Name -> UserTypeCtxt
TyVarBndrKindCtxt Name
hs_nm) LHsType GhcRn
lhs_kind
           ; String -> SDoc -> TcM ()
traceTc String
"musd3:unifying" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
sig_kind SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
expected_kind)
           ; TcM Coercion -> TcM ()
forall a. TcM a -> TcM ()
discardResult (TcM Coercion -> TcM ()) -> TcM Coercion -> TcM ()
forall a b. (a -> b) -> a -> b
$ -- See Note [discardResult in kcCheckDeclHeader_sig]
             Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyKind (TypedThing -> Maybe TypedThing
forall a. a -> Maybe a
Just (Name -> TypedThing
NameThing Name
hs_nm)) Type
sig_kind Type
expected_kind }

    -- See GHC Proposal #425, section "Kind checking",
    -- where zippable and skippable are defined.
    -- In particular: we match up if
    -- (a) HsBndr looks like @k, and TyCon binder is forall k. (NamedTCB Specified)
    -- (b) HsBndr looks like a,  and TyCon binder is forall k -> (NamedTCB Required)
    --                                            or k -> (AnonTCB)
    zippable :: TyConBndrVis -> HsBndrVis GhcRn -> Bool
    zippable :: TyConBndrVis -> HsBndrVis GhcRn -> Bool
zippable TyConBndrVis
vis (HsBndrInvisible LHsToken "@" GhcRn
_) = TyConBndrVis -> Bool
isInvisSpecTcbVis TyConBndrVis
vis  -- (a)
    zippable TyConBndrVis
vis  HsBndrVis GhcRn
HsBndrRequired     = TyConBndrVis -> Bool
isVisibleTcbVis TyConBndrVis
vis    -- (b)

    -- See GHC Proposal #425, section "Kind checking",
    -- where zippable and skippable are defined.
    skippable :: TyConBndrVis -> Bool
    skippable :: TyConBndrVis -> Bool
skippable TyConBndrVis
vis = Bool -> Bool
not (TyConBndrVis -> Bool
isVisibleTcbVis TyConBndrVis
vis)

substTyConBinderX :: Subst -> TyConBinder -> (Subst, TyConBinder)
substTyConBinderX :: Subst -> TyConBinder -> (Subst, TyConBinder)
substTyConBinderX Subst
subst (Bndr TcTyVar
tv TyConBndrVis
vis)
  = (Subst
subst', TcTyVar -> TyConBndrVis -> TyConBinder
forall var argf. var -> argf -> VarBndr var argf
Bndr TcTyVar
tv' TyConBndrVis
vis)
  where
    (Subst
subst', TcTyVar
tv') = HasDebugCallStack => Subst -> TcTyVar -> (Subst, TcTyVar)
Subst -> TcTyVar -> (Subst, TcTyVar)
substTyVarBndr Subst
subst TcTyVar
tv

substTyConBindersX :: Subst -> [TyConBinder] -> (Subst, [TyConBinder])
substTyConBindersX :: Subst -> [TyConBinder] -> (Subst, [TyConBinder])
substTyConBindersX = (Subst -> TyConBinder -> (Subst, TyConBinder))
-> Subst -> [TyConBinder] -> (Subst, [TyConBinder])
forall (t :: * -> *) s a b.
Traversable t =>
(s -> a -> (s, b)) -> s -> t a -> (s, t b)
mapAccumL Subst -> TyConBinder -> (Subst, TyConBinder)
substTyConBinderX

swizzleTcb :: VarEnv Name -> Subst -> TyConBinder -> (Subst, TyConBinder)
swizzleTcb :: VarEnv Name -> Subst -> TyConBinder -> (Subst, TyConBinder)
swizzleTcb VarEnv Name
swizzle_env Subst
subst (Bndr TcTyVar
tv TyConBndrVis
vis)
  = (Subst
subst', TcTyVar -> TyConBndrVis -> TyConBinder
forall var argf. var -> argf -> VarBndr var argf
Bndr TcTyVar
tv2 TyConBndrVis
vis)
  where
    subst' :: Subst
subst' = Subst -> TcTyVar -> TcTyVar -> Subst
extendTCvSubstWithClone Subst
subst TcTyVar
tv TcTyVar
tv2
    tv1 :: TcTyVar
tv1 = (Type -> Type) -> TcTyVar -> TcTyVar
updateTyVarKind (HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst) TcTyVar
tv
    tv2 :: TcTyVar
tv2 = case VarEnv Name -> TcTyVar -> Maybe Name
forall a. VarEnv a -> TcTyVar -> Maybe a
lookupVarEnv VarEnv Name
swizzle_env TcTyVar
tv of
             Just Name
user_name -> TcTyVar -> Name -> TcTyVar
setTyVarName TcTyVar
tv1 Name
user_name
             Maybe Name
Nothing        -> TcTyVar
tv1
    -- NB: the SrcSpan on an implicitly-bound name deliberately spans
    -- the whole declaration. e.g.
    --    data T (a :: k) (b :: Type -> k) = ....
    -- There is no single binding site for 'k'.
    -- See Note [Source locations for implicitly bound type variables]
    -- in GHC.Tc.Rename.HsType

{- See Note [kcCheckDeclHeader_sig]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given a kind signature 'sig_kind' and a declaration header,
kcCheckDeclHeader_sig verifies that the declaration conforms to the
signature. The end result is a PolyTcTyCon 'tc' such that:
  tyConKind tc == sig_kind

Basic plan is this:
  * splitTyConKind: Take the Kind from the separate kind signature, and
    decompose it all the way to a [TyConBinder] and a Kind in the corner.

    NB: these TyConBinders contain TyVars, not TcTyVars.

  * matchUpSigWithDecl: match the [TyConBinder] from the signature with
    the [LHsTyVarBndr (HsBndrVis GhcRn) GhcRn] from the declaration.  The latter are the
    explicit, user-written binders.  e.g.
        data T (a :: k) b = ....
    There may be more of the former than the latter, because the former
    include invisible binders.  matchUpSigWithDecl uses isVisibleTcbVis
    to decide which TyConBinders are visible.

  * matchUpSigWithDecl also skolemises the [TyConBinder] to produce
    a [TyConBinder], corresponding 1-1 with the consumed [TyConBinder].
    Each new TyConBinder
      - Uses the Name from the LHsTyVarBndr, if available, both because that's
        what the user expects, and because the binding site accurately comes
        from the data/type declaration.
      - Uses a skolem TcTyVar.  We need these to allow unification.

  * machUpSigWithDecl also unifies the user-supplied kind signature for each
    LHsTyVarBndr with the kind that comes from the TyConBinder (itself coming
    from the separate kind signature).

  * Finally, kcCheckDeclHeader_sig unifies the return kind of the separate
    signature with the kind signature (if any) in the data/type declaration.
    E.g.
           type S :: forall k. k -> k -> Type
           type family S (a :: j) :: j -> Type
    Here we match up the 'k ->' with (a :: j); and then must unify the leftover
    part of the signature (k -> Type) with the kind signature of the decl,
    (j -> Type).  This unification, done in kcCheckDeclHeader, needs TcTyVars.

  * The tricky extra_arity part is described in
    Note [Arity inference in kcCheckDeclHeader_sig]

Note [Arity inference in kcCheckDeclHeader_sig]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider these declarations:
  type family S1 :: forall k2. k1 -> k2 -> Type
  type family S2 (a :: k1) (b :: k2) :: Type

Both S1 and S2 can be given the same standalone kind signature:
  type S1 :: forall k1 k2. k1 -> k2 -> Type
  type S2 :: forall k1 k2. k1 -> k2 -> Type

And, indeed, tyConKind S1 == tyConKind S2. However,
tyConBinders and tyConResKind for S1 and S2 are different:

  tyConBinders S1  ==  [spec k1]
  tyConResKind S1  ==  forall k2. k1 -> k2 -> Type
  tyConKind    S1  ==  forall k1 k2. k1 -> k2 -> Type

  tyConBinders S2  ==  [spec k1, spec k2, anon-vis (a :: k1), anon-vis (b :: k2)]
  tyConResKind S2  ==  Type
  tyConKind    S1  ==  forall k1 k2. k1 -> k2 -> Type

This difference determines the /arity/:
  tyConArity tc == length (tyConBinders tc)
That is, the arity of S1 is 1, while the arity of S2 is 4.

'kcCheckDeclHeader_sig' needs to infer the desired arity, to split the
standalone kind signature into binders and the result kind. It does so
in two rounds:

1. matchUpSigWithDecl matches up
   - the [TyConBinder] from (applying splitTyConKind to) the kind signature
   - with the [LHsTyVarBndr] from the type declaration.
   That may leave some excess TyConBinder: in the case of S2 there are
   no excess TyConBinders, but in the case of S1 there are two (since
   there are no LHsTYVarBndrs.

2. Split off further TyConBinders (in the case of S1, one more) to
   make it possible to unify the residual return kind with the
   signature in the type declaration.  More precisely, split off such
   enough invisible that the remainder of the standalone kind
   signature and the user-written result kind signature have the same
   number of invisible quantifiers.

As another example consider the following declarations:

    type F :: Type -> forall j. j -> forall k1 k2. (k1, k2) -> Type
    type family F a b

    type G :: Type -> forall j. j -> forall k1 k2. (k1, k2) -> Type
    type family G a b :: forall r2. (r1, r2) -> Type

For both F and G, the signature (after splitTyConKind) has
  sig_tcbs :: [TyConBinder]
    = [ anon-vis (@a_aBq), spec (@j_auA), anon-vis (@(b_aBr :: j_auA))
      , spec (@k1_auB), spec (@k2_auC)
      , anon-vis (@(c_aBs :: (k1_auB, k2_auC)))]

matchUpSigWithDecl will consume the first three of these, passing on
  excess_sig_tcbs
    = [ spec (@k1_auB), spec (@k2_auC)
      , anon-vis (@(c_aBs :: (k1_auB, k2_auC)))]

For F, there is no result kind signature in the declaration for F, so
we absorb all invisible binders into F's arity. The resulting arity of
F is 3+2=5.

Now, in the case of G, we have a result kind sig 'forall r2. (r2,r2)->Type'.
This has one invisible binder, so we split of enough extra binders from
our excess_sig_tcbs to leave just one to match 'r2'.

    res_ki  =  forall    r2. (r1, r2) -> Type
    kisig   =  forall k1 k2. (k1, k2) -> Type
                     ^^^
                     split off this one.

The resulting arity of G is 3+1=4.

Note [discardResult in kcCheckDeclHeader_sig]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We use 'unifyKind' to check inline kind annotations in declaration headers
against the signature.

  type T :: [i] -> Maybe j -> Type
  data T (a :: [k1]) (b :: Maybe k2) :: Type where ...

Here, we will unify:

       [k1] ~ [i]
  Maybe k2  ~ Maybe j
      Type  ~ Type

The end result is that we fill in unification variables k1, k2:

    k1  :=  i
    k2  :=  j

We also validate that the user isn't confused:

  type T :: Type -> Type
  data T (a :: Bool) = ...

This will report that (Type ~ Bool) failed to unify.

Now, consider the following example:

  type family Id a where Id x = x
  type T :: Bool -> Type
  type T (a :: Id Bool) = ...

We will unify (Bool ~ Id Bool), and this will produce a non-reflexive coercion.
However, we are free to discard it, as the kind of 'T' is determined by the
signature, not by the inline kind annotation:

      we have   T ::    Bool -> Type
  rather than   T :: Id Bool -> Type

This (Id Bool) will not show up anywhere after we're done validating it, so we
have no use for the produced coercion.

Note [Kind variable ordering for associated types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What should be the kind of `T` in the following example? (#15591)

  class C (a :: Type) where
    type T (x :: f a)

As per Note [Ordering of implicit variables] in GHC.Rename.HsType, we want to quantify
the kind variables in left-to-right order of first occurrence in order to
support visible kind application. But we cannot perform this analysis on just
T alone, since its variable `a` actually occurs /before/ `f` if you consider
the fact that `a` was previously bound by the parent class `C`. That is to say,
the kind of `T` should end up being:

  T :: forall a f. f a -> Type

(It wouldn't necessarily be /wrong/ if the kind ended up being, say,
forall f a. f a -> Type, but that would not be as predictable for users of
visible kind application.)

In contrast, if `T` were redefined to be a top-level type family, like `T2`
below:

  type family T2 (x :: f (a :: Type))

Then `a` first appears /after/ `f`, so the kind of `T2` should be:

  T2 :: forall f a. f a -> Type

In order to make this distinction, we need to know (in kcCheckDeclHeader) which
type variables have been bound by the parent class (if there is one). With
the class-bound variables in hand, we can ensure that we always quantify
these first.
-}


{- *********************************************************************
*                                                                      *
             Expected kinds
*                                                                      *
********************************************************************* -}

-- | Describes the kind expected in a certain context.
data ContextKind = TheKind TcKind   -- ^ a specific kind
                 | AnyKind        -- ^ any kind will do
                 | OpenKind       -- ^ something of the form @TYPE _@

-----------------------
newExpectedKind :: ContextKind -> TcM TcKind
newExpectedKind :: ContextKind -> TcM Type
newExpectedKind (TheKind Type
k)   = Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Type
k
newExpectedKind ContextKind
AnyKind       = TcM Type
newMetaKindVar
newExpectedKind ContextKind
OpenKind      = TcM Type
newOpenTypeKind

-----------------------
expectedKindInCtxt :: UserTypeCtxt -> ContextKind
-- Depending on the context, we might accept any kind (for instance, in a TH
-- splice), or only certain kinds (like in type signatures).
expectedKindInCtxt :: UserTypeCtxt -> ContextKind
expectedKindInCtxt (TySynCtxt Name
_)   = ContextKind
AnyKind
expectedKindInCtxt (GhciCtxt {})   = ContextKind
AnyKind
-- The types in a 'default' decl can have varying kinds
-- See Note [Extended defaults]" in GHC.Tc.Utils.Env
expectedKindInCtxt UserTypeCtxt
DefaultDeclCtxt     = ContextKind
AnyKind
expectedKindInCtxt UserTypeCtxt
DerivClauseCtxt     = ContextKind
AnyKind
expectedKindInCtxt UserTypeCtxt
TypeAppCtxt         = ContextKind
AnyKind
expectedKindInCtxt (ForSigCtxt Name
_)      = Type -> ContextKind
TheKind Type
liftedTypeKind
expectedKindInCtxt (InstDeclCtxt {})   = Type -> ContextKind
TheKind Type
constraintKind
expectedKindInCtxt UserTypeCtxt
SpecInstCtxt        = Type -> ContextKind
TheKind Type
constraintKind
expectedKindInCtxt UserTypeCtxt
_                   = ContextKind
OpenKind


{- *********************************************************************
*                                                                      *
          Scoped tyvars that map to the same thing
*                                                                      *
********************************************************************* -}

checkForDisconnectedScopedTyVars :: TyConFlavour TyCon -> [TcTyConBinder]
                                 -> [(Name,TcTyVar)] -> TcM ()
-- See Note [Disconnected type variables]
-- `scoped_prs` is the mapping gotten by unifying
--    - the standalone kind signature for T, with
--    - the header of the type/class declaration for T
checkForDisconnectedScopedTyVars :: TyConFlavour TyCon -> [TyConBinder] -> [(Name, TcTyVar)] -> TcM ()
checkForDisconnectedScopedTyVars TyConFlavour TyCon
flav [TyConBinder]
sig_tcbs [(Name, TcTyVar)]
scoped_prs
  = Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (TyConFlavour TyCon -> Bool
forall tc. TyConFlavour tc -> Bool
needsEtaExpansion TyConFlavour TyCon
flav) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
         -- needsEtaExpansion: see wrinkle (DTV1) in Note [Disconnected type variables]
    ((Name, TcTyVar) -> TcM ()) -> [(Name, TcTyVar)] -> TcM ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Name, TcTyVar) -> TcM ()
report_disconnected (((Name, TcTyVar) -> Bool) -> [(Name, TcTyVar)] -> [(Name, TcTyVar)]
forall a. (a -> Bool) -> [a] -> [a]
filterOut (Name, TcTyVar) -> Bool
ok [(Name, TcTyVar)]
scoped_prs)
  where
    sig_tvs :: TyVarSet
sig_tvs = [TcTyVar] -> TyVarSet
mkVarSet ([TyConBinder] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [TyConBinder]
sig_tcbs)
    ok :: (Name, TcTyVar) -> Bool
ok (Name
_, TcTyVar
tc_tv) = TcTyVar
tc_tv TcTyVar -> TyVarSet -> Bool
`elemVarSet` TyVarSet
sig_tvs

    report_disconnected :: (Name,TcTyVar) -> TcM ()
    report_disconnected :: (Name, TcTyVar) -> TcM ()
report_disconnected (Name
nm, TcTyVar
_)
      = SrcSpan -> TcM () -> TcM ()
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan (Name -> SrcSpan
forall a. NamedThing a => a -> SrcSpan
getSrcSpan Name
nm) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
        TcRnMessage -> TcM ()
addErrTc (TcRnMessage -> TcM ()) -> TcRnMessage -> TcM ()
forall a b. (a -> b) -> a -> b
$ Name -> TcRnMessage
TcRnDisconnectedTyVar Name
nm

checkForDuplicateScopedTyVars :: [(Name,TcTyVar)] -> TcM ()
-- Check for duplicates
-- See Note [Aliasing in type and class declarations]
checkForDuplicateScopedTyVars :: [(Name, TcTyVar)] -> TcM ()
checkForDuplicateScopedTyVars [(Name, TcTyVar)]
scoped_prs
  = Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([(Name, Name)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(Name, Name)]
err_prs) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
    do { ((Name, Name) -> TcM ()) -> [(Name, Name)] -> TcM ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Name, Name) -> TcM ()
report_dup [(Name, Name)]
err_prs; TcM ()
forall env a. IOEnv env a
failM }
  where
    -------------- Error reporting ------------
    err_prs :: [(Name,Name)]
    err_prs :: [(Name, Name)]
err_prs = [ (Name
n1,Name
n2)
              | NonEmpty (Name, TcTyVar)
prs :: NonEmpty (Name,TyVar) <- ((Name, TcTyVar) -> (Name, TcTyVar) -> Bool)
-> [(Name, TcTyVar)] -> [NonEmpty (Name, TcTyVar)]
forall a. (a -> a -> Bool) -> [a] -> [NonEmpty a]
findDupsEq (TcTyVar -> TcTyVar -> Bool
forall a. Eq a => a -> a -> Bool
(==) (TcTyVar -> TcTyVar -> Bool)
-> ((Name, TcTyVar) -> TcTyVar)
-> (Name, TcTyVar)
-> (Name, TcTyVar)
-> Bool
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` (Name, TcTyVar) -> TcTyVar
forall a b. (a, b) -> b
snd) [(Name, TcTyVar)]
scoped_prs
              , (Name
n1,TcTyVar
_) :| ((Name
n2,TcTyVar
_) : [(Name, TcTyVar)]
_) <- [((Name, TcTyVar) -> (Name, TcTyVar) -> Bool)
-> NonEmpty (Name, TcTyVar) -> NonEmpty (Name, TcTyVar)
forall a. (a -> a -> Bool) -> NonEmpty a -> NonEmpty a
NE.nubBy (Name -> Name -> Bool
forall a. Eq a => a -> a -> Bool
(==) (Name -> Name -> Bool)
-> ((Name, TcTyVar) -> Name)
-> (Name, TcTyVar)
-> (Name, TcTyVar)
-> Bool
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` (Name, TcTyVar) -> Name
forall a b. (a, b) -> a
fst) NonEmpty (Name, TcTyVar)
prs] ]
              -- This nubBy avoids bogus error reports when we have
              --    [("f", f), ..., ("f",f)....] in swizzle_prs
              -- which happens with  class C f where { type T f }

    report_dup :: (Name,Name) -> TcM ()
    report_dup :: (Name, Name) -> TcM ()
report_dup (Name
n1,Name
n2)
      = SrcSpan -> TcM () -> TcM ()
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan (Name -> SrcSpan
forall a. NamedThing a => a -> SrcSpan
getSrcSpan Name
n2) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
        TcRnMessage -> TcM ()
addErrTc (TcRnMessage -> TcM ()) -> TcRnMessage -> TcM ()
forall a b. (a -> b) -> a -> b
$ Name -> Name -> TcRnMessage
TcRnDifferentNamesForTyVar Name
n1 Name
n2


{- Note [Aliasing in type and class declarations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  data SameKind (a::k) (b::k)
  data T1 (a::k1) (b::k2) c = MkT (SameKind a b) c
We do not allow this, because `k1` and `k2` would both stand for the same type
variable -- they are both aliases for `k`.

Other examples
  data T2 (a::k1)                 = MkT2 (SameKind a Int) -- k1 stands for Type
  data T3 @k1 @k2 (a::k1) (b::k2) = MkT (SameKind a b)    -- k1 and k2 are aliases

  type UF :: forall zk. zk -> Constraint
  class UF @kk (xb :: k) where   -- kk and k are aliases
    op :: (xs::kk) -> Bool

See #24604 for an example that crashed GHC.

There is a design choice here. It would be possible to allow implicit type variables
like `k1` and `k2` in T1's declartion to stand for /abitrary kinds/.  This is in fact
the rule we use in /terms/ pattern signatures:
    f :: [Int] -> Int
    f ((x::a) : xs) = ...
Here `a` stands for `Int`.  But in type /signatures/ we make a different choice:
    f1 :: forall (a::k1) (b::k2). SameKind a b -> blah
    f2 :: forall (a::k). SameKind a Int -> blah

Here f1's signature is rejected because `k1` and `k2` are aliased; and f2's is
rejected because `k` stands for `Int`.

Our current choice is that type and class declarations behave more like signatures;
we do not allow aliasing.  That is what `checkForDuplicateScopedTyVars` checks.
See !12328 for some design discussion.


Note [Disconnected type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This note applies when kind-checking the header of a type/class decl that has
a separate, standalone kind signature.  See #24083.

Consider:
   type S a = Type

   type C :: forall k. S k -> Constraint
   class C (a :: S kk) where
     op :: ...kk...

Note that the class has a separate kind signature, so the elaborated decl should
look like
   class C @kk (a :: S kk) where ...

But how can we "connect up" the scoped variable `kk` with the skolem kind from the
standalone kind signature for `C`?  In general we do this by unifying the two.
For example
   type T k = (k,Type)
   type W :: forall k. T k -> Type
   data W (a :: (x,Type)) = ..blah blah..

When we encounter (a :: (x,Type)) we unify the kind (x,Type) with the kind (T k)
from the standalone kind signature.  Of course, unification looks through synonyms
so we end up with the mapping [x :-> k] that connects the scoped type variable `x`
with the kind from the signature.

But in our earlier example this unification is ineffective -- because `S` is a
phantom synonym that just discards its argument.  So our plan is this:

  if matchUpSigWithDecl fails to connect `kk with `k`, by unification,
  we give up and complain about a "disconnected" type variable.

See #24083 for dicussion of alternatives, none satisfactory.  Also the fix is
easy: just add an explicit `@kk` parameter to the declaration, to bind `kk`
explicitly, rather than binding it implicitly via unification.

(DTV1) We only want to make this check when there /are/ scoped type variables; and
  that is determined by needsEtaExpansion.  Examples:

     type C :: x -> y -> Constraint
     class C a :: b -> Constraint where { ... }
     -- The a,b scope over the "..."

     type D :: forall k. k -> Type
     data family D :: kk -> Type
     -- Nothing for `kk` to scope over!

  In the latter data-family case, the match-up stuff in kcCheckDeclHeader_sig will
  return [] for `extra_tcbs`, and in fact `all_tcbs` will be empty.  So if we do
  the check-for-disconnected-tyvars check we'll complain that `kk` is not bound
  to one of `all_tcbs` (see #24083, comments about the `singletons` package).

  The scoped-tyvar stuff is needed precisely for data/class/newtype declarations,
  where needsEtaExpansion is True.
-}

{- *********************************************************************
*                                                                      *
             Bringing type variables into scope
*                                                                      *
********************************************************************* -}

--------------------------------------
--    HsForAllTelescope
--------------------------------------

tcTKTelescope :: TcTyMode
              -> HsForAllTelescope GhcRn
              -> TcM a
              -> TcM ([TcTyVarBinder], a)
-- A HsForAllTelescope comes only from a HsForAllTy,
-- an explicit, user-written forall type
tcTKTelescope :: forall a.
TcTyMode
-> HsForAllTelescope GhcRn -> TcM a -> TcM ([TcTyVarBinder], a)
tcTKTelescope TcTyMode
mode HsForAllTelescope GhcRn
tele TcM a
thing_inside = case HsForAllTelescope GhcRn
tele of
  HsForAllVis { hsf_vis_bndrs :: forall pass. HsForAllTelescope pass -> [LHsTyVarBndr () pass]
hsf_vis_bndrs = [LHsTyVarBndr () GhcRn]
bndrs }
    -> do { SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo (TyVarBndrs -> SkolemInfoAnon
ForAllSkol ([HsTyVarBndr () GhcRn] -> TyVarBndrs
forall flag.
OutputableBndrFlag flag 'Renamed =>
[HsTyVarBndr flag GhcRn] -> TyVarBndrs
HsTyVarBndrsRn (GenLocated SrcSpanAnnA (HsTyVarBndr () GhcRn)
-> HsTyVarBndr () GhcRn
forall l e. GenLocated l e -> e
unLoc (GenLocated SrcSpanAnnA (HsTyVarBndr () GhcRn)
 -> HsTyVarBndr () GhcRn)
-> [GenLocated SrcSpanAnnA (HsTyVarBndr () GhcRn)]
-> [HsTyVarBndr () GhcRn]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [LHsTyVarBndr () GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr () GhcRn)]
bndrs)))
          ; let skol_mode :: SkolemMode
skol_mode = SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = False, sm_holes = mode_holes mode
                                      , sm_tvtv = SMDSkolemTv skol_info }
          ; ([VarBndr TcTyVar ()]
req_tv_bndrs, a
thing) <- SkolemMode
-> [LHsTyVarBndr () GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar ()], a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
tcExplicitTKBndrsX SkolemMode
skol_mode [LHsTyVarBndr () GhcRn]
bndrs TcM a
thing_inside
            -- req_tv_bndrs :: [VarBndr TyVar ()],
            -- but we want [VarBndr TyVar ForAllTyFlag]
          ; ([TcTyVarBinder], a) -> TcM ([TcTyVarBinder], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([VarBndr TcTyVar ()] -> [TcTyVarBinder]
forall a. [VarBndr a ()] -> [VarBndr a ForAllTyFlag]
tyVarReqToBinders [VarBndr TcTyVar ()]
req_tv_bndrs, a
thing) }

  HsForAllInvis { hsf_invis_bndrs :: forall pass.
HsForAllTelescope pass -> [LHsTyVarBndr Specificity pass]
hsf_invis_bndrs = [LHsTyVarBndr Specificity GhcRn]
bndrs }
    -> do { SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo (TyVarBndrs -> SkolemInfoAnon
ForAllSkol ([HsTyVarBndr Specificity GhcRn] -> TyVarBndrs
forall flag.
OutputableBndrFlag flag 'Renamed =>
[HsTyVarBndr flag GhcRn] -> TyVarBndrs
HsTyVarBndrsRn (GenLocated SrcSpanAnnA (HsTyVarBndr Specificity GhcRn)
-> HsTyVarBndr Specificity GhcRn
forall l e. GenLocated l e -> e
unLoc (GenLocated SrcSpanAnnA (HsTyVarBndr Specificity GhcRn)
 -> HsTyVarBndr Specificity GhcRn)
-> [GenLocated SrcSpanAnnA (HsTyVarBndr Specificity GhcRn)]
-> [HsTyVarBndr Specificity GhcRn]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [LHsTyVarBndr Specificity GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr Specificity GhcRn)]
bndrs)))
          ; let skol_mode :: SkolemMode
skol_mode = SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = False, sm_holes = mode_holes mode
                                      , sm_tvtv = SMDSkolemTv skol_info }
          ; ([VarBndr TcTyVar Specificity]
inv_tv_bndrs, a
thing) <- SkolemMode
-> [LHsTyVarBndr Specificity GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar Specificity], a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
tcExplicitTKBndrsX SkolemMode
skol_mode [LHsTyVarBndr Specificity GhcRn]
bndrs TcM a
thing_inside
            -- inv_tv_bndrs :: [VarBndr TyVar Specificity],
            -- but we want [VarBndr TyVar ForAllTyFlag]
          ; ([TcTyVarBinder], a) -> TcM ([TcTyVarBinder], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([VarBndr TcTyVar Specificity] -> [TcTyVarBinder]
forall a. [VarBndr a Specificity] -> [VarBndr a ForAllTyFlag]
tyVarSpecToBinders [VarBndr TcTyVar Specificity]
inv_tv_bndrs, a
thing) }

--------------------------------------
--    HsOuterTyVarBndrs
--------------------------------------

bindOuterTKBndrsX :: OutputableBndrFlag flag 'Renamed  -- Only to support traceTc
                  => SkolemMode
                  -> HsOuterTyVarBndrs flag GhcRn
                  -> TcM a
                  -> TcM (HsOuterTyVarBndrs flag GhcTc, a)
bindOuterTKBndrsX :: forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> HsOuterTyVarBndrs flag GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
bindOuterTKBndrsX SkolemMode
skol_mode HsOuterTyVarBndrs flag GhcRn
outer_bndrs TcM a
thing_inside
  = case HsOuterTyVarBndrs flag GhcRn
outer_bndrs of
      HsOuterImplicit{hso_ximplicit :: forall flag pass.
HsOuterTyVarBndrs flag pass -> XHsOuterImplicit pass
hso_ximplicit = XHsOuterImplicit GhcRn
imp_tvs} ->
        do { ([TcTyVar]
imp_tvs', a
thing) <- SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
forall a. SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrsX SkolemMode
skol_mode HsQTvsRn
XHsOuterImplicit GhcRn
imp_tvs TcM a
thing_inside
           ; (HsOuterTyVarBndrs flag GhcTc, a)
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ( HsOuterImplicit{hso_ximplicit :: XHsOuterImplicit GhcTc
hso_ximplicit = [TcTyVar]
XHsOuterImplicit GhcTc
imp_tvs'}
                    , a
thing) }
      HsOuterExplicit{hso_bndrs :: forall flag pass.
HsOuterTyVarBndrs flag pass -> [LHsTyVarBndr flag (NoGhcTc pass)]
hso_bndrs = [LHsTyVarBndr flag (NoGhcTc GhcRn)]
exp_bndrs} ->
        do { ([VarBndr TcTyVar flag]
exp_tvs', a
thing) <- SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrsX SkolemMode
skol_mode [LHsTyVarBndr flag (NoGhcTc GhcRn)]
[LHsTyVarBndr flag GhcRn]
exp_bndrs TcM a
thing_inside
           ; (HsOuterTyVarBndrs flag GhcTc, a)
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ( HsOuterExplicit { hso_xexplicit :: XHsOuterExplicit GhcTc flag
hso_xexplicit = [VarBndr TcTyVar flag]
XHsOuterExplicit GhcTc flag
exp_tvs'
                                      , hso_bndrs :: [LHsTyVarBndr flag (NoGhcTc GhcTc)]
hso_bndrs     = [LHsTyVarBndr flag (NoGhcTc GhcRn)]
[LHsTyVarBndr flag (NoGhcTc GhcTc)]
exp_bndrs }
                    , a
thing) }

---------------
outerTyVars :: HsOuterTyVarBndrs flag GhcTc -> [TcTyVar]
-- The returned [TcTyVar] is not necessarily in dependency order
-- at least for the HsOuterImplicit case
outerTyVars :: forall flag. HsOuterTyVarBndrs flag GhcTc -> [TcTyVar]
outerTyVars (HsOuterImplicit { hso_ximplicit :: forall flag pass.
HsOuterTyVarBndrs flag pass -> XHsOuterImplicit pass
hso_ximplicit = XHsOuterImplicit GhcTc
tvs })  = [TcTyVar]
XHsOuterImplicit GhcTc
tvs
outerTyVars (HsOuterExplicit { hso_xexplicit :: forall flag pass.
HsOuterTyVarBndrs flag pass -> XHsOuterExplicit pass flag
hso_xexplicit = XHsOuterExplicit GhcTc flag
tvbs }) = [VarBndr TcTyVar flag] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [VarBndr TcTyVar flag]
XHsOuterExplicit GhcTc flag
tvbs

---------------
outerTyVarBndrs :: HsOuterTyVarBndrs Specificity GhcTc -> [InvisTVBinder]
outerTyVarBndrs :: HsOuterTyVarBndrs Specificity GhcTc
-> [VarBndr TcTyVar Specificity]
outerTyVarBndrs (HsOuterImplicit{hso_ximplicit :: forall flag pass.
HsOuterTyVarBndrs flag pass -> XHsOuterImplicit pass
hso_ximplicit = XHsOuterImplicit GhcTc
imp_tvs}) = [TcTyVar -> Specificity -> VarBndr TcTyVar Specificity
forall var argf. var -> argf -> VarBndr var argf
Bndr TcTyVar
tv Specificity
SpecifiedSpec | TcTyVar
tv <- [TcTyVar]
XHsOuterImplicit GhcTc
imp_tvs]
outerTyVarBndrs (HsOuterExplicit{hso_xexplicit :: forall flag pass.
HsOuterTyVarBndrs flag pass -> XHsOuterExplicit pass flag
hso_xexplicit = XHsOuterExplicit GhcTc Specificity
exp_tvs}) = [VarBndr TcTyVar Specificity]
XHsOuterExplicit GhcTc Specificity
exp_tvs

---------------
scopedSortOuter :: HsOuterTyVarBndrs flag GhcTc -> TcM (HsOuterTyVarBndrs flag GhcTc)
-- Sort any /implicit/ binders into dependency order
--     (zonking first so we can see the dependencies)
-- /Explicit/ ones are already in the right order
scopedSortOuter :: forall flag.
HsOuterTyVarBndrs flag GhcTc -> TcM (HsOuterTyVarBndrs flag GhcTc)
scopedSortOuter (HsOuterImplicit{hso_ximplicit :: forall flag pass.
HsOuterTyVarBndrs flag pass -> XHsOuterImplicit pass
hso_ximplicit = XHsOuterImplicit GhcTc
imp_tvs})
  = do { [TcTyVar]
imp_tvs <- [TcTyVar] -> TcM [TcTyVar]
zonkAndScopedSort [TcTyVar]
XHsOuterImplicit GhcTc
imp_tvs
       ; HsOuterTyVarBndrs flag GhcTc -> TcM (HsOuterTyVarBndrs flag GhcTc)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsOuterImplicit { hso_ximplicit :: XHsOuterImplicit GhcTc
hso_ximplicit = [TcTyVar]
XHsOuterImplicit GhcTc
imp_tvs }) }
scopedSortOuter bndrs :: HsOuterTyVarBndrs flag GhcTc
bndrs@(HsOuterExplicit{})
  = -- No need to dependency-sort (or zonk) explicit quantifiers
    HsOuterTyVarBndrs flag GhcTc -> TcM (HsOuterTyVarBndrs flag GhcTc)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return HsOuterTyVarBndrs flag GhcTc
bndrs

---------------
bindOuterSigTKBndrs_Tv :: HsOuterSigTyVarBndrs GhcRn
                       -> TcM a -> TcM (HsOuterSigTyVarBndrs GhcTc, a)
bindOuterSigTKBndrs_Tv :: forall a.
HsOuterSigTyVarBndrs GhcRn
-> TcM a -> TcM (HsOuterTyVarBndrs Specificity GhcTc, a)
bindOuterSigTKBndrs_Tv
  = SkolemMode
-> HsOuterSigTyVarBndrs GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs Specificity GhcTc, a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> HsOuterTyVarBndrs flag GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
bindOuterTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = True, sm_tvtv = SMDTyVarTv })

bindOuterSigTKBndrs_Tv_M :: TcTyMode
                         -> HsOuterSigTyVarBndrs GhcRn
                         -> TcM a -> TcM (HsOuterSigTyVarBndrs GhcTc, a)
-- Do not push level; do not make implication constraint; use Tvs
-- Two major clients of this "bind-only" path are:
--    Note [Using TyVarTvs for kind-checking GADTs] in GHC.Tc.TyCl
--    Note [Checking partial type signatures]
bindOuterSigTKBndrs_Tv_M :: forall a.
TcTyMode
-> HsOuterSigTyVarBndrs GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs Specificity GhcTc, a)
bindOuterSigTKBndrs_Tv_M TcTyMode
mode
  = SkolemMode
-> HsOuterSigTyVarBndrs GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs Specificity GhcTc, a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> HsOuterTyVarBndrs flag GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
bindOuterTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = True, sm_tvtv = SMDTyVarTv
                                 , sm_holes = mode_holes mode })

bindOuterFamEqnTKBndrs_Q_Tv :: HsOuterFamEqnTyVarBndrs GhcRn
                            -> TcM a
                            -> TcM (HsOuterFamEqnTyVarBndrs GhcTc, a)
bindOuterFamEqnTKBndrs_Q_Tv :: forall a.
HsOuterFamEqnTyVarBndrs GhcRn
-> TcM a -> TcM (HsOuterFamEqnTyVarBndrs GhcTc, a)
bindOuterFamEqnTKBndrs_Q_Tv HsOuterFamEqnTyVarBndrs GhcRn
hs_bndrs TcM a
thing_inside
  = SkolemMode
-> HsOuterFamEqnTyVarBndrs GhcRn
-> TcM a
-> TcM (HsOuterFamEqnTyVarBndrs GhcTc, a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> HsOuterTyVarBndrs flag GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
bindOuterTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = False, sm_parent = True
                                 , sm_tvtv = SMDTyVarTv })
                      HsOuterFamEqnTyVarBndrs GhcRn
hs_bndrs TcM a
thing_inside
    -- sm_clone=False: see Note [Cloning for type variable binders]

bindOuterFamEqnTKBndrs :: SkolemInfo
                       -> HsOuterFamEqnTyVarBndrs GhcRn
                       -> TcM a
                       -> TcM (HsOuterFamEqnTyVarBndrs GhcTc, a)
bindOuterFamEqnTKBndrs :: forall a.
SkolemInfo
-> HsOuterFamEqnTyVarBndrs GhcRn
-> TcM a
-> TcM (HsOuterFamEqnTyVarBndrs GhcTc, a)
bindOuterFamEqnTKBndrs SkolemInfo
skol_info
  = SkolemMode
-> HsOuterFamEqnTyVarBndrs GhcRn
-> TcM a
-> TcM (HsOuterFamEqnTyVarBndrs GhcTc, a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> HsOuterTyVarBndrs flag GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
bindOuterTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = False, sm_parent = True
                                 , sm_tvtv = SMDSkolemTv skol_info })
    -- sm_clone=False: see Note [Cloning for type variable binders]

---------------
tcOuterTKBndrs :: OutputableBndrFlag flag 'Renamed   -- Only to support traceTc
               => SkolemInfo
               -> HsOuterTyVarBndrs flag GhcRn
               -> TcM a -> TcM (HsOuterTyVarBndrs flag GhcTc, a)
tcOuterTKBndrs :: forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemInfo
-> HsOuterTyVarBndrs flag GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
tcOuterTKBndrs SkolemInfo
skol_info
  = SkolemMode
-> SkolemInfo
-> HsOuterTyVarBndrs flag GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> SkolemInfo
-> HsOuterTyVarBndrs flag GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
tcOuterTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = False
                               , sm_tvtv = SMDSkolemTv skol_info })
                    SkolemInfo
skol_info
  -- Do not clone the outer binders
  -- See Note [Cloning for type variable binders] under "must not"

tcOuterTKBndrsX :: OutputableBndrFlag flag 'Renamed   -- Only to support traceTc
                => SkolemMode -> SkolemInfo
                -> HsOuterTyVarBndrs flag GhcRn
                -> TcM a -> TcM (HsOuterTyVarBndrs flag GhcTc, a)
-- Push level, capture constraints, make implication
tcOuterTKBndrsX :: forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> SkolemInfo
-> HsOuterTyVarBndrs flag GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
tcOuterTKBndrsX SkolemMode
skol_mode SkolemInfo
skol_info HsOuterTyVarBndrs flag GhcRn
outer_bndrs TcM a
thing_inside
  = case HsOuterTyVarBndrs flag GhcRn
outer_bndrs of
      HsOuterImplicit{hso_ximplicit :: forall flag pass.
HsOuterTyVarBndrs flag pass -> XHsOuterImplicit pass
hso_ximplicit = XHsOuterImplicit GhcRn
imp_tvs} ->
        do { ([TcTyVar]
imp_tvs', a
thing) <- SkolemMode -> SkolemInfo -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
forall a.
SkolemMode -> SkolemInfo -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
tcImplicitTKBndrsX SkolemMode
skol_mode SkolemInfo
skol_info HsQTvsRn
XHsOuterImplicit GhcRn
imp_tvs TcM a
thing_inside
           ; (HsOuterTyVarBndrs flag GhcTc, a)
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ( HsOuterImplicit{hso_ximplicit :: XHsOuterImplicit GhcTc
hso_ximplicit = [TcTyVar]
XHsOuterImplicit GhcTc
imp_tvs'}
                    , a
thing) }
      HsOuterExplicit{hso_bndrs :: forall flag pass.
HsOuterTyVarBndrs flag pass -> [LHsTyVarBndr flag (NoGhcTc pass)]
hso_bndrs = [LHsTyVarBndr flag (NoGhcTc GhcRn)]
exp_bndrs} ->
        do { ([VarBndr TcTyVar flag]
exp_tvs', a
thing) <- SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
tcExplicitTKBndrsX SkolemMode
skol_mode [LHsTyVarBndr flag (NoGhcTc GhcRn)]
[LHsTyVarBndr flag GhcRn]
exp_bndrs TcM a
thing_inside
           ; (HsOuterTyVarBndrs flag GhcTc, a)
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ( HsOuterExplicit { hso_xexplicit :: XHsOuterExplicit GhcTc flag
hso_xexplicit = [VarBndr TcTyVar flag]
XHsOuterExplicit GhcTc flag
exp_tvs'
                                      , hso_bndrs :: [LHsTyVarBndr flag (NoGhcTc GhcTc)]
hso_bndrs     = [LHsTyVarBndr flag (NoGhcTc GhcRn)]
[LHsTyVarBndr flag (NoGhcTc GhcTc)]
exp_bndrs }
                    , a
thing) }

--------------------------------------
--    Explicit tyvar binders
--------------------------------------

tcExplicitTKBndrs :: OutputableBndrFlag flag 'Renamed    -- Only to suppor traceTc
                  => SkolemInfo
                  -> [LHsTyVarBndr flag GhcRn]
                  -> TcM a
                  -> TcM ([VarBndr TyVar flag], a)
tcExplicitTKBndrs :: forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemInfo
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
tcExplicitTKBndrs SkolemInfo
skol_info
  = SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> IOEnv (Env TcGblEnv TcLclEnv) a
-> IOEnv (Env TcGblEnv TcLclEnv) ([VarBndr TcTyVar flag], a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
tcExplicitTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = True, sm_tvtv = SMDSkolemTv skol_info })

tcExplicitTKBndrsX :: OutputableBndrFlag flag 'Renamed    -- Only to suppor traceTc
                   => SkolemMode
                   -> [LHsTyVarBndr flag GhcRn]
                   -> TcM a
                   -> TcM ([VarBndr TyVar flag], a)
-- Push level, capture constraints, and emit an implication constraint.
-- The implication constraint has a ForAllSkol ic_info,
--   so that it is subject to a telescope test.
tcExplicitTKBndrsX :: forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
tcExplicitTKBndrsX SkolemMode
skol_mode [LHsTyVarBndr flag GhcRn]
bndrs TcM a
thing_inside = case [GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)]
-> Maybe
     (NonEmpty (GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)))
forall a. [a] -> Maybe (NonEmpty a)
nonEmpty [LHsTyVarBndr flag GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)]
bndrs of
    Maybe (NonEmpty (GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)))
Nothing -> do
       { a
res <- TcM a
thing_inside
       ; ([VarBndr TcTyVar flag], a) -> TcM ([VarBndr TcTyVar flag], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([], a
res) }

    Just NonEmpty (GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn))
bndrs1 -> do
       { (TcLevel
tclvl, WantedConstraints
wanted, ([VarBndr TcTyVar flag]
skol_tvs, a
res))
             <- TcM ([VarBndr TcTyVar flag], a)
-> TcM (TcLevel, WantedConstraints, ([VarBndr TcTyVar flag], a))
forall a. TcM a -> TcM (TcLevel, WantedConstraints, a)
pushLevelAndCaptureConstraints (TcM ([VarBndr TcTyVar flag], a)
 -> TcM (TcLevel, WantedConstraints, ([VarBndr TcTyVar flag], a)))
-> TcM ([VarBndr TcTyVar flag], a)
-> TcM (TcLevel, WantedConstraints, ([VarBndr TcTyVar flag], a))
forall a b. (a -> b) -> a -> b
$
                SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrsX SkolemMode
skol_mode [LHsTyVarBndr flag GhcRn]
bndrs (TcM a -> TcM ([VarBndr TcTyVar flag], a))
-> TcM a -> TcM ([VarBndr TcTyVar flag], a)
forall a b. (a -> b) -> a -> b
$
                TcM a
thing_inside

       -- Set up SkolemInfo for telescope test
       ; let bndr_1 :: GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)
bndr_1 = NonEmpty (GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn))
-> GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)
forall a. NonEmpty a -> a
NE.head NonEmpty (GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn))
bndrs1; bndr_n :: GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)
bndr_n = NonEmpty (GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn))
-> GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)
forall a. NonEmpty a -> a
NE.last NonEmpty (GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn))
bndrs1
       ; SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo (TyVarBndrs -> SkolemInfoAnon
ForAllSkol ([HsTyVarBndr flag GhcRn] -> TyVarBndrs
forall flag.
OutputableBndrFlag flag 'Renamed =>
[HsTyVarBndr flag GhcRn] -> TyVarBndrs
HsTyVarBndrsRn  (GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)
-> HsTyVarBndr flag GhcRn
forall l e. GenLocated l e -> e
unLoc (GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)
 -> HsTyVarBndr flag GhcRn)
-> [GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)]
-> [HsTyVarBndr flag GhcRn]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [LHsTyVarBndr flag GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)]
bndrs)))
         -- Notice that we use ForAllSkol here, ignoring the enclosing
         -- skol_info unlike tcImplicitTKBndrs, because the bad-telescope
         -- test applies only to ForAllSkol

       ; SrcSpan -> TcM () -> TcM ()
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan (SrcSpan -> SrcSpan -> SrcSpan
combineSrcSpans (GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn) -> SrcSpan
forall a e. GenLocated (SrcSpanAnn' a) e -> SrcSpan
getLocA GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)
bndr_1) (GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn) -> SrcSpan
forall a e. GenLocated (SrcSpanAnn' a) e -> SrcSpan
getLocA GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)
bndr_n))
       (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$ SkolemInfo -> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM ()
emitResidualTvConstraint SkolemInfo
skol_info ([VarBndr TcTyVar flag] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [VarBndr TcTyVar flag]
skol_tvs) TcLevel
tclvl WantedConstraints
wanted

       ; ([VarBndr TcTyVar flag], a) -> TcM ([VarBndr TcTyVar flag], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([VarBndr TcTyVar flag]
skol_tvs, a
res) }

----------------
-- | Skolemise the 'HsTyVarBndr's in an 'HsForAllTelescope' with the supplied
-- 'TcTyMode'.
bindExplicitTKBndrs_Skol
    :: (OutputableBndrFlag flag 'Renamed)      -- Only to suppor traceTc
    => SkolemInfo
    -> [LHsTyVarBndr flag GhcRn]
    -> TcM a
    -> TcM ([VarBndr TyVar flag], a)

bindExplicitTKBndrs_Tv
    :: (OutputableBndrFlag flag 'Renamed)    -- Only to suppor traceTc
    => [LHsTyVarBndr flag GhcRn]
    -> TcM a
    -> TcM ([VarBndr TyVar flag], a)

bindExplicitTKBndrs_Skol :: forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemInfo
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrs_Skol SkolemInfo
skol_info = SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> IOEnv (Env TcGblEnv TcLclEnv) a
-> IOEnv (Env TcGblEnv TcLclEnv) ([VarBndr TcTyVar flag], a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = False, sm_tvtv = SMDSkolemTv skol_info })
bindExplicitTKBndrs_Tv :: forall flag a.
OutputableBndrFlag flag 'Renamed =>
[LHsTyVarBndr flag GhcRn]
-> TcM a -> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrs_Tv   = SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> IOEnv (Env TcGblEnv TcLclEnv) a
-> IOEnv (Env TcGblEnv TcLclEnv) ([VarBndr TcTyVar flag], a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = True, sm_tvtv = SMDTyVarTv })
   -- sm_clone: see Note [Cloning for type variable binders]

bindExplicitTKBndrs_Q_Skol
    :: (OutputableBndrFlag flag 'Renamed)   -- Only to support traceTc
    => SkolemInfo
    -> ContextKind
    -> [LHsTyVarBndr flag GhcRn]
    -> TcM a
    -> TcM ([VarBndr TyVar flag], a)

bindExplicitTKBndrs_Q_Tv
    :: (OutputableBndrFlag flag 'Renamed)   -- Only to support traceTc
    => ContextKind
    -> [LHsTyVarBndr flag GhcRn]
    -> TcM a
    -> TcM ([VarBndr TyVar flag], a)
-- These do not clone: see Note [Cloning for type variable binders]
bindExplicitTKBndrs_Q_Skol :: forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemInfo
-> ContextKind
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrs_Q_Skol SkolemInfo
skol_info ContextKind
ctxt_kind [LHsTyVarBndr flag GhcRn]
hs_bndrs TcM a
thing_inside
  = SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = False, sm_parent = True
                                    , sm_kind = ctxt_kind, sm_tvtv = SMDSkolemTv skol_info })
                         [LHsTyVarBndr flag GhcRn]
hs_bndrs TcM a
thing_inside
    -- sm_clone=False: see Note [Cloning for type variable binders]

bindExplicitTKBndrs_Q_Tv :: forall flag a.
OutputableBndrFlag flag 'Renamed =>
ContextKind
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrs_Q_Tv  ContextKind
ctxt_kind [LHsTyVarBndr flag GhcRn]
hs_bndrs TcM a
thing_inside
  = SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = False, sm_parent = True
                                    , sm_tvtv = SMDTyVarTv, sm_kind = ctxt_kind })
                         [LHsTyVarBndr flag GhcRn]
hs_bndrs TcM a
thing_inside
    -- sm_clone=False: see Note [Cloning for type variable binders]

bindExplicitTKBndrsX
    :: (OutputableBndrFlag flag 'Renamed)   -- Only to support traceTc
    => SkolemMode
    -> [LHsTyVarBndr flag GhcRn]
    -> TcM a
    -> TcM ([VarBndr TyVar flag], a)  -- Returned [TcTyVar] are in 1-1 correspondence
                                      -- with the passed-in [LHsTyVarBndr]
bindExplicitTKBndrsX :: forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemMode
-> [LHsTyVarBndr flag GhcRn]
-> TcM a
-> TcM ([VarBndr TcTyVar flag], a)
bindExplicitTKBndrsX skol_mode :: SkolemMode
skol_mode@(SM { sm_parent :: SkolemMode -> Bool
sm_parent = Bool
check_parent, sm_kind :: SkolemMode -> ContextKind
sm_kind = ContextKind
ctxt_kind
                                   , sm_holes :: SkolemMode -> HoleInfo
sm_holes = HoleInfo
hole_info })
                     [LHsTyVarBndr flag GhcRn]
hs_tvs TcM a
thing_inside
  = do { String -> SDoc -> TcM ()
traceTc String
"bindExplicitTKBndrs" ([GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [LHsTyVarBndr flag GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)]
hs_tvs)
       ; [GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)]
-> TcM ([VarBndr TcTyVar flag], a)
go [LHsTyVarBndr flag GhcRn]
[GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)]
hs_tvs }
  where
    tc_ki_mode :: TcTyMode
tc_ki_mode = TcTyMode { mode_tyki :: TypeOrKind
mode_tyki = TypeOrKind
KindLevel, mode_holes :: HoleInfo
mode_holes = HoleInfo
hole_info }
                 -- Inherit the HoleInfo from the context

    go :: [GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)]
-> TcM ([VarBndr TcTyVar flag], a)
go [] = do { a
res <- TcM a
thing_inside
               ; ([VarBndr TcTyVar flag], a) -> TcM ([VarBndr TcTyVar flag], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([], a
res) }
    go (L SrcSpanAnnA
_ HsTyVarBndr flag GhcRn
hs_tv : [GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)]
hs_tvs)
       = do { NameEnv TcTyThing
lcl_env <- TcM (NameEnv TcTyThing)
getLclTypeEnv
            ; TcTyVar
tv <- NameEnv TcTyThing
-> HsTyVarBndr flag GhcRn -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
tc_hs_bndr NameEnv TcTyThing
lcl_env HsTyVarBndr flag GhcRn
hs_tv
            -- Extend the environment as we go, in case a binder
            -- is mentioned in the kind of a later binder
            --   e.g. forall k (a::k). blah
            -- NB: tv's Name may differ from hs_tv's
            -- See Note [Cloning for type variable binders]
            ; ([VarBndr TcTyVar flag]
tvs,a
res) <- [(Name, TcTyVar)]
-> TcM ([VarBndr TcTyVar flag], a)
-> TcM ([VarBndr TcTyVar flag], a)
forall r. [(Name, TcTyVar)] -> TcM r -> TcM r
tcExtendNameTyVarEnv [(HsTyVarBndr flag GhcRn -> IdP GhcRn
forall flag (p :: Pass).
HsTyVarBndr flag (GhcPass p) -> IdP (GhcPass p)
hsTyVarName HsTyVarBndr flag GhcRn
hs_tv, TcTyVar
tv)] (TcM ([VarBndr TcTyVar flag], a)
 -> TcM ([VarBndr TcTyVar flag], a))
-> TcM ([VarBndr TcTyVar flag], a)
-> TcM ([VarBndr TcTyVar flag], a)
forall a b. (a -> b) -> a -> b
$
                           [GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)]
-> TcM ([VarBndr TcTyVar flag], a)
go [GenLocated SrcSpanAnnA (HsTyVarBndr flag GhcRn)]
hs_tvs
            ; ([VarBndr TcTyVar flag], a) -> TcM ([VarBndr TcTyVar flag], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TcTyVar -> flag -> VarBndr TcTyVar flag
forall var argf. var -> argf -> VarBndr var argf
Bndr TcTyVar
tv (HsTyVarBndr flag GhcRn -> flag
forall flag (pass :: Pass). HsTyVarBndr flag (GhcPass pass) -> flag
hsTyVarBndrFlag HsTyVarBndr flag GhcRn
hs_tv)VarBndr TcTyVar flag
-> [VarBndr TcTyVar flag] -> [VarBndr TcTyVar flag]
forall a. a -> [a] -> [a]
:[VarBndr TcTyVar flag]
tvs, a
res) }


    tc_hs_bndr :: NameEnv TcTyThing
-> HsTyVarBndr flag GhcRn -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
tc_hs_bndr NameEnv TcTyThing
lcl_env (UserTyVar XUserTyVar GhcRn
_ flag
_ (L Anno (IdGhcP 'Renamed)
_ Name
name))
      | Bool
check_parent
      , Just (ATyVar Name
_ TcTyVar
tv) <- NameEnv TcTyThing -> Name -> Maybe TcTyThing
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv NameEnv TcTyThing
lcl_env Name
name
      = TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TcTyVar
tv
      | Bool
otherwise
      = do { Type
kind <- ContextKind -> TcM Type
newExpectedKind ContextKind
ctxt_kind
           ; SkolemMode -> Name -> Type -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newTyVarBndr SkolemMode
skol_mode Name
name Type
kind }

    tc_hs_bndr NameEnv TcTyThing
lcl_env (KindedTyVar XKindedTyVar GhcRn
_ flag
_ (L SrcSpanAnnN
_ Name
name) LHsType GhcRn
lhs_kind)
      | Bool
check_parent
      , Just (ATyVar Name
_ TcTyVar
tv) <- NameEnv TcTyThing -> Name -> Maybe TcTyThing
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv NameEnv TcTyThing
lcl_env Name
name
      = do { Type
kind <- TcTyMode -> UserTypeCtxt -> LHsType GhcRn -> TcM Type
tc_lhs_kind_sig TcTyMode
tc_ki_mode (Name -> UserTypeCtxt
TyVarBndrKindCtxt Name
name) LHsType GhcRn
lhs_kind
           ; TcM Coercion -> TcM ()
forall a. TcM a -> TcM ()
discardResult (TcM Coercion -> TcM ()) -> TcM Coercion -> TcM ()
forall a b. (a -> b) -> a -> b
$
             Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyKind (TypedThing -> Maybe TypedThing
forall a. a -> Maybe a
Just (TypedThing -> Maybe TypedThing)
-> (Name -> TypedThing) -> Name -> Maybe TypedThing
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Name -> TypedThing
NameThing (Name -> Maybe TypedThing) -> Name -> Maybe TypedThing
forall a b. (a -> b) -> a -> b
$ Name
name) Type
kind (TcTyVar -> Type
tyVarKind TcTyVar
tv)
                          -- This unify rejects:
                          --    class C (m :: * -> *) where
                          --      type F (m :: *) = ...
           ; TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TcTyVar
tv }

      | Bool
otherwise
      = do { Type
kind <- TcTyMode -> UserTypeCtxt -> LHsType GhcRn -> TcM Type
tc_lhs_kind_sig TcTyMode
tc_ki_mode (Name -> UserTypeCtxt
TyVarBndrKindCtxt Name
name) LHsType GhcRn
lhs_kind
           ; SkolemMode -> Name -> Type -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newTyVarBndr SkolemMode
skol_mode Name
name Type
kind }

newTyVarBndr :: SkolemMode -> Name -> Kind -> TcM TcTyVar
newTyVarBndr :: SkolemMode -> Name -> Type -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newTyVarBndr (SM { sm_clone :: SkolemMode -> Bool
sm_clone = Bool
clone, sm_tvtv :: SkolemMode -> SkolemModeDetails
sm_tvtv = SkolemModeDetails
tvtv }) Name
name Type
kind
  = do { Name
name <- case Bool
clone of
              Bool
True -> do { Unique
uniq <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
                         ; Name -> TcM Name
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Unique -> Name
setNameUnique Name
name Unique
uniq) }
              Bool
False -> Name -> TcM Name
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Name
name
       ; TcTyVarDetails
details <- case SkolemModeDetails
tvtv of
                 SkolemModeDetails
SMDTyVarTv  -> MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
TyVarTv
                 SMDSkolemTv SkolemInfo
skol_info ->
                  do { TcLevel
lvl <- TcM TcLevel
getTcLevel
                     ; TcTyVarDetails -> TcM TcTyVarDetails
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (SkolemInfo -> TcLevel -> Bool -> TcTyVarDetails
SkolemTv SkolemInfo
skol_info TcLevel
lvl Bool
False) }
       ; TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Type -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
name Type
kind TcTyVarDetails
details) }

--------------------------------------
--    Implicit tyvar binders
--------------------------------------

tcImplicitTKBndrsX :: SkolemMode -> SkolemInfo
                   -> [Name]
                   -> TcM a
                   -> TcM ([TcTyVar], a)
-- The workhorse:
--    push level, capture constraints, and emit an implication constraint
tcImplicitTKBndrsX :: forall a.
SkolemMode -> SkolemInfo -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
tcImplicitTKBndrsX SkolemMode
skol_mode SkolemInfo
skol_info HsQTvsRn
bndrs TcM a
thing_inside
  | HsQTvsRn -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null HsQTvsRn
bndrs  -- Short-cut the common case with no quantifiers
                -- E.g. f :: Int -> Int
                --      makes a HsOuterImplicit with empty bndrs,
                --      and tcOuterTKBndrsX goes via here
  = do { a
res <- TcM a
thing_inside; ([TcTyVar], a) -> TcM ([TcTyVar], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([], a
res) }
  | Bool
otherwise
  = do { (TcLevel
tclvl, WantedConstraints
wanted, ([TcTyVar]
skol_tvs, a
res))
             <- TcM ([TcTyVar], a)
-> TcM (TcLevel, WantedConstraints, ([TcTyVar], a))
forall a. TcM a -> TcM (TcLevel, WantedConstraints, a)
pushLevelAndCaptureConstraints       (TcM ([TcTyVar], a)
 -> TcM (TcLevel, WantedConstraints, ([TcTyVar], a)))
-> TcM ([TcTyVar], a)
-> TcM (TcLevel, WantedConstraints, ([TcTyVar], a))
forall a b. (a -> b) -> a -> b
$
                SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
forall a. SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrsX SkolemMode
skol_mode HsQTvsRn
bndrs (TcM a -> TcM ([TcTyVar], a)) -> TcM a -> TcM ([TcTyVar], a)
forall a b. (a -> b) -> a -> b
$
                TcM a
thing_inside

       ; SkolemInfo -> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM ()
emitResidualTvConstraint SkolemInfo
skol_info [TcTyVar]
skol_tvs TcLevel
tclvl WantedConstraints
wanted

       ; ([TcTyVar], a) -> TcM ([TcTyVar], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([TcTyVar]
skol_tvs, a
res) }

------------------
bindImplicitTKBndrs_Skol,
  bindImplicitTKBndrs_Q_Skol :: SkolemInfo -> [Name] -> TcM a -> TcM ([TcTyVar], a)

bindImplicitTKBndrs_Tv, bindImplicitTKBndrs_Q_Tv :: [Name] -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrs_Skol :: forall a. SkolemInfo -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrs_Skol SkolemInfo
skol_info = SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
forall a. SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = True, sm_tvtv = SMDSkolemTv skol_info })
bindImplicitTKBndrs_Tv :: forall a. HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrs_Tv   = SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
forall a. SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = True, sm_tvtv = SMDTyVarTv })
bindImplicitTKBndrs_Q_Skol :: forall a. SkolemInfo -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrs_Q_Skol SkolemInfo
skol_info = SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
forall a. SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = False, sm_parent = True, sm_tvtv = SMDSkolemTv skol_info })
bindImplicitTKBndrs_Q_Tv :: forall a. HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrs_Q_Tv = SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
forall a. SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrsX (SkolemMode
HasDebugCallStack => SkolemMode
smVanilla { sm_clone = False, sm_parent = True, sm_tvtv = SMDTyVarTv })

bindImplicitTKBndrsX
   :: SkolemMode
   -> [Name]               -- Generated by renamer; not in dependency order
   -> TcM a
   -> TcM ([TcTyVar], a)   -- Returned [TcTyVar] are in 1-1 correspondence
                           -- with the passed in [Name]
bindImplicitTKBndrsX :: forall a. SkolemMode -> HsQTvsRn -> TcM a -> TcM ([TcTyVar], a)
bindImplicitTKBndrsX skol_mode :: SkolemMode
skol_mode@(SM { sm_parent :: SkolemMode -> Bool
sm_parent = Bool
check_parent, sm_kind :: SkolemMode -> ContextKind
sm_kind = ContextKind
ctxt_kind })
                     HsQTvsRn
tv_names TcM a
thing_inside
  = do { NameEnv TcTyThing
lcl_env <- TcM (NameEnv TcTyThing)
getLclTypeEnv
       ; [TcTyVar]
tkvs <- (Name -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar)
-> HsQTvsRn -> TcM [TcTyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (NameEnv TcTyThing -> Name -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
new_tv NameEnv TcTyThing
lcl_env) HsQTvsRn
tv_names
       ; String -> SDoc -> TcM ()
traceTc String
"bindImplicitTKBndrsX" (HsQTvsRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsQTvsRn
tv_names SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
tkvs)
       ; a
res <- [(Name, TcTyVar)] -> TcM a -> TcM a
forall r. [(Name, TcTyVar)] -> TcM r -> TcM r
tcExtendNameTyVarEnv (HsQTvsRn
tv_names HsQTvsRn -> [TcTyVar] -> [(Name, TcTyVar)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [TcTyVar]
tkvs)
                TcM a
thing_inside
       ; ([TcTyVar], a) -> TcM ([TcTyVar], a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([TcTyVar]
tkvs, a
res) }
  where
    new_tv :: NameEnv TcTyThing -> Name -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
new_tv NameEnv TcTyThing
lcl_env Name
name
      | Bool
check_parent
      , Just (ATyVar Name
_ TcTyVar
tv) <- NameEnv TcTyThing -> Name -> Maybe TcTyThing
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv NameEnv TcTyThing
lcl_env Name
name
      = TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TcTyVar
tv
      | Bool
otherwise
      = do { Type
kind <- ContextKind -> TcM Type
newExpectedKind ContextKind
ctxt_kind
           ; SkolemMode -> Name -> Type -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newTyVarBndr SkolemMode
skol_mode Name
name Type
kind }

--------------------------------------
--           SkolemMode
--------------------------------------

-- | 'SkolemMode' describes how to typecheck an explicit ('HsTyVarBndr') or
-- implicit ('Name') binder in a type. It is just a record of flags
-- that describe what sort of 'TcTyVar' to create.
data SkolemMode
  = SM { SkolemMode -> Bool
sm_parent :: Bool    -- True <=> check the in-scope parent type variable
                              -- Used only for asssociated types

       , SkolemMode -> Bool
sm_clone  :: Bool    -- True <=> fresh unique
                              -- See Note [Cloning for type variable binders]

       , SkolemMode -> SkolemModeDetails
sm_tvtv   :: SkolemModeDetails    -- True <=> use a TyVarTv, rather than SkolemTv
                              -- Why?  See Note [Inferring kinds for type declarations]
                              -- in GHC.Tc.TyCl, and (in this module)
                              -- Note [Checking partial type signatures]

       , SkolemMode -> ContextKind
sm_kind   :: ContextKind  -- Use this for the kind of any new binders

       , SkolemMode -> HoleInfo
sm_holes  :: HoleInfo     -- What to do for wildcards in the kind
       }

data SkolemModeDetails
  = SMDTyVarTv
  | SMDSkolemTv SkolemInfo


smVanilla :: HasDebugCallStack => SkolemMode
smVanilla :: HasDebugCallStack => SkolemMode
smVanilla = SM { sm_clone :: Bool
sm_clone  = String -> Bool
forall a. HasCallStack => String -> a
panic String
"sm_clone"  -- We always override this
               , sm_parent :: Bool
sm_parent = Bool
False
               , sm_tvtv :: SkolemModeDetails
sm_tvtv   = String -> SDoc -> SkolemModeDetails
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"sm_tvtv" SDoc
HasCallStack => SDoc
callStackDoc -- We always override this
               , sm_kind :: ContextKind
sm_kind   = ContextKind
AnyKind
               , sm_holes :: HoleInfo
sm_holes  = HoleInfo
forall a. Maybe a
Nothing }

{- Note [Cloning for type variable binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes we must clone the Name of a type variable binder (written in
the source program); and sometimes we must not. This is controlled by
the sm_clone field of SkolemMode.

In some cases it doesn't matter whether or not we clone. Perhaps
it'd be better to use MustClone/MayClone/MustNotClone.

When we /must not/ clone
* In the binders of a type signature (tcOuterTKBndrs)
      f :: forall a{27}. blah
      f = rhs
  Then 'a' scopes over 'rhs'. When we kind-check the signature (tcHsSigType),
  we must get the type (forall a{27}. blah) for the Id f, because
  we bring that type variable into scope when we typecheck 'rhs'.

* In the binders of a data family instance (bindOuterFamEqnTKBndrs)
     data instance
       forall p q. D (p,q) = D1 p | D2 q
  We kind-check the LHS in tcDataFamInstHeader, and then separately
  (in tcDataFamInstDecl) bring p,q into scope before looking at the
  the constructor decls.

* bindExplicitTKBndrs_Q_Tv/bindImplicitTKBndrs_Q_Tv do not clone
  We take advantage of this in kcInferDeclHeader:
     all_tv_prs = mkTyVarNamePairs (scoped_kvs ++ tc_tvs)
  If we cloned, we'd need to take a bit more care here; not hard.

* bindExplicitTKBndrs_Q_Skol, bindExplicitTKBndrs_Skol, do not clone.
  There is no need, I think.

  The payoff here is that avoiding gratuitous cloning means that we can
  almost always take the fast path in swizzleTcTyConBndrs.

When we /must/ clone.
* bindOuterSigTKBndrs_Tv, bindExplicitTKBndrs_Tv do cloning

  This for a narrow and tricky reason which, alas, I couldn't find a
  simpler way round.  #16221 is the poster child:

     data SameKind :: k -> k -> *
     data T a = forall k2 (b :: k2). MkT (SameKind a b) !Int

  When kind-checking T, we give (a :: kappa1). Then:

  - In kcConDecl we make a TyVarTv unification variable kappa2 for k2
    (as described in Note [Using TyVarTvs for kind-checking GADTs],
    even though this example is an existential)
  - So we get (b :: kappa2) via bindExplicitTKBndrs_Tv
  - We end up unifying kappa1 := kappa2, because of the (SameKind a b)

  Now we generalise over kappa2. But if kappa2's Name is precisely k2
  (i.e. we did not clone) we'll end up giving T the utterly final kind
    T :: forall k2. k2 -> *
  Nothing directly wrong with that but when we typecheck the data constructor
  we have k2 in scope; but then it's brought into scope /again/ when we find
  the forall k2.  This is chaotic, and we end up giving it the type
    MkT :: forall k2 (a :: k2) k2 (b :: k2).
           SameKind @k2 a b -> Int -> T @{k2} a
  which is bogus -- because of the shadowing of k2, we can't
  apply T to the kind or a!

  And there no reason /not/ to clone the Name when making a unification
  variable.  So that's what we do.
-}

--------------------------------------
-- Binding type/class variables in the
-- kind-checking and typechecking phases
--------------------------------------

bindTyClTyVars :: Name -> ([TcTyConBinder] -> TcKind -> TcM a) -> TcM a
-- ^ Bring into scope the binders of a PolyTcTyCon
-- Used for the type variables of a type or class decl
-- in the "kind checking" and "type checking" pass,
-- but not in the initial-kind run.
bindTyClTyVars :: forall a. Name -> ([TyConBinder] -> Type -> TcM a) -> TcM a
bindTyClTyVars Name
tycon_name [TyConBinder] -> Type -> TcM a
thing_inside
  = do { TyCon
tycon <- HasDebugCallStack => Name -> TcM TyCon
Name -> TcM TyCon
tcLookupTcTyCon Name
tycon_name     -- The tycon is a PolyTcTyCon
       ; let res_kind :: Type
res_kind   = TyCon -> Type
tyConResKind TyCon
tycon
             binders :: [TyConBinder]
binders    = TyCon -> [TyConBinder]
tyConBinders TyCon
tycon
       ; String -> SDoc -> TcM ()
traceTc String
"bindTyClTyVars" (Name -> SDoc
forall a. Outputable a => a -> SDoc
ppr Name
tycon_name SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [TyConBinder] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TyConBinder]
binders)
       ; [TcTyVar] -> TcM a -> TcM a
forall r. [TcTyVar] -> TcM r -> TcM r
tcExtendTyVarEnv ([TyConBinder] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [TyConBinder]
binders) (TcM a -> TcM a) -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$
         [TyConBinder] -> Type -> TcM a
thing_inside [TyConBinder]
binders Type
res_kind }

bindTyClTyVarsAndZonk :: Name -> ([TyConBinder] -> Kind -> TcM a) -> TcM a
-- Like bindTyClTyVars, but in addition
-- zonk the skolem TcTyVars of a PolyTcTyCon to TyVars
-- We always do this same zonking after a call to bindTyClTyVars, but
-- here we do it right away because there are no more unifications to come
bindTyClTyVarsAndZonk :: forall a. Name -> ([TyConBinder] -> Type -> TcM a) -> TcM a
bindTyClTyVarsAndZonk Name
tycon_name [TyConBinder] -> Type -> TcM a
thing_inside
  = Name -> ([TyConBinder] -> Type -> TcM a) -> TcM a
forall a. Name -> ([TyConBinder] -> Type -> TcM a) -> TcM a
bindTyClTyVars Name
tycon_name (([TyConBinder] -> Type -> TcM a) -> TcM a)
-> ([TyConBinder] -> Type -> TcM a) -> TcM a
forall a b. (a -> b) -> a -> b
$ \ [TyConBinder]
tc_bndrs Type
tc_kind ->
    do { ([TyConBinder]
bndrs, Type
kind) <- ZonkFlexi
-> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) ([TyConBinder], Type)
-> TcM ([TyConBinder], Type)
forall (m :: * -> *) b. MonadIO m => ZonkFlexi -> ZonkT m b -> m b
initZonkEnv ZonkFlexi
NoFlexi (ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) ([TyConBinder], Type)
 -> TcM ([TyConBinder], Type))
-> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) ([TyConBinder], Type)
-> TcM ([TyConBinder], Type)
forall a b. (a -> b) -> a -> b
$
          ZonkBndrT (IOEnv (Env TcGblEnv TcLclEnv)) [TyConBinder]
-> forall r.
   ([TyConBinder] -> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) r)
   -> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) r
forall (m :: * -> *) a.
ZonkBndrT m a -> forall r. (a -> ZonkT m r) -> ZonkT m r
runZonkBndrT ([TyConBinder]
-> ZonkBndrT (IOEnv (Env TcGblEnv TcLclEnv)) [TyConBinder]
forall vis.
[VarBndr TcTyVar vis] -> ZonkBndrTcM [VarBndr TcTyVar vis]
zonkTyVarBindersX [TyConBinder]
tc_bndrs) (([TyConBinder]
  -> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) ([TyConBinder], Type))
 -> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) ([TyConBinder], Type))
-> ([TyConBinder]
    -> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) ([TyConBinder], Type))
-> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) ([TyConBinder], Type)
forall a b. (a -> b) -> a -> b
$ \ [TyConBinder]
bndrs ->
            do { Type
kind <- Type -> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) Type
zonkTcTypeToTypeX Type
tc_kind
               ; ([TyConBinder], Type)
-> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) ([TyConBinder], Type)
forall a. a -> ZonkT (IOEnv (Env TcGblEnv TcLclEnv)) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([TyConBinder]
bndrs, Type
kind) }
       ; [TyConBinder] -> Type -> TcM a
thing_inside [TyConBinder]
bndrs Type
kind }


{- *********************************************************************
*                                                                      *
             Kind generalisation
*                                                                      *
********************************************************************* -}

zonkAndScopedSort :: [TcTyVar] -> TcM [TcTyVar]
zonkAndScopedSort :: [TcTyVar] -> TcM [TcTyVar]
zonkAndScopedSort [TcTyVar]
spec_tkvs
  = do { [TcTyVar]
spec_tkvs <- ZonkM [TcTyVar] -> TcM [TcTyVar]
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM [TcTyVar] -> TcM [TcTyVar])
-> ZonkM [TcTyVar] -> TcM [TcTyVar]
forall a b. (a -> b) -> a -> b
$ [TcTyVar] -> ZonkM [TcTyVar]
HasDebugCallStack => [TcTyVar] -> ZonkM [TcTyVar]
zonkTcTyVarsToTcTyVars [TcTyVar]
spec_tkvs
         -- Zonk the kinds, to we can do the dependency analysis

       -- Do a stable topological sort, following
       -- Note [Ordering of implicit variables] in GHC.Rename.HsType
       ; [TcTyVar] -> TcM [TcTyVar]
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([TcTyVar] -> [TcTyVar]
scopedSort [TcTyVar]
spec_tkvs) }

-- | Generalize some of the free variables in the given type.
-- All such variables should be *kind* variables; any type variables
-- should be explicitly quantified (with a `forall`) before now.
--
-- The WantedConstraints are un-solved kind constraints. Generally
-- they'll be reported as errors later, but meanwhile we refrain
-- from quantifying over any variable free in these unsolved
-- constraints. See Note [Failure in local type signatures].
--
-- But in all cases, generalize only those variables whose TcLevel is
-- strictly greater than the ambient level. This "strictly greater
-- than" means that you likely need to push the level before creating
-- whatever type gets passed here.
--
-- Any variable whose level is greater than the ambient level but is
-- not selected to be generalized will be promoted. (See [Promoting
-- unification variables] in "GHC.Tc.Solver" and Note [Recipe for
-- checking a signature].)
--
-- The resulting KindVar are the variables to quantify over, in the
-- correct, well-scoped order. They should generally be Inferred, not
-- Specified, but that's really up to the caller of this function.
kindGeneralizeSome :: SkolemInfo
                   -> WantedConstraints
                   -> TcType    -- ^ needn't be zonked
                   -> TcM [KindVar]
kindGeneralizeSome :: SkolemInfo -> WantedConstraints -> Type -> TcM [TcTyVar]
kindGeneralizeSome SkolemInfo
skol_info WantedConstraints
wanted Type
kind_or_type
  = do { -- Use the "Kind" variant here, as any types we see
         -- here will already have all type variables quantified;
         -- thus, every free variable is really a kv, never a tv.
       ; CandidatesQTvs
dvs <- Type -> TcM CandidatesQTvs
candidateQTyVarsOfKind Type
kind_or_type
       ; CandidatesQTvs
filtered_dvs <- WantedConstraints -> CandidatesQTvs -> TcM CandidatesQTvs
filterConstrainedCandidates WantedConstraints
wanted CandidatesQTvs
dvs
       ; String -> SDoc -> TcM ()
traceTc String
"kindGeneralizeSome" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"type:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
kind_or_type
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"dvs:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> CandidatesQTvs -> SDoc
forall a. Outputable a => a -> SDoc
ppr CandidatesQTvs
dvs
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"filtered_dvs:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> CandidatesQTvs -> SDoc
forall a. Outputable a => a -> SDoc
ppr CandidatesQTvs
filtered_dvs ]
       ; SkolemInfo
-> NonStandardDefaultingStrategy -> CandidatesQTvs -> TcM [TcTyVar]
quantifyTyVars SkolemInfo
skol_info NonStandardDefaultingStrategy
DefaultNonStandardTyVars CandidatesQTvs
filtered_dvs }

filterConstrainedCandidates
  :: WantedConstraints    -- Don't quantify over variables free in these
                          --   Not necessarily fully zonked
  -> CandidatesQTvs       -- Candidates for quantification
  -> TcM CandidatesQTvs
-- filterConstrainedCandidates removes any candidates that are free in
-- 'wanted'; instead, it promotes them.  This bit is very much like
-- decideMonoTyVars in GHC.Tc.Solver, but constraints are so much
-- simpler in kinds, it is much easier here. (In particular, we never
-- quantify over a constraint in a type.)
filterConstrainedCandidates :: WantedConstraints -> CandidatesQTvs -> TcM CandidatesQTvs
filterConstrainedCandidates WantedConstraints
wanted CandidatesQTvs
dvs
  | WantedConstraints -> Bool
isEmptyWC WantedConstraints
wanted   -- Fast path for a common case
  = CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dvs
  | Bool
otherwise
  = do { TyVarSet
wc_tvs <- ZonkM TyVarSet -> TcM TyVarSet
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM TyVarSet -> TcM TyVarSet) -> ZonkM TyVarSet -> TcM TyVarSet
forall a b. (a -> b) -> a -> b
$ TyVarSet -> ZonkM TyVarSet
zonkTyCoVarsAndFV (WantedConstraints -> TyVarSet
tyCoVarsOfWC WantedConstraints
wanted)
       ; let (TyVarSet
to_promote, CandidatesQTvs
dvs') = CandidatesQTvs -> (TcTyVar -> Bool) -> (TyVarSet, CandidatesQTvs)
partitionCandidates CandidatesQTvs
dvs (TcTyVar -> TyVarSet -> Bool
`elemVarSet` TyVarSet
wc_tvs)
       ; Bool
_ <- HasDebugCallStack => TyVarSet -> TcRnIf TcGblEnv TcLclEnv Bool
TyVarSet -> TcRnIf TcGblEnv TcLclEnv Bool
promoteTyVarSet TyVarSet
to_promote
       ; CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dvs' }

-- |- Specialised version of 'kindGeneralizeSome', but with empty
-- WantedConstraints, so no filtering is needed
-- i.e.   kindGeneraliseAll = kindGeneralizeSome emptyWC
kindGeneralizeAll :: SkolemInfo -> TcType -> TcM [KindVar]
kindGeneralizeAll :: SkolemInfo -> Type -> TcM [TcTyVar]
kindGeneralizeAll SkolemInfo
skol_info Type
kind_or_type
  = do { String -> SDoc -> TcM ()
traceTc String
"kindGeneralizeAll" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
kind_or_type)
       ; CandidatesQTvs
dvs <- Type -> TcM CandidatesQTvs
candidateQTyVarsOfKind Type
kind_or_type
       ; SkolemInfo
-> NonStandardDefaultingStrategy -> CandidatesQTvs -> TcM [TcTyVar]
quantifyTyVars SkolemInfo
skol_info NonStandardDefaultingStrategy
DefaultNonStandardTyVars CandidatesQTvs
dvs }

-- | Specialized version of 'kindGeneralizeSome', but where no variables
-- can be generalized, but perhaps some may need to be promoted.
-- Use this variant when it is unknowable whether metavariables might
-- later be constrained.
--
-- To see why this promotion is needed, see
-- Note [Recipe for checking a signature], and especially
-- Note [Promotion in signatures].
kindGeneralizeNone :: TcType  -- needn't be zonked
                   -> TcM ()
kindGeneralizeNone :: Type -> TcM ()
kindGeneralizeNone Type
kind_or_type
  = do { String -> SDoc -> TcM ()
traceTc String
"kindGeneralizeNone" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
kind_or_type)
       ; CandidatesQTvs
dvs <- Type -> TcM CandidatesQTvs
candidateQTyVarsOfKind Type
kind_or_type
       ; Bool
_ <- HasDebugCallStack => TyVarSet -> TcRnIf TcGblEnv TcLclEnv Bool
TyVarSet -> TcRnIf TcGblEnv TcLclEnv Bool
promoteTyVarSet (CandidatesQTvs -> TyVarSet
candidateKindVars CandidatesQTvs
dvs)
       ; () -> TcM ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return () }

{- Note [Levels and generalisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  f x = e
with no type signature. We are currently at level i.
We must
  * Push the level to level (i+1)
  * Allocate a fresh alpha[i+1] for the result type
  * Check that e :: alpha[i+1], gathering constraint WC
  * Solve WC as far as possible
  * Zonking the result type alpha[i+1], say to beta[i-1] -> gamma[i]
  * Find the free variables with level > i, in this case gamma[i]
  * Skolemise those free variables and quantify over them, giving
       f :: forall g. beta[i-1] -> g
  * Emit the residual constraint wrapped in an implication for g,
    thus   forall g. WC

All of this happens for types too.  Consider
  f :: Int -> (forall a. Proxy a -> Int)

Note [Kind generalisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~
We do kind generalisation only at the outer level of a type signature.
For example, consider
  T :: forall k. k -> *
  f :: (forall a. T a -> Int) -> Int
When kind-checking f's type signature we generalise the kind at
the outermost level, thus:
  f1 :: forall k. (forall (a:k). T k a -> Int) -> Int  -- YES!
and *not* at the inner forall:
  f2 :: (forall k. forall (a:k). T k a -> Int) -> Int  -- NO!
Reason: same as for HM inference on value level declarations,
we want to infer the most general type.  The f2 type signature
would be *less applicable* than f1, because it requires a more
polymorphic argument.

NB: There are no explicit kind variables written in f's signature.
When there are, the renamer adds these kind variables to the list of
variables bound by the forall, so you can indeed have a type that's
higher-rank in its kind. But only by explicit request.

Note [Kinds of quantified type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tcTyVarBndrsGen quantifies over a specified list of type variables,
*and* over the kind variables mentioned in the kinds of those tyvars.

Note that we must zonk those kinds (obviously) but less obviously, we
must return type variables whose kinds are zonked too. Example
    (a :: k7)  where  k7 := k9 -> k9
We must return
    [k9, a:k9->k9]
and NOT
    [k9, a:k7]
Reason: we're going to turn this into a for-all type,
   forall k9. forall (a:k7). blah
which the type checker will then instantiate, and instantiate does not
look through unification variables!

Hence using zonked_kinds when forming tvs'.

-}

-----------------------------------
etaExpandAlgTyCon :: TyConFlavour tc  -> SkolemInfo
                  -> [TcTyConBinder] -> Kind
                  -> TcM ([TcTyConBinder], Kind)
etaExpandAlgTyCon :: forall tc.
TyConFlavour tc
-> SkolemInfo -> [TyConBinder] -> Type -> TcM ([TyConBinder], Type)
etaExpandAlgTyCon TyConFlavour tc
flav SkolemInfo
skol_info [TyConBinder]
tcbs Type
res_kind
  | TyConFlavour tc -> Bool
forall tc. TyConFlavour tc -> Bool
needsEtaExpansion TyConFlavour tc
flav
  = SkolemInfo
-> InScopeSet -> [OccName] -> Type -> TcM ([TyConBinder], Type)
splitTyConKind SkolemInfo
skol_info InScopeSet
in_scope [OccName]
avoid_occs Type
res_kind
  | Bool
otherwise
  = ([TyConBinder], Type) -> TcM ([TyConBinder], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([], Type
res_kind)
  where
    tyvars :: [TcTyVar]
tyvars     = [TyConBinder] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [TyConBinder]
tcbs
    in_scope :: InScopeSet
in_scope   = [TcTyVar] -> InScopeSet
mkInScopeSetList [TcTyVar]
tyvars
    avoid_occs :: [OccName]
avoid_occs = (TcTyVar -> OccName) -> [TcTyVar] -> [OccName]
forall a b. (a -> b) -> [a] -> [b]
map TcTyVar -> OccName
forall a. NamedThing a => a -> OccName
getOccName [TcTyVar]
tyvars

needsEtaExpansion :: TyConFlavour tc -> Bool
needsEtaExpansion :: forall tc. TyConFlavour tc -> Bool
needsEtaExpansion TyConFlavour tc
NewtypeFlavour  = Bool
True
needsEtaExpansion TyConFlavour tc
DataTypeFlavour = Bool
True
needsEtaExpansion TyConFlavour tc
ClassFlavour    = Bool
True
needsEtaExpansion TyConFlavour tc
_               = Bool
False

splitTyConKind :: SkolemInfo
               -> InScopeSet
               -> [OccName]  -- Avoid these OccNames
               -> Kind       -- Must be zonked
               -> TcM ([TcTyConBinder], TcKind)
-- GADT decls can have a (perhaps partial) kind signature
--      e.g.  data T a :: * -> * -> * where ...
-- This function makes up suitable (kinded) TyConBinders for the
-- argument kinds.  E.g. in this case it might return
--   ([b::*, c::*], *)
-- Skolemises the type as it goes, returning skolem TcTyVars
-- Never emits constraints.
-- It's a little trickier than you might think: see Note [splitTyConKind]
-- See also Note [Datatype return kinds] in GHC.Tc.TyCl
splitTyConKind :: SkolemInfo
-> InScopeSet -> [OccName] -> Type -> TcM ([TyConBinder], Type)
splitTyConKind SkolemInfo
skol_info InScopeSet
in_scope [OccName]
avoid_occs Type
kind
  = do  { SrcSpan
loc     <- TcRn SrcSpan
getSrcSpanM
        ; [Unique]
new_uniqs <- IOEnv (Env TcGblEnv TcLclEnv) [Unique]
forall (m :: * -> *). MonadUnique m => m [Unique]
getUniquesM
        ; LocalRdrEnv
rdr_env <- RnM LocalRdrEnv
getLocalRdrEnv
        ; TcLevel
lvl     <- TcM TcLevel
getTcLevel
        ; let new_occs :: Infinite OccName
new_occs = (OccName -> Bool) -> Infinite OccName -> Infinite OccName
forall a. (a -> Bool) -> Infinite a -> Infinite a
Inf.filter (\ OccName
occ ->
                  Maybe Name -> Bool
forall a. Maybe a -> Bool
isNothing (LocalRdrEnv -> OccName -> Maybe Name
lookupLocalRdrOcc LocalRdrEnv
rdr_env OccName
occ) Bool -> Bool -> Bool
&&
                  -- Note [Avoid name clashes for associated data types]
                  Bool -> Bool
not (OccName
occ OccName -> [OccName] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [OccName]
avoid_occs)) (Infinite OccName -> Infinite OccName)
-> Infinite OccName -> Infinite OccName
forall a b. (a -> b) -> a -> b
$ NameSpace -> String -> OccName
mkOccName NameSpace
tvName (String -> OccName) -> Infinite String -> Infinite OccName
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Infinite String
allNameStrings
              subst :: Subst
subst = InScopeSet -> Subst
mkEmptySubst InScopeSet
in_scope
              details :: TcTyVarDetails
details = SkolemInfo -> TcLevel -> Bool -> TcTyVarDetails
SkolemTv SkolemInfo
skol_info (TcLevel -> TcLevel
pushTcLevel TcLevel
lvl) Bool
False
                        -- As always, allocate skolems one level in

              go :: Infinite OccName
-> [Unique]
-> Subst
-> [TyConBinder]
-> Type
-> ([TyConBinder], Type)
go Infinite OccName
occs [Unique]
uniqs Subst
subst [TyConBinder]
acc Type
kind
                = case Type -> Maybe (PiTyVarBinder, Type)
splitPiTy_maybe Type
kind of
                    Maybe (PiTyVarBinder, Type)
Nothing -> ([TyConBinder] -> [TyConBinder]
forall a. [a] -> [a]
reverse [TyConBinder]
acc, HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst Type
kind)

                    Just (Anon Scaled Type
arg FunTyFlag
af, Type
kind')
                      -> Bool -> ([TyConBinder], Type) -> ([TyConBinder], Type)
forall a. HasCallStack => Bool -> a -> a
assert (FunTyFlag
af FunTyFlag -> FunTyFlag -> Bool
forall a. Eq a => a -> a -> Bool
== FunTyFlag
FTF_T_T) (([TyConBinder], Type) -> ([TyConBinder], Type))
-> ([TyConBinder], Type) -> ([TyConBinder], Type)
forall a b. (a -> b) -> a -> b
$
                         Infinite OccName
-> [Unique]
-> Subst
-> [TyConBinder]
-> Type
-> ([TyConBinder], Type)
go Infinite OccName
occs' [Unique]
uniqs' Subst
subst' (TyConBinder
tcb TyConBinder -> [TyConBinder] -> [TyConBinder]
forall a. a -> [a] -> [a]
: [TyConBinder]
acc) Type
kind'
                      where
                        tcb :: TyConBinder
tcb    = TcTyVar -> TyConBndrVis -> TyConBinder
forall var argf. var -> argf -> VarBndr var argf
Bndr TcTyVar
tv TyConBndrVis
AnonTCB
                        arg' :: Type
arg'   = HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst (Scaled Type -> Type
forall a. Scaled a -> a
scaledThing Scaled Type
arg)
                        name :: Name
name   = Unique -> OccName -> SrcSpan -> Name
mkInternalName Unique
uniq OccName
occ SrcSpan
loc
                        tv :: TcTyVar
tv     = Name -> Type -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
name Type
arg' TcTyVarDetails
details
                        subst' :: Subst
subst' = Subst -> TcTyVar -> Subst
extendSubstInScope Subst
subst TcTyVar
tv
                        Unique
uniq:[Unique]
uniqs' = [Unique]
uniqs
                        Inf OccName
occ Infinite OccName
occs' = Infinite OccName
occs

                    Just (Named (Bndr TcTyVar
tv ForAllTyFlag
vis), Type
kind')
                      -> Infinite OccName
-> [Unique]
-> Subst
-> [TyConBinder]
-> Type
-> ([TyConBinder], Type)
go Infinite OccName
occs [Unique]
uniqs Subst
subst' (TyConBinder
tcb TyConBinder -> [TyConBinder] -> [TyConBinder]
forall a. a -> [a] -> [a]
: [TyConBinder]
acc) Type
kind'
                      where
                        tcb :: TyConBinder
tcb           = TcTyVar -> TyConBndrVis -> TyConBinder
forall var argf. var -> argf -> VarBndr var argf
Bndr TcTyVar
tv' (ForAllTyFlag -> TyConBndrVis
NamedTCB ForAllTyFlag
vis)
                        tc_tyvar :: TcTyVar
tc_tyvar      = Name -> Type -> TcTyVarDetails -> TcTyVar
mkTcTyVar (TcTyVar -> Name
tyVarName TcTyVar
tv) (TcTyVar -> Type
tyVarKind TcTyVar
tv) TcTyVarDetails
details
                        (Subst
subst', TcTyVar
tv') = HasDebugCallStack => Subst -> TcTyVar -> (Subst, TcTyVar)
Subst -> TcTyVar -> (Subst, TcTyVar)
substTyVarBndr Subst
subst TcTyVar
tc_tyvar

        ; ([TyConBinder], Type) -> TcM ([TyConBinder], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Infinite OccName
-> [Unique]
-> Subst
-> [TyConBinder]
-> Type
-> ([TyConBinder], Type)
go Infinite OccName
new_occs [Unique]
new_uniqs Subst
subst [] Type
kind) }

isAllowedDataResKind :: AllowedDataResKind -> Kind -> Bool
isAllowedDataResKind :: AllowedDataResKind -> Type -> Bool
isAllowedDataResKind AllowedDataResKind
AnyTYPEKind  Type
kind = Type -> Bool
isTypeLikeKind     Type
kind
isAllowedDataResKind AllowedDataResKind
AnyBoxedKind Type
kind = Type -> Bool
tcIsBoxedTypeKind  Type
kind
isAllowedDataResKind AllowedDataResKind
LiftedKind   Type
kind = Type -> Bool
tcIsLiftedTypeKind Type
kind

-- | Checks that the return kind in a data declaration's kind signature is
-- permissible. There are three cases:
--
-- If dealing with a @data@, @newtype@, @data instance@, or @newtype instance@
-- declaration, check that the return kind is @Type@.
--
-- If the declaration is a @newtype@ or @newtype instance@ and the
-- @UnliftedNewtypes@ extension is enabled, this check is slightly relaxed so
-- that a return kind of the form @TYPE r@ (for some @r@) is permitted.
-- See @Note [Implementation of UnliftedNewtypes]@ in "GHC.Tc.TyCl".
--
-- If dealing with a @data family@ declaration, check that the return kind is
-- either of the form:
--
-- 1. @TYPE r@ (for some @r@), or
--
-- 2. @k@ (where @k@ is a bare kind variable; see #12369)
--
-- See also Note [Datatype return kinds] in "GHC.Tc.TyCl"
checkDataKindSig :: DataSort -> Kind  -- any arguments in the kind are stripped off
                 -> TcM ()
checkDataKindSig :: DataSort -> Type -> TcM ()
checkDataKindSig DataSort
data_sort Type
kind
  = do { DynFlags
dflags <- IOEnv (Env TcGblEnv TcLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; String -> SDoc -> TcM ()
traceTc String
"checkDataKindSig" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
kind)
       ; Bool -> TcRnMessage -> TcM ()
checkTc (DynFlags -> Bool
tYPE_ok DynFlags
dflags Bool -> Bool -> Bool
|| Bool
is_kind_var)
                 (DynFlags -> TcRnMessage
err_msg DynFlags
dflags) }
  where
    res_kind :: Type
res_kind = ([PiTyVarBinder], Type) -> Type
forall a b. (a, b) -> b
snd (Type -> ([PiTyVarBinder], Type)
tcSplitPiTys Type
kind)
       -- Look for the result kind after
       -- peeling off any foralls and arrows

    is_newtype :: Bool
    is_newtype :: Bool
is_newtype =
      case DataSort
data_sort of
        DataDeclSort     NewOrData
new_or_data -> NewOrData
new_or_data NewOrData -> NewOrData -> Bool
forall a. Eq a => a -> a -> Bool
== NewOrData
NewType
        DataInstanceSort NewOrData
new_or_data -> NewOrData
new_or_data NewOrData -> NewOrData -> Bool
forall a. Eq a => a -> a -> Bool
== NewOrData
NewType
        DataSort
DataFamilySort               -> Bool
False

    is_datatype :: Bool
    is_datatype :: Bool
is_datatype =
      case DataSort
data_sort of
        DataDeclSort     NewOrData
DataType -> Bool
True
        DataInstanceSort NewOrData
DataType -> Bool
True
        DataSort
_                         -> Bool
False

    is_data_family :: Bool
    is_data_family :: Bool
is_data_family =
      case DataSort
data_sort of
        DataDeclSort{}     -> Bool
False
        DataInstanceSort{} -> Bool
False
        DataSort
DataFamilySort     -> Bool
True

    allowed_kind :: DynFlags -> AllowedDataResKind
    allowed_kind :: DynFlags -> AllowedDataResKind
allowed_kind DynFlags
dflags
      | Bool
is_newtype Bool -> Bool -> Bool
&& Extension -> DynFlags -> Bool
xopt Extension
LangExt.UnliftedNewtypes DynFlags
dflags
        -- With UnliftedNewtypes, we allow kinds other than Type, but they
        -- must still be of the form `TYPE r` since we don't want to accept
        -- Constraint or Nat.
        -- See Note [Implementation of UnliftedNewtypes] in GHC.Tc.TyCl.
      = AllowedDataResKind
AnyTYPEKind
      | Bool
is_data_family
        -- If this is a `data family` declaration, we don't need to check if
        -- UnliftedNewtypes is enabled, since data family declarations can
        -- have return kind `TYPE r` unconditionally (#16827).
      = AllowedDataResKind
AnyTYPEKind
      | Bool
is_datatype Bool -> Bool -> Bool
&& Extension -> DynFlags -> Bool
xopt Extension
LangExt.UnliftedDatatypes DynFlags
dflags
        -- With UnliftedDatatypes, we allow kinds other than Type, but they
        -- must still be of the form `TYPE (BoxedRep l)`, so that we don't
        -- accept result kinds like `TYPE IntRep`.
        -- See Note [Implementation of UnliftedDatatypes] in GHC.Tc.TyCl.
      = AllowedDataResKind
AnyBoxedKind
      | Bool
otherwise
      = AllowedDataResKind
LiftedKind

    tYPE_ok :: DynFlags -> Bool
    tYPE_ok :: DynFlags -> Bool
tYPE_ok DynFlags
dflags = AllowedDataResKind -> Type -> Bool
isAllowedDataResKind (DynFlags -> AllowedDataResKind
allowed_kind DynFlags
dflags) Type
res_kind

    -- In the particular case of a data family, permit a return kind of the
    -- form `:: k` (where `k` is a bare kind variable).
    is_kind_var :: Bool
    is_kind_var :: Bool
is_kind_var | Bool
is_data_family = Maybe (TcTyVar, Coercion) -> Bool
forall a. Maybe a -> Bool
isJust (Type -> Maybe (TcTyVar, Coercion)
getCastedTyVar_maybe Type
res_kind)
                | Bool
otherwise      = Bool
False

    err_msg :: DynFlags -> TcRnMessage
    err_msg :: DynFlags -> TcRnMessage
err_msg DynFlags
dflags =
      DataSort
-> AllowedDataResKind
-> Type
-> Maybe SuggestUnliftedTypes
-> TcRnMessage
TcRnInvalidReturnKind DataSort
data_sort (DynFlags -> AllowedDataResKind
allowed_kind DynFlags
dflags) Type
kind (DynFlags -> Maybe SuggestUnliftedTypes
ext_hint DynFlags
dflags)

    ext_hint :: DynFlags -> Maybe SuggestUnliftedTypes
ext_hint DynFlags
dflags
      | Type -> Bool
isTypeLikeKind Type
kind
      , Bool
is_newtype
      , Bool -> Bool
not (Extension -> DynFlags -> Bool
xopt Extension
LangExt.UnliftedNewtypes DynFlags
dflags)
      = SuggestUnliftedTypes -> Maybe SuggestUnliftedTypes
forall a. a -> Maybe a
Just SuggestUnliftedTypes
SuggestUnliftedNewtypes
      | Type -> Bool
tcIsBoxedTypeKind Type
kind
      , Bool
is_datatype
      , Bool -> Bool
not (Extension -> DynFlags -> Bool
xopt Extension
LangExt.UnliftedDatatypes DynFlags
dflags)
      = SuggestUnliftedTypes -> Maybe SuggestUnliftedTypes
forall a. a -> Maybe a
Just SuggestUnliftedTypes
SuggestUnliftedDatatypes
      | Bool
otherwise
      = Maybe SuggestUnliftedTypes
forall a. Maybe a
Nothing

-- | Checks that the result kind of a class is exactly `Constraint`, rejecting
-- type synonyms and type families that reduce to `Constraint`. See #16826.
checkClassKindSig :: Kind -> TcM ()
checkClassKindSig :: Type -> TcM ()
checkClassKindSig Type
kind = Bool -> TcRnMessage -> TcM ()
checkTc (Type -> Bool
isConstraintKind Type
kind) TcRnMessage
err_msg
  where
    err_msg :: TcRnMessage
    err_msg :: TcRnMessage
err_msg = Type -> TcRnMessage
TcRnClassKindNotConstraint Type
kind

tcbVisibilities :: TyCon -> [Type] -> [TyConBndrVis]
-- Result is in 1-1 correspondence with orig_args
tcbVisibilities :: TyCon -> [Type] -> [TyConBndrVis]
tcbVisibilities TyCon
tc [Type]
orig_args
  = Type -> Subst -> [Type] -> [TyConBndrVis]
go (TyCon -> Type
tyConKind TyCon
tc) Subst
init_subst [Type]
orig_args
  where
    init_subst :: Subst
init_subst = InScopeSet -> Subst
mkEmptySubst (TyVarSet -> InScopeSet
mkInScopeSet ([Type] -> TyVarSet
tyCoVarsOfTypes [Type]
orig_args))
    go :: Type -> Subst -> [Type] -> [TyConBndrVis]
go Type
_ Subst
_ []
      = []

    go Type
fun_kind Subst
subst all_args :: [Type]
all_args@(Type
arg : [Type]
args)
      | Just (PiTyVarBinder
tcb, Type
inner_kind) <- Type -> Maybe (PiTyVarBinder, Type)
splitPiTy_maybe Type
fun_kind
      = case PiTyVarBinder
tcb of
          Anon Scaled Type
_ FunTyFlag
af           -> Bool -> [TyConBndrVis] -> [TyConBndrVis]
forall a. HasCallStack => Bool -> a -> a
assert (FunTyFlag
af FunTyFlag -> FunTyFlag -> Bool
forall a. Eq a => a -> a -> Bool
== FunTyFlag
FTF_T_T) ([TyConBndrVis] -> [TyConBndrVis])
-> [TyConBndrVis] -> [TyConBndrVis]
forall a b. (a -> b) -> a -> b
$
                                 TyConBndrVis
AnonTCB      TyConBndrVis -> [TyConBndrVis] -> [TyConBndrVis]
forall a. a -> [a] -> [a]
: Type -> Subst -> [Type] -> [TyConBndrVis]
go Type
inner_kind Subst
subst  [Type]
args
          Named (Bndr TcTyVar
tv ForAllTyFlag
vis) -> ForAllTyFlag -> TyConBndrVis
NamedTCB ForAllTyFlag
vis TyConBndrVis -> [TyConBndrVis] -> [TyConBndrVis]
forall a. a -> [a] -> [a]
: Type -> Subst -> [Type] -> [TyConBndrVis]
go Type
inner_kind Subst
subst' [Type]
args
                 where
                    subst' :: Subst
subst' = Subst -> TcTyVar -> Type -> Subst
extendTCvSubst Subst
subst TcTyVar
tv Type
arg

      | Bool -> Bool
not (Subst -> Bool
isEmptyTCvSubst Subst
subst)
      = Type -> Subst -> [Type] -> [TyConBndrVis]
go (HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst Type
fun_kind) Subst
init_subst [Type]
all_args

      | Bool
otherwise
      = String -> SDoc -> [TyConBndrVis]
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"addTcbVisibilities" (TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
orig_args)


{- Note [splitTyConKind]
~~~~~~~~~~~~~~~~~~~~~~~~
Given
  data T (a::*) :: * -> forall k. k -> *
we want to generate the extra TyConBinders for T, so we finally get
  (a::*) (b::*) (k::*) (c::k)
The function splitTyConKind generates these extra TyConBinders from
the result kind signature.  The same function is also used by
kcCheckDeclHeader_sig to get the [TyConBinder] from the Kind of
the TyCon given in a standalone kind signature.  E.g.
  type T :: forall (a::*). * -> forall k. k -> *

We need to take care to give the TyConBinders
  (a) Uniques that are fresh: the TyConBinders of a TyCon
      must have distinct uniques.

  (b) Preferably, OccNames that are fresh. If we happen to re-use
      OccNames that are other TyConBinders, we'll get a TyCon with
      TyConBinders like [a_72, a_53]; same OccName, different Uniques.
      Then when pretty-printing (e.g. in GHCi :info) we'll see
          data T a a0
      whereas we'd prefer
          data T a b
      (NB: the tidying happens in the conversion to Iface syntax,
      which happens as part of pretty-printing a TyThing.)

      Using fresh OccNames is not essential; it's cosmetic.
      And also see Note [Avoid name clashes for associated data types].

For (a) perhaps surprisingly, duplicated uniques can happen, even if
we use fresh uniques for Anon arrows.  Consider
   data T :: forall k. k -> forall k. k -> *
where the two k's are identical even up to their uniques.  Surprisingly,
this can happen: see #14515, #19092,3,4.  Then if we use those k's in
as TyConBinders we'll get duplicated uniques.

For (b) we'd like to avoid OccName clashes with the tyvars declared by
the user before the "::"; in the above example that is 'a'.

It's reasonably easy to solve all this; just run down the list with a
substitution; hence the recursive 'go' function.  But for the Uniques
it has to be done.

Note [Avoid name clashes for associated data types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider    class C a b where
               data D b :: * -> *
When typechecking the decl for D, we'll invent an extra type variable
for D, to fill out its kind.  Ideally we don't want this type variable
to be 'a', because when pretty printing we'll get
            class C a b where
               data D b a0
(NB: the tidying happens in the conversion to Iface syntax, which happens
as part of pretty-printing a TyThing.)

That's why we look in the LocalRdrEnv to see what's in scope. This is
important only to get nice-looking output when doing ":info C" in GHCi.
It isn't essential for correctness.


************************************************************************
*                                                                      *
             Partial signatures
*                                                                      *
************************************************************************

-}

tcHsPartialSigType
  :: UserTypeCtxt
  -> LHsSigWcType GhcRn       -- The type signature
  -> TcM ( [(Name, TcTyVar)]  -- Wildcards
         , Maybe TcType       -- Extra-constraints wildcard
         , [(Name,InvisTVBinder)] -- Original tyvar names, in correspondence with
                              --   the implicitly and explicitly bound type variables
         , TcThetaType        -- Theta part
         , TcType )           -- Tau part
-- See Note [Checking partial type signatures]
tcHsPartialSigType :: UserTypeCtxt
-> LHsSigWcType GhcRn
-> TcM
     ([(Name, TcTyVar)], Maybe Type,
      [(Name, VarBndr TcTyVar Specificity)], [Type], Type)
tcHsPartialSigType UserTypeCtxt
ctxt LHsSigWcType GhcRn
sig_ty
  | HsWC { hswc_ext :: forall pass thing. HsWildCardBndrs pass thing -> XHsWC pass thing
hswc_ext  = XHsWC GhcRn (LHsSigType GhcRn)
sig_wcs, hswc_body :: forall pass thing. HsWildCardBndrs pass thing -> thing
hswc_body = LHsSigType GhcRn
sig_ty } <- LHsSigWcType GhcRn
sig_ty
  , L SrcSpanAnnA
_ (HsSig{sig_bndrs :: forall pass. HsSigType pass -> HsOuterSigTyVarBndrs pass
sig_bndrs = HsOuterSigTyVarBndrs GhcRn
hs_outer_bndrs, sig_body :: forall pass. HsSigType pass -> LHsType pass
sig_body = LHsType GhcRn
body_ty}) <- LHsSigType GhcRn
sig_ty
  , (Maybe (LHsContext GhcRn)
hs_ctxt, LHsType GhcRn
hs_tau) <- LHsType GhcRn -> (Maybe (LHsContext GhcRn), LHsType GhcRn)
forall (pass :: Pass).
LHsType (GhcPass pass)
-> (Maybe (LHsContext (GhcPass pass)), LHsType (GhcPass pass))
splitLHsQualTy LHsType GhcRn
body_ty
  = UserTypeCtxt
-> GenLocated SrcSpanAnnA (HsSigType GhcRn)
-> TcM
     ([(Name, TcTyVar)], Maybe Type,
      [(Name, VarBndr TcTyVar Specificity)], [Type], Type)
-> TcM
     ([(Name, TcTyVar)], Maybe Type,
      [(Name, VarBndr TcTyVar Specificity)], [Type], Type)
forall hs_ty a.
Outputable hs_ty =>
UserTypeCtxt -> LocatedA hs_ty -> TcM a -> TcM a
addSigCtxt UserTypeCtxt
ctxt LHsSigType GhcRn
GenLocated SrcSpanAnnA (HsSigType GhcRn)
sig_ty (TcM
   ([(Name, TcTyVar)], Maybe Type,
    [(Name, VarBndr TcTyVar Specificity)], [Type], Type)
 -> TcM
      ([(Name, TcTyVar)], Maybe Type,
       [(Name, VarBndr TcTyVar Specificity)], [Type], Type))
-> TcM
     ([(Name, TcTyVar)], Maybe Type,
      [(Name, VarBndr TcTyVar Specificity)], [Type], Type)
-> TcM
     ([(Name, TcTyVar)], Maybe Type,
      [(Name, VarBndr TcTyVar Specificity)], [Type], Type)
forall a b. (a -> b) -> a -> b
$
    do { TcTyMode
mode <- TypeOrKind -> HoleMode -> TcM TcTyMode
mkHoleMode TypeOrKind
TypeLevel HoleMode
HM_Sig
       ; (HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs, ([(Name, TcTyVar)]
wcs, Maybe Type
wcx, [Type]
theta, Type
tau))
            <- String
-> TcM
     (HsOuterTyVarBndrs Specificity GhcTc,
      ([(Name, TcTyVar)], Maybe Type, [Type], Type))
-> TcM
     (HsOuterTyVarBndrs Specificity GhcTc,
      ([(Name, TcTyVar)], Maybe Type, [Type], Type))
forall a. String -> TcM a -> TcM a
solveEqualities String
"tcHsPartialSigType" (TcM
   (HsOuterTyVarBndrs Specificity GhcTc,
    ([(Name, TcTyVar)], Maybe Type, [Type], Type))
 -> TcM
      (HsOuterTyVarBndrs Specificity GhcTc,
       ([(Name, TcTyVar)], Maybe Type, [Type], Type)))
-> TcM
     (HsOuterTyVarBndrs Specificity GhcTc,
      ([(Name, TcTyVar)], Maybe Type, [Type], Type))
-> TcM
     (HsOuterTyVarBndrs Specificity GhcTc,
      ([(Name, TcTyVar)], Maybe Type, [Type], Type))
forall a b. (a -> b) -> a -> b
$
               -- See Note [Failure in local type signatures]
               HsQTvsRn
-> ([(Name, TcTyVar)]
    -> TcM
         (HsOuterTyVarBndrs Specificity GhcTc,
          ([(Name, TcTyVar)], Maybe Type, [Type], Type)))
-> TcM
     (HsOuterTyVarBndrs Specificity GhcTc,
      ([(Name, TcTyVar)], Maybe Type, [Type], Type))
forall a. HsQTvsRn -> ([(Name, TcTyVar)] -> TcM a) -> TcM a
bindNamedWildCardBinders HsQTvsRn
XHsWC GhcRn (LHsSigType GhcRn)
sig_wcs             (([(Name, TcTyVar)]
  -> TcM
       (HsOuterTyVarBndrs Specificity GhcTc,
        ([(Name, TcTyVar)], Maybe Type, [Type], Type)))
 -> TcM
      (HsOuterTyVarBndrs Specificity GhcTc,
       ([(Name, TcTyVar)], Maybe Type, [Type], Type)))
-> ([(Name, TcTyVar)]
    -> TcM
         (HsOuterTyVarBndrs Specificity GhcTc,
          ([(Name, TcTyVar)], Maybe Type, [Type], Type)))
-> TcM
     (HsOuterTyVarBndrs Specificity GhcTc,
      ([(Name, TcTyVar)], Maybe Type, [Type], Type))
forall a b. (a -> b) -> a -> b
$ \ [(Name, TcTyVar)]
wcs ->
               TcTyMode
-> HsOuterSigTyVarBndrs GhcRn
-> TcM ([(Name, TcTyVar)], Maybe Type, [Type], Type)
-> TcM
     (HsOuterTyVarBndrs Specificity GhcTc,
      ([(Name, TcTyVar)], Maybe Type, [Type], Type))
forall a.
TcTyMode
-> HsOuterSigTyVarBndrs GhcRn
-> TcM a
-> TcM (HsOuterTyVarBndrs Specificity GhcTc, a)
bindOuterSigTKBndrs_Tv_M TcTyMode
mode HsOuterSigTyVarBndrs GhcRn
hs_outer_bndrs (TcM ([(Name, TcTyVar)], Maybe Type, [Type], Type)
 -> TcM
      (HsOuterTyVarBndrs Specificity GhcTc,
       ([(Name, TcTyVar)], Maybe Type, [Type], Type)))
-> TcM ([(Name, TcTyVar)], Maybe Type, [Type], Type)
-> TcM
     (HsOuterTyVarBndrs Specificity GhcTc,
      ([(Name, TcTyVar)], Maybe Type, [Type], Type))
forall a b. (a -> b) -> a -> b
$
               do {   -- Instantiate the type-class context; but if there
                      -- is an extra-constraints wildcard, just discard it here
                    ([Type]
theta, Maybe Type
wcx) <- TcTyMode -> Maybe (LHsContext GhcRn) -> TcM ([Type], Maybe Type)
tcPartialContext TcTyMode
mode Maybe (LHsContext GhcRn)
hs_ctxt

                  ; Type
ek <- TcM Type
newOpenTypeKind
                  ; Type
tau <- -- Don't do (addTypeCtxt hs_tau) here else we get
                           --   In the type <blah>
                           --   In the type signature: foo :: <blah>
                           TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
hs_tau Type
ek

                  ; ([(Name, TcTyVar)], Maybe Type, [Type], Type)
-> TcM ([(Name, TcTyVar)], Maybe Type, [Type], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([(Name, TcTyVar)]
wcs, Maybe Type
wcx, [Type]
theta, Type
tau) }

       ; String -> SDoc -> TcM ()
traceTc String
"tcHsPartialSigType 2" SDoc
forall doc. IsOutput doc => doc
empty
       ; HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs <- HsOuterTyVarBndrs Specificity GhcTc
-> TcM (HsOuterTyVarBndrs Specificity GhcTc)
forall flag.
HsOuterTyVarBndrs flag GhcTc -> TcM (HsOuterTyVarBndrs flag GhcTc)
scopedSortOuter HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs
       ; let outer_tv_bndrs :: [VarBndr TcTyVar Specificity]
outer_tv_bndrs = HsOuterTyVarBndrs Specificity GhcTc
-> [VarBndr TcTyVar Specificity]
outerTyVarBndrs HsOuterTyVarBndrs Specificity GhcTc
outer_bndrs
       ; String -> SDoc -> TcM ()
traceTc String
"tcHsPartialSigType 3" SDoc
forall doc. IsOutput doc => doc
empty

         -- No kind-generalization here:
       ; Type -> TcM ()
kindGeneralizeNone ([VarBndr TcTyVar Specificity] -> Type -> Type
mkInvisForAllTys [VarBndr TcTyVar Specificity]
outer_tv_bndrs (Type -> Type) -> Type -> Type
forall a b. (a -> b) -> a -> b
$
                             [Type] -> Type -> Type
HasDebugCallStack => [Type] -> Type -> Type
tcMkPhiTy [Type]
theta (Type -> Type) -> Type -> Type
forall a b. (a -> b) -> a -> b
$
                             Type
tau)

       -- Spit out the wildcards (including the extra-constraints one)
       -- as "hole" constraints, so that they'll be reported if necessary
       -- See Note [Extra-constraint holes in partial type signatures]
       ; ((Name, TcTyVar) -> TcM ()) -> [(Name, TcTyVar)] -> TcM ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Name, TcTyVar) -> TcM ()
emitNamedTypeHole [(Name, TcTyVar)]
wcs

         -- The "tau" from tcHsPartialSigType might very well have some foralls
         -- at the top, hidden behind a type synonym. Instantiate them! E.g.
         --    type T x = forall b. x -> b -> b
         --    f :: forall a. T (a,_)
         -- We must instantiate the `forall b` just as we do the `forall a`!
         -- Missing this led to #21667.
       ; ([(Name, VarBndr TcTyVar Specificity)]
tv_prs', [Type]
theta', Type
tau) <- Type -> TcM ([(Name, VarBndr TcTyVar Specificity)], [Type], Type)
tcInstTypeBndrs Type
tau

         -- We return a proper (Name,InvisTVBinder) environment, to be sure that
         -- we bring the right name into scope in the function body.
         -- Test case: partial-sigs/should_compile/LocalDefinitionBug
       ; let outer_bndr_names :: [Name]
             outer_bndr_names :: HsQTvsRn
outer_bndr_names = HsOuterSigTyVarBndrs GhcRn -> HsQTvsRn
forall flag. HsOuterTyVarBndrs flag GhcRn -> HsQTvsRn
hsOuterTyVarNames HsOuterSigTyVarBndrs GhcRn
hs_outer_bndrs
             tv_prs :: [(Name,InvisTVBinder)]
             tv_prs :: [(Name, VarBndr TcTyVar Specificity)]
tv_prs = HsQTvsRn
outer_bndr_names HsQTvsRn
-> [VarBndr TcTyVar Specificity]
-> [(Name, VarBndr TcTyVar Specificity)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [VarBndr TcTyVar Specificity]
outer_tv_bndrs

       -- Zonk, so that any nested foralls can "see" their occurrences
       -- See Note [Checking partial type signatures], and in particular
       -- Note [Levels for wildcards]
       ; ([(Name, VarBndr TcTyVar Specificity)]
tv_prs, [Type]
theta, Type
tau) <- ZonkM ([(Name, VarBndr TcTyVar Specificity)], [Type], Type)
-> TcM ([(Name, VarBndr TcTyVar Specificity)], [Type], Type)
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM ([(Name, VarBndr TcTyVar Specificity)], [Type], Type)
 -> TcM ([(Name, VarBndr TcTyVar Specificity)], [Type], Type))
-> ZonkM ([(Name, VarBndr TcTyVar Specificity)], [Type], Type)
-> TcM ([(Name, VarBndr TcTyVar Specificity)], [Type], Type)
forall a b. (a -> b) -> a -> b
$
         do { [(Name, VarBndr TcTyVar Specificity)]
tv_prs <- (VarBndr TcTyVar Specificity
 -> ZonkM (VarBndr TcTyVar Specificity))
-> [(Name, VarBndr TcTyVar Specificity)]
-> ZonkM [(Name, VarBndr TcTyVar Specificity)]
forall (m :: * -> *) (f :: * -> *) b c a.
(Applicative m, Traversable f) =>
(b -> m c) -> f (a, b) -> m (f (a, c))
mapSndM VarBndr TcTyVar Specificity -> ZonkM (VarBndr TcTyVar Specificity)
forall flag. VarBndr TcTyVar flag -> ZonkM (VarBndr TcTyVar flag)
zonkInvisTVBinder ([(Name, VarBndr TcTyVar Specificity)]
tv_prs [(Name, VarBndr TcTyVar Specificity)]
-> [(Name, VarBndr TcTyVar Specificity)]
-> [(Name, VarBndr TcTyVar Specificity)]
forall a. [a] -> [a] -> [a]
++ [(Name, VarBndr TcTyVar Specificity)]
tv_prs')
            ; [Type]
theta  <- (Type -> ZonkM Type) -> [Type] -> ZonkM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM    Type -> ZonkM Type
zonkTcType        ([Type]
theta [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
theta')
            ; Type
tau    <- Type -> ZonkM Type
zonkTcType                Type
tau
            ; ([(Name, VarBndr TcTyVar Specificity)], [Type], Type)
-> ZonkM ([(Name, VarBndr TcTyVar Specificity)], [Type], Type)
forall a. a -> ZonkM a
forall (m :: * -> *) a. Monad m => a -> m a
return ([(Name, VarBndr TcTyVar Specificity)]
tv_prs, [Type]
theta, Type
tau) }

      -- NB: checkValidType on the final inferred type will be
      --     done later by checkInferredPolyId.  We can't do it
      --     here because we don't have a complete type to check

       ; String -> SDoc -> TcM ()
traceTc String
"tcHsPartialSigType" ([(Name, VarBndr TcTyVar Specificity)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [(Name, VarBndr TcTyVar Specificity)]
tv_prs)
       ; ([(Name, TcTyVar)], Maybe Type,
 [(Name, VarBndr TcTyVar Specificity)], [Type], Type)
-> TcM
     ([(Name, TcTyVar)], Maybe Type,
      [(Name, VarBndr TcTyVar Specificity)], [Type], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([(Name, TcTyVar)]
wcs, Maybe Type
wcx, [(Name, VarBndr TcTyVar Specificity)]
tv_prs, [Type]
theta, Type
tau) }

tcPartialContext :: TcTyMode -> Maybe (LHsContext GhcRn) -> TcM (TcThetaType, Maybe TcType)
tcPartialContext :: TcTyMode -> Maybe (LHsContext GhcRn) -> TcM ([Type], Maybe Type)
tcPartialContext TcTyMode
_ Maybe (LHsContext GhcRn)
Nothing = ([Type], Maybe Type) -> TcM ([Type], Maybe Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([], Maybe Type
forall a. Maybe a
Nothing)
tcPartialContext TcTyMode
mode (Just (L SrcSpanAnnC
_ [GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_theta))
  | Just ([GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_theta1, GenLocated SrcSpanAnnA (HsType GhcRn)
hs_ctxt_last) <- [GenLocated SrcSpanAnnA (HsType GhcRn)]
-> Maybe
     ([GenLocated SrcSpanAnnA (HsType GhcRn)],
      GenLocated SrcSpanAnnA (HsType GhcRn))
forall a. [a] -> Maybe ([a], a)
snocView [GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_theta
  , L SrcSpanAnnA
wc_loc ty :: HsType GhcRn
ty@(HsWildCardTy XWildCardTy GhcRn
_) <- LHsType GhcRn -> LHsType GhcRn
forall (p :: Pass). LHsType (GhcPass p) -> LHsType (GhcPass p)
ignoreParens LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
hs_ctxt_last
  = do { Type
wc_tv_ty <- SrcSpanAnnA -> TcM Type -> TcM Type
forall ann a. SrcSpanAnn' ann -> TcRn a -> TcRn a
setSrcSpanA SrcSpanAnnA
wc_loc (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
                     IsExtraConstraint -> TcTyMode -> HsType GhcRn -> Type -> TcM Type
tcAnonWildCardOcc IsExtraConstraint
YesExtraConstraint TcTyMode
mode HsType GhcRn
ty Type
constraintKind
       ; [Type]
theta <- (GenLocated SrcSpanAnnA (HsType GhcRn) -> TcM Type)
-> [GenLocated SrcSpanAnnA (HsType GhcRn)] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (TcTyMode -> LHsType GhcRn -> TcM Type
tc_lhs_pred TcTyMode
mode) [GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_theta1
       ; ([Type], Maybe Type) -> TcM ([Type], Maybe Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([Type]
theta, Type -> Maybe Type
forall a. a -> Maybe a
Just Type
wc_tv_ty) }
  | Bool
otherwise
  = do { [Type]
theta <- (GenLocated SrcSpanAnnA (HsType GhcRn) -> TcM Type)
-> [GenLocated SrcSpanAnnA (HsType GhcRn)] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (TcTyMode -> LHsType GhcRn -> TcM Type
tc_lhs_pred TcTyMode
mode) [GenLocated SrcSpanAnnA (HsType GhcRn)]
hs_theta
       ; ([Type], Maybe Type) -> TcM ([Type], Maybe Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([Type]
theta, Maybe Type
forall a. Maybe a
Nothing) }

{- Note [Checking partial type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This Note is about tcHsPartialSigType.  See also
Note [Recipe for checking a signature]

When we have a partial signature like
   f :: forall a. a -> _
we do the following

* tcHsPartialSigType does not make quantified type (forall a. blah)
  and then instantiate it -- it makes no sense to instantiate a type
  with wildcards in it.  Rather, tcHsPartialSigType just returns the
  'a' and the 'blah' separately.

  Nor, for the same reason, do we push a level in tcHsPartialSigType.

* We instantiate 'a' to a unification variable, a TyVarTv, and /not/
  a skolem; hence the "_Tv" in bindExplicitTKBndrs_Tv.  Consider
    f :: forall a. a -> _
    g :: forall b. _ -> b
    f = g
    g = f
  They are typechecked as a recursive group, with monomorphic types,
  so 'a' and 'b' will get unified together.  Very like kind inference
  for mutually recursive data types (sans CUSKs or SAKS); see
  Note [Cloning for type variable binders]

* In GHC.Tc.Gen.Sig.tcUserSigType we return a PartialSig, which (unlike
  the companion CompleteSig) contains the original, as-yet-unchecked
  source-code LHsSigWcType

* Then, for f and g /separately/, we call tcInstSig, which in turn
  call tcHsPartialSig (defined near this Note).  It kind-checks the
  LHsSigWcType, creating fresh unification variables for each "_"
  wildcard.  It's important that the wildcards for f and g are distinct
  because they might get instantiated completely differently.  E.g.
     f,g :: forall a. a -> _
     f x = a
     g x = True
  It's really as if we'd written two distinct signatures.

* Nested foralls. See Note [Levels for wildcards]

* Just as for ordinary signatures, we must solve local equalities and
  zonk the type after kind-checking it, to ensure that all the nested
  forall binders can "see" their occurrences

  Just as for ordinary signatures, this zonk also gets any Refl casts
  out of the way of instantiation.  Example: #18008 had
       foo :: (forall a. (Show a => blah) |> Refl) -> _
  and that Refl cast messed things up.  See #18062.

Note [Levels for wildcards]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
     f :: forall b. (forall a. a -> _) -> b
We do /not/ allow the "_" to be instantiated to 'a'; although we do
(as before) allow it to be instantiated to the (top level) 'b'.
Why not?  Suppose
   f x = (x True, x 'c')

During typecking the RHS we must instantiate that (forall a. a -> _),
so we must know /precisely/ where all the a's are; they must not be
hidden under (possibly-not-yet-filled-in) unification variables!

We achieve this as follows:

- For /named/ wildcards such sas
     g :: forall b. (forall la. a -> _x) -> b
  there is no problem: we create them at the outer level (ie the
  ambient level of the signature itself), and push the level when we
  go inside a forall.  So now the unification variable for the "_x"
  can't unify with skolem 'a'.

- For /anonymous/ wildcards, such as 'f' above, we carry the ambient
  level of the signature to the hole in the TcLevel part of the
  mode_holes field of TcTyMode.  Then, in tcAnonWildCardOcc we us that
  level (and /not/ the level ambient at the occurrence of "_") to
  create the unification variable for the wildcard.  That is the sole
  purpose of the TcLevel in the mode_holes field: to transport the
  ambient level of the signature down to the anonymous wildcard
  occurrences.

Note [Extra-constraint holes in partial type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  f :: (_) => a -> a
  f x = ...

* The renamer leaves '_' untouched.

* Then, in tcHsPartialSigType, we make a new hole TcTyVar, in
  tcWildCardBinders.

* GHC.Tc.Gen.Bind.chooseInferredQuantifiers fills in that hole TcTyVar
  with the inferred constraints, e.g. (Eq a, Show a)

* GHC.Tc.Errors.mkHoleError finally reports the error.

An annoying difficulty happens if there are more than 64 inferred
constraints. Then we need to fill in the TcTyVar with (say) a 70-tuple.
Where do we find the TyCon?  For good reasons we only have constraint
tuples up to 62 (see Note [How tuples work] in GHC.Builtin.Types).  So how
can we make a 70-tuple?  This was the root cause of #14217.

It's incredibly tiresome, because we only need this type to fill
in the hole, to communicate to the error reporting machinery.  Nothing
more.  So I use a HACK:

* I make an /ordinary/ tuple of the constraints, in
  GHC.Tc.Gen.Bind.chooseInferredQuantifiers. This is ill-kinded because
  ordinary tuples can't contain constraints, but it works fine. And for
  ordinary tuples we don't have the same limit as for constraint
  tuples (which need selectors and an associated class).

* Because it is ill-kinded (unifying something of kind Constraint with
  something of kind Type), it should trip an assert in writeMetaTyVarRef.

Result works fine, but it may eventually bite us.

See also Note [Do not simplify ConstraintHoles] in GHC.Tc.Solver for
information about how these are printed.

************************************************************************
*                                                                      *
      Pattern signatures (i.e signatures that occur in patterns)
*                                                                      *
********************************************************************* -}

tcHsPatSigType :: UserTypeCtxt
               -> HoleMode -- HM_Sig when in a SigPat, HM_TyAppPat when in a ConPat checking type applications.
               -> HsPatSigType GhcRn          -- The type signature
               -> ContextKind                -- What kind is expected
               -> TcM ( [(Name, TcTyVar)]     -- Wildcards
                      , [(Name, TcTyVar)]     -- The new bit of type environment, binding
                                              -- the scoped type variables
                      , TcType)       -- The type
-- Used for type-checking type signatures in
-- (a) patterns           e.g  f (x::Int) = e
-- (b) RULE forall bndrs  e.g. forall (x::Int). f x = x
-- See Note [Pattern signature binders and scoping] in GHC.Hs.Type
--
-- This may emit constraints
-- See Note [Recipe for checking a signature]
tcHsPatSigType :: UserTypeCtxt
-> HoleMode
-> HsPatSigType GhcRn
-> ContextKind
-> TcM ([(Name, TcTyVar)], [(Name, TcTyVar)], Type)
tcHsPatSigType UserTypeCtxt
ctxt HoleMode
hole_mode
  (HsPS { hsps_ext :: forall pass. HsPatSigType pass -> XHsPS pass
hsps_ext  = HsPSRn { hsps_nwcs :: HsPSRn -> HsQTvsRn
hsps_nwcs = HsQTvsRn
sig_wcs, hsps_imp_tvs :: HsPSRn -> HsQTvsRn
hsps_imp_tvs = HsQTvsRn
sig_ns }
        , hsps_body :: forall pass. HsPatSigType pass -> LHsType pass
hsps_body = LHsType GhcRn
hs_ty })
  ContextKind
ctxt_kind
  = UserTypeCtxt
-> GenLocated SrcSpanAnnA (HsType GhcRn)
-> TcM ([(Name, TcTyVar)], [(Name, TcTyVar)], Type)
-> TcM ([(Name, TcTyVar)], [(Name, TcTyVar)], Type)
forall hs_ty a.
Outputable hs_ty =>
UserTypeCtxt -> LocatedA hs_ty -> TcM a -> TcM a
addSigCtxt UserTypeCtxt
ctxt LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
hs_ty (TcM ([(Name, TcTyVar)], [(Name, TcTyVar)], Type)
 -> TcM ([(Name, TcTyVar)], [(Name, TcTyVar)], Type))
-> TcM ([(Name, TcTyVar)], [(Name, TcTyVar)], Type)
-> TcM ([(Name, TcTyVar)], [(Name, TcTyVar)], Type)
forall a b. (a -> b) -> a -> b
$
    do { [(Name, TcTyVar)]
sig_tkv_prs <- (Name -> IOEnv (Env TcGblEnv TcLclEnv) (Name, TcTyVar))
-> HsQTvsRn -> IOEnv (Env TcGblEnv TcLclEnv) [(Name, TcTyVar)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM Name -> IOEnv (Env TcGblEnv TcLclEnv) (Name, TcTyVar)
new_implicit_tv HsQTvsRn
sig_ns
       ; TcTyMode
mode <- TypeOrKind -> HoleMode -> TcM TcTyMode
mkHoleMode TypeOrKind
TypeLevel HoleMode
hole_mode
       ; ([(Name, TcTyVar)]
wcs, Type
sig_ty)
            <- LHsType GhcRn
-> TcM ([(Name, TcTyVar)], Type) -> TcM ([(Name, TcTyVar)], Type)
forall a. LHsType GhcRn -> TcM a -> TcM a
addTypeCtxt LHsType GhcRn
hs_ty                     (TcM ([(Name, TcTyVar)], Type) -> TcM ([(Name, TcTyVar)], Type))
-> TcM ([(Name, TcTyVar)], Type) -> TcM ([(Name, TcTyVar)], Type)
forall a b. (a -> b) -> a -> b
$
               String
-> TcM ([(Name, TcTyVar)], Type) -> TcM ([(Name, TcTyVar)], Type)
forall a. String -> TcM a -> TcM a
solveEqualities String
"tcHsPatSigType" (TcM ([(Name, TcTyVar)], Type) -> TcM ([(Name, TcTyVar)], Type))
-> TcM ([(Name, TcTyVar)], Type) -> TcM ([(Name, TcTyVar)], Type)
forall a b. (a -> b) -> a -> b
$
                 -- See Note [Failure in local type signatures]
                 -- and c.f #16033
               HsQTvsRn
-> ([(Name, TcTyVar)] -> TcM ([(Name, TcTyVar)], Type))
-> TcM ([(Name, TcTyVar)], Type)
forall a. HsQTvsRn -> ([(Name, TcTyVar)] -> TcM a) -> TcM a
bindNamedWildCardBinders HsQTvsRn
sig_wcs (([(Name, TcTyVar)] -> TcM ([(Name, TcTyVar)], Type))
 -> TcM ([(Name, TcTyVar)], Type))
-> ([(Name, TcTyVar)] -> TcM ([(Name, TcTyVar)], Type))
-> TcM ([(Name, TcTyVar)], Type)
forall a b. (a -> b) -> a -> b
$ \ [(Name, TcTyVar)]
wcs ->
               [(Name, TcTyVar)]
-> TcM ([(Name, TcTyVar)], Type) -> TcM ([(Name, TcTyVar)], Type)
forall r. [(Name, TcTyVar)] -> TcM r -> TcM r
tcExtendNameTyVarEnv [(Name, TcTyVar)]
sig_tkv_prs (TcM ([(Name, TcTyVar)], Type) -> TcM ([(Name, TcTyVar)], Type))
-> TcM ([(Name, TcTyVar)], Type) -> TcM ([(Name, TcTyVar)], Type)
forall a b. (a -> b) -> a -> b
$
               do { Type
ek     <- ContextKind -> TcM Type
newExpectedKind ContextKind
ctxt_kind
                  ; Type
sig_ty <- TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
hs_ty Type
ek
                  ; ([(Name, TcTyVar)], Type) -> TcM ([(Name, TcTyVar)], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([(Name, TcTyVar)]
wcs, Type
sig_ty) }

        ; ((Name, TcTyVar) -> TcM ()) -> [(Name, TcTyVar)] -> TcM ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Name, TcTyVar) -> TcM ()
emitNamedTypeHole [(Name, TcTyVar)]
wcs

          -- sig_ty might have tyvars that are at a higher TcLevel (if hs_ty
          -- contains a forall). Promote these.
          -- Ex: f (x :: forall a. Proxy a -> ()) = ... x ...
          -- When we instantiate x, we have to compare the kind of the argument
          -- to a's kind, which will be a metavariable.
          -- kindGeneralizeNone does this:
        ; Type -> TcM ()
kindGeneralizeNone Type
sig_ty
        ; Type
sig_ty <- ZonkM Type -> TcM Type
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM Type -> TcM Type) -> ZonkM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ Type -> ZonkM Type
zonkTcType Type
sig_ty
        ; UserTypeCtxt -> Type -> TcM ()
checkValidType UserTypeCtxt
ctxt Type
sig_ty

        ; String -> SDoc -> TcM ()
traceTc String
"tcHsPatSigType" ([(Name, TcTyVar)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [(Name, TcTyVar)]
sig_tkv_prs)
        ; ([(Name, TcTyVar)], [(Name, TcTyVar)], Type)
-> TcM ([(Name, TcTyVar)], [(Name, TcTyVar)], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([(Name, TcTyVar)]
wcs, [(Name, TcTyVar)]
sig_tkv_prs, Type
sig_ty) }
  where
    new_implicit_tv :: Name -> IOEnv (Env TcGblEnv TcLclEnv) (Name, TcTyVar)
new_implicit_tv Name
name
      = do { Type
kind <- TcM Type
newMetaKindVar
           ; TcTyVar
tv   <- case UserTypeCtxt
ctxt of
                       RuleSigCtxt FastString
rname Name
_  -> do
                        SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo (FastString -> SkolemInfoAnon
RuleSkol FastString
rname)
                        SkolemInfo -> Name -> Type -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newSkolemTyVar SkolemInfo
skol_info Name
name Type
kind
                       UserTypeCtxt
_              -> Name -> Type -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newPatSigTyVar Name
name Type
kind
                       -- See Note [Typechecking pattern signature binders]
             -- NB: tv's Name may be fresh (in the case of newPatSigTyVar)
           ; (Name, TcTyVar) -> IOEnv (Env TcGblEnv TcLclEnv) (Name, TcTyVar)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Name
name, TcTyVar
tv) }

{- Note [Typechecking pattern signature binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See also Note [Type variables in the type environment] in GHC.Tc.Utils.
Consider

  data T where
    MkT :: forall a. a -> (a -> Int) -> T

  f :: T -> ...
  f (MkT x (f :: b -> c)) = <blah>

Here
 * The pattern (MkT p1 p2) creates a *skolem* type variable 'a_sk',
   It must be a skolem so that it retains its identity, and
   GHC.Tc.Errors.getSkolemInfo can thereby find the binding site for the skolem.

 * The type signature pattern (f :: b -> c) makes fresh meta-tyvars
   beta and gamma (TauTvs), and binds "b" :-> beta, "c" :-> gamma in the
   environment

 * Then unification makes beta := a_sk, gamma := Int
   That's why we must make beta and gamma a MetaTv,
   not a SkolemTv, so that it can unify to a_sk (or Int, respectively).

 * Finally, in '<blah>' we have the envt "b" :-> beta, "c" :-> gamma,
   so we return the pairs ("b" :-> beta, "c" :-> gamma) from tcHsPatSigType,

Another example (#13881):
   fl :: forall (l :: [a]). Sing l -> Sing l
   fl (SNil :: Sing (l :: [y])) = SNil
When we reach the pattern signature, 'l' is in scope from the
outer 'forall':
   "a" :-> a_sk :: *
   "l" :-> l_sk :: [a_sk]
We make up a fresh meta-TauTv, y_sig, for 'y', and kind-check
the pattern signature
   Sing (l :: [y])
That unifies y_sig := a_sk.  We return from tcHsPatSigType with
the pair ("y" :-> y_sig).

For RULE binders, though, things are a bit different (yuk).
  RULE "foo" forall (x::a) (y::[a]).  f x y = ...
Here this really is the binding site of the type variable so we'd like
to use a skolem, so that we get a complaint if we unify two of them
together.  Hence the new_implicit_tv function in tcHsPatSigType.


************************************************************************
*                                                                      *
        Checking kinds
*                                                                      *
************************************************************************

-}

unifyKinds :: [LHsType GhcRn] -> [(TcType, TcKind)] -> TcM ([TcType], TcKind)
unifyKinds :: [LHsType GhcRn] -> [(Type, Type)] -> TcM ([Type], Type)
unifyKinds [LHsType GhcRn]
rn_tys [(Type, Type)]
act_kinds
  = do { Type
kind <- TcM Type
newMetaKindVar
       ; let check :: GenLocated SrcSpanAnnA (HsType GhcRn) -> (Type, Type) -> TcM Type
check GenLocated SrcSpanAnnA (HsType GhcRn)
rn_ty (Type
ty, Type
act_kind)
               = HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind (GenLocated SrcSpanAnnA (HsType GhcRn) -> HsType GhcRn
forall l e. GenLocated l e -> e
unLoc GenLocated SrcSpanAnnA (HsType GhcRn)
rn_ty) Type
ty Type
act_kind Type
kind
       ; [Type]
tys' <- (GenLocated SrcSpanAnnA (HsType GhcRn) -> (Type, Type) -> TcM Type)
-> [GenLocated SrcSpanAnnA (HsType GhcRn)]
-> [(Type, Type)]
-> TcM [Type]
forall (m :: * -> *) a b c.
Applicative m =>
(a -> b -> m c) -> [a] -> [b] -> m [c]
zipWithM GenLocated SrcSpanAnnA (HsType GhcRn) -> (Type, Type) -> TcM Type
check [LHsType GhcRn]
[GenLocated SrcSpanAnnA (HsType GhcRn)]
rn_tys [(Type, Type)]
act_kinds
       ; ([Type], Type) -> TcM ([Type], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([Type]
tys', Type
kind) }

{-
************************************************************************
*                                                                      *
        Sort checking kinds
*                                                                      *
************************************************************************

tcLHsKindSig converts a user-written kind to an internal, sort-checked kind.
It does sort checking and desugaring at the same time, in one single pass.
-}

tcLHsKindSig :: UserTypeCtxt -> LHsKind GhcRn -> TcM Kind
tcLHsKindSig :: UserTypeCtxt -> LHsType GhcRn -> TcM Type
tcLHsKindSig UserTypeCtxt
ctxt LHsType GhcRn
hs_kind
  = TcTyMode -> UserTypeCtxt -> LHsType GhcRn -> TcM Type
tc_lhs_kind_sig TcTyMode
kindLevelMode UserTypeCtxt
ctxt LHsType GhcRn
hs_kind

tc_lhs_kind_sig :: TcTyMode -> UserTypeCtxt -> LHsKind GhcRn -> TcM Kind
tc_lhs_kind_sig :: TcTyMode -> UserTypeCtxt -> LHsType GhcRn -> TcM Type
tc_lhs_kind_sig TcTyMode
mode UserTypeCtxt
ctxt LHsType GhcRn
hs_kind
-- See  Note [Recipe for checking a signature] in GHC.Tc.Gen.HsType
-- Result is zonked
  = do { Type
kind <- SDoc -> TcM Type -> TcM Type
forall a. SDoc -> TcM a -> TcM a
addErrCtxt (String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"In the kind" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc -> SDoc
quotes (GenLocated SrcSpanAnnA (HsType GhcRn) -> SDoc
forall a. Outputable a => a -> SDoc
ppr LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
hs_kind)) (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
                 String -> TcM Type -> TcM Type
forall a. String -> TcM a -> TcM a
solveEqualities String
"tcLHsKindSig" (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
                 TcTyMode -> LHsType GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsType GhcRn
hs_kind Type
liftedTypeKind
       ; String -> SDoc -> TcM ()
traceTc String
"tcLHsKindSig" (GenLocated SrcSpanAnnA (HsType GhcRn) -> SDoc
forall a. Outputable a => a -> SDoc
ppr LHsType GhcRn
GenLocated SrcSpanAnnA (HsType GhcRn)
hs_kind SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
kind)
       -- No generalization:
       ; Type -> TcM ()
kindGeneralizeNone Type
kind
       ; Type
kind <- ZonkM Type -> TcM Type
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM Type -> TcM Type) -> ZonkM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ Type -> ZonkM Type
zonkTcType Type
kind
         -- This zonk is very important in the case of higher rank kinds
         -- E.g. #13879    f :: forall (p :: forall z (y::z). <blah>).
         --                          <more blah>
         --      When instantiating p's kind at occurrences of p in <more blah>
         --      it's crucial that the kind we instantiate is fully zonked,
         --      else we may fail to substitute properly

       ; UserTypeCtxt -> Type -> TcM ()
checkValidType UserTypeCtxt
ctxt Type
kind
       ; String -> SDoc -> TcM ()
traceTc String
"tcLHsKindSig2" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
kind)
       ; Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Type
kind }

promotionErr :: Name -> PromotionErr -> TcM a
promotionErr :: forall a. Name -> PromotionErr -> TcM a
promotionErr Name
name PromotionErr
err
  = TcRnMessage -> TcM a
forall a. TcRnMessage -> TcM a
failWithTc (TcRnMessage -> TcM a) -> TcRnMessage -> TcM a
forall a b. (a -> b) -> a -> b
$ Name -> PromotionErr -> TcRnMessage
TcRnUnpromotableThing Name
name PromotionErr
err

{-
************************************************************************
*                                                                      *
          Error messages and such
*                                                                      *
************************************************************************
-}


-- | Make an appropriate message for an error in a function argument.
-- Used for both expressions and types.
funAppCtxt :: (Outputable fun, Outputable arg) => fun -> arg -> Int -> SDoc
funAppCtxt :: forall fun arg.
(Outputable fun, Outputable arg) =>
fun -> arg -> Int -> SDoc
funAppCtxt fun
fun arg
arg Int
arg_no
  = SDoc -> Int -> SDoc -> SDoc
hang ([SDoc] -> SDoc
forall doc. IsLine doc => [doc] -> doc
hsep [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"In the", Int -> SDoc
speakNth Int
arg_no, String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"argument of",
                    SDoc -> SDoc
quotes (fun -> SDoc
forall a. Outputable a => a -> SDoc
ppr fun
fun) SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> String -> SDoc
forall doc. IsLine doc => String -> doc
text String
", namely"])
       Int
2 (SDoc -> SDoc
quotes (arg -> SDoc
forall a. Outputable a => a -> SDoc
ppr arg
arg))

-- | Add a "In the data declaration for T" or some such.
addTyConFlavCtxt :: Name -> TyConFlavour tc -> TcM a -> TcM a
addTyConFlavCtxt :: forall tc a. Name -> TyConFlavour tc -> TcM a -> TcM a
addTyConFlavCtxt Name
name TyConFlavour tc
flav
  = SDoc -> TcM a -> TcM a
forall a. SDoc -> TcM a -> TcM a
addErrCtxt (SDoc -> TcM a -> TcM a) -> SDoc -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
forall doc. IsLine doc => [doc] -> doc
hsep [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"In the", TyConFlavour tc -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyConFlavour tc
flav
                      , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"declaration for", SDoc -> SDoc
quotes (Name -> SDoc
forall a. Outputable a => a -> SDoc
ppr Name
name) ]