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, TyVarDetails(..), mkClassPred )
30 import Kind ( argTypeKind, 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, noLoc )
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 argTypeKind `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 argTypeKind `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 -- Note argTypeKind, so that
154 -- is rejected when f applied to an unboxed tuple
155 -- However, this means that
156 -- (case g x of _ -> ...)
157 -- is rejected g returns an unboxed tuple, which is perhpas
158 -- annoying. I suppose we could pass the context into tc_pat...
159 returnM (WildPat pat_ty', emptyBag, emptyBag, [])
161 tc_pat tc_bndr (ParPat parend_pat) pat_ty
162 -- Leave the parens in, so that warnings from the
163 -- desugarer have parens in them
164 = tcPat tc_bndr parend_pat pat_ty `thenM` \ (pat', tvs, ids, lie_avail) ->
165 returnM (ParPat pat', tvs, ids, lie_avail)
167 tc_pat tc_bndr pat_in@(SigPatIn pat sig) pat_ty
168 = addErrCtxt (patCtxt pat_in) $
169 tcHsSigType PatSigCtxt sig `thenM` \ sig_ty ->
170 tcSubPat sig_ty pat_ty `thenM` \ co_fn ->
171 tcPat tc_bndr pat (Check sig_ty) `thenM` \ (pat', tvs, ids, lie_avail) ->
172 returnM (co_fn <$> unLoc pat', tvs, ids, lie_avail)
176 %************************************************************************
178 \subsection{Explicit lists, parallel arrays, and tuples}
180 %************************************************************************
183 tc_pat tc_bndr pat_in@(ListPat pats _) pat_ty
184 = addErrCtxt (patCtxt pat_in) $
185 zapToListTy pat_ty `thenM` \ elem_ty ->
186 tcPats tc_bndr pats (repeat elem_ty) `thenM` \ (pats', tvs, ids, lie_avail) ->
187 returnM (ListPat pats' elem_ty, tvs, ids, lie_avail)
189 tc_pat tc_bndr pat_in@(PArrPat pats _) pat_ty
190 = addErrCtxt (patCtxt pat_in) $
191 zapToPArrTy pat_ty `thenM` \ elem_ty ->
192 tcPats tc_bndr pats (repeat elem_ty) `thenM` \ (pats', tvs, ids, lie_avail) ->
193 returnM (PArrPat pats' elem_ty, tvs, ids, lie_avail)
195 tc_pat tc_bndr pat_in@(TuplePat pats boxity) pat_ty
196 = addErrCtxt (patCtxt pat_in) $
198 zapToTupleTy boxity arity pat_ty `thenM` \ arg_tys ->
199 tcPats tc_bndr pats arg_tys `thenM` \ (pats', tvs, ids, lie_avail) ->
201 -- possibly do the "make all tuple-pats irrefutable" test:
203 unmangled_result = TuplePat pats' boxity
205 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
206 -- so that we can experiment with lazy tuple-matching.
207 -- This is a pretty odd place to make the switch, but
208 -- it was easy to do.
210 possibly_mangled_result
211 | opt_IrrefutableTuples && isBoxed boxity = LazyPat (noLoc unmangled_result)
212 | otherwise = unmangled_result
214 returnM (possibly_mangled_result, tvs, ids, lie_avail)
220 %************************************************************************
222 \subsection{Other constructors}
225 %************************************************************************
228 tc_pat tc_bndr pat_in@(ConPatIn con_name arg_pats) pat_ty
229 = addErrCtxt (patCtxt pat_in) $
231 -- Check that it's a constructor, and instantiate it
232 tcLookupLocatedDataCon con_name `thenM` \ data_con ->
233 tcInstDataCon (PatOrigin pat_in) ExistTv data_con `thenM` \ (_, ex_dicts1, arg_tys, con_res_ty, ex_tvs) ->
235 -- Check overall type matches.
236 -- The pat_ty might be a for-all type, in which
237 -- case we must instantiate to match
238 tcSubPat con_res_ty pat_ty `thenM` \ co_fn ->
240 -- Check the argument patterns
241 tcConStuff tc_bndr data_con arg_pats arg_tys `thenM` \ (arg_pats', arg_tvs, arg_ids, ex_dicts2) ->
243 returnM (co_fn <$> ConPatOut data_con arg_pats' con_res_ty ex_tvs (map instToId ex_dicts1),
244 listToBag ex_tvs `unionBags` arg_tvs,
246 ex_dicts1 ++ ex_dicts2)
250 %************************************************************************
252 \subsection{Literals}
254 %************************************************************************
257 tc_pat tc_bndr pat@(LitPat lit@(HsString _)) pat_ty
258 = zapExpectedType pat_ty liftedTypeKind `thenM` \ pat_ty' ->
259 unifyTauTy pat_ty' stringTy `thenM_`
260 tcLookupId eqStringName `thenM` \ eq_id ->
261 returnM (NPatOut lit stringTy (nlHsVar eq_id `HsApp` nlHsLit lit),
262 emptyBag, emptyBag, [])
264 tc_pat tc_bndr (LitPat simple_lit) pat_ty
265 = zapExpectedType pat_ty argTypeKind `thenM` \ pat_ty' ->
266 unifyTauTy pat_ty' (hsLitType simple_lit) `thenM_`
267 returnM (LitPat simple_lit, emptyBag, emptyBag, [])
269 tc_pat tc_bndr pat@(NPatIn over_lit mb_neg) pat_ty
270 = zapExpectedType pat_ty liftedTypeKind `thenM` \ pat_ty' ->
271 newOverloadedLit origin over_lit pat_ty' `thenM` \ pos_lit_expr ->
272 newMethodFromName origin pat_ty' eqName `thenM` \ eq ->
274 Nothing -> returnM pos_lit_expr -- Positive literal
275 Just neg -> -- Negative literal
276 -- The 'negate' is re-mappable syntax
277 tcSyntaxName origin pat_ty' (negateName, HsVar neg) `thenM` \ (_, neg_expr) ->
278 returnM (mkHsApp (noLoc neg_expr) pos_lit_expr)
279 ) `thenM` \ lit_expr ->
282 -- The literal in an NPatIn is always positive...
283 -- But in NPat, the literal is used to find identical patterns
284 -- so we must negate the literal when necessary!
285 lit' = case (over_lit, mb_neg) of
286 (HsIntegral i _, Nothing) -> HsInteger i pat_ty'
287 (HsIntegral i _, Just _) -> HsInteger (-i) pat_ty'
288 (HsFractional f _, Nothing) -> HsRat f pat_ty'
289 (HsFractional f _, Just _) -> HsRat (-f) pat_ty'
291 returnM (NPatOut lit' pat_ty' (HsApp (nlHsVar eq) lit_expr),
292 emptyBag, emptyBag, [])
294 origin = PatOrigin pat
297 %************************************************************************
299 \subsection{n+k patterns}
301 %************************************************************************
304 tc_pat tc_bndr pat@(NPlusKPatIn (L nm_loc name) lit@(HsIntegral i _) minus_name) pat_ty
305 = addSrcSpan nm_loc (tc_bndr name pat_ty) `thenM` \ (co_fn, bndr_id) ->
307 pat_ty' = idType bndr_id
309 newOverloadedLit origin lit pat_ty' `thenM` \ over_lit_expr ->
310 newMethodFromName origin pat_ty' geName `thenM` \ ge ->
312 -- The '-' part is re-mappable syntax
313 tcSyntaxName origin pat_ty' (minusName, HsVar minus_name) `thenM` \ (_, minus_expr) ->
315 -- The Report says that n+k patterns must be in Integral
316 -- We may not want this when using re-mappable syntax, though (ToDo?)
317 tcLookupClass integralClassName `thenM` \ icls ->
318 newDicts origin [mkClassPred icls [pat_ty']] `thenM` \ dicts ->
319 extendLIEs dicts `thenM_`
321 returnM (NPlusKPatOut (L nm_loc bndr_id) i
322 (SectionR (nlHsVar ge) over_lit_expr)
323 (SectionR (noLoc minus_expr) over_lit_expr),
324 emptyBag, unitBag (name, bndr_id), [])
326 origin = PatOrigin pat
330 %************************************************************************
332 \subsection{Lists of patterns}
334 %************************************************************************
339 tcPats :: BinderChecker -- How to deal with variables
340 -> [LPat Name] -> [TcType] -- Excess 'expected types' discarded
343 Bag (Name, TcId), -- Ids bound by the pattern
344 [Inst]) -- Dicts bound by the pattern
346 tcPats tc_bndr [] tys = returnM ([], emptyBag, emptyBag, [])
348 tcPats tc_bndr (pat:pats) (ty:tys)
349 = tcPat tc_bndr pat (Check ty) `thenM` \ (pat', tvs1, ids1, lie_avail1) ->
350 tcPats tc_bndr pats tys `thenM` \ (pats', tvs2, ids2, lie_avail2) ->
353 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
354 lie_avail1 ++ lie_avail2)
358 %************************************************************************
360 \subsection{Constructor arguments}
362 %************************************************************************
365 tcConStuff tc_bndr data_con (PrefixCon arg_pats) arg_tys
366 = -- Check correct arity
367 checkTc (con_arity == no_of_args)
368 (arityErr "Constructor" data_con con_arity no_of_args) `thenM_`
371 tcPats tc_bndr arg_pats arg_tys `thenM` \ (arg_pats', tvs, ids, lie_avail) ->
373 returnM (PrefixCon arg_pats', tvs, ids, lie_avail)
375 con_arity = dataConSourceArity data_con
376 no_of_args = length arg_pats
378 tcConStuff tc_bndr data_con (InfixCon p1 p2) arg_tys
379 = -- Check correct arity
380 checkTc (con_arity == 2)
381 (arityErr "Constructor" data_con con_arity 2) `thenM_`
384 tcPat tc_bndr p1 (Check ty1) `thenM` \ (p1', tvs1, ids1, lie_avail1) ->
385 tcPat tc_bndr p2 (Check ty2) `thenM` \ (p2', tvs2, ids2, lie_avail2) ->
387 returnM (InfixCon p1' p2',
388 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
389 lie_avail1 ++ lie_avail2)
391 con_arity = dataConSourceArity data_con
394 tcConStuff tc_bndr data_con (RecCon rpats) arg_tys
395 = -- Check the fields
396 tc_fields field_tys rpats `thenM` \ (rpats', tvs, ids, lie_avail) ->
397 returnM (RecCon rpats', tvs, ids, lie_avail)
400 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con)) arg_tys
401 -- Don't use zipEqual! If the constructor isn't really a record, then
402 -- dataConFieldLabels will be empty (and each field in the pattern
403 -- will generate an error below).
405 tc_fields field_tys []
406 = returnM ([], emptyBag, emptyBag, [])
408 tc_fields field_tys ((L lbl_loc field_label, rhs_pat) : rpats)
409 = tc_fields field_tys rpats `thenM` \ (rpats', tvs1, ids1, lie_avail1) ->
411 (case [ty | (f,ty) <- field_tys, f == field_label] of
413 -- No matching field; chances are this field label comes from some
414 -- other record type (or maybe none). As well as reporting an
415 -- error we still want to typecheck the pattern, principally to
416 -- make sure that all the variables it binds are put into the
417 -- environment, else the type checker crashes later:
418 -- f (R { foo = (a,b) }) = a+b
419 -- If foo isn't one of R's fields, we don't want to crash when
420 -- typechecking the "a+b".
421 [] -> addErrTc (badFieldCon data_con field_label) `thenM_`
422 newTyVarTy liftedTypeKind `thenM` \ bogus_ty ->
423 returnM (error "Bogus selector Id", bogus_ty)
425 -- The normal case, when the field comes from the right constructor
427 ASSERT( null extras )
428 addSrcSpan lbl_loc (tcLookupId field_label) `thenM` \ sel_id ->
429 returnM (sel_id, pat_ty)
430 ) `thenM` \ (sel_id, pat_ty) ->
432 tcPat tc_bndr rhs_pat (Check pat_ty) `thenM` \ (rhs_pat', tvs2, ids2, lie_avail2) ->
434 returnM ((L lbl_loc sel_id, rhs_pat') : rpats',
435 tvs1 `unionBags` tvs2,
436 ids1 `unionBags` ids2,
437 lie_avail1 ++ lie_avail2)
441 %************************************************************************
443 \subsection{Subsumption}
445 %************************************************************************
448 f :: (forall a. a->a) -> Int -> Int
449 f (g::Int->Int) y = g y
450 This is ok: the type signature allows fewer callers than
451 the (more general) signature f :: (Int->Int) -> Int -> Int
452 I.e. (forall a. a->a) <= Int -> Int
453 We end up translating this to:
454 f = \g' :: (forall a. a->a). let g = g' Int in g' y
456 tcSubPat does the work
457 sig_ty is the signature on the pattern itself
458 (Int->Int in the example)
459 expected_ty is the type passed inwards from the context
460 (forall a. a->a in the example)
463 tcSubPat :: TcSigmaType -> Expected TcSigmaType -> TcM PatCoFn
465 tcSubPat sig_ty exp_ty
466 = tcSubOff sig_ty exp_ty `thenM` \ co_fn ->
467 -- co_fn is a coercion on *expressions*, and we
468 -- need to make a coercion on *patterns*
469 if isIdCoercion co_fn then
472 newUnique `thenM` \ uniq ->
473 readExpectedType exp_ty `thenM` \ exp_ty' ->
475 arg_id = mkSysLocal FSLIT("sub") uniq exp_ty'
476 the_fn = DictLam [arg_id] (noLoc (co_fn <$> HsVar arg_id))
477 pat_co_fn p = SigPatOut (noLoc p) exp_ty' the_fn
479 returnM (mkCoercion pat_co_fn)
483 %************************************************************************
485 \subsection{Errors and contexts}
487 %************************************************************************
490 patCtxt pat = hang (ptext SLIT("When checking the pattern:"))
493 badFieldCon :: DataCon -> Name -> SDoc
494 badFieldCon con field
495 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
496 ptext SLIT("does not have field"), quotes (ppr field)]
498 polyPatSig :: TcType -> SDoc
500 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
503 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat