TcPat.hs 44.7 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998

5 6

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

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

11 12 13
module TcPat ( tcLetPat, TcSigFun
             , 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 FastString
50
import Maybes( orElse )
51
import qualified GHC.LanguageExtensions as LangExt
Ian Lynagh's avatar
Ian Lynagh committed
52
import Control.Monad
53

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

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

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

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

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

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

96
tcPat :: HsMatchContext Name
97
      -> LPat Name -> TcSigmaType
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
98
      -> TcM a                     -- Checker for body
99
      -> TcM (LPat TcId, a)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
100 101 102 103 104 105 106 107 108
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
109 110
  = tc_lpat pat pat_ty penv thing_inside
  where
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
111
    penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt, pe_orig = orig }
112

113

114
-----------------
115
data PatEnv
116 117
  = 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
118
       , pe_orig :: CtOrigin    -- origin to use if the pat_ty needs inst'ing
119
       }
120 121 122

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

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

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

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

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

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

---------------
147
type TcPragEnv = NameEnv [LSig Name]
148
type TcSigFun  = Name -> Maybe TcSigInfo
149

150 151 152 153 154 155
emptyPragEnv :: TcPragEnv
emptyPragEnv = emptyNameEnv

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

156
{- *********************************************************************
Austin Seipp's avatar
Austin Seipp committed
157
*                                                                      *
158
                Binders
Austin Seipp's avatar
Austin Seipp committed
159
*                                                                      *
160
********************************************************************* -}
161

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

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

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

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

----------
addInlinePrags :: TcId -> [LSig Name] -> TcM TcId
addInlinePrags poly_id prags
202 203 204 205 206 207
  | 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
208
  where
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    inl_prags = [L loc prag | L loc (InlineSig _ prag) <- prags]

    warn_multiple_inlines _ [] = return ()

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

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

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

256

Austin Seipp's avatar
Austin Seipp committed
257 258
************************************************************************
*                                                                      *
259
                The main worker functions
Austin Seipp's avatar
Austin Seipp committed
260 261
*                                                                      *
************************************************************************
262

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

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

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

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

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

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

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

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

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

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

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

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

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

362
        ; return (LazyPat pat', res) }
363

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

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

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

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

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

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

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

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

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

433
tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
434 435
  = do  { let arity = length pats
              tc = tupleTyCon boxity arity
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
436 437
        ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc)
                                               penv pat_ty
438 439 440 441 442
                     -- 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
443

444
        ; dflags <- getDynFlags
445

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

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

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

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

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

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

499 500 501
        -- 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
502 503 504 505 506
        ; let pat' = mkHsWrapPat wrap_lit
                                 (NPlusKPat (L nm_loc bndr_id)
                                            (L loc lit')
                                            ge' minus')
                                 pat_ty
507

508 509 510 511
        -- 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']]
512

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

tc_pat _ _other_pat _ _ = panic "tc_pat"        -- ConPatOut, SigPatOut
517 518

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

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

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

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

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

551

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

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

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

586
In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
587

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

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.

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

608 609 610
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
611
-}
612

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

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

641 642 643
          -- 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
644
        ; (wrap, ctxt_res_tys) <- matchExpectedConTy penv tycon pat_ty
645

646 647
          -- Add the stupid theta
        ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
648

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

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

659
              arg_tys' = substTys tenv arg_tys
660

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

677
                  ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
678

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

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

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

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

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

720
        ; (subst, univ_tvs') <- newMetaTyVars univ_tvs
cactus's avatar
cactus committed
721

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

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

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

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

763
----------------------------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
764 765 766
-- | Convenient wrapper for calling a matchExpectedXXX function
matchExpectedPatTy :: (TcRhoType -> TcM (TcCoercionN, a))
                    -> PatEnv -> TcSigmaType -> TcM (HsWrapper, a)
767
-- See Note [Matching polytyped patterns]
768
-- Returns a wrapper : pat_ty ~R inner_ty
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
769 770 771 772 773
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) }
774 775

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

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

796
       ; traceTc "matchExpectedConTy" (vcat [ppr data_tc,
797 798
                                             ppr (tyConTyVars data_tc),
                                             ppr fam_tc, ppr fam_args