[project @ 2001-11-29 12:20:08 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 pat_ty       `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
226     let
227         -- Don't use zipEqual! If the constructor isn't really a record, then
228         -- dataConFieldLabels will be empty (and each field in the pattern
229         -- will generate an error below).
230         field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
231                         arg_tys
232     in
233
234         -- Check the fields
235     tc_fields field_tys rpats           `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
236
237     returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
238               lie_req,
239               listToBag ex_tvs `unionBags` tvs,
240               ids,
241               lie_avail1 `plusLIE` lie_avail2)
242
243   where
244     tc_fields field_tys []
245       = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
246
247     tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
248       = tc_fields field_tys rpats       `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
249
250         (case [ty | (f,ty) <- field_tys, f == field_label] of
251
252                 -- No matching field; chances are this field label comes from some
253                 -- other record type (or maybe none).  As well as reporting an
254                 -- error we still want to typecheck the pattern, principally to
255                 -- make sure that all the variables it binds are put into the
256                 -- environment, else the type checker crashes later:
257                 --      f (R { foo = (a,b) }) = a+b
258                 -- If foo isn't one of R's fields, we don't want to crash when
259                 -- typechecking the "a+b".
260            [] -> addErrTc (badFieldCon name field_label)        `thenNF_Tc_` 
261                  newTyVarTy liftedTypeKind                      `thenNF_Tc_` 
262                  returnTc (error "Bogus selector Id", pat_ty)
263
264                 -- The normal case, when the field comes from the right constructor
265            (pat_ty : extras) -> 
266                 ASSERT( null extras )
267                 tcLookupGlobalId field_label                    `thenNF_Tc` \ sel_id ->
268                 returnTc (sel_id, pat_ty)
269         )                                                       `thenTc` \ (sel_id, pat_ty) ->
270
271         tcPat tc_bndr rhs_pat pat_ty    `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
272
273         returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
274                   lie_req1 `plusLIE` lie_req2,
275                   tvs1 `unionBags` tvs2,
276                   ids1 `unionBags` ids2,
277                   lie_avail1 `plusLIE` lie_avail2)
278 \end{code}
279
280 %************************************************************************
281 %*                                                                      *
282 \subsection{Literals}
283 %*                                                                      *
284 %************************************************************************
285
286 \begin{code}
287 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty 
288         -- cf tcExpr on LitLits
289   = tcLookupClass cCallableClassName            `thenNF_Tc` \ cCallableClass ->
290     newDicts (LitLitOrigin (_UNPK_ s))
291              [mkClassPred cCallableClass [pat_ty]]      `thenNF_Tc` \ dicts ->
292     returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
293
294 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
295   = unifyTauTy pat_ty stringTy                  `thenTc_` 
296     tcLookupGlobalId eqStringName               `thenNF_Tc` \ eq_id ->
297     returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit), 
298               emptyLIE, emptyBag, emptyBag, emptyLIE)
299
300 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
301   = unifyTauTy pat_ty (simpleHsLitTy simple_lit)                `thenTc_` 
302     returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
303
304 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
305   = newOverloadedLit (PatOrigin pat) over_lit pat_ty    `thenNF_Tc` \ (over_lit_expr, lie1) ->
306     tcLookupGlobalId eqName                             `thenNF_Tc` \ eq_sel_id ->
307     newMethod origin eq_sel_id [pat_ty]                 `thenNF_Tc` \ eq ->
308
309     returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) over_lit_expr),
310               lie1 `plusLIE` unitLIE eq,
311               emptyBag, emptyBag, emptyLIE)
312   where
313     origin = PatOrigin pat
314     lit' = case over_lit of
315                 HsIntegral i _   -> HsInteger i
316                 HsFractional f _ -> HsRat f pat_ty
317 \end{code}
318
319 %************************************************************************
320 %*                                                                      *
321 \subsection{n+k patterns}
322 %*                                                                      *
323 %************************************************************************
324
325 \begin{code}
326 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
327   = tc_bndr name pat_ty                         `thenTc` \ (co_fn, lie1, bndr_id) ->
328         -- The '-' part is re-mappable syntax
329     tcLookupId minus_name                       `thenNF_Tc` \ minus_sel_id ->
330     tcLookupGlobalId geName                     `thenNF_Tc` \ ge_sel_id ->
331     newOverloadedLit origin lit pat_ty          `thenNF_Tc` \ (over_lit_expr, lie2) ->
332     newMethod origin ge_sel_id    [pat_ty]      `thenNF_Tc` \ ge ->
333     newMethod origin minus_sel_id [pat_ty]      `thenNF_Tc` \ minus ->
334
335     returnTc (NPlusKPat bndr_id i pat_ty
336                         (SectionR (HsVar (instToId ge)) over_lit_expr)
337                         (SectionR (HsVar (instToId minus)) over_lit_expr),
338               lie1 `plusLIE` lie2 `plusLIE` mkLIE [ge,minus],
339               emptyBag, unitBag (name, bndr_id), emptyLIE)
340   where
341     origin = PatOrigin pat
342 \end{code}
343
344 %************************************************************************
345 %*                                                                      *
346 \subsection{Lists of patterns}
347 %*                                                                      *
348 %************************************************************************
349
350 Helper functions
351
352 \begin{code}
353 tcPats :: BinderChecker                         -- How to deal with variables
354        -> [RenamedPat] -> [TcType]              -- Excess 'expected types' discarded
355        -> TcM ([TcPat], 
356                  LIE,                           -- Required by n+k and literal pats
357                  Bag TcTyVar,
358                  Bag (Name, TcId),      -- Ids bound by the pattern
359                  LIE)                           -- Dicts bound by the pattern
360
361 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
362
363 tcPats tc_bndr (ty:tys) (pat:pats)
364   = tcPat tc_bndr ty pat                `thenTc` \ (pat',  lie_req1, tvs1, ids1, lie_avail1) ->
365     tcPats tc_bndr tys pats     `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
366
367     returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
368               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
369               lie_avail1 `plusLIE` lie_avail2)
370 \end{code}
371
372 ------------------------------------------------------
373 \begin{code}
374 tcConstructor pat con_name pat_ty
375   =     -- Check that it's a constructor
376     tcLookupDataCon con_name            `thenNF_Tc` \ data_con ->
377
378         -- Instantiate it
379     let 
380         (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
381              -- Ignore the theta; overloaded constructors only
382              -- behave differently when called, not when used for
383              -- matching.
384     in
385     tcInstTyVars (ex_tvs ++ tvs)        `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
386     let
387         ex_theta' = substTheta tenv ex_theta
388         arg_tys'  = map (substTy tenv) arg_tys
389
390         n_ex_tvs  = length ex_tvs
391         ex_tvs'   = take n_ex_tvs all_tvs'
392         result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
393     in
394     newDicts (PatOrigin pat) ex_theta'  `thenNF_Tc` \ dicts ->
395
396         -- Check overall type matches
397     unifyTauTy pat_ty result_ty         `thenTc_`
398
399     returnTc (data_con, ex_tvs', map instToId dicts, mkLIE dicts, arg_tys')
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 pat_ty   `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
409
410         -- Check correct arity
411     let
412         con_arity  = dataConSourceArity data_con
413         no_of_args = length arg_pats
414     in
415     checkTc (con_arity == no_of_args)
416             (arityErr "Constructor" data_con con_arity no_of_args)      `thenTc_`
417
418         -- Check arguments
419     tcPats tc_bndr arg_pats arg_tys'    `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
420
421     returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
422               lie_req,
423               listToBag ex_tvs' `unionBags` tvs,
424               ids,
425               lie_avail1 `plusLIE` lie_avail2)
426 \end{code}
427
428
429 %************************************************************************
430 %*                                                                      *
431 \subsection{Subsumption}
432 %*                                                                      *
433 %************************************************************************
434
435 Example:  
436         f :: (forall a. a->a) -> Int -> Int
437         f (g::Int->Int) y = g y
438 This is ok: the type signature allows fewer callers than
439 the (more general) signature f :: (Int->Int) -> Int -> Int
440 I.e.    (forall a. a->a) <= Int -> Int
441 We end up translating this to:
442         f = \g' :: (forall a. a->a).  let g = g' Int in g' y
443
444 tcSubPat does the work
445         sig_ty is the signature on the pattern itself 
446                 (Int->Int in the example)
447         expected_ty is the type passed inwards from the context
448                 (forall a. a->a in the example)
449
450 \begin{code}
451 tcSubPat :: TcSigmaType -> TcSigmaType -> TcM (PatCoFn, LIE)
452
453 tcSubPat sig_ty exp_ty
454  = tcSub exp_ty sig_ty                  `thenTc` \ (co_fn, lie) ->
455         -- co_fn is a coercion on *expressions*, and we
456         -- need to make a coercion on *patterns*
457    if isIdCoercion co_fn then
458         ASSERT( isEmptyLIE lie )
459         returnNF_Tc (idCoercion, emptyLIE)
460    else
461    tcGetUnique                          `thenNF_Tc` \ uniq ->
462    let
463         arg_id  = mkSysLocal SLIT("sub") uniq exp_ty
464         the_fn  = DictLam [arg_id] (co_fn <$> HsVar arg_id)
465         pat_co_fn p = SigPat p exp_ty the_fn
466    in
467    returnNF_Tc (mkCoercion pat_co_fn, lie)
468 \end{code}
469
470
471 %************************************************************************
472 %*                                                                      *
473 \subsection{Errors and contexts}
474 %*                                                                      *
475 %************************************************************************
476
477 \begin{code}
478 patCtxt pat = hang (ptext SLIT("In the pattern:")) 
479                  4 (ppr pat)
480
481 badFieldCon :: Name -> Name -> SDoc
482 badFieldCon con field
483   = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
484           ptext SLIT("does not have field"), quotes (ppr field)]
485
486 polyPatSig :: TcType -> SDoc
487 polyPatSig sig_ty
488   = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
489          4 (ppr sig_ty)
490
491 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
492 \end{code}
493