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, tcLamPat, tcLamPats, tcOverloadedLit,
10 addDataConStupidTheta, badFieldCon, polyPatSig ) where
12 #include "HsVersions.h"
14 import {-# SOURCE #-} TcExpr( tcSyntaxOp )
38 import BasicTypes hiding (SuccessFlag(..))
48 %************************************************************************
52 %************************************************************************
55 tcLetPat :: (Name -> Maybe TcRhoType)
56 -> LPat Name -> BoxySigmaType
59 tcLetPat sig_fn pat pat_ty thing_inside
60 = do { let init_state = PS { pat_ctxt = LetPat sig_fn,
61 pat_reft = emptyRefinement }
62 ; (pat', ex_tvs, res) <- tc_lpat pat pat_ty init_state (\ _ -> thing_inside)
64 -- Don't know how to deal with pattern-bound existentials yet
65 ; checkTc (null ex_tvs) (existentialExplode pat)
67 ; return (pat', res) }
70 tcLamPats :: [LPat Name] -- Patterns,
71 -> [BoxySigmaType] -- and their types
72 -> BoxyRhoType -- Result type,
73 -> ((Refinement, BoxyRhoType) -> TcM a) -- and the checker for the body
74 -> TcM ([LPat TcId], a)
76 -- This is the externally-callable wrapper function
77 -- Typecheck the patterns, extend the environment to bind the variables,
78 -- do the thing inside, use any existentially-bound dictionaries to
79 -- discharge parts of the returning LIE, and deal with pattern type
82 -- 1. Initialise the PatState
83 -- 2. Check the patterns
84 -- 3. Apply the refinement to the environment and result type
86 -- 5. Check that no existentials escape
88 tcLamPats pats tys res_ty thing_inside
89 = tc_lam_pats (zipEqual "tcLamPats" pats tys)
90 (emptyRefinement, res_ty) thing_inside
92 tcLamPat :: LPat Name -> BoxySigmaType
93 -> (Refinement,BoxyRhoType) -- Result type
94 -> ((Refinement,BoxyRhoType) -> TcM a) -- Checker for body, given its result type
96 tcLamPat pat pat_ty res_ty thing_inside
97 = do { ([pat'],thing) <- tc_lam_pats [(pat, pat_ty)] res_ty thing_inside
98 ; return (pat', thing) }
101 tc_lam_pats :: [(LPat Name,BoxySigmaType)]
102 -> (Refinement,BoxyRhoType) -- Result type
103 -> ((Refinement,BoxyRhoType) -> TcM a) -- Checker for body, given its result type
104 -> TcM ([LPat TcId], a)
105 tc_lam_pats pat_ty_prs (reft, res_ty) thing_inside
106 = do { let init_state = PS { pat_ctxt = LamPat, pat_reft = reft }
108 ; (pats', ex_tvs, res) <- tcMultiple tc_lpat_pr pat_ty_prs init_state $ \ pstate' ->
109 refineEnvironment (pat_reft pstate') $
110 thing_inside (pat_reft pstate', res_ty)
112 ; let tys = map snd pat_ty_prs
113 ; tcCheckExistentialPat pats' ex_tvs tys res_ty
115 ; returnM (pats', res) }
119 tcCheckExistentialPat :: [LPat TcId] -- Patterns (just for error message)
120 -> [TcTyVar] -- Existentially quantified tyvars bound by pattern
121 -> [BoxySigmaType] -- Types of the patterns
122 -> BoxyRhoType -- Type of the body of the match
123 -- Tyvars in either of these must not escape
125 -- NB: we *must* pass "pats_tys" not just "body_ty" to tcCheckExistentialPat
126 -- For example, we must reject this program:
127 -- data C = forall a. C (a -> Int)
129 -- Here, result_ty will be simply Int, but expected_ty is (C -> a -> Int).
131 tcCheckExistentialPat pats [] pat_tys body_ty
132 = return () -- Short cut for case when there are no existentials
134 tcCheckExistentialPat pats ex_tvs pat_tys body_ty
135 = addErrCtxtM (sigPatCtxt pats ex_tvs pat_tys body_ty) $
136 checkSigTyVarsWrt (tcTyVarsOfTypes (body_ty:pat_tys)) ex_tvs
140 pat_reft :: Refinement -- Binds rigid TcTyVars to their refinements
145 | LetPat (Name -> Maybe TcRhoType) -- Used for let(rec) bindings
147 patSigCtxt :: PatState -> UserTypeCtxt
148 patSigCtxt (PS { pat_ctxt = LetPat _ }) = BindPatSigCtxt
149 patSigCtxt other = LamPatSigCtxt
154 %************************************************************************
158 %************************************************************************
161 tcPatBndr :: PatState -> Name -> BoxySigmaType -> TcM TcId
162 tcPatBndr (PS { pat_ctxt = LamPat }) bndr_name pat_ty
163 = do { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
164 -- We have an undecorated binder, so we do rule ABS1,
165 -- by unboxing the boxy type, forcing any un-filled-in
166 -- boxes to become monotypes
167 -- NB that pat_ty' can still be a polytype:
168 -- data T = MkT (forall a. a->a)
169 -- f t = case t of { MkT g -> ... }
170 -- Here, the 'g' must get type (forall a. a->a) from the
172 ; return (Id.mkLocalId bndr_name pat_ty') }
174 tcPatBndr (PS { pat_ctxt = LetPat lookup_sig }) bndr_name pat_ty
175 | Just mono_ty <- lookup_sig bndr_name
176 = do { mono_name <- newLocalName bndr_name
177 ; boxyUnify mono_ty pat_ty
178 ; return (Id.mkLocalId mono_name mono_ty) }
181 = do { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
182 ; mono_name <- newLocalName bndr_name
183 ; return (Id.mkLocalId mono_name pat_ty') }
187 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, LHsBinds TcId)
188 bindInstsOfPatId id thing_inside
189 | not (isOverloadedTy (idType id))
190 = do { res <- thing_inside; return (res, emptyLHsBinds) }
192 = do { (res, lie) <- getLIE thing_inside
193 ; binds <- bindInstsOfLocalFuns lie [id]
194 ; return (res, binds) }
197 unBoxPatBndrType ty name = unBoxArgType ty (ptext SLIT("The variable") <+> quotes (ppr name))
198 unBoxWildCardType ty = unBoxArgType ty (ptext SLIT("A wild-card pattern"))
200 unBoxArgType :: BoxyType -> SDoc -> TcM TcType
201 -- In addition to calling unbox, unBoxArgType ensures that the type is of ArgTypeKind;
202 -- that is, it can't be an unboxed tuple. For example,
203 -- case (f x) of r -> ...
204 -- should fail if 'f' returns an unboxed tuple.
205 unBoxArgType ty pp_this
206 = do { ty' <- unBox ty -- Returns a zonked type
208 -- Neither conditional is strictly necesssary (the unify alone will do)
209 -- but they improve error messages, and allocate fewer tyvars
210 ; if isUnboxedTupleType ty' then
212 else if isSubArgTypeKind (typeKind ty') then
214 else do -- OpenTypeKind, so constrain it
215 { ty2 <- newFlexiTyVarTy argTypeKind
219 msg = pp_this <+> ptext SLIT("cannot be bound to an unboxed tuple")
223 %************************************************************************
225 The main worker functions
227 %************************************************************************
231 tcPat takes a "thing inside" over which the pattern scopes. This is partly
232 so that tcPat can extend the environment for the thing_inside, but also
233 so that constraints arising in the thing_inside can be discharged by the
236 This does not work so well for the ErrCtxt carried by the monad: we don't
237 want the error-context for the pattern to scope over the RHS.
238 Hence the getErrCtxt/setErrCtxt stuff in tc_lpats.
242 type Checker inp out = forall r.
245 -> (PatState -> TcM r)
246 -> TcM (out, [TcTyVar], r)
248 tcMultiple :: Checker inp out -> Checker [inp] [out]
249 tcMultiple tc_pat args pstate thing_inside
250 = do { err_ctxt <- getErrCtxt
252 = do { res <- thing_inside pstate
253 ; return ([], [], res) }
255 loop pstate (arg:args)
256 = do { (p', p_tvs, (ps', ps_tvs, res))
257 <- tc_pat arg pstate $ \ pstate' ->
258 setErrCtxt err_ctxt $
260 -- setErrCtxt: restore context before doing the next pattern
261 -- See note [Nesting] above
263 ; return (p':ps', p_tvs ++ ps_tvs, res) }
268 tc_lpat_pr :: (LPat Name, BoxySigmaType)
270 -> (PatState -> TcM a)
271 -> TcM (LPat TcId, [TcTyVar], a)
272 tc_lpat_pr (pat, ty) = tc_lpat pat ty
277 -> (PatState -> TcM a)
278 -> TcM (LPat TcId, [TcTyVar], a)
279 tc_lpat (L span pat) pat_ty pstate thing_inside
281 maybeAddErrCtxt (patCtxt pat) $
282 do { let mb_reft = refineType (pat_reft pstate) pat_ty
283 pat_ty' = case mb_reft of { Just (_, ty') -> ty'; Nothing -> pat_ty }
285 -- Make sure the result type reflects the current refinement
286 -- We must do this here, so that it correctly ``sees'' all
287 -- the refinements to the left. Example:
288 -- Suppose C :: forall a. T a -> a -> Foo
289 -- Pattern C a p1 True
290 -- So p1 might refine 'a' to True, and the True
291 -- pattern had better see it.
293 ; (pat', tvs, res) <- tc_pat pstate pat pat_ty' thing_inside
294 ; let final_pat = case mb_reft of
296 Just (co,_) -> CoPat (WpCo co) pat' pat_ty
297 ; return (L span final_pat, tvs, res) }
301 -> Pat Name -> BoxySigmaType -- Fully refined result type
302 -> (PatState -> TcM a) -- Thing inside
303 -> TcM (Pat TcId, -- Translated pattern
304 [TcTyVar], -- Existential binders
305 a) -- Result of thing inside
307 tc_pat pstate (VarPat name) pat_ty thing_inside
308 = do { id <- tcPatBndr pstate name pat_ty
309 ; (res, binds) <- bindInstsOfPatId id $
310 tcExtendIdEnv1 name id $
311 (traceTc (text "binding" <+> ppr name <+> ppr (idType id))
312 >> thing_inside pstate)
313 ; let pat' | isEmptyLHsBinds binds = VarPat id
314 | otherwise = VarPatOut id binds
315 ; return (pat', [], res) }
317 tc_pat pstate (ParPat pat) pat_ty thing_inside
318 = do { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
319 ; return (ParPat pat', tvs, res) }
321 tc_pat pstate (BangPat pat) pat_ty thing_inside
322 = do { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
323 ; return (BangPat pat', tvs, res) }
325 -- There's a wrinkle with irrefutable patterns, namely that we
326 -- must not propagate type refinement from them. For example
327 -- data T a where { T1 :: Int -> T Int; ... }
328 -- f :: T a -> Int -> a
330 -- It's obviously not sound to refine a to Int in the right
331 -- hand side, because the arugment might not match T1 at all!
333 -- Nor should a lazy pattern bind any existential type variables
334 -- because they won't be in scope when we do the desugaring
336 -- Note [Hopping the LIE in lazy patterns]
337 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
338 -- In a lazy pattern, we must *not* discharge constraints from the RHS
339 -- from dictionaries bound in the pattern. E.g.
341 -- We can't discharge the Num constraint from dictionaries bound by
344 -- So we have to make the constraints from thing_inside "hop around"
345 -- the pattern. Hence the getLLE and extendLIEs later.
347 tc_pat pstate lpat@(LazyPat pat) pat_ty thing_inside
348 = do { (pat', pat_tvs, (res,lie))
349 <- tc_lpat pat pat_ty pstate $ \ _ ->
350 getLIE (thing_inside pstate)
351 -- Ignore refined pstate', revert to pstate
353 -- getLIE/extendLIEs: see Note [Hopping the LIE in lazy patterns]
355 -- Check no existentials
356 ; if (null pat_tvs) then return ()
357 else lazyPatErr lpat pat_tvs
359 -- Check that the pattern has a lifted type
360 ; pat_tv <- newBoxyTyVar liftedTypeKind
361 ; boxyUnify pat_ty (mkTyVarTy pat_tv)
363 ; return (LazyPat pat', [], res) }
365 tc_pat pstate (WildPat _) pat_ty thing_inside
366 = do { pat_ty' <- unBoxWildCardType pat_ty -- Make sure it's filled in with monotypes
367 ; res <- thing_inside pstate
368 ; return (WildPat pat_ty', [], res) }
370 tc_pat pstate (AsPat (L nm_loc name) pat) pat_ty thing_inside
371 = do { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
372 ; (pat', tvs, res) <- tcExtendIdEnv1 name bndr_id $
373 tc_lpat pat (idType bndr_id) pstate thing_inside
374 -- NB: if we do inference on:
375 -- \ (y@(x::forall a. a->a)) = e
376 -- we'll fail. The as-pattern infers a monotype for 'y', which then
377 -- fails to unify with the polymorphic type for 'x'. This could
378 -- perhaps be fixed, but only with a bit more work.
380 -- If you fix it, don't forget the bindInstsOfPatIds!
381 ; return (AsPat (L nm_loc bndr_id) pat', tvs, res) }
383 -- Type signatures in patterns
384 -- See Note [Pattern coercions] below
385 tc_pat pstate (SigPatIn pat sig_ty) pat_ty thing_inside
386 = do { (inner_ty, tv_binds) <- tcPatSig (patSigCtxt pstate) sig_ty pat_ty
387 ; (pat', tvs, res) <- tcExtendTyVarEnv2 tv_binds $
388 tc_lpat pat inner_ty pstate thing_inside
389 ; return (SigPatOut pat' inner_ty, tvs, res) }
391 tc_pat pstate pat@(TypePat ty) pat_ty thing_inside
392 = failWithTc (badTypePat pat)
394 ------------------------
395 -- Lists, tuples, arrays
396 tc_pat pstate (ListPat pats _) pat_ty thing_inside
397 = do { elt_ty <- boxySplitListTy pat_ty
398 ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
399 pats pstate thing_inside
400 ; return (ListPat pats' elt_ty, pats_tvs, res) }
402 tc_pat pstate (PArrPat pats _) pat_ty thing_inside
403 = do { [elt_ty] <- boxySplitTyConApp parrTyCon pat_ty
404 ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
405 pats pstate thing_inside
406 ; ifM (null pats) (zapToMonotype pat_ty) -- c.f. ExplicitPArr in TcExpr
407 ; return (PArrPat pats' elt_ty, pats_tvs, res) }
409 tc_pat pstate (TuplePat pats boxity _) pat_ty thing_inside
410 = do { arg_tys <- boxySplitTyConApp (tupleTyCon boxity (length pats)) pat_ty
411 ; (pats', pats_tvs, res) <- tcMultiple tc_lpat_pr (pats `zip` arg_tys)
414 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
415 -- so that we can experiment with lazy tuple-matching.
416 -- This is a pretty odd place to make the switch, but
417 -- it was easy to do.
418 ; let unmangled_result = TuplePat pats' boxity pat_ty
419 possibly_mangled_result
420 | opt_IrrefutableTuples && isBoxed boxity = LazyPat (noLoc unmangled_result)
421 | otherwise = unmangled_result
423 ; ASSERT( length arg_tys == length pats ) -- Syntactically enforced
424 return (possibly_mangled_result, pats_tvs, res) }
426 ------------------------
428 tc_pat pstate pat_in@(ConPatIn (L con_span con_name) arg_pats) pat_ty thing_inside
429 = do { data_con <- tcLookupDataCon con_name
430 ; let tycon = dataConTyCon data_con
431 ; tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside }
433 ------------------------
435 tc_pat pstate (LitPat simple_lit) pat_ty thing_inside
436 = do { boxyUnify (hsLitType simple_lit) pat_ty
437 ; res <- thing_inside pstate
438 ; returnM (LitPat simple_lit, [], res) }
440 ------------------------
441 -- Overloaded patterns: n, and n+k
442 tc_pat pstate pat@(NPat over_lit mb_neg eq _) pat_ty thing_inside
443 = do { let orig = LiteralOrigin over_lit
444 ; lit' <- tcOverloadedLit orig over_lit pat_ty
445 ; eq' <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
446 ; mb_neg' <- case mb_neg of
447 Nothing -> return Nothing -- Positive literal
448 Just neg -> -- Negative literal
449 -- The 'negate' is re-mappable syntax
450 do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
451 ; return (Just neg') }
452 ; res <- thing_inside pstate
453 ; returnM (NPat lit' mb_neg' eq' pat_ty, [], res) }
455 tc_pat pstate pat@(NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
456 = do { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
457 ; let pat_ty' = idType bndr_id
458 orig = LiteralOrigin lit
459 ; lit' <- tcOverloadedLit orig lit pat_ty'
461 -- The '>=' and '-' parts are re-mappable syntax
462 ; ge' <- tcSyntaxOp orig ge (mkFunTys [pat_ty', pat_ty'] boolTy)
463 ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
465 -- The Report says that n+k patterns must be in Integral
466 -- We may not want this when using re-mappable syntax, though (ToDo?)
467 ; icls <- tcLookupClass integralClassName
468 ; instStupidTheta orig [mkClassPred icls [pat_ty']]
470 ; res <- tcExtendIdEnv1 name bndr_id (thing_inside pstate)
471 ; returnM (NPlusKPat (L nm_loc bndr_id) lit' ge' minus', [], res) }
473 tc_pat _ _other_pat _ _ = panic "tc_pat" -- DictPat, ConPatOut, SigPatOut, VarPatOut
477 %************************************************************************
479 Most of the work for constructors is here
480 (the rest is in the ConPatIn case of tc_pat)
482 %************************************************************************
484 [Pattern matching indexed data types]
485 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
486 Consider the following declarations:
488 data family Map k :: * -> *
489 data instance Map (a, b) v = MapPair (Map a (Pair b v))
491 and a case expression
493 case x :: Map (Int, c) w of MapPair m -> ...
495 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
496 worker/wrapper types for MapPair are
498 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
499 $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
501 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
502 :R123Map, which means the straight use of boxySplitTyConApp would give a type
503 error. Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
504 boxySplitTyConApp with the family tycon Map instead, which gives us the family
505 type list {(Int, c), w}. To get the correct split for :R123Map, we need to
506 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
507 (provided by tyConFamInst_maybe together with the family tycon). This
508 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
509 the split arguments for the representation tycon :R123Map as {Int, c, w}
511 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
513 Co123Map a b v :: {Map (a, b) v :=: :R123Map a b v}
515 moving between representation and family type into account. To produce type
516 correct Core, this coercion needs to be used to case the type of the scrutinee
517 from the family to the representation type. This is achieved by
518 unwrapFamInstScrutinee using a CoPat around the result pattern.
520 Now it might appear seem as if we could have used the existing GADT type
521 refinement infrastructure of refineAlt and friends instead of the explicit
522 unification and CoPat generation. However, that would be wrong. Why? The
523 whole point of GADT refinement is that the refinement is local to the case
524 alternative. In contrast, the substitution generated by the unification of
525 the family type list and instance types needs to be propagated to the outside.
526 Imagine that in the above example, the type of the scrutinee would have been
527 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
528 substitution [x -> (a, b), v -> w]. In contrast to GADT matching, the
529 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
530 alternatives of the case expression, whereas in the GADT case it might vary
531 between alternatives.
533 In fact, if we have a data instance declaration defining a GADT, eq_spec will
534 be non-empty and we will get a mixture of global instantiations and local
535 refinement from a single match. This neatly reflects that, as soon as we
536 have constrained the type of the scrutinee to the required type index, all
537 further type refinement is local to the alternative.
541 -- MkT :: forall a b c. (a:=:[b]) => b -> c -> T a
542 -- with scrutinee of type (T ty)
544 tcConPat :: PatState -> SrcSpan -> DataCon -> TyCon
545 -> BoxySigmaType -- Type of the pattern
546 -> HsConDetails Name (LPat Name) -> (PatState -> TcM a)
547 -> TcM (Pat TcId, [TcTyVar], a)
548 tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside
549 = do { let (univ_tvs, ex_tvs, eq_spec, theta, arg_tys) = dataConFullSig data_con
550 skol_info = PatSkol data_con
551 origin = SigOrigin skol_info
553 -- Instantiate the constructor type variables [a->ty]
554 ; ctxt_res_tys <- boxySplitTyConAppWithFamily tycon pat_ty
555 ; ex_tvs' <- tcInstSkolTyVars skol_info ex_tvs -- Get location from monad,
557 ; let tenv = zipTopTvSubst (univ_tvs ++ ex_tvs)
558 (ctxt_res_tys ++ mkTyVarTys ex_tvs')
559 eq_spec' = substEqSpec tenv eq_spec
560 theta' = substTheta tenv theta
561 arg_tys' = substTys tenv arg_tys
563 ; co_vars <- newCoVars eq_spec' -- Make coercion variables
564 ; pstate' <- refineAlt data_con pstate ex_tvs' co_vars pat_ty
566 ; ((arg_pats', inner_tvs, res), lie_req) <- getLIE $
567 tcConArgs data_con arg_tys' arg_pats pstate' thing_inside
569 ; loc <- getInstLoc origin
570 ; dicts <- newDictBndrs loc theta'
571 ; dict_binds <- tcSimplifyCheckPat loc co_vars (pat_reft pstate')
572 ex_tvs' dicts lie_req
574 ; addDataConStupidTheta data_con ctxt_res_tys
577 (unwrapFamInstScrutinee tycon ctxt_res_tys $
578 ConPatOut { pat_con = L con_span data_con,
579 pat_tvs = ex_tvs' ++ co_vars,
580 pat_dicts = map instToId dicts,
581 pat_binds = dict_binds,
582 pat_args = arg_pats', pat_ty = pat_ty },
583 ex_tvs' ++ inner_tvs, res)
586 -- Split against the family tycon if the pattern constructor belongs to a
587 -- representation tycon.
589 boxySplitTyConAppWithFamily tycon pat_ty =
591 case tyConFamInst_maybe tycon of
592 Nothing -> boxySplitTyConApp tycon pat_ty
593 Just (fam_tycon, instTys) ->
594 do { scrutinee_arg_tys <- boxySplitTyConApp fam_tycon pat_ty
595 ; (_, freshTvs, subst) <- tcInstTyVars (tyConTyVars tycon)
596 ; boxyUnifyList (substTys subst instTys) scrutinee_arg_tys
600 traceMsg = sep [ text "tcConPat:boxySplitTyConAppWithFamily:" <+>
601 ppr tycon <+> ppr pat_ty
602 , text " family instance:" <+>
603 ppr (tyConFamInst_maybe tycon)
606 -- Wraps the pattern (which must be a ConPatOut pattern) in a coercion
607 -- pattern if the tycon is an instance of a family.
609 unwrapFamInstScrutinee :: TyCon -> [Type] -> Pat Id -> Pat Id
610 unwrapFamInstScrutinee tycon args pat
611 | Just co_con <- tyConFamilyCoercion_maybe tycon
612 -- , not (isNewTyCon tycon) -- newtypes are explicitly unwrapped by
614 -- NB: We can use CoPat directly, rather than mkCoPat, as we know the
615 -- coercion is not the identity; mkCoPat is inconvenient as it
616 -- wants a located pattern.
617 = CoPat (WpCo $ mkTyConApp co_con args) -- co fam ty to repr ty
618 (pat {pat_ty = mkTyConApp tycon args}) -- representation type
619 pat_ty -- family inst type
624 tcConArgs :: DataCon -> [TcSigmaType]
625 -> Checker (HsConDetails Name (LPat Name))
626 (HsConDetails Id (LPat Id))
628 tcConArgs data_con arg_tys (PrefixCon arg_pats) pstate thing_inside
629 = do { checkTc (con_arity == no_of_args) -- Check correct arity
630 (arityErr "Constructor" data_con con_arity no_of_args)
631 ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
632 ; (arg_pats', tvs, res) <- tcMultiple tcConArg pats_w_tys
634 ; return (PrefixCon arg_pats', tvs, res) }
636 con_arity = dataConSourceArity data_con
637 no_of_args = length arg_pats
639 tcConArgs data_con [arg_ty1,arg_ty2] (InfixCon p1 p2) pstate thing_inside
640 = do { checkTc (con_arity == 2) -- Check correct arity
641 (arityErr "Constructor" data_con con_arity 2)
642 ; ([p1',p2'], tvs, res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
644 ; return (InfixCon p1' p2', tvs, res) }
646 con_arity = dataConSourceArity data_con
648 tcConArgs data_con other_args (InfixCon p1 p2) pstate thing_inside
649 = pprPanic "tcConArgs" (ppr data_con) -- InfixCon always has two arguments
651 tcConArgs data_con arg_tys (RecCon rpats) pstate thing_inside
652 = do { (rpats', tvs, res) <- tcMultiple tc_field rpats pstate thing_inside
653 ; return (RecCon rpats', tvs, res) }
655 -- doc comments are typechecked to Nothing here
656 tc_field :: Checker (HsRecField FieldLabel (LPat Name)) (HsRecField TcId (LPat TcId))
657 tc_field (HsRecField field_lbl pat _) pstate thing_inside
658 = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
659 ; (pat', tvs, res) <- tcConArg (pat, pat_ty) pstate thing_inside
660 ; return (mkRecField sel_id pat', tvs, res) }
662 find_field_ty :: FieldLabel -> TcM (Id, TcType)
663 find_field_ty field_lbl
664 = case [ty | (f,ty) <- field_tys, f == field_lbl] of
666 -- No matching field; chances are this field label comes from some
667 -- other record type (or maybe none). As well as reporting an
668 -- error we still want to typecheck the pattern, principally to
669 -- make sure that all the variables it binds are put into the
670 -- environment, else the type checker crashes later:
671 -- f (R { foo = (a,b) }) = a+b
672 -- If foo isn't one of R's fields, we don't want to crash when
673 -- typechecking the "a+b".
674 [] -> do { addErrTc (badFieldCon data_con field_lbl)
675 ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
676 ; return (error "Bogus selector Id", bogus_ty) }
678 -- The normal case, when the field comes from the right constructor
680 ASSERT( null extras )
681 do { sel_id <- tcLookupField field_lbl
682 ; return (sel_id, pat_ty) }
684 field_tys :: [(FieldLabel, TcType)]
685 field_tys = zip (dataConFieldLabels data_con) arg_tys
686 -- Don't use zipEqual! If the constructor isn't really a record, then
687 -- dataConFieldLabels will be empty (and each field in the pattern
688 -- will generate an error below).
690 tcConArg :: Checker (LPat Name, BoxySigmaType) (LPat Id)
691 tcConArg (arg_pat, arg_ty) pstate thing_inside
692 = tc_lpat arg_pat arg_ty pstate thing_inside
693 -- NB: the tc_lpat will refine pat_ty if necessary
694 -- based on the current pstate, which may include
695 -- refinements from peer argument patterns to the left
699 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
700 -- Instantiate the "stupid theta" of the data con, and throw
701 -- the constraints into the constraint set
702 addDataConStupidTheta data_con inst_tys
703 | null stupid_theta = return ()
704 | otherwise = instStupidTheta origin inst_theta
706 origin = OccurrenceOf (dataConName data_con)
707 -- The origin should always report "occurrence of C"
708 -- even when C occurs in a pattern
709 stupid_theta = dataConStupidTheta data_con
710 tenv = zipTopTvSubst (dataConUnivTyVars data_con) inst_tys
711 inst_theta = substTheta tenv stupid_theta
715 %************************************************************************
719 %************************************************************************
722 refineAlt :: DataCon -- For tracing only
724 -> [TcTyVar] -- Existentials
725 -> [CoVar] -- Equational constraints
726 -> BoxySigmaType -- Pattern type
729 refineAlt con pstate ex_tvs [] pat_ty
730 = return pstate -- Common case: no equational constraints
732 refineAlt con pstate ex_tvs co_vars pat_ty
733 | not (isRigidTy pat_ty)
734 = failWithTc (nonRigidMatch con)
735 -- We are matching against a GADT constructor with non-trivial
736 -- constraints, but pattern type is wobbly. For now we fail.
737 -- We can make sense of this, however:
738 -- Suppose MkT :: forall a b. (a:=:[b]) => b -> T a
739 -- (\x -> case x of { MkT v -> v })
740 -- We can infer that x must have type T [c], for some wobbly 'c'
742 -- (\(x::T [c]) -> case x of
743 -- MkT b (g::([c]:=:[b])) (v::b) -> v `cast` sym g
744 -- To implement this, we'd first instantiate the equational
745 -- constraints with *wobbly* type variables for the existentials;
746 -- then unify these constraints to make pat_ty the right shape;
747 -- then proceed exactly as in the rigid case
749 | otherwise -- In the rigid case, we perform type refinement
750 = case gadtRefine (pat_reft pstate) ex_tvs co_vars of {
751 Failed msg -> failWithTc (inaccessibleAlt msg) ;
752 Succeeded reft -> do { traceTc trace_msg
753 ; return (pstate { pat_reft = reft }) }
754 -- DO NOT refine the envt right away, because we
755 -- might be inside a lazy pattern. Instead, refine pstate
758 trace_msg = text "refineAlt:match" <+>
759 vcat [ ppr con <+> ppr ex_tvs,
760 ppr [(v, tyVarKind v) | v <- co_vars],
766 %************************************************************************
770 %************************************************************************
772 In tcOverloadedLit we convert directly to an Int or Integer if we
773 know that's what we want. This may save some time, by not
774 temporarily generating overloaded literals, but it won't catch all
775 cases (the rest are caught in lookupInst).
778 tcOverloadedLit :: InstOrigin
781 -> TcM (HsOverLit TcId)
782 tcOverloadedLit orig lit@(HsIntegral i fi) res_ty
783 | not (fi `isHsVar` fromIntegerName) -- Do not generate a LitInst for rebindable syntax.
784 -- Reason: If we do, tcSimplify will call lookupInst, which
785 -- will call tcSyntaxName, which does unification,
786 -- which tcSimplify doesn't like
787 -- ToDo: noLoc sadness
788 = do { integer_ty <- tcMetaTy integerTyConName
789 ; fi' <- tcSyntaxOp orig fi (mkFunTy integer_ty res_ty)
790 ; return (HsIntegral i (HsApp (noLoc fi') (nlHsLit (HsInteger i integer_ty)))) }
792 | Just expr <- shortCutIntLit i res_ty
793 = return (HsIntegral i expr)
796 = do { expr <- newLitInst orig lit res_ty
797 ; return (HsIntegral i expr) }
799 tcOverloadedLit orig lit@(HsFractional r fr) res_ty
800 | not (fr `isHsVar` fromRationalName) -- c.f. HsIntegral case
801 = do { rat_ty <- tcMetaTy rationalTyConName
802 ; fr' <- tcSyntaxOp orig fr (mkFunTy rat_ty res_ty)
803 -- Overloaded literals must have liftedTypeKind, because
804 -- we're instantiating an overloaded function here,
805 -- whereas res_ty might be openTypeKind. This was a bug in 6.2.2
806 -- However this'll be picked up by tcSyntaxOp if necessary
807 ; return (HsFractional r (HsApp (noLoc fr') (nlHsLit (HsRat r rat_ty)))) }
809 | Just expr <- shortCutFracLit r res_ty
810 = return (HsFractional r expr)
813 = do { expr <- newLitInst orig lit res_ty
814 ; return (HsFractional r expr) }
816 tcOverloadedLit orig lit@(HsIsString s fr) res_ty
817 | not (fr `isHsVar` fromStringName) -- c.f. HsIntegral case
818 = do { str_ty <- tcMetaTy stringTyConName
819 ; fr' <- tcSyntaxOp orig fr (mkFunTy str_ty res_ty)
820 ; return (HsIsString s (HsApp (noLoc fr') (nlHsLit (HsString s)))) }
822 | Just expr <- shortCutStringLit s res_ty
823 = return (HsIsString s expr)
826 = do { expr <- newLitInst orig lit res_ty
827 ; return (HsIsString s expr) }
829 newLitInst :: InstOrigin -> HsOverLit Name -> BoxyRhoType -> TcM (HsExpr TcId)
830 newLitInst orig lit res_ty -- Make a LitInst
831 = do { loc <- getInstLoc orig
832 ; res_tau <- zapToMonotype res_ty
833 ; new_uniq <- newUnique
834 ; let lit_nm = mkSystemVarName new_uniq FSLIT("lit")
835 lit_inst = LitInst {tci_name = lit_nm, tci_lit = lit,
836 tci_ty = res_tau, tci_loc = loc}
838 ; return (HsVar (instToId lit_inst)) }
842 %************************************************************************
844 Note [Pattern coercions]
846 %************************************************************************
848 In principle, these program would be reasonable:
850 f :: (forall a. a->a) -> Int
851 f (x :: Int->Int) = x 3
853 g :: (forall a. [a]) -> Bool
856 In both cases, the function type signature restricts what arguments can be passed
857 in a call (to polymorphic ones). The pattern type signature then instantiates this
858 type. For example, in the first case, (forall a. a->a) <= Int -> Int, and we
859 generate the translated term
860 f = \x' :: (forall a. a->a). let x = x' Int in x 3
862 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
863 And it requires a significant amount of code to implement, becuase we need to decorate
864 the translated pattern with coercion functions (generated from the subsumption check
867 So for now I'm just insisting on type *equality* in patterns. No subsumption.
869 Old notes about desugaring, at a time when pattern coercions were handled:
871 A SigPat is a type coercion and must be handled one at at time. We can't
872 combine them unless the type of the pattern inside is identical, and we don't
873 bother to check for that. For example:
875 data T = T1 Int | T2 Bool
876 f :: (forall a. a -> a) -> T -> t
877 f (g::Int->Int) (T1 i) = T1 (g i)
878 f (g::Bool->Bool) (T2 b) = T2 (g b)
880 We desugar this as follows:
882 f = \ g::(forall a. a->a) t::T ->
884 in case t of { T1 i -> T1 (gi i)
887 in case t of { T2 b -> T2 (gb b)
890 Note that we do not treat the first column of patterns as a
891 column of variables, because the coerced variables (gi, gb)
892 would be of different types. So we get rather grotty code.
893 But I don't think this is a common case, and if it was we could
894 doubtless improve it.
896 Meanwhile, the strategy is:
897 * treat each SigPat coercion (always non-identity coercions)
899 * deal with the stuff inside, and then wrap a binding round
900 the result to bind the new variable (gi, gb, etc)
903 %************************************************************************
905 \subsection{Errors and contexts}
907 %************************************************************************
910 patCtxt :: Pat Name -> Maybe Message -- Not all patterns are worth pushing a context
911 patCtxt (VarPat _) = Nothing
912 patCtxt (ParPat _) = Nothing
913 patCtxt (AsPat _ _) = Nothing
914 patCtxt pat = Just (hang (ptext SLIT("In the pattern:"))
917 -----------------------------------------------
919 existentialExplode pat
920 = hang (vcat [text "My brain just exploded.",
921 text "I can't handle pattern bindings for existentially-quantified constructors.",
922 text "In the binding group for"])
925 sigPatCtxt pats bound_tvs pat_tys body_ty tidy_env
926 = do { pat_tys' <- mapM zonkTcType pat_tys
927 ; body_ty' <- zonkTcType body_ty
928 ; let (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
929 (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
930 (env3, tidy_body_ty) = tidyOpenType env2 body_ty'
932 sep [ptext SLIT("When checking an existential match that binds"),
933 nest 4 (vcat (zipWith ppr_id show_ids tidy_tys)),
934 ptext SLIT("The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
935 ptext SLIT("The body has type:") <+> ppr tidy_body_ty
938 bound_ids = collectPatsBinders pats
939 show_ids = filter is_interesting bound_ids
940 is_interesting id = any (`elemVarSet` varTypeTyVars id) bound_tvs
942 ppr_id id ty = ppr id <+> dcolon <+> ppr ty
943 -- Don't zonk the types so we get the separate, un-unified versions
945 badFieldCon :: DataCon -> Name -> SDoc
946 badFieldCon con field
947 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
948 ptext SLIT("does not have field"), quotes (ppr field)]
950 polyPatSig :: TcType -> SDoc
952 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
955 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
959 hang (ptext SLIT("A lazy (~) pattern connot bind existential type variables"))
960 2 (vcat (map pprSkolTvBinding tvs))
963 = hang (ptext SLIT("GADT pattern match in non-rigid context for") <+> quotes (ppr con))
964 2 (ptext SLIT("Tell GHC HQ if you'd like this to unify the context"))
967 = hang (ptext SLIT("Inaccessible case alternative:")) 2 msg