2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcPat]{Typechecking patterns}
7 module TcPat ( tcPat, tcPatBndr_NoSigs, 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, 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, idType, isDataConId_maybe )
38 import Type ( Type, isTauTy, mkTyConApp )
39 import Subst ( substTy, substTheta )
40 import TysPrim ( charPrimTy, intPrimTy, floatPrimTy,
41 doublePrimTy, addrPrimTy
43 import TysWiredIn ( charTy, stringTy, intTy )
44 import SrcLoc ( SrcLoc )
45 import Unique ( eqClassOpKey, geClassOpKey, minusClassOpKey )
47 import Util ( zipEqual )
52 %************************************************************************
54 \subsection{Variable patterns}
56 %************************************************************************
59 -- This is the right function to pass to tcPat when there are no signatures
60 tcPatBndr_NoSigs binder_name pat_ty
61 = -- Need to make a new, monomorphic, Id
62 -- The binder_name is already being used for the polymorphic Id
63 newLocalId (getOccName binder_name) pat_ty loc `thenNF_Tc` \ bndr_id ->
66 loc = getSrcLoc binder_name
70 %************************************************************************
72 \subsection{Typechecking patterns}
74 %************************************************************************
77 tcPat :: (Name -> TcType -> TcM s TcId) -- How to construct a suitable (monomorphic)
78 -- Id for variables found in the pattern
79 -- The TcType is the expected type, see note below
82 -> TcType -- Expected type derived from the context
83 -- In the case of a function with a rank-2 signature,
84 -- this type might be a forall type.
85 -- INVARIANT: if it is, the foralls will always be visible,
86 -- not hidden inside a mutable type variable
89 LIE, -- Required by n+k and literal pats
90 Bag TcTyVar, -- TyVars bound by the pattern
91 -- These are just the existentially-bound ones.
92 -- Any tyvars bound by *type signatures* in the
93 -- patterns are brought into scope before we begin.
94 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
95 -- which it occurs in the pattern
96 -- The two aren't the same because we conjure up a new
97 -- local name for each variable.
98 LIE) -- Dicts or methods [see below] bound by the pattern
99 -- from existential constructor patterns
103 %************************************************************************
105 \subsection{Variables, wildcards, lazy pats, as-pats}
107 %************************************************************************
110 tcPat tc_bndr (VarPatIn name) pat_ty
111 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
112 returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
114 tcPat tc_bndr (LazyPatIn pat) pat_ty
115 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
116 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
118 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
119 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
120 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
121 tcAddErrCtxt (patCtxt pat_in) $
122 returnTc (AsPat bndr_id pat', lie_req,
123 tvs, (name, bndr_id) `consBag` ids, lie_avail)
125 tcPat tc_bndr WildPatIn pat_ty
126 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
128 tcPat tc_bndr (NegPatIn pat) pat_ty
129 = tcPat tc_bndr (negate_lit pat) pat_ty
131 negate_lit (LitPatIn (HsInt i)) = LitPatIn (HsInt (-i))
132 negate_lit (LitPatIn (HsFrac f)) = LitPatIn (HsFrac (-f))
133 negate_lit _ = panic "TcPat:negate_pat"
135 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
136 = tcPat tc_bndr parend_pat pat_ty
138 tcPat tc_bndr (SigPatIn pat sig) pat_ty
139 = tcHsType sig `thenTc` \ sig_ty ->
141 -- Check that the signature isn't a polymorphic one, which
142 -- we don't permit (at present, anyway)
143 checkTc (isTauTy sig_ty) (polyPatSig sig_ty) `thenTc_`
145 unifyTauTy pat_ty sig_ty `thenTc_`
146 tcPat tc_bndr pat sig_ty
149 %************************************************************************
151 \subsection{Explicit lists and tuples}
153 %************************************************************************
156 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
157 = tcAddErrCtxt (patCtxt pat_in) $
158 unifyListTy pat_ty `thenTc` \ elem_ty ->
159 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
160 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
162 tcPat tc_bndr pat_in@(TuplePatIn pats boxed) pat_ty
163 = tcAddErrCtxt (patCtxt pat_in) $
166 then unifyTupleTy arity pat_ty
167 else unifyUnboxedTupleTy arity pat_ty) `thenTc` \ arg_tys ->
169 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
171 -- possibly do the "make all tuple-pats irrefutable" test:
173 unmangled_result = TuplePat pats' boxed
175 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
176 -- so that we can experiment with lazy tuple-matching.
177 -- This is a pretty odd place to make the switch, but
178 -- it was easy to do.
180 possibly_mangled_result
181 | opt_IrrefutableTuples && boxed = LazyPat unmangled_result
182 | otherwise = unmangled_result
184 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
189 %************************************************************************
191 \subsection{Other constructors}
194 %************************************************************************
197 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
198 = tcConPat tc_bndr pat name arg_pats pat_ty
200 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
201 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
205 %************************************************************************
209 %************************************************************************
212 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
213 = tcAddErrCtxt (patCtxt pat) $
215 -- Check the constructor itself
216 tcConstructor pat name pat_ty `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
218 field_tys = zipEqual "tcPat"
219 (map fieldLabelName (dataConFieldLabels data_con))
224 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
226 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
228 listToBag ex_tvs `unionBags` tvs,
230 lie_avail1 `plusLIE` lie_avail2)
233 tc_fields field_tys []
234 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
236 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
237 | null matching_fields
238 = addErrTc (badFieldCon name field_label) `thenNF_Tc_`
239 tc_fields field_tys rpats
242 = ASSERT( null extras )
243 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
245 tcLookupValue field_label `thenNF_Tc` \ sel_id ->
246 tcPat tc_bndr rhs_pat rhs_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
248 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
249 lie_req1 `plusLIE` lie_req2,
250 tvs1 `unionBags` tvs2,
251 ids1 `unionBags` ids2,
252 lie_avail1 `plusLIE` lie_avail2)
254 matching_fields = [ty | (f,ty) <- field_tys, f == field_label]
255 (rhs_ty : extras) = matching_fields
258 %************************************************************************
260 \subsection{Non-overloaded literals}
262 %************************************************************************
265 tcPat tc_bndr (LitPatIn lit@(HsChar _)) pat_ty = tcSimpleLitPat lit charTy pat_ty
266 tcPat tc_bndr (LitPatIn lit@(HsIntPrim _)) pat_ty = tcSimpleLitPat lit intPrimTy pat_ty
267 tcPat tc_bndr (LitPatIn lit@(HsCharPrim _)) pat_ty = tcSimpleLitPat lit charPrimTy pat_ty
268 tcPat tc_bndr (LitPatIn lit@(HsStringPrim _)) pat_ty = tcSimpleLitPat lit addrPrimTy pat_ty
269 tcPat tc_bndr (LitPatIn lit@(HsFloatPrim _)) pat_ty = tcSimpleLitPat lit floatPrimTy pat_ty
270 tcPat tc_bndr (LitPatIn lit@(HsDoublePrim _)) pat_ty = tcSimpleLitPat lit doublePrimTy pat_ty
272 tcPat tc_bndr (LitPatIn lit@(HsLitLit s)) pat_ty = tcSimpleLitPat lit intTy pat_ty
273 -- This one looks weird!
276 %************************************************************************
278 \subsection{Overloaded patterns: int literals and \tr{n+k} patterns}
280 %************************************************************************
283 tcPat tc_bndr pat@(LitPatIn lit@(HsString str)) pat_ty
284 = unifyTauTy pat_ty stringTy `thenTc_`
285 tcLookupValueByKey eqClassOpKey `thenNF_Tc` \ sel_id ->
286 newMethod (PatOrigin pat) sel_id [stringTy] `thenNF_Tc` \ (lie, eq_id) ->
288 comp_op = HsApp (HsVar eq_id) (HsLitOut lit stringTy)
290 returnTc (NPat lit stringTy comp_op, lie, emptyBag, emptyBag, emptyLIE)
293 tcPat tc_bndr pat@(LitPatIn lit@(HsInt i)) pat_ty
294 = tcOverloadedLitPat pat lit (OverloadedIntegral i) pat_ty
296 tcPat tc_bndr pat@(LitPatIn lit@(HsFrac f)) pat_ty
297 = tcOverloadedLitPat pat lit (OverloadedFractional f) pat_ty
300 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsInt i)) pat_ty
301 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
302 tcLookupValueByKey geClassOpKey `thenNF_Tc` \ ge_sel_id ->
303 tcLookupValueByKey minusClassOpKey `thenNF_Tc` \ minus_sel_id ->
305 newOverloadedLit origin
306 (OverloadedIntegral i) pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
308 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ (lie2, ge_id) ->
309 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ (lie3, minus_id) ->
311 returnTc (NPlusKPat bndr_id lit pat_ty
312 (SectionR (HsVar ge_id) over_lit_expr)
313 (SectionR (HsVar minus_id) over_lit_expr),
314 lie1 `plusLIE` lie2 `plusLIE` lie3,
315 emptyBag, unitBag (name, bndr_id), emptyLIE)
317 origin = PatOrigin pat
319 tcPat tc_bndr (NPlusKPatIn pat other) pat_ty
320 = panic "TcPat:NPlusKPat: not an HsInt literal"
323 %************************************************************************
325 \subsection{Lists of patterns}
327 %************************************************************************
332 tcPats :: (Name -> TcType -> TcM s TcId) -- How to deal with variables
333 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
335 LIE, -- Required by n+k and literal pats
337 Bag (Name, TcId), -- Ids bound by the pattern
338 LIE) -- Dicts bound by the pattern
340 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
342 tcPats tc_bndr (ty:tys) (pat:pats)
343 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
344 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
346 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
347 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
348 lie_avail1 `plusLIE` lie_avail2)
351 ------------------------------------------------------
353 tcSimpleLitPat lit lit_ty pat_ty
354 = unifyTauTy pat_ty lit_ty `thenTc_`
355 returnTc (LitPat lit lit_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
358 tcOverloadedLitPat pat lit over_lit pat_ty
359 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
360 tcLookupValueByKey eqClassOpKey `thenNF_Tc` \ eq_sel_id ->
361 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ (lie2, eq_id) ->
363 returnTc (NPat lit pat_ty (HsApp (HsVar eq_id)
366 emptyBag, emptyBag, emptyLIE)
368 origin = PatOrigin pat
371 ------------------------------------------------------
373 tcConstructor pat con_name pat_ty
374 = -- Check that it's a constructor
375 tcLookupValue con_name `thenNF_Tc` \ con_id ->
376 case isDataConId_maybe con_id of {
377 Nothing -> failWithTc (badCon con_id);
382 (tvs, theta, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
383 -- Ignore the theta; overloaded constructors only
384 -- behave differently when called, not when used for
387 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
389 ex_theta' = substTheta tenv ex_theta
390 arg_tys' = map (substTy tenv) arg_tys
392 n_ex_tvs = length ex_tvs
393 ex_tvs' = take n_ex_tvs all_tvs'
394 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
396 newDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ (lie_avail, dicts) ->
398 -- Check overall type matches
399 unifyTauTy pat_ty result_ty `thenTc_`
401 returnTc (data_con, ex_tvs', dicts, lie_avail, arg_tys')
405 ------------------------------------------------------
407 tcConPat tc_bndr pat con_name arg_pats pat_ty
408 = tcAddErrCtxt (patCtxt pat) $
410 -- Check the constructor itself
411 tcConstructor pat con_name pat_ty `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
413 -- Check correct arity
415 con_arity = dataConSourceArity data_con
416 no_of_args = length arg_pats
418 checkTc (con_arity == no_of_args)
419 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
422 tcPats tc_bndr arg_pats arg_tys' `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
424 returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
426 listToBag ex_tvs' `unionBags` tvs,
428 lie_avail1 `plusLIE` lie_avail2)
432 %************************************************************************
434 \subsection{Errors and contexts}
436 %************************************************************************
439 patCtxt pat = hang (ptext SLIT("In the pattern:"))
442 recordLabel field_label
443 = hang (hcat [ptext SLIT("When matching record field"), ppr field_label])
444 4 (hcat [ptext SLIT("with its immediately enclosing constructor")])
446 recordRhs field_label pat
447 = hang (ptext SLIT("In the record field pattern"))
448 4 (sep [ppr field_label, char '=', ppr pat])
450 badFieldCon :: Name -> Name -> SDoc
451 badFieldCon con field
452 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
453 ptext SLIT("does not have field"), quotes (ppr field)]
455 polyPatSig :: TcType -> SDoc
457 = hang (ptext SLIT("Polymorphic type signature in pattern"))