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 )
18 import Inst ( InstOrigin(..),
19 newMethodFromName, newOverloadedLit, newDicts,
20 instToId, tcInstDataCon, tcSyntaxName
22 import Id ( mkLocalId, mkSysLocal )
24 import FieldLabel ( fieldLabelName )
25 import TcEnv ( tcLookupClass, tcLookupDataCon, tcLookupId )
26 import TcMType ( newTyVarTy, zapToType, arityErr )
27 import TcType ( TcType, TcTyVar, TcSigmaType,
28 mkClassPred, liftedTypeKind )
29 import TcUnify ( tcSubOff, TcHoleType,
30 unifyTauTy, unifyListTy, unifyPArrTy, unifyTupleTy,
31 mkCoercion, idCoercion, isIdCoercion,
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 -> 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 = zapToType 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 -> TcHoleType -- 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 pat_ty `thenM` \ (pat', tvs, ids, lie_avail) ->
134 returnM (co_fn <$> (AsPat bndr_id pat'),
135 tvs, (name, bndr_id) `consBag` ids, lie_avail)
137 tcPat tc_bndr (WildPat _) pat_ty
138 = zapToType pat_ty `thenM` \ pat_ty' ->
139 -- We might have an incoming 'hole' type variable; no annotation
140 -- so zap it to a type. Rather like tcMonoPatBndr.
141 returnM (WildPat pat_ty', emptyBag, emptyBag, [])
143 tcPat tc_bndr (ParPat parend_pat) pat_ty
144 -- Leave the parens in, so that warnings from the
145 -- desugarer have parens in them
146 = tcPat tc_bndr parend_pat pat_ty `thenM` \ (pat', tvs, ids, lie_avail) ->
147 returnM (ParPat pat', tvs, ids, lie_avail)
149 tcPat tc_bndr pat_in@(SigPatIn pat sig) pat_ty
150 = addErrCtxt (patCtxt pat_in) $
151 tcHsSigType PatSigCtxt sig `thenM` \ sig_ty ->
152 tcSubPat sig_ty pat_ty `thenM` \ co_fn ->
153 tcPat tc_bndr pat sig_ty `thenM` \ (pat', tvs, ids, lie_avail) ->
154 returnM (co_fn <$> pat', tvs, ids, lie_avail)
158 %************************************************************************
160 \subsection{Explicit lists, parallel arrays, and tuples}
162 %************************************************************************
165 tcPat tc_bndr pat_in@(ListPat pats _) pat_ty
166 = addErrCtxt (patCtxt pat_in) $
167 unifyListTy pat_ty `thenM` \ elem_ty ->
168 tcPats tc_bndr pats (repeat elem_ty) `thenM` \ (pats', tvs, ids, lie_avail) ->
169 returnM (ListPat pats' elem_ty, tvs, ids, lie_avail)
171 tcPat tc_bndr pat_in@(PArrPat pats _) pat_ty
172 = addErrCtxt (patCtxt pat_in) $
173 unifyPArrTy pat_ty `thenM` \ elem_ty ->
174 tcPats tc_bndr pats (repeat elem_ty) `thenM` \ (pats', tvs, ids, lie_avail) ->
175 returnM (PArrPat pats' elem_ty, tvs, ids, lie_avail)
177 tcPat tc_bndr pat_in@(TuplePat pats boxity) pat_ty
178 = addErrCtxt (patCtxt pat_in) $
180 unifyTupleTy boxity arity pat_ty `thenM` \ arg_tys ->
181 tcPats tc_bndr pats arg_tys `thenM` \ (pats', tvs, ids, lie_avail) ->
183 -- possibly do the "make all tuple-pats irrefutable" test:
185 unmangled_result = TuplePat pats' boxity
187 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
188 -- so that we can experiment with lazy tuple-matching.
189 -- This is a pretty odd place to make the switch, but
190 -- it was easy to do.
192 possibly_mangled_result
193 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
194 | otherwise = unmangled_result
196 returnM (possibly_mangled_result, tvs, ids, lie_avail)
202 %************************************************************************
204 \subsection{Other constructors}
207 %************************************************************************
210 tcPat tc_bndr pat_in@(ConPatIn con_name arg_pats) pat_ty
211 = addErrCtxt (patCtxt pat_in) $
213 -- Check that it's a constructor, and instantiate it
214 tcLookupDataCon con_name `thenM` \ data_con ->
215 tcInstDataCon (PatOrigin pat_in) data_con `thenM` \ (_, ex_dicts1, arg_tys, con_res_ty, ex_tvs) ->
217 -- Check overall type matches.
218 -- The pat_ty might be a for-all type, in which
219 -- case we must instantiate to match
220 tcSubPat con_res_ty pat_ty `thenM` \ co_fn ->
222 -- Check the argument patterns
223 tcConStuff tc_bndr data_con arg_pats arg_tys `thenM` \ (arg_pats', arg_tvs, arg_ids, ex_dicts2) ->
225 returnM (co_fn <$> ConPatOut data_con arg_pats' con_res_ty ex_tvs (map instToId ex_dicts1),
226 listToBag ex_tvs `unionBags` arg_tvs,
228 ex_dicts1 ++ ex_dicts2)
232 %************************************************************************
234 \subsection{Literals}
236 %************************************************************************
239 tcPat tc_bndr (LitPat lit@(HsLitLit s _)) pat_ty
240 -- cf tcExpr on LitLits
241 = tcLookupClass cCallableClassName `thenM` \ cCallableClass ->
242 newDicts (LitLitOrigin (unpackFS s))
243 [mkClassPred cCallableClass [pat_ty]] `thenM` \ dicts ->
244 extendLIEs dicts `thenM_`
245 returnM (LitPat (HsLitLit s pat_ty), emptyBag, emptyBag, [])
247 tcPat tc_bndr pat@(LitPat lit@(HsString _)) pat_ty
248 = unifyTauTy pat_ty stringTy `thenM_`
249 tcLookupId eqStringName `thenM` \ eq_id ->
250 returnM (NPatOut lit stringTy (HsVar eq_id `HsApp` HsLit lit),
251 emptyBag, emptyBag, [])
253 tcPat tc_bndr (LitPat simple_lit) pat_ty
254 = unifyTauTy pat_ty (hsLitType simple_lit) `thenM_`
255 returnM (LitPat simple_lit, emptyBag, emptyBag, [])
257 tcPat tc_bndr pat@(NPatIn over_lit mb_neg) pat_ty
258 = newOverloadedLit origin over_lit pat_ty `thenM` \ pos_lit_expr ->
259 newMethodFromName origin pat_ty eqName `thenM` \ eq ->
261 Nothing -> returnM pos_lit_expr -- Positive literal
262 Just neg -> -- Negative literal
263 -- The 'negate' is re-mappable syntax
264 tcSyntaxName origin pat_ty negateName neg `thenM` \ (neg_expr, _) ->
265 returnM (HsApp neg_expr pos_lit_expr)
266 ) `thenM` \ lit_expr ->
268 returnM (NPatOut lit' pat_ty (HsApp (HsVar eq) lit_expr),
269 emptyBag, emptyBag, [])
271 origin = PatOrigin pat
273 -- The literal in an NPatIn is always positive...
274 -- But in NPat, the literal is used to find identical patterns
275 -- so we must negate the literal when necessary!
276 lit' = case (over_lit, mb_neg) of
277 (HsIntegral i _, Nothing) -> HsInteger i
278 (HsIntegral i _, Just _) -> HsInteger (-i)
279 (HsFractional f _, Nothing) -> HsRat f pat_ty
280 (HsFractional f _, Just _) -> HsRat (-f) pat_ty
283 %************************************************************************
285 \subsection{n+k patterns}
287 %************************************************************************
290 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
291 = tc_bndr name pat_ty `thenM` \ (co_fn, bndr_id) ->
292 newOverloadedLit origin lit pat_ty `thenM` \ over_lit_expr ->
293 newMethodFromName origin pat_ty geName `thenM` \ ge ->
295 -- The '-' part is re-mappable syntax
296 tcSyntaxName origin pat_ty minusName minus_name `thenM` \ (minus_expr, _) ->
298 returnM (NPlusKPatOut bndr_id i
299 (SectionR (HsVar ge) over_lit_expr)
300 (SectionR minus_expr over_lit_expr),
301 emptyBag, unitBag (name, bndr_id), [])
303 origin = PatOrigin pat
306 %************************************************************************
308 \subsection{Lists of patterns}
310 %************************************************************************
315 tcPats :: BinderChecker -- How to deal with variables
316 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
319 Bag (Name, TcId), -- Ids bound by the pattern
320 [Inst]) -- Dicts bound by the pattern
322 tcPats tc_bndr [] tys = returnM ([], emptyBag, emptyBag, [])
324 tcPats tc_bndr (ty:tys) (pat:pats)
325 = tcPat tc_bndr ty pat `thenM` \ (pat', tvs1, ids1, lie_avail1) ->
326 tcPats tc_bndr tys pats `thenM` \ (pats', tvs2, ids2, lie_avail2) ->
329 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
330 lie_avail1 ++ lie_avail2)
334 %************************************************************************
336 \subsection{Constructor arguments}
338 %************************************************************************
341 tcConStuff tc_bndr data_con (PrefixCon arg_pats) arg_tys
342 = -- Check correct arity
343 checkTc (con_arity == no_of_args)
344 (arityErr "Constructor" data_con con_arity no_of_args) `thenM_`
347 tcPats tc_bndr arg_pats arg_tys `thenM` \ (arg_pats', tvs, ids, lie_avail) ->
349 returnM (PrefixCon arg_pats', tvs, ids, lie_avail)
351 con_arity = dataConSourceArity data_con
352 no_of_args = length arg_pats
354 tcConStuff tc_bndr data_con (InfixCon p1 p2) arg_tys
355 = -- Check correct arity
356 checkTc (con_arity == 2)
357 (arityErr "Constructor" data_con con_arity 2) `thenM_`
360 tcPat tc_bndr p1 ty1 `thenM` \ (p1', tvs1, ids1, lie_avail1) ->
361 tcPat tc_bndr p2 ty2 `thenM` \ (p2', tvs2, ids2, lie_avail2) ->
363 returnM (InfixCon p1' p2',
364 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
365 lie_avail1 ++ lie_avail2)
367 con_arity = dataConSourceArity data_con
370 tcConStuff tc_bndr data_con (RecCon rpats) arg_tys
371 = -- Check the fields
372 tc_fields field_tys rpats `thenM` \ (rpats', tvs, ids, lie_avail) ->
373 returnM (RecCon rpats', tvs, ids, lie_avail)
376 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con)) arg_tys
377 -- Don't use zipEqual! If the constructor isn't really a record, then
378 -- dataConFieldLabels will be empty (and each field in the pattern
379 -- will generate an error below).
381 tc_fields field_tys []
382 = returnM ([], emptyBag, emptyBag, [])
384 tc_fields field_tys ((field_label, rhs_pat) : rpats)
385 = tc_fields field_tys rpats `thenM` \ (rpats', tvs1, ids1, lie_avail1) ->
387 (case [ty | (f,ty) <- field_tys, f == field_label] of
389 -- No matching field; chances are this field label comes from some
390 -- other record type (or maybe none). As well as reporting an
391 -- error we still want to typecheck the pattern, principally to
392 -- make sure that all the variables it binds are put into the
393 -- environment, else the type checker crashes later:
394 -- f (R { foo = (a,b) }) = a+b
395 -- If foo isn't one of R's fields, we don't want to crash when
396 -- typechecking the "a+b".
397 [] -> addErrTc (badFieldCon data_con field_label) `thenM_`
398 newTyVarTy liftedTypeKind `thenM` \ bogus_ty ->
399 returnM (error "Bogus selector Id", bogus_ty)
401 -- The normal case, when the field comes from the right constructor
403 ASSERT( null extras )
404 tcLookupId field_label `thenM` \ sel_id ->
405 returnM (sel_id, pat_ty)
406 ) `thenM` \ (sel_id, pat_ty) ->
408 tcPat tc_bndr rhs_pat pat_ty `thenM` \ (rhs_pat', tvs2, ids2, lie_avail2) ->
410 returnM ((sel_id, rhs_pat') : rpats',
411 tvs1 `unionBags` tvs2,
412 ids1 `unionBags` ids2,
413 lie_avail1 ++ lie_avail2)
417 %************************************************************************
419 \subsection{Subsumption}
421 %************************************************************************
424 f :: (forall a. a->a) -> Int -> Int
425 f (g::Int->Int) y = g y
426 This is ok: the type signature allows fewer callers than
427 the (more general) signature f :: (Int->Int) -> Int -> Int
428 I.e. (forall a. a->a) <= Int -> Int
429 We end up translating this to:
430 f = \g' :: (forall a. a->a). let g = g' Int in g' y
432 tcSubPat does the work
433 sig_ty is the signature on the pattern itself
434 (Int->Int in the example)
435 expected_ty is the type passed inwards from the context
436 (forall a. a->a in the example)
439 tcSubPat :: TcSigmaType -> TcHoleType -> TcM PatCoFn
441 tcSubPat sig_ty exp_ty
442 = tcSubOff sig_ty exp_ty `thenM` \ co_fn ->
443 -- co_fn is a coercion on *expressions*, and we
444 -- need to make a coercion on *patterns*
445 if isIdCoercion co_fn then
448 newUnique `thenM` \ uniq ->
450 arg_id = mkSysLocal FSLIT("sub") uniq exp_ty
451 the_fn = DictLam [arg_id] (co_fn <$> HsVar arg_id)
452 pat_co_fn p = SigPatOut p exp_ty the_fn
454 returnM (mkCoercion pat_co_fn)
458 %************************************************************************
460 \subsection{Errors and contexts}
462 %************************************************************************
465 patCtxt pat = hang (ptext SLIT("When checking the pattern:"))
468 badFieldCon :: DataCon -> Name -> SDoc
469 badFieldCon con field
470 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
471 ptext SLIT("does not have field"), quotes (ppr field)]
473 polyPatSig :: TcType -> SDoc
475 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
478 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat