c353085b413cf4621631dfd29491d3115bf83ee8
[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, 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 -> Expected 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   = zapExpectedType 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       -> Expected TcSigmaType   -- 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 (Check (idType bndr_id))  `thenM` \ (pat', tvs, ids, lie_avail) ->
134         -- NB: if we have:
135         --      \ (y@(x::forall a. a->a)) = e
136         -- we'll fail.  The as-pattern infers a monotype for 'y', which then
137         -- fails to unify with the polymorphic type for 'x'.  This could be
138         -- fixed, but only with a bit more work.
139     returnM (co_fn <$> (AsPat bndr_id pat'), 
140               tvs, (name, bndr_id) `consBag` ids, lie_avail)
141
142 tcPat tc_bndr (WildPat _) pat_ty
143   = zapExpectedType pat_ty              `thenM` \ pat_ty' ->
144         -- We might have an incoming 'hole' type variable; no annotation
145         -- so zap it to a type.  Rather like tcMonoPatBndr.
146     returnM (WildPat pat_ty', emptyBag, emptyBag, [])
147
148 tcPat tc_bndr (ParPat parend_pat) pat_ty
149 -- Leave the parens in, so that warnings from the
150 -- desugarer have parens in them
151   = tcPat tc_bndr parend_pat pat_ty     `thenM` \ (pat', tvs, ids, lie_avail) ->
152     returnM (ParPat pat', tvs, ids, lie_avail)
153
154 tcPat tc_bndr pat_in@(SigPatIn pat sig) pat_ty
155   = addErrCtxt (patCtxt pat_in) $
156     tcHsSigType PatSigCtxt sig          `thenM` \ sig_ty ->
157     tcSubPat sig_ty pat_ty              `thenM` \ co_fn ->
158     tcPat tc_bndr pat (Check sig_ty)    `thenM` \ (pat', tvs, ids, lie_avail) ->
159     returnM (co_fn <$> pat', tvs, ids, lie_avail)
160 \end{code}
161
162
163 %************************************************************************
164 %*                                                                      *
165 \subsection{Explicit lists, parallel arrays, and tuples}
166 %*                                                                      *
167 %************************************************************************
168
169 \begin{code}
170 tcPat tc_bndr pat_in@(ListPat pats _) pat_ty
171   = addErrCtxt (patCtxt pat_in)         $
172     zapToListTy pat_ty                          `thenM` \ elem_ty ->
173     tcPats tc_bndr pats (repeat elem_ty)        `thenM` \ (pats', tvs, ids, lie_avail) ->
174     returnM (ListPat pats' elem_ty, tvs, ids, lie_avail)
175
176 tcPat tc_bndr pat_in@(PArrPat pats _) pat_ty
177   = addErrCtxt (patCtxt pat_in)         $
178     zapToPArrTy pat_ty                          `thenM` \ elem_ty ->
179     tcPats tc_bndr pats (repeat elem_ty)        `thenM` \ (pats', tvs, ids, lie_avail) ->
180     returnM (PArrPat pats' elem_ty, tvs, ids, lie_avail)
181
182 tcPat tc_bndr pat_in@(TuplePat pats boxity) pat_ty
183   = addErrCtxt (patCtxt pat_in) $
184
185     zapToTupleTy boxity arity pat_ty            `thenM` \ arg_tys ->
186     tcPats tc_bndr pats arg_tys                 `thenM` \ (pats', tvs, ids, lie_avail) ->
187
188         -- possibly do the "make all tuple-pats irrefutable" test:
189     let
190         unmangled_result = TuplePat pats' boxity
191
192         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
193         -- so that we can experiment with lazy tuple-matching.
194         -- This is a pretty odd place to make the switch, but
195         -- it was easy to do.
196
197         possibly_mangled_result
198           | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
199           | otherwise                               = unmangled_result
200     in
201     returnM (possibly_mangled_result, tvs, ids, lie_avail)
202   where
203     arity = length pats
204 \end{code}
205
206
207 %************************************************************************
208 %*                                                                      *
209 \subsection{Other constructors}
210 %*                                                                      *
211
212 %************************************************************************
213
214 \begin{code}
215 tcPat tc_bndr pat_in@(ConPatIn con_name arg_pats) pat_ty
216   = addErrCtxt (patCtxt pat_in)                 $
217
218         -- Check that it's a constructor, and instantiate it
219     tcLookupDataCon con_name                    `thenM` \ data_con ->
220     tcInstDataCon (PatOrigin pat_in) data_con   `thenM` \ (_, ex_dicts1, arg_tys, con_res_ty, ex_tvs) ->
221
222         -- Check overall type matches.
223         -- The pat_ty might be a for-all type, in which
224         -- case we must instantiate to match
225     tcSubPat con_res_ty pat_ty                          `thenM` \ co_fn ->
226
227         -- Check the argument patterns
228     tcConStuff tc_bndr data_con arg_pats arg_tys        `thenM` \ (arg_pats', arg_tvs, arg_ids, ex_dicts2) ->
229
230     returnM (co_fn <$> ConPatOut data_con arg_pats' con_res_ty ex_tvs (map instToId ex_dicts1),
231               listToBag ex_tvs `unionBags` arg_tvs,
232               arg_ids,
233               ex_dicts1 ++ ex_dicts2)
234 \end{code}
235
236
237 %************************************************************************
238 %*                                                                      *
239 \subsection{Literals}
240 %*                                                                      *
241 %************************************************************************
242
243 \begin{code}
244 tcPat tc_bndr (LitPat lit@(HsLitLit s _)) pat_ty 
245         -- cf tcExpr on LitLits
246   = zapExpectedType pat_ty                              `thenM` \ pat_ty' ->
247     tcLookupClass cCallableClassName                    `thenM` \ cCallableClass ->
248     newDicts (LitLitOrigin (unpackFS s))
249              [mkClassPred cCallableClass [pat_ty']]     `thenM` \ dicts ->
250     extendLIEs dicts                                    `thenM_`
251     returnM (LitPat (HsLitLit s pat_ty'), emptyBag, emptyBag, [])
252
253 tcPat tc_bndr pat@(LitPat lit@(HsString _)) pat_ty
254   = zapExpectedType pat_ty              `thenM` \ pat_ty' ->
255     unifyTauTy pat_ty' stringTy         `thenM_` 
256     tcLookupId eqStringName             `thenM` \ eq_id ->
257     returnM (NPatOut lit stringTy (HsVar eq_id `HsApp` HsLit lit), 
258             emptyBag, emptyBag, [])
259
260 tcPat tc_bndr (LitPat simple_lit) pat_ty
261   = zapExpectedType pat_ty                      `thenM` \ pat_ty' ->
262     unifyTauTy pat_ty' (hsLitType simple_lit)   `thenM_` 
263     returnM (LitPat simple_lit, emptyBag, emptyBag, [])
264
265 tcPat tc_bndr pat@(NPatIn over_lit mb_neg) pat_ty
266   = zapExpectedType pat_ty                      `thenM` \ pat_ty' ->
267     newOverloadedLit origin over_lit pat_ty'    `thenM` \ pos_lit_expr ->
268     newMethodFromName origin pat_ty' eqName     `thenM` \ eq ->
269     (case mb_neg of
270         Nothing  -> returnM pos_lit_expr        -- Positive literal
271         Just neg ->     -- Negative literal
272                         -- The 'negate' is re-mappable syntax
273                     tcSyntaxName origin pat_ty' negateName neg  `thenM` \ (neg_expr, _) ->
274                     returnM (HsApp neg_expr pos_lit_expr)
275     )                                                           `thenM` \ lit_expr ->
276
277     let
278         -- The literal in an NPatIn is always positive...
279         -- But in NPat, the literal is used to find identical patterns
280         --      so we must negate the literal when necessary!
281         lit' = case (over_lit, mb_neg) of
282                  (HsIntegral i _,   Nothing) -> HsInteger i
283                  (HsIntegral i _,   Just _)  -> HsInteger (-i)
284                  (HsFractional f _, Nothing) -> HsRat f pat_ty'
285                  (HsFractional f _, Just _)  -> HsRat (-f) pat_ty'
286     in
287     returnM (NPatOut lit' pat_ty' (HsApp (HsVar eq) lit_expr),
288              emptyBag, emptyBag, [])
289   where
290     origin = PatOrigin pat
291 \end{code}
292
293 %************************************************************************
294 %*                                                                      *
295 \subsection{n+k patterns}
296 %*                                                                      *
297 %************************************************************************
298
299 \begin{code}
300 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
301   = tc_bndr name pat_ty                          `thenM` \ (co_fn, bndr_id) ->
302     let 
303         pat_ty' = idType bndr_id
304     in
305     newOverloadedLit origin lit pat_ty'          `thenM` \ over_lit_expr ->
306     newMethodFromName origin pat_ty' geName      `thenM` \ ge ->
307
308         -- The '-' part is re-mappable syntax
309     tcSyntaxName origin pat_ty' minusName minus_name    `thenM` \ (minus_expr, _) ->
310
311     returnM (NPlusKPatOut bndr_id i 
312                            (SectionR (HsVar ge) over_lit_expr)
313                            (SectionR minus_expr over_lit_expr),
314               emptyBag, unitBag (name, bndr_id), [])
315   where
316     origin = PatOrigin pat
317 \end{code}
318
319
320 %************************************************************************
321 %*                                                                      *
322 \subsection{Lists of patterns}
323 %*                                                                      *
324 %************************************************************************
325
326 Helper functions
327
328 \begin{code}
329 tcPats :: BinderChecker                 -- How to deal with variables
330        -> [RenamedPat] -> [TcType]      -- Excess 'expected types' discarded
331        -> TcM ([TcPat], 
332                  Bag TcTyVar,
333                  Bag (Name, TcId),      -- Ids bound by the pattern
334                  [Inst])                -- Dicts bound by the pattern
335
336 tcPats tc_bndr [] tys = returnM ([], emptyBag, emptyBag, [])
337
338 tcPats tc_bndr (pat:pats) (ty:tys)
339   = tcPat tc_bndr pat (Check ty)        `thenM` \ (pat',  tvs1, ids1, lie_avail1) ->
340     tcPats tc_bndr pats tys             `thenM` \ (pats', tvs2, ids2, lie_avail2) ->
341
342     returnM (pat':pats', 
343               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
344               lie_avail1 ++ lie_avail2)
345 \end{code}
346
347
348 %************************************************************************
349 %*                                                                      *
350 \subsection{Constructor arguments}
351 %*                                                                      *
352 %************************************************************************
353
354 \begin{code}
355 tcConStuff tc_bndr data_con (PrefixCon arg_pats) arg_tys
356   =     -- Check correct arity
357     checkTc (con_arity == no_of_args)
358             (arityErr "Constructor" data_con con_arity no_of_args)      `thenM_`
359
360         -- Check arguments
361     tcPats tc_bndr arg_pats arg_tys     `thenM` \ (arg_pats', tvs, ids, lie_avail) ->
362
363     returnM (PrefixCon arg_pats', tvs, ids, lie_avail)
364   where
365     con_arity  = dataConSourceArity data_con
366     no_of_args = length arg_pats
367
368 tcConStuff tc_bndr data_con (InfixCon p1 p2) arg_tys
369   =     -- Check correct arity
370     checkTc (con_arity == 2)
371             (arityErr "Constructor" data_con con_arity 2)       `thenM_`
372
373         -- Check arguments
374     tcPat tc_bndr p1 (Check ty1)        `thenM` \ (p1', tvs1, ids1, lie_avail1) ->
375     tcPat tc_bndr p2 (Check ty2)        `thenM` \ (p2', tvs2, ids2, lie_avail2) ->
376
377     returnM (InfixCon p1' p2', 
378               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
379               lie_avail1 ++ lie_avail2)
380   where
381     con_arity  = dataConSourceArity data_con
382     [ty1, ty2] = arg_tys
383
384 tcConStuff tc_bndr data_con (RecCon rpats) arg_tys
385   =     -- Check the fields
386     tc_fields field_tys rpats   `thenM` \ (rpats', tvs, ids, lie_avail) ->
387     returnM (RecCon rpats', tvs, ids, lie_avail)
388
389   where
390     field_tys = zip (map fieldLabelName (dataConFieldLabels data_con)) arg_tys
391         -- Don't use zipEqual! If the constructor isn't really a record, then
392         -- dataConFieldLabels will be empty (and each field in the pattern
393         -- will generate an error below).
394
395     tc_fields field_tys []
396       = returnM ([], emptyBag, emptyBag, [])
397
398     tc_fields field_tys ((field_label, rhs_pat) : rpats)
399       = tc_fields field_tys rpats       `thenM` \ (rpats', tvs1, ids1, lie_avail1) ->
400
401         (case [ty | (f,ty) <- field_tys, f == field_label] of
402
403                 -- No matching field; chances are this field label comes from some
404                 -- other record type (or maybe none).  As well as reporting an
405                 -- error we still want to typecheck the pattern, principally to
406                 -- make sure that all the variables it binds are put into the
407                 -- environment, else the type checker crashes later:
408                 --      f (R { foo = (a,b) }) = a+b
409                 -- If foo isn't one of R's fields, we don't want to crash when
410                 -- typechecking the "a+b".
411            [] -> addErrTc (badFieldCon data_con field_label)    `thenM_` 
412                  newTyVarTy liftedTypeKind                      `thenM` \ bogus_ty ->
413                  returnM (error "Bogus selector Id", bogus_ty)
414
415                 -- The normal case, when the field comes from the right constructor
416            (pat_ty : extras) -> 
417                 ASSERT( null extras )
418                 tcLookupId field_label                  `thenM` \ sel_id ->
419                 returnM (sel_id, pat_ty)
420         )                                               `thenM` \ (sel_id, pat_ty) ->
421
422         tcPat tc_bndr rhs_pat (Check pat_ty)    `thenM` \ (rhs_pat', tvs2, ids2, lie_avail2) ->
423
424         returnM ((sel_id, rhs_pat') : rpats',
425                   tvs1 `unionBags` tvs2,
426                   ids1 `unionBags` ids2,
427                   lie_avail1 ++ lie_avail2)
428 \end{code}
429
430
431 %************************************************************************
432 %*                                                                      *
433 \subsection{Subsumption}
434 %*                                                                      *
435 %************************************************************************
436
437 Example:  
438         f :: (forall a. a->a) -> Int -> Int
439         f (g::Int->Int) y = g y
440 This is ok: the type signature allows fewer callers than
441 the (more general) signature f :: (Int->Int) -> Int -> Int
442 I.e.    (forall a. a->a) <= Int -> Int
443 We end up translating this to:
444         f = \g' :: (forall a. a->a).  let g = g' Int in g' y
445
446 tcSubPat does the work
447         sig_ty is the signature on the pattern itself 
448                 (Int->Int in the example)
449         expected_ty is the type passed inwards from the context
450                 (forall a. a->a in the example)
451
452 \begin{code}
453 tcSubPat :: TcSigmaType -> Expected TcSigmaType -> TcM PatCoFn
454
455 tcSubPat sig_ty exp_ty
456  = tcSubOff sig_ty exp_ty               `thenM` \ co_fn ->
457         -- co_fn is a coercion on *expressions*, and we
458         -- need to make a coercion on *patterns*
459    if isIdCoercion co_fn then
460         returnM idCoercion
461    else
462    newUnique                            `thenM` \ uniq ->
463    readExpectedType exp_ty              `thenM` \ exp_ty' ->
464    let
465         arg_id  = mkSysLocal FSLIT("sub") uniq exp_ty'
466         the_fn  = DictLam [arg_id] (co_fn <$> HsVar arg_id)
467         pat_co_fn p = SigPatOut p exp_ty' the_fn
468    in
469    returnM (mkCoercion pat_co_fn)
470 \end{code}
471
472
473 %************************************************************************
474 %*                                                                      *
475 \subsection{Errors and contexts}
476 %*                                                                      *
477 %************************************************************************
478
479 \begin{code}
480 patCtxt pat = hang (ptext SLIT("When checking the pattern:")) 
481                  4 (ppr pat)
482
483 badFieldCon :: DataCon -> Name -> SDoc
484 badFieldCon con field
485   = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
486           ptext SLIT("does not have field"), quotes (ppr field)]
487
488 polyPatSig :: TcType -> SDoc
489 polyPatSig sig_ty
490   = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
491          4 (ppr sig_ty)
492
493 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
494 \end{code}
495