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(..), HsOverLit(..), HsExpr(..),
15 LHsBinds, emptyLHsBinds, isEmptyLHsBinds,
16 collectPatsBinders, nlHsLit )
17 import TcHsSyn ( TcId, hsLitType )
19 import Inst ( InstOrigin(..), shortCutFracLit, shortCutIntLit,
20 newDictBndrs, instToId, instStupidTheta, isHsVar
22 import Id ( Id, idType, mkLocalId )
23 import CoreFVs ( idFreeTyVars )
24 import Name ( Name, mkSystemVarName )
25 import TcSimplify ( tcSimplifyCheck, bindInstsOfLocalFuns )
26 import TcEnv ( newLocalName, tcExtendIdEnv1, tcExtendTyVarEnv2,
27 tcLookupClass, tcLookupDataCon, refineEnvironment,
28 tcLookupField, tcMetaTy )
29 import TcMType ( newFlexiTyVarTy, arityErr, tcInstSkolTyVars,
30 + newCoVars, zonkTcType )
31 import TcType ( TcType, TcTyVar, TcSigmaType, TcRhoType, BoxyType,
33 BoxySigmaType, BoxyRhoType, argTypeKind, typeKind,
34 pprSkolTvBinding, isRigidTy, tcTyVarsOfTypes,
35 zipTopTvSubst, isArgTypeKind, isUnboxedTupleType,
36 mkTyVarTys, mkClassPred, isOverloadedTy, substEqSpec,
37 mkFunTy, mkFunTys, tidyOpenType, tidyOpenTypes )
38 import VarSet ( elemVarSet )
39 import {- Kind parts of -}
40 Type ( liftedTypeKind )
41 import TcUnify ( boxySplitTyConApp, boxySplitListTy, unBox,
42 zapToMonotype, boxyUnify, checkSigTyVarsWrt,
44 import TcHsType ( UserTypeCtxt(..), tcPatSig )
45 import TysWiredIn ( boolTy, parrTyCon, tupleTyCon )
46 import Type ( substTys, substTheta )
47 import StaticFlags ( opt_IrrefutableTuples )
48 import TyCon ( TyCon, FieldLabel )
49 import DataCon ( DataCon, dataConTyCon, dataConFullSig, dataConName,
50 dataConFieldLabels, dataConSourceArity,
51 dataConStupidTheta, dataConUnivTyVars )
52 import PrelNames ( integralClassName, fromIntegerName, integerTyConName,
53 fromRationalName, rationalTyConName )
54 import BasicTypes ( isBoxed )
55 import SrcLoc ( Located(..), SrcSpan, noLoc )
56 import ErrUtils ( Message )
57 import Util ( zipEqual )
58 import Maybes ( MaybeErr(..) )
64 %************************************************************************
68 %************************************************************************
71 tcLetPat :: (Name -> Maybe TcRhoType)
72 -> LPat Name -> BoxySigmaType
75 tcLetPat sig_fn pat pat_ty thing_inside
76 = do { let init_state = PS { pat_ctxt = LetPat sig_fn,
77 pat_reft = emptyRefinement }
78 ; (pat', ex_tvs, res) <- tc_lpat pat pat_ty init_state (\ _ -> thing_inside)
80 -- Don't know how to deal with pattern-bound existentials yet
81 ; checkTc (null ex_tvs) (existentialExplode pat)
83 ; return (pat', res) }
86 tcLamPats :: [LPat Name] -- Patterns,
87 -> [BoxySigmaType] -- and their types
88 -> BoxyRhoType -- Result type,
89 -> ((Refinement, BoxyRhoType) -> TcM a) -- and the checker for the body
90 -> TcM ([LPat TcId], a)
92 -- This is the externally-callable wrapper function
93 -- Typecheck the patterns, extend the environment to bind the variables,
94 -- do the thing inside, use any existentially-bound dictionaries to
95 -- discharge parts of the returning LIE, and deal with pattern type
98 -- 1. Initialise the PatState
99 -- 2. Check the patterns
100 -- 3. Apply the refinement to the environment and result type
102 -- 5. Check that no existentials escape
104 tcLamPats pats tys res_ty thing_inside
105 = tc_lam_pats (zipEqual "tcLamPats" pats tys)
106 (emptyRefinement, res_ty) thing_inside
108 tcLamPat :: LPat Name -> BoxySigmaType
109 -> (Refinement,BoxyRhoType) -- Result type
110 -> ((Refinement,BoxyRhoType) -> TcM a) -- Checker for body, given its result type
111 -> TcM (LPat TcId, a)
112 tcLamPat pat pat_ty res_ty thing_inside
113 = do { ([pat'],thing) <- tc_lam_pats [(pat, pat_ty)] res_ty thing_inside
114 ; return (pat', thing) }
117 tc_lam_pats :: [(LPat Name,BoxySigmaType)]
118 -> (Refinement,BoxyRhoType) -- Result type
119 -> ((Refinement,BoxyRhoType) -> TcM a) -- Checker for body, given its result type
120 -> TcM ([LPat TcId], a)
121 tc_lam_pats pat_ty_prs (reft, res_ty) thing_inside
122 = do { let init_state = PS { pat_ctxt = LamPat, pat_reft = reft }
124 ; (pats', ex_tvs, res) <- tcMultiple tc_lpat_pr pat_ty_prs init_state $ \ pstate' ->
125 refineEnvironment (pat_reft pstate') $
126 thing_inside (pat_reft pstate', res_ty)
128 ; let tys = map snd pat_ty_prs
129 ; tcCheckExistentialPat pats' ex_tvs tys res_ty
131 ; returnM (pats', res) }
135 tcCheckExistentialPat :: [LPat TcId] -- Patterns (just for error message)
136 -> [TcTyVar] -- Existentially quantified tyvars bound by pattern
137 -> [BoxySigmaType] -- Types of the patterns
138 -> BoxyRhoType -- Type of the body of the match
139 -- Tyvars in either of these must not escape
141 -- NB: we *must* pass "pats_tys" not just "body_ty" to tcCheckExistentialPat
142 -- For example, we must reject this program:
143 -- data C = forall a. C (a -> Int)
145 -- Here, result_ty will be simply Int, but expected_ty is (C -> a -> Int).
147 tcCheckExistentialPat pats [] pat_tys body_ty
148 = return () -- Short cut for case when there are no existentials
150 tcCheckExistentialPat pats ex_tvs pat_tys body_ty
151 = addErrCtxtM (sigPatCtxt (collectPatsBinders pats) ex_tvs pat_tys body_ty) $
152 checkSigTyVarsWrt (tcTyVarsOfTypes (body_ty:pat_tys)) ex_tvs
156 pat_reft :: Refinement -- Binds rigid TcTyVars to their refinements
161 | LetPat (Name -> Maybe TcRhoType) -- Used for let(rec) bindings
163 patSigCtxt :: PatState -> UserTypeCtxt
164 patSigCtxt (PS { pat_ctxt = LetPat _ }) = BindPatSigCtxt
165 patSigCtxt other = LamPatSigCtxt
170 %************************************************************************
174 %************************************************************************
177 tcPatBndr :: PatState -> Name -> BoxySigmaType -> TcM TcId
178 tcPatBndr (PS { pat_ctxt = LamPat }) bndr_name pat_ty
179 = do { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
180 -- We have an undecorated binder, so we do rule ABS1,
181 -- by unboxing the boxy type, forcing any un-filled-in
182 -- boxes to become monotypes
183 -- NB that pat_ty' can still be a polytype:
184 -- data T = MkT (forall a. a->a)
185 -- f t = case t of { MkT g -> ... }
186 -- Here, the 'g' must get type (forall a. a->a) from the
188 ; return (mkLocalId bndr_name pat_ty') }
190 tcPatBndr (PS { pat_ctxt = LetPat lookup_sig }) bndr_name pat_ty
191 | Just mono_ty <- lookup_sig bndr_name
192 = do { mono_name <- newLocalName bndr_name
193 ; boxyUnify mono_ty pat_ty
194 ; return (mkLocalId mono_name mono_ty) }
197 = do { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
198 ; mono_name <- newLocalName bndr_name
199 ; return (mkLocalId mono_name pat_ty') }
203 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, LHsBinds TcId)
204 bindInstsOfPatId id thing_inside
205 | not (isOverloadedTy (idType id))
206 = do { res <- thing_inside; return (res, emptyLHsBinds) }
208 = do { (res, lie) <- getLIE thing_inside
209 ; binds <- bindInstsOfLocalFuns lie [id]
210 ; return (res, binds) }
213 unBoxPatBndrType ty name = unBoxArgType ty (ptext SLIT("The variable") <+> quotes (ppr name))
214 unBoxWildCardType ty = unBoxArgType ty (ptext SLIT("A wild-card pattern"))
216 unBoxArgType :: BoxyType -> SDoc -> TcM TcType
217 -- In addition to calling unbox, unBoxArgType ensures that the type is of ArgTypeKind;
218 -- that is, it can't be an unboxed tuple. For example,
219 -- case (f x) of r -> ...
220 -- should fail if 'f' returns an unboxed tuple.
221 unBoxArgType ty pp_this
222 = do { ty' <- unBox ty -- Returns a zonked type
224 -- Neither conditional is strictly necesssary (the unify alone will do)
225 -- but they improve error messages, and allocate fewer tyvars
226 ; if isUnboxedTupleType ty' then
228 else if isArgTypeKind (typeKind ty') then
230 else do -- OpenTypeKind, so constrain it
231 { ty2 <- newFlexiTyVarTy argTypeKind
235 msg = pp_this <+> ptext SLIT("cannot be bound to an unboxed tuple")
239 %************************************************************************
241 The main worker functions
243 %************************************************************************
247 tcPat takes a "thing inside" over which the patter scopes. This is partly
248 so that tcPat can extend the environment for the thing_inside, but also
249 so that constraints arising in the thing_inside can be discharged by the
252 This does not work so well for the ErrCtxt carried by the monad: we don't
253 want the error-context for the pattern to scope over the RHS.
254 Hence the getErrCtxt/setErrCtxt stuff in tc_lpats.
258 type Checker inp out = forall r.
261 -> (PatState -> TcM r)
262 -> TcM (out, [TcTyVar], r)
264 tcMultiple :: Checker inp out -> Checker [inp] [out]
265 tcMultiple tc_pat args pstate thing_inside
266 = do { err_ctxt <- getErrCtxt
268 = do { res <- thing_inside pstate
269 ; return ([], [], res) }
271 loop pstate (arg:args)
272 = do { (p', p_tvs, (ps', ps_tvs, res))
273 <- tc_pat arg pstate $ \ pstate' ->
274 setErrCtxt err_ctxt $
276 -- setErrCtxt: restore context before doing the next pattern
277 -- See note [Nesting] above
279 ; return (p':ps', p_tvs ++ ps_tvs, res) }
284 tc_lpat_pr :: (LPat Name, BoxySigmaType)
286 -> (PatState -> TcM a)
287 -> TcM (LPat TcId, [TcTyVar], a)
288 tc_lpat_pr (pat, ty) = tc_lpat pat ty
293 -> (PatState -> TcM a)
294 -> TcM (LPat TcId, [TcTyVar], a)
295 tc_lpat (L span pat) pat_ty pstate thing_inside
297 maybeAddErrCtxt (patCtxt pat) $
298 do { let (coercion, pat_ty') = refineType (pat_reft pstate) 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 ; return (mkCoPat coercion (L span pat') pat_ty, tvs, res) }
312 -> Pat Name -> BoxySigmaType -- Fully refined result type
313 -> (PatState -> TcM a) -- Thing inside
314 -> TcM (Pat TcId, -- Translated pattern
315 [TcTyVar], -- Existential binders
316 a) -- Result of thing inside
318 tc_pat pstate (VarPat name) pat_ty thing_inside
319 = do { id <- tcPatBndr pstate name pat_ty
320 ; (res, binds) <- bindInstsOfPatId id $
321 tcExtendIdEnv1 name id $
322 (traceTc (text "binding" <+> ppr name <+> ppr (idType id))
323 >> thing_inside pstate)
324 ; let pat' | isEmptyLHsBinds binds = VarPat id
325 | otherwise = VarPatOut id binds
326 ; return (pat', [], res) }
328 tc_pat pstate (ParPat pat) pat_ty thing_inside
329 = do { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
330 ; return (ParPat pat', tvs, res) }
332 tc_pat pstate (BangPat pat) pat_ty thing_inside
333 = do { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
334 ; return (BangPat pat', tvs, res) }
336 -- There's a wrinkle with irrefutable patterns, namely that we
337 -- must not propagate type refinement from them. For example
338 -- data T a where { T1 :: Int -> T Int; ... }
339 -- f :: T a -> Int -> a
341 -- It's obviously not sound to refine a to Int in the right
342 -- hand side, because the arugment might not match T1 at all!
344 -- Nor should a lazy pattern bind any existential type variables
345 -- because they won't be in scope when we do the desugaring
346 tc_pat pstate lpat@(LazyPat pat) pat_ty thing_inside
347 = do { (pat', pat_tvs, res) <- tc_lpat pat pat_ty pstate $ \ _ ->
349 -- Ignore refined pstate',
351 -- Check no existentials
352 ; if (null pat_tvs) then return ()
353 else lazyPatErr lpat pat_tvs
355 -- Check that the pattern has a lifted type
356 ; pat_tv <- newBoxyTyVar liftedTypeKind
357 ; boxyUnify pat_ty (mkTyVarTy pat_tv)
359 ; return (LazyPat pat', [], res) }
361 tc_pat pstate (WildPat _) pat_ty thing_inside
362 = do { pat_ty' <- unBoxWildCardType pat_ty -- Make sure it's filled in with monotypes
363 ; res <- thing_inside pstate
364 ; return (WildPat pat_ty', [], res) }
366 tc_pat pstate (AsPat (L nm_loc name) pat) pat_ty thing_inside
367 = do { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
368 ; (pat', tvs, res) <- tcExtendIdEnv1 name bndr_id $
369 tc_lpat pat (idType bndr_id) pstate thing_inside
370 -- NB: if we do inference on:
371 -- \ (y@(x::forall a. a->a)) = e
372 -- we'll fail. The as-pattern infers a monotype for 'y', which then
373 -- fails to unify with the polymorphic type for 'x'. This could
374 -- perhaps be fixed, but only with a bit more work.
376 -- If you fix it, don't forget the bindInstsOfPatIds!
377 ; return (AsPat (L nm_loc bndr_id) pat', tvs, res) }
379 -- Type signatures in patterns
380 -- See Note [Pattern coercions] below
381 tc_pat pstate (SigPatIn pat sig_ty) pat_ty thing_inside
382 = do { (inner_ty, tv_binds) <- tcPatSig (patSigCtxt pstate) sig_ty pat_ty
383 ; (pat', tvs, res) <- tcExtendTyVarEnv2 tv_binds $
384 tc_lpat pat inner_ty pstate thing_inside
385 ; return (SigPatOut pat' inner_ty, tvs, res) }
387 tc_pat pstate pat@(TypePat ty) pat_ty thing_inside
388 = failWithTc (badTypePat pat)
390 ------------------------
391 -- Lists, tuples, arrays
392 tc_pat pstate (ListPat pats _) pat_ty thing_inside
393 = do { elt_ty <- boxySplitListTy pat_ty
394 ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
395 pats pstate thing_inside
396 ; return (ListPat pats' elt_ty, pats_tvs, res) }
398 tc_pat pstate (PArrPat pats _) pat_ty thing_inside
399 = do { [elt_ty] <- boxySplitTyConApp parrTyCon pat_ty
400 ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
401 pats pstate thing_inside
402 ; ifM (null pats) (zapToMonotype pat_ty) -- c.f. ExplicitPArr in TcExpr
403 ; return (PArrPat pats' elt_ty, pats_tvs, res) }
405 tc_pat pstate (TuplePat pats boxity _) pat_ty thing_inside
406 = do { arg_tys <- boxySplitTyConApp (tupleTyCon boxity (length pats)) pat_ty
407 ; (pats', pats_tvs, res) <- tcMultiple tc_lpat_pr (pats `zip` arg_tys)
410 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
411 -- so that we can experiment with lazy tuple-matching.
412 -- This is a pretty odd place to make the switch, but
413 -- it was easy to do.
414 ; let unmangled_result = TuplePat pats' boxity pat_ty
415 possibly_mangled_result
416 | opt_IrrefutableTuples && isBoxed boxity = LazyPat (noLoc unmangled_result)
417 | otherwise = unmangled_result
419 ; ASSERT( length arg_tys == length pats ) -- Syntactically enforced
420 return (possibly_mangled_result, pats_tvs, res) }
422 ------------------------
424 tc_pat pstate pat_in@(ConPatIn (L con_span con_name) arg_pats) pat_ty thing_inside
425 = do { data_con <- tcLookupDataCon con_name
426 ; let tycon = dataConTyCon data_con
427 ; tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside }
429 ------------------------
431 tc_pat pstate (LitPat simple_lit) pat_ty thing_inside
432 = do { boxyUnify (hsLitType simple_lit) pat_ty
433 ; res <- thing_inside pstate
434 ; returnM (LitPat simple_lit, [], res) }
436 ------------------------
437 -- Overloaded patterns: n, and n+k
438 tc_pat pstate pat@(NPat over_lit mb_neg eq _) pat_ty thing_inside
439 = do { let orig = LiteralOrigin over_lit
440 ; lit' <- tcOverloadedLit orig over_lit pat_ty
441 ; eq' <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
442 ; mb_neg' <- case mb_neg of
443 Nothing -> return Nothing -- Positive literal
444 Just neg -> -- Negative literal
445 -- The 'negate' is re-mappable syntax
446 do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
447 ; return (Just neg') }
448 ; res <- thing_inside pstate
449 ; returnM (NPat lit' mb_neg' eq' pat_ty, [], res) }
451 tc_pat pstate pat@(NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
452 = do { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
453 ; let pat_ty' = idType bndr_id
454 orig = LiteralOrigin lit
455 ; lit' <- tcOverloadedLit orig lit pat_ty'
457 -- The '>=' and '-' parts are re-mappable syntax
458 ; ge' <- tcSyntaxOp orig ge (mkFunTys [pat_ty', pat_ty'] boolTy)
459 ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
461 -- The Report says that n+k patterns must be in Integral
462 -- We may not want this when using re-mappable syntax, though (ToDo?)
463 ; icls <- tcLookupClass integralClassName
464 ; instStupidTheta orig [mkClassPred icls [pat_ty']]
466 ; res <- tcExtendIdEnv1 name bndr_id (thing_inside pstate)
467 ; returnM (NPlusKPat (L nm_loc bndr_id) lit' ge' minus', [], res) }
469 tc_pat _ _other_pat _ _ = panic "tc_pat" -- DictPat, ConPatOut, SigPatOut, VarPatOut
473 %************************************************************************
475 Most of the work for constructors is here
476 (the rest is in the ConPatIn case of tc_pat)
478 %************************************************************************
482 -- MkT :: forall a b c. (a:=:[b]) => b -> c -> T a
483 -- with scrutinee of type (T ty)
485 tcConPat :: PatState -> SrcSpan -> DataCon -> TyCon
486 -> BoxySigmaType -- Type of the pattern
487 -> HsConDetails Name (LPat Name) -> (PatState -> TcM a)
488 -> TcM (Pat TcId, [TcTyVar], a)
489 tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside
490 = do { span <- getSrcSpanM -- Span for the whole pattern
491 ; let (univ_tvs, ex_tvs, eq_spec, theta, arg_tys) = dataConFullSig data_con
492 skol_info = PatSkol data_con span
493 origin = SigOrigin skol_info
495 -- Instantiate the constructor type variables [a->ty]
496 ; ctxt_res_tys <- boxySplitTyConApp tycon pat_ty
497 ; ex_tvs' <- tcInstSkolTyVars skol_info ex_tvs
498 ; let tenv = zipTopTvSubst (univ_tvs ++ ex_tvs)
499 (ctxt_res_tys ++ mkTyVarTys ex_tvs')
500 eq_spec' = substEqSpec tenv eq_spec
501 theta' = substTheta tenv theta
502 arg_tys' = substTys tenv arg_tys
504 ; co_vars <- newCoVars eq_spec' -- Make coercion variables
505 ; pstate' <- refineAlt data_con pstate ex_tvs co_vars pat_ty
507 ; ((arg_pats', inner_tvs, res), lie_req) <- getLIE $
508 tcConArgs data_con arg_tys' arg_pats pstate' thing_inside
510 ; loc <- getInstLoc origin
511 ; dicts <- newDictBndrs loc theta'
512 ; dict_binds <- tcSimplifyCheck doc ex_tvs' dicts lie_req
514 ; addDataConStupidTheta origin data_con ctxt_res_tys
516 ; return (ConPatOut { pat_con = L con_span data_con,
517 pat_tvs = ex_tvs' ++ co_vars,
518 pat_dicts = map instToId dicts, pat_binds = dict_binds,
519 pat_args = arg_pats', pat_ty = pat_ty },
520 ex_tvs' ++ inner_tvs, res)
523 doc = ptext SLIT("existential context for") <+> quotes (ppr data_con)
525 tcConArgs :: DataCon -> [TcSigmaType]
526 -> Checker (HsConDetails Name (LPat Name)) (HsConDetails Id (LPat Id))
528 tcConArgs data_con arg_tys (PrefixCon arg_pats) pstate thing_inside
529 = do { checkTc (con_arity == no_of_args) -- Check correct arity
530 (arityErr "Constructor" data_con con_arity no_of_args)
531 ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
532 ; (arg_pats', tvs, res) <- tcMultiple tcConArg pats_w_tys
534 ; return (PrefixCon arg_pats', tvs, res) }
536 con_arity = dataConSourceArity data_con
537 no_of_args = length arg_pats
539 tcConArgs data_con [arg_ty1,arg_ty2] (InfixCon p1 p2) pstate thing_inside
540 = do { checkTc (con_arity == 2) -- Check correct arity
541 (arityErr "Constructor" data_con con_arity 2)
542 ; ([p1',p2'], tvs, res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
544 ; return (InfixCon p1' p2', tvs, res) }
546 con_arity = dataConSourceArity data_con
548 tcConArgs data_con arg_tys (RecCon rpats) pstate thing_inside
549 = do { (rpats', tvs, res) <- tcMultiple tc_field rpats pstate thing_inside
550 ; return (RecCon rpats', tvs, res) }
552 tc_field :: Checker (Located Name, LPat Name) (Located TcId, LPat TcId)
553 tc_field (field_lbl, pat) pstate thing_inside
554 = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
555 ; (pat', tvs, res) <- tcConArg (pat, pat_ty) pstate thing_inside
556 ; return ((sel_id, pat'), tvs, res) }
558 find_field_ty :: FieldLabel -> TcM (Id, TcType)
559 find_field_ty field_lbl
560 = case [ty | (f,ty) <- field_tys, f == field_lbl] of
562 -- No matching field; chances are this field label comes from some
563 -- other record type (or maybe none). As well as reporting an
564 -- error we still want to typecheck the pattern, principally to
565 -- make sure that all the variables it binds are put into the
566 -- environment, else the type checker crashes later:
567 -- f (R { foo = (a,b) }) = a+b
568 -- If foo isn't one of R's fields, we don't want to crash when
569 -- typechecking the "a+b".
570 [] -> do { addErrTc (badFieldCon data_con field_lbl)
571 ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
572 ; return (error "Bogus selector Id", bogus_ty) }
574 -- The normal case, when the field comes from the right constructor
576 ASSERT( null extras )
577 do { sel_id <- tcLookupField field_lbl
578 ; return (sel_id, pat_ty) }
580 field_tys :: [(FieldLabel, TcType)]
581 field_tys = zip (dataConFieldLabels data_con) arg_tys
582 -- Don't use zipEqual! If the constructor isn't really a record, then
583 -- dataConFieldLabels will be empty (and each field in the pattern
584 -- will generate an error below).
586 tcConArg :: Checker (LPat Name, BoxySigmaType) (LPat Id)
587 tcConArg (arg_pat, arg_ty) pstate thing_inside
588 = tc_lpat arg_pat arg_ty pstate thing_inside
589 -- NB: the tc_lpat will refine pat_ty if necessary
590 -- based on the current pstate, which may include
591 -- refinements from peer argument patterns to the left
595 addDataConStupidTheta :: InstOrigin -> DataCon -> [TcType] -> TcM ()
596 -- Instantiate the "stupid theta" of the data con, and throw
597 -- the constraints into the constraint set
598 addDataConStupidTheta origin data_con inst_tys
599 | null stupid_theta = return ()
600 | otherwise = instStupidTheta origin inst_theta
602 stupid_theta = dataConStupidTheta data_con
603 tenv = zipTopTvSubst (dataConUnivTyVars data_con) inst_tys
604 inst_theta = substTheta tenv stupid_theta
608 %************************************************************************
612 %************************************************************************
615 refineAlt :: DataCon -- For tracing only
617 -> [TcTyVar] -- Existentials
618 -> [CoVar] -- Equational constraints
619 -> BoxySigmaType -- Pattern type
622 refineAlt con pstate ex_tvs [] pat_ty
623 = return pstate -- Common case: no equational constraints
625 refineAlt con pstate ex_tvs co_vars pat_ty
626 | not (isRigidTy pat_ty)
627 = failWithTc (nonRigidMatch con)
628 -- We are matching against a GADT constructor with non-trivial
629 -- constraints, but pattern type is wobbly. For now we fail.
630 -- We can make sense of this, however:
631 -- Suppose MkT :: forall a b. (a:=:[b]) => b -> T a
632 -- (\x -> case x of { MkT v -> v })
633 -- We can infer that x must have type T [c], for some wobbly 'c'
635 -- (\(x::T [c]) -> case x of
636 -- MkT b (g::([c]:=:[b])) (v::b) -> v `cast` sym g
637 -- To implement this, we'd first instantiate the equational
638 -- constraints with *wobbly* type variables for the existentials;
639 -- then unify these constraints to make pat_ty the right shape;
640 -- then proceed exactly as in the rigid case
642 | otherwise -- In the rigid case, we perform type refinement
643 = case gadtRefine (pat_reft pstate) ex_tvs co_vars of {
644 Failed msg -> failWithTc (inaccessibleAlt msg) ;
645 Succeeded reft -> do { traceTc trace_msg
646 ; return (pstate { pat_reft = reft }) }
647 -- DO NOT refine the envt right away, because we
648 -- might be inside a lazy pattern. Instead, refine pstate
651 trace_msg = text "refineAlt:match" <+> ppr con <+> ppr reft
656 %************************************************************************
660 %************************************************************************
662 In tcOverloadedLit we convert directly to an Int or Integer if we
663 know that's what we want. This may save some time, by not
664 temporarily generating overloaded literals, but it won't catch all
665 cases (the rest are caught in lookupInst).
668 tcOverloadedLit :: InstOrigin
671 -> TcM (HsOverLit TcId)
672 tcOverloadedLit orig lit@(HsIntegral i fi) res_ty
673 | not (fi `isHsVar` fromIntegerName) -- Do not generate a LitInst for rebindable syntax.
674 -- Reason: If we do, tcSimplify will call lookupInst, which
675 -- will call tcSyntaxName, which does unification,
676 -- which tcSimplify doesn't like
677 -- ToDo: noLoc sadness
678 = do { integer_ty <- tcMetaTy integerTyConName
679 ; fi' <- tcSyntaxOp orig fi (mkFunTy integer_ty res_ty)
680 ; return (HsIntegral i (HsApp (noLoc fi') (nlHsLit (HsInteger i integer_ty)))) }
682 | Just expr <- shortCutIntLit i res_ty
683 = return (HsIntegral i expr)
686 = do { expr <- newLitInst orig lit res_ty
687 ; return (HsIntegral i expr) }
689 tcOverloadedLit orig lit@(HsFractional r fr) res_ty
690 | not (fr `isHsVar` fromRationalName) -- c.f. HsIntegral case
691 = do { rat_ty <- tcMetaTy rationalTyConName
692 ; fr' <- tcSyntaxOp orig fr (mkFunTy rat_ty res_ty)
693 -- Overloaded literals must have liftedTypeKind, because
694 -- we're instantiating an overloaded function here,
695 -- whereas res_ty might be openTypeKind. This was a bug in 6.2.2
696 -- However this'll be picked up by tcSyntaxOp if necessary
697 ; return (HsFractional r (HsApp (noLoc fr') (nlHsLit (HsRat r rat_ty)))) }
699 | Just expr <- shortCutFracLit r res_ty
700 = return (HsFractional r expr)
703 = do { expr <- newLitInst orig lit res_ty
704 ; return (HsFractional r expr) }
706 newLitInst :: InstOrigin -> HsOverLit Name -> BoxyRhoType -> TcM (HsExpr TcId)
707 newLitInst orig lit res_ty -- Make a LitInst
708 = do { loc <- getInstLoc orig
709 ; res_tau <- zapToMonotype res_ty
710 ; new_uniq <- newUnique
711 ; let lit_nm = mkSystemVarName new_uniq FSLIT("lit")
712 lit_inst = LitInst lit_nm lit res_tau loc
714 ; return (HsVar (instToId lit_inst)) }
718 %************************************************************************
720 Note [Pattern coercions]
722 %************************************************************************
724 In principle, these program would be reasonable:
726 f :: (forall a. a->a) -> Int
727 f (x :: Int->Int) = x 3
729 g :: (forall a. [a]) -> Bool
732 In both cases, the function type signature restricts what arguments can be passed
733 in a call (to polymorphic ones). The pattern type signature then instantiates this
734 type. For example, in the first case, (forall a. a->a) <= Int -> Int, and we
735 generate the translated term
736 f = \x' :: (forall a. a->a). let x = x' Int in x 3
738 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
739 And it requires a significant amount of code to implement, becuase we need to decorate
740 the translated pattern with coercion functions (generated from the subsumption check
743 So for now I'm just insisting on type *equality* in patterns. No subsumption.
745 Old notes about desugaring, at a time when pattern coercions were handled:
747 A SigPat is a type coercion and must be handled one at at time. We can't
748 combine them unless the type of the pattern inside is identical, and we don't
749 bother to check for that. For example:
751 data T = T1 Int | T2 Bool
752 f :: (forall a. a -> a) -> T -> t
753 f (g::Int->Int) (T1 i) = T1 (g i)
754 f (g::Bool->Bool) (T2 b) = T2 (g b)
756 We desugar this as follows:
758 f = \ g::(forall a. a->a) t::T ->
760 in case t of { T1 i -> T1 (gi i)
763 in case t of { T2 b -> T2 (gb b)
766 Note that we do not treat the first column of patterns as a
767 column of variables, because the coerced variables (gi, gb)
768 would be of different types. So we get rather grotty code.
769 But I don't think this is a common case, and if it was we could
770 doubtless improve it.
772 Meanwhile, the strategy is:
773 * treat each SigPat coercion (always non-identity coercions)
775 * deal with the stuff inside, and then wrap a binding round
776 the result to bind the new variable (gi, gb, etc)
779 %************************************************************************
781 \subsection{Errors and contexts}
783 %************************************************************************
786 patCtxt :: Pat Name -> Maybe Message -- Not all patterns are worth pushing a context
787 patCtxt (VarPat _) = Nothing
788 patCtxt (ParPat _) = Nothing
789 patCtxt (AsPat _ _) = Nothing
790 patCtxt pat = Just (hang (ptext SLIT("In the pattern:"))
793 -----------------------------------------------
795 existentialExplode pat
796 = hang (vcat [text "My brain just exploded.",
797 text "I can't handle pattern bindings for existentially-quantified constructors.",
798 text "In the binding group for"])
801 sigPatCtxt bound_ids bound_tvs pat_tys body_ty tidy_env
802 = do { pat_tys' <- mapM zonkTcType pat_tys
803 ; body_ty' <- zonkTcType body_ty
804 ; let (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
805 (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
806 (env3, tidy_body_ty) = tidyOpenType env2 body_ty'
808 sep [ptext SLIT("When checking an existential match that binds"),
809 nest 4 (vcat (zipWith ppr_id show_ids tidy_tys)),
810 ptext SLIT("The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
811 ptext SLIT("The body has type:") <+> ppr tidy_body_ty
814 show_ids = filter is_interesting bound_ids
815 is_interesting id = any (`elemVarSet` idFreeTyVars id) bound_tvs
817 ppr_id id ty = ppr id <+> dcolon <+> ppr ty
818 -- Don't zonk the types so we get the separate, un-unified versions
820 badFieldCon :: DataCon -> Name -> SDoc
821 badFieldCon con field
822 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
823 ptext SLIT("does not have field"), quotes (ppr field)]
825 polyPatSig :: TcType -> SDoc
827 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
830 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
834 hang (ptext SLIT("A lazy (~) pattern connot bind existential type variables"))
835 2 (vcat (map pprSkolTvBinding tvs))
838 = hang (ptext SLIT("GADT pattern match in non-rigid context for") <+> quotes (ppr con))
839 2 (ptext SLIT("Tell GHC HQ if you'd like this to unify the context"))
842 = hang (ptext SLIT("Inaccessible case alternative:")) 2 msg