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