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, tcLookupGlobalId, newLocalId, badCon )
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 ( eqClassOpKey, geClassOpKey,
39 cCallableClassKey, eqStringIdKey,
41 import BasicTypes ( isBoxed )
47 %************************************************************************
49 \subsection{Variable patterns}
51 %************************************************************************
54 -- This is the right function to pass to tcPat when there are no signatures
55 tcPatBndr_NoSigs binder_name pat_ty
56 = -- Need to make a new, monomorphic, Id
57 -- The binder_name is already being used for the polymorphic Id
58 newLocalId (getOccName binder_name) pat_ty loc `thenNF_Tc` \ bndr_id ->
61 loc = getSrcLoc binder_name
65 %************************************************************************
67 \subsection{Typechecking patterns}
69 %************************************************************************
72 tcPat :: (Name -> TcType -> TcM TcId) -- How to construct a suitable (monomorphic)
73 -- Id for variables found in the pattern
74 -- The TcType is the expected type, see note below
77 -> TcType -- Expected type derived from the context
78 -- In the case of a function with a rank-2 signature,
79 -- this type might be a forall type.
80 -- INVARIANT: if it is, the foralls will always be visible,
81 -- not hidden inside a mutable type variable
84 LIE, -- Required by n+k and literal pats
85 Bag TcTyVar, -- TyVars bound by the pattern
86 -- These are just the existentially-bound ones.
87 -- Any tyvars bound by *type signatures* in the
88 -- patterns are brought into scope before we begin.
89 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
90 -- which it occurs in the pattern
91 -- The two aren't the same because we conjure up a new
92 -- local name for each variable.
93 LIE) -- Dicts or methods [see below] bound by the pattern
94 -- from existential constructor patterns
98 %************************************************************************
100 \subsection{Variables, wildcards, lazy pats, as-pats}
102 %************************************************************************
105 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
106 = failWithTc (badTypePat pat)
108 tcPat tc_bndr (VarPatIn name) pat_ty
109 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
110 returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
112 tcPat tc_bndr (LazyPatIn pat) pat_ty
113 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
114 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
116 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
117 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
118 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
119 tcAddErrCtxt (patCtxt pat_in) $
120 returnTc (AsPat bndr_id pat', lie_req,
121 tvs, (name, bndr_id) `consBag` ids, lie_avail)
123 tcPat tc_bndr WildPatIn pat_ty
124 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
126 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
127 = tcPat tc_bndr parend_pat pat_ty
129 tcPat tc_bndr (SigPatIn pat sig) pat_ty
130 = tcHsSigType sig `thenTc` \ sig_ty ->
132 -- Check that the signature isn't a polymorphic one, which
133 -- we don't permit (at present, anyway)
134 checkTc (isTauTy sig_ty) (polyPatSig sig_ty) `thenTc_`
136 unifyTauTy pat_ty sig_ty `thenTc_`
137 tcPat tc_bndr pat sig_ty
140 %************************************************************************
142 \subsection{Explicit lists and tuples}
144 %************************************************************************
147 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
148 = tcAddErrCtxt (patCtxt pat_in) $
149 unifyListTy pat_ty `thenTc` \ elem_ty ->
150 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
151 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
153 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
154 = tcAddErrCtxt (patCtxt pat_in) $
156 unifyTupleTy boxity arity pat_ty `thenTc` \ arg_tys ->
157 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
159 -- possibly do the "make all tuple-pats irrefutable" test:
161 unmangled_result = TuplePat pats' boxity
163 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
164 -- so that we can experiment with lazy tuple-matching.
165 -- This is a pretty odd place to make the switch, but
166 -- it was easy to do.
168 possibly_mangled_result
169 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
170 | otherwise = unmangled_result
172 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
177 %************************************************************************
179 \subsection{Other constructors}
182 %************************************************************************
185 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
186 = tcConPat tc_bndr pat name arg_pats pat_ty
188 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
189 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
193 %************************************************************************
197 %************************************************************************
200 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
201 = tcAddErrCtxt (patCtxt pat) $
203 -- Check the constructor itself
204 tcConstructor pat name pat_ty `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
206 -- Don't use zipEqual! If the constructor isn't really a record, then
207 -- dataConFieldLabels will be empty (and each field in the pattern
208 -- will generate an error below).
209 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
214 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
216 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
218 listToBag ex_tvs `unionBags` tvs,
220 lie_avail1 `plusLIE` lie_avail2)
223 tc_fields field_tys []
224 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
226 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
227 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
229 (case [ty | (f,ty) <- field_tys, f == field_label] of
231 -- No matching field; chances are this field label comes from some
232 -- other record type (or maybe none). As well as reporting an
233 -- error we still want to typecheck the pattern, principally to
234 -- make sure that all the variables it binds are put into the
235 -- environment, else the type checker crashes later:
236 -- f (R { foo = (a,b) }) = a+b
237 -- If foo isn't one of R's fields, we don't want to crash when
238 -- typechecking the "a+b".
239 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
240 newTyVarTy boxedTypeKind `thenNF_Tc_`
241 returnTc (error "Bogus selector Id", pat_ty)
243 -- The normal case, when the field comes from the right constructor
245 ASSERT( null extras )
246 tcLookupGlobalId field_label `thenNF_Tc` \ sel_id ->
247 returnTc (sel_id, pat_ty)
248 ) `thenTc` \ (sel_id, pat_ty) ->
250 tcPat tc_bndr rhs_pat pat_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)
259 %************************************************************************
261 \subsection{Literals}
263 %************************************************************************
266 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty
267 -- cf tcExpr on LitLits
268 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
269 newDicts (LitLitOrigin (_UNPK_ s))
270 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ (dicts, _) ->
271 returnTc (LitPat (HsLitLit s pat_ty) pat_ty, dicts, emptyBag, emptyBag, emptyLIE)
273 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
274 = unifyTauTy pat_ty stringTy `thenTc_`
275 tcLookupGlobalId eqStringIdName `thenNF_Tc` \ eq_id ->
276 returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit),
277 emptyLIE, emptyBag, emptyBag, emptyLIE)
279 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
280 = unifyTauTy pat_ty (simpleHsLitTy simple_lit) `thenTc_`
281 returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
283 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
284 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
285 tcLookupGlobalId eqClassOpName `thenNF_Tc` \ eq_sel_id ->
286 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ (lie2, eq_id) ->
288 returnTc (NPat lit' pat_ty (HsApp (HsVar eq_id) over_lit_expr),
290 emptyBag, emptyBag, emptyLIE)
292 origin = PatOrigin pat
293 lit' = case over_lit of
294 HsIntegral i _ -> HsInteger i
295 HsFractional f _ -> HsRat f pat_ty
298 %************************************************************************
300 \subsection{n+k patterns}
302 %************************************************************************
305 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus) pat_ty
306 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
307 tcLookupGlobalId minus `thenNF_Tc` \ minus_sel_id ->
308 tcLookupGlobalId geClassOpName `thenNF_Tc` \ ge_sel_id ->
309 newOverloadedLit origin lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
310 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ (lie2, ge_id) ->
311 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ (lie3, minus_id) ->
313 returnTc (NPlusKPat bndr_id i pat_ty
314 (SectionR (HsVar ge_id) over_lit_expr)
315 (SectionR (HsVar minus_id) over_lit_expr),
316 lie1 `plusLIE` lie2 `plusLIE` lie3,
317 emptyBag, unitBag (name, bndr_id), emptyLIE)
319 origin = PatOrigin pat
322 %************************************************************************
324 \subsection{Lists of patterns}
326 %************************************************************************
331 tcPats :: (Name -> TcType -> TcM TcId) -- How to deal with variables
332 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
334 LIE, -- Required by n+k and literal pats
336 Bag (Name, TcId), -- Ids bound by the pattern
337 LIE) -- Dicts bound by the pattern
339 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
341 tcPats tc_bndr (ty:tys) (pat:pats)
342 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
343 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
345 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
346 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
347 lie_avail1 `plusLIE` lie_avail2)
350 ------------------------------------------------------
352 simpleHsLitTy :: HsLit -> TcType
353 simpleHsLitTy (HsCharPrim c) = charPrimTy
354 simpleHsLitTy (HsStringPrim s) = addrPrimTy
355 simpleHsLitTy (HsInt i) = intTy
356 simpleHsLitTy (HsInteger i) = integerTy
357 simpleHsLitTy (HsIntPrim i) = intPrimTy
358 simpleHsLitTy (HsFloatPrim f) = floatPrimTy
359 simpleHsLitTy (HsDoublePrim d) = doublePrimTy
360 simpleHsLitTy (HsChar c) = charTy
361 simpleHsLitTy (HsString str) = stringTy
365 ------------------------------------------------------
367 tcConstructor pat con_name pat_ty
368 = -- Check that it's a constructor
369 tcLookupDataCon `thenNF_Tc` \ data_con ->
373 (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
374 -- Ignore the theta; overloaded constructors only
375 -- behave differently when called, not when used for
378 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
380 ex_theta' = substClasses tenv ex_theta
381 arg_tys' = map (substTy tenv) arg_tys
383 n_ex_tvs = length ex_tvs
384 ex_tvs' = take n_ex_tvs all_tvs'
385 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
387 newClassDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ (lie_avail, dicts) ->
389 -- Check overall type matches
390 unifyTauTy pat_ty result_ty `thenTc_`
392 returnTc (data_con, ex_tvs', dicts, lie_avail, arg_tys')
396 ------------------------------------------------------
398 tcConPat tc_bndr pat con_name arg_pats pat_ty
399 = tcAddErrCtxt (patCtxt pat) $
401 -- Check the constructor itself
402 tcConstructor pat con_name pat_ty `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
404 -- Check correct arity
406 con_arity = dataConSourceArity data_con
407 no_of_args = length arg_pats
409 checkTc (con_arity == no_of_args)
410 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
413 tcPats tc_bndr arg_pats arg_tys' `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
415 returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
417 listToBag ex_tvs' `unionBags` tvs,
419 lie_avail1 `plusLIE` lie_avail2)
423 %************************************************************************
425 \subsection{Errors and contexts}
427 %************************************************************************
430 patCtxt pat = hang (ptext SLIT("In the pattern:"))
433 badFieldCon :: Name -> Name -> SDoc
434 badFieldCon con field
435 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
436 ptext SLIT("does not have field"), quotes (ppr field)]
438 polyPatSig :: TcType -> SDoc
440 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
443 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat