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