2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcPat]{Typechecking patterns}
7 module TcPat ( tcPat, tcPatBndr_NoSigs, simpleHsLitTy, badFieldCon, polyPatSig ) where
9 #include "HsVersions.h"
11 import HsSyn ( InPat(..), OutPat(..), HsLit(..), HsOverLit(..), HsExpr(..) )
12 import RnHsSyn ( RenamedPat )
13 import TcHsSyn ( TcPat, TcId )
16 import Inst ( InstOrigin(..),
17 emptyLIE, plusLIE, LIE,
18 newMethod, newOverloadedLit, newDicts, newClassDicts
20 import Name ( Name, getOccName, getSrcLoc )
21 import FieldLabel ( fieldLabelName )
22 import TcEnv ( tcLookupClass, tcLookupDataCon, tcLookupGlobalId, newLocalId )
23 import TcType ( TcType, TcTyVar, tcInstTyVars, newTyVarTy )
24 import TcMonoType ( tcHsSigType )
25 import TcUnify ( unifyTauTy, unifyListTy, unifyTupleTy )
27 import CmdLineOpts ( opt_IrrefutableTuples )
28 import DataCon ( dataConSig, dataConFieldLabels,
31 import Id ( isDataConWrapId_maybe )
32 import Type ( isTauTy, mkTyConApp, mkClassPred, boxedTypeKind )
33 import Subst ( substTy, substClasses )
34 import TysPrim ( charPrimTy, intPrimTy, floatPrimTy,
35 doublePrimTy, addrPrimTy
37 import TysWiredIn ( charTy, stringTy, intTy, integerTy )
38 import PrelNames ( eqStringName, eqName, geName, cCallableClassName )
39 import BasicTypes ( isBoxed )
45 %************************************************************************
47 \subsection{Variable patterns}
49 %************************************************************************
52 -- This is the right function to pass to tcPat when there are no signatures
53 tcPatBndr_NoSigs binder_name pat_ty
54 = -- Need to make a new, monomorphic, Id
55 -- The binder_name is already being used for the polymorphic Id
56 newLocalId (getOccName binder_name) pat_ty loc `thenNF_Tc` \ bndr_id ->
59 loc = getSrcLoc binder_name
63 %************************************************************************
65 \subsection{Typechecking patterns}
67 %************************************************************************
70 tcPat :: (Name -> TcType -> TcM TcId) -- How to construct a suitable (monomorphic)
71 -- Id for variables found in the pattern
72 -- The TcType is the expected type, see note below
75 -> TcType -- Expected type derived from the context
76 -- In the case of a function with a rank-2 signature,
77 -- this type might be a forall type.
78 -- INVARIANT: if it is, the foralls will always be visible,
79 -- not hidden inside a mutable type variable
82 LIE, -- Required by n+k and literal pats
83 Bag TcTyVar, -- TyVars bound by the pattern
84 -- These are just the existentially-bound ones.
85 -- Any tyvars bound by *type signatures* in the
86 -- patterns are brought into scope before we begin.
87 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
88 -- which it occurs in the pattern
89 -- The two aren't the same because we conjure up a new
90 -- local name for each variable.
91 LIE) -- Dicts or methods [see below] bound by the pattern
92 -- from existential constructor patterns
96 %************************************************************************
98 \subsection{Variables, wildcards, lazy pats, as-pats}
100 %************************************************************************
103 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
104 = failWithTc (badTypePat pat)
106 tcPat tc_bndr (VarPatIn name) pat_ty
107 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
108 returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
110 tcPat tc_bndr (LazyPatIn pat) pat_ty
111 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
112 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
114 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
115 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
116 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
117 tcAddErrCtxt (patCtxt pat_in) $
118 returnTc (AsPat bndr_id pat', lie_req,
119 tvs, (name, bndr_id) `consBag` ids, lie_avail)
121 tcPat tc_bndr WildPatIn pat_ty
122 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
124 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
125 = tcPat tc_bndr parend_pat pat_ty
127 tcPat tc_bndr (SigPatIn pat sig) pat_ty
128 = tcHsSigType sig `thenTc` \ sig_ty ->
130 -- Check that the signature isn't a polymorphic one, which
131 -- we don't permit (at present, anyway)
132 checkTc (isTauTy sig_ty) (polyPatSig sig_ty) `thenTc_`
134 unifyTauTy pat_ty sig_ty `thenTc_`
135 tcPat tc_bndr pat sig_ty
138 %************************************************************************
140 \subsection{Explicit lists and tuples}
142 %************************************************************************
145 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
146 = tcAddErrCtxt (patCtxt pat_in) $
147 unifyListTy pat_ty `thenTc` \ elem_ty ->
148 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
149 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
151 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
152 = tcAddErrCtxt (patCtxt pat_in) $
154 unifyTupleTy boxity arity pat_ty `thenTc` \ arg_tys ->
155 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
157 -- possibly do the "make all tuple-pats irrefutable" test:
159 unmangled_result = TuplePat pats' boxity
161 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
162 -- so that we can experiment with lazy tuple-matching.
163 -- This is a pretty odd place to make the switch, but
164 -- it was easy to do.
166 possibly_mangled_result
167 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
168 | otherwise = unmangled_result
170 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
175 %************************************************************************
177 \subsection{Other constructors}
180 %************************************************************************
183 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
184 = tcConPat tc_bndr pat name arg_pats pat_ty
186 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
187 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
191 %************************************************************************
195 %************************************************************************
198 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
199 = tcAddErrCtxt (patCtxt pat) $
201 -- Check the constructor itself
202 tcConstructor pat name pat_ty `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
204 -- Don't use zipEqual! If the constructor isn't really a record, then
205 -- dataConFieldLabels will be empty (and each field in the pattern
206 -- will generate an error below).
207 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
212 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
214 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
216 listToBag ex_tvs `unionBags` tvs,
218 lie_avail1 `plusLIE` lie_avail2)
221 tc_fields field_tys []
222 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
224 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
225 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
227 (case [ty | (f,ty) <- field_tys, f == field_label] of
229 -- No matching field; chances are this field label comes from some
230 -- other record type (or maybe none). As well as reporting an
231 -- error we still want to typecheck the pattern, principally to
232 -- make sure that all the variables it binds are put into the
233 -- environment, else the type checker crashes later:
234 -- f (R { foo = (a,b) }) = a+b
235 -- If foo isn't one of R's fields, we don't want to crash when
236 -- typechecking the "a+b".
237 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
238 newTyVarTy boxedTypeKind `thenNF_Tc_`
239 returnTc (error "Bogus selector Id", pat_ty)
241 -- The normal case, when the field comes from the right constructor
243 ASSERT( null extras )
244 tcLookupGlobalId field_label `thenNF_Tc` \ sel_id ->
245 returnTc (sel_id, pat_ty)
246 ) `thenTc` \ (sel_id, pat_ty) ->
248 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
250 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
251 lie_req1 `plusLIE` lie_req2,
252 tvs1 `unionBags` tvs2,
253 ids1 `unionBags` ids2,
254 lie_avail1 `plusLIE` lie_avail2)
257 %************************************************************************
259 \subsection{Literals}
261 %************************************************************************
264 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty
265 -- cf tcExpr on LitLits
266 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
267 newDicts (LitLitOrigin (_UNPK_ s))
268 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ (dicts, _) ->
269 returnTc (LitPat (HsLitLit s pat_ty) pat_ty, dicts, emptyBag, emptyBag, emptyLIE)
271 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
272 = unifyTauTy pat_ty stringTy `thenTc_`
273 tcLookupGlobalId eqStringName `thenNF_Tc` \ eq_id ->
274 returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit),
275 emptyLIE, emptyBag, emptyBag, emptyLIE)
277 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
278 = unifyTauTy pat_ty (simpleHsLitTy simple_lit) `thenTc_`
279 returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
281 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
282 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
283 tcLookupGlobalId eqName `thenNF_Tc` \ eq_sel_id ->
284 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ (lie2, eq_id) ->
286 returnTc (NPat lit' pat_ty (HsApp (HsVar eq_id) over_lit_expr),
288 emptyBag, emptyBag, emptyLIE)
290 origin = PatOrigin pat
291 lit' = case over_lit of
292 HsIntegral i _ -> HsInteger i
293 HsFractional f _ -> HsRat f pat_ty
296 %************************************************************************
298 \subsection{n+k patterns}
300 %************************************************************************
303 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus) pat_ty
304 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
305 tcLookupGlobalId minus `thenNF_Tc` \ minus_sel_id ->
306 tcLookupGlobalId geName `thenNF_Tc` \ ge_sel_id ->
307 newOverloadedLit origin lit 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 i 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
320 %************************************************************************
322 \subsection{Lists of patterns}
324 %************************************************************************
329 tcPats :: (Name -> TcType -> TcM TcId) -- How to deal with variables
330 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
332 LIE, -- Required by n+k and literal pats
334 Bag (Name, TcId), -- Ids bound by the pattern
335 LIE) -- Dicts bound by the pattern
337 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
339 tcPats tc_bndr (ty:tys) (pat:pats)
340 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
341 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
343 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
344 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
345 lie_avail1 `plusLIE` lie_avail2)
348 ------------------------------------------------------
350 simpleHsLitTy :: HsLit -> TcType
351 simpleHsLitTy (HsCharPrim c) = charPrimTy
352 simpleHsLitTy (HsStringPrim s) = addrPrimTy
353 simpleHsLitTy (HsInt i) = intTy
354 simpleHsLitTy (HsInteger i) = integerTy
355 simpleHsLitTy (HsIntPrim i) = intPrimTy
356 simpleHsLitTy (HsFloatPrim f) = floatPrimTy
357 simpleHsLitTy (HsDoublePrim d) = doublePrimTy
358 simpleHsLitTy (HsChar c) = charTy
359 simpleHsLitTy (HsString str) = stringTy
363 ------------------------------------------------------
365 tcConstructor pat con_name pat_ty
366 = -- Check that it's a constructor
367 tcLookupDataCon con_name `thenNF_Tc` \ data_con ->
371 (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
372 -- Ignore the theta; overloaded constructors only
373 -- behave differently when called, not when used for
376 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
378 ex_theta' = substClasses tenv ex_theta
379 arg_tys' = map (substTy tenv) arg_tys
381 n_ex_tvs = length ex_tvs
382 ex_tvs' = take n_ex_tvs all_tvs'
383 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
385 newClassDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ (lie_avail, dicts) ->
387 -- Check overall type matches
388 unifyTauTy pat_ty result_ty `thenTc_`
390 returnTc (data_con, ex_tvs', dicts, lie_avail, arg_tys')
393 ------------------------------------------------------
395 tcConPat tc_bndr pat con_name arg_pats pat_ty
396 = tcAddErrCtxt (patCtxt pat) $
398 -- Check the constructor itself
399 tcConstructor pat con_name pat_ty `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
401 -- Check correct arity
403 con_arity = dataConSourceArity data_con
404 no_of_args = length arg_pats
406 checkTc (con_arity == no_of_args)
407 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
410 tcPats tc_bndr arg_pats arg_tys' `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
412 returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
414 listToBag ex_tvs' `unionBags` tvs,
416 lie_avail1 `plusLIE` lie_avail2)
420 %************************************************************************
422 \subsection{Errors and contexts}
424 %************************************************************************
427 patCtxt pat = hang (ptext SLIT("In the pattern:"))
430 badFieldCon :: Name -> Name -> SDoc
431 badFieldCon con field
432 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
433 ptext SLIT("does not have field"), quotes (ppr field)]
435 polyPatSig :: TcType -> SDoc
437 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
440 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat