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, unifyTupleTy,
31 mkCoercion, idCoercion, isIdCoercion, (<$>), PatCoFn )
32 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
34 import TysWiredIn ( stringTy )
35 import CmdLineOpts ( opt_IrrefutableTuples )
36 import DataCon ( dataConSig, dataConFieldLabels,
39 import Subst ( substTy, substTheta )
40 import PrelNames ( eqStringName, eqName, geName, cCallableClassName )
41 import BasicTypes ( isBoxed )
47 %************************************************************************
49 \subsection{Variable patterns}
51 %************************************************************************
54 type BinderChecker = Name -> TcSigmaType -> TcM (PatCoFn, LIE, TcId)
55 -- How to construct a suitable (monomorphic)
56 -- Id for variables found in the pattern
57 -- The TcSigmaType is the expected type
58 -- from the pattern context
60 -- The Id may have a sigma type (e.g. f (x::forall a. a->a))
61 -- so we want to *create* it during pattern type checking.
62 -- We don't want to make Ids first with a type-variable type
63 -- and then unify... becuase we can't unify a sigma type with a type variable.
65 tcMonoPatBndr :: BinderChecker
66 -- This is the right function to pass to tcPat when
67 -- we're looking at a lambda-bound pattern,
68 -- so there's no polymorphic guy to worry about
70 tcMonoPatBndr binder_name pat_ty
71 | Just tv <- tcGetTyVar_maybe pat_ty,
73 -- If there are *no constraints* on the pattern type, we
74 -- revert to good old H-M typechecking, making
75 -- the type of the binder into an *ordinary*
76 -- type variable. We find out if there are no constraints
77 -- by seeing if we are given an "open hole" as our info.
78 -- What we are trying to avoid here is giving a binder
79 -- a type that is a 'hole'. The only place holes should
80 -- appear is as an argument to tcPat and tcExpr/tcMonoExpr.
81 = getTcTyVar tv `thenNF_Tc` \ maybe_ty ->
83 Just ty -> tcMonoPatBndr binder_name ty
84 Nothing -> newTyVarTy openTypeKind `thenNF_Tc` \ ty ->
85 putTcTyVar tv ty `thenNF_Tc_`
86 returnTc (idCoercion, emptyLIE, mkLocalId binder_name ty)
88 = returnTc (idCoercion, emptyLIE, mkLocalId binder_name pat_ty)
92 %************************************************************************
94 \subsection{Typechecking patterns}
96 %************************************************************************
99 tcPat :: BinderChecker
102 -> TcSigmaType -- Expected type derived from the context
103 -- In the case of a function with a rank-2 signature,
104 -- this type might be a forall type.
107 LIE, -- Required by n+k and literal pats
108 Bag TcTyVar, -- TyVars bound by the pattern
109 -- These are just the existentially-bound ones.
110 -- Any tyvars bound by *type signatures* in the
111 -- patterns are brought into scope before we begin.
112 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
113 -- which it occurs in the pattern
114 -- The two aren't the same because we conjure up a new
115 -- local name for each variable.
116 LIE) -- Dicts or methods [see below] bound by the pattern
117 -- from existential constructor patterns
121 %************************************************************************
123 \subsection{Variables, wildcards, lazy pats, as-pats}
125 %************************************************************************
128 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
129 = failWithTc (badTypePat pat)
131 tcPat tc_bndr (VarPatIn name) pat_ty
132 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie_req, bndr_id) ->
133 returnTc (co_fn <$> VarPat bndr_id, lie_req,
134 emptyBag, unitBag (name, bndr_id), emptyLIE)
136 tcPat tc_bndr (LazyPatIn pat) pat_ty
137 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
138 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
140 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
141 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie_req1, bndr_id) ->
142 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req2, tvs, ids, lie_avail) ->
143 returnTc (co_fn <$> (AsPat bndr_id pat'), lie_req1 `plusLIE` lie_req2,
144 tvs, (name, bndr_id) `consBag` ids, lie_avail)
146 tcPat tc_bndr WildPatIn pat_ty
147 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
149 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
150 = tcPat tc_bndr parend_pat pat_ty
152 tcPat tc_bndr (SigPatIn pat sig) pat_ty
153 = tcHsSigType PatSigCtxt sig `thenTc` \ sig_ty ->
154 tcSubPat sig_ty pat_ty `thenTc` \ (co_fn, lie_sig) ->
155 tcPat tc_bndr pat sig_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
156 returnTc (co_fn <$> pat', lie_req `plusLIE` lie_sig, tvs, ids, lie_avail)
160 %************************************************************************
162 \subsection{Explicit lists and tuples}
164 %************************************************************************
167 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
168 = tcAddErrCtxt (patCtxt pat_in) $
169 unifyListTy pat_ty `thenTc` \ elem_ty ->
170 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
171 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
173 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
174 = tcAddErrCtxt (patCtxt pat_in) $
176 unifyTupleTy boxity arity pat_ty `thenTc` \ arg_tys ->
177 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
179 -- possibly do the "make all tuple-pats irrefutable" test:
181 unmangled_result = TuplePat pats' boxity
183 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
184 -- so that we can experiment with lazy tuple-matching.
185 -- This is a pretty odd place to make the switch, but
186 -- it was easy to do.
188 possibly_mangled_result
189 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
190 | otherwise = unmangled_result
192 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
198 %************************************************************************
200 \subsection{Other constructors}
203 %************************************************************************
206 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
207 = tcConPat tc_bndr pat name arg_pats pat_ty
209 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
210 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
214 %************************************************************************
218 %************************************************************************
221 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
222 = tcAddErrCtxt (patCtxt pat) $
224 -- Check the constructor itself
225 tcConstructor pat name `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
227 -- Check overall type matches (c.f. tcConPat)
228 tcSubPat con_res_ty pat_ty `thenTc` \ (co_fn, lie_req1) ->
230 -- Don't use zipEqual! If the constructor isn't really a record, then
231 -- dataConFieldLabels will be empty (and each field in the pattern
232 -- will generate an error below).
233 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
238 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req2, tvs, ids, lie_avail2) ->
240 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
241 lie_req1 `plusLIE` lie_req2,
242 listToBag ex_tvs `unionBags` tvs,
244 lie_avail1 `plusLIE` lie_avail2)
247 tc_fields field_tys []
248 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
250 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
251 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
253 (case [ty | (f,ty) <- field_tys, f == field_label] of
255 -- No matching field; chances are this field label comes from some
256 -- other record type (or maybe none). As well as reporting an
257 -- error we still want to typecheck the pattern, principally to
258 -- make sure that all the variables it binds are put into the
259 -- environment, else the type checker crashes later:
260 -- f (R { foo = (a,b) }) = a+b
261 -- If foo isn't one of R's fields, we don't want to crash when
262 -- typechecking the "a+b".
263 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
264 newTyVarTy liftedTypeKind `thenNF_Tc_`
265 returnTc (error "Bogus selector Id", pat_ty)
267 -- The normal case, when the field comes from the right constructor
269 ASSERT( null extras )
270 tcLookupGlobalId field_label `thenNF_Tc` \ sel_id ->
271 returnTc (sel_id, pat_ty)
272 ) `thenTc` \ (sel_id, pat_ty) ->
274 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
276 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
277 lie_req1 `plusLIE` lie_req2,
278 tvs1 `unionBags` tvs2,
279 ids1 `unionBags` ids2,
280 lie_avail1 `plusLIE` lie_avail2)
283 %************************************************************************
285 \subsection{Literals}
287 %************************************************************************
290 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty
291 -- cf tcExpr on LitLits
292 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
293 newDicts (LitLitOrigin (_UNPK_ s))
294 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ dicts ->
295 returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
297 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
298 = unifyTauTy pat_ty stringTy `thenTc_`
299 tcLookupGlobalId eqStringName `thenNF_Tc` \ eq_id ->
300 returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit),
301 emptyLIE, emptyBag, emptyBag, emptyLIE)
303 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
304 = unifyTauTy pat_ty (simpleHsLitTy simple_lit) `thenTc_`
305 returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
307 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
308 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
309 tcLookupGlobalId eqName `thenNF_Tc` \ eq_sel_id ->
310 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ eq ->
312 returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) over_lit_expr),
313 lie1 `plusLIE` unitLIE eq,
314 emptyBag, emptyBag, emptyLIE)
316 origin = PatOrigin pat
317 lit' = case over_lit of
318 HsIntegral i _ -> HsInteger i
319 HsFractional f _ -> HsRat f pat_ty
322 %************************************************************************
324 \subsection{n+k patterns}
326 %************************************************************************
329 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
330 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie1, bndr_id) ->
331 -- The '-' part is re-mappable syntax
332 tcLookupId minus_name `thenNF_Tc` \ minus_sel_id ->
333 tcLookupGlobalId geName `thenNF_Tc` \ ge_sel_id ->
334 newOverloadedLit origin lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie2) ->
335 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ ge ->
336 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ minus ->
338 returnTc (NPlusKPat bndr_id i pat_ty
339 (SectionR (HsVar (instToId ge)) over_lit_expr)
340 (SectionR (HsVar (instToId minus)) over_lit_expr),
341 lie1 `plusLIE` lie2 `plusLIE` mkLIE [ge,minus],
342 emptyBag, unitBag (name, bndr_id), emptyLIE)
344 origin = PatOrigin pat
347 %************************************************************************
349 \subsection{Lists of patterns}
351 %************************************************************************
356 tcPats :: BinderChecker -- How to deal with variables
357 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
359 LIE, -- Required by n+k and literal pats
361 Bag (Name, TcId), -- Ids bound by the pattern
362 LIE) -- Dicts bound by the pattern
364 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
366 tcPats tc_bndr (ty:tys) (pat:pats)
367 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
368 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
370 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
371 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
372 lie_avail1 `plusLIE` lie_avail2)
375 ------------------------------------------------------
377 tcConstructor pat con_name
378 = -- Check that it's a constructor
379 tcLookupDataCon con_name `thenNF_Tc` \ data_con ->
383 (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
384 -- Ignore the theta; overloaded constructors only
385 -- behave differently when called, not when used for
388 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
390 ex_theta' = substTheta tenv ex_theta
391 arg_tys' = map (substTy tenv) arg_tys
393 n_ex_tvs = length ex_tvs
394 ex_tvs' = take n_ex_tvs all_tvs'
395 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
397 newDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ dicts ->
399 returnTc (data_con, ex_tvs', map instToId dicts, mkLIE dicts, arg_tys', result_ty)
402 ------------------------------------------------------
404 tcConPat tc_bndr pat con_name arg_pats pat_ty
405 = tcAddErrCtxt (patCtxt pat) $
407 -- Check the constructor itself
408 tcConstructor pat con_name `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
410 -- Check overall type matches.
411 -- The pat_ty might be a for-all type, in which
412 -- case we must instantiate to match
413 tcSubPat con_res_ty pat_ty `thenTc` \ (co_fn, lie_req1) ->
415 -- Check correct arity
417 con_arity = dataConSourceArity data_con
418 no_of_args = length arg_pats
420 checkTc (con_arity == no_of_args)
421 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
424 tcPats tc_bndr arg_pats arg_tys `thenTc` \ (arg_pats', lie_req2, tvs, ids, lie_avail2) ->
426 returnTc (co_fn <$> ConPat data_con pat_ty ex_tvs dicts arg_pats',
427 lie_req1 `plusLIE` lie_req2,
428 listToBag ex_tvs `unionBags` tvs,
430 lie_avail1 `plusLIE` lie_avail2)
434 %************************************************************************
436 \subsection{Subsumption}
438 %************************************************************************
441 f :: (forall a. a->a) -> Int -> Int
442 f (g::Int->Int) y = g y
443 This is ok: the type signature allows fewer callers than
444 the (more general) signature f :: (Int->Int) -> Int -> Int
445 I.e. (forall a. a->a) <= Int -> Int
446 We end up translating this to:
447 f = \g' :: (forall a. a->a). let g = g' Int in g' y
449 tcSubPat does the work
450 sig_ty is the signature on the pattern itself
451 (Int->Int in the example)
452 expected_ty is the type passed inwards from the context
453 (forall a. a->a in the example)
456 tcSubPat :: TcSigmaType -> TcSigmaType -> TcM (PatCoFn, LIE)
458 tcSubPat sig_ty exp_ty
459 = tcSub exp_ty sig_ty `thenTc` \ (co_fn, lie) ->
460 -- co_fn is a coercion on *expressions*, and we
461 -- need to make a coercion on *patterns*
462 if isIdCoercion co_fn then
463 ASSERT( isEmptyLIE lie )
464 returnNF_Tc (idCoercion, emptyLIE)
466 tcGetUnique `thenNF_Tc` \ uniq ->
468 arg_id = mkSysLocal SLIT("sub") uniq exp_ty
469 the_fn = DictLam [arg_id] (co_fn <$> HsVar arg_id)
470 pat_co_fn p = SigPat p exp_ty the_fn
472 returnNF_Tc (mkCoercion pat_co_fn, lie)
476 %************************************************************************
478 \subsection{Errors and contexts}
480 %************************************************************************
483 patCtxt pat = hang (ptext SLIT("In the pattern:"))
486 badFieldCon :: Name -> Name -> SDoc
487 badFieldCon con field
488 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
489 ptext SLIT("does not have field"), quotes (ppr field)]
491 polyPatSig :: TcType -> SDoc
493 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
496 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat