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 TcType ( TcType, TcTyVar, tcInstTyVars, newTyVarTy )
25 import TcMonoType ( tcHsSigType )
26 import TcUnify ( unifyTauTy, unifyListTy, unifyTupleTy )
28 import CmdLineOpts ( opt_IrrefutableTuples )
29 import DataCon ( dataConSig, dataConFieldLabels,
32 import Type ( isTauTy, mkTyConApp, mkClassPred, liftedTypeKind )
33 import Subst ( substTy, substTheta )
34 import TysPrim ( charPrimTy, intPrimTy, floatPrimTy,
35 doublePrimTy, addrPrimTy
37 import TysWiredIn ( charTy, stringTy, intTy, integerTy )
38 import PrelNames ( minusName, 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
53 -- we're looking at a lambda-bound pattern,
54 -- so there's no polymorphic guy to worry about
55 tcMonoPatBndr binder_name pat_ty = returnTc (mkLocalId binder_name pat_ty)
59 %************************************************************************
61 \subsection{Typechecking patterns}
63 %************************************************************************
66 tcPat :: (Name -> TcType -> TcM TcId) -- How to construct a suitable (monomorphic)
67 -- Id for variables found in the pattern
68 -- The TcType is the expected type, see note below
71 -> TcType -- Expected type derived from the context
72 -- In the case of a function with a rank-2 signature,
73 -- this type might be a forall type.
74 -- INVARIANT: if it is, the foralls will always be visible,
75 -- not hidden inside a mutable type variable
78 LIE, -- Required by n+k and literal pats
79 Bag TcTyVar, -- TyVars bound by the pattern
80 -- These are just the existentially-bound ones.
81 -- Any tyvars bound by *type signatures* in the
82 -- patterns are brought into scope before we begin.
83 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
84 -- which it occurs in the pattern
85 -- The two aren't the same because we conjure up a new
86 -- local name for each variable.
87 LIE) -- Dicts or methods [see below] bound by the pattern
88 -- from existential constructor patterns
92 %************************************************************************
94 \subsection{Variables, wildcards, lazy pats, as-pats}
96 %************************************************************************
99 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
100 = failWithTc (badTypePat pat)
102 tcPat tc_bndr (VarPatIn name) pat_ty
103 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
104 returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
106 tcPat tc_bndr (LazyPatIn pat) pat_ty
107 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
108 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
110 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
111 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
112 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
113 tcAddErrCtxt (patCtxt pat_in) $
114 returnTc (AsPat bndr_id pat', lie_req,
115 tvs, (name, bndr_id) `consBag` ids, lie_avail)
117 tcPat tc_bndr WildPatIn pat_ty
118 = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
120 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
121 = tcPat tc_bndr parend_pat pat_ty
123 tcPat tc_bndr (SigPatIn pat sig) pat_ty
124 = tcHsSigType sig `thenTc` \ sig_ty ->
126 -- Check that the signature isn't a polymorphic one, which
127 -- we don't permit (at present, anyway)
128 checkTc (isTauTy sig_ty) (polyPatSig sig_ty) `thenTc_`
130 unifyTauTy pat_ty sig_ty `thenTc_`
131 tcPat tc_bndr pat sig_ty
134 %************************************************************************
136 \subsection{Explicit lists and tuples}
138 %************************************************************************
141 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
142 = tcAddErrCtxt (patCtxt pat_in) $
143 unifyListTy pat_ty `thenTc` \ elem_ty ->
144 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
145 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
147 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
148 = tcAddErrCtxt (patCtxt pat_in) $
150 unifyTupleTy boxity arity pat_ty `thenTc` \ arg_tys ->
151 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
153 -- possibly do the "make all tuple-pats irrefutable" test:
155 unmangled_result = TuplePat pats' boxity
157 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
158 -- so that we can experiment with lazy tuple-matching.
159 -- This is a pretty odd place to make the switch, but
160 -- it was easy to do.
162 possibly_mangled_result
163 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
164 | otherwise = unmangled_result
166 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
171 %************************************************************************
173 \subsection{Other constructors}
176 %************************************************************************
179 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
180 = tcConPat tc_bndr pat name arg_pats pat_ty
182 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
183 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
187 %************************************************************************
191 %************************************************************************
194 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
195 = tcAddErrCtxt (patCtxt pat) $
197 -- Check the constructor itself
198 tcConstructor pat name pat_ty `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
200 -- Don't use zipEqual! If the constructor isn't really a record, then
201 -- dataConFieldLabels will be empty (and each field in the pattern
202 -- will generate an error below).
203 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
208 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
210 returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
212 listToBag ex_tvs `unionBags` tvs,
214 lie_avail1 `plusLIE` lie_avail2)
217 tc_fields field_tys []
218 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
220 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
221 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
223 (case [ty | (f,ty) <- field_tys, f == field_label] of
225 -- No matching field; chances are this field label comes from some
226 -- other record type (or maybe none). As well as reporting an
227 -- error we still want to typecheck the pattern, principally to
228 -- make sure that all the variables it binds are put into the
229 -- environment, else the type checker crashes later:
230 -- f (R { foo = (a,b) }) = a+b
231 -- If foo isn't one of R's fields, we don't want to crash when
232 -- typechecking the "a+b".
233 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
234 newTyVarTy liftedTypeKind `thenNF_Tc_`
235 returnTc (error "Bogus selector Id", pat_ty)
237 -- The normal case, when the field comes from the right constructor
239 ASSERT( null extras )
240 tcLookupGlobalId field_label `thenNF_Tc` \ sel_id ->
241 returnTc (sel_id, pat_ty)
242 ) `thenTc` \ (sel_id, pat_ty) ->
244 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
246 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
247 lie_req1 `plusLIE` lie_req2,
248 tvs1 `unionBags` tvs2,
249 ids1 `unionBags` ids2,
250 lie_avail1 `plusLIE` lie_avail2)
253 %************************************************************************
255 \subsection{Literals}
257 %************************************************************************
260 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty
261 -- cf tcExpr on LitLits
262 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
263 newDicts (LitLitOrigin (_UNPK_ s))
264 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ dicts ->
265 returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
267 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
268 = unifyTauTy pat_ty stringTy `thenTc_`
269 tcLookupGlobalId eqStringName `thenNF_Tc` \ eq_id ->
270 returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit),
271 emptyLIE, emptyBag, emptyBag, emptyLIE)
273 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
274 = unifyTauTy pat_ty (simpleHsLitTy simple_lit) `thenTc_`
275 returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
277 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
278 = newOverloadedLit (PatOrigin pat) over_lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
279 tcLookupGlobalId eqName `thenNF_Tc` \ eq_sel_id ->
280 newMethod origin eq_sel_id [pat_ty] `thenNF_Tc` \ eq ->
282 returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) over_lit_expr),
283 lie1 `plusLIE` unitLIE eq,
284 emptyBag, emptyBag, emptyLIE)
286 origin = PatOrigin pat
287 lit' = case over_lit of
288 HsIntegral i -> HsInteger i
289 HsFractional f -> HsRat f pat_ty
292 %************************************************************************
294 \subsection{n+k patterns}
296 %************************************************************************
299 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i)) pat_ty
300 = tc_bndr name pat_ty `thenTc` \ bndr_id ->
301 -- The '-' part is re-mappable syntax
302 tcLookupSyntaxId minusName `thenNF_Tc` \ minus_sel_id ->
303 tcLookupGlobalId geName `thenNF_Tc` \ ge_sel_id ->
304 newOverloadedLit origin lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie1) ->
305 newMethod origin ge_sel_id [pat_ty] `thenNF_Tc` \ ge ->
306 newMethod origin minus_sel_id [pat_ty] `thenNF_Tc` \ minus ->
308 returnTc (NPlusKPat bndr_id i pat_ty
309 (SectionR (HsVar (instToId ge)) over_lit_expr)
310 (SectionR (HsVar (instToId minus)) over_lit_expr),
311 lie1 `plusLIE` mkLIE [ge,minus],
312 emptyBag, unitBag (name, bndr_id), emptyLIE)
314 origin = PatOrigin pat
317 %************************************************************************
319 \subsection{Lists of patterns}
321 %************************************************************************
326 tcPats :: (Name -> TcType -> TcM TcId) -- How to deal with variables
327 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
329 LIE, -- Required by n+k and literal pats
331 Bag (Name, TcId), -- Ids bound by the pattern
332 LIE) -- Dicts bound by the pattern
334 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
336 tcPats tc_bndr (ty:tys) (pat:pats)
337 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
338 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
340 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
341 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
342 lie_avail1 `plusLIE` lie_avail2)
345 ------------------------------------------------------
347 simpleHsLitTy :: HsLit -> TcType
348 simpleHsLitTy (HsCharPrim c) = charPrimTy
349 simpleHsLitTy (HsStringPrim s) = addrPrimTy
350 simpleHsLitTy (HsInt i) = intTy
351 simpleHsLitTy (HsInteger i) = integerTy
352 simpleHsLitTy (HsIntPrim i) = intPrimTy
353 simpleHsLitTy (HsFloatPrim f) = floatPrimTy
354 simpleHsLitTy (HsDoublePrim d) = doublePrimTy
355 simpleHsLitTy (HsChar c) = charTy
356 simpleHsLitTy (HsString str) = stringTy
360 ------------------------------------------------------
362 tcConstructor pat con_name pat_ty
363 = -- Check that it's a constructor
364 tcLookupDataCon con_name `thenNF_Tc` \ data_con ->
368 (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
369 -- Ignore the theta; overloaded constructors only
370 -- behave differently when called, not when used for
373 tcInstTyVars (ex_tvs ++ tvs) `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
375 ex_theta' = substTheta tenv ex_theta
376 arg_tys' = map (substTy tenv) arg_tys
378 n_ex_tvs = length ex_tvs
379 ex_tvs' = take n_ex_tvs all_tvs'
380 result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
382 newDicts (PatOrigin pat) ex_theta' `thenNF_Tc` \ dicts ->
384 -- Check overall type matches
385 unifyTauTy pat_ty result_ty `thenTc_`
387 returnTc (data_con, ex_tvs', map instToId dicts, mkLIE dicts, arg_tys')
390 ------------------------------------------------------
392 tcConPat tc_bndr pat con_name arg_pats pat_ty
393 = tcAddErrCtxt (patCtxt pat) $
395 -- Check the constructor itself
396 tcConstructor pat con_name pat_ty `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
398 -- Check correct arity
400 con_arity = dataConSourceArity data_con
401 no_of_args = length arg_pats
403 checkTc (con_arity == no_of_args)
404 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
407 tcPats tc_bndr arg_pats arg_tys' `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
409 returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
411 listToBag ex_tvs' `unionBags` tvs,
413 lie_avail1 `plusLIE` lie_avail2)
417 %************************************************************************
419 \subsection{Errors and contexts}
421 %************************************************************************
424 patCtxt pat = hang (ptext SLIT("In the pattern:"))
427 badFieldCon :: Name -> Name -> SDoc
428 badFieldCon con field
429 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
430 ptext SLIT("does not have field"), quotes (ppr field)]
432 polyPatSig :: TcType -> SDoc
434 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
437 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat