2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcPat]{Typechecking patterns}
7 module TcPat ( tcLetPat, tcLamPat, tcLamPats, tcOverloadedLit,
8 addDataConStupidTheta, badFieldCon, polyPatSig ) where
10 #include "HsVersions.h"
12 import {-# SOURCE #-} TcExpr( tcSyntaxOp )
13 import HsSyn ( Pat(..), LPat, HsConDetails(..), HsLit(..),
14 HsOverLit(..), HsExpr(..), ExprCoFn(..),
16 LHsBinds, emptyLHsBinds, isEmptyLHsBinds,
17 collectPatsBinders, nlHsLit )
18 import TcHsSyn ( TcId, hsLitType )
20 import Inst ( InstOrigin(..), shortCutFracLit, shortCutIntLit,
21 newDictBndrs, instToId, instStupidTheta, isHsVar
23 import Id ( Id, idType, mkLocalId )
24 import Var ( CoVar, tyVarKind )
25 import CoreFVs ( idFreeTyVars )
26 import Name ( Name, mkSystemVarName )
27 import TcSimplify ( tcSimplifyCheck, bindInstsOfLocalFuns )
28 import TcEnv ( newLocalName, tcExtendIdEnv1, tcExtendTyVarEnv2,
29 tcLookupClass, tcLookupDataCon, refineEnvironment,
30 tcLookupField, tcMetaTy )
31 import TcMType ( newFlexiTyVarTy, arityErr, tcInstSkolTyVars,
32 newCoVars, zonkTcType, tcInstTyVars, newBoxyTyVar )
33 import TcType ( TcType, TcTyVar, TcSigmaType, TcRhoType, BoxyType,
35 BoxySigmaType, BoxyRhoType, argTypeKind, typeKind,
36 pprSkolTvBinding, isRigidTy, tcTyVarsOfTypes,
37 zipTopTvSubst, isSubArgTypeKind, isUnboxedTupleType,
38 mkTyVarTys, mkClassPred, isOverloadedTy, substEqSpec,
39 mkFunTy, mkFunTys, tidyOpenType, tidyOpenTypes,
41 import VarSet ( elemVarSet )
42 import {- Kind parts of -}
43 Type ( liftedTypeKind )
44 import TcUnify ( boxySplitTyConApp, boxySplitListTy, unBox,
45 zapToMonotype, boxyUnify, boxyUnifyList,
46 checkSigTyVarsWrt, unifyType )
47 import TcHsType ( UserTypeCtxt(..), tcPatSig )
48 import TysWiredIn ( boolTy, parrTyCon, tupleTyCon )
49 import TcGadt ( Refinement, emptyRefinement, gadtRefine, refineType )
50 import Type ( Type, mkTyConApp, substTys, substTheta )
51 import StaticFlags ( opt_IrrefutableTuples )
52 import TyCon ( TyCon, FieldLabel, tyConFamInst_maybe,
53 tyConFamilyCoercion_maybe, tyConTyVars )
54 import DataCon ( DataCon, dataConTyCon, dataConFullSig, dataConName,
55 dataConFieldLabels, dataConSourceArity,
56 dataConStupidTheta, dataConUnivTyVars )
57 import PrelNames ( integralClassName, fromIntegerName, integerTyConName,
58 fromRationalName, rationalTyConName )
59 import BasicTypes ( isBoxed )
60 import SrcLoc ( Located(..), SrcSpan, noLoc )
61 import ErrUtils ( Message )
62 import Util ( zipEqual )
63 import Maybes ( MaybeErr(..) )
69 %************************************************************************
73 %************************************************************************
76 tcLetPat :: (Name -> Maybe TcRhoType)
77 -> LPat Name -> BoxySigmaType
80 tcLetPat sig_fn pat pat_ty thing_inside
81 = do { let init_state = PS { pat_ctxt = LetPat sig_fn,
82 pat_reft = emptyRefinement }
83 ; (pat', ex_tvs, res) <- tc_lpat pat pat_ty init_state (\ _ -> thing_inside)
85 -- Don't know how to deal with pattern-bound existentials yet
86 ; checkTc (null ex_tvs) (existentialExplode pat)
88 ; return (pat', res) }
91 tcLamPats :: [LPat Name] -- Patterns,
92 -> [BoxySigmaType] -- and their types
93 -> BoxyRhoType -- Result type,
94 -> ((Refinement, BoxyRhoType) -> TcM a) -- and the checker for the body
95 -> TcM ([LPat TcId], a)
97 -- This is the externally-callable wrapper function
98 -- Typecheck the patterns, extend the environment to bind the variables,
99 -- do the thing inside, use any existentially-bound dictionaries to
100 -- discharge parts of the returning LIE, and deal with pattern type
103 -- 1. Initialise the PatState
104 -- 2. Check the patterns
105 -- 3. Apply the refinement to the environment and result type
107 -- 5. Check that no existentials escape
109 tcLamPats pats tys res_ty thing_inside
110 = tc_lam_pats (zipEqual "tcLamPats" pats tys)
111 (emptyRefinement, res_ty) thing_inside
113 tcLamPat :: LPat Name -> BoxySigmaType
114 -> (Refinement,BoxyRhoType) -- Result type
115 -> ((Refinement,BoxyRhoType) -> TcM a) -- Checker for body, given its result type
116 -> TcM (LPat TcId, a)
117 tcLamPat pat pat_ty res_ty thing_inside
118 = do { ([pat'],thing) <- tc_lam_pats [(pat, pat_ty)] res_ty thing_inside
119 ; return (pat', thing) }
122 tc_lam_pats :: [(LPat Name,BoxySigmaType)]
123 -> (Refinement,BoxyRhoType) -- Result type
124 -> ((Refinement,BoxyRhoType) -> TcM a) -- Checker for body, given its result type
125 -> TcM ([LPat TcId], a)
126 tc_lam_pats pat_ty_prs (reft, res_ty) thing_inside
127 = do { let init_state = PS { pat_ctxt = LamPat, pat_reft = reft }
129 ; (pats', ex_tvs, res) <- tcMultiple tc_lpat_pr pat_ty_prs init_state $ \ pstate' ->
130 refineEnvironment (pat_reft pstate') $
131 thing_inside (pat_reft pstate', res_ty)
133 ; let tys = map snd pat_ty_prs
134 ; tcCheckExistentialPat pats' ex_tvs tys res_ty
136 ; returnM (pats', res) }
140 tcCheckExistentialPat :: [LPat TcId] -- Patterns (just for error message)
141 -> [TcTyVar] -- Existentially quantified tyvars bound by pattern
142 -> [BoxySigmaType] -- Types of the patterns
143 -> BoxyRhoType -- Type of the body of the match
144 -- Tyvars in either of these must not escape
146 -- NB: we *must* pass "pats_tys" not just "body_ty" to tcCheckExistentialPat
147 -- For example, we must reject this program:
148 -- data C = forall a. C (a -> Int)
150 -- Here, result_ty will be simply Int, but expected_ty is (C -> a -> Int).
152 tcCheckExistentialPat pats [] pat_tys body_ty
153 = return () -- Short cut for case when there are no existentials
155 tcCheckExistentialPat pats ex_tvs pat_tys body_ty
156 = addErrCtxtM (sigPatCtxt (collectPatsBinders pats) ex_tvs pat_tys body_ty) $
157 checkSigTyVarsWrt (tcTyVarsOfTypes (body_ty:pat_tys)) ex_tvs
161 pat_reft :: Refinement -- Binds rigid TcTyVars to their refinements
166 | LetPat (Name -> Maybe TcRhoType) -- Used for let(rec) bindings
168 patSigCtxt :: PatState -> UserTypeCtxt
169 patSigCtxt (PS { pat_ctxt = LetPat _ }) = BindPatSigCtxt
170 patSigCtxt other = LamPatSigCtxt
175 %************************************************************************
179 %************************************************************************
182 tcPatBndr :: PatState -> Name -> BoxySigmaType -> TcM TcId
183 tcPatBndr (PS { pat_ctxt = LamPat }) bndr_name pat_ty
184 = do { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
185 -- We have an undecorated binder, so we do rule ABS1,
186 -- by unboxing the boxy type, forcing any un-filled-in
187 -- boxes to become monotypes
188 -- NB that pat_ty' can still be a polytype:
189 -- data T = MkT (forall a. a->a)
190 -- f t = case t of { MkT g -> ... }
191 -- Here, the 'g' must get type (forall a. a->a) from the
193 ; return (mkLocalId bndr_name pat_ty') }
195 tcPatBndr (PS { pat_ctxt = LetPat lookup_sig }) bndr_name pat_ty
196 | Just mono_ty <- lookup_sig bndr_name
197 = do { mono_name <- newLocalName bndr_name
198 ; boxyUnify mono_ty pat_ty
199 ; return (mkLocalId mono_name mono_ty) }
202 = do { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
203 ; mono_name <- newLocalName bndr_name
204 ; return (mkLocalId mono_name pat_ty') }
208 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, LHsBinds TcId)
209 bindInstsOfPatId id thing_inside
210 | not (isOverloadedTy (idType id))
211 = do { res <- thing_inside; return (res, emptyLHsBinds) }
213 = do { (res, lie) <- getLIE thing_inside
214 ; binds <- bindInstsOfLocalFuns lie [id]
215 ; return (res, binds) }
218 unBoxPatBndrType ty name = unBoxArgType ty (ptext SLIT("The variable") <+> quotes (ppr name))
219 unBoxWildCardType ty = unBoxArgType ty (ptext SLIT("A wild-card pattern"))
221 unBoxArgType :: BoxyType -> SDoc -> TcM TcType
222 -- In addition to calling unbox, unBoxArgType ensures that the type is of ArgTypeKind;
223 -- that is, it can't be an unboxed tuple. For example,
224 -- case (f x) of r -> ...
225 -- should fail if 'f' returns an unboxed tuple.
226 unBoxArgType ty pp_this
227 = do { ty' <- unBox ty -- Returns a zonked type
229 -- Neither conditional is strictly necesssary (the unify alone will do)
230 -- but they improve error messages, and allocate fewer tyvars
231 ; if isUnboxedTupleType ty' then
233 else if isSubArgTypeKind (typeKind ty') then
235 else do -- OpenTypeKind, so constrain it
236 { ty2 <- newFlexiTyVarTy argTypeKind
240 msg = pp_this <+> ptext SLIT("cannot be bound to an unboxed tuple")
244 %************************************************************************
246 The main worker functions
248 %************************************************************************
252 tcPat takes a "thing inside" over which the patter scopes. This is partly
253 so that tcPat can extend the environment for the thing_inside, but also
254 so that constraints arising in the thing_inside can be discharged by the
257 This does not work so well for the ErrCtxt carried by the monad: we don't
258 want the error-context for the pattern to scope over the RHS.
259 Hence the getErrCtxt/setErrCtxt stuff in tc_lpats.
263 type Checker inp out = forall r.
266 -> (PatState -> TcM r)
267 -> TcM (out, [TcTyVar], r)
269 tcMultiple :: Checker inp out -> Checker [inp] [out]
270 tcMultiple tc_pat args pstate thing_inside
271 = do { err_ctxt <- getErrCtxt
273 = do { res <- thing_inside pstate
274 ; return ([], [], res) }
276 loop pstate (arg:args)
277 = do { (p', p_tvs, (ps', ps_tvs, res))
278 <- tc_pat arg pstate $ \ pstate' ->
279 setErrCtxt err_ctxt $
281 -- setErrCtxt: restore context before doing the next pattern
282 -- See note [Nesting] above
284 ; return (p':ps', p_tvs ++ ps_tvs, res) }
289 tc_lpat_pr :: (LPat Name, BoxySigmaType)
291 -> (PatState -> TcM a)
292 -> TcM (LPat TcId, [TcTyVar], a)
293 tc_lpat_pr (pat, ty) = tc_lpat pat ty
298 -> (PatState -> TcM a)
299 -> TcM (LPat TcId, [TcTyVar], a)
300 tc_lpat (L span pat) pat_ty pstate thing_inside
302 maybeAddErrCtxt (patCtxt pat) $
303 do { let (coercion, pat_ty') = refineType (pat_reft pstate) pat_ty
304 -- Make sure the result type reflects the current refinement
305 -- We must do this here, so that it correctly ``sees'' all
306 -- the refinements to the left. Example:
307 -- Suppose C :: forall a. T a -> a -> Foo
308 -- Pattern C a p1 True
309 -- So p1 might refine 'a' to True, and the True
310 -- pattern had better see it.
312 ; (pat', tvs, res) <- tc_pat pstate pat pat_ty' thing_inside
313 ; return (mkCoPat coercion (L span pat') pat_ty, tvs, res) }
317 -> Pat Name -> BoxySigmaType -- Fully refined result type
318 -> (PatState -> TcM a) -- Thing inside
319 -> TcM (Pat TcId, -- Translated pattern
320 [TcTyVar], -- Existential binders
321 a) -- Result of thing inside
323 tc_pat pstate (VarPat name) pat_ty thing_inside
324 = do { id <- tcPatBndr pstate name pat_ty
325 ; (res, binds) <- bindInstsOfPatId id $
326 tcExtendIdEnv1 name id $
327 (traceTc (text "binding" <+> ppr name <+> ppr (idType id))
328 >> thing_inside pstate)
329 ; let pat' | isEmptyLHsBinds binds = VarPat id
330 | otherwise = VarPatOut id binds
331 ; return (pat', [], res) }
333 tc_pat pstate (ParPat pat) pat_ty thing_inside
334 = do { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
335 ; return (ParPat pat', tvs, res) }
337 tc_pat pstate (BangPat pat) pat_ty thing_inside
338 = do { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
339 ; return (BangPat pat', tvs, res) }
341 -- There's a wrinkle with irrefutable patterns, namely that we
342 -- must not propagate type refinement from them. For example
343 -- data T a where { T1 :: Int -> T Int; ... }
344 -- f :: T a -> Int -> a
346 -- It's obviously not sound to refine a to Int in the right
347 -- hand side, because the arugment might not match T1 at all!
349 -- Nor should a lazy pattern bind any existential type variables
350 -- because they won't be in scope when we do the desugaring
351 tc_pat pstate lpat@(LazyPat pat) pat_ty thing_inside
352 = do { (pat', pat_tvs, res) <- tc_lpat pat pat_ty pstate $ \ _ ->
354 -- Ignore refined pstate',
356 -- Check no existentials
357 ; if (null pat_tvs) then return ()
358 else lazyPatErr lpat pat_tvs
360 -- Check that the pattern has a lifted type
361 ; pat_tv <- newBoxyTyVar liftedTypeKind
362 ; boxyUnify pat_ty (mkTyVarTy pat_tv)
364 ; return (LazyPat pat', [], res) }
366 tc_pat pstate (WildPat _) pat_ty thing_inside
367 = do { pat_ty' <- unBoxWildCardType pat_ty -- Make sure it's filled in with monotypes
368 ; res <- thing_inside pstate
369 ; return (WildPat pat_ty', [], res) }
371 tc_pat pstate (AsPat (L nm_loc name) pat) pat_ty thing_inside
372 = do { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
373 ; (pat', tvs, res) <- tcExtendIdEnv1 name bndr_id $
374 tc_lpat pat (idType bndr_id) pstate thing_inside
375 -- NB: if we do inference on:
376 -- \ (y@(x::forall a. a->a)) = e
377 -- we'll fail. The as-pattern infers a monotype for 'y', which then
378 -- fails to unify with the polymorphic type for 'x'. This could
379 -- perhaps be fixed, but only with a bit more work.
381 -- If you fix it, don't forget the bindInstsOfPatIds!
382 ; return (AsPat (L nm_loc bndr_id) pat', tvs, res) }
384 -- Type signatures in patterns
385 -- See Note [Pattern coercions] below
386 tc_pat pstate (SigPatIn pat sig_ty) pat_ty thing_inside
387 = do { (inner_ty, tv_binds) <- tcPatSig (patSigCtxt pstate) sig_ty pat_ty
388 ; (pat', tvs, res) <- tcExtendTyVarEnv2 tv_binds $
389 tc_lpat pat inner_ty pstate thing_inside
390 ; return (SigPatOut pat' inner_ty, tvs, res) }
392 tc_pat pstate pat@(TypePat ty) pat_ty thing_inside
393 = failWithTc (badTypePat pat)
395 ------------------------
396 -- Lists, tuples, arrays
397 tc_pat pstate (ListPat pats _) pat_ty thing_inside
398 = do { elt_ty <- boxySplitListTy pat_ty
399 ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
400 pats pstate thing_inside
401 ; return (ListPat pats' elt_ty, pats_tvs, res) }
403 tc_pat pstate (PArrPat pats _) pat_ty thing_inside
404 = do { [elt_ty] <- boxySplitTyConApp parrTyCon pat_ty
405 ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
406 pats pstate thing_inside
407 ; ifM (null pats) (zapToMonotype pat_ty) -- c.f. ExplicitPArr in TcExpr
408 ; return (PArrPat pats' elt_ty, pats_tvs, res) }
410 tc_pat pstate (TuplePat pats boxity _) pat_ty thing_inside
411 = do { arg_tys <- boxySplitTyConApp (tupleTyCon boxity (length pats)) pat_ty
412 ; (pats', pats_tvs, res) <- tcMultiple tc_lpat_pr (pats `zip` arg_tys)
415 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
416 -- so that we can experiment with lazy tuple-matching.
417 -- This is a pretty odd place to make the switch, but
418 -- it was easy to do.
419 ; let unmangled_result = TuplePat pats' boxity pat_ty
420 possibly_mangled_result
421 | opt_IrrefutableTuples && isBoxed boxity = LazyPat (noLoc unmangled_result)
422 | otherwise = unmangled_result
424 ; ASSERT( length arg_tys == length pats ) -- Syntactically enforced
425 return (possibly_mangled_result, pats_tvs, res) }
427 ------------------------
429 tc_pat pstate pat_in@(ConPatIn (L con_span con_name) arg_pats) pat_ty thing_inside
430 = do { data_con <- tcLookupDataCon con_name
431 ; let tycon = dataConTyCon data_con
432 ; tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside }
434 ------------------------
436 tc_pat pstate (LitPat simple_lit) pat_ty thing_inside
437 = do { boxyUnify (hsLitType simple_lit) pat_ty
438 ; res <- thing_inside pstate
439 ; returnM (LitPat simple_lit, [], res) }
441 ------------------------
442 -- Overloaded patterns: n, and n+k
443 tc_pat pstate pat@(NPat over_lit mb_neg eq _) pat_ty thing_inside
444 = do { let orig = LiteralOrigin over_lit
445 ; lit' <- tcOverloadedLit orig over_lit pat_ty
446 ; eq' <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
447 ; mb_neg' <- case mb_neg of
448 Nothing -> return Nothing -- Positive literal
449 Just neg -> -- Negative literal
450 -- The 'negate' is re-mappable syntax
451 do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
452 ; return (Just neg') }
453 ; res <- thing_inside pstate
454 ; returnM (NPat lit' mb_neg' eq' pat_ty, [], res) }
456 tc_pat pstate pat@(NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
457 = do { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
458 ; let pat_ty' = idType bndr_id
459 orig = LiteralOrigin lit
460 ; lit' <- tcOverloadedLit orig lit pat_ty'
462 -- The '>=' and '-' parts are re-mappable syntax
463 ; ge' <- tcSyntaxOp orig ge (mkFunTys [pat_ty', pat_ty'] boolTy)
464 ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
466 -- The Report says that n+k patterns must be in Integral
467 -- We may not want this when using re-mappable syntax, though (ToDo?)
468 ; icls <- tcLookupClass integralClassName
469 ; instStupidTheta orig [mkClassPred icls [pat_ty']]
471 ; res <- tcExtendIdEnv1 name bndr_id (thing_inside pstate)
472 ; returnM (NPlusKPat (L nm_loc bndr_id) lit' ge' minus', [], res) }
474 tc_pat _ _other_pat _ _ = panic "tc_pat" -- DictPat, ConPatOut, SigPatOut, VarPatOut
478 %************************************************************************
480 Most of the work for constructors is here
481 (the rest is in the ConPatIn case of tc_pat)
483 %************************************************************************
485 [Pattern matching indexed data types]
486 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
487 Consider the following declarations:
489 data family Map k :: * -> *
490 data instance Map (a, b) v = MapPair (Map a (Pair b v))
492 and a case expression
494 case x :: Map (Int, c) w of MapPair m -> ...
496 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
497 worker/wrapper types for MapPair are
499 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
500 $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
502 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
503 :R123Map, which means the straight use of boxySplitTyConApp would give a type
504 error. Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
505 boxySplitTyConApp with the family tycon Map instead, which gives us the family
506 type list {(Int, c), w}. To get the correct split for :R123Map, we need to
507 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
508 (provided by tyConFamInst_maybe together with the family tycon). This
509 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
510 the split arguments for the representation tycon :R123Map as {Int, c, w}
512 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
514 Co123Map a b v :: {Map (a, b) v :=: :R123Map a b v}
516 moving between representation and family type into account. To produce type
517 correct Core, this coercion needs to be used to case the type of the scrutinee
518 from the family to the representation type. This is achieved by
519 unwrapFamInstScrutinee using a CoPat around the result pattern.
521 Now it might appear seem as if we could have used the existing GADT type
522 refinement infrastructure of refineAlt and friends instead of the explicit
523 unification and CoPat generation. However, that would be wrong. Why? The
524 whole point of GADT refinement is that the refinement is local to the case
525 alternative. In contrast, the substitution generated by the unification of
526 the family type list and instance types needs to be propagated to the outside.
527 Imagine that in the above example, the type of the scrutinee would have been
528 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
529 substitution [x -> (a, b), v -> w]. In contrast to GADT matching, the
530 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
531 alternatives of the case expression, whereas in the GADT case it might vary
532 between alternatives.
534 In fact, if we have a data instance declaration defining a GADT, eq_spec will
535 be non-empty and we will get a mixture of global instantiations and local
536 refinement from a single match. This neatly reflects that, as soon as we
537 have constrained the type of the scrutinee to the required type index, all
538 further type refinement is local to the alternative.
542 -- MkT :: forall a b c. (a:=:[b]) => b -> c -> T a
543 -- with scrutinee of type (T ty)
545 tcConPat :: PatState -> SrcSpan -> DataCon -> TyCon
546 -> BoxySigmaType -- Type of the pattern
547 -> HsConDetails Name (LPat Name) -> (PatState -> TcM a)
548 -> TcM (Pat TcId, [TcTyVar], a)
549 tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside
550 = do { span <- getSrcSpanM -- Span for the whole pattern
551 ; let (univ_tvs, ex_tvs, eq_spec, theta, arg_tys) = dataConFullSig data_con
552 skol_info = PatSkol data_con span
553 origin = SigOrigin skol_info
555 -- Instantiate the constructor type variables [a->ty]
556 ; ctxt_res_tys <- boxySplitTyConAppWithFamily tycon pat_ty
557 ; ex_tvs' <- tcInstSkolTyVars skol_info ex_tvs
558 ; let tenv = zipTopTvSubst (univ_tvs ++ ex_tvs)
559 (ctxt_res_tys ++ mkTyVarTys ex_tvs')
560 eq_spec' = substEqSpec tenv eq_spec
561 theta' = substTheta tenv theta
562 arg_tys' = substTys tenv arg_tys
564 ; co_vars <- newCoVars eq_spec' -- Make coercion variables
565 ; pstate' <- refineAlt data_con pstate ex_tvs' co_vars pat_ty
567 ; ((arg_pats', inner_tvs, res), lie_req) <- getLIE $
568 tcConArgs data_con arg_tys' arg_pats pstate' thing_inside
570 ; loc <- getInstLoc origin
571 ; dicts <- newDictBndrs loc theta'
572 ; dict_binds <- tcSimplifyCheck doc 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 doc = ptext SLIT("existential context for") <+> quotes (ppr data_con)
588 -- Split against the family tycon if the pattern constructor belongs to a
589 -- representation tycon.
591 boxySplitTyConAppWithFamily tycon pat_ty =
593 case tyConFamInst_maybe tycon of
594 Nothing -> boxySplitTyConApp tycon pat_ty
595 Just (fam_tycon, instTys) ->
596 do { scrutinee_arg_tys <- boxySplitTyConApp fam_tycon pat_ty
597 ; (_, freshTvs, subst) <- tcInstTyVars (tyConTyVars tycon)
598 ; boxyUnifyList (substTys subst instTys) scrutinee_arg_tys
602 traceMsg = sep [ text "tcConPat:boxySplitTyConAppWithFamily:" <+>
603 ppr tycon <+> ppr pat_ty
604 , text " family instance:" <+>
605 ppr (tyConFamInst_maybe tycon)
608 -- Wraps the pattern (which must be a ConPatOut pattern) in a coercion
609 -- pattern if the tycon is an instance of a family.
611 unwrapFamInstScrutinee :: TyCon -> [Type] -> Pat Id -> Pat Id
612 unwrapFamInstScrutinee tycon args pat
613 | Just co_con <- tyConFamilyCoercion_maybe tycon
614 -- , not (isNewTyCon tycon) -- newtypes are explicitly unwrapped by
616 -- NB: We can use CoPat directly, rather than mkCoPat, as we know the
617 -- coercion is not the identity; mkCoPat is inconvenient as it
618 -- wants a located pattern.
619 = CoPat (ExprCoFn $ mkTyConApp co_con args) -- co fam ty to repr ty
620 (pat {pat_ty = mkTyConApp tycon args}) -- representation type
621 pat_ty -- family inst type
626 tcConArgs :: DataCon -> [TcSigmaType]
627 -> Checker (HsConDetails Name (LPat Name))
628 (HsConDetails Id (LPat Id))
630 tcConArgs data_con arg_tys (PrefixCon arg_pats) pstate thing_inside
631 = do { checkTc (con_arity == no_of_args) -- Check correct arity
632 (arityErr "Constructor" data_con con_arity no_of_args)
633 ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
634 ; (arg_pats', tvs, res) <- tcMultiple tcConArg pats_w_tys
636 ; return (PrefixCon arg_pats', tvs, res) }
638 con_arity = dataConSourceArity data_con
639 no_of_args = length arg_pats
641 tcConArgs data_con [arg_ty1,arg_ty2] (InfixCon p1 p2) pstate thing_inside
642 = do { checkTc (con_arity == 2) -- Check correct arity
643 (arityErr "Constructor" data_con con_arity 2)
644 ; ([p1',p2'], tvs, res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
646 ; return (InfixCon p1' p2', tvs, res) }
648 con_arity = dataConSourceArity data_con
650 tcConArgs data_con other_args (InfixCon p1 p2) pstate thing_inside
651 = pprPanic "tcConArgs" (ppr data_con) -- InfixCon always has two arguments
653 tcConArgs data_con arg_tys (RecCon rpats) pstate thing_inside
654 = do { (rpats', tvs, res) <- tcMultiple tc_field rpats pstate thing_inside
655 ; return (RecCon rpats', tvs, res) }
657 tc_field :: Checker (Located Name, LPat Name) (Located TcId, LPat TcId)
658 tc_field (field_lbl, pat) pstate thing_inside
659 = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
660 ; (pat', tvs, res) <- tcConArg (pat, pat_ty) pstate thing_inside
661 ; return ((sel_id, pat'), tvs, res) }
663 find_field_ty :: FieldLabel -> TcM (Id, TcType)
664 find_field_ty field_lbl
665 = case [ty | (f,ty) <- field_tys, f == field_lbl] of
667 -- No matching field; chances are this field label comes from some
668 -- other record type (or maybe none). As well as reporting an
669 -- error we still want to typecheck the pattern, principally to
670 -- make sure that all the variables it binds are put into the
671 -- environment, else the type checker crashes later:
672 -- f (R { foo = (a,b) }) = a+b
673 -- If foo isn't one of R's fields, we don't want to crash when
674 -- typechecking the "a+b".
675 [] -> do { addErrTc (badFieldCon data_con field_lbl)
676 ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
677 ; return (error "Bogus selector Id", bogus_ty) }
679 -- The normal case, when the field comes from the right constructor
681 ASSERT( null extras )
682 do { sel_id <- tcLookupField field_lbl
683 ; return (sel_id, pat_ty) }
685 field_tys :: [(FieldLabel, TcType)]
686 field_tys = zip (dataConFieldLabels data_con) arg_tys
687 -- Don't use zipEqual! If the constructor isn't really a record, then
688 -- dataConFieldLabels will be empty (and each field in the pattern
689 -- will generate an error below).
691 tcConArg :: Checker (LPat Name, BoxySigmaType) (LPat Id)
692 tcConArg (arg_pat, arg_ty) pstate thing_inside
693 = tc_lpat arg_pat arg_ty pstate thing_inside
694 -- NB: the tc_lpat will refine pat_ty if necessary
695 -- based on the current pstate, which may include
696 -- refinements from peer argument patterns to the left
700 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
701 -- Instantiate the "stupid theta" of the data con, and throw
702 -- the constraints into the constraint set
703 addDataConStupidTheta data_con inst_tys
704 | null stupid_theta = return ()
705 | otherwise = instStupidTheta origin inst_theta
707 origin = OccurrenceOf (dataConName data_con)
708 -- The origin should always report "occurrence of C"
709 -- even when C occurs in a pattern
710 stupid_theta = dataConStupidTheta data_con
711 tenv = zipTopTvSubst (dataConUnivTyVars data_con) inst_tys
712 inst_theta = substTheta tenv stupid_theta
716 %************************************************************************
720 %************************************************************************
723 refineAlt :: DataCon -- For tracing only
725 -> [TcTyVar] -- Existentials
726 -> [CoVar] -- Equational constraints
727 -> BoxySigmaType -- Pattern type
730 refineAlt con pstate ex_tvs [] pat_ty
731 = return pstate -- Common case: no equational constraints
733 refineAlt con pstate ex_tvs co_vars pat_ty
734 | not (isRigidTy pat_ty)
735 = failWithTc (nonRigidMatch con)
736 -- We are matching against a GADT constructor with non-trivial
737 -- constraints, but pattern type is wobbly. For now we fail.
738 -- We can make sense of this, however:
739 -- Suppose MkT :: forall a b. (a:=:[b]) => b -> T a
740 -- (\x -> case x of { MkT v -> v })
741 -- We can infer that x must have type T [c], for some wobbly 'c'
743 -- (\(x::T [c]) -> case x of
744 -- MkT b (g::([c]:=:[b])) (v::b) -> v `cast` sym g
745 -- To implement this, we'd first instantiate the equational
746 -- constraints with *wobbly* type variables for the existentials;
747 -- then unify these constraints to make pat_ty the right shape;
748 -- then proceed exactly as in the rigid case
750 | otherwise -- In the rigid case, we perform type refinement
751 = case gadtRefine (pat_reft pstate) ex_tvs co_vars of {
752 Failed msg -> failWithTc (inaccessibleAlt msg) ;
753 Succeeded reft -> do { traceTc trace_msg
754 ; return (pstate { pat_reft = reft }) }
755 -- DO NOT refine the envt right away, because we
756 -- might be inside a lazy pattern. Instead, refine pstate
759 trace_msg = text "refineAlt:match" <+>
760 vcat [ ppr con <+> ppr ex_tvs,
761 ppr [(v, tyVarKind v) | v <- co_vars],
767 %************************************************************************
771 %************************************************************************
773 In tcOverloadedLit we convert directly to an Int or Integer if we
774 know that's what we want. This may save some time, by not
775 temporarily generating overloaded literals, but it won't catch all
776 cases (the rest are caught in lookupInst).
779 tcOverloadedLit :: InstOrigin
782 -> TcM (HsOverLit TcId)
783 tcOverloadedLit orig lit@(HsIntegral i fi) res_ty
784 | not (fi `isHsVar` fromIntegerName) -- Do not generate a LitInst for rebindable syntax.
785 -- Reason: If we do, tcSimplify will call lookupInst, which
786 -- will call tcSyntaxName, which does unification,
787 -- which tcSimplify doesn't like
788 -- ToDo: noLoc sadness
789 = do { integer_ty <- tcMetaTy integerTyConName
790 ; fi' <- tcSyntaxOp orig fi (mkFunTy integer_ty res_ty)
791 ; return (HsIntegral i (HsApp (noLoc fi') (nlHsLit (HsInteger i integer_ty)))) }
793 | Just expr <- shortCutIntLit i res_ty
794 = return (HsIntegral i expr)
797 = do { expr <- newLitInst orig lit res_ty
798 ; return (HsIntegral i expr) }
800 tcOverloadedLit orig lit@(HsFractional r fr) res_ty
801 | not (fr `isHsVar` fromRationalName) -- c.f. HsIntegral case
802 = do { rat_ty <- tcMetaTy rationalTyConName
803 ; fr' <- tcSyntaxOp orig fr (mkFunTy rat_ty res_ty)
804 -- Overloaded literals must have liftedTypeKind, because
805 -- we're instantiating an overloaded function here,
806 -- whereas res_ty might be openTypeKind. This was a bug in 6.2.2
807 -- However this'll be picked up by tcSyntaxOp if necessary
808 ; return (HsFractional r (HsApp (noLoc fr') (nlHsLit (HsRat r rat_ty)))) }
810 | Just expr <- shortCutFracLit r res_ty
811 = return (HsFractional r expr)
814 = do { expr <- newLitInst orig lit res_ty
815 ; return (HsFractional r expr) }
817 newLitInst :: InstOrigin -> HsOverLit Name -> BoxyRhoType -> TcM (HsExpr TcId)
818 newLitInst orig lit res_ty -- Make a LitInst
819 = do { loc <- getInstLoc orig
820 ; res_tau <- zapToMonotype res_ty
821 ; new_uniq <- newUnique
822 ; let lit_nm = mkSystemVarName new_uniq FSLIT("lit")
823 lit_inst = LitInst lit_nm lit res_tau loc
825 ; return (HsVar (instToId lit_inst)) }
829 %************************************************************************
831 Note [Pattern coercions]
833 %************************************************************************
835 In principle, these program would be reasonable:
837 f :: (forall a. a->a) -> Int
838 f (x :: Int->Int) = x 3
840 g :: (forall a. [a]) -> Bool
843 In both cases, the function type signature restricts what arguments can be passed
844 in a call (to polymorphic ones). The pattern type signature then instantiates this
845 type. For example, in the first case, (forall a. a->a) <= Int -> Int, and we
846 generate the translated term
847 f = \x' :: (forall a. a->a). let x = x' Int in x 3
849 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
850 And it requires a significant amount of code to implement, becuase we need to decorate
851 the translated pattern with coercion functions (generated from the subsumption check
854 So for now I'm just insisting on type *equality* in patterns. No subsumption.
856 Old notes about desugaring, at a time when pattern coercions were handled:
858 A SigPat is a type coercion and must be handled one at at time. We can't
859 combine them unless the type of the pattern inside is identical, and we don't
860 bother to check for that. For example:
862 data T = T1 Int | T2 Bool
863 f :: (forall a. a -> a) -> T -> t
864 f (g::Int->Int) (T1 i) = T1 (g i)
865 f (g::Bool->Bool) (T2 b) = T2 (g b)
867 We desugar this as follows:
869 f = \ g::(forall a. a->a) t::T ->
871 in case t of { T1 i -> T1 (gi i)
874 in case t of { T2 b -> T2 (gb b)
877 Note that we do not treat the first column of patterns as a
878 column of variables, because the coerced variables (gi, gb)
879 would be of different types. So we get rather grotty code.
880 But I don't think this is a common case, and if it was we could
881 doubtless improve it.
883 Meanwhile, the strategy is:
884 * treat each SigPat coercion (always non-identity coercions)
886 * deal with the stuff inside, and then wrap a binding round
887 the result to bind the new variable (gi, gb, etc)
890 %************************************************************************
892 \subsection{Errors and contexts}
894 %************************************************************************
897 patCtxt :: Pat Name -> Maybe Message -- Not all patterns are worth pushing a context
898 patCtxt (VarPat _) = Nothing
899 patCtxt (ParPat _) = Nothing
900 patCtxt (AsPat _ _) = Nothing
901 patCtxt pat = Just (hang (ptext SLIT("In the pattern:"))
904 -----------------------------------------------
906 existentialExplode pat
907 = hang (vcat [text "My brain just exploded.",
908 text "I can't handle pattern bindings for existentially-quantified constructors.",
909 text "In the binding group for"])
912 sigPatCtxt bound_ids bound_tvs pat_tys body_ty tidy_env
913 = do { pat_tys' <- mapM zonkTcType pat_tys
914 ; body_ty' <- zonkTcType body_ty
915 ; let (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
916 (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
917 (env3, tidy_body_ty) = tidyOpenType env2 body_ty'
919 sep [ptext SLIT("When checking an existential match that binds"),
920 nest 4 (vcat (zipWith ppr_id show_ids tidy_tys)),
921 ptext SLIT("The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
922 ptext SLIT("The body has type:") <+> ppr tidy_body_ty
925 show_ids = filter is_interesting bound_ids
926 is_interesting id = any (`elemVarSet` idFreeTyVars id) bound_tvs
928 ppr_id id ty = ppr id <+> dcolon <+> ppr ty
929 -- Don't zonk the types so we get the separate, un-unified versions
931 badFieldCon :: DataCon -> Name -> SDoc
932 badFieldCon con field
933 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
934 ptext SLIT("does not have field"), quotes (ppr field)]
936 polyPatSig :: TcType -> SDoc
938 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
941 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
945 hang (ptext SLIT("A lazy (~) pattern connot bind existential type variables"))
946 2 (vcat (map pprSkolTvBinding tvs))
949 = hang (ptext SLIT("GADT pattern match in non-rigid context for") <+> quotes (ppr con))
950 2 (ptext SLIT("Tell GHC HQ if you'd like this to unify the context"))
953 = hang (ptext SLIT("Inaccessible case alternative:")) 2 msg