2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcPat]{Typechecking patterns}
7 module TcPat ( tcPat, tcVarPat, badFieldCon, polyPatSig ) where
9 #include "HsVersions.h"
11 import {-# SOURCE #-} TcExpr( tcExpr )
13 import HsSyn ( InPat(..), OutPat(..), HsLit(..), HsExpr(..), Sig(..) )
14 import RnHsSyn ( RenamedPat )
15 import TcHsSyn ( TcPat, TcId )
18 import Inst ( Inst, OverloadedLit(..), InstOrigin(..),
19 emptyLIE, plusLIE, LIE,
20 newMethod, newMethodWithGivenTy, newOverloadedLit,
21 newDicts, instToIdBndr
23 import Name ( Name, getOccName, getSrcLoc )
24 import FieldLabel ( fieldLabelName )
25 import TcEnv ( tcLookupValue,
26 tcLookupValueByKey, newLocalId, badCon
28 import TcType ( TcType, TcTyVar, tcInstTyVars )
29 import TcMonoType ( tcHsType )
30 import TcUnify ( unifyTauTy, unifyListTy,
31 unifyTupleTy, unifyUnboxedTupleTy
35 import CmdLineOpts ( opt_IrrefutableTuples )
36 import DataCon ( DataCon, dataConSig, dataConFieldLabels, dataConSourceArity )
37 import Id ( Id, mkUserId, idType, isDataConId_maybe )
38 import Type ( Type, isTauTy, substTopTy, substTopTheta, mkTyConApp )
39 import TysPrim ( charPrimTy, intPrimTy, floatPrimTy,
40 doublePrimTy, addrPrimTy
42 import TysWiredIn ( charTy, stringTy, intTy )
43 import SrcLoc ( SrcLoc )
44 import Unique ( eqClassOpKey, geClassOpKey, minusClassOpKey )
46 import Util ( zipEqual )
51 %************************************************************************
53 \subsection{Variable patterns}
55 %************************************************************************
58 tcVarPat :: (Name -> Maybe TcId) -- Info about signatures; gives the *monomorphic*
59 -- Id for variables with a type signature
62 -> TcType -- Expected type, derived from the context
63 -- In the case of a function with a rank-2 signature,
64 -- this type might be a forall type.
65 -- INVARIANT: if it is, the foralls will always be visible,
66 -- not hidden inside a mutable type variable
68 -> TcM s TcId -- The monomorphic Id; this is put in the pattern itself
70 tcVarPat sig_fn binder_name pat_ty
71 = case sig_fn binder_name of
72 Nothing -> newLocalId (getOccName binder_name) pat_ty `thenNF_Tc` \ bndr_id ->
75 Just bndr_id -> tcAddSrcLoc (getSrcLoc binder_name) $
76 unifyTauTy (idType bndr_id) pat_ty `thenTc_`
81 %************************************************************************
83 \subsection{Typechecking patterns}
85 %************************************************************************
88 tcPat :: (Name -> Maybe TcId) -- Info about signatures; gives the *monomorphic*
89 -- Id for variables with a type signature
91 -> TcType -- Expected type; see invariant in tcVarPat
93 LIE, -- Required by n+k and literal pats
94 Bag TcTyVar, -- TyVars bound by the pattern
95 -- These are just the existentially-bound ones.
96 -- Any tyvars bound by *type signatures* in the
97 -- patterns are brought into scope before we begin.
98 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
99 -- which it occurs in the pattern
100 -- The two aren't the same because we conjure up a new
101 -- local name for each variable.
102 LIE) -- Dicts or methods [see below] bound by the pattern
103 -- from existential constructor patterns
107 %************************************************************************
109 \subsection{Variables, wildcards, lazy pats, as-pats}
111 %************************************************************************
114 tcPat sig_fn (VarPatIn name) pat_ty
115 = tcVarPat sig_fn name pat_ty `thenTc` \ bndr_id ->
116 returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
118 tcPat sig_fn (LazyPatIn pat) pat_ty
119 = tcPat sig_fn pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
120 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
122 tcPat sig_fn pat_in@(AsPatIn name pat) pat_ty
123 = tcVarPat sig_fn name pat_ty `thenTc` \ bndr_id ->
124 tcPat sig_fn pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
125 tcAddErrCtxt (patCtxt pat_in) $
126 returnTc (AsPat bndr_id pat', lie_req,
127 tvs, (name, bndr_id) `consBag` ids, lie_avail)
129 tcPat sig_fn WildPatIn pat_ty
130 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
132 tcPat sig_fn (NegPatIn pat) pat_ty
133 = tcPat sig_fn (negate_lit pat) pat_ty
135 negate_lit (LitPatIn (HsInt i)) = LitPatIn (HsInt (-i))
136 negate_lit (LitPatIn (HsFrac f)) = LitPatIn (HsFrac (-f))
137 negate_lit _ = panic "TcPat:negate_pat"
139 tcPat sig_fn (ParPatIn parend_pat) pat_ty
140 = tcPat sig_fn parend_pat pat_ty
142 tcPat sig_fn (SigPatIn pat sig) pat_ty
143 = tcHsType sig `thenTc` \ sig_ty ->
145 -- Check that the signature isn't a polymorphic one, which
146 -- we don't permit (at present, anyway)
147 checkTc (isTauTy sig_ty) (polyPatSig sig_ty) `thenTc_`
149 unifyTauTy pat_ty sig_ty `thenTc_`
150 tcPat sig_fn pat sig_ty
153 %************************************************************************
155 \subsection{Explicit lists and tuples}
157 %************************************************************************
160 tcPat sig_fn pat_in@(ListPatIn pats) pat_ty
161 = tcAddErrCtxt (patCtxt pat_in) $
162 unifyListTy pat_ty `thenTc` \ elem_ty ->
163 tcPats sig_fn pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
164 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
166 tcPat sig_fn pat_in@(TuplePatIn pats boxed) pat_ty
167 = tcAddErrCtxt (patCtxt pat_in) $
170 then unifyTupleTy arity pat_ty
171 else unifyUnboxedTupleTy arity pat_ty) `thenTc` \ arg_tys ->
173 tcPats sig_fn pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
175 -- possibly do the "make all tuple-pats irrefutable" test:
177 unmangled_result = TuplePat pats' boxed
179 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
180 -- so that we can experiment with lazy tuple-matching.
181 -- This is a pretty odd place to make the switch, but
182 -- it was easy to do.
184 possibly_mangled_result
185 | opt_IrrefutableTuples && boxed = LazyPat unmangled_result
186 | otherwise = unmangled_result
188 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
193 %************************************************************************
195 \subsection{Other constructors}
198 %************************************************************************
201 tcPat sig_fn pat@(ConPatIn name arg_pats) pat_ty
202 = tcConPat sig_fn pat name arg_pats pat_ty
204 tcPat sig_fn pat@(ConOpPatIn pat1 op _ pat2) pat_ty
205 = tcConPat sig_fn pat op [pat1, pat2] pat_ty
209 %************************************************************************
213 %************************************************************************
216 tcPat sig_fn pat@(RecPatIn name rpats) pat_ty
217 = tcAddErrCtxt (patCtxt pat) $
219 -- Check the constructor itself
220 tcConstructor pat name pat_ty `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
222 field_tys = zipEqual "tcPat"
223 (map fieldLabelName (dataConFieldLabels data_con))
228 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
230 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
232 listToBag ex_tvs `unionBags` tvs,
234 lie_avail1 `plusLIE` lie_avail2)
237 tc_fields field_tys []
238 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
240 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
241 | null matching_fields
242 = addErrTc (badFieldCon name field_label) `thenNF_Tc_`
243 tc_fields field_tys rpats
246 = ASSERT( null extras )
247 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
249 tcLookupValue field_label `thenNF_Tc` \ sel_id ->
250 tcPat sig_fn rhs_pat rhs_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
252 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
253 lie_req1 `plusLIE` lie_req2,
254 tvs1 `unionBags` tvs2,
255 ids1 `unionBags` ids2,
256 lie_avail1 `plusLIE` lie_avail2)
258 matching_fields = [ty | (f,ty) <- field_tys, f == field_label]
259 (rhs_ty : extras) = matching_fields
262 %************************************************************************
264 \subsection{Non-overloaded literals}
266 %************************************************************************
269 tcPat sig_fn (LitPatIn lit@(HsChar _)) pat_ty = tcSimpleLitPat lit charTy pat_ty
270 tcPat sig_fn (LitPatIn lit@(HsIntPrim _)) pat_ty = tcSimpleLitPat lit intPrimTy pat_ty
271 tcPat sig_fn (LitPatIn lit@(HsCharPrim _)) pat_ty = tcSimpleLitPat lit charPrimTy pat_ty
272 tcPat sig_fn (LitPatIn lit@(HsStringPrim _)) pat_ty = tcSimpleLitPat lit addrPrimTy pat_ty
273 tcPat sig_fn (LitPatIn lit@(HsFloatPrim _)) pat_ty = tcSimpleLitPat lit floatPrimTy pat_ty
274 tcPat sig_fn (LitPatIn lit@(HsDoublePrim _)) pat_ty = tcSimpleLitPat lit doublePrimTy pat_ty
276 tcPat sig_fn (LitPatIn lit@(HsLitLit s)) pat_ty = tcSimpleLitPat lit intTy pat_ty
277 -- This one looks weird!
280 %************************************************************************
282 \subsection{Overloaded patterns: int literals and \tr{n+k} patterns}
284 %************************************************************************
287 tcPat sig_fn pat@(LitPatIn lit@(HsString str)) pat_ty
288 = unifyTauTy pat_ty stringTy `thenTc_`
289 tcLookupValueByKey eqClassOpKey `thenNF_Tc` \ sel_id ->
290 newMethod (PatOrigin pat) sel_id [stringTy] `thenNF_Tc` \ (lie, eq_id) ->
292 comp_op = HsApp (HsVar eq_id) (HsLitOut lit stringTy)
294 returnTc (NPat lit stringTy comp_op, lie, emptyBag, emptyBag, emptyLIE)
297 tcPat sig_fn pat@(LitPatIn lit@(HsInt i)) pat_ty
298 = tcOverloadedLitPat pat lit (OverloadedIntegral i) pat_ty
300 tcPat sig_fn pat@(LitPatIn lit@(HsFrac f)) pat_ty
301 = tcOverloadedLitPat pat lit (OverloadedFractional f) pat_ty
304 tcPat sig_fn pat@(NPlusKPatIn name lit@(HsInt i)) pat_ty
305 = tcVarPat sig_fn name pat_ty `thenTc` \ bndr_id ->
306 tcLookupValueByKey geClassOpKey `thenNF_Tc` \ ge_sel_id ->
307 tcLookupValueByKey minusClassOpKey `thenNF_Tc` \ minus_sel_id ->
309 newOverloadedLit origin
310 (OverloadedIntegral i) pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
312 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ (lie2, ge_id) ->
313 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ (lie3, minus_id) ->
315 returnTc (NPlusKPat bndr_id lit pat_ty
316 (SectionR (HsVar ge_id) over_lit_expr)
317 (SectionR (HsVar minus_id) over_lit_expr),
318 lie1 `plusLIE` lie2 `plusLIE` lie3,
319 emptyBag, unitBag (name, bndr_id), emptyLIE)
321 origin = PatOrigin pat
323 tcPat sig_fn (NPlusKPatIn pat other) pat_ty
324 = panic "TcPat:NPlusKPat: not an HsInt literal"
327 %************************************************************************
329 \subsection{Lists of patterns}
331 %************************************************************************
336 tcPats :: (Name -> Maybe TcId) -- Info about signatures
337 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
339 LIE, -- Required by n+k and literal pats
341 Bag (Name, TcId), -- Ids bound by the pattern
342 LIE) -- Dicts bound by the pattern
344 tcPats sig_fn [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
346 tcPats sig_fn (ty:tys) (pat:pats)
347 = tcPat sig_fn ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
348 tcPats sig_fn tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
350 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
351 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
352 lie_avail1 `plusLIE` lie_avail2)
355 ------------------------------------------------------
357 tcSimpleLitPat lit lit_ty pat_ty
358 = unifyTauTy pat_ty lit_ty `thenTc_`
359 returnTc (LitPat lit lit_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
362 tcOverloadedLitPat pat lit over_lit pat_ty
363 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
364 tcLookupValueByKey eqClassOpKey `thenNF_Tc` \ eq_sel_id ->
365 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ (lie2, eq_id) ->
367 returnTc (NPat lit pat_ty (HsApp (HsVar eq_id)
370 emptyBag, emptyBag, emptyLIE)
372 origin = PatOrigin pat
375 ------------------------------------------------------
377 tcConstructor pat con_name pat_ty
378 = -- Check that it's a constructor
379 tcLookupValue con_name `thenNF_Tc` \ con_id ->
380 case isDataConId_maybe con_id of {
381 Nothing -> failWithTc (badCon con_id);
386 (tvs, theta, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
387 -- Ignore the theta; overloaded constructors only
388 -- behave differently when called, not when used for
391 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
393 ex_theta' = substTopTheta tenv ex_theta
394 arg_tys' = map (substTopTy tenv) arg_tys
396 n_ex_tvs = length ex_tvs
397 ex_tvs' = take n_ex_tvs all_tvs'
398 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
400 newDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ (lie_avail, dicts) ->
402 -- Check overall type matches
403 unifyTauTy pat_ty result_ty `thenTc_`
405 returnTc (data_con, ex_tvs', dicts, lie_avail, arg_tys')
409 ------------------------------------------------------
411 tcConPat sig_fn pat con_name arg_pats pat_ty
412 = tcAddErrCtxt (patCtxt pat) $
414 -- Check the constructor itself
415 tcConstructor pat con_name pat_ty `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
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 sig_fn arg_pats arg_tys' `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
428 returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
430 listToBag ex_tvs' `unionBags` tvs,
432 lie_avail1 `plusLIE` lie_avail2)
436 %************************************************************************
438 \subsection{Errors and contexts}
440 %************************************************************************
443 patCtxt pat = hang (ptext SLIT("In the pattern:"))
446 recordLabel field_label
447 = hang (hcat [ptext SLIT("When matching record field"), ppr field_label])
448 4 (hcat [ptext SLIT("with its immediately enclosing constructor")])
450 recordRhs field_label pat
451 = hang (ptext SLIT("In the record field pattern"))
452 4 (sep [ppr field_label, char '=', ppr pat])
454 badFieldCon :: Name -> Name -> SDoc
455 badFieldCon con field
456 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
457 ptext SLIT("does not have field"), quotes (ppr field)]
459 polyPatSig :: TcType -> SDoc
461 = hang (ptext SLIT("Polymorphic type signature in pattern"))