[project @ 2003-12-30 16:29:17 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(..), LPat, HsConDetails(..), HsLit(..), HsOverLit(..), HsExpr(..) )
14 import HsUtils
15 import TcHsSyn          ( 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, tcLookupLocatedDataCon, tcLookupId )
28 import TcMType          ( newTyVarTy, arityErr )
29 import TcType           ( TcType, TcTyVar, TcSigmaType, mkClassPred )
30 import Kind             ( argTypeKind, liftedTypeKind )
31 import TcUnify          ( tcSubOff, Expected(..), readExpectedType, zapExpectedType, 
32                           unifyTauTy, zapToListTy, zapToPArrTy, zapToTupleTy )  
33 import TcHsType         ( 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 )
40 import BasicTypes       ( isBoxed )
41 import SrcLoc           ( Located(..), noLoc, unLoc )
42 import Bag
43 import Outputable
44 import FastString
45 \end{code}
46
47
48 %************************************************************************
49 %*                                                                      *
50 \subsection{Variable patterns}
51 %*                                                                      *
52 %************************************************************************
53
54 \begin{code}
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
60
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.
65
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
70
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.
81
82     returnM (idCoercion, mkLocalId binder_name pat_ty')
83 \end{code}
84
85
86 %************************************************************************
87 %*                                                                      *
88 \subsection{Typechecking patterns}
89 %*                                                                      *
90 %************************************************************************
91
92 \begin{code}
93 tcPat :: BinderChecker
94       -> LPat Name
95
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.
99
100       -> TcM   (LPat TcId, 
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
112   = addSrcSpan span $
113     do  { (pat', tvs, ids, lie) <- tc_pat tc_bndr pat exp_ty
114         ; return (L span pat', tvs, ids, lie) }
115 \end{code}
116
117
118 %************************************************************************
119 %*                                                                      *
120 \subsection{Variables, wildcards, lazy pats, as-pats}
121 %*                                                                      *
122 %************************************************************************
123
124 \begin{code}
125 tc_pat tc_bndr pat@(TypePat ty) pat_ty
126   = failWithTc (badTypePat pat)
127
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), [])
132
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)
136
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) ->
140         -- NB: if we have:
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)
147
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
153         --      f _ = 3
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, [])
160
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)
166
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)
173 \end{code}
174
175
176 %************************************************************************
177 %*                                                                      *
178 \subsection{Explicit lists, parallel arrays, and tuples}
179 %*                                                                      *
180 %************************************************************************
181
182 \begin{code}
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)
188
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)
194
195 tc_pat tc_bndr pat_in@(TuplePat pats boxity) pat_ty
196   = addErrCtxt (patCtxt pat_in) $
197
198     zapToTupleTy boxity arity pat_ty            `thenM` \ arg_tys ->
199     tcPats tc_bndr pats arg_tys                 `thenM` \ (pats', tvs, ids, lie_avail) ->
200
201         -- possibly do the "make all tuple-pats irrefutable" test:
202     let
203         unmangled_result = TuplePat pats' boxity
204
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.
209
210         possibly_mangled_result
211           | opt_IrrefutableTuples && isBoxed boxity = LazyPat (noLoc unmangled_result)
212           | otherwise                               = unmangled_result
213     in
214     returnM (possibly_mangled_result, tvs, ids, lie_avail)
215   where
216     arity = length pats
217 \end{code}
218
219
220 %************************************************************************
221 %*                                                                      *
222 \subsection{Other constructors}
223 %*                                                                      *
224
225 %************************************************************************
226
227 \begin{code}
228 tc_pat tc_bndr pat_in@(ConPatIn con_name arg_pats) pat_ty
229   = addErrCtxt (patCtxt pat_in)                 $
230
231         -- Check that it's a constructor, and instantiate it
232     tcLookupLocatedDataCon con_name             `thenM` \ data_con ->
233     tcInstDataCon (PatOrigin pat_in) data_con   `thenM` \ (_, ex_dicts1, arg_tys, con_res_ty, ex_tvs) ->
234
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 ->
239
240         -- Check the argument patterns
241     tcConStuff tc_bndr data_con arg_pats arg_tys        `thenM` \ (arg_pats', arg_tvs, arg_ids, ex_dicts2) ->
242
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,
245               arg_ids,
246               ex_dicts1 ++ ex_dicts2)
247 \end{code}
248
249
250 %************************************************************************
251 %*                                                                      *
252 \subsection{Literals}
253 %*                                                                      *
254 %************************************************************************
255
256 \begin{code}
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, [])
263
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, [])
268
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 ->
273     (case mb_neg of
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, noLoc (HsVar neg)) `thenM` \ (_, neg_expr) ->
278             returnM (mkHsApp neg_expr pos_lit_expr)
279     )                                                           `thenM` \ lit_expr ->
280
281     let
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'
290     in
291     returnM (NPatOut lit' pat_ty' (HsApp (nlHsVar eq) lit_expr),
292              emptyBag, emptyBag, [])
293   where
294     origin = PatOrigin pat
295 \end{code}
296
297 %************************************************************************
298 %*                                                                      *
299 \subsection{n+k patterns}
300 %*                                                                      *
301 %************************************************************************
302
303 \begin{code}
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) ->
306     let 
307         pat_ty' = idType bndr_id
308     in
309     newOverloadedLit origin lit pat_ty'          `thenM` \ over_lit_expr ->
310     newMethodFromName origin pat_ty' geName      `thenM` \ ge ->
311
312         -- The '-' part is re-mappable syntax
313     tcSyntaxName origin pat_ty' (minusName, noLoc (HsVar minus_name))   `thenM` \ (_, minus_expr) ->
314
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_`
320     
321     returnM (NPlusKPatOut (L nm_loc bndr_id) i 
322                            (SectionR (nlHsVar ge) over_lit_expr)
323                            (SectionR minus_expr over_lit_expr),
324               emptyBag, unitBag (name, bndr_id), [])
325   where
326     origin = PatOrigin pat
327 \end{code}
328
329
330 %************************************************************************
331 %*                                                                      *
332 \subsection{Lists of patterns}
333 %*                                                                      *
334 %************************************************************************
335
336 Helper functions
337
338 \begin{code}
339 tcPats :: BinderChecker                 -- How to deal with variables
340        -> [LPat Name] -> [TcType]       -- Excess 'expected types' discarded
341        -> TcM ([LPat TcId], 
342                  Bag TcTyVar,
343                  Bag (Name, TcId),      -- Ids bound by the pattern
344                  [Inst])                -- Dicts bound by the pattern
345
346 tcPats tc_bndr [] tys = returnM ([], emptyBag, emptyBag, [])
347
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) ->
351
352     returnM (pat':pats', 
353               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
354               lie_avail1 ++ lie_avail2)
355 \end{code}
356
357
358 %************************************************************************
359 %*                                                                      *
360 \subsection{Constructor arguments}
361 %*                                                                      *
362 %************************************************************************
363
364 \begin{code}
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_`
369
370         -- Check arguments
371     tcPats tc_bndr arg_pats arg_tys     `thenM` \ (arg_pats', tvs, ids, lie_avail) ->
372
373     returnM (PrefixCon arg_pats', tvs, ids, lie_avail)
374   where
375     con_arity  = dataConSourceArity data_con
376     no_of_args = length arg_pats
377
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_`
382
383         -- Check arguments
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) ->
386
387     returnM (InfixCon p1' p2', 
388               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
389               lie_avail1 ++ lie_avail2)
390   where
391     con_arity  = dataConSourceArity data_con
392     [ty1, ty2] = arg_tys
393
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)
398
399   where
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).
404
405     tc_fields field_tys []
406       = returnM ([], emptyBag, emptyBag, [])
407
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) ->
410
411         (case [ty | (f,ty) <- field_tys, f == field_label] of
412
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)
424
425                 -- The normal case, when the field comes from the right constructor
426            (pat_ty : extras) -> 
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) ->
431
432         tcPat tc_bndr rhs_pat (Check pat_ty)    `thenM` \ (rhs_pat', tvs2, ids2, lie_avail2) ->
433
434         returnM ((L lbl_loc sel_id, rhs_pat') : rpats',
435                   tvs1 `unionBags` tvs2,
436                   ids1 `unionBags` ids2,
437                   lie_avail1 ++ lie_avail2)
438 \end{code}
439
440
441 %************************************************************************
442 %*                                                                      *
443 \subsection{Subsumption}
444 %*                                                                      *
445 %************************************************************************
446
447 Example:  
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
455
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)
461
462 \begin{code}
463 tcSubPat :: TcSigmaType -> Expected TcSigmaType -> TcM PatCoFn
464
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
470         returnM idCoercion
471    else
472    newUnique                            `thenM` \ uniq ->
473    readExpectedType exp_ty              `thenM` \ exp_ty' ->
474    let
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
478    in
479    returnM (mkCoercion pat_co_fn)
480 \end{code}
481
482
483 %************************************************************************
484 %*                                                                      *
485 \subsection{Errors and contexts}
486 %*                                                                      *
487 %************************************************************************
488
489 \begin{code}
490 patCtxt pat = hang (ptext SLIT("When checking the pattern:")) 
491                  4 (ppr pat)
492
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)]
497
498 polyPatSig :: TcType -> SDoc
499 polyPatSig sig_ty
500   = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
501          4 (ppr sig_ty)
502
503 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
504 \end{code}
505