2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 TcPat: Typechecking patterns
9 module TcPat ( tcLetPat, TcSigFun, TcSigInfo(..)
10 , tcPat, tcPats, newLetBndr
11 , addDataConStupidTheta, badFieldCon, polyPatSig ) where
13 #include "HsVersions.h"
15 import {-# SOURCE #-} TcExpr( tcSyntaxOp, tcInferRho)
34 import VarSet ( emptyVarSet )
36 import BasicTypes hiding (SuccessFlag(..))
47 %************************************************************************
51 %************************************************************************
54 tcLetPat :: (Name -> Maybe TcSigInfo)
55 -> Bool -- True <=> monomorphic
56 -> LPat Name -> TcSigmaType
59 tcLetPat sig_fn is_mono pat pat_ty thing_inside
60 = tc_lpat pat pat_ty penv thing_inside
62 penv = PE { pe_res_tvs = emptyVarSet, pe_lazy = True
63 , pe_ctxt = LetPat sig_fn is_mono }
66 tcPats :: HsMatchContext Name
67 -> [LPat Name] -- Patterns,
68 -> [TcSigmaType] -- and their types
69 -> TcRhoType -- Result type,
70 -> TcM a -- and the checker for the body
71 -> TcM ([LPat TcId], a)
73 -- This is the externally-callable wrapper function
74 -- Typecheck the patterns, extend the environment to bind the variables,
75 -- do the thing inside, use any existentially-bound dictionaries to
76 -- discharge parts of the returning LIE, and deal with pattern type
79 -- 1. Initialise the PatState
80 -- 2. Check the patterns
82 -- 4. Check that no existentials escape
84 tcPats ctxt pats pat_tys res_ty thing_inside
85 = tc_lpats penv pats pat_tys thing_inside
87 penv = PE { pe_res_tvs = tyVarsOfTypes (res_ty : pat_tys)
89 , pe_ctxt = LamPat ctxt }
91 tcPat :: HsMatchContext Name
92 -> LPat Name -> TcSigmaType
93 -> TcRhoType -- Result type
94 -> TcM a -- Checker for body, given
97 tcPat ctxt pat pat_ty res_ty thing_inside
98 = tc_lpat pat pat_ty penv thing_inside
100 penv = PE { pe_res_tvs = tyVarsOfTypes [res_ty, pat_ty]
102 , pe_ctxt = LamPat ctxt }
107 = PE { pe_res_tvs :: TcTyVarSet
108 -- For existential escape check; see Note [Existential check]
109 -- Nothing <=> inside a "~"
110 -- Just tvs <=> unification tvs free in the result
111 -- (which should be made untouchable in
112 -- any existentials we encounter in the pattern)
114 , pe_lazy :: Bool -- True <=> lazy context, so no existentials allowed
115 , pe_ctxt :: PatCtxt -- Context in which the whole pattern appears
119 = LamPat -- Used for lambdas, case etc
120 (HsMatchContext Name)
122 | LetPat -- Used only for let(rec) bindings
123 -- See Note [Let binders]
124 TcSigFun -- Tells type sig if any
125 Bool -- True <=> no generalisation of this let
127 makeLazy :: PatEnv -> PatEnv
128 makeLazy penv = penv { pe_lazy = True }
130 patSigCtxt :: PatEnv -> UserTypeCtxt
131 patSigCtxt (PE { pe_ctxt = LetPat {} }) = BindPatSigCtxt
132 patSigCtxt (PE { pe_ctxt = LamPat {} }) = LamPatSigCtxt
135 type TcSigFun = Name -> Maybe TcSigInfo
139 sig_id :: TcId, -- *Polymorphic* binder for this value...
141 sig_scoped :: [Name], -- Scoped type variables
142 -- 1-1 correspondence with a prefix of sig_tvs
143 -- However, may be fewer than sig_tvs;
144 -- see Note [More instantiated than scoped]
145 sig_tvs :: [TcTyVar], -- Instantiated type variables
146 -- See Note [Instantiate sig]
148 sig_theta :: TcThetaType, -- Instantiated theta
150 sig_tau :: TcSigmaType, -- Instantiated tau
151 -- See Note [sig_tau may be polymorphic]
153 sig_loc :: SrcSpan -- The location of the signature
156 instance Outputable TcSigInfo where
157 ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
158 = ppr id <+> ptext (sLit "::") <+> ppr tyvars <+> pprThetaArrow theta <+> ppr tau
161 Note [sig_tau may be polymorphic]
162 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
163 Note that "sig_tau" might actually be a polymorphic type,
164 if the original function had a signature like
165 forall a. Eq a => forall b. Ord b => ....
166 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
167 It happens, too! See Note [Polymorphic methods] in TcClassDcl.
175 ...more notes to add here..
178 Note [Existential check]
179 ~~~~~~~~~~~~~~~~~~~~~~~~
180 Lazy patterns can't bind existentials. They arise in two ways:
181 * Let bindings let { C a b = e } in b
182 * Twiddle patterns f ~(C a b) = e
183 The pe_res_tvs field of PatEnv says whether we are inside a lazy
184 pattern (perhaps deeply)
186 If we aren't inside a lazy pattern then we can bind existentials,
187 but we need to be careful about "extra" tyvars. Consider
188 (\C x -> d) : pat_ty -> res_ty
189 When looking for existential escape we must check that the existential
190 bound by C don't unify with the free variables of pat_ty, OR res_ty
191 (or of course the environment). Hence we need to keep track of the
195 %************************************************************************
199 %************************************************************************
202 tcPatBndr :: PatEnv -> Name -> TcSigmaType -> TcM (CoercionI, TcId)
203 -- (coi, xp) = tcPatBndr penv x pat_ty
204 -- Then coi : pat_ty ~ typeof(xp)
206 tcPatBndr (PE { pe_ctxt = LetPat lookup_sig no_gen}) bndr_name pat_ty
207 | Just sig <- lookup_sig bndr_name
208 = do { bndr_id <- if no_gen then return (sig_id sig)
209 else do { mono_name <- newLocalName bndr_name
210 ; return (Id.mkLocalId mono_name (sig_tau sig)) }
211 ; coi <- unifyPatType (idType bndr_id) pat_ty
212 ; return (coi, bndr_id) }
215 = do { bndr_id <- newLetBndr no_gen bndr_name pat_ty
216 ; return (IdCo pat_ty, bndr_id) }
218 tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty
219 = do { bndr <- mkLocalBinder bndr_name pat_ty
220 ; return (IdCo pat_ty, bndr) }
222 newLetBndr :: Bool -> Name -> TcType -> TcM TcId
223 -- In the polymorphic case (no_gen = False), generate a "monomorphic version"
224 -- of the Id; the original name will be bound to the polymorphic version
226 -- In the monomorphic case there is no AbsBinds, and we use the original
228 newLetBndr no_gen name ty
229 | no_gen = mkLocalBinder name ty
230 | otherwise = do { mono_name <- newLocalName name
231 ; mkLocalBinder mono_name ty }
234 mkLocalBinder :: Name -> TcType -> TcM TcId
235 mkLocalBinder name ty
236 = do { checkUnboxedTuple ty $
237 ptext (sLit "The variable") <+> quotes (ppr name)
238 ; return (Id.mkLocalId name ty) }
240 checkUnboxedTuple :: TcType -> SDoc -> TcM ()
241 -- Check for an unboxed tuple type
242 -- f = (# True, False #)
243 -- Zonk first just in case it's hidden inside a meta type variable
244 -- (This shows up as a (more obscure) kind error
245 -- in the 'otherwise' case of tcMonoBinds.)
246 checkUnboxedTuple ty what
247 = do { zonked_ty <- zonkTcTypeCarefully ty
248 ; checkTc (not (isUnboxedTupleType zonked_ty))
249 (unboxedTupleErr what zonked_ty) }
252 {- Only needed if we re-add Method constraints
253 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, TcEvBinds)
254 bindInstsOfPatId id thing_inside
255 | not (isOverloadedTy (idType id))
256 = do { res <- thing_inside; return (res, emptyTcEvBinds) }
258 = do { (res, lie) <- getConstraints thing_inside
259 ; binds <- bindLocalMethods lie [id]
260 ; return (res, binds) }
264 Note [Polymorphism and pattern bindings]
265 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
266 When is_mono holds we are not generalising
267 But the signature can still be polymoprhic!
268 data T = MkT (forall a. a->a)
271 So the no_gen flag decides whether the pattern-bound variables should
272 have exactly the type in the type signature (when not generalising) or
273 the instantiated version (when generalising)
275 %************************************************************************
277 The main worker functions
279 %************************************************************************
283 tcPat takes a "thing inside" over which the pattern scopes. This is partly
284 so that tcPat can extend the environment for the thing_inside, but also
285 so that constraints arising in the thing_inside can be discharged by the
288 This does not work so well for the ErrCtxt carried by the monad: we don't
289 want the error-context for the pattern to scope over the RHS.
290 Hence the getErrCtxt/setErrCtxt stuff in tcMultiple
294 type Checker inp out = forall r.
300 tcMultiple :: Checker inp out -> Checker [inp] [out]
301 tcMultiple tc_pat args penv thing_inside
302 = do { err_ctxt <- getErrCtxt
304 = do { res <- thing_inside
308 = do { (p', (ps', res))
310 setErrCtxt err_ctxt $
312 -- setErrCtxt: restore context before doing the next pattern
313 -- See note [Nesting] above
315 ; return (p':ps', res) }
324 -> TcM (LPat TcId, a)
325 tc_lpat (L span pat) pat_ty penv thing_inside
327 maybeAddErrCtxt (patCtxt pat) $
328 do { (pat', res) <- tc_pat penv pat pat_ty thing_inside
329 ; return (L span pat', res) }
332 -> [LPat Name] -> [TcSigmaType]
334 -> TcM ([LPat TcId], a)
335 tc_lpats penv pats tys thing_inside
336 = tcMultiple (\(p,t) -> tc_lpat p t)
337 (zipEqual "tc_lpats" pats tys)
343 -> TcSigmaType -- Fully refined result type
344 -> TcM a -- Thing inside
345 -> TcM (Pat TcId, -- Translated pattern
346 a) -- Result of thing inside
348 tc_pat penv (VarPat name) pat_ty thing_inside
349 = do { (coi, id) <- tcPatBndr penv name pat_ty
350 ; res <- tcExtendIdEnv1 name id thing_inside
351 ; return (mkHsWrapPatCoI coi (VarPat id) pat_ty, res) }
353 {- Need this if we re-add Method constraints
354 ; (res, binds) <- bindInstsOfPatId id $
355 tcExtendIdEnv1 name id $
356 (traceTc (text "binding" <+> ppr name <+> ppr (idType id))
358 ; let pat' | isEmptyTcEvBinds binds = VarPat id
359 | otherwise = VarPatOut id binds
360 ; return (mkHsWrapPatCoI coi pat' pat_ty, res) }
363 tc_pat penv (ParPat pat) pat_ty thing_inside
364 = do { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
365 ; return (ParPat pat', res) }
367 tc_pat penv (BangPat pat) pat_ty thing_inside
368 = do { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
369 ; return (BangPat pat', res) }
371 tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside
372 = do { (pat', (res, pat_ct))
373 <- tc_lpat pat pat_ty (makeLazy penv) $
374 getConstraints thing_inside
375 -- Ignore refined penv', revert to penv
377 ; emitConstraints pat_ct
378 -- getConstraints/extendConstraintss: see Note [Hopping the LIE in lazy patterns]
380 -- Check there are no unlifted types under the lazy pattern
381 ; when (any (isUnLiftedType . idType) $ collectPatBinders pat') $
382 lazyUnliftedPatErr lpat
384 -- Check that the expected pattern type is itself lifted
385 ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
386 ; _ <- unifyType pat_ty pat_ty'
388 ; return (LazyPat pat', res) }
390 tc_pat _ p@(QuasiQuotePat _) _ _
391 = pprPanic "Should never see QuasiQuotePat in type checker" (ppr p)
393 tc_pat _ (WildPat _) pat_ty thing_inside
394 = do { checkUnboxedTuple pat_ty $
395 ptext (sLit "A wild-card pattern")
396 ; res <- thing_inside
397 ; return (WildPat pat_ty, res) }
399 tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
400 = do { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
401 ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
402 tc_lpat pat (idType bndr_id) penv thing_inside
403 -- NB: if we do inference on:
404 -- \ (y@(x::forall a. a->a)) = e
405 -- we'll fail. The as-pattern infers a monotype for 'y', which then
406 -- fails to unify with the polymorphic type for 'x'. This could
407 -- perhaps be fixed, but only with a bit more work.
409 -- If you fix it, don't forget the bindInstsOfPatIds!
410 ; return (mkHsWrapPatCoI coi (AsPat (L nm_loc bndr_id) pat') pat_ty, res) }
412 tc_pat penv vpat@(ViewPat expr pat _) overall_pat_ty thing_inside
413 = do { checkUnboxedTuple overall_pat_ty $
414 ptext (sLit "The view pattern") <+> ppr vpat
416 -- Morally, expr must have type `forall a1...aN. OPT' -> B`
417 -- where overall_pat_ty is an instance of OPT'.
418 -- Here, we infer a rho type for it,
419 -- which replaces the leading foralls and constraints
420 -- with fresh unification variables.
421 ; (expr',expr'_inferred) <- tcInferRho expr
423 -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
424 -- NOTE: this forces pat_ty to be a monotype (because we use a unification
425 -- variable to find it). this means that in an example like
426 -- (view -> f) where view :: _ -> forall b. b
427 -- we will only be able to use view at one instantation in the
429 ; (expr_coi, pat_ty) <- tcInfer $ \ pat_ty ->
430 unifyPatType expr'_inferred (mkFunTy overall_pat_ty pat_ty)
432 -- pattern must have pat_ty
433 ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside
435 ; return (ViewPat (mkLHsWrapCoI expr_coi expr') pat' overall_pat_ty, res) }
437 -- Type signatures in patterns
438 -- See Note [Pattern coercions] below
439 tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
440 = do { (inner_ty, tv_binds, wrap) <- tcPatSig (patSigCtxt penv) sig_ty pat_ty
441 ; (pat', res) <- tcExtendTyVarEnv2 tv_binds $
442 tc_lpat pat inner_ty penv thing_inside
444 ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
446 tc_pat _ pat@(TypePat _) _ _
447 = failWithTc (badTypePat pat)
449 ------------------------
450 -- Lists, tuples, arrays
451 tc_pat penv (ListPat pats _) pat_ty thing_inside
452 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy pat_ty
453 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
454 pats penv thing_inside
455 ; return (mkHsWrapPat coi (ListPat pats' elt_ty) pat_ty, res)
458 tc_pat penv (PArrPat pats _) pat_ty thing_inside
459 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTy pat_ty
460 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
461 pats penv thing_inside
462 ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
465 tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
466 = do { let tc = tupleTyCon boxity (length pats)
467 ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc) pat_ty
468 ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
470 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
471 -- so that we can experiment with lazy tuple-matching.
472 -- This is a pretty odd place to make the switch, but
473 -- it was easy to do.
474 ; let pat_ty' = mkTyConApp tc arg_tys
475 -- pat_ty /= pat_ty iff coi /= IdCo
476 unmangled_result = TuplePat pats' boxity pat_ty'
477 possibly_mangled_result
478 | opt_IrrefutableTuples &&
479 isBoxed boxity = LazyPat (noLoc unmangled_result)
480 | otherwise = unmangled_result
482 ; ASSERT( length arg_tys == length pats ) -- Syntactically enforced
483 return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
486 ------------------------
488 tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
489 = tcConPat penv con pat_ty arg_pats thing_inside
491 ------------------------
493 tc_pat _ (LitPat simple_lit) pat_ty thing_inside
494 = do { let lit_ty = hsLitType simple_lit
495 ; coi <- unifyPatType lit_ty pat_ty
496 -- coi is of kind: pat_ty ~ lit_ty
497 ; res <- thing_inside
498 ; return ( mkHsWrapPatCoI coi (LitPat simple_lit) pat_ty
501 ------------------------
502 -- Overloaded patterns: n, and n+k
503 tc_pat _ (NPat over_lit mb_neg eq) pat_ty thing_inside
504 = do { let orig = LiteralOrigin over_lit
505 ; lit' <- newOverloadedLit orig over_lit pat_ty
506 ; eq' <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
507 ; mb_neg' <- case mb_neg of
508 Nothing -> return Nothing -- Positive literal
509 Just neg -> -- Negative literal
510 -- The 'negate' is re-mappable syntax
511 do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
512 ; return (Just neg') }
513 ; res <- thing_inside
514 ; return (NPat lit' mb_neg' eq', res) }
516 tc_pat penv (NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
517 = do { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
518 ; let pat_ty' = idType bndr_id
519 orig = LiteralOrigin lit
520 ; lit' <- newOverloadedLit orig lit pat_ty'
522 -- The '>=' and '-' parts are re-mappable syntax
523 ; ge' <- tcSyntaxOp orig ge (mkFunTys [pat_ty', pat_ty'] boolTy)
524 ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
525 ; let pat' = NPlusKPat (L nm_loc bndr_id) lit' ge' minus'
527 -- The Report says that n+k patterns must be in Integral
528 -- We may not want this when using re-mappable syntax, though (ToDo?)
529 ; icls <- tcLookupClass integralClassName
530 ; instStupidTheta orig [mkClassPred icls [pat_ty']]
532 ; res <- tcExtendIdEnv1 name bndr_id thing_inside
533 ; return (mkHsWrapPatCoI coi pat' pat_ty, res) }
535 tc_pat _ _other_pat _ _ = panic "tc_pat" -- ConPatOut, SigPatOut, VarPatOut
538 unifyPatType :: TcType -> TcType -> TcM CoercionI
539 -- In patterns we want a coercion from the
540 -- context type (expected) to the actual pattern type
541 -- But we don't want to reverse the args to unifyType because
542 -- that controls the actual/expected stuff in error messages
543 unifyPatType actual_ty expected_ty
544 = do { coi <- unifyType actual_ty expected_ty
545 ; return (mkSymCoI coi) }
548 Note [Hopping the LIE in lazy patterns]
549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
550 In a lazy pattern, we must *not* discharge constraints from the RHS
551 from dictionaries bound in the pattern. E.g.
553 We can't discharge the Num constraint from dictionaries bound by
556 So we have to make the constraints from thing_inside "hop around"
557 the pattern. Hence the getConstraints and emitConstraints.
559 The same thing ensures that equality constraints in a lazy match
560 are not made available in the RHS of the match. For example
561 data T a where { T1 :: Int -> T Int; ... }
564 It's obviously not sound to refine a to Int in the right
565 hand side, because the arugment might not match T1 at all!
567 Finally, a lazy pattern should not bind any existential type variables
568 because they won't be in scope when we do the desugaring
571 %************************************************************************
573 Most of the work for constructors is here
574 (the rest is in the ConPatIn case of tc_pat)
576 %************************************************************************
578 [Pattern matching indexed data types]
579 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
580 Consider the following declarations:
582 data family Map k :: * -> *
583 data instance Map (a, b) v = MapPair (Map a (Pair b v))
585 and a case expression
587 case x :: Map (Int, c) w of MapPair m -> ...
589 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
590 worker/wrapper types for MapPair are
592 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
593 $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
595 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
596 :R123Map, which means the straight use of boxySplitTyConApp would give a type
597 error. Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
598 boxySplitTyConApp with the family tycon Map instead, which gives us the family
599 type list {(Int, c), w}. To get the correct split for :R123Map, we need to
600 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
601 (provided by tyConFamInst_maybe together with the family tycon). This
602 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
603 the split arguments for the representation tycon :R123Map as {Int, c, w}
605 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
607 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
609 moving between representation and family type into account. To produce type
610 correct Core, this coercion needs to be used to case the type of the scrutinee
611 from the family to the representation type. This is achieved by
612 unwrapFamInstScrutinee using a CoPat around the result pattern.
614 Now it might appear seem as if we could have used the previous GADT type
615 refinement infrastructure of refineAlt and friends instead of the explicit
616 unification and CoPat generation. However, that would be wrong. Why? The
617 whole point of GADT refinement is that the refinement is local to the case
618 alternative. In contrast, the substitution generated by the unification of
619 the family type list and instance types needs to be propagated to the outside.
620 Imagine that in the above example, the type of the scrutinee would have been
621 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
622 substitution [x -> (a, b), v -> w]. In contrast to GADT matching, the
623 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
624 alternatives of the case expression, whereas in the GADT case it might vary
625 between alternatives.
627 RIP GADT refinement: refinements have been replaced by the use of explicit
628 equality constraints that are used in conjunction with implication constraints
629 to express the local scope of GADT refinements.
633 -- MkT :: forall a b c. (a~[b]) => b -> c -> T a
634 -- with scrutinee of type (T ty)
636 tcConPat :: PatEnv -> Located Name
637 -> TcRhoType -- Type of the pattern
638 -> HsConPatDetails Name -> TcM a
640 tcConPat penv (L con_span con_name) pat_ty arg_pats thing_inside
641 = do { data_con <- tcLookupDataCon con_name
642 ; let tycon = dataConTyCon data_con
643 -- For data families this is the representation tycon
644 (univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _)
645 = dataConFullSig data_con
647 -- Instantiate the constructor type variables [a->ty]
648 -- This may involve doing a family-instance coercion,
649 -- and building a wrapper
650 ; (wrap, ctxt_res_tys) <- matchExpectedPatTy (matchExpectedConTy tycon) pat_ty
652 -- Add the stupid theta
653 ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
655 ; checkExistentials ex_tvs penv
656 ; let skol_info = case pe_ctxt penv of
657 LamPat mc -> PatSkol data_con mc
658 LetPat {} -> UnkSkol -- Doesn't matter
659 ; ex_tvs' <- tcInstSkolTyVars skol_info ex_tvs
660 -- Get location from monad, not from ex_tvs
662 ; let pat_ty' = mkTyConApp tycon ctxt_res_tys
663 -- pat_ty' is type of the actual constructor application
664 -- pat_ty' /= pat_ty iff coi /= IdCo
666 tenv = zipTopTvSubst (univ_tvs ++ ex_tvs)
667 (ctxt_res_tys ++ mkTyVarTys ex_tvs')
668 arg_tys' = substTys tenv arg_tys
669 full_theta = eq_theta ++ dict_theta
671 ; if null ex_tvs && null eq_spec && null full_theta
672 then do { -- The common case; no class bindings etc
673 -- (see Note [Arrows and patterns])
674 (arg_pats', res) <- tcConArgs data_con arg_tys'
675 arg_pats penv thing_inside
676 ; let res_pat = ConPatOut { pat_con = L con_span data_con,
677 pat_tvs = [], pat_dicts = [],
678 pat_binds = emptyTcEvBinds,
679 pat_args = arg_pats',
682 ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
684 else do -- The general case, with existential,
685 -- and local equality constraints
686 { let eq_preds = [mkEqPred (mkTyVarTy tv, ty) | (tv, ty) <- eq_spec]
687 theta' = substTheta tenv (eq_preds ++ full_theta)
688 -- order is *important* as we generate the list of
689 -- dictionary binders from theta'
690 no_equalities = not (any isEqPred theta')
692 ; gadts_on <- doptM Opt_GADTs
693 ; checkTc (no_equalities || gadts_on)
694 (ptext (sLit "A pattern match on a GADT requires -XGADTs"))
695 -- Trac #2905 decided that a *pattern-match* of a GADT
696 -- should require the GADT language flag
698 ; given <- newEvVars theta'
699 ; let free_tvs = pe_res_tvs penv
700 -- Since we have done checkExistentials,
701 -- pe_res_tvs can only be Just at this point
703 -- Nor do we need pat_ty, because we've put all the
704 -- unification variables in right at the start when
705 -- initialising the PatEnv; and the pattern itself
706 -- only adds skolems.
708 ; (ev_binds, (arg_pats', res))
709 <- checkConstraints skol_info free_tvs ex_tvs' given $
710 tcConArgs data_con arg_tys' arg_pats penv thing_inside
712 ; let res_pat = ConPatOut { pat_con = L con_span data_con,
715 pat_binds = ev_binds,
716 pat_args = arg_pats',
718 ; return (mkHsWrapPat wrap res_pat pat_ty, res)
721 ----------------------------
722 matchExpectedPatTy :: (TcRhoType -> TcM (CoercionI, a))
723 -> TcRhoType -> TcM (HsWrapper, a)
724 -- See Note [Matching polytyped patterns]
725 -- Returns a wrapper : pat_ty ~ inner_ty
726 matchExpectedPatTy inner_match pat_ty
727 | null tvs && null theta
728 = do { (coi, res) <- inner_match pat_ty
729 ; return (coiToHsWrapper (mkSymCoI coi), res) }
730 -- The Sym is because the inner_match returns a coercion
731 -- that is the other way round to matchExpectedPatTy
734 = do { (_, tys, subst) <- tcInstTyVars tvs
735 ; wrap1 <- instCall PatOrigin tys (substTheta subst theta)
736 ; (wrap2, arg_tys) <- matchExpectedPatTy inner_match (substTy subst tau)
737 ; return (wrap2 <.> wrap1 , arg_tys) }
739 (tvs, theta, tau) = tcSplitSigmaTy pat_ty
741 ----------------------------
742 matchExpectedConTy :: TyCon -- The TyCon that this data
743 -- constructor actually returns
744 -> TcRhoType -- The type of the pattern
745 -> TcM (CoercionI, [TcSigmaType])
746 -- See Note [Matching constructor patterns]
747 -- Returns a coercion : T ty1 ... tyn ~ pat_ty
748 -- This is the same way round as matchExpectedListTy etc
749 -- but the other way round to matchExpectedPatTy
750 matchExpectedConTy data_tc pat_ty
751 | Just (fam_tc, fam_args, co_tc) <- tyConFamInstSig_maybe data_tc
752 -- Comments refer to Note [Matching constructor patterns]
753 -- co_tc :: forall a. T [a] ~ T7 a
754 = do { (_, tys, subst) <- tcInstTyVars (tyConTyVars data_tc)
757 ; coi1 <- unifyType (mkTyConApp fam_tc (substTys subst fam_args)) pat_ty
758 -- coi1 : T (ty1,ty2) ~ pat_ty
760 ; let coi2 = ACo (mkTyConApp co_tc tys)
761 -- coi2 : T (ty1,ty2) ~ T7 ty1 ty2
763 ; return (mkTransCoI (mkSymCoI coi2) coi1, tys) }
766 = matchExpectedTyConApp data_tc pat_ty
767 -- coi : T tys ~ pat_ty
771 Note [Matching constructor patterns]
772 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
773 Suppose (coi, tys) = matchExpectedConType data_tc pat_ty
775 * In the simple case, pat_ty = tc tys
777 * If pat_ty is a polytype, we want to instantiate it
778 This is like part of a subsumption check. Eg
779 f :: (forall a. [a]) -> blah
782 * In a type family case, suppose we have
784 data instance T (p,q) = A p | B q
785 Then we'll have internally generated
786 data T7 p q = A p | B q
787 axiom coT7 p q :: T (p,q) ~ T7 p q
789 So if pat_ty = T (ty1,ty2), we return (coi, [ty1,ty2]) such that
790 coi = coi2 . coi1 : T7 t ~ pat_ty
791 coi1 : T (ty1,ty2) ~ pat_ty
792 coi2 : T7 ty1 ty2 ~ T (ty1,ty2)
794 For families we do all this matching here, not in the unifier,
795 because we never want a whisper of the data_tycon to appear in
796 error messages; it's a purely internal thing
799 tcConArgs :: DataCon -> [TcSigmaType]
800 -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
802 tcConArgs data_con arg_tys (PrefixCon arg_pats) penv thing_inside
803 = do { checkTc (con_arity == no_of_args) -- Check correct arity
804 (arityErr "Constructor" data_con con_arity no_of_args)
805 ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
806 ; (arg_pats', res) <- tcMultiple tcConArg pats_w_tys
808 ; return (PrefixCon arg_pats', res) }
810 con_arity = dataConSourceArity data_con
811 no_of_args = length arg_pats
813 tcConArgs data_con arg_tys (InfixCon p1 p2) penv thing_inside
814 = do { checkTc (con_arity == 2) -- Check correct arity
815 (arityErr "Constructor" data_con con_arity 2)
816 ; let [arg_ty1,arg_ty2] = arg_tys -- This can't fail after the arity check
817 ; ([p1',p2'], res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
819 ; return (InfixCon p1' p2', res) }
821 con_arity = dataConSourceArity data_con
823 tcConArgs data_con arg_tys (RecCon (HsRecFields rpats dd)) penv thing_inside
824 = do { (rpats', res) <- tcMultiple tc_field rpats penv thing_inside
825 ; return (RecCon (HsRecFields rpats' dd), res) }
827 tc_field :: Checker (HsRecField FieldLabel (LPat Name)) (HsRecField TcId (LPat TcId))
828 tc_field (HsRecField field_lbl pat pun) penv thing_inside
829 = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
830 ; (pat', res) <- tcConArg (pat, pat_ty) penv thing_inside
831 ; return (HsRecField sel_id pat' pun, res) }
833 find_field_ty :: FieldLabel -> TcM (Id, TcType)
834 find_field_ty field_lbl
835 = case [ty | (f,ty) <- field_tys, f == field_lbl] of
837 -- No matching field; chances are this field label comes from some
838 -- other record type (or maybe none). As well as reporting an
839 -- error we still want to typecheck the pattern, principally to
840 -- make sure that all the variables it binds are put into the
841 -- environment, else the type checker crashes later:
842 -- f (R { foo = (a,b) }) = a+b
843 -- If foo isn't one of R's fields, we don't want to crash when
844 -- typechecking the "a+b".
845 [] -> do { addErrTc (badFieldCon data_con field_lbl)
846 ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
847 ; return (error "Bogus selector Id", bogus_ty) }
849 -- The normal case, when the field comes from the right constructor
851 ASSERT( null extras )
852 do { sel_id <- tcLookupField field_lbl
853 ; return (sel_id, pat_ty) }
855 field_tys :: [(FieldLabel, TcType)]
856 field_tys = zip (dataConFieldLabels data_con) arg_tys
857 -- Don't use zipEqual! If the constructor isn't really a record, then
858 -- dataConFieldLabels will be empty (and each field in the pattern
859 -- will generate an error below).
861 tcConArg :: Checker (LPat Name, TcSigmaType) (LPat Id)
862 tcConArg (arg_pat, arg_ty) penv thing_inside
863 = tc_lpat arg_pat arg_ty penv thing_inside
867 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
868 -- Instantiate the "stupid theta" of the data con, and throw
869 -- the constraints into the constraint set
870 addDataConStupidTheta data_con inst_tys
871 | null stupid_theta = return ()
872 | otherwise = instStupidTheta origin inst_theta
874 origin = OccurrenceOf (dataConName data_con)
875 -- The origin should always report "occurrence of C"
876 -- even when C occurs in a pattern
877 stupid_theta = dataConStupidTheta data_con
878 tenv = mkTopTvSubst (dataConUnivTyVars data_con `zip` inst_tys)
879 -- NB: inst_tys can be longer than the univ tyvars
880 -- because the constructor might have existentials
881 inst_theta = substTheta tenv stupid_theta
884 Note [Arrows and patterns]
885 ~~~~~~~~~~~~~~~~~~~~~~~~~~
886 (Oct 07) Arrow noation has the odd property that it involves
887 "holes in the scope". For example:
888 expr :: Arrow a => a () Int
889 expr = proc (y,z) -> do
893 Here the 'proc (y,z)' binding scopes over the arrow tails but not the
894 arrow body (e.g 'term'). As things stand (bogusly) all the
895 constraints from the proc body are gathered together, so constraints
896 from 'term' will be seen by the tcPat for (y,z). But we must *not*
897 bind constraints from 'term' here, becuase the desugarer will not make
898 these bindings scope over 'term'.
900 The Right Thing is not to confuse these constraints together. But for
901 now the Easy Thing is to ensure that we do not have existential or
902 GADT constraints in a 'proc', and to short-cut the constraint
903 simplification for such vanilla patterns so that it binds no
904 constraints. Hence the 'fast path' in tcConPat; but it's also a good
905 plan for ordinary vanilla patterns to bypass the constraint
908 %************************************************************************
910 Note [Pattern coercions]
912 %************************************************************************
914 In principle, these program would be reasonable:
916 f :: (forall a. a->a) -> Int
917 f (x :: Int->Int) = x 3
919 g :: (forall a. [a]) -> Bool
922 In both cases, the function type signature restricts what arguments can be passed
923 in a call (to polymorphic ones). The pattern type signature then instantiates this
924 type. For example, in the first case, (forall a. a->a) <= Int -> Int, and we
925 generate the translated term
926 f = \x' :: (forall a. a->a). let x = x' Int in x 3
928 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
929 And it requires a significant amount of code to implement, becuase we need to decorate
930 the translated pattern with coercion functions (generated from the subsumption check
933 So for now I'm just insisting on type *equality* in patterns. No subsumption.
935 Old notes about desugaring, at a time when pattern coercions were handled:
937 A SigPat is a type coercion and must be handled one at at time. We can't
938 combine them unless the type of the pattern inside is identical, and we don't
939 bother to check for that. For example:
941 data T = T1 Int | T2 Bool
942 f :: (forall a. a -> a) -> T -> t
943 f (g::Int->Int) (T1 i) = T1 (g i)
944 f (g::Bool->Bool) (T2 b) = T2 (g b)
946 We desugar this as follows:
948 f = \ g::(forall a. a->a) t::T ->
950 in case t of { T1 i -> T1 (gi i)
953 in case t of { T2 b -> T2 (gb b)
956 Note that we do not treat the first column of patterns as a
957 column of variables, because the coerced variables (gi, gb)
958 would be of different types. So we get rather grotty code.
959 But I don't think this is a common case, and if it was we could
960 doubtless improve it.
962 Meanwhile, the strategy is:
963 * treat each SigPat coercion (always non-identity coercions)
965 * deal with the stuff inside, and then wrap a binding round
966 the result to bind the new variable (gi, gb, etc)
969 %************************************************************************
971 \subsection{Errors and contexts}
973 %************************************************************************
975 {- This was used to improve the error message from
976 an existential escape. Need to think how to do this.
978 sigPatCtxt :: [LPat Var] -> [Var] -> [TcType] -> TcType -> TidyEnv
979 -> TcM (TidyEnv, SDoc)
980 sigPatCtxt pats bound_tvs pat_tys body_ty tidy_env
981 = do { pat_tys' <- mapM zonkTcType pat_tys
982 ; body_ty' <- zonkTcType body_ty
983 ; let (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
984 (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
985 (env3, tidy_body_ty) = tidyOpenType env2 body_ty'
987 sep [ptext (sLit "When checking an existential match that binds"),
988 nest 2 (vcat (zipWith ppr_id show_ids tidy_tys)),
989 ptext (sLit "The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
990 ptext (sLit "The body has type:") <+> ppr tidy_body_ty
993 bound_ids = collectPatsBinders pats
994 show_ids = filter is_interesting bound_ids
995 is_interesting id = any (`elemVarSet` varTypeTyVars id) bound_tvs
997 ppr_id id ty = ppr id <+> dcolon <+> ppr ty
998 -- Don't zonk the types so we get the separate, un-unified versions
1002 patCtxt :: Pat Name -> Maybe Message -- Not all patterns are worth pushing a context
1003 patCtxt (VarPat _) = Nothing
1004 patCtxt (ParPat _) = Nothing
1005 patCtxt (AsPat _ _) = Nothing
1006 patCtxt pat = Just (hang (ptext (sLit "In the pattern:"))
1009 -----------------------------------------------
1010 checkExistentials :: [TyVar] -> PatEnv -> TcM ()
1011 -- See Note [Arrows and patterns]
1012 checkExistentials [] _ = return ()
1013 checkExistentials _ (PE { pe_ctxt = LetPat {}}) = failWithTc existentialLetPat
1014 checkExistentials _ (PE { pe_ctxt = LamPat ProcExpr }) = failWithTc existentialProcPat
1015 checkExistentials _ (PE { pe_lazy = True }) = failWithTc existentialLazyPat
1016 checkExistentials _ _ = return ()
1018 existentialLazyPat :: SDoc
1020 = hang (ptext (sLit "An existential or GADT data constructor cannot be used"))
1021 2 (ptext (sLit "inside a lazy (~) pattern"))
1023 existentialProcPat :: SDoc
1025 = ptext (sLit "Proc patterns cannot use existential or GADT data constructors")
1027 existentialLetPat :: SDoc
1029 = vcat [text "My brain just exploded",
1030 text "I can't handle pattern bindings for existential or GADT data constructors.",
1031 text "Instead, use a case-expression, or do-notation, to unpack the constructor."]
1033 badFieldCon :: DataCon -> Name -> SDoc
1034 badFieldCon con field
1035 = hsep [ptext (sLit "Constructor") <+> quotes (ppr con),
1036 ptext (sLit "does not have field"), quotes (ppr field)]
1038 polyPatSig :: TcType -> SDoc
1040 = hang (ptext (sLit "Illegal polymorphic type signature in pattern:"))
1043 badTypePat :: Pat Name -> SDoc
1044 badTypePat pat = ptext (sLit "Illegal type pattern") <+> ppr pat
1046 lazyUnliftedPatErr :: OutputableBndr name => Pat name -> TcM ()
1047 lazyUnliftedPatErr pat
1049 hang (ptext (sLit "A lazy (~) pattern cannot contain unlifted types:"))
1052 unboxedTupleErr :: SDoc -> Type -> SDoc
1053 unboxedTupleErr what ty
1054 = hang (what <+> ptext (sLit "cannot have an unboxed tuple type:"))