2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcPat]{Typechecking patterns}
7 module TcPat ( tcPat, tcMonoPatBndr, tcSubPat,
8 badFieldCon, polyPatSig
11 #include "HsVersions.h"
13 import HsSyn ( Pat(..), HsConDetails(..), HsLit(..), HsOverLit(..), HsExpr(..) )
14 import RnHsSyn ( RenamedPat )
15 import TcHsSyn ( TcPat, TcId, hsLitType,
16 mkCoercion, idCoercion, isIdCoercion,
20 import Inst ( InstOrigin(..),
21 newMethodFromName, newOverloadedLit, newDicts,
22 instToId, tcInstDataCon, tcSyntaxName
24 import Id ( idType, mkLocalId, mkSysLocal )
26 import FieldLabel ( fieldLabelName )
27 import TcEnv ( tcLookupClass, tcLookupDataCon, tcLookupId )
28 import TcMType ( newTyVarTy, arityErr )
29 import TcType ( TcType, TcTyVar, TcSigmaType,
30 mkClassPred, liftedTypeKind )
31 import TcUnify ( tcSubOff, Expected(..), readExpectedType, zapExpectedType,
32 unifyTauTy, zapToListTy, zapToPArrTy, zapToTupleTy )
33 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
35 import TysWiredIn ( stringTy )
36 import CmdLineOpts ( opt_IrrefutableTuples )
37 import DataCon ( DataCon, dataConFieldLabels, dataConSourceArity )
38 import PrelNames ( eqStringName, eqName, geName, negateName, minusName, cCallableClassName )
39 import BasicTypes ( isBoxed )
46 %************************************************************************
48 \subsection{Variable patterns}
50 %************************************************************************
53 type BinderChecker = Name -> Expected TcSigmaType -> TcM (PatCoFn, TcId)
54 -- How to construct a suitable (monomorphic)
55 -- Id for variables found in the pattern
56 -- The TcSigmaType is the expected type
57 -- from the pattern context
59 -- The Id may have a sigma type (e.g. f (x::forall a. a->a))
60 -- so we want to *create* it during pattern type checking.
61 -- We don't want to make Ids first with a type-variable type
62 -- and then unify... becuase we can't unify a sigma type with a type variable.
64 tcMonoPatBndr :: BinderChecker
65 -- This is the right function to pass to tcPat when
66 -- we're looking at a lambda-bound pattern,
67 -- so there's no polymorphic guy to worry about
69 tcMonoPatBndr binder_name pat_ty
70 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
71 -- If there are *no constraints* on the pattern type, we
72 -- revert to good old H-M typechecking, making
73 -- the type of the binder into an *ordinary*
74 -- type variable. We find out if there are no constraints
75 -- by seeing if we are given an "open hole" as our info.
76 -- What we are trying to avoid here is giving a binder
77 -- a type that is a 'hole'. The only place holes should
78 -- appear is as an argument to tcPat and tcExpr/tcMonoExpr.
80 returnM (idCoercion, mkLocalId binder_name pat_ty')
84 %************************************************************************
86 \subsection{Typechecking patterns}
88 %************************************************************************
91 tcPat :: BinderChecker
94 -> Expected TcSigmaType -- Expected type derived from the context
95 -- In the case of a function with a rank-2 signature,
96 -- this type might be a forall type.
99 Bag TcTyVar, -- TyVars bound by the pattern
100 -- These are just the existentially-bound ones.
101 -- Any tyvars bound by *type signatures* in the
102 -- patterns are brought into scope before we begin.
103 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
104 -- which it occurs in the pattern
105 -- The two aren't the same because we conjure up a new
106 -- local name for each variable.
107 [Inst]) -- Dicts or methods [see below] bound by the pattern
108 -- from existential constructor patterns
112 %************************************************************************
114 \subsection{Variables, wildcards, lazy pats, as-pats}
116 %************************************************************************
119 tcPat tc_bndr pat@(TypePat ty) pat_ty
120 = failWithTc (badTypePat pat)
122 tcPat tc_bndr (VarPat name) pat_ty
123 = tc_bndr name pat_ty `thenM` \ (co_fn, bndr_id) ->
124 returnM (co_fn <$> VarPat bndr_id,
125 emptyBag, unitBag (name, bndr_id), [])
127 tcPat tc_bndr (LazyPat pat) pat_ty
128 = tcPat tc_bndr pat pat_ty `thenM` \ (pat', tvs, ids, lie_avail) ->
129 returnM (LazyPat pat', tvs, ids, lie_avail)
131 tcPat tc_bndr pat_in@(AsPat name pat) pat_ty
132 = tc_bndr name pat_ty `thenM` \ (co_fn, bndr_id) ->
133 tcPat tc_bndr pat (Check (idType bndr_id)) `thenM` \ (pat', tvs, ids, lie_avail) ->
135 -- \ (y@(x::forall a. a->a)) = e
136 -- we'll fail. The as-pattern infers a monotype for 'y', which then
137 -- fails to unify with the polymorphic type for 'x'. This could be
138 -- fixed, but only with a bit more work.
139 returnM (co_fn <$> (AsPat bndr_id pat'),
140 tvs, (name, bndr_id) `consBag` ids, lie_avail)
142 tcPat tc_bndr (WildPat _) pat_ty
143 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
144 -- We might have an incoming 'hole' type variable; no annotation
145 -- so zap it to a type. Rather like tcMonoPatBndr.
146 returnM (WildPat pat_ty', emptyBag, emptyBag, [])
148 tcPat tc_bndr (ParPat parend_pat) pat_ty
149 -- Leave the parens in, so that warnings from the
150 -- desugarer have parens in them
151 = tcPat tc_bndr parend_pat pat_ty `thenM` \ (pat', tvs, ids, lie_avail) ->
152 returnM (ParPat pat', tvs, ids, lie_avail)
154 tcPat tc_bndr pat_in@(SigPatIn pat sig) pat_ty
155 = addErrCtxt (patCtxt pat_in) $
156 tcHsSigType PatSigCtxt sig `thenM` \ sig_ty ->
157 tcSubPat sig_ty pat_ty `thenM` \ co_fn ->
158 tcPat tc_bndr pat (Check sig_ty) `thenM` \ (pat', tvs, ids, lie_avail) ->
159 returnM (co_fn <$> pat', tvs, ids, lie_avail)
163 %************************************************************************
165 \subsection{Explicit lists, parallel arrays, and tuples}
167 %************************************************************************
170 tcPat tc_bndr pat_in@(ListPat pats _) pat_ty
171 = addErrCtxt (patCtxt pat_in) $
172 zapToListTy pat_ty `thenM` \ elem_ty ->
173 tcPats tc_bndr pats (repeat elem_ty) `thenM` \ (pats', tvs, ids, lie_avail) ->
174 returnM (ListPat pats' elem_ty, tvs, ids, lie_avail)
176 tcPat tc_bndr pat_in@(PArrPat pats _) pat_ty
177 = addErrCtxt (patCtxt pat_in) $
178 zapToPArrTy pat_ty `thenM` \ elem_ty ->
179 tcPats tc_bndr pats (repeat elem_ty) `thenM` \ (pats', tvs, ids, lie_avail) ->
180 returnM (PArrPat pats' elem_ty, tvs, ids, lie_avail)
182 tcPat tc_bndr pat_in@(TuplePat pats boxity) pat_ty
183 = addErrCtxt (patCtxt pat_in) $
185 zapToTupleTy boxity arity pat_ty `thenM` \ arg_tys ->
186 tcPats tc_bndr pats arg_tys `thenM` \ (pats', tvs, ids, lie_avail) ->
188 -- possibly do the "make all tuple-pats irrefutable" test:
190 unmangled_result = TuplePat pats' boxity
192 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
193 -- so that we can experiment with lazy tuple-matching.
194 -- This is a pretty odd place to make the switch, but
195 -- it was easy to do.
197 possibly_mangled_result
198 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
199 | otherwise = unmangled_result
201 returnM (possibly_mangled_result, tvs, ids, lie_avail)
207 %************************************************************************
209 \subsection{Other constructors}
212 %************************************************************************
215 tcPat tc_bndr pat_in@(ConPatIn con_name arg_pats) pat_ty
216 = addErrCtxt (patCtxt pat_in) $
218 -- Check that it's a constructor, and instantiate it
219 tcLookupDataCon con_name `thenM` \ data_con ->
220 tcInstDataCon (PatOrigin pat_in) data_con `thenM` \ (_, ex_dicts1, arg_tys, con_res_ty, ex_tvs) ->
222 -- Check overall type matches.
223 -- The pat_ty might be a for-all type, in which
224 -- case we must instantiate to match
225 tcSubPat con_res_ty pat_ty `thenM` \ co_fn ->
227 -- Check the argument patterns
228 tcConStuff tc_bndr data_con arg_pats arg_tys `thenM` \ (arg_pats', arg_tvs, arg_ids, ex_dicts2) ->
230 returnM (co_fn <$> ConPatOut data_con arg_pats' con_res_ty ex_tvs (map instToId ex_dicts1),
231 listToBag ex_tvs `unionBags` arg_tvs,
233 ex_dicts1 ++ ex_dicts2)
237 %************************************************************************
239 \subsection{Literals}
241 %************************************************************************
244 tcPat tc_bndr (LitPat lit@(HsLitLit s _)) pat_ty
245 -- cf tcExpr on LitLits
246 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
247 tcLookupClass cCallableClassName `thenM` \ cCallableClass ->
248 newDicts (LitLitOrigin (unpackFS s))
249 [mkClassPred cCallableClass [pat_ty']] `thenM` \ dicts ->
250 extendLIEs dicts `thenM_`
251 returnM (LitPat (HsLitLit s pat_ty'), emptyBag, emptyBag, [])
253 tcPat tc_bndr pat@(LitPat lit@(HsString _)) pat_ty
254 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
255 unifyTauTy pat_ty' stringTy `thenM_`
256 tcLookupId eqStringName `thenM` \ eq_id ->
257 returnM (NPatOut lit stringTy (HsVar eq_id `HsApp` HsLit lit),
258 emptyBag, emptyBag, [])
260 tcPat tc_bndr (LitPat simple_lit) pat_ty
261 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
262 unifyTauTy pat_ty' (hsLitType simple_lit) `thenM_`
263 returnM (LitPat simple_lit, emptyBag, emptyBag, [])
265 tcPat tc_bndr pat@(NPatIn over_lit mb_neg) pat_ty
266 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
267 newOverloadedLit origin over_lit pat_ty' `thenM` \ pos_lit_expr ->
268 newMethodFromName origin pat_ty' eqName `thenM` \ eq ->
270 Nothing -> returnM pos_lit_expr -- Positive literal
271 Just neg -> -- Negative literal
272 -- The 'negate' is re-mappable syntax
273 tcSyntaxName origin pat_ty' negateName neg `thenM` \ (neg_expr, _) ->
274 returnM (HsApp neg_expr pos_lit_expr)
275 ) `thenM` \ lit_expr ->
278 -- The literal in an NPatIn is always positive...
279 -- But in NPat, the literal is used to find identical patterns
280 -- so we must negate the literal when necessary!
281 lit' = case (over_lit, mb_neg) of
282 (HsIntegral i _, Nothing) -> HsInteger i
283 (HsIntegral i _, Just _) -> HsInteger (-i)
284 (HsFractional f _, Nothing) -> HsRat f pat_ty'
285 (HsFractional f _, Just _) -> HsRat (-f) pat_ty'
287 returnM (NPatOut lit' pat_ty' (HsApp (HsVar eq) lit_expr),
288 emptyBag, emptyBag, [])
290 origin = PatOrigin pat
293 %************************************************************************
295 \subsection{n+k patterns}
297 %************************************************************************
300 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
301 = tc_bndr name pat_ty `thenM` \ (co_fn, bndr_id) ->
303 pat_ty' = idType bndr_id
305 newOverloadedLit origin lit pat_ty' `thenM` \ over_lit_expr ->
306 newMethodFromName origin pat_ty' geName `thenM` \ ge ->
308 -- The '-' part is re-mappable syntax
309 tcSyntaxName origin pat_ty' minusName minus_name `thenM` \ (minus_expr, _) ->
311 returnM (NPlusKPatOut bndr_id i
312 (SectionR (HsVar ge) over_lit_expr)
313 (SectionR minus_expr over_lit_expr),
314 emptyBag, unitBag (name, bndr_id), [])
316 origin = PatOrigin pat
320 %************************************************************************
322 \subsection{Lists of patterns}
324 %************************************************************************
329 tcPats :: BinderChecker -- How to deal with variables
330 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
333 Bag (Name, TcId), -- Ids bound by the pattern
334 [Inst]) -- Dicts bound by the pattern
336 tcPats tc_bndr [] tys = returnM ([], emptyBag, emptyBag, [])
338 tcPats tc_bndr (pat:pats) (ty:tys)
339 = tcPat tc_bndr pat (Check ty) `thenM` \ (pat', tvs1, ids1, lie_avail1) ->
340 tcPats tc_bndr pats tys `thenM` \ (pats', tvs2, ids2, lie_avail2) ->
343 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
344 lie_avail1 ++ lie_avail2)
348 %************************************************************************
350 \subsection{Constructor arguments}
352 %************************************************************************
355 tcConStuff tc_bndr data_con (PrefixCon arg_pats) arg_tys
356 = -- Check correct arity
357 checkTc (con_arity == no_of_args)
358 (arityErr "Constructor" data_con con_arity no_of_args) `thenM_`
361 tcPats tc_bndr arg_pats arg_tys `thenM` \ (arg_pats', tvs, ids, lie_avail) ->
363 returnM (PrefixCon arg_pats', tvs, ids, lie_avail)
365 con_arity = dataConSourceArity data_con
366 no_of_args = length arg_pats
368 tcConStuff tc_bndr data_con (InfixCon p1 p2) arg_tys
369 = -- Check correct arity
370 checkTc (con_arity == 2)
371 (arityErr "Constructor" data_con con_arity 2) `thenM_`
374 tcPat tc_bndr p1 (Check ty1) `thenM` \ (p1', tvs1, ids1, lie_avail1) ->
375 tcPat tc_bndr p2 (Check ty2) `thenM` \ (p2', tvs2, ids2, lie_avail2) ->
377 returnM (InfixCon p1' p2',
378 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
379 lie_avail1 ++ lie_avail2)
381 con_arity = dataConSourceArity data_con
384 tcConStuff tc_bndr data_con (RecCon rpats) arg_tys
385 = -- Check the fields
386 tc_fields field_tys rpats `thenM` \ (rpats', tvs, ids, lie_avail) ->
387 returnM (RecCon rpats', tvs, ids, lie_avail)
390 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con)) arg_tys
391 -- Don't use zipEqual! If the constructor isn't really a record, then
392 -- dataConFieldLabels will be empty (and each field in the pattern
393 -- will generate an error below).
395 tc_fields field_tys []
396 = returnM ([], emptyBag, emptyBag, [])
398 tc_fields field_tys ((field_label, rhs_pat) : rpats)
399 = tc_fields field_tys rpats `thenM` \ (rpats', tvs1, ids1, lie_avail1) ->
401 (case [ty | (f,ty) <- field_tys, f == field_label] of
403 -- No matching field; chances are this field label comes from some
404 -- other record type (or maybe none). As well as reporting an
405 -- error we still want to typecheck the pattern, principally to
406 -- make sure that all the variables it binds are put into the
407 -- environment, else the type checker crashes later:
408 -- f (R { foo = (a,b) }) = a+b
409 -- If foo isn't one of R's fields, we don't want to crash when
410 -- typechecking the "a+b".
411 [] -> addErrTc (badFieldCon data_con field_label) `thenM_`
412 newTyVarTy liftedTypeKind `thenM` \ bogus_ty ->
413 returnM (error "Bogus selector Id", bogus_ty)
415 -- The normal case, when the field comes from the right constructor
417 ASSERT( null extras )
418 tcLookupId field_label `thenM` \ sel_id ->
419 returnM (sel_id, pat_ty)
420 ) `thenM` \ (sel_id, pat_ty) ->
422 tcPat tc_bndr rhs_pat (Check pat_ty) `thenM` \ (rhs_pat', tvs2, ids2, lie_avail2) ->
424 returnM ((sel_id, rhs_pat') : rpats',
425 tvs1 `unionBags` tvs2,
426 ids1 `unionBags` ids2,
427 lie_avail1 ++ lie_avail2)
431 %************************************************************************
433 \subsection{Subsumption}
435 %************************************************************************
438 f :: (forall a. a->a) -> Int -> Int
439 f (g::Int->Int) y = g y
440 This is ok: the type signature allows fewer callers than
441 the (more general) signature f :: (Int->Int) -> Int -> Int
442 I.e. (forall a. a->a) <= Int -> Int
443 We end up translating this to:
444 f = \g' :: (forall a. a->a). let g = g' Int in g' y
446 tcSubPat does the work
447 sig_ty is the signature on the pattern itself
448 (Int->Int in the example)
449 expected_ty is the type passed inwards from the context
450 (forall a. a->a in the example)
453 tcSubPat :: TcSigmaType -> Expected TcSigmaType -> TcM PatCoFn
455 tcSubPat sig_ty exp_ty
456 = tcSubOff sig_ty exp_ty `thenM` \ co_fn ->
457 -- co_fn is a coercion on *expressions*, and we
458 -- need to make a coercion on *patterns*
459 if isIdCoercion co_fn then
462 newUnique `thenM` \ uniq ->
463 readExpectedType exp_ty `thenM` \ exp_ty' ->
465 arg_id = mkSysLocal FSLIT("sub") uniq exp_ty'
466 the_fn = DictLam [arg_id] (co_fn <$> HsVar arg_id)
467 pat_co_fn p = SigPatOut p exp_ty' the_fn
469 returnM (mkCoercion pat_co_fn)
473 %************************************************************************
475 \subsection{Errors and contexts}
477 %************************************************************************
480 patCtxt pat = hang (ptext SLIT("When checking the pattern:"))
483 badFieldCon :: DataCon -> Name -> SDoc
484 badFieldCon con field
485 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
486 ptext SLIT("does not have field"), quotes (ppr field)]
488 polyPatSig :: TcType -> SDoc
490 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
493 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat