TcPat.hs 47.9 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(..)
thomasw's avatar
thomasw committed
13
             , findScopedTyVars, isPartialSig
14
             , LetBndrSpec(..), addInlinePrags, warnPrags
15
             , tcPat, tcPats, newNoSigLetBndr
16
             , addDataConStupidTheta, badFieldCon, polyPatSig ) where
17

18
#include "HsVersions.h"
19

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

import HsSyn
import TcHsSyn
24
import TcRnMonad
25 26 27 28
import Inst
import Id
import Var
import Name
29
import NameSet
30
import TcEnv
31
--import TcExpr
32
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
51

Austin Seipp's avatar
Austin Seipp committed
52 53 54
{-
************************************************************************
*                                                                      *
55
                External interface
Austin Seipp's avatar
Austin Seipp committed
56 57 58
*                                                                      *
************************************************************************
-}
59

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

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

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

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

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

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

103

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

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

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

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

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

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

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

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

data TcSigInfo
  = TcSigInfo {
        sig_id     :: TcId,         --  *Polymorphic* binder for this value...

143
        sig_tvs    :: [(Maybe Name, TcTyVar)],
144 145
                           -- Instantiated type and kind variables
                           -- Just n <=> this skolem is lexically in scope with name n
146
                           -- See Note [Binding scoped type variables]
147

thomasw's avatar
thomasw committed
148 149 150
        sig_nwcs   :: [(Name, TcTyVar)],
                           -- Instantiated wildcard variables

151 152
        sig_theta  :: TcThetaType,  -- Instantiated theta

thomasw's avatar
thomasw committed
153 154 155 156 157 158 159
        sig_extra_cts :: Maybe SrcSpan, -- Just loc <=> An extra-constraints
                                        -- wildcard was present. Any extra
                                        -- constraints inferred during
                                        -- type-checking will be added to the
                                        -- partial type signature. Stores the
                                        -- location of the wildcard.

160
        sig_tau    :: TcSigmaType,  -- Instantiated tau
161
                                    -- See Note [sig_tau may be polymorphic]
162

thomasw's avatar
thomasw committed
163 164 165 166
        sig_loc    :: SrcSpan,      -- The location of the signature

        sig_partial :: Bool         -- True <=> a partial type signature
                                    -- containing wildcards
167
    }
168 169 170 171 172 173 174 175 176 177 178
  | TcPatSynInfo TcPatSynInfo

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

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
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

198 199 200 201
instance NamedThing TcSigInfo where
    getName TcSigInfo{ sig_id = id } = idName id
    getName (TcPatSynInfo tpsi) = patsig_name tpsi

202
instance Outputable TcSigInfo where
thomasw's avatar
thomasw committed
203
    ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau })
204 205
        = ppr id <+> dcolon <+> vcat [ pprSigmaType (mkSigmaTy (map snd tyvars) theta tau)
                                     , ppr (map fst tyvars) ]
206 207 208 209 210
    ppr (TcPatSynInfo tpsi) = text "TcPatSynInfo" <+> ppr tpsi

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

thomasw's avatar
thomasw committed
211 212
isPartialSig :: TcSigInfo -> Bool
isPartialSig = sig_partial
213

Austin Seipp's avatar
Austin Seipp committed
214
{-
215 216 217 218 219 220 221
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
222
  may actually give rise to
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    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.
241

242 243 244 245 246 247 248
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.
249

250 251 252 253 254
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
255
The pe_lazy field of PatEnv says whether we are inside a lazy
256
pattern (perhaps deeply)
257

258 259 260 261 262
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
263
(or of course the environment).   Hence we need to keep track of the
264
res_ty free vars.
265

266

Austin Seipp's avatar
Austin Seipp committed
267 268
************************************************************************
*                                                                      *
269
                Binders
Austin Seipp's avatar
Austin Seipp committed
270 271 272
*                                                                      *
************************************************************************
-}
273

274
tcPatBndr :: PatEnv -> Name -> TcSigmaType -> TcM (TcCoercion, TcId)
275 276 277 278
-- (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
279 280 281 282
          -- See Note [Typing patterns in pattern bindings]
  | LetGblBndr prags <- no_gen
  , Just sig <- lookup_sig bndr_name
  = do { bndr_id <- addInlinePrags (sig_id sig) (prags bndr_name)
283
       ; traceTc "tcPatBndr(gbl,sig)" (ppr bndr_id $$ ppr (idType bndr_id))
batterseapower's avatar
batterseapower committed
284 285
       ; co <- unifyPatType (idType bndr_id) pat_ty
       ; return (co, bndr_id) }
286 287

  | otherwise
288
  = do { bndr_id <- newNoSigLetBndr no_gen bndr_name pat_ty
289
       ; traceTc "tcPatBndr(no-sig)" (ppr bndr_id $$ ppr (idType bndr_id))
290
       ; return (mkTcNomReflCo pat_ty, bndr_id) }
291 292 293

tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty
  = do { bndr <- mkLocalBinder bndr_name pat_ty
294
       ; return (mkTcNomReflCo pat_ty, bndr) }
295

296 297
------------
newNoSigLetBndr :: LetBndrSpec -> Name -> TcType -> TcM TcId
298
-- In the polymorphic case (no_gen = LetLclBndr), generate a "monomorphic version"
299 300
--    of the Id; the original name will be bound to the polymorphic version
--    by the AbsBinds
301
-- In the monomorphic case (no_gen = LetBglBndr) there is no AbsBinds, and we
302
--    use the original name directly
303
newNoSigLetBndr LetLclBndr name ty
304 305
  =do  { mono_name <- newLocalName name
       ; mkLocalBinder mono_name ty }
306
newNoSigLetBndr (LetGblBndr prags) name ty
307 308 309 310 311 312
  = do { id <- mkLocalBinder name ty
       ; addInlinePrags id (prags name) }

----------
addInlinePrags :: TcId -> [LSig Name] -> TcM TcId
addInlinePrags poly_id prags
313
  = do { traceTc "addInlinePrags" (ppr poly_id $$ ppr prags)
314
       ; tc_inl inl_sigs }
315 316 317 318 319
  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)
320
            ; traceTc "addInlinePrag" (ppr poly_id $$ ppr prag)
321 322 323 324 325 326 327 328 329 330 331 332
            ; 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)
333

334 335 336
-----------------
mkLocalBinder :: Name -> TcType -> TcM TcId
mkLocalBinder name ty
337
  = return (Id.mkLocalId name ty)
338

Austin Seipp's avatar
Austin Seipp committed
339
{-
340 341 342 343 344 345 346 347
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
348
     x :: forall a. a->a
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
     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.

368

Austin Seipp's avatar
Austin Seipp committed
369 370
************************************************************************
*                                                                      *
371
                The main worker functions
Austin Seipp's avatar
Austin Seipp committed
372 373
*                                                                      *
************************************************************************
374

375 376
Note [Nesting]
~~~~~~~~~~~~~~
lennart@augustsson.net's avatar
lennart@augustsson.net committed
377
tcPat takes a "thing inside" over which the pattern scopes.  This is partly
378
so that tcPat can extend the environment for the thing_inside, but also
379 380 381 382
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
383
want the error-context for the pattern to scope over the RHS.
384
Hence the getErrCtxt/setErrCtxt stuff in tcMultiple
Austin Seipp's avatar
Austin Seipp committed
385
-}
386 387

--------------------
388
type Checker inp out =  forall r.
389 390 391 392
                          inp
                       -> PatEnv
                       -> TcM r
                       -> TcM (out, r)
393 394

tcMultiple :: Checker inp out -> Checker [inp] [out]
395
tcMultiple tc_pat args penv thing_inside
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
  = 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 }
412 413

--------------------
414 415 416 417 418
tc_lpat :: LPat Name
        -> TcSigmaType
        -> PatEnv
        -> TcM a
        -> TcM (LPat TcId, a)
419
tc_lpat (L span pat) pat_ty penv thing_inside
420
  = setSrcSpan span $
421
    do  { (pat', res) <- maybeWrapPatCtxt pat (tc_pat penv pat pat_ty)
422
                                          thing_inside
423
        ; return (L span pat', res) }
424 425

tc_lpats :: PatEnv
426 427 428 429
         -> [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
430
  = ASSERT2( equalLength pats tys, ppr pats $$ ppr tys )
431
    tcMultiple (\(p,t) -> tc_lpat p t)
432
                (zipEqual "tc_lpats" pats tys)
433
                penv thing_inside
434 435

--------------------
436 437 438 439 440 441
tc_pat  :: PatEnv
        -> Pat Name
        -> TcSigmaType  -- Fully refined result type
        -> TcM a                -- Thing inside
        -> TcM (Pat TcId,       -- Translated pattern
                a)              -- Result of thing inside
442

443
tc_pat penv (VarPat name) pat_ty thing_inside
444
  = do  { (co, id) <- tcPatBndr penv name pat_ty
batterseapower's avatar
batterseapower committed
445 446
        ; res <- tcExtendIdEnv1 name id thing_inside
        ; return (mkHsWrapPatCo co (VarPat id) pat_ty, res) }
447 448

tc_pat penv (ParPat pat) pat_ty thing_inside
449 450
  = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
        ; return (ParPat pat', res) }
451 452

tc_pat penv (BangPat pat) pat_ty thing_inside
453 454
  = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
        ; return (BangPat pat', res) }
455

456
tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside
457 458 459 460
  = do  { (pat', (res, pat_ct))
                <- tc_lpat pat pat_ty (makeLazy penv) $
                   captureConstraints thing_inside
                -- Ignore refined penv', revert to penv
461

462 463
        ; emitConstraints pat_ct
        -- captureConstraints/extendConstraints:
464
        --   see Note [Hopping the LIE in lazy patterns]
465

466 467
        -- Check there are no unlifted types under the lazy pattern
        ; when (any (isUnLiftedType . idType) $ collectPatBinders pat') $
468 469
               lazyUnliftedPatErr lpat

470 471 472
        -- Check that the expected pattern type is itself lifted
        ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
        ; _ <- unifyType pat_ty pat_ty'
473

474
        ; return (LazyPat pat', res) }
475

476 477 478
tc_pat _ p@(QuasiQuotePat _) _ _
  = pprPanic "Should never see QuasiQuotePat in type checker" (ppr p)

479
tc_pat _ (WildPat _) pat_ty thing_inside
480 481
  = do  { res <- thing_inside
        ; return (WildPat pat_ty, res) }
482

483
tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
484
  = do  { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
batterseapower's avatar
batterseapower committed
485
        ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
486 487 488 489 490 491 492 493 494 495 496 497 498
                         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`
499 500 501 502
         -- 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.
503 504
        ; (expr',expr'_inferred) <- tcInferRho expr

505
         -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
506
         -- NOTE: this forces pat_ty to be a monotype (because we use a unification
507 508 509 510
         -- 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
511 512 513
        ; (expr_co, pat_ty) <- tcInfer $ \ pat_ty ->
                unifyType expr'_inferred (mkFunTy overall_pat_ty pat_ty)

514
         -- pattern must have pat_ty
515 516
        ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside

517
        ; return (ViewPat (mkLHsWrapCo expr_co expr') pat' overall_pat_ty, res) }
518

519 520
-- Type signatures in patterns
-- See Note [Pattern coercions] below
521
tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
thomasw's avatar
thomasw committed
522 523 524
  = do  { (inner_ty, tv_binds, nwc_binds, wrap) <- tcPatSig (inPatBind penv)
                                                            sig_ty pat_ty
        ; (pat', res) <- tcExtendTyVarEnv2 (tv_binds ++ nwc_binds) $
525
                         tc_lpat pat inner_ty penv thing_inside
526
        ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
527 528 529

------------------------
-- Lists, tuples, arrays
530
tc_pat penv (ListPat pats _ Nothing) pat_ty thing_inside
531
  = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy pat_ty
532
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
533 534
                                     pats penv thing_inside
        ; return (mkHsWrapPat coi (ListPat pats' elt_ty Nothing) pat_ty, res)
535 536 537
        }

tc_pat penv (ListPat pats _ (Just (_,e))) pat_ty thing_inside
538
  = do  { list_pat_ty <- newFlexiTyVarTy liftedTypeKind
539 540 541
        ; 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)
542 543
                                     pats penv thing_inside
        ; return (mkHsWrapPat coi (ListPat pats' elt_ty (Just (pat_ty,e'))) list_pat_ty, res)
544
        }
545

546
tc_pat penv (PArrPat pats _) pat_ty thing_inside
547 548 549 550
  = 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)
551
        }
552

553
tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
554
  = do  { let tc = tupleTyCon (boxityNormalTupleSort boxity) (length pats)
555
        ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc) pat_ty
556
        ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
557

558
        ; dflags <- getDynFlags
559

560 561 562 563 564
        -- 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
565 566
              unmangled_result = TuplePat pats' boxity arg_tys
                                 -- pat_ty /= pat_ty iff coi /= IdCo
567 568
              possibly_mangled_result
                | gopt Opt_IrrefutableTuples dflags &&
569
                  isBoxed boxity            = LazyPat (noLoc unmangled_result)
570
                | otherwise                 = unmangled_result
571

572 573
        ; ASSERT( length arg_tys == length pats )      -- Syntactically enforced
          return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
574
        }
575 576 577

------------------------
-- Data constructors
578 579
tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
  = tcConPat penv con pat_ty arg_pats thing_inside
580 581 582

------------------------
-- Literal patterns
583
tc_pat _ (LitPat simple_lit) pat_ty thing_inside
584 585 586 587 588
  = 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
589
                 , res) }
590 591 592

------------------------
-- Overloaded patterns: n, and n+k
593
tc_pat _ (NPat over_lit mb_neg eq) pat_ty thing_inside
594 595 596 597 598 599 600 601 602 603 604
  = 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
        ; return (NPat lit' mb_neg' eq', res) }
605

606
tc_pat penv (NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
607
  = do  { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
batterseapower's avatar
batterseapower committed
608
        ; let pat_ty' = idType bndr_id
609 610
              orig    = LiteralOrigin lit
        ; lit' <- newOverloadedLit orig lit pat_ty'
611

612 613 614
        -- 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')
615
        ; let pat' = NPlusKPat (L nm_loc bndr_id) lit' ge' minus'
616

617 618 619 620
        -- 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']]
621

622 623 624 625
        ; res <- tcExtendIdEnv1 name bndr_id thing_inside
        ; return (mkHsWrapPatCo co pat' pat_ty, res) }

tc_pat _ _other_pat _ _ = panic "tc_pat"        -- ConPatOut, SigPatOut
626 627

----------------
628
unifyPatType :: TcType -> TcType -> TcM TcCoercion
629 630 631 632 633 634
-- 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
635
       ; return (mkTcSymCo coi) }
636

Austin Seipp's avatar
Austin Seipp committed
637
{-
638 639 640 641
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.
642
        f ~(C x) = 3
643
We can't discharge the Num constraint from dictionaries bound by
644
the pattern C!
645

646
So we have to make the constraints from thing_inside "hop around"
647
the pattern.  Hence the captureConstraints and emitConstraints.
648 649 650

The same thing ensures that equality constraints in a lazy match
are not made available in the RHS of the match. For example
651 652 653
        data T a where { T1 :: Int -> T Int; ... }
        f :: T a -> Int -> a
        f ~(T1 i) y = y
654 655 656 657 658 659
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

660

Austin Seipp's avatar
Austin Seipp committed
661 662
************************************************************************
*                                                                      *
663 664
        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
665 666
*                                                                      *
************************************************************************
667

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
[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 -> ...

As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
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}

695
In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
696

697
  Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
698 699 700 701 702 703

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.

704
Now it might appear seem as if we could have used the previous GADT type
705 706 707 708 709 710 711 712 713 714 715 716
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.

717 718 719
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
720
-}
721

722
--      Running example:
723
-- MkT :: forall a b c. (a~[b]) => b -> c -> T a
724
--       with scrutinee of type (T ty)
725

726 727 728 729
tcConPat :: PatEnv -> Located Name
         -> TcRhoType           -- Type of the pattern
         -> HsConPatDetails Name -> TcM a
         -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
730 731 732 733 734 735 736 737 738 739
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
740 741 742
             -> TcRhoType               -- Type of the pattern
             -> HsConPatDetails Name -> TcM a
             -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
743
tcDataConPat penv (L con_span con_name) data_con pat_ty arg_pats thing_inside
744 745 746
  = do  { let tycon = dataConTyCon data_con
                  -- For data families this is the representation tycon
              (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _)
747
                = dataConFullSig data_con
cactus's avatar
cactus committed
748
              header = L con_span (RealDataCon data_con)
749

750 751 752 753
          -- 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
754

755 756
          -- Add the stupid theta
        ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
757

758
        ; checkExistentials ex_tvs penv
759 760
        ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX
                               (zipTopTvSubst univ_tvs ctxt_res_tys) ex_tvs
761 762
                     -- Get location from monad, not from ex_tvs

763
        ; let -- pat_ty' = mkTyConApp tycon ctxt_res_tys
764
              -- pat_ty' is type of the actual constructor application
765
              -- pat_ty' /= pat_ty iff coi /= IdCo
Simon Peyton Jones's avatar
Simon Peyton Jones committed
766

767
              arg_tys' = substTys tenv arg_tys
768

Simon Peyton Jones's avatar
Simon Peyton Jones committed
769
        ; traceTc "tcConPat" (vcat [ ppr con_name, ppr univ_tvs, ppr ex_tvs, ppr eq_spec
770
                                   , ppr ex_tvs', ppr ctxt_res_tys, ppr arg_tys' ])
771 772
        ; if null ex_tvs && null eq_spec && null theta
          then do { -- The common case; no class bindings etc
773
                    -- (see Note [Arrows and patterns])
774 775 776 777
                    (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 = [],
778
                                              pat_binds = emptyTcEvBinds,
779
                                              pat_args = arg_pats',
780
                                              pat_arg_tys = ctxt_res_tys,
cactus's avatar
cactus committed
781
                                              pat_wrap = idHsWrapper }
782

783
                  ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
784

785
          else do   -- The general case, with existential,
786
                    -- and local equality constraints
787
        { let theta'   = substTheta tenv (eqSpecPreds eq_spec ++ theta)
788 789
                           -- order is *important* as we generate the list of
                           -- dictionary binders from theta'
790
              no_equalities = not (any isEqPred theta')
791
              skol_info = case pe_ctxt penv of
cactus's avatar
cactus committed
792
                            LamPat mc -> PatSkol (RealDataCon data_con) mc
793
                            LetPat {} -> UnkSkol -- Doesn't matter
794

795 796
        ; gadts_on    <- xoptM Opt_GADTs
        ; families_on <- xoptM Opt_TypeFamilies
797
        ; checkTc (no_equalities || gadts_on || families_on)
sivteck's avatar
sivteck committed
798 799
                  (text "A pattern match on a GADT requires the" <+>
                   text "GADTs or TypeFamilies language extension")
800 801 802
                  -- Trac #2905 decided that a *pattern-match* of a GADT
                  -- should require the GADT language flag.
                  -- Re TypeFamilies see also #7156
803

804
        ; given <- newEvVars theta'
805
        ; (ev_binds, (arg_pats', res))
806
             <- checkConstraints skol_info ex_tvs' given $
cactus's avatar
cactus committed
807
                tcConArgs (RealDataCon data_con) arg_tys' arg_pats penv thing_inside
808

cactus's avatar
cactus committed
809
        ; let res_pat = ConPatOut { pat_con   = header,
810 811 812 813
                                    pat_tvs   = ex_tvs',
                                    pat_dicts = given,
                                    pat_binds = ev_binds,
                                    pat_args  = arg_pats',
814
                                    pat_arg_tys = ctxt_res_tys,
cactus's avatar
cactus committed
815
                                    pat_wrap  = idHsWrapper }
816 817
        ; return (mkHsWrapPat wrap res_pat pat_ty, res)
        } }
818

cactus's avatar
cactus committed
819
tcPatSynPat :: PatEnv -> Located Name -> PatSyn
820 821 822
            -> TcRhoType                -- Type of the pattern
            -> HsConPatDetails Name -> TcM a
            -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
823
tcPatSynPat penv (L con_span _) pat_syn pat_ty arg_pats thing_inside
824
  = do  { let (univ_tvs, ex_tvs, prov_theta, req_theta, arg_tys, ty) = patSynSig pat_syn
cactus's avatar
cactus committed
825

826
        ; (subst, univ_tvs') <- tcInstTyVars univ_tvs
cactus's avatar
cactus committed
827

828
        ; checkExistentials ex_tvs penv
cactus's avatar
cactus committed
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
        ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX subst ex_tvs
        ; let ty' = substTy tenv ty
              arg_tys' = substTys tenv arg_tys
              prov_theta' = substTheta tenv prov_theta
              req_theta' = substTheta tenv req_theta

        ; wrap <- coToHsWrapper <$> unifyType ty' pat_ty
        ; traceTc "tcPatSynPat" (ppr pat_syn $$
                                 ppr pat_ty $$
                                 ppr ty' $$
                                 ppr ex_tvs' $$
                                 ppr prov_theta' $$
                                 ppr req_theta' $$
                                 ppr arg_tys')

        ; prov_dicts' <- newEvVars prov_theta'

        ; let skol_info = case pe_ctxt penv of
                            LamPat mc -> PatSkol (PatSynCon pat_syn) mc
                            LetPat {} -> UnkSkol -- Doesn't matter

850
        ; req_wrap <- instCall PatOrigin (mkTyVarTys univ_tvs') req_theta'
cactus's avatar
cactus committed
851 852
        ; traceTc "instCall" (ppr req_wrap)

853
        ; traceTc "checkConstraints {" Outputable.empty
cactus's avatar
cactus committed
854 855 856 857 858 859
        ; (ev_binds, (arg_pats', res))
             <- checkConstraints skol_info ex_tvs' prov_dicts' $
                tcConArgs (PatSynCon pat_syn) arg_tys' arg_pats penv thing_inside

        ; traceTc "checkConstraints }" (ppr ev_binds)
        ; let res_pat = ConPatOut { pat_con   = L con_span $ PatSynCon pat_syn,
860 861 862 863
                                    pat_tvs   = ex_tvs',
                                    pat_dicts = prov_dicts',
                                    pat_binds = ev_binds,
                                    pat_args  = arg_pats',
864
                                    pat_arg_tys = mkTyVarTys univ_tvs',
cactus's avatar
cactus committed
865
                                    pat_wrap  = req_wrap }
866
        ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
cactus's avatar
cactus committed
867