[project @ 2002-07-29 13:19:52 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, newMethodFromName, newOverloadedLit, newDicts,
21                           tcInstDataCon, tcSyntaxName
22                         )
23 import Id               ( mkLocalId, mkSysLocal )
24 import Name             ( Name )
25 import FieldLabel       ( fieldLabelName )
26 import TcEnv            ( tcLookupClass, tcLookupDataCon, tcLookupGlobalId, tcLookupId )
27 import TcMType          ( newTyVarTy, zapToType )
28 import TcType           ( TcType, TcTyVar, TcSigmaType, 
29                           mkClassPred, liftedTypeKind )
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          ( dataConFieldLabels, dataConSourceArity )
39 import PrelNames        ( eqStringName, eqName, geName, minusName, cCallableClassName )
40 import BasicTypes       ( isBoxed )
41 import Bag
42 import Outputable
43 import FastString
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   = zapToType pat_ty    `thenNF_Tc` \ pat_ty' ->
72         -- If there are *no constraints* on the pattern type, we
73         -- revert to good old H-M typechecking, making
74         -- the type of the binder into an *ordinary* 
75         -- type variable.  We find out if there are no constraints
76         -- by seeing if we are given an "open hole" as our info.
77         -- What we are trying to avoid here is giving a binder
78         -- a type that is a 'hole'.  The only place holes should
79         -- appear is as an argument to tcPat and tcExpr/tcMonoExpr.
80
81     returnTc (idCoercion, emptyLIE, mkLocalId binder_name pat_ty')
82 \end{code}
83
84
85 %************************************************************************
86 %*                                                                      *
87 \subsection{Typechecking patterns}
88 %*                                                                      *
89 %************************************************************************
90
91 \begin{code}
92 tcPat :: BinderChecker
93       -> RenamedPat
94
95       -> TcHoleType     -- Expected type derived from the context
96                         --      In the case of a function with a rank-2 signature,
97                         --      this type might be a forall type.
98
99       -> TcM (TcPat, 
100                 LIE,                    -- Required by n+k and literal pats
101                 Bag TcTyVar,    -- TyVars bound by the pattern
102                                         --      These are just the existentially-bound ones.
103                                         --      Any tyvars bound by *type signatures* in the
104                                         --      patterns are brought into scope before we begin.
105                 Bag (Name, TcId),       -- Ids bound by the pattern, along with the Name under
106                                         --      which it occurs in the pattern
107                                         --      The two aren't the same because we conjure up a new
108                                         --      local name for each variable.
109                 LIE)                    -- Dicts or methods [see below] bound by the pattern
110                                         --      from existential constructor patterns
111 \end{code}
112
113
114 %************************************************************************
115 %*                                                                      *
116 \subsection{Variables, wildcards, lazy pats, as-pats}
117 %*                                                                      *
118 %************************************************************************
119
120 \begin{code}
121 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
122   = failWithTc (badTypePat pat)
123
124 tcPat tc_bndr (VarPatIn name) pat_ty
125   = tc_bndr name pat_ty                         `thenTc` \ (co_fn, lie_req, bndr_id) ->
126     returnTc (co_fn <$> VarPat bndr_id, lie_req,
127               emptyBag, unitBag (name, bndr_id), emptyLIE)
128
129 tcPat tc_bndr (LazyPatIn pat) pat_ty
130   = tcPat tc_bndr pat pat_ty            `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
131     returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
132
133 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
134   = tc_bndr name pat_ty                 `thenTc` \ (co_fn, lie_req1, bndr_id) ->
135     tcPat tc_bndr pat pat_ty            `thenTc` \ (pat', lie_req2, tvs, ids, lie_avail) ->
136     returnTc (co_fn <$> (AsPat bndr_id pat'), lie_req1 `plusLIE` lie_req2, 
137               tvs, (name, bndr_id) `consBag` ids, lie_avail)
138
139 tcPat tc_bndr WildPatIn pat_ty
140   = zapToType pat_ty                    `thenNF_Tc` \ pat_ty' ->
141         -- We might have an incoming 'hole' type variable; no annotation
142         -- so zap it to a type.  Rather like tcMonoPatBndr.
143     returnTc (WildPat pat_ty', emptyLIE, emptyBag, emptyBag, emptyLIE)
144
145 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
146   = tcPat tc_bndr parend_pat pat_ty
147
148 tcPat tc_bndr pat_in@(SigPatIn pat sig) pat_ty
149   = tcAddErrCtxt (patCtxt pat_in)       $
150     tcHsSigType PatSigCtxt sig          `thenTc` \ sig_ty ->
151     tcSubPat sig_ty pat_ty              `thenTc` \ (co_fn, lie_sig) ->
152     tcPat tc_bndr pat sig_ty            `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
153     returnTc (co_fn <$> pat', lie_req `plusLIE` lie_sig, tvs, ids, lie_avail)
154 \end{code}
155
156
157 %************************************************************************
158 %*                                                                      *
159 \subsection{Explicit lists, parallel arrays, and tuples}
160 %*                                                                      *
161 %************************************************************************
162
163 \begin{code}
164 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
165   = tcAddErrCtxt (patCtxt pat_in)               $
166     unifyListTy pat_ty                          `thenTc` \ elem_ty ->
167     tcPats tc_bndr pats (repeat elem_ty)        `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
168     returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
169
170 tcPat tc_bndr pat_in@(PArrPatIn pats) pat_ty
171   = tcAddErrCtxt (patCtxt pat_in)               $
172     unifyPArrTy pat_ty                          `thenTc` \ elem_ty ->
173     tcPats tc_bndr pats (repeat elem_ty)        `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
174     returnTc (PArrPat elem_ty pats', lie_req, tvs, ids, lie_avail)
175
176 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
177   = tcAddErrCtxt (patCtxt pat_in)       $
178
179     unifyTupleTy boxity arity pat_ty            `thenTc` \ arg_tys ->
180     tcPats tc_bndr pats arg_tys                 `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
181
182         -- possibly do the "make all tuple-pats irrefutable" test:
183     let
184         unmangled_result = TuplePat pats' boxity
185
186         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
187         -- so that we can experiment with lazy tuple-matching.
188         -- This is a pretty odd place to make the switch, but
189         -- it was easy to do.
190
191         possibly_mangled_result
192           | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
193           | otherwise                               = unmangled_result
194     in
195     returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
196   where
197     arity = length pats
198 \end{code}
199
200
201 %************************************************************************
202 %*                                                                      *
203 \subsection{Other constructors}
204 %*                                                                      *
205
206 %************************************************************************
207
208 \begin{code}
209 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
210   = tcConPat tc_bndr pat name arg_pats pat_ty
211
212 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
213   = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
214 \end{code}
215
216
217 %************************************************************************
218 %*                                                                      *
219 \subsection{Records}
220 %*                                                                      *
221 %************************************************************************
222
223 \begin{code}
224 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
225   = tcAddErrCtxt (patCtxt pat)  $
226
227         -- Check the constructor itself
228     tcConstructor pat name              `thenTc` \ (data_con, lie_req1, ex_tvs, ex_dicts, lie_avail1, arg_tys, con_res_ty) ->
229
230         -- Check overall type matches (c.f. tcConPat)
231     tcSubPat con_res_ty pat_ty          `thenTc` \ (co_fn, lie_req2) ->
232     let
233         -- Don't use zipEqual! If the constructor isn't really a record, then
234         -- dataConFieldLabels will be empty (and each field in the pattern
235         -- will generate an error below).
236         field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
237                         arg_tys
238     in
239
240         -- Check the fields
241     tc_fields field_tys rpats           `thenTc` \ (rpats', lie_req3, tvs, ids, lie_avail2) ->
242
243     returnTc (RecPat data_con pat_ty ex_tvs ex_dicts rpats',
244               lie_req1 `plusLIE` lie_req2 `plusLIE` lie_req3,
245               listToBag ex_tvs `unionBags` tvs,
246               ids,
247               lie_avail1 `plusLIE` lie_avail2)
248
249   where
250     tc_fields field_tys []
251       = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
252
253     tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
254       = tc_fields field_tys rpats       `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
255
256         (case [ty | (f,ty) <- field_tys, f == field_label] of
257
258                 -- No matching field; chances are this field label comes from some
259                 -- other record type (or maybe none).  As well as reporting an
260                 -- error we still want to typecheck the pattern, principally to
261                 -- make sure that all the variables it binds are put into the
262                 -- environment, else the type checker crashes later:
263                 --      f (R { foo = (a,b) }) = a+b
264                 -- If foo isn't one of R's fields, we don't want to crash when
265                 -- typechecking the "a+b".
266            [] -> addErrTc (badFieldCon name field_label)        `thenNF_Tc_` 
267                  newTyVarTy liftedTypeKind                      `thenNF_Tc_` 
268                  returnTc (error "Bogus selector Id", pat_ty)
269
270                 -- The normal case, when the field comes from the right constructor
271            (pat_ty : extras) -> 
272                 ASSERT( null extras )
273                 tcLookupGlobalId field_label                    `thenNF_Tc` \ sel_id ->
274                 returnTc (sel_id, pat_ty)
275         )                                                       `thenTc` \ (sel_id, pat_ty) ->
276
277         tcPat tc_bndr rhs_pat pat_ty    `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
278
279         returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
280                   lie_req1 `plusLIE` lie_req2,
281                   tvs1 `unionBags` tvs2,
282                   ids1 `unionBags` ids2,
283                   lie_avail1 `plusLIE` lie_avail2)
284 \end{code}
285
286 %************************************************************************
287 %*                                                                      *
288 \subsection{Literals}
289 %*                                                                      *
290 %************************************************************************
291
292 \begin{code}
293 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty 
294         -- cf tcExpr on LitLits
295   = tcLookupClass cCallableClassName            `thenNF_Tc` \ cCallableClass ->
296     newDicts (LitLitOrigin (unpackFS s))
297              [mkClassPred cCallableClass [pat_ty]]      `thenNF_Tc` \ dicts ->
298     returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
299
300 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
301   = unifyTauTy pat_ty stringTy                  `thenTc_` 
302     tcLookupGlobalId eqStringName               `thenNF_Tc` \ eq_id ->
303     returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit), 
304               emptyLIE, emptyBag, emptyBag, emptyLIE)
305
306 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
307   = unifyTauTy pat_ty (simpleHsLitTy simple_lit)                `thenTc_` 
308     returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
309
310 tcPat tc_bndr pat@(NPatIn over_lit mb_neg) pat_ty
311   = newOverloadedLit origin over_lit pat_ty             `thenNF_Tc` \ (pos_lit_expr, lie1) ->
312     newMethodFromName origin pat_ty eqName              `thenNF_Tc` \ eq ->
313     (case mb_neg of
314         Nothing  -> returnNF_Tc (pos_lit_expr, emptyLIE)        -- Positive literal
315         Just neg ->     -- Negative literal
316                         -- The 'negate' is re-mappable syntax
317                     tcLookupId neg                              `thenNF_Tc` \ neg_sel_id ->
318                     newMethod origin neg_sel_id [pat_ty]        `thenNF_Tc` \ neg ->
319                     returnNF_Tc (HsApp (HsVar (instToId neg)) pos_lit_expr, unitLIE neg)
320     )                                                           `thenNF_Tc` \ (lit_expr, lie2) ->
321
322     returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) lit_expr),
323               lie1 `plusLIE` lie2 `plusLIE` unitLIE eq,
324               emptyBag, emptyBag, emptyLIE)
325   where
326     origin = PatOrigin pat
327
328         -- The literal in an NPatIn is always positive...
329         -- But in NPat, the literal is used to find identical patterns
330         --      so we must negate the literal when necessary!
331     lit' = case (over_lit, mb_neg) of
332              (HsIntegral i _, Nothing)   -> HsInteger i
333              (HsIntegral i _, Just _)    -> HsInteger (-i)
334              (HsFractional f _, Nothing) -> HsRat f pat_ty
335              (HsFractional f _, Just _)  -> HsRat (-f) pat_ty
336 \end{code}
337
338 %************************************************************************
339 %*                                                                      *
340 \subsection{n+k patterns}
341 %*                                                                      *
342 %************************************************************************
343
344 \begin{code}
345 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus_name) pat_ty
346   = tc_bndr name pat_ty                         `thenTc` \ (co_fn, lie1, bndr_id) ->
347     newOverloadedLit origin lit pat_ty          `thenNF_Tc` \ (over_lit_expr, lie2) ->
348     newMethodFromName origin pat_ty geName      `thenNF_Tc` \ ge ->
349
350         -- The '-' part is re-mappable syntax
351     tcSyntaxName origin pat_ty minusName minus_name     `thenTc` \ (minus_expr, minus_lie, _) ->
352
353     returnTc (NPlusKPat bndr_id i pat_ty
354                         (SectionR (HsVar (instToId ge)) over_lit_expr)
355                         (SectionR minus_expr over_lit_expr),
356               lie1 `plusLIE` lie2 `plusLIE` minus_lie `plusLIE` unitLIE ge,
357               emptyBag, unitBag (name, bndr_id), emptyLIE)
358   where
359     origin = PatOrigin pat
360 \end{code}
361
362 %************************************************************************
363 %*                                                                      *
364 \subsection{Lists of patterns}
365 %*                                                                      *
366 %************************************************************************
367
368 Helper functions
369
370 \begin{code}
371 tcPats :: BinderChecker                         -- How to deal with variables
372        -> [RenamedPat] -> [TcType]              -- Excess 'expected types' discarded
373        -> TcM ([TcPat], 
374                  LIE,                           -- Required by n+k and literal pats
375                  Bag TcTyVar,
376                  Bag (Name, TcId),      -- Ids bound by the pattern
377                  LIE)                           -- Dicts bound by the pattern
378
379 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
380
381 tcPats tc_bndr (ty:tys) (pat:pats)
382   = tcPat tc_bndr ty pat                `thenTc` \ (pat',  lie_req1, tvs1, ids1, lie_avail1) ->
383     tcPats tc_bndr tys pats     `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
384
385     returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
386               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
387               lie_avail1 `plusLIE` lie_avail2)
388 \end{code}
389
390 ------------------------------------------------------
391 \begin{code}
392 tcConstructor pat con_name
393   =     -- Check that it's a constructor
394     tcLookupDataCon con_name            `thenNF_Tc` \ data_con ->
395
396         -- Instantiate it
397     tcInstDataCon (PatOrigin pat) data_con      `thenNF_Tc` \ (_, ex_dicts, arg_tys, result_ty, lie_req, ex_lie, ex_tvs) ->
398
399     returnTc (data_con, lie_req, ex_tvs, ex_dicts, ex_lie, 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, lie_req1, ex_tvs, ex_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_req2) ->
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_req3, tvs, ids, lie_avail2) ->
425
426     returnTc (co_fn <$> ConPat data_con pat_ty ex_tvs ex_dicts arg_pats',
427               lie_req1 `plusLIE` lie_req2 `plusLIE` lie_req3,
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 -> TcHoleType -> TcM (PatCoFn, LIE)
457
458 tcSubPat sig_ty exp_ty
459  = tcSubOff sig_ty exp_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 FSLIT("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("When checking 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