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