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, zapToType )
27 import TcType ( TcType, TcTyVar, TcSigmaType, TyVarDetails(VanillaTv),
28 mkTyConApp, mkClassPred, liftedTypeKind, tcGetTyVar_maybe,
29 isHoleTyVar, openTypeKind )
30 import TcUnify ( tcSubOff, TcHoleType,
31 unifyTauTy, unifyListTy, unifyPArrTy, unifyTupleTy,
32 mkCoercion, idCoercion, isIdCoercion,
34 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
36 import TysWiredIn ( stringTy )
37 import CmdLineOpts ( opt_IrrefutableTuples )
38 import DataCon ( dataConSig, dataConFieldLabels,
41 import Subst ( substTy, substTheta )
42 import PrelNames ( eqStringName, eqName, geName, cCallableClassName )
43 import BasicTypes ( isBoxed )
49 %************************************************************************
51 \subsection{Variable patterns}
53 %************************************************************************
56 type BinderChecker = Name -> TcSigmaType -> TcM (PatCoFn, LIE, TcId)
57 -- How to construct a suitable (monomorphic)
58 -- Id for variables found in the pattern
59 -- The TcSigmaType is the expected type
60 -- from the pattern context
62 -- The Id may have a sigma type (e.g. f (x::forall a. a->a))
63 -- so we want to *create* it during pattern type checking.
64 -- We don't want to make Ids first with a type-variable type
65 -- and then unify... becuase we can't unify a sigma type with a type variable.
67 tcMonoPatBndr :: BinderChecker
68 -- This is the right function to pass to tcPat when
69 -- we're looking at a lambda-bound pattern,
70 -- so there's no polymorphic guy to worry about
72 tcMonoPatBndr binder_name pat_ty
73 = zapToType pat_ty `thenNF_Tc` \ 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.
83 returnTc (idCoercion, emptyLIE, mkLocalId binder_name pat_ty')
87 %************************************************************************
89 \subsection{Typechecking patterns}
91 %************************************************************************
94 tcPat :: BinderChecker
97 -> TcHoleType -- Expected type derived from the context
98 -- In the case of a function with a rank-2 signature,
99 -- this type might be a forall type.
102 LIE, -- Required by n+k and literal pats
103 Bag TcTyVar, -- TyVars bound by the pattern
104 -- These are just the existentially-bound ones.
105 -- Any tyvars bound by *type signatures* in the
106 -- patterns are brought into scope before we begin.
107 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
108 -- which it occurs in the pattern
109 -- The two aren't the same because we conjure up a new
110 -- local name for each variable.
111 LIE) -- Dicts or methods [see below] bound by the pattern
112 -- from existential constructor patterns
116 %************************************************************************
118 \subsection{Variables, wildcards, lazy pats, as-pats}
120 %************************************************************************
123 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
124 = failWithTc (badTypePat pat)
126 tcPat tc_bndr (VarPatIn name) pat_ty
127 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie_req, bndr_id) ->
128 returnTc (co_fn <$> VarPat bndr_id, lie_req,
129 emptyBag, unitBag (name, bndr_id), emptyLIE)
131 tcPat tc_bndr (LazyPatIn pat) pat_ty
132 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
133 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
135 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
136 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie_req1, bndr_id) ->
137 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req2, tvs, ids, lie_avail) ->
138 returnTc (co_fn <$> (AsPat bndr_id pat'), lie_req1 `plusLIE` lie_req2,
139 tvs, (name, bndr_id) `consBag` ids, lie_avail)
141 tcPat tc_bndr WildPatIn pat_ty
142 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
144 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
145 = tcPat tc_bndr parend_pat pat_ty
147 tcPat tc_bndr pat_in@(SigPatIn pat sig) pat_ty
148 = tcAddErrCtxt (patCtxt pat_in) $
149 tcHsSigType PatSigCtxt sig `thenTc` \ sig_ty ->
150 tcSubPat sig_ty pat_ty `thenTc` \ (co_fn, lie_sig) ->
151 tcPat tc_bndr pat sig_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
152 returnTc (co_fn <$> pat', lie_req `plusLIE` lie_sig, tvs, ids, lie_avail)
156 %************************************************************************
158 \subsection{Explicit lists, parallel arrays, and tuples}
160 %************************************************************************
163 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
164 = tcAddErrCtxt (patCtxt pat_in) $
165 unifyListTy pat_ty `thenTc` \ elem_ty ->
166 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
167 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
169 tcPat tc_bndr pat_in@(PArrPatIn pats) pat_ty
170 = tcAddErrCtxt (patCtxt pat_in) $
171 unifyPArrTy pat_ty `thenTc` \ elem_ty ->
172 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
173 returnTc (PArrPat elem_ty pats', lie_req, tvs, ids, lie_avail)
175 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
176 = tcAddErrCtxt (patCtxt pat_in) $
178 unifyTupleTy boxity arity pat_ty `thenTc` \ arg_tys ->
179 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
181 -- possibly do the "make all tuple-pats irrefutable" test:
183 unmangled_result = TuplePat pats' boxity
185 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
186 -- so that we can experiment with lazy tuple-matching.
187 -- This is a pretty odd place to make the switch, but
188 -- it was easy to do.
190 possibly_mangled_result
191 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
192 | otherwise = unmangled_result
194 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
200 %************************************************************************
202 \subsection{Other constructors}
205 %************************************************************************
208 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
209 = tcConPat tc_bndr pat name arg_pats pat_ty
211 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
212 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
216 %************************************************************************
220 %************************************************************************
223 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
224 = tcAddErrCtxt (patCtxt pat) $
226 -- Check the constructor itself
227 tcConstructor pat name `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
229 -- Check overall type matches (c.f. tcConPat)
230 tcSubPat con_res_ty pat_ty `thenTc` \ (co_fn, lie_req1) ->
232 -- Don't use zipEqual! If the constructor isn't really a record, then
233 -- dataConFieldLabels will be empty (and each field in the pattern
234 -- will generate an error below).
235 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
240 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req2, tvs, ids, lie_avail2) ->
242 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
243 lie_req1 `plusLIE` lie_req2,
244 listToBag ex_tvs `unionBags` tvs,
246 lie_avail1 `plusLIE` lie_avail2)
249 tc_fields field_tys []
250 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
252 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
253 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
255 (case [ty | (f,ty) <- field_tys, f == field_label] of
257 -- No matching field; chances are this field label comes from some
258 -- other record type (or maybe none). As well as reporting an
259 -- error we still want to typecheck the pattern, principally to
260 -- make sure that all the variables it binds are put into the
261 -- environment, else the type checker crashes later:
262 -- f (R { foo = (a,b) }) = a+b
263 -- If foo isn't one of R's fields, we don't want to crash when
264 -- typechecking the "a+b".
265 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
266 newTyVarTy liftedTypeKind `thenNF_Tc_`
267 returnTc (error "Bogus selector Id", pat_ty)
269 -- The normal case, when the field comes from the right constructor
271 ASSERT( null extras )
272 tcLookupGlobalId field_label `thenNF_Tc` \ sel_id ->
273 returnTc (sel_id, pat_ty)
274 ) `thenTc` \ (sel_id, pat_ty) ->
276 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
278 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
279 lie_req1 `plusLIE` lie_req2,
280 tvs1 `unionBags` tvs2,
281 ids1 `unionBags` ids2,
282 lie_avail1 `plusLIE` lie_avail2)
285 %************************************************************************
287 \subsection{Literals}
289 %************************************************************************
292 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty
293 -- cf tcExpr on LitLits
294 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
295 newDicts (LitLitOrigin (_UNPK_ s))
296 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ dicts ->
297 returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
299 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
300 = unifyTauTy pat_ty stringTy `thenTc_`
301 tcLookupGlobalId eqStringName `thenNF_Tc` \ eq_id ->
302 returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit),
303 emptyLIE, emptyBag, emptyBag, emptyLIE)
305 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
306 = unifyTauTy pat_ty (simpleHsLitTy simple_lit) `thenTc_`
307 returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
309 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
310 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
311 tcLookupGlobalId eqName `thenNF_Tc` \ eq_sel_id ->
312 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ eq ->
314 returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) over_lit_expr),
315 lie1 `plusLIE` unitLIE eq,
316 emptyBag, emptyBag, emptyLIE)
318 origin = PatOrigin pat
319 lit' = case over_lit of
320 HsIntegral i _ -> HsInteger i
321 HsFractional f _ -> HsRat f pat_ty
324 %************************************************************************
326 \subsection{n+k patterns}
328 %************************************************************************
331 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
332 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie1, bndr_id) ->
333 -- The '-' part is re-mappable syntax
334 tcLookupId minus_name `thenNF_Tc` \ minus_sel_id ->
335 tcLookupGlobalId geName `thenNF_Tc` \ ge_sel_id ->
336 newOverloadedLit origin lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie2) ->
337 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ ge ->
338 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ minus ->
340 returnTc (NPlusKPat bndr_id i pat_ty
341 (SectionR (HsVar (instToId ge)) over_lit_expr)
342 (SectionR (HsVar (instToId minus)) over_lit_expr),
343 lie1 `plusLIE` lie2 `plusLIE` mkLIE [ge,minus],
344 emptyBag, unitBag (name, bndr_id), emptyLIE)
346 origin = PatOrigin pat
349 %************************************************************************
351 \subsection{Lists of patterns}
353 %************************************************************************
358 tcPats :: BinderChecker -- How to deal with variables
359 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
361 LIE, -- Required by n+k and literal pats
363 Bag (Name, TcId), -- Ids bound by the pattern
364 LIE) -- Dicts bound by the pattern
366 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
368 tcPats tc_bndr (ty:tys) (pat:pats)
369 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
370 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
372 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
373 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
374 lie_avail1 `plusLIE` lie_avail2)
377 ------------------------------------------------------
379 tcConstructor pat con_name
380 = -- Check that it's a constructor
381 tcLookupDataCon con_name `thenNF_Tc` \ data_con ->
385 (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
386 -- Ignore the theta; overloaded constructors only
387 -- behave differently when called, not when used for
390 tcInstTyVars VanillaTv (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
392 ex_theta' = substTheta tenv ex_theta
393 arg_tys' = map (substTy tenv) arg_tys
395 n_ex_tvs = length ex_tvs
396 ex_tvs' = take n_ex_tvs all_tvs'
397 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
399 newDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ dicts ->
401 returnTc (data_con, ex_tvs', map instToId dicts, mkLIE dicts, arg_tys', result_ty)
404 ------------------------------------------------------
406 tcConPat tc_bndr pat con_name arg_pats pat_ty
407 = tcAddErrCtxt (patCtxt pat) $
409 -- Check the constructor itself
410 tcConstructor pat con_name `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
412 -- Check overall type matches.
413 -- The pat_ty might be a for-all type, in which
414 -- case we must instantiate to match
415 tcSubPat con_res_ty pat_ty `thenTc` \ (co_fn, lie_req1) ->
417 -- Check correct arity
419 con_arity = dataConSourceArity data_con
420 no_of_args = length arg_pats
422 checkTc (con_arity == no_of_args)
423 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
426 tcPats tc_bndr arg_pats arg_tys `thenTc` \ (arg_pats', lie_req2, tvs, ids, lie_avail2) ->
428 returnTc (co_fn <$> ConPat data_con pat_ty ex_tvs dicts arg_pats',
429 lie_req1 `plusLIE` lie_req2,
430 listToBag ex_tvs `unionBags` tvs,
432 lie_avail1 `plusLIE` lie_avail2)
436 %************************************************************************
438 \subsection{Subsumption}
440 %************************************************************************
443 f :: (forall a. a->a) -> Int -> Int
444 f (g::Int->Int) y = g y
445 This is ok: the type signature allows fewer callers than
446 the (more general) signature f :: (Int->Int) -> Int -> Int
447 I.e. (forall a. a->a) <= Int -> Int
448 We end up translating this to:
449 f = \g' :: (forall a. a->a). let g = g' Int in g' y
451 tcSubPat does the work
452 sig_ty is the signature on the pattern itself
453 (Int->Int in the example)
454 expected_ty is the type passed inwards from the context
455 (forall a. a->a in the example)
458 tcSubPat :: TcSigmaType -> TcHoleType -> TcM (PatCoFn, LIE)
460 tcSubPat sig_ty exp_ty
461 = tcSubOff sig_ty exp_ty `thenTc` \ (co_fn, lie) ->
462 -- co_fn is a coercion on *expressions*, and we
463 -- need to make a coercion on *patterns*
464 if isIdCoercion co_fn then
465 ASSERT( isEmptyLIE lie )
466 returnNF_Tc (idCoercion, emptyLIE)
468 tcGetUnique `thenNF_Tc` \ uniq ->
470 arg_id = mkSysLocal FSLIT("sub") uniq exp_ty
471 the_fn = DictLam [arg_id] (co_fn <$> HsVar arg_id)
472 pat_co_fn p = SigPat p exp_ty the_fn
474 returnNF_Tc (mkCoercion pat_co_fn, lie)
478 %************************************************************************
480 \subsection{Errors and contexts}
482 %************************************************************************
485 patCtxt pat = hang (ptext SLIT("When checking the pattern:"))
488 badFieldCon :: Name -> Name -> SDoc
489 badFieldCon con field
490 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
491 ptext SLIT("does not have field"), quotes (ppr field)]
493 polyPatSig :: TcType -> SDoc
495 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
498 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat