[project @ 2002-09-13 15:02:25 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
17 import TcRnMonad
18 import Inst             ( InstOrigin(..),
19                           newMethodFromName, newOverloadedLit, newDicts,
20                           instToId, tcInstDataCon, tcSyntaxName
21                         )
22 import Id               ( mkLocalId, mkSysLocal )
23 import Name             ( Name )
24 import FieldLabel       ( fieldLabelName )
25 import TcEnv            ( tcLookupClass, tcLookupDataCon, tcLookupId )
26 import TcMType          ( newTyVarTy, zapToType, arityErr )
27 import TcType           ( TcType, TcTyVar, TcSigmaType, 
28                           mkClassPred, liftedTypeKind )
29 import TcUnify          ( tcSubOff, TcHoleType, 
30                           unifyTauTy, unifyListTy, unifyPArrTy, unifyTupleTy,  
31                           mkCoercion, idCoercion, isIdCoercion,
32                           (<$>), PatCoFn )
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, cCallableClassName )
39 import BasicTypes       ( isBoxed )
40 import Bag
41 import Outputable
42 import FastString
43 \end{code}
44
45
46 %************************************************************************
47 %*                                                                      *
48 \subsection{Variable patterns}
49 %*                                                                      *
50 %************************************************************************
51
52 \begin{code}
53 type BinderChecker = Name -> TcSigmaType -> TcM (PatCoFn, TcId)
54                         -- How to construct a suitable (monomorphic)
55                         -- Id for variables found in the pattern
56                         -- The TcSigmaType is the expected type 
57                         -- from the pattern context
58
59 -- The Id may have a sigma type (e.g. f (x::forall a. a->a))
60 -- so we want to *create* it during pattern type checking.
61 -- We don't want to make Ids first with a type-variable type
62 -- and then unify... becuase we can't unify a sigma type with a type variable.
63
64 tcMonoPatBndr :: BinderChecker
65   -- This is the right function to pass to tcPat when 
66   -- we're looking at a lambda-bound pattern, 
67   -- so there's no polymorphic guy to worry about
68
69 tcMonoPatBndr binder_name pat_ty 
70   = zapToType pat_ty    `thenM` \ pat_ty' ->
71         -- If there are *no constraints* on the pattern type, we
72         -- revert to good old H-M typechecking, making
73         -- the type of the binder into an *ordinary* 
74         -- type variable.  We find out if there are no constraints
75         -- by seeing if we are given an "open hole" as our info.
76         -- What we are trying to avoid here is giving a binder
77         -- a type that is a 'hole'.  The only place holes should
78         -- appear is as an argument to tcPat and tcExpr/tcMonoExpr.
79
80     returnM (idCoercion, mkLocalId binder_name pat_ty')
81 \end{code}
82
83
84 %************************************************************************
85 %*                                                                      *
86 \subsection{Typechecking patterns}
87 %*                                                                      *
88 %************************************************************************
89
90 \begin{code}
91 tcPat :: BinderChecker
92       -> RenamedPat
93
94       -> TcHoleType     -- Expected type derived from the context
95                         --      In the case of a function with a rank-2 signature,
96                         --      this type might be a forall type.
97
98       -> TcM (TcPat, 
99                 Bag TcTyVar,    -- TyVars bound by the pattern
100                                         --      These are just the existentially-bound ones.
101                                         --      Any tyvars bound by *type signatures* in the
102                                         --      patterns are brought into scope before we begin.
103                 Bag (Name, TcId),       -- Ids bound by the pattern, along with the Name under
104                                         --      which it occurs in the pattern
105                                         --      The two aren't the same because we conjure up a new
106                                         --      local name for each variable.
107                 [Inst])                 -- Dicts or methods [see below] bound by the pattern
108                                         --      from existential constructor patterns
109 \end{code}
110
111
112 %************************************************************************
113 %*                                                                      *
114 \subsection{Variables, wildcards, lazy pats, as-pats}
115 %*                                                                      *
116 %************************************************************************
117
118 \begin{code}
119 tcPat tc_bndr pat@(TypePat ty) pat_ty
120   = failWithTc (badTypePat pat)
121
122 tcPat tc_bndr (VarPat name) pat_ty
123   = tc_bndr name pat_ty                         `thenM` \ (co_fn, bndr_id) ->
124     returnM (co_fn <$> VarPat bndr_id, 
125               emptyBag, unitBag (name, bndr_id), [])
126
127 tcPat tc_bndr (LazyPat pat) pat_ty
128   = tcPat tc_bndr pat pat_ty            `thenM` \ (pat', tvs, ids, lie_avail) ->
129     returnM (LazyPat pat', tvs, ids, lie_avail)
130
131 tcPat tc_bndr pat_in@(AsPat name pat) pat_ty
132   = tc_bndr name pat_ty                 `thenM` \ (co_fn, bndr_id) ->
133     tcPat tc_bndr pat pat_ty            `thenM` \ (pat', tvs, ids, lie_avail) ->
134     returnM (co_fn <$> (AsPat bndr_id pat'), 
135               tvs, (name, bndr_id) `consBag` ids, lie_avail)
136
137 tcPat tc_bndr (WildPat _) pat_ty
138   = zapToType pat_ty                    `thenM` \ pat_ty' ->
139         -- We might have an incoming 'hole' type variable; no annotation
140         -- so zap it to a type.  Rather like tcMonoPatBndr.
141     returnM (WildPat pat_ty', emptyBag, emptyBag, [])
142
143 tcPat tc_bndr (ParPat parend_pat) pat_ty
144 -- Leave the parens in, so that warnings from the
145 -- desugarer have parens in them
146   = tcPat tc_bndr parend_pat pat_ty     `thenM` \ (pat', tvs, ids, lie_avail) ->
147     returnM (ParPat pat', tvs, ids, lie_avail)
148
149 tcPat tc_bndr pat_in@(SigPatIn pat sig) pat_ty
150   = addErrCtxt (patCtxt pat_in) $
151     tcHsSigType PatSigCtxt sig          `thenM` \ sig_ty ->
152     tcSubPat sig_ty pat_ty              `thenM` \ co_fn ->
153     tcPat tc_bndr pat sig_ty            `thenM` \ (pat', tvs, ids, lie_avail) ->
154     returnM (co_fn <$> pat', tvs, ids, lie_avail)
155 \end{code}
156
157
158 %************************************************************************
159 %*                                                                      *
160 \subsection{Explicit lists, parallel arrays, and tuples}
161 %*                                                                      *
162 %************************************************************************
163
164 \begin{code}
165 tcPat tc_bndr pat_in@(ListPat pats _) pat_ty
166   = addErrCtxt (patCtxt pat_in)         $
167     unifyListTy pat_ty                          `thenM` \ elem_ty ->
168     tcPats tc_bndr pats (repeat elem_ty)        `thenM` \ (pats', tvs, ids, lie_avail) ->
169     returnM (ListPat pats' elem_ty, tvs, ids, lie_avail)
170
171 tcPat tc_bndr pat_in@(PArrPat pats _) pat_ty
172   = addErrCtxt (patCtxt pat_in)         $
173     unifyPArrTy pat_ty                          `thenM` \ elem_ty ->
174     tcPats tc_bndr pats (repeat elem_ty)        `thenM` \ (pats', tvs, ids, lie_avail) ->
175     returnM (PArrPat pats' elem_ty, tvs, ids, lie_avail)
176
177 tcPat tc_bndr pat_in@(TuplePat pats boxity) pat_ty
178   = addErrCtxt (patCtxt pat_in) $
179
180     unifyTupleTy boxity arity pat_ty            `thenM` \ arg_tys ->
181     tcPats tc_bndr pats arg_tys                 `thenM` \ (pats', tvs, ids, lie_avail) ->
182
183         -- possibly do the "make all tuple-pats irrefutable" test:
184     let
185         unmangled_result = TuplePat pats' boxity
186
187         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
188         -- so that we can experiment with lazy tuple-matching.
189         -- This is a pretty odd place to make the switch, but
190         -- it was easy to do.
191
192         possibly_mangled_result
193           | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
194           | otherwise                               = unmangled_result
195     in
196     returnM (possibly_mangled_result, tvs, ids, lie_avail)
197   where
198     arity = length pats
199 \end{code}
200
201
202 %************************************************************************
203 %*                                                                      *
204 \subsection{Other constructors}
205 %*                                                                      *
206
207 %************************************************************************
208
209 \begin{code}
210 tcPat tc_bndr pat_in@(ConPatIn con_name arg_pats) pat_ty
211   = addErrCtxt (patCtxt pat_in)                 $
212
213         -- Check that it's a constructor, and instantiate it
214     tcLookupDataCon con_name                    `thenM` \ data_con ->
215     tcInstDataCon (PatOrigin pat_in) data_con   `thenM` \ (_, ex_dicts1, arg_tys, con_res_ty, ex_tvs) ->
216
217         -- Check overall type matches.
218         -- The pat_ty might be a for-all type, in which
219         -- case we must instantiate to match
220     tcSubPat con_res_ty pat_ty                          `thenM` \ co_fn ->
221
222         -- Check the argument patterns
223     tcConStuff tc_bndr data_con arg_pats arg_tys        `thenM` \ (arg_pats', arg_tvs, arg_ids, ex_dicts2) ->
224
225     returnM (co_fn <$> ConPatOut data_con arg_pats' con_res_ty ex_tvs (map instToId ex_dicts1),
226               listToBag ex_tvs `unionBags` arg_tvs,
227               arg_ids,
228               ex_dicts1 ++ ex_dicts2)
229 \end{code}
230
231
232 %************************************************************************
233 %*                                                                      *
234 \subsection{Literals}
235 %*                                                                      *
236 %************************************************************************
237
238 \begin{code}
239 tcPat tc_bndr (LitPat lit@(HsLitLit s _)) pat_ty 
240         -- cf tcExpr on LitLits
241   = tcLookupClass cCallableClassName            `thenM` \ cCallableClass ->
242     newDicts (LitLitOrigin (unpackFS s))
243              [mkClassPred cCallableClass [pat_ty]]      `thenM` \ dicts ->
244     extendLIEs dicts                                    `thenM_`
245     returnM (LitPat (HsLitLit s pat_ty), emptyBag, emptyBag, [])
246
247 tcPat tc_bndr pat@(LitPat lit@(HsString _)) pat_ty
248   = unifyTauTy pat_ty stringTy          `thenM_` 
249     tcLookupId eqStringName             `thenM` \ eq_id ->
250     returnM (NPatOut lit stringTy (HsVar eq_id `HsApp` HsLit lit), 
251               emptyBag, emptyBag, [])
252
253 tcPat tc_bndr (LitPat simple_lit) pat_ty
254   = unifyTauTy pat_ty (hsLitType simple_lit)            `thenM_` 
255     returnM (LitPat simple_lit, emptyBag, emptyBag, [])
256
257 tcPat tc_bndr pat@(NPatIn over_lit mb_neg) pat_ty
258   = newOverloadedLit origin over_lit pat_ty             `thenM` \ pos_lit_expr ->
259     newMethodFromName origin pat_ty eqName              `thenM` \ eq ->
260     (case mb_neg of
261         Nothing  -> returnM pos_lit_expr        -- Positive literal
262         Just neg ->     -- Negative literal
263                         -- The 'negate' is re-mappable syntax
264                     tcSyntaxName origin pat_ty negateName neg   `thenM` \ (neg_expr, _) ->
265                     returnM (HsApp neg_expr pos_lit_expr)
266     )                                                           `thenM` \ lit_expr ->
267
268     returnM (NPatOut lit' pat_ty (HsApp (HsVar eq) lit_expr),
269              emptyBag, emptyBag, [])
270   where
271     origin = PatOrigin pat
272
273         -- The literal in an NPatIn is always positive...
274         -- But in NPat, the literal is used to find identical patterns
275         --      so we must negate the literal when necessary!
276     lit' = case (over_lit, mb_neg) of
277              (HsIntegral i _, Nothing)   -> HsInteger i
278              (HsIntegral i _, Just _)    -> HsInteger (-i)
279              (HsFractional f _, Nothing) -> HsRat f pat_ty
280              (HsFractional f _, Just _)  -> HsRat (-f) pat_ty
281 \end{code}
282
283 %************************************************************************
284 %*                                                                      *
285 \subsection{n+k patterns}
286 %*                                                                      *
287 %************************************************************************
288
289 \begin{code}
290 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
291   = tc_bndr name pat_ty                         `thenM` \ (co_fn, bndr_id) ->
292     newOverloadedLit origin lit pat_ty          `thenM` \ over_lit_expr ->
293     newMethodFromName origin pat_ty geName      `thenM` \ ge ->
294
295         -- The '-' part is re-mappable syntax
296     tcSyntaxName origin pat_ty minusName minus_name     `thenM` \ (minus_expr, _) ->
297
298     returnM (NPlusKPatOut bndr_id i 
299                            (SectionR (HsVar ge) over_lit_expr)
300                            (SectionR minus_expr over_lit_expr),
301               emptyBag, unitBag (name, bndr_id), [])
302   where
303     origin = PatOrigin pat
304 \end{code}
305
306 %************************************************************************
307 %*                                                                      *
308 \subsection{Lists of patterns}
309 %*                                                                      *
310 %************************************************************************
311
312 Helper functions
313
314 \begin{code}
315 tcPats :: BinderChecker                 -- How to deal with variables
316        -> [RenamedPat] -> [TcType]      -- Excess 'expected types' discarded
317        -> TcM ([TcPat], 
318                  Bag TcTyVar,
319                  Bag (Name, TcId),      -- Ids bound by the pattern
320                  [Inst])                -- Dicts bound by the pattern
321
322 tcPats tc_bndr [] tys = returnM ([], emptyBag, emptyBag, [])
323
324 tcPats tc_bndr (ty:tys) (pat:pats)
325   = tcPat tc_bndr ty pat        `thenM` \ (pat',  tvs1, ids1, lie_avail1) ->
326     tcPats tc_bndr tys pats     `thenM` \ (pats', tvs2, ids2, lie_avail2) ->
327
328     returnM (pat':pats', 
329               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
330               lie_avail1 ++ lie_avail2)
331 \end{code}
332
333
334 %************************************************************************
335 %*                                                                      *
336 \subsection{Constructor arguments}
337 %*                                                                      *
338 %************************************************************************
339
340 \begin{code}
341 tcConStuff tc_bndr data_con (PrefixCon arg_pats) arg_tys
342   =     -- Check correct arity
343     checkTc (con_arity == no_of_args)
344             (arityErr "Constructor" data_con con_arity no_of_args)      `thenM_`
345
346         -- Check arguments
347     tcPats tc_bndr arg_pats arg_tys     `thenM` \ (arg_pats', tvs, ids, lie_avail) ->
348
349     returnM (PrefixCon arg_pats', tvs, ids, lie_avail)
350   where
351     con_arity  = dataConSourceArity data_con
352     no_of_args = length arg_pats
353
354 tcConStuff tc_bndr data_con (InfixCon p1 p2) arg_tys
355   =     -- Check correct arity
356     checkTc (con_arity == 2)
357             (arityErr "Constructor" data_con con_arity 2)       `thenM_`
358
359         -- Check arguments
360     tcPat tc_bndr p1 ty1        `thenM` \ (p1', tvs1, ids1, lie_avail1) ->
361     tcPat tc_bndr p2 ty2        `thenM` \ (p2', tvs2, ids2, lie_avail2) ->
362
363     returnM (InfixCon p1' p2', 
364               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
365               lie_avail1 ++ lie_avail2)
366   where
367     con_arity  = dataConSourceArity data_con
368     [ty1, ty2] = arg_tys
369
370 tcConStuff tc_bndr data_con (RecCon rpats) arg_tys
371   =     -- Check the fields
372     tc_fields field_tys rpats   `thenM` \ (rpats', tvs, ids, lie_avail) ->
373     returnM (RecCon rpats', tvs, ids, lie_avail)
374
375   where
376     field_tys = zip (map fieldLabelName (dataConFieldLabels data_con)) arg_tys
377         -- Don't use zipEqual! If the constructor isn't really a record, then
378         -- dataConFieldLabels will be empty (and each field in the pattern
379         -- will generate an error below).
380
381     tc_fields field_tys []
382       = returnM ([], emptyBag, emptyBag, [])
383
384     tc_fields field_tys ((field_label, rhs_pat) : rpats)
385       = tc_fields field_tys rpats       `thenM` \ (rpats', tvs1, ids1, lie_avail1) ->
386
387         (case [ty | (f,ty) <- field_tys, f == field_label] of
388
389                 -- No matching field; chances are this field label comes from some
390                 -- other record type (or maybe none).  As well as reporting an
391                 -- error we still want to typecheck the pattern, principally to
392                 -- make sure that all the variables it binds are put into the
393                 -- environment, else the type checker crashes later:
394                 --      f (R { foo = (a,b) }) = a+b
395                 -- If foo isn't one of R's fields, we don't want to crash when
396                 -- typechecking the "a+b".
397            [] -> addErrTc (badFieldCon data_con field_label)    `thenM_` 
398                  newTyVarTy liftedTypeKind                      `thenM` \ bogus_ty ->
399                  returnM (error "Bogus selector Id", bogus_ty)
400
401                 -- The normal case, when the field comes from the right constructor
402            (pat_ty : extras) -> 
403                 ASSERT( null extras )
404                 tcLookupId field_label                  `thenM` \ sel_id ->
405                 returnM (sel_id, pat_ty)
406         )                                               `thenM` \ (sel_id, pat_ty) ->
407
408         tcPat tc_bndr rhs_pat pat_ty    `thenM` \ (rhs_pat', tvs2, ids2, lie_avail2) ->
409
410         returnM ((sel_id, rhs_pat') : rpats',
411                   tvs1 `unionBags` tvs2,
412                   ids1 `unionBags` ids2,
413                   lie_avail1 ++ lie_avail2)
414 \end{code}
415
416
417 %************************************************************************
418 %*                                                                      *
419 \subsection{Subsumption}
420 %*                                                                      *
421 %************************************************************************
422
423 Example:  
424         f :: (forall a. a->a) -> Int -> Int
425         f (g::Int->Int) y = g y
426 This is ok: the type signature allows fewer callers than
427 the (more general) signature f :: (Int->Int) -> Int -> Int
428 I.e.    (forall a. a->a) <= Int -> Int
429 We end up translating this to:
430         f = \g' :: (forall a. a->a).  let g = g' Int in g' y
431
432 tcSubPat does the work
433         sig_ty is the signature on the pattern itself 
434                 (Int->Int in the example)
435         expected_ty is the type passed inwards from the context
436                 (forall a. a->a in the example)
437
438 \begin{code}
439 tcSubPat :: TcSigmaType -> TcHoleType -> TcM PatCoFn
440
441 tcSubPat sig_ty exp_ty
442  = tcSubOff sig_ty exp_ty               `thenM` \ co_fn ->
443         -- co_fn is a coercion on *expressions*, and we
444         -- need to make a coercion on *patterns*
445    if isIdCoercion co_fn then
446         returnM idCoercion
447    else
448    newUnique                            `thenM` \ uniq ->
449    let
450         arg_id  = mkSysLocal FSLIT("sub") uniq exp_ty
451         the_fn  = DictLam [arg_id] (co_fn <$> HsVar arg_id)
452         pat_co_fn p = SigPatOut p exp_ty the_fn
453    in
454    returnM (mkCoercion pat_co_fn)
455 \end{code}
456
457
458 %************************************************************************
459 %*                                                                      *
460 \subsection{Errors and contexts}
461 %*                                                                      *
462 %************************************************************************
463
464 \begin{code}
465 patCtxt pat = hang (ptext SLIT("When checking the pattern:")) 
466                  4 (ppr pat)
467
468 badFieldCon :: DataCon -> Name -> SDoc
469 badFieldCon con field
470   = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
471           ptext SLIT("does not have field"), quotes (ppr field)]
472
473 polyPatSig :: TcType -> SDoc
474 polyPatSig sig_ty
475   = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
476          4 (ppr sig_ty)
477
478 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
479 \end{code}
480