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(..), LPat, HsConDetails(..), HsLit(..), HsOverLit(..), HsExpr(..) )
15 import TcHsSyn ( 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, tcLookupLocatedDataCon, 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 )
41 import SrcLoc ( Located(..), noLoc, unLoc )
48 %************************************************************************
50 \subsection{Variable patterns}
52 %************************************************************************
55 type BinderChecker = Name -> Expected TcSigmaType -> TcM (PatCoFn, TcId)
56 -- How to construct a suitable (monomorphic)
57 -- Id for variables found in the pattern
58 -- The TcSigmaType is the expected type
59 -- from the pattern context
61 -- The Id may have a sigma type (e.g. f (x::forall a. a->a))
62 -- so we want to *create* it during pattern type checking.
63 -- We don't want to make Ids first with a type-variable type
64 -- and then unify... becuase we can't unify a sigma type with a type variable.
66 tcMonoPatBndr :: BinderChecker
67 -- This is the right function to pass to tcPat when
68 -- we're looking at a lambda-bound pattern,
69 -- so there's no polymorphic guy to worry about
71 tcMonoPatBndr binder_name pat_ty
72 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
73 -- If there are *no constraints* on the pattern type, we
74 -- revert to good old H-M typechecking, making
75 -- the type of the binder into an *ordinary*
76 -- type variable. We find out if there are no constraints
77 -- by seeing if we are given an "open hole" as our info.
78 -- What we are trying to avoid here is giving a binder
79 -- a type that is a 'hole'. The only place holes should
80 -- appear is as an argument to tcPat and tcExpr/tcMonoExpr.
82 returnM (idCoercion, mkLocalId binder_name pat_ty')
86 %************************************************************************
88 \subsection{Typechecking patterns}
90 %************************************************************************
93 tcPat :: BinderChecker
96 -> Expected TcSigmaType -- Expected type derived from the context
97 -- In the case of a function with a rank-2 signature,
98 -- this type might be a forall type.
101 Bag TcTyVar, -- TyVars bound by the pattern
102 -- These are just the existentially-bound ones.
103 -- Any tyvars bound by *type signatures* in the
104 -- patterns are brought into scope before we begin.
105 Bag (Name, TcId), -- Ids bound by the pattern, along with the Name under
106 -- which it occurs in the pattern
107 -- The two aren't the same because we conjure up a new
108 -- local name for each variable.
109 [Inst]) -- Dicts or methods [see below] bound by the pattern
110 -- from existential constructor patterns
111 tcPat tc_bndr (L span pat) exp_ty
113 do { (pat', tvs, ids, lie) <- tc_pat tc_bndr pat exp_ty
114 ; return (L span pat', tvs, ids, lie) }
118 %************************************************************************
120 \subsection{Variables, wildcards, lazy pats, as-pats}
122 %************************************************************************
125 tc_pat tc_bndr pat@(TypePat ty) pat_ty
126 = failWithTc (badTypePat pat)
128 tc_pat tc_bndr (VarPat name) pat_ty
129 = tc_bndr name pat_ty `thenM` \ (co_fn, bndr_id) ->
130 returnM (co_fn <$> VarPat bndr_id,
131 emptyBag, unitBag (name, bndr_id), [])
133 tc_pat tc_bndr (LazyPat pat) pat_ty
134 = tcPat tc_bndr pat pat_ty `thenM` \ (pat', tvs, ids, lie_avail) ->
135 returnM (LazyPat pat', tvs, ids, lie_avail)
137 tc_pat tc_bndr pat_in@(AsPat (L nm_loc name) pat) pat_ty
138 = addSrcSpan nm_loc (tc_bndr name pat_ty) `thenM` \ (co_fn, bndr_id) ->
139 tcPat tc_bndr pat (Check (idType bndr_id)) `thenM` \ (pat', tvs, ids, lie_avail) ->
141 -- \ (y@(x::forall a. a->a)) = e
142 -- we'll fail. The as-pattern infers a monotype for 'y', which then
143 -- fails to unify with the polymorphic type for 'x'. This could be
144 -- fixed, but only with a bit more work.
145 returnM (co_fn <$> (AsPat (L nm_loc bndr_id) pat'),
146 tvs, (name, bndr_id) `consBag` ids, lie_avail)
148 tc_pat tc_bndr (WildPat _) pat_ty
149 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
150 -- We might have an incoming 'hole' type variable; no annotation
151 -- so zap it to a type. Rather like tcMonoPatBndr.
152 returnM (WildPat pat_ty', emptyBag, emptyBag, [])
154 tc_pat tc_bndr (ParPat parend_pat) pat_ty
155 -- Leave the parens in, so that warnings from the
156 -- desugarer have parens in them
157 = tcPat tc_bndr parend_pat pat_ty `thenM` \ (pat', tvs, ids, lie_avail) ->
158 returnM (ParPat pat', tvs, ids, lie_avail)
160 tc_pat tc_bndr pat_in@(SigPatIn pat sig) pat_ty
161 = addErrCtxt (patCtxt pat_in) $
162 tcHsSigType PatSigCtxt sig `thenM` \ sig_ty ->
163 tcSubPat sig_ty pat_ty `thenM` \ co_fn ->
164 tcPat tc_bndr pat (Check sig_ty) `thenM` \ (pat', tvs, ids, lie_avail) ->
165 returnM (co_fn <$> unLoc pat', tvs, ids, lie_avail)
169 %************************************************************************
171 \subsection{Explicit lists, parallel arrays, and tuples}
173 %************************************************************************
176 tc_pat tc_bndr pat_in@(ListPat pats _) pat_ty
177 = addErrCtxt (patCtxt pat_in) $
178 zapToListTy pat_ty `thenM` \ elem_ty ->
179 tcPats tc_bndr pats (repeat elem_ty) `thenM` \ (pats', tvs, ids, lie_avail) ->
180 returnM (ListPat pats' elem_ty, tvs, ids, lie_avail)
182 tc_pat tc_bndr pat_in@(PArrPat pats _) pat_ty
183 = addErrCtxt (patCtxt pat_in) $
184 zapToPArrTy pat_ty `thenM` \ elem_ty ->
185 tcPats tc_bndr pats (repeat elem_ty) `thenM` \ (pats', tvs, ids, lie_avail) ->
186 returnM (PArrPat pats' elem_ty, tvs, ids, lie_avail)
188 tc_pat tc_bndr pat_in@(TuplePat pats boxity) pat_ty
189 = addErrCtxt (patCtxt pat_in) $
191 zapToTupleTy boxity arity pat_ty `thenM` \ arg_tys ->
192 tcPats tc_bndr pats arg_tys `thenM` \ (pats', tvs, ids, lie_avail) ->
194 -- possibly do the "make all tuple-pats irrefutable" test:
196 unmangled_result = TuplePat pats' boxity
198 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
199 -- so that we can experiment with lazy tuple-matching.
200 -- This is a pretty odd place to make the switch, but
201 -- it was easy to do.
203 possibly_mangled_result
204 | opt_IrrefutableTuples && isBoxed boxity = LazyPat (noLoc unmangled_result)
205 | otherwise = unmangled_result
207 returnM (possibly_mangled_result, tvs, ids, lie_avail)
213 %************************************************************************
215 \subsection{Other constructors}
218 %************************************************************************
221 tc_pat tc_bndr pat_in@(ConPatIn con_name arg_pats) pat_ty
222 = addErrCtxt (patCtxt pat_in) $
224 -- Check that it's a constructor, and instantiate it
225 tcLookupLocatedDataCon con_name `thenM` \ data_con ->
226 tcInstDataCon (PatOrigin pat_in) data_con `thenM` \ (_, ex_dicts1, arg_tys, con_res_ty, ex_tvs) ->
228 -- Check overall type matches.
229 -- The pat_ty might be a for-all type, in which
230 -- case we must instantiate to match
231 tcSubPat con_res_ty pat_ty `thenM` \ co_fn ->
233 -- Check the argument patterns
234 tcConStuff tc_bndr data_con arg_pats arg_tys `thenM` \ (arg_pats', arg_tvs, arg_ids, ex_dicts2) ->
236 returnM (co_fn <$> ConPatOut data_con arg_pats' con_res_ty ex_tvs (map instToId ex_dicts1),
237 listToBag ex_tvs `unionBags` arg_tvs,
239 ex_dicts1 ++ ex_dicts2)
243 %************************************************************************
245 \subsection{Literals}
247 %************************************************************************
250 tc_pat tc_bndr pat@(LitPat lit@(HsString _)) pat_ty
251 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
252 unifyTauTy pat_ty' stringTy `thenM_`
253 tcLookupId eqStringName `thenM` \ eq_id ->
254 returnM (NPatOut lit stringTy (nlHsVar eq_id `HsApp` nlHsLit lit),
255 emptyBag, emptyBag, [])
257 tc_pat tc_bndr (LitPat simple_lit) pat_ty
258 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
259 unifyTauTy pat_ty' (hsLitType simple_lit) `thenM_`
260 returnM (LitPat simple_lit, emptyBag, emptyBag, [])
262 tc_pat tc_bndr pat@(NPatIn over_lit mb_neg) pat_ty
263 = zapExpectedType pat_ty `thenM` \ pat_ty' ->
264 newOverloadedLit origin over_lit pat_ty' `thenM` \ pos_lit_expr ->
265 newMethodFromName origin pat_ty' eqName `thenM` \ eq ->
267 Nothing -> returnM pos_lit_expr -- Positive literal
268 Just neg -> -- Negative literal
269 -- The 'negate' is re-mappable syntax
270 tcSyntaxName origin pat_ty' (negateName, noLoc (HsVar neg)) `thenM` \ (_, neg_expr) ->
271 returnM (mkHsApp neg_expr pos_lit_expr)
272 ) `thenM` \ lit_expr ->
275 -- The literal in an NPatIn is always positive...
276 -- But in NPat, the literal is used to find identical patterns
277 -- so we must negate the literal when necessary!
278 lit' = case (over_lit, mb_neg) of
279 (HsIntegral i _, Nothing) -> HsInteger i pat_ty'
280 (HsIntegral i _, Just _) -> HsInteger (-i) pat_ty'
281 (HsFractional f _, Nothing) -> HsRat f pat_ty'
282 (HsFractional f _, Just _) -> HsRat (-f) pat_ty'
284 returnM (NPatOut lit' pat_ty' (HsApp (nlHsVar eq) lit_expr),
285 emptyBag, emptyBag, [])
287 origin = PatOrigin pat
290 %************************************************************************
292 \subsection{n+k patterns}
294 %************************************************************************
297 tc_pat tc_bndr pat@(NPlusKPatIn (L nm_loc name) lit@(HsIntegral i _) minus_name) pat_ty
298 = addSrcSpan nm_loc (tc_bndr name pat_ty) `thenM` \ (co_fn, bndr_id) ->
300 pat_ty' = idType bndr_id
302 newOverloadedLit origin lit pat_ty' `thenM` \ over_lit_expr ->
303 newMethodFromName origin pat_ty' geName `thenM` \ ge ->
305 -- The '-' part is re-mappable syntax
306 tcSyntaxName origin pat_ty' (minusName, noLoc (HsVar minus_name)) `thenM` \ (_, minus_expr) ->
308 -- The Report says that n+k patterns must be in Integral
309 -- We may not want this when using re-mappable syntax, though (ToDo?)
310 tcLookupClass integralClassName `thenM` \ icls ->
311 newDicts origin [mkClassPred icls [pat_ty']] `thenM` \ dicts ->
312 extendLIEs dicts `thenM_`
314 returnM (NPlusKPatOut (L nm_loc bndr_id) i
315 (SectionR (nlHsVar ge) over_lit_expr)
316 (SectionR minus_expr over_lit_expr),
317 emptyBag, unitBag (name, bndr_id), [])
319 origin = PatOrigin pat
323 %************************************************************************
325 \subsection{Lists of patterns}
327 %************************************************************************
332 tcPats :: BinderChecker -- How to deal with variables
333 -> [LPat Name] -> [TcType] -- Excess 'expected types' discarded
336 Bag (Name, TcId), -- Ids bound by the pattern
337 [Inst]) -- Dicts bound by the pattern
339 tcPats tc_bndr [] tys = returnM ([], emptyBag, emptyBag, [])
341 tcPats tc_bndr (pat:pats) (ty:tys)
342 = tcPat tc_bndr pat (Check ty) `thenM` \ (pat', tvs1, ids1, lie_avail1) ->
343 tcPats tc_bndr pats tys `thenM` \ (pats', tvs2, ids2, lie_avail2) ->
346 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
347 lie_avail1 ++ lie_avail2)
351 %************************************************************************
353 \subsection{Constructor arguments}
355 %************************************************************************
358 tcConStuff tc_bndr data_con (PrefixCon arg_pats) arg_tys
359 = -- Check correct arity
360 checkTc (con_arity == no_of_args)
361 (arityErr "Constructor" data_con con_arity no_of_args) `thenM_`
364 tcPats tc_bndr arg_pats arg_tys `thenM` \ (arg_pats', tvs, ids, lie_avail) ->
366 returnM (PrefixCon arg_pats', tvs, ids, lie_avail)
368 con_arity = dataConSourceArity data_con
369 no_of_args = length arg_pats
371 tcConStuff tc_bndr data_con (InfixCon p1 p2) arg_tys
372 = -- Check correct arity
373 checkTc (con_arity == 2)
374 (arityErr "Constructor" data_con con_arity 2) `thenM_`
377 tcPat tc_bndr p1 (Check ty1) `thenM` \ (p1', tvs1, ids1, lie_avail1) ->
378 tcPat tc_bndr p2 (Check ty2) `thenM` \ (p2', tvs2, ids2, lie_avail2) ->
380 returnM (InfixCon p1' p2',
381 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
382 lie_avail1 ++ lie_avail2)
384 con_arity = dataConSourceArity data_con
387 tcConStuff tc_bndr data_con (RecCon rpats) arg_tys
388 = -- Check the fields
389 tc_fields field_tys rpats `thenM` \ (rpats', tvs, ids, lie_avail) ->
390 returnM (RecCon rpats', tvs, ids, lie_avail)
393 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con)) arg_tys
394 -- Don't use zipEqual! If the constructor isn't really a record, then
395 -- dataConFieldLabels will be empty (and each field in the pattern
396 -- will generate an error below).
398 tc_fields field_tys []
399 = returnM ([], emptyBag, emptyBag, [])
401 tc_fields field_tys ((L lbl_loc field_label, rhs_pat) : rpats)
402 = tc_fields field_tys rpats `thenM` \ (rpats', tvs1, ids1, lie_avail1) ->
404 (case [ty | (f,ty) <- field_tys, f == field_label] of
406 -- No matching field; chances are this field label comes from some
407 -- other record type (or maybe none). As well as reporting an
408 -- error we still want to typecheck the pattern, principally to
409 -- make sure that all the variables it binds are put into the
410 -- environment, else the type checker crashes later:
411 -- f (R { foo = (a,b) }) = a+b
412 -- If foo isn't one of R's fields, we don't want to crash when
413 -- typechecking the "a+b".
414 [] -> addErrTc (badFieldCon data_con field_label) `thenM_`
415 newTyVarTy liftedTypeKind `thenM` \ bogus_ty ->
416 returnM (error "Bogus selector Id", bogus_ty)
418 -- The normal case, when the field comes from the right constructor
420 ASSERT( null extras )
421 addSrcSpan lbl_loc (tcLookupId field_label) `thenM` \ sel_id ->
422 returnM (sel_id, pat_ty)
423 ) `thenM` \ (sel_id, pat_ty) ->
425 tcPat tc_bndr rhs_pat (Check pat_ty) `thenM` \ (rhs_pat', tvs2, ids2, lie_avail2) ->
427 returnM ((L lbl_loc sel_id, rhs_pat') : rpats',
428 tvs1 `unionBags` tvs2,
429 ids1 `unionBags` ids2,
430 lie_avail1 ++ lie_avail2)
434 %************************************************************************
436 \subsection{Subsumption}
438 %************************************************************************
441 f :: (forall a. a->a) -> Int -> Int
442 f (g::Int->Int) y = g y
443 This is ok: the type signature allows fewer callers than
444 the (more general) signature f :: (Int->Int) -> Int -> Int
445 I.e. (forall a. a->a) <= Int -> Int
446 We end up translating this to:
447 f = \g' :: (forall a. a->a). let g = g' Int in g' y
449 tcSubPat does the work
450 sig_ty is the signature on the pattern itself
451 (Int->Int in the example)
452 expected_ty is the type passed inwards from the context
453 (forall a. a->a in the example)
456 tcSubPat :: TcSigmaType -> Expected TcSigmaType -> TcM PatCoFn
458 tcSubPat sig_ty exp_ty
459 = tcSubOff sig_ty exp_ty `thenM` \ co_fn ->
460 -- co_fn is a coercion on *expressions*, and we
461 -- need to make a coercion on *patterns*
462 if isIdCoercion co_fn then
465 newUnique `thenM` \ uniq ->
466 readExpectedType exp_ty `thenM` \ exp_ty' ->
468 arg_id = mkSysLocal FSLIT("sub") uniq exp_ty'
469 the_fn = DictLam [arg_id] (noLoc (co_fn <$> HsVar arg_id))
470 pat_co_fn p = SigPatOut (noLoc p) exp_ty' the_fn
472 returnM (mkCoercion pat_co_fn)
476 %************************************************************************
478 \subsection{Errors and contexts}
480 %************************************************************************
483 patCtxt pat = hang (ptext SLIT("When checking the pattern:"))
486 badFieldCon :: DataCon -> Name -> SDoc
487 badFieldCon con field
488 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
489 ptext SLIT("does not have field"), quotes (ppr field)]
491 polyPatSig :: TcType -> SDoc
493 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
496 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat