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 <+> pprThetaArrowTy 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 (Coercion, 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 (mkReflCo 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 (mkReflCo 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 (mkHsWrapPatCo 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 (mkHsWrapPatCo 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 (mkLHsWrapCo 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 tc_pat _ pat@(TypePat _) _ _
463 = failWithTc (badTypePat pat)
465 ------------------------
466 -- Lists, tuples, arrays
467 tc_pat penv (ListPat pats _) pat_ty thing_inside
468 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy pat_ty
469 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
470 pats penv thing_inside
471 ; return (mkHsWrapPat coi (ListPat pats' elt_ty) pat_ty, res)
474 tc_pat penv (PArrPat pats _) pat_ty thing_inside
475 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTy pat_ty
476 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
477 pats penv thing_inside
478 ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
481 tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
482 = do { let tc = tupleTyCon boxity (length pats)
483 ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc) pat_ty
484 ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
486 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
487 -- so that we can experiment with lazy tuple-matching.
488 -- This is a pretty odd place to make the switch, but
489 -- it was easy to do.
490 ; let pat_ty' = mkTyConApp tc arg_tys
491 -- pat_ty /= pat_ty iff coi /= IdCo
492 unmangled_result = TuplePat pats' boxity pat_ty'
493 possibly_mangled_result
494 | opt_IrrefutableTuples &&
495 isBoxed boxity = LazyPat (noLoc unmangled_result)
496 | otherwise = unmangled_result
498 ; ASSERT( length arg_tys == length pats ) -- Syntactically enforced
499 return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
502 ------------------------
504 tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
505 = tcConPat penv con pat_ty arg_pats thing_inside
507 ------------------------
509 tc_pat _ (LitPat simple_lit) pat_ty thing_inside
510 = do { let lit_ty = hsLitType simple_lit
511 ; coi <- unifyPatType lit_ty pat_ty
512 -- coi is of kind: pat_ty ~ lit_ty
513 ; res <- thing_inside
514 ; return ( mkHsWrapPatCo coi (LitPat simple_lit) pat_ty
517 ------------------------
518 -- Overloaded patterns: n, and n+k
519 tc_pat _ (NPat over_lit mb_neg eq) pat_ty thing_inside
520 = do { let orig = LiteralOrigin over_lit
521 ; lit' <- newOverloadedLit orig over_lit pat_ty
522 ; eq' <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
523 ; mb_neg' <- case mb_neg of
524 Nothing -> return Nothing -- Positive literal
525 Just neg -> -- Negative literal
526 -- The 'negate' is re-mappable syntax
527 do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
528 ; return (Just neg') }
529 ; res <- thing_inside
530 ; return (NPat lit' mb_neg' eq', res) }
532 tc_pat penv (NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
533 = do { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
534 ; let pat_ty' = idType bndr_id
535 orig = LiteralOrigin lit
536 ; lit' <- newOverloadedLit orig lit pat_ty'
538 -- The '>=' and '-' parts are re-mappable syntax
539 ; ge' <- tcSyntaxOp orig ge (mkFunTys [pat_ty', pat_ty'] boolTy)
540 ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
541 ; let pat' = NPlusKPat (L nm_loc bndr_id) lit' ge' minus'
543 -- The Report says that n+k patterns must be in Integral
544 -- We may not want this when using re-mappable syntax, though (ToDo?)
545 ; icls <- tcLookupClass integralClassName
546 ; instStupidTheta orig [mkClassPred icls [pat_ty']]
548 ; res <- tcExtendIdEnv1 name bndr_id thing_inside
549 ; return (mkHsWrapPatCo coi pat' pat_ty, res) }
551 tc_pat _ _other_pat _ _ = panic "tc_pat" -- ConPatOut, SigPatOut
554 unifyPatType :: TcType -> TcType -> TcM Coercion
555 -- In patterns we want a coercion from the
556 -- context type (expected) to the actual pattern type
557 -- But we don't want to reverse the args to unifyType because
558 -- that controls the actual/expected stuff in error messages
559 unifyPatType actual_ty expected_ty
560 = do { coi <- unifyType actual_ty expected_ty
561 ; return (mkSymCo coi) }
564 Note [Hopping the LIE in lazy patterns]
565 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
566 In a lazy pattern, we must *not* discharge constraints from the RHS
567 from dictionaries bound in the pattern. E.g.
569 We can't discharge the Num constraint from dictionaries bound by
572 So we have to make the constraints from thing_inside "hop around"
573 the pattern. Hence the captureConstraints and emitConstraints.
575 The same thing ensures that equality constraints in a lazy match
576 are not made available in the RHS of the match. For example
577 data T a where { T1 :: Int -> T Int; ... }
580 It's obviously not sound to refine a to Int in the right
581 hand side, because the arugment might not match T1 at all!
583 Finally, a lazy pattern should not bind any existential type variables
584 because they won't be in scope when we do the desugaring
587 %************************************************************************
589 Most of the work for constructors is here
590 (the rest is in the ConPatIn case of tc_pat)
592 %************************************************************************
594 [Pattern matching indexed data types]
595 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
596 Consider the following declarations:
598 data family Map k :: * -> *
599 data instance Map (a, b) v = MapPair (Map a (Pair b v))
601 and a case expression
603 case x :: Map (Int, c) w of MapPair m -> ...
605 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
606 worker/wrapper types for MapPair are
608 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
609 $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
611 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
612 :R123Map, which means the straight use of boxySplitTyConApp would give a type
613 error. Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
614 boxySplitTyConApp with the family tycon Map instead, which gives us the family
615 type list {(Int, c), w}. To get the correct split for :R123Map, we need to
616 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
617 (provided by tyConFamInst_maybe together with the family tycon). This
618 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
619 the split arguments for the representation tycon :R123Map as {Int, c, w}
621 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
623 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
625 moving between representation and family type into account. To produce type
626 correct Core, this coercion needs to be used to case the type of the scrutinee
627 from the family to the representation type. This is achieved by
628 unwrapFamInstScrutinee using a CoPat around the result pattern.
630 Now it might appear seem as if we could have used the previous GADT type
631 refinement infrastructure of refineAlt and friends instead of the explicit
632 unification and CoPat generation. However, that would be wrong. Why? The
633 whole point of GADT refinement is that the refinement is local to the case
634 alternative. In contrast, the substitution generated by the unification of
635 the family type list and instance types needs to be propagated to the outside.
636 Imagine that in the above example, the type of the scrutinee would have been
637 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
638 substitution [x -> (a, b), v -> w]. In contrast to GADT matching, the
639 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
640 alternatives of the case expression, whereas in the GADT case it might vary
641 between alternatives.
643 RIP GADT refinement: refinements have been replaced by the use of explicit
644 equality constraints that are used in conjunction with implication constraints
645 to express the local scope of GADT refinements.
649 -- MkT :: forall a b c. (a~[b]) => b -> c -> T a
650 -- with scrutinee of type (T ty)
652 tcConPat :: PatEnv -> Located Name
653 -> TcRhoType -- Type of the pattern
654 -> HsConPatDetails Name -> TcM a
656 tcConPat penv (L con_span con_name) pat_ty arg_pats thing_inside
657 = do { data_con <- tcLookupDataCon con_name
658 ; let tycon = dataConTyCon data_con
659 -- For data families this is the representation tycon
660 (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _)
661 = dataConFullSig data_con
663 -- Instantiate the constructor type variables [a->ty]
664 -- This may involve doing a family-instance coercion,
665 -- and building a wrapper
666 ; (wrap, ctxt_res_tys) <- matchExpectedPatTy (matchExpectedConTy tycon) pat_ty
668 -- Add the stupid theta
669 ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
671 ; checkExistentials ex_tvs penv
672 ; ex_tvs' <- tcInstSuperSkolTyVars ex_tvs
673 -- Get location from monad, not from ex_tvs
675 ; let pat_ty' = mkTyConApp tycon ctxt_res_tys
676 -- pat_ty' is type of the actual constructor application
677 -- pat_ty' /= pat_ty iff coi /= IdCo
679 tenv = zipTopTvSubst (univ_tvs ++ ex_tvs)
680 (ctxt_res_tys ++ mkTyVarTys ex_tvs')
681 arg_tys' = substTys tenv arg_tys
683 ; if null ex_tvs && null eq_spec && null theta
684 then do { -- The common case; no class bindings etc
685 -- (see Note [Arrows and patterns])
686 (arg_pats', res) <- tcConArgs data_con arg_tys'
687 arg_pats penv thing_inside
688 ; let res_pat = ConPatOut { pat_con = L con_span data_con,
689 pat_tvs = [], pat_dicts = [],
690 pat_binds = emptyTcEvBinds,
691 pat_args = arg_pats',
694 ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
696 else do -- The general case, with existential,
697 -- and local equality constraints
698 { let theta' = substTheta tenv (eqSpecPreds eq_spec ++ theta)
699 -- order is *important* as we generate the list of
700 -- dictionary binders from theta'
701 no_equalities = not (any isEqPred theta')
702 skol_info = case pe_ctxt penv of
703 LamPat mc -> PatSkol data_con mc
704 LetPat {} -> UnkSkol -- Doesn't matter
706 ; gadts_on <- xoptM Opt_GADTs
707 ; checkTc (no_equalities || gadts_on)
708 (ptext (sLit "A pattern match on a GADT requires -XGADTs"))
709 -- Trac #2905 decided that a *pattern-match* of a GADT
710 -- should require the GADT language flag
712 ; given <- newEvVars theta'
713 ; (ev_binds, (arg_pats', res))
714 <- checkConstraints skol_info ex_tvs' given $
715 tcConArgs data_con arg_tys' arg_pats penv thing_inside
717 ; let res_pat = ConPatOut { pat_con = L con_span data_con,
720 pat_binds = ev_binds,
721 pat_args = arg_pats',
723 ; return (mkHsWrapPat wrap res_pat pat_ty, res)
726 ----------------------------
727 matchExpectedPatTy :: (TcRhoType -> TcM (Coercion, a))
728 -> TcRhoType -> TcM (HsWrapper, a)
729 -- See Note [Matching polytyped patterns]
730 -- Returns a wrapper : pat_ty ~ inner_ty
731 matchExpectedPatTy inner_match pat_ty
732 | null tvs && null theta
733 = do { (coi, res) <- inner_match pat_ty
734 ; return (coToHsWrapper (mkSymCo coi), res) }
735 -- The Sym is because the inner_match returns a coercion
736 -- that is the other way round to matchExpectedPatTy
739 = do { (_, tys, subst) <- tcInstTyVars tvs
740 ; wrap1 <- instCall PatOrigin tys (substTheta subst theta)
741 ; (wrap2, arg_tys) <- matchExpectedPatTy inner_match (TcType.substTy subst tau)
742 ; return (wrap2 <.> wrap1 , arg_tys) }
744 (tvs, theta, tau) = tcSplitSigmaTy pat_ty
746 ----------------------------
747 matchExpectedConTy :: TyCon -- The TyCon that this data
748 -- constructor actually returns
749 -> TcRhoType -- The type of the pattern
750 -> TcM (Coercion, [TcSigmaType])
751 -- See Note [Matching constructor patterns]
752 -- Returns a coercion : T ty1 ... tyn ~ pat_ty
753 -- This is the same way round as matchExpectedListTy etc
754 -- but the other way round to matchExpectedPatTy
755 matchExpectedConTy data_tc pat_ty
756 | Just (fam_tc, fam_args, co_tc) <- tyConFamInstSig_maybe data_tc
757 -- Comments refer to Note [Matching constructor patterns]
758 -- co_tc :: forall a. T [a] ~ T7 a
759 = do { (_, tys, subst) <- tcInstTyVars (tyConTyVars data_tc)
762 ; coi1 <- unifyType (mkTyConApp fam_tc (substTys subst fam_args)) pat_ty
763 -- coi1 : T (ty1,ty2) ~ pat_ty
765 ; let coi2 = mkAxInstCo co_tc tys
766 -- coi2 : T (ty1,ty2) ~ T7 ty1 ty2
768 ; return (mkTransCo (mkSymCo coi2) coi1, tys) }
771 = matchExpectedTyConApp data_tc pat_ty
772 -- coi : T tys ~ pat_ty
776 Note [Matching constructor patterns]
777 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
778 Suppose (coi, tys) = matchExpectedConType data_tc pat_ty
780 * In the simple case, pat_ty = tc tys
782 * If pat_ty is a polytype, we want to instantiate it
783 This is like part of a subsumption check. Eg
784 f :: (forall a. [a]) -> blah
787 * In a type family case, suppose we have
789 data instance T (p,q) = A p | B q
790 Then we'll have internally generated
791 data T7 p q = A p | B q
792 axiom coT7 p q :: T (p,q) ~ T7 p q
794 So if pat_ty = T (ty1,ty2), we return (coi, [ty1,ty2]) such that
795 coi = coi2 . coi1 : T7 t ~ pat_ty
796 coi1 : T (ty1,ty2) ~ pat_ty
797 coi2 : T7 ty1 ty2 ~ T (ty1,ty2)
799 For families we do all this matching here, not in the unifier,
800 because we never want a whisper of the data_tycon to appear in
801 error messages; it's a purely internal thing
804 tcConArgs :: DataCon -> [TcSigmaType]
805 -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
807 tcConArgs data_con arg_tys (PrefixCon arg_pats) penv thing_inside
808 = do { checkTc (con_arity == no_of_args) -- Check correct arity
809 (arityErr "Constructor" data_con con_arity no_of_args)
810 ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
811 ; (arg_pats', res) <- tcMultiple tcConArg pats_w_tys
813 ; return (PrefixCon arg_pats', res) }
815 con_arity = dataConSourceArity data_con
816 no_of_args = length arg_pats
818 tcConArgs data_con arg_tys (InfixCon p1 p2) penv thing_inside
819 = do { checkTc (con_arity == 2) -- Check correct arity
820 (arityErr "Constructor" data_con con_arity 2)
821 ; let [arg_ty1,arg_ty2] = arg_tys -- This can't fail after the arity check
822 ; ([p1',p2'], res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
824 ; return (InfixCon p1' p2', res) }
826 con_arity = dataConSourceArity data_con
828 tcConArgs data_con arg_tys (RecCon (HsRecFields rpats dd)) penv thing_inside
829 = do { (rpats', res) <- tcMultiple tc_field rpats penv thing_inside
830 ; return (RecCon (HsRecFields rpats' dd), res) }
832 tc_field :: Checker (HsRecField FieldLabel (LPat Name)) (HsRecField TcId (LPat TcId))
833 tc_field (HsRecField field_lbl pat pun) penv thing_inside
834 = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
835 ; (pat', res) <- tcConArg (pat, pat_ty) penv thing_inside
836 ; return (HsRecField sel_id pat' pun, res) }
838 find_field_ty :: FieldLabel -> TcM (Id, TcType)
839 find_field_ty field_lbl
840 = case [ty | (f,ty) <- field_tys, f == field_lbl] of
842 -- No matching field; chances are this field label comes from some
843 -- other record type (or maybe none). As well as reporting an
844 -- error we still want to typecheck the pattern, principally to
845 -- make sure that all the variables it binds are put into the
846 -- environment, else the type checker crashes later:
847 -- f (R { foo = (a,b) }) = a+b
848 -- If foo isn't one of R's fields, we don't want to crash when
849 -- typechecking the "a+b".
850 [] -> do { addErrTc (badFieldCon data_con field_lbl)
851 ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
852 ; return (error "Bogus selector Id", bogus_ty) }
854 -- The normal case, when the field comes from the right constructor
856 ASSERT( null extras )
857 do { sel_id <- tcLookupField field_lbl
858 ; return (sel_id, pat_ty) }
860 field_tys :: [(FieldLabel, TcType)]
861 field_tys = zip (dataConFieldLabels data_con) arg_tys
862 -- Don't use zipEqual! If the constructor isn't really a record, then
863 -- dataConFieldLabels will be empty (and each field in the pattern
864 -- will generate an error below).
866 tcConArg :: Checker (LPat Name, TcSigmaType) (LPat Id)
867 tcConArg (arg_pat, arg_ty) penv thing_inside
868 = tc_lpat arg_pat arg_ty penv thing_inside
872 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
873 -- Instantiate the "stupid theta" of the data con, and throw
874 -- the constraints into the constraint set
875 addDataConStupidTheta data_con inst_tys
876 | null stupid_theta = return ()
877 | otherwise = instStupidTheta origin inst_theta
879 origin = OccurrenceOf (dataConName data_con)
880 -- The origin should always report "occurrence of C"
881 -- even when C occurs in a pattern
882 stupid_theta = dataConStupidTheta data_con
883 tenv = mkTopTvSubst (dataConUnivTyVars data_con `zip` inst_tys)
884 -- NB: inst_tys can be longer than the univ tyvars
885 -- because the constructor might have existentials
886 inst_theta = substTheta tenv stupid_theta
889 Note [Arrows and patterns]
890 ~~~~~~~~~~~~~~~~~~~~~~~~~~
891 (Oct 07) Arrow noation has the odd property that it involves
892 "holes in the scope". For example:
893 expr :: Arrow a => a () Int
894 expr = proc (y,z) -> do
898 Here the 'proc (y,z)' binding scopes over the arrow tails but not the
899 arrow body (e.g 'term'). As things stand (bogusly) all the
900 constraints from the proc body are gathered together, so constraints
901 from 'term' will be seen by the tcPat for (y,z). But we must *not*
902 bind constraints from 'term' here, becuase the desugarer will not make
903 these bindings scope over 'term'.
905 The Right Thing is not to confuse these constraints together. But for
906 now the Easy Thing is to ensure that we do not have existential or
907 GADT constraints in a 'proc', and to short-cut the constraint
908 simplification for such vanilla patterns so that it binds no
909 constraints. Hence the 'fast path' in tcConPat; but it's also a good
910 plan for ordinary vanilla patterns to bypass the constraint
913 %************************************************************************
915 Note [Pattern coercions]
917 %************************************************************************
919 In principle, these program would be reasonable:
921 f :: (forall a. a->a) -> Int
922 f (x :: Int->Int) = x 3
924 g :: (forall a. [a]) -> Bool
927 In both cases, the function type signature restricts what arguments can be passed
928 in a call (to polymorphic ones). The pattern type signature then instantiates this
929 type. For example, in the first case, (forall a. a->a) <= Int -> Int, and we
930 generate the translated term
931 f = \x' :: (forall a. a->a). let x = x' Int in x 3
933 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
934 And it requires a significant amount of code to implement, becuase we need to decorate
935 the translated pattern with coercion functions (generated from the subsumption check
938 So for now I'm just insisting on type *equality* in patterns. No subsumption.
940 Old notes about desugaring, at a time when pattern coercions were handled:
942 A SigPat is a type coercion and must be handled one at at time. We can't
943 combine them unless the type of the pattern inside is identical, and we don't
944 bother to check for that. For example:
946 data T = T1 Int | T2 Bool
947 f :: (forall a. a -> a) -> T -> t
948 f (g::Int->Int) (T1 i) = T1 (g i)
949 f (g::Bool->Bool) (T2 b) = T2 (g b)
951 We desugar this as follows:
953 f = \ g::(forall a. a->a) t::T ->
955 in case t of { T1 i -> T1 (gi i)
958 in case t of { T2 b -> T2 (gb b)
961 Note that we do not treat the first column of patterns as a
962 column of variables, because the coerced variables (gi, gb)
963 would be of different types. So we get rather grotty code.
964 But I don't think this is a common case, and if it was we could
965 doubtless improve it.
967 Meanwhile, the strategy is:
968 * treat each SigPat coercion (always non-identity coercions)
970 * deal with the stuff inside, and then wrap a binding round
971 the result to bind the new variable (gi, gb, etc)
974 %************************************************************************
976 \subsection{Errors and contexts}
978 %************************************************************************
980 {- This was used to improve the error message from
981 an existential escape. Need to think how to do this.
983 sigPatCtxt :: [LPat Var] -> [Var] -> [TcType] -> TcType -> TidyEnv
984 -> TcM (TidyEnv, SDoc)
985 sigPatCtxt pats bound_tvs pat_tys body_ty tidy_env
986 = do { pat_tys' <- mapM zonkTcType pat_tys
987 ; body_ty' <- zonkTcType body_ty
988 ; let (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
989 (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
990 (env3, tidy_body_ty) = tidyOpenType env2 body_ty'
992 sep [ptext (sLit "When checking an existential match that binds"),
993 nest 2 (vcat (zipWith ppr_id show_ids tidy_tys)),
994 ptext (sLit "The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
995 ptext (sLit "The body has type:") <+> ppr tidy_body_ty
998 bound_ids = collectPatsBinders pats
999 show_ids = filter is_interesting bound_ids
1000 is_interesting id = any (`elemVarSet` varTypeTyVars id) bound_tvs
1002 ppr_id id ty = ppr id <+> dcolon <+> ppr ty
1003 -- Don't zonk the types so we get the separate, un-unified versions
1007 patCtxt :: Pat Name -> Maybe Message -- Not all patterns are worth pushing a context
1008 patCtxt (VarPat _) = Nothing
1009 patCtxt (ParPat _) = Nothing
1010 patCtxt (AsPat _ _) = Nothing
1011 patCtxt pat = Just (hang (ptext (sLit "In the pattern:"))
1014 -----------------------------------------------
1015 checkExistentials :: [TyVar] -> PatEnv -> TcM ()
1016 -- See Note [Arrows and patterns]
1017 checkExistentials [] _ = return ()
1018 checkExistentials _ (PE { pe_ctxt = LetPat {}}) = failWithTc existentialLetPat
1019 checkExistentials _ (PE { pe_ctxt = LamPat ProcExpr }) = failWithTc existentialProcPat
1020 checkExistentials _ (PE { pe_lazy = True }) = failWithTc existentialLazyPat
1021 checkExistentials _ _ = return ()
1023 existentialLazyPat :: SDoc
1025 = hang (ptext (sLit "An existential or GADT data constructor cannot be used"))
1026 2 (ptext (sLit "inside a lazy (~) pattern"))
1028 existentialProcPat :: SDoc
1030 = ptext (sLit "Proc patterns cannot use existential or GADT data constructors")
1032 existentialLetPat :: SDoc
1034 = vcat [text "My brain just exploded",
1035 text "I can't handle pattern bindings for existential or GADT data constructors.",
1036 text "Instead, use a case-expression, or do-notation, to unpack the constructor."]
1038 badFieldCon :: DataCon -> Name -> SDoc
1039 badFieldCon con field
1040 = hsep [ptext (sLit "Constructor") <+> quotes (ppr con),
1041 ptext (sLit "does not have field"), quotes (ppr field)]
1043 polyPatSig :: TcType -> SDoc
1045 = hang (ptext (sLit "Illegal polymorphic type signature in pattern:"))
1048 badTypePat :: Pat Name -> SDoc
1049 badTypePat pat = ptext (sLit "Illegal type pattern") <+> ppr pat
1051 lazyUnliftedPatErr :: OutputableBndr name => Pat name -> TcM ()
1052 lazyUnliftedPatErr pat
1054 hang (ptext (sLit "A lazy (~) pattern cannot contain unlifted types:"))
1057 unboxedTupleErr :: SDoc -> Type -> SDoc
1058 unboxedTupleErr what ty
1059 = hang (what <+> ptext (sLit "cannot have an unboxed tuple type:"))