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, newDicts, newClassDicts
22 import Name ( Name, getOccName, getSrcLoc )
23 import FieldLabel ( fieldLabelName )
24 import TcEnv ( tcLookupValue, tcLookupClassByKey,
25 tcLookupValueByKey, newLocalId, badCon
27 import TcType ( TcType, TcTyVar, tcInstTyVars, newTyVarTy )
28 import TcMonoType ( tcHsSigType )
29 import TcUnify ( unifyTauTy, unifyListTy,
30 unifyTupleTy, unifyUnboxedTupleTy
34 import CmdLineOpts ( opt_IrrefutableTuples )
35 import DataCon ( DataCon, dataConSig, dataConFieldLabels,
38 import Id ( Id, idType, isDataConWrapId_maybe )
39 import Type ( Type, isTauTy, mkTyConApp, mkClassPred, boxedTypeKind )
40 import PprType ( {- instance Outputable Type -} )
41 import Subst ( substTy, substClasses )
42 import TysPrim ( charPrimTy, intPrimTy, floatPrimTy,
43 doublePrimTy, addrPrimTy
45 import TysWiredIn ( charTy, stringTy, intTy )
46 import SrcLoc ( SrcLoc )
47 import Unique ( eqClassOpKey, geClassOpKey, minusClassOpKey,
51 import Util ( zipEqual )
56 %************************************************************************
58 \subsection{Variable patterns}
60 %************************************************************************
63 -- This is the right function to pass to tcPat when there are no signatures
64 tcPatBndr_NoSigs binder_name pat_ty
65 = -- Need to make a new, monomorphic, Id
66 -- The binder_name is already being used for the polymorphic Id
67 newLocalId (getOccName binder_name) pat_ty loc `thenNF_Tc` \ bndr_id ->
70 loc = getSrcLoc binder_name
74 %************************************************************************
76 \subsection{Typechecking patterns}
78 %************************************************************************
81 tcPat :: (Name -> TcType -> TcM s TcId) -- How to construct a suitable (monomorphic)
82 -- Id for variables found in the pattern
83 -- The TcType is the expected type, see note below
86 -> TcType -- Expected type derived from the context
87 -- In the case of a function with a rank-2 signature,
88 -- this type might be a forall type.
89 -- INVARIANT: if it is, the foralls will always be visible,
90 -- not hidden inside a mutable type variable
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 tc_bndr (VarPatIn name) pat_ty
115 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
116 returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
118 tcPat tc_bndr (LazyPatIn pat) pat_ty
119 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
120 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
122 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
123 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
124 tcPat tc_bndr 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 tc_bndr WildPatIn pat_ty
130 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
132 tcPat tc_bndr (NegPatIn pat) pat_ty
133 = tcPat tc_bndr (negate_lit pat) pat_ty
135 negate_lit (LitPatIn (HsInt i)) = LitPatIn (HsInt (-i))
136 negate_lit (LitPatIn (HsIntPrim i)) = LitPatIn (HsIntPrim (-i))
137 negate_lit (LitPatIn (HsFrac f)) = LitPatIn (HsFrac (-f))
138 negate_lit (LitPatIn (HsFloatPrim f)) = LitPatIn (HsFloatPrim (-f))
139 negate_lit (LitPatIn (HsDoublePrim f)) = LitPatIn (HsDoublePrim (-f))
140 negate_lit _ = panic "TcPat:negate_pat"
142 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
143 = tcPat tc_bndr parend_pat pat_ty
145 tcPat tc_bndr (SigPatIn pat sig) pat_ty
146 = tcHsSigType sig `thenTc` \ sig_ty ->
148 -- Check that the signature isn't a polymorphic one, which
149 -- we don't permit (at present, anyway)
150 checkTc (isTauTy sig_ty) (polyPatSig sig_ty) `thenTc_`
152 unifyTauTy pat_ty sig_ty `thenTc_`
153 tcPat tc_bndr pat sig_ty
156 %************************************************************************
158 \subsection{Explicit lists 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@(TuplePatIn pats boxed) pat_ty
170 = tcAddErrCtxt (patCtxt pat_in) $
173 then unifyTupleTy arity pat_ty
174 else unifyUnboxedTupleTy arity pat_ty) `thenTc` \ arg_tys ->
176 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
178 -- possibly do the "make all tuple-pats irrefutable" test:
180 unmangled_result = TuplePat pats' boxed
182 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
183 -- so that we can experiment with lazy tuple-matching.
184 -- This is a pretty odd place to make the switch, but
185 -- it was easy to do.
187 possibly_mangled_result
188 | opt_IrrefutableTuples && boxed = LazyPat unmangled_result
189 | otherwise = unmangled_result
191 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
196 %************************************************************************
198 \subsection{Other constructors}
201 %************************************************************************
204 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
205 = tcConPat tc_bndr pat name arg_pats pat_ty
207 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
208 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
212 %************************************************************************
216 %************************************************************************
219 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
220 = tcAddErrCtxt (patCtxt pat) $
222 -- Check the constructor itself
223 tcConstructor pat name pat_ty `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
225 field_tys = zipEqual "tcPat"
226 (map fieldLabelName (dataConFieldLabels data_con))
231 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
233 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
235 listToBag ex_tvs `unionBags` tvs,
237 lie_avail1 `plusLIE` lie_avail2)
240 tc_fields field_tys []
241 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
243 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
244 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
246 (case [ty | (f,ty) <- field_tys, f == field_label] of
248 -- No matching field; chances are this field label comes from some
249 -- other record type (or maybe none). As well as reporting an
250 -- error we still want to typecheck the pattern, principally to
251 -- make sure that all the variables it binds are put into the
252 -- environment, else the type checker crashes later:
253 -- f (R { foo = (a,b) }) = a+b
254 -- If foo isn't one of R's fields, we don't want to crash when
255 -- typechecking the "a+b".
256 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
257 newTyVarTy boxedTypeKind `thenNF_Tc_`
258 returnTc (error "Bogus selector Id", pat_ty)
260 -- The normal case, when the field comes from the right constructor
262 ASSERT( null extras )
263 tcLookupValue field_label `thenNF_Tc` \ sel_id ->
264 returnTc (sel_id, pat_ty)
265 ) `thenTc` \ (sel_id, pat_ty) ->
267 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
269 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
270 lie_req1 `plusLIE` lie_req2,
271 tvs1 `unionBags` tvs2,
272 ids1 `unionBags` ids2,
273 lie_avail1 `plusLIE` lie_avail2)
276 %************************************************************************
278 \subsection{Non-overloaded literals}
280 %************************************************************************
283 tcPat tc_bndr (LitPatIn lit@(HsChar _)) pat_ty = tcSimpleLitPat lit charTy pat_ty
284 tcPat tc_bndr (LitPatIn lit@(HsIntPrim _)) pat_ty = tcSimpleLitPat lit intPrimTy pat_ty
285 tcPat tc_bndr (LitPatIn lit@(HsCharPrim _)) pat_ty = tcSimpleLitPat lit charPrimTy pat_ty
286 tcPat tc_bndr (LitPatIn lit@(HsStringPrim _)) pat_ty = tcSimpleLitPat lit addrPrimTy pat_ty
287 tcPat tc_bndr (LitPatIn lit@(HsFloatPrim _)) pat_ty = tcSimpleLitPat lit floatPrimTy pat_ty
288 tcPat tc_bndr (LitPatIn lit@(HsDoublePrim _)) pat_ty = tcSimpleLitPat lit doublePrimTy pat_ty
290 tcPat tc_bndr (LitPatIn lit@(HsLitLit s)) pat_ty
291 -- cf tcExpr on LitLits
292 = tcLookupClassByKey cCallableClassKey `thenNF_Tc` \ cCallableClass ->
293 newDicts (LitLitOrigin (_UNPK_ s))
294 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ (dicts, _) ->
295 returnTc (LitPat lit pat_ty, dicts, emptyBag, emptyBag, emptyLIE)
298 %************************************************************************
300 \subsection{Overloaded patterns: int literals and \tr{n+k} patterns}
302 %************************************************************************
305 tcPat tc_bndr pat@(LitPatIn lit@(HsString str)) pat_ty
306 = unifyTauTy pat_ty stringTy `thenTc_`
307 tcLookupValueByKey eqClassOpKey `thenNF_Tc` \ sel_id ->
308 newMethod (PatOrigin pat) sel_id [stringTy] `thenNF_Tc` \ (lie, eq_id) ->
310 comp_op = HsApp (HsVar eq_id) (HsLitOut lit stringTy)
312 returnTc (NPat lit stringTy comp_op, lie, emptyBag, emptyBag, emptyLIE)
315 tcPat tc_bndr pat@(LitPatIn lit@(HsInt i)) pat_ty
316 = tcOverloadedLitPat pat lit (OverloadedIntegral i) pat_ty
318 tcPat tc_bndr pat@(LitPatIn lit@(HsFrac f)) pat_ty
319 = tcOverloadedLitPat pat lit (OverloadedFractional f) pat_ty
322 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsInt i)) pat_ty
323 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
324 tcLookupValueByKey geClassOpKey `thenNF_Tc` \ ge_sel_id ->
325 tcLookupValueByKey minusClassOpKey `thenNF_Tc` \ minus_sel_id ->
327 newOverloadedLit origin
328 (OverloadedIntegral i) pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
330 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ (lie2, ge_id) ->
331 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ (lie3, minus_id) ->
333 returnTc (NPlusKPat bndr_id lit pat_ty
334 (SectionR (HsVar ge_id) over_lit_expr)
335 (SectionR (HsVar minus_id) over_lit_expr),
336 lie1 `plusLIE` lie2 `plusLIE` lie3,
337 emptyBag, unitBag (name, bndr_id), emptyLIE)
339 origin = PatOrigin pat
341 tcPat tc_bndr (NPlusKPatIn pat other) pat_ty
342 = panic "TcPat:NPlusKPat: not an HsInt literal"
345 %************************************************************************
347 \subsection{Lists of patterns}
349 %************************************************************************
354 tcPats :: (Name -> TcType -> TcM s TcId) -- How to deal with variables
355 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
357 LIE, -- Required by n+k and literal pats
359 Bag (Name, TcId), -- Ids bound by the pattern
360 LIE) -- Dicts bound by the pattern
362 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
364 tcPats tc_bndr (ty:tys) (pat:pats)
365 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
366 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
368 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
369 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
370 lie_avail1 `plusLIE` lie_avail2)
373 ------------------------------------------------------
375 tcSimpleLitPat lit lit_ty pat_ty
376 = unifyTauTy pat_ty lit_ty `thenTc_`
377 returnTc (LitPat lit lit_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
380 tcOverloadedLitPat pat lit over_lit pat_ty
381 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
382 tcLookupValueByKey eqClassOpKey `thenNF_Tc` \ eq_sel_id ->
383 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ (lie2, eq_id) ->
385 returnTc (NPat lit pat_ty (HsApp (HsVar eq_id)
388 emptyBag, emptyBag, emptyLIE)
390 origin = PatOrigin pat
393 ------------------------------------------------------
395 tcConstructor pat con_name pat_ty
396 = -- Check that it's a constructor
397 tcLookupValue con_name `thenNF_Tc` \ con_id ->
398 case isDataConWrapId_maybe con_id of {
399 Nothing -> failWithTc (badCon con_id);
404 (tvs, theta, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
405 -- Ignore the theta; overloaded constructors only
406 -- behave differently when called, not when used for
409 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
411 ex_theta' = substClasses tenv ex_theta
412 arg_tys' = map (substTy tenv) arg_tys
414 n_ex_tvs = length ex_tvs
415 ex_tvs' = take n_ex_tvs all_tvs'
416 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
418 newClassDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ (lie_avail, dicts) ->
420 -- Check overall type matches
421 unifyTauTy pat_ty result_ty `thenTc_`
423 returnTc (data_con, ex_tvs', dicts, lie_avail, arg_tys')
427 ------------------------------------------------------
429 tcConPat tc_bndr pat con_name arg_pats pat_ty
430 = tcAddErrCtxt (patCtxt pat) $
432 -- Check the constructor itself
433 tcConstructor pat con_name pat_ty `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
435 -- Check correct arity
437 con_arity = dataConSourceArity data_con
438 no_of_args = length arg_pats
440 checkTc (con_arity == no_of_args)
441 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
444 tcPats tc_bndr arg_pats arg_tys' `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
446 returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
448 listToBag ex_tvs' `unionBags` tvs,
450 lie_avail1 `plusLIE` lie_avail2)
454 %************************************************************************
456 \subsection{Errors and contexts}
458 %************************************************************************
461 patCtxt pat = hang (ptext SLIT("In the pattern:"))
464 recordLabel field_label
465 = hang (hcat [ptext SLIT("When matching record field"), ppr field_label])
466 4 (hcat [ptext SLIT("with its immediately enclosing constructor")])
468 recordRhs field_label pat
469 = hang (ptext SLIT("In the record field pattern"))
470 4 (sep [ppr field_label, char '=', ppr pat])
472 badFieldCon :: Name -> Name -> SDoc
473 badFieldCon con field
474 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
475 ptext SLIT("does not have field"), quotes (ppr field)]
477 polyPatSig :: TcType -> SDoc
479 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))