TcPat.hs 50.1 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
module TcPat ( tcLetPat, TcSigFun, TcPragFun
12
             , TcSigInfo(..), TcPatSynInfo(..)
13 14
             , findScopedTyVars, isPartialSig
             , completeSigPolyId, completeSigPolyId_maybe
15
             , LetBndrSpec(..), addInlinePrags, warnPrags
16
             , tcPat, tcPats, newNoSigLetBndr
17
             , addDataConStupidTheta, badFieldCon, polyPatSig ) where
18

19
#include "HsVersions.h"
20

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

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

59
tcLetPat :: TcSigFun -> LetBndrSpec
60 61 62
         -> LPat Name -> TcSigmaType
         -> TcM a
         -> TcM (LPat TcId, a)
63
tcLetPat sig_fn no_gen pat pat_ty thing_inside
64
  = tc_lpat pat pat_ty penv thing_inside
65
  where
66
    penv = PE { pe_lazy = True
67
              , pe_ctxt = LetPat sig_fn no_gen }
68 69

-----------------
70
tcPats :: HsMatchContext Name
71 72
       -> [LPat Name]            -- Patterns,
       -> [TcSigmaType]          --   and their types
73
       -> TcM a                  --   and the checker for the body
74
       -> TcM ([LPat TcId], a)
75 76 77

-- This is the externally-callable wrapper function
-- Typecheck the patterns, extend the environment to bind the variables,
78
-- do the thing inside, use any existentially-bound dictionaries to
79 80 81 82 83
-- discharge parts of the returning LIE, and deal with pattern type
-- signatures

--   1. Initialise the PatState
--   2. Check the patterns
84 85
--   3. Check the body
--   4. Check that no existentials escape
86

87
tcPats ctxt pats pat_tys thing_inside
88 89
  = tc_lpats penv pats pat_tys thing_inside
  where
90
    penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt }
91

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

102

103
-----------------
104
data PatEnv
105 106
  = PE { pe_lazy :: Bool        -- True <=> lazy context, so no existentials allowed
       , pe_ctxt :: PatCtxt     -- Context in which the whole pattern appears
107
       }
108 109 110

data PatCtxt
  = LamPat   -- Used for lambdas, case etc
111
       (HsMatchContext Name)
112

113
  | LetPat   -- Used only for let(rec) pattern bindings
114
             -- See Note [Typing patterns in pattern bindings]
115 116 117
       TcSigFun        -- Tells type sig if any
       LetBndrSpec     -- True <=> no generalisation of this let

118 119 120
data LetBndrSpec
  = LetLclBndr            -- The binder is just a local one;
                          -- an AbsBinds will provide the global version
121

122
  | LetGblBndr TcPragFun  -- Generalisation plan is NoGen, so there isn't going
123
                          -- to be an AbsBinds; So we must bind the global version
124
                          -- of the binder right away.
125
                          -- Oh, and here is the inline-pragma information
126

127 128 129
makeLazy :: PatEnv -> PatEnv
makeLazy penv = penv { pe_lazy = True }

130 131 132
inPatBind :: PatEnv -> Bool
inPatBind (PE { pe_ctxt = LetPat {} }) = True
inPatBind (PE { pe_ctxt = LamPat {} }) = False
133 134

---------------
135 136
type TcPragFun = Name -> [LSig Name]
type TcSigFun  = Name -> Maybe TcSigInfo
137 138 139

data TcSigInfo
  = TcSigInfo {
thomasw's avatar
thomasw committed
140 141 142 143
        sig_name    :: Name,  -- The binder name of the type signature. When
                              -- sig_id = Just id, then sig_name = idName id.

        sig_poly_id :: Maybe TcId,
144
             -- Just f <=> the type signature had no wildcards, so the precise,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
145 146
             --            complete polymorphic type is known.  In that case,
             --            f is the polymorphic Id, with that type
147

Simon Peyton Jones's avatar
Simon Peyton Jones committed
148 149 150 151 152 153
             -- Nothing <=> the type signature is partial (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
             --
             -- See Note [Complete and partial type signatures]
154

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

thomasw's avatar
thomasw committed
160 161
        sig_nwcs   :: [(Name, TcTyVar)],
                           -- Instantiated wildcard variables
Simon Peyton Jones's avatar
Simon Peyton Jones committed
162
                           -- If sig_poly_id = Just f, then sig_nwcs must be empty
thomasw's avatar
thomasw committed
163

164
        sig_extra_cts :: Maybe SrcSpan,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
165 166 167 168 169 170
                           -- 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.
                           -- If sig_poly_id = Just f, sig_extra_cts must be Nothing
thomasw's avatar
thomasw committed
171

Simon Peyton Jones's avatar
Simon Peyton Jones committed
172
        sig_theta  :: TcThetaType,  -- Instantiated theta
173
        sig_tau    :: TcSigmaType,  -- Instantiated tau
174
                                    -- See Note [sig_tau may be polymorphic]
175

thomasw's avatar
thomasw committed
176 177
        sig_loc    :: SrcSpan,      -- The location of the signature

178 179 180 181 182 183 184 185
        sig_warn_redundant :: Bool  -- True <=> report redundant constraints
                                    --          when typechecking the value binding
                                    --          for this type signature
           -- 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
186
    }
187 188 189 190 191 192 193 194 195 196 197
  | TcPatSynInfo TcPatSynInfo

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

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
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

217
instance NamedThing TcSigInfo where
thomasw's avatar
thomasw committed
218
    getName TcSigInfo{ sig_name = name } = name
219 220
    getName (TcPatSynInfo tpsi) = patsig_name tpsi

thomasw's avatar
thomasw committed
221

222
instance Outputable TcSigInfo where
thomasw's avatar
thomasw committed
223 224 225 226 227
    ppr (TcSigInfo { sig_name = name, sig_poly_id = mb_poly_id, sig_tvs = tyvars
                   , sig_theta = theta, sig_tau = tau })
        = maybe (ppr name) ppr mb_poly_id <+> dcolon <+>
          vcat [ pprSigmaType (mkSigmaTy (map snd tyvars) theta tau)
               , ppr (map fst tyvars) ]
228 229 230 231 232
    ppr (TcPatSynInfo tpsi) = text "TcPatSynInfo" <+> ppr tpsi

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

thomasw's avatar
thomasw committed
233
isPartialSig :: TcSigInfo -> Bool
thomasw's avatar
thomasw committed
234 235 236 237 238 239 240 241
isPartialSig (TcSigInfo { sig_poly_id = Nothing }) = True
isPartialSig _ = False

-- Helper for cases when we know for sure we have a complete type
-- signature, e.g. class methods.
completeSigPolyId :: TcSigInfo -> TcId
completeSigPolyId (TcSigInfo { sig_poly_id = Just id }) = id
completeSigPolyId _ = panic "completeSigPolyId"
242

243 244 245 246
completeSigPolyId_maybe :: TcSigInfo -> Maybe TcId
completeSigPolyId_maybe (TcSigInfo { sig_poly_id = mb_id }) = mb_id
completeSigPolyId_maybe (TcPatSynInfo {})                   = Nothing

Austin Seipp's avatar
Austin Seipp committed
247
{-
248 249 250 251 252 253 254
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
255
  may actually give rise to
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    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.
274

275 276 277 278 279 280 281
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.
282

283 284 285 286 287
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
288
The pe_lazy field of PatEnv says whether we are inside a lazy
289
pattern (perhaps deeply)
290

291 292 293 294 295
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
296
(or of course the environment).   Hence we need to keep track of the
297
res_ty free vars.
298

thomasw's avatar
thomasw committed
299 300
Note [Complete and partial type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
301 302
A type signature is partial when it contains one or more wildcards
(= type holes).  The wildcard can either be:
thomasw's avatar
thomasw committed
303 304 305 306 307 308 309 310 311 312
* A (type) wildcard occurring in sig_theta or sig_tau. These are
  stored in sig_nwcs.
      f :: Bool -> _
      g :: Eq _a => _a -> _a -> Bool
* Or an extra-constraints wildcard, stored in sig_extra_cts:
      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.
313

Austin Seipp's avatar
Austin Seipp committed
314 315
************************************************************************
*                                                                      *
316
                Binders
Austin Seipp's avatar
Austin Seipp committed
317 318 319
*                                                                      *
************************************************************************
-}
320

321
tcPatBndr :: PatEnv -> Name -> TcSigmaType -> TcM (TcCoercion, TcId)
322 323 324 325
-- (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
326 327 328
          -- See Note [Typing patterns in pattern bindings]
  | LetGblBndr prags <- no_gen
  , Just sig <- lookup_sig bndr_name
thomasw's avatar
thomasw committed
329 330
  , Just poly_id <- sig_poly_id sig
  = do { bndr_id <- addInlinePrags poly_id (prags bndr_name)
331
       ; traceTc "tcPatBndr(gbl,sig)" (ppr bndr_id $$ ppr (idType bndr_id))
batterseapower's avatar
batterseapower committed
332 333
       ; co <- unifyPatType (idType bndr_id) pat_ty
       ; return (co, bndr_id) }
334 335

  | otherwise
336
  = do { bndr_id <- newNoSigLetBndr no_gen bndr_name pat_ty
337
       ; traceTc "tcPatBndr(no-sig)" (ppr bndr_id $$ ppr (idType bndr_id))
338
       ; return (mkTcNomReflCo pat_ty, bndr_id) }
339 340

tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty
341
  = return (mkTcNomReflCo pat_ty, mkLocalId bndr_name pat_ty)
342

343 344
------------
newNoSigLetBndr :: LetBndrSpec -> Name -> TcType -> TcM TcId
345
-- In the polymorphic case (no_gen = LetLclBndr), generate a "monomorphic version"
346 347
--    of the Id; the original name will be bound to the polymorphic version
--    by the AbsBinds
348
-- In the monomorphic case (no_gen = LetBglBndr) there is no AbsBinds, and we
349
--    use the original name directly
350
newNoSigLetBndr LetLclBndr name ty
351
  =do  { mono_name <- newLocalName name
352
       ; return (mkLocalId mono_name ty) }
353
newNoSigLetBndr (LetGblBndr prags) name ty
354
  = addInlinePrags (mkLocalId name ty) (prags name)
355 356 357 358

----------
addInlinePrags :: TcId -> [LSig Name] -> TcM TcId
addInlinePrags poly_id prags
359
  = do { traceTc "addInlinePrags" (ppr poly_id $$ ppr prags)
360
       ; tc_inl inl_sigs }
361 362 363 364 365
  where
    inl_sigs = filter isInlineLSig prags
    tc_inl [] = return poly_id
    tc_inl (L loc (InlineSig _ prag) : other_inls)
       = do { unless (null other_inls) (setSrcSpan loc warn_dup_inline)
366
            ; traceTc "addInlinePrag" (ppr poly_id $$ ppr prag)
367 368 369 370 371 372 373 374 375 376 377 378
            ; return (poly_id `setInlinePragma` prag) }
    tc_inl _ = panic "tc_inl"

    warn_dup_inline = warnPrags poly_id inl_sigs $
                      ptext (sLit "Duplicate INLINE pragmas for")

warnPrags :: Id -> [LSig Name] -> SDoc -> TcM ()
warnPrags id bad_sigs herald
  = addWarnTc (hang (herald <+> quotes (ppr id))
                  2 (ppr_sigs bad_sigs))
  where
    ppr_sigs sigs = vcat (map (ppr . getLoc) sigs)
379

Austin Seipp's avatar
Austin Seipp committed
380
{-
381 382 383 384 385 386 387 388
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
389
     x :: forall a. a->a
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
     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
   generalisation step will do the checking and impedence matching
   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.

409

Austin Seipp's avatar
Austin Seipp committed
410 411
************************************************************************
*                                                                      *
412
                The main worker functions
Austin Seipp's avatar
Austin Seipp committed
413 414
*                                                                      *
************************************************************************
415

416 417
Note [Nesting]
~~~~~~~~~~~~~~
lennart@augustsson.net's avatar
lennart@augustsson.net committed
418
tcPat takes a "thing inside" over which the pattern scopes.  This is partly
419
so that tcPat can extend the environment for the thing_inside, but also
420 421 422 423
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
424
want the error-context for the pattern to scope over the RHS.
425
Hence the getErrCtxt/setErrCtxt stuff in tcMultiple
Austin Seipp's avatar
Austin Seipp committed
426
-}
427 428

--------------------
429
type Checker inp out =  forall r.
430 431 432 433
                          inp
                       -> PatEnv
                       -> TcM r
                       -> TcM (out, r)
434 435

tcMultiple :: Checker inp out -> Checker [inp] [out]
436
tcMultiple tc_pat args penv thing_inside
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
  = 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 }
453 454

--------------------
455 456 457 458 459
tc_lpat :: LPat Name
        -> TcSigmaType
        -> PatEnv
        -> TcM a
        -> TcM (LPat TcId, a)
460
tc_lpat (L span pat) pat_ty penv thing_inside
461
  = setSrcSpan span $
462
    do  { (pat', res) <- maybeWrapPatCtxt pat (tc_pat penv pat pat_ty)
463
                                          thing_inside
464
        ; return (L span pat', res) }
465 466

tc_lpats :: PatEnv
467 468 469 470
         -> [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
471
  = ASSERT2( equalLength pats tys, ppr pats $$ ppr tys )
472
    tcMultiple (\(p,t) -> tc_lpat p t)
473
                (zipEqual "tc_lpats" pats tys)
474
                penv thing_inside
475 476

--------------------
477 478 479 480 481 482
tc_pat  :: PatEnv
        -> Pat Name
        -> TcSigmaType  -- Fully refined result type
        -> TcM a                -- Thing inside
        -> TcM (Pat TcId,       -- Translated pattern
                a)              -- Result of thing inside
483

484
tc_pat penv (VarPat name) pat_ty thing_inside
485
  = do  { (co, id) <- tcPatBndr penv name pat_ty
batterseapower's avatar
batterseapower committed
486 487
        ; res <- tcExtendIdEnv1 name id thing_inside
        ; return (mkHsWrapPatCo co (VarPat id) pat_ty, res) }
488 489

tc_pat penv (ParPat pat) pat_ty thing_inside
490 491
  = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
        ; return (ParPat pat', res) }
492 493

tc_pat penv (BangPat pat) pat_ty thing_inside
494 495
  = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
        ; return (BangPat pat', res) }
496

497
tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside
498 499 500 501
  = do  { (pat', (res, pat_ct))
                <- tc_lpat pat pat_ty (makeLazy penv) $
                   captureConstraints thing_inside
                -- Ignore refined penv', revert to penv
502

503 504
        ; emitConstraints pat_ct
        -- captureConstraints/extendConstraints:
505
        --   see Note [Hopping the LIE in lazy patterns]
506

507 508
        -- Check there are no unlifted types under the lazy pattern
        ; when (any (isUnLiftedType . idType) $ collectPatBinders pat') $
509 510
               lazyUnliftedPatErr lpat

511 512 513
        -- Check that the expected pattern type is itself lifted
        ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
        ; _ <- unifyType pat_ty pat_ty'
514

515
        ; return (LazyPat pat', res) }
516

517
tc_pat _ (WildPat _) pat_ty thing_inside
518 519
  = do  { res <- thing_inside
        ; return (WildPat pat_ty, res) }
520

521
tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
522
  = do  { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
batterseapower's avatar
batterseapower committed
523
        ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
524 525 526 527 528 529 530 531 532 533 534 535 536
                         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`
537 538 539 540
         -- 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.
541 542
        ; (expr',expr'_inferred) <- tcInferRho expr

543
         -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
544
         -- NOTE: this forces pat_ty to be a monotype (because we use a unification
545 546 547 548
         -- 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
549 550 551
        ; (expr_co, pat_ty) <- tcInfer $ \ pat_ty ->
                unifyType expr'_inferred (mkFunTy overall_pat_ty pat_ty)

552
         -- pattern must have pat_ty
553 554
        ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside

555
        ; return (ViewPat (mkLHsWrapCo expr_co expr') pat' overall_pat_ty, res) }
556

557 558
-- Type signatures in patterns
-- See Note [Pattern coercions] below
559
tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
thomasw's avatar
thomasw committed
560 561 562
  = do  { (inner_ty, tv_binds, nwc_binds, wrap) <- tcPatSig (inPatBind penv)
                                                            sig_ty pat_ty
        ; (pat', res) <- tcExtendTyVarEnv2 (tv_binds ++ nwc_binds) $
563
                         tc_lpat pat inner_ty penv thing_inside
564
        ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
565 566 567

------------------------
-- Lists, tuples, arrays
568
tc_pat penv (ListPat pats _ Nothing) pat_ty thing_inside
569
  = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy pat_ty
570
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
571 572
                                     pats penv thing_inside
        ; return (mkHsWrapPat coi (ListPat pats' elt_ty Nothing) pat_ty, res)
573 574 575
        }

tc_pat penv (ListPat pats _ (Just (_,e))) pat_ty thing_inside
576
  = do  { list_pat_ty <- newFlexiTyVarTy liftedTypeKind
577 578 579
        ; e' <- tcSyntaxOp ListOrigin e (mkFunTy pat_ty list_pat_ty)
        ; (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy list_pat_ty
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
580 581
                                     pats penv thing_inside
        ; return (mkHsWrapPat coi (ListPat pats' elt_ty (Just (pat_ty,e'))) list_pat_ty, res)
582
        }
583

584
tc_pat penv (PArrPat pats _) pat_ty thing_inside
585 586 587 588
  = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTy pat_ty
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
                                     pats penv thing_inside
        ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
589
        }
590

591
tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
592
  = do  { let tc = tupleTyCon (boxityNormalTupleSort boxity) (length pats)
593
        ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc) pat_ty
594
        ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
595

596
        ; dflags <- getDynFlags
597

598 599 600 601 602
        -- 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
603 604
              unmangled_result = TuplePat pats' boxity arg_tys
                                 -- pat_ty /= pat_ty iff coi /= IdCo
605 606
              possibly_mangled_result
                | gopt Opt_IrrefutableTuples dflags &&
607
                  isBoxed boxity            = LazyPat (noLoc unmangled_result)
608
                | otherwise                 = unmangled_result
609

610 611
        ; ASSERT( length arg_tys == length pats )      -- Syntactically enforced
          return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
612
        }
613 614 615

------------------------
-- Data constructors
616 617
tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
  = tcConPat penv con pat_ty arg_pats thing_inside
618 619 620

------------------------
-- Literal patterns
621
tc_pat _ (LitPat simple_lit) pat_ty thing_inside
622 623 624 625 626
  = 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
627
                 , res) }
628 629 630

------------------------
-- Overloaded patterns: n, and n+k
Alan Zimmerman's avatar
Alan Zimmerman committed
631
tc_pat _ (NPat (L l over_lit) mb_neg eq) pat_ty thing_inside
632 633 634 635 636 637 638 639 640 641
  = 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
642
        ; return (NPat (L l lit') mb_neg' eq', res) }
643

Alan Zimmerman's avatar
Alan Zimmerman committed
644
tc_pat penv (NPlusKPat (L nm_loc name) (L loc lit) ge minus) pat_ty thing_inside
645
  = do  { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
batterseapower's avatar
batterseapower committed
646
        ; let pat_ty' = idType bndr_id
647 648
              orig    = LiteralOrigin lit
        ; lit' <- newOverloadedLit orig lit pat_ty'
649

650 651 652
        -- 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
653
        ; let pat' = NPlusKPat (L nm_loc bndr_id) (L loc lit') ge' minus'
654

655 656 657 658
        -- 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']]
659

660 661 662 663
        ; res <- tcExtendIdEnv1 name bndr_id thing_inside
        ; return (mkHsWrapPatCo co pat' pat_ty, res) }

tc_pat _ _other_pat _ _ = panic "tc_pat"        -- ConPatOut, SigPatOut
664 665

----------------
666
unifyPatType :: TcType -> TcType -> TcM TcCoercion
667 668 669 670 671 672
-- 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
673
       ; return (mkTcSymCo coi) }
674

Austin Seipp's avatar
Austin Seipp committed
675
{-
676 677 678 679
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.
680
        f ~(C x) = 3
681
We can't discharge the Num constraint from dictionaries bound by
682
the pattern C!
683

684
So we have to make the constraints from thing_inside "hop around"
685
the pattern.  Hence the captureConstraints and emitConstraints.
686 687 688

The same thing ensures that equality constraints in a lazy match
are not made available in the RHS of the match. For example
689 690 691
        data T a where { T1 :: Int -> T Int; ... }
        f :: T a -> Int -> a
        f ~(T1 i) y = y
692 693 694 695 696 697
It's obviously not sound to refine a to Int in the right
hand side, because the arugment might not match T1 at all!

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

698

Austin Seipp's avatar
Austin Seipp committed
699 700
************************************************************************
*                                                                      *
701 702
        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
703 704
*                                                                      *
************************************************************************
705

706 707 708 709 710 711 712 713 714 715 716
[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 -> ...

717
As explained by [Wrappers for data instance tycons] in MkIds.hs, the
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
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}

733
In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
734

735
  Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
736 737 738 739 740 741

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.

742
Now it might appear seem as if we could have used the previous GADT type
743 744 745 746 747 748 749 750 751 752 753 754
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.

755 756 757
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
758
-}
759

760
--      Running example:
761
-- MkT :: forall a b c. (a~[b]) => b -> c -> T a
762
--       with scrutinee of type (T ty)
763

764 765 766 767
tcConPat :: PatEnv -> Located Name
         -> TcRhoType           -- Type of the pattern
         -> HsConPatDetails Name -> TcM a
         -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
768 769 770 771 772 773 774 775 776 777
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
778 779 780
             -> TcRhoType               -- Type of the pattern
             -> HsConPatDetails Name -> TcM a
             -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
781
tcDataConPat penv (L con_span con_name) data_con pat_ty arg_pats thing_inside
782 783 784
  = do  { let tycon = dataConTyCon data_con
                  -- For data families this is the representation tycon
              (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _)
785
                = dataConFullSig data_con
cactus's avatar
cactus committed
786
              header = L con_span (RealDataCon data_con)
787

788 789 790 791
          -- 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
792

793 794
          -- Add the stupid theta
        ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
795

796
        ; checkExistentials ex_tvs penv
797 798
        ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX
                               (zipTopTvSubst univ_tvs ctxt_res_tys) ex_tvs
799 800
                     -- Get location from monad, not from ex_tvs

801
        ; let -- pat_ty' = mkTyConApp tycon ctxt_res_tys
802
              -- pat_ty' is type of the actual constructor application
803
              -- pat_ty' /= pat_ty iff coi /= IdCo
Simon Peyton Jones's avatar
Simon Peyton Jones committed
804

805
              arg_tys' = substTys tenv arg_tys
806

Simon Peyton Jones's avatar
Simon Peyton Jones committed
807
        ; traceTc "tcConPat" (vcat [ ppr con_name, ppr univ_tvs, ppr ex_tvs, ppr eq_spec
808
                                   , ppr ex_tvs', ppr ctxt_res_tys, ppr arg_tys' ])
809 810
        ; if null ex_tvs && null eq_spec && null theta
          then do { -- The common case; no class bindings etc
811
                    -- (see Note [Arrows and patterns])
812 813 814 815
                    (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 = [],
816
                                              pat_binds = emptyTcEvBinds,
817
                                              pat_args = arg_pats',
818
                                              pat_arg_tys = ctxt_res_tys,
cactus's avatar
cactus committed
819
                                              pat_wrap = idHsWrapper }
820

821
                  ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
822

823
          else do   -- The general case, with existential,
824
                    -- and local equality constraints
825
        { let theta'   = substTheta tenv (eqSpecPreds eq_spec ++ theta)
826 827
                           -- order is *important* as we generate the list of
                           -- dictionary binders from theta'
828
              no_equalities = not (any isEqPred theta')
829
              skol_info = case pe_ctxt penv of
cactus's avatar
cactus committed
830
                            LamPat mc -> PatSkol (RealDataCon data_con) mc
831
                            LetPat {} -> UnkSkol -- Doesn't matter
832

833 834
        ; gadts_on    <- xoptM Opt_GADTs
        ; families_on <- xoptM Opt_TypeFamilies
835
        ; checkTc (no_equalities || gadts_on || families_on)
sivteck's avatar
sivteck committed
836 837
                  (text "A pattern match on a GADT requires the" <+>
                   text "GADTs or TypeFamilies language extension")
838 839 840
                  -- Trac #2905 decided that a *pattern-match* of a GADT
                  -- should require the GADT language flag.
                  -- Re TypeFamilies see also #7156
841

842
        ; given <- newEvVars theta'
843
        ; (ev_binds, (arg_pats', res))
844
             <- checkConstraints skol_info ex_tvs' given $
cactus's avatar
cactus committed
845
                tcConArgs (RealDataCon data_con) arg_tys' arg_pats penv thing_inside
846

cactus's avatar
cactus committed
847
        ; let res_pat = ConPatOut { pat_con   = header,
848 849 850 851
                                    pat_tvs   = ex_tvs',
                                    pat_dicts = given,
                                    pat_binds = ev_binds,
                                    pat_args  = arg_pats',
852
                                    pat_arg_tys = ctxt_res_tys,
cactus's avatar
cactus committed
853
                                    pat_wrap  = idHsWrapper }
854 855
        ; return (mkHsWrapPat wrap res_pat pat_ty, res)
        } }
856

cactus's avatar
cactus committed
857
tcPatSynPat :: PatEnv -> Located Name -> PatSyn
858 859 860
            -> TcRhoType                -- Type of the pattern
            -> HsConPatDetails Name -> TcM a
            -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
861
tcPatSynPat penv (L con_span _) pat_syn pat_ty arg_pats thing_inside
862
  = do  { let (univ_tvs, ex_tvs, prov_theta, req_theta, arg_tys, ty) = patSynSig pat_syn