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