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 ( tcLookupValue, tcLookupClassByKey,
23 tcLookupValueByKey, newLocalId, badCon
25 import TcType ( TcType, TcTyVar, tcInstTyVars, newTyVarTy )
26 import TcMonoType ( tcHsSigType )
27 import TcUnify ( unifyTauTy, unifyListTy, unifyTupleTy )
29 import CmdLineOpts ( opt_IrrefutableTuples )
30 import DataCon ( dataConSig, dataConFieldLabels,
33 import Id ( isDataConWrapId_maybe )
34 import Type ( isTauTy, mkTyConApp, mkClassPred, boxedTypeKind )
35 import Subst ( substTy, substClasses )
36 import TysPrim ( charPrimTy, intPrimTy, floatPrimTy,
37 doublePrimTy, addrPrimTy
39 import TysWiredIn ( charTy, stringTy, intTy, integerTy )
40 import PrelNames ( eqClassOpKey, geClassOpKey,
41 cCallableClassKey, eqStringIdKey,
43 import BasicTypes ( isBoxed )
49 %************************************************************************
51 \subsection{Variable patterns}
53 %************************************************************************
56 -- This is the right function to pass to tcPat when there are no signatures
57 tcPatBndr_NoSigs binder_name pat_ty
58 = -- Need to make a new, monomorphic, Id
59 -- The binder_name is already being used for the polymorphic Id
60 newLocalId (getOccName binder_name) pat_ty loc `thenNF_Tc` \ bndr_id ->
63 loc = getSrcLoc binder_name
67 %************************************************************************
69 \subsection{Typechecking patterns}
71 %************************************************************************
74 tcPat :: (Name -> TcType -> TcM s TcId) -- How to construct a suitable (monomorphic)
75 -- Id for variables found in the pattern
76 -- The TcType is the expected type, see note below
79 -> TcType -- Expected type derived from the context
80 -- In the case of a function with a rank-2 signature,
81 -- this type might be a forall type.
82 -- INVARIANT: if it is, the foralls will always be visible,
83 -- not hidden inside a mutable type variable
86 LIE, -- Required by n+k and literal pats
87 Bag TcTyVar, -- TyVars bound by the pattern
88 -- These are just the existentially-bound ones.
89 -- Any tyvars bound by *type signatures* in the
90 -- patterns are brought into scope before we begin.
91 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
92 -- which it occurs in the pattern
93 -- The two aren't the same because we conjure up a new
94 -- local name for each variable.
95 LIE) -- Dicts or methods [see below] bound by the pattern
96 -- from existential constructor patterns
100 %************************************************************************
102 \subsection{Variables, wildcards, lazy pats, as-pats}
104 %************************************************************************
107 tcPat tc_bndr (VarPatIn name) pat_ty
108 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
109 returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
111 tcPat tc_bndr (LazyPatIn pat) pat_ty
112 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
113 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
115 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
116 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
117 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
118 tcAddErrCtxt (patCtxt pat_in) $
119 returnTc (AsPat bndr_id pat', lie_req,
120 tvs, (name, bndr_id) `consBag` ids, lie_avail)
122 tcPat tc_bndr WildPatIn pat_ty
123 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
125 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
126 = tcPat tc_bndr parend_pat pat_ty
128 tcPat tc_bndr (SigPatIn pat sig) pat_ty
129 = tcHsSigType sig `thenTc` \ sig_ty ->
131 -- Check that the signature isn't a polymorphic one, which
132 -- we don't permit (at present, anyway)
133 checkTc (isTauTy sig_ty) (polyPatSig sig_ty) `thenTc_`
135 unifyTauTy pat_ty sig_ty `thenTc_`
136 tcPat tc_bndr pat sig_ty
139 %************************************************************************
141 \subsection{Explicit lists and tuples}
143 %************************************************************************
146 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
147 = tcAddErrCtxt (patCtxt pat_in) $
148 unifyListTy pat_ty `thenTc` \ elem_ty ->
149 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
150 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
152 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
153 = tcAddErrCtxt (patCtxt pat_in) $
155 unifyTupleTy boxity arity pat_ty `thenTc` \ arg_tys ->
156 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
158 -- possibly do the "make all tuple-pats irrefutable" test:
160 unmangled_result = TuplePat pats' boxity
162 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
163 -- so that we can experiment with lazy tuple-matching.
164 -- This is a pretty odd place to make the switch, but
165 -- it was easy to do.
167 possibly_mangled_result
168 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
169 | otherwise = unmangled_result
171 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
176 %************************************************************************
178 \subsection{Other constructors}
181 %************************************************************************
184 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
185 = tcConPat tc_bndr pat name arg_pats pat_ty
187 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
188 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
192 %************************************************************************
196 %************************************************************************
199 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
200 = tcAddErrCtxt (patCtxt pat) $
202 -- Check the constructor itself
203 tcConstructor pat name pat_ty `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
205 -- Don't use zipEqual! If the constructor isn't really a record, then
206 -- dataConFieldLabels will be empty (and each field in the pattern
207 -- will generate an error below).
208 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
213 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
215 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
217 listToBag ex_tvs `unionBags` tvs,
219 lie_avail1 `plusLIE` lie_avail2)
222 tc_fields field_tys []
223 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
225 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
226 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
228 (case [ty | (f,ty) <- field_tys, f == field_label] of
230 -- No matching field; chances are this field label comes from some
231 -- other record type (or maybe none). As well as reporting an
232 -- error we still want to typecheck the pattern, principally to
233 -- make sure that all the variables it binds are put into the
234 -- environment, else the type checker crashes later:
235 -- f (R { foo = (a,b) }) = a+b
236 -- If foo isn't one of R's fields, we don't want to crash when
237 -- typechecking the "a+b".
238 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
239 newTyVarTy boxedTypeKind `thenNF_Tc_`
240 returnTc (error "Bogus selector Id", pat_ty)
242 -- The normal case, when the field comes from the right constructor
244 ASSERT( null extras )
245 tcLookupValue field_label `thenNF_Tc` \ sel_id ->
246 returnTc (sel_id, pat_ty)
247 ) `thenTc` \ (sel_id, pat_ty) ->
249 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
251 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
252 lie_req1 `plusLIE` lie_req2,
253 tvs1 `unionBags` tvs2,
254 ids1 `unionBags` ids2,
255 lie_avail1 `plusLIE` lie_avail2)
258 %************************************************************************
260 \subsection{Literals}
262 %************************************************************************
265 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty
266 -- cf tcExpr on LitLits
267 = tcLookupClassByKey cCallableClassKey `thenNF_Tc` \ cCallableClass ->
268 newDicts (LitLitOrigin (_UNPK_ s))
269 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ (dicts, _) ->
270 returnTc (LitPat (HsLitLit s pat_ty) pat_ty, dicts, emptyBag, emptyBag, emptyLIE)
272 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
273 = unifyTauTy pat_ty stringTy `thenTc_`
274 tcLookupValueByKey eqStringIdKey `thenNF_Tc` \ eq_id ->
275 returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit),
276 emptyLIE, emptyBag, emptyBag, emptyLIE)
278 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
279 = unifyTauTy pat_ty (simpleHsLitTy simple_lit) `thenTc_`
280 returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
282 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
283 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
284 tcLookupValueByKey eqClassOpKey `thenNF_Tc` \ eq_sel_id ->
285 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ (lie2, eq_id) ->
287 returnTc (NPat lit' pat_ty (HsApp (HsVar eq_id) over_lit_expr),
289 emptyBag, emptyBag, emptyLIE)
291 origin = PatOrigin pat
292 lit' = case over_lit of
293 HsIntegral i _ -> HsInteger i
294 HsFractional f _ -> HsRat f pat_ty
297 %************************************************************************
299 \subsection{n+k patterns}
301 %************************************************************************
304 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus) pat_ty
305 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
306 tcLookupValue minus `thenNF_Tc` \ minus_sel_id ->
307 tcLookupValueByKey geClassOpKey `thenNF_Tc` \ ge_sel_id ->
308 newOverloadedLit origin lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
309 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ (lie2, ge_id) ->
310 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ (lie3, minus_id) ->
312 returnTc (NPlusKPat bndr_id i pat_ty
313 (SectionR (HsVar ge_id) over_lit_expr)
314 (SectionR (HsVar minus_id) over_lit_expr),
315 lie1 `plusLIE` lie2 `plusLIE` lie3,
316 emptyBag, unitBag (name, bndr_id), emptyLIE)
318 origin = PatOrigin pat
321 %************************************************************************
323 \subsection{Lists of patterns}
325 %************************************************************************
330 tcPats :: (Name -> TcType -> TcM s TcId) -- How to deal with variables
331 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
333 LIE, -- Required by n+k and literal pats
335 Bag (Name, TcId), -- Ids bound by the pattern
336 LIE) -- Dicts bound by the pattern
338 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
340 tcPats tc_bndr (ty:tys) (pat:pats)
341 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
342 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
344 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
345 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
346 lie_avail1 `plusLIE` lie_avail2)
349 ------------------------------------------------------
351 simpleHsLitTy :: HsLit -> TcType
352 simpleHsLitTy (HsCharPrim c) = charPrimTy
353 simpleHsLitTy (HsStringPrim s) = addrPrimTy
354 simpleHsLitTy (HsInt i) = intTy
355 simpleHsLitTy (HsInteger i) = integerTy
356 simpleHsLitTy (HsIntPrim i) = intPrimTy
357 simpleHsLitTy (HsFloatPrim f) = floatPrimTy
358 simpleHsLitTy (HsDoublePrim d) = doublePrimTy
359 simpleHsLitTy (HsChar c) = charTy
360 simpleHsLitTy (HsString str) = stringTy
364 ------------------------------------------------------
366 tcConstructor pat con_name pat_ty
367 = -- Check that it's a constructor
368 tcLookupValue con_name `thenNF_Tc` \ con_id ->
369 case isDataConWrapId_maybe con_id of {
370 Nothing -> failWithTc (badCon con_id);
375 (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
376 -- Ignore the theta; overloaded constructors only
377 -- behave differently when called, not when used for
380 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
382 ex_theta' = substClasses tenv ex_theta
383 arg_tys' = map (substTy tenv) arg_tys
385 n_ex_tvs = length ex_tvs
386 ex_tvs' = take n_ex_tvs all_tvs'
387 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
389 newClassDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ (lie_avail, dicts) ->
391 -- Check overall type matches
392 unifyTauTy pat_ty result_ty `thenTc_`
394 returnTc (data_con, ex_tvs', dicts, lie_avail, arg_tys')
398 ------------------------------------------------------
400 tcConPat tc_bndr pat con_name arg_pats pat_ty
401 = tcAddErrCtxt (patCtxt pat) $
403 -- Check the constructor itself
404 tcConstructor pat con_name pat_ty `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
406 -- Check correct arity
408 con_arity = dataConSourceArity data_con
409 no_of_args = length arg_pats
411 checkTc (con_arity == no_of_args)
412 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
415 tcPats tc_bndr arg_pats arg_tys' `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
417 returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
419 listToBag ex_tvs' `unionBags` tvs,
421 lie_avail1 `plusLIE` lie_avail2)
425 %************************************************************************
427 \subsection{Errors and contexts}
429 %************************************************************************
432 patCtxt pat = hang (ptext SLIT("In the pattern:"))
435 badFieldCon :: Name -> Name -> SDoc
436 badFieldCon con field
437 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
438 ptext SLIT("does not have field"), quotes (ppr field)]
440 polyPatSig :: TcType -> SDoc
442 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))