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