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(..), TcPragFun
10 , LetBndrSpec(..), addInlinePrags, warnPrags
11 , tcPat, tcPats, newNoSigLetBndr, newSigLetBndr
12 , addDataConStupidTheta, badFieldCon, polyPatSig ) where
14 #include "HsVersions.h"
16 import {-# SOURCE #-} TcExpr( tcSyntaxOp, tcInferRho)
36 import BasicTypes hiding (SuccessFlag(..))
47 %************************************************************************
51 %************************************************************************
54 tcLetPat :: TcSigFun -> LetBndrSpec
55 -> LPat Name -> TcSigmaType
58 tcLetPat sig_fn no_gen pat pat_ty thing_inside
59 = tc_lpat pat pat_ty penv thing_inside
61 penv = PE { pe_lazy = True
62 , pe_ctxt = LetPat sig_fn no_gen }
65 tcPats :: HsMatchContext Name
66 -> [LPat Name] -- Patterns,
67 -> [TcSigmaType] -- and their types
68 -> TcM a -- and the checker for the body
69 -> TcM ([LPat TcId], a)
71 -- This is the externally-callable wrapper function
72 -- Typecheck the patterns, extend the environment to bind the variables,
73 -- do the thing inside, use any existentially-bound dictionaries to
74 -- discharge parts of the returning LIE, and deal with pattern type
77 -- 1. Initialise the PatState
78 -- 2. Check the patterns
80 -- 4. Check that no existentials escape
82 tcPats ctxt pats pat_tys thing_inside
83 = tc_lpats penv pats pat_tys thing_inside
85 penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt }
87 tcPat :: HsMatchContext Name
88 -> LPat Name -> TcSigmaType
89 -> TcM a -- Checker for body, given
92 tcPat ctxt pat pat_ty thing_inside
93 = tc_lpat pat pat_ty penv thing_inside
95 penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt }
100 = PE { pe_lazy :: Bool -- True <=> lazy context, so no existentials allowed
101 , pe_ctxt :: PatCtxt -- Context in which the whole pattern appears
105 = LamPat -- Used for lambdas, case etc
106 (HsMatchContext Name)
108 | LetPat -- Used only for let(rec) bindings
109 -- See Note [Let binders]
110 TcSigFun -- Tells type sig if any
111 LetBndrSpec -- True <=> no generalisation of this let
114 = LetLclBndr -- The binder is just a local one;
115 -- an AbsBinds will provide the global version
117 | LetGblBndr TcPragFun -- There isn't going to be an AbsBinds;
118 -- here is the inline-pragma information
120 makeLazy :: PatEnv -> PatEnv
121 makeLazy penv = penv { pe_lazy = True }
123 patSigCtxt :: PatEnv -> UserTypeCtxt
124 patSigCtxt (PE { pe_ctxt = LetPat {} }) = BindPatSigCtxt
125 patSigCtxt (PE { pe_ctxt = LamPat {} }) = LamPatSigCtxt
128 type TcPragFun = Name -> [LSig Name]
129 type TcSigFun = Name -> Maybe TcSigInfo
133 sig_id :: TcId, -- *Polymorphic* binder for this value...
135 sig_scoped :: [Name], -- Scoped type variables
136 -- 1-1 correspondence with a prefix of sig_tvs
137 -- However, may be fewer than sig_tvs;
138 -- see Note [More instantiated than scoped]
139 sig_tvs :: [TcTyVar], -- Instantiated type variables
140 -- See Note [Instantiate sig]
142 sig_theta :: TcThetaType, -- Instantiated theta
144 sig_tau :: TcSigmaType, -- Instantiated tau
145 -- See Note [sig_tau may be polymorphic]
147 sig_loc :: SrcSpan -- The location of the signature
150 instance Outputable TcSigInfo where
151 ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
152 = ppr id <+> ptext (sLit "::") <+> ppr tyvars <+> pprThetaArrow theta <+> ppr tau
155 Note [sig_tau may be polymorphic]
156 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
157 Note that "sig_tau" might actually be a polymorphic type,
158 if the original function had a signature like
159 forall a. Eq a => forall b. Ord b => ....
160 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
161 It happens, too! See Note [Polymorphic methods] in TcClassDcl.
169 ...more notes to add here..
172 Note [Existential check]
173 ~~~~~~~~~~~~~~~~~~~~~~~~
174 Lazy patterns can't bind existentials. They arise in two ways:
175 * Let bindings let { C a b = e } in b
176 * Twiddle patterns f ~(C a b) = e
177 The pe_lazy field of PatEnv says whether we are inside a lazy
178 pattern (perhaps deeply)
180 If we aren't inside a lazy pattern then we can bind existentials,
181 but we need to be careful about "extra" tyvars. Consider
182 (\C x -> d) : pat_ty -> res_ty
183 When looking for existential escape we must check that the existential
184 bound by C don't unify with the free variables of pat_ty, OR res_ty
185 (or of course the environment). Hence we need to keep track of the
189 %************************************************************************
193 %************************************************************************
196 tcPatBndr :: PatEnv -> Name -> TcSigmaType -> TcM (CoercionI, TcId)
197 -- (coi, xp) = tcPatBndr penv x pat_ty
198 -- Then coi : pat_ty ~ typeof(xp)
200 tcPatBndr (PE { pe_ctxt = LetPat lookup_sig no_gen}) bndr_name pat_ty
201 | Just sig <- lookup_sig bndr_name
202 = do { bndr_id <- newSigLetBndr no_gen bndr_name sig
203 ; coi <- unifyPatType (idType bndr_id) pat_ty
204 ; return (coi, bndr_id) }
207 = do { bndr_id <- newNoSigLetBndr no_gen bndr_name pat_ty
208 ; return (IdCo pat_ty, bndr_id) }
210 tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty
211 = do { bndr <- mkLocalBinder bndr_name pat_ty
212 ; return (IdCo pat_ty, bndr) }
215 newSigLetBndr :: LetBndrSpec -> Name -> TcSigInfo -> TcM TcId
216 newSigLetBndr LetLclBndr name sig
217 = do { mono_name <- newLocalName name
218 ; mkLocalBinder mono_name (sig_tau sig) }
219 newSigLetBndr (LetGblBndr prags) name sig
220 = addInlinePrags (sig_id sig) (prags name)
223 newNoSigLetBndr :: LetBndrSpec -> Name -> TcType -> TcM TcId
224 -- In the polymorphic case (no_gen = False), generate a "monomorphic version"
225 -- of the Id; the original name will be bound to the polymorphic version
227 -- In the monomorphic case there is no AbsBinds, and we use the original
229 newNoSigLetBndr LetLclBndr name ty
230 =do { mono_name <- newLocalName name
231 ; mkLocalBinder mono_name ty }
232 newNoSigLetBndr (LetGblBndr prags) name ty
233 = do { id <- mkLocalBinder name ty
234 ; addInlinePrags id (prags name) }
237 addInlinePrags :: TcId -> [LSig Name] -> TcM TcId
238 addInlinePrags poly_id prags
241 inl_sigs = filter isInlineLSig prags
242 tc_inl [] = return poly_id
243 tc_inl (L loc (InlineSig _ prag) : other_inls)
244 = do { unless (null other_inls) (setSrcSpan loc warn_dup_inline)
245 ; return (poly_id `setInlinePragma` prag) }
246 tc_inl _ = panic "tc_inl"
248 warn_dup_inline = warnPrags poly_id inl_sigs $
249 ptext (sLit "Duplicate INLINE pragmas for")
251 warnPrags :: Id -> [LSig Name] -> SDoc -> TcM ()
252 warnPrags id bad_sigs herald
253 = addWarnTc (hang (herald <+> quotes (ppr id))
254 2 (ppr_sigs bad_sigs))
256 ppr_sigs sigs = vcat (map (ppr . getLoc) sigs)
259 mkLocalBinder :: Name -> TcType -> TcM TcId
260 mkLocalBinder name ty
261 = do { checkUnboxedTuple ty $
262 ptext (sLit "The variable") <+> quotes (ppr name)
263 ; return (Id.mkLocalId name ty) }
265 checkUnboxedTuple :: TcType -> SDoc -> TcM ()
266 -- Check for an unboxed tuple type
267 -- f = (# True, False #)
268 -- Zonk first just in case it's hidden inside a meta type variable
269 -- (This shows up as a (more obscure) kind error
270 -- in the 'otherwise' case of tcMonoBinds.)
271 checkUnboxedTuple ty what
272 = do { zonked_ty <- zonkTcTypeCarefully ty
273 ; checkTc (not (isUnboxedTupleType zonked_ty))
274 (unboxedTupleErr what zonked_ty) }
277 {- Only needed if we re-add Method constraints
278 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, TcEvBinds)
279 bindInstsOfPatId id thing_inside
280 | not (isOverloadedTy (idType id))
281 = do { res <- thing_inside; return (res, emptyTcEvBinds) }
283 = do { (res, lie) <- captureConstraints thing_inside
284 ; binds <- bindLocalMethods lie [id]
285 ; return (res, binds) }
289 Note [Polymorphism and pattern bindings]
290 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
291 When is_mono holds we are not generalising
292 But the signature can still be polymoprhic!
293 data T = MkT (forall a. a->a)
296 So the no_gen flag decides whether the pattern-bound variables should
297 have exactly the type in the type signature (when not generalising) or
298 the instantiated version (when generalising)
300 %************************************************************************
302 The main worker functions
304 %************************************************************************
308 tcPat takes a "thing inside" over which the pattern scopes. This is partly
309 so that tcPat can extend the environment for the thing_inside, but also
310 so that constraints arising in the thing_inside can be discharged by the
313 This does not work so well for the ErrCtxt carried by the monad: we don't
314 want the error-context for the pattern to scope over the RHS.
315 Hence the getErrCtxt/setErrCtxt stuff in tcMultiple
319 type Checker inp out = forall r.
325 tcMultiple :: Checker inp out -> Checker [inp] [out]
326 tcMultiple tc_pat args penv thing_inside
327 = do { err_ctxt <- getErrCtxt
329 = do { res <- thing_inside
333 = do { (p', (ps', res))
335 setErrCtxt err_ctxt $
337 -- setErrCtxt: restore context before doing the next pattern
338 -- See note [Nesting] above
340 ; return (p':ps', res) }
349 -> TcM (LPat TcId, a)
350 tc_lpat (L span pat) pat_ty penv thing_inside
352 maybeAddErrCtxt (patCtxt pat) $
353 do { (pat', res) <- tc_pat penv pat pat_ty thing_inside
354 ; return (L span pat', res) }
357 -> [LPat Name] -> [TcSigmaType]
359 -> TcM ([LPat TcId], a)
360 tc_lpats penv pats tys thing_inside
361 = tcMultiple (\(p,t) -> tc_lpat p t)
362 (zipEqual "tc_lpats" pats tys)
368 -> TcSigmaType -- Fully refined result type
369 -> TcM a -- Thing inside
370 -> TcM (Pat TcId, -- Translated pattern
371 a) -- Result of thing inside
373 tc_pat penv (VarPat name) pat_ty thing_inside
374 = do { (coi, id) <- tcPatBndr penv name pat_ty
375 ; res <- tcExtendIdEnv1 name id thing_inside
376 ; return (mkHsWrapPatCoI coi (VarPat id) pat_ty, res) }
378 tc_pat penv (ParPat pat) pat_ty thing_inside
379 = do { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
380 ; return (ParPat pat', res) }
382 tc_pat penv (BangPat pat) pat_ty thing_inside
383 = do { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
384 ; return (BangPat pat', res) }
386 tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside
387 = do { (pat', (res, pat_ct))
388 <- tc_lpat pat pat_ty (makeLazy penv) $
389 captureConstraints thing_inside
390 -- Ignore refined penv', revert to penv
392 ; emitConstraints pat_ct
393 -- captureConstraints/extendConstraints:
394 -- see Note [Hopping the LIE in lazy patterns]
396 -- Check there are no unlifted types under the lazy pattern
397 ; when (any (isUnLiftedType . idType) $ collectPatBinders pat') $
398 lazyUnliftedPatErr lpat
400 -- Check that the expected pattern type is itself lifted
401 ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
402 ; _ <- unifyType pat_ty pat_ty'
404 ; return (LazyPat pat', res) }
406 tc_pat _ p@(QuasiQuotePat _) _ _
407 = pprPanic "Should never see QuasiQuotePat in type checker" (ppr p)
409 tc_pat _ (WildPat _) pat_ty thing_inside
410 = do { checkUnboxedTuple pat_ty $
411 ptext (sLit "A wild-card pattern")
412 ; res <- thing_inside
413 ; return (WildPat pat_ty, res) }
415 tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
416 = do { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
417 ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
418 tc_lpat pat (idType bndr_id) penv thing_inside
419 -- NB: if we do inference on:
420 -- \ (y@(x::forall a. a->a)) = e
421 -- we'll fail. The as-pattern infers a monotype for 'y', which then
422 -- fails to unify with the polymorphic type for 'x'. This could
423 -- perhaps be fixed, but only with a bit more work.
425 -- If you fix it, don't forget the bindInstsOfPatIds!
426 ; return (mkHsWrapPatCoI coi (AsPat (L nm_loc bndr_id) pat') pat_ty, res) }
428 tc_pat penv vpat@(ViewPat expr pat _) overall_pat_ty thing_inside
429 = do { checkUnboxedTuple overall_pat_ty $
430 ptext (sLit "The view pattern") <+> ppr vpat
432 -- Morally, expr must have type `forall a1...aN. OPT' -> B`
433 -- where overall_pat_ty is an instance of OPT'.
434 -- Here, we infer a rho type for it,
435 -- which replaces the leading foralls and constraints
436 -- with fresh unification variables.
437 ; (expr',expr'_inferred) <- tcInferRho expr
439 -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
440 -- NOTE: this forces pat_ty to be a monotype (because we use a unification
441 -- variable to find it). this means that in an example like
442 -- (view -> f) where view :: _ -> forall b. b
443 -- we will only be able to use view at one instantation in the
445 ; (expr_coi, pat_ty) <- tcInfer $ \ pat_ty ->
446 unifyPatType expr'_inferred (mkFunTy overall_pat_ty pat_ty)
448 -- pattern must have pat_ty
449 ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside
451 ; return (ViewPat (mkLHsWrapCoI expr_coi expr') pat' overall_pat_ty, res) }
453 -- Type signatures in patterns
454 -- See Note [Pattern coercions] below
455 tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
456 = do { (inner_ty, tv_binds, wrap) <- tcPatSig (patSigCtxt penv) sig_ty pat_ty
457 ; (pat', res) <- tcExtendTyVarEnv2 tv_binds $
458 tc_lpat pat inner_ty penv thing_inside
460 ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
462 ------------------------
463 -- Lists, tuples, arrays
464 tc_pat penv (ListPat pats _) pat_ty thing_inside
465 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy pat_ty
466 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
467 pats penv thing_inside
468 ; return (mkHsWrapPat coi (ListPat pats' elt_ty) pat_ty, res)
471 tc_pat penv (PArrPat pats _) pat_ty thing_inside
472 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTy pat_ty
473 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
474 pats penv thing_inside
475 ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
478 tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
479 = do { let tc = tupleTyCon boxity (length pats)
480 ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc) pat_ty
481 ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
483 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
484 -- so that we can experiment with lazy tuple-matching.
485 -- This is a pretty odd place to make the switch, but
486 -- it was easy to do.
487 ; let pat_ty' = mkTyConApp tc arg_tys
488 -- pat_ty /= pat_ty iff coi /= IdCo
489 unmangled_result = TuplePat pats' boxity pat_ty'
490 possibly_mangled_result
491 | opt_IrrefutableTuples &&
492 isBoxed boxity = LazyPat (noLoc unmangled_result)
493 | otherwise = unmangled_result
495 ; ASSERT( length arg_tys == length pats ) -- Syntactically enforced
496 return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
499 ------------------------
501 tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
502 = tcConPat penv con pat_ty arg_pats thing_inside
504 ------------------------
506 tc_pat _ (LitPat simple_lit) pat_ty thing_inside
507 = do { let lit_ty = hsLitType simple_lit
508 ; coi <- unifyPatType lit_ty pat_ty
509 -- coi is of kind: pat_ty ~ lit_ty
510 ; res <- thing_inside
511 ; return ( mkHsWrapPatCoI coi (LitPat simple_lit) pat_ty
514 ------------------------
515 -- Overloaded patterns: n, and n+k
516 tc_pat _ (NPat over_lit mb_neg eq) pat_ty thing_inside
517 = do { let orig = LiteralOrigin over_lit
518 ; lit' <- newOverloadedLit orig over_lit pat_ty
519 ; eq' <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
520 ; mb_neg' <- case mb_neg of
521 Nothing -> return Nothing -- Positive literal
522 Just neg -> -- Negative literal
523 -- The 'negate' is re-mappable syntax
524 do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
525 ; return (Just neg') }
526 ; res <- thing_inside
527 ; return (NPat lit' mb_neg' eq', res) }
529 tc_pat penv (NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
530 = do { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
531 ; let pat_ty' = idType bndr_id
532 orig = LiteralOrigin lit
533 ; lit' <- newOverloadedLit orig lit pat_ty'
535 -- The '>=' and '-' parts are re-mappable syntax
536 ; ge' <- tcSyntaxOp orig ge (mkFunTys [pat_ty', pat_ty'] boolTy)
537 ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
538 ; let pat' = NPlusKPat (L nm_loc bndr_id) lit' ge' minus'
540 -- The Report says that n+k patterns must be in Integral
541 -- We may not want this when using re-mappable syntax, though (ToDo?)
542 ; icls <- tcLookupClass integralClassName
543 ; instStupidTheta orig [mkClassPred icls [pat_ty']]
545 ; res <- tcExtendIdEnv1 name bndr_id thing_inside
546 ; return (mkHsWrapPatCoI coi pat' pat_ty, res) }
548 tc_pat _ _other_pat _ _ = panic "tc_pat" -- ConPatOut, SigPatOut
551 unifyPatType :: TcType -> TcType -> TcM CoercionI
552 -- In patterns we want a coercion from the
553 -- context type (expected) to the actual pattern type
554 -- But we don't want to reverse the args to unifyType because
555 -- that controls the actual/expected stuff in error messages
556 unifyPatType actual_ty expected_ty
557 = do { coi <- unifyType actual_ty expected_ty
558 ; return (mkSymCoI coi) }
561 Note [Hopping the LIE in lazy patterns]
562 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
563 In a lazy pattern, we must *not* discharge constraints from the RHS
564 from dictionaries bound in the pattern. E.g.
566 We can't discharge the Num constraint from dictionaries bound by
569 So we have to make the constraints from thing_inside "hop around"
570 the pattern. Hence the captureConstraints and emitConstraints.
572 The same thing ensures that equality constraints in a lazy match
573 are not made available in the RHS of the match. For example
574 data T a where { T1 :: Int -> T Int; ... }
577 It's obviously not sound to refine a to Int in the right
578 hand side, because the arugment might not match T1 at all!
580 Finally, a lazy pattern should not bind any existential type variables
581 because they won't be in scope when we do the desugaring
584 %************************************************************************
586 Most of the work for constructors is here
587 (the rest is in the ConPatIn case of tc_pat)
589 %************************************************************************
591 [Pattern matching indexed data types]
592 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
593 Consider the following declarations:
595 data family Map k :: * -> *
596 data instance Map (a, b) v = MapPair (Map a (Pair b v))
598 and a case expression
600 case x :: Map (Int, c) w of MapPair m -> ...
602 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
603 worker/wrapper types for MapPair are
605 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
606 $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
608 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
609 :R123Map, which means the straight use of boxySplitTyConApp would give a type
610 error. Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
611 boxySplitTyConApp with the family tycon Map instead, which gives us the family
612 type list {(Int, c), w}. To get the correct split for :R123Map, we need to
613 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
614 (provided by tyConFamInst_maybe together with the family tycon). This
615 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
616 the split arguments for the representation tycon :R123Map as {Int, c, w}
618 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
620 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
622 moving between representation and family type into account. To produce type
623 correct Core, this coercion needs to be used to case the type of the scrutinee
624 from the family to the representation type. This is achieved by
625 unwrapFamInstScrutinee using a CoPat around the result pattern.
627 Now it might appear seem as if we could have used the previous GADT type
628 refinement infrastructure of refineAlt and friends instead of the explicit
629 unification and CoPat generation. However, that would be wrong. Why? The
630 whole point of GADT refinement is that the refinement is local to the case
631 alternative. In contrast, the substitution generated by the unification of
632 the family type list and instance types needs to be propagated to the outside.
633 Imagine that in the above example, the type of the scrutinee would have been
634 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
635 substitution [x -> (a, b), v -> w]. In contrast to GADT matching, the
636 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
637 alternatives of the case expression, whereas in the GADT case it might vary
638 between alternatives.
640 RIP GADT refinement: refinements have been replaced by the use of explicit
641 equality constraints that are used in conjunction with implication constraints
642 to express the local scope of GADT refinements.
646 -- MkT :: forall a b c. (a~[b]) => b -> c -> T a
647 -- with scrutinee of type (T ty)
649 tcConPat :: PatEnv -> Located Name
650 -> TcRhoType -- Type of the pattern
651 -> HsConPatDetails Name -> TcM a
653 tcConPat penv (L con_span con_name) pat_ty arg_pats thing_inside
654 = do { data_con <- tcLookupDataCon con_name
655 ; let tycon = dataConTyCon data_con
656 -- For data families this is the representation tycon
657 (univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _)
658 = dataConFullSig data_con
660 -- Instantiate the constructor type variables [a->ty]
661 -- This may involve doing a family-instance coercion,
662 -- and building a wrapper
663 ; (wrap, ctxt_res_tys) <- matchExpectedPatTy (matchExpectedConTy tycon) pat_ty
665 -- Add the stupid theta
666 ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
668 ; checkExistentials ex_tvs penv
669 ; ex_tvs' <- tcInstSuperSkolTyVars ex_tvs
670 -- Get location from monad, not from ex_tvs
672 ; let pat_ty' = mkTyConApp tycon ctxt_res_tys
673 -- pat_ty' is type of the actual constructor application
674 -- pat_ty' /= pat_ty iff coi /= IdCo
676 tenv = zipTopTvSubst (univ_tvs ++ ex_tvs)
677 (ctxt_res_tys ++ mkTyVarTys ex_tvs')
678 arg_tys' = substTys tenv arg_tys
679 full_theta = eq_theta ++ dict_theta
681 ; if null ex_tvs && null eq_spec && null full_theta
682 then do { -- The common case; no class bindings etc
683 -- (see Note [Arrows and patterns])
684 (arg_pats', res) <- tcConArgs data_con arg_tys'
685 arg_pats penv thing_inside
686 ; let res_pat = ConPatOut { pat_con = L con_span data_con,
687 pat_tvs = [], pat_dicts = [],
688 pat_binds = emptyTcEvBinds,
689 pat_args = arg_pats',
692 ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
694 else do -- The general case, with existential,
695 -- and local equality constraints
696 { let eq_preds = [mkEqPred (mkTyVarTy tv, ty) | (tv, ty) <- eq_spec]
697 theta' = substTheta tenv (eq_preds ++ full_theta)
698 -- order is *important* as we generate the list of
699 -- dictionary binders from theta'
700 no_equalities = not (any isEqPred theta')
701 skol_info = case pe_ctxt penv of
702 LamPat mc -> PatSkol data_con mc
703 LetPat {} -> UnkSkol -- Doesn't matter
705 ; gadts_on <- xoptM Opt_GADTs
706 ; checkTc (no_equalities || gadts_on)
707 (ptext (sLit "A pattern match on a GADT requires -XGADTs"))
708 -- Trac #2905 decided that a *pattern-match* of a GADT
709 -- should require the GADT language flag
711 ; given <- newEvVars theta'
712 ; (ev_binds, (arg_pats', res))
713 <- checkConstraints skol_info ex_tvs' given $
714 tcConArgs data_con arg_tys' arg_pats penv thing_inside
716 ; let res_pat = ConPatOut { pat_con = L con_span data_con,
719 pat_binds = ev_binds,
720 pat_args = arg_pats',
722 ; return (mkHsWrapPat wrap res_pat pat_ty, res)
725 ----------------------------
726 matchExpectedPatTy :: (TcRhoType -> TcM (CoercionI, a))
727 -> TcRhoType -> TcM (HsWrapper, a)
728 -- See Note [Matching polytyped patterns]
729 -- Returns a wrapper : pat_ty ~ inner_ty
730 matchExpectedPatTy inner_match pat_ty
731 | null tvs && null theta
732 = do { (coi, res) <- inner_match pat_ty
733 ; return (coiToHsWrapper (mkSymCoI coi), res) }
734 -- The Sym is because the inner_match returns a coercion
735 -- that is the other way round to matchExpectedPatTy
738 = do { (_, tys, subst) <- tcInstTyVars tvs
739 ; wrap1 <- instCall PatOrigin tys (substTheta subst theta)
740 ; (wrap2, arg_tys) <- matchExpectedPatTy inner_match (substTy subst tau)
741 ; return (wrap2 <.> wrap1 , arg_tys) }
743 (tvs, theta, tau) = tcSplitSigmaTy pat_ty
745 ----------------------------
746 matchExpectedConTy :: TyCon -- The TyCon that this data
747 -- constructor actually returns
748 -> TcRhoType -- The type of the pattern
749 -> TcM (CoercionI, [TcSigmaType])
750 -- See Note [Matching constructor patterns]
751 -- Returns a coercion : T ty1 ... tyn ~ pat_ty
752 -- This is the same way round as matchExpectedListTy etc
753 -- but the other way round to matchExpectedPatTy
754 matchExpectedConTy data_tc pat_ty
755 | Just (fam_tc, fam_args, co_tc) <- tyConFamInstSig_maybe data_tc
756 -- Comments refer to Note [Matching constructor patterns]
757 -- co_tc :: forall a. T [a] ~ T7 a
758 = do { (_, tys, subst) <- tcInstTyVars (tyConTyVars data_tc)
761 ; coi1 <- unifyType (mkTyConApp fam_tc (substTys subst fam_args)) pat_ty
762 -- coi1 : T (ty1,ty2) ~ pat_ty
764 ; let coi2 = ACo (mkTyConApp co_tc tys)
765 -- coi2 : T (ty1,ty2) ~ T7 ty1 ty2
767 ; return (mkTransCoI (mkSymCoI coi2) coi1, tys) }
770 = matchExpectedTyConApp data_tc pat_ty
771 -- coi : T tys ~ pat_ty
775 Note [Matching constructor patterns]
776 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
777 Suppose (coi, tys) = matchExpectedConType data_tc pat_ty
779 * In the simple case, pat_ty = tc tys
781 * If pat_ty is a polytype, we want to instantiate it
782 This is like part of a subsumption check. Eg
783 f :: (forall a. [a]) -> blah
786 * In a type family case, suppose we have
788 data instance T (p,q) = A p | B q
789 Then we'll have internally generated
790 data T7 p q = A p | B q
791 axiom coT7 p q :: T (p,q) ~ T7 p q
793 So if pat_ty = T (ty1,ty2), we return (coi, [ty1,ty2]) such that
794 coi = coi2 . coi1 : T7 t ~ pat_ty
795 coi1 : T (ty1,ty2) ~ pat_ty
796 coi2 : T7 ty1 ty2 ~ T (ty1,ty2)
798 For families we do all this matching here, not in the unifier,
799 because we never want a whisper of the data_tycon to appear in
800 error messages; it's a purely internal thing
803 tcConArgs :: DataCon -> [TcSigmaType]
804 -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
806 tcConArgs data_con arg_tys (PrefixCon arg_pats) penv thing_inside
807 = do { checkTc (con_arity == no_of_args) -- Check correct arity
808 (arityErr "Constructor" data_con con_arity no_of_args)
809 ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
810 ; (arg_pats', res) <- tcMultiple tcConArg pats_w_tys
812 ; return (PrefixCon arg_pats', res) }
814 con_arity = dataConSourceArity data_con
815 no_of_args = length arg_pats
817 tcConArgs data_con arg_tys (InfixCon p1 p2) penv thing_inside
818 = do { checkTc (con_arity == 2) -- Check correct arity
819 (arityErr "Constructor" data_con con_arity 2)
820 ; let [arg_ty1,arg_ty2] = arg_tys -- This can't fail after the arity check
821 ; ([p1',p2'], res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
823 ; return (InfixCon p1' p2', res) }
825 con_arity = dataConSourceArity data_con
827 tcConArgs data_con arg_tys (RecCon (HsRecFields rpats dd)) penv thing_inside
828 = do { (rpats', res) <- tcMultiple tc_field rpats penv thing_inside
829 ; return (RecCon (HsRecFields rpats' dd), res) }
831 tc_field :: Checker (HsRecField FieldLabel (LPat Name)) (HsRecField TcId (LPat TcId))
832 tc_field (HsRecField field_lbl pat pun) penv thing_inside
833 = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
834 ; (pat', res) <- tcConArg (pat, pat_ty) penv thing_inside
835 ; return (HsRecField sel_id pat' pun, res) }
837 find_field_ty :: FieldLabel -> TcM (Id, TcType)
838 find_field_ty field_lbl
839 = case [ty | (f,ty) <- field_tys, f == field_lbl] of
841 -- No matching field; chances are this field label comes from some
842 -- other record type (or maybe none). As well as reporting an
843 -- error we still want to typecheck the pattern, principally to
844 -- make sure that all the variables it binds are put into the
845 -- environment, else the type checker crashes later:
846 -- f (R { foo = (a,b) }) = a+b
847 -- If foo isn't one of R's fields, we don't want to crash when
848 -- typechecking the "a+b".
849 [] -> do { addErrTc (badFieldCon data_con field_lbl)
850 ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
851 ; return (error "Bogus selector Id", bogus_ty) }
853 -- The normal case, when the field comes from the right constructor
855 ASSERT( null extras )
856 do { sel_id <- tcLookupField field_lbl
857 ; return (sel_id, pat_ty) }
859 field_tys :: [(FieldLabel, TcType)]
860 field_tys = zip (dataConFieldLabels data_con) arg_tys
861 -- Don't use zipEqual! If the constructor isn't really a record, then
862 -- dataConFieldLabels will be empty (and each field in the pattern
863 -- will generate an error below).
865 tcConArg :: Checker (LPat Name, TcSigmaType) (LPat Id)
866 tcConArg (arg_pat, arg_ty) penv thing_inside
867 = tc_lpat arg_pat arg_ty penv thing_inside
871 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
872 -- Instantiate the "stupid theta" of the data con, and throw
873 -- the constraints into the constraint set
874 addDataConStupidTheta data_con inst_tys
875 | null stupid_theta = return ()
876 | otherwise = instStupidTheta origin inst_theta
878 origin = OccurrenceOf (dataConName data_con)
879 -- The origin should always report "occurrence of C"
880 -- even when C occurs in a pattern
881 stupid_theta = dataConStupidTheta data_con
882 tenv = mkTopTvSubst (dataConUnivTyVars data_con `zip` inst_tys)
883 -- NB: inst_tys can be longer than the univ tyvars
884 -- because the constructor might have existentials
885 inst_theta = substTheta tenv stupid_theta
888 Note [Arrows and patterns]
889 ~~~~~~~~~~~~~~~~~~~~~~~~~~
890 (Oct 07) Arrow noation has the odd property that it involves
891 "holes in the scope". For example:
892 expr :: Arrow a => a () Int
893 expr = proc (y,z) -> do
897 Here the 'proc (y,z)' binding scopes over the arrow tails but not the
898 arrow body (e.g 'term'). As things stand (bogusly) all the
899 constraints from the proc body are gathered together, so constraints
900 from 'term' will be seen by the tcPat for (y,z). But we must *not*
901 bind constraints from 'term' here, becuase the desugarer will not make
902 these bindings scope over 'term'.
904 The Right Thing is not to confuse these constraints together. But for
905 now the Easy Thing is to ensure that we do not have existential or
906 GADT constraints in a 'proc', and to short-cut the constraint
907 simplification for such vanilla patterns so that it binds no
908 constraints. Hence the 'fast path' in tcConPat; but it's also a good
909 plan for ordinary vanilla patterns to bypass the constraint
912 %************************************************************************
914 Note [Pattern coercions]
916 %************************************************************************
918 In principle, these program would be reasonable:
920 f :: (forall a. a->a) -> Int
921 f (x :: Int->Int) = x 3
923 g :: (forall a. [a]) -> Bool
926 In both cases, the function type signature restricts what arguments can be passed
927 in a call (to polymorphic ones). The pattern type signature then instantiates this
928 type. For example, in the first case, (forall a. a->a) <= Int -> Int, and we
929 generate the translated term
930 f = \x' :: (forall a. a->a). let x = x' Int in x 3
932 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
933 And it requires a significant amount of code to implement, becuase we need to decorate
934 the translated pattern with coercion functions (generated from the subsumption check
937 So for now I'm just insisting on type *equality* in patterns. No subsumption.
939 Old notes about desugaring, at a time when pattern coercions were handled:
941 A SigPat is a type coercion and must be handled one at at time. We can't
942 combine them unless the type of the pattern inside is identical, and we don't
943 bother to check for that. For example:
945 data T = T1 Int | T2 Bool
946 f :: (forall a. a -> a) -> T -> t
947 f (g::Int->Int) (T1 i) = T1 (g i)
948 f (g::Bool->Bool) (T2 b) = T2 (g b)
950 We desugar this as follows:
952 f = \ g::(forall a. a->a) t::T ->
954 in case t of { T1 i -> T1 (gi i)
957 in case t of { T2 b -> T2 (gb b)
960 Note that we do not treat the first column of patterns as a
961 column of variables, because the coerced variables (gi, gb)
962 would be of different types. So we get rather grotty code.
963 But I don't think this is a common case, and if it was we could
964 doubtless improve it.
966 Meanwhile, the strategy is:
967 * treat each SigPat coercion (always non-identity coercions)
969 * deal with the stuff inside, and then wrap a binding round
970 the result to bind the new variable (gi, gb, etc)
973 %************************************************************************
975 \subsection{Errors and contexts}
977 %************************************************************************
979 {- This was used to improve the error message from
980 an existential escape. Need to think how to do this.
982 sigPatCtxt :: [LPat Var] -> [Var] -> [TcType] -> TcType -> TidyEnv
983 -> TcM (TidyEnv, SDoc)
984 sigPatCtxt pats bound_tvs pat_tys body_ty tidy_env
985 = do { pat_tys' <- mapM zonkTcType pat_tys
986 ; body_ty' <- zonkTcType body_ty
987 ; let (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
988 (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
989 (env3, tidy_body_ty) = tidyOpenType env2 body_ty'
991 sep [ptext (sLit "When checking an existential match that binds"),
992 nest 2 (vcat (zipWith ppr_id show_ids tidy_tys)),
993 ptext (sLit "The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
994 ptext (sLit "The body has type:") <+> ppr tidy_body_ty
997 bound_ids = collectPatsBinders pats
998 show_ids = filter is_interesting bound_ids
999 is_interesting id = any (`elemVarSet` varTypeTyVars id) bound_tvs
1001 ppr_id id ty = ppr id <+> dcolon <+> ppr ty
1002 -- Don't zonk the types so we get the separate, un-unified versions
1006 patCtxt :: Pat Name -> Maybe Message -- Not all patterns are worth pushing a context
1007 patCtxt (VarPat _) = Nothing
1008 patCtxt (ParPat _) = Nothing
1009 patCtxt (AsPat _ _) = Nothing
1010 patCtxt pat = Just (hang (ptext (sLit "In the pattern:"))
1013 -----------------------------------------------
1014 checkExistentials :: [TyVar] -> PatEnv -> TcM ()
1015 -- See Note [Arrows and patterns]
1016 checkExistentials [] _ = return ()
1017 checkExistentials _ (PE { pe_ctxt = LetPat {}}) = failWithTc existentialLetPat
1018 checkExistentials _ (PE { pe_ctxt = LamPat ProcExpr }) = failWithTc existentialProcPat
1019 checkExistentials _ (PE { pe_lazy = True }) = failWithTc existentialLazyPat
1020 checkExistentials _ _ = return ()
1022 existentialLazyPat :: SDoc
1024 = hang (ptext (sLit "An existential or GADT data constructor cannot be used"))
1025 2 (ptext (sLit "inside a lazy (~) pattern"))
1027 existentialProcPat :: SDoc
1029 = ptext (sLit "Proc patterns cannot use existential or GADT data constructors")
1031 existentialLetPat :: SDoc
1033 = vcat [text "My brain just exploded",
1034 text "I can't handle pattern bindings for existential or GADT data constructors.",
1035 text "Instead, use a case-expression, or do-notation, to unpack the constructor."]
1037 badFieldCon :: DataCon -> Name -> SDoc
1038 badFieldCon con field
1039 = hsep [ptext (sLit "Constructor") <+> quotes (ppr con),
1040 ptext (sLit "does not have field"), quotes (ppr field)]
1042 polyPatSig :: TcType -> SDoc
1044 = hang (ptext (sLit "Illegal polymorphic type signature in pattern:"))
1047 lazyUnliftedPatErr :: OutputableBndr name => Pat name -> TcM ()
1048 lazyUnliftedPatErr pat
1050 hang (ptext (sLit "A lazy (~) pattern cannot contain unlifted types:"))
1053 unboxedTupleErr :: SDoc -> Type -> SDoc
1054 unboxedTupleErr what ty
1055 = hang (what <+> ptext (sLit "cannot have an unboxed tuple type:"))