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)
35 import VarSet ( emptyVarSet )
37 import BasicTypes hiding (SuccessFlag(..))
48 %************************************************************************
52 %************************************************************************
55 tcLetPat :: TcSigFun -> LetBndrSpec
56 -> LPat Name -> TcSigmaType
59 tcLetPat sig_fn no_gen 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 no_gen }
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 LetBndrSpec -- True <=> no generalisation of this let
128 = LetLclBndr -- The binder is just a local one;
129 -- an AbsBinds will provide the global version
131 | LetGblBndr TcPragFun -- There isn't going to be an AbsBinds;
132 -- here is the inline-pragma information
134 makeLazy :: PatEnv -> PatEnv
135 makeLazy penv = penv { pe_lazy = True }
137 patSigCtxt :: PatEnv -> UserTypeCtxt
138 patSigCtxt (PE { pe_ctxt = LetPat {} }) = BindPatSigCtxt
139 patSigCtxt (PE { pe_ctxt = LamPat {} }) = LamPatSigCtxt
142 type TcPragFun = Name -> [LSig Name]
143 type TcSigFun = Name -> Maybe TcSigInfo
147 sig_id :: TcId, -- *Polymorphic* binder for this value...
149 sig_scoped :: [Name], -- Scoped type variables
150 -- 1-1 correspondence with a prefix of sig_tvs
151 -- However, may be fewer than sig_tvs;
152 -- see Note [More instantiated than scoped]
153 sig_tvs :: [TcTyVar], -- Instantiated type variables
154 -- See Note [Instantiate sig]
156 sig_theta :: TcThetaType, -- Instantiated theta
158 sig_tau :: TcSigmaType, -- Instantiated tau
159 -- See Note [sig_tau may be polymorphic]
161 sig_loc :: SrcSpan -- The location of the signature
164 instance Outputable TcSigInfo where
165 ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
166 = ppr id <+> ptext (sLit "::") <+> ppr tyvars <+> pprThetaArrow theta <+> ppr tau
169 Note [sig_tau may be polymorphic]
170 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
171 Note that "sig_tau" might actually be a polymorphic type,
172 if the original function had a signature like
173 forall a. Eq a => forall b. Ord b => ....
174 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
175 It happens, too! See Note [Polymorphic methods] in TcClassDcl.
183 ...more notes to add here..
186 Note [Existential check]
187 ~~~~~~~~~~~~~~~~~~~~~~~~
188 Lazy patterns can't bind existentials. They arise in two ways:
189 * Let bindings let { C a b = e } in b
190 * Twiddle patterns f ~(C a b) = e
191 The pe_res_tvs field of PatEnv says whether we are inside a lazy
192 pattern (perhaps deeply)
194 If we aren't inside a lazy pattern then we can bind existentials,
195 but we need to be careful about "extra" tyvars. Consider
196 (\C x -> d) : pat_ty -> res_ty
197 When looking for existential escape we must check that the existential
198 bound by C don't unify with the free variables of pat_ty, OR res_ty
199 (or of course the environment). Hence we need to keep track of the
203 %************************************************************************
207 %************************************************************************
210 tcPatBndr :: PatEnv -> Name -> TcSigmaType -> TcM (CoercionI, TcId)
211 -- (coi, xp) = tcPatBndr penv x pat_ty
212 -- Then coi : pat_ty ~ typeof(xp)
214 tcPatBndr (PE { pe_ctxt = LetPat lookup_sig no_gen}) bndr_name pat_ty
215 | Just sig <- lookup_sig bndr_name
216 = do { bndr_id <- newSigLetBndr no_gen bndr_name sig
217 ; coi <- unifyPatType (idType bndr_id) pat_ty
218 ; return (coi, bndr_id) }
221 = do { bndr_id <- newNoSigLetBndr no_gen bndr_name pat_ty
222 ; return (IdCo pat_ty, bndr_id) }
224 tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty
225 = do { bndr <- mkLocalBinder bndr_name pat_ty
226 ; return (IdCo pat_ty, bndr) }
229 newSigLetBndr :: LetBndrSpec -> Name -> TcSigInfo -> TcM TcId
230 newSigLetBndr LetLclBndr name sig
231 = do { mono_name <- newLocalName name
232 ; mkLocalBinder mono_name (sig_tau sig) }
233 newSigLetBndr (LetGblBndr prags) name sig
234 = addInlinePrags (sig_id sig) (prags name)
237 newNoSigLetBndr :: LetBndrSpec -> Name -> TcType -> TcM TcId
238 -- In the polymorphic case (no_gen = False), generate a "monomorphic version"
239 -- of the Id; the original name will be bound to the polymorphic version
241 -- In the monomorphic case there is no AbsBinds, and we use the original
243 newNoSigLetBndr LetLclBndr name ty
244 =do { mono_name <- newLocalName name
245 ; mkLocalBinder mono_name ty }
246 newNoSigLetBndr (LetGblBndr prags) name ty
247 = do { id <- mkLocalBinder name ty
248 ; addInlinePrags id (prags name) }
251 addInlinePrags :: TcId -> [LSig Name] -> TcM TcId
252 addInlinePrags poly_id prags
255 inl_sigs = filter isInlineLSig prags
256 tc_inl [] = return poly_id
257 tc_inl (L loc (InlineSig _ prag) : other_inls)
258 = do { unless (null other_inls) (setSrcSpan loc warn_dup_inline)
259 ; return (poly_id `setInlinePragma` prag) }
260 tc_inl _ = panic "tc_inl"
262 warn_dup_inline = warnPrags poly_id inl_sigs $
263 ptext (sLit "Duplicate INLINE pragmas for")
265 warnPrags :: Id -> [LSig Name] -> SDoc -> TcM ()
266 warnPrags id bad_sigs herald
267 = addWarnTc (hang (herald <+> quotes (ppr id))
268 2 (ppr_sigs bad_sigs))
270 ppr_sigs sigs = vcat (map (ppr . getLoc) sigs)
273 mkLocalBinder :: Name -> TcType -> TcM TcId
274 mkLocalBinder name ty
275 = do { checkUnboxedTuple ty $
276 ptext (sLit "The variable") <+> quotes (ppr name)
277 ; return (Id.mkLocalId name ty) }
279 checkUnboxedTuple :: TcType -> SDoc -> TcM ()
280 -- Check for an unboxed tuple type
281 -- f = (# True, False #)
282 -- Zonk first just in case it's hidden inside a meta type variable
283 -- (This shows up as a (more obscure) kind error
284 -- in the 'otherwise' case of tcMonoBinds.)
285 checkUnboxedTuple ty what
286 = do { zonked_ty <- zonkTcTypeCarefully ty
287 ; checkTc (not (isUnboxedTupleType zonked_ty))
288 (unboxedTupleErr what zonked_ty) }
291 {- Only needed if we re-add Method constraints
292 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, TcEvBinds)
293 bindInstsOfPatId id thing_inside
294 | not (isOverloadedTy (idType id))
295 = do { res <- thing_inside; return (res, emptyTcEvBinds) }
297 = do { (res, lie) <- getConstraints thing_inside
298 ; binds <- bindLocalMethods lie [id]
299 ; return (res, binds) }
303 Note [Polymorphism and pattern bindings]
304 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
305 When is_mono holds we are not generalising
306 But the signature can still be polymoprhic!
307 data T = MkT (forall a. a->a)
310 So the no_gen flag decides whether the pattern-bound variables should
311 have exactly the type in the type signature (when not generalising) or
312 the instantiated version (when generalising)
314 %************************************************************************
316 The main worker functions
318 %************************************************************************
322 tcPat takes a "thing inside" over which the pattern scopes. This is partly
323 so that tcPat can extend the environment for the thing_inside, but also
324 so that constraints arising in the thing_inside can be discharged by the
327 This does not work so well for the ErrCtxt carried by the monad: we don't
328 want the error-context for the pattern to scope over the RHS.
329 Hence the getErrCtxt/setErrCtxt stuff in tcMultiple
333 type Checker inp out = forall r.
339 tcMultiple :: Checker inp out -> Checker [inp] [out]
340 tcMultiple tc_pat args penv thing_inside
341 = do { err_ctxt <- getErrCtxt
343 = do { res <- thing_inside
347 = do { (p', (ps', res))
349 setErrCtxt err_ctxt $
351 -- setErrCtxt: restore context before doing the next pattern
352 -- See note [Nesting] above
354 ; return (p':ps', res) }
363 -> TcM (LPat TcId, a)
364 tc_lpat (L span pat) pat_ty penv thing_inside
366 maybeAddErrCtxt (patCtxt pat) $
367 do { (pat', res) <- tc_pat penv pat pat_ty thing_inside
368 ; return (L span pat', res) }
371 -> [LPat Name] -> [TcSigmaType]
373 -> TcM ([LPat TcId], a)
374 tc_lpats penv pats tys thing_inside
375 = tcMultiple (\(p,t) -> tc_lpat p t)
376 (zipEqual "tc_lpats" pats tys)
382 -> TcSigmaType -- Fully refined result type
383 -> TcM a -- Thing inside
384 -> TcM (Pat TcId, -- Translated pattern
385 a) -- Result of thing inside
387 tc_pat penv (VarPat name) pat_ty thing_inside
388 = do { (coi, id) <- tcPatBndr penv name pat_ty
389 ; res <- tcExtendIdEnv1 name id thing_inside
390 ; return (mkHsWrapPatCoI coi (VarPat id) pat_ty, res) }
392 {- Need this if we re-add Method constraints
393 ; (res, binds) <- bindInstsOfPatId id $
394 tcExtendIdEnv1 name id $
395 (traceTc (text "binding" <+> ppr name <+> ppr (idType id))
397 ; let pat' | isEmptyTcEvBinds binds = VarPat id
398 | otherwise = VarPatOut id binds
399 ; return (mkHsWrapPatCoI coi pat' pat_ty, res) }
402 tc_pat penv (ParPat pat) pat_ty thing_inside
403 = do { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
404 ; return (ParPat pat', res) }
406 tc_pat penv (BangPat pat) pat_ty thing_inside
407 = do { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
408 ; return (BangPat pat', res) }
410 tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside
411 = do { (pat', (res, pat_ct))
412 <- tc_lpat pat pat_ty (makeLazy penv) $
413 getConstraints thing_inside
414 -- Ignore refined penv', revert to penv
416 ; emitConstraints pat_ct
417 -- getConstraints/extendConstraintss: see Note [Hopping the LIE in lazy patterns]
419 -- Check there are no unlifted types under the lazy pattern
420 ; when (any (isUnLiftedType . idType) $ collectPatBinders pat') $
421 lazyUnliftedPatErr lpat
423 -- Check that the expected pattern type is itself lifted
424 ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
425 ; _ <- unifyType pat_ty pat_ty'
427 ; return (LazyPat pat', res) }
429 tc_pat _ p@(QuasiQuotePat _) _ _
430 = pprPanic "Should never see QuasiQuotePat in type checker" (ppr p)
432 tc_pat _ (WildPat _) pat_ty thing_inside
433 = do { checkUnboxedTuple pat_ty $
434 ptext (sLit "A wild-card pattern")
435 ; res <- thing_inside
436 ; return (WildPat pat_ty, res) }
438 tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
439 = do { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
440 ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
441 tc_lpat pat (idType bndr_id) penv thing_inside
442 -- NB: if we do inference on:
443 -- \ (y@(x::forall a. a->a)) = e
444 -- we'll fail. The as-pattern infers a monotype for 'y', which then
445 -- fails to unify with the polymorphic type for 'x'. This could
446 -- perhaps be fixed, but only with a bit more work.
448 -- If you fix it, don't forget the bindInstsOfPatIds!
449 ; return (mkHsWrapPatCoI coi (AsPat (L nm_loc bndr_id) pat') pat_ty, res) }
451 tc_pat penv vpat@(ViewPat expr pat _) overall_pat_ty thing_inside
452 = do { checkUnboxedTuple overall_pat_ty $
453 ptext (sLit "The view pattern") <+> ppr vpat
455 -- Morally, expr must have type `forall a1...aN. OPT' -> B`
456 -- where overall_pat_ty is an instance of OPT'.
457 -- Here, we infer a rho type for it,
458 -- which replaces the leading foralls and constraints
459 -- with fresh unification variables.
460 ; (expr',expr'_inferred) <- tcInferRho expr
462 -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
463 -- NOTE: this forces pat_ty to be a monotype (because we use a unification
464 -- variable to find it). this means that in an example like
465 -- (view -> f) where view :: _ -> forall b. b
466 -- we will only be able to use view at one instantation in the
468 ; (expr_coi, pat_ty) <- tcInfer $ \ pat_ty ->
469 unifyPatType expr'_inferred (mkFunTy overall_pat_ty pat_ty)
471 -- pattern must have pat_ty
472 ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside
474 ; return (ViewPat (mkLHsWrapCoI expr_coi expr') pat' overall_pat_ty, res) }
476 -- Type signatures in patterns
477 -- See Note [Pattern coercions] below
478 tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
479 = do { (inner_ty, tv_binds, wrap) <- tcPatSig (patSigCtxt penv) sig_ty pat_ty
480 ; (pat', res) <- tcExtendTyVarEnv2 tv_binds $
481 tc_lpat pat inner_ty penv thing_inside
483 ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
485 tc_pat _ pat@(TypePat _) _ _
486 = failWithTc (badTypePat pat)
488 ------------------------
489 -- Lists, tuples, arrays
490 tc_pat penv (ListPat pats _) pat_ty thing_inside
491 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy pat_ty
492 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
493 pats penv thing_inside
494 ; return (mkHsWrapPat coi (ListPat pats' elt_ty) pat_ty, res)
497 tc_pat penv (PArrPat pats _) pat_ty thing_inside
498 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTy pat_ty
499 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
500 pats penv thing_inside
501 ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
504 tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
505 = do { let tc = tupleTyCon boxity (length pats)
506 ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc) pat_ty
507 ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
509 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
510 -- so that we can experiment with lazy tuple-matching.
511 -- This is a pretty odd place to make the switch, but
512 -- it was easy to do.
513 ; let pat_ty' = mkTyConApp tc arg_tys
514 -- pat_ty /= pat_ty iff coi /= IdCo
515 unmangled_result = TuplePat pats' boxity pat_ty'
516 possibly_mangled_result
517 | opt_IrrefutableTuples &&
518 isBoxed boxity = LazyPat (noLoc unmangled_result)
519 | otherwise = unmangled_result
521 ; ASSERT( length arg_tys == length pats ) -- Syntactically enforced
522 return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
525 ------------------------
527 tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
528 = tcConPat penv con pat_ty arg_pats thing_inside
530 ------------------------
532 tc_pat _ (LitPat simple_lit) pat_ty thing_inside
533 = do { let lit_ty = hsLitType simple_lit
534 ; coi <- unifyPatType lit_ty pat_ty
535 -- coi is of kind: pat_ty ~ lit_ty
536 ; res <- thing_inside
537 ; return ( mkHsWrapPatCoI coi (LitPat simple_lit) pat_ty
540 ------------------------
541 -- Overloaded patterns: n, and n+k
542 tc_pat _ (NPat over_lit mb_neg eq) pat_ty thing_inside
543 = do { let orig = LiteralOrigin over_lit
544 ; lit' <- newOverloadedLit orig over_lit pat_ty
545 ; eq' <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
546 ; mb_neg' <- case mb_neg of
547 Nothing -> return Nothing -- Positive literal
548 Just neg -> -- Negative literal
549 -- The 'negate' is re-mappable syntax
550 do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
551 ; return (Just neg') }
552 ; res <- thing_inside
553 ; return (NPat lit' mb_neg' eq', res) }
555 tc_pat penv (NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
556 = do { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
557 ; let pat_ty' = idType bndr_id
558 orig = LiteralOrigin lit
559 ; lit' <- newOverloadedLit orig lit pat_ty'
561 -- The '>=' and '-' parts are re-mappable syntax
562 ; ge' <- tcSyntaxOp orig ge (mkFunTys [pat_ty', pat_ty'] boolTy)
563 ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
564 ; let pat' = NPlusKPat (L nm_loc bndr_id) lit' ge' minus'
566 -- The Report says that n+k patterns must be in Integral
567 -- We may not want this when using re-mappable syntax, though (ToDo?)
568 ; icls <- tcLookupClass integralClassName
569 ; instStupidTheta orig [mkClassPred icls [pat_ty']]
571 ; res <- tcExtendIdEnv1 name bndr_id thing_inside
572 ; return (mkHsWrapPatCoI coi pat' pat_ty, res) }
574 tc_pat _ _other_pat _ _ = panic "tc_pat" -- ConPatOut, SigPatOut, VarPatOut
577 unifyPatType :: TcType -> TcType -> TcM CoercionI
578 -- In patterns we want a coercion from the
579 -- context type (expected) to the actual pattern type
580 -- But we don't want to reverse the args to unifyType because
581 -- that controls the actual/expected stuff in error messages
582 unifyPatType actual_ty expected_ty
583 = do { coi <- unifyType actual_ty expected_ty
584 ; return (mkSymCoI coi) }
587 Note [Hopping the LIE in lazy patterns]
588 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
589 In a lazy pattern, we must *not* discharge constraints from the RHS
590 from dictionaries bound in the pattern. E.g.
592 We can't discharge the Num constraint from dictionaries bound by
595 So we have to make the constraints from thing_inside "hop around"
596 the pattern. Hence the getConstraints and emitConstraints.
598 The same thing ensures that equality constraints in a lazy match
599 are not made available in the RHS of the match. For example
600 data T a where { T1 :: Int -> T Int; ... }
603 It's obviously not sound to refine a to Int in the right
604 hand side, because the arugment might not match T1 at all!
606 Finally, a lazy pattern should not bind any existential type variables
607 because they won't be in scope when we do the desugaring
610 %************************************************************************
612 Most of the work for constructors is here
613 (the rest is in the ConPatIn case of tc_pat)
615 %************************************************************************
617 [Pattern matching indexed data types]
618 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
619 Consider the following declarations:
621 data family Map k :: * -> *
622 data instance Map (a, b) v = MapPair (Map a (Pair b v))
624 and a case expression
626 case x :: Map (Int, c) w of MapPair m -> ...
628 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
629 worker/wrapper types for MapPair are
631 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
632 $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
634 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
635 :R123Map, which means the straight use of boxySplitTyConApp would give a type
636 error. Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
637 boxySplitTyConApp with the family tycon Map instead, which gives us the family
638 type list {(Int, c), w}. To get the correct split for :R123Map, we need to
639 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
640 (provided by tyConFamInst_maybe together with the family tycon). This
641 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
642 the split arguments for the representation tycon :R123Map as {Int, c, w}
644 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
646 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
648 moving between representation and family type into account. To produce type
649 correct Core, this coercion needs to be used to case the type of the scrutinee
650 from the family to the representation type. This is achieved by
651 unwrapFamInstScrutinee using a CoPat around the result pattern.
653 Now it might appear seem as if we could have used the previous GADT type
654 refinement infrastructure of refineAlt and friends instead of the explicit
655 unification and CoPat generation. However, that would be wrong. Why? The
656 whole point of GADT refinement is that the refinement is local to the case
657 alternative. In contrast, the substitution generated by the unification of
658 the family type list and instance types needs to be propagated to the outside.
659 Imagine that in the above example, the type of the scrutinee would have been
660 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
661 substitution [x -> (a, b), v -> w]. In contrast to GADT matching, the
662 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
663 alternatives of the case expression, whereas in the GADT case it might vary
664 between alternatives.
666 RIP GADT refinement: refinements have been replaced by the use of explicit
667 equality constraints that are used in conjunction with implication constraints
668 to express the local scope of GADT refinements.
672 -- MkT :: forall a b c. (a~[b]) => b -> c -> T a
673 -- with scrutinee of type (T ty)
675 tcConPat :: PatEnv -> Located Name
676 -> TcRhoType -- Type of the pattern
677 -> HsConPatDetails Name -> TcM a
679 tcConPat penv (L con_span con_name) pat_ty arg_pats thing_inside
680 = do { data_con <- tcLookupDataCon con_name
681 ; let tycon = dataConTyCon data_con
682 -- For data families this is the representation tycon
683 (univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _)
684 = dataConFullSig data_con
686 -- Instantiate the constructor type variables [a->ty]
687 -- This may involve doing a family-instance coercion,
688 -- and building a wrapper
689 ; (wrap, ctxt_res_tys) <- matchExpectedPatTy (matchExpectedConTy tycon) pat_ty
691 -- Add the stupid theta
692 ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
694 ; checkExistentials ex_tvs penv
695 ; let skol_info = case pe_ctxt penv of
696 LamPat mc -> PatSkol data_con mc
697 LetPat {} -> UnkSkol -- Doesn't matter
698 ; ex_tvs' <- tcInstSkolTyVars skol_info ex_tvs
699 -- Get location from monad, not from ex_tvs
701 ; let pat_ty' = mkTyConApp tycon ctxt_res_tys
702 -- pat_ty' is type of the actual constructor application
703 -- pat_ty' /= pat_ty iff coi /= IdCo
705 tenv = zipTopTvSubst (univ_tvs ++ ex_tvs)
706 (ctxt_res_tys ++ mkTyVarTys ex_tvs')
707 arg_tys' = substTys tenv arg_tys
708 full_theta = eq_theta ++ dict_theta
710 ; if null ex_tvs && null eq_spec && null full_theta
711 then do { -- The common case; no class bindings etc
712 -- (see Note [Arrows and patterns])
713 (arg_pats', res) <- tcConArgs data_con arg_tys'
714 arg_pats penv thing_inside
715 ; let res_pat = ConPatOut { pat_con = L con_span data_con,
716 pat_tvs = [], pat_dicts = [],
717 pat_binds = emptyTcEvBinds,
718 pat_args = arg_pats',
721 ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
723 else do -- The general case, with existential,
724 -- and local equality constraints
725 { let eq_preds = [mkEqPred (mkTyVarTy tv, ty) | (tv, ty) <- eq_spec]
726 theta' = substTheta tenv (eq_preds ++ full_theta)
727 -- order is *important* as we generate the list of
728 -- dictionary binders from theta'
729 no_equalities = not (any isEqPred theta')
731 ; gadts_on <- xoptM Opt_GADTs
732 ; checkTc (no_equalities || gadts_on)
733 (ptext (sLit "A pattern match on a GADT requires -XGADTs"))
734 -- Trac #2905 decided that a *pattern-match* of a GADT
735 -- should require the GADT language flag
737 ; given <- newEvVars theta'
738 ; let free_tvs = pe_res_tvs penv
739 -- Since we have done checkExistentials,
740 -- pe_res_tvs can only be Just at this point
742 -- Nor do we need pat_ty, because we've put all the
743 -- unification variables in right at the start when
744 -- initialising the PatEnv; and the pattern itself
745 -- only adds skolems.
747 ; (ev_binds, (arg_pats', res))
748 <- checkConstraints skol_info free_tvs ex_tvs' given $
749 tcConArgs data_con arg_tys' arg_pats penv thing_inside
751 ; let res_pat = ConPatOut { pat_con = L con_span data_con,
754 pat_binds = ev_binds,
755 pat_args = arg_pats',
757 ; return (mkHsWrapPat wrap res_pat pat_ty, res)
760 ----------------------------
761 matchExpectedPatTy :: (TcRhoType -> TcM (CoercionI, a))
762 -> TcRhoType -> TcM (HsWrapper, a)
763 -- See Note [Matching polytyped patterns]
764 -- Returns a wrapper : pat_ty ~ inner_ty
765 matchExpectedPatTy inner_match pat_ty
766 | null tvs && null theta
767 = do { (coi, res) <- inner_match pat_ty
768 ; return (coiToHsWrapper (mkSymCoI coi), res) }
769 -- The Sym is because the inner_match returns a coercion
770 -- that is the other way round to matchExpectedPatTy
773 = do { (_, tys, subst) <- tcInstTyVars tvs
774 ; wrap1 <- instCall PatOrigin tys (substTheta subst theta)
775 ; (wrap2, arg_tys) <- matchExpectedPatTy inner_match (substTy subst tau)
776 ; return (wrap2 <.> wrap1 , arg_tys) }
778 (tvs, theta, tau) = tcSplitSigmaTy pat_ty
780 ----------------------------
781 matchExpectedConTy :: TyCon -- The TyCon that this data
782 -- constructor actually returns
783 -> TcRhoType -- The type of the pattern
784 -> TcM (CoercionI, [TcSigmaType])
785 -- See Note [Matching constructor patterns]
786 -- Returns a coercion : T ty1 ... tyn ~ pat_ty
787 -- This is the same way round as matchExpectedListTy etc
788 -- but the other way round to matchExpectedPatTy
789 matchExpectedConTy data_tc pat_ty
790 | Just (fam_tc, fam_args, co_tc) <- tyConFamInstSig_maybe data_tc
791 -- Comments refer to Note [Matching constructor patterns]
792 -- co_tc :: forall a. T [a] ~ T7 a
793 = do { (_, tys, subst) <- tcInstTyVars (tyConTyVars data_tc)
796 ; coi1 <- unifyType (mkTyConApp fam_tc (substTys subst fam_args)) pat_ty
797 -- coi1 : T (ty1,ty2) ~ pat_ty
799 ; let coi2 = ACo (mkTyConApp co_tc tys)
800 -- coi2 : T (ty1,ty2) ~ T7 ty1 ty2
802 ; return (mkTransCoI (mkSymCoI coi2) coi1, tys) }
805 = matchExpectedTyConApp data_tc pat_ty
806 -- coi : T tys ~ pat_ty
810 Note [Matching constructor patterns]
811 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
812 Suppose (coi, tys) = matchExpectedConType data_tc pat_ty
814 * In the simple case, pat_ty = tc tys
816 * If pat_ty is a polytype, we want to instantiate it
817 This is like part of a subsumption check. Eg
818 f :: (forall a. [a]) -> blah
821 * In a type family case, suppose we have
823 data instance T (p,q) = A p | B q
824 Then we'll have internally generated
825 data T7 p q = A p | B q
826 axiom coT7 p q :: T (p,q) ~ T7 p q
828 So if pat_ty = T (ty1,ty2), we return (coi, [ty1,ty2]) such that
829 coi = coi2 . coi1 : T7 t ~ pat_ty
830 coi1 : T (ty1,ty2) ~ pat_ty
831 coi2 : T7 ty1 ty2 ~ T (ty1,ty2)
833 For families we do all this matching here, not in the unifier,
834 because we never want a whisper of the data_tycon to appear in
835 error messages; it's a purely internal thing
838 tcConArgs :: DataCon -> [TcSigmaType]
839 -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
841 tcConArgs data_con arg_tys (PrefixCon arg_pats) penv thing_inside
842 = do { checkTc (con_arity == no_of_args) -- Check correct arity
843 (arityErr "Constructor" data_con con_arity no_of_args)
844 ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
845 ; (arg_pats', res) <- tcMultiple tcConArg pats_w_tys
847 ; return (PrefixCon arg_pats', res) }
849 con_arity = dataConSourceArity data_con
850 no_of_args = length arg_pats
852 tcConArgs data_con arg_tys (InfixCon p1 p2) penv thing_inside
853 = do { checkTc (con_arity == 2) -- Check correct arity
854 (arityErr "Constructor" data_con con_arity 2)
855 ; let [arg_ty1,arg_ty2] = arg_tys -- This can't fail after the arity check
856 ; ([p1',p2'], res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
858 ; return (InfixCon p1' p2', res) }
860 con_arity = dataConSourceArity data_con
862 tcConArgs data_con arg_tys (RecCon (HsRecFields rpats dd)) penv thing_inside
863 = do { (rpats', res) <- tcMultiple tc_field rpats penv thing_inside
864 ; return (RecCon (HsRecFields rpats' dd), res) }
866 tc_field :: Checker (HsRecField FieldLabel (LPat Name)) (HsRecField TcId (LPat TcId))
867 tc_field (HsRecField field_lbl pat pun) penv thing_inside
868 = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
869 ; (pat', res) <- tcConArg (pat, pat_ty) penv thing_inside
870 ; return (HsRecField sel_id pat' pun, res) }
872 find_field_ty :: FieldLabel -> TcM (Id, TcType)
873 find_field_ty field_lbl
874 = case [ty | (f,ty) <- field_tys, f == field_lbl] of
876 -- No matching field; chances are this field label comes from some
877 -- other record type (or maybe none). As well as reporting an
878 -- error we still want to typecheck the pattern, principally to
879 -- make sure that all the variables it binds are put into the
880 -- environment, else the type checker crashes later:
881 -- f (R { foo = (a,b) }) = a+b
882 -- If foo isn't one of R's fields, we don't want to crash when
883 -- typechecking the "a+b".
884 [] -> do { addErrTc (badFieldCon data_con field_lbl)
885 ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
886 ; return (error "Bogus selector Id", bogus_ty) }
888 -- The normal case, when the field comes from the right constructor
890 ASSERT( null extras )
891 do { sel_id <- tcLookupField field_lbl
892 ; return (sel_id, pat_ty) }
894 field_tys :: [(FieldLabel, TcType)]
895 field_tys = zip (dataConFieldLabels data_con) arg_tys
896 -- Don't use zipEqual! If the constructor isn't really a record, then
897 -- dataConFieldLabels will be empty (and each field in the pattern
898 -- will generate an error below).
900 tcConArg :: Checker (LPat Name, TcSigmaType) (LPat Id)
901 tcConArg (arg_pat, arg_ty) penv thing_inside
902 = tc_lpat arg_pat arg_ty penv thing_inside
906 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
907 -- Instantiate the "stupid theta" of the data con, and throw
908 -- the constraints into the constraint set
909 addDataConStupidTheta data_con inst_tys
910 | null stupid_theta = return ()
911 | otherwise = instStupidTheta origin inst_theta
913 origin = OccurrenceOf (dataConName data_con)
914 -- The origin should always report "occurrence of C"
915 -- even when C occurs in a pattern
916 stupid_theta = dataConStupidTheta data_con
917 tenv = mkTopTvSubst (dataConUnivTyVars data_con `zip` inst_tys)
918 -- NB: inst_tys can be longer than the univ tyvars
919 -- because the constructor might have existentials
920 inst_theta = substTheta tenv stupid_theta
923 Note [Arrows and patterns]
924 ~~~~~~~~~~~~~~~~~~~~~~~~~~
925 (Oct 07) Arrow noation has the odd property that it involves
926 "holes in the scope". For example:
927 expr :: Arrow a => a () Int
928 expr = proc (y,z) -> do
932 Here the 'proc (y,z)' binding scopes over the arrow tails but not the
933 arrow body (e.g 'term'). As things stand (bogusly) all the
934 constraints from the proc body are gathered together, so constraints
935 from 'term' will be seen by the tcPat for (y,z). But we must *not*
936 bind constraints from 'term' here, becuase the desugarer will not make
937 these bindings scope over 'term'.
939 The Right Thing is not to confuse these constraints together. But for
940 now the Easy Thing is to ensure that we do not have existential or
941 GADT constraints in a 'proc', and to short-cut the constraint
942 simplification for such vanilla patterns so that it binds no
943 constraints. Hence the 'fast path' in tcConPat; but it's also a good
944 plan for ordinary vanilla patterns to bypass the constraint
947 %************************************************************************
949 Note [Pattern coercions]
951 %************************************************************************
953 In principle, these program would be reasonable:
955 f :: (forall a. a->a) -> Int
956 f (x :: Int->Int) = x 3
958 g :: (forall a. [a]) -> Bool
961 In both cases, the function type signature restricts what arguments can be passed
962 in a call (to polymorphic ones). The pattern type signature then instantiates this
963 type. For example, in the first case, (forall a. a->a) <= Int -> Int, and we
964 generate the translated term
965 f = \x' :: (forall a. a->a). let x = x' Int in x 3
967 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
968 And it requires a significant amount of code to implement, becuase we need to decorate
969 the translated pattern with coercion functions (generated from the subsumption check
972 So for now I'm just insisting on type *equality* in patterns. No subsumption.
974 Old notes about desugaring, at a time when pattern coercions were handled:
976 A SigPat is a type coercion and must be handled one at at time. We can't
977 combine them unless the type of the pattern inside is identical, and we don't
978 bother to check for that. For example:
980 data T = T1 Int | T2 Bool
981 f :: (forall a. a -> a) -> T -> t
982 f (g::Int->Int) (T1 i) = T1 (g i)
983 f (g::Bool->Bool) (T2 b) = T2 (g b)
985 We desugar this as follows:
987 f = \ g::(forall a. a->a) t::T ->
989 in case t of { T1 i -> T1 (gi i)
992 in case t of { T2 b -> T2 (gb b)
995 Note that we do not treat the first column of patterns as a
996 column of variables, because the coerced variables (gi, gb)
997 would be of different types. So we get rather grotty code.
998 But I don't think this is a common case, and if it was we could
999 doubtless improve it.
1001 Meanwhile, the strategy is:
1002 * treat each SigPat coercion (always non-identity coercions)
1004 * deal with the stuff inside, and then wrap a binding round
1005 the result to bind the new variable (gi, gb, etc)
1008 %************************************************************************
1010 \subsection{Errors and contexts}
1012 %************************************************************************
1014 {- This was used to improve the error message from
1015 an existential escape. Need to think how to do this.
1017 sigPatCtxt :: [LPat Var] -> [Var] -> [TcType] -> TcType -> TidyEnv
1018 -> TcM (TidyEnv, SDoc)
1019 sigPatCtxt pats bound_tvs pat_tys body_ty tidy_env
1020 = do { pat_tys' <- mapM zonkTcType pat_tys
1021 ; body_ty' <- zonkTcType body_ty
1022 ; let (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
1023 (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
1024 (env3, tidy_body_ty) = tidyOpenType env2 body_ty'
1026 sep [ptext (sLit "When checking an existential match that binds"),
1027 nest 2 (vcat (zipWith ppr_id show_ids tidy_tys)),
1028 ptext (sLit "The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
1029 ptext (sLit "The body has type:") <+> ppr tidy_body_ty
1032 bound_ids = collectPatsBinders pats
1033 show_ids = filter is_interesting bound_ids
1034 is_interesting id = any (`elemVarSet` varTypeTyVars id) bound_tvs
1036 ppr_id id ty = ppr id <+> dcolon <+> ppr ty
1037 -- Don't zonk the types so we get the separate, un-unified versions
1041 patCtxt :: Pat Name -> Maybe Message -- Not all patterns are worth pushing a context
1042 patCtxt (VarPat _) = Nothing
1043 patCtxt (ParPat _) = Nothing
1044 patCtxt (AsPat _ _) = Nothing
1045 patCtxt pat = Just (hang (ptext (sLit "In the pattern:"))
1048 -----------------------------------------------
1049 checkExistentials :: [TyVar] -> PatEnv -> TcM ()
1050 -- See Note [Arrows and patterns]
1051 checkExistentials [] _ = return ()
1052 checkExistentials _ (PE { pe_ctxt = LetPat {}}) = failWithTc existentialLetPat
1053 checkExistentials _ (PE { pe_ctxt = LamPat ProcExpr }) = failWithTc existentialProcPat
1054 checkExistentials _ (PE { pe_lazy = True }) = failWithTc existentialLazyPat
1055 checkExistentials _ _ = return ()
1057 existentialLazyPat :: SDoc
1059 = hang (ptext (sLit "An existential or GADT data constructor cannot be used"))
1060 2 (ptext (sLit "inside a lazy (~) pattern"))
1062 existentialProcPat :: SDoc
1064 = ptext (sLit "Proc patterns cannot use existential or GADT data constructors")
1066 existentialLetPat :: SDoc
1068 = vcat [text "My brain just exploded",
1069 text "I can't handle pattern bindings for existential or GADT data constructors.",
1070 text "Instead, use a case-expression, or do-notation, to unpack the constructor."]
1072 badFieldCon :: DataCon -> Name -> SDoc
1073 badFieldCon con field
1074 = hsep [ptext (sLit "Constructor") <+> quotes (ppr con),
1075 ptext (sLit "does not have field"), quotes (ppr field)]
1077 polyPatSig :: TcType -> SDoc
1079 = hang (ptext (sLit "Illegal polymorphic type signature in pattern:"))
1082 badTypePat :: Pat Name -> SDoc
1083 badTypePat pat = ptext (sLit "Illegal type pattern") <+> ppr pat
1085 lazyUnliftedPatErr :: OutputableBndr name => Pat name -> TcM ()
1086 lazyUnliftedPatErr pat
1088 hang (ptext (sLit "A lazy (~) pattern cannot contain unlifted types:"))
1091 unboxedTupleErr :: SDoc -> Type -> SDoc
1092 unboxedTupleErr what ty
1093 = hang (what <+> ptext (sLit "cannot have an unboxed tuple type:"))