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 TcHsType ( 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,
40 import BasicTypes ( isBoxed )
47 %************************************************************************
49 \subsection{Variable patterns}
51 %************************************************************************
54 type BinderChecker = Name -> Expected TcSigmaType -> TcM (PatCoFn, TcId)
55 -- How to construct a suitable (monomorphic)
56 -- Id for variables found in the pattern
57 -- The TcSigmaType is the expected type
58 -- from the pattern context
60 -- The Id may have a sigma type (e.g. f (x::forall a. a->a))
61 -- so we want to *create* it during pattern type checking.
62 -- We don't want to make Ids first with a type-variable type
63 -- and then unify... becuase we can't unify a sigma type with a type variable.
65 tcMonoPatBndr :: BinderChecker
66 -- This is the right function to pass to tcPat when
67 -- we're looking at a lambda-bound pattern,
68 -- so there's no polymorphic guy to worry about
70 tcMonoPatBndr binder_name pat_ty
71 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
72 -- If there are *no constraints* on the pattern type, we
73 -- revert to good old H-M typechecking, making
74 -- the type of the binder into an *ordinary*
75 -- type variable. We find out if there are no constraints
76 -- by seeing if we are given an "open hole" as our info.
77 -- What we are trying to avoid here is giving a binder
78 -- a type that is a 'hole'. The only place holes should
79 -- appear is as an argument to tcPat and tcExpr/tcMonoExpr.
81 returnM (idCoercion, mkLocalId binder_name pat_ty')
85 %************************************************************************
87 \subsection{Typechecking patterns}
89 %************************************************************************
92 tcPat :: BinderChecker
95 -> Expected TcSigmaType -- Expected type derived from the context
96 -- In the case of a function with a rank-2 signature,
97 -- this type might be a forall type.
100 Bag TcTyVar, -- TyVars bound by the pattern
101 -- These are just the existentially-bound ones.
102 -- Any tyvars bound by *type signatures* in the
103 -- patterns are brought into scope before we begin.
104 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
105 -- which it occurs in the pattern
106 -- The two aren't the same because we conjure up a new
107 -- local name for each variable.
108 [Inst]) -- Dicts or methods [see below] bound by the pattern
109 -- from existential constructor patterns
113 %************************************************************************
115 \subsection{Variables, wildcards, lazy pats, as-pats}
117 %************************************************************************
120 tcPat tc_bndr pat@(TypePat ty) pat_ty
121 = failWithTc (badTypePat pat)
123 tcPat tc_bndr (VarPat name) pat_ty
124 = tc_bndr name pat_ty `thenM` \ (co_fn, bndr_id) ->
125 returnM (co_fn <$> VarPat bndr_id,
126 emptyBag, unitBag (name, bndr_id), [])
128 tcPat tc_bndr (LazyPat pat) pat_ty
129 = tcPat tc_bndr pat pat_ty `thenM` \ (pat', tvs, ids, lie_avail) ->
130 returnM (LazyPat pat', tvs, ids, lie_avail)
132 tcPat tc_bndr pat_in@(AsPat name pat) pat_ty
133 = tc_bndr name pat_ty `thenM` \ (co_fn, bndr_id) ->
134 tcPat tc_bndr pat (Check (idType bndr_id)) `thenM` \ (pat', tvs, ids, lie_avail) ->
136 -- \ (y@(x::forall a. a->a)) = e
137 -- we'll fail. The as-pattern infers a monotype for 'y', which then
138 -- fails to unify with the polymorphic type for 'x'. This could be
139 -- fixed, but only with a bit more work.
140 returnM (co_fn <$> (AsPat bndr_id pat'),
141 tvs, (name, bndr_id) `consBag` ids, lie_avail)
143 tcPat tc_bndr (WildPat _) pat_ty
144 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
145 -- We might have an incoming 'hole' type variable; no annotation
146 -- so zap it to a type. Rather like tcMonoPatBndr.
147 returnM (WildPat pat_ty', emptyBag, emptyBag, [])
149 tcPat tc_bndr (ParPat parend_pat) pat_ty
150 -- Leave the parens in, so that warnings from the
151 -- desugarer have parens in them
152 = tcPat tc_bndr parend_pat pat_ty `thenM` \ (pat', tvs, ids, lie_avail) ->
153 returnM (ParPat pat', tvs, ids, lie_avail)
155 tcPat tc_bndr pat_in@(SigPatIn pat sig) pat_ty
156 = addErrCtxt (patCtxt pat_in) $
157 tcHsSigType PatSigCtxt sig `thenM` \ sig_ty ->
158 tcSubPat sig_ty pat_ty `thenM` \ co_fn ->
159 tcPat tc_bndr pat (Check sig_ty) `thenM` \ (pat', tvs, ids, lie_avail) ->
160 returnM (co_fn <$> pat', tvs, ids, lie_avail)
164 %************************************************************************
166 \subsection{Explicit lists, parallel arrays, and tuples}
168 %************************************************************************
171 tcPat tc_bndr pat_in@(ListPat pats _) pat_ty
172 = addErrCtxt (patCtxt pat_in) $
173 zapToListTy pat_ty `thenM` \ elem_ty ->
174 tcPats tc_bndr pats (repeat elem_ty) `thenM` \ (pats', tvs, ids, lie_avail) ->
175 returnM (ListPat pats' elem_ty, tvs, ids, lie_avail)
177 tcPat tc_bndr pat_in@(PArrPat pats _) pat_ty
178 = addErrCtxt (patCtxt pat_in) $
179 zapToPArrTy pat_ty `thenM` \ elem_ty ->
180 tcPats tc_bndr pats (repeat elem_ty) `thenM` \ (pats', tvs, ids, lie_avail) ->
181 returnM (PArrPat pats' elem_ty, tvs, ids, lie_avail)
183 tcPat tc_bndr pat_in@(TuplePat pats boxity) pat_ty
184 = addErrCtxt (patCtxt pat_in) $
186 zapToTupleTy boxity arity pat_ty `thenM` \ arg_tys ->
187 tcPats tc_bndr pats arg_tys `thenM` \ (pats', tvs, ids, lie_avail) ->
189 -- possibly do the "make all tuple-pats irrefutable" test:
191 unmangled_result = TuplePat pats' boxity
193 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
194 -- so that we can experiment with lazy tuple-matching.
195 -- This is a pretty odd place to make the switch, but
196 -- it was easy to do.
198 possibly_mangled_result
199 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
200 | otherwise = unmangled_result
202 returnM (possibly_mangled_result, tvs, ids, lie_avail)
208 %************************************************************************
210 \subsection{Other constructors}
213 %************************************************************************
216 tcPat tc_bndr pat_in@(ConPatIn con_name arg_pats) pat_ty
217 = addErrCtxt (patCtxt pat_in) $
219 -- Check that it's a constructor, and instantiate it
220 tcLookupDataCon con_name `thenM` \ data_con ->
221 tcInstDataCon (PatOrigin pat_in) data_con `thenM` \ (_, ex_dicts1, arg_tys, con_res_ty, ex_tvs) ->
223 -- Check overall type matches.
224 -- The pat_ty might be a for-all type, in which
225 -- case we must instantiate to match
226 tcSubPat con_res_ty pat_ty `thenM` \ co_fn ->
228 -- Check the argument patterns
229 tcConStuff tc_bndr data_con arg_pats arg_tys `thenM` \ (arg_pats', arg_tvs, arg_ids, ex_dicts2) ->
231 returnM (co_fn <$> ConPatOut data_con arg_pats' con_res_ty ex_tvs (map instToId ex_dicts1),
232 listToBag ex_tvs `unionBags` arg_tvs,
234 ex_dicts1 ++ ex_dicts2)
238 %************************************************************************
240 \subsection{Literals}
242 %************************************************************************
245 tcPat tc_bndr pat@(LitPat lit@(HsString _)) pat_ty
246 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
247 unifyTauTy pat_ty' stringTy `thenM_`
248 tcLookupId eqStringName `thenM` \ eq_id ->
249 returnM (NPatOut lit stringTy (HsVar eq_id `HsApp` HsLit lit),
250 emptyBag, emptyBag, [])
252 tcPat tc_bndr (LitPat simple_lit) pat_ty
253 = zapExpectedType pat_ty `thenM` \ 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 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
259 newOverloadedLit origin over_lit pat_ty' `thenM` \ pos_lit_expr ->
260 newMethodFromName origin pat_ty' eqName `thenM` \ eq ->
262 Nothing -> returnM pos_lit_expr -- Positive literal
263 Just neg -> -- Negative literal
264 -- The 'negate' is re-mappable syntax
265 tcSyntaxName origin pat_ty' (negateName, HsVar neg) `thenM` \ (_, neg_expr) ->
266 returnM (HsApp neg_expr pos_lit_expr)
267 ) `thenM` \ lit_expr ->
270 -- The literal in an NPatIn is always positive...
271 -- But in NPat, the literal is used to find identical patterns
272 -- so we must negate the literal when necessary!
273 lit' = case (over_lit, mb_neg) of
274 (HsIntegral i _, Nothing) -> HsInteger i pat_ty'
275 (HsIntegral i _, Just _) -> HsInteger (-i) pat_ty'
276 (HsFractional f _, Nothing) -> HsRat f pat_ty'
277 (HsFractional f _, Just _) -> HsRat (-f) pat_ty'
279 returnM (NPatOut lit' pat_ty' (HsApp (HsVar eq) lit_expr),
280 emptyBag, emptyBag, [])
282 origin = PatOrigin pat
285 %************************************************************************
287 \subsection{n+k patterns}
289 %************************************************************************
292 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
293 = tc_bndr name pat_ty `thenM` \ (co_fn, bndr_id) ->
295 pat_ty' = idType bndr_id
297 newOverloadedLit origin lit pat_ty' `thenM` \ over_lit_expr ->
298 newMethodFromName origin pat_ty' geName `thenM` \ ge ->
300 -- The '-' part is re-mappable syntax
301 tcSyntaxName origin pat_ty' (minusName, HsVar minus_name) `thenM` \ (_, minus_expr) ->
303 -- The Report says that n+k patterns must be in Integral
304 -- We may not want this when using re-mappable syntax, though (ToDo?)
305 tcLookupClass integralClassName `thenM` \ icls ->
306 newDicts origin [mkClassPred icls [pat_ty']] `thenM` \ dicts ->
307 extendLIEs dicts `thenM_`
309 returnM (NPlusKPatOut bndr_id i
310 (SectionR (HsVar ge) over_lit_expr)
311 (SectionR minus_expr over_lit_expr),
312 emptyBag, unitBag (name, bndr_id), [])
314 origin = PatOrigin pat
318 %************************************************************************
320 \subsection{Lists of patterns}
322 %************************************************************************
327 tcPats :: BinderChecker -- How to deal with variables
328 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
331 Bag (Name, TcId), -- Ids bound by the pattern
332 [Inst]) -- Dicts bound by the pattern
334 tcPats tc_bndr [] tys = returnM ([], emptyBag, emptyBag, [])
336 tcPats tc_bndr (pat:pats) (ty:tys)
337 = tcPat tc_bndr pat (Check ty) `thenM` \ (pat', tvs1, ids1, lie_avail1) ->
338 tcPats tc_bndr pats tys `thenM` \ (pats', tvs2, ids2, lie_avail2) ->
341 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
342 lie_avail1 ++ lie_avail2)
346 %************************************************************************
348 \subsection{Constructor arguments}
350 %************************************************************************
353 tcConStuff tc_bndr data_con (PrefixCon arg_pats) arg_tys
354 = -- Check correct arity
355 checkTc (con_arity == no_of_args)
356 (arityErr "Constructor" data_con con_arity no_of_args) `thenM_`
359 tcPats tc_bndr arg_pats arg_tys `thenM` \ (arg_pats', tvs, ids, lie_avail) ->
361 returnM (PrefixCon arg_pats', tvs, ids, lie_avail)
363 con_arity = dataConSourceArity data_con
364 no_of_args = length arg_pats
366 tcConStuff tc_bndr data_con (InfixCon p1 p2) arg_tys
367 = -- Check correct arity
368 checkTc (con_arity == 2)
369 (arityErr "Constructor" data_con con_arity 2) `thenM_`
372 tcPat tc_bndr p1 (Check ty1) `thenM` \ (p1', tvs1, ids1, lie_avail1) ->
373 tcPat tc_bndr p2 (Check ty2) `thenM` \ (p2', tvs2, ids2, lie_avail2) ->
375 returnM (InfixCon p1' p2',
376 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
377 lie_avail1 ++ lie_avail2)
379 con_arity = dataConSourceArity data_con
382 tcConStuff tc_bndr data_con (RecCon rpats) arg_tys
383 = -- Check the fields
384 tc_fields field_tys rpats `thenM` \ (rpats', tvs, ids, lie_avail) ->
385 returnM (RecCon rpats', tvs, ids, lie_avail)
388 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con)) arg_tys
389 -- Don't use zipEqual! If the constructor isn't really a record, then
390 -- dataConFieldLabels will be empty (and each field in the pattern
391 -- will generate an error below).
393 tc_fields field_tys []
394 = returnM ([], emptyBag, emptyBag, [])
396 tc_fields field_tys ((field_label, rhs_pat) : rpats)
397 = tc_fields field_tys rpats `thenM` \ (rpats', tvs1, ids1, lie_avail1) ->
399 (case [ty | (f,ty) <- field_tys, f == field_label] of
401 -- No matching field; chances are this field label comes from some
402 -- other record type (or maybe none). As well as reporting an
403 -- error we still want to typecheck the pattern, principally to
404 -- make sure that all the variables it binds are put into the
405 -- environment, else the type checker crashes later:
406 -- f (R { foo = (a,b) }) = a+b
407 -- If foo isn't one of R's fields, we don't want to crash when
408 -- typechecking the "a+b".
409 [] -> addErrTc (badFieldCon data_con field_label) `thenM_`
410 newTyVarTy liftedTypeKind `thenM` \ bogus_ty ->
411 returnM (error "Bogus selector Id", bogus_ty)
413 -- The normal case, when the field comes from the right constructor
415 ASSERT( null extras )
416 tcLookupId field_label `thenM` \ sel_id ->
417 returnM (sel_id, pat_ty)
418 ) `thenM` \ (sel_id, pat_ty) ->
420 tcPat tc_bndr rhs_pat (Check pat_ty) `thenM` \ (rhs_pat', tvs2, ids2, lie_avail2) ->
422 returnM ((sel_id, rhs_pat') : rpats',
423 tvs1 `unionBags` tvs2,
424 ids1 `unionBags` ids2,
425 lie_avail1 ++ lie_avail2)
429 %************************************************************************
431 \subsection{Subsumption}
433 %************************************************************************
436 f :: (forall a. a->a) -> Int -> Int
437 f (g::Int->Int) y = g y
438 This is ok: the type signature allows fewer callers than
439 the (more general) signature f :: (Int->Int) -> Int -> Int
440 I.e. (forall a. a->a) <= Int -> Int
441 We end up translating this to:
442 f = \g' :: (forall a. a->a). let g = g' Int in g' y
444 tcSubPat does the work
445 sig_ty is the signature on the pattern itself
446 (Int->Int in the example)
447 expected_ty is the type passed inwards from the context
448 (forall a. a->a in the example)
451 tcSubPat :: TcSigmaType -> Expected TcSigmaType -> TcM PatCoFn
453 tcSubPat sig_ty exp_ty
454 = tcSubOff sig_ty exp_ty `thenM` \ co_fn ->
455 -- co_fn is a coercion on *expressions*, and we
456 -- need to make a coercion on *patterns*
457 if isIdCoercion co_fn then
460 newUnique `thenM` \ uniq ->
461 readExpectedType exp_ty `thenM` \ exp_ty' ->
463 arg_id = mkSysLocal FSLIT("sub") uniq exp_ty'
464 the_fn = DictLam [arg_id] (co_fn <$> HsVar arg_id)
465 pat_co_fn p = SigPatOut p exp_ty' the_fn
467 returnM (mkCoercion pat_co_fn)
471 %************************************************************************
473 \subsection{Errors and contexts}
475 %************************************************************************
478 patCtxt pat = hang (ptext SLIT("When checking the pattern:"))
481 badFieldCon :: DataCon -> Name -> SDoc
482 badFieldCon con field
483 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
484 ptext SLIT("does not have field"), quotes (ppr field)]
486 polyPatSig :: TcType -> SDoc
488 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
491 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat