TcPat.hs 44.5 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
12 13
             , TcPragEnv, lookupPragEnv, emptyPragEnv
             , LetBndrSpec(..), addInlinePrags
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
14
             , tcPat, tcPat_O, tcPats, newNoSigLetBndr
15
             , addDataConStupidTheta, badFieldCon, polyPatSig ) where
16

17
#include "HsVersions.h"
18

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
19
import {-# SOURCE #-}   TcExpr( tcSyntaxOp, tcInferSigma )
20 21 22

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

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

61
tcLetPat :: TcSigFun -> LetBndrSpec
62 63 64
         -> LPat Name -> TcSigmaType
         -> TcM a
         -> TcM (LPat TcId, a)
65
tcLetPat sig_fn no_gen pat pat_ty thing_inside
66
  = tc_lpat pat pat_ty penv thing_inside
67
  where
68
    penv = PE { pe_lazy = True
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
69 70
              , pe_ctxt = LetPat sig_fn no_gen
              , pe_orig = PatOrigin }
71 72

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

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

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

90
tcPats ctxt pats pat_tys thing_inside
91 92
  = tc_lpats penv pats pat_tys thing_inside
  where
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
93
    penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt, pe_orig = PatOrigin }
94

95
tcPat :: HsMatchContext Name
96
      -> LPat Name -> TcSigmaType
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
97
      -> TcM a                     -- Checker for body
98
      -> TcM (LPat TcId, a)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
99 100 101 102 103 104 105 106 107
tcPat ctxt = tcPat_O ctxt PatOrigin

-- | A variant of 'tcPat' that takes a custom origin
tcPat_O :: HsMatchContext Name
        -> CtOrigin              -- ^ origin to use if the type needs inst'ing
        -> LPat Name -> TcSigmaType
        -> TcM a                 -- Checker for body
        -> TcM (LPat TcId, a)
tcPat_O ctxt orig pat pat_ty thing_inside
108 109
  = tc_lpat pat pat_ty penv thing_inside
  where
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
110
    penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt, pe_orig = orig }
111

112

113
-----------------
114
data PatEnv
115 116
  = PE { pe_lazy :: Bool        -- True <=> lazy context, so no existentials allowed
       , pe_ctxt :: PatCtxt     -- Context in which the whole pattern appears
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
117
       , pe_orig :: CtOrigin    -- origin to use if the pat_ty needs inst'ing
118
       }
119 120 121

data PatCtxt
  = LamPat   -- Used for lambdas, case etc
122
       (HsMatchContext Name)
123

124
  | LetPat   -- Used only for let(rec) pattern bindings
125
             -- See Note [Typing patterns in pattern bindings]
126 127 128
       TcSigFun        -- Tells type sig if any
       LetBndrSpec     -- True <=> no generalisation of this let

129 130 131
data LetBndrSpec
  = LetLclBndr            -- The binder is just a local one;
                          -- an AbsBinds will provide the global version
132

133
  | LetGblBndr TcPragEnv  -- Generalisation plan is NoGen, so there isn't going
134
                          -- to be an AbsBinds; So we must bind the global version
135
                          -- of the binder right away.
136
                          -- Oh, and here is the inline-pragma information
137

138 139 140
makeLazy :: PatEnv -> PatEnv
makeLazy penv = penv { pe_lazy = True }

141 142 143
inPatBind :: PatEnv -> Bool
inPatBind (PE { pe_ctxt = LetPat {} }) = True
inPatBind (PE { pe_ctxt = LamPat {} }) = False
144 145

---------------
146
type TcPragEnv = NameEnv [LSig Name]
147

148 149 150 151 152 153
emptyPragEnv :: TcPragEnv
emptyPragEnv = emptyNameEnv

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

154
{- *********************************************************************
Austin Seipp's avatar
Austin Seipp committed
155
*                                                                      *
156
                Binders
Austin Seipp's avatar
Austin Seipp committed
157
*                                                                      *
158
********************************************************************* -}
159

160
tcPatBndr :: PatEnv -> Name -> TcSigmaType -> TcM (TcCoercionN, TcId)
161 162 163 164
-- (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
165
          -- See Note [Typing patterns in pattern bindings]
166 167 168
  | LetGblBndr prags   <- no_gen
  , Just (TcIdSig sig) <- lookup_sig bndr_name
  , Just poly_id <- completeIdSigPolyId_maybe sig
169
  = do { bndr_id <- addInlinePrags poly_id (lookupPragEnv prags bndr_name)
170
       ; traceTc "tcPatBndr(gbl,sig)" (ppr bndr_id $$ ppr (idType bndr_id))
171
       ; co <- unifyPatType bndr_id (idType bndr_id) pat_ty
batterseapower's avatar
batterseapower committed
172
       ; return (co, bndr_id) }
173 174

  | otherwise
175
  = do { bndr_id <- newNoSigLetBndr no_gen bndr_name pat_ty
176
       ; traceTc "tcPatBndr(no-sig)" (ppr bndr_id $$ ppr (idType bndr_id))
177
       ; return (mkTcNomReflCo pat_ty, bndr_id) }
178 179

tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty
180
  = return (mkTcNomReflCo pat_ty, mkLocalId bndr_name pat_ty)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
181 182
               -- whether or not there is a sig is irrelevant, as this
               -- is local
183

184 185
------------
newNoSigLetBndr :: LetBndrSpec -> Name -> TcType -> TcM TcId
186
-- In the polymorphic case (no_gen = LetLclBndr), generate a "monomorphic version"
187 188
--    of the Id; the original name will be bound to the polymorphic version
--    by the AbsBinds
189
-- In the monomorphic case (no_gen = LetBglBndr) there is no AbsBinds, and we
190
--    use the original name directly
191
newNoSigLetBndr LetLclBndr name ty
192
  =do  { mono_name <- newLocalName name
193
       ; return (mkLocalId mono_name ty) }
194
newNoSigLetBndr (LetGblBndr prags) name ty
195
  = addInlinePrags (mkLocalId name ty) (lookupPragEnv prags name)
196 197 198 199

----------
addInlinePrags :: TcId -> [LSig Name] -> TcM TcId
addInlinePrags poly_id prags
200 201 202 203 204 205
  | 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
206
  where
207 208 209 210 211 212 213 214 215 216 217 218
    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 $
219 220
         addWarnTc (hang (text "Multiple INLINE pragmas for" <+> ppr poly_id)
                       2 (vcat (text "Ignoring all but the first"
221 222 223
                                : map pp_inl (inl1:inl2:inls))))

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

Austin Seipp's avatar
Austin Seipp committed
225
{-
226 227 228 229 230 231 232 233
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
234
     x :: forall a. a->a
235 236 237 238 239 240 241 242 243 244
     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
245
   generalisation step will do the checking and impedance matching
246 247 248 249 250 251 252 253
   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.

254

Austin Seipp's avatar
Austin Seipp committed
255 256
************************************************************************
*                                                                      *
257
                The main worker functions
Austin Seipp's avatar
Austin Seipp committed
258 259
*                                                                      *
************************************************************************
260

261 262
Note [Nesting]
~~~~~~~~~~~~~~
lennart@augustsson.net's avatar
lennart@augustsson.net committed
263
tcPat takes a "thing inside" over which the pattern scopes.  This is partly
264
so that tcPat can extend the environment for the thing_inside, but also
265 266 267 268
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
269
want the error-context for the pattern to scope over the RHS.
270
Hence the getErrCtxt/setErrCtxt stuff in tcMultiple
Austin Seipp's avatar
Austin Seipp committed
271
-}
272 273

--------------------
274
type Checker inp out =  forall r.
275 276 277 278
                          inp
                       -> PatEnv
                       -> TcM r
                       -> TcM (out, r)
279 280

tcMultiple :: Checker inp out -> Checker [inp] [out]
281
tcMultiple tc_pat args penv thing_inside
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
  = 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 }
298 299

--------------------
300 301 302 303 304
tc_lpat :: LPat Name
        -> TcSigmaType
        -> PatEnv
        -> TcM a
        -> TcM (LPat TcId, a)
305
tc_lpat (L span pat) pat_ty penv thing_inside
306
  = setSrcSpan span $
307
    do  { (pat', res) <- maybeWrapPatCtxt pat (tc_pat penv pat pat_ty)
308
                                          thing_inside
309
        ; return (L span pat', res) }
310 311

tc_lpats :: PatEnv
312 313 314 315
         -> [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
316
  = ASSERT2( equalLength pats tys, ppr pats $$ ppr tys )
317
    tcMultiple (\(p,t) -> tc_lpat p t)
318
                (zipEqual "tc_lpats" pats tys)
319
                penv thing_inside
320 321

--------------------
322 323 324 325 326 327
tc_pat  :: PatEnv
        -> Pat Name
        -> TcSigmaType  -- Fully refined result type
        -> TcM a                -- Thing inside
        -> TcM (Pat TcId,       -- Translated pattern
                a)              -- Result of thing inside
328

329
tc_pat penv (VarPat (L l name)) pat_ty thing_inside
330
  = do  { (co, id) <- tcPatBndr penv name pat_ty
batterseapower's avatar
batterseapower committed
331
        ; res <- tcExtendIdEnv1 name id thing_inside
332
        ; return (mkHsWrapPatCo co (VarPat (L l id)) pat_ty, res) }
333 334

tc_pat penv (ParPat pat) pat_ty thing_inside
335 336
  = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
        ; return (ParPat pat', res) }
337 338

tc_pat penv (BangPat pat) pat_ty thing_inside
339 340
  = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
        ; return (BangPat pat', res) }
341

342
tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside
343 344 345 346
  = do  { (pat', (res, pat_ct))
                <- tc_lpat pat pat_ty (makeLazy penv) $
                   captureConstraints thing_inside
                -- Ignore refined penv', revert to penv
347

348 349
        ; emitConstraints pat_ct
        -- captureConstraints/extendConstraints:
350
        --   see Note [Hopping the LIE in lazy patterns]
351

352
        -- Check there are no unlifted types under the lazy pattern
353
        ; when (any (isUnliftedType . idType) $ collectPatBinders pat') $
354 355
               lazyUnliftedPatErr lpat

356 357
        -- Check that the expected pattern type is itself lifted
        ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
358
        ; _ <- unifyType noThing pat_ty pat_ty'
359

360
        ; return (LazyPat pat', res) }
361

362
tc_pat _ (WildPat _) pat_ty thing_inside
363 364
  = do  { res <- thing_inside
        ; return (WildPat pat_ty, res) }
365

366
tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
367
  = do  { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
batterseapower's avatar
batterseapower committed
368
        ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
369 370 371 372 373 374 375 376 377 378 379 380
                         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  {
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
381
         -- Expr must have type `forall a1...aN. OPT' -> B`
382
         -- where overall_pat_ty is an instance of OPT'.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
383
        ; (expr',expr'_inferred) <- tcInferSigma expr
384

385
         -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
386 387 388 389
        ; (expr_wrap, pat_ty) <- tcInfer $ \ pat_ty ->
                tcSubTypeDS_O (exprCtOrigin (unLoc expr)) GenSigCtxt (Just expr)
                              expr'_inferred
                              (mkFunTy overall_pat_ty pat_ty)
390

391
         -- pattern must have pat_ty
392 393
        ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
394
        ; return (ViewPat (mkLHsWrap expr_wrap expr') pat' overall_pat_ty, res) }
395

396 397
-- Type signatures in patterns
-- See Note [Pattern coercions] below
398
tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
399
  = do  { (inner_ty, tv_binds, wcs, wrap) <- tcPatSig (inPatBind penv)
thomasw's avatar
thomasw committed
400
                                                            sig_ty pat_ty
401 402
        ; (pat', res) <- tcExtendTyVarEnv2 wcs      $
                         tcExtendTyVarEnv  tv_binds $
403
                         tc_lpat pat inner_ty penv thing_inside
404
        ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
405 406 407

------------------------
-- Lists, tuples, arrays
408
tc_pat penv (ListPat pats _ Nothing) pat_ty thing_inside
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
409
  = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy penv pat_ty
410
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
411 412
                                     pats penv thing_inside
        ; return (mkHsWrapPat coi (ListPat pats' elt_ty Nothing) pat_ty, res)
413 414 415
        }

tc_pat penv (ListPat pats _ (Just (_,e))) pat_ty thing_inside
416
  = do  { list_pat_ty <- newFlexiTyVarTy liftedTypeKind
417
        ; e' <- tcSyntaxOp ListOrigin e (mkFunTy pat_ty list_pat_ty)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
418
        ; (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy penv list_pat_ty
419
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
420 421
                                     pats penv thing_inside
        ; return (mkHsWrapPat coi (ListPat pats' elt_ty (Just (pat_ty,e'))) list_pat_ty, res)
422
        }
423

424
tc_pat penv (PArrPat pats _) pat_ty thing_inside
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
425
  = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTy penv pat_ty
426 427 428
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
                                     pats penv thing_inside
        ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
429
        }
430

431
tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
432 433
  = do  { let arity = length pats
              tc = tupleTyCon boxity arity
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
434 435
        ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc)
                                               penv pat_ty
436 437 438 439 440
                     -- Unboxed tuples have levity vars, which we discard:
                     -- See Note [Unboxed tuple levity vars] in TyCon
        ; let con_arg_tys = case boxity of Unboxed -> drop arity arg_tys
                                           Boxed   -> arg_tys
        ; (pats', res) <- tc_lpats penv pats con_arg_tys thing_inside
441

442
        ; dflags <- getDynFlags
443

444 445 446 447 448
        -- 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
449
              unmangled_result = TuplePat pats' boxity con_arg_tys
450
                                 -- pat_ty /= pat_ty iff coi /= IdCo
451 452
              possibly_mangled_result
                | gopt Opt_IrrefutableTuples dflags &&
453
                  isBoxed boxity            = LazyPat (noLoc unmangled_result)
454
                | otherwise                 = unmangled_result
455

456
        ; ASSERT( length con_arg_tys == length pats ) -- Syntactically enforced
457
          return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
458
        }
459 460 461

------------------------
-- Data constructors
462 463
tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
  = tcConPat penv con pat_ty arg_pats thing_inside
464 465 466

------------------------
-- Literal patterns
467
tc_pat _ (LitPat simple_lit) pat_ty thing_inside
468
  = do  { let lit_ty = hsLitType simple_lit
469
        ; co <- unifyPatType simple_lit lit_ty pat_ty
470 471 472
                -- coi is of kind: pat_ty ~ lit_ty
        ; res <- thing_inside
        ; return ( mkHsWrapPatCo co (LitPat simple_lit) pat_ty
473
                 , res) }
474 475 476

------------------------
-- Overloaded patterns: n, and n+k
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
477 478
tc_pat (PE { pe_orig = pat_orig })
       (NPat (L l over_lit) mb_neg eq) pat_ty thing_inside
479
  = do  { let orig = LiteralOrigin over_lit
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
480
        ; (wrap, lit') <- newOverloadedLit over_lit pat_ty pat_orig
481 482 483 484 485 486 487 488
        ; 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
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
489
        ; return (mkHsWrapPat wrap (NPat (L l lit') mb_neg' eq') pat_ty, res) }
490

Alan Zimmerman's avatar
Alan Zimmerman committed
491
tc_pat penv (NPlusKPat (L nm_loc name) (L loc lit) ge minus) pat_ty thing_inside
492
  = do  { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
batterseapower's avatar
batterseapower committed
493
        ; let pat_ty' = idType bndr_id
494
              orig    = LiteralOrigin lit
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
495
        ; (wrap_lit, lit') <- newOverloadedLit lit pat_ty' (pe_orig penv)
496

497 498 499
        -- 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')
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
500 501 502 503 504
        ; let pat' = mkHsWrapPat wrap_lit
                                 (NPlusKPat (L nm_loc bndr_id)
                                            (L loc lit')
                                            ge' minus')
                                 pat_ty
505

506 507 508 509
        -- 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']]
510

511 512 513 514
        ; res <- tcExtendIdEnv1 name bndr_id thing_inside
        ; return (mkHsWrapPatCo co pat' pat_ty, res) }

tc_pat _ _other_pat _ _ = panic "tc_pat"        -- ConPatOut, SigPatOut
515 516

----------------
517
unifyPatType :: Outputable a => a -> TcType -> TcType -> TcM TcCoercion
518 519 520 521
-- 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
522 523
unifyPatType thing actual_ty expected_ty
  = do { coi <- unifyType (Just thing) actual_ty expected_ty
524
       ; return (mkTcSymCo coi) }
525

Austin Seipp's avatar
Austin Seipp committed
526
{-
527 528 529 530
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.
531
        f ~(C x) = 3
532
We can't discharge the Num constraint from dictionaries bound by
533
the pattern C!
534

535
So we have to make the constraints from thing_inside "hop around"
536
the pattern.  Hence the captureConstraints and emitConstraints.
537 538 539

The same thing ensures that equality constraints in a lazy match
are not made available in the RHS of the match. For example
540 541 542
        data T a where { T1 :: Int -> T Int; ... }
        f :: T a -> Int -> a
        f ~(T1 i) y = y
543
It's obviously not sound to refine a to Int in the right
544
hand side, because the argument might not match T1 at all!
545 546 547 548

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

549

Austin Seipp's avatar
Austin Seipp committed
550 551
************************************************************************
*                                                                      *
552 553
        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
554 555
*                                                                      *
************************************************************************
556

557 558 559 560 561 562 563 564 565 566 567
[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 -> ...

568
As explained by [Wrappers for data instance tycons] in MkIds.hs, the
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
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}

584
In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
585

586
  Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
587 588 589 590 591 592

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.

593
Now it might appear seem as if we could have used the previous GADT type
594 595 596 597 598 599 600 601 602 603 604 605
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.

606 607 608
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
609
-}
610

611
--      Running example:
612
-- MkT :: forall a b c. (a~[b]) => b -> c -> T a
613
--       with scrutinee of type (T ty)
614

615 616 617 618
tcConPat :: PatEnv -> Located Name
         -> TcRhoType           -- Type of the pattern
         -> HsConPatDetails Name -> TcM a
         -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
619 620 621 622 623 624 625 626 627 628
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
629 630 631
             -> TcRhoType               -- Type of the pattern
             -> HsConPatDetails Name -> TcM a
             -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
632
tcDataConPat penv (L con_span con_name) data_con pat_ty arg_pats thing_inside
633 634 635
  = do  { let tycon = dataConTyCon data_con
                  -- For data families this is the representation tycon
              (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _)
636
                = dataConFullSig data_con
cactus's avatar
cactus committed
637
              header = L con_span (RealDataCon data_con)
638

639 640 641
          -- Instantiate the constructor type variables [a->ty]
          -- This may involve doing a family-instance coercion,
          -- and building a wrapper
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
642
        ; (wrap, ctxt_res_tys) <- matchExpectedConTy penv tycon pat_ty
643

644 645
          -- Add the stupid theta
        ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
646

647 648
        ; let all_arg_tys = eqSpecPreds eq_spec ++ theta ++ arg_tys
        ; checkExistentials ex_tvs all_arg_tys penv
649
        ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX
650
                               (zipOpenTCvSubst univ_tvs ctxt_res_tys) ex_tvs
651 652
                     -- Get location from monad, not from ex_tvs

653
        ; let -- pat_ty' = mkTyConApp tycon ctxt_res_tys
654
              -- pat_ty' is type of the actual constructor application
655
              -- pat_ty' /= pat_ty iff coi /= IdCo
Simon Peyton Jones's avatar
Simon Peyton Jones committed
656

657
              arg_tys' = substTys tenv arg_tys
658

659 660 661 662
        ; traceTc "tcConPat" (vcat [ ppr con_name, ppr univ_tvs, ppr ex_tvs
                                   , ppr eq_spec
                                   , ppr ex_tvs', ppr ctxt_res_tys, ppr arg_tys'
                                   , ppr arg_pats ])
663 664
        ; if null ex_tvs && null eq_spec && null theta
          then do { -- The common case; no class bindings etc
665
                    -- (see Note [Arrows and patterns])
666 667 668 669
                    (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 = [],
670
                                              pat_binds = emptyTcEvBinds,
671
                                              pat_args = arg_pats',
672
                                              pat_arg_tys = ctxt_res_tys,
cactus's avatar
cactus committed
673
                                              pat_wrap = idHsWrapper }
674

675
                  ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
676

677
          else do   -- The general case, with existential,
678
                    -- and local equality constraints
679
        { let theta'     = substTheta tenv (eqSpecPreds eq_spec ++ theta)
680 681
                           -- order is *important* as we generate the list of
                           -- dictionary binders from theta'
682
              no_equalities = not (any isNomEqPred theta')
683
              skol_info = case pe_ctxt penv of
cactus's avatar
cactus committed
684
                            LamPat mc -> PatSkol (RealDataCon data_con) mc
685
                            LetPat {} -> UnkSkol -- Doesn't matter
686

687 688
        ; gadts_on    <- xoptM LangExt.GADTs
        ; families_on <- xoptM LangExt.TypeFamilies
689
        ; checkTc (no_equalities || gadts_on || families_on)
sivteck's avatar
sivteck committed
690 691
                  (text "A pattern match on a GADT requires the" <+>
                   text "GADTs or TypeFamilies language extension")
692 693 694
                  -- Trac #2905 decided that a *pattern-match* of a GADT
                  -- should require the GADT language flag.
                  -- Re TypeFamilies see also #7156
695

696
        ; given <- newEvVars theta'
697
        ; (ev_binds, (arg_pats', res))
698
             <- checkConstraints skol_info ex_tvs' given $
cactus's avatar
cactus committed
699
                tcConArgs (RealDataCon data_con) arg_tys' arg_pats penv thing_inside
700

cactus's avatar
cactus committed
701
        ; let res_pat = ConPatOut { pat_con   = header,
702 703 704 705
                                    pat_tvs   = ex_tvs',
                                    pat_dicts = given,
                                    pat_binds = ev_binds,
                                    pat_args  = arg_pats',
706
                                    pat_arg_tys = ctxt_res_tys,
cactus's avatar
cactus committed
707
                                    pat_wrap  = idHsWrapper }
708 709
        ; return (mkHsWrapPat wrap res_pat pat_ty, res)
        } }
710

cactus's avatar
cactus committed
711
tcPatSynPat :: PatEnv -> Located Name -> PatSyn
712 713 714
            -> TcRhoType                -- Type of the pattern
            -> HsConPatDetails Name -> TcM a
            -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
715
tcPatSynPat penv (L con_span _) pat_syn pat_ty arg_pats thing_inside
716
  = do  { let (univ_tvs, req_theta, ex_tvs, prov_theta, arg_tys, ty) = patSynSig pat_syn
cactus's avatar
cactus committed
717

718
        ; (subst, univ_tvs') <- newMetaTyVars univ_tvs
cactus's avatar
cactus committed
719

720 721
        ; let all_arg_tys = ty : prov_theta ++ arg_tys
        ; checkExistentials ex_tvs all_arg_tys penv
cactus's avatar
cactus committed
722
        ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX subst ex_tvs
723 724
        ; let ty'         = substTy tenv ty
              arg_tys'    = substTys tenv arg_tys
cactus's avatar
cactus committed
725
              prov_theta' = substTheta tenv prov_theta
726
              req_theta'  = substTheta tenv req_theta
cactus's avatar
cactus committed
727

728
        ; wrap <- mkWpCastN <$> unifyType noThing ty' pat_ty
cactus's avatar
cactus committed
729 730 731 732 733 734 735 736 737 738 739 740 741 742
        ; 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

743
        ; req_wrap <- instCall PatOrigin (mkTyVarTys univ_tvs') req_theta'
cactus's avatar
cactus committed
744 745
        ; traceTc "instCall" (ppr req_wrap)

746
        ; traceTc "checkConstraints {" Outputable.empty
cactus's avatar
cactus committed
747 748 749 750 751 752
        ; (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,
753 754 755 756
                                    pat_tvs   = ex_tvs',
                                    pat_dicts = prov_dicts',
                                    pat_binds = ev_binds,
                                    pat_args  = arg_pats',
757
                                    pat_arg_tys = mkTyVarTys univ_tvs',
cactus's avatar
cactus committed
758
                                    pat_wrap  = req_wrap }
759
        ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
cactus's avatar
cactus committed
760

761
----------------------------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
762 763 764
-- | Convenient wrapper for calling a matchExpectedXXX function
matchExpectedPatTy :: (TcRhoType -> TcM (TcCoercionN, a))
                    -> PatEnv -> TcSigmaType -> TcM (HsWrapper, a)
765
-- See Note [Matching polytyped patterns]
766
-- Returns a wrapper : pat_ty ~R inner_ty
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
767 768 769 770 771
matchExpectedPatTy inner_match (PE { pe_orig = orig }) pat_ty
  = do { (wrap, pat_rho) <- topInstantiate orig pat_ty
       ; (co, res) <- inner_match pat_rho
       ; traceTc "matchExpectedPatTy" (ppr pat_ty $$ ppr wrap)
       ; return (mkWpCastN (mkTcSymCo co) <.> wrap, res) }
772 773

----------------------------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
774 775
matchExpectedConTy :: PatEnv
                   -> TyCon      -- The TyCon that this data
776
                                 -- constructor actually returns
777 778
                                 -- In the case of a data family this is
                                 -- the /representation/ TyCon
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
779 780 781 782
                   -> TcSigmaType  -- The type of the pattern; in the case
                                   -- of a data family this would mention
                                   -- the /family/ TyCon
                   -> TcM (HsWrapper, [TcSigmaType])
783
-- See Note [Matching constructor patterns]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
784 785
-- Returns a wrapper : pat_ty "->" T ty1 ... tyn
matchExpectedConTy (PE { pe_orig = orig }) data_tc pat_ty
786
  | Just (fam_tc, fam_args, co_tc) <- tyConFamInstSig_maybe data_tc
787 788
         -- Comments refer to Note [Matching constructor patterns]
         -- co_tc :: forall a. T [a] ~ T7 a
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
789 790 791
  = do { (wrap, pat_ty) <- topInstantiate orig pat_ty

       ; (subst, tvs') <- newMetaTyVars (tyConTyVars data_tc)
792
             -- tys = [ty1,ty2]
793

794
       ; traceTc "matchExpectedConTy" (vcat [ppr data_tc,
Simon Peyton Jones's avatar