TcPat.hs 51.3 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

TcPat: Typechecking patterns
Austin Seipp's avatar
Austin Seipp committed
7
-}
8

9
{-# LANGUAGE CPP, RankNTypes #-}
Ian Lynagh's avatar
Ian Lynagh committed
10

11 12
module TcPat ( tcLetPat, TcSigFun
             , TcPragEnv, lookupPragEnv, emptyPragEnv
13 14 15
             , TcSigInfo(..), TcIdSigInfo(..), TcPatSynInfo(..), TcIdSigBndr(..)
             , findScopedTyVars, isPartialSig, noCompleteSig
             , completeIdSigPolyId, completeSigPolyId_maybe, completeIdSigPolyId_maybe
16
             , LetBndrSpec(..), addInlinePrags
17
             , tcPat, tcPats, newNoSigLetBndr
18
             , addDataConStupidTheta, badFieldCon, polyPatSig ) where
19

20
#include "HsVersions.h"
21

22
import {-# SOURCE #-}   TcExpr( tcSyntaxOp, tcInferRho)
23 24 25

import HsSyn
import TcHsSyn
26
import TcRnMonad
27 28 29 30
import Inst
import Id
import Var
import Name
31
import NameSet
32
import NameEnv
Adam Gundry's avatar
Adam Gundry committed
33
import RdrName
34 35
import TcEnv
import TcMType
36
import TcValidity( arityErr )
37 38 39 40
import TcType
import TcUnify
import TcHsType
import TysWiredIn
41
import TcEvidence
42 43
import TyCon
import DataCon
cactus's avatar
cactus committed
44 45
import PatSyn
import ConLike
46 47
import PrelNames
import BasicTypes hiding (SuccessFlag(..))
48
import DynFlags
49 50
import SrcLoc
import Util
sof's avatar
sof committed
51
import Outputable
52
import FastString
53
import Maybes( orElse )
Ian Lynagh's avatar
Ian Lynagh committed
54
import Control.Monad
55

Austin Seipp's avatar
Austin Seipp committed
56 57 58
{-
************************************************************************
*                                                                      *
59
                External interface
Austin Seipp's avatar
Austin Seipp committed
60 61 62
*                                                                      *
************************************************************************
-}
63

64
tcLetPat :: TcSigFun -> LetBndrSpec
65 66 67
         -> LPat Name -> TcSigmaType
         -> TcM a
         -> TcM (LPat TcId, a)
68
tcLetPat sig_fn no_gen pat pat_ty thing_inside
69
  = tc_lpat pat pat_ty penv thing_inside
70
  where
71
    penv = PE { pe_lazy = True
72
              , pe_ctxt = LetPat sig_fn no_gen }
73 74

-----------------
75
tcPats :: HsMatchContext Name
76 77
       -> [LPat Name]            -- Patterns,
       -> [TcSigmaType]          --   and their types
78
       -> TcM a                  --   and the checker for the body
79
       -> TcM ([LPat TcId], a)
80 81 82

-- This is the externally-callable wrapper function
-- Typecheck the patterns, extend the environment to bind the variables,
83
-- do the thing inside, use any existentially-bound dictionaries to
84 85 86 87 88
-- discharge parts of the returning LIE, and deal with pattern type
-- signatures

--   1. Initialise the PatState
--   2. Check the patterns
89 90
--   3. Check the body
--   4. Check that no existentials escape
91

92
tcPats ctxt pats pat_tys thing_inside
93 94
  = tc_lpats penv pats pat_tys thing_inside
  where
95
    penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt }
96

97
tcPat :: HsMatchContext Name
98
      -> LPat Name -> TcSigmaType
99 100
      -> TcM a                 -- Checker for body, given
                               -- its result type
101
      -> TcM (LPat TcId, a)
102
tcPat ctxt pat pat_ty thing_inside
103 104
  = tc_lpat pat pat_ty penv thing_inside
  where
105
    penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt }
106

107

108
-----------------
109
data PatEnv
110 111
  = PE { pe_lazy :: Bool        -- True <=> lazy context, so no existentials allowed
       , pe_ctxt :: PatCtxt     -- Context in which the whole pattern appears
112
       }
113 114 115

data PatCtxt
  = LamPat   -- Used for lambdas, case etc
116
       (HsMatchContext Name)
117

118
  | LetPat   -- Used only for let(rec) pattern bindings
119
             -- See Note [Typing patterns in pattern bindings]
120 121 122
       TcSigFun        -- Tells type sig if any
       LetBndrSpec     -- True <=> no generalisation of this let

123 124 125
data LetBndrSpec
  = LetLclBndr            -- The binder is just a local one;
                          -- an AbsBinds will provide the global version
126

127
  | LetGblBndr TcPragEnv  -- Generalisation plan is NoGen, so there isn't going
128
                          -- to be an AbsBinds; So we must bind the global version
129
                          -- of the binder right away.
130
                          -- Oh, and here is the inline-pragma information
131

132 133 134
makeLazy :: PatEnv -> PatEnv
makeLazy penv = penv { pe_lazy = True }

135 136 137
inPatBind :: PatEnv -> Bool
inPatBind (PE { pe_ctxt = LetPat {} }) = True
inPatBind (PE { pe_ctxt = LamPat {} }) = False
138 139

---------------
140
type TcPragEnv = NameEnv [LSig Name]
141
type TcSigFun  = Name -> Maybe TcSigInfo
142

143 144 145 146 147 148
emptyPragEnv :: TcPragEnv
emptyPragEnv = emptyNameEnv

lookupPragEnv :: TcPragEnv -> Name -> [LSig Name]
lookupPragEnv prag_fn n = lookupNameEnv prag_fn n `orElse` []

149 150
data TcSigInfo = TcIdSig     TcIdSigInfo
               | TcPatSynSig TcPatSynInfo
thomasw's avatar
thomasw committed
151

152 153 154
data TcIdSigInfo
  = TISI {
        sig_bndr   :: TcIdSigBndr,
155

156
        sig_tvs    :: [(Maybe Name, TcTyVar)],
157 158
                           -- Instantiated type and kind variables
                           -- Just n <=> this skolem is lexically in scope with name n
159
                           -- See Note [Binding scoped type variables]
160

Simon Peyton Jones's avatar
Simon Peyton Jones committed
161
        sig_theta  :: TcThetaType,  -- Instantiated theta
162
        sig_tau    :: TcSigmaType,  -- Instantiated tau
163
                                    -- See Note [sig_tau may be polymorphic]
164

165 166
        sig_ctxt   :: UserTypeCtxt, -- FunSigCtxt or CheckSigCtxt
        sig_loc    :: SrcSpan       -- Location of the type signature
167
    }
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

data TcIdSigBndr   -- See Note [Complete and partial type signatures]
  = CompleteSig    -- A complete signature with no wildards,
                   -- so the complete polymorphic type is known.
        TcId          -- The polymoprhic Id with that type

  | PartialSig     -- A partial type signature (i.e. includes one or more
                   -- wildcards). In this case it doesn't make sense to give
                   -- the polymorphic Id, because we are going to /infer/ its
                   -- type, so we can't make the polymorphic Id ab-initio
       { sig_name  :: Name              -- Name of the function
       , sig_hs_ty :: LHsType Name      -- The original partial signatur
       , sig_nwcs  :: [(Name, TcTyVar)] -- Instantiated wildcard variables
       , sig_cts   :: Maybe SrcSpan     -- Just loc <=> An extra-constraints wildcard was present
       }                                --              at location loc
                                        --   e.g.   f :: (Eq a, _) => a -> a
                                        -- Any extra constraints inferred during
                                        -- type-checking will be added to the sig_theta.
186 187 188 189 190 191 192 193 194 195

data TcPatSynInfo
  = TPSI {
        patsig_name  :: Name,
        patsig_tau   :: TcSigmaType,
        patsig_ex    :: [TcTyVar],
        patsig_prov  :: TcThetaType,
        patsig_univ  :: [TcTyVar],
        patsig_req   :: TcThetaType
    }
196

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
findScopedTyVars  -- See Note [Binding scoped type variables]
  :: LHsType Name             -- The HsType
  -> TcType                   -- The corresponding Type:
                              --   uses same Names as the HsType
  -> [TcTyVar]                -- The instantiated forall variables of the Type
  -> [(Maybe Name, TcTyVar)]  -- In 1-1 correspondence with the instantiated vars
findScopedTyVars hs_ty sig_ty inst_tvs
  = zipWith find sig_tvs inst_tvs
  where
    find sig_tv inst_tv
      | tv_name `elemNameSet` scoped_names = (Just tv_name, inst_tv)
      | otherwise                          = (Nothing,      inst_tv)
      where
        tv_name = tyVarName sig_tv

    scoped_names = mkNameSet (hsExplicitTvs hs_ty)
    (sig_tvs,_)  = tcSplitForAllTys sig_ty

215 216
instance NamedThing TcIdSigInfo where
    getName (TISI { sig_bndr = bndr }) = getName bndr
217

218 219 220 221 222 223 224
instance NamedThing TcIdSigBndr where
    getName (CompleteSig id)              = idName id
    getName (PartialSig { sig_name = n }) = n

instance NamedThing TcSigInfo where
    getName (TcIdSig     idsi) = getName     idsi
    getName (TcPatSynSig tpsi) = patsig_name tpsi
thomasw's avatar
thomasw committed
225

226
instance Outputable TcSigInfo where
227 228 229 230 231 232 233
  ppr (TcIdSig     idsi) = ppr idsi
  ppr (TcPatSynSig tpsi) = text "TcPatSynInfo" <+> ppr tpsi

instance Outputable TcIdSigInfo where
    ppr (TISI { sig_bndr = bndr, sig_tvs = tyvars
              , sig_theta = theta, sig_tau = tau })
        = ppr bndr <+> dcolon <+>
thomasw's avatar
thomasw committed
234 235
          vcat [ pprSigmaType (mkSigmaTy (map snd tyvars) theta tau)
               , ppr (map fst tyvars) ]
236 237 238

instance Outputable TcIdSigBndr where
  ppr s_bndr = ppr (getName s_bndr)
239 240 241 242

instance Outputable TcPatSynInfo where
    ppr (TPSI{ patsig_name = name}) = ppr name

243 244 245 246 247 248 249 250
isPartialSig :: TcIdSigInfo -> Bool
isPartialSig (TISI { sig_bndr = PartialSig {} }) = True
isPartialSig _                                   = False

-- | No signature or a partial signature
noCompleteSig :: Maybe TcSigInfo -> Bool
noCompleteSig (Just (TcIdSig sig)) = isPartialSig sig
noCompleteSig _                    = True
thomasw's avatar
thomasw committed
251 252 253

-- Helper for cases when we know for sure we have a complete type
-- signature, e.g. class methods.
254 255 256 257 258 259 260
completeIdSigPolyId :: TcIdSigInfo -> TcId
completeIdSigPolyId (TISI { sig_bndr = CompleteSig id }) = id
completeIdSigPolyId _ = panic "completeSigPolyId"

completeIdSigPolyId_maybe :: TcIdSigInfo -> Maybe TcId
completeIdSigPolyId_maybe (TISI { sig_bndr = CompleteSig id }) = Just id
completeIdSigPolyId_maybe _                                    = Nothing
261

262
completeSigPolyId_maybe :: TcSigInfo -> Maybe TcId
263 264
completeSigPolyId_maybe (TcIdSig sig)    = completeIdSigPolyId_maybe sig
completeSigPolyId_maybe (TcPatSynSig {}) = Nothing
265

Austin Seipp's avatar
Austin Seipp committed
266
{-
267 268 269 270 271 272 273
Note [Binding scoped type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The type variables *brought into lexical scope* by a type signature may
be a subset of the *quantified type variables* of the signatures, for two reasons:

* With kind polymorphism a signature like
    f :: forall f a. f a -> f a
274
  may actually give rise to
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    f :: forall k. forall (f::k -> *) (a:k). f a -> f a
  So the sig_tvs will be [k,f,a], but only f,a are scoped.
  NB: the scoped ones are not necessarily the *inital* ones!

* Even aside from kind polymorphism, tere may be more instantiated
  type variables than lexically-scoped ones.  For example:
        type T a = forall b. b -> (a,b)
        f :: forall c. T c
  Here, the signature for f will have one scoped type variable, c,
  but two instantiated type variables, c' and b'.

The function findScopedTyVars takes
  * hs_ty:    the original HsForAllTy
  * sig_ty:   the corresponding Type (which is guaranteed to use the same Names
              as the HsForAllTy)
  * inst_tvs: the skolems instantiated from the forall's in sig_ty
It returns a [(Maybe Name, TcTyVar)], in 1-1 correspondence with inst_tvs
but with a (Just n) for the lexically scoped name of each in-scope tyvar.
293

294 295 296 297 298 299 300
Note [sig_tau may be polymorphic]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Note that "sig_tau" might actually be a polymorphic type,
if the original function had a signature like
   forall a. Eq a => forall b. Ord b => ....
But that's ok: tcMatchesFun (called by tcRhs) can deal with that
It happens, too!  See Note [Polymorphic methods] in TcClassDcl.
301

302 303 304 305 306
Note [Existential check]
~~~~~~~~~~~~~~~~~~~~~~~~
Lazy patterns can't bind existentials.  They arise in two ways:
  * Let bindings      let { C a b = e } in b
  * Twiddle patterns  f ~(C a b) = e
307
The pe_lazy field of PatEnv says whether we are inside a lazy
308
pattern (perhaps deeply)
309

310 311 312 313 314
If we aren't inside a lazy pattern then we can bind existentials,
but we need to be careful about "extra" tyvars. Consider
    (\C x -> d) : pat_ty -> res_ty
When looking for existential escape we must check that the existential
bound by C don't unify with the free variables of pat_ty, OR res_ty
315
(or of course the environment).   Hence we need to keep track of the
316
res_ty free vars.
317

thomasw's avatar
thomasw committed
318 319
Note [Complete and partial type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
320 321
A type signature is partial when it contains one or more wildcards
(= type holes).  The wildcard can either be:
thomasw's avatar
thomasw committed
322 323 324 325
* A (type) wildcard occurring in sig_theta or sig_tau. These are
  stored in sig_nwcs.
      f :: Bool -> _
      g :: Eq _a => _a -> _a -> Bool
326
* Or an extra-constraints wildcard, stored in sig_cts:
thomasw's avatar
thomasw committed
327 328 329 330 331
      h :: (Num a, _) => a -> a

A type signature is a complete type signature when there are no
wildcards in the type signature, i.e. iff sig_nwcs is empty and
sig_extra_cts is Nothing.
332

Austin Seipp's avatar
Austin Seipp committed
333 334
************************************************************************
*                                                                      *
335
                Binders
Austin Seipp's avatar
Austin Seipp committed
336 337 338
*                                                                      *
************************************************************************
-}
339

340
tcPatBndr :: PatEnv -> Name -> TcSigmaType -> TcM (TcCoercion, TcId)
341 342 343 344
-- (coi, xp) = tcPatBndr penv x pat_ty
-- Then coi : pat_ty ~ typeof(xp)
--
tcPatBndr (PE { pe_ctxt = LetPat lookup_sig no_gen}) bndr_name pat_ty
345
          -- See Note [Typing patterns in pattern bindings]
346 347 348
  | LetGblBndr prags   <- no_gen
  , Just (TcIdSig sig) <- lookup_sig bndr_name
  , Just poly_id <- completeIdSigPolyId_maybe sig
349
  = do { bndr_id <- addInlinePrags poly_id (lookupPragEnv prags bndr_name)
350
       ; traceTc "tcPatBndr(gbl,sig)" (ppr bndr_id $$ ppr (idType bndr_id))
batterseapower's avatar
batterseapower committed
351 352
       ; co <- unifyPatType (idType bndr_id) pat_ty
       ; return (co, bndr_id) }
353 354

  | otherwise
355
  = do { bndr_id <- newNoSigLetBndr no_gen bndr_name pat_ty
356
       ; traceTc "tcPatBndr(no-sig)" (ppr bndr_id $$ ppr (idType bndr_id))
357
       ; return (mkTcNomReflCo pat_ty, bndr_id) }
358 359

tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty
360
  = return (mkTcNomReflCo pat_ty, mkLocalId bndr_name pat_ty)
361

362 363
------------
newNoSigLetBndr :: LetBndrSpec -> Name -> TcType -> TcM TcId
364
-- In the polymorphic case (no_gen = LetLclBndr), generate a "monomorphic version"
365 366
--    of the Id; the original name will be bound to the polymorphic version
--    by the AbsBinds
367
-- In the monomorphic case (no_gen = LetBglBndr) there is no AbsBinds, and we
368
--    use the original name directly
369
newNoSigLetBndr LetLclBndr name ty
370
  =do  { mono_name <- newLocalName name
371
       ; return (mkLocalId mono_name ty) }
372
newNoSigLetBndr (LetGblBndr prags) name ty
373
  = addInlinePrags (mkLocalId name ty) (lookupPragEnv prags name)
374 375 376 377

----------
addInlinePrags :: TcId -> [LSig Name] -> TcM TcId
addInlinePrags poly_id prags
378 379 380 381 382 383
  | inl@(L _ prag) : inls <- inl_prags
  = do { traceTc "addInlinePrag" (ppr poly_id $$ ppr prag)
       ; unless (null inls) (warn_multiple_inlines inl inls)
       ; return (poly_id `setInlinePragma` prag) }
  | otherwise
  = return poly_id
384
  where
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    inl_prags = [L loc prag | L loc (InlineSig _ prag) <- prags]

    warn_multiple_inlines _ [] = return ()

    warn_multiple_inlines inl1@(L loc prag1) (inl2@(L _ prag2) : inls)
       | inlinePragmaActivation prag1 == inlinePragmaActivation prag2
       , isEmptyInlineSpec (inlinePragmaSpec prag1)
       =    -- Tiresome: inl1 is put there by virtue of being in a hs-boot loop
            -- and inl2 is a user NOINLINE pragma; we don't want to complain
         warn_multiple_inlines inl2 inls
       | otherwise
       = setSrcSpan loc $
         addWarnTc (hang (ptext (sLit "Multiple INLINE pragmas for") <+> ppr poly_id)
                       2 (vcat (ptext (sLit "Ignoring all but the first")
                                : map pp_inl (inl1:inl2:inls))))

    pp_inl (L loc prag) = ppr prag <+> parens (ppr loc)
402

Austin Seipp's avatar
Austin Seipp committed
403
{-
404 405 406 407 408 409 410 411
Note [Typing patterns in pattern bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are typing a pattern binding
    pat = rhs
Then the PatCtxt will be (LetPat sig_fn let_bndr_spec).

There can still be signatures for the binders:
     data T = MkT (forall a. a->a) Int
412
     x :: forall a. a->a
413 414 415 416 417 418 419 420 421 422
     y :: Int
     MkT x y = <rhs>

Two cases, dealt with by the LetPat case of tcPatBndr

 * If we are generalising (generalisation plan is InferGen or
   CheckGen), then the let_bndr_spec will be LetLclBndr.  In that case
   we want to bind a cloned, local version of the variable, with the
   type given by the pattern context, *not* by the signature (even if
   there is one; see Trac #7268). The mkExport part of the
Gabor Greif's avatar
Gabor Greif committed
423
   generalisation step will do the checking and impedance matching
424 425 426 427 428 429 430 431
   against the signature.

 * If for some some reason we are not generalising (plan = NoGen), the
   LetBndrSpec will be LetGblBndr.  In that case we must bind the
   global version of the Id, and do so with precisely the type given
   in the signature.  (Then we unify with the type from the pattern
   context type.

432

Austin Seipp's avatar
Austin Seipp committed
433 434
************************************************************************
*                                                                      *
435
                The main worker functions
Austin Seipp's avatar
Austin Seipp committed
436 437
*                                                                      *
************************************************************************
438

439 440
Note [Nesting]
~~~~~~~~~~~~~~
lennart@augustsson.net's avatar
lennart@augustsson.net committed
441
tcPat takes a "thing inside" over which the pattern scopes.  This is partly
442
so that tcPat can extend the environment for the thing_inside, but also
443 444 445 446
so that constraints arising in the thing_inside can be discharged by the
pattern.

This does not work so well for the ErrCtxt carried by the monad: we don't
447
want the error-context for the pattern to scope over the RHS.
448
Hence the getErrCtxt/setErrCtxt stuff in tcMultiple
Austin Seipp's avatar
Austin Seipp committed
449
-}
450 451

--------------------
452
type Checker inp out =  forall r.
453 454 455 456
                          inp
                       -> PatEnv
                       -> TcM r
                       -> TcM (out, r)
457 458

tcMultiple :: Checker inp out -> Checker [inp] [out]
459
tcMultiple tc_pat args penv thing_inside
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
  = do  { err_ctxt <- getErrCtxt
        ; let loop _ []
                = do { res <- thing_inside
                     ; return ([], res) }

              loop penv (arg:args)
                = do { (p', (ps', res))
                                <- tc_pat arg penv $
                                   setErrCtxt err_ctxt $
                                   loop penv args
                -- setErrCtxt: restore context before doing the next pattern
                -- See note [Nesting] above

                     ; return (p':ps', res) }

        ; loop penv args }
476 477

--------------------
478 479 480 481 482
tc_lpat :: LPat Name
        -> TcSigmaType
        -> PatEnv
        -> TcM a
        -> TcM (LPat TcId, a)
483
tc_lpat (L span pat) pat_ty penv thing_inside
484
  = setSrcSpan span $
485
    do  { (pat', res) <- maybeWrapPatCtxt pat (tc_pat penv pat pat_ty)
486
                                          thing_inside
487
        ; return (L span pat', res) }
488 489

tc_lpats :: PatEnv
490 491 492 493
         -> [LPat Name] -> [TcSigmaType]
         -> TcM a
         -> TcM ([LPat TcId], a)
tc_lpats penv pats tys thing_inside
Simon Peyton Jones's avatar
Simon Peyton Jones committed
494
  = ASSERT2( equalLength pats tys, ppr pats $$ ppr tys )
495
    tcMultiple (\(p,t) -> tc_lpat p t)
496
                (zipEqual "tc_lpats" pats tys)
497
                penv thing_inside
498 499

--------------------
500 501 502 503 504 505
tc_pat  :: PatEnv
        -> Pat Name
        -> TcSigmaType  -- Fully refined result type
        -> TcM a                -- Thing inside
        -> TcM (Pat TcId,       -- Translated pattern
                a)              -- Result of thing inside
506

507
tc_pat penv (VarPat (L l name)) pat_ty thing_inside
508
  = do  { (co, id) <- tcPatBndr penv name pat_ty
batterseapower's avatar
batterseapower committed
509
        ; res <- tcExtendIdEnv1 name id thing_inside
510
        ; return (mkHsWrapPatCo co (VarPat (L l id)) pat_ty, res) }
511 512

tc_pat penv (ParPat pat) pat_ty thing_inside
513 514
  = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
        ; return (ParPat pat', res) }
515 516

tc_pat penv (BangPat pat) pat_ty thing_inside
517 518
  = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
        ; return (BangPat pat', res) }
519

520
tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside
521 522 523 524
  = do  { (pat', (res, pat_ct))
                <- tc_lpat pat pat_ty (makeLazy penv) $
                   captureConstraints thing_inside
                -- Ignore refined penv', revert to penv
525

526 527
        ; emitConstraints pat_ct
        -- captureConstraints/extendConstraints:
528
        --   see Note [Hopping the LIE in lazy patterns]
529

530 531
        -- Check there are no unlifted types under the lazy pattern
        ; when (any (isUnLiftedType . idType) $ collectPatBinders pat') $
532 533
               lazyUnliftedPatErr lpat

534 535 536
        -- Check that the expected pattern type is itself lifted
        ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
        ; _ <- unifyType pat_ty pat_ty'
537

538
        ; return (LazyPat pat', res) }
539

540
tc_pat _ (WildPat _) pat_ty thing_inside
541 542
  = do  { res <- thing_inside
        ; return (WildPat pat_ty, res) }
543

544
tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
545
  = do  { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
batterseapower's avatar
batterseapower committed
546
        ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
547 548 549 550 551 552 553 554 555 556 557 558 559
                         tc_lpat pat (idType bndr_id) penv thing_inside
            -- NB: if we do inference on:
            --          \ (y@(x::forall a. a->a)) = e
            -- we'll fail.  The as-pattern infers a monotype for 'y', which then
            -- fails to unify with the polymorphic type for 'x'.  This could
            -- perhaps be fixed, but only with a bit more work.
            --
            -- If you fix it, don't forget the bindInstsOfPatIds!
        ; return (mkHsWrapPatCo co (AsPat (L nm_loc bndr_id) pat') pat_ty, res) }

tc_pat penv (ViewPat expr pat _) overall_pat_ty thing_inside
  = do  {
         -- Morally, expr must have type `forall a1...aN. OPT' -> B`
560 561 562 563
         -- where overall_pat_ty is an instance of OPT'.
         -- Here, we infer a rho type for it,
         -- which replaces the leading foralls and constraints
         -- with fresh unification variables.
564 565
        ; (expr',expr'_inferred) <- tcInferRho expr

566
         -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
567
         -- NOTE: this forces pat_ty to be a monotype (because we use a unification
568 569 570 571
         -- variable to find it).  this means that in an example like
         -- (view -> f)    where view :: _ -> forall b. b
         -- we will only be able to use view at one instantation in the
         -- rest of the view
572 573 574
        ; (expr_co, pat_ty) <- tcInfer $ \ pat_ty ->
                unifyType expr'_inferred (mkFunTy overall_pat_ty pat_ty)

575
         -- pattern must have pat_ty
576 577
        ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside

578
        ; return (ViewPat (mkLHsWrapCo expr_co expr') pat' overall_pat_ty, res) }
579

580 581
-- Type signatures in patterns
-- See Note [Pattern coercions] below
582
tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
thomasw's avatar
thomasw committed
583 584 585
  = do  { (inner_ty, tv_binds, nwc_binds, wrap) <- tcPatSig (inPatBind penv)
                                                            sig_ty pat_ty
        ; (pat', res) <- tcExtendTyVarEnv2 (tv_binds ++ nwc_binds) $
586
                         tc_lpat pat inner_ty penv thing_inside
587
        ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
588 589 590

------------------------
-- Lists, tuples, arrays
591
tc_pat penv (ListPat pats _ Nothing) pat_ty thing_inside
592
  = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTyR pat_ty
593
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
594 595
                                     pats penv thing_inside
        ; return (mkHsWrapPat coi (ListPat pats' elt_ty Nothing) pat_ty, res)
596 597 598
        }

tc_pat penv (ListPat pats _ (Just (_,e))) pat_ty thing_inside
599
  = do  { list_pat_ty <- newFlexiTyVarTy liftedTypeKind
600
        ; e' <- tcSyntaxOp ListOrigin e (mkFunTy pat_ty list_pat_ty)
601
        ; (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTyR list_pat_ty
602
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
603 604
                                     pats penv thing_inside
        ; return (mkHsWrapPat coi (ListPat pats' elt_ty (Just (pat_ty,e'))) list_pat_ty, res)
605
        }
606

607
tc_pat penv (PArrPat pats _) pat_ty thing_inside
608
  = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTyR pat_ty
609 610 611
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
                                     pats penv thing_inside
        ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
612
        }
613

614
tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
615
  = do  { let tc = tupleTyCon boxity (length pats)
616
        ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConAppR tc) pat_ty
617
        ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
618

619
        ; dflags <- getDynFlags
620

621 622 623 624 625
        -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
        -- so that we can experiment with lazy tuple-matching.
        -- This is a pretty odd place to make the switch, but
        -- it was easy to do.
        ; let
626 627
              unmangled_result = TuplePat pats' boxity arg_tys
                                 -- pat_ty /= pat_ty iff coi /= IdCo
628 629
              possibly_mangled_result
                | gopt Opt_IrrefutableTuples dflags &&
630
                  isBoxed boxity            = LazyPat (noLoc unmangled_result)
631
                | otherwise                 = unmangled_result
632

633 634
        ; ASSERT( length arg_tys == length pats )      -- Syntactically enforced
          return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
635
        }
636 637 638

------------------------
-- Data constructors
639 640
tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
  = tcConPat penv con pat_ty arg_pats thing_inside
641 642 643

------------------------
-- Literal patterns
644
tc_pat _ (LitPat simple_lit) pat_ty thing_inside
645 646 647 648 649
  = do  { let lit_ty = hsLitType simple_lit
        ; co <- unifyPatType lit_ty pat_ty
                -- coi is of kind: pat_ty ~ lit_ty
        ; res <- thing_inside
        ; return ( mkHsWrapPatCo co (LitPat simple_lit) pat_ty
650
                 , res) }
651 652 653

------------------------
-- Overloaded patterns: n, and n+k
Alan Zimmerman's avatar
Alan Zimmerman committed
654
tc_pat _ (NPat (L l over_lit) mb_neg eq) pat_ty thing_inside
655 656 657 658 659 660 661 662 663 664
  = do  { let orig = LiteralOrigin over_lit
        ; lit'    <- newOverloadedLit orig over_lit pat_ty
        ; eq'     <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
        ; mb_neg' <- case mb_neg of
                        Nothing  -> return Nothing      -- Positive literal
                        Just neg ->     -- Negative literal
                                        -- The 'negate' is re-mappable syntax
                            do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
                               ; return (Just neg') }
        ; res <- thing_inside
Alan Zimmerman's avatar
Alan Zimmerman committed
665
        ; return (NPat (L l lit') mb_neg' eq', res) }
666

Alan Zimmerman's avatar
Alan Zimmerman committed
667
tc_pat penv (NPlusKPat (L nm_loc name) (L loc lit) ge minus) pat_ty thing_inside
668
  = do  { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
batterseapower's avatar
batterseapower committed
669
        ; let pat_ty' = idType bndr_id
670 671
              orig    = LiteralOrigin lit
        ; lit' <- newOverloadedLit orig lit pat_ty'
672

673 674 675
        -- The '>=' and '-' parts are re-mappable syntax
        ; ge'    <- tcSyntaxOp orig ge    (mkFunTys [pat_ty', pat_ty'] boolTy)
        ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
Alan Zimmerman's avatar
Alan Zimmerman committed
676
        ; let pat' = NPlusKPat (L nm_loc bndr_id) (L loc lit') ge' minus'
677

678 679 680 681
        -- The Report says that n+k patterns must be in Integral
        -- We may not want this when using re-mappable syntax, though (ToDo?)
        ; icls <- tcLookupClass integralClassName
        ; instStupidTheta orig [mkClassPred icls [pat_ty']]
682

683 684 685 686
        ; res <- tcExtendIdEnv1 name bndr_id thing_inside
        ; return (mkHsWrapPatCo co pat' pat_ty, res) }

tc_pat _ _other_pat _ _ = panic "tc_pat"        -- ConPatOut, SigPatOut
687 688

----------------
689
unifyPatType :: TcType -> TcType -> TcM TcCoercion
690 691 692 693 694 695
-- In patterns we want a coercion from the
-- context type (expected) to the actual pattern type
-- But we don't want to reverse the args to unifyType because
-- that controls the actual/expected stuff in error messages
unifyPatType actual_ty expected_ty
  = do { coi <- unifyType actual_ty expected_ty
696
       ; return (mkTcSymCo coi) }
697

Austin Seipp's avatar
Austin Seipp committed
698
{-
699 700 701 702
Note [Hopping the LIE in lazy patterns]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a lazy pattern, we must *not* discharge constraints from the RHS
from dictionaries bound in the pattern.  E.g.
703
        f ~(C x) = 3
704
We can't discharge the Num constraint from dictionaries bound by
705
the pattern C!
706

707
So we have to make the constraints from thing_inside "hop around"
708
the pattern.  Hence the captureConstraints and emitConstraints.
709 710 711

The same thing ensures that equality constraints in a lazy match
are not made available in the RHS of the match. For example
712 713 714
        data T a where { T1 :: Int -> T Int; ... }
        f :: T a -> Int -> a
        f ~(T1 i) y = y
715
It's obviously not sound to refine a to Int in the right
716
hand side, because the argument might not match T1 at all!
717 718 719 720

Finally, a lazy pattern should not bind any existential type variables
because they won't be in scope when we do the desugaring

721

Austin Seipp's avatar
Austin Seipp committed
722 723
************************************************************************
*                                                                      *
724 725
        Most of the work for constructors is here
        (the rest is in the ConPatIn case of tc_pat)
Austin Seipp's avatar
Austin Seipp committed
726 727
*                                                                      *
************************************************************************
728

729 730 731 732 733 734 735 736 737 738 739
[Pattern matching indexed data types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following declarations:

  data family Map k :: * -> *
  data instance Map (a, b) v = MapPair (Map a (Pair b v))

and a case expression

  case x :: Map (Int, c) w of MapPair m -> ...

740
As explained by [Wrappers for data instance tycons] in MkIds.hs, the
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
worker/wrapper types for MapPair are

  $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
  $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v

So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
:R123Map, which means the straight use of boxySplitTyConApp would give a type
error.  Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
boxySplitTyConApp with the family tycon Map instead, which gives us the family
type list {(Int, c), w}.  To get the correct split for :R123Map, we need to
unify the family type list {(Int, c), w} with the instance types {(a, b), v}
(provided by tyConFamInst_maybe together with the family tycon).  This
unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
the split arguments for the representation tycon :R123Map as {Int, c, w}

756
In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
757

758
  Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
759 760 761 762 763 764

moving between representation and family type into account.  To produce type
correct Core, this coercion needs to be used to case the type of the scrutinee
from the family to the representation type.  This is achieved by
unwrapFamInstScrutinee using a CoPat around the result pattern.

765
Now it might appear seem as if we could have used the previous GADT type
766 767 768 769 770 771 772 773 774 775 776 777
refinement infrastructure of refineAlt and friends instead of the explicit
unification and CoPat generation.  However, that would be wrong.  Why?  The
whole point of GADT refinement is that the refinement is local to the case
alternative.  In contrast, the substitution generated by the unification of
the family type list and instance types needs to be propagated to the outside.
Imagine that in the above example, the type of the scrutinee would have been
(Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
substitution [x -> (a, b), v -> w].  In contrast to GADT matching, the
instantiation of x with (a, b) must be global; ie, it must be valid in *all*
alternatives of the case expression, whereas in the GADT case it might vary
between alternatives.

778 779 780
RIP GADT refinement: refinements have been replaced by the use of explicit
equality constraints that are used in conjunction with implication constraints
to express the local scope of GADT refinements.
Austin Seipp's avatar
Austin Seipp committed
781
-}
782

783
--      Running example:
784
-- MkT :: forall a b c. (a~[b]) => b -> c -> T a
785
--       with scrutinee of type (T ty)
786

787 788 789 790
tcConPat :: PatEnv -> Located Name
         -> TcRhoType           -- Type of the pattern
         -> HsConPatDetails Name -> TcM a
         -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
791 792 793 794 795 796 797 798 799 800
tcConPat penv con_lname@(L _ con_name) pat_ty arg_pats thing_inside
  = do  { con_like <- tcLookupConLike con_name
        ; case con_like of
            RealDataCon data_con -> tcDataConPat penv con_lname data_con
                                                 pat_ty arg_pats thing_inside
            PatSynCon pat_syn -> tcPatSynPat penv con_lname pat_syn
                                             pat_ty arg_pats thing_inside
        }

tcDataConPat :: PatEnv -> Located Name -> DataCon
801 802 803
             -> TcRhoType               -- Type of the pattern
             -> HsConPatDetails Name -> TcM a
             -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
804
tcDataConPat penv (L con_span con_name) data_con pat_ty arg_pats thing_inside
805 806 807
  = do  { let tycon = dataConTyCon data_con
                  -- For data families this is the representation tycon
              (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _)
808
                = dataConFullSig data_con
cactus's avatar
cactus committed
809
              header = L con_span (RealDataCon data_con)
810

811 812 813 814
          -- Instantiate the constructor type variables [a->ty]
          -- This may involve doing a family-instance coercion,
          -- and building a wrapper
        ; (wrap, ctxt_res_tys) <- matchExpectedPatTy (matchExpectedConTy tycon) pat_ty
815

816 817
          -- Add the stupid theta
        ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
818

819
        ; checkExistentials ex_tvs penv
820 821
        ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX
                               (zipTopTvSubst univ_tvs ctxt_res_tys) ex_tvs
822 823
                     -- Get location from monad, not from ex_tvs

824
        ; let -- pat_ty' = mkTyConApp tycon ctxt_res_tys
825
              -- pat_ty' is type of the actual constructor application
826
              -- pat_ty' /= pat_ty iff coi /= IdCo
Simon Peyton Jones's avatar
Simon Peyton Jones committed
827

828
              arg_tys' = substTys tenv arg_tys
829

Simon Peyton Jones's avatar
Simon Peyton Jones committed
830
        ; traceTc "tcConPat" (vcat [ ppr con_name, ppr univ_tvs, ppr ex_tvs, ppr eq_spec
831
                                   , ppr ex_tvs', ppr ctxt_res_tys, ppr arg_tys' ])
832 833
        ; if null ex_tvs && null eq_spec && null theta
          then do { -- The common case; no class bindings etc
834
                    -- (see Note [Arrows and patterns])
835 836 837 838
                    (arg_pats', res) <- tcConArgs (RealDataCon data_con) arg_tys'
                                                  arg_pats penv thing_inside
                  ; let res_pat = ConPatOut { pat_con = header,
                                              pat_tvs = [], pat_dicts = [],
839
                                              pat_binds = emptyTcEvBinds,
840
                                              pat_args = arg_pats',
841
                                              pat_arg_tys = ctxt_res_tys,
cactus's avatar
cactus committed
842
                                              pat_wrap = idHsWrapper }
843

844
                  ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
845

846
          else do   -- The general case, with existential,
847
                    -- and local equality constraints
848
        { let theta'   = substTheta tenv (eqSpecPreds eq_spec ++ theta)
849 850
                           -- order is *important* as we generate the list of
                           -- dictionary binders from theta'
851
              no_equalities = not (any isEqPred theta')
852
              skol_info = case pe_ctxt penv of
cactus's avatar
cactus committed
853
                            LamPat mc -> PatSkol (RealDataCon data_con) mc
854
                            LetPat {} -> UnkSkol -- Doesn't matter
855

856 857
        ; gadts_on    <- xoptM Opt_GADTs
        ; families_on <- xoptM Opt_TypeFamilies
858
        ; checkTc (no_equalities || gadts_on || families_on)
sivteck's avatar
sivteck committed
859 860
                  (text "A pattern match on a GADT requires the" <+>
                   text "GADTs or TypeFamilies language extension")
861 862 863
                  -- Trac #2905 decided that a *pattern-match* of a GADT
                  -- should require the GADT language flag.
                  -- Re TypeFamilies see also #7156
864

865
        ; given <- newEvVars theta'
866
        ; (ev_binds, (arg_pats', res))
Austin Seipp's avatar