[project @ 2002-02-28 12:17:19 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            ( 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 pat_in@(SigPatIn pat sig) pat_ty
154   = tcAddErrCtxt (patCtxt pat_in)       $
155     tcHsSigType PatSigCtxt sig          `thenTc` \ sig_ty ->
156     tcSubPat sig_ty pat_ty              `thenTc` \ (co_fn, lie_sig) ->
157     tcPat tc_bndr pat sig_ty            `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
158     returnTc (co_fn <$> pat', lie_req `plusLIE` lie_sig, tvs, ids, lie_avail)
159 \end{code}
160
161
162 %************************************************************************
163 %*                                                                      *
164 \subsection{Explicit lists, parallel arrays, and tuples}
165 %*                                                                      *
166 %************************************************************************
167
168 \begin{code}
169 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
170   = tcAddErrCtxt (patCtxt pat_in)               $
171     unifyListTy pat_ty                          `thenTc` \ elem_ty ->
172     tcPats tc_bndr pats (repeat elem_ty)        `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
173     returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
174
175 tcPat tc_bndr pat_in@(PArrPatIn pats) pat_ty
176   = tcAddErrCtxt (patCtxt pat_in)               $
177     unifyPArrTy pat_ty                          `thenTc` \ elem_ty ->
178     tcPats tc_bndr pats (repeat elem_ty)        `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
179     returnTc (PArrPat elem_ty pats', lie_req, tvs, ids, lie_avail)
180
181 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
182   = tcAddErrCtxt (patCtxt pat_in)       $
183
184     unifyTupleTy boxity arity pat_ty            `thenTc` \ arg_tys ->
185     tcPats tc_bndr pats arg_tys                 `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
186
187         -- possibly do the "make all tuple-pats irrefutable" test:
188     let
189         unmangled_result = TuplePat pats' boxity
190
191         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
192         -- so that we can experiment with lazy tuple-matching.
193         -- This is a pretty odd place to make the switch, but
194         -- it was easy to do.
195
196         possibly_mangled_result
197           | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
198           | otherwise                               = unmangled_result
199     in
200     returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
201   where
202     arity = length pats
203 \end{code}
204
205
206 %************************************************************************
207 %*                                                                      *
208 \subsection{Other constructors}
209 %*                                                                      *
210
211 %************************************************************************
212
213 \begin{code}
214 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
215   = tcConPat tc_bndr pat name arg_pats pat_ty
216
217 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
218   = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
219 \end{code}
220
221
222 %************************************************************************
223 %*                                                                      *
224 \subsection{Records}
225 %*                                                                      *
226 %************************************************************************
227
228 \begin{code}
229 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
230   = tcAddErrCtxt (patCtxt pat)  $
231
232         -- Check the constructor itself
233     tcConstructor pat name              `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
234
235         -- Check overall type matches (c.f. tcConPat)
236     tcSubPat con_res_ty pat_ty          `thenTc` \ (co_fn, lie_req1) ->
237     let
238         -- Don't use zipEqual! If the constructor isn't really a record, then
239         -- dataConFieldLabels will be empty (and each field in the pattern
240         -- will generate an error below).
241         field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
242                         arg_tys
243     in
244
245         -- Check the fields
246     tc_fields field_tys rpats           `thenTc` \ (rpats', lie_req2, tvs, ids, lie_avail2) ->
247
248     returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
249               lie_req1 `plusLIE` lie_req2,
250               listToBag ex_tvs `unionBags` tvs,
251               ids,
252               lie_avail1 `plusLIE` lie_avail2)
253
254   where
255     tc_fields field_tys []
256       = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
257
258     tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
259       = tc_fields field_tys rpats       `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
260
261         (case [ty | (f,ty) <- field_tys, f == field_label] of
262
263                 -- No matching field; chances are this field label comes from some
264                 -- other record type (or maybe none).  As well as reporting an
265                 -- error we still want to typecheck the pattern, principally to
266                 -- make sure that all the variables it binds are put into the
267                 -- environment, else the type checker crashes later:
268                 --      f (R { foo = (a,b) }) = a+b
269                 -- If foo isn't one of R's fields, we don't want to crash when
270                 -- typechecking the "a+b".
271            [] -> addErrTc (badFieldCon name field_label)        `thenNF_Tc_` 
272                  newTyVarTy liftedTypeKind                      `thenNF_Tc_` 
273                  returnTc (error "Bogus selector Id", pat_ty)
274
275                 -- The normal case, when the field comes from the right constructor
276            (pat_ty : extras) -> 
277                 ASSERT( null extras )
278                 tcLookupGlobalId field_label                    `thenNF_Tc` \ sel_id ->
279                 returnTc (sel_id, pat_ty)
280         )                                                       `thenTc` \ (sel_id, pat_ty) ->
281
282         tcPat tc_bndr rhs_pat pat_ty    `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
283
284         returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
285                   lie_req1 `plusLIE` lie_req2,
286                   tvs1 `unionBags` tvs2,
287                   ids1 `unionBags` ids2,
288                   lie_avail1 `plusLIE` lie_avail2)
289 \end{code}
290
291 %************************************************************************
292 %*                                                                      *
293 \subsection{Literals}
294 %*                                                                      *
295 %************************************************************************
296
297 \begin{code}
298 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty 
299         -- cf tcExpr on LitLits
300   = tcLookupClass cCallableClassName            `thenNF_Tc` \ cCallableClass ->
301     newDicts (LitLitOrigin (_UNPK_ s))
302              [mkClassPred cCallableClass [pat_ty]]      `thenNF_Tc` \ dicts ->
303     returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
304
305 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
306   = unifyTauTy pat_ty stringTy                  `thenTc_` 
307     tcLookupGlobalId eqStringName               `thenNF_Tc` \ eq_id ->
308     returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit), 
309               emptyLIE, emptyBag, emptyBag, emptyLIE)
310
311 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
312   = unifyTauTy pat_ty (simpleHsLitTy simple_lit)                `thenTc_` 
313     returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
314
315 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
316   = newOverloadedLit (PatOrigin pat) over_lit pat_ty    `thenNF_Tc` \ (over_lit_expr, lie1) ->
317     tcLookupGlobalId eqName                             `thenNF_Tc` \ eq_sel_id ->
318     newMethod origin eq_sel_id [pat_ty]                 `thenNF_Tc` \ eq ->
319
320     returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) over_lit_expr),
321               lie1 `plusLIE` unitLIE eq,
322               emptyBag, emptyBag, emptyLIE)
323   where
324     origin = PatOrigin pat
325     lit' = case over_lit of
326                 HsIntegral i _   -> HsInteger i
327                 HsFractional f _ -> HsRat f pat_ty
328 \end{code}
329
330 %************************************************************************
331 %*                                                                      *
332 \subsection{n+k patterns}
333 %*                                                                      *
334 %************************************************************************
335
336 \begin{code}
337 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
338   = tc_bndr name pat_ty                         `thenTc` \ (co_fn, lie1, bndr_id) ->
339         -- The '-' part is re-mappable syntax
340     tcLookupId minus_name                       `thenNF_Tc` \ minus_sel_id ->
341     tcLookupGlobalId geName                     `thenNF_Tc` \ ge_sel_id ->
342     newOverloadedLit origin lit pat_ty          `thenNF_Tc` \ (over_lit_expr, lie2) ->
343     newMethod origin ge_sel_id    [pat_ty]      `thenNF_Tc` \ ge ->
344     newMethod origin minus_sel_id [pat_ty]      `thenNF_Tc` \ minus ->
345
346     returnTc (NPlusKPat bndr_id i pat_ty
347                         (SectionR (HsVar (instToId ge)) over_lit_expr)
348                         (SectionR (HsVar (instToId minus)) over_lit_expr),
349               lie1 `plusLIE` lie2 `plusLIE` mkLIE [ge,minus],
350               emptyBag, unitBag (name, bndr_id), emptyLIE)
351   where
352     origin = PatOrigin pat
353 \end{code}
354
355 %************************************************************************
356 %*                                                                      *
357 \subsection{Lists of patterns}
358 %*                                                                      *
359 %************************************************************************
360
361 Helper functions
362
363 \begin{code}
364 tcPats :: BinderChecker                         -- How to deal with variables
365        -> [RenamedPat] -> [TcType]              -- Excess 'expected types' discarded
366        -> TcM ([TcPat], 
367                  LIE,                           -- Required by n+k and literal pats
368                  Bag TcTyVar,
369                  Bag (Name, TcId),      -- Ids bound by the pattern
370                  LIE)                           -- Dicts bound by the pattern
371
372 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
373
374 tcPats tc_bndr (ty:tys) (pat:pats)
375   = tcPat tc_bndr ty pat                `thenTc` \ (pat',  lie_req1, tvs1, ids1, lie_avail1) ->
376     tcPats tc_bndr tys pats     `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
377
378     returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
379               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
380               lie_avail1 `plusLIE` lie_avail2)
381 \end{code}
382
383 ------------------------------------------------------
384 \begin{code}
385 tcConstructor pat con_name
386   =     -- Check that it's a constructor
387     tcLookupDataCon con_name            `thenNF_Tc` \ data_con ->
388
389         -- Instantiate it
390     let 
391         (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
392              -- Ignore the theta; overloaded constructors only
393              -- behave differently when called, not when used for
394              -- matching.
395     in
396     tcInstTyVars (ex_tvs ++ tvs)        `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
397     let
398         ex_theta' = substTheta tenv ex_theta
399         arg_tys'  = map (substTy tenv) arg_tys
400
401         n_ex_tvs  = length ex_tvs
402         ex_tvs'   = take n_ex_tvs all_tvs'
403         result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
404     in
405     newDicts (PatOrigin pat) ex_theta'  `thenNF_Tc` \ dicts ->
406
407     returnTc (data_con, ex_tvs', map instToId dicts, mkLIE dicts, arg_tys', result_ty)
408 \end{code}            
409
410 ------------------------------------------------------
411 \begin{code}
412 tcConPat tc_bndr pat con_name arg_pats pat_ty
413   = tcAddErrCtxt (patCtxt pat)  $
414
415         -- Check the constructor itself
416     tcConstructor pat con_name  `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys, con_res_ty) ->
417
418         -- Check overall type matches.
419         -- The pat_ty might be a for-all type, in which
420         -- case we must instantiate to match
421     tcSubPat con_res_ty pat_ty  `thenTc` \ (co_fn, lie_req1) ->
422
423         -- Check correct arity
424     let
425         con_arity  = dataConSourceArity data_con
426         no_of_args = length arg_pats
427     in
428     checkTc (con_arity == no_of_args)
429             (arityErr "Constructor" data_con con_arity no_of_args)      `thenTc_`
430
431         -- Check arguments
432     tcPats tc_bndr arg_pats arg_tys     `thenTc` \ (arg_pats', lie_req2, tvs, ids, lie_avail2) ->
433
434     returnTc (co_fn <$> ConPat data_con pat_ty ex_tvs dicts arg_pats',
435               lie_req1 `plusLIE` lie_req2,
436               listToBag ex_tvs `unionBags` tvs,
437               ids,
438               lie_avail1 `plusLIE` lie_avail2)
439 \end{code}
440
441
442 %************************************************************************
443 %*                                                                      *
444 \subsection{Subsumption}
445 %*                                                                      *
446 %************************************************************************
447
448 Example:  
449         f :: (forall a. a->a) -> Int -> Int
450         f (g::Int->Int) y = g y
451 This is ok: the type signature allows fewer callers than
452 the (more general) signature f :: (Int->Int) -> Int -> Int
453 I.e.    (forall a. a->a) <= Int -> Int
454 We end up translating this to:
455         f = \g' :: (forall a. a->a).  let g = g' Int in g' y
456
457 tcSubPat does the work
458         sig_ty is the signature on the pattern itself 
459                 (Int->Int in the example)
460         expected_ty is the type passed inwards from the context
461                 (forall a. a->a in the example)
462
463 \begin{code}
464 tcSubPat :: TcSigmaType -> TcSigmaType -> TcM (PatCoFn, LIE)
465
466 tcSubPat sig_ty exp_ty
467  = tcSub sig_ty exp_ty                  `thenTc` \ (co_fn, lie) ->
468         -- co_fn is a coercion on *expressions*, and we
469         -- need to make a coercion on *patterns*
470    if isIdCoercion co_fn then
471         ASSERT( isEmptyLIE lie )
472         returnNF_Tc (idCoercion, emptyLIE)
473    else
474    tcGetUnique                          `thenNF_Tc` \ uniq ->
475    let
476         arg_id  = mkSysLocal SLIT("sub") uniq exp_ty
477         the_fn  = DictLam [arg_id] (co_fn <$> HsVar arg_id)
478         pat_co_fn p = SigPat p exp_ty the_fn
479    in
480    returnNF_Tc (mkCoercion pat_co_fn, lie)
481 \end{code}
482
483
484 %************************************************************************
485 %*                                                                      *
486 \subsection{Errors and contexts}
487 %*                                                                      *
488 %************************************************************************
489
490 \begin{code}
491 patCtxt pat = hang (ptext SLIT("When checking the pattern:")) 
492                  4 (ppr pat)
493
494 badFieldCon :: Name -> Name -> SDoc
495 badFieldCon con field
496   = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
497           ptext SLIT("does not have field"), quotes (ppr field)]
498
499 polyPatSig :: TcType -> SDoc
500 polyPatSig sig_ty
501   = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
502          4 (ppr sig_ty)
503
504 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
505 \end{code}
506