TcHsType.hs 88.4 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998

5
\section[TcMonoType]{Typechecking user-specified @MonoTypes@}
Austin Seipp's avatar
Austin Seipp committed
6
-}
7

8
{-# LANGUAGE CPP, TupleSections, MultiWayIf #-}
Ian Lynagh's avatar
Ian Lynagh committed
9

10
module TcHsType (
11
        -- Type signatures
Alan Zimmerman's avatar
Alan Zimmerman committed
12
        kcHsSigType, tcClassSigType,
13
        tcHsSigType, tcHsSigWcType,
14 15
        tcHsPartialSigType,
        funsSigCtxt, addSigCtxt, pprSigCtxt,
16 17 18

        tcHsClsInstType,
        tcHsDeriv, tcHsVectInst,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
19
        tcHsTypeApp,
20
        UserTypeCtxt(..),
21
        tcImplicitTKBndrs, tcImplicitTKBndrsType, tcExplicitTKBndrs,
22

23
                -- Type checking type and class decls
24
        kcLookupTcTyCon, kcTyClTyVars, tcTyClTyVars,
25
        tcDataKindSig,
dreixel's avatar
dreixel committed
26

27 28 29
        -- Kind-checking types
        -- No kind generalisation, no checkValidType
        tcWildCardBinders,
30
        kcHsTyVarBndrs,
31 32 33
        tcHsLiftedType,   tcHsOpenType,
        tcHsLiftedTypeNC, tcHsOpenTypeNC,
        tcLHsType, tcCheckLHsType,
34 35
        tcHsContext, tcLHsPredType, tcInferApps, tcInferArgs,
        solveEqualities, -- useful re-export
batterseapower's avatar
batterseapower committed
36

37
        kindGeneralize,
38

39
        -- Sort-checking kinds
40
        tcLHsKind,
41

42
        -- Pattern type signatures
43
        tcHsPatSigType, tcPatSig, funAppCtxt
44 45 46 47
   ) where

#include "HsVersions.h"

48
import HsSyn
49
import TcRnMonad
50
import TcEvidence
51 52
import TcEnv
import TcMType
53
import TcValidity
54 55
import TcUnify
import TcIface
56
import TcSimplify ( solveEqualities )
57
import TcType
58
import TcHsSyn( zonkSigType )
59
import Inst   ( tcInstBinders, tcInstBindersX, tcInstBinderX )
60
import Type
dreixel's avatar
dreixel committed
61
import Kind
62
import RdrName( lookupLocalRdrOcc )
63
import Var
64
import VarSet
65
import TyCon
cactus's avatar
cactus committed
66
import ConLike
67
import DataCon
68 69
import Class
import Name
70
import NameEnv
71 72
import NameSet
import VarEnv
73 74 75
import TysWiredIn
import BasicTypes
import SrcLoc
76 77
import Constants ( mAX_CTUPLE_SIZE )
import ErrUtils( MsgDoc )
78
import Unique
79
import Util
80
import UniqSupply
81
import Outputable
82
import FastString
83
import PrelNames hiding ( wildCardName )
84
import qualified GHC.LanguageExtensions as LangExt
85

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
86
import Maybes
87
import Data.List ( partition, zipWith4 )
88
import Control.Monad
89

Austin Seipp's avatar
Austin Seipp committed
90
{-
91 92 93
        ----------------------------
                General notes
        ----------------------------
94

95 96 97 98 99
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.
100

101 102 103 104 105 106 107
During type-checking, we perform as little validity checking as possible.
This is because some type-checking is done in a mutually-recursive knot, and
if we look too closely at the tycons, we'll loop. This is why we always must
use mkNakedTyConApp and mkNakedAppTys, etc., which never look at a tycon.
The mkNamed... functions don't uphold Type invariants, but zonkTcTypeToType
will repair this for us. Note that zonkTcType *is* safe within a knot, and
can be done repeatedly with no ill effect: it just squeezes out metavariables.
108

109 110
Generally, after type-checking, you will want to do validity checking, say
with TcValidity.checkValidType.
111 112 113

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

- During desugaring, we normalise by expanding type synonyms.  Only
  after this step can we check things like type-synonym saturation
119 120
  e.g.  type T k = k Int
        type S a = a
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
  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, and it's easier to wait
  until knots have been resolved before poking into them

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).

Knot tying
~~~~~~~~~~
During step (1) we might fault in a TyCon defined in another module, and it might
(via a loop) refer back to a TyCon defined in this module. So when we tie a big
knot around type declarations with ARecThing, so that the fault-in code can get
the TyCon being defined.

141 142
%************************************************************************
%*                                                                      *
143
              Check types AND do validity checking
Austin Seipp's avatar
Austin Seipp committed
144 145 146
*                                                                      *
************************************************************************
-}
147

148 149 150 151 152 153 154
funsSigCtxt :: [Located Name] -> UserTypeCtxt
-- Returns FunSigCtxt, with no redundant-context-reporting,
-- form a list of located names
funsSigCtxt (L _ name1 : _) = FunSigCtxt name1 False
funsSigCtxt []              = panic "funSigCtxt"

addSigCtxt :: UserTypeCtxt -> LHsType Name -> TcM a -> TcM a
155 156 157
addSigCtxt ctxt hs_ty thing_inside
  = setSrcSpan (getLoc hs_ty) $
    addErrCtxt (pprSigCtxt ctxt hs_ty) $
158 159
    thing_inside

160 161 162 163 164 165 166 167 168 169 170 171 172 173
pprSigCtxt :: UserTypeCtxt -> LHsType Name -> 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 ctxt hs_ty
  | Just n <- isSigMaybe ctxt
  = hang (text "In the type signature:")
       2 (pprPrefixOcc n <+> dcolon <+> ppr hs_ty)

  | otherwise
  = hang (text "In" <+> pprUserTypeCtxt ctxt <> colon)
       2 (ppr hs_ty)

174 175 176
tcHsSigWcType :: UserTypeCtxt -> LHsSigWcType Name -> TcM Type
-- This one is used when we have a LHsSigWcType, but in
-- a place where wildards aren't allowed. The renamer has
Gabor Greif's avatar
Gabor Greif committed
177
-- already checked this, so we can simply ignore it.
178 179
tcHsSigWcType ctxt sig_ty = tcHsSigType ctxt (dropWildCards sig_ty)

Alan Zimmerman's avatar
Alan Zimmerman committed
180 181
kcHsSigType :: [Located Name] -> LHsSigType Name -> TcM ()
kcHsSigType names (HsIB { hsib_body = hs_ty
182
                        , hsib_vars = sig_vars })
183
  = addSigCtxt (funsSigCtxt names) hs_ty $
184 185 186
    discardResult $
    tcImplicitTKBndrsType sig_vars $
    tc_lhs_type typeLevelMode hs_ty liftedTypeKind
187 188 189 190 191 192

tcClassSigType :: [Located Name] -> LHsSigType Name -> TcM Type
-- Does not do validity checking; this must be done outside
-- the recursive class declaration "knot"
tcClassSigType names sig_ty
  = addSigCtxt (funsSigCtxt names) (hsSigType sig_ty) $
193 194
    do { ty <- tc_hs_sig_type sig_ty liftedTypeKind
       ; kindGeneralizeType ty }
195 196 197 198 199 200

tcHsSigType :: UserTypeCtxt -> LHsSigType Name -> TcM Type
-- Does validity checking
tcHsSigType ctxt sig_ty
  = addSigCtxt ctxt (hsSigType sig_ty) $
    do { kind <- case expectedKindInCtxt ctxt of
201 202
                    AnythingKind -> newMetaKindVar
                    TheKind k    -> return k
203
                    OpenKind     -> newOpenTypeKind
204 205 206 207
              -- The kind is checked by checkValidType, and isn't necessarily
              -- of kind * in a Template Haskell quote eg [t| Maybe |]

       ; ty <- tc_hs_sig_type sig_ty kind
208

209
          -- Generalise here: see Note [Kind generalisation]
210 211 212 213 214
       ; do_kind_gen <- decideKindGeneralisationPlan ty
       ; ty <- if do_kind_gen
               then kindGeneralizeType ty
               else zonkTcType ty

215 216 217 218
       ; checkValidType ctxt ty
       ; return ty }

tc_hs_sig_type :: LHsSigType Name -> Kind -> TcM Type
219
-- Does not do validity checking or zonking
220
tc_hs_sig_type (HsIB { hsib_body = hs_ty
221 222 223 224
                     , hsib_vars = sig_vars }) kind
  = do { (tkvs, ty) <- solveEqualities $
                       tcImplicitTKBndrsType sig_vars $
                       tc_lhs_type typeLevelMode hs_ty kind
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
225
       ; return (mkSpecForAllTys tkvs ty) }
batterseapower's avatar
batterseapower committed
226

227
-----------------
228
tcHsDeriv :: LHsSigType Name -> TcM ([TyVar], Class, [Type], [Kind])
229
-- Like tcHsSigType, but for the ...deriving( C t1 ty2 ) clause
230
-- Returns the C, [ty1, ty2, and the kinds of C's remaining arguments
231 232
-- E.g.    class C (a::*) (b::k->k)
--         data T a b = ... deriving( C Int )
233
--    returns ([k], C, [k, Int], [k->k])
234
tcHsDeriv hs_ty
235
  = do { cls_kind <- newMetaKindVar
236 237 238 239
                    -- always safe to kind-generalize, because there
                    -- can be no covars in an outer scope
       ; ty <- checkNoErrs $
                 -- avoid redundant error report with "illegal deriving", below
240
               tc_hs_sig_type hs_ty cls_kind
241
       ; ty <- kindGeneralizeType ty  -- also zonks
242
       ; cls_kind <- zonkTcType cls_kind
243
       ; let (tvs, pred) = splitForAllTys ty
244
       ; let (args, _) = splitFunTys cls_kind
245
       ; case getClassPredTys_maybe pred of
246
           Just (cls, tys) -> return (tvs, cls, tys, args)
247
           Nothing -> failWithTc (text "Illegal deriving item" <+> quotes (ppr hs_ty)) }
248

249 250 251 252
tcHsClsInstType :: UserTypeCtxt    -- InstDeclCtxt or SpecInstCtxt
                -> LHsSigType Name
                -> TcM ([TyVar], ThetaType, Class, [Type])
-- Like tcHsSigType, but for a class instance declaration
253 254 255
tcHsClsInstType user_ctxt hs_inst_ty
  = setSrcSpan (getLoc (hsSigType hs_inst_ty)) $
    do { inst_ty <- tc_hs_sig_type hs_inst_ty constraintKind
256 257 258
       ; inst_ty <- kindGeneralizeType inst_ty
       ; checkValidInstance user_ctxt hs_inst_ty inst_ty }

259
-- Used for 'VECTORISE [SCALAR] instance' declarations
260
tcHsVectInst :: LHsSigType Name -> TcM (Class, [Type])
261
tcHsVectInst ty
262
  | Just (L _ cls_name, tys) <- hsTyGetAppHead_maybe (hsSigType ty)
263
    -- Ignoring the binders looks pretty dodgy to me
264
  = do { (cls, cls_kind) <- tcClass cls_name
265 266 267 268 269 270
       ; (applied_class, _res_kind)
           <- tcInferApps typeLevelMode cls_name (mkClassPred cls []) cls_kind tys
       ; case tcSplitTyConApp_maybe applied_class of
           Just (_tc, args) -> ASSERT( _tc == classTyCon cls )
                               return (cls, args)
           _ -> failWithTc (text "Too many arguments passed to" <+> ppr cls_name) }
271
  | otherwise
272
  = failWithTc $ text "Malformed instance type"
273

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
274 275 276 277
----------------------------------------------
-- | Type-check a visible type application
tcHsTypeApp :: LHsWcType Name -> Kind -> TcM Type
tcHsTypeApp wc_ty kind
278 279 280 281
  | HsWC { hswc_wcs = sig_wcs, hswc_body = hs_ty } <- wc_ty
  = do { ty <- solveEqualities $
               tcWildCardBindersX newWildTyVar sig_wcs $ \ _ ->
               tcCheckLHsType hs_ty kind
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
282 283 284 285 286 287 288
       ; ty <- zonkTcType ty
       ; checkValidType TypeAppCtxt ty
       ; return ty }
        -- NB: we don't call emitWildcardHoleConstraints here, because
        -- we want any holes in visible type applications to be used
        -- without fuss. No errors, warnings, extensions, etc.

Austin Seipp's avatar
Austin Seipp committed
289 290 291
{-
************************************************************************
*                                                                      *
292
            The main kind checker: no validity checks here
293 294
%*                                                                      *
%************************************************************************
295 296

        First a couple of simple wrappers for kcHsType
Austin Seipp's avatar
Austin Seipp committed
297
-}
298

dreixel's avatar
dreixel committed
299
---------------------------
300 301
tcHsOpenType, tcHsLiftedType,
  tcHsOpenTypeNC, tcHsLiftedTypeNC :: LHsType Name -> TcM TcType
302 303
-- Used for type signatures
-- Do not do validity checking
304 305 306
tcHsOpenType ty   = addTypeCtxt ty $ tcHsOpenTypeNC ty
tcHsLiftedType ty = addTypeCtxt ty $ tcHsLiftedTypeNC ty

307
tcHsOpenTypeNC   ty = do { ek <- newOpenTypeKind
308 309
                         ; tc_lhs_type typeLevelMode ty ek }
tcHsLiftedTypeNC ty = tc_lhs_type typeLevelMode ty liftedTypeKind
310 311 312 313

-- Like tcHsType, but takes an expected kind
tcCheckLHsType :: LHsType Name -> Kind -> TcM Type
tcCheckLHsType hs_ty exp_kind
314
  = addTypeCtxt hs_ty $
315
    tc_lhs_type typeLevelMode hs_ty exp_kind
316 317 318

tcLHsType :: LHsType Name -> TcM (TcType, TcKind)
-- Called from outside: set the context
319
tcLHsType ty = addTypeCtxt ty (tc_infer_lhs_type typeLevelMode ty)
dreixel's avatar
dreixel committed
320

321
---------------------------
322
-- | Should we generalise the kind of this type signature?
Gabor Greif's avatar
Gabor Greif committed
323
-- We *should* generalise if the type mentions no scoped type variables
324 325 326
-- or if NoMonoLocalBinds is set. Otherwise, nope.
decideKindGeneralisationPlan :: Type -> TcM Bool
decideKindGeneralisationPlan ty
327
  = do { mono_locals <- xoptM LangExt.MonoLocalBinds
328 329 330 331 332 333 334 335 336
       ; in_scope <- getInLocalScope
       ; let fvs        = tyCoVarsOfTypeList ty
             should_gen = not mono_locals || all (not . in_scope . getName) fvs
       ; traceTc "decideKindGeneralisationPlan"
           (vcat [ text "type:" <+> ppr ty
                 , text "ftvs:" <+> ppr fvs
                 , text "should gen?" <+> ppr should_gen ])
       ; return should_gen }

Austin Seipp's avatar
Austin Seipp committed
337
{-
338 339 340 341 342 343 344 345 346 347 348 349
************************************************************************
*                                                                      *
      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.

Austin Seipp's avatar
Austin Seipp committed
350
-}
351

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
352 353 354 355 356
-- | 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.
newtype TcTyMode
357 358 359 360 361 362 363 364 365 366 367 368 369
  = TcTyMode { mode_level :: TypeOrKind  -- True <=> type, False <=> kind
             }

typeLevelMode :: TcTyMode
typeLevelMode = TcTyMode { mode_level = TypeLevel }

kindLevelMode :: TcTyMode
kindLevelMode = TcTyMode { mode_level = KindLevel }

-- switch to kind level
kindLevel :: TcTyMode -> TcTyMode
kindLevel mode = mode { mode_level = KindLevel }

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
370 371 372
instance Outputable TcTyMode where
  ppr = ppr . mode_level

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
{-
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 tcInstBinders and tcInstBindersX.

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.
-}
418

419
------------------------------------------
420 421 422 423 424 425
-- | 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 Name -> TcM (TcType, TcKind)
tc_infer_lhs_type mode (L span ty)
  = setSrcSpan span $
426 427
    do { (ty', kind) <- tc_infer_hs_type mode ty
       ; return (ty', kind) }
428 429 430 431

-- | 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 Name -> TcM (TcType, TcKind)
Alan Zimmerman's avatar
Alan Zimmerman committed
432
tc_infer_hs_type mode (HsTyVar _ (L _ tv)) = tcTyVar mode tv
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
tc_infer_hs_type mode (HsAppTy ty1 ty2)
  = do { let (fun_ty, arg_tys) = splitHsAppTys ty1 [ty2]
       ; (fun_ty', fun_kind) <- tc_infer_lhs_type mode fun_ty
       ; fun_kind' <- zonkTcType fun_kind
       ; tcInferApps mode fun_ty fun_ty' fun_kind' arg_tys }
tc_infer_hs_type mode (HsParTy t)     = tc_infer_lhs_type mode t
tc_infer_hs_type mode (HsOpTy lhs (L _ op) rhs)
  | not (op `hasKey` funTyConKey)
  = do { (op', op_kind) <- tcTyVar mode op
       ; op_kind' <- zonkTcType op_kind
       ; tcInferApps mode op op' op_kind' [lhs, rhs] }
tc_infer_hs_type mode (HsKindSig ty sig)
  = do { sig' <- tc_lhs_kind (kindLevel mode) sig
       ; ty' <- tc_lhs_type mode ty sig'
       ; return (ty', sig') }
448 449 450 451 452 453 454 455
-- HsSpliced is an annotation produced by 'RnSplice.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 mode (HsSpliceTy (HsSpliced _ (HsSplicedTy ty)) _)
  = tc_infer_hs_type mode ty
456 457 458 459 460 461 462
tc_infer_hs_type mode (HsDocTy ty _) = tc_infer_lhs_type mode ty
tc_infer_hs_type _    (HsCoreTy ty)  = return (ty, typeKind ty)
tc_infer_hs_type mode other_ty
  = do { kv <- newMetaKindVar
       ; ty' <- tc_hs_type mode other_ty kv
       ; return (ty', kv) }

463
------------------------------------------
464 465
tc_lhs_type :: TcTyMode -> LHsType Name -> TcKind -> TcM TcType
tc_lhs_type mode (L span ty) exp_kind
466
  = setSrcSpan span $
467 468
    do { ty' <- tc_hs_type mode ty exp_kind
       ; return ty' }
469

470
------------------------------------------
471
tc_fun_type :: TcTyMode -> LHsType Name -> LHsType Name -> TcKind -> TcM TcType
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
472 473
tc_fun_type mode ty1 ty2 exp_kind = case mode_level mode of
  TypeLevel ->
474 475 476 477
    do { arg_k <- newOpenTypeKind
       ; res_k <- newOpenTypeKind
       ; ty1' <- tc_lhs_type mode ty1 arg_k
       ; ty2' <- tc_lhs_type mode ty2 res_k
478
       ; checkExpectedKind (mkFunTy ty1' ty2') liftedTypeKind exp_kind }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
479 480 481 482
  KindLevel ->  -- no representation polymorphism in kinds. yet.
    do { ty1' <- tc_lhs_type mode ty1 liftedTypeKind
       ; ty2' <- tc_lhs_type mode ty2 liftedTypeKind
       ; checkExpectedKind (mkFunTy ty1' ty2') liftedTypeKind exp_kind }
483

484
------------------------------------------
485 486 487 488 489
-- See also Note [Bidirectional type checking]
tc_hs_type :: TcTyMode -> HsType Name -> TcKind -> TcM TcType
tc_hs_type mode (HsParTy ty)   exp_kind = tc_lhs_type mode ty exp_kind
tc_hs_type mode (HsDocTy ty _) exp_kind = tc_lhs_type mode ty exp_kind
tc_hs_type _ ty@(HsBangTy {}) _
490 491 492
    -- 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)
493
    = failWithTc (text "Unexpected strictness annotation:" <+> ppr ty)
494
tc_hs_type _ ty@(HsRecTy _)      _
495
      -- Record types (which only show up temporarily in constructor
496
      -- signatures) should have been removed by now
497
    = failWithTc (text "Record syntax is illegal here:" <+> ppr ty)
498

499 500 501 502 503 504 505 506 507 508 509 510
-- HsSpliced is an annotation produced by 'RnSplice.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 mode (HsSpliceTy (HsSpliced mod_finalizers (HsSplicedTy ty))
                            _
                )
           exp_kind
  = do addModFinalizersWithLclEnv mod_finalizers
       tc_hs_type mode ty exp_kind

511 512
-- This should never happen; type splices are expanded by the renamer
tc_hs_type _ ty@(HsSpliceTy {}) _exp_kind
513
  = failWithTc (text "Unexpected type splice:" <+> ppr ty)
514

515 516 517
---------- Functions and applications
tc_hs_type mode (HsFunTy ty1 ty2) exp_kind
  = tc_fun_type mode ty1 ty2 exp_kind
518

519
tc_hs_type mode (HsOpTy ty1 (L _ op) ty2) exp_kind
520
  | op `hasKey` funTyConKey
521
  = tc_fun_type mode ty1 ty2 exp_kind
522 523

--------- Foralls
524
tc_hs_type mode (HsForAllTy { hst_bndrs = hs_tvs, hst_body = ty }) exp_kind
525
  = fmap fst $
526
    tcExplicitTKBndrs hs_tvs $ \ tvs' ->
527
    -- Do not kind-generalise here!  See Note [Kind generalisation]
528
    -- Why exp_kind?  See Note [Body kind of HsForAllTy]
529 530
    do { ty' <- tc_lhs_type mode ty exp_kind
       ; let bound_vars = allBoundVariables ty'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
531
             bndrs      = mkTyVarBinders Specified tvs'
532
       ; return (mkForAllTys bndrs ty', bound_vars) }
533

534
tc_hs_type mode (HsQualTy { hst_ctxt = ctxt, hst_body = ty }) exp_kind
535 536 537 538
  | null (unLoc ctxt)
  = tc_lhs_type mode ty exp_kind

  | otherwise
539
  = do { ctxt' <- tc_hs_context mode ctxt
540 541 542 543

         -- See Note [Body kind of a HsQualTy]
       ; ty' <- if isConstraintKind exp_kind
                then tc_lhs_type mode ty constraintKind
544 545 546
                else do { ek <- newOpenTypeKind
                                -- The body kind (result of the function)
                                -- can be * or #, hence newOpenTypeKind
547 548 549 550
                        ; ty <- tc_lhs_type mode ty ek
                        ; checkExpectedKind ty liftedTypeKind exp_kind }

       ; return (mkPhiTy ctxt' ty') }
551 552 553 554

--------- Lists, arrays, and tuples
tc_hs_type mode (HsListTy elt_ty) exp_kind
  = do { tau_ty <- tc_lhs_type mode elt_ty liftedTypeKind
555
       ; checkWiredInTyCon listTyCon
556
       ; checkExpectedKind (mkListTy tau_ty) liftedTypeKind exp_kind }
557

558 559 560
tc_hs_type mode (HsPArrTy elt_ty) exp_kind
  = do { MASSERT( isTypeLevel (mode_level mode) )
       ; tau_ty <- tc_lhs_type mode elt_ty liftedTypeKind
561
       ; checkWiredInTyCon parrTyCon
562
       ; checkExpectedKind (mkPArrTy tau_ty) liftedTypeKind exp_kind }
563

dreixel's avatar
dreixel committed
564
-- See Note [Distinguishing tuple kinds] in HsTypes
565
-- See Note [Inferring tuple kinds]
566
tc_hs_type mode (HsTupleTy HsBoxedOrConstraintTuple hs_tys) exp_kind
567
     -- (NB: not zonking before looking at exp_k, to avoid left-right bias)
568
  | Just tup_sort <- tupKindSort_maybe exp_kind
569
  = traceTc "tc_hs_type tuple" (ppr hs_tys) >>
570
    tc_tuple mode tup_sort hs_tys exp_kind
dreixel's avatar
dreixel committed
571
  | otherwise
Austin Seipp's avatar
Austin Seipp committed
572
  = do { traceTc "tc_hs_type tuple 2" (ppr hs_tys)
573 574
       ; (tys, kinds) <- mapAndUnzipM (tc_infer_lhs_type mode) hs_tys
       ; kinds <- mapM zonkTcType kinds
575 576 577 578 579 580
           -- Infer each arg type separately, because errors can be
           -- confusing if we give them a shared kind.  Eg Trac #7410
           -- (Either Int, Int), we do not want to get an error saying
           -- "the second argument of a tuple should have kind *->*"

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

587 588 589
       ; tys' <- sequence [ setSrcSpan loc $
                            checkExpectedKind ty kind arg_kind
                          | ((L loc _),ty,kind) <- zip3 hs_tys tys kinds ]
590

591
       ; finish_tuple tup_sort tys' (map (const arg_kind) tys') exp_kind }
592

dreixel's avatar
dreixel committed
593

594 595
tc_hs_type mode (HsTupleTy hs_tup_sort tys) exp_kind
  = tc_tuple mode tup_sort tys exp_kind
596 597 598 599 600 601 602
  where
    tup_sort = case hs_tup_sort of  -- Fourth case dealt with above
                  HsUnboxedTuple    -> UnboxedTuple
                  HsBoxedTuple      -> BoxedTuple
                  HsConstraintTuple -> ConstraintTuple
                  _                 -> panic "tc_hs_type HsTupleTy"

603 604
tc_hs_type mode (HsSumTy hs_tys) exp_kind
  = do { let arity = length hs_tys
605 606
       ; arg_kinds <- mapM (\_ -> newOpenTypeKind) hs_tys
       ; tau_tys   <- zipWithM (tc_lhs_type mode) hs_tys arg_kinds
Richard Eisenberg's avatar
Richard Eisenberg committed
607 608 609 610 611
       ; let arg_reps = map (getRuntimeRepFromKind "tc_hs_type HsSumTy") arg_kinds
             arg_tys  = arg_reps ++ tau_tys
       ; checkExpectedKind (mkTyConApp (sumTyCon arity) arg_tys)
                           (unboxedSumKind arg_reps)
                           exp_kind
612
       }
dreixel's avatar
dreixel committed
613

614
--------- Promoted lists and tuples
Alan Zimmerman's avatar
Alan Zimmerman committed
615
tc_hs_type mode (HsExplicitListTy _ _k tys) exp_kind
616 617 618 619
  = do { tks <- mapM (tc_infer_lhs_type mode) tys
       ; (taus', kind) <- unifyKinds tks
       ; let ty = (foldr (mk_cons kind) (mk_nil kind) taus')
       ; checkExpectedKind ty (mkListTy kind) exp_kind }
620
  where
621 622
    mk_cons k a b = mkTyConApp (promoteDataCon consDataCon) [k, a, b]
    mk_nil  k     = mkTyConApp (promoteDataCon nilDataCon) [k]
623

624
tc_hs_type mode (HsExplicitTupleTy _ tys) exp_kind
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
625 626 627 628 629 630
  -- 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 { ks   <- replicateM arity newMetaKindVar
       ; taus <- zipWithM (tc_lhs_type mode) tys ks
       ; let kind_con   = tupleTyCon           Boxed arity
             ty_con     = promotedTupleDataCon Boxed arity
631
             tup_k      = mkTyConApp kind_con ks
632
       ; checkExpectedKind (mkTyConApp ty_con (ks ++ taus)) tup_k exp_kind }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
633 634
  where
    arity = length tys
635 636

--------- Constraint types
637
tc_hs_type mode (HsIParamTy (L _ n) ty) exp_kind
638 639
  = do { MASSERT( isTypeLevel (mode_level mode) )
       ; ty' <- tc_lhs_type mode ty liftedTypeKind
640
       ; let n' = mkStrLitTy $ hsIPNameFS n
641
       ; ipClass <- tcLookupClass ipClassName
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
       ; checkExpectedKind (mkClassPred ipClass [n',ty'])
           constraintKind exp_kind }

tc_hs_type mode (HsEqTy ty1 ty2) exp_kind
  = do { (ty1', kind1) <- tc_infer_lhs_type mode ty1
       ; (ty2', kind2) <- tc_infer_lhs_type mode ty2
       ; ty2'' <- checkExpectedKind ty2' kind2 kind1
       ; eq_tc <- tcLookupTyCon eqTyConName
       ; let ty' = mkNakedTyConApp eq_tc [kind1, ty1', ty2'']
       ; checkExpectedKind ty' constraintKind exp_kind }

--------- Literals
tc_hs_type _ (HsTyLit (HsNumTy _ n)) exp_kind
  = do { checkWiredInTyCon typeNatKindCon
       ; checkExpectedKind (mkNumLitTy n) typeNatKind exp_kind }

tc_hs_type _ (HsTyLit (HsStrTy _ s)) exp_kind
  = do { checkWiredInTyCon typeSymbolKindCon
       ; checkExpectedKind (mkStrLitTy s) typeSymbolKind exp_kind }

--------- Potentially kind-polymorphic types: call the "up" checker
-- See Note [Future-proofing the type checker]
tc_hs_type mode ty@(HsTyVar {})   ek = tc_infer_hs_type_ek mode ty ek
tc_hs_type mode ty@(HsAppTy {})   ek = tc_infer_hs_type_ek mode ty ek
tc_hs_type mode ty@(HsOpTy {})    ek = tc_infer_hs_type_ek mode ty ek
tc_hs_type mode ty@(HsKindSig {}) ek = tc_infer_hs_type_ek mode ty ek
tc_hs_type mode ty@(HsCoreTy {})  ek = tc_infer_hs_type_ek mode ty ek

tc_hs_type _ (HsWildCardTy wc) exp_kind
671 672
  = do { wc_tv <- tcWildCardOcc wc exp_kind
       ; return (mkTyVarTy wc_tv) }
673 674 675 676 677

-- disposed of by renamer
tc_hs_type _ ty@(HsAppsTy {}) _
  = pprPanic "tc_hs_tyep HsAppsTy" (ppr ty)

678 679 680 681 682 683 684 685
tcWildCardOcc :: HsWildCardInfo Name -> Kind -> TcM TcTyVar
tcWildCardOcc wc_info exp_kind
  = do { wc_tv <- tcLookupTyVar (wildCardName wc_info)
          -- The wildcard's kind should be an un-filled-in meta tyvar
       ; let Just wc_kind_var = tcGetTyVar_maybe (tyVarKind wc_tv)
       ; writeMetaTyVar wc_kind_var exp_kind
       ; return wc_tv }

686 687 688 689 690 691
---------------------------
-- | Call 'tc_infer_hs_type' and check its result against an expected kind.
tc_infer_hs_type_ek :: TcTyMode -> HsType Name -> TcKind -> TcM TcType
tc_infer_hs_type_ek mode ty ek
  = do { (ty', k) <- tc_infer_hs_type mode ty
       ; checkExpectedKind ty' k ek }
thomasw's avatar
thomasw committed
692

693
---------------------------
694
tupKindSort_maybe :: TcKind -> Maybe TupleSort
695
tupKindSort_maybe k
Simon Peyton Jones's avatar
Simon Peyton Jones committed
696 697
  | Just (k', _) <- splitCastTy_maybe k = tupKindSort_maybe k'
  | Just k'      <- coreView k          = tupKindSort_maybe k'
698 699
  | isConstraintKind k = Just ConstraintTuple
  | isLiftedTypeKind k = Just BoxedTuple
700 701
  | otherwise          = Nothing

702 703 704 705
tc_tuple :: TcTyMode -> TupleSort -> [LHsType Name] -> TcKind -> TcM TcType
tc_tuple mode tup_sort tys exp_kind
  = do { arg_kinds <- case tup_sort of
           BoxedTuple      -> return (nOfThem arity liftedTypeKind)
706
           UnboxedTuple    -> mapM (\_ -> newOpenTypeKind) tys
707 708 709
           ConstraintTuple -> return (nOfThem arity constraintKind)
       ; tau_tys <- zipWithM (tc_lhs_type mode) tys arg_kinds
       ; finish_tuple tup_sort tau_tys arg_kinds exp_kind }
dreixel's avatar
dreixel committed
710
  where
711 712 713 714 715 716 717 718 719 720
    arity   = length tys

finish_tuple :: TupleSort
             -> [TcType]    -- ^ argument types
             -> [TcKind]    -- ^ of these kinds
             -> TcKind      -- ^ expected kind of the whole tuple
             -> TcM TcType
finish_tuple tup_sort tau_tys tau_kinds exp_kind
  = do { traceTc "finish_tuple" (ppr res_kind $$ ppr tau_kinds $$ ppr exp_kind)
       ; let arg_tys  = case tup_sort of
721
                   -- See also Note [Unboxed tuple RuntimeRep vars] in TyCon
Richard Eisenberg's avatar
Richard Eisenberg committed
722
                 UnboxedTuple    -> tau_reps ++ tau_tys
723 724
                 BoxedTuple      -> tau_tys
                 ConstraintTuple -> tau_tys
725
       ; tycon <- case tup_sort of
726 727 728 729 730 731 732 733
           ConstraintTuple
             | arity > mAX_CTUPLE_SIZE
                         -> failWith (bigConstraintTuple arity)
             | otherwise -> tcLookupTyCon (cTupleTyConName arity)
           BoxedTuple    -> do { let tc = tupleTyCon Boxed arity
                               ; checkWiredInTyCon tc
                               ; return tc }
           UnboxedTuple  -> return (tupleTyCon Unboxed arity)
734
       ; checkExpectedKind (mkTyConApp tycon arg_tys) res_kind exp_kind }
735
  where
736
    arity = length tau_tys
Richard Eisenberg's avatar
Richard Eisenberg committed
737
    tau_reps = map (getRuntimeRepFromKind "finish_tuple") tau_kinds
738
    res_kind = case tup_sort of
Richard Eisenberg's avatar
Richard Eisenberg committed
739
                 UnboxedTuple    -> unboxedTupleKind tau_reps
740 741
                 BoxedTuple      -> liftedTypeKind
                 ConstraintTuple -> constraintKind
742

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

749
---------------------------
750 751 752
-- | Apply a type of a given kind to a list of arguments. This instantiates
-- invisible parameters as necessary. However, it does *not* necessarily
-- apply all the arguments, if the kind runs out of binders.
753 754
-- Never calls 'matchExpectedFunKind'; when the kind runs out of binders,
-- this stops processing.
755 756 757 758
-- 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.
-- This version will instantiate all invisible arguments left over after
759 760 761 762
-- the visible ones. Used only when typechecking type/data family patterns
-- (where we need to instantiate all remaining invisible parameters; for
-- example, consider @type family F :: k where F = Int; F = Maybe@. We
-- need to instantiate the @k@.)
763 764
tcInferArgs :: Outputable fun
            => fun                      -- ^ the function
765
            -> [TyConBinder]            -- ^ function kind's binders
766 767
            -> Maybe (VarEnv Kind)      -- ^ possibly, kind info (see above)
            -> [LHsType Name]           -- ^ args
768 769 770
            -> TcM (TCvSubst, [TyBinder], [TcType], [LHsType Name], Int)
               -- ^ (instantiating subst, un-insted leftover binders,
               --   typechecked args, untypechecked args, n)
771 772 773
tcInferArgs fun tc_binders mb_kind_info args
  = do { let binders = tyConBindersTyBinders tc_binders  -- UGH!
       ; (subst, leftover_binders, args', leftovers, n)
774
           <- tc_infer_args typeLevelMode fun binders mb_kind_info args 1
775
        -- now, we need to instantiate any remaining invisible arguments
776
       ; let (invis_bndrs, other_binders) = break isVisibleBinder leftover_binders
777 778 779 780
       ; (subst', invis_args)
           <- tcInstBindersX subst mb_kind_info invis_bndrs
       ; return ( subst'
                , other_binders
Simon Peyton Jones's avatar
Simon Peyton Jones committed
781
                , args' `chkAppend` invis_args
782 783 784 785 786 787 788
                , leftovers, n ) }

-- | See comments for 'tcInferArgs'. But this version does not instantiate
-- any remaining invisible arguments.
tc_infer_args :: Outputable fun
              => TcTyMode
              -> fun                      -- ^ the function
789
              -> [TyBinder]               -- ^ function kind's binders (zonked)
790 791 792
              -> Maybe (VarEnv Kind)      -- ^ possibly, kind info (see above)
              -> [LHsType Name]           -- ^ args
              -> Int                      -- ^ number to start arg counter at
793 794
              -> TcM (TCvSubst, [TyBinder], [TcType], [LHsType Name], Int)
tc_infer_args mode orig_ty binders mb_kind_info orig_args n0
Simon Peyton Jones's avatar
Simon Peyton Jones committed
795
  = go emptyTCvSubst binders orig_args n0 []
796
  where
797 798
    go subst binders []   n acc
      = return ( subst, binders, reverse acc, [], n )
799 800 801 802
    -- when we call this when checking type family patterns, we really
    -- do want to instantiate all invisible arguments. During other
    -- typechecking, we don't.

803 804 805 806 807
    go subst (binder:binders) all_args@(arg:args) n acc
      | isInvisibleBinder binder
      = do { traceTc "tc_infer_args (invis)" (ppr binder)
           ; (subst', arg') <- tcInstBinderX mb_kind_info subst binder
           ; go subst' binders all_args n (arg' : acc) }
808

809 810
      | otherwise
      = do { traceTc "tc_infer_args (vis)" (ppr binder $$ ppr arg)
811
           ; arg' <- addErrCtxt (funAppCtxt orig_ty arg n) $
812 813 814
                     tc_lhs_type mode arg (substTyUnchecked subst $
                                           tyBinderType binder)
           ; let subst' = extendTvSubstBinder subst binder arg'
815
           ; go subst' binders args (n+1) (arg' : acc) }
816

817 818
    go subst [] all_args n acc
      = return (subst, [], reverse acc, all_args, n)
819

820
-- | Applies a type to a list of arguments.
821 822 823 824
-- Always consumes all the arguments, using 'matchExpectedFunKind' as
-- necessary. If you wish to apply a type to a list of HsTypes, this is
-- your function.
-- Used for type-checking types only.
825
tcInferApps :: Outputable fun
826 827 828 829 830 831
            => TcTyMode
            -> fun                  -- ^ Function (for printing only)
            -> TcType               -- ^ Function (could be knot-tied)
            -> TcKind               -- ^ Function kind (zonked)
            -> [LHsType Name]       -- ^ Args
            -> TcM (TcType, TcKind) -- ^ (f args, result kind)
832
tcInferApps mode orig_ty ty ki args = go ty ki args 1
833
  where
834 835
    go fun fun_kind []   _ = return (fun, fun_kind)
    go fun fun_kind args n
836 837 838 839 840
      | let (binders, res_kind) = splitPiTys fun_kind
      , not (null binders)
      = do { (subst, leftover_binders, args', leftover_args, n')
                <- tc_infer_args mode orig_ty binders Nothing args n
           ; let fun_kind' = substTyUnchecked subst $
Simon Peyton Jones's avatar
Simon Peyton Jones committed
841
                             mkPiTys leftover_binders res_kind
842
           ; go (mkNakedAppTys fun args') fun_kind' leftover_args n' }
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863

    go fun fun_kind all_args@(arg:args) n
      = do { (co, arg_k, res_k) <- matchExpectedFunKind (length all_args)
                                                        fun fun_kind
           ; arg' <- addErrCtxt (funAppCtxt orig_ty arg n) $
                     tc_lhs_type mode arg arg_k
           ; go (mkNakedAppTy (fun `mkNakedCastTy` co) arg')
                res_k args (n+1) }

--------------------------
checkExpectedKind :: TcType               -- the type whose kind we're checking
                  -> TcKind               -- the known kind of that type, k
                  -> TcKind               -- the expected kind, exp_kind
                  -> TcM TcType    -- a possibly-inst'ed, casted type :: exp_kind
-- Instantiate a kind (if necessary) and then call unifyType
--      (checkExpectedKind ty act_kind exp_kind)
-- checks that the actual kind act_kind is compatible
--      with the expected kind exp_kind
checkExpectedKind ty act_kind exp_kind
 = do { (ty', act_kind') <- instantiate ty act_kind exp_kind
      ; let origin = TypeEqOrigin { uo_actual   = act_kind'
864
                                  , uo_expected = exp_kind
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
                                  , uo_thing    = Just $ mkTypeErrorThing ty'
                                  }
      ; co_k <- uType origin KindLevel act_kind' exp_kind
      ; traceTc "checkExpectedKind" (vcat [ ppr act_kind
                                          , ppr exp_kind
                                          , ppr co_k ])
      ; let result_ty = ty' `mkNakedCastTy` co_k
      ; return result_ty }
  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.
    instantiate :: TcType    -- the type
                -> TcKind    -- of this kind
                -> TcKind   -- but expected to be of this one
                -> TcM ( TcType   -- the inst'ed type
                       , TcKind ) -- its new kind
    instantiate ty act_ki exp_ki
      = let (exp_bndrs, _) = splitPiTysInvisible exp_ki in
        instantiateTyN (length exp_bndrs) ty act_ki

-- | Instantiate a type to have at most @n@ invisible arguments.
instantiateTyN :: Int    -- ^ @n@
               -> TcType -- ^ the type
               -> TcKind -- ^ its kind
               -> TcM (TcType, TcKind)   -- ^ The inst'ed type with kind
instantiateTyN n ty ki
  = let (bndrs, inner_ki)            = splitPiTysInvisible ki
        num_to_inst                  = length bndrs - n
           -- NB: splitAt is forgiving with invalid numbers
        (inst_bndrs, leftover_bndrs) = splitAt num_to_inst bndrs
    in
    if num_to_inst <= 0 then return (ty, ki) else
    do { (subst, inst_args) <- tcInstBinders inst_bndrs
Simon Peyton Jones's avatar
Simon Peyton Jones committed
900
       ; let rebuilt_ki = mkPiTys leftover_bndrs inner_ki
901 902
             ki'        = substTy subst rebuilt_ki
       ; return (mkNakedAppTys ty inst_args, ki') }
903

904
---------------------------
905
tcHsContext :: LHsContext Name -> TcM [PredType]
906
tcHsContext = tc_hs_context typeLevelMode
907

908
tcLHsPredType :: LHsType Name -> TcM PredType
909 910 911 912 913 914 915
tcLHsPredType = tc_lhs_pred typeLevelMode

tc_hs_context :: TcTyMode -> LHsContext Name -> TcM [PredType]
tc_hs_context mode ctxt = mapM (tc_lhs_pred mode) (unLoc ctxt)

tc_lhs_pred :: TcTyMode -> LHsType Name -> TcM PredType
tc_lhs_pred mode pred = tc_lhs_type mode pred constraintKind
916 917

---------------------------
918
tcTyVar :: TcTyMode -> Name -> TcM (TcType, TcKind)
dreixel's avatar
dreixel committed
919 920
-- See Note [Type checking recursive type and class declarations]
-- in TcTyClsDecls
921
tcTyVar mode name         -- Could be a tyvar, a tycon, or a datacon
dreixel's avatar
dreixel committed
922 923 924
  = do { traceTc "lk1" (ppr name)
       ; thing <- tcLookup name
       ; case thing of
925 926
           ATyVar _ tv -> return (mkTyVarTy tv, tyVarKind tv)

Alexander Vieth's avatar
Alexander Vieth committed
927 928 929 930 931
           ATcTyCon tc_tc -> do { -- See Note [GADT kind self-reference]
                                  unless
                                    (isTypeLevel (mode_level mode))
                                    (promotionErr name TyConPE)
                                ; check_tc tc_tc
932
                                ; tc <- get_loopy_tc name tc_tc
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
933
                                ; handle_tyfams tc tc_tc }
934 935 936 937
                             -- mkNakedTyConApp: see Note [Type-checking inside the knot]
                 -- NB: we really should check if we're at the kind level
                 -- and if the tycon is promotable if -XNoTypeInType is set.
                 -- But this is a terribly large amount of work! Not worth it.
938

939
           AGlobal (ATyCon tc)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
940 941
             -> do { check_tc tc
                   ; handle_tyfams tc tc }