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