TcType.hs 95 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 6
\section[TcType]{Types used in the typechecker}

7 8
This module provides the Type interface for front-end parts of the
compiler.  These parts
9

10 11 12
        * treat "source types" as opaque:
                newtypes, and predicates are meaningful.
        * look through usage types
13

14
The "tc" prefix is for "TypeChecker", because the type checker
15
is the principal client.
Austin Seipp's avatar
Austin Seipp committed
16
-}
17

18
{-# LANGUAGE CPP, MultiWayIf #-}
19

20
module TcType (
21
  --------------------------------
22 23
  -- Types
  TcType, TcSigmaType, TcRhoType, TcTauType, TcPredType, TcThetaType,
24
  TcTyVar, TcTyVarSet, TcDTyVarSet, TcTyCoVarSet, TcDTyCoVarSet,
25
  TcKind, TcCoVar, TcTyCoVar, TcTyBinder, TcTyCon,
26

27 28 29 30
  ExpType(..), ExpSigmaType, ExpRhoType, mkCheckExpType,

  SyntaxOpType(..), synKnownType, mkSynFunTys,

31
  -- TcLevel
32
  TcLevel(..), topTcLevel, pushTcLevel, isTopTcLevel,
33
  strictlyDeeperThan, sameDepthAs, fmvTcLevel,
34

35
  --------------------------------
36
  -- MetaDetails
37
  UserTypeCtxt(..), pprUserTypeCtxt, pprSigCtxt, isSigMaybe,
38
  TcTyVarDetails(..), pprTcTyVarDetails, vanillaSkolemTv, superSkolemTv,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
39 40
  MetaDetails(Flexi, Indirect), MetaInfo(..), TauTvFlavour(..),
  isImmutableTyVar, isSkolemTyVar, isMetaTyVar,  isMetaTyVarTy, isTyVarTy,
Austin Seipp's avatar
Austin Seipp committed
41
  isSigTyVar, isOverlappableTyVar,  isTyConableTyVar,
42
  isFskTyVar, isFmvTyVar, isFlattenTyVar,
43
  isAmbiguousTyVar, metaTvRef, metaTyVarInfo,
44
  isFlexi, isIndirect, isRuntimeUnkSkol,
45
  metaTyVarTcLevel, setMetaTyVarTcLevel, metaTyVarTcLevel_maybe,
46 47
  isTouchableMetaTyVar, isTouchableOrFmv,
  isFloatedTouchableMetaTyVar,
48
  canUnifyWithPolyType,
49 50

  --------------------------------
51
  -- Builders
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
52
  mkPhiTy, mkInvSigmaTy, mkSpecSigmaTy, mkSigmaTy,
53 54
  mkNakedTyConApp, mkNakedAppTys, mkNakedAppTy,
  mkNakedCastTy,
55

56
  --------------------------------
57
  -- Splitters
58
  -- These are important because they do not look through newtypes
59
  getTyVar,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
60
  tcSplitForAllTy_maybe,
61 62
  tcSplitForAllTys, tcSplitPiTys, tcSplitNamedPiTys,
  tcSplitPhiTy, tcSplitPredFunTy_maybe,
63
  tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy, tcSplitFunTysN,
64 65 66
  tcSplitTyConApp, tcSplitTyConApp_maybe, tcRepSplitTyConApp_maybe,
  tcTyConAppTyCon, tcTyConAppArgs,
  tcSplitAppTy_maybe, tcSplitAppTy, tcSplitAppTys, tcRepSplitAppTy_maybe,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
67
  tcGetTyVar_maybe, tcGetTyVar, nextRole,
68
  tcSplitSigmaTy, tcDeepSplitSigmaTy_maybe,
69 70

  ---------------------------------
71
  -- Predicates.
72
  -- Again, newtypes are opaque
73 74
  eqType, eqTypes, cmpType, cmpTypes, eqTypeX,
  pickyEqType, tcEqType, tcEqKind, tcEqTypeNoKindCheck, tcEqTypeVis,
75
  isSigmaTy, isRhoTy, isRhoExpTy, isOverloadedTy,
Ben Gamari's avatar
Ben Gamari committed
76
  isFloatingTy, isDoubleTy, isFloatTy, isIntTy, isWordTy, isStringTy,
Eric Seidel's avatar
Eric Seidel committed
77
  isIntegerTy, isBoolTy, isUnitTy, isCharTy, isCallStackTy, isCallStackPred,
78
  isTauTy, isTauTyCon, tcIsTyVarTy, tcIsForAllTy,
79
  isPredTy, isTyVarClassPred, isTyVarExposed, isTyVarUnderDatatype,
80
  checkValidClsArgs, hasTyVarHead,
81
  isRigidEqPred, isRigidTy,
82

83 84
  ---------------------------------
  -- Misc type manipulators
85
  deNoteType, occurCheckExpand, OccCheckResult(..),
Simon Peyton Jones's avatar
Simon Peyton Jones committed
86
  orphNamesOfType, orphNamesOfCo,
87
  orphNamesOfTypes, orphNamesOfCoCon,
88
  getDFunTyKey,
89
  evVarPred_maybe, evVarPred,
90 91

  ---------------------------------
92
  -- Predicate types
93
  mkMinimalBySCs, transSuperClasses,
94
  pickQuantifiablePreds,
95 96
  immSuperClasses,
  isImprovementPred,
97

98 99 100 101
  -- * Finding type instances
  tcTyFamInsts,

  -- * Finding "exact" (non-dead) type variables
102
  exactTyCoVarsOfType, exactTyCoVarsOfTypes,
103
  splitDepVarsOfType, splitDepVarsOfTypes, TcDepVars(..), depVarsTyVars,
104 105 106

  -- * Extracting bound variables
  allBoundVariables, allBoundVariabless,
107

108 109 110 111 112 113
  ---------------------------------
  -- Foreign import and export
  isFFIArgumentTy,     -- :: DynFlags -> Safety -> Type -> Bool
  isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
  isFFIExportResultTy, -- :: Type -> Bool
  isFFIExternalTy,     -- :: Type -> Bool
114
  isFFIDynTy,          -- :: Type -> Type -> Bool
115 116
  isFFIPrimArgumentTy, -- :: DynFlags -> Type -> Bool
  isFFIPrimResultTy,   -- :: DynFlags -> Type -> Bool
117
  isFFILabelTy,        -- :: Type -> Bool
118
  isFFITy,             -- :: Type -> Bool
119
  isFunPtrTy,          -- :: Type -> Bool
120
  tcSplitIOType_maybe, -- :: Type -> Maybe Type
121

122
  --------------------------------
123 124
  -- Rexported from Kind
  Kind, typeKind,
125
  liftedTypeKind,
126 127
  constraintKind,
  isLiftedTypeKind, isUnliftedTypeKind, classifiesTypeWithValues,
128

129 130
  --------------------------------
  -- Rexported from Type
131 132
  Type, PredType, ThetaType, TyBinder, VisibilityFlag(..),

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
133
  mkForAllTy, mkForAllTys, mkInvForAllTys, mkSpecForAllTys, mkNamedForAllTy,
134
  mkFunTy, mkFunTys,
135
  mkTyConApp, mkAppTy, mkAppTys,
136 137
  mkTyConTy, mkTyVarTy,
  mkTyVarTys,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
138
  mkNamedBinder,
139

140
  isClassPred, isEqPred, isNomEqPred, isIPPred,
141
  mkClassPred,
142
  isDictLikeTy,
143
  tcSplitDFunTy, tcSplitDFunHead,
144
  isRuntimeRepVar, isRuntimeRepPolymorphic,
145
  isVisibleBinder, isInvisibleBinder,
146

147
  -- Type substitutions
148 149
  TCvSubst(..),         -- Representation visible to a few friends
  TvSubstEnv, emptyTCvSubst,
niteria's avatar
niteria committed
150 151
  zipTvSubst,
  mkTvSubstPrs, notElemTCvSubst, unionTCvSubst,
152
  getTvSubstEnv, setTvSubstEnv, getTCvInScope, extendTCvInScope,
153
  extendTCvInScopeList, extendTCvInScopeSet, extendTvSubstAndInScope,
154
  Type.lookupTyVar, Type.extendTCvSubst, Type.substTyVarBndr,
155 156
  Type.extendTvSubst,
  isInScope, mkTCvSubst, mkTvSubst, zipTyEnv, zipCoEnv,
157
  Type.substTy, substTys, substTyWith, substTyWithCoVars,
158 159 160 161
  substTyAddInScope,
  substTyUnchecked, substTysUnchecked, substThetaUnchecked,
  substTyWithBindersUnchecked, substTyWithUnchecked,
  substCoUnchecked, substCoWithUnchecked,
162
  substTheta,
163

164
  isUnliftedType,       -- Source types are always lifted
165 166
  isUnboxedTupleType,   -- Ditto
  isPrimitiveType,
167

168 169 170 171
  coreView,

  tyCoVarsOfType, tyCoVarsOfTypes, closeOverKinds,
  tyCoVarsOfTelescope,
niteria's avatar
niteria committed
172
  tyCoFVsOfType, tyCoFVsOfTypes,
173 174
  tyCoVarsOfTypeDSet, tyCoVarsOfTypesDSet, closeOverKindsDSet,
  tyCoVarsOfTypeList, tyCoVarsOfTypesList,
175

176 177 178 179 180
  --------------------------------
  -- Transforming Types to TcTypes
  toTcType,    -- :: Type -> TcType
  toTcTypeBag, -- :: Bag EvVar -> Bag EvVar

181
  pprKind, pprParendKind, pprSigmaType,
182
  pprType, pprParendType, pprTypeApp, pprTyThingCategory,
183
  pprTheta, pprThetaArrowTy, pprClassPred,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
184
  pprTvBndr, pprTvBndrs,
185

186
  TypeSize, sizeType, sizeTypes, toposortTyVars
187

188
  ) where
189

190
#include "HsVersions.h"
191

192
-- friends:
193
import Kind
194
import TyCoRep
195 196 197
import Class
import Var
import ForeignCall
198
import VarSet
199
import Coercion
200
import Type
201
import TyCon
202 203

-- others:
204
import DynFlags
Simon Peyton Jones's avatar
Simon Peyton Jones committed
205
import CoreFVs
206 207 208
import Name -- hiding (varName)
            -- We use this to make dictionaries for type literals.
            -- Perhaps there's a better way to do this?
209
import NameSet
210 211 212 213 214
import VarEnv
import PrelNames
import TysWiredIn
import BasicTypes
import Util
215
import Bag
216
import Maybes
217
import Pair
218
import Outputable
219
import FastString
220
import ErrUtils( Validity(..), MsgDoc, isValid )
221
import FV
222
import qualified GHC.LanguageExtensions as LangExt
Simon Marlow's avatar
Simon Marlow committed
223 224

import Data.IORef
Austin Seipp's avatar
Austin Seipp committed
225
import Control.Monad (liftM, ap)
226
#if __GLASGOW_HASKELL__ < 709
227 228
import Data.Monoid (mempty, mappend)
import Data.Foldable (foldMap)
229
import Control.Applicative (Applicative(..), (<$>) )
230
#endif
231
import Data.Functor.Identity
232

Austin Seipp's avatar
Austin Seipp committed
233 234 235
{-
************************************************************************
*                                                                      *
236
\subsection{Types}
Austin Seipp's avatar
Austin Seipp committed
237 238
*                                                                      *
************************************************************************
239

240
The type checker divides the generic Type world into the
241 242
following more structured beasts:

243
sigma ::= forall tyvars. phi
244 245 246 247
        -- A sigma type is a qualified type
        --
        -- Note that even if 'tyvars' is empty, theta
        -- may not be: e.g.   (?x::Int) => Int
248

249 250 251 252
        -- Note that 'sigma' is in prenex form:
        -- all the foralls are at the front.
        -- A 'phi' type has no foralls to the right of
        -- an arrow
253

254 255 256
phi :: theta => rho

rho ::= sigma -> rho
257 258 259 260 261 262 263 264 265 266 267
     |  tau

-- A 'tau' type has no quantification anywhere
-- Note that the args of a type constructor must be taus
tau ::= tyvar
     |  tycon tau_1 .. tau_n
     |  tau_1 tau_2
     |  tau_1 -> tau_2

-- In all cases, a (saturated) type synonym application is legal,
-- provided it expands to the required form.
Austin Seipp's avatar
Austin Seipp committed
268
-}
269

270
type TcTyVar = TyVar    -- Used only during type inference
271
type TcCoVar = CoVar    -- Used only during type inference
272
type TcType = Type      -- A TcType can have mutable type variables
273
type TcTyCoVar = Var    -- Either a TcTyVar or a CoVar
274 275 276 277
        -- Invariant on ForAllTy in TcTypes:
        --      forall a. T
        -- a cannot occur inside a MutTyVar in T; that is,
        -- T is "flattened" before quantifying over a
278
type TcTyBinder = TyBinder
279
type TcTyCon = TyCon   -- these can be the TcTyCon constructor
280

281
-- These types do not have boxy type variables in them
282 283
type TcPredType     = PredType
type TcThetaType    = ThetaType
284
type TcSigmaType    = TcType
285
type TcRhoType      = TcType  -- Note [TcRhoType]
286
type TcTauType      = TcType
287
type TcKind         = Kind
288
type TcTyVarSet     = TyVarSet
289
type TcTyCoVarSet   = TyCoVarSet
290
type TcDTyVarSet    = DTyVarSet
291
type TcDTyCoVarSet  = DTyCoVarSet
292

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
-- | An expected type to check against during type-checking.
-- See Note [ExpType] in TcMType, where you'll also find manipulators.
data ExpType = Check TcType
             | Infer Unique  -- for debugging only
                     TcLevel -- See Note [TcLevel of ExpType] in TcMType
                     Kind
                     (IORef (Maybe TcType))

type ExpSigmaType = ExpType
type ExpRhoType   = ExpType

instance Outputable ExpType where
  ppr (Check ty) = ppr ty
  ppr (Infer u lvl ki _)
    = parens (text "Infer" <> braces (ppr u <> comma <> ppr lvl)
              <+> dcolon <+> ppr ki)

-- | Make an 'ExpType' suitable for checking.
mkCheckExpType :: TcType -> ExpType
mkCheckExpType = Check

-- | What to expect for an argument to a rebindable-syntax operator.
-- Quite like 'Type', but allows for holes to be filled in by tcSyntaxOp.
-- The callback called from tcSyntaxOp gets a list of types; the meaning
-- of these types is determined by a left-to-right depth-first traversal
-- of the 'SyntaxOpType' tree. So if you pass in
--
-- > SynAny `SynFun` (SynList `SynFun` SynType Int) `SynFun` SynAny
--
-- you'll get three types back: one for the first 'SynAny', the /element/
-- type of the list, and one for the last 'SynAny'. You don't get anything
-- for the 'SynType', because you've said positively that it should be an
-- Int, and so it shall be.
--
-- This is defined here to avoid defining it in TcExpr.hs-boot.
data SyntaxOpType
  = SynAny     -- ^ Any type
  | SynRho     -- ^ A rho type, deeply skolemised or instantiated as appropriate
  | SynList    -- ^ A list type. You get back the element type of the list
  | SynFun SyntaxOpType SyntaxOpType
               -- ^ A function.
  | SynType ExpType   -- ^ A known type.
infixr 0 `SynFun`

-- | Like 'SynType' but accepts a regular TcType
synKnownType :: TcType -> SyntaxOpType
synKnownType = SynType . mkCheckExpType

-- | Like 'mkFunTys' but for 'SyntaxOpType'
mkSynFunTys :: [SyntaxOpType] -> ExpType -> SyntaxOpType
mkSynFunTys arg_tys res_ty = foldr SynFun (SynType res_ty) arg_tys


Austin Seipp's avatar
Austin Seipp committed
346
{-
347 348 349 350 351 352 353 354
Note [TcRhoType]
~~~~~~~~~~~~~~~~
A TcRhoType has no foralls or contexts at the top, or to the right of an arrow
  YES    (forall a. a->a) -> Int
  NO     forall a. a ->  Int
  NO     Eq a => a -> a
  NO     Int -> forall a. a -> Int

355

Austin Seipp's avatar
Austin Seipp committed
356 357
************************************************************************
*                                                                      *
358
\subsection{TyVarDetails}
Austin Seipp's avatar
Austin Seipp committed
359 360
*                                                                      *
************************************************************************
361

362 363
TyVarDetails gives extra info about type variables, used during type
checking.  It's attached to mutable type variables only.
364 365
It's knot-tied back to Var.hs.  There is no reason in principle
why Var.hs shouldn't actually have the definition, but it "belongs" here.
366

367 368 369 370
Note [Signature skolems]
~~~~~~~~~~~~~~~~~~~~~~~~
Consider this

371 372 373 374 375 376 377 378 379 380 381 382 383
  f :: forall a. [a] -> Int
  f (x::b : xs) = 3

Here 'b' is a lexically scoped type variable, but it turns out to be
the same as the skolem 'a'.  So we have a special kind of skolem
constant, SigTv, which can unify with other SigTvs. They are used
*only* for pattern type signatures.

Similarly consider
  data T (a:k1) = MkT (S a)
  data S (b:k2) = MkS (T b)
When doing kind inference on {S,T} we don't want *skolems* for k1,k2,
because they end up unifying; we want those SigTvs again.
384

385 386
Note [TyVars and TcTyVars during type checking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
387 388 389
The Var type has constructors TyVar and TcTyVar.  They are used
as follows:

390
* TcTyVar: used /only/ during type checking.  Should never appear
391 392
  afterwards.  May contain a mutable field, in the MetaTv case.

393 394 395 396 397 398 399 400 401 402 403 404
* TyVar: is never seen by the constraint solver, except locally
  inside a type like (forall a. [a] ->[a]), where 'a' is a TyVar.
  We instantiate these with TcTyVars before exposing the type
  to the constraint solver.

I have swithered about the latter invariant, excluding TyVars from the
constraint solver.  It's not strictly essential, and indeed
(historically but still there) Var.tcTyVarDetails returns
vanillaSkolemTv for a TyVar.

But ultimately I want to seeparate Type from TcType, and in that case
we would need to enforce the separation.
Austin Seipp's avatar
Austin Seipp committed
405
-}
406

407
-- A TyVarDetails is inside a TyVar
408
-- See Note [TyVars and TcTyVars]
409
data TcTyVarDetails
410 411 412 413
  = SkolemTv      -- A skolem
       Bool       -- True <=> this skolem type variable can be overlapped
                  --          when looking up instances
                  -- See Note [Binding when looking up instances] in InstEnv
414

415 416 417 418
  | FlatSkol      -- A flatten-skolem.  It stands for the TcType, and zonking
       TcType     -- will replace it by that type.
                  -- See Note [The flattening story] in TcFlatten

419 420 421
  | RuntimeUnk    -- Stands for an as-yet-unknown type in the GHCi
                  -- interactive context

422 423
  | MetaTv { mtv_info  :: MetaInfo
           , mtv_ref   :: IORef MetaDetails
424
           , mtv_tclvl :: TcLevel }  -- See Note [TcLevel and untouchable type variables]
425

426 427 428 429 430
vanillaSkolemTv, superSkolemTv :: TcTyVarDetails
-- See Note [Binding when looking up instances] in InstEnv
vanillaSkolemTv = SkolemTv False  -- Might be instantiated
superSkolemTv   = SkolemTv True   -- Treat this as a completely distinct type

431
-----------------------------
432
data MetaDetails
433
  = Flexi  -- Flexi type variables unify to become Indirects
434 435
  | Indirect TcType

436
instance Outputable MetaDetails where
437 438
  ppr Flexi         = text "Flexi"
  ppr (Indirect ty) = text "Indirect" <+> ppr ty
439

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
440 441 442 443
data TauTvFlavour
  = VanillaTau
  | WildcardTau    -- ^ A tyvar that originates from a type wildcard.

444
data MetaInfo
445
   = TauTv         -- This MetaTv is an ordinary unification variable
446
                   -- A TauTv is always filled in with a tau-type, which
thomasw's avatar
thomasw committed
447
                   -- never contains any ForAlls.
448

449 450 451 452 453 454
   | SigTv         -- A variant of TauTv, except that it should not be
                   -- unified with a type, only with a type variable
                   -- SigTvs are only distinguished to improve error messages
                   --      see Note [Signature skolems]
                   --      The MetaDetails, if filled in, will
                   --      always be another SigTv or a SkolemTv
455

456 457 458 459
   | FlatMetaTv    -- A flatten meta-tyvar
                   -- It is a meta-tyvar, but it is always untouchable, with level 0
                   -- See Note [The flattening story] in TcFlatten

460
-------------------------------------
461 462 463 464
-- UserTypeCtxt describes the origin of the polymorphic type
-- in the places where we need to an expression has that type

data UserTypeCtxt
465 466 467 468 469 470 471 472 473 474 475
  = FunSigCtxt      -- Function type signature, when checking the type
                    -- Also used for types in SPECIALISE pragmas
       Name              -- Name of the function
       Bool              -- True <=> report redundant constraints
                            -- This is usually True, but False for
                            --   * Record selectors (not important here)
                            --   * Class and instance methods.  Here
                            --     the code may legitimately be more
                            --     polymorphic than the signature
                            --     generated from the class
                            --     declaration
476

477 478
  | InfSigCtxt Name     -- Inferred type for function
  | ExprSigCtxt         -- Expression type signature
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
479
  | TypeAppCtxt         -- Visible type application
480 481
  | ConArgCtxt Name     -- Data constructor argument
  | TySynCtxt Name      -- RHS of a type synonym decl
482
  | PatSynBuilderCtxt Name -- Type sig for the builder of a bidirectional pattern synonym
483 484 485
  | PatSigCtxt          -- Type sig in pattern
                        --   eg  f (x::t) = ...
                        --   or  (x::t, y) = e
486 487
  | RuleSigCtxt Name    -- LHS of a RULE forall
                        --    RULE "foo" forall (x :: a -> a). f (Just x) = ...
488 489 490 491
  | ResSigCtxt          -- Result type sig
                        --      f x :: t = ....
  | ForSigCtxt Name     -- Foreign import or export signature
  | DefaultDeclCtxt     -- Types in a default declaration
dreixel's avatar
dreixel committed
492
  | InstDeclCtxt        -- An instance declaration
493 494
  | SpecInstCtxt        -- SPECIALISE instance pragma
  | ThBrackCtxt         -- Template Haskell type brackets [t| ... |]
495 496 497
  | GenSigCtxt          -- Higher-rank or impredicative situations
                        -- e.g. (f e) where f has a higher-rank type
                        -- We might want to elaborate this
498
  | GhciCtxt            -- GHCi command :kind <type>
499

500 501 502 503 504
  | ClassSCCtxt Name    -- Superclasses of a class
  | SigmaCtxt           -- Theta part of a normal for-all type
                        --      f :: <S> => a -> a
  | DataTyCtxt Name     -- Theta part of a data decl
                        --      data <S> => T a = MkT a
dreixel's avatar
dreixel committed
505

Austin Seipp's avatar
Austin Seipp committed
506
{-
507 508 509
-- Notes re TySynCtxt
-- We allow type synonyms that aren't types; e.g.  type List = []
--
510
-- If the RHS mentions tyvars that aren't in scope, we'll
511
-- quantify over them:
512 513
--      e.g.    type T = a->a
-- will become  type T = forall a. a->a
514
--
515
-- With gla-exts that's right, but for H98 we should complain.
516
-}
517 518


519
{- *********************************************************************
Austin Seipp's avatar
Austin Seipp committed
520
*                                                                      *
521
                Untoucable type variables
Austin Seipp's avatar
Austin Seipp committed
522
*                                                                      *
523
********************************************************************* -}
524

525
newtype TcLevel = TcLevel Int deriving( Eq, Ord )
526
  -- See Note [TcLevel and untouchable type variables] for what this Int is
527
  -- See also Note [TcLevel assignment]
528

Austin Seipp's avatar
Austin Seipp committed
529
{-
530 531
Note [TcLevel and untouchable type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
532
* Each unification variable (MetaTv)
533
  and each Implication
534
  has a level number (of type TcLevel)
535

536 537 538
* INVARIANTS.  In a tree of Implications,

    (ImplicInv) The level number of an Implication is
539 540
                STRICTLY GREATER THAN that of its parent

541 542
    (MetaTvInv) The level number of a unification variable is
                LESS THAN OR EQUAL TO that of its parent
543 544 545 546 547
                implication

* A unification variable is *touchable* if its level number
  is EQUAL TO that of its immediate parent implication.

548 549 550
* INVARIANT
    (GivenInv)  The free variables of the ic_given of an
                implication are all untouchable; ie their level
551
                numbers are LESS THAN the ic_tclvl of the implication
552

553 554 555
Note [Skolem escape prevention]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We only unify touchable unification variables.  Because of
556 557
(MetaTvInv), there can be no occurrences of the variable further out,
so the unification can't cause the skolems to escape. Example:
558 559 560 561 562 563 564 565 566 567 568 569
     data T = forall a. MkT a (a->Int)
     f x (MkT v f) = length [v,x]
We decide (x::alpha), and generate an implication like
      [1]forall a. (a ~ alpha[0])
But we must not unify alpha:=a, because the skolem would escape.

For the cases where we DO want to unify, we rely on floating the
equality.   Example (with same T)
     g x (MkT v f) = x && True
We decide (x::alpha), and generate an implication like
      [1]forall a. (Bool ~ alpha[0])
We do NOT unify directly, bur rather float out (if the constraint
Krzysztof Gogolewski's avatar
Typos  
Krzysztof Gogolewski committed
570
does not mention 'a') to get
571 572 573 574 575
      (Bool ~ alpha[0]) /\ [1]forall a.()
and NOW we can unify alpha.

The same idea of only unifying touchables solves another problem.
Suppose we had
576 577
   (F Int ~ uf[0])  /\  [1](forall a. C a => F Int ~ beta[1])
In this example, beta is touchable inside the implication. The
578
first solveSimpleWanteds step leaves 'uf' un-unified. Then we move inside
579
the implication where a new constraint
580 581 582
       uf  ~  beta
emerges. If we (wrongly) spontaneously solved it to get uf := beta,
the whole implication disappears but when we pop out again we are left with
583
(F Int ~ uf) which will be unified by our final zonking stage and
584
uf will get unified *once more* to (F Int).
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

Note [TcLevel assignment]
~~~~~~~~~~~~~~~~~~~~~~~~~
We arrange the TcLevels like this

   1   Top level
   2     Flatten-meta-vars of level 3
   3   First-level implication constraints
   4     Flatten-meta-vars of level 5
   5   Second-level implication constraints
   ...etc...

The even-numbered levels are for the flatten-meta-variables assigned
at the next level in.  Eg for a second-level implication conststraint
(level 5), the flatten meta-vars are level 4, which makes them untouchable.
The flatten meta-vars could equally well all have level 0, or just NotALevel
since they do not live across implications.
Austin Seipp's avatar
Austin Seipp committed
602
-}
603

604
fmvTcLevel :: TcLevel -> TcLevel
605
-- See Note [TcLevel assignment]
606
fmvTcLevel (TcLevel n) = TcLevel (n-1)
607

608
topTcLevel :: TcLevel
609
-- See Note [TcLevel assignment]
610
topTcLevel = TcLevel 1   -- 1 = outermost level
611

612 613 614 615
isTopTcLevel :: TcLevel -> Bool
isTopTcLevel (TcLevel 1) = True
isTopTcLevel _           = False

616
pushTcLevel :: TcLevel -> TcLevel
617
-- See Note [TcLevel assignment]
618
pushTcLevel (TcLevel us) = TcLevel (us + 2)
619

620 621 622
strictlyDeeperThan :: TcLevel -> TcLevel -> Bool
strictlyDeeperThan (TcLevel tv_tclvl) (TcLevel ctxt_tclvl)
  = tv_tclvl > ctxt_tclvl
623

624 625 626
sameDepthAs :: TcLevel -> TcLevel -> Bool
sameDepthAs (TcLevel ctxt_tclvl) (TcLevel tv_tclvl)
  = ctxt_tclvl == tv_tclvl   -- NB: invariant ctxt_tclvl >= tv_tclvl
627 628
                             --     So <= would be equivalent

629 630 631 632
checkTcLevelInvariant :: TcLevel -> TcLevel -> Bool
-- Checks (MetaTvInv) from Note [TcLevel and untouchable type variables]
checkTcLevelInvariant (TcLevel ctxt_tclvl) (TcLevel tv_tclvl)
  = ctxt_tclvl >= tv_tclvl
633

634 635
instance Outputable TcLevel where
  ppr (TcLevel us) = ppr us
636

Austin Seipp's avatar
Austin Seipp committed
637 638 639
{-
************************************************************************
*                                                                      *
640
                Pretty-printing
Austin Seipp's avatar
Austin Seipp committed
641 642 643
*                                                                      *
************************************************************************
-}
644

645 646
pprTcTyVarDetails :: TcTyVarDetails -> SDoc
-- For debugging
647 648 649 650
pprTcTyVarDetails (SkolemTv True)  = text "ssk"
pprTcTyVarDetails (SkolemTv False) = text "sk"
pprTcTyVarDetails (RuntimeUnk {})  = text "rt"
pprTcTyVarDetails (FlatSkol {})    = text "fsk"
651 652
pprTcTyVarDetails (MetaTv { mtv_info = info, mtv_tclvl = tclvl })
  = pp_info <> colon <> ppr tclvl
653 654
  where
    pp_info = case info of
655 656 657
                TauTv      -> text "tau"
                SigTv      -> text "sig"
                FlatMetaTv -> text "fuv"
658 659

pprUserTypeCtxt :: UserTypeCtxt -> SDoc
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
pprUserTypeCtxt (FunSigCtxt n _)  = text "the type signature for" <+> quotes (ppr n)
pprUserTypeCtxt (InfSigCtxt n)    = text "the inferred type for" <+> quotes (ppr n)
pprUserTypeCtxt (RuleSigCtxt n)   = text "a RULE for" <+> quotes (ppr n)
pprUserTypeCtxt ExprSigCtxt       = text "an expression type signature"
pprUserTypeCtxt TypeAppCtxt       = text "a type argument"
pprUserTypeCtxt (ConArgCtxt c)    = text "the type of the constructor" <+> quotes (ppr c)
pprUserTypeCtxt (TySynCtxt c)     = text "the RHS of the type synonym" <+> quotes (ppr c)
pprUserTypeCtxt ThBrackCtxt       = text "a Template Haskell quotation [t|...|]"
pprUserTypeCtxt PatSigCtxt        = text "a pattern type signature"
pprUserTypeCtxt ResSigCtxt        = text "a result type signature"
pprUserTypeCtxt (ForSigCtxt n)    = text "the foreign declaration for" <+> quotes (ppr n)
pprUserTypeCtxt DefaultDeclCtxt   = text "a type in a `default' declaration"
pprUserTypeCtxt InstDeclCtxt      = text "an instance declaration"
pprUserTypeCtxt SpecInstCtxt      = text "a SPECIALISE instance pragma"
pprUserTypeCtxt GenSigCtxt        = text "a type expected by the context"
pprUserTypeCtxt GhciCtxt          = text "a type in a GHCi command"
pprUserTypeCtxt (ClassSCCtxt c)   = text "the super-classes of class" <+> quotes (ppr c)
pprUserTypeCtxt SigmaCtxt         = text "the context of a polymorphic type"
pprUserTypeCtxt (DataTyCtxt tc)   = text "the context of the data type declaration for" <+> quotes (ppr tc)
679 680 681
pprUserTypeCtxt (PatSynBuilderCtxt n)
  = vcat [ text "the type signature for bidirectional pattern synonym" <+> quotes (ppr n)
         , text "when used in an expression context" ]
682 683 684 685 686 687 688

pprSigCtxt :: UserTypeCtxt -> SDoc -> SDoc -> SDoc
-- (pprSigCtxt ctxt <extra> <type>)
-- prints    In <extra> the type signature for 'f':
--              f :: <type>
-- The <extra> is either empty or "the ambiguity check for"
pprSigCtxt ctxt extra pp_ty
689
  | Just n <- isSigMaybe ctxt
690
  = vcat [ text "In" <+> extra <+> ptext (sLit "the type signature:")
691 692 693
         , nest 2 (pprPrefixOcc n <+> dcolon <+> pp_ty) ]

  | otherwise
694
  = hang (text "In" <+> extra <+> pprUserTypeCtxt ctxt <> colon)
695 696
       2 pp_ty

697 698
  where

699
isSigMaybe :: UserTypeCtxt -> Maybe Name
700 701 702 703 704
isSigMaybe (FunSigCtxt n _)      = Just n
isSigMaybe (ConArgCtxt n)        = Just n
isSigMaybe (ForSigCtxt n)        = Just n
isSigMaybe (PatSynBuilderCtxt n) = Just n
isSigMaybe _                     = Nothing
705

Austin Seipp's avatar
Austin Seipp committed
706 707 708
{-
************************************************************************
*                  *
709
    Finding type family instances
Austin Seipp's avatar
Austin Seipp committed
710 711 712
*                  *
************************************************************************
-}
713

Simon Peyton Jones's avatar
Simon Peyton Jones committed
714 715
-- | Finds outermost type-family applications occuring in a type,
-- after expanding synonyms.
716
tcTyFamInsts :: Type -> [(TyCon, [Type])]
717
tcTyFamInsts ty
718
  | Just exp_ty <- coreView ty  = tcTyFamInsts exp_ty
719
tcTyFamInsts (TyVarTy _)        = []
720
tcTyFamInsts (TyConApp tc tys)
721
  | isTypeFamilyTyCon tc        = [(tc, tys)]
722
  | otherwise                   = concat (map tcTyFamInsts tys)
723
tcTyFamInsts (LitTy {})         = []
724 725
tcTyFamInsts (ForAllTy bndr ty) = tcTyFamInsts (binderType bndr)
                                  ++ tcTyFamInsts ty
726
tcTyFamInsts (AppTy ty1 ty2)    = tcTyFamInsts ty1 ++ tcTyFamInsts ty2
727 728 729
tcTyFamInsts (CastTy ty _)      = tcTyFamInsts ty
tcTyFamInsts (CoercionTy _)     = []  -- don't count tyfams in coercions,
                                      -- as they never get normalized, anyway
Austin Seipp's avatar
Austin Seipp committed
730 731 732
{-
************************************************************************
*                  *
733
          The "exact" free variables of a type
Austin Seipp's avatar
Austin Seipp committed
734 735
*                  *
************************************************************************
736 737 738 739 740

Note [Silly type synonym]
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  type T a = Int
741
What are the free tyvars of (T x)?  Empty, of course!
742 743 744 745 746 747 748 749 750 751
Here's the example that Ralf Laemmel showed me:
  foo :: (forall a. C u a -> C u a) -> u
  mappend :: Monoid u => u -> u -> u

  bar :: Monoid u => u
  bar = foo (\t -> t `mappend` t)
We have to generalise at the arg to f, and we don't
want to capture the constraint (Monad (C u a)) because
it appears to mention a.  Pretty silly, but it was useful to him.

752
exactTyCoVarsOfType is used by the type checker to figure out exactly
753 754 755 756 757 758
which type variables are mentioned in a type.  It's also used in the
smart-app checking code --- see TcExpr.tcIdApp

On the other hand, consider a *top-level* definition
  f = (\x -> x) :: T a -> T a
If we don't abstract over 'a' it'll get fixed to GHC.Prim.Any, and then
759
if we have an application like (f "x") we get a confusing error message
760
involving Any.  So the conclusion is this: when generalising
761 762
  - at top level use tyCoVarsOfType
  - in nested bindings use exactTyCoVarsOfType
763
See Trac #1813 for example.
Austin Seipp's avatar
Austin Seipp committed
764
-}
765

766
exactTyCoVarsOfType :: Type -> TyCoVarSet
767 768
-- Find the free type variables (of any kind)
-- but *expand* type synonyms.  See Note [Silly type synonym] above.
769
exactTyCoVarsOfType ty
770 771
  = go ty
  where
772
    go ty | Just ty' <- coreView ty = go ty'  -- This is the key line
773
    go (TyVarTy tv)         = unitVarSet tv `unionVarSet` go (tyVarKind tv)
774
    go (TyConApp _ tys)     = exactTyCoVarsOfTypes tys
775
    go (LitTy {})           = emptyVarSet
776
    go (AppTy fun arg)      = go fun `unionVarSet` go arg
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
    go (ForAllTy bndr ty)   = delBinderVar (go ty) bndr `unionVarSet` go (binderType bndr)
    go (CastTy ty co)       = go ty `unionVarSet` goCo co
    go (CoercionTy co)      = goCo co

    goCo (Refl _ ty)        = go ty
    goCo (TyConAppCo _ _ args)= goCos args
    goCo (AppCo co arg)     = goCo co `unionVarSet` goCo arg
    goCo (ForAllCo tv k_co co)
      = goCo co `delVarSet` tv `unionVarSet` goCo k_co
    goCo (CoVarCo v)         = unitVarSet v `unionVarSet` go (varType v)
    goCo (AxiomInstCo _ _ args) = goCos args
    goCo (UnivCo p _ t1 t2)  = goProv p `unionVarSet` go t1 `unionVarSet` go t2
    goCo (SymCo co)          = goCo co
    goCo (TransCo co1 co2)   = goCo co1 `unionVarSet` goCo co2
    goCo (NthCo _ co)        = goCo co
    goCo (LRCo _ co)         = goCo co
    goCo (InstCo co arg)     = goCo co `unionVarSet` goCo arg
    goCo (CoherenceCo c1 c2) = goCo c1 `unionVarSet` goCo c2
    goCo (KindCo co)         = goCo co
    goCo (SubCo co)          = goCo co
    goCo (AxiomRuleCo _ c)   = goCos c

    goCos cos = foldr (unionVarSet . goCo) emptyVarSet cos

    goProv UnsafeCoerceProv     = emptyVarSet
    goProv (PhantomProv kco)    = goCo kco
    goProv (ProofIrrelProv kco) = goCo kco
    goProv (PluginProv _)       = emptyVarSet
    goProv (HoleProv _)         = emptyVarSet

exactTyCoVarsOfTypes :: [Type] -> TyVarSet
exactTyCoVarsOfTypes tys = mapUnionVarSet exactTyCoVarsOfType tys
809

810 811 812 813 814 815 816 817 818 819 820
{-
************************************************************************
*                  *
          Bound variables in a type
*                  *
************************************************************************
-}

-- | Find all variables bound anywhere in a type.
-- See also Note [Scope-check inferred kinds] in TcHsType
allBoundVariables :: Type -> TyVarSet
niteria's avatar
niteria committed
821
allBoundVariables ty = fvVarSet $ go ty
822 823 824 825 826 827
  where
    go :: Type -> FV
    go (TyVarTy tv)     = go (tyVarKind tv)
    go (TyConApp _ tys) = mapUnionFV go tys
    go (AppTy t1 t2)    = go t1 `unionFV` go t2
    go (ForAllTy (Anon t1) t2) = go t1 `unionFV` go t2
niteria's avatar
niteria committed
828
    go (ForAllTy (Named tv _) t2) = FV.unitFV tv `unionFV`
829
                                    go (tyVarKind tv) `unionFV` go t2
niteria's avatar
niteria committed
830
    go (LitTy {})       = emptyFV
831
    go (CastTy ty _)    = go ty
niteria's avatar
niteria committed
832
    go (CoercionTy {})  = emptyFV
833 834 835 836 837
      -- any types mentioned in a coercion should also be mentioned in
      -- a type.

allBoundVariabless :: [Type] -> TyVarSet
allBoundVariabless = mapUnionVarSet allBoundVariables
838

Austin Seipp's avatar
Austin Seipp committed
839 840 841
{-
************************************************************************
*                                                                      *
842
                Predicates
Austin Seipp's avatar
Austin Seipp committed
843 844 845
*                                                                      *
************************************************************************
-}
846

847
isTouchableOrFmv :: TcLevel -> TcTyVar -> Bool
848 849 850 851 852 853
{- *********************************************************************
*                                                                      *
          Type and kind variables in a type
*                                                                      *
********************************************************************* -}

854 855 856 857 858
data TcDepVars  -- See Note [Dependent type variables]
                -- See Note [TcDepVars determinism]
  = DV { dv_kvs :: DTyCoVarSet  -- "kind" variables (dependent)
       , dv_tvs :: DTyVarSet    -- "type" variables (non-dependent)
                                -- The two are disjoint sets
859 860
    }

861
depVarsTyVars :: TcDepVars -> DTyVarSet
862 863 864 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
depVarsTyVars = dv_tvs

instance Outputable TcDepVars where
  ppr (DV {dv_kvs = kvs, dv_tvs = tvs })
    = text "DV" <+> braces (sep [ text "dv_kvs =" <+> ppr kvs
                                , text "dv_tvs =" <+> ppr tvs ])

{- Note [Dependent type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In Haskell type inference we quantify over type variables; but we only
quantify over /kind/ variables when -XPolyKinds is on. So when
collecting the free vars of a type, prior to quantifying, we must keep
the type and kind veraibles separate.  But what does that mean in a
system where kind variables /are/ type variables? It's a fairly
arbitrary distinction based on how the variables appear:

  - "Kind variables" appear in the kind of some other free variable
     PLUS any free coercion variables

  - "Type variables" are all free vars that are not kind variables

E.g.  In the type    T k (a::k)
      'k' is a kind variable, because it occurs in the kind of 'a',
          even though it also appears at "top level" of the type
      'a' is a type variable, becuase it doesn't

Note that

* We include any coercion variables in the "dependent",
  "kind-variable" set because we never quantify over them.

* Both sets are un-ordered, of course.

* The "kind variables" might depend on each other; e.g
     (k1 :: k2), (k2 :: *)
  The "type variables" do not depend on each other; if
  one did, it'd be classified as a kind variable!
899 900 901 902 903 904 905 906 907 908 909 910 911

Note [TcDepVars determinism]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we quantify over type variables we decide the order in which they
appear in the final type. Because the order of type variables in the type
can end up in the interface file and affects some optimizations like
worker-wrapper we want this order to be deterministic.

To achieve that we use deterministic sets of variables that can be converted to
lists in a deterministic order.

For more information about deterministic sets see
Note [Deterministic UniqFM] in UniqDFM.
912 913 914 915 916 917
-}

splitDepVarsOfType :: Type -> TcDepVars
-- See Note [Dependent type variables]
splitDepVarsOfType ty
  = DV { dv_kvs = dep_vars
918
       , dv_tvs = nondep_vars `minusDVarSet` dep_vars }
919 920 921 922 923 924 925 926
  where
    Pair dep_vars nondep_vars = split_dep_vars ty

-- | Like 'splitDepVarsOfType', but over a list of types
splitDepVarsOfTypes :: [Type] -> TcDepVars
-- See Note [Dependent type variables]
splitDepVarsOfTypes tys
  = DV { dv_kvs = dep_vars
927
       , dv_tvs = nondep_vars `minusDVarSet` dep_vars }
928 929 930 931 932
  where
    Pair dep_vars nondep_vars = foldMap split_dep_vars tys

-- | Worker for 'splitDepVarsOfType'. This might output the same var
-- in both sets, if it's used in both a type and a kind.
933 934
-- See Note [TcDepVars determinism]
split_dep_vars :: Type -> Pair DTyCoVarSet   -- Pair kvs tvs
935 936
split_dep_vars = go
  where
937 938
    go (TyVarTy tv)              = Pair (tyCoVarsOfTypeDSet $ tyVarKind tv)
                                        (unitDVarSet tv)
939 940 941 942 943
    go (AppTy t1 t2)             = go t1 `mappend` go t2
    go (TyConApp _ tys)          = foldMap go tys
    go (ForAllTy (Anon arg) res) = go arg `mappend` go res
    go (ForAllTy (Named tv _) ty)
      = let Pair kvs tvs = go ty in
944 945