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) <- captureConstraints 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 captureConstraints thing_inside
414 -- Ignore refined penv', revert to penv
416 ; emitConstraints pat_ct
417 -- captureConstraints/extendConstraints:
418 -- see Note [Hopping the LIE in lazy patterns]
420 -- Check there are no unlifted types under the lazy pattern
421 ; when (any (isUnLiftedType . idType) $ collectPatBinders pat') $
422 lazyUnliftedPatErr lpat
424 -- Check that the expected pattern type is itself lifted
425 ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
426 ; _ <- unifyType pat_ty pat_ty'
428 ; return (LazyPat pat', res) }
430 tc_pat _ p@(QuasiQuotePat _) _ _
431 = pprPanic "Should never see QuasiQuotePat in type checker" (ppr p)
433 tc_pat _ (WildPat _) pat_ty thing_inside
434 = do { checkUnboxedTuple pat_ty $
435 ptext (sLit "A wild-card pattern")
436 ; res <- thing_inside
437 ; return (WildPat pat_ty, res) }
439 tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
440 = do { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
441 ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
442 tc_lpat pat (idType bndr_id) penv thing_inside
443 -- NB: if we do inference on:
444 -- \ (y@(x::forall a. a->a)) = e
445 -- we'll fail. The as-pattern infers a monotype for 'y', which then
446 -- fails to unify with the polymorphic type for 'x'. This could
447 -- perhaps be fixed, but only with a bit more work.
449 -- If you fix it, don't forget the bindInstsOfPatIds!
450 ; return (mkHsWrapPatCoI coi (AsPat (L nm_loc bndr_id) pat') pat_ty, res) }
452 tc_pat penv vpat@(ViewPat expr pat _) overall_pat_ty thing_inside
453 = do { checkUnboxedTuple overall_pat_ty $
454 ptext (sLit "The view pattern") <+> ppr vpat
456 -- Morally, expr must have type `forall a1...aN. OPT' -> B`
457 -- where overall_pat_ty is an instance of OPT'.
458 -- Here, we infer a rho type for it,
459 -- which replaces the leading foralls and constraints
460 -- with fresh unification variables.
461 ; (expr',expr'_inferred) <- tcInferRho expr
463 -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
464 -- NOTE: this forces pat_ty to be a monotype (because we use a unification
465 -- variable to find it). this means that in an example like
466 -- (view -> f) where view :: _ -> forall b. b
467 -- we will only be able to use view at one instantation in the
469 ; (expr_coi, pat_ty) <- tcInfer $ \ pat_ty ->
470 unifyPatType expr'_inferred (mkFunTy overall_pat_ty pat_ty)
472 -- pattern must have pat_ty
473 ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside
475 ; return (ViewPat (mkLHsWrapCoI expr_coi expr') pat' overall_pat_ty, res) }
477 -- Type signatures in patterns
478 -- See Note [Pattern coercions] below
479 tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
480 = do { (inner_ty, tv_binds, wrap) <- tcPatSig (patSigCtxt penv) sig_ty pat_ty
481 ; (pat', res) <- tcExtendTyVarEnv2 tv_binds $
482 tc_lpat pat inner_ty penv thing_inside
484 ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
486 tc_pat _ pat@(TypePat _) _ _
487 = failWithTc (badTypePat pat)
489 ------------------------
490 -- Lists, tuples, arrays
491 tc_pat penv (ListPat pats _) pat_ty thing_inside
492 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy pat_ty
493 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
494 pats penv thing_inside
495 ; return (mkHsWrapPat coi (ListPat pats' elt_ty) pat_ty, res)
498 tc_pat penv (PArrPat pats _) pat_ty thing_inside
499 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTy pat_ty
500 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
501 pats penv thing_inside
502 ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
505 tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
506 = do { let tc = tupleTyCon boxity (length pats)
507 ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc) pat_ty
508 ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
510 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
511 -- so that we can experiment with lazy tuple-matching.
512 -- This is a pretty odd place to make the switch, but
513 -- it was easy to do.
514 ; let pat_ty' = mkTyConApp tc arg_tys
515 -- pat_ty /= pat_ty iff coi /= IdCo
516 unmangled_result = TuplePat pats' boxity pat_ty'
517 possibly_mangled_result
518 | opt_IrrefutableTuples &&
519 isBoxed boxity = LazyPat (noLoc unmangled_result)
520 | otherwise = unmangled_result
522 ; ASSERT( length arg_tys == length pats ) -- Syntactically enforced
523 return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
526 ------------------------
528 tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
529 = tcConPat penv con pat_ty arg_pats thing_inside
531 ------------------------
533 tc_pat _ (LitPat simple_lit) pat_ty thing_inside
534 = do { let lit_ty = hsLitType simple_lit
535 ; coi <- unifyPatType lit_ty pat_ty
536 -- coi is of kind: pat_ty ~ lit_ty
537 ; res <- thing_inside
538 ; return ( mkHsWrapPatCoI coi (LitPat simple_lit) pat_ty
541 ------------------------
542 -- Overloaded patterns: n, and n+k
543 tc_pat _ (NPat over_lit mb_neg eq) pat_ty thing_inside
544 = do { let orig = LiteralOrigin over_lit
545 ; lit' <- newOverloadedLit orig over_lit pat_ty
546 ; eq' <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
547 ; mb_neg' <- case mb_neg of
548 Nothing -> return Nothing -- Positive literal
549 Just neg -> -- Negative literal
550 -- The 'negate' is re-mappable syntax
551 do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
552 ; return (Just neg') }
553 ; res <- thing_inside
554 ; return (NPat lit' mb_neg' eq', res) }
556 tc_pat penv (NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
557 = do { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
558 ; let pat_ty' = idType bndr_id
559 orig = LiteralOrigin lit
560 ; lit' <- newOverloadedLit orig lit pat_ty'
562 -- The '>=' and '-' parts are re-mappable syntax
563 ; ge' <- tcSyntaxOp orig ge (mkFunTys [pat_ty', pat_ty'] boolTy)
564 ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
565 ; let pat' = NPlusKPat (L nm_loc bndr_id) lit' ge' minus'
567 -- The Report says that n+k patterns must be in Integral
568 -- We may not want this when using re-mappable syntax, though (ToDo?)
569 ; icls <- tcLookupClass integralClassName
570 ; instStupidTheta orig [mkClassPred icls [pat_ty']]
572 ; res <- tcExtendIdEnv1 name bndr_id thing_inside
573 ; return (mkHsWrapPatCoI coi pat' pat_ty, res) }
575 tc_pat _ _other_pat _ _ = panic "tc_pat" -- ConPatOut, SigPatOut, VarPatOut
578 unifyPatType :: TcType -> TcType -> TcM CoercionI
579 -- In patterns we want a coercion from the
580 -- context type (expected) to the actual pattern type
581 -- But we don't want to reverse the args to unifyType because
582 -- that controls the actual/expected stuff in error messages
583 unifyPatType actual_ty expected_ty
584 = do { coi <- unifyType actual_ty expected_ty
585 ; return (mkSymCoI coi) }
588 Note [Hopping the LIE in lazy patterns]
589 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
590 In a lazy pattern, we must *not* discharge constraints from the RHS
591 from dictionaries bound in the pattern. E.g.
593 We can't discharge the Num constraint from dictionaries bound by
596 So we have to make the constraints from thing_inside "hop around"
597 the pattern. Hence the captureConstraints and emitConstraints.
599 The same thing ensures that equality constraints in a lazy match
600 are not made available in the RHS of the match. For example
601 data T a where { T1 :: Int -> T Int; ... }
604 It's obviously not sound to refine a to Int in the right
605 hand side, because the arugment might not match T1 at all!
607 Finally, a lazy pattern should not bind any existential type variables
608 because they won't be in scope when we do the desugaring
611 %************************************************************************
613 Most of the work for constructors is here
614 (the rest is in the ConPatIn case of tc_pat)
616 %************************************************************************
618 [Pattern matching indexed data types]
619 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
620 Consider the following declarations:
622 data family Map k :: * -> *
623 data instance Map (a, b) v = MapPair (Map a (Pair b v))
625 and a case expression
627 case x :: Map (Int, c) w of MapPair m -> ...
629 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
630 worker/wrapper types for MapPair are
632 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
633 $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
635 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
636 :R123Map, which means the straight use of boxySplitTyConApp would give a type
637 error. Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
638 boxySplitTyConApp with the family tycon Map instead, which gives us the family
639 type list {(Int, c), w}. To get the correct split for :R123Map, we need to
640 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
641 (provided by tyConFamInst_maybe together with the family tycon). This
642 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
643 the split arguments for the representation tycon :R123Map as {Int, c, w}
645 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
647 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
649 moving between representation and family type into account. To produce type
650 correct Core, this coercion needs to be used to case the type of the scrutinee
651 from the family to the representation type. This is achieved by
652 unwrapFamInstScrutinee using a CoPat around the result pattern.
654 Now it might appear seem as if we could have used the previous GADT type
655 refinement infrastructure of refineAlt and friends instead of the explicit
656 unification and CoPat generation. However, that would be wrong. Why? The
657 whole point of GADT refinement is that the refinement is local to the case
658 alternative. In contrast, the substitution generated by the unification of
659 the family type list and instance types needs to be propagated to the outside.
660 Imagine that in the above example, the type of the scrutinee would have been
661 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
662 substitution [x -> (a, b), v -> w]. In contrast to GADT matching, the
663 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
664 alternatives of the case expression, whereas in the GADT case it might vary
665 between alternatives.
667 RIP GADT refinement: refinements have been replaced by the use of explicit
668 equality constraints that are used in conjunction with implication constraints
669 to express the local scope of GADT refinements.
673 -- MkT :: forall a b c. (a~[b]) => b -> c -> T a
674 -- with scrutinee of type (T ty)
676 tcConPat :: PatEnv -> Located Name
677 -> TcRhoType -- Type of the pattern
678 -> HsConPatDetails Name -> TcM a
680 tcConPat penv (L con_span con_name) pat_ty arg_pats thing_inside
681 = do { data_con <- tcLookupDataCon con_name
682 ; let tycon = dataConTyCon data_con
683 -- For data families this is the representation tycon
684 (univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _)
685 = dataConFullSig data_con
687 -- Instantiate the constructor type variables [a->ty]
688 -- This may involve doing a family-instance coercion,
689 -- and building a wrapper
690 ; (wrap, ctxt_res_tys) <- matchExpectedPatTy (matchExpectedConTy tycon) pat_ty
692 -- Add the stupid theta
693 ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
695 ; checkExistentials ex_tvs penv
696 ; let skol_info = case pe_ctxt penv of
697 LamPat mc -> PatSkol data_con mc
698 LetPat {} -> UnkSkol -- Doesn't matter
699 ; ex_tvs' <- tcInstSkolTyVars skol_info ex_tvs
700 -- Get location from monad, not from ex_tvs
702 ; let pat_ty' = mkTyConApp tycon ctxt_res_tys
703 -- pat_ty' is type of the actual constructor application
704 -- pat_ty' /= pat_ty iff coi /= IdCo
706 tenv = zipTopTvSubst (univ_tvs ++ ex_tvs)
707 (ctxt_res_tys ++ mkTyVarTys ex_tvs')
708 arg_tys' = substTys tenv arg_tys
709 full_theta = eq_theta ++ dict_theta
711 ; if null ex_tvs && null eq_spec && null full_theta
712 then do { -- The common case; no class bindings etc
713 -- (see Note [Arrows and patterns])
714 (arg_pats', res) <- tcConArgs data_con arg_tys'
715 arg_pats penv thing_inside
716 ; let res_pat = ConPatOut { pat_con = L con_span data_con,
717 pat_tvs = [], pat_dicts = [],
718 pat_binds = emptyTcEvBinds,
719 pat_args = arg_pats',
722 ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
724 else do -- The general case, with existential,
725 -- and local equality constraints
726 { let eq_preds = [mkEqPred (mkTyVarTy tv, ty) | (tv, ty) <- eq_spec]
727 theta' = substTheta tenv (eq_preds ++ full_theta)
728 -- order is *important* as we generate the list of
729 -- dictionary binders from theta'
730 no_equalities = not (any isEqPred theta')
732 ; gadts_on <- xoptM Opt_GADTs
733 ; checkTc (no_equalities || gadts_on)
734 (ptext (sLit "A pattern match on a GADT requires -XGADTs"))
735 -- Trac #2905 decided that a *pattern-match* of a GADT
736 -- should require the GADT language flag
738 ; given <- newEvVars theta'
739 ; let free_tvs = pe_res_tvs penv
740 -- Since we have done checkExistentials,
741 -- pe_res_tvs can only be Just at this point
743 -- Nor do we need pat_ty, because we've put all the
744 -- unification variables in right at the start when
745 -- initialising the PatEnv; and the pattern itself
746 -- only adds skolems.
748 ; (ev_binds, (arg_pats', res))
749 <- checkConstraints skol_info free_tvs ex_tvs' given $
750 tcConArgs data_con arg_tys' arg_pats penv thing_inside
752 ; let res_pat = ConPatOut { pat_con = L con_span data_con,
755 pat_binds = ev_binds,
756 pat_args = arg_pats',
758 ; return (mkHsWrapPat wrap res_pat pat_ty, res)
761 ----------------------------
762 matchExpectedPatTy :: (TcRhoType -> TcM (CoercionI, a))
763 -> TcRhoType -> TcM (HsWrapper, a)
764 -- See Note [Matching polytyped patterns]
765 -- Returns a wrapper : pat_ty ~ inner_ty
766 matchExpectedPatTy inner_match pat_ty
767 | null tvs && null theta
768 = do { (coi, res) <- inner_match pat_ty
769 ; return (coiToHsWrapper (mkSymCoI coi), res) }
770 -- The Sym is because the inner_match returns a coercion
771 -- that is the other way round to matchExpectedPatTy
774 = do { (_, tys, subst) <- tcInstTyVars tvs
775 ; wrap1 <- instCall PatOrigin tys (substTheta subst theta)
776 ; (wrap2, arg_tys) <- matchExpectedPatTy inner_match (substTy subst tau)
777 ; return (wrap2 <.> wrap1 , arg_tys) }
779 (tvs, theta, tau) = tcSplitSigmaTy pat_ty
781 ----------------------------
782 matchExpectedConTy :: TyCon -- The TyCon that this data
783 -- constructor actually returns
784 -> TcRhoType -- The type of the pattern
785 -> TcM (CoercionI, [TcSigmaType])
786 -- See Note [Matching constructor patterns]
787 -- Returns a coercion : T ty1 ... tyn ~ pat_ty
788 -- This is the same way round as matchExpectedListTy etc
789 -- but the other way round to matchExpectedPatTy
790 matchExpectedConTy data_tc pat_ty
791 | Just (fam_tc, fam_args, co_tc) <- tyConFamInstSig_maybe data_tc
792 -- Comments refer to Note [Matching constructor patterns]
793 -- co_tc :: forall a. T [a] ~ T7 a
794 = do { (_, tys, subst) <- tcInstTyVars (tyConTyVars data_tc)
797 ; coi1 <- unifyType (mkTyConApp fam_tc (substTys subst fam_args)) pat_ty
798 -- coi1 : T (ty1,ty2) ~ pat_ty
800 ; let coi2 = ACo (mkTyConApp co_tc tys)
801 -- coi2 : T (ty1,ty2) ~ T7 ty1 ty2
803 ; return (mkTransCoI (mkSymCoI coi2) coi1, tys) }
806 = matchExpectedTyConApp data_tc pat_ty
807 -- coi : T tys ~ pat_ty
811 Note [Matching constructor patterns]
812 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
813 Suppose (coi, tys) = matchExpectedConType data_tc pat_ty
815 * In the simple case, pat_ty = tc tys
817 * If pat_ty is a polytype, we want to instantiate it
818 This is like part of a subsumption check. Eg
819 f :: (forall a. [a]) -> blah
822 * In a type family case, suppose we have
824 data instance T (p,q) = A p | B q
825 Then we'll have internally generated
826 data T7 p q = A p | B q
827 axiom coT7 p q :: T (p,q) ~ T7 p q
829 So if pat_ty = T (ty1,ty2), we return (coi, [ty1,ty2]) such that
830 coi = coi2 . coi1 : T7 t ~ pat_ty
831 coi1 : T (ty1,ty2) ~ pat_ty
832 coi2 : T7 ty1 ty2 ~ T (ty1,ty2)
834 For families we do all this matching here, not in the unifier,
835 because we never want a whisper of the data_tycon to appear in
836 error messages; it's a purely internal thing
839 tcConArgs :: DataCon -> [TcSigmaType]
840 -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
842 tcConArgs data_con arg_tys (PrefixCon arg_pats) penv thing_inside
843 = do { checkTc (con_arity == no_of_args) -- Check correct arity
844 (arityErr "Constructor" data_con con_arity no_of_args)
845 ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
846 ; (arg_pats', res) <- tcMultiple tcConArg pats_w_tys
848 ; return (PrefixCon arg_pats', res) }
850 con_arity = dataConSourceArity data_con
851 no_of_args = length arg_pats
853 tcConArgs data_con arg_tys (InfixCon p1 p2) penv thing_inside
854 = do { checkTc (con_arity == 2) -- Check correct arity
855 (arityErr "Constructor" data_con con_arity 2)
856 ; let [arg_ty1,arg_ty2] = arg_tys -- This can't fail after the arity check
857 ; ([p1',p2'], res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
859 ; return (InfixCon p1' p2', res) }
861 con_arity = dataConSourceArity data_con
863 tcConArgs data_con arg_tys (RecCon (HsRecFields rpats dd)) penv thing_inside
864 = do { (rpats', res) <- tcMultiple tc_field rpats penv thing_inside
865 ; return (RecCon (HsRecFields rpats' dd), res) }
867 tc_field :: Checker (HsRecField FieldLabel (LPat Name)) (HsRecField TcId (LPat TcId))
868 tc_field (HsRecField field_lbl pat pun) penv thing_inside
869 = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
870 ; (pat', res) <- tcConArg (pat, pat_ty) penv thing_inside
871 ; return (HsRecField sel_id pat' pun, res) }
873 find_field_ty :: FieldLabel -> TcM (Id, TcType)
874 find_field_ty field_lbl
875 = case [ty | (f,ty) <- field_tys, f == field_lbl] of
877 -- No matching field; chances are this field label comes from some
878 -- other record type (or maybe none). As well as reporting an
879 -- error we still want to typecheck the pattern, principally to
880 -- make sure that all the variables it binds are put into the
881 -- environment, else the type checker crashes later:
882 -- f (R { foo = (a,b) }) = a+b
883 -- If foo isn't one of R's fields, we don't want to crash when
884 -- typechecking the "a+b".
885 [] -> do { addErrTc (badFieldCon data_con field_lbl)
886 ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
887 ; return (error "Bogus selector Id", bogus_ty) }
889 -- The normal case, when the field comes from the right constructor
891 ASSERT( null extras )
892 do { sel_id <- tcLookupField field_lbl
893 ; return (sel_id, pat_ty) }
895 field_tys :: [(FieldLabel, TcType)]
896 field_tys = zip (dataConFieldLabels data_con) arg_tys
897 -- Don't use zipEqual! If the constructor isn't really a record, then
898 -- dataConFieldLabels will be empty (and each field in the pattern
899 -- will generate an error below).
901 tcConArg :: Checker (LPat Name, TcSigmaType) (LPat Id)
902 tcConArg (arg_pat, arg_ty) penv thing_inside
903 = tc_lpat arg_pat arg_ty penv thing_inside
907 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
908 -- Instantiate the "stupid theta" of the data con, and throw
909 -- the constraints into the constraint set
910 addDataConStupidTheta data_con inst_tys
911 | null stupid_theta = return ()
912 | otherwise = instStupidTheta origin inst_theta
914 origin = OccurrenceOf (dataConName data_con)
915 -- The origin should always report "occurrence of C"
916 -- even when C occurs in a pattern
917 stupid_theta = dataConStupidTheta data_con
918 tenv = mkTopTvSubst (dataConUnivTyVars data_con `zip` inst_tys)
919 -- NB: inst_tys can be longer than the univ tyvars
920 -- because the constructor might have existentials
921 inst_theta = substTheta tenv stupid_theta
924 Note [Arrows and patterns]
925 ~~~~~~~~~~~~~~~~~~~~~~~~~~
926 (Oct 07) Arrow noation has the odd property that it involves
927 "holes in the scope". For example:
928 expr :: Arrow a => a () Int
929 expr = proc (y,z) -> do
933 Here the 'proc (y,z)' binding scopes over the arrow tails but not the
934 arrow body (e.g 'term'). As things stand (bogusly) all the
935 constraints from the proc body are gathered together, so constraints
936 from 'term' will be seen by the tcPat for (y,z). But we must *not*
937 bind constraints from 'term' here, becuase the desugarer will not make
938 these bindings scope over 'term'.
940 The Right Thing is not to confuse these constraints together. But for
941 now the Easy Thing is to ensure that we do not have existential or
942 GADT constraints in a 'proc', and to short-cut the constraint
943 simplification for such vanilla patterns so that it binds no
944 constraints. Hence the 'fast path' in tcConPat; but it's also a good
945 plan for ordinary vanilla patterns to bypass the constraint
948 %************************************************************************
950 Note [Pattern coercions]
952 %************************************************************************
954 In principle, these program would be reasonable:
956 f :: (forall a. a->a) -> Int
957 f (x :: Int->Int) = x 3
959 g :: (forall a. [a]) -> Bool
962 In both cases, the function type signature restricts what arguments can be passed
963 in a call (to polymorphic ones). The pattern type signature then instantiates this
964 type. For example, in the first case, (forall a. a->a) <= Int -> Int, and we
965 generate the translated term
966 f = \x' :: (forall a. a->a). let x = x' Int in x 3
968 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
969 And it requires a significant amount of code to implement, becuase we need to decorate
970 the translated pattern with coercion functions (generated from the subsumption check
973 So for now I'm just insisting on type *equality* in patterns. No subsumption.
975 Old notes about desugaring, at a time when pattern coercions were handled:
977 A SigPat is a type coercion and must be handled one at at time. We can't
978 combine them unless the type of the pattern inside is identical, and we don't
979 bother to check for that. For example:
981 data T = T1 Int | T2 Bool
982 f :: (forall a. a -> a) -> T -> t
983 f (g::Int->Int) (T1 i) = T1 (g i)
984 f (g::Bool->Bool) (T2 b) = T2 (g b)
986 We desugar this as follows:
988 f = \ g::(forall a. a->a) t::T ->
990 in case t of { T1 i -> T1 (gi i)
993 in case t of { T2 b -> T2 (gb b)
996 Note that we do not treat the first column of patterns as a
997 column of variables, because the coerced variables (gi, gb)
998 would be of different types. So we get rather grotty code.
999 But I don't think this is a common case, and if it was we could
1000 doubtless improve it.
1002 Meanwhile, the strategy is:
1003 * treat each SigPat coercion (always non-identity coercions)
1005 * deal with the stuff inside, and then wrap a binding round
1006 the result to bind the new variable (gi, gb, etc)
1009 %************************************************************************
1011 \subsection{Errors and contexts}
1013 %************************************************************************
1015 {- This was used to improve the error message from
1016 an existential escape. Need to think how to do this.
1018 sigPatCtxt :: [LPat Var] -> [Var] -> [TcType] -> TcType -> TidyEnv
1019 -> TcM (TidyEnv, SDoc)
1020 sigPatCtxt pats bound_tvs pat_tys body_ty tidy_env
1021 = do { pat_tys' <- mapM zonkTcType pat_tys
1022 ; body_ty' <- zonkTcType body_ty
1023 ; let (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
1024 (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
1025 (env3, tidy_body_ty) = tidyOpenType env2 body_ty'
1027 sep [ptext (sLit "When checking an existential match that binds"),
1028 nest 2 (vcat (zipWith ppr_id show_ids tidy_tys)),
1029 ptext (sLit "The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
1030 ptext (sLit "The body has type:") <+> ppr tidy_body_ty
1033 bound_ids = collectPatsBinders pats
1034 show_ids = filter is_interesting bound_ids
1035 is_interesting id = any (`elemVarSet` varTypeTyVars id) bound_tvs
1037 ppr_id id ty = ppr id <+> dcolon <+> ppr ty
1038 -- Don't zonk the types so we get the separate, un-unified versions
1042 patCtxt :: Pat Name -> Maybe Message -- Not all patterns are worth pushing a context
1043 patCtxt (VarPat _) = Nothing
1044 patCtxt (ParPat _) = Nothing
1045 patCtxt (AsPat _ _) = Nothing
1046 patCtxt pat = Just (hang (ptext (sLit "In the pattern:"))
1049 -----------------------------------------------
1050 checkExistentials :: [TyVar] -> PatEnv -> TcM ()
1051 -- See Note [Arrows and patterns]
1052 checkExistentials [] _ = return ()
1053 checkExistentials _ (PE { pe_ctxt = LetPat {}}) = failWithTc existentialLetPat
1054 checkExistentials _ (PE { pe_ctxt = LamPat ProcExpr }) = failWithTc existentialProcPat
1055 checkExistentials _ (PE { pe_lazy = True }) = failWithTc existentialLazyPat
1056 checkExistentials _ _ = return ()
1058 existentialLazyPat :: SDoc
1060 = hang (ptext (sLit "An existential or GADT data constructor cannot be used"))
1061 2 (ptext (sLit "inside a lazy (~) pattern"))
1063 existentialProcPat :: SDoc
1065 = ptext (sLit "Proc patterns cannot use existential or GADT data constructors")
1067 existentialLetPat :: SDoc
1069 = vcat [text "My brain just exploded",
1070 text "I can't handle pattern bindings for existential or GADT data constructors.",
1071 text "Instead, use a case-expression, or do-notation, to unpack the constructor."]
1073 badFieldCon :: DataCon -> Name -> SDoc
1074 badFieldCon con field
1075 = hsep [ptext (sLit "Constructor") <+> quotes (ppr con),
1076 ptext (sLit "does not have field"), quotes (ppr field)]
1078 polyPatSig :: TcType -> SDoc
1080 = hang (ptext (sLit "Illegal polymorphic type signature in pattern:"))
1083 badTypePat :: Pat Name -> SDoc
1084 badTypePat pat = ptext (sLit "Illegal type pattern") <+> ppr pat
1086 lazyUnliftedPatErr :: OutputableBndr name => Pat name -> TcM ()
1087 lazyUnliftedPatErr pat
1089 hang (ptext (sLit "A lazy (~) pattern cannot contain unlifted types:"))
1092 unboxedTupleErr :: SDoc -> Type -> SDoc
1093 unboxedTupleErr what ty
1094 = hang (what <+> ptext (sLit "cannot have an unboxed tuple type:"))