[project @ 2003-06-24 07:58:18 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcPat.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcPat]{Typechecking patterns}
5
6 \begin{code}
7 module TcPat ( tcPat, tcMonoPatBndr, tcSubPat,
8                badFieldCon, polyPatSig
9   ) where
10
11 #include "HsVersions.h"
12
13 import HsSyn            ( Pat(..), HsConDetails(..), HsLit(..), HsOverLit(..), HsExpr(..) )
14 import RnHsSyn          ( RenamedPat )
15 import TcHsSyn          ( TcPat, TcId, hsLitType,
16                           mkCoercion, idCoercion, isIdCoercion,
17                           (<$>), PatCoFn )
18
19 import TcRnMonad
20 import Inst             ( InstOrigin(..),
21                           newMethodFromName, newOverloadedLit, newDicts,
22                           instToId, tcInstDataCon, tcSyntaxName
23                         )
24 import Id               ( idType, mkLocalId, mkSysLocal )
25 import Name             ( Name )
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 TcMonoType       ( tcHsSigType, UserTypeCtxt(..) )
34
35 import TysWiredIn       ( stringTy )
36 import CmdLineOpts      ( opt_IrrefutableTuples )
37 import DataCon          ( DataCon, dataConFieldLabels, dataConSourceArity )
38 import PrelNames        ( eqStringName, eqName, geName, negateName, minusName, 
39                           integralClassName, cCallableClassName )
40 import BasicTypes       ( isBoxed )
41 import Bag
42 import Outputable
43 import FastString
44 \end{code}
45
46
47 %************************************************************************
48 %*                                                                      *
49 \subsection{Variable patterns}
50 %*                                                                      *
51 %************************************************************************
52
53 \begin{code}
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
59
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.
64
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
69
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.
80
81     returnM (idCoercion, mkLocalId binder_name pat_ty')
82 \end{code}
83
84
85 %************************************************************************
86 %*                                                                      *
87 \subsection{Typechecking patterns}
88 %*                                                                      *
89 %************************************************************************
90
91 \begin{code}
92 tcPat :: BinderChecker
93       -> RenamedPat
94
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.
98
99       -> TcM (TcPat, 
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
110 \end{code}
111
112
113 %************************************************************************
114 %*                                                                      *
115 \subsection{Variables, wildcards, lazy pats, as-pats}
116 %*                                                                      *
117 %************************************************************************
118
119 \begin{code}
120 tcPat tc_bndr pat@(TypePat ty) pat_ty
121   = failWithTc (badTypePat pat)
122
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), [])
127
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)
131
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) ->
135         -- NB: if we have:
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)
142
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, [])
148
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)
154
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)
161 \end{code}
162
163
164 %************************************************************************
165 %*                                                                      *
166 \subsection{Explicit lists, parallel arrays, and tuples}
167 %*                                                                      *
168 %************************************************************************
169
170 \begin{code}
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)
176
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)
182
183 tcPat tc_bndr pat_in@(TuplePat pats boxity) pat_ty
184   = addErrCtxt (patCtxt pat_in) $
185
186     zapToTupleTy boxity arity pat_ty            `thenM` \ arg_tys ->
187     tcPats tc_bndr pats arg_tys                 `thenM` \ (pats', tvs, ids, lie_avail) ->
188
189         -- possibly do the "make all tuple-pats irrefutable" test:
190     let
191         unmangled_result = TuplePat pats' boxity
192
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.
197
198         possibly_mangled_result
199           | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
200           | otherwise                               = unmangled_result
201     in
202     returnM (possibly_mangled_result, tvs, ids, lie_avail)
203   where
204     arity = length pats
205 \end{code}
206
207
208 %************************************************************************
209 %*                                                                      *
210 \subsection{Other constructors}
211 %*                                                                      *
212
213 %************************************************************************
214
215 \begin{code}
216 tcPat tc_bndr pat_in@(ConPatIn con_name arg_pats) pat_ty
217   = addErrCtxt (patCtxt pat_in)                 $
218
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) ->
222
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 ->
227
228         -- Check the argument patterns
229     tcConStuff tc_bndr data_con arg_pats arg_tys        `thenM` \ (arg_pats', arg_tvs, arg_ids, ex_dicts2) ->
230
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,
233               arg_ids,
234               ex_dicts1 ++ ex_dicts2)
235 \end{code}
236
237
238 %************************************************************************
239 %*                                                                      *
240 \subsection{Literals}
241 %*                                                                      *
242 %************************************************************************
243
244 \begin{code}
245 tcPat tc_bndr (LitPat lit@(HsLitLit s _)) pat_ty 
246         -- cf tcExpr on LitLits
247   = zapExpectedType pat_ty                              `thenM` \ pat_ty' ->
248     tcLookupClass cCallableClassName                    `thenM` \ cCallableClass ->
249     newDicts (LitLitOrigin (unpackFS s))
250              [mkClassPred cCallableClass [pat_ty']]     `thenM` \ dicts ->
251     extendLIEs dicts                                    `thenM_`
252     returnM (LitPat (HsLitLit s pat_ty'), emptyBag, emptyBag, [])
253
254 tcPat tc_bndr pat@(LitPat lit@(HsString _)) pat_ty
255   = zapExpectedType pat_ty              `thenM` \ pat_ty' ->
256     unifyTauTy pat_ty' stringTy         `thenM_` 
257     tcLookupId eqStringName             `thenM` \ eq_id ->
258     returnM (NPatOut lit stringTy (HsVar eq_id `HsApp` HsLit lit), 
259             emptyBag, emptyBag, [])
260
261 tcPat tc_bndr (LitPat simple_lit) pat_ty
262   = zapExpectedType pat_ty                      `thenM` \ pat_ty' ->
263     unifyTauTy pat_ty' (hsLitType simple_lit)   `thenM_` 
264     returnM (LitPat simple_lit, emptyBag, emptyBag, [])
265
266 tcPat tc_bndr pat@(NPatIn over_lit mb_neg) pat_ty
267   = zapExpectedType pat_ty                      `thenM` \ pat_ty' ->
268     newOverloadedLit origin over_lit pat_ty'    `thenM` \ pos_lit_expr ->
269     newMethodFromName origin pat_ty' eqName     `thenM` \ eq ->
270     (case mb_neg of
271         Nothing  -> returnM pos_lit_expr        -- Positive literal
272         Just neg ->     -- Negative literal
273                         -- The 'negate' is re-mappable syntax
274             tcSyntaxName origin pat_ty' (negateName, HsVar neg) `thenM` \ (_, neg_expr) ->
275             returnM (HsApp neg_expr pos_lit_expr)
276     )                                                           `thenM` \ lit_expr ->
277
278     let
279         -- The literal in an NPatIn is always positive...
280         -- But in NPat, the literal is used to find identical patterns
281         --      so we must negate the literal when necessary!
282         lit' = case (over_lit, mb_neg) of
283                  (HsIntegral i _,   Nothing) -> HsInteger i
284                  (HsIntegral i _,   Just _)  -> HsInteger (-i)
285                  (HsFractional f _, Nothing) -> HsRat f pat_ty'
286                  (HsFractional f _, Just _)  -> HsRat (-f) pat_ty'
287     in
288     returnM (NPatOut lit' pat_ty' (HsApp (HsVar eq) lit_expr),
289              emptyBag, emptyBag, [])
290   where
291     origin = PatOrigin pat
292 \end{code}
293
294 %************************************************************************
295 %*                                                                      *
296 \subsection{n+k patterns}
297 %*                                                                      *
298 %************************************************************************
299
300 \begin{code}
301 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
302   = tc_bndr name pat_ty                          `thenM` \ (co_fn, bndr_id) ->
303     let 
304         pat_ty' = idType bndr_id
305     in
306     newOverloadedLit origin lit pat_ty'          `thenM` \ over_lit_expr ->
307     newMethodFromName origin pat_ty' geName      `thenM` \ ge ->
308
309         -- The '-' part is re-mappable syntax
310     tcSyntaxName origin pat_ty' (minusName, HsVar minus_name)   `thenM` \ (_, minus_expr) ->
311
312         -- The Report says that n+k patterns must be in Integral
313         -- We may not want this when using re-mappable syntax, though (ToDo?)
314     tcLookupClass integralClassName                     `thenM` \ icls ->
315     newDicts origin [mkClassPred icls [pat_ty']]        `thenM` \ dicts ->
316     extendLIEs dicts                                    `thenM_`
317     
318     returnM (NPlusKPatOut bndr_id i 
319                            (SectionR (HsVar ge) over_lit_expr)
320                            (SectionR minus_expr over_lit_expr),
321               emptyBag, unitBag (name, bndr_id), [])
322   where
323     origin = PatOrigin pat
324 \end{code}
325
326
327 %************************************************************************
328 %*                                                                      *
329 \subsection{Lists of patterns}
330 %*                                                                      *
331 %************************************************************************
332
333 Helper functions
334
335 \begin{code}
336 tcPats :: BinderChecker                 -- How to deal with variables
337        -> [RenamedPat] -> [TcType]      -- Excess 'expected types' discarded
338        -> TcM ([TcPat], 
339                  Bag TcTyVar,
340                  Bag (Name, TcId),      -- Ids bound by the pattern
341                  [Inst])                -- Dicts bound by the pattern
342
343 tcPats tc_bndr [] tys = returnM ([], emptyBag, emptyBag, [])
344
345 tcPats tc_bndr (pat:pats) (ty:tys)
346   = tcPat tc_bndr pat (Check ty)        `thenM` \ (pat',  tvs1, ids1, lie_avail1) ->
347     tcPats tc_bndr pats tys             `thenM` \ (pats', tvs2, ids2, lie_avail2) ->
348
349     returnM (pat':pats', 
350               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
351               lie_avail1 ++ lie_avail2)
352 \end{code}
353
354
355 %************************************************************************
356 %*                                                                      *
357 \subsection{Constructor arguments}
358 %*                                                                      *
359 %************************************************************************
360
361 \begin{code}
362 tcConStuff tc_bndr data_con (PrefixCon arg_pats) arg_tys
363   =     -- Check correct arity
364     checkTc (con_arity == no_of_args)
365             (arityErr "Constructor" data_con con_arity no_of_args)      `thenM_`
366
367         -- Check arguments
368     tcPats tc_bndr arg_pats arg_tys     `thenM` \ (arg_pats', tvs, ids, lie_avail) ->
369
370     returnM (PrefixCon arg_pats', tvs, ids, lie_avail)
371   where
372     con_arity  = dataConSourceArity data_con
373     no_of_args = length arg_pats
374
375 tcConStuff tc_bndr data_con (InfixCon p1 p2) arg_tys
376   =     -- Check correct arity
377     checkTc (con_arity == 2)
378             (arityErr "Constructor" data_con con_arity 2)       `thenM_`
379
380         -- Check arguments
381     tcPat tc_bndr p1 (Check ty1)        `thenM` \ (p1', tvs1, ids1, lie_avail1) ->
382     tcPat tc_bndr p2 (Check ty2)        `thenM` \ (p2', tvs2, ids2, lie_avail2) ->
383
384     returnM (InfixCon p1' p2', 
385               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
386               lie_avail1 ++ lie_avail2)
387   where
388     con_arity  = dataConSourceArity data_con
389     [ty1, ty2] = arg_tys
390
391 tcConStuff tc_bndr data_con (RecCon rpats) arg_tys
392   =     -- Check the fields
393     tc_fields field_tys rpats   `thenM` \ (rpats', tvs, ids, lie_avail) ->
394     returnM (RecCon rpats', tvs, ids, lie_avail)
395
396   where
397     field_tys = zip (map fieldLabelName (dataConFieldLabels data_con)) arg_tys
398         -- Don't use zipEqual! If the constructor isn't really a record, then
399         -- dataConFieldLabels will be empty (and each field in the pattern
400         -- will generate an error below).
401
402     tc_fields field_tys []
403       = returnM ([], emptyBag, emptyBag, [])
404
405     tc_fields field_tys ((field_label, rhs_pat) : rpats)
406       = tc_fields field_tys rpats       `thenM` \ (rpats', tvs1, ids1, lie_avail1) ->
407
408         (case [ty | (f,ty) <- field_tys, f == field_label] of
409
410                 -- No matching field; chances are this field label comes from some
411                 -- other record type (or maybe none).  As well as reporting an
412                 -- error we still want to typecheck the pattern, principally to
413                 -- make sure that all the variables it binds are put into the
414                 -- environment, else the type checker crashes later:
415                 --      f (R { foo = (a,b) }) = a+b
416                 -- If foo isn't one of R's fields, we don't want to crash when
417                 -- typechecking the "a+b".
418            [] -> addErrTc (badFieldCon data_con field_label)    `thenM_` 
419                  newTyVarTy liftedTypeKind                      `thenM` \ bogus_ty ->
420                  returnM (error "Bogus selector Id", bogus_ty)
421
422                 -- The normal case, when the field comes from the right constructor
423            (pat_ty : extras) -> 
424                 ASSERT( null extras )
425                 tcLookupId field_label                  `thenM` \ sel_id ->
426                 returnM (sel_id, pat_ty)
427         )                                               `thenM` \ (sel_id, pat_ty) ->
428
429         tcPat tc_bndr rhs_pat (Check pat_ty)    `thenM` \ (rhs_pat', tvs2, ids2, lie_avail2) ->
430
431         returnM ((sel_id, rhs_pat') : rpats',
432                   tvs1 `unionBags` tvs2,
433                   ids1 `unionBags` ids2,
434                   lie_avail1 ++ lie_avail2)
435 \end{code}
436
437
438 %************************************************************************
439 %*                                                                      *
440 \subsection{Subsumption}
441 %*                                                                      *
442 %************************************************************************
443
444 Example:  
445         f :: (forall a. a->a) -> Int -> Int
446         f (g::Int->Int) y = g y
447 This is ok: the type signature allows fewer callers than
448 the (more general) signature f :: (Int->Int) -> Int -> Int
449 I.e.    (forall a. a->a) <= Int -> Int
450 We end up translating this to:
451         f = \g' :: (forall a. a->a).  let g = g' Int in g' y
452
453 tcSubPat does the work
454         sig_ty is the signature on the pattern itself 
455                 (Int->Int in the example)
456         expected_ty is the type passed inwards from the context
457                 (forall a. a->a in the example)
458
459 \begin{code}
460 tcSubPat :: TcSigmaType -> Expected TcSigmaType -> TcM PatCoFn
461
462 tcSubPat sig_ty exp_ty
463  = tcSubOff sig_ty exp_ty               `thenM` \ co_fn ->
464         -- co_fn is a coercion on *expressions*, and we
465         -- need to make a coercion on *patterns*
466    if isIdCoercion co_fn then
467         returnM idCoercion
468    else
469    newUnique                            `thenM` \ uniq ->
470    readExpectedType exp_ty              `thenM` \ exp_ty' ->
471    let
472         arg_id  = mkSysLocal FSLIT("sub") uniq exp_ty'
473         the_fn  = DictLam [arg_id] (co_fn <$> HsVar arg_id)
474         pat_co_fn p = SigPatOut p exp_ty' the_fn
475    in
476    returnM (mkCoercion pat_co_fn)
477 \end{code}
478
479
480 %************************************************************************
481 %*                                                                      *
482 \subsection{Errors and contexts}
483 %*                                                                      *
484 %************************************************************************
485
486 \begin{code}
487 patCtxt pat = hang (ptext SLIT("When checking the pattern:")) 
488                  4 (ppr pat)
489
490 badFieldCon :: DataCon -> Name -> SDoc
491 badFieldCon con field
492   = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
493           ptext SLIT("does not have field"), quotes (ppr field)]
494
495 polyPatSig :: TcType -> SDoc
496 polyPatSig sig_ty
497   = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
498          4 (ppr sig_ty)
499
500 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
501 \end{code}
502