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 (SigPatIn pat sig) pat_ty
154 = tcHsSigType PatSigCtxt sig `thenTc` \ sig_ty ->
155 tcSubPat sig_ty pat_ty `thenTc` \ (co_fn, lie_sig) ->
156 tcPat tc_bndr pat sig_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
157 returnTc (co_fn <$> pat', lie_req `plusLIE` lie_sig, tvs, ids, lie_avail)
161 %************************************************************************
163 \subsection{Explicit lists, parallel arrays, and tuples}
165 %************************************************************************
168 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
169 = tcAddErrCtxt (patCtxt pat_in) $
170 unifyListTy pat_ty `thenTc` \ elem_ty ->
171 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
172 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
174 tcPat tc_bndr pat_in@(PArrPatIn pats) pat_ty
175 = tcAddErrCtxt (patCtxt pat_in) $
176 unifyPArrTy pat_ty `thenTc` \ elem_ty ->
177 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
178 returnTc (PArrPat elem_ty pats', lie_req, tvs, ids, lie_avail)
180 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
181 = tcAddErrCtxt (patCtxt pat_in) $
183 unifyTupleTy boxity arity pat_ty `thenTc` \ arg_tys ->
184 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
186 -- possibly do the "make all tuple-pats irrefutable" test:
188 unmangled_result = TuplePat pats' boxity
190 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
191 -- so that we can experiment with lazy tuple-matching.
192 -- This is a pretty odd place to make the switch, but
193 -- it was easy to do.
195 possibly_mangled_result
196 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
197 | otherwise = unmangled_result
199 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
205 %************************************************************************
207 \subsection{Other constructors}
210 %************************************************************************
213 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
214 = tcConPat tc_bndr pat name arg_pats pat_ty
216 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
217 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
221 %************************************************************************
225 %************************************************************************
228 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
229 = tcAddErrCtxt (patCtxt pat) $
231 -- Check the constructor itself
232 tcConstructor pat name `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
234 -- Check overall type matches (c.f. tcConPat)
235 tcSubPat con_res_ty pat_ty `thenTc` \ (co_fn, lie_req1) ->
237 -- Don't use zipEqual! If the constructor isn't really a record, then
238 -- dataConFieldLabels will be empty (and each field in the pattern
239 -- will generate an error below).
240 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
245 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req2, tvs, ids, lie_avail2) ->
247 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
248 lie_req1 `plusLIE` lie_req2,
249 listToBag ex_tvs `unionBags` tvs,
251 lie_avail1 `plusLIE` lie_avail2)
254 tc_fields field_tys []
255 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
257 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
258 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
260 (case [ty | (f,ty) <- field_tys, f == field_label] of
262 -- No matching field; chances are this field label comes from some
263 -- other record type (or maybe none). As well as reporting an
264 -- error we still want to typecheck the pattern, principally to
265 -- make sure that all the variables it binds are put into the
266 -- environment, else the type checker crashes later:
267 -- f (R { foo = (a,b) }) = a+b
268 -- If foo isn't one of R's fields, we don't want to crash when
269 -- typechecking the "a+b".
270 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
271 newTyVarTy liftedTypeKind `thenNF_Tc_`
272 returnTc (error "Bogus selector Id", pat_ty)
274 -- The normal case, when the field comes from the right constructor
276 ASSERT( null extras )
277 tcLookupGlobalId field_label `thenNF_Tc` \ sel_id ->
278 returnTc (sel_id, pat_ty)
279 ) `thenTc` \ (sel_id, pat_ty) ->
281 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
283 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
284 lie_req1 `plusLIE` lie_req2,
285 tvs1 `unionBags` tvs2,
286 ids1 `unionBags` ids2,
287 lie_avail1 `plusLIE` lie_avail2)
290 %************************************************************************
292 \subsection{Literals}
294 %************************************************************************
297 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty
298 -- cf tcExpr on LitLits
299 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
300 newDicts (LitLitOrigin (_UNPK_ s))
301 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ dicts ->
302 returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
304 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
305 = unifyTauTy pat_ty stringTy `thenTc_`
306 tcLookupGlobalId eqStringName `thenNF_Tc` \ eq_id ->
307 returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit),
308 emptyLIE, emptyBag, emptyBag, emptyLIE)
310 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
311 = unifyTauTy pat_ty (simpleHsLitTy simple_lit) `thenTc_`
312 returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
314 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
315 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
316 tcLookupGlobalId eqName `thenNF_Tc` \ eq_sel_id ->
317 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ eq ->
319 returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) over_lit_expr),
320 lie1 `plusLIE` unitLIE eq,
321 emptyBag, emptyBag, emptyLIE)
323 origin = PatOrigin pat
324 lit' = case over_lit of
325 HsIntegral i _ -> HsInteger i
326 HsFractional f _ -> HsRat f pat_ty
329 %************************************************************************
331 \subsection{n+k patterns}
333 %************************************************************************
336 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
337 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie1, bndr_id) ->
338 -- The '-' part is re-mappable syntax
339 tcLookupId minus_name `thenNF_Tc` \ minus_sel_id ->
340 tcLookupGlobalId geName `thenNF_Tc` \ ge_sel_id ->
341 newOverloadedLit origin lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie2) ->
342 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ ge ->
343 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ minus ->
345 returnTc (NPlusKPat bndr_id i pat_ty
346 (SectionR (HsVar (instToId ge)) over_lit_expr)
347 (SectionR (HsVar (instToId minus)) over_lit_expr),
348 lie1 `plusLIE` lie2 `plusLIE` mkLIE [ge,minus],
349 emptyBag, unitBag (name, bndr_id), emptyLIE)
351 origin = PatOrigin pat
354 %************************************************************************
356 \subsection{Lists of patterns}
358 %************************************************************************
363 tcPats :: BinderChecker -- How to deal with variables
364 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
366 LIE, -- Required by n+k and literal pats
368 Bag (Name, TcId), -- Ids bound by the pattern
369 LIE) -- Dicts bound by the pattern
371 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
373 tcPats tc_bndr (ty:tys) (pat:pats)
374 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
375 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
377 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
378 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
379 lie_avail1 `plusLIE` lie_avail2)
382 ------------------------------------------------------
384 tcConstructor pat con_name
385 = -- Check that it's a constructor
386 tcLookupDataCon con_name `thenNF_Tc` \ data_con ->
390 (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
391 -- Ignore the theta; overloaded constructors only
392 -- behave differently when called, not when used for
395 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
397 ex_theta' = substTheta tenv ex_theta
398 arg_tys' = map (substTy tenv) arg_tys
400 n_ex_tvs = length ex_tvs
401 ex_tvs' = take n_ex_tvs all_tvs'
402 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
404 newDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ dicts ->
406 returnTc (data_con, ex_tvs', map instToId dicts, mkLIE dicts, arg_tys', result_ty)
409 ------------------------------------------------------
411 tcConPat tc_bndr pat con_name arg_pats pat_ty
412 = tcAddErrCtxt (patCtxt pat) $
414 -- Check the constructor itself
415 tcConstructor pat con_name `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
417 -- Check overall type matches.
418 -- The pat_ty might be a for-all type, in which
419 -- case we must instantiate to match
420 tcSubPat con_res_ty pat_ty `thenTc` \ (co_fn, lie_req1) ->
422 -- Check correct arity
424 con_arity = dataConSourceArity data_con
425 no_of_args = length arg_pats
427 checkTc (con_arity == no_of_args)
428 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
431 tcPats tc_bndr arg_pats arg_tys `thenTc` \ (arg_pats', lie_req2, tvs, ids, lie_avail2) ->
433 returnTc (co_fn <$> ConPat data_con pat_ty ex_tvs dicts arg_pats',
434 lie_req1 `plusLIE` lie_req2,
435 listToBag ex_tvs `unionBags` tvs,
437 lie_avail1 `plusLIE` lie_avail2)
441 %************************************************************************
443 \subsection{Subsumption}
445 %************************************************************************
448 f :: (forall a. a->a) -> Int -> Int
449 f (g::Int->Int) y = g y
450 This is ok: the type signature allows fewer callers than
451 the (more general) signature f :: (Int->Int) -> Int -> Int
452 I.e. (forall a. a->a) <= Int -> Int
453 We end up translating this to:
454 f = \g' :: (forall a. a->a). let g = g' Int in g' y
456 tcSubPat does the work
457 sig_ty is the signature on the pattern itself
458 (Int->Int in the example)
459 expected_ty is the type passed inwards from the context
460 (forall a. a->a in the example)
463 tcSubPat :: TcSigmaType -> TcSigmaType -> TcM (PatCoFn, LIE)
465 tcSubPat sig_ty exp_ty
466 = tcSub exp_ty sig_ty `thenTc` \ (co_fn, lie) ->
467 -- co_fn is a coercion on *expressions*, and we
468 -- need to make a coercion on *patterns*
469 if isIdCoercion co_fn then
470 ASSERT( isEmptyLIE lie )
471 returnNF_Tc (idCoercion, emptyLIE)
473 tcGetUnique `thenNF_Tc` \ uniq ->
475 arg_id = mkSysLocal SLIT("sub") uniq exp_ty
476 the_fn = DictLam [arg_id] (co_fn <$> HsVar arg_id)
477 pat_co_fn p = SigPat p exp_ty the_fn
479 returnNF_Tc (mkCoercion pat_co_fn, lie)
483 %************************************************************************
485 \subsection{Errors and contexts}
487 %************************************************************************
490 patCtxt pat = hang (ptext SLIT("In the pattern:"))
493 badFieldCon :: Name -> Name -> SDoc
494 badFieldCon con field
495 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
496 ptext SLIT("does not have field"), quotes (ppr field)]
498 polyPatSig :: TcType -> SDoc
500 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
503 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat