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

-}

{-# LANGUAGE CPP, TupleSections, MultiWayIf, RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}

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

-- | 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,
        ContextKind(..),

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

          -- tyvars
        zonkAndScopedSort,

        -- Kind-checking types
        -- No kind generalisation, no checkValidType
        InitialKindStrategy(..),
        SAKS_or_CUSK(..),
        kcDeclHeader,
        tcNamedWildCardBinders,
        tcHsLiftedType,   tcHsOpenType,
        tcHsLiftedTypeNC, tcHsOpenTypeNC,
        tcInferLHsTypeKind, tcInferLHsType, tcInferLHsTypeUnsaturated,
        tcCheckLHsType,
        tcHsMbContext, tcHsContext, tcLHsPredType,
        failIfEmitsConstraints,
        solveEqualities, -- useful re-export

        kindGeneralizeAll, kindGeneralizeSome, kindGeneralizeNone,

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

        -- Multiplicity
        tcMult,

        -- Pattern type signatures
        tcHsPatSigType,

        -- Error messages
        funAppCtxt, addTyConFlavCtxt
   ) where

#include "HsVersions.h"

import GHC.Prelude

import GHC.Hs
import GHC.Tc.Utils.Monad
import GHC.Tc.Types.Origin
import GHC.Core.Predicate
import GHC.Tc.Types.Constraint
import GHC.Tc.Utils.Env
import GHC.Tc.Utils.Instantiate( tcInstInvisibleTyBinders )
import GHC.Tc.Utils.TcMType
import GHC.Tc.Validity
import GHC.Tc.Utils.Unify
import GHC.IfaceToCore
import GHC.Tc.Solver
import GHC.Tc.Utils.Zonk
import GHC.Core.TyCo.Rep
import GHC.Core.TyCo.Ppr
import GHC.Tc.Errors      ( reportAllUnsolved )
import GHC.Tc.Utils.TcType
import GHC.Tc.Utils.Instantiate ( tcInstInvisibleTyBindersN, tcInstInvisibleTyBinder )
import GHC.Core.Type
import GHC.Builtin.Types.Prim
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.Name.Set
import GHC.Types.Var.Env
import GHC.Builtin.Types
import GHC.Types.Basic
import GHC.Types.SrcLoc
import GHC.Settings.Constants ( mAX_CTUPLE_SIZE )
import GHC.Utils.Error( MsgDoc )
import GHC.Types.Unique
import GHC.Types.Unique.FM
import GHC.Types.Unique.Set
import GHC.Utils.Misc
import GHC.Types.Unique.Supply
import GHC.Utils.Outputable
import GHC.Data.FastString
import GHC.Builtin.Names hiding ( wildCardName )
import GHC.Driver.Session
import qualified GHC.LanguageExtensions as LangExt
import GHC.Parser.Annotation

import GHC.Data.Maybe
import GHC.Data.Bag( unitBag )
import Data.List ( find )
import Control.Monad

{-
        ----------------------------
                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]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Checking a user-written signature requires several steps:

 1. Generate constraints.
 2. Solve constraints.
 3. Promote tyvars and/or kind-generalize.
 4. Zonk.
 5. Check validity.

There may be some surprises in here:

Step 2 is necessary for two reasons: most signatures also bring
implicitly quantified variables into scope, and solving is necessary
to get these in the right order (see Note [Keeping implicitly
quantified variables in order]). Additionally, solving is necessary in
order to kind-generalize correctly: otherwise, we do not know which
metavariables are left unsolved.

Step 3 is done by a call to candidateQTyVarsOfType, followed by a call to
kindGeneralize{All,Some,None}. Here, we have to deal with the fact that
metatyvars generated in the type may 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

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

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.

After promoting/generalizing, we need to zonk again because both
promoting and generalizing fill in metavariables.

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 (WantedTvInv) of Note [TcLevel and untouchable type variables]
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
matavariable with level 2 would violate the (WantedTvInv) invariant of
Note [TcLevel and untouchable type variables]. So, instead of kind-generalizing,
we promote the metavariable to level 1. This is all done in kindGeneralizeNone.

-}

funsSigCtxt :: [Located Name] -> UserTypeCtxt
-- Returns FunSigCtxt, with no redundant-context-reporting,
-- form a list of located names
funsSigCtxt :: [Located Name] -> UserTypeCtxt
funsSigCtxt (L SrcSpan
_ Name
name1 : [Located Name]
_) = Name -> Bool -> UserTypeCtxt
FunSigCtxt Name
name1 Bool
False
funsSigCtxt []              = String -> UserTypeCtxt
forall a. String -> a
panic String
"funSigCtxt"

addSigCtxt :: UserTypeCtxt -> LHsType GhcRn -> TcM a -> TcM a
addSigCtxt :: forall a. UserTypeCtxt -> LHsKind GhcRn -> TcM a -> TcM a
addSigCtxt UserTypeCtxt
ctxt LHsKind GhcRn
hs_ty TcM a
thing_inside
  = SrcSpan -> TcM a -> TcM a
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan (LHsKind GhcRn -> SrcSpan
forall l e. GenLocated l e -> l
getLoc LHsKind GhcRn
hs_ty) (TcM a -> TcM a) -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$
    MsgDoc -> TcM a -> TcM a
forall a. MsgDoc -> TcM a -> TcM a
addErrCtxt (UserTypeCtxt -> LHsKind GhcRn -> MsgDoc
pprSigCtxt UserTypeCtxt
ctxt LHsKind GhcRn
hs_ty) (TcM a -> TcM a) -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$
    TcM a
thing_inside

pprSigCtxt :: UserTypeCtxt -> LHsType GhcRn -> 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 :: UserTypeCtxt -> LHsKind GhcRn -> MsgDoc
pprSigCtxt UserTypeCtxt
ctxt LHsKind GhcRn
hs_ty
  | Just Name
n <- UserTypeCtxt -> Maybe Name
isSigMaybe UserTypeCtxt
ctxt
  = MsgDoc -> Arity -> MsgDoc -> MsgDoc
hang (String -> MsgDoc
text String
"In the type signature:")
       Arity
2 (Name -> MsgDoc
forall a. OutputableBndr a => a -> MsgDoc
pprPrefixOcc Name
n MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc
dcolon MsgDoc -> MsgDoc -> MsgDoc
<+> LHsKind GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsKind GhcRn
hs_ty)

  | Bool
otherwise
  = MsgDoc -> Arity -> MsgDoc -> MsgDoc
hang (String -> MsgDoc
text String
"In" MsgDoc -> MsgDoc -> MsgDoc
<+> UserTypeCtxt -> MsgDoc
pprUserTypeCtxt UserTypeCtxt
ctxt MsgDoc -> MsgDoc -> MsgDoc
<> MsgDoc
colon)
       Arity
2 (LHsKind GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsKind GhcRn
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 :: SkolemInfo -> [Located 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_hs_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 block unification (Note [Equalities with incompatible kinds] in
-- TcCanonical) 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 :: SkolemInfo -> [Located Name] -> LHsSigType GhcRn -> TcM ()
kcClassSigType SkolemInfo
skol_info [Located Name]
names (HsIB { hsib_ext :: forall pass thing. HsImplicitBndrs pass thing -> XHsIB pass thing
hsib_ext  = XHsIB GhcRn (LHsKind GhcRn)
sig_vars
                                     , hsib_body :: forall pass thing. HsImplicitBndrs pass thing -> thing
hsib_body = LHsKind GhcRn
hs_ty })
  = UserTypeCtxt -> LHsKind GhcRn -> TcM () -> TcM ()
forall a. UserTypeCtxt -> LHsKind GhcRn -> TcM a -> TcM a
addSigCtxt ([Located Name] -> UserTypeCtxt
funsSigCtxt [Located Name]
names) LHsKind GhcRn
hs_ty (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
    do { (TcLevel
tc_lvl, (WantedConstraints
wanted, ([TyVar]
spec_tkvs, Type
_)))
           <- TcM (WantedConstraints, ([TyVar], Type))
-> TcM (TcLevel, (WantedConstraints, ([TyVar], Type)))
forall a. TcM a -> TcM (TcLevel, a)
pushTcLevelM                           (TcM (WantedConstraints, ([TyVar], Type))
 -> TcM (TcLevel, (WantedConstraints, ([TyVar], Type))))
-> TcM (WantedConstraints, ([TyVar], Type))
-> TcM (TcLevel, (WantedConstraints, ([TyVar], Type)))
forall a b. (a -> b) -> a -> b
$
              String
-> TcM ([TyVar], Type) -> TcM (WantedConstraints, ([TyVar], Type))
forall a. String -> TcM a -> TcM (WantedConstraints, a)
solveLocalEqualitiesX String
"kcClassSigType" (TcM ([TyVar], Type) -> TcM (WantedConstraints, ([TyVar], Type)))
-> TcM ([TyVar], Type) -> TcM (WantedConstraints, ([TyVar], Type))
forall a b. (a -> b) -> a -> b
$
              HsQTvsRn -> TcM Type -> TcM ([TyVar], Type)
forall a. HsQTvsRn -> TcM a -> TcM ([TyVar], a)
bindImplicitTKBndrs_Skol HsQTvsRn
XHsIB GhcRn (LHsKind GhcRn)
sig_vars      (TcM Type -> TcM ([TyVar], Type))
-> TcM Type -> TcM ([TyVar], Type)
forall a b. (a -> b) -> a -> b
$
              LHsKind GhcRn -> Type -> TcM Type
tcLHsType LHsKind GhcRn
hs_ty Type
liftedTypeKind

       ; SkolemInfo -> [TyVar] -> TcLevel -> WantedConstraints -> TcM ()
emitResidualTvConstraint SkolemInfo
skol_info [TyVar]
spec_tkvs TcLevel
tc_lvl WantedConstraints
wanted }

tcClassSigType :: SkolemInfo -> [Located Name] -> LHsSigType GhcRn -> TcM Type
-- Does not do validity checking
tcClassSigType :: SkolemInfo -> [Located Name] -> LHsSigType GhcRn -> TcM Type
tcClassSigType SkolemInfo
skol_info [Located Name]
names LHsSigType GhcRn
sig_ty
  = UserTypeCtxt -> LHsKind GhcRn -> TcM Type -> TcM Type
forall a. UserTypeCtxt -> LHsKind GhcRn -> TcM a -> TcM a
addSigCtxt ([Located Name] -> UserTypeCtxt
funsSigCtxt [Located Name]
names) (LHsSigType GhcRn -> LHsKind GhcRn
forall (p :: Pass). LHsSigType (GhcPass p) -> LHsType (GhcPass p)
hsSigType LHsSigType GhcRn
sig_ty) (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
    do { (Implication
implic, Type
ty) <- SkolemInfo
-> LHsSigType GhcRn -> ContextKind -> TcM (Implication, Type)
tc_hs_sig_type SkolemInfo
skol_info LHsSigType GhcRn
sig_ty (Type -> ContextKind
TheKind Type
liftedTypeKind)
       ; Implication -> TcM ()
emitImplication Implication
implic
       ; Type -> TcM Type
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.

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 -> LHsKind GhcRn -> TcM Type -> TcM Type
forall a. UserTypeCtxt -> LHsKind GhcRn -> TcM a -> TcM a
addSigCtxt UserTypeCtxt
ctxt (LHsSigType GhcRn -> LHsKind GhcRn
forall (p :: Pass). LHsSigType (GhcPass p) -> LHsType (GhcPass p)
hsSigType LHsSigType GhcRn
sig_ty) (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
    do { String -> MsgDoc -> TcM ()
traceTc String
"tcHsSigType {" (LHsSigType GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsSigType GhcRn
sig_ty)

          -- Generalise here: see Note [Kind generalisation]
       ; (Implication
implic, Type
ty) <- SkolemInfo
-> LHsSigType GhcRn -> ContextKind -> TcM (Implication, Type)
tc_hs_sig_type SkolemInfo
skol_info LHsSigType GhcRn
sig_ty  (UserTypeCtxt -> ContextKind
expectedKindInCtxt UserTypeCtxt
ctxt)

       -- Spit out the implication (and perhaps fail fast)
       -- See Note [Failure in local type signatures] in GHC.Tc.Solver
       ; WantedConstraints -> TcM ()
emitFlatConstraints (Bag Implication -> WantedConstraints
mkImplicWC (Implication -> Bag Implication
forall a. a -> Bag a
unitBag Implication
implic))

       ; Type
ty <- Type -> TcM Type
zonkTcType Type
ty
       ; UserTypeCtxt -> Type -> TcM ()
checkValidType UserTypeCtxt
ctxt Type
ty
       ; String -> MsgDoc -> TcM ()
traceTc String
"end tcHsSigType }" (Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
ty)
       ; Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return Type
ty }
  where
    skol_info :: SkolemInfo
skol_info = UserTypeCtxt -> SkolemInfo
SigTypeSkol UserTypeCtxt
ctxt

tc_hs_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_hs_sig_type :: SkolemInfo
-> LHsSigType GhcRn -> ContextKind -> TcM (Implication, Type)
tc_hs_sig_type SkolemInfo
skol_info LHsSigType GhcRn
hs_sig_type ContextKind
ctxt_kind
  | HsIB { hsib_ext :: forall pass thing. HsImplicitBndrs pass thing -> XHsIB pass thing
hsib_ext = XHsIB GhcRn (LHsKind GhcRn)
sig_vars, hsib_body :: forall pass thing. HsImplicitBndrs pass thing -> thing
hsib_body = LHsKind GhcRn
hs_ty } <- LHsSigType GhcRn
hs_sig_type
  = do { (TcLevel
tc_lvl, (WantedConstraints
wanted, ([TyVar]
spec_tkvs, Type
ty)))
              <- TcM (WantedConstraints, ([TyVar], Type))
-> TcM (TcLevel, (WantedConstraints, ([TyVar], Type)))
forall a. TcM a -> TcM (TcLevel, a)
pushTcLevelM                           (TcM (WantedConstraints, ([TyVar], Type))
 -> TcM (TcLevel, (WantedConstraints, ([TyVar], Type))))
-> TcM (WantedConstraints, ([TyVar], Type))
-> TcM (TcLevel, (WantedConstraints, ([TyVar], Type)))
forall a b. (a -> b) -> a -> b
$
                 String
-> TcM ([TyVar], Type) -> TcM (WantedConstraints, ([TyVar], Type))
forall a. String -> TcM a -> TcM (WantedConstraints, a)
solveLocalEqualitiesX String
"tc_hs_sig_type" (TcM ([TyVar], Type) -> TcM (WantedConstraints, ([TyVar], Type)))
-> TcM ([TyVar], Type) -> TcM (WantedConstraints, ([TyVar], Type))
forall a b. (a -> b) -> a -> b
$
                 -- See Note [Failure in local type signatures]
                 HsQTvsRn -> TcM Type -> TcM ([TyVar], Type)
forall a. HsQTvsRn -> TcM a -> TcM ([TyVar], a)
bindImplicitTKBndrs_Skol HsQTvsRn
XHsIB GhcRn (LHsKind GhcRn)
sig_vars      (TcM Type -> TcM ([TyVar], Type))
-> TcM Type -> TcM ([TyVar], Type)
forall a b. (a -> b) -> a -> b
$
                 do { Type
kind <- ContextKind -> TcM Type
newExpectedKind ContextKind
ctxt_kind
                    ; LHsKind GhcRn -> Type -> TcM Type
tcLHsType LHsKind GhcRn
hs_ty Type
kind }
       -- Any remaining variables (unsolved in the solveLocalEqualities)
       -- should be in the global tyvars, and therefore won't be quantified

       ; [TyVar]
spec_tkvs <- [TyVar] -> TcM [TyVar]
zonkAndScopedSort [TyVar]
spec_tkvs
       ; let ty1 :: Type
ty1 = [TyVar] -> Type -> Type
mkSpecForAllTys [TyVar]
spec_tkvs Type
ty

       -- 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.)
       ; TyVarSet
constrained <- TyVarSet -> TcM TyVarSet
zonkTyCoVarsAndFV (WantedConstraints -> TyVarSet
tyCoVarsOfWC WantedConstraints
wanted)
       ; let should_gen :: TyVar -> Bool
should_gen = Bool -> Bool
not (Bool -> Bool) -> (TyVar -> Bool) -> TyVar -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TyVar -> TyVarSet -> Bool
`elemVarSet` TyVarSet
constrained)

       ; [TyVar]
kvs <- (TyVar -> Bool) -> Type -> TcM [TyVar]
kindGeneralizeSome TyVar -> Bool
should_gen Type
ty1

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

       ; (Implication, Type) -> TcM (Implication, Type)
forall (m :: * -> *) a. Monad m => a -> m a
return (Implication
implic, [TyVar] -> Type -> Type
mkInfForAllTys [TyVar]
kvs Type
ty1) }

{- 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 becuase of a nested skolem-escape.

That will show up as an un-solvable constraint in the implication
returned by buildTvImplication in tc_hs_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.emitFlatConstraints (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_hs_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 emitFlatConstraints (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 SrcSpan
_ StandaloneKindSig GhcRn
kisig) = case StandaloneKindSig GhcRn
kisig of
  StandaloneKindSig XStandaloneKindSig GhcRn
_ (L SrcSpan
_ IdP GhcRn
name) LHsSigType GhcRn
ksig ->
    let ctxt :: UserTypeCtxt
ctxt = Name -> UserTypeCtxt
StandaloneKindSigCtxt Name
IdP GhcRn
name in
    UserTypeCtxt
-> LHsKind GhcRn -> TcM (Name, Type) -> TcM (Name, Type)
forall a. UserTypeCtxt -> LHsKind GhcRn -> TcM a -> TcM a
addSigCtxt UserTypeCtxt
ctxt (LHsSigType GhcRn -> LHsKind GhcRn
forall (p :: Pass). LHsSigType (GhcPass p) -> LHsType (GhcPass p)
hsSigType LHsSigType GhcRn
ksig) (TcM (Name, Type) -> TcM (Name, Type))
-> TcM (Name, Type) -> TcM (Name, Type)
forall a b. (a -> b) -> a -> b
$
    do { let mode :: TcTyMode
mode = TypeOrKind -> TcTyMode
mkMode TypeOrKind
KindLevel
       ; Type
kind <- TcTyMode -> LHsSigType GhcRn -> ContextKind -> TcM Type
tc_top_lhs_type TcTyMode
mode LHsSigType GhcRn
ksig (UserTypeCtxt -> ContextKind
expectedKindInCtxt UserTypeCtxt
ctxt)
       ; UserTypeCtxt -> Type -> TcM ()
checkValidType UserTypeCtxt
ctxt Type
kind
       ; (Name, Type) -> TcM (Name, Type)
forall (m :: * -> *) a. Monad m => a -> m a
return (Name
IdP GhcRn
name, Type
kind) }


tcTopLHsType :: LHsSigType GhcRn -> ContextKind -> TcM Type
tcTopLHsType :: LHsSigType GhcRn -> ContextKind -> TcM Type
tcTopLHsType LHsSigType GhcRn
hs_ty ContextKind
ctxt_kind
  = TcTyMode -> LHsSigType GhcRn -> ContextKind -> TcM Type
tc_top_lhs_type (TypeOrKind -> TcTyMode
mkMode TypeOrKind
TypeLevel) LHsSigType GhcRn
hs_ty ContextKind
ctxt_kind

tc_top_lhs_type :: TcTyMode -> LHsSigType GhcRn -> ContextKind -> TcM Type
-- tcTopLHsType is used for kind-checking top-level HsType 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 :: TcTyMode -> LHsSigType GhcRn -> ContextKind -> TcM Type
tc_top_lhs_type TcTyMode
mode LHsSigType GhcRn
hs_sig_type ContextKind
ctxt_kind
  | HsIB { hsib_ext :: forall pass thing. HsImplicitBndrs pass thing -> XHsIB pass thing
hsib_ext = XHsIB GhcRn (LHsKind GhcRn)
sig_vars, hsib_body :: forall pass thing. HsImplicitBndrs pass thing -> thing
hsib_body = LHsKind GhcRn
hs_ty } <- LHsSigType GhcRn
hs_sig_type
  = do { String -> MsgDoc -> TcM ()
traceTc String
"tcTopLHsType {" (LHsKind GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsKind GhcRn
hs_ty)
       ; ([TyVar]
spec_tkvs, Type
ty)
              <- TcM ([TyVar], Type) -> TcM ([TyVar], Type)
forall a. TcM a -> TcM a
pushTcLevelM_                     (TcM ([TyVar], Type) -> TcM ([TyVar], Type))
-> TcM ([TyVar], Type) -> TcM ([TyVar], Type)
forall a b. (a -> b) -> a -> b
$
                 TcM ([TyVar], Type) -> TcM ([TyVar], Type)
forall a. TcM a -> TcM a
solveEqualities                   (TcM ([TyVar], Type) -> TcM ([TyVar], Type))
-> TcM ([TyVar], Type) -> TcM ([TyVar], Type)
forall a b. (a -> b) -> a -> b
$
                 HsQTvsRn -> TcM Type -> TcM ([TyVar], Type)
forall a. HsQTvsRn -> TcM a -> TcM ([TyVar], a)
bindImplicitTKBndrs_Skol HsQTvsRn
XHsIB GhcRn (LHsKind GhcRn)
sig_vars (TcM Type -> TcM ([TyVar], Type))
-> TcM Type -> TcM ([TyVar], Type)
forall a b. (a -> b) -> a -> b
$
                 do { Type
kind <- ContextKind -> TcM Type
newExpectedKind ContextKind
ctxt_kind
                    ; TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind GhcRn
hs_ty Type
kind }

       ; [TyVar]
spec_tkvs <- [TyVar] -> TcM [TyVar]
zonkAndScopedSort [TyVar]
spec_tkvs
       ; let ty1 :: Type
ty1 = [TyVar] -> Type -> Type
mkSpecForAllTys [TyVar]
spec_tkvs Type
ty
       ; [TyVar]
kvs <- Type -> TcM [TyVar]
kindGeneralizeAll Type
ty1  -- "All" because it's a top-level type
       ; Type
final_ty <- Type -> TcM Type
zonkTcTypeToType ([TyVar] -> Type -> Type
mkInfForAllTys [TyVar]
kvs Type
ty1)
       ; String -> MsgDoc -> TcM ()
traceTc String
"End tcTopLHsType }" ([MsgDoc] -> MsgDoc
vcat [LHsKind GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsKind GhcRn
hs_ty, Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
final_ty])
       ; Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return Type
final_ty}

-----------------
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 ([TyVar], Class, [Type], [Type])
tcHsDeriv LHsSigType GhcRn
hs_ty
  = do { Type
ty <- TcM Type -> TcM Type
forall a. TcM a -> TcM a
checkNoErrs (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$  -- Avoid redundant error report
                              -- with "illegal deriving", below
               LHsSigType GhcRn -> ContextKind -> TcM Type
tcTopLHsType LHsSigType GhcRn
hs_ty ContextKind
AnyKind
       ; let ([TyVar]
tvs, Type
pred)    = Type -> ([TyVar], Type)
splitForAllTys Type
ty
             ([Scaled Type]
kind_args, Type
_) = Type -> ([Scaled Type], Type)
splitFunTys (HasDebugCallStack => Type -> Type
Type -> Type
tcTypeKind Type
pred)
       ; case Type -> Maybe (Class, [Type])
getClassPredTys_maybe Type
pred of
           Just (Class
cls, [Type]
tys) -> ([TyVar], Class, [Type], [Type])
-> TcM ([TyVar], Class, [Type], [Type])
forall (m :: * -> *) a. Monad m => a -> m a
return ([TyVar]
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 -> MsgDoc -> TcM ([TyVar], Class, [Type], [Type])
forall a. MsgDoc -> TcM a
failWithTc (String -> MsgDoc
text String
"Illegal deriving item" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
quotes (LHsSigType GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr 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), [TyVar])
     -- ^ The typechecked deriving strategy and the tyvars that it binds
     -- (if using 'ViaStrategy').
tcDerivStrategy :: Maybe (LDerivStrategy GhcRn)
-> TcM (Maybe (LDerivStrategy GhcTc), [TyVar])
tcDerivStrategy Maybe (LDerivStrategy GhcRn)
mb_lds
  = case Maybe (LDerivStrategy GhcRn)
mb_lds of
      Maybe (LDerivStrategy GhcRn)
Nothing -> Maybe (LDerivStrategy GhcTc)
-> TcM (Maybe (LDerivStrategy GhcTc), [TyVar])
forall ds. ds -> TcM (ds, [TyVar])
boring_case Maybe (LDerivStrategy GhcTc)
forall a. Maybe a
Nothing
      Just (L SrcSpan
loc DerivStrategy GhcRn
ds) ->
        SrcSpan
-> TcM (Maybe (LDerivStrategy GhcTc), [TyVar])
-> TcM (Maybe (LDerivStrategy GhcTc), [TyVar])
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan SrcSpan
loc (TcM (Maybe (LDerivStrategy GhcTc), [TyVar])
 -> TcM (Maybe (LDerivStrategy GhcTc), [TyVar]))
-> TcM (Maybe (LDerivStrategy GhcTc), [TyVar])
-> TcM (Maybe (LDerivStrategy GhcTc), [TyVar])
forall a b. (a -> b) -> a -> b
$ do
          (DerivStrategy GhcTc
ds', [TyVar]
tvs) <- DerivStrategy GhcRn -> TcM (DerivStrategy GhcTc, [TyVar])
tc_deriv_strategy DerivStrategy GhcRn
ds
          (Maybe (LDerivStrategy GhcTc), [TyVar])
-> TcM (Maybe (LDerivStrategy GhcTc), [TyVar])
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LDerivStrategy GhcTc -> Maybe (LDerivStrategy GhcTc)
forall a. a -> Maybe a
Just (SrcSpan -> DerivStrategy GhcTc -> LDerivStrategy GhcTc
forall l e. l -> e -> GenLocated l e
L SrcSpan
loc DerivStrategy GhcTc
ds'), [TyVar]
tvs)
  where
    tc_deriv_strategy :: DerivStrategy GhcRn
                      -> TcM (DerivStrategy GhcTc, [TyVar])
    tc_deriv_strategy :: DerivStrategy GhcRn -> TcM (DerivStrategy GhcTc, [TyVar])
tc_deriv_strategy DerivStrategy GhcRn
StockStrategy    = DerivStrategy GhcTc -> TcM (DerivStrategy GhcTc, [TyVar])
forall ds. ds -> TcM (ds, [TyVar])
boring_case DerivStrategy GhcTc
forall pass. DerivStrategy pass
StockStrategy
    tc_deriv_strategy DerivStrategy GhcRn
AnyclassStrategy = DerivStrategy GhcTc -> TcM (DerivStrategy GhcTc, [TyVar])
forall ds. ds -> TcM (ds, [TyVar])
boring_case DerivStrategy GhcTc
forall pass. DerivStrategy pass
AnyclassStrategy
    tc_deriv_strategy DerivStrategy GhcRn
NewtypeStrategy  = DerivStrategy GhcTc -> TcM (DerivStrategy GhcTc, [TyVar])
forall ds. ds -> TcM (ds, [TyVar])
boring_case DerivStrategy GhcTc
forall pass. DerivStrategy pass
NewtypeStrategy
    tc_deriv_strategy (ViaStrategy XViaStrategy GhcRn
ty) = do
      Type
ty' <- TcM Type -> TcM Type
forall a. TcM a -> TcM a
checkNoErrs (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ LHsSigType GhcRn -> ContextKind -> TcM Type
tcTopLHsType XViaStrategy GhcRn
LHsSigType GhcRn
ty ContextKind
AnyKind
      let ([TyVar]
via_tvs, Type
via_pred) = Type -> ([TyVar], Type)
splitForAllTys Type
ty'
      (DerivStrategy GhcTc, [TyVar])
-> TcM (DerivStrategy GhcTc, [TyVar])
forall (f :: * -> *) a. Applicative f => a -> f a
pure (XViaStrategy GhcTc -> DerivStrategy GhcTc
forall pass. XViaStrategy pass -> DerivStrategy pass
ViaStrategy Type
XViaStrategy GhcTc
via_pred, [TyVar]
via_tvs)

    boring_case :: ds -> TcM (ds, [TyVar])
    boring_case :: forall ds. ds -> TcM (ds, [TyVar])
boring_case ds
ds = (ds, [TyVar]) -> IOEnv (Env TcGblEnv TcLclEnv) (ds, [TyVar])
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 (LHsKind GhcRn -> SrcSpan
forall l e. GenLocated l e -> l
getLoc (LHsSigType GhcRn -> LHsKind GhcRn
forall (p :: Pass). LHsSigType (GhcPass p) -> LHsType (GhcPass p)
hsSigType LHsSigType GhcRn
hs_inst_ty)) (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
    do { -- Fail eagerly if tcTopLHsType fails.  We are at top level so
         -- these constraints will never be solved later. And failing
         -- eagerly avoids follow-on errors when checkValidInstance
         -- sees an unsolved coercion hole
         Type
inst_ty <- TcM Type -> TcM Type
forall a. TcM a -> TcM a
checkNoErrs (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
                    LHsSigType GhcRn -> ContextKind -> TcM Type
tcTopLHsType LHsSigType GhcRn
hs_inst_ty (Type -> ContextKind
TheKind Type
constraintKind)
       ; UserTypeCtxt -> LHsSigType GhcRn -> Type -> TcM ()
checkValidInstance UserTypeCtxt
user_ctxt LHsSigType GhcRn
hs_inst_ty Type
inst_ty
       ; Type -> TcM Type
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 (LHsKind GhcRn)
sig_wcs, hswc_body :: forall pass thing. HsWildCardBndrs pass thing -> thing
hswc_body = LHsKind 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 <- LHsKind GhcRn -> TcM Type -> TcM Type
forall a. LHsKind GhcRn -> TcM a -> TcM a
addTypeCtxt LHsKind 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
solveLocalEqualities 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, TyVar)] -> TcM Type) -> TcM Type
forall a. HsQTvsRn -> ([(Name, TyVar)] -> TcM a) -> TcM a
tcNamedWildCardBinders HsQTvsRn
XHsWC GhcRn (LHsKind GhcRn)
sig_wcs (([(Name, TyVar)] -> TcM Type) -> TcM Type)
-> ([(Name, TyVar)] -> TcM Type) -> TcM Type
forall a b. (a -> b) -> a -> b
$ \ [(Name, TyVar)]
_ ->
               TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind 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 <- Type -> TcM Type
zonkTcType Type
ty
       ; UserTypeCtxt -> Type -> TcM ()
checkValidType UserTypeCtxt
TypeAppCtxt Type
ty
       ; Type -> TcM Type
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 -> [LHsTypeArg GhcRn] -> TcM (Type, Type)
tcFamTyPats TyCon
fam_tc [LHsTypeArg GhcRn]
hs_pats
  = do { String -> MsgDoc -> TcM ()
traceTc String
"tcFamTyPats {" (MsgDoc -> TcM ()) -> MsgDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [MsgDoc] -> MsgDoc
vcat [ TyCon -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TyCon
fam_tc, String -> MsgDoc
text String
"arity:" MsgDoc -> MsgDoc -> MsgDoc
<+> Arity -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Arity
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
-> LHsKind GhcRn -> Type -> [LHsTypeArg GhcRn] -> TcM (Type, Type)
tcInferTyApps TcTyMode
mode LHsKind GhcRn
lhs_fun Type
fun_ty [LHsTypeArg GhcRn]
hs_pats

       -- Hack alert: see Note [tcFamTyPats: zonking the result kind]
       ; Type
res_kind <- Type -> TcM Type
zonkTcType Type
res_kind

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

       ; (Type, Type) -> TcM (Type, Type)
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 :: Arity
fam_arity = TyCon -> Arity
tyConArity TyCon
fam_tc
    lhs_fun :: LHsKind GhcRn
lhs_fun   = HsType GhcRn -> LHsKind GhcRn
forall e. e -> Located e
noLoc (XTyVar GhcRn
-> PromotionFlag -> GenLocated SrcSpan (IdP GhcRn) -> HsType GhcRn
forall pass.
XTyVar pass -> PromotionFlag -> Located (IdP pass) -> HsType pass
HsTyVar NoExtField
XTyVar GhcRn
noExtField PromotionFlag
NotPromoted (Name -> Located Name
forall e. e -> Located e
noLoc 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 :: LHsKind GhcRn -> TcM Type
tcHsOpenType   LHsKind GhcRn
hs_ty = LHsKind GhcRn -> TcM Type -> TcM Type
forall a. LHsKind GhcRn -> TcM a -> TcM a
addTypeCtxt LHsKind GhcRn
hs_ty (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ LHsKind GhcRn -> TcM Type
tcHsOpenTypeNC LHsKind GhcRn
hs_ty
tcHsLiftedType :: LHsKind GhcRn -> TcM Type
tcHsLiftedType LHsKind GhcRn
hs_ty = LHsKind GhcRn -> TcM Type -> TcM Type
forall a. LHsKind GhcRn -> TcM a -> TcM a
addTypeCtxt LHsKind GhcRn
hs_ty (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ LHsKind GhcRn -> TcM Type
tcHsLiftedTypeNC LHsKind GhcRn
hs_ty

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

-- Like tcHsType, but takes an expected kind
tcCheckLHsType :: LHsType GhcRn -> ContextKind -> TcM TcType
tcCheckLHsType :: LHsKind GhcRn -> ContextKind -> TcM Type
tcCheckLHsType LHsKind GhcRn
hs_ty ContextKind
exp_kind
  = LHsKind GhcRn -> TcM Type -> TcM Type
forall a. LHsKind GhcRn -> TcM a -> TcM a
addTypeCtxt LHsKind 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
       ; LHsKind GhcRn -> Type -> TcM Type
tcLHsType LHsKind GhcRn
hs_ty Type
ek }

tcInferLHsType :: LHsType GhcRn -> TcM TcType
tcInferLHsType :: LHsKind GhcRn -> TcM Type
tcInferLHsType LHsKind GhcRn
hs_ty
  = do { (Type
ty,Type
_kind) <- LHsKind GhcRn -> TcM (Type, Type)
tcInferLHsTypeKind LHsKind GhcRn
hs_ty
       ; Type -> TcM Type
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 :: LHsKind GhcRn -> TcM (Type, Type)
tcInferLHsTypeKind lhs_ty :: LHsKind GhcRn
lhs_ty@(L SrcSpan
loc HsType GhcRn
hs_ty)
  = LHsKind GhcRn -> TcM (Type, Type) -> TcM (Type, Type)
forall a. LHsKind GhcRn -> TcM a -> TcM a
addTypeCtxt LHsKind GhcRn
lhs_ty (TcM (Type, Type) -> TcM (Type, Type))
-> TcM (Type, Type) -> TcM (Type, Type)
forall a b. (a -> b) -> a -> b
$
    SrcSpan -> TcM (Type, Type) -> TcM (Type, Type)
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan SrcSpan
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 (TypeOrKind -> TcTyMode
mkMode TypeOrKind
TypeLevel) 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 :: LHsKind GhcRn -> TcM (Type, Type)
tcInferLHsTypeUnsaturated LHsKind GhcRn
hs_ty
  = LHsKind GhcRn -> TcM (Type, Type) -> TcM (Type, Type)
forall a. LHsKind GhcRn -> TcM a -> TcM a
addTypeCtxt LHsKind 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 (LHsKind GhcRn, [LHsTypeArg GhcRn])
splitHsAppTys (LHsKind GhcRn -> HsType GhcRn
forall l e. GenLocated l e -> e
unLoc LHsKind GhcRn
hs_ty) of
           Just (LHsKind GhcRn
hs_fun_ty, [LHsTypeArg GhcRn]
hs_args)
              -> do { (Type
fun_ty, Type
_ki) <- TcTyMode -> LHsKind GhcRn -> TcM (Type, Type)
tcInferTyAppHead TcTyMode
mode LHsKind GhcRn
hs_fun_ty
                    ; TcTyMode
-> LHsKind GhcRn -> Type -> [LHsTypeArg GhcRn] -> TcM (Type, Type)
tcInferTyApps_nosat TcTyMode
mode LHsKind GhcRn
hs_fun_ty Type
fun_ty [LHsTypeArg GhcRn]
hs_args }
                      -- Notice the 'nosat'; do not instantiate trailing
                      -- invisible arguments of a type family.
                      -- See Note [Dealing with :kind]
           Maybe (LHsKind GhcRn, [LHsTypeArg GhcRn])
Nothing -> TcTyMode -> LHsKind GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode LHsKind 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 (TypeOrKind -> TcTyMode
mkMode TypeOrKind
TypeLevel) 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

             -- See Note [Levels for wildcards]
             -- Nothing <=> no wildcards expected
             , TcTyMode -> Maybe (TcLevel, HoleMode)
mode_holes :: 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 @(_ -> _)

mkMode :: TypeOrKind -> TcTyMode
mkMode :: TypeOrKind -> TcTyMode
mkMode TypeOrKind
tyki = TcTyMode :: TypeOrKind -> Maybe (TcLevel, HoleMode) -> TcTyMode
TcTyMode { mode_tyki :: TypeOrKind
mode_tyki = TypeOrKind
tyki, mode_holes :: Maybe (TcLevel, HoleMode)
mode_holes = Maybe (TcLevel, HoleMode)
forall a. Maybe a
Nothing }

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 (m :: * -> *) a. Monad m => a -> m a
return (TcTyMode :: TypeOrKind -> Maybe (TcLevel, HoleMode) -> TcTyMode
TcTyMode { mode_tyki :: TypeOrKind
mode_tyki  = TypeOrKind
tyki
                          , mode_holes :: Maybe (TcLevel, HoleMode)
mode_holes = (TcLevel, HoleMode) -> Maybe (TcLevel, HoleMode)
forall a. a -> Maybe a
Just (TcLevel
lvl,HoleMode
hm) }) }

kindLevel :: TcTyMode -> TcTyMode
kindLevel :: TcTyMode -> TcTyMode
kindLevel TcTyMode
mode = TcTyMode
mode { mode_tyki :: TypeOrKind
mode_tyki = TypeOrKind
KindLevel }

instance Outputable HoleMode where
  ppr :: HoleMode -> MsgDoc
ppr HoleMode
HM_Sig     = String -> MsgDoc
text String
"HM_Sig"
  ppr HoleMode
HM_FamPat  = String -> MsgDoc
text String
"HM_FamPat"
  ppr HoleMode
HM_VTA     = String -> MsgDoc
text String
"HM_VTA"

instance Outputable TcTyMode where
  ppr :: TcTyMode -> MsgDoc
ppr (TcTyMode { mode_tyki :: TcTyMode -> TypeOrKind
mode_tyki = TypeOrKind
tyki, mode_holes :: TcTyMode -> Maybe (TcLevel, HoleMode)
mode_holes = Maybe (TcLevel, HoleMode)
hm })
    = String -> MsgDoc
text String
"TcTyMode" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
braces ([MsgDoc] -> MsgDoc
sep [ TypeOrKind -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TypeOrKind
tyki MsgDoc -> MsgDoc -> MsgDoc
<> MsgDoc
comma
                                      , Maybe (TcLevel, HoleMode) -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Maybe (TcLevel, HoleMode)
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 -> LHsKind GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode (L SrcSpan
span HsType GhcRn
ty)
  = SrcSpan -> TcM (Type, Type) -> TcM (Type, Type)
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan SrcSpan
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
_ LHsKind GhcRn
t)
  = TcTyMode -> LHsKind GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode LHsKind GhcRn
t

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

tc_infer_hs_type TcTyMode
mode (HsKindSig XKindSig GhcRn
_ LHsKind GhcRn
ty LHsKind GhcRn
sig)
  = do { let mode' :: TcTyMode
mode' = TcTyMode
mode { mode_tyki :: TypeOrKind
mode_tyki = TypeOrKind
KindLevel }
       ; Type
sig' <- TcTyMode -> UserTypeCtxt -> LHsKind GhcRn -> TcM Type
tc_lhs_kind_sig TcTyMode
mode' UserTypeCtxt
KindSigCtxt LHsKind 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 -> MsgDoc -> TcM ()
traceTc String
"tc_infer_hs_type:sig" (LHsKind GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsKind GhcRn
ty MsgDoc -> MsgDoc -> MsgDoc
$$ Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
sig')
       ; Type
ty' <- TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind GhcRn
ty Type
sig'
       ; (Type, Type) -> TcM (Type, Type)
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 XSpliceTy GhcRn
_ (HsSpliced XSpliced GhcRn
_ ThModFinalizers
_ (HsSplicedTy HsType GhcRn
ty)))
  = TcTyMode -> HsType GhcRn -> TcM (Type, Type)
tc_infer_hs_type TcTyMode
mode HsType GhcRn
ty

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

-- See Note [Typechecking NHsCoreTys]
tc_infer_hs_type TcTyMode
_ (XHsType (NHsCoreTy Type
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, TyVar)]
subst_prs = [ (Name -> Unique
forall a. Uniquable a => a -> Unique
getUnique Name
nm, TyVar
tv)
                       | ATyVar Name
nm TyVar
tv <- NameEnv TcTyThing -> [TcTyThing]
forall a. NameEnv a -> [a]
nameEnvElts (TcLclEnv -> NameEnv TcTyThing
tcl_env TcLclEnv
env) ]
           subst :: TCvSubst
subst = InScopeSet -> TvSubstEnv -> TCvSubst
mkTvSubst
                     (TyVarSet -> InScopeSet
mkInScopeSet (TyVarSet -> InScopeSet) -> TyVarSet -> InScopeSet
forall a b. (a -> b) -> a -> b
$ [TyVar] -> TyVarSet
mkVarSet ([TyVar] -> TyVarSet) -> [TyVar] -> TyVarSet
forall a b. (a -> b) -> a -> b
$ ((Unique, TyVar) -> TyVar) -> [(Unique, TyVar)] -> [TyVar]
forall a b. (a -> b) -> [a] -> [b]
map (Unique, TyVar) -> TyVar
forall a b. (a, b) -> b
snd [(Unique, TyVar)]
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, TyVar) -> (Unique, Type))
-> [(Unique, TyVar)] -> [(Unique, Type)]
forall a b. (a -> b) -> [a] -> [b]
map ((TyVar -> Type) -> (Unique, TyVar) -> (Unique, Type)
forall a b c. (a -> b) -> (c, a) -> (c, b)
liftSnd TyVar -> Type
mkTyVarTy) [(Unique, TyVar)]
subst_prs)
           ty' :: Type
ty' = HasCallStack => TCvSubst -> Type -> Type
TCvSubst -> Type -> Type
substTy TCvSubst
subst Type
ty
       (Type, Type) -> TcM (Type, Type)
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
ty', HasDebugCallStack => Type -> Type
Type -> Type
tcTypeKind Type
ty')

tc_infer_hs_type TcTyMode
_ (HsExplicitListTy XExplicitListTy GhcRn
_ PromotionFlag
_ [LHsKind GhcRn]
tys)
  | [LHsKind GhcRn] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [LHsKind GhcRn]
tys  -- this is so that we can use visible kind application with '[]
              -- e.g ... '[] @Bool
  = (Type, Type) -> TcM (Type, Type)
forall (m :: * -> *) a. Monad m => a -> m a
return (TyCon -> Type
mkTyConTy TyCon
promotedNilDataCon,
            [TyVar] -> Type -> Type
mkSpecForAllTys [TyVar
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 (m :: * -> *) a. Monad m => a -> m a
return (Type
ty', Type
kv) }

{-
Note [Typechecking NHsCoreTys]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NHsCoreTy 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 NHsCoreTy,
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 NHsCoreTy (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 NHsCoreTy
                  @(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
NHsCoreTys 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 NHsCoreTy 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 :: LHsKind GhcRn -> Type -> TcM Type
tcLHsType LHsKind GhcRn
hs_ty Type
exp_kind
  = TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type (TypeOrKind -> TcTyMode
mkMode TypeOrKind
TypeLevel) LHsKind GhcRn
hs_ty Type
exp_kind

tc_lhs_type :: TcTyMode -> LHsType GhcRn -> TcKind -> TcM TcType
tc_lhs_type :: TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode (L SrcSpan
span HsType GhcRn
ty) Type
exp_kind
  = SrcSpan -> TcM Type -> TcM Type
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan SrcSpan
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
_ LHsKind GhcRn
ty)   Type
exp_kind = TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind GhcRn
ty Type
exp_kind
tc_hs_type TcTyMode
mode (HsDocTy XDocTy GhcRn
_ LHsKind GhcRn
ty LHsDocString
_) Type
exp_kind = TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind GhcRn
ty Type
exp_kind
tc_hs_type TcTyMode
_ ty :: HsType GhcRn
ty@(HsBangTy XBangTy GhcRn
_ HsSrcBang
bang LHsKind 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)
    = do { let bangError :: String -> TcM Type
bangError String
err = MsgDoc -> TcM Type
forall a. MsgDoc -> TcM a
failWith (MsgDoc -> TcM Type) -> MsgDoc -> TcM Type
forall a b. (a -> b) -> a -> b
$
                 String -> MsgDoc
text String
"Unexpected" MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text String
err MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text String
"annotation:" MsgDoc -> MsgDoc -> MsgDoc
<+> HsType GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsType GhcRn
ty MsgDoc -> MsgDoc -> MsgDoc
$$
                 String -> MsgDoc
text String
err MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text String
"annotation cannot appear nested inside a type"
         ; case HsSrcBang
bang of
             HsSrcBang SourceText
_ SrcUnpackedness
SrcUnpack SrcStrictness
_           -> String -> TcM Type
bangError String
"UNPACK"
             HsSrcBang SourceText
_ SrcUnpackedness
SrcNoUnpack SrcStrictness
_         -> String -> TcM Type
bangError String
"NOUNPACK"
             HsSrcBang SourceText
_ SrcUnpackedness
NoSrcUnpack SrcStrictness
SrcLazy   -> String -> TcM Type
bangError String
"laziness"
             HsSrcBang SourceText
_ SrcUnpackedness
_ SrcStrictness
_                   -> String -> TcM Type
bangError String
"strictness" }
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
    = MsgDoc -> TcM Type
forall a. MsgDoc -> TcM a
failWithTc (String -> MsgDoc
text String
"Record syntax is illegal here:" MsgDoc -> MsgDoc -> MsgDoc
<+> HsType GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr 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 XSpliceTy GhcRn
_ (HsSpliced XSpliced GhcRn
_ ThModFinalizers
mod_finalizers (HsSplicedTy HsType GhcRn
ty)))
           Type
exp_kind
  = do ThModFinalizers -> TcM ()
addModFinalizersWithLclEnv ThModFinalizers
mod_finalizers
       TcTyMode -> HsType GhcRn -> Type -> TcM Type
tc_hs_type TcTyMode
mode HsType GhcRn
ty Type
exp_kind

-- This should never happen; type splices are expanded by the renamer
tc_hs_type TcTyMode
_ ty :: HsType GhcRn
ty@(HsSpliceTy {}) Type
_exp_kind
  = MsgDoc -> TcM Type
forall a. MsgDoc -> TcM a
failWithTc (String -> MsgDoc
text String
"Unexpected type splice:" MsgDoc -> MsgDoc -> MsgDoc
<+> HsType GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsType GhcRn
ty)

---------- Functions and applications
tc_hs_type TcTyMode
mode ty :: HsType GhcRn
ty@(HsFunTy XFunTy GhcRn
_ HsArrow GhcRn
mult LHsKind GhcRn
ty1 LHsKind GhcRn
ty2) Type
exp_kind
  | TcTyMode -> TypeOrKind
mode_tyki TcTyMode
mode TypeOrKind -> TypeOrKind -> Bool
forall a. Eq a => a -> a -> Bool
== TypeOrKind
KindLevel Bool -> Bool -> Bool
&& Bool -> Bool
not (HsArrow GhcRn -> Bool
isUnrestricted HsArrow GhcRn
mult)
    = MsgDoc -> TcM Type
forall a. MsgDoc -> TcM a
failWithTc (String -> MsgDoc
text String
"Linear arrows disallowed in kinds:" MsgDoc -> MsgDoc -> MsgDoc
<+> HsType GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsType GhcRn
ty)
  | Bool
otherwise
    = TcTyMode
-> HsArrow GhcRn
-> LHsKind GhcRn
-> LHsKind GhcRn
-> Type
-> TcM Type
tc_fun_type TcTyMode
mode HsArrow GhcRn
mult LHsKind GhcRn
ty1 LHsKind GhcRn
ty2 Type
exp_kind

tc_hs_type TcTyMode
mode (HsOpTy XOpTy GhcRn
_ LHsKind GhcRn
ty1 (L SrcSpan
_ IdP GhcRn
op) LHsKind GhcRn
ty2) Type
exp_kind
  | Name
IdP GhcRn
op Name -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
funTyConKey
  = TcTyMode
-> HsArrow GhcRn
-> LHsKind GhcRn
-> LHsKind GhcRn
-> Type
-> TcM Type
tc_fun_type TcTyMode
mode (IsUnicodeSyntax -> HsArrow GhcRn
forall pass. IsUnicodeSyntax -> HsArrow pass
HsUnrestrictedArrow IsUnicodeSyntax
NormalSyntax) LHsKind GhcRn
ty1 LHsKind GhcRn
ty2 Type
exp_kind

--------- Foralls
tc_hs_type TcTyMode
mode forall :: HsType GhcRn
forall@(HsForAllTy { hst_tele :: forall pass. HsType pass -> HsForAllTelescope pass
hst_tele = HsForAllTelescope GhcRn
tele, hst_body :: forall pass. HsType pass -> LHsType pass
hst_body = LHsKind GhcRn
ty }) Type
exp_kind
  = do { (TcLevel
tclvl, WantedConstraints
wanted, (Either [TcReqTVBinder] [VarBndr TyVar Specificity]
tv_bndrs, Type
ty'))
            <- TcM (Either [TcReqTVBinder] [VarBndr TyVar Specificity], Type)
-> TcM
     (TcLevel, WantedConstraints,
      (Either [TcReqTVBinder] [VarBndr TyVar Specificity], Type))
forall a. TcM a -> TcM (TcLevel, WantedConstraints, a)
pushLevelAndCaptureConstraints      (TcM (Either [TcReqTVBinder] [VarBndr TyVar Specificity], Type)
 -> TcM
      (TcLevel, WantedConstraints,
       (Either [TcReqTVBinder] [VarBndr TyVar Specificity], Type)))
-> TcM (Either [TcReqTVBinder] [VarBndr TyVar Specificity], Type)
-> TcM
     (TcLevel, WantedConstraints,
      (Either [TcReqTVBinder] [VarBndr TyVar Specificity], Type))
forall a b. (a -> b) -> a -> b
$
               TcTyMode
-> HsForAllTelescope GhcRn
-> TcM Type
-> TcM (Either [TcReqTVBinder] [VarBndr TyVar Specificity], Type)
forall a.
TcTyMode
-> HsForAllTelescope GhcRn
-> TcM a
-> TcM (Either [TcReqTVBinder] [VarBndr TyVar Specificity], a)
bindExplicitTKTele_Skol_M TcTyMode
mode HsForAllTelescope GhcRn
tele (TcM Type
 -> TcM (Either [TcReqTVBinder] [VarBndr TyVar Specificity], Type))
-> TcM Type
-> TcM (Either [TcReqTVBinder] [VarBndr TyVar Specificity], Type)
forall a b. (a -> b) -> a -> b
$
                 -- The _M variant passes on the mode from the type, to
                 -- any wildards in kind signatures on the forall'd variables
                 -- e.g.      f :: _ -> Int -> forall (a :: _). blah
               TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind GhcRn
ty Type
exp_kind
                 -- Why exp_kind?  See Note [Body kind of HsForAllTy]

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

       ; let skol_info :: SkolemInfo
skol_info = MsgDoc -> MsgDoc -> SkolemInfo
ForAllSkol (HsType GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsType GhcRn
forall) (MsgDoc -> SkolemInfo) -> MsgDoc -> SkolemInfo
forall a b. (a -> b) -> a -> b
$ [MsgDoc] -> MsgDoc
sep ([MsgDoc] -> MsgDoc) -> [MsgDoc] -> MsgDoc
forall a b. (a -> b) -> a -> b
$ case HsForAllTelescope GhcRn
tele of
                           HsForAllVis { hsf_vis_bndrs :: forall pass. HsForAllTelescope pass -> [LHsTyVarBndr () pass]
hsf_vis_bndrs = [LHsTyVarBndr () GhcRn]
hs_tvs } ->
                             (LHsTyVarBndr () GhcRn -> MsgDoc)
-> [LHsTyVarBndr () GhcRn] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map LHsTyVarBndr () GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [LHsTyVarBndr () GhcRn]
hs_tvs
                           HsForAllInvis { hsf_invis_bndrs :: forall pass.
HsForAllTelescope pass -> [LHsTyVarBndr Specificity pass]
hsf_invis_bndrs = [LHsTyVarBndr Specificity GhcRn]
hs_tvs } ->
                             (LHsTyVarBndr Specificity GhcRn -> MsgDoc)
-> [LHsTyVarBndr Specificity GhcRn] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map LHsTyVarBndr Specificity GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [LHsTyVarBndr Specificity GhcRn]
hs_tvs
             tv_bndrs' :: [TcTyVarBinder]
tv_bndrs' = Either [TcReqTVBinder] [VarBndr TyVar Specificity]
-> [TcTyVarBinder]
construct_bndrs Either [TcReqTVBinder] [VarBndr TyVar Specificity]
tv_bndrs
             skol_tvs :: [TyVar]
skol_tvs  = [TcTyVarBinder] -> [TyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [TcTyVarBinder]
tv_bndrs'
       ; Implication
implic <- SkolemInfo
-> [TyVar] -> TcLevel -> WantedConstraints -> TcM Implication
buildTvImplication SkolemInfo
skol_info [TyVar]
skol_tvs TcLevel
tclvl WantedConstraints
wanted
       ; Implication -> TcM ()
emitImplication Implication
implic
             -- /Always/ emit this implication even if wanted is empty
             -- We need the implication so that we check for a bad telescope
             -- See Note [Skolem escape and forall-types]

       ; Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return ([TcTyVarBinder] -> Type -> Type
mkForAllTys [TcTyVarBinder]
tv_bndrs' Type
ty') }
  where
    construct_bndrs :: Either [TcReqTVBinder] [TcInvisTVBinder]
                    -> [TcTyVarBinder]
    construct_bndrs :: Either [TcReqTVBinder] [VarBndr TyVar Specificity]
-> [TcTyVarBinder]
construct_bndrs (Left [TcReqTVBinder]
req_tv_bndrs) =
      (TcReqTVBinder -> TcTyVarBinder)
-> [TcReqTVBinder] -> [TcTyVarBinder]
forall a b. (a -> b) -> [a] -> [b]
map (ArgFlag -> TyVar -> TcTyVarBinder
forall vis. vis -> TyVar -> VarBndr TyVar vis
mkTyVarBinder ArgFlag
Required (TyVar -> TcTyVarBinder)
-> (TcReqTVBinder -> TyVar) -> TcReqTVBinder -> TcTyVarBinder
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TcReqTVBinder -> TyVar
forall tv argf. VarBndr tv argf -> tv
binderVar) [TcReqTVBinder]
req_tv_bndrs
    construct_bndrs (Right [VarBndr TyVar Specificity]
inv_tv_bndrs) =
      (VarBndr TyVar Specificity -> TcTyVarBinder)
-> [VarBndr TyVar Specificity] -> [TcTyVarBinder]
forall a b. (a -> b) -> [a] -> [b]
map VarBndr TyVar Specificity -> TcTyVarBinder
forall a. VarBndr a Specificity -> VarBndr a ArgFlag
tyVarSpecToBinder [VarBndr TyVar Specificity]
inv_tv_bndrs

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 = LHsKind GhcRn
rn_ty }) Type
exp_kind
  | [LHsKind GhcRn] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (LHsContext GhcRn -> [LHsKind GhcRn]
forall l e. GenLocated l e -> e
unLoc LHsContext GhcRn
ctxt)
  = TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind GhcRn
rn_ty Type
exp_kind

  -- See Note [Body kind of a HsQualTy]
  | Type -> Bool
tcIsConstraintKind Type
exp_kind
  = do { [Type]
ctxt' <- TcTyMode -> LHsContext GhcRn -> TcM [Type]
tc_hs_context TcTyMode
mode LHsContext GhcRn
ctxt
       ; Type
ty'   <- TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind GhcRn
rn_ty Type
constraintKind
       ; Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return ([Type] -> Type -> Type
mkPhiTy [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 -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind GhcRn
rn_ty Type
ek
       ; HasDebugCallStack =>
HsType GhcRn -> Type -> Type -> Type -> TcM Type
HsType GhcRn -> Type -> Type -> Type -> TcM Type
checkExpectedKind (LHsKind GhcRn -> HsType GhcRn
forall l e. GenLocated l e -> e
unLoc LHsKind GhcRn
rn_ty) ([Type] -> Type -> Type
mkPhiTy [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
_ LHsKind GhcRn
elt_ty) Type
exp_kind
  = do { Type
tau_ty <- TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind 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 [LHsKind 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 -> MsgDoc -> TcM ()
traceTc String
"tc_hs_type tuple" ([LHsKind GhcRn] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [LHsKind GhcRn]
hs_tys) TcM () -> TcM Type -> TcM Type
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
    HsType GhcRn
-> TcTyMode -> TupleSort -> [LHsKind GhcRn] -> Type -> TcM Type
tc_tuple HsType GhcRn
rn_ty TcTyMode
mode TupleSort
tup_sort [LHsKind GhcRn]
hs_tys Type
exp_kind
  | Bool
otherwise
  = do { String -> MsgDoc -> TcM ()
traceTc String
"tc_hs_type tuple 2" ([LHsKind GhcRn] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [LHsKind GhcRn]
hs_tys)
       ; ([Type]
tys, [Type]
kinds) <- (LHsKind GhcRn -> TcM (Type, Type))
-> [LHsKind GhcRn]
-> IOEnv (Env TcGblEnv TcLclEnv) ([Type], [Type])
forall (m :: * -> *) a b c.
Applicative m =>
(a -> m (b, c)) -> [a] -> m ([b], [c])
mapAndUnzipM (TcTyMode -> LHsKind GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode) [LHsKind GhcRn]
hs_tys
       ; [Type]
kinds <- (Type -> TcM Type) -> [Type] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Type -> TcM 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)
sequence [ SrcSpan -> TcM Type -> TcM Type
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan SrcSpan
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 SrcSpan
loc HsType GhcRn
hs_ty),Type
ty,Type
kind) <- [LHsKind GhcRn]
-> [Type] -> [Type] -> [(LHsKind GhcRn, Type, Type)]
forall a b c. [a] -> [b] -> [c] -> [(a, b, c)]
zip3 [LHsKind 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
hs_tup_sort [LHsKind GhcRn]
tys) Type
exp_kind
  = HsType GhcRn
-> TcTyMode -> TupleSort -> [LHsKind GhcRn] -> Type -> TcM Type
tc_tuple HsType GhcRn
rn_ty TcTyMode
mode TupleSort
tup_sort [LHsKind GhcRn]
tys Type
exp_kind
  where
    tup_sort :: TupleSort
tup_sort = case HsTupleSort
hs_tup_sort of  -- Fourth case dealt with above
                  HsTupleSort
HsUnboxedTuple    -> TupleSort
UnboxedTuple
                  HsTupleSort
HsBoxedTuple      -> TupleSort
BoxedTuple
                  HsTupleSort
HsConstraintTuple -> TupleSort
ConstraintTuple
                  HsTupleSort
_                 -> String -> TupleSort
forall a. String -> a
panic String
"tc_hs_type HsTupleTy"

tc_hs_type TcTyMode
mode rn_ty :: HsType GhcRn
rn_ty@(HsSumTy XSumTy GhcRn
_ [LHsKind GhcRn]
hs_tys) Type
exp_kind
  = do { let arity :: Arity
arity = [LHsKind GhcRn] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [LHsKind GhcRn]
hs_tys
       ; [Type]
arg_kinds <- (LHsKind GhcRn -> TcM Type) -> [LHsKind GhcRn] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (\LHsKind GhcRn
_ -> TcM Type
newOpenTypeKind) [LHsKind GhcRn]
hs_tys
       ; [Type]
tau_tys   <- (LHsKind GhcRn -> Type -> TcM Type)
-> [LHsKind GhcRn] -> [Type] -> TcM [Type]
forall (m :: * -> *) a b c.
Applicative m =>
(a -> b -> m c) -> [a] -> [b] -> m [c]
zipWithM (TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode) [LHsKind 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 (Arity -> TyCon
sumTyCon Arity
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
_ [LHsKind GhcRn]
tys) Type
exp_kind
  = do { [(Type, Type)]
tks <- (LHsKind GhcRn -> TcM (Type, Type))
-> [LHsKind GhcRn] -> IOEnv (Env TcGblEnv TcLclEnv) [(Type, Type)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (TcTyMode -> LHsKind GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode) [LHsKind GhcRn]
tys
       ; ([Type]
taus', Type
kind) <- [LHsKind GhcRn] -> [(Type, Type)] -> TcM ([Type], Type)
unifyKinds [LHsKind GhcRn]
tys [(Type, Type)]
tks
       ; let ty :: Type
ty = ((Type -> Type -> Type) -> Type -> [Type] -> Type
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
_ [LHsKind 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   <- Arity -> TcM Type -> TcM [Type]
forall (m :: * -> *) a. Applicative m => Arity -> m a -> m [a]
replicateM Arity
arity TcM Type
newMetaKindVar
       ; [Type]
taus <- (LHsKind GhcRn -> Type -> TcM Type)
-> [LHsKind GhcRn] -> [Type] -> TcM [Type]
forall (m :: * -> *) a b c.
Applicative m =>
(a -> b -> m c) -> [a] -> [b] -> m [c]
zipWithM (TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode) [LHsKind GhcRn]
tys [Type]
ks
       ; let kind_con :: TyCon
kind_con   = Boxity -> Arity -> TyCon
tupleTyCon           Boxity
Boxed Arity
arity
             ty_con :: TyCon
ty_con     = Boxity -> Arity -> TyCon
promotedTupleDataCon Boxity
Boxed Arity
arity
             tup_k :: Type
tup_k      = TyCon -> [Type] -> Type
mkTyConApp TyCon
kind_con [Type]
ks
       ; 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 :: Arity
arity = [LHsKind GhcRn] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [LHsKind GhcRn]
tys

--------- Constraint types
tc_hs_type TcTyMode
mode rn_ty :: HsType GhcRn
rn_ty@(HsIParamTy XIParamTy GhcRn
_ (L SrcSpan
_ HsIPName
n) LHsKind GhcRn
ty) Type
exp_kind
  = do { MASSERT( isTypeLevel (mode_tyki mode) )
       ; Type
ty' <- TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind 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' and 'tcView'.
  = 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 SourceText
_ Integer
n)) Type
exp_kind
  = do { TyCon -> TcM ()
checkWiredInTyCon TyCon
typeNatKindCon
       ; 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
typeNatKind Type
exp_kind }

tc_hs_type TcTyMode
_ rn_ty :: HsType GhcRn
rn_ty@(HsTyLit XTyLit GhcRn
_ (HsStrTy SourceText
_ 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 }

--------- 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 (NHsCoreTy{})) 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@(HsWildCardTy XWildCardTy GhcRn
_)        Type
ek = TcTyMode -> HsType GhcRn -> Type -> TcM Type
tcAnonWildCardOcc 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 (ArgFlag) for each
variable in the generated ForAllTy type.

This table summarises this relation:
----------------------------------------------------------------------------
| User-written type         HsForAllTelescope   Specificity        ArgFlag
|---------------------------------------------------------------------------
| 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 non-sensical and is thus rejected.
----------------------------------------------------------------------------

For more information regarding the interpretation of the resulting ArgFlag, see
Note [VarBndrs, TyCoVarBinders, 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 -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode (HsArrow GhcRn -> LHsKind 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
-> LHsKind GhcRn
-> LHsKind GhcRn
-> Type
-> TcM Type
tc_fun_type TcTyMode
mode HsArrow GhcRn
mult LHsKind GhcRn
ty1 LHsKind GhcRn
ty2 Type
exp_kind = case TcTyMode -> TypeOrKind
mode_tyki TcTyMode
mode of
  TypeOrKind
TypeLevel ->
    do { Type
arg_k <- TcM Type
newOpenTypeKind
       ; Type
res_k <- TcM Type
newOpenTypeKind
       ; Type
ty1' <- TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind GhcRn
ty1 Type
arg_k
       ; Type
ty2' <- TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind 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 -> LHsKind GhcRn -> LHsKind GhcRn -> HsType GhcRn
forall pass.
XFunTy pass
-> HsArrow pass -> LHsType pass -> LHsType pass -> HsType pass
HsFunTy NoExtField
XFunTy GhcRn
noExtField HsArrow GhcRn
mult LHsKind GhcRn
ty1 LHsKind GhcRn
ty2) (Type -> Type -> Type -> Type
mkVisFunTy Type
mult' Type
ty1' Type
ty2')
                           Type
liftedTypeKind Type
exp_kind }
  TypeOrKind
KindLevel ->  -- no representation polymorphism in kinds. yet.
    do { Type
ty1' <- TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind GhcRn
ty1 Type
liftedTypeKind
       ; Type
ty2' <- TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind 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 -> LHsKind GhcRn -> LHsKind GhcRn -> HsType GhcRn
forall pass.
XFunTy pass
-> HsArrow pass -> LHsType pass -> LHsType pass -> HsType pass
HsFunTy NoExtField
XFunTy GhcRn
noExtField HsArrow GhcRn
mult LHsKind GhcRn
ty1 LHsKind GhcRn
ty2) (Type -> Type -> Type -> Type
mkVisFunTy 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
tcView Type
k            = Type -> Maybe TupleSort
tupKindSort_maybe Type
k'
  | Type -> Bool
tcIsConstraintKind 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 -> [LHsKind GhcRn] -> Type -> TcM Type
tc_tuple HsType GhcRn
rn_ty TcTyMode
mode TupleSort
tup_sort [LHsKind GhcRn]
tys Type
exp_kind
  = do { [Type]
arg_kinds <- case TupleSort
tup_sort of
           TupleSort
BoxedTuple      -> [Type] -> TcM [Type]
forall (m :: * -> *) a. Monad m => a -> m a
return (Arity -> Type -> [Type]
forall a. Arity -> a -> [a]
replicate Arity
arity Type
liftedTypeKind)
           TupleSort
UnboxedTuple    -> Arity -> TcM Type -> TcM [Type]
forall (m :: * -> *) a. Applicative m => Arity -> m a -> m [a]
replicateM Arity
arity TcM Type
newOpenTypeKind
           TupleSort
ConstraintTuple -> [Type] -> TcM [Type]
forall (m :: * -> *) a. Monad m => a -> m a
return (Arity -> Type -> [Type]
forall a. Arity -> a -> [a]
replicate Arity
arity Type
constraintKind)
       ; [Type]
tau_tys <- (LHsKind GhcRn -> Type -> TcM Type)
-> [LHsKind GhcRn] -> [Type] -> TcM [Type]
forall (m :: * -> *) a b c.
Applicative m =>
(a -> b -> m c) -> [a] -> [b] -> m [c]
zipWithM (TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode) [LHsKind 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 :: Arity
arity   = [LHsKind GhcRn] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [LHsKind 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 -> MsgDoc -> TcM ()
traceTc String
"finish_tuple" (TupleSort -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TupleSort
tup_sort MsgDoc -> MsgDoc -> MsgDoc
$$ [Type] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [Type]
tau_kinds MsgDoc -> MsgDoc -> MsgDoc
$$ Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
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
      |  Arity
arity Arity -> Arity -> Bool
forall a. Ord a => a -> a -> Bool
> Arity
mAX_CTUPLE_SIZE
      -> MsgDoc -> TcM Type
forall a. MsgDoc -> TcM a
failWith (Arity -> MsgDoc
bigConstraintTuple Arity
arity)
      |  Bool
otherwise
      -> do TyCon
tycon <- Name -> TcM TyCon
tcLookupTyCon (Arity -> Name
cTupleTyConName Arity
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 -> Arity -> TyCon
tupleTyCon Boxity
Boxed Arity
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 ->
      let tycon :: TyCon
tycon    = Boxity -> Arity -> TyCon
tupleTyCon Boxity
Unboxed Arity
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 in
      Type -> Type -> TcM Type
check_expected_kind (TyCon -> [Type] -> Type
mkTyConApp TyCon
tycon [Type]
arg_tys) Type
res_kind
  where
    arity :: Arity
arity = [Type] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
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

bigConstraintTuple :: Arity -> MsgDoc
bigConstraintTuple :: Arity -> MsgDoc
bigConstraintTuple Arity
arity
  = MsgDoc -> Arity -> MsgDoc -> MsgDoc
hang (String -> MsgDoc
text String
"Constraint tuple arity too large:" MsgDoc -> MsgDoc -> MsgDoc
<+> Arity -> MsgDoc
int Arity
arity
          MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
parens (String -> MsgDoc
text String
"max arity =" MsgDoc -> MsgDoc -> MsgDoc
<+> Arity -> MsgDoc
int Arity
mAX_CTUPLE_SIZE))
       Arity
2 (String -> MsgDoc
text String
"Instead, use a nested tuple")

{-
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 (LHsKind GhcRn, [LHsTypeArg GhcRn])
splitHsAppTys HsType GhcRn
hs_ty
  | HsType GhcRn -> Bool
is_app HsType GhcRn
hs_ty = (LHsKind GhcRn, [LHsTypeArg GhcRn])
-> Maybe (LHsKind GhcRn, [LHsTypeArg GhcRn])
forall a. a -> Maybe a
Just (LHsKind GhcRn
-> [LHsTypeArg GhcRn] -> (LHsKind GhcRn, [LHsTypeArg GhcRn])
forall {pass}.
(XTyVar pass ~ NoExtField, XAppKindTy pass ~ SrcSpan) =>
LHsType pass
-> [HsArg (LHsType pass) (LHsType pass)]
-> (LHsType pass, [HsArg (LHsType pass) (LHsType pass)])
go (HsType GhcRn -> LHsKind GhcRn
forall e. e -> Located e
noLoc HsType GhcRn
hs_ty) [])
  | Bool
otherwise    = Maybe (LHsKind GhcRn, [LHsTypeArg 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
_ LHsKind GhcRn
_ (L SrcSpan
_ IdP GhcRn
op) LHsKind GhcRn
_) = Bool -> Bool
not (Name
IdP GhcRn
op Name -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
funTyConKey)
      -- 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 SrcSpan
_ HsType GhcRn
ty))    = HsType GhcRn -> Bool
is_app HsType GhcRn
ty
    is_app HsType GhcRn
_                       = Bool
False

    go :: LHsType pass
-> [HsArg (LHsType pass) (LHsType pass)]
-> (LHsType pass, [HsArg (LHsType pass) (LHsType pass)])
go (L SrcSpan
_  (HsAppTy XAppTy pass
_ LHsType pass
f LHsType pass
a))      [HsArg (LHsType pass) (LHsType pass)]
as = LHsType pass
-> [HsArg (LHsType pass) (LHsType pass)]
-> (LHsType pass, [HsArg (LHsType pass) (LHsType pass)])
go LHsType pass
f (LHsType pass -> HsArg (LHsType pass) (LHsType pass)
forall tm ty. tm -> HsArg tm ty
HsValArg LHsType pass
a HsArg (LHsType pass) (LHsType pass)
-> [HsArg (LHsType pass) (LHsType pass)]
-> [HsArg (LHsType pass) (LHsType pass)]
forall a. a -> [a] -> [a]
: [HsArg (LHsType pass) (LHsType pass)]
as)
    go (L SrcSpan
_  (HsAppKindTy XAppKindTy pass
l LHsType pass
ty LHsType pass
k)) [HsArg (LHsType pass) (LHsType pass)]
as = LHsType pass
-> [HsArg (LHsType pass) (LHsType pass)]
-> (LHsType pass, [HsArg (LHsType pass) (LHsType pass)])
go LHsType pass
ty (SrcSpan -> LHsType pass -> HsArg (LHsType pass) (LHsType pass)
forall tm ty. SrcSpan -> ty -> HsArg tm ty
HsTypeArg SrcSpan
XAppKindTy pass
l LHsType pass
k HsArg (LHsType pass) (LHsType pass)
-> [HsArg (LHsType pass) (LHsType pass)]
-> [HsArg (LHsType pass) (LHsType pass)]
forall a. a -> [a] -> [a]
: [HsArg (LHsType pass) (LHsType pass)]
as)
    go (L SrcSpan
sp (HsParTy XParTy pass
_ LHsType pass
f))        [HsArg (LHsType pass) (LHsType pass)]
as = LHsType pass
-> [HsArg (LHsType pass) (LHsType pass)]
-> (LHsType pass, [HsArg (LHsType pass) (LHsType pass)])
go LHsType pass
f (SrcSpan -> HsArg (LHsType pass) (LHsType pass)
forall tm ty. SrcSpan -> HsArg tm ty
HsArgPar SrcSpan
sp HsArg (LHsType pass) (LHsType pass)
-> [HsArg (LHsType pass) (LHsType pass)]
-> [HsArg (LHsType pass) (LHsType pass)]
forall a. a -> [a] -> [a]
: [HsArg (LHsType pass) (LHsType pass)]
as)
    go (L SrcSpan
_  (HsOpTy XOpTy pass
_ LHsType pass
l op :: Located (IdP pass)
op@(L SrcSpan
sp IdP pass
_) LHsType pass
r)) [HsArg (LHsType pass) (LHsType pass)]
as
      = ( SrcSpan -> HsType pass -> LHsType pass
forall l e. l -> e -> GenLocated l e
L SrcSpan
sp (XTyVar pass -> PromotionFlag -> Located (IdP pass) -> HsType pass
forall pass.
XTyVar pass -> PromotionFlag -> Located (IdP pass) -> HsType pass
HsTyVar NoExtField
XTyVar pass
noExtField PromotionFlag
NotPromoted Located (IdP pass)
op)
        , LHsType pass -> HsArg (LHsType pass) (LHsType pass)
forall tm ty. tm -> HsArg tm ty
HsValArg LHsType pass
l HsArg (LHsType pass) (LHsType pass)
-> [HsArg (LHsType pass) (LHsType pass)]
-> [HsArg (LHsType pass) (LHsType pass)]
forall a. a -> [a] -> [a]
: LHsType pass -> HsArg (LHsType pass) (LHsType pass)
forall tm ty. tm -> HsArg tm ty
HsValArg LHsType pass
r HsArg (LHsType pass) (LHsType pass)
-> [HsArg (LHsType pass) (LHsType pass)]
-> [HsArg (LHsType pass) (LHsType pass)]
forall a. a -> [a] -> [a]
: [HsArg (LHsType pass) (LHsType pass)]
as )
    go LHsType pass
f [HsArg (LHsType pass) (LHsType pass)]
as = (LHsType pass
f, [HsArg (LHsType pass) (LHsType pass)]
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 -> LHsKind GhcRn -> TcM (Type, Type)
tcInferTyAppHead TcTyMode
mode (L SrcSpan
_ (HsTyVar XTyVar GhcRn
_ PromotionFlag
_ (L SrcSpan
_ IdP GhcRn
tv)))
  = TcTyMode -> Name -> TcM (Type, Type)
tcTyVar TcTyMode
mode Name
IdP GhcRn
tv
tcInferTyAppHead TcTyMode
mode LHsKind GhcRn
ty
  = TcTyMode -> LHsKind GhcRn -> TcM (Type, Type)
tc_infer_lhs_type TcTyMode
mode LHsKind 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, args, result kind)
tcInferTyApps :: TcTyMode
-> LHsKind GhcRn -> Type -> [LHsTypeArg GhcRn] -> TcM (Type, Type)
tcInferTyApps TcTyMode
mode LHsKind GhcRn
hs_ty Type
fun [LHsTypeArg GhcRn]
hs_args
  = do { (Type
f_args, Type
res_k) <- TcTyMode
-> LHsKind GhcRn -> Type -> [LHsTypeArg GhcRn] -> TcM (Type, Type)
tcInferTyApps_nosat TcTyMode
mode LHsKind GhcRn
hs_ty Type
fun [LHsTypeArg GhcRn]
hs_args
       ; Type -> Type -> TcM (Type, Type)
saturateFamApp Type
f_args Type
res_k }

tcInferTyApps_nosat :: TcTyMode
-> LHsKind GhcRn -> Type -> [LHsTypeArg GhcRn] -> TcM (Type, Type)
tcInferTyApps_nosat TcTyMode
mode LHsKind GhcRn
orig_hs_ty Type
fun [LHsTypeArg GhcRn]
orig_hs_args
  = do { String -> MsgDoc -> TcM ()
traceTc String
"tcInferTyApps {" (LHsKind GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsKind GhcRn
orig_hs_ty MsgDoc -> MsgDoc -> MsgDoc
$$ [LHsTypeArg GhcRn] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [LHsTypeArg GhcRn]
orig_hs_args)
       ; (Type
f_args, Type
res_k) <- Arity -> Type -> [LHsTypeArg GhcRn] -> TcM (Type, Type)
go_init Arity
1 Type
fun [LHsTypeArg GhcRn]
orig_hs_args
       ; String -> MsgDoc -> TcM ()
traceTc String
"tcInferTyApps }" (Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
f_args MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc
dcolon MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
res_k)
       ; (Type, Type) -> TcM (Type, Type)
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 :: Arity -> Type -> [LHsTypeArg GhcRn] -> TcM (Type, Type)
go_init Arity
n Type
fun [LHsTypeArg GhcRn]
all_args
      = Arity
-> Type
-> TCvSubst
-> Type
-> [LHsTypeArg GhcRn]
-> TcM (Type, Type)
go Arity
n Type
fun TCvSubst
empty_subst Type
fun_ki [LHsTypeArg GhcRn]
all_args
      where
        fun_ki :: Type
fun_ki = HasDebugCallStack => Type -> Type
Type -> Type
tcTypeKind Type
fun
           -- We do (tcTypeKind 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 tcTypeKind is fast

        empty_subst :: TCvSubst
empty_subst = InScopeSet -> TCvSubst
mkEmptyTCvSubst (InScopeSet -> TCvSubst) -> InScopeSet -> TCvSubst
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
       -> TCvSubst        -- 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)
    --               tcTypeKind fun  =  subst(fun_ki)
    -- So the 'subst' and 'fun_ki' arguments are simply
    -- there to avoid repeatedly calling tcTypeKind.
    --
    -- Reason for INVARIANT: to support the Purely Kinded Type Invariant
    -- it's important that if fun_ki has a forall, then so does
    -- (tcTypeKind 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 :: Arity
-> Type
-> TCvSubst
-> Type
-> [LHsTypeArg GhcRn]
-> TcM (Type, Type)
go Arity
n Type
fun TCvSubst
subst Type
fun_ki [LHsTypeArg GhcRn]
all_args = case ([LHsTypeArg GhcRn]
all_args, Type -> Maybe (TyBinder, Type)
tcSplitPiTy_maybe Type
fun_ki) of

      ---------------- No user-written args left. We're done!
      ([], Maybe (TyBinder, Type)
_) -> (Type, Type) -> TcM (Type, Type)
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
fun, HasCallStack => TCvSubst -> Type -> Type
TCvSubst -> Type -> Type
substTy TCvSubst
subst Type
fun_ki)

      ---------------- HsArgPar: We don't care about parens here
      (HsArgPar SrcSpan
_ : [LHsTypeArg GhcRn]
args, Maybe (TyBinder, Type)
_) -> Arity
-> Type
-> TCvSubst
-> Type
-> [LHsTypeArg GhcRn]
-> TcM (Type, Type)
go Arity
n Type
fun TCvSubst
subst Type
fun_ki [LHsTypeArg GhcRn]
args

      ---------------- HsTypeArg: a kind application (fun @ki)
      (HsTypeArg SrcSpan
_ LHsKind GhcRn
hs_ki_arg : [LHsTypeArg GhcRn]
hs_args, Just (TyBinder
ki_binder, Type
inner_ki)) ->
        case TyBinder
ki_binder of

        -- FunTy with PredTy on LHS, or ForAllTy with Inferred
        Named (Bndr TyVar
_ ArgFlag
Inferred) -> TyBinder -> Type -> TcM (Type, Type)
instantiate TyBinder
ki_binder Type
inner_ki
        Anon AnonArgFlag
InvisArg Scaled Type
_         -> TyBinder -> Type -> TcM (Type, Type)
instantiate TyBinder
ki_binder Type
inner_ki

        Named (Bndr TyVar
_ ArgFlag
Specified) ->  -- Visible kind application
          do { String -> MsgDoc -> TcM ()
traceTc String
"tcInferTyApps (vis kind app)"
                       ([MsgDoc] -> MsgDoc
vcat [ TyBinder -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TyBinder
ki_binder, LHsKind GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsKind GhcRn
hs_ki_arg
                             , Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (TyBinder -> Type
tyBinderType TyBinder
ki_binder)
                             , TCvSubst -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TCvSubst
subst ])

             ; let exp_kind :: Type
exp_kind = HasCallStack => TCvSubst -> Type -> Type
TCvSubst -> Type -> Type
substTy TCvSubst
subst (Type -> Type) -> Type -> Type
forall a b. (a -> b) -> a -> b
$ TyBinder -> Type
tyBinderType TyBinder
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 <- MsgDoc -> TcM Type -> TcM Type
forall a. MsgDoc -> TcM a -> TcM a
addErrCtxt (LHsKind GhcRn -> LHsKind GhcRn -> Arity -> MsgDoc
forall fun arg.
(Outputable fun, Outputable arg) =>
fun -> arg -> Arity -> MsgDoc
funAppCtxt LHsKind GhcRn
orig_hs_ty LHsKind GhcRn
hs_ki_arg Arity
n) (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
                         TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
arg_mode LHsKind GhcRn
hs_ki_arg Type
exp_kind

             ; String -> MsgDoc -> TcM ()
traceTc String
"tcInferTyApps (vis kind app)" (Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
exp_kind)
             ; (TCvSubst
subst', Type
fun') <- TCvSubst -> Type -> TyBinder -> Type -> TcM (TCvSubst, Type)
mkAppTyM TCvSubst
subst Type
fun TyBinder
ki_binder Type
ki_arg
             ; Arity
-> Type
-> TCvSubst
-> Type
-> [LHsTypeArg GhcRn]
-> TcM (Type, Type)
go (Arity
nArity -> Arity -> Arity
forall a. Num a => a -> a -> a
+Arity
1) Type
fun' TCvSubst
subst' Type
inner_ki [LHsTypeArg 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.
        TyBinder
_ -> LHsKind GhcRn -> Type -> TcM (Type, Type)
forall {a} {a} {a}.
(Outputable a, Outputable a) =>
a -> a -> TcRn a
ty_app_err LHsKind GhcRn
hs_ki_arg (Type -> TcM (Type, Type)) -> Type -> TcM (Type, Type)
forall a b. (a -> b) -> a -> b
$ HasCallStack => TCvSubst -> Type -> Type
TCvSubst -> Type -> Type
substTy TCvSubst
subst Type
fun_ki

      -- No binder; try applying the substitution, or fail if that's not possible
      (HsTypeArg SrcSpan
_ LHsKind GhcRn
ki_arg : [LHsTypeArg GhcRn]
_, Maybe (TyBinder, 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
$
                                           LHsKind GhcRn -> Type -> TcM (Type, Type)
forall {a} {a} {a}.
(Outputable a, Outputable a) =>
a -> a -> TcRn a
ty_app_err LHsKind GhcRn
ki_arg Type
substed_fun_ki

      ---------------- HsValArg: a normal argument (fun ty)
      (HsValArg LHsKind GhcRn
arg : [LHsTypeArg GhcRn]
args, Just (TyBinder
ki_binder, Type
inner_ki))
        -- next binder is invisible; need to instantiate it
        | TyBinder -> Bool
isInvisibleBinder TyBinder
ki_binder   -- FunTy with InvisArg on LHS;
                                        -- or ForAllTy with Inferred or Specified
         -> TyBinder -> Type -> TcM (Type, Type)
instantiate TyBinder
ki_binder Type
inner_ki

        -- "normal" case
        | Bool
otherwise
         -> do { String -> MsgDoc -> TcM ()
traceTc String
"tcInferTyApps (vis normal app)"
                          ([MsgDoc] -> MsgDoc
vcat [ TyBinder -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TyBinder
ki_binder
                                , LHsKind GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsKind GhcRn
arg
                                , Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (TyBinder -> Type
tyBinderType TyBinder
ki_binder)
                                , TCvSubst -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TCvSubst
subst ])
                ; let exp_kind :: Type
exp_kind = HasCallStack => TCvSubst -> Type -> Type
TCvSubst -> Type -> Type
substTy TCvSubst
subst (Type -> Type) -> Type -> Type
forall a b. (a -> b) -> a -> b
$ TyBinder -> Type
tyBinderType TyBinder
ki_binder
                ; Type
arg' <- MsgDoc -> TcM Type -> TcM Type
forall a. MsgDoc -> TcM a -> TcM a
addErrCtxt (LHsKind GhcRn -> LHsKind GhcRn -> Arity -> MsgDoc
forall fun arg.
(Outputable fun, Outputable arg) =>
fun -> arg -> Arity -> MsgDoc
funAppCtxt LHsKind GhcRn
orig_hs_ty LHsKind GhcRn
arg Arity
n) (TcM Type -> TcM Type) -> TcM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$
                          TcTyMode -> LHsKind GhcRn -> Type -> TcM Type
tc_lhs_type TcTyMode
mode LHsKind GhcRn
arg Type
exp_kind
                ; String -> MsgDoc -> TcM ()
traceTc String
"tcInferTyApps (vis normal app) 2" (Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
exp_kind)
                ; (TCvSubst
subst', Type
fun') <- TCvSubst -> Type -> TyBinder -> Type -> TcM (TCvSubst, Type)
mkAppTyM TCvSubst
subst Type
fun TyBinder
ki_binder Type
arg'
                ; Arity
-> Type
-> TCvSubst
-> Type
-> [LHsTypeArg GhcRn]
-> TcM (Type, Type)
go (Arity
nArity -> Arity -> Arity
forall a. Num a => a -> a -> a
+Arity
1) Type
fun' TCvSubst
subst' Type
inner_ki [LHsTypeArg GhcRn]
args }

          -- no binder; try applying the substitution, or infer another arrow in fun kind
      (HsValArg LHsKind GhcRn
_ : [LHsTypeArg GhcRn]
_, Maybe (TyBinder, 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 :: Arity
arrows_needed = [LHsTypeArg GhcRn] -> Arity
forall tm ty. [HsArg tm ty] -> Arity
n_initial_val_args [LHsTypeArg GhcRn]
all_args
              ; Coercion
co <- LHsKind GhcRn -> Arity -> Type -> TcM Coercion
forall fun. Outputable fun => fun -> Arity -> Type -> TcM Coercion
matchExpectedFunKind LHsKind GhcRn
hs_ty Arity
arrows_needed Type
substed_fun_ki

              ; Type
fun' <- Type -> TcM Type
zonkTcType (Type
fun Type -> Coercion -> Type
`mkTcCastTy` Coercion
co)
                     -- This zonk is essential, to expose the fruits
                     -- of matchExpectedFunKind to the 'go' loop

              ; String -> MsgDoc -> TcM ()
traceTc String
"tcInferTyApps (no binder)" (MsgDoc -> TcM ()) -> MsgDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
                   [MsgDoc] -> MsgDoc
vcat [ Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
fun MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc
dcolon MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
fun_ki
                        , Arity -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Arity
arrows_needed
                        , Coercion -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Coercion
co
                        , Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
fun' MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc
dcolon MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (HasDebugCallStack => Type -> Type
Type -> Type
tcTypeKind Type
fun')]
              ; Arity -> Type -> [LHsTypeArg GhcRn] -> TcM (Type, Type)
go_init Arity
n Type
fun' [LHsTypeArg GhcRn]
all_args }
                -- Use go_init to establish go's INVARIANT
      where
        instantiate :: TyBinder -> Type -> TcM (Type, Type)
instantiate TyBinder
ki_binder Type
inner_ki
          = do { String -> MsgDoc -> TcM ()
traceTc String
"tcInferTyApps (need to instantiate)"
                         ([MsgDoc] -> MsgDoc
vcat [ TyBinder -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TyBinder
ki_binder, TCvSubst -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TCvSubst
subst])
               ; (TCvSubst
subst', Type
arg') <- TCvSubst -> TyBinder -> TcM (TCvSubst, Type)
tcInstInvisibleTyBinder TCvSubst
subst TyBinder
ki_binder
               ; Arity
-> Type
-> TCvSubst
-> Type
-> [LHsTypeArg GhcRn]
-> TcM (Type, Type)
go Arity
n (Type -> Type -> Type
mkAppTy Type
fun Type
arg') TCvSubst
subst' Type
inner_ki [LHsTypeArg 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 (TCvSubst -> Bool
isEmptyTCvSubst TCvSubst
subst)
          = Arity
-> Type
-> TCvSubst
-> Type
-> [LHsTypeArg GhcRn]
-> TcM (Type, Type)
go Arity
n Type
fun TCvSubst
zapped_subst Type
substed_fun_ki [LHsTypeArg GhcRn]
all_args
          | Bool
otherwise
          = TcM (Type, Type)
fallthrough

        zapped_subst :: TCvSubst
zapped_subst   = TCvSubst -> TCvSubst
zapTCvSubst TCvSubst
subst
        substed_fun_ki :: Type
substed_fun_ki = HasCallStack => TCvSubst -> Type -> Type
TCvSubst -> Type -> Type
substTy TCvSubst
subst Type
fun_ki
        hs_ty :: LHsKind GhcRn
hs_ty          = LHsKind GhcRn -> [LHsTypeArg GhcRn] -> LHsKind GhcRn
appTypeToArg LHsKind GhcRn
orig_hs_ty (Arity -> [LHsTypeArg GhcRn] -> [LHsTypeArg GhcRn]
forall a. Arity -> [a] -> [a]
take (Arity
nArity -> Arity -> Arity
forall a. Num a => a -> a -> a
-Arity
1) [LHsTypeArg GhcRn]
orig_hs_args)

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

    ty_app_err :: a -> a -> TcRn a
ty_app_err a
arg a
ty
      = MsgDoc -> TcRn a
forall a. MsgDoc -> TcM a
failWith (MsgDoc -> TcRn a) -> MsgDoc -> TcRn a
forall a b. (a -> b) -> a -> b
$ String -> MsgDoc
text String
"Cannot apply function of kind" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
quotes (a -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr a
ty)
                MsgDoc -> MsgDoc -> MsgDoc
$$ String -> MsgDoc
text String
"to visible kind argument" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
quotes (a -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr a
arg)


mkAppTyM :: TCvSubst
         -> TcType -> TyCoBinder    -- fun, plus its top-level binder
         -> TcType                  -- arg
         -> TcM (TCvSubst, 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)
--       tcTypeKind 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
--    tcTypeKind arg = tyVarKind (binderVar bndr)
-- This must be true after zonking (precondition 1), but it's not
-- required for the (PKTI).
mkAppTyM :: TCvSubst -> Type -> TyBinder -> Type -> TcM (TCvSubst, Type)
mkAppTyM TCvSubst
subst Type
fun TyBinder
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] -> Arity -> Bool
forall a. [a] -> Arity -> Bool
`lengthIs` (TyCon -> Arity
tyConArity TyCon
tc Arity -> Arity -> Arity
forall a. Num a => a -> a -> a
- Arity
1)
  , (TyVar -> Bool) -> [TyVar] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any TyVar -> Bool
isTrickyTvBinder (TyCon -> [TyVar]
tyConTyVars TyCon
tc) -- We could cache this in the synonym
  = do { Type
arg'  <- Type -> TcM Type
zonkTcType  Type
arg
       ; [Type]
args' <- [Type] -> TcM [Type]
zonkTcTypes [Type]
args
       ; let subst' :: TCvSubst
subst' = case TyBinder
ki_binder of
                        Anon {}           -> TCvSubst
subst
                        Named (Bndr TyVar
tv ArgFlag
_) -> TCvSubst -> TyVar -> Type -> TCvSubst
extendTvSubstAndInScope TCvSubst
subst TyVar
tv Type
arg'
       ; (TCvSubst, Type) -> TcM (TCvSubst, Type)
forall (m :: * -> *) a. Monad m => a -> m a
return (TCvSubst
subst', TyCon -> [Type] -> Type
mkTyConApp TyCon
tc ([Type]
args' [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type
arg'])) }


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

mkAppTyM TCvSubst
subst Type
fun (Named (Bndr TyVar
tv ArgFlag
_)) Type
arg
  = do { Type
arg' <- if TyVar -> Bool
isTrickyTvBinder TyVar
tv
                 then -- See Note [mkAppTyM]: Nasty case 1
                      Type -> TcM Type
zonkTcType Type
arg
                 else Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return     Type
arg
       ; (TCvSubst, Type) -> TcM (TCvSubst, Type)
forall (m :: * -> *) a. Monad m => a -> m a
return ( TCvSubst -> TyVar -> Type -> TCvSubst
extendTvSubstAndInScope TCvSubst
subst TyVar
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
  = ASSERT2( isPiTy fun_kind
           ,  ppr fun <+> dcolon <+> ppr fun_kind $$ ppr arg )
    Type -> Type -> Type
mkAppTy Type
fun Type
arg
  where
    fun_kind :: Type
fun_kind = HasDebugCallStack => Type -> Type
Type -> Type
tcTypeKind Type
fun

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

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

 (PKTI) It is legal to call 'tcTypeKind' 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 tcTypeKind" we mean "tcTypeKind will not crash".
The way in which tcTypeKind 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 tcTypeKind 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.

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):
--     tcTypeKind 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) <- HasCallStack => Type -> Maybe (TyCon, [Type])
Type -> Maybe (TyCon, [Type])
tcSplitTyConApp_maybe Type
ty
  , TyCon -> Bool
mustBeSaturated TyCon
tc
  , let n_to_inst :: Arity
n_to_inst = TyCon -> Arity
tyConArity TyCon
tc Arity -> Arity -> Arity
forall a. Num a => a -> a -> a
- [Type] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [Type]
args
  = do { ([Type]
extra_args, Type
ki') <- Arity -> Type -> TcM ([Type], Type)
tcInstInvisibleTyBindersN Arity
n_to_inst Type
kind
       ; (Type, Type) -> TcM (Type, Type)
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
ty Type -> [Type] -> Type
`mkTcAppTys` [Type]
extra_args, Type
ki') }
  | Bool
otherwise
  = (Type, Type) -> TcM (Type, Type)
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 :: LHsKind GhcRn -> [LHsTypeArg GhcRn] -> LHsKind GhcRn
appTypeToArg LHsKind GhcRn
f []                       = LHsKind GhcRn
f
appTypeToArg LHsKind GhcRn
f (HsValArg LHsKind GhcRn
arg    : [LHsTypeArg GhcRn]
args) = LHsKind GhcRn -> [LHsTypeArg GhcRn] -> LHsKind GhcRn
appTypeToArg (LHsKind GhcRn -> LHsKind GhcRn -> LHsKind GhcRn
forall (p :: Pass).
LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
mkHsAppTy LHsKind GhcRn
f LHsKind GhcRn
arg) [LHsTypeArg GhcRn]
args
appTypeToArg LHsKind GhcRn
f (HsArgPar SrcSpan
_      : [LHsTypeArg GhcRn]
args) = LHsKind GhcRn -> [LHsTypeArg GhcRn] -> LHsKind GhcRn
appTypeToArg LHsKind GhcRn
f                 [LHsTypeArg GhcRn]
args
appTypeToArg LHsKind GhcRn
f (HsTypeArg SrcSpan
l LHsKind GhcRn
arg : [LHsTypeArg GhcRn]
args)
  = LHsKind GhcRn -> [LHsTypeArg GhcRn] -> LHsKind GhcRn
appTypeToArg (XAppKindTy GhcRn -> LHsKind GhcRn -> LHsKind GhcRn -> LHsKind GhcRn
forall (p :: Pass).
XAppKindTy (GhcPass p)
-> LHsType (GhcPass p)
-> LHsType (GhcPass p)
-> LHsType (GhcPass p)
mkHsAppKindTy SrcSpan
XAppKindTy GhcRn
l LHsKind GhcRn
f LHsKind GhcRn
arg) [LHsTypeArg 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 -> MsgDoc -> TcM ()
traceTc String
"checkExpectedKind" (Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
ty MsgDoc -> MsgDoc -> MsgDoc
$$ Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
act_kind)

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

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

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

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

       ; if Type
act_kind' HasDebugCallStack => Type -> Type -> Bool
Type -> Type -> Bool
`tcEqType` Type
exp_kind
         then Type -> TcM Type
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
uType TypeOrKind
KindLevel CtOrigin
origin Type
act_kind' Type
exp_kind
                 ; String -> MsgDoc -> TcM ()
traceTc String
"checkExpectedKind" ([MsgDoc] -> MsgDoc
vcat [ Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
act_kind
                                                     , Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
exp_kind
                                                     , Coercion -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Coercion
co_k ])
                ; Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
res_ty Type -> Coercion -> Type
`mkTcCastTy` 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 :: Arity
n_exp_invis_bndrs = Type -> Arity
invisibleTyBndrCount Type
exp_kind
      n_act_invis_bndrs :: Arity
n_act_invis_bndrs = Type -> Arity
invisibleTyBndrCount Type
act_kind
      n_to_inst :: Arity
n_to_inst         = Arity
n_act_invis_bndrs Arity -> Arity -> Arity
forall a. Num a => a -> a -> a
- Arity
n_exp_invis_bndrs

---------------------------
tcHsMbContext :: Maybe (LHsContext GhcRn) -> TcM [PredType]
tcHsMbContext :: Maybe (LHsContext GhcRn) -> TcM [Type]
tcHsMbContext Maybe (LHsContext GhcRn)
Nothing    = [Type] -> TcM [Type]
forall (m :: * -> *) a. Monad m => a -> m a
return []
tcHsMbContext (Just LHsContext GhcRn
cxt) = LHsContext GhcRn -> TcM [Type]
tcHsContext LHsContext GhcRn
cxt

tcHsContext :: LHsContext GhcRn -> TcM [PredType]
tcHsContext :: LHsContext GhcRn -> TcM [Type]
tcHsContext LHsContext GhcRn
cxt = TcTyMode -> LHsContext GhcRn -> TcM [Type]
tc_hs_context (TypeOrKind -> TcTyMode
mkMode TypeOrKind
TypeLevel) LHsContext GhcRn
cxt

tcLHsPredType :: LHsType GhcRn -> TcM PredType
tcLHsPredType :: LHsKind GhcRn -> TcM Type
tcLHsPredType LHsKind GhcRn
pred = TcTyMode -> LHsKind GhcRn -> TcM Type
tc_lhs_pred (TypeOrKind -> TcTyMode
mkMode TypeOrKind
TypeLevel) LHsKind 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 = (LHsKind GhcRn -> TcM Type) -> [LHsKind GhcRn] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (TcTyMode -> LHsKind GhcRn -> TcM Type
tc_lhs_pred TcTyMode
mode) (LHsContext GhcRn -> [LHsKind GhcRn]
forall l e. GenLocated l e -> e
unLoc LHsContext GhcRn
ctxt)

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

---------------------------
tcTyVar :: TcTyMode -> 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 :: TcTyMode -> Name -> TcM (Type, Type)
tcTyVar TcTyMode
mode Name
name         -- Could be a tyvar, a tycon, or a datacon
  = do { String -> MsgDoc -> TcM ()
traceTc String
"lk1" (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name)
       ; TcTyThing
thing <- Name -> TcM TcTyThing
tcLookup Name
name
       ; case TcTyThing
thing of
           ATyVar Name
_ TyVar
tv -> (Type, Type) -> TcM (Type, Type)
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar -> Type
mkTyVarTy TyVar
tv, TyVar -> Type
tyVarKind TyVar
tv)

           ATcTyCon TyCon
tc_tc
             -> do { -- See Note [GADT kind self-reference]
                     Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (TypeOrKind -> Bool
isTypeLevel (TcTyMode -> TypeOrKind
mode_tyki TcTyMode
mode))
                            (Name -> PromotionErr -> TcM ()
forall a. Name -> PromotionErr -> TcM a
promotionErr Name
name PromotionErr
TyConPE)
                   ; TyCon -> TcM ()
check_tc TyCon
tc_tc
                   ; (Type, Type) -> TcM (Type, Type)
forall (m :: * -> *) a. Monad m => a -> m a
return (TyCon -> Type
mkTyConTy TyCon
tc_tc, TyCon -> Type
tyConKind TyCon
tc_tc) }

           AGlobal (ATyCon TyCon
tc)
             -> do { TyCon -> TcM ()
check_tc TyCon
tc
                   ; (Type, Type) -> TcM (Type, Type)
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 ([TyVar]
_, [TyVar]
_, [EqSpec]
_, [Type]
theta, [Scaled Type]
_, Type
_) = DataCon
-> ([TyVar], [TyVar], [EqSpec], [Type], [Scaled Type], Type)
dataConFullSig DataCon
dc
                   ; String -> MsgDoc -> TcM ()
traceTc String
"tcTyVar" (DataCon -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr DataCon
dc MsgDoc -> MsgDoc -> MsgDoc
<+> [Type] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [Type]
theta MsgDoc -> MsgDoc -> MsgDoc
$$ Maybe Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr ([Type] -> Maybe Type
dc_theta_illegal_constraint [Type]
theta))
                   ; case [Type] -> Maybe Type
dc_theta_illegal_constraint [Type]
theta of
                       Just Type
pred -> Name -> PromotionErr -> TcM ()
forall a. Name -> PromotionErr -> TcM a
promotionErr Name
name (PromotionErr -> TcM ()) -> PromotionErr -> TcM ()
forall a b. (a -> b) -> a -> b
$
                                    Type -> PromotionErr
ConstrainedDataConPE Type
pred
                       Maybe Type
Nothing   -> () -> TcM ()
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
                   ; let tc :: TyCon
tc = DataCon -> TyCon
promoteDataCon DataCon
dc
                   ; (Type, Type) -> TcM (Type, Type)
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
_  -> String -> TcTyThing -> Name -> TcM (Type, Type)
forall a. String -> TcTyThing -> Name -> TcM a
wrongThingErr String
"type" TcTyThing
thing Name
name }
  where
    check_tc :: TyCon -> TcM ()
    check_tc :: TyCon -> TcM ()
check_tc TyCon
tc = 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 (TypeOrKind -> Bool
isTypeLevel (TcTyMode -> TypeOrKind
mode_tyki TcTyMode
mode) Bool -> Bool -> Bool
||
                               Bool
data_kinds Bool -> Bool -> Bool
||
                               TyCon -> Bool
isKindTyCon TyCon
tc) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
                       Name -> PromotionErr -> TcM ()
forall a. Name -> PromotionErr -> TcM a
promotionErr Name
name PromotionErr
NoDataKindsTC }

    -- We cannot promote a data constructor with a context that contains
    -- constraints other than equalities, so error if we find one.
    -- See Note [Constraints in kinds] in GHC.Core.TyCo.Rep
    dc_theta_illegal_constraint :: ThetaType -> Maybe PredType
    dc_theta_illegal_constraint :: [Type] -> Maybe Type
dc_theta_illegal_constraint = (Type -> Bool) -> [Type] -> Maybe Type
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (Bool -> Bool
not (Bool -> Bool) -> (Type -> Bool) -> Type -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Type -> Bool
isEqPred)

{-
Note [GADT kind self-reference]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A promoted type cannot be used in the body of that type's declaration.
#11554 shows this example, which made GHC loop:

  import Data.Kind
  data P (x :: k) = Q
  data A :: Type where
    B :: forall (a :: A). P a -> A

In order to check the constructor B, we need to have the promoted type A, but in
order to get that promoted type, B must first be checked. To prevent looping, a
TyConPE promotion error is given when tcTyVar checks an ATcTyCon in kind mode.
Any ATcTyCon is a TyCon being defined in the current recursive group (see data
type decl for TcTyThing), and all such TyCons are illegal in kinds.

#11962 proposes checking the head of a data declaration separately from
its constructors. This would allow the example above to pass.

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 either * or #. 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 * or # 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.Utils.Zonk.
      - 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. LHsKind GhcRn -> TcM a -> TcM a
addTypeCtxt (L SrcSpan
_ (HsWildCardTy XWildCardTy GhcRn
_)) TcM a
thing = TcM a
thing   -- "In the type '_'" just isn't helpful.
addTypeCtxt (L SrcSpan
_ HsType GhcRn
ty) TcM a
thing
  = MsgDoc -> TcM a -> TcM a
forall a. MsgDoc -> TcM a -> TcM a
addErrCtxt MsgDoc
doc TcM a
thing
  where
    doc :: MsgDoc
doc = String -> MsgDoc
text String
"In the type" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
quotes (HsType GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsType GhcRn
ty)


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

tcNamedWildCardBinders :: [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
tcNamedWildCardBinders :: forall a. HsQTvsRn -> ([(Name, TyVar)] -> TcM a) -> TcM a
tcNamedWildCardBinders HsQTvsRn
wc_names [(Name, TyVar)] -> TcM a
thing_inside
  = do { [TyVar]
wcs <- (Name -> IOEnv (Env TcGblEnv TcLclEnv) TyVar)
-> HsQTvsRn -> TcM [TyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Name -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
newNamedWildTyVar HsQTvsRn
wc_names
       ; let wc_prs :: [(Name, TyVar)]
wc_prs = HsQTvsRn
wc_names HsQTvsRn -> [TyVar] -> [(Name, TyVar)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [TyVar]
wcs
       ; [(Name, TyVar)] -> TcM a -> TcM a
forall r. [(Name, TyVar)] -> TcM r -> TcM r
tcExtendNameTyVarEnv [(Name, TyVar)]
wc_prs (TcM a -> TcM a) -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$
         [(Name, TyVar)] -> TcM a
thing_inside [(Name, TyVar)]
wc_prs }

newNamedWildTyVar :: Name -> TcM TcTyVar
-- ^ New unification variable '_' for a wildcard
newNamedWildTyVar :: Name -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
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 :: TyVar
tyvar = Name -> Type -> TcTyVarDetails -> TyVar
mkTcTyVar Name
wc_name Type
kind TcTyVarDetails
details
       ; String -> MsgDoc -> TcM ()
traceTc String
"newWildTyVar" (TyVar -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TyVar
tyvar)
       ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return TyVar
tyvar }

---------------------------
tcAnonWildCardOcc :: TcTyMode -> HsType GhcRn -> Kind -> TcM TcType
tcAnonWildCardOcc :: TcTyMode -> HsType GhcRn -> Type -> TcM Type
tcAnonWildCardOcc (TcTyMode { mode_holes :: TcTyMode -> Maybe (TcLevel, HoleMode)
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 :: TyVar
kv      = Name -> Type -> TcTyVarDetails -> TyVar
mkTcTyVar Name
kv_name Type
liftedTypeKind TcTyVarDetails
kv_details
             wc_kind :: Type
wc_kind = TyVar -> Type
mkTyVarTy TyVar
kv
             wc_tv :: TyVar
wc_tv   = Name -> Type -> TcTyVarDetails -> TyVar
mkTcTyVar Name
wc_name Type
wc_kind TcTyVarDetails
wc_details

       ; String -> MsgDoc -> TcM ()
traceTc String
"tcAnonWildCardOcc" (TcLevel -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TcLevel
hole_lvl MsgDoc -> MsgDoc -> MsgDoc
<+> Bool -> MsgDoc
forall a. Outputable a => a -> MsgDoc
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
$
         TyVar -> TcM ()
emitAnonTypeHole TyVar
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 (TyVar -> Type
mkTyVarTy TyVar
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"

     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

tcAnonWildCardOcc TcTyMode
mode HsType GhcRn
ty Type
_
-- mode_holes is Nothing.  Should not happen, because renamer
-- should already have rejected holes in unexpected places
  = String -> MsgDoc -> TcM Type
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"tcWildCardOcc" (TcTyMode -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TcTyMode
mode MsgDoc -> MsgDoc -> MsgDoc
$$ HsType GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsType GhcRn
ty)

{- 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-specified kind (CUSK)?
data SAKS_or_CUSK
  = SAKS Kind  -- Standalone kind signature, fully zonked! (zonkTcTypeToType)
  | CUSK       -- Complete user-specified kind (CUSK)

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

-- See Note [kcCheckDeclHeader vs kcInferDeclHeader]
kcDeclHeader
  :: InitialKindStrategy
  -> Name              -- ^ of the thing being checked
  -> TyConFlavour      -- ^ 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
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcDeclHeader (InitialKindCheck SAKS_or_CUSK
msig) = SAKS_or_CUSK
-> Name
-> TyConFlavour
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcCheckDeclHeader SAKS_or_CUSK
msig
kcDeclHeader InitialKindStrategy
InitialKindInfer = Name
-> TyConFlavour -> 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      -- ^ What sort of 'TyCon' is being checked
  -> LHsQTyVars GhcRn  -- ^ Binders in the header
  -> TcM ContextKind   -- ^ The result kind. AnyKind == no result signature
  -> TcM TcTyCon       -- ^ A suitably-kinded generalized TcTyCon
kcCheckDeclHeader :: SAKS_or_CUSK
-> Name
-> TyConFlavour
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcCheckDeclHeader (SAKS Type
sig) = Type
-> Name
-> TyConFlavour
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcCheckDeclHeader_sig Type
sig
kcCheckDeclHeader SAKS_or_CUSK
CUSK       = Name
-> TyConFlavour -> LHsQTyVars GhcRn -> TcM ContextKind -> TcM TyCon
kcCheckDeclHeader_cusk

kcCheckDeclHeader_cusk
  :: Name              -- ^ of the thing being checked
  -> TyConFlavour      -- ^ What sort of 'TyCon' is being checked
  -> LHsQTyVars GhcRn  -- ^ Binders in the header
  -> TcM ContextKind   -- ^ The result kind
  -> TcM TcTyCon       -- ^ A suitably-kinded generalized TcTyCon
kcCheckDeclHeader_cusk :: Name
-> TyConFlavour -> LHsQTyVars GhcRn -> TcM ContextKind -> TcM TyCon
kcCheckDeclHeader_cusk Name
name TyConFlavour
flav
              (HsQTvs { hsq_ext :: forall pass. LHsQTyVars pass -> XHsQTvs pass
hsq_ext = XHsQTvs GhcRn
kv_ns
                      , hsq_explicit :: forall pass. LHsQTyVars pass -> [LHsTyVarBndr () pass]
hsq_explicit = [LHsTyVarBndr () GhcRn]
hs_tvs }) TcM ContextKind
kc_res_ki
  -- CUSK case
  -- See note [Required, Specified, and Inferred for types] in GHC.Tc.TyCl
  = Name -> TyConFlavour -> TcM TyCon -> TcM TyCon
forall a. Name -> TyConFlavour -> TcM a -> TcM a
addTyConFlavCtxt Name
name TyConFlavour
flav (TcM TyCon -> TcM TyCon) -> TcM TyCon -> TcM TyCon
forall a b. (a -> b) -> a -> b
$
    do { ([TyVar]
scoped_kvs, ([TyVar]
tc_tvs, Type
res_kind))
           <- TcM ([TyVar], ([TyVar], Type)) -> TcM ([TyVar], ([TyVar], Type))
forall a. TcM a -> TcM a
pushTcLevelM_                               (TcM ([TyVar], ([TyVar], Type)) -> TcM ([TyVar], ([TyVar], Type)))
-> TcM ([TyVar], ([TyVar], Type)) -> TcM ([TyVar], ([TyVar], Type))
forall a b. (a -> b) -> a -> b
$
              TcM ([TyVar], ([TyVar], Type)) -> TcM ([TyVar], ([TyVar], Type))
forall a. TcM a -> TcM a
solveEqualities                             (TcM ([TyVar], ([TyVar], Type)) -> TcM ([TyVar], ([TyVar], Type)))
-> TcM ([TyVar], ([TyVar], Type)) -> TcM ([TyVar], ([TyVar], Type))
forall a b. (a -> b) -> a -> b
$
              HsQTvsRn -> TcM ([TyVar], Type) -> TcM ([TyVar], ([TyVar], Type))
forall a. HsQTvsRn -> TcM a -> TcM ([TyVar], a)
bindImplicitTKBndrs_Q_Skol HsQTvsRn
XHsQTvs GhcRn
kv_ns            (TcM ([TyVar], Type) -> TcM ([TyVar], ([TyVar], Type)))
-> TcM ([TyVar], Type) -> TcM ([TyVar], ([TyVar], Type))
forall a b. (a -> b) -> a -> b
$
              ContextKind
-> [LHsTyVarBndr () GhcRn] -> TcM Type -> TcM ([TyVar], Type)
forall a.
ContextKind -> [LHsTyVarBndr () GhcRn] -> TcM a -> TcM ([TyVar], a)
bindExplicitTKBndrs_Q_Skol ContextKind
ctxt_kind [LHsTyVarBndr () GhcRn]
hs_tvs (TcM Type -> TcM ([TyVar], Type))
-> TcM Type -> TcM ([TyVar], 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 :: [TyVar]
spec_req_tkvs = [TyVar]
scoped_kvs [TyVar] -> [TyVar] -> [TyVar]
forall a. [a] -> [a] -> [a]
++ [TyVar]
tc_tvs
             all_kinds :: [Type]
all_kinds     = Type
res_kind Type -> [Type] -> [Type]
forall a. a -> [a] -> [a]
: (TyVar -> Type) -> [TyVar] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map TyVar -> Type
tyVarKind [TyVar]
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

       ; let non_tc_candidates :: [TyVar]
non_tc_candidates = (TyVar -> Bool) -> [TyVar] -> [TyVar]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (TyVar -> Bool) -> TyVar -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TyVar -> Bool
isTcTyVar) (TyVarSet -> [TyVar]
forall elt. UniqSet elt -> [elt]
nonDetEltsUniqSet ([Type] -> TyVarSet
tyCoVarsOfTypes [Type]
all_kinds))
             candidates :: CandidatesQTvs
candidates = CandidatesQTvs
candidates' { dv_kvs :: DTyVarSet
dv_kvs = CandidatesQTvs -> DTyVarSet
dv_kvs CandidatesQTvs
candidates' DTyVarSet -> [TyVar] -> DTyVarSet
`extendDVarSetList` [TyVar]
non_tc_candidates }
             inf_candidates :: CandidatesQTvs
inf_candidates = CandidatesQTvs
candidates CandidatesQTvs -> [TyVar] -> CandidatesQTvs
`delCandidates` [TyVar]
spec_req_tkvs

       ; [TyVar]
inferred <- CandidatesQTvs -> TcM [TyVar]
quantifyTyVars CandidatesQTvs
inf_candidates
                     -- NB: 'inferred' comes back sorted in dependency order

       ; [TyVar]
scoped_kvs <- (TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar)
-> [TyVar] -> TcM [TyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTyCoVarKind [TyVar]
scoped_kvs
       ; [TyVar]
tc_tvs     <- (TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar)
-> [TyVar] -> TcM [TyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTyCoVarKind [TyVar]
tc_tvs
       ; Type
res_kind   <- Type -> TcM Type
zonkTcType           Type
res_kind

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

             final_tc_binders :: [TyConBinder]
final_tc_binders =  ArgFlag -> [TyVar] -> [TyConBinder]
mkNamedTyConBinders ArgFlag
Inferred  [TyVar]
inferred
                              [TyConBinder] -> [TyConBinder] -> [TyConBinder]
forall a. [a] -> [a] -> [a]
++ ArgFlag -> [TyVar] -> [TyConBinder]
mkNamedTyConBinders ArgFlag
Specified [TyVar]
specified
                              [TyConBinder] -> [TyConBinder] -> [TyConBinder]
forall a. [a] -> [a] -> [a]
++ (TyVar -> TyConBinder) -> [TyVar] -> [TyConBinder]
forall a b. (a -> b) -> [a] -> [b]
map (TyVarSet -> TyVar -> TyConBinder
mkRequiredTyConBinder TyVarSet
mentioned_kv_set) [TyVar]
tc_tvs

             all_tv_prs :: [(Name, TyVar)]
all_tv_prs =  [TyVar] -> [(Name, TyVar)]
mkTyVarNamePairs ([TyVar]
scoped_kvs [TyVar] -> [TyVar] -> [TyVar]
forall a. [a] -> [a] -> [a]
++ [TyVar]
tc_tvs)
             tycon :: TyCon
tycon = Name
-> [TyConBinder]
-> Type
-> [(Name, TyVar)]
-> Bool
-> TyConFlavour
-> TyCon
mkTcTyCon Name
name [TyConBinder]
final_tc_binders Type
res_kind [(Name, TyVar)]
all_tv_prs
                               Bool
True -- it is generalised
                               TyConFlavour
flav
         -- 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 -> MsgDoc -> TcM ()
traceTc String
"kcCheckDeclHeader_cusk " (MsgDoc -> TcM ()) -> MsgDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [MsgDoc] -> MsgDoc
vcat [ String -> MsgDoc
text String
"name" MsgDoc -> MsgDoc -> MsgDoc
<+> Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name
              , String -> MsgDoc
text String
"kv_ns" MsgDoc -> MsgDoc -> MsgDoc
<+> HsQTvsRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsQTvsRn
XHsQTvs GhcRn
kv_ns
              , String -> MsgDoc
text String
"hs_tvs" MsgDoc -> MsgDoc -> MsgDoc
<+> [LHsTyVarBndr () GhcRn] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [LHsTyVarBndr () GhcRn]
hs_tvs
              , String -> MsgDoc
text String
"scoped_kvs" MsgDoc -> MsgDoc -> MsgDoc
<+> [TyVar] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [TyVar]
scoped_kvs
              , String -> MsgDoc
text String
"tc_tvs" MsgDoc -> MsgDoc -> MsgDoc
<+> [TyVar] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [TyVar]
tc_tvs
              , String -> MsgDoc
text String
"res_kind" MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
res_kind
              , String -> MsgDoc
text String
"candidates" MsgDoc -> MsgDoc -> MsgDoc
<+> CandidatesQTvs -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr CandidatesQTvs
candidates
              , String -> MsgDoc
text String
"inferred" MsgDoc -> MsgDoc -> MsgDoc
<+> [TyVar] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [TyVar]
inferred
              , String -> MsgDoc
text String
"specified" MsgDoc -> MsgDoc -> MsgDoc
<+> [TyVar] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [TyVar]
specified
              , String -> MsgDoc
text String
"final_tc_binders" MsgDoc -> MsgDoc -> MsgDoc
<+> [TyConBinder] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [TyConBinder]
final_tc_binders
              , String -> MsgDoc
text String
"mkTyConKind final_tc_bndrs res_kind"
                MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr ([TyConBinder] -> Type -> Type
mkTyConKind [TyConBinder]
final_tc_binders Type
res_kind)
              , String -> MsgDoc
text String
"all_tv_prs" MsgDoc -> MsgDoc -> MsgDoc
<+> [(Name, TyVar)] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [(Name, TyVar)]
all_tv_prs ]

       ; TyCon -> TcM TyCon
forall (m :: * -> *) a. Monad m => a -> m a
return TyCon
tycon }
  where
    ctxt_kind :: ContextKind
ctxt_kind | TyConFlavour -> Bool
tcFlavourIsOpen TyConFlavour
flav = Type -> ContextKind
TheKind Type
liftedTypeKind
              | Bool
otherwise            = ContextKind
AnyKind

-- | 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      -- ^ What sort of 'TyCon' is being checked
  -> LHsQTyVars GhcRn
  -> TcM ContextKind   -- ^ The result kind
  -> TcM TcTyCon       -- ^ A suitably-kinded non-generalized TcTyCon
kcInferDeclHeader :: Name
-> TyConFlavour -> LHsQTyVars GhcRn -> TcM ContextKind -> TcM TyCon
kcInferDeclHeader Name
name TyConFlavour
flav
              (HsQTvs { hsq_ext :: forall pass. LHsQTyVars pass -> XHsQTvs pass
hsq_ext = XHsQTvs GhcRn
kv_ns
                      , hsq_explicit :: forall pass. LHsQTyVars pass -> [LHsTyVarBndr () pass]
hsq_explicit = [LHsTyVarBndr () GhcRn]
hs_tvs }) TcM ContextKind
kc_res_ki
  -- No standalane kind signature and no CUSK.
  -- See note [Required, Specified, and Inferred for types] in GHC.Tc.TyCl
  = Name -> TyConFlavour -> TcM TyCon -> TcM TyCon
forall a. Name -> TyConFlavour -> TcM a -> TcM a
addTyConFlavCtxt Name
name TyConFlavour
flav (TcM TyCon -> TcM TyCon) -> TcM TyCon -> TcM TyCon
forall a b. (a -> b) -> a -> b
$
    do { ([TyVar]
scoped_kvs, ([TyVar]
tc_tvs, Type
res_kind))
           -- Why bindImplicitTKBndrs_Q_Tv which uses newTyVarTyVar?
           -- See Note [Inferring kinds for type declarations] in GHC.Tc.TyCl
           <- HsQTvsRn -> TcM ([TyVar], Type) -> TcM ([TyVar], ([TyVar], Type))
forall a. HsQTvsRn -> TcM a -> TcM ([TyVar], a)
bindImplicitTKBndrs_Q_Tv HsQTvsRn
XHsQTvs GhcRn
kv_ns            (TcM ([TyVar], Type) -> TcM ([TyVar], ([TyVar], Type)))
-> TcM ([TyVar], Type) -> TcM ([TyVar], ([TyVar], Type))
forall a b. (a -> b) -> a -> b
$
              ContextKind
-> [LHsTyVarBndr () GhcRn] -> TcM Type -> TcM ([TyVar], Type)
forall a.
ContextKind -> [LHsTyVarBndr () GhcRn] -> TcM a -> TcM ([TyVar], a)
bindExplicitTKBndrs_Q_Tv ContextKind
ctxt_kind [LHsTyVarBndr () GhcRn]
hs_tvs (TcM Type -> TcM ([TyVar], Type))
-> TcM Type -> TcM ([TyVar], 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_binders :: [TyConBinder]
tc_binders = AnonArgFlag -> [TyVar] -> [TyConBinder]
mkAnonTyConBinders AnonArgFlag
VisArg [TyVar]
tc_tvs
               -- Also, note that tc_binders has the tyvars from only the
               -- user-written tyvarbinders. See S1 in Note [How TcTyCons work]
               -- in GHC.Tc.TyCl
               --
               -- mkAnonTyConBinder: see Note [No polymorphic recursion]

             all_tv_prs :: [(Name, TyVar)]
all_tv_prs = [TyVar] -> [(Name, TyVar)]
mkTyVarNamePairs ([TyVar]
scoped_kvs [TyVar] -> [TyVar] -> [TyVar]
forall a. [a] -> [a] -> [a]
++ [TyVar]
tc_tvs)
               -- NB: bindExplicitTKBndrs_Q_Tv does not clone;
               --     ditto Implicit
               -- See Note [Non-cloning for tyvar binders]

             tycon :: TyCon
tycon = Name
-> [TyConBinder]
-> Type
-> [(Name, TyVar)]
-> Bool
-> TyConFlavour
-> TyCon
mkTcTyCon Name
name [TyConBinder]
tc_binders Type
res_kind [(Name, TyVar)]
all_tv_prs
                               Bool
False -- not yet generalised
                               TyConFlavour
flav

       ; String -> MsgDoc -> TcM ()
traceTc String
"kcInferDeclHeader: not-cusk" (MsgDoc -> TcM ()) -> MsgDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [MsgDoc] -> MsgDoc
vcat [ Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name, HsQTvsRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsQTvsRn
XHsQTvs GhcRn
kv_ns, [LHsTyVarBndr () GhcRn] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [LHsTyVarBndr () GhcRn]
hs_tvs
              , [TyVar] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [TyVar]
scoped_kvs
              , [TyVar] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [TyVar]
tc_tvs, Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr ([TyConBinder] -> Type -> Type
mkTyConKind [TyConBinder]
tc_binders Type
res_kind) ]
       ; TyCon -> TcM TyCon
forall (m :: * -> *) a. Monad m => a -> m a
return TyCon
tycon }
  where
    ctxt_kind :: ContextKind
ctxt_kind | TyConFlavour -> Bool
tcFlavourIsOpen TyConFlavour
flav = Type -> ContextKind
TheKind Type
liftedTypeKind
              | Bool
otherwise            = ContextKind
AnyKind

-- | Kind-check a declaration header against a standalone kind signature.
-- See Note [Arity inference in kcCheckDeclHeader_sig]
kcCheckDeclHeader_sig
  :: Kind              -- ^ Standalone kind signature, fully zonked! (zonkTcTypeToType)
  -> Name              -- ^ of the thing being checked
  -> TyConFlavour      -- ^ What sort of 'TyCon' is being checked
  -> LHsQTyVars GhcRn  -- ^ Binders in the header
  -> TcM ContextKind   -- ^ The result kind. AnyKind == no result signature
  -> TcM TcTyCon       -- ^ A suitably-kinded TcTyCon
kcCheckDeclHeader_sig :: Type
-> Name
-> TyConFlavour
-> LHsQTyVars GhcRn
-> TcM ContextKind
-> TcM TyCon
kcCheckDeclHeader_sig Type
kisig Name
name TyConFlavour
flav
          (HsQTvs { hsq_ext :: forall pass. LHsQTyVars pass -> XHsQTvs pass
hsq_ext      = XHsQTvs GhcRn
implicit_nms
                  , hsq_explicit :: forall pass. LHsQTyVars pass -> [LHsTyVarBndr () pass]
hsq_explicit = [LHsTyVarBndr () GhcRn]
explicit_nms }) TcM ContextKind
kc_res_ki
  = Name -> TyConFlavour -> TcM TyCon -> TcM TyCon
forall a. Name -> TyConFlavour -> TcM a -> TcM a
addTyConFlavCtxt Name
name TyConFlavour
flav (TcM TyCon -> TcM TyCon) -> TcM TyCon -> TcM TyCon
forall a b. (a -> b) -> a -> b
$
    do {  -- Step 1: zip user-written binders with quantifiers from the kind signature.
          -- For example:
          --
          --   type F :: forall k -> k -> forall j. j -> Type
          --   data F i a b = ...
          --
          -- Results in the following 'zipped_binders':
          --
          --                   TyBinder      LHsTyVarBndr
          --    ---------------------------------------
          --    ZippedBinder   forall k ->   i
          --    ZippedBinder   k ->          a
          --    ZippedBinder   forall j.
          --    ZippedBinder   j ->          b
          --
          let ([ZippedBinder]
zipped_binders, [LHsTyVarBndr () GhcRn]
excess_bndrs, Type
kisig') = Type
-> [LHsTyVarBndr () GhcRn]
-> ([ZippedBinder], [LHsTyVarBndr () GhcRn], Type)
zipBinders Type
kisig [LHsTyVarBndr () GhcRn]
explicit_nms

          -- Report binders that don't have a corresponding quantifier.
          -- For example:
          --
          --   type T :: Type -> Type
          --   data T b1 b2 b3 = ...
          --
          -- Here, b1 is zipped with Type->, while b2 and b3 are excess binders.
          --
        ; Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([LHsTyVarBndr () GhcRn] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [LHsTyVarBndr () GhcRn]
excess_bndrs) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$ MsgDoc -> TcM ()
forall a. MsgDoc -> TcM a
failWithTc (Type -> [LHsTyVarBndr () GhcRn] -> MsgDoc
tooManyBindersErr Type
kisig' [LHsTyVarBndr () GhcRn]
excess_bndrs)

          -- Convert each ZippedBinder to TyConBinder        for  tyConBinders
          --                       and to [(Name, TcTyVar)]  for  tcTyConScopedTyVars
        ; ([TyConBinder]
vis_tcbs, [[(Name, TyVar)]] -> [(Name, TyVar)]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat -> [(Name, TyVar)]
explicit_tv_prs) <- (ZippedBinder
 -> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)]))
-> [ZippedBinder]
-> IOEnv (Env TcGblEnv TcLclEnv) ([TyConBinder], [[(Name, TyVar)]])
forall (m :: * -> *) a b c.
Applicative m =>
(a -> m (b, c)) -> [a] -> m ([b], [c])
mapAndUnzipM ZippedBinder
-> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)])
zipped_to_tcb [ZippedBinder]
zipped_binders

        ; ([TyVar]
implicit_tvs, ([TyBinder]
invis_binders, Type
r_ki))
             <- TcM ([TyVar], ([TyBinder], Type))
-> TcM ([TyVar], ([TyBinder], Type))
forall a. TcM a -> TcM a
pushTcLevelM_ (TcM ([TyVar], ([TyBinder], Type))
 -> TcM ([TyVar], ([TyBinder], Type)))
-> TcM ([TyVar], ([TyBinder], Type))
-> TcM ([TyVar], ([TyBinder], Type))
forall a b. (a -> b) -> a -> b
$
                TcM ([TyVar], ([TyBinder], Type))
-> TcM ([TyVar], ([TyBinder], Type))
forall a. TcM a -> TcM a
solveEqualities (TcM ([TyVar], ([TyBinder], Type))
 -> TcM ([TyVar], ([TyBinder], Type)))
-> TcM ([TyVar], ([TyBinder], Type))
-> TcM ([TyVar], ([TyBinder], Type))
forall a b. (a -> b) -> a -> b
$  -- #16687
                HsQTvsRn
-> TcM ([TyBinder], Type) -> TcM ([TyVar], ([TyBinder], Type))
forall a. HsQTvsRn -> TcM a -> TcM ([TyVar], a)
bindImplicitTKBndrs_Tv HsQTvsRn
XHsQTvs GhcRn
implicit_nms (TcM ([TyBinder], Type) -> TcM ([TyVar], ([TyBinder], Type)))
-> TcM ([TyBinder], Type) -> TcM ([TyVar], ([TyBinder], Type))
forall a b. (a -> b) -> a -> b
$
                [(Name, TyVar)] -> TcM ([TyBinder], Type) -> TcM ([TyBinder], Type)
forall r. [(Name, TyVar)] -> TcM r -> TcM r
tcExtendNameTyVarEnv [(Name, TyVar)]
explicit_tv_prs  (TcM ([TyBinder], Type) -> TcM ([TyBinder], Type))
-> TcM ([TyBinder], Type) -> TcM ([TyBinder], Type)
forall a b. (a -> b) -> a -> b
$
                do { -- Check that inline kind annotations on binders are valid.
                     -- For example:
                     --
                     --   type T :: Maybe k -> Type
                     --   data T (a :: Maybe j) = ...
                     --
                     -- Here we unify   Maybe k ~ Maybe j
                     (ZippedBinder -> TcM ()) -> [ZippedBinder] -> TcM ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ ZippedBinder -> TcM ()
check_zipped_binder [ZippedBinder]
zipped_binders

                     -- 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
ctx_k <- TcM ContextKind
kc_res_ki
                   ; Maybe Type
m_res_ki <- case ContextKind
ctx_k of
                                  ContextKind
AnyKind -> Maybe Type -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Type
forall a. Maybe a
Nothing
                                  ContextKind
_ -> Type -> Maybe Type
forall a. a -> Maybe a
Just (Type -> Maybe Type)
-> TcM Type -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ContextKind -> TcM Type
newExpectedKind ContextKind
ctx_k

                     -- Step 2: split off invisible binders.
                     -- For example:
                     --
                     --   type F :: forall k1 k2. (k1, k2) -> Type
                     --   type family F
                     --
                     -- Does 'forall k1 k2' become a part of 'tyConBinders' or 'tyConResKind'?
                     -- See Note [Arity inference in kcCheckDeclHeader_sig]
                   ; let ([TyBinder]
invis_binders, Type
r_ki) = Type -> Maybe Type -> ([TyBinder], Type)
split_invis Type
kisig' Maybe Type
m_res_ki

                     -- Check that the inline result kind annotation is valid.
                     -- For example:
                     --
                     --   type T :: Type -> Maybe k
                     --   type family T a :: Maybe j where
                     --
                     -- Here we unify   Maybe k ~ Maybe j
                   ; Maybe Type -> (Type -> TcM ()) -> TcM ()
forall (m :: * -> *) a. Monad m => Maybe a -> (a -> m ()) -> m ()
whenIsJust Maybe Type
m_res_ki ((Type -> TcM ()) -> TcM ()) -> (Type -> TcM ()) -> TcM ()
forall a b. (a -> b) -> a -> b
$ \Type
res_ki ->
                      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 (HsType GhcRn) -> Type -> Type -> TcM Coercion
unifyKind Maybe (HsType GhcRn)
forall a. Maybe a
Nothing Type
r_ki Type
res_ki

                   ; ([TyBinder], Type) -> TcM ([TyBinder], Type)
forall (m :: * -> *) a. Monad m => a -> m a
return ([TyBinder]
invis_binders, Type
r_ki) }

        -- Zonk the implicitly quantified variables.
        ; [TyVar]
implicit_tvs <- (TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar)
-> [TyVar] -> TcM [TyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM HasDebugCallStack => TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTcTyVarToTyVar [TyVar]
implicit_tvs

        -- Convert each invisible TyCoBinder to TyConBinder for tyConBinders.
        ; [TyConBinder]
invis_tcbs <- (TyBinder -> IOEnv (Env TcGblEnv TcLclEnv) TyConBinder)
-> [TyBinder] -> IOEnv (Env TcGblEnv TcLclEnv) [TyConBinder]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TyBinder -> IOEnv (Env TcGblEnv TcLclEnv) TyConBinder
invis_to_tcb [TyBinder]
invis_binders

        -- Build the final, generalized TcTyCon
        ; let tcbs :: [TyConBinder]
tcbs            = [TyConBinder]
vis_tcbs [TyConBinder] -> [TyConBinder] -> [TyConBinder]
forall a. [a] -> [a] -> [a]
++ [TyConBinder]
invis_tcbs
              implicit_tv_prs :: [(Name, TyVar)]
implicit_tv_prs = HsQTvsRn
XHsQTvs GhcRn
implicit_nms HsQTvsRn -> [TyVar] -> [(Name, TyVar)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [TyVar]
implicit_tvs
              all_tv_prs :: [(Name, TyVar)]
all_tv_prs      = [(Name, TyVar)]
implicit_tv_prs [(Name, TyVar)] -> [(Name, TyVar)] -> [(Name, TyVar)]
forall a. [a] -> [a] -> [a]
++ [(Name, TyVar)]
explicit_tv_prs
              tc :: TyCon
tc = Name
-> [TyConBinder]
-> Type
-> [(Name, TyVar)]
-> Bool
-> TyConFlavour
-> TyCon
mkTcTyCon Name
name [TyConBinder]
tcbs Type
r_ki [(Name, TyVar)]
all_tv_prs Bool
True TyConFlavour
flav

        ; String -> MsgDoc -> TcM ()
traceTc String
"kcCheckDeclHeader_sig done:" (MsgDoc -> TcM ()) -> MsgDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$ [MsgDoc] -> MsgDoc
vcat
          [ String -> MsgDoc
text String
"tyConName = " MsgDoc -> MsgDoc -> MsgDoc
<+> Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (TyCon -> Name
tyConName TyCon
tc)
          , String -> MsgDoc
text String
"kisig =" MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
debugPprType Type
kisig
          , String -> MsgDoc
text String
"tyConKind =" MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
debugPprType (TyCon -> Type
tyConKind TyCon
tc)
          , String -> MsgDoc
text String
"tyConBinders = " MsgDoc -> MsgDoc -> MsgDoc
<+> [TyConBinder] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (TyCon -> [TyConBinder]
tyConBinders TyCon
tc)
          , String -> MsgDoc
text String
"tcTyConScopedTyVars" MsgDoc -> MsgDoc -> MsgDoc
<+> [(Name, TyVar)] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (TyCon -> [(Name, TyVar)]
tcTyConScopedTyVars TyCon
tc)
          , String -> MsgDoc
text String
"tyConResKind" MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
debugPprType (TyCon -> Type
tyConResKind TyCon
tc)
          ]
        ; TyCon -> TcM TyCon
forall (m :: * -> *) a. Monad m => a -> m a
return TyCon
tc }
  where
    -- Consider this declaration:
    --
    --    type T :: forall a. forall b -> (a~b) => Proxy a -> Type
    --    data T x p = MkT
    --
    -- Here, we have every possible variant of ZippedBinder:
    --
    --                   TyBinder           LHsTyVarBndr
    --    ----------------------------------------------
    --    ZippedBinder   forall {k}.
    --    ZippedBinder   forall (a::k).
    --    ZippedBinder   forall (b::k) ->   x
    --    ZippedBinder   (a~b) =>
    --    ZippedBinder   Proxy a ->         p
    --
    -- Given a ZippedBinder zipped_to_tcb produces:
    --
    --  * TyConBinder      for  tyConBinders
    --  * (Name, TcTyVar)  for  tcTyConScopedTyVars, if there's a user-written LHsTyVarBndr
    --
    zipped_to_tcb :: ZippedBinder -> TcM (TyConBinder, [(Name, TcTyVar)])
    zipped_to_tcb :: ZippedBinder
-> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)])
zipped_to_tcb ZippedBinder
zb = case ZippedBinder
zb of

      -- Inferred variable, no user-written binder.
      -- Example:   forall {k}.
      ZippedBinder (Named (Bndr TyVar
v ArgFlag
Specified)) Maybe (LHsTyVarBndr () GhcRn)
Nothing ->
        (TyConBinder, [(Name, TyVar)])
-> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)])
forall (m :: * -> *) a. Monad m => a -> m a
return (ArgFlag -> TyVar -> TyConBinder
mkNamedTyConBinder ArgFlag
Specified TyVar
v, [])

      -- Specified variable, no user-written binder.
      -- Example:   forall (a::k).
      ZippedBinder (Named (Bndr TyVar
v ArgFlag
Inferred)) Maybe (LHsTyVarBndr () GhcRn)
Nothing ->
        (TyConBinder, [(Name, TyVar)])
-> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)])
forall (m :: * -> *) a. Monad m => a -> m a
return (ArgFlag -> TyVar -> TyConBinder
mkNamedTyConBinder ArgFlag
Inferred TyVar
v, [])

      -- Constraint, no user-written binder.
      -- Example:   (a~b) =>
      ZippedBinder (Anon AnonArgFlag
InvisArg Scaled Type
bndr_ki) Maybe (LHsTyVarBndr () GhcRn)
Nothing -> do
        Name
name <- OccName -> TcM Name
forall gbl lcl. OccName -> TcRnIf gbl lcl Name
newSysName (FastString -> OccName
mkTyVarOccFS (String -> FastString
fsLit String
"ev"))
        let tv :: TyVar
tv = Name -> Type -> TyVar
mkTyVar Name
name (Scaled Type -> Type
forall a. Scaled a -> a
scaledThing Scaled Type
bndr_ki)
        (TyConBinder, [(Name, TyVar)])
-> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)])
forall (m :: * -> *) a. Monad m => a -> m a
return (AnonArgFlag -> TyVar -> TyConBinder
mkAnonTyConBinder AnonArgFlag
InvisArg TyVar
tv, [])

      -- Non-dependent visible argument with a user-written binder.
      -- Example:   Proxy a ->
      ZippedBinder (Anon AnonArgFlag
VisArg Scaled Type
bndr_ki) (Just LHsTyVarBndr () GhcRn
b) ->
        (TyConBinder, [(Name, TyVar)])
-> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)])
forall (m :: * -> *) a. Monad m => a -> m a
return ((TyConBinder, [(Name, TyVar)])
 -> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)]))
-> (TyConBinder, [(Name, TyVar)])
-> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)])
forall a b. (a -> b) -> a -> b
$
          let v_name :: Name
v_name = LHsTyVarBndr () GhcRn -> Name
forall a. NamedThing a => a -> Name
getName LHsTyVarBndr () GhcRn
b
              tv :: TyVar
tv = Name -> Type -> TyVar
mkTyVar Name
v_name (Scaled Type -> Type
forall a. Scaled a -> a
scaledThing Scaled Type
bndr_ki)
              tcb :: TyConBinder
tcb = AnonArgFlag -> TyVar -> TyConBinder
mkAnonTyConBinder AnonArgFlag
VisArg TyVar
tv
          in (TyConBinder
tcb, [(Name
v_name, TyVar
tv)])

      -- Dependent visible argument with a user-written binder.
      -- Example:   forall (b::k) ->
      ZippedBinder (Named (Bndr TyVar
v ArgFlag
Required)) (Just LHsTyVarBndr () GhcRn
b) ->
        (TyConBinder, [(Name, TyVar)])
-> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)])
forall (m :: * -> *) a. Monad m => a -> m a
return ((TyConBinder, [(Name, TyVar)])
 -> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)]))
-> (TyConBinder, [(Name, TyVar)])
-> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)])
forall a b. (a -> b) -> a -> b
$
          let v_name :: Name
v_name = LHsTyVarBndr () GhcRn -> Name
forall a. NamedThing a => a -> Name
getName LHsTyVarBndr () GhcRn
b
              tcb :: TyConBinder
tcb = ArgFlag -> TyVar -> TyConBinder
mkNamedTyConBinder ArgFlag
Required TyVar
v
          in (TyConBinder
tcb, [(Name
v_name, TyVar
v)])

      -- 'zipBinders' does not produce any other variants of ZippedBinder.
      ZippedBinder
_ -> String
-> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)])
forall a. String -> a
panic String
"goVis: invalid ZippedBinder"

    -- Given an invisible binder that comes from 'split_invis',
    -- convert it to TyConBinder.
    invis_to_tcb :: TyCoBinder -> TcM TyConBinder
    invis_to_tcb :: TyBinder -> IOEnv (Env TcGblEnv TcLclEnv) TyConBinder
invis_to_tcb TyBinder
tb = do
      (TyConBinder
tcb, [(Name, TyVar)]
stv) <- ZippedBinder
-> IOEnv (Env TcGblEnv TcLclEnv) (TyConBinder, [(Name, TyVar)])
zipped_to_tcb (TyBinder -> Maybe (LHsTyVarBndr () GhcRn) -> ZippedBinder
ZippedBinder TyBinder
tb Maybe (LHsTyVarBndr () GhcRn)
forall a. Maybe a
Nothing)
      MASSERT(null stv)
      TyConBinder -> IOEnv (Env TcGblEnv TcLclEnv) TyConBinder
forall (m :: * -> *) a. Monad m => a -> m a
return TyConBinder
tcb

    -- Check that the inline kind annotation on a binder is valid
    -- by unifying it with the kind of the quantifier.
    check_zipped_binder :: ZippedBinder -> TcM ()
    check_zipped_binder :: ZippedBinder -> TcM ()
check_zipped_binder (ZippedBinder TyBinder
_ Maybe (LHsTyVarBndr () GhcRn)
Nothing) = () -> TcM ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    check_zipped_binder (ZippedBinder TyBinder
tb (Just LHsTyVarBndr () GhcRn
b)) =
      case LHsTyVarBndr () GhcRn -> HsTyVarBndr () GhcRn
forall l e. GenLocated l e -> e
unLoc LHsTyVarBndr () GhcRn
b of
        UserTyVar XUserTyVar GhcRn
_ ()
_ GenLocated SrcSpan (IdP GhcRn)
_ -> () -> TcM ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
        KindedTyVar XKindedTyVar GhcRn
_ ()
_ GenLocated SrcSpan (IdP GhcRn)
v LHsKind GhcRn
v_hs_ki -> do
          Type
v_ki <- UserTypeCtxt -> LHsKind GhcRn -> TcM Type
tcLHsKindSig (Name -> UserTypeCtxt
TyVarBndrKindCtxt (Located Name -> Name
forall l e. GenLocated l e -> e
unLoc Located Name
GenLocated SrcSpan (IdP GhcRn)
v)) LHsKind GhcRn
v_hs_ki
          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 (HsType GhcRn) -> Type -> Type -> TcM Coercion
unifyKind (HsType GhcRn -> Maybe (HsType GhcRn)
forall a. a -> Maybe a
Just (XTyVar GhcRn
-> PromotionFlag -> GenLocated SrcSpan (IdP GhcRn) -> HsType GhcRn
forall pass.
XTyVar pass -> PromotionFlag -> Located (IdP pass) -> HsType pass
HsTyVar NoExtField
XTyVar GhcRn
noExtField PromotionFlag
NotPromoted GenLocated SrcSpan (IdP GhcRn)
v))
                      (TyBinder -> Type
tyBinderType TyBinder
tb)
                      Type
v_ki

    -- Split the invisible binders that should become a part of 'tyConBinders'
    -- rather than 'tyConResKind'.
    -- See Note [Arity inference in kcCheckDeclHeader_sig]
    split_invis :: Kind -> Maybe Kind -> ([TyCoBinder], Kind)
    split_invis :: Type -> Maybe Type -> ([TyBinder], Type)
split_invis Type
sig_ki Maybe Type
Nothing =
      -- instantiate all invisible binders
      Type -> ([TyBinder], Type)
splitPiTysInvisible Type
sig_ki
    split_invis Type
sig_ki (Just Type
res_ki) =
      -- subtraction a la checkExpectedKind
      let n_res_invis_bndrs :: Arity
n_res_invis_bndrs = Type -> Arity
invisibleTyBndrCount Type
res_ki
          n_sig_invis_bndrs :: Arity
n_sig_invis_bndrs = Type -> Arity
invisibleTyBndrCount Type
sig_ki
          n_inst :: Arity
n_inst = Arity
n_sig_invis_bndrs Arity -> Arity -> Arity
forall a. Num a => a -> a -> a