2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 TcPat: Typechecking patterns
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 module TcPat ( tcLetPat, tcLamPat, tcLamPats, tcOverloadedLit,
17 addDataConStupidTheta, badFieldCon, polyPatSig ) where
19 #include "HsVersions.h"
21 import {-# SOURCE #-} TcExpr( tcSyntaxOp )
47 import BasicTypes hiding (SuccessFlag(..))
57 %************************************************************************
61 %************************************************************************
64 tcLetPat :: (Name -> Maybe TcRhoType)
65 -> LPat Name -> BoxySigmaType
68 tcLetPat sig_fn pat pat_ty thing_inside
69 = do { let init_state = PS { pat_ctxt = LetPat sig_fn,
70 pat_reft = emptyRefinement,
72 ; (pat', ex_tvs, res) <- tc_lpat pat pat_ty init_state (\ _ -> thing_inside)
74 -- Don't know how to deal with pattern-bound existentials yet
75 ; checkTc (null ex_tvs) (existentialExplode pat)
77 ; return (pat', res) }
80 tcLamPats :: [LPat Name] -- Patterns,
81 -> [BoxySigmaType] -- and their types
82 -> BoxyRhoType -- Result type,
83 -> ((Refinement, BoxyRhoType) -> TcM a) -- and the checker for the body
84 -> TcM ([LPat TcId], a)
86 -- This is the externally-callable wrapper function
87 -- Typecheck the patterns, extend the environment to bind the variables,
88 -- do the thing inside, use any existentially-bound dictionaries to
89 -- discharge parts of the returning LIE, and deal with pattern type
92 -- 1. Initialise the PatState
93 -- 2. Check the patterns
94 -- 3. Apply the refinement to the environment and result type
96 -- 5. Check that no existentials escape
98 tcLamPats pats tys res_ty thing_inside
99 = tc_lam_pats (zipEqual "tcLamPats" pats tys)
100 (emptyRefinement, res_ty) thing_inside
102 tcLamPat :: LPat Name -> BoxySigmaType
103 -> (Refinement,BoxyRhoType) -- Result type
104 -> ((Refinement,BoxyRhoType) -> TcM a) -- Checker for body, given its result type
105 -> TcM (LPat TcId, a)
106 tcLamPat pat pat_ty res_ty thing_inside
107 = do { ([pat'],thing) <- tc_lam_pats [(pat, pat_ty)] res_ty thing_inside
108 ; return (pat', thing) }
111 tc_lam_pats :: [(LPat Name,BoxySigmaType)]
112 -> (Refinement,BoxyRhoType) -- Result type
113 -> ((Refinement,BoxyRhoType) -> TcM a) -- Checker for body, given its result type
114 -> TcM ([LPat TcId], a)
115 tc_lam_pats pat_ty_prs (reft, res_ty) thing_inside
116 = do { let init_state = PS { pat_ctxt = LamPat, pat_reft = reft, pat_eqs = False }
118 ; (pats', ex_tvs, res) <- tcMultiple tc_lpat_pr pat_ty_prs init_state $ \ pstate' ->
119 refineEnvironment (pat_reft pstate') (pat_eqs pstate') $
120 if (pat_eqs pstate' && (not $ isRigidTy res_ty))
121 then failWithTc (nonRigidResult res_ty)
122 else thing_inside (pat_reft pstate', res_ty)
124 ; let tys = map snd pat_ty_prs
125 ; tcCheckExistentialPat pats' ex_tvs tys res_ty
127 ; returnM (pats', res) }
131 tcCheckExistentialPat :: [LPat TcId] -- Patterns (just for error message)
132 -> [TcTyVar] -- Existentially quantified tyvars bound by pattern
133 -> [BoxySigmaType] -- Types of the patterns
134 -> BoxyRhoType -- Type of the body of the match
135 -- Tyvars in either of these must not escape
137 -- NB: we *must* pass "pats_tys" not just "body_ty" to tcCheckExistentialPat
138 -- For example, we must reject this program:
139 -- data C = forall a. C (a -> Int)
141 -- Here, result_ty will be simply Int, but expected_ty is (C -> a -> Int).
143 tcCheckExistentialPat pats [] pat_tys body_ty
144 = return () -- Short cut for case when there are no existentials
146 tcCheckExistentialPat pats ex_tvs pat_tys body_ty
147 = addErrCtxtM (sigPatCtxt pats ex_tvs pat_tys body_ty) $
148 checkSigTyVarsWrt (tcTyVarsOfTypes (body_ty:pat_tys)) ex_tvs
152 pat_reft :: Refinement, -- Binds rigid TcTyVars to their refinements
153 pat_eqs :: Bool -- <=> there are GADT equational constraints
159 | LetPat (Name -> Maybe TcRhoType) -- Used for let(rec) bindings
161 patSigCtxt :: PatState -> UserTypeCtxt
162 patSigCtxt (PS { pat_ctxt = LetPat _ }) = BindPatSigCtxt
163 patSigCtxt other = LamPatSigCtxt
168 %************************************************************************
172 %************************************************************************
175 tcPatBndr :: PatState -> Name -> BoxySigmaType -> TcM TcId
176 tcPatBndr (PS { pat_ctxt = LamPat }) bndr_name pat_ty
177 = do { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
178 -- We have an undecorated binder, so we do rule ABS1,
179 -- by unboxing the boxy type, forcing any un-filled-in
180 -- boxes to become monotypes
181 -- NB that pat_ty' can still be a polytype:
182 -- data T = MkT (forall a. a->a)
183 -- f t = case t of { MkT g -> ... }
184 -- Here, the 'g' must get type (forall a. a->a) from the
186 ; return (Id.mkLocalId bndr_name pat_ty') }
188 tcPatBndr (PS { pat_ctxt = LetPat lookup_sig }) bndr_name pat_ty
189 | Just mono_ty <- lookup_sig bndr_name
190 = do { mono_name <- newLocalName bndr_name
191 ; boxyUnify mono_ty pat_ty
192 ; return (Id.mkLocalId mono_name mono_ty) }
195 = do { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
196 ; mono_name <- newLocalName bndr_name
197 ; return (Id.mkLocalId mono_name pat_ty') }
201 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, LHsBinds TcId)
202 bindInstsOfPatId id thing_inside
203 | not (isOverloadedTy (idType id))
204 = do { res <- thing_inside; return (res, emptyLHsBinds) }
206 = do { (res, lie) <- getLIE thing_inside
207 ; binds <- bindInstsOfLocalFuns lie [id]
208 ; return (res, binds) }
211 unBoxPatBndrType ty name = unBoxArgType ty (ptext SLIT("The variable") <+> quotes (ppr name))
212 unBoxWildCardType ty = unBoxArgType ty (ptext SLIT("A wild-card pattern"))
214 unBoxArgType :: BoxyType -> SDoc -> TcM TcType
215 -- In addition to calling unbox, unBoxArgType ensures that the type is of ArgTypeKind;
216 -- that is, it can't be an unboxed tuple. For example,
217 -- case (f x) of r -> ...
218 -- should fail if 'f' returns an unboxed tuple.
219 unBoxArgType ty pp_this
220 = do { ty' <- unBox ty -- Returns a zonked type
222 -- Neither conditional is strictly necesssary (the unify alone will do)
223 -- but they improve error messages, and allocate fewer tyvars
224 ; if isUnboxedTupleType ty' then
226 else if isSubArgTypeKind (typeKind ty') then
228 else do -- OpenTypeKind, so constrain it
229 { ty2 <- newFlexiTyVarTy argTypeKind
233 msg = pp_this <+> ptext SLIT("cannot be bound to an unboxed tuple")
237 %************************************************************************
239 The main worker functions
241 %************************************************************************
245 tcPat takes a "thing inside" over which the pattern scopes. This is partly
246 so that tcPat can extend the environment for the thing_inside, but also
247 so that constraints arising in the thing_inside can be discharged by the
250 This does not work so well for the ErrCtxt carried by the monad: we don't
251 want the error-context for the pattern to scope over the RHS.
252 Hence the getErrCtxt/setErrCtxt stuff in tc_lpats.
256 type Checker inp out = forall r.
259 -> (PatState -> TcM r)
260 -> TcM (out, [TcTyVar], r)
262 tcMultiple :: Checker inp out -> Checker [inp] [out]
263 tcMultiple tc_pat args pstate thing_inside
264 = do { err_ctxt <- getErrCtxt
266 = do { res <- thing_inside pstate
267 ; return ([], [], res) }
269 loop pstate (arg:args)
270 = do { (p', p_tvs, (ps', ps_tvs, res))
271 <- tc_pat arg pstate $ \ pstate' ->
272 setErrCtxt err_ctxt $
274 -- setErrCtxt: restore context before doing the next pattern
275 -- See note [Nesting] above
277 ; return (p':ps', p_tvs ++ ps_tvs, res) }
282 tc_lpat_pr :: (LPat Name, BoxySigmaType)
284 -> (PatState -> TcM a)
285 -> TcM (LPat TcId, [TcTyVar], a)
286 tc_lpat_pr (pat, ty) = tc_lpat pat ty
291 -> (PatState -> TcM a)
292 -> TcM (LPat TcId, [TcTyVar], a)
293 tc_lpat (L span pat) pat_ty pstate thing_inside
295 maybeAddErrCtxt (patCtxt pat) $
296 do { let mb_reft = refineType (pat_reft pstate) pat_ty
297 pat_ty' = case mb_reft of { Just (_, ty') -> ty'; Nothing -> pat_ty }
299 -- Make sure the result type reflects the current refinement
300 -- We must do this here, so that it correctly ``sees'' all
301 -- the refinements to the left. Example:
302 -- Suppose C :: forall a. T a -> a -> Foo
303 -- Pattern C a p1 True
304 -- So p1 might refine 'a' to True, and the True
305 -- pattern had better see it.
307 ; (pat', tvs, res) <- tc_pat pstate pat pat_ty' thing_inside
308 ; let final_pat = case mb_reft of
310 Just (co,_) -> CoPat (WpCo co) pat' pat_ty
311 ; return (L span final_pat, tvs, res) }
315 -> Pat Name -> BoxySigmaType -- Fully refined result type
316 -> (PatState -> TcM a) -- Thing inside
317 -> TcM (Pat TcId, -- Translated pattern
318 [TcTyVar], -- Existential binders
319 a) -- Result of thing inside
321 tc_pat pstate (VarPat name) pat_ty thing_inside
322 = do { id <- tcPatBndr pstate name pat_ty
323 ; (res, binds) <- bindInstsOfPatId id $
324 tcExtendIdEnv1 name id $
325 (traceTc (text "binding" <+> ppr name <+> ppr (idType id))
326 >> thing_inside pstate)
327 ; let pat' | isEmptyLHsBinds binds = VarPat id
328 | otherwise = VarPatOut id binds
329 ; return (pat', [], res) }
331 tc_pat pstate (ParPat pat) pat_ty thing_inside
332 = do { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
333 ; return (ParPat pat', tvs, res) }
335 tc_pat pstate (BangPat pat) pat_ty thing_inside
336 = do { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
337 ; return (BangPat pat', tvs, res) }
339 -- There's a wrinkle with irrefutable patterns, namely that we
340 -- must not propagate type refinement from them. For example
341 -- data T a where { T1 :: Int -> T Int; ... }
342 -- f :: T a -> Int -> a
344 -- It's obviously not sound to refine a to Int in the right
345 -- hand side, because the arugment might not match T1 at all!
347 -- Nor should a lazy pattern bind any existential type variables
348 -- because they won't be in scope when we do the desugaring
350 -- Note [Hopping the LIE in lazy patterns]
351 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
352 -- In a lazy pattern, we must *not* discharge constraints from the RHS
353 -- from dictionaries bound in the pattern. E.g.
355 -- We can't discharge the Num constraint from dictionaries bound by
358 -- So we have to make the constraints from thing_inside "hop around"
359 -- the pattern. Hence the getLLE and extendLIEs later.
361 tc_pat pstate lpat@(LazyPat pat) pat_ty thing_inside
362 = do { (pat', pat_tvs, (res,lie))
363 <- tc_lpat pat pat_ty pstate $ \ _ ->
364 getLIE (thing_inside pstate)
365 -- Ignore refined pstate', revert to pstate
367 -- getLIE/extendLIEs: see Note [Hopping the LIE in lazy patterns]
369 -- Check no existentials
370 ; if (null pat_tvs) then return ()
371 else lazyPatErr lpat pat_tvs
373 -- Check that the pattern has a lifted type
374 ; pat_tv <- newBoxyTyVar liftedTypeKind
375 ; boxyUnify pat_ty (mkTyVarTy pat_tv)
377 ; return (LazyPat pat', [], res) }
379 tc_pat pstate (WildPat _) pat_ty thing_inside
380 = do { pat_ty' <- unBoxWildCardType pat_ty -- Make sure it's filled in with monotypes
381 ; res <- thing_inside pstate
382 ; return (WildPat pat_ty', [], res) }
384 tc_pat pstate (AsPat (L nm_loc name) pat) pat_ty thing_inside
385 = do { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
386 ; (pat', tvs, res) <- tcExtendIdEnv1 name bndr_id $
387 tc_lpat pat (idType bndr_id) pstate thing_inside
388 -- NB: if we do inference on:
389 -- \ (y@(x::forall a. a->a)) = e
390 -- we'll fail. The as-pattern infers a monotype for 'y', which then
391 -- fails to unify with the polymorphic type for 'x'. This could
392 -- perhaps be fixed, but only with a bit more work.
394 -- If you fix it, don't forget the bindInstsOfPatIds!
395 ; return (AsPat (L nm_loc bndr_id) pat', tvs, res) }
397 -- Type signatures in patterns
398 -- See Note [Pattern coercions] below
399 tc_pat pstate (SigPatIn pat sig_ty) pat_ty thing_inside
400 = do { (inner_ty, tv_binds) <- tcPatSig (patSigCtxt pstate) sig_ty pat_ty
401 ; (pat', tvs, res) <- tcExtendTyVarEnv2 tv_binds $
402 tc_lpat pat inner_ty pstate thing_inside
403 ; return (SigPatOut pat' inner_ty, tvs, res) }
405 tc_pat pstate pat@(TypePat ty) pat_ty thing_inside
406 = failWithTc (badTypePat pat)
408 ------------------------
409 -- Lists, tuples, arrays
410 tc_pat pstate (ListPat pats _) pat_ty thing_inside
411 = do { elt_ty <- boxySplitListTy pat_ty
412 ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
413 pats pstate thing_inside
414 ; return (ListPat pats' elt_ty, pats_tvs, res) }
416 tc_pat pstate (PArrPat pats _) pat_ty thing_inside
417 = do { [elt_ty] <- boxySplitTyConApp parrTyCon pat_ty
418 ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
419 pats pstate thing_inside
420 ; ifM (null pats) (zapToMonotype pat_ty) -- c.f. ExplicitPArr in TcExpr
421 ; return (PArrPat pats' elt_ty, pats_tvs, res) }
423 tc_pat pstate (TuplePat pats boxity _) pat_ty thing_inside
424 = do { arg_tys <- boxySplitTyConApp (tupleTyCon boxity (length pats)) pat_ty
425 ; (pats', pats_tvs, res) <- tcMultiple tc_lpat_pr (pats `zip` arg_tys)
428 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
429 -- so that we can experiment with lazy tuple-matching.
430 -- This is a pretty odd place to make the switch, but
431 -- it was easy to do.
432 ; let unmangled_result = TuplePat pats' boxity pat_ty
433 possibly_mangled_result
434 | opt_IrrefutableTuples && isBoxed boxity = LazyPat (noLoc unmangled_result)
435 | otherwise = unmangled_result
437 ; ASSERT( length arg_tys == length pats ) -- Syntactically enforced
438 return (possibly_mangled_result, pats_tvs, res) }
440 ------------------------
442 tc_pat pstate pat_in@(ConPatIn (L con_span con_name) arg_pats) pat_ty thing_inside
443 = do { data_con <- tcLookupDataCon con_name
444 ; let tycon = dataConTyCon data_con
445 ; tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside }
447 ------------------------
449 tc_pat pstate (LitPat simple_lit) pat_ty thing_inside
450 = do { let lit_ty = hsLitType simple_lit
451 ; coi <- boxyUnify lit_ty pat_ty
452 -- coi is of kind: lit_ty ~ pat_ty
453 ; res <- thing_inside pstate
454 ; span <- getSrcSpanM
455 -- pattern coercions have to
456 -- be of kind: pat_ty ~ lit_ty
458 ; returnM (wrapPatCoI (mkSymCoI coi) (LitPat simple_lit) pat_ty, [], res) }
460 ------------------------
461 -- Overloaded patterns: n, and n+k
462 tc_pat pstate pat@(NPat over_lit mb_neg eq _) pat_ty thing_inside
463 = do { let orig = LiteralOrigin over_lit
464 ; lit' <- tcOverloadedLit orig over_lit pat_ty
465 ; eq' <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
466 ; mb_neg' <- case mb_neg of
467 Nothing -> return Nothing -- Positive literal
468 Just neg -> -- Negative literal
469 -- The 'negate' is re-mappable syntax
470 do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
471 ; return (Just neg') }
472 ; res <- thing_inside pstate
473 ; returnM (NPat lit' mb_neg' eq' pat_ty, [], res) }
475 tc_pat pstate pat@(NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
476 = do { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
477 ; let pat_ty' = idType bndr_id
478 orig = LiteralOrigin lit
479 ; lit' <- tcOverloadedLit orig lit pat_ty'
481 -- The '>=' and '-' parts are re-mappable syntax
482 ; ge' <- tcSyntaxOp orig ge (mkFunTys [pat_ty', pat_ty'] boolTy)
483 ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
485 -- The Report says that n+k patterns must be in Integral
486 -- We may not want this when using re-mappable syntax, though (ToDo?)
487 ; icls <- tcLookupClass integralClassName
488 ; instStupidTheta orig [mkClassPred icls [pat_ty']]
490 ; res <- tcExtendIdEnv1 name bndr_id (thing_inside pstate)
491 ; returnM (NPlusKPat (L nm_loc bndr_id) lit' ge' minus', [], res) }
493 tc_pat _ _other_pat _ _ = panic "tc_pat" -- ConPatOut, SigPatOut, VarPatOut
497 %************************************************************************
499 Most of the work for constructors is here
500 (the rest is in the ConPatIn case of tc_pat)
502 %************************************************************************
504 [Pattern matching indexed data types]
505 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
506 Consider the following declarations:
508 data family Map k :: * -> *
509 data instance Map (a, b) v = MapPair (Map a (Pair b v))
511 and a case expression
513 case x :: Map (Int, c) w of MapPair m -> ...
515 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
516 worker/wrapper types for MapPair are
518 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
519 $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
521 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
522 :R123Map, which means the straight use of boxySplitTyConApp would give a type
523 error. Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
524 boxySplitTyConApp with the family tycon Map instead, which gives us the family
525 type list {(Int, c), w}. To get the correct split for :R123Map, we need to
526 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
527 (provided by tyConFamInst_maybe together with the family tycon). This
528 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
529 the split arguments for the representation tycon :R123Map as {Int, c, w}
531 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
533 Co123Map a b v :: {Map (a, b) v :=: :R123Map a b v}
535 moving between representation and family type into account. To produce type
536 correct Core, this coercion needs to be used to case the type of the scrutinee
537 from the family to the representation type. This is achieved by
538 unwrapFamInstScrutinee using a CoPat around the result pattern.
540 Now it might appear seem as if we could have used the existing GADT type
541 refinement infrastructure of refineAlt and friends instead of the explicit
542 unification and CoPat generation. However, that would be wrong. Why? The
543 whole point of GADT refinement is that the refinement is local to the case
544 alternative. In contrast, the substitution generated by the unification of
545 the family type list and instance types needs to be propagated to the outside.
546 Imagine that in the above example, the type of the scrutinee would have been
547 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
548 substitution [x -> (a, b), v -> w]. In contrast to GADT matching, the
549 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
550 alternatives of the case expression, whereas in the GADT case it might vary
551 between alternatives.
553 In fact, if we have a data instance declaration defining a GADT, eq_spec will
554 be non-empty and we will get a mixture of global instantiations and local
555 refinement from a single match. This neatly reflects that, as soon as we
556 have constrained the type of the scrutinee to the required type index, all
557 further type refinement is local to the alternative.
561 -- MkT :: forall a b c. (a:=:[b]) => b -> c -> T a
562 -- with scrutinee of type (T ty)
564 tcConPat :: PatState -> SrcSpan -> DataCon -> TyCon
565 -> BoxySigmaType -- Type of the pattern
566 -> HsConPatDetails Name -> (PatState -> TcM a)
567 -> TcM (Pat TcId, [TcTyVar], a)
568 tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside
569 = do { let (univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _) = dataConFullSig data_con
570 skol_info = PatSkol data_con
571 origin = SigOrigin skol_info
573 -- Instantiate the constructor type variables [a->ty]
574 ; ctxt_res_tys <- boxySplitTyConAppWithFamily tycon pat_ty
575 ; ex_tvs' <- tcInstSkolTyVars skol_info ex_tvs -- Get location from monad,
577 ; let tenv = zipTopTvSubst (univ_tvs ++ ex_tvs)
578 (ctxt_res_tys ++ mkTyVarTys ex_tvs')
579 eq_spec' = substEqSpec tenv eq_spec
580 theta' = substTheta tenv (eq_theta ++ dict_theta)
581 arg_tys' = substTys tenv arg_tys
583 ; co_vars <- newCoVars eq_spec' -- Make coercion variables
584 ; pstate' <- refineAlt data_con pstate ex_tvs' co_vars pat_ty
586 ; ((arg_pats', inner_tvs, res), lie_req) <- getLIE $
587 tcConArgs data_con arg_tys' arg_pats pstate' thing_inside
589 ; loc <- getInstLoc origin
590 ; dicts <- newDictBndrs loc theta'
591 ; dict_binds <- tcSimplifyCheckPat loc co_vars (pat_reft pstate')
592 ex_tvs' dicts lie_req
594 ; addDataConStupidTheta data_con ctxt_res_tys
597 (unwrapFamInstScrutinee tycon ctxt_res_tys $
598 ConPatOut { pat_con = L con_span data_con,
599 pat_tvs = ex_tvs' ++ co_vars,
600 pat_dicts = map instToVar dicts,
601 pat_binds = dict_binds,
602 pat_args = arg_pats', pat_ty = pat_ty },
603 ex_tvs' ++ inner_tvs, res)
606 -- Split against the family tycon if the pattern constructor
607 -- belongs to a family instance tycon.
608 boxySplitTyConAppWithFamily tycon pat_ty =
610 case tyConFamInst_maybe tycon of
611 Nothing -> boxySplitTyConApp tycon pat_ty
612 Just (fam_tycon, instTys) ->
613 do { scrutinee_arg_tys <- boxySplitTyConApp fam_tycon pat_ty
614 ; (_, freshTvs, subst) <- tcInstTyVars (tyConTyVars tycon)
615 ; boxyUnifyList (substTys subst instTys) scrutinee_arg_tys
619 traceMsg = sep [ text "tcConPat:boxySplitTyConAppWithFamily:" <+>
620 ppr tycon <+> ppr pat_ty
621 , text " family instance:" <+>
622 ppr (tyConFamInst_maybe tycon)
625 -- Wraps the pattern (which must be a ConPatOut pattern) in a coercion
626 -- pattern if the tycon is an instance of a family.
628 unwrapFamInstScrutinee :: TyCon -> [Type] -> Pat Id -> Pat Id
629 unwrapFamInstScrutinee tycon args pat
630 | Just co_con <- tyConFamilyCoercion_maybe tycon
631 -- , not (isNewTyCon tycon) -- newtypes are explicitly unwrapped by
633 -- NB: We can use CoPat directly, rather than mkCoPat, as we know the
634 -- coercion is not the identity; mkCoPat is inconvenient as it
635 -- wants a located pattern.
636 = CoPat (WpCo $ mkTyConApp co_con args) -- co fam ty to repr ty
637 (pat {pat_ty = mkTyConApp tycon args}) -- representation type
638 pat_ty -- family inst type
643 tcConArgs :: DataCon -> [TcSigmaType]
644 -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
646 tcConArgs data_con arg_tys (PrefixCon arg_pats) pstate thing_inside
647 = do { checkTc (con_arity == no_of_args) -- Check correct arity
648 (arityErr "Constructor" data_con con_arity no_of_args)
649 ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
650 ; (arg_pats', tvs, res) <- tcMultiple tcConArg pats_w_tys
652 ; return (PrefixCon arg_pats', tvs, res) }
654 con_arity = dataConSourceArity data_con
655 no_of_args = length arg_pats
657 tcConArgs data_con [arg_ty1,arg_ty2] (InfixCon p1 p2) pstate thing_inside
658 = do { checkTc (con_arity == 2) -- Check correct arity
659 (arityErr "Constructor" data_con con_arity 2)
660 ; ([p1',p2'], tvs, res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
662 ; return (InfixCon p1' p2', tvs, res) }
664 con_arity = dataConSourceArity data_con
666 tcConArgs data_con other_args (InfixCon p1 p2) pstate thing_inside
667 = pprPanic "tcConArgs" (ppr data_con) -- InfixCon always has two arguments
669 tcConArgs data_con arg_tys (RecCon (HsRecFields rpats dd)) pstate thing_inside
670 = do { (rpats', tvs, res) <- tcMultiple tc_field rpats pstate thing_inside
671 ; return (RecCon (HsRecFields rpats' dd), tvs, res) }
673 tc_field :: Checker (HsRecField FieldLabel (LPat Name)) (HsRecField TcId (LPat TcId))
674 tc_field (HsRecField field_lbl pat pun) pstate thing_inside
675 = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
676 ; (pat', tvs, res) <- tcConArg (pat, pat_ty) pstate thing_inside
677 ; return (HsRecField sel_id pat' pun, tvs, res) }
679 find_field_ty :: FieldLabel -> TcM (Id, TcType)
680 find_field_ty field_lbl
681 = case [ty | (f,ty) <- field_tys, f == field_lbl] of
683 -- No matching field; chances are this field label comes from some
684 -- other record type (or maybe none). As well as reporting an
685 -- error we still want to typecheck the pattern, principally to
686 -- make sure that all the variables it binds are put into the
687 -- environment, else the type checker crashes later:
688 -- f (R { foo = (a,b) }) = a+b
689 -- If foo isn't one of R's fields, we don't want to crash when
690 -- typechecking the "a+b".
691 [] -> do { addErrTc (badFieldCon data_con field_lbl)
692 ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
693 ; return (error "Bogus selector Id", bogus_ty) }
695 -- The normal case, when the field comes from the right constructor
697 ASSERT( null extras )
698 do { sel_id <- tcLookupField field_lbl
699 ; return (sel_id, pat_ty) }
701 field_tys :: [(FieldLabel, TcType)]
702 field_tys = zip (dataConFieldLabels data_con) arg_tys
703 -- Don't use zipEqual! If the constructor isn't really a record, then
704 -- dataConFieldLabels will be empty (and each field in the pattern
705 -- will generate an error below).
707 tcConArg :: Checker (LPat Name, BoxySigmaType) (LPat Id)
708 tcConArg (arg_pat, arg_ty) pstate thing_inside
709 = tc_lpat arg_pat arg_ty pstate thing_inside
710 -- NB: the tc_lpat will refine pat_ty if necessary
711 -- based on the current pstate, which may include
712 -- refinements from peer argument patterns to the left
716 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
717 -- Instantiate the "stupid theta" of the data con, and throw
718 -- the constraints into the constraint set
719 addDataConStupidTheta data_con inst_tys
720 | null stupid_theta = return ()
721 | otherwise = instStupidTheta origin inst_theta
723 origin = OccurrenceOf (dataConName data_con)
724 -- The origin should always report "occurrence of C"
725 -- even when C occurs in a pattern
726 stupid_theta = dataConStupidTheta data_con
727 tenv = zipTopTvSubst (dataConUnivTyVars data_con) inst_tys
728 inst_theta = substTheta tenv stupid_theta
732 %************************************************************************
736 %************************************************************************
739 refineAlt :: DataCon -- For tracing only
741 -> [TcTyVar] -- Existentials
742 -> [CoVar] -- Equational constraints
743 -> BoxySigmaType -- Pattern type
746 refineAlt con pstate ex_tvs [] pat_ty
747 | null $ dataConEqTheta con
748 = return pstate -- Common case: no equational constraints
750 refineAlt con pstate ex_tvs co_vars pat_ty
751 = do { opt_gadt <- doptM Opt_GADTs -- No type-refinement unless GADTs are on
752 ; if (not opt_gadt) then return pstate
755 { checkTc (isRigidTy pat_ty) (nonRigidMatch con)
756 -- We are matching against a GADT constructor with non-trivial
757 -- constraints, but pattern type is wobbly. For now we fail.
758 -- We can make sense of this, however:
759 -- Suppose MkT :: forall a b. (a:=:[b]) => b -> T a
760 -- (\x -> case x of { MkT v -> v })
761 -- We can infer that x must have type T [c], for some wobbly 'c'
763 -- (\(x::T [c]) -> case x of
764 -- MkT b (g::([c]:=:[b])) (v::b) -> v `cast` sym g
765 -- To implement this, we'd first instantiate the equational
766 -- constraints with *wobbly* type variables for the existentials;
767 -- then unify these constraints to make pat_ty the right shape;
768 -- then proceed exactly as in the rigid case
770 -- In the rigid case, we perform type refinement
771 ; case gadtRefine (pat_reft pstate) ex_tvs co_vars of {
772 Failed msg -> failWithTc (inaccessibleAlt msg) ;
773 Succeeded reft -> do { traceTc trace_msg
774 ; return (pstate { pat_reft = reft, pat_eqs = (pat_eqs pstate || not (null $ dataConEqTheta con)) }) }
775 -- DO NOT refine the envt right away, because we
776 -- might be inside a lazy pattern. Instead, refine pstate
779 trace_msg = text "refineAlt:match" <+>
780 vcat [ ppr con <+> ppr ex_tvs,
781 ppr [(v, tyVarKind v) | v <- co_vars],
787 %************************************************************************
791 %************************************************************************
793 In tcOverloadedLit we convert directly to an Int or Integer if we
794 know that's what we want. This may save some time, by not
795 temporarily generating overloaded literals, but it won't catch all
796 cases (the rest are caught in lookupInst).
799 tcOverloadedLit :: InstOrigin
802 -> TcM (HsOverLit TcId)
803 tcOverloadedLit orig lit@(HsIntegral i fi) res_ty
804 | not (fi `isHsVar` fromIntegerName) -- Do not generate a LitInst for rebindable syntax.
805 -- Reason: If we do, tcSimplify will call lookupInst, which
806 -- will call tcSyntaxName, which does unification,
807 -- which tcSimplify doesn't like
808 -- ToDo: noLoc sadness
809 = do { integer_ty <- tcMetaTy integerTyConName
810 ; fi' <- tcSyntaxOp orig fi (mkFunTy integer_ty res_ty)
811 ; return (HsIntegral i (HsApp (noLoc fi') (nlHsLit (HsInteger i integer_ty)))) }
813 | Just expr <- shortCutIntLit i res_ty
814 = return (HsIntegral i expr)
817 = do { expr <- newLitInst orig lit res_ty
818 ; return (HsIntegral i expr) }
820 tcOverloadedLit orig lit@(HsFractional r fr) res_ty
821 | not (fr `isHsVar` fromRationalName) -- c.f. HsIntegral case
822 = do { rat_ty <- tcMetaTy rationalTyConName
823 ; fr' <- tcSyntaxOp orig fr (mkFunTy rat_ty res_ty)
824 -- Overloaded literals must have liftedTypeKind, because
825 -- we're instantiating an overloaded function here,
826 -- whereas res_ty might be openTypeKind. This was a bug in 6.2.2
827 -- However this'll be picked up by tcSyntaxOp if necessary
828 ; return (HsFractional r (HsApp (noLoc fr') (nlHsLit (HsRat r rat_ty)))) }
830 | Just expr <- shortCutFracLit r res_ty
831 = return (HsFractional r expr)
834 = do { expr <- newLitInst orig lit res_ty
835 ; return (HsFractional r expr) }
837 tcOverloadedLit orig lit@(HsIsString s fr) res_ty
838 | not (fr `isHsVar` fromStringName) -- c.f. HsIntegral case
839 = do { str_ty <- tcMetaTy stringTyConName
840 ; fr' <- tcSyntaxOp orig fr (mkFunTy str_ty res_ty)
841 ; return (HsIsString s (HsApp (noLoc fr') (nlHsLit (HsString s)))) }
843 | Just expr <- shortCutStringLit s res_ty
844 = return (HsIsString s expr)
847 = do { expr <- newLitInst orig lit res_ty
848 ; return (HsIsString s expr) }
850 newLitInst :: InstOrigin -> HsOverLit Name -> BoxyRhoType -> TcM (HsExpr TcId)
851 newLitInst orig lit res_ty -- Make a LitInst
852 = do { loc <- getInstLoc orig
853 ; res_tau <- zapToMonotype res_ty
854 ; new_uniq <- newUnique
855 ; let lit_nm = mkSystemVarName new_uniq FSLIT("lit")
856 lit_inst = LitInst {tci_name = lit_nm, tci_lit = lit,
857 tci_ty = res_tau, tci_loc = loc}
859 ; return (HsVar (instToId lit_inst)) }
863 %************************************************************************
865 Note [Pattern coercions]
867 %************************************************************************
869 In principle, these program would be reasonable:
871 f :: (forall a. a->a) -> Int
872 f (x :: Int->Int) = x 3
874 g :: (forall a. [a]) -> Bool
877 In both cases, the function type signature restricts what arguments can be passed
878 in a call (to polymorphic ones). The pattern type signature then instantiates this
879 type. For example, in the first case, (forall a. a->a) <= Int -> Int, and we
880 generate the translated term
881 f = \x' :: (forall a. a->a). let x = x' Int in x 3
883 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
884 And it requires a significant amount of code to implement, becuase we need to decorate
885 the translated pattern with coercion functions (generated from the subsumption check
888 So for now I'm just insisting on type *equality* in patterns. No subsumption.
890 Old notes about desugaring, at a time when pattern coercions were handled:
892 A SigPat is a type coercion and must be handled one at at time. We can't
893 combine them unless the type of the pattern inside is identical, and we don't
894 bother to check for that. For example:
896 data T = T1 Int | T2 Bool
897 f :: (forall a. a -> a) -> T -> t
898 f (g::Int->Int) (T1 i) = T1 (g i)
899 f (g::Bool->Bool) (T2 b) = T2 (g b)
901 We desugar this as follows:
903 f = \ g::(forall a. a->a) t::T ->
905 in case t of { T1 i -> T1 (gi i)
908 in case t of { T2 b -> T2 (gb b)
911 Note that we do not treat the first column of patterns as a
912 column of variables, because the coerced variables (gi, gb)
913 would be of different types. So we get rather grotty code.
914 But I don't think this is a common case, and if it was we could
915 doubtless improve it.
917 Meanwhile, the strategy is:
918 * treat each SigPat coercion (always non-identity coercions)
920 * deal with the stuff inside, and then wrap a binding round
921 the result to bind the new variable (gi, gb, etc)
924 %************************************************************************
926 \subsection{Errors and contexts}
928 %************************************************************************
931 patCtxt :: Pat Name -> Maybe Message -- Not all patterns are worth pushing a context
932 patCtxt (VarPat _) = Nothing
933 patCtxt (ParPat _) = Nothing
934 patCtxt (AsPat _ _) = Nothing
935 patCtxt pat = Just (hang (ptext SLIT("In the pattern:"))
938 -----------------------------------------------
940 existentialExplode pat
941 = hang (vcat [text "My brain just exploded.",
942 text "I can't handle pattern bindings for existentially-quantified constructors.",
943 text "Instead, use a case-expression, or do-notation, to unpack the constructor.",
944 text "In the binding group for"])
947 sigPatCtxt pats bound_tvs pat_tys body_ty tidy_env
948 = do { pat_tys' <- mapM zonkTcType pat_tys
949 ; body_ty' <- zonkTcType body_ty
950 ; let (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
951 (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
952 (env3, tidy_body_ty) = tidyOpenType env2 body_ty'
954 sep [ptext SLIT("When checking an existential match that binds"),
955 nest 4 (vcat (zipWith ppr_id show_ids tidy_tys)),
956 ptext SLIT("The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
957 ptext SLIT("The body has type:") <+> ppr tidy_body_ty
960 bound_ids = collectPatsBinders pats
961 show_ids = filter is_interesting bound_ids
962 is_interesting id = any (`elemVarSet` varTypeTyVars id) bound_tvs
964 ppr_id id ty = ppr id <+> dcolon <+> ppr ty
965 -- Don't zonk the types so we get the separate, un-unified versions
967 badFieldCon :: DataCon -> Name -> SDoc
968 badFieldCon con field
969 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
970 ptext SLIT("does not have field"), quotes (ppr field)]
972 polyPatSig :: TcType -> SDoc
974 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
977 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
981 hang (ptext SLIT("A lazy (~) pattern cannot bind existential type variables"))
982 2 (vcat (map pprSkolTvBinding tvs))
985 = hang (ptext SLIT("GADT pattern match in non-rigid context for") <+> quotes (ppr con))
986 2 (ptext SLIT("Tell GHC HQ if you'd like this to unify the context"))
988 nonRigidResult res_ty
989 = hang (ptext SLIT("GADT pattern match with non-rigid result type") <+> quotes (ppr res_ty))
990 2 (ptext SLIT("Tell GHC HQ if you'd like this to unify the context"))
993 = hang (ptext SLIT("Inaccessible case alternative:")) 2 msg
997 wrapPatCoI :: CoercionI -> Pat a -> TcType -> Pat a
998 wrapPatCoI IdCo pat ty = pat
999 wrapPatCoI (ACo co) pat ty = CoPat (WpCo co) pat ty