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