2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcPat]{Typechecking patterns}
7 module TcPat ( tcPat, tcMonoPatBndr, tcSubPat,
8 badFieldCon, polyPatSig
11 #include "HsVersions.h"
13 import HsSyn ( InPat(..), OutPat(..), HsLit(..), HsOverLit(..), HsExpr(..) )
14 import RnHsSyn ( RenamedPat )
15 import TcHsSyn ( TcPat, TcId, simpleHsLitTy )
18 import Inst ( InstOrigin(..),
19 emptyLIE, plusLIE, LIE, mkLIE, unitLIE, instToId, isEmptyLIE,
20 newMethod, newOverloadedLit, newDicts
22 import Id ( mkLocalId, mkSysLocal )
24 import FieldLabel ( fieldLabelName )
25 import TcEnv ( tcLookupClass, tcLookupDataCon, tcLookupGlobalId, tcLookupId )
26 import TcMType ( tcInstTyVars, newTyVarTy, getTcTyVar, putTcTyVar )
27 import TcType ( TcType, TcTyVar, TcSigmaType,
28 mkTyConApp, mkClassPred, liftedTypeKind, tcGetTyVar_maybe,
29 isHoleTyVar, openTypeKind )
30 import TcUnify ( tcSub, unifyTauTy, unifyListTy, unifyPArrTy,
31 unifyTupleTy, mkCoercion, idCoercion, isIdCoercion,
33 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
35 import TysWiredIn ( stringTy )
36 import CmdLineOpts ( opt_IrrefutableTuples )
37 import DataCon ( dataConSig, dataConFieldLabels,
40 import Subst ( substTy, substTheta )
41 import PrelNames ( eqStringName, eqName, geName, cCallableClassName )
42 import BasicTypes ( isBoxed )
48 %************************************************************************
50 \subsection{Variable patterns}
52 %************************************************************************
55 type BinderChecker = Name -> TcSigmaType -> TcM (PatCoFn, LIE, TcId)
56 -- How to construct a suitable (monomorphic)
57 -- Id for variables found in the pattern
58 -- The TcSigmaType is the expected type
59 -- from the pattern context
61 -- The Id may have a sigma type (e.g. f (x::forall a. a->a))
62 -- so we want to *create* it during pattern type checking.
63 -- We don't want to make Ids first with a type-variable type
64 -- and then unify... becuase we can't unify a sigma type with a type variable.
66 tcMonoPatBndr :: BinderChecker
67 -- This is the right function to pass to tcPat when
68 -- we're looking at a lambda-bound pattern,
69 -- so there's no polymorphic guy to worry about
71 tcMonoPatBndr binder_name pat_ty
72 | Just tv <- tcGetTyVar_maybe pat_ty,
74 -- If there are *no constraints* on the pattern type, we
75 -- revert to good old H-M typechecking, making
76 -- the type of the binder into an *ordinary*
77 -- type variable. We find out if there are no constraints
78 -- by seeing if we are given an "open hole" as our info.
79 -- What we are trying to avoid here is giving a binder
80 -- a type that is a 'hole'. The only place holes should
81 -- appear is as an argument to tcPat and tcExpr/tcMonoExpr.
82 = getTcTyVar tv `thenNF_Tc` \ maybe_ty ->
84 Just ty -> tcMonoPatBndr binder_name ty
85 Nothing -> newTyVarTy openTypeKind `thenNF_Tc` \ ty ->
86 putTcTyVar tv ty `thenNF_Tc_`
87 returnTc (idCoercion, emptyLIE, mkLocalId binder_name ty)
89 = returnTc (idCoercion, emptyLIE, mkLocalId binder_name pat_ty)
93 %************************************************************************
95 \subsection{Typechecking patterns}
97 %************************************************************************
100 tcPat :: BinderChecker
103 -> TcSigmaType -- Expected type derived from the context
104 -- In the case of a function with a rank-2 signature,
105 -- this type might be a forall type.
108 LIE, -- Required by n+k and literal pats
109 Bag TcTyVar, -- TyVars bound by the pattern
110 -- These are just the existentially-bound ones.
111 -- Any tyvars bound by *type signatures* in the
112 -- patterns are brought into scope before we begin.
113 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
114 -- which it occurs in the pattern
115 -- The two aren't the same because we conjure up a new
116 -- local name for each variable.
117 LIE) -- Dicts or methods [see below] bound by the pattern
118 -- from existential constructor patterns
122 %************************************************************************
124 \subsection{Variables, wildcards, lazy pats, as-pats}
126 %************************************************************************
129 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
130 = failWithTc (badTypePat pat)
132 tcPat tc_bndr (VarPatIn name) pat_ty
133 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie_req, bndr_id) ->
134 returnTc (co_fn <$> VarPat bndr_id, lie_req,
135 emptyBag, unitBag (name, bndr_id), emptyLIE)
137 tcPat tc_bndr (LazyPatIn pat) pat_ty
138 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
139 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
141 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
142 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie_req1, bndr_id) ->
143 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req2, tvs, ids, lie_avail) ->
144 returnTc (co_fn <$> (AsPat bndr_id pat'), lie_req1 `plusLIE` lie_req2,
145 tvs, (name, bndr_id) `consBag` ids, lie_avail)
147 tcPat tc_bndr WildPatIn pat_ty
148 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
150 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
151 = tcPat tc_bndr parend_pat pat_ty
153 tcPat tc_bndr pat_in@(SigPatIn pat sig) pat_ty
154 = tcAddErrCtxt (patCtxt pat_in) $
155 tcHsSigType PatSigCtxt sig `thenTc` \ sig_ty ->
156 tcSubPat sig_ty pat_ty `thenTc` \ (co_fn, lie_sig) ->
157 tcPat tc_bndr pat sig_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
158 returnTc (co_fn <$> pat', lie_req `plusLIE` lie_sig, tvs, ids, lie_avail)
162 %************************************************************************
164 \subsection{Explicit lists, parallel arrays, and tuples}
166 %************************************************************************
169 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
170 = tcAddErrCtxt (patCtxt pat_in) $
171 unifyListTy pat_ty `thenTc` \ elem_ty ->
172 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
173 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
175 tcPat tc_bndr pat_in@(PArrPatIn pats) pat_ty
176 = tcAddErrCtxt (patCtxt pat_in) $
177 unifyPArrTy pat_ty `thenTc` \ elem_ty ->
178 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
179 returnTc (PArrPat elem_ty pats', lie_req, tvs, ids, lie_avail)
181 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
182 = tcAddErrCtxt (patCtxt pat_in) $
184 unifyTupleTy boxity arity pat_ty `thenTc` \ arg_tys ->
185 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
187 -- possibly do the "make all tuple-pats irrefutable" test:
189 unmangled_result = TuplePat pats' boxity
191 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
192 -- so that we can experiment with lazy tuple-matching.
193 -- This is a pretty odd place to make the switch, but
194 -- it was easy to do.
196 possibly_mangled_result
197 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
198 | otherwise = unmangled_result
200 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
206 %************************************************************************
208 \subsection{Other constructors}
211 %************************************************************************
214 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
215 = tcConPat tc_bndr pat name arg_pats pat_ty
217 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
218 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
222 %************************************************************************
226 %************************************************************************
229 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
230 = tcAddErrCtxt (patCtxt pat) $
232 -- Check the constructor itself
233 tcConstructor pat name `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
235 -- Check overall type matches (c.f. tcConPat)
236 tcSubPat con_res_ty pat_ty `thenTc` \ (co_fn, lie_req1) ->
238 -- Don't use zipEqual! If the constructor isn't really a record, then
239 -- dataConFieldLabels will be empty (and each field in the pattern
240 -- will generate an error below).
241 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
246 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req2, tvs, ids, lie_avail2) ->
248 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
249 lie_req1 `plusLIE` lie_req2,
250 listToBag ex_tvs `unionBags` tvs,
252 lie_avail1 `plusLIE` lie_avail2)
255 tc_fields field_tys []
256 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
258 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
259 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
261 (case [ty | (f,ty) <- field_tys, f == field_label] of
263 -- No matching field; chances are this field label comes from some
264 -- other record type (or maybe none). As well as reporting an
265 -- error we still want to typecheck the pattern, principally to
266 -- make sure that all the variables it binds are put into the
267 -- environment, else the type checker crashes later:
268 -- f (R { foo = (a,b) }) = a+b
269 -- If foo isn't one of R's fields, we don't want to crash when
270 -- typechecking the "a+b".
271 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
272 newTyVarTy liftedTypeKind `thenNF_Tc_`
273 returnTc (error "Bogus selector Id", pat_ty)
275 -- The normal case, when the field comes from the right constructor
277 ASSERT( null extras )
278 tcLookupGlobalId field_label `thenNF_Tc` \ sel_id ->
279 returnTc (sel_id, pat_ty)
280 ) `thenTc` \ (sel_id, pat_ty) ->
282 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
284 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
285 lie_req1 `plusLIE` lie_req2,
286 tvs1 `unionBags` tvs2,
287 ids1 `unionBags` ids2,
288 lie_avail1 `plusLIE` lie_avail2)
291 %************************************************************************
293 \subsection{Literals}
295 %************************************************************************
298 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty
299 -- cf tcExpr on LitLits
300 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
301 newDicts (LitLitOrigin (_UNPK_ s))
302 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ dicts ->
303 returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
305 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
306 = unifyTauTy pat_ty stringTy `thenTc_`
307 tcLookupGlobalId eqStringName `thenNF_Tc` \ eq_id ->
308 returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit),
309 emptyLIE, emptyBag, emptyBag, emptyLIE)
311 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
312 = unifyTauTy pat_ty (simpleHsLitTy simple_lit) `thenTc_`
313 returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
315 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
316 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
317 tcLookupGlobalId eqName `thenNF_Tc` \ eq_sel_id ->
318 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ eq ->
320 returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) over_lit_expr),
321 lie1 `plusLIE` unitLIE eq,
322 emptyBag, emptyBag, emptyLIE)
324 origin = PatOrigin pat
325 lit' = case over_lit of
326 HsIntegral i _ -> HsInteger i
327 HsFractional f _ -> HsRat f pat_ty
330 %************************************************************************
332 \subsection{n+k patterns}
334 %************************************************************************
337 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
338 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie1, bndr_id) ->
339 -- The '-' part is re-mappable syntax
340 tcLookupId minus_name `thenNF_Tc` \ minus_sel_id ->
341 tcLookupGlobalId geName `thenNF_Tc` \ ge_sel_id ->
342 newOverloadedLit origin lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie2) ->
343 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ ge ->
344 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ minus ->
346 returnTc (NPlusKPat bndr_id i pat_ty
347 (SectionR (HsVar (instToId ge)) over_lit_expr)
348 (SectionR (HsVar (instToId minus)) over_lit_expr),
349 lie1 `plusLIE` lie2 `plusLIE` mkLIE [ge,minus],
350 emptyBag, unitBag (name, bndr_id), emptyLIE)
352 origin = PatOrigin pat
355 %************************************************************************
357 \subsection{Lists of patterns}
359 %************************************************************************
364 tcPats :: BinderChecker -- How to deal with variables
365 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
367 LIE, -- Required by n+k and literal pats
369 Bag (Name, TcId), -- Ids bound by the pattern
370 LIE) -- Dicts bound by the pattern
372 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
374 tcPats tc_bndr (ty:tys) (pat:pats)
375 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
376 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
378 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
379 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
380 lie_avail1 `plusLIE` lie_avail2)
383 ------------------------------------------------------
385 tcConstructor pat con_name
386 = -- Check that it's a constructor
387 tcLookupDataCon con_name `thenNF_Tc` \ data_con ->
391 (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
392 -- Ignore the theta; overloaded constructors only
393 -- behave differently when called, not when used for
396 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
398 ex_theta' = substTheta tenv ex_theta
399 arg_tys' = map (substTy tenv) arg_tys
401 n_ex_tvs = length ex_tvs
402 ex_tvs' = take n_ex_tvs all_tvs'
403 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
405 newDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ dicts ->
407 returnTc (data_con, ex_tvs', map instToId dicts, mkLIE dicts, arg_tys', result_ty)
410 ------------------------------------------------------
412 tcConPat tc_bndr pat con_name arg_pats pat_ty
413 = tcAddErrCtxt (patCtxt pat) $
415 -- Check the constructor itself
416 tcConstructor pat con_name `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
418 -- Check overall type matches.
419 -- The pat_ty might be a for-all type, in which
420 -- case we must instantiate to match
421 tcSubPat con_res_ty pat_ty `thenTc` \ (co_fn, lie_req1) ->
423 -- Check correct arity
425 con_arity = dataConSourceArity data_con
426 no_of_args = length arg_pats
428 checkTc (con_arity == no_of_args)
429 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
432 tcPats tc_bndr arg_pats arg_tys `thenTc` \ (arg_pats', lie_req2, tvs, ids, lie_avail2) ->
434 returnTc (co_fn <$> ConPat data_con pat_ty ex_tvs dicts arg_pats',
435 lie_req1 `plusLIE` lie_req2,
436 listToBag ex_tvs `unionBags` tvs,
438 lie_avail1 `plusLIE` lie_avail2)
442 %************************************************************************
444 \subsection{Subsumption}
446 %************************************************************************
449 f :: (forall a. a->a) -> Int -> Int
450 f (g::Int->Int) y = g y
451 This is ok: the type signature allows fewer callers than
452 the (more general) signature f :: (Int->Int) -> Int -> Int
453 I.e. (forall a. a->a) <= Int -> Int
454 We end up translating this to:
455 f = \g' :: (forall a. a->a). let g = g' Int in g' y
457 tcSubPat does the work
458 sig_ty is the signature on the pattern itself
459 (Int->Int in the example)
460 expected_ty is the type passed inwards from the context
461 (forall a. a->a in the example)
464 tcSubPat :: TcSigmaType -> TcSigmaType -> TcM (PatCoFn, LIE)
466 tcSubPat sig_ty exp_ty
467 = tcSub sig_ty exp_ty `thenTc` \ (co_fn, lie) ->
468 -- co_fn is a coercion on *expressions*, and we
469 -- need to make a coercion on *patterns*
470 if isIdCoercion co_fn then
471 ASSERT( isEmptyLIE lie )
472 returnNF_Tc (idCoercion, emptyLIE)
474 tcGetUnique `thenNF_Tc` \ uniq ->
476 arg_id = mkSysLocal FSLIT("sub") uniq exp_ty
477 the_fn = DictLam [arg_id] (co_fn <$> HsVar arg_id)
478 pat_co_fn p = SigPat p exp_ty the_fn
480 returnNF_Tc (mkCoercion pat_co_fn, lie)
484 %************************************************************************
486 \subsection{Errors and contexts}
488 %************************************************************************
491 patCtxt pat = hang (ptext SLIT("When checking the pattern:"))
494 badFieldCon :: Name -> Name -> SDoc
495 badFieldCon con field
496 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
497 ptext SLIT("does not have field"), quotes (ppr field)]
499 polyPatSig :: TcType -> SDoc
501 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
504 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat