[project @ 2002-02-11 08:20:38 by chak]
[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            ( InPat(..), OutPat(..), HsLit(..), HsOverLit(..), HsExpr(..) )
14 import RnHsSyn          ( RenamedPat )
15 import TcHsSyn          ( TcPat, TcId, simpleHsLitTy )
16
17 import TcMonad
18 import Inst             ( InstOrigin(..),
19                           emptyLIE, plusLIE, LIE, mkLIE, unitLIE, instToId, isEmptyLIE,
20                           newMethod, newOverloadedLit, newDicts
21                         )
22 import Id               ( mkLocalId, mkSysLocal )
23 import Name             ( Name )
24 import FieldLabel       ( fieldLabelName )
25 import TcEnv            ( tcLookupClass, tcLookupDataCon, tcLookupGlobalId, tcLookupId )
26 import TcMType          ( tcInstTyVars, newTyVarTy, getTcTyVar, putTcTyVar )
27 import TcType           ( TcType, TcTyVar, TcSigmaType,
28                           mkTyConApp, mkClassPred, liftedTypeKind, tcGetTyVar_maybe,
29                           isHoleTyVar, openTypeKind )
30 import TcUnify          ( tcSub, unifyTauTy, unifyListTy, unifyPArrTy,
31                           unifyTupleTy,  mkCoercion, idCoercion, isIdCoercion,
32                           (<$>), PatCoFn )
33 import TcMonoType       ( tcHsSigType, UserTypeCtxt(..) )
34
35 import TysWiredIn       ( stringTy )
36 import CmdLineOpts      ( opt_IrrefutableTuples )
37 import DataCon          ( dataConSig, dataConFieldLabels, 
38                           dataConSourceArity
39                         )
40 import Subst            ( substTy, substTheta )
41 import PrelNames        ( eqStringName, eqName, geName, cCallableClassName )
42 import BasicTypes       ( isBoxed )
43 import Bag
44 import Outputable
45 \end{code}
46
47
48 %************************************************************************
49 %*                                                                      *
50 \subsection{Variable patterns}
51 %*                                                                      *
52 %************************************************************************
53
54 \begin{code}
55 type BinderChecker = Name -> TcSigmaType -> TcM (PatCoFn, LIE, 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   | Just tv <- tcGetTyVar_maybe pat_ty,
73     isHoleTyVar tv
74         -- If there are *no constraints* on the pattern type, we
75         -- revert to good old H-M typechecking, making
76         -- the type of the binder into an *ordinary* 
77         -- type variable.  We find out if there are no constraints
78         -- by seeing if we are given an "open hole" as our info.
79         -- What we are trying to avoid here is giving a binder
80         -- a type that is a 'hole'.  The only place holes should
81         -- appear is as an argument to tcPat and tcExpr/tcMonoExpr.
82   = getTcTyVar tv       `thenNF_Tc` \ maybe_ty ->
83     case maybe_ty of
84         Just ty -> tcMonoPatBndr binder_name ty
85         Nothing -> newTyVarTy openTypeKind      `thenNF_Tc` \ ty ->
86                    putTcTyVar tv ty             `thenNF_Tc_`
87                    returnTc (idCoercion, emptyLIE, mkLocalId binder_name ty)
88   | otherwise
89   = returnTc (idCoercion, emptyLIE, mkLocalId binder_name pat_ty)
90 \end{code}
91
92
93 %************************************************************************
94 %*                                                                      *
95 \subsection{Typechecking patterns}
96 %*                                                                      *
97 %************************************************************************
98
99 \begin{code}
100 tcPat :: BinderChecker
101       -> RenamedPat
102
103       -> TcSigmaType    -- Expected type derived from the context
104                         --      In the case of a function with a rank-2 signature,
105                         --      this type might be a forall type.
106
107       -> TcM (TcPat, 
108                 LIE,                    -- Required by n+k and literal pats
109                 Bag TcTyVar,    -- TyVars bound by the pattern
110                                         --      These are just the existentially-bound ones.
111                                         --      Any tyvars bound by *type signatures* in the
112                                         --      patterns are brought into scope before we begin.
113                 Bag (Name, TcId),       -- Ids bound by the pattern, along with the Name under
114                                         --      which it occurs in the pattern
115                                         --      The two aren't the same because we conjure up a new
116                                         --      local name for each variable.
117                 LIE)                    -- Dicts or methods [see below] bound by the pattern
118                                         --      from existential constructor patterns
119 \end{code}
120
121
122 %************************************************************************
123 %*                                                                      *
124 \subsection{Variables, wildcards, lazy pats, as-pats}
125 %*                                                                      *
126 %************************************************************************
127
128 \begin{code}
129 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
130   = failWithTc (badTypePat pat)
131
132 tcPat tc_bndr (VarPatIn name) pat_ty
133   = tc_bndr name pat_ty                         `thenTc` \ (co_fn, lie_req, bndr_id) ->
134     returnTc (co_fn <$> VarPat bndr_id, lie_req,
135               emptyBag, unitBag (name, bndr_id), emptyLIE)
136
137 tcPat tc_bndr (LazyPatIn pat) pat_ty
138   = tcPat tc_bndr pat pat_ty            `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
139     returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
140
141 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
142   = tc_bndr name pat_ty                 `thenTc` \ (co_fn, lie_req1, bndr_id) ->
143     tcPat tc_bndr pat pat_ty            `thenTc` \ (pat', lie_req2, tvs, ids, lie_avail) ->
144     returnTc (co_fn <$> (AsPat bndr_id pat'), lie_req1 `plusLIE` lie_req2, 
145               tvs, (name, bndr_id) `consBag` ids, lie_avail)
146
147 tcPat tc_bndr WildPatIn pat_ty
148   = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
149
150 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
151   = tcPat tc_bndr parend_pat pat_ty
152
153 tcPat tc_bndr (SigPatIn pat sig) pat_ty
154   = tcHsSigType PatSigCtxt sig          `thenTc` \ sig_ty ->
155     tcSubPat sig_ty pat_ty              `thenTc` \ (co_fn, lie_sig) ->
156     tcPat tc_bndr pat sig_ty            `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
157     returnTc (co_fn <$> pat', lie_req `plusLIE` lie_sig, tvs, ids, lie_avail)
158 \end{code}
159
160
161 %************************************************************************
162 %*                                                                      *
163 \subsection{Explicit lists, parallel arrays, and tuples}
164 %*                                                                      *
165 %************************************************************************
166
167 \begin{code}
168 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
169   = tcAddErrCtxt (patCtxt pat_in)               $
170     unifyListTy pat_ty                          `thenTc` \ elem_ty ->
171     tcPats tc_bndr pats (repeat elem_ty)        `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
172     returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
173
174 tcPat tc_bndr pat_in@(PArrPatIn pats) pat_ty
175   = tcAddErrCtxt (patCtxt pat_in)               $
176     unifyPArrTy pat_ty                          `thenTc` \ elem_ty ->
177     tcPats tc_bndr pats (repeat elem_ty)        `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
178     returnTc (PArrPat elem_ty pats', lie_req, tvs, ids, lie_avail)
179
180 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
181   = tcAddErrCtxt (patCtxt pat_in)       $
182
183     unifyTupleTy boxity arity pat_ty            `thenTc` \ arg_tys ->
184     tcPats tc_bndr pats arg_tys                 `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
185
186         -- possibly do the "make all tuple-pats irrefutable" test:
187     let
188         unmangled_result = TuplePat pats' boxity
189
190         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
191         -- so that we can experiment with lazy tuple-matching.
192         -- This is a pretty odd place to make the switch, but
193         -- it was easy to do.
194
195         possibly_mangled_result
196           | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
197           | otherwise                               = unmangled_result
198     in
199     returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
200   where
201     arity = length pats
202 \end{code}
203
204
205 %************************************************************************
206 %*                                                                      *
207 \subsection{Other constructors}
208 %*                                                                      *
209
210 %************************************************************************
211
212 \begin{code}
213 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
214   = tcConPat tc_bndr pat name arg_pats pat_ty
215
216 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
217   = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
218 \end{code}
219
220
221 %************************************************************************
222 %*                                                                      *
223 \subsection{Records}
224 %*                                                                      *
225 %************************************************************************
226
227 \begin{code}
228 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
229   = tcAddErrCtxt (patCtxt pat)  $
230
231         -- Check the constructor itself
232     tcConstructor pat name              `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
233
234         -- Check overall type matches (c.f. tcConPat)
235     tcSubPat con_res_ty pat_ty          `thenTc` \ (co_fn, lie_req1) ->
236     let
237         -- Don't use zipEqual! If the constructor isn't really a record, then
238         -- dataConFieldLabels will be empty (and each field in the pattern
239         -- will generate an error below).
240         field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
241                         arg_tys
242     in
243
244         -- Check the fields
245     tc_fields field_tys rpats           `thenTc` \ (rpats', lie_req2, tvs, ids, lie_avail2) ->
246
247     returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
248               lie_req1 `plusLIE` lie_req2,
249               listToBag ex_tvs `unionBags` tvs,
250               ids,
251               lie_avail1 `plusLIE` lie_avail2)
252
253   where
254     tc_fields field_tys []
255       = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
256
257     tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
258       = tc_fields field_tys rpats       `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
259
260         (case [ty | (f,ty) <- field_tys, f == field_label] of
261
262                 -- No matching field; chances are this field label comes from some
263                 -- other record type (or maybe none).  As well as reporting an
264                 -- error we still want to typecheck the pattern, principally to
265                 -- make sure that all the variables it binds are put into the
266                 -- environment, else the type checker crashes later:
267                 --      f (R { foo = (a,b) }) = a+b
268                 -- If foo isn't one of R's fields, we don't want to crash when
269                 -- typechecking the "a+b".
270            [] -> addErrTc (badFieldCon name field_label)        `thenNF_Tc_` 
271                  newTyVarTy liftedTypeKind                      `thenNF_Tc_` 
272                  returnTc (error "Bogus selector Id", pat_ty)
273
274                 -- The normal case, when the field comes from the right constructor
275            (pat_ty : extras) -> 
276                 ASSERT( null extras )
277                 tcLookupGlobalId field_label                    `thenNF_Tc` \ sel_id ->
278                 returnTc (sel_id, pat_ty)
279         )                                                       `thenTc` \ (sel_id, pat_ty) ->
280
281         tcPat tc_bndr rhs_pat pat_ty    `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
282
283         returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
284                   lie_req1 `plusLIE` lie_req2,
285                   tvs1 `unionBags` tvs2,
286                   ids1 `unionBags` ids2,
287                   lie_avail1 `plusLIE` lie_avail2)
288 \end{code}
289
290 %************************************************************************
291 %*                                                                      *
292 \subsection{Literals}
293 %*                                                                      *
294 %************************************************************************
295
296 \begin{code}
297 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty 
298         -- cf tcExpr on LitLits
299   = tcLookupClass cCallableClassName            `thenNF_Tc` \ cCallableClass ->
300     newDicts (LitLitOrigin (_UNPK_ s))
301              [mkClassPred cCallableClass [pat_ty]]      `thenNF_Tc` \ dicts ->
302     returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
303
304 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
305   = unifyTauTy pat_ty stringTy                  `thenTc_` 
306     tcLookupGlobalId eqStringName               `thenNF_Tc` \ eq_id ->
307     returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit), 
308               emptyLIE, emptyBag, emptyBag, emptyLIE)
309
310 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
311   = unifyTauTy pat_ty (simpleHsLitTy simple_lit)                `thenTc_` 
312     returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
313
314 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
315   = newOverloadedLit (PatOrigin pat) over_lit pat_ty    `thenNF_Tc` \ (over_lit_expr, lie1) ->
316     tcLookupGlobalId eqName                             `thenNF_Tc` \ eq_sel_id ->
317     newMethod origin eq_sel_id [pat_ty]                 `thenNF_Tc` \ eq ->
318
319     returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) over_lit_expr),
320               lie1 `plusLIE` unitLIE eq,
321               emptyBag, emptyBag, emptyLIE)
322   where
323     origin = PatOrigin pat
324     lit' = case over_lit of
325                 HsIntegral i _   -> HsInteger i
326                 HsFractional f _ -> HsRat f pat_ty
327 \end{code}
328
329 %************************************************************************
330 %*                                                                      *
331 \subsection{n+k patterns}
332 %*                                                                      *
333 %************************************************************************
334
335 \begin{code}
336 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
337   = tc_bndr name pat_ty                         `thenTc` \ (co_fn, lie1, bndr_id) ->
338         -- The '-' part is re-mappable syntax
339     tcLookupId minus_name                       `thenNF_Tc` \ minus_sel_id ->
340     tcLookupGlobalId geName                     `thenNF_Tc` \ ge_sel_id ->
341     newOverloadedLit origin lit pat_ty          `thenNF_Tc` \ (over_lit_expr, lie2) ->
342     newMethod origin ge_sel_id    [pat_ty]      `thenNF_Tc` \ ge ->
343     newMethod origin minus_sel_id [pat_ty]      `thenNF_Tc` \ minus ->
344
345     returnTc (NPlusKPat bndr_id i pat_ty
346                         (SectionR (HsVar (instToId ge)) over_lit_expr)
347                         (SectionR (HsVar (instToId minus)) over_lit_expr),
348               lie1 `plusLIE` lie2 `plusLIE` mkLIE [ge,minus],
349               emptyBag, unitBag (name, bndr_id), emptyLIE)
350   where
351     origin = PatOrigin pat
352 \end{code}
353
354 %************************************************************************
355 %*                                                                      *
356 \subsection{Lists of patterns}
357 %*                                                                      *
358 %************************************************************************
359
360 Helper functions
361
362 \begin{code}
363 tcPats :: BinderChecker                         -- How to deal with variables
364        -> [RenamedPat] -> [TcType]              -- Excess 'expected types' discarded
365        -> TcM ([TcPat], 
366                  LIE,                           -- Required by n+k and literal pats
367                  Bag TcTyVar,
368                  Bag (Name, TcId),      -- Ids bound by the pattern
369                  LIE)                           -- Dicts bound by the pattern
370
371 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
372
373 tcPats tc_bndr (ty:tys) (pat:pats)
374   = tcPat tc_bndr ty pat                `thenTc` \ (pat',  lie_req1, tvs1, ids1, lie_avail1) ->
375     tcPats tc_bndr tys pats     `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
376
377     returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
378               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
379               lie_avail1 `plusLIE` lie_avail2)
380 \end{code}
381
382 ------------------------------------------------------
383 \begin{code}
384 tcConstructor pat con_name
385   =     -- Check that it's a constructor
386     tcLookupDataCon con_name            `thenNF_Tc` \ data_con ->
387
388         -- Instantiate it
389     let 
390         (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
391              -- Ignore the theta; overloaded constructors only
392              -- behave differently when called, not when used for
393              -- matching.
394     in
395     tcInstTyVars (ex_tvs ++ tvs)        `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
396     let
397         ex_theta' = substTheta tenv ex_theta
398         arg_tys'  = map (substTy tenv) arg_tys
399
400         n_ex_tvs  = length ex_tvs
401         ex_tvs'   = take n_ex_tvs all_tvs'
402         result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
403     in
404     newDicts (PatOrigin pat) ex_theta'  `thenNF_Tc` \ dicts ->
405
406     returnTc (data_con, ex_tvs', map instToId dicts, mkLIE dicts, arg_tys', result_ty)
407 \end{code}            
408
409 ------------------------------------------------------
410 \begin{code}
411 tcConPat tc_bndr pat con_name arg_pats pat_ty
412   = tcAddErrCtxt (patCtxt pat)  $
413
414         -- Check the constructor itself
415     tcConstructor pat con_name  `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
416
417         -- Check overall type matches.
418         -- The pat_ty might be a for-all type, in which
419         -- case we must instantiate to match
420     tcSubPat con_res_ty pat_ty  `thenTc` \ (co_fn, lie_req1) ->
421
422         -- Check correct arity
423     let
424         con_arity  = dataConSourceArity data_con
425         no_of_args = length arg_pats
426     in
427     checkTc (con_arity == no_of_args)
428             (arityErr "Constructor" data_con con_arity no_of_args)      `thenTc_`
429
430         -- Check arguments
431     tcPats tc_bndr arg_pats arg_tys     `thenTc` \ (arg_pats', lie_req2, tvs, ids, lie_avail2) ->
432
433     returnTc (co_fn <$> ConPat data_con pat_ty ex_tvs dicts arg_pats',
434               lie_req1 `plusLIE` lie_req2,
435               listToBag ex_tvs `unionBags` tvs,
436               ids,
437               lie_avail1 `plusLIE` 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 -> TcSigmaType -> TcM (PatCoFn, LIE)
464
465 tcSubPat sig_ty exp_ty
466  = tcSub exp_ty sig_ty                  `thenTc` \ (co_fn, lie) ->
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         ASSERT( isEmptyLIE lie )
471         returnNF_Tc (idCoercion, emptyLIE)
472    else
473    tcGetUnique                          `thenNF_Tc` \ uniq ->
474    let
475         arg_id  = mkSysLocal SLIT("sub") uniq exp_ty
476         the_fn  = DictLam [arg_id] (co_fn <$> HsVar arg_id)
477         pat_co_fn p = SigPat p exp_ty the_fn
478    in
479    returnNF_Tc (mkCoercion pat_co_fn, lie)
480 \end{code}
481
482
483 %************************************************************************
484 %*                                                                      *
485 \subsection{Errors and contexts}
486 %*                                                                      *
487 %************************************************************************
488
489 \begin{code}
490 patCtxt pat = hang (ptext SLIT("In the pattern:")) 
491                  4 (ppr pat)
492
493 badFieldCon :: Name -> 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