2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcPat]{Typechecking patterns}
7 module TcPat ( tcPat, tcMonoPatBndr, 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, mkLIE, unitLIE, instToId,
18 newMethod, newOverloadedLit, newDicts
20 import Id ( mkLocalId )
22 import FieldLabel ( fieldLabelName )
23 import TcEnv ( tcLookupClass, tcLookupDataCon, tcLookupGlobalId, tcLookupSyntaxId )
24 import TcMType ( tcInstTyVars, newTyVarTy, unifyTauTy, unifyListTy, unifyTupleTy )
25 import TcType ( isTauTy, mkTyConApp, mkClassPred, liftedTypeKind )
26 import TcMonoType ( tcHsSigType )
28 import CmdLineOpts ( opt_IrrefutableTuples )
29 import DataCon ( dataConSig, dataConFieldLabels,
32 import Subst ( substTy, substTheta )
33 import TysPrim ( charPrimTy, intPrimTy, floatPrimTy,
34 doublePrimTy, addrPrimTy
36 import TysWiredIn ( charTy, stringTy, intTy, integerTy )
37 import PrelNames ( minusName, eqStringName, eqName, geName, cCallableClassName )
38 import BasicTypes ( isBoxed )
44 %************************************************************************
46 \subsection{Variable patterns}
48 %************************************************************************
51 -- This is the right function to pass to tcPat when
52 -- we're looking at a lambda-bound pattern,
53 -- so there's no polymorphic guy to worry about
54 tcMonoPatBndr binder_name pat_ty = returnTc (mkLocalId binder_name pat_ty)
58 %************************************************************************
60 \subsection{Typechecking patterns}
62 %************************************************************************
65 tcPat :: (Name -> TcType -> TcM TcId) -- How to construct a suitable (monomorphic)
66 -- Id for variables found in the pattern
67 -- The TcType is the expected type, see note below
70 -> TcType -- Expected type derived from the context
71 -- In the case of a function with a rank-2 signature,
72 -- this type might be a forall type.
73 -- INVARIANT: if it is, the foralls will always be visible,
74 -- not hidden inside a mutable type variable
77 LIE, -- Required by n+k and literal pats
78 Bag TcTyVar, -- TyVars bound by the pattern
79 -- These are just the existentially-bound ones.
80 -- Any tyvars bound by *type signatures* in the
81 -- patterns are brought into scope before we begin.
82 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
83 -- which it occurs in the pattern
84 -- The two aren't the same because we conjure up a new
85 -- local name for each variable.
86 LIE) -- Dicts or methods [see below] bound by the pattern
87 -- from existential constructor patterns
91 %************************************************************************
93 \subsection{Variables, wildcards, lazy pats, as-pats}
95 %************************************************************************
98 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
99 = failWithTc (badTypePat pat)
101 tcPat tc_bndr (VarPatIn name) pat_ty
102 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
103 returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
105 tcPat tc_bndr (LazyPatIn pat) pat_ty
106 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
107 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
109 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
110 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
111 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
112 tcAddErrCtxt (patCtxt pat_in) $
113 returnTc (AsPat bndr_id pat', lie_req,
114 tvs, (name, bndr_id) `consBag` ids, lie_avail)
116 tcPat tc_bndr WildPatIn pat_ty
117 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
119 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
120 = tcPat tc_bndr parend_pat pat_ty
122 tcPat tc_bndr (SigPatIn pat sig) pat_ty
123 = tcHsSigType sig `thenTc` \ sig_ty ->
125 -- Check that the signature isn't a polymorphic one, which
126 -- we don't permit (at present, anyway)
127 checkTc (isTauTy sig_ty) (polyPatSig sig_ty) `thenTc_`
129 unifyTauTy pat_ty sig_ty `thenTc_`
130 tcPat tc_bndr pat sig_ty
133 %************************************************************************
135 \subsection{Explicit lists and tuples}
137 %************************************************************************
140 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
141 = tcAddErrCtxt (patCtxt pat_in) $
142 unifyListTy pat_ty `thenTc` \ elem_ty ->
143 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
144 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
146 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
147 = tcAddErrCtxt (patCtxt pat_in) $
149 unifyTupleTy boxity arity pat_ty `thenTc` \ arg_tys ->
150 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
152 -- possibly do the "make all tuple-pats irrefutable" test:
154 unmangled_result = TuplePat pats' boxity
156 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
157 -- so that we can experiment with lazy tuple-matching.
158 -- This is a pretty odd place to make the switch, but
159 -- it was easy to do.
161 possibly_mangled_result
162 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
163 | otherwise = unmangled_result
165 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
170 %************************************************************************
172 \subsection{Other constructors}
175 %************************************************************************
178 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
179 = tcConPat tc_bndr pat name arg_pats pat_ty
181 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
182 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
186 %************************************************************************
190 %************************************************************************
193 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
194 = tcAddErrCtxt (patCtxt pat) $
196 -- Check the constructor itself
197 tcConstructor pat name pat_ty `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
199 -- Don't use zipEqual! If the constructor isn't really a record, then
200 -- dataConFieldLabels will be empty (and each field in the pattern
201 -- will generate an error below).
202 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
207 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
209 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
211 listToBag ex_tvs `unionBags` tvs,
213 lie_avail1 `plusLIE` lie_avail2)
216 tc_fields field_tys []
217 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
219 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
220 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
222 (case [ty | (f,ty) <- field_tys, f == field_label] of
224 -- No matching field; chances are this field label comes from some
225 -- other record type (or maybe none). As well as reporting an
226 -- error we still want to typecheck the pattern, principally to
227 -- make sure that all the variables it binds are put into the
228 -- environment, else the type checker crashes later:
229 -- f (R { foo = (a,b) }) = a+b
230 -- If foo isn't one of R's fields, we don't want to crash when
231 -- typechecking the "a+b".
232 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
233 newTyVarTy liftedTypeKind `thenNF_Tc_`
234 returnTc (error "Bogus selector Id", pat_ty)
236 -- The normal case, when the field comes from the right constructor
238 ASSERT( null extras )
239 tcLookupGlobalId field_label `thenNF_Tc` \ sel_id ->
240 returnTc (sel_id, pat_ty)
241 ) `thenTc` \ (sel_id, pat_ty) ->
243 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
245 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
246 lie_req1 `plusLIE` lie_req2,
247 tvs1 `unionBags` tvs2,
248 ids1 `unionBags` ids2,
249 lie_avail1 `plusLIE` lie_avail2)
252 %************************************************************************
254 \subsection{Literals}
256 %************************************************************************
259 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty
260 -- cf tcExpr on LitLits
261 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
262 newDicts (LitLitOrigin (_UNPK_ s))
263 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ dicts ->
264 returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
266 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
267 = unifyTauTy pat_ty stringTy `thenTc_`
268 tcLookupGlobalId eqStringName `thenNF_Tc` \ eq_id ->
269 returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit),
270 emptyLIE, emptyBag, emptyBag, emptyLIE)
272 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
273 = unifyTauTy pat_ty (simpleHsLitTy simple_lit) `thenTc_`
274 returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
276 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
277 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
278 tcLookupGlobalId eqName `thenNF_Tc` \ eq_sel_id ->
279 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ eq ->
281 returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) over_lit_expr),
282 lie1 `plusLIE` unitLIE eq,
283 emptyBag, emptyBag, emptyLIE)
285 origin = PatOrigin pat
286 lit' = case over_lit of
287 HsIntegral i -> HsInteger i
288 HsFractional f -> HsRat f pat_ty
291 %************************************************************************
293 \subsection{n+k patterns}
295 %************************************************************************
298 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i)) pat_ty
299 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
300 -- The '-' part is re-mappable syntax
301 tcLookupSyntaxId minusName `thenNF_Tc` \ minus_sel_id ->
302 tcLookupGlobalId geName `thenNF_Tc` \ ge_sel_id ->
303 newOverloadedLit origin lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
304 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ ge ->
305 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ minus ->
307 returnTc (NPlusKPat bndr_id i pat_ty
308 (SectionR (HsVar (instToId ge)) over_lit_expr)
309 (SectionR (HsVar (instToId minus)) over_lit_expr),
310 lie1 `plusLIE` mkLIE [ge,minus],
311 emptyBag, unitBag (name, bndr_id), emptyLIE)
313 origin = PatOrigin pat
316 %************************************************************************
318 \subsection{Lists of patterns}
320 %************************************************************************
325 tcPats :: (Name -> TcType -> TcM TcId) -- How to deal with variables
326 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
328 LIE, -- Required by n+k and literal pats
330 Bag (Name, TcId), -- Ids bound by the pattern
331 LIE) -- Dicts bound by the pattern
333 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
335 tcPats tc_bndr (ty:tys) (pat:pats)
336 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
337 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
339 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
340 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
341 lie_avail1 `plusLIE` lie_avail2)
344 ------------------------------------------------------
346 simpleHsLitTy :: HsLit -> TcType
347 simpleHsLitTy (HsCharPrim c) = charPrimTy
348 simpleHsLitTy (HsStringPrim s) = addrPrimTy
349 simpleHsLitTy (HsInt i) = intTy
350 simpleHsLitTy (HsInteger i) = integerTy
351 simpleHsLitTy (HsIntPrim i) = intPrimTy
352 simpleHsLitTy (HsFloatPrim f) = floatPrimTy
353 simpleHsLitTy (HsDoublePrim d) = doublePrimTy
354 simpleHsLitTy (HsChar c) = charTy
355 simpleHsLitTy (HsString str) = stringTy
359 ------------------------------------------------------
361 tcConstructor pat con_name pat_ty
362 = -- Check that it's a constructor
363 tcLookupDataCon con_name `thenNF_Tc` \ data_con ->
367 (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
368 -- Ignore the theta; overloaded constructors only
369 -- behave differently when called, not when used for
372 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
374 ex_theta' = substTheta tenv ex_theta
375 arg_tys' = map (substTy tenv) arg_tys
377 n_ex_tvs = length ex_tvs
378 ex_tvs' = take n_ex_tvs all_tvs'
379 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
381 newDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ dicts ->
383 -- Check overall type matches
384 unifyTauTy pat_ty result_ty `thenTc_`
386 returnTc (data_con, ex_tvs', map instToId dicts, mkLIE dicts, arg_tys')
389 ------------------------------------------------------
391 tcConPat tc_bndr pat con_name arg_pats pat_ty
392 = tcAddErrCtxt (patCtxt pat) $
394 -- Check the constructor itself
395 tcConstructor pat con_name pat_ty `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
397 -- Check correct arity
399 con_arity = dataConSourceArity data_con
400 no_of_args = length arg_pats
402 checkTc (con_arity == no_of_args)
403 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
406 tcPats tc_bndr arg_pats arg_tys' `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
408 returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
410 listToBag ex_tvs' `unionBags` tvs,
412 lie_avail1 `plusLIE` lie_avail2)
416 %************************************************************************
418 \subsection{Errors and contexts}
420 %************************************************************************
423 patCtxt pat = hang (ptext SLIT("In the pattern:"))
426 badFieldCon :: Name -> Name -> SDoc
427 badFieldCon con field
428 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
429 ptext SLIT("does not have field"), quotes (ppr field)]
431 polyPatSig :: TcType -> SDoc
433 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
436 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat