TcPat.hs 48 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, TupleSections #-}
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

19
import {-# SOURCE #-}   TcExpr( tcSyntaxOp, tcSyntaxOpGen, 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
import Control.Arrow  ( second )
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
         -> LPat Name -> ExpSigmaType
64 65
         -> 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
       -> [LPat Name]            -- Patterns,
76
       -> [ExpSigmaType]         --   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 -> ExpSigmaType
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
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
105
        -> LPat Name -> ExpSigmaType
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
106 107 108
        -> 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

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

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

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

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

  | otherwise
176 177
  = do { pat_ty <- expTypeToType pat_ty
       ; 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 183
  = do { pat_ty <- expTypeToType pat_ty
       ; return (mkTcNomReflCo pat_ty, mkLocalId bndr_name pat_ty) }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
184 185
               -- whether or not there is a sig is irrelevant, as this
               -- is local
186

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

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

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

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

257

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

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

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

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

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

tc_lpats :: PatEnv
315
         -> [LPat Name] -> [ExpSigmaType]
316 317 318
         -> TcM a
         -> TcM ([LPat TcId], a)
tc_lpats penv pats tys thing_inside
Simon Peyton Jones's avatar
Simon Peyton Jones committed
319
  = ASSERT2( equalLength pats tys, ppr pats $$ ppr tys )
320
    tcMultiple (\(p,t) -> tc_lpat p t)
321
                (zipEqual "tc_lpats" pats tys)
322
                penv thing_inside
323 324

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

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

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

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

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

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

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

360
        -- Check that the expected pattern type is itself lifted
361 362
        ; pat_ty <- readExpType pat_ty
        ; _ <- unifyType noThing (typeKind pat_ty) liftedTypeKind
363

364
        ; return (LazyPat pat', res) }
365

366
tc_pat _ (WildPat _) pat_ty thing_inside
367
  = do  { res <- thing_inside
368
        ; pat_ty <- expTypeToType pat_ty
369
        ; return (WildPat pat_ty, res) }
370

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

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
         -- expression must be a function
        ; let expr_orig = exprCtOrigin (unLoc expr)
              herald    = text "A view pattern expression expects"
        ; (expr_wrap1, [inf_arg_ty], inf_res_ty)
            <- matchActualFunTys herald expr_orig (Just expr) 1 expr'_inferred
            -- expr_wrap1 :: expr'_inferred "->" (inf_arg_ty -> inf_res_ty)

         -- check that overall pattern is more polymorphic than arg type
        ; let pat_origin = GivenOrigin (SigSkol GenSigCtxt overall_pat_ty)
        ; expr_wrap2 <- tcSubTypeET pat_origin overall_pat_ty inf_arg_ty
            -- expr_wrap2 :: overall_pat_ty "->" inf_arg_ty

         -- pattern must have inf_res_ty
        ; (pat', res) <- tc_lpat pat (mkCheckExpType inf_res_ty) penv thing_inside

        ; overall_pat_ty <- readExpType overall_pat_ty
        ; let expr_wrap2' = mkWpFun expr_wrap2 idHsWrapper
                                    overall_pat_ty inf_res_ty
               -- expr_wrap2' :: (inf_arg_ty -> inf_res_ty) "->"
               --                (overall_pat_ty -> inf_res_ty)
              expr_wrap = expr_wrap2' <.> expr_wrap1
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
413
        ; return (ViewPat (mkLHsWrap expr_wrap expr') pat' overall_pat_ty, res) }
414

415 416
-- Type signatures in patterns
-- See Note [Pattern coercions] below
417
tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
418
  = do  { (inner_ty, tv_binds, wcs, wrap) <- tcPatSig (inPatBind penv)
thomasw's avatar
thomasw committed
419
                                                            sig_ty pat_ty
420 421
        ; (pat', res) <- tcExtendTyVarEnv2 wcs      $
                         tcExtendTyVarEnv  tv_binds $
422 423
                         tc_lpat pat (mkCheckExpType inner_ty) penv thing_inside
        ; pat_ty <- readExpType pat_ty
424
        ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
425 426 427

------------------------
-- Lists, tuples, arrays
428
tc_pat penv (ListPat pats _ Nothing) pat_ty thing_inside
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
429
  = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy penv pat_ty
430
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p (mkCheckExpType elt_ty))
431
                                     pats penv thing_inside
432
        ; pat_ty <- readExpType pat_ty
433
        ; return (mkHsWrapPat coi (ListPat pats' elt_ty Nothing) pat_ty, res)
434 435 436
        }

tc_pat penv (ListPat pats _ (Just (_,e))) pat_ty thing_inside
437 438 439 440 441 442 443 444 445
  = do  { tau_pat_ty <- expTypeToType pat_ty
        ; ((pats', res, elt_ty), e')
            <- tcSyntaxOpGen ListOrigin e [SynType (mkCheckExpType tau_pat_ty)]
                                          SynList $
                 \ [elt_ty] ->
                 do { (pats', res) <- tcMultiple (\p -> tc_lpat p (mkCheckExpType elt_ty))
                                                 pats penv thing_inside
                    ; return (pats', res, elt_ty) }
        ; return (ListPat pats' elt_ty (Just (tau_pat_ty,e')), res)
446
        }
447

448
tc_pat penv (PArrPat pats _) pat_ty thing_inside
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
449
  = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTy penv pat_ty
450
        ; (pats', res) <- tcMultiple (\p -> tc_lpat p (mkCheckExpType elt_ty))
451
                                     pats penv thing_inside
452
        ; pat_ty <- readExpType pat_ty
453
        ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
454
        }
455

456
tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
457 458
  = do  { let arity = length pats
              tc = tupleTyCon boxity arity
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
459 460
        ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc)
                                               penv pat_ty
461 462 463 464
                     -- 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
465 466
        ; (pats', res) <- tc_lpats penv pats (map mkCheckExpType con_arg_tys)
                                   thing_inside
467

468
        ; dflags <- getDynFlags
469

470 471 472 473 474
        -- 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
475
              unmangled_result = TuplePat pats' boxity con_arg_tys
476
                                 -- pat_ty /= pat_ty iff coi /= IdCo
477 478
              possibly_mangled_result
                | gopt Opt_IrrefutableTuples dflags &&
479
                  isBoxed boxity            = LazyPat (noLoc unmangled_result)
480
                | otherwise                 = unmangled_result
481

482
        ; pat_ty <- readExpType pat_ty
483
        ; ASSERT( length con_arg_tys == length pats ) -- Syntactically enforced
484
          return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
485
        }
486 487 488

------------------------
-- Data constructors
489 490
tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
  = tcConPat penv con pat_ty arg_pats thing_inside
491 492 493

------------------------
-- Literal patterns
494
tc_pat _ (LitPat simple_lit) pat_ty thing_inside
495
  = do  { let lit_ty = hsLitType simple_lit
496
        ; co <- unifyPatType simple_lit lit_ty pat_ty
497 498
                -- coi is of kind: pat_ty ~ lit_ty
        ; res <- thing_inside
499
        ; pat_ty <- readExpType pat_ty
500
        ; return ( mkHsWrapPatCo co (LitPat simple_lit) pat_ty
501
                 , res) }
502 503 504

------------------------
-- Overloaded patterns: n, and n+k
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

-- In the case of a negative literal (the more complicated case),
-- we get
--
--   case v of (-5) -> blah
--
-- becoming
--
--   if v == (negate (fromInteger 5)) then blah else ...
--
-- There are two bits of rebindable syntax:
--   (==)   :: pat_ty -> neg_lit_ty -> Bool
--   negate :: lit_ty -> neg_lit_ty
-- where lit_ty is the type of the overloaded literal 5.
--
-- When there is no negation, neg_lit_ty and lit_ty are the same
tc_pat _ (NPat (L l over_lit) mb_neg eq _) pat_ty thing_inside
522
  = do  { let orig = LiteralOrigin over_lit
523 524 525 526 527 528 529 530 531 532 533 534 535 536
        ; ((lit', mb_neg'), eq')
            <- tcSyntaxOp orig eq [SynType pat_ty, SynAny]
                          (mkCheckExpType boolTy) $
               \ [neg_lit_ty] ->
               let new_over_lit lit_ty = newOverloadedLit over_lit
                                           (mkCheckExpType lit_ty)
               in case mb_neg of
                 Nothing  -> (, Nothing) <$> new_over_lit neg_lit_ty
                 Just neg -> -- Negative literal
                             -- The 'negate' is re-mappable syntax
                   second Just <$>
                   (tcSyntaxOp orig neg [SynRho] (mkCheckExpType neg_lit_ty) $
                    \ [lit_ty] -> new_over_lit lit_ty)

537
        ; res <- thing_inside
538 539
        ; pat_ty <- readExpType pat_ty
        ; return (NPat (L l lit') mb_neg' eq' pat_ty, res) }
540

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
{-
Note [NPlusK patterns]
~~~~~~~~~~~~~~~~~~~~~~
From

  case v of x + 5 -> blah

we get

  if v >= 5 then (\x -> blah) (v - 5) else ...

There are two bits of rebindable syntax:
  (>=) :: pat_ty -> lit1_ty -> Bool
  (-)  :: pat_ty -> lit2_ty -> var_ty

lit1_ty and lit2_ty could conceivably be different.
var_ty is the type inferred for x, the variable in the pattern.

If the pushed-down pattern type isn't a tau-type, the two pat_ty's above
could conceivably be different specializations. But this is very much
like the situation in Note [Case branches must be taus] in TcMatches.
So we tauify the pat_ty before proceeding.

Note that we need to type-check the literal twice, because it is used
twice, and may be used at different types. The second HsOverLit stored in the
AST is used for the subtraction operation.
-}

-- See Note [NPlusK patterns]
tc_pat penv (NPlusKPat (L nm_loc name) (L loc lit) _ ge minus _) pat_ty thing_inside
  = do  { pat_ty <- expTypeToType pat_ty
        ; let orig = LiteralOrigin lit
        ; (lit1', ge')
            <- tcSyntaxOp orig ge [synKnownType pat_ty, SynRho]
                                  (mkCheckExpType boolTy) $
               \ [lit1_ty] ->
               newOverloadedLit lit (mkCheckExpType lit1_ty)
        ; ((lit2', minus_wrap, bndr_id), minus')
            <- tcSyntaxOpGen orig minus [synKnownType pat_ty, SynRho] SynAny $
               \ [lit2_ty, var_ty] ->
               do { lit2' <- newOverloadedLit lit (mkCheckExpType lit2_ty)
                  ; (co, bndr_id) <- setSrcSpan nm_loc $
                                     tcPatBndr penv name (mkCheckExpType var_ty)
                           -- co :: var_ty ~ idType bndr_id

                           -- minus_wrap is applicable to minus'
                  ; return (lit2', mkWpCastN co, bndr_id) }
588

589
        -- The Report says that n+k patterns must be in Integral
590 591 592 593
        -- but it's silly to insist on this in the RebindableSyntax case
        ; unlessM (xoptM LangExt.RebindableSyntax) $
          do { icls <- tcLookupClass integralClassName
             ; instStupidTheta orig [mkClassPred icls [pat_ty]] }
594

595
        ; res <- tcExtendIdEnv1 name bndr_id thing_inside
596 597 598 599 600 601

        ; let minus'' = minus' { syn_res_wrap =
                                    minus_wrap <.> syn_res_wrap minus' }
              pat' = NPlusKPat (L nm_loc bndr_id) (L loc lit1') lit2'
                               ge' minus'' pat_ty
        ; return (pat', res) }
602 603

tc_pat _ _other_pat _ _ = panic "tc_pat"        -- ConPatOut, SigPatOut
604 605

----------------
606
unifyPatType :: Outputable a => a -> TcType -> ExpSigmaType -> TcM TcCoercion
607 608 609 610
-- 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
611
unifyPatType thing actual_ty expected_ty
612
  = do { coi <- unifyExpType (Just thing) actual_ty expected_ty
613
       ; return (mkTcSymCo coi) }
614

Austin Seipp's avatar
Austin Seipp committed
615
{-
616 617 618 619
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.
620
        f ~(C x) = 3
621
We can't discharge the Num constraint from dictionaries bound by
622
the pattern C!
623

624
So we have to make the constraints from thing_inside "hop around"
625
the pattern.  Hence the captureConstraints and emitConstraints.
626 627 628

The same thing ensures that equality constraints in a lazy match
are not made available in the RHS of the match. For example
629 630 631
        data T a where { T1 :: Int -> T Int; ... }
        f :: T a -> Int -> a
        f ~(T1 i) y = y
632
It's obviously not sound to refine a to Int in the right
633
hand side, because the argument might not match T1 at all!
634 635 636 637

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

638

Austin Seipp's avatar
Austin Seipp committed
639 640
************************************************************************
*                                                                      *
641 642
        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
643 644
*                                                                      *
************************************************************************
645

646 647 648 649 650 651 652 653 654 655 656
[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 -> ...

657
As explained by [Wrappers for data instance tycons] in MkIds.hs, the
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
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}

673
In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
674

675
  Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
676 677 678 679 680 681

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.

682
Now it might appear seem as if we could have used the previous GADT type
683 684 685 686 687 688 689 690 691 692 693 694
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.

695 696 697
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
698
-}
699

700
--      Running example:
701
-- MkT :: forall a b c. (a~[b]) => b -> c -> T a
702
--       with scrutinee of type (T ty)
703

704
tcConPat :: PatEnv -> Located Name
705
         -> ExpSigmaType           -- Type of the pattern
706 707
         -> HsConPatDetails Name -> TcM a
         -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
708 709 710 711 712 713 714 715 716 717
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
718
             -> ExpSigmaType               -- Type of the pattern
719 720
             -> HsConPatDetails Name -> TcM a
             -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
721
tcDataConPat penv (L con_span con_name) data_con pat_ty arg_pats thing_inside
722 723 724
  = do  { let tycon = dataConTyCon data_con
                  -- For data families this is the representation tycon
              (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _)
725
                = dataConFullSig data_con
cactus's avatar
cactus committed
726
              header = L con_span (RealDataCon data_con)
727

728 729 730
          -- 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
731
        ; (wrap, ctxt_res_tys) <- matchExpectedConTy penv tycon pat_ty
732
        ; pat_ty <- readExpType pat_ty
733

734 735
          -- Add the stupid theta
        ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
736

737 738
        ; let all_arg_tys = eqSpecPreds eq_spec ++ theta ++ arg_tys
        ; checkExistentials ex_tvs all_arg_tys penv
739
        ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX
740
                               (zipOpenTCvSubst univ_tvs ctxt_res_tys) ex_tvs
741 742
                     -- Get location from monad, not from ex_tvs

743
        ; let -- pat_ty' = mkTyConApp tycon ctxt_res_tys
744
              -- pat_ty' is type of the actual constructor application
745
              -- pat_ty' /= pat_ty iff coi /= IdCo
Simon Peyton Jones's avatar
Simon Peyton Jones committed
746

747
              arg_tys' = substTys tenv arg_tys
748

749 750 751 752
        ; 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 ])
753 754
        ; if null ex_tvs && null eq_spec && null theta
          then do { -- The common case; no class bindings etc
755
                    -- (see Note [Arrows and patterns])
756 757 758 759
                    (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 = [],
760
                                              pat_binds = emptyTcEvBinds,
761
                                              pat_args = arg_pats',
762
                                              pat_arg_tys = ctxt_res_tys,
cactus's avatar
cactus committed
763
                                              pat_wrap = idHsWrapper }
764

765
                  ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
766

767
          else do   -- The general case, with existential,
768
                    -- and local equality constraints
769
        { let theta'     = substTheta tenv (eqSpecPreds eq_spec ++ theta)
770 771
                           -- order is *important* as we generate the list of
                           -- dictionary binders from theta'
772
              no_equalities = not (any isNomEqPred theta')
773
              skol_info = case pe_ctxt penv of
cactus's avatar
cactus committed
774
                            LamPat mc -> PatSkol (RealDataCon data_con) mc
775
                            LetPat {} -> UnkSkol -- Doesn't matter
776

777 778
        ; gadts_on    <- xoptM LangExt.GADTs
        ; families_on <- xoptM LangExt.TypeFamilies
779
        ; checkTc (no_equalities || gadts_on || families_on)
sivteck's avatar
sivteck committed
780 781
                  (text "A pattern match on a GADT requires the" <+>
                   text "GADTs or TypeFamilies language extension")
782 783 784
                  -- Trac #2905 decided that a *pattern-match* of a GADT
                  -- should require the GADT language flag.
                  -- Re TypeFamilies see also #7156
785

786
        ; given <- newEvVars theta'
787
        ; (ev_binds, (arg_pats', res))
788
             <- checkConstraints skol_info ex_tvs' given $
cactus's avatar
cactus committed
789
                tcConArgs (RealDataCon data_con) arg_tys' arg_pats penv thing_inside
790

cactus's avatar
cactus committed
791
        ; let res_pat = ConPatOut { pat_con   = header,
792 793 794 795
                                    pat_tvs   = ex_tvs',
                                    pat_dicts = given,
                                    pat_binds = ev_binds,
                                    pat_args  = arg_pats',
796
                                    pat_arg_tys = ctxt_res_tys,
cactus's avatar
cactus committed
797
                                    pat_wrap  = idHsWrapper }
798 799
        ; return (mkHsWrapPat wrap res_pat pat_ty, res)
        } }
800

cactus's avatar
cactus committed
801
tcPatSynPat :: PatEnv -> Located Name -> PatSyn
802
            -> ExpSigmaType                -- Type of the pattern
803 804
            -> HsConPatDetails Name -> TcM a
            -> TcM (Pat TcId, a)
cactus's avatar
cactus committed
805
tcPatSynPat penv (L con_span _) pat_syn pat_ty arg_pats thing_inside
806
  = do  { let (univ_tvs, req_theta, ex_tvs, prov_theta, arg_tys, ty) = patSynSig pat_syn
cactus's avatar
cactus committed
807

808
        ; (subst, univ_tvs') <- newMetaTyVars univ_tvs
cactus's avatar
cactus committed
809

810 811
        ; let all_arg_tys = ty : prov_theta ++ arg_tys
        ; checkExistentials ex_tvs all_arg_tys penv
cactus's avatar
cactus committed
812
        ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX subst ex_tvs
813 814
        ; let ty'         = substTy tenv ty
              arg_tys'    = substTys tenv arg_tys
cactus's avatar
cactus committed
815
              prov_theta' = substTheta tenv prov_theta
816
              req_theta'  = substTheta tenv req_theta
cactus's avatar
cactus committed
817

818
        ; wrap <- tcSubTypeO (pe_orig penv) GenSigCtxt ty' pat_ty
cactus's avatar
cactus committed
819 820 821 822 823 824 825 826 827 828 829 830 831 832
        ; 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

Simon Peyton Jones's avatar