[project @ 2003-10-09 11:58:39 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 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 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 pat@(LitPat lit@(HsString _)) pat_ty
246   = zapExpectedType pat_ty              `thenM` \ pat_ty' ->
247     unifyTauTy pat_ty' stringTy         `thenM_` 
248     tcLookupId eqStringName             `thenM` \ eq_id ->
249     returnM (NPatOut lit stringTy (HsVar eq_id `HsApp` HsLit lit), 
250             emptyBag, emptyBag, [])
251
252 tcPat tc_bndr (LitPat simple_lit) pat_ty
253   = zapExpectedType pat_ty                      `thenM` \ 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   = zapExpectedType pat_ty                      `thenM` \ pat_ty' ->
259     newOverloadedLit origin over_lit pat_ty'    `thenM` \ pos_lit_expr ->
260     newMethodFromName origin pat_ty' eqName     `thenM` \ eq ->
261     (case mb_neg of
262         Nothing  -> returnM pos_lit_expr        -- Positive literal
263         Just neg ->     -- Negative literal
264                         -- The 'negate' is re-mappable syntax
265             tcSyntaxName origin pat_ty' (negateName, HsVar neg) `thenM` \ (_, neg_expr) ->
266             returnM (HsApp neg_expr pos_lit_expr)
267     )                                                           `thenM` \ lit_expr ->
268
269     let
270         -- The literal in an NPatIn is always positive...
271         -- But in NPat, the literal is used to find identical patterns
272         --      so we must negate the literal when necessary!
273         lit' = case (over_lit, mb_neg) of
274                  (HsIntegral i _,   Nothing) -> HsInteger i pat_ty'
275                  (HsIntegral i _,   Just _)  -> HsInteger (-i) pat_ty'
276                  (HsFractional f _, Nothing) -> HsRat f pat_ty'
277                  (HsFractional f _, Just _)  -> HsRat (-f) pat_ty'
278     in
279     returnM (NPatOut lit' pat_ty' (HsApp (HsVar eq) lit_expr),
280              emptyBag, emptyBag, [])
281   where
282     origin = PatOrigin pat
283 \end{code}
284
285 %************************************************************************
286 %*                                                                      *
287 \subsection{n+k patterns}
288 %*                                                                      *
289 %************************************************************************
290
291 \begin{code}
292 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
293   = tc_bndr name pat_ty                          `thenM` \ (co_fn, bndr_id) ->
294     let 
295         pat_ty' = idType bndr_id
296     in
297     newOverloadedLit origin lit pat_ty'          `thenM` \ over_lit_expr ->
298     newMethodFromName origin pat_ty' geName      `thenM` \ ge ->
299
300         -- The '-' part is re-mappable syntax
301     tcSyntaxName origin pat_ty' (minusName, HsVar minus_name)   `thenM` \ (_, minus_expr) ->
302
303         -- The Report says that n+k patterns must be in Integral
304         -- We may not want this when using re-mappable syntax, though (ToDo?)
305     tcLookupClass integralClassName                     `thenM` \ icls ->
306     newDicts origin [mkClassPred icls [pat_ty']]        `thenM` \ dicts ->
307     extendLIEs dicts                                    `thenM_`
308     
309     returnM (NPlusKPatOut bndr_id i 
310                            (SectionR (HsVar ge) over_lit_expr)
311                            (SectionR minus_expr over_lit_expr),
312               emptyBag, unitBag (name, bndr_id), [])
313   where
314     origin = PatOrigin pat
315 \end{code}
316
317
318 %************************************************************************
319 %*                                                                      *
320 \subsection{Lists of patterns}
321 %*                                                                      *
322 %************************************************************************
323
324 Helper functions
325
326 \begin{code}
327 tcPats :: BinderChecker                 -- How to deal with variables
328        -> [RenamedPat] -> [TcType]      -- Excess 'expected types' discarded
329        -> TcM ([TcPat], 
330                  Bag TcTyVar,
331                  Bag (Name, TcId),      -- Ids bound by the pattern
332                  [Inst])                -- Dicts bound by the pattern
333
334 tcPats tc_bndr [] tys = returnM ([], emptyBag, emptyBag, [])
335
336 tcPats tc_bndr (pat:pats) (ty:tys)
337   = tcPat tc_bndr pat (Check ty)        `thenM` \ (pat',  tvs1, ids1, lie_avail1) ->
338     tcPats tc_bndr pats tys             `thenM` \ (pats', tvs2, ids2, lie_avail2) ->
339
340     returnM (pat':pats', 
341               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
342               lie_avail1 ++ lie_avail2)
343 \end{code}
344
345
346 %************************************************************************
347 %*                                                                      *
348 \subsection{Constructor arguments}
349 %*                                                                      *
350 %************************************************************************
351
352 \begin{code}
353 tcConStuff tc_bndr data_con (PrefixCon arg_pats) arg_tys
354   =     -- Check correct arity
355     checkTc (con_arity == no_of_args)
356             (arityErr "Constructor" data_con con_arity no_of_args)      `thenM_`
357
358         -- Check arguments
359     tcPats tc_bndr arg_pats arg_tys     `thenM` \ (arg_pats', tvs, ids, lie_avail) ->
360
361     returnM (PrefixCon arg_pats', tvs, ids, lie_avail)
362   where
363     con_arity  = dataConSourceArity data_con
364     no_of_args = length arg_pats
365
366 tcConStuff tc_bndr data_con (InfixCon p1 p2) arg_tys
367   =     -- Check correct arity
368     checkTc (con_arity == 2)
369             (arityErr "Constructor" data_con con_arity 2)       `thenM_`
370
371         -- Check arguments
372     tcPat tc_bndr p1 (Check ty1)        `thenM` \ (p1', tvs1, ids1, lie_avail1) ->
373     tcPat tc_bndr p2 (Check ty2)        `thenM` \ (p2', tvs2, ids2, lie_avail2) ->
374
375     returnM (InfixCon p1' p2', 
376               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
377               lie_avail1 ++ lie_avail2)
378   where
379     con_arity  = dataConSourceArity data_con
380     [ty1, ty2] = arg_tys
381
382 tcConStuff tc_bndr data_con (RecCon rpats) arg_tys
383   =     -- Check the fields
384     tc_fields field_tys rpats   `thenM` \ (rpats', tvs, ids, lie_avail) ->
385     returnM (RecCon rpats', tvs, ids, lie_avail)
386
387   where
388     field_tys = zip (map fieldLabelName (dataConFieldLabels data_con)) arg_tys
389         -- Don't use zipEqual! If the constructor isn't really a record, then
390         -- dataConFieldLabels will be empty (and each field in the pattern
391         -- will generate an error below).
392
393     tc_fields field_tys []
394       = returnM ([], emptyBag, emptyBag, [])
395
396     tc_fields field_tys ((field_label, rhs_pat) : rpats)
397       = tc_fields field_tys rpats       `thenM` \ (rpats', tvs1, ids1, lie_avail1) ->
398
399         (case [ty | (f,ty) <- field_tys, f == field_label] of
400
401                 -- No matching field; chances are this field label comes from some
402                 -- other record type (or maybe none).  As well as reporting an
403                 -- error we still want to typecheck the pattern, principally to
404                 -- make sure that all the variables it binds are put into the
405                 -- environment, else the type checker crashes later:
406                 --      f (R { foo = (a,b) }) = a+b
407                 -- If foo isn't one of R's fields, we don't want to crash when
408                 -- typechecking the "a+b".
409            [] -> addErrTc (badFieldCon data_con field_label)    `thenM_` 
410                  newTyVarTy liftedTypeKind                      `thenM` \ bogus_ty ->
411                  returnM (error "Bogus selector Id", bogus_ty)
412
413                 -- The normal case, when the field comes from the right constructor
414            (pat_ty : extras) -> 
415                 ASSERT( null extras )
416                 tcLookupId field_label                  `thenM` \ sel_id ->
417                 returnM (sel_id, pat_ty)
418         )                                               `thenM` \ (sel_id, pat_ty) ->
419
420         tcPat tc_bndr rhs_pat (Check pat_ty)    `thenM` \ (rhs_pat', tvs2, ids2, lie_avail2) ->
421
422         returnM ((sel_id, rhs_pat') : rpats',
423                   tvs1 `unionBags` tvs2,
424                   ids1 `unionBags` ids2,
425                   lie_avail1 ++ lie_avail2)
426 \end{code}
427
428
429 %************************************************************************
430 %*                                                                      *
431 \subsection{Subsumption}
432 %*                                                                      *
433 %************************************************************************
434
435 Example:  
436         f :: (forall a. a->a) -> Int -> Int
437         f (g::Int->Int) y = g y
438 This is ok: the type signature allows fewer callers than
439 the (more general) signature f :: (Int->Int) -> Int -> Int
440 I.e.    (forall a. a->a) <= Int -> Int
441 We end up translating this to:
442         f = \g' :: (forall a. a->a).  let g = g' Int in g' y
443
444 tcSubPat does the work
445         sig_ty is the signature on the pattern itself 
446                 (Int->Int in the example)
447         expected_ty is the type passed inwards from the context
448                 (forall a. a->a in the example)
449
450 \begin{code}
451 tcSubPat :: TcSigmaType -> Expected TcSigmaType -> TcM PatCoFn
452
453 tcSubPat sig_ty exp_ty
454  = tcSubOff sig_ty exp_ty               `thenM` \ co_fn ->
455         -- co_fn is a coercion on *expressions*, and we
456         -- need to make a coercion on *patterns*
457    if isIdCoercion co_fn then
458         returnM idCoercion
459    else
460    newUnique                            `thenM` \ uniq ->
461    readExpectedType exp_ty              `thenM` \ exp_ty' ->
462    let
463         arg_id  = mkSysLocal FSLIT("sub") uniq exp_ty'
464         the_fn  = DictLam [arg_id] (co_fn <$> HsVar arg_id)
465         pat_co_fn p = SigPatOut p exp_ty' the_fn
466    in
467    returnM (mkCoercion pat_co_fn)
468 \end{code}
469
470
471 %************************************************************************
472 %*                                                                      *
473 \subsection{Errors and contexts}
474 %*                                                                      *
475 %************************************************************************
476
477 \begin{code}
478 patCtxt pat = hang (ptext SLIT("When checking the pattern:")) 
479                  4 (ppr pat)
480
481 badFieldCon :: DataCon -> Name -> SDoc
482 badFieldCon con field
483   = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
484           ptext SLIT("does not have field"), quotes (ppr field)]
485
486 polyPatSig :: TcType -> SDoc
487 polyPatSig sig_ty
488   = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
489          4 (ppr sig_ty)
490
491 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
492 \end{code}
493