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 Type ( isTauTy, mkTyConApp, mkClassPred, boxedTypeKind )
32 import Subst ( substTy, substClasses )
33 import TysPrim ( charPrimTy, intPrimTy, floatPrimTy,
34 doublePrimTy, addrPrimTy
36 import TysWiredIn ( charTy, stringTy, intTy, integerTy )
37 import PrelNames ( 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 there are no signatures
52 tcPatBndr_NoSigs binder_name pat_ty
53 = -- Need to make a new, monomorphic, Id
54 -- The binder_name is already being used for the polymorphic Id
55 newLocalId (getOccName binder_name) pat_ty loc `thenNF_Tc` \ bndr_id ->
58 loc = getSrcLoc binder_name
62 %************************************************************************
64 \subsection{Typechecking patterns}
66 %************************************************************************
69 tcPat :: (Name -> TcType -> TcM TcId) -- How to construct a suitable (monomorphic)
70 -- Id for variables found in the pattern
71 -- The TcType is the expected type, see note below
74 -> TcType -- Expected type derived from the context
75 -- In the case of a function with a rank-2 signature,
76 -- this type might be a forall type.
77 -- INVARIANT: if it is, the foralls will always be visible,
78 -- not hidden inside a mutable type variable
81 LIE, -- Required by n+k and literal pats
82 Bag TcTyVar, -- TyVars bound by the pattern
83 -- These are just the existentially-bound ones.
84 -- Any tyvars bound by *type signatures* in the
85 -- patterns are brought into scope before we begin.
86 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
87 -- which it occurs in the pattern
88 -- The two aren't the same because we conjure up a new
89 -- local name for each variable.
90 LIE) -- Dicts or methods [see below] bound by the pattern
91 -- from existential constructor patterns
95 %************************************************************************
97 \subsection{Variables, wildcards, lazy pats, as-pats}
99 %************************************************************************
102 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
103 = failWithTc (badTypePat pat)
105 tcPat tc_bndr (VarPatIn name) pat_ty
106 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
107 returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
109 tcPat tc_bndr (LazyPatIn pat) pat_ty
110 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
111 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
113 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
114 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
115 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
116 tcAddErrCtxt (patCtxt pat_in) $
117 returnTc (AsPat bndr_id pat', lie_req,
118 tvs, (name, bndr_id) `consBag` ids, lie_avail)
120 tcPat tc_bndr WildPatIn pat_ty
121 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
123 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
124 = tcPat tc_bndr parend_pat pat_ty
126 tcPat tc_bndr (SigPatIn pat sig) pat_ty
127 = tcHsSigType sig `thenTc` \ sig_ty ->
129 -- Check that the signature isn't a polymorphic one, which
130 -- we don't permit (at present, anyway)
131 checkTc (isTauTy sig_ty) (polyPatSig sig_ty) `thenTc_`
133 unifyTauTy pat_ty sig_ty `thenTc_`
134 tcPat tc_bndr pat sig_ty
137 %************************************************************************
139 \subsection{Explicit lists and tuples}
141 %************************************************************************
144 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
145 = tcAddErrCtxt (patCtxt pat_in) $
146 unifyListTy pat_ty `thenTc` \ elem_ty ->
147 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
148 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
150 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
151 = tcAddErrCtxt (patCtxt pat_in) $
153 unifyTupleTy boxity arity pat_ty `thenTc` \ arg_tys ->
154 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
156 -- possibly do the "make all tuple-pats irrefutable" test:
158 unmangled_result = TuplePat pats' boxity
160 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
161 -- so that we can experiment with lazy tuple-matching.
162 -- This is a pretty odd place to make the switch, but
163 -- it was easy to do.
165 possibly_mangled_result
166 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
167 | otherwise = unmangled_result
169 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
174 %************************************************************************
176 \subsection{Other constructors}
179 %************************************************************************
182 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
183 = tcConPat tc_bndr pat name arg_pats pat_ty
185 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
186 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
190 %************************************************************************
194 %************************************************************************
197 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
198 = tcAddErrCtxt (patCtxt pat) $
200 -- Check the constructor itself
201 tcConstructor pat name pat_ty `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
203 -- Don't use zipEqual! If the constructor isn't really a record, then
204 -- dataConFieldLabels will be empty (and each field in the pattern
205 -- will generate an error below).
206 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
211 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
213 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
215 listToBag ex_tvs `unionBags` tvs,
217 lie_avail1 `plusLIE` lie_avail2)
220 tc_fields field_tys []
221 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
223 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
224 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
226 (case [ty | (f,ty) <- field_tys, f == field_label] of
228 -- No matching field; chances are this field label comes from some
229 -- other record type (or maybe none). As well as reporting an
230 -- error we still want to typecheck the pattern, principally to
231 -- make sure that all the variables it binds are put into the
232 -- environment, else the type checker crashes later:
233 -- f (R { foo = (a,b) }) = a+b
234 -- If foo isn't one of R's fields, we don't want to crash when
235 -- typechecking the "a+b".
236 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
237 newTyVarTy boxedTypeKind `thenNF_Tc_`
238 returnTc (error "Bogus selector Id", pat_ty)
240 -- The normal case, when the field comes from the right constructor
242 ASSERT( null extras )
243 tcLookupGlobalId field_label `thenNF_Tc` \ sel_id ->
244 returnTc (sel_id, pat_ty)
245 ) `thenTc` \ (sel_id, pat_ty) ->
247 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
249 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
250 lie_req1 `plusLIE` lie_req2,
251 tvs1 `unionBags` tvs2,
252 ids1 `unionBags` ids2,
253 lie_avail1 `plusLIE` lie_avail2)
256 %************************************************************************
258 \subsection{Literals}
260 %************************************************************************
263 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty
264 -- cf tcExpr on LitLits
265 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
266 newDicts (LitLitOrigin (_UNPK_ s))
267 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ (dicts, _) ->
268 returnTc (LitPat (HsLitLit s pat_ty) pat_ty, dicts, emptyBag, emptyBag, emptyLIE)
270 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
271 = unifyTauTy pat_ty stringTy `thenTc_`
272 tcLookupGlobalId eqStringName `thenNF_Tc` \ eq_id ->
273 returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit),
274 emptyLIE, emptyBag, emptyBag, emptyLIE)
276 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
277 = unifyTauTy pat_ty (simpleHsLitTy simple_lit) `thenTc_`
278 returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
280 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
281 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
282 tcLookupGlobalId eqName `thenNF_Tc` \ eq_sel_id ->
283 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ (lie2, eq_id) ->
285 returnTc (NPat lit' pat_ty (HsApp (HsVar eq_id) over_lit_expr),
287 emptyBag, emptyBag, emptyLIE)
289 origin = PatOrigin pat
290 lit' = case over_lit of
291 HsIntegral i _ -> HsInteger i
292 HsFractional f _ -> HsRat f pat_ty
295 %************************************************************************
297 \subsection{n+k patterns}
299 %************************************************************************
302 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus) pat_ty
303 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
304 tcLookupGlobalId minus `thenNF_Tc` \ minus_sel_id ->
305 tcLookupGlobalId geName `thenNF_Tc` \ ge_sel_id ->
306 newOverloadedLit origin lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
307 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ (lie2, ge_id) ->
308 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ (lie3, minus_id) ->
310 returnTc (NPlusKPat bndr_id i pat_ty
311 (SectionR (HsVar ge_id) over_lit_expr)
312 (SectionR (HsVar minus_id) over_lit_expr),
313 lie1 `plusLIE` lie2 `plusLIE` lie3,
314 emptyBag, unitBag (name, bndr_id), emptyLIE)
316 origin = PatOrigin pat
319 %************************************************************************
321 \subsection{Lists of patterns}
323 %************************************************************************
328 tcPats :: (Name -> TcType -> TcM TcId) -- How to deal with variables
329 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
331 LIE, -- Required by n+k and literal pats
333 Bag (Name, TcId), -- Ids bound by the pattern
334 LIE) -- Dicts bound by the pattern
336 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
338 tcPats tc_bndr (ty:tys) (pat:pats)
339 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
340 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
342 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
343 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
344 lie_avail1 `plusLIE` lie_avail2)
347 ------------------------------------------------------
349 simpleHsLitTy :: HsLit -> TcType
350 simpleHsLitTy (HsCharPrim c) = charPrimTy
351 simpleHsLitTy (HsStringPrim s) = addrPrimTy
352 simpleHsLitTy (HsInt i) = intTy
353 simpleHsLitTy (HsInteger i) = integerTy
354 simpleHsLitTy (HsIntPrim i) = intPrimTy
355 simpleHsLitTy (HsFloatPrim f) = floatPrimTy
356 simpleHsLitTy (HsDoublePrim d) = doublePrimTy
357 simpleHsLitTy (HsChar c) = charTy
358 simpleHsLitTy (HsString str) = stringTy
362 ------------------------------------------------------
364 tcConstructor pat con_name pat_ty
365 = -- Check that it's a constructor
366 tcLookupDataCon con_name `thenNF_Tc` \ data_con ->
370 (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
371 -- Ignore the theta; overloaded constructors only
372 -- behave differently when called, not when used for
375 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
377 ex_theta' = substClasses tenv ex_theta
378 arg_tys' = map (substTy tenv) arg_tys
380 n_ex_tvs = length ex_tvs
381 ex_tvs' = take n_ex_tvs all_tvs'
382 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
384 newClassDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ (lie_avail, dicts) ->
386 -- Check overall type matches
387 unifyTauTy pat_ty result_ty `thenTc_`
389 returnTc (data_con, ex_tvs', dicts, lie_avail, arg_tys')
392 ------------------------------------------------------
394 tcConPat tc_bndr pat con_name arg_pats pat_ty
395 = tcAddErrCtxt (patCtxt pat) $
397 -- Check the constructor itself
398 tcConstructor pat con_name pat_ty `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
400 -- Check correct arity
402 con_arity = dataConSourceArity data_con
403 no_of_args = length arg_pats
405 checkTc (con_arity == no_of_args)
406 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
409 tcPats tc_bndr arg_pats arg_tys' `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
411 returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
413 listToBag ex_tvs' `unionBags` tvs,
415 lie_avail1 `plusLIE` lie_avail2)
419 %************************************************************************
421 \subsection{Errors and contexts}
423 %************************************************************************
426 patCtxt pat = hang (ptext SLIT("In the pattern:"))
429 badFieldCon :: Name -> Name -> SDoc
430 badFieldCon con field
431 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
432 ptext SLIT("does not have field"), quotes (ppr field)]
434 polyPatSig :: TcType -> SDoc
436 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
439 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat