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 ( tcHsType )
29 import TcUnify ( unifyTauTy, unifyListTy,
30 unifyTupleTy, unifyUnboxedTupleTy
34 import CmdLineOpts ( opt_IrrefutableTuples )
35 import DataCon ( DataCon, dataConSig, dataConFieldLabels,
38 import Id ( Id, idType, isDataConId_maybe )
39 import Type ( Type, isTauTy, mkTyConApp, mkClassPred, boxedTypeKind )
40 import Subst ( substTy, substClasses )
41 import TysPrim ( charPrimTy, intPrimTy, floatPrimTy,
42 doublePrimTy, addrPrimTy
44 import TysWiredIn ( charTy, stringTy, intTy )
45 import SrcLoc ( SrcLoc )
46 import Unique ( eqClassOpKey, geClassOpKey, minusClassOpKey,
50 import Util ( zipEqual )
55 %************************************************************************
57 \subsection{Variable patterns}
59 %************************************************************************
62 -- This is the right function to pass to tcPat when there are no signatures
63 tcPatBndr_NoSigs binder_name pat_ty
64 = -- Need to make a new, monomorphic, Id
65 -- The binder_name is already being used for the polymorphic Id
66 newLocalId (getOccName binder_name) pat_ty loc `thenNF_Tc` \ bndr_id ->
69 loc = getSrcLoc binder_name
73 %************************************************************************
75 \subsection{Typechecking patterns}
77 %************************************************************************
80 tcPat :: (Name -> TcType -> TcM s TcId) -- How to construct a suitable (monomorphic)
81 -- Id for variables found in the pattern
82 -- The TcType is the expected type, see note below
85 -> TcType -- Expected type derived from the context
86 -- In the case of a function with a rank-2 signature,
87 -- this type might be a forall type.
88 -- INVARIANT: if it is, the foralls will always be visible,
89 -- not hidden inside a mutable type variable
92 LIE, -- Required by n+k and literal pats
93 Bag TcTyVar, -- TyVars bound by the pattern
94 -- These are just the existentially-bound ones.
95 -- Any tyvars bound by *type signatures* in the
96 -- patterns are brought into scope before we begin.
97 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
98 -- which it occurs in the pattern
99 -- The two aren't the same because we conjure up a new
100 -- local name for each variable.
101 LIE) -- Dicts or methods [see below] bound by the pattern
102 -- from existential constructor patterns
106 %************************************************************************
108 \subsection{Variables, wildcards, lazy pats, as-pats}
110 %************************************************************************
113 tcPat tc_bndr (VarPatIn name) pat_ty
114 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
115 returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
117 tcPat tc_bndr (LazyPatIn pat) pat_ty
118 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
119 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
121 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
122 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
123 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
124 tcAddErrCtxt (patCtxt pat_in) $
125 returnTc (AsPat bndr_id pat', lie_req,
126 tvs, (name, bndr_id) `consBag` ids, lie_avail)
128 tcPat tc_bndr WildPatIn pat_ty
129 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
131 tcPat tc_bndr (NegPatIn pat) pat_ty
132 = tcPat tc_bndr (negate_lit pat) pat_ty
134 negate_lit (LitPatIn (HsInt i)) = LitPatIn (HsInt (-i))
135 negate_lit (LitPatIn (HsIntPrim i)) = LitPatIn (HsIntPrim (-i))
136 negate_lit (LitPatIn (HsFrac f)) = LitPatIn (HsFrac (-f))
137 negate_lit (LitPatIn (HsFloatPrim f)) = LitPatIn (HsFloatPrim (-f))
138 negate_lit (LitPatIn (HsDoublePrim f)) = LitPatIn (HsDoublePrim (-f))
139 negate_lit _ = panic "TcPat:negate_pat"
141 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
142 = tcPat tc_bndr parend_pat pat_ty
144 tcPat tc_bndr (SigPatIn pat sig) pat_ty
145 = tcHsType sig `thenTc` \ sig_ty ->
147 -- Check that the signature isn't a polymorphic one, which
148 -- we don't permit (at present, anyway)
149 checkTc (isTauTy sig_ty) (polyPatSig sig_ty) `thenTc_`
151 unifyTauTy pat_ty sig_ty `thenTc_`
152 tcPat tc_bndr pat sig_ty
155 %************************************************************************
157 \subsection{Explicit lists and tuples}
159 %************************************************************************
162 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
163 = tcAddErrCtxt (patCtxt pat_in) $
164 unifyListTy pat_ty `thenTc` \ elem_ty ->
165 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
166 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
168 tcPat tc_bndr pat_in@(TuplePatIn pats boxed) pat_ty
169 = tcAddErrCtxt (patCtxt pat_in) $
172 then unifyTupleTy arity pat_ty
173 else unifyUnboxedTupleTy arity pat_ty) `thenTc` \ arg_tys ->
175 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
177 -- possibly do the "make all tuple-pats irrefutable" test:
179 unmangled_result = TuplePat pats' boxed
181 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
182 -- so that we can experiment with lazy tuple-matching.
183 -- This is a pretty odd place to make the switch, but
184 -- it was easy to do.
186 possibly_mangled_result
187 | opt_IrrefutableTuples && boxed = LazyPat unmangled_result
188 | otherwise = unmangled_result
190 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
195 %************************************************************************
197 \subsection{Other constructors}
200 %************************************************************************
203 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
204 = tcConPat tc_bndr pat name arg_pats pat_ty
206 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
207 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
211 %************************************************************************
215 %************************************************************************
218 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
219 = tcAddErrCtxt (patCtxt pat) $
221 -- Check the constructor itself
222 tcConstructor pat name pat_ty `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
224 field_tys = zipEqual "tcPat"
225 (map fieldLabelName (dataConFieldLabels data_con))
230 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
232 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
234 listToBag ex_tvs `unionBags` tvs,
236 lie_avail1 `plusLIE` lie_avail2)
239 tc_fields field_tys []
240 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
242 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
243 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
245 (case [ty | (f,ty) <- field_tys, f == field_label] of
247 -- No matching field; chances are this field label comes from some
248 -- other record type (or maybe none). As well as reporting an
249 -- error we still want to typecheck the pattern, principally to
250 -- make sure that all the variables it binds are put into the
251 -- environment, else the type checker crashes later:
252 -- f (R { foo = (a,b) }) = a+b
253 -- If foo isn't one of R's fields, we don't want to crash when
254 -- typechecking the "a+b".
255 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
256 newTyVarTy boxedTypeKind `thenNF_Tc_`
257 returnTc (error "Bogus selector Id", pat_ty)
259 -- The normal case, when the field comes from the right constructor
261 ASSERT( null extras )
262 tcLookupValue field_label `thenNF_Tc` \ sel_id ->
263 returnTc (sel_id, pat_ty)
264 ) `thenTc` \ (sel_id, pat_ty) ->
266 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
268 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
269 lie_req1 `plusLIE` lie_req2,
270 tvs1 `unionBags` tvs2,
271 ids1 `unionBags` ids2,
272 lie_avail1 `plusLIE` lie_avail2)
275 %************************************************************************
277 \subsection{Non-overloaded literals}
279 %************************************************************************
282 tcPat tc_bndr (LitPatIn lit@(HsChar _)) pat_ty = tcSimpleLitPat lit charTy pat_ty
283 tcPat tc_bndr (LitPatIn lit@(HsIntPrim _)) pat_ty = tcSimpleLitPat lit intPrimTy pat_ty
284 tcPat tc_bndr (LitPatIn lit@(HsCharPrim _)) pat_ty = tcSimpleLitPat lit charPrimTy pat_ty
285 tcPat tc_bndr (LitPatIn lit@(HsStringPrim _)) pat_ty = tcSimpleLitPat lit addrPrimTy pat_ty
286 tcPat tc_bndr (LitPatIn lit@(HsFloatPrim _)) pat_ty = tcSimpleLitPat lit floatPrimTy pat_ty
287 tcPat tc_bndr (LitPatIn lit@(HsDoublePrim _)) pat_ty = tcSimpleLitPat lit doublePrimTy pat_ty
289 tcPat tc_bndr (LitPatIn lit@(HsLitLit s)) pat_ty
290 -- cf tcExpr on LitLits
291 = tcLookupClassByKey cCallableClassKey `thenNF_Tc` \ cCallableClass ->
292 newDicts (LitLitOrigin (_UNPK_ s))
293 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ (dicts, _) ->
294 returnTc (LitPat lit pat_ty, dicts, emptyBag, emptyBag, emptyLIE)
297 %************************************************************************
299 \subsection{Overloaded patterns: int literals and \tr{n+k} patterns}
301 %************************************************************************
304 tcPat tc_bndr pat@(LitPatIn lit@(HsString str)) pat_ty
305 = unifyTauTy pat_ty stringTy `thenTc_`
306 tcLookupValueByKey eqClassOpKey `thenNF_Tc` \ sel_id ->
307 newMethod (PatOrigin pat) sel_id [stringTy] `thenNF_Tc` \ (lie, eq_id) ->
309 comp_op = HsApp (HsVar eq_id) (HsLitOut lit stringTy)
311 returnTc (NPat lit stringTy comp_op, lie, emptyBag, emptyBag, emptyLIE)
314 tcPat tc_bndr pat@(LitPatIn lit@(HsInt i)) pat_ty
315 = tcOverloadedLitPat pat lit (OverloadedIntegral i) pat_ty
317 tcPat tc_bndr pat@(LitPatIn lit@(HsFrac f)) pat_ty
318 = tcOverloadedLitPat pat lit (OverloadedFractional f) pat_ty
321 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsInt i)) pat_ty
322 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
323 tcLookupValueByKey geClassOpKey `thenNF_Tc` \ ge_sel_id ->
324 tcLookupValueByKey minusClassOpKey `thenNF_Tc` \ minus_sel_id ->
326 newOverloadedLit origin
327 (OverloadedIntegral i) pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
329 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ (lie2, ge_id) ->
330 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ (lie3, minus_id) ->
332 returnTc (NPlusKPat bndr_id lit pat_ty
333 (SectionR (HsVar ge_id) over_lit_expr)
334 (SectionR (HsVar minus_id) over_lit_expr),
335 lie1 `plusLIE` lie2 `plusLIE` lie3,
336 emptyBag, unitBag (name, bndr_id), emptyLIE)
338 origin = PatOrigin pat
340 tcPat tc_bndr (NPlusKPatIn pat other) pat_ty
341 = panic "TcPat:NPlusKPat: not an HsInt literal"
344 %************************************************************************
346 \subsection{Lists of patterns}
348 %************************************************************************
353 tcPats :: (Name -> TcType -> TcM s TcId) -- How to deal with variables
354 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
356 LIE, -- Required by n+k and literal pats
358 Bag (Name, TcId), -- Ids bound by the pattern
359 LIE) -- Dicts bound by the pattern
361 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
363 tcPats tc_bndr (ty:tys) (pat:pats)
364 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
365 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
367 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
368 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
369 lie_avail1 `plusLIE` lie_avail2)
372 ------------------------------------------------------
374 tcSimpleLitPat lit lit_ty pat_ty
375 = unifyTauTy pat_ty lit_ty `thenTc_`
376 returnTc (LitPat lit lit_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
379 tcOverloadedLitPat pat lit over_lit pat_ty
380 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
381 tcLookupValueByKey eqClassOpKey `thenNF_Tc` \ eq_sel_id ->
382 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ (lie2, eq_id) ->
384 returnTc (NPat lit pat_ty (HsApp (HsVar eq_id)
387 emptyBag, emptyBag, emptyLIE)
389 origin = PatOrigin pat
392 ------------------------------------------------------
394 tcConstructor pat con_name pat_ty
395 = -- Check that it's a constructor
396 tcLookupValue con_name `thenNF_Tc` \ con_id ->
397 case isDataConId_maybe con_id of {
398 Nothing -> failWithTc (badCon con_id);
403 (tvs, theta, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
404 -- Ignore the theta; overloaded constructors only
405 -- behave differently when called, not when used for
408 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
410 ex_theta' = substClasses tenv ex_theta
411 arg_tys' = map (substTy tenv) arg_tys
413 n_ex_tvs = length ex_tvs
414 ex_tvs' = take n_ex_tvs all_tvs'
415 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
417 newClassDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ (lie_avail, dicts) ->
419 -- Check overall type matches
420 unifyTauTy pat_ty result_ty `thenTc_`
422 returnTc (data_con, ex_tvs', dicts, lie_avail, arg_tys')
426 ------------------------------------------------------
428 tcConPat tc_bndr pat con_name arg_pats pat_ty
429 = tcAddErrCtxt (patCtxt pat) $
431 -- Check the constructor itself
432 tcConstructor pat con_name pat_ty `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
434 -- Check correct arity
436 con_arity = dataConSourceArity data_con
437 no_of_args = length arg_pats
439 checkTc (con_arity == no_of_args)
440 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
443 tcPats tc_bndr arg_pats arg_tys' `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
445 returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
447 listToBag ex_tvs' `unionBags` tvs,
449 lie_avail1 `plusLIE` lie_avail2)
453 %************************************************************************
455 \subsection{Errors and contexts}
457 %************************************************************************
460 patCtxt pat = hang (ptext SLIT("In the pattern:"))
463 recordLabel field_label
464 = hang (hcat [ptext SLIT("When matching record field"), ppr field_label])
465 4 (hcat [ptext SLIT("with its immediately enclosing constructor")])
467 recordRhs field_label pat
468 = hang (ptext SLIT("In the record field pattern"))
469 4 (sep [ppr field_label, char '=', ppr pat])
471 badFieldCon :: Name -> Name -> SDoc
472 badFieldCon con field
473 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
474 ptext SLIT("does not have field"), quotes (ppr field)]
476 polyPatSig :: TcType -> SDoc
478 = hang (ptext SLIT("Polymorphic type signature in pattern"))