Use a Representaional coercion for data families
[ghc.git] / compiler / typecheck / TcPat.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 TcPat: Typechecking patterns
7 -}
8
9 {-# LANGUAGE CPP, RankNTypes #-}
10
11 module TcPat ( tcLetPat, TcSigFun, TcPragFun
12 , TcSigInfo(..), TcPatSynInfo(..)
13 , findScopedTyVars, isPartialSig
14 , completeSigPolyId, completeSigPolyId_maybe
15 , LetBndrSpec(..), addInlinePrags, warnPrags
16 , tcPat, tcPats, newNoSigLetBndr
17 , addDataConStupidTheta, badFieldCon, polyPatSig ) where
18
19 #include "HsVersions.h"
20
21 import {-# SOURCE #-} TcExpr( tcSyntaxOp, tcInferRho)
22
23 import HsSyn
24 import TcHsSyn
25 import TcRnMonad
26 import Inst
27 import Id
28 import Var
29 import Name
30 import NameSet
31 import TcEnv
32 import TcMType
33 import TcValidity( arityErr )
34 import TcType
35 import TcUnify
36 import TcHsType
37 import TysWiredIn
38 import TcEvidence
39 import TyCon
40 import DataCon
41 import PatSyn
42 import ConLike
43 import PrelNames
44 import BasicTypes hiding (SuccessFlag(..))
45 import DynFlags
46 import SrcLoc
47 import Util
48 import Outputable
49 import FastString
50 import Control.Monad
51 {-
52 ************************************************************************
53 * *
54 External interface
55 * *
56 ************************************************************************
57 -}
58
59 tcLetPat :: TcSigFun -> LetBndrSpec
60 -> LPat Name -> TcSigmaType
61 -> TcM a
62 -> TcM (LPat TcId, a)
63 tcLetPat sig_fn no_gen pat pat_ty thing_inside
64 = tc_lpat pat pat_ty penv thing_inside
65 where
66 penv = PE { pe_lazy = True
67 , pe_ctxt = LetPat sig_fn no_gen }
68
69 -----------------
70 tcPats :: HsMatchContext Name
71 -> [LPat Name] -- Patterns,
72 -> [TcSigmaType] -- and their types
73 -> TcM a -- and the checker for the body
74 -> TcM ([LPat TcId], a)
75
76 -- This is the externally-callable wrapper function
77 -- Typecheck the patterns, extend the environment to bind the variables,
78 -- do the thing inside, use any existentially-bound dictionaries to
79 -- discharge parts of the returning LIE, and deal with pattern type
80 -- signatures
81
82 -- 1. Initialise the PatState
83 -- 2. Check the patterns
84 -- 3. Check the body
85 -- 4. Check that no existentials escape
86
87 tcPats ctxt pats pat_tys thing_inside
88 = tc_lpats penv pats pat_tys thing_inside
89 where
90 penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt }
91
92 tcPat :: HsMatchContext Name
93 -> LPat Name -> TcSigmaType
94 -> TcM a -- Checker for body, given
95 -- its result type
96 -> TcM (LPat TcId, a)
97 tcPat ctxt pat pat_ty thing_inside
98 = tc_lpat pat pat_ty penv thing_inside
99 where
100 penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt }
101
102
103 -----------------
104 data PatEnv
105 = PE { pe_lazy :: Bool -- True <=> lazy context, so no existentials allowed
106 , pe_ctxt :: PatCtxt -- Context in which the whole pattern appears
107 }
108
109 data PatCtxt
110 = LamPat -- Used for lambdas, case etc
111 (HsMatchContext Name)
112
113 | LetPat -- Used only for let(rec) pattern bindings
114 -- See Note [Typing patterns in pattern bindings]
115 TcSigFun -- Tells type sig if any
116 LetBndrSpec -- True <=> no generalisation of this let
117
118 data LetBndrSpec
119 = LetLclBndr -- The binder is just a local one;
120 -- an AbsBinds will provide the global version
121
122 | LetGblBndr TcPragFun -- Generalisation plan is NoGen, so there isn't going
123 -- to be an AbsBinds; So we must bind the global version
124 -- of the binder right away.
125 -- Oh, and here is the inline-pragma information
126
127 makeLazy :: PatEnv -> PatEnv
128 makeLazy penv = penv { pe_lazy = True }
129
130 inPatBind :: PatEnv -> Bool
131 inPatBind (PE { pe_ctxt = LetPat {} }) = True
132 inPatBind (PE { pe_ctxt = LamPat {} }) = False
133
134 ---------------
135 type TcPragFun = Name -> [LSig Name]
136 type TcSigFun = Name -> Maybe TcSigInfo
137
138 data TcSigInfo
139 = TcSigInfo {
140 sig_name :: Name, -- The binder name of the type signature. When
141 -- sig_id = Just id, then sig_name = idName id.
142
143 sig_poly_id :: Maybe TcId,
144 -- Just f <=> the type signature had no wildcards, so the precise,
145 -- complete polymorphic type is known. In that case,
146 -- f is the polymorphic Id, with that type
147
148 -- Nothing <=> the type signature is partial (i.e. includes one or more
149 -- wildcards). In this case it doesn't make sense to give
150 -- the polymorphic Id, because we are going to /infer/ its
151 -- type, so we can't make the polymorphic Id ab-initio
152 --
153 -- See Note [Complete and partial type signatures]
154
155 sig_tvs :: [(Maybe Name, TcTyVar)],
156 -- Instantiated type and kind variables
157 -- Just n <=> this skolem is lexically in scope with name n
158 -- See Note [Binding scoped type variables]
159
160 sig_nwcs :: [(Name, TcTyVar)],
161 -- Instantiated wildcard variables
162 -- If sig_poly_id = Just f, then sig_nwcs must be empty
163
164 sig_extra_cts :: Maybe SrcSpan,
165 -- Just loc <=> An extra-constraints wildcard was present
166 -- at location loc
167 -- e.g. f :: (Eq a, _) => a -> a
168 -- Any extra constraints inferred during
169 -- type-checking will be added to the sig_theta.
170 -- If sig_poly_id = Just f, sig_extra_cts must be Nothing
171
172 sig_theta :: TcThetaType, -- Instantiated theta
173 sig_tau :: TcSigmaType, -- Instantiated tau
174 -- See Note [sig_tau may be polymorphic]
175
176 sig_loc :: SrcSpan, -- The location of the signature
177
178 sig_warn_redundant :: Bool -- True <=> report redundant constraints
179 -- when typechecking the value binding
180 -- for this type signature
181 -- This is usually True, but False for
182 -- * Record selectors (not important here)
183 -- * Class and instance methods. Here the code may legitimately
184 -- be more polymorphic than the signature generated from the
185 -- class declaration
186 }
187 | TcPatSynInfo TcPatSynInfo
188
189 data TcPatSynInfo
190 = TPSI {
191 patsig_name :: Name,
192 patsig_tau :: TcSigmaType,
193 patsig_ex :: [TcTyVar],
194 patsig_prov :: TcThetaType,
195 patsig_univ :: [TcTyVar],
196 patsig_req :: TcThetaType
197 }
198
199 findScopedTyVars -- See Note [Binding scoped type variables]
200 :: LHsType Name -- The HsType
201 -> TcType -- The corresponding Type:
202 -- uses same Names as the HsType
203 -> [TcTyVar] -- The instantiated forall variables of the Type
204 -> [(Maybe Name, TcTyVar)] -- In 1-1 correspondence with the instantiated vars
205 findScopedTyVars hs_ty sig_ty inst_tvs
206 = zipWith find sig_tvs inst_tvs
207 where
208 find sig_tv inst_tv
209 | tv_name `elemNameSet` scoped_names = (Just tv_name, inst_tv)
210 | otherwise = (Nothing, inst_tv)
211 where
212 tv_name = tyVarName sig_tv
213
214 scoped_names = mkNameSet (hsExplicitTvs hs_ty)
215 (sig_tvs,_) = tcSplitForAllTys sig_ty
216
217 instance NamedThing TcSigInfo where
218 getName TcSigInfo{ sig_name = name } = name
219 getName (TcPatSynInfo tpsi) = patsig_name tpsi
220
221
222 instance Outputable TcSigInfo where
223 ppr (TcSigInfo { sig_name = name, sig_poly_id = mb_poly_id, sig_tvs = tyvars
224 , sig_theta = theta, sig_tau = tau })
225 = maybe (ppr name) ppr mb_poly_id <+> dcolon <+>
226 vcat [ pprSigmaType (mkSigmaTy (map snd tyvars) theta tau)
227 , ppr (map fst tyvars) ]
228 ppr (TcPatSynInfo tpsi) = text "TcPatSynInfo" <+> ppr tpsi
229
230 instance Outputable TcPatSynInfo where
231 ppr (TPSI{ patsig_name = name}) = ppr name
232
233 isPartialSig :: TcSigInfo -> Bool
234 isPartialSig (TcSigInfo { sig_poly_id = Nothing }) = True
235 isPartialSig _ = False
236
237 -- Helper for cases when we know for sure we have a complete type
238 -- signature, e.g. class methods.
239 completeSigPolyId :: TcSigInfo -> TcId
240 completeSigPolyId (TcSigInfo { sig_poly_id = Just id }) = id
241 completeSigPolyId _ = panic "completeSigPolyId"
242
243 completeSigPolyId_maybe :: TcSigInfo -> Maybe TcId
244 completeSigPolyId_maybe (TcSigInfo { sig_poly_id = mb_id }) = mb_id
245 completeSigPolyId_maybe (TcPatSynInfo {}) = Nothing
246
247 {-
248 Note [Binding scoped type variables]
249 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
250 The type variables *brought into lexical scope* by a type signature may
251 be a subset of the *quantified type variables* of the signatures, for two reasons:
252
253 * With kind polymorphism a signature like
254 f :: forall f a. f a -> f a
255 may actually give rise to
256 f :: forall k. forall (f::k -> *) (a:k). f a -> f a
257 So the sig_tvs will be [k,f,a], but only f,a are scoped.
258 NB: the scoped ones are not necessarily the *inital* ones!
259
260 * Even aside from kind polymorphism, tere may be more instantiated
261 type variables than lexically-scoped ones. For example:
262 type T a = forall b. b -> (a,b)
263 f :: forall c. T c
264 Here, the signature for f will have one scoped type variable, c,
265 but two instantiated type variables, c' and b'.
266
267 The function findScopedTyVars takes
268 * hs_ty: the original HsForAllTy
269 * sig_ty: the corresponding Type (which is guaranteed to use the same Names
270 as the HsForAllTy)
271 * inst_tvs: the skolems instantiated from the forall's in sig_ty
272 It returns a [(Maybe Name, TcTyVar)], in 1-1 correspondence with inst_tvs
273 but with a (Just n) for the lexically scoped name of each in-scope tyvar.
274
275 Note [sig_tau may be polymorphic]
276 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
277 Note that "sig_tau" might actually be a polymorphic type,
278 if the original function had a signature like
279 forall a. Eq a => forall b. Ord b => ....
280 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
281 It happens, too! See Note [Polymorphic methods] in TcClassDcl.
282
283 Note [Existential check]
284 ~~~~~~~~~~~~~~~~~~~~~~~~
285 Lazy patterns can't bind existentials. They arise in two ways:
286 * Let bindings let { C a b = e } in b
287 * Twiddle patterns f ~(C a b) = e
288 The pe_lazy field of PatEnv says whether we are inside a lazy
289 pattern (perhaps deeply)
290
291 If we aren't inside a lazy pattern then we can bind existentials,
292 but we need to be careful about "extra" tyvars. Consider
293 (\C x -> d) : pat_ty -> res_ty
294 When looking for existential escape we must check that the existential
295 bound by C don't unify with the free variables of pat_ty, OR res_ty
296 (or of course the environment). Hence we need to keep track of the
297 res_ty free vars.
298
299 Note [Complete and partial type signatures]
300 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
301 A type signature is partial when it contains one or more wildcards
302 (= type holes). The wildcard can either be:
303 * A (type) wildcard occurring in sig_theta or sig_tau. These are
304 stored in sig_nwcs.
305 f :: Bool -> _
306 g :: Eq _a => _a -> _a -> Bool
307 * Or an extra-constraints wildcard, stored in sig_extra_cts:
308 h :: (Num a, _) => a -> a
309
310 A type signature is a complete type signature when there are no
311 wildcards in the type signature, i.e. iff sig_nwcs is empty and
312 sig_extra_cts is Nothing.
313
314 ************************************************************************
315 * *
316 Binders
317 * *
318 ************************************************************************
319 -}
320
321 tcPatBndr :: PatEnv -> Name -> TcSigmaType -> TcM (TcCoercion, TcId)
322 -- (coi, xp) = tcPatBndr penv x pat_ty
323 -- Then coi : pat_ty ~ typeof(xp)
324 --
325 tcPatBndr (PE { pe_ctxt = LetPat lookup_sig no_gen}) bndr_name pat_ty
326 -- See Note [Typing patterns in pattern bindings]
327 | LetGblBndr prags <- no_gen
328 , Just sig <- lookup_sig bndr_name
329 , Just poly_id <- sig_poly_id sig
330 = do { bndr_id <- addInlinePrags poly_id (prags bndr_name)
331 ; traceTc "tcPatBndr(gbl,sig)" (ppr bndr_id $$ ppr (idType bndr_id))
332 ; co <- unifyPatType (idType bndr_id) pat_ty
333 ; return (co, bndr_id) }
334
335 | otherwise
336 = do { bndr_id <- newNoSigLetBndr no_gen bndr_name pat_ty
337 ; traceTc "tcPatBndr(no-sig)" (ppr bndr_id $$ ppr (idType bndr_id))
338 ; return (mkTcNomReflCo pat_ty, bndr_id) }
339
340 tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty
341 = return (mkTcNomReflCo pat_ty, mkLocalId bndr_name pat_ty)
342
343 ------------
344 newNoSigLetBndr :: LetBndrSpec -> Name -> TcType -> TcM TcId
345 -- In the polymorphic case (no_gen = LetLclBndr), generate a "monomorphic version"
346 -- of the Id; the original name will be bound to the polymorphic version
347 -- by the AbsBinds
348 -- In the monomorphic case (no_gen = LetBglBndr) there is no AbsBinds, and we
349 -- use the original name directly
350 newNoSigLetBndr LetLclBndr name ty
351 =do { mono_name <- newLocalName name
352 ; return (mkLocalId mono_name ty) }
353 newNoSigLetBndr (LetGblBndr prags) name ty
354 = addInlinePrags (mkLocalId name ty) (prags name)
355
356 ----------
357 addInlinePrags :: TcId -> [LSig Name] -> TcM TcId
358 addInlinePrags poly_id prags
359 = do { traceTc "addInlinePrags" (ppr poly_id $$ ppr prags)
360 ; tc_inl inl_sigs }
361 where
362 inl_sigs = filter isInlineLSig prags
363 tc_inl [] = return poly_id
364 tc_inl (L loc (InlineSig _ prag) : other_inls)
365 = do { unless (null other_inls) (setSrcSpan loc warn_dup_inline)
366 ; traceTc "addInlinePrag" (ppr poly_id $$ ppr prag)
367 ; return (poly_id `setInlinePragma` prag) }
368 tc_inl _ = panic "tc_inl"
369
370 warn_dup_inline = warnPrags poly_id inl_sigs $
371 ptext (sLit "Duplicate INLINE pragmas for")
372
373 warnPrags :: Id -> [LSig Name] -> SDoc -> TcM ()
374 warnPrags id bad_sigs herald
375 = addWarnTc (hang (herald <+> quotes (ppr id))
376 2 (ppr_sigs bad_sigs))
377 where
378 ppr_sigs sigs = vcat (map (ppr . getLoc) sigs)
379
380 {-
381 Note [Typing patterns in pattern bindings]
382 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
383 Suppose we are typing a pattern binding
384 pat = rhs
385 Then the PatCtxt will be (LetPat sig_fn let_bndr_spec).
386
387 There can still be signatures for the binders:
388 data T = MkT (forall a. a->a) Int
389 x :: forall a. a->a
390 y :: Int
391 MkT x y = <rhs>
392
393 Two cases, dealt with by the LetPat case of tcPatBndr
394
395 * If we are generalising (generalisation plan is InferGen or
396 CheckGen), then the let_bndr_spec will be LetLclBndr. In that case
397 we want to bind a cloned, local version of the variable, with the
398 type given by the pattern context, *not* by the signature (even if
399 there is one; see Trac #7268). The mkExport part of the
400 generalisation step will do the checking and impedance matching
401 against the signature.
402
403 * If for some some reason we are not generalising (plan = NoGen), the
404 LetBndrSpec will be LetGblBndr. In that case we must bind the
405 global version of the Id, and do so with precisely the type given
406 in the signature. (Then we unify with the type from the pattern
407 context type.
408
409
410 ************************************************************************
411 * *
412 The main worker functions
413 * *
414 ************************************************************************
415
416 Note [Nesting]
417 ~~~~~~~~~~~~~~
418 tcPat takes a "thing inside" over which the pattern scopes. This is partly
419 so that tcPat can extend the environment for the thing_inside, but also
420 so that constraints arising in the thing_inside can be discharged by the
421 pattern.
422
423 This does not work so well for the ErrCtxt carried by the monad: we don't
424 want the error-context for the pattern to scope over the RHS.
425 Hence the getErrCtxt/setErrCtxt stuff in tcMultiple
426 -}
427
428 --------------------
429 type Checker inp out = forall r.
430 inp
431 -> PatEnv
432 -> TcM r
433 -> TcM (out, r)
434
435 tcMultiple :: Checker inp out -> Checker [inp] [out]
436 tcMultiple tc_pat args penv thing_inside
437 = do { err_ctxt <- getErrCtxt
438 ; let loop _ []
439 = do { res <- thing_inside
440 ; return ([], res) }
441
442 loop penv (arg:args)
443 = do { (p', (ps', res))
444 <- tc_pat arg penv $
445 setErrCtxt err_ctxt $
446 loop penv args
447 -- setErrCtxt: restore context before doing the next pattern
448 -- See note [Nesting] above
449
450 ; return (p':ps', res) }
451
452 ; loop penv args }
453
454 --------------------
455 tc_lpat :: LPat Name
456 -> TcSigmaType
457 -> PatEnv
458 -> TcM a
459 -> TcM (LPat TcId, a)
460 tc_lpat (L span pat) pat_ty penv thing_inside
461 = setSrcSpan span $
462 do { (pat', res) <- maybeWrapPatCtxt pat (tc_pat penv pat pat_ty)
463 thing_inside
464 ; return (L span pat', res) }
465
466 tc_lpats :: PatEnv
467 -> [LPat Name] -> [TcSigmaType]
468 -> TcM a
469 -> TcM ([LPat TcId], a)
470 tc_lpats penv pats tys thing_inside
471 = ASSERT2( equalLength pats tys, ppr pats $$ ppr tys )
472 tcMultiple (\(p,t) -> tc_lpat p t)
473 (zipEqual "tc_lpats" pats tys)
474 penv thing_inside
475
476 --------------------
477 tc_pat :: PatEnv
478 -> Pat Name
479 -> TcSigmaType -- Fully refined result type
480 -> TcM a -- Thing inside
481 -> TcM (Pat TcId, -- Translated pattern
482 a) -- Result of thing inside
483
484 tc_pat penv (VarPat name) pat_ty thing_inside
485 = do { (co, id) <- tcPatBndr penv name pat_ty
486 ; res <- tcExtendIdEnv1 name id thing_inside
487 ; return (mkHsWrapPatCo co (VarPat id) pat_ty, res) }
488
489 tc_pat penv (ParPat pat) pat_ty thing_inside
490 = do { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
491 ; return (ParPat pat', res) }
492
493 tc_pat penv (BangPat pat) pat_ty thing_inside
494 = do { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
495 ; return (BangPat pat', res) }
496
497 tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside
498 = do { (pat', (res, pat_ct))
499 <- tc_lpat pat pat_ty (makeLazy penv) $
500 captureConstraints thing_inside
501 -- Ignore refined penv', revert to penv
502
503 ; emitConstraints pat_ct
504 -- captureConstraints/extendConstraints:
505 -- see Note [Hopping the LIE in lazy patterns]
506
507 -- Check there are no unlifted types under the lazy pattern
508 ; when (any (isUnLiftedType . idType) $ collectPatBinders pat') $
509 lazyUnliftedPatErr lpat
510
511 -- Check that the expected pattern type is itself lifted
512 ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
513 ; _ <- unifyType pat_ty pat_ty'
514
515 ; return (LazyPat pat', res) }
516
517 tc_pat _ (WildPat _) pat_ty thing_inside
518 = do { res <- thing_inside
519 ; return (WildPat pat_ty, res) }
520
521 tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
522 = do { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
523 ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
524 tc_lpat pat (idType bndr_id) penv thing_inside
525 -- NB: if we do inference on:
526 -- \ (y@(x::forall a. a->a)) = e
527 -- we'll fail. The as-pattern infers a monotype for 'y', which then
528 -- fails to unify with the polymorphic type for 'x'. This could
529 -- perhaps be fixed, but only with a bit more work.
530 --
531 -- If you fix it, don't forget the bindInstsOfPatIds!
532 ; return (mkHsWrapPatCo co (AsPat (L nm_loc bndr_id) pat') pat_ty, res) }
533
534 tc_pat penv (ViewPat expr pat _) overall_pat_ty thing_inside
535 = do {
536 -- Morally, expr must have type `forall a1...aN. OPT' -> B`
537 -- where overall_pat_ty is an instance of OPT'.
538 -- Here, we infer a rho type for it,
539 -- which replaces the leading foralls and constraints
540 -- with fresh unification variables.
541 ; (expr',expr'_inferred) <- tcInferRho expr
542
543 -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
544 -- NOTE: this forces pat_ty to be a monotype (because we use a unification
545 -- variable to find it). this means that in an example like
546 -- (view -> f) where view :: _ -> forall b. b
547 -- we will only be able to use view at one instantation in the
548 -- rest of the view
549 ; (expr_co, pat_ty) <- tcInfer $ \ pat_ty ->
550 unifyType expr'_inferred (mkFunTy overall_pat_ty pat_ty)
551
552 -- pattern must have pat_ty
553 ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside
554
555 ; return (ViewPat (mkLHsWrapCo expr_co expr') pat' overall_pat_ty, res) }
556
557 -- Type signatures in patterns
558 -- See Note [Pattern coercions] below
559 tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
560 = do { (inner_ty, tv_binds, nwc_binds, wrap) <- tcPatSig (inPatBind penv)
561 sig_ty pat_ty
562 ; (pat', res) <- tcExtendTyVarEnv2 (tv_binds ++ nwc_binds) $
563 tc_lpat pat inner_ty penv thing_inside
564 ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
565
566 ------------------------
567 -- Lists, tuples, arrays
568 tc_pat penv (ListPat pats _ Nothing) pat_ty thing_inside
569 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTyR pat_ty
570 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
571 pats penv thing_inside
572 ; return (mkHsWrapPat coi (ListPat pats' elt_ty Nothing) pat_ty, res)
573 }
574
575 tc_pat penv (ListPat pats _ (Just (_,e))) pat_ty thing_inside
576 = do { list_pat_ty <- newFlexiTyVarTy liftedTypeKind
577 ; e' <- tcSyntaxOp ListOrigin e (mkFunTy pat_ty list_pat_ty)
578 ; (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTyR list_pat_ty
579 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
580 pats penv thing_inside
581 ; return (mkHsWrapPat coi (ListPat pats' elt_ty (Just (pat_ty,e'))) list_pat_ty, res)
582 }
583
584 tc_pat penv (PArrPat pats _) pat_ty thing_inside
585 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTyR pat_ty
586 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
587 pats penv thing_inside
588 ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
589 }
590
591 tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
592 = do { let tc = tupleTyCon boxity (length pats)
593 ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConAppR tc) pat_ty
594 ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
595
596 ; dflags <- getDynFlags
597
598 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
599 -- so that we can experiment with lazy tuple-matching.
600 -- This is a pretty odd place to make the switch, but
601 -- it was easy to do.
602 ; let
603 unmangled_result = TuplePat pats' boxity arg_tys
604 -- pat_ty /= pat_ty iff coi /= IdCo
605 possibly_mangled_result
606 | gopt Opt_IrrefutableTuples dflags &&
607 isBoxed boxity = LazyPat (noLoc unmangled_result)
608 | otherwise = unmangled_result
609
610 ; ASSERT( length arg_tys == length pats ) -- Syntactically enforced
611 return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
612 }
613
614 ------------------------
615 -- Data constructors
616 tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
617 = tcConPat penv con pat_ty arg_pats thing_inside
618
619 ------------------------
620 -- Literal patterns
621 tc_pat _ (LitPat simple_lit) pat_ty thing_inside
622 = do { let lit_ty = hsLitType simple_lit
623 ; co <- unifyPatType lit_ty pat_ty
624 -- coi is of kind: pat_ty ~ lit_ty
625 ; res <- thing_inside
626 ; return ( mkHsWrapPatCo co (LitPat simple_lit) pat_ty
627 , res) }
628
629 ------------------------
630 -- Overloaded patterns: n, and n+k
631 tc_pat _ (NPat (L l over_lit) mb_neg eq) pat_ty thing_inside
632 = do { let orig = LiteralOrigin over_lit
633 ; lit' <- newOverloadedLit orig over_lit pat_ty
634 ; eq' <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
635 ; mb_neg' <- case mb_neg of
636 Nothing -> return Nothing -- Positive literal
637 Just neg -> -- Negative literal
638 -- The 'negate' is re-mappable syntax
639 do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
640 ; return (Just neg') }
641 ; res <- thing_inside
642 ; return (NPat (L l lit') mb_neg' eq', res) }
643
644 tc_pat penv (NPlusKPat (L nm_loc name) (L loc lit) ge minus) pat_ty thing_inside
645 = do { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
646 ; let pat_ty' = idType bndr_id
647 orig = LiteralOrigin lit
648 ; lit' <- newOverloadedLit orig lit pat_ty'
649
650 -- The '>=' and '-' parts are re-mappable syntax
651 ; ge' <- tcSyntaxOp orig ge (mkFunTys [pat_ty', pat_ty'] boolTy)
652 ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
653 ; let pat' = NPlusKPat (L nm_loc bndr_id) (L loc lit') ge' minus'
654
655 -- The Report says that n+k patterns must be in Integral
656 -- We may not want this when using re-mappable syntax, though (ToDo?)
657 ; icls <- tcLookupClass integralClassName
658 ; instStupidTheta orig [mkClassPred icls [pat_ty']]
659
660 ; res <- tcExtendIdEnv1 name bndr_id thing_inside
661 ; return (mkHsWrapPatCo co pat' pat_ty, res) }
662
663 tc_pat _ _other_pat _ _ = panic "tc_pat" -- ConPatOut, SigPatOut
664
665 ----------------
666 unifyPatType :: TcType -> TcType -> TcM TcCoercion
667 -- In patterns we want a coercion from the
668 -- context type (expected) to the actual pattern type
669 -- But we don't want to reverse the args to unifyType because
670 -- that controls the actual/expected stuff in error messages
671 unifyPatType actual_ty expected_ty
672 = do { coi <- unifyType actual_ty expected_ty
673 ; return (mkTcSymCo coi) }
674
675 {-
676 Note [Hopping the LIE in lazy patterns]
677 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
678 In a lazy pattern, we must *not* discharge constraints from the RHS
679 from dictionaries bound in the pattern. E.g.
680 f ~(C x) = 3
681 We can't discharge the Num constraint from dictionaries bound by
682 the pattern C!
683
684 So we have to make the constraints from thing_inside "hop around"
685 the pattern. Hence the captureConstraints and emitConstraints.
686
687 The same thing ensures that equality constraints in a lazy match
688 are not made available in the RHS of the match. For example
689 data T a where { T1 :: Int -> T Int; ... }
690 f :: T a -> Int -> a
691 f ~(T1 i) y = y
692 It's obviously not sound to refine a to Int in the right
693 hand side, because the argument might not match T1 at all!
694
695 Finally, a lazy pattern should not bind any existential type variables
696 because they won't be in scope when we do the desugaring
697
698
699 ************************************************************************
700 * *
701 Most of the work for constructors is here
702 (the rest is in the ConPatIn case of tc_pat)
703 * *
704 ************************************************************************
705
706 [Pattern matching indexed data types]
707 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
708 Consider the following declarations:
709
710 data family Map k :: * -> *
711 data instance Map (a, b) v = MapPair (Map a (Pair b v))
712
713 and a case expression
714
715 case x :: Map (Int, c) w of MapPair m -> ...
716
717 As explained by [Wrappers for data instance tycons] in MkIds.hs, the
718 worker/wrapper types for MapPair are
719
720 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
721 $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
722
723 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
724 :R123Map, which means the straight use of boxySplitTyConApp would give a type
725 error. Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
726 boxySplitTyConApp with the family tycon Map instead, which gives us the family
727 type list {(Int, c), w}. To get the correct split for :R123Map, we need to
728 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
729 (provided by tyConFamInst_maybe together with the family tycon). This
730 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
731 the split arguments for the representation tycon :R123Map as {Int, c, w}
732
733 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
734
735 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
736
737 moving between representation and family type into account. To produce type
738 correct Core, this coercion needs to be used to case the type of the scrutinee
739 from the family to the representation type. This is achieved by
740 unwrapFamInstScrutinee using a CoPat around the result pattern.
741
742 Now it might appear seem as if we could have used the previous GADT type
743 refinement infrastructure of refineAlt and friends instead of the explicit
744 unification and CoPat generation. However, that would be wrong. Why? The
745 whole point of GADT refinement is that the refinement is local to the case
746 alternative. In contrast, the substitution generated by the unification of
747 the family type list and instance types needs to be propagated to the outside.
748 Imagine that in the above example, the type of the scrutinee would have been
749 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
750 substitution [x -> (a, b), v -> w]. In contrast to GADT matching, the
751 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
752 alternatives of the case expression, whereas in the GADT case it might vary
753 between alternatives.
754
755 RIP GADT refinement: refinements have been replaced by the use of explicit
756 equality constraints that are used in conjunction with implication constraints
757 to express the local scope of GADT refinements.
758 -}
759
760 -- Running example:
761 -- MkT :: forall a b c. (a~[b]) => b -> c -> T a
762 -- with scrutinee of type (T ty)
763
764 tcConPat :: PatEnv -> Located Name
765 -> TcRhoType -- Type of the pattern
766 -> HsConPatDetails Name -> TcM a
767 -> TcM (Pat TcId, a)
768 tcConPat penv con_lname@(L _ con_name) pat_ty arg_pats thing_inside
769 = do { con_like <- tcLookupConLike con_name
770 ; case con_like of
771 RealDataCon data_con -> tcDataConPat penv con_lname data_con
772 pat_ty arg_pats thing_inside
773 PatSynCon pat_syn -> tcPatSynPat penv con_lname pat_syn
774 pat_ty arg_pats thing_inside
775 }
776
777 tcDataConPat :: PatEnv -> Located Name -> DataCon
778 -> TcRhoType -- Type of the pattern
779 -> HsConPatDetails Name -> TcM a
780 -> TcM (Pat TcId, a)
781 tcDataConPat penv (L con_span con_name) data_con pat_ty arg_pats thing_inside
782 = do { let tycon = dataConTyCon data_con
783 -- For data families this is the representation tycon
784 (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _)
785 = dataConFullSig data_con
786 header = L con_span (RealDataCon data_con)
787
788 -- Instantiate the constructor type variables [a->ty]
789 -- This may involve doing a family-instance coercion,
790 -- and building a wrapper
791 ; (wrap, ctxt_res_tys) <- matchExpectedPatTy (matchExpectedConTy tycon) pat_ty
792
793 -- Add the stupid theta
794 ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
795
796 ; checkExistentials ex_tvs penv
797 ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX
798 (zipTopTvSubst univ_tvs ctxt_res_tys) ex_tvs
799 -- Get location from monad, not from ex_tvs
800
801 ; let -- pat_ty' = mkTyConApp tycon ctxt_res_tys
802 -- pat_ty' is type of the actual constructor application
803 -- pat_ty' /= pat_ty iff coi /= IdCo
804
805 arg_tys' = substTys tenv arg_tys
806
807 ; traceTc "tcConPat" (vcat [ ppr con_name, ppr univ_tvs, ppr ex_tvs, ppr eq_spec
808 , ppr ex_tvs', ppr ctxt_res_tys, ppr arg_tys' ])
809 ; if null ex_tvs && null eq_spec && null theta
810 then do { -- The common case; no class bindings etc
811 -- (see Note [Arrows and patterns])
812 (arg_pats', res) <- tcConArgs (RealDataCon data_con) arg_tys'
813 arg_pats penv thing_inside
814 ; let res_pat = ConPatOut { pat_con = header,
815 pat_tvs = [], pat_dicts = [],
816 pat_binds = emptyTcEvBinds,
817 pat_args = arg_pats',
818 pat_arg_tys = ctxt_res_tys,
819 pat_wrap = idHsWrapper }
820
821 ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
822
823 else do -- The general case, with existential,
824 -- and local equality constraints
825 { let theta' = substTheta tenv (eqSpecPreds eq_spec ++ theta)
826 -- order is *important* as we generate the list of
827 -- dictionary binders from theta'
828 no_equalities = not (any isEqPred theta')
829 skol_info = case pe_ctxt penv of
830 LamPat mc -> PatSkol (RealDataCon data_con) mc
831 LetPat {} -> UnkSkol -- Doesn't matter
832
833 ; gadts_on <- xoptM Opt_GADTs
834 ; families_on <- xoptM Opt_TypeFamilies
835 ; checkTc (no_equalities || gadts_on || families_on)
836 (text "A pattern match on a GADT requires the" <+>
837 text "GADTs or TypeFamilies language extension")
838 -- Trac #2905 decided that a *pattern-match* of a GADT
839 -- should require the GADT language flag.
840 -- Re TypeFamilies see also #7156
841
842 ; given <- newEvVars theta'
843 ; (ev_binds, (arg_pats', res))
844 <- checkConstraints skol_info ex_tvs' given $
845 tcConArgs (RealDataCon data_con) arg_tys' arg_pats penv thing_inside
846
847 ; let res_pat = ConPatOut { pat_con = header,
848 pat_tvs = ex_tvs',
849 pat_dicts = given,
850 pat_binds = ev_binds,
851 pat_args = arg_pats',
852 pat_arg_tys = ctxt_res_tys,
853 pat_wrap = idHsWrapper }
854 ; return (mkHsWrapPat wrap res_pat pat_ty, res)
855 } }
856
857 tcPatSynPat :: PatEnv -> Located Name -> PatSyn
858 -> TcRhoType -- Type of the pattern
859 -> HsConPatDetails Name -> TcM a
860 -> TcM (Pat TcId, a)
861 tcPatSynPat penv (L con_span _) pat_syn pat_ty arg_pats thing_inside
862 = do { let (univ_tvs, ex_tvs, prov_theta, req_theta, arg_tys, ty) = patSynSig pat_syn
863
864 ; (subst, univ_tvs') <- tcInstTyVars univ_tvs
865
866 ; checkExistentials ex_tvs penv
867 ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX subst ex_tvs
868 ; let ty' = substTy tenv ty
869 arg_tys' = substTys tenv arg_tys
870 prov_theta' = substTheta tenv prov_theta
871 req_theta' = substTheta tenv req_theta
872
873 ; wrap <- coToHsWrapper <$> unifyType ty' pat_ty
874 ; traceTc "tcPatSynPat" (ppr pat_syn $$
875 ppr pat_ty $$
876 ppr ty' $$
877 ppr ex_tvs' $$
878 ppr prov_theta' $$
879 ppr req_theta' $$
880 ppr arg_tys')
881
882 ; prov_dicts' <- newEvVars prov_theta'
883
884 ; let skol_info = case pe_ctxt penv of
885 LamPat mc -> PatSkol (PatSynCon pat_syn) mc
886 LetPat {} -> UnkSkol -- Doesn't matter
887
888 ; req_wrap <- instCall PatOrigin (mkTyVarTys univ_tvs') req_theta'
889 ; traceTc "instCall" (ppr req_wrap)
890
891 ; traceTc "checkConstraints {" Outputable.empty
892 ; (ev_binds, (arg_pats', res))
893 <- checkConstraints skol_info ex_tvs' prov_dicts' $
894 tcConArgs (PatSynCon pat_syn) arg_tys' arg_pats penv thing_inside
895
896 ; traceTc "checkConstraints }" (ppr ev_binds)
897 ; let res_pat = ConPatOut { pat_con = L con_span $ PatSynCon pat_syn,
898 pat_tvs = ex_tvs',
899 pat_dicts = prov_dicts',
900 pat_binds = ev_binds,
901 pat_args = arg_pats',
902 pat_arg_tys = mkTyVarTys univ_tvs',
903 pat_wrap = req_wrap }
904 ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
905
906 ----------------------------
907 downgrade :: (TcRhoType -> TcM (TcCoercionN, a))
908 -> TcRhoType -> TcM (TcCoercionR, a)
909 downgrade f a = do { (co,res) <- f a; return (mkTcSubCo co, res) }
910
911 matchExpectedListTyR :: TcRhoType -> TcM (TcCoercionR, TcRhoType)
912 matchExpectedListTyR = downgrade matchExpectedListTy
913 matchExpectedPArrTyR :: TcRhoType -> TcM (TcCoercionR, TcRhoType)
914 matchExpectedPArrTyR = downgrade matchExpectedPArrTy
915 matchExpectedTyConAppR :: TyCon -> TcRhoType -> TcM (TcCoercionR, [TcSigmaType])
916 matchExpectedTyConAppR tc = downgrade (matchExpectedTyConApp tc)
917
918 ----------------------------
919 matchExpectedPatTy :: (TcRhoType -> TcM (TcCoercionR, a))
920 -> TcRhoType -> TcM (HsWrapper, a)
921 -- See Note [Matching polytyped patterns]
922 -- Returns a wrapper : pat_ty ~R inner_ty
923 matchExpectedPatTy inner_match pat_ty
924 | null tvs && null theta
925 = do { (co, res) <- inner_match pat_ty -- 'co' is Representational
926 ; traceTc "matchExpectedPatTy" (ppr pat_ty $$ ppr co $$ ppr (isTcReflCo co))
927 ; return (coToHsWrapperR (mkTcSymCo co), res) }
928 -- The Sym is because the inner_match returns a coercion
929 -- that is the other way round to matchExpectedPatTy
930
931 | otherwise
932 = do { (subst, tvs') <- tcInstTyVars tvs
933 ; wrap1 <- instCall PatOrigin (mkTyVarTys tvs') (substTheta subst theta)
934 ; (wrap2, arg_tys) <- matchExpectedPatTy inner_match (TcType.substTy subst tau)
935 ; return (wrap2 <.> wrap1, arg_tys) }
936 where
937 (tvs, theta, tau) = tcSplitSigmaTy pat_ty
938
939 ----------------------------
940 matchExpectedConTy :: TyCon -- The TyCon that this data
941 -- constructor actually returns
942 -> TcRhoType -- The type of the pattern
943 -> TcM (TcCoercionR, [TcSigmaType])
944 -- See Note [Matching constructor patterns]
945 -- Returns a coercion : T ty1 ... tyn ~ pat_ty
946 -- This is the same way round as matchExpectedListTy etc
947 -- but the other way round to matchExpectedPatTy
948 matchExpectedConTy data_tc pat_ty
949 | Just (fam_tc, fam_args, co_tc) <- tyConFamInstSig_maybe data_tc
950 -- Comments refer to Note [Matching constructor patterns]
951 -- co_tc :: forall a. T [a] ~ T7 a
952 = do { (subst, tvs') <- tcInstTyVars (tyConTyVars data_tc)
953 -- tys = [ty1,ty2]
954
955 ; traceTc "matchExpectedConTy" (vcat [ppr data_tc,
956 ppr (tyConTyVars data_tc),
957 ppr fam_tc, ppr fam_args])
958 ; co1 <- unifyType (mkTyConApp fam_tc (substTys subst fam_args)) pat_ty
959 -- co1 : T (ty1,ty2) ~N pat_ty
960
961 ; let tys' = mkTyVarTys tvs'
962 co2 = mkTcUnbranchedAxInstCo Representational co_tc tys'
963 -- co2 : T (ty1,ty2) ~R T7 ty1 ty2
964
965 ; return (mkTcSymCo co2 `mkTcTransCo` mkTcSubCo co1, tys') }
966
967 | otherwise
968 = matchExpectedTyConAppR data_tc pat_ty
969 -- coi : T tys ~R pat_ty
970
971 {-
972 Note [Matching constructor patterns]
973 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
974 Suppose (coi, tys) = matchExpectedConType data_tc pat_ty
975
976 * In the simple case, pat_ty = tc tys
977
978 * If pat_ty is a polytype, we want to instantiate it
979 This is like part of a subsumption check. Eg
980 f :: (forall a. [a]) -> blah
981 f [] = blah
982
983 * In a type family case, suppose we have
984 data family T a
985 data instance T (p,q) = A p | B q
986 Then we'll have internally generated
987 data T7 p q = A p | B q
988 axiom coT7 p q :: T (p,q) ~ T7 p q
989
990 So if pat_ty = T (ty1,ty2), we return (coi, [ty1,ty2]) such that
991 coi = coi2 . coi1 : T7 t ~ pat_ty
992 coi1 : T (ty1,ty2) ~ pat_ty
993 coi2 : T7 ty1 ty2 ~ T (ty1,ty2)
994
995 For families we do all this matching here, not in the unifier,
996 because we never want a whisper of the data_tycon to appear in
997 error messages; it's a purely internal thing
998 -}
999
1000 tcConArgs :: ConLike -> [TcSigmaType]
1001 -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
1002
1003 tcConArgs con_like arg_tys (PrefixCon arg_pats) penv thing_inside
1004 = do { checkTc (con_arity == no_of_args) -- Check correct arity
1005 (arityErr "constructor" con_like con_arity no_of_args)
1006 ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
1007 ; (arg_pats', res) <- tcMultiple tcConArg pats_w_tys
1008 penv thing_inside
1009 ; return (PrefixCon arg_pats', res) }
1010 where
1011 con_arity = conLikeArity con_like
1012 no_of_args = length arg_pats
1013
1014 tcConArgs con_like arg_tys (InfixCon p1 p2) penv thing_inside
1015 = do { checkTc (con_arity == 2) -- Check correct arity
1016 (arityErr "constructor" con_like con_arity 2)
1017 ; let [arg_ty1,arg_ty2] = arg_tys -- This can't fail after the arity check
1018 ; ([p1',p2'], res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
1019 penv thing_inside
1020 ; return (InfixCon p1' p2', res) }
1021 where
1022 con_arity = conLikeArity con_like
1023
1024 tcConArgs con_like arg_tys (RecCon (HsRecFields rpats dd)) penv thing_inside
1025 = do { (rpats', res) <- tcMultiple tc_field rpats penv thing_inside
1026 ; return (RecCon (HsRecFields rpats' dd), res) }
1027 where
1028 tc_field :: Checker (LHsRecField FieldLabel (LPat Name))
1029 (LHsRecField TcId (LPat TcId))
1030 tc_field (L l (HsRecField field_lbl pat pun)) penv thing_inside
1031 = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
1032 ; (pat', res) <- tcConArg (pat, pat_ty) penv thing_inside
1033 ; return (L l (HsRecField sel_id pat' pun), res) }
1034
1035 find_field_ty :: FieldLabel -> TcM (Id, TcType)
1036 find_field_ty field_lbl
1037 = case [ty | (f,ty) <- field_tys, f == field_lbl] of
1038
1039 -- No matching field; chances are this field label comes from some
1040 -- other record type (or maybe none). If this happens, just fail,
1041 -- otherwise we get crashes later (Trac #8570), and similar:
1042 -- f (R { foo = (a,b) }) = a+b
1043 -- If foo isn't one of R's fields, we don't want to crash when
1044 -- typechecking the "a+b".
1045 [] -> failWith (badFieldCon con_like field_lbl)
1046
1047 -- The normal case, when the field comes from the right constructor
1048 (pat_ty : extras) ->
1049 ASSERT( null extras )
1050 do { sel_id <- tcLookupField field_lbl
1051 ; return (sel_id, pat_ty) }
1052
1053 field_tys :: [(FieldLabel, TcType)]
1054 field_tys = case con_like of
1055 RealDataCon data_con -> zip (dataConFieldLabels data_con) arg_tys
1056 -- Don't use zipEqual! If the constructor isn't really a record, then
1057 -- dataConFieldLabels will be empty (and each field in the pattern
1058 -- will generate an error below).
1059 PatSynCon{} -> []
1060
1061 conLikeArity :: ConLike -> Arity
1062 conLikeArity (RealDataCon data_con) = dataConSourceArity data_con
1063 conLikeArity (PatSynCon pat_syn) = patSynArity pat_syn
1064
1065 tcConArg :: Checker (LPat Name, TcSigmaType) (LPat Id)
1066 tcConArg (arg_pat, arg_ty) penv thing_inside
1067 = tc_lpat arg_pat arg_ty penv thing_inside
1068
1069 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
1070 -- Instantiate the "stupid theta" of the data con, and throw
1071 -- the constraints into the constraint set
1072 addDataConStupidTheta data_con inst_tys
1073 | null stupid_theta = return ()
1074 | otherwise = instStupidTheta origin inst_theta
1075 where
1076 origin = OccurrenceOf (dataConName data_con)
1077 -- The origin should always report "occurrence of C"
1078 -- even when C occurs in a pattern
1079 stupid_theta = dataConStupidTheta data_con
1080 tenv = mkTopTvSubst (dataConUnivTyVars data_con `zip` inst_tys)
1081 -- NB: inst_tys can be longer than the univ tyvars
1082 -- because the constructor might have existentials
1083 inst_theta = substTheta tenv stupid_theta
1084
1085 {-
1086 Note [Arrows and patterns]
1087 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1088 (Oct 07) Arrow noation has the odd property that it involves
1089 "holes in the scope". For example:
1090 expr :: Arrow a => a () Int
1091 expr = proc (y,z) -> do
1092 x <- term -< y
1093 expr' -< x
1094
1095 Here the 'proc (y,z)' binding scopes over the arrow tails but not the
1096 arrow body (e.g 'term'). As things stand (bogusly) all the
1097 constraints from the proc body are gathered together, so constraints
1098 from 'term' will be seen by the tcPat for (y,z). But we must *not*
1099 bind constraints from 'term' here, because the desugarer will not make
1100 these bindings scope over 'term'.
1101
1102 The Right Thing is not to confuse these constraints together. But for
1103 now the Easy Thing is to ensure that we do not have existential or
1104 GADT constraints in a 'proc', and to short-cut the constraint
1105 simplification for such vanilla patterns so that it binds no
1106 constraints. Hence the 'fast path' in tcConPat; but it's also a good
1107 plan for ordinary vanilla patterns to bypass the constraint
1108 simplification step.
1109
1110 ************************************************************************
1111 * *
1112 Note [Pattern coercions]
1113 * *
1114 ************************************************************************
1115
1116 In principle, these program would be reasonable:
1117
1118 f :: (forall a. a->a) -> Int
1119 f (x :: Int->Int) = x 3
1120
1121 g :: (forall a. [a]) -> Bool
1122 g [] = True
1123
1124 In both cases, the function type signature restricts what arguments can be passed
1125 in a call (to polymorphic ones). The pattern type signature then instantiates this
1126 type. For example, in the first case, (forall a. a->a) <= Int -> Int, and we
1127 generate the translated term
1128 f = \x' :: (forall a. a->a). let x = x' Int in x 3
1129
1130 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
1131 And it requires a significant amount of code to implement, because we need to decorate
1132 the translated pattern with coercion functions (generated from the subsumption check
1133 by tcSub).
1134
1135 So for now I'm just insisting on type *equality* in patterns. No subsumption.
1136
1137 Old notes about desugaring, at a time when pattern coercions were handled:
1138
1139 A SigPat is a type coercion and must be handled one at at time. We can't
1140 combine them unless the type of the pattern inside is identical, and we don't
1141 bother to check for that. For example:
1142
1143 data T = T1 Int | T2 Bool
1144 f :: (forall a. a -> a) -> T -> t
1145 f (g::Int->Int) (T1 i) = T1 (g i)
1146 f (g::Bool->Bool) (T2 b) = T2 (g b)
1147
1148 We desugar this as follows:
1149
1150 f = \ g::(forall a. a->a) t::T ->
1151 let gi = g Int
1152 in case t of { T1 i -> T1 (gi i)
1153 other ->
1154 let gb = g Bool
1155 in case t of { T2 b -> T2 (gb b)
1156 other -> fail }}
1157
1158 Note that we do not treat the first column of patterns as a
1159 column of variables, because the coerced variables (gi, gb)
1160 would be of different types. So we get rather grotty code.
1161 But I don't think this is a common case, and if it was we could
1162 doubtless improve it.
1163
1164 Meanwhile, the strategy is:
1165 * treat each SigPat coercion (always non-identity coercions)
1166 as a separate block
1167 * deal with the stuff inside, and then wrap a binding round
1168 the result to bind the new variable (gi, gb, etc)
1169
1170
1171 ************************************************************************
1172 * *
1173 \subsection{Errors and contexts}
1174 * *
1175 ************************************************************************
1176 -}
1177
1178 maybeWrapPatCtxt :: Pat Name -> (TcM a -> TcM b) -> TcM a -> TcM b
1179 -- Not all patterns are worth pushing a context
1180 maybeWrapPatCtxt pat tcm thing_inside
1181 | not (worth_wrapping pat) = tcm thing_inside
1182 | otherwise = addErrCtxt msg $ tcm $ popErrCtxt thing_inside
1183 -- Remember to pop before doing thing_inside
1184 where
1185 worth_wrapping (VarPat {}) = False
1186 worth_wrapping (ParPat {}) = False
1187 worth_wrapping (AsPat {}) = False
1188 worth_wrapping _ = True
1189 msg = hang (ptext (sLit "In the pattern:")) 2 (ppr pat)
1190
1191 -----------------------------------------------
1192 checkExistentials :: [TyVar] -> PatEnv -> TcM ()
1193 -- See Note [Arrows and patterns]
1194 checkExistentials [] _ = return ()
1195 checkExistentials _ (PE { pe_ctxt = LetPat {}}) = failWithTc existentialLetPat
1196 checkExistentials _ (PE { pe_ctxt = LamPat ProcExpr }) = failWithTc existentialProcPat
1197 checkExistentials _ (PE { pe_lazy = True }) = failWithTc existentialLazyPat
1198 checkExistentials _ _ = return ()
1199
1200 existentialLazyPat :: SDoc
1201 existentialLazyPat
1202 = hang (ptext (sLit "An existential or GADT data constructor cannot be used"))
1203 2 (ptext (sLit "inside a lazy (~) pattern"))
1204
1205 existentialProcPat :: SDoc
1206 existentialProcPat
1207 = ptext (sLit "Proc patterns cannot use existential or GADT data constructors")
1208
1209 existentialLetPat :: SDoc
1210 existentialLetPat
1211 = vcat [text "My brain just exploded",
1212 text "I can't handle pattern bindings for existential or GADT data constructors.",
1213 text "Instead, use a case-expression, or do-notation, to unpack the constructor."]
1214
1215 badFieldCon :: ConLike -> Name -> SDoc
1216 badFieldCon con field
1217 = hsep [ptext (sLit "Constructor") <+> quotes (ppr con),
1218 ptext (sLit "does not have field"), quotes (ppr field)]
1219
1220 polyPatSig :: TcType -> SDoc
1221 polyPatSig sig_ty
1222 = hang (ptext (sLit "Illegal polymorphic type signature in pattern:"))
1223 2 (ppr sig_ty)
1224
1225 lazyUnliftedPatErr :: OutputableBndr name => Pat name -> TcM ()
1226 lazyUnliftedPatErr pat
1227 = failWithTc $
1228 hang (ptext (sLit "A lazy (~) pattern cannot contain unlifted types:"))
1229 2 (ppr pat)