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 ( InPat(..), OutPat(..), HsLit(..), HsOverLit(..), HsExpr(..) )
14 import RnHsSyn ( RenamedPat )
15 import TcHsSyn ( TcPat, TcId, simpleHsLitTy )
18 import Inst ( InstOrigin(..),
19 emptyLIE, plusLIE, LIE, mkLIE, unitLIE, instToId, isEmptyLIE,
20 newMethod, newMethodFromName, newOverloadedLit, newDicts,
21 tcInstDataCon, tcSyntaxName
23 import Id ( mkLocalId, mkSysLocal )
25 import FieldLabel ( fieldLabelName )
26 import TcEnv ( tcLookupClass, tcLookupDataCon, tcLookupGlobalId, tcLookupId )
27 import TcMType ( newTyVarTy, zapToType )
28 import TcType ( TcType, TcTyVar, TcSigmaType,
29 mkClassPred, liftedTypeKind )
30 import TcUnify ( tcSubOff, TcHoleType,
31 unifyTauTy, unifyListTy, unifyPArrTy, unifyTupleTy,
32 mkCoercion, idCoercion, isIdCoercion,
34 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
36 import TysWiredIn ( stringTy )
37 import CmdLineOpts ( opt_IrrefutableTuples )
38 import DataCon ( dataConFieldLabels, dataConSourceArity )
39 import PrelNames ( eqStringName, eqName, geName, minusName, cCallableClassName )
40 import BasicTypes ( isBoxed )
47 %************************************************************************
49 \subsection{Variable patterns}
51 %************************************************************************
54 type BinderChecker = Name -> TcSigmaType -> TcM (PatCoFn, LIE, 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 = zapToType pat_ty `thenNF_Tc` \ 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 returnTc (idCoercion, emptyLIE, mkLocalId binder_name pat_ty')
85 %************************************************************************
87 \subsection{Typechecking patterns}
89 %************************************************************************
92 tcPat :: BinderChecker
95 -> TcHoleType -- 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 LIE, -- Required by n+k and literal pats
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 LIE) -- Dicts or methods [see below] bound by the pattern
110 -- from existential constructor patterns
114 %************************************************************************
116 \subsection{Variables, wildcards, lazy pats, as-pats}
118 %************************************************************************
121 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
122 = failWithTc (badTypePat pat)
124 tcPat tc_bndr (VarPatIn name) pat_ty
125 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie_req, bndr_id) ->
126 returnTc (co_fn <$> VarPat bndr_id, lie_req,
127 emptyBag, unitBag (name, bndr_id), emptyLIE)
129 tcPat tc_bndr (LazyPatIn pat) pat_ty
130 = tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
131 returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
133 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
134 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie_req1, bndr_id) ->
135 tcPat tc_bndr pat pat_ty `thenTc` \ (pat', lie_req2, tvs, ids, lie_avail) ->
136 returnTc (co_fn <$> (AsPat bndr_id pat'), lie_req1 `plusLIE` lie_req2,
137 tvs, (name, bndr_id) `consBag` ids, lie_avail)
139 tcPat tc_bndr WildPatIn pat_ty
140 = zapToType pat_ty `thenNF_Tc` \ pat_ty' ->
141 -- We might have an incoming 'hole' type variable; no annotation
142 -- so zap it to a type. Rather like tcMonoPatBndr.
143 returnTc (WildPat pat_ty', emptyLIE, emptyBag, emptyBag, emptyLIE)
145 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
146 = tcPat tc_bndr parend_pat pat_ty
148 tcPat tc_bndr pat_in@(SigPatIn pat sig) pat_ty
149 = tcAddErrCtxt (patCtxt pat_in) $
150 tcHsSigType PatSigCtxt sig `thenTc` \ sig_ty ->
151 tcSubPat sig_ty pat_ty `thenTc` \ (co_fn, lie_sig) ->
152 tcPat tc_bndr pat sig_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
153 returnTc (co_fn <$> pat', lie_req `plusLIE` lie_sig, tvs, ids, lie_avail)
157 %************************************************************************
159 \subsection{Explicit lists, parallel arrays, and tuples}
161 %************************************************************************
164 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
165 = tcAddErrCtxt (patCtxt pat_in) $
166 unifyListTy pat_ty `thenTc` \ elem_ty ->
167 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
168 returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
170 tcPat tc_bndr pat_in@(PArrPatIn pats) pat_ty
171 = tcAddErrCtxt (patCtxt pat_in) $
172 unifyPArrTy pat_ty `thenTc` \ elem_ty ->
173 tcPats tc_bndr pats (repeat elem_ty) `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
174 returnTc (PArrPat elem_ty pats', lie_req, tvs, ids, lie_avail)
176 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
177 = tcAddErrCtxt (patCtxt pat_in) $
179 unifyTupleTy boxity arity pat_ty `thenTc` \ arg_tys ->
180 tcPats tc_bndr pats arg_tys `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
182 -- possibly do the "make all tuple-pats irrefutable" test:
184 unmangled_result = TuplePat pats' boxity
186 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
187 -- so that we can experiment with lazy tuple-matching.
188 -- This is a pretty odd place to make the switch, but
189 -- it was easy to do.
191 possibly_mangled_result
192 | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
193 | otherwise = unmangled_result
195 returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
201 %************************************************************************
203 \subsection{Other constructors}
206 %************************************************************************
209 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
210 = tcConPat tc_bndr pat name arg_pats pat_ty
212 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
213 = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
217 %************************************************************************
221 %************************************************************************
224 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
225 = tcAddErrCtxt (patCtxt pat) $
227 -- Check the constructor itself
228 tcConstructor pat name `thenTc` \ (data_con, lie_req1, ex_tvs, ex_dicts, lie_avail1, arg_tys, con_res_ty) ->
230 -- Check overall type matches (c.f. tcConPat)
231 tcSubPat con_res_ty pat_ty `thenTc` \ (co_fn, lie_req2) ->
233 -- Don't use zipEqual! If the constructor isn't really a record, then
234 -- dataConFieldLabels will be empty (and each field in the pattern
235 -- will generate an error below).
236 field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
241 tc_fields field_tys rpats `thenTc` \ (rpats', lie_req3, tvs, ids, lie_avail2) ->
243 returnTc (RecPat data_con pat_ty ex_tvs ex_dicts rpats',
244 lie_req1 `plusLIE` lie_req2 `plusLIE` lie_req3,
245 listToBag ex_tvs `unionBags` tvs,
247 lie_avail1 `plusLIE` lie_avail2)
250 tc_fields field_tys []
251 = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
253 tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
254 = tc_fields field_tys rpats `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
256 (case [ty | (f,ty) <- field_tys, f == field_label] of
258 -- No matching field; chances are this field label comes from some
259 -- other record type (or maybe none). As well as reporting an
260 -- error we still want to typecheck the pattern, principally to
261 -- make sure that all the variables it binds are put into the
262 -- environment, else the type checker crashes later:
263 -- f (R { foo = (a,b) }) = a+b
264 -- If foo isn't one of R's fields, we don't want to crash when
265 -- typechecking the "a+b".
266 [] -> addErrTc (badFieldCon name field_label) `thenNF_Tc_`
267 newTyVarTy liftedTypeKind `thenNF_Tc_`
268 returnTc (error "Bogus selector Id", pat_ty)
270 -- The normal case, when the field comes from the right constructor
272 ASSERT( null extras )
273 tcLookupGlobalId field_label `thenNF_Tc` \ sel_id ->
274 returnTc (sel_id, pat_ty)
275 ) `thenTc` \ (sel_id, pat_ty) ->
277 tcPat tc_bndr rhs_pat pat_ty `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
279 returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
280 lie_req1 `plusLIE` lie_req2,
281 tvs1 `unionBags` tvs2,
282 ids1 `unionBags` ids2,
283 lie_avail1 `plusLIE` lie_avail2)
286 %************************************************************************
288 \subsection{Literals}
290 %************************************************************************
293 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty
294 -- cf tcExpr on LitLits
295 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
296 newDicts (LitLitOrigin (unpackFS s))
297 [mkClassPred cCallableClass [pat_ty]] `thenNF_Tc` \ dicts ->
298 returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
300 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
301 = unifyTauTy pat_ty stringTy `thenTc_`
302 tcLookupGlobalId eqStringName `thenNF_Tc` \ eq_id ->
303 returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit),
304 emptyLIE, emptyBag, emptyBag, emptyLIE)
306 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
307 = unifyTauTy pat_ty (simpleHsLitTy simple_lit) `thenTc_`
308 returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
310 tcPat tc_bndr pat@(NPatIn over_lit mb_neg) pat_ty
311 = newOverloadedLit origin over_lit pat_ty `thenNF_Tc` \ (pos_lit_expr, lie1) ->
312 newMethodFromName origin pat_ty eqName `thenNF_Tc` \ eq ->
314 Nothing -> returnNF_Tc (pos_lit_expr, emptyLIE) -- Positive literal
315 Just neg -> -- Negative literal
316 -- The 'negate' is re-mappable syntax
317 tcLookupId neg `thenNF_Tc` \ neg_sel_id ->
318 newMethod origin neg_sel_id [pat_ty] `thenNF_Tc` \ neg ->
319 returnNF_Tc (HsApp (HsVar (instToId neg)) pos_lit_expr, unitLIE neg)
320 ) `thenNF_Tc` \ (lit_expr, lie2) ->
322 returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) lit_expr),
323 lie1 `plusLIE` lie2 `plusLIE` unitLIE eq,
324 emptyBag, emptyBag, emptyLIE)
326 origin = PatOrigin pat
328 -- The literal in an NPatIn is always positive...
329 -- But in NPat, the literal is used to find identical patterns
330 -- so we must negate the literal when necessary!
331 lit' = case (over_lit, mb_neg) of
332 (HsIntegral i _, Nothing) -> HsInteger i
333 (HsIntegral i _, Just _) -> HsInteger (-i)
334 (HsFractional f _, Nothing) -> HsRat f pat_ty
335 (HsFractional f _, Just _) -> HsRat (-f) pat_ty
338 %************************************************************************
340 \subsection{n+k patterns}
342 %************************************************************************
345 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
346 = tc_bndr name pat_ty `thenTc` \ (co_fn, lie1, bndr_id) ->
347 newOverloadedLit origin lit pat_ty `thenNF_Tc` \ (over_lit_expr, lie2) ->
348 newMethodFromName origin pat_ty geName `thenNF_Tc` \ ge ->
350 -- The '-' part is re-mappable syntax
351 tcGetInstLoc origin `thenNF_Tc` \ loc ->
352 tcSyntaxName loc pat_ty minusName minus_name `thenTc` \ (minus_expr, minus_lie, _) ->
354 returnTc (NPlusKPat bndr_id i pat_ty
355 (SectionR (HsVar (instToId ge)) over_lit_expr)
356 (SectionR minus_expr over_lit_expr),
357 lie1 `plusLIE` lie2 `plusLIE` minus_lie `plusLIE` unitLIE ge,
358 emptyBag, unitBag (name, bndr_id), emptyLIE)
360 origin = PatOrigin pat
363 %************************************************************************
365 \subsection{Lists of patterns}
367 %************************************************************************
372 tcPats :: BinderChecker -- How to deal with variables
373 -> [RenamedPat] -> [TcType] -- Excess 'expected types' discarded
375 LIE, -- Required by n+k and literal pats
377 Bag (Name, TcId), -- Ids bound by the pattern
378 LIE) -- Dicts bound by the pattern
380 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
382 tcPats tc_bndr (ty:tys) (pat:pats)
383 = tcPat tc_bndr ty pat `thenTc` \ (pat', lie_req1, tvs1, ids1, lie_avail1) ->
384 tcPats tc_bndr tys pats `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
386 returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
387 tvs1 `unionBags` tvs2, ids1 `unionBags` ids2,
388 lie_avail1 `plusLIE` lie_avail2)
391 ------------------------------------------------------
393 tcConstructor pat con_name
394 = -- Check that it's a constructor
395 tcLookupDataCon con_name `thenNF_Tc` \ data_con ->
398 tcInstDataCon (PatOrigin pat) data_con `thenNF_Tc` \ (_, ex_dicts, arg_tys, result_ty, lie_req, ex_lie, ex_tvs) ->
400 returnTc (data_con, lie_req, ex_tvs, ex_dicts, ex_lie, arg_tys, result_ty)
403 ------------------------------------------------------
405 tcConPat tc_bndr pat con_name arg_pats pat_ty
406 = tcAddErrCtxt (patCtxt pat) $
408 -- Check the constructor itself
409 tcConstructor pat con_name `thenTc` \ (data_con, lie_req1, ex_tvs, ex_dicts, lie_avail1, arg_tys, con_res_ty) ->
411 -- Check overall type matches.
412 -- The pat_ty might be a for-all type, in which
413 -- case we must instantiate to match
414 tcSubPat con_res_ty pat_ty `thenTc` \ (co_fn, lie_req2) ->
416 -- Check correct arity
418 con_arity = dataConSourceArity data_con
419 no_of_args = length arg_pats
421 checkTc (con_arity == no_of_args)
422 (arityErr "Constructor" data_con con_arity no_of_args) `thenTc_`
425 tcPats tc_bndr arg_pats arg_tys `thenTc` \ (arg_pats', lie_req3, tvs, ids, lie_avail2) ->
427 returnTc (co_fn <$> ConPat data_con pat_ty ex_tvs ex_dicts arg_pats',
428 lie_req1 `plusLIE` lie_req2 `plusLIE` lie_req3,
429 listToBag ex_tvs `unionBags` tvs,
431 lie_avail1 `plusLIE` lie_avail2)
435 %************************************************************************
437 \subsection{Subsumption}
439 %************************************************************************
442 f :: (forall a. a->a) -> Int -> Int
443 f (g::Int->Int) y = g y
444 This is ok: the type signature allows fewer callers than
445 the (more general) signature f :: (Int->Int) -> Int -> Int
446 I.e. (forall a. a->a) <= Int -> Int
447 We end up translating this to:
448 f = \g' :: (forall a. a->a). let g = g' Int in g' y
450 tcSubPat does the work
451 sig_ty is the signature on the pattern itself
452 (Int->Int in the example)
453 expected_ty is the type passed inwards from the context
454 (forall a. a->a in the example)
457 tcSubPat :: TcSigmaType -> TcHoleType -> TcM (PatCoFn, LIE)
459 tcSubPat sig_ty exp_ty
460 = tcSubOff sig_ty exp_ty `thenTc` \ (co_fn, lie) ->
461 -- co_fn is a coercion on *expressions*, and we
462 -- need to make a coercion on *patterns*
463 if isIdCoercion co_fn then
464 ASSERT( isEmptyLIE lie )
465 returnNF_Tc (idCoercion, emptyLIE)
467 tcGetUnique `thenNF_Tc` \ uniq ->
469 arg_id = mkSysLocal FSLIT("sub") uniq exp_ty
470 the_fn = DictLam [arg_id] (co_fn <$> HsVar arg_id)
471 pat_co_fn p = SigPat p exp_ty the_fn
473 returnNF_Tc (mkCoercion pat_co_fn, lie)
477 %************************************************************************
479 \subsection{Errors and contexts}
481 %************************************************************************
484 patCtxt pat = hang (ptext SLIT("When checking the pattern:"))
487 badFieldCon :: Name -> Name -> SDoc
488 badFieldCon con field
489 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
490 ptext SLIT("does not have field"), quotes (ppr field)]
492 polyPatSig :: TcType -> SDoc
494 = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
497 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat