[project @ 1998-12-18 17:40:31 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, tcVarPat, badFieldCon, polyPatSig ) where
8
9 #include "HsVersions.h"
10
11 import {-# SOURCE #-}   TcExpr( tcExpr )
12
13 import HsSyn            ( InPat(..), OutPat(..), HsLit(..), HsExpr(..), Sig(..) )
14 import RnHsSyn          ( RenamedPat )
15 import TcHsSyn          ( TcPat, TcId )
16
17 import TcMonad
18 import Inst             ( Inst, OverloadedLit(..), InstOrigin(..),
19                           emptyLIE, plusLIE, LIE,
20                           newMethod, newMethodWithGivenTy, newOverloadedLit, 
21                           newDicts, instToIdBndr
22                         )
23 import Name             ( Name, getOccName, getSrcLoc )
24 import FieldLabel       ( fieldLabelName )
25 import TcEnv            ( tcLookupValue, 
26                           tcLookupValueByKey, newLocalId, badCon
27                         )
28 import TcType           ( TcType, TcTyVar, tcInstTyVars )
29 import TcMonoType       ( tcHsType )
30 import TcUnify          ( unifyTauTy, unifyListTy,
31                           unifyTupleTy, unifyUnboxedTupleTy
32                         )
33
34 import Bag              ( Bag )
35 import CmdLineOpts      ( opt_IrrefutableTuples )
36 import DataCon          ( DataCon, dataConSig, dataConFieldLabels, dataConSourceArity )
37 import Id               ( Id, mkUserId, idType, isDataConId_maybe )
38 import Type             ( Type, isTauTy, substTopTy, substTopTheta, mkTyConApp )
39 import TysPrim          ( charPrimTy, intPrimTy, floatPrimTy,
40                           doublePrimTy, addrPrimTy
41                         )
42 import TysWiredIn       ( charTy, stringTy, intTy )
43 import SrcLoc           ( SrcLoc )
44 import Unique           ( eqClassOpKey, geClassOpKey, minusClassOpKey )
45 import Bag
46 import Util             ( zipEqual )
47 import Outputable
48 \end{code}
49
50
51 %************************************************************************
52 %*                                                                      *
53 \subsection{Variable patterns}
54 %*                                                                      *
55 %************************************************************************
56
57 \begin{code}
58 tcVarPat :: (Name -> Maybe TcId) -- Info about signatures; gives the *monomorphic*
59                                  -- Id for variables with a type signature
60          -> Name
61
62          -> TcType              -- Expected type, derived from the context
63                                 --      In the case of a function with a rank-2 signature,
64                                 --      this type might be a forall type.
65                                 --      INVARIANT: if it is, the foralls will always be visible,
66                                 --      not hidden inside a mutable type variable
67
68          -> TcM s TcId  -- The monomorphic Id; this is put in the pattern itself
69
70 tcVarPat sig_fn binder_name pat_ty
71  = case sig_fn binder_name of
72         Nothing -> newLocalId (getOccName binder_name) pat_ty           `thenNF_Tc` \ bndr_id ->
73                    returnTc bndr_id
74
75         Just bndr_id -> tcAddSrcLoc (getSrcLoc binder_name)             $
76                         unifyTauTy (idType bndr_id) pat_ty              `thenTc_`
77                         returnTc bndr_id
78 \end{code}
79
80
81 %************************************************************************
82 %*                                                                      *
83 \subsection{Typechecking patterns}
84 %*                                                                      *
85 %************************************************************************
86
87 \begin{code}
88 tcPat :: (Name -> Maybe TcId)   -- Info about signatures; gives the *monomorphic*
89                                         -- Id for variables with a type signature
90       -> RenamedPat
91       -> TcType                 -- Expected type; see invariant in tcVarPat
92       -> TcM s (TcPat, 
93                 LIE,                    -- Required by n+k and literal pats
94                 Bag TcTyVar,    -- TyVars bound by the pattern
95                                         --      These are just the existentially-bound ones.
96                                         --      Any tyvars bound by *type signatures* in the
97                                         --      patterns are brought into scope before we begin.
98                 Bag (Name, TcId),       -- Ids bound by the pattern, along with the Name under
99                                         --      which it occurs in the pattern
100                                         --      The two aren't the same because we conjure up a new
101                                         --      local name for each variable.
102                 LIE)                    -- Dicts or methods [see below] bound by the pattern
103                                         --      from existential constructor patterns
104 \end{code}
105
106
107 %************************************************************************
108 %*                                                                      *
109 \subsection{Variables, wildcards, lazy pats, as-pats}
110 %*                                                                      *
111 %************************************************************************
112
113 \begin{code}
114 tcPat sig_fn (VarPatIn name) pat_ty
115   = tcVarPat sig_fn name pat_ty         `thenTc` \ bndr_id ->
116     returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
117
118 tcPat sig_fn (LazyPatIn pat) pat_ty
119   = tcPat sig_fn pat pat_ty             `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
120     returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
121
122 tcPat sig_fn pat_in@(AsPatIn name pat) pat_ty
123   = tcVarPat sig_fn name pat_ty         `thenTc` \ bndr_id ->
124     tcPat sig_fn pat pat_ty             `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
125     tcAddErrCtxt (patCtxt pat_in)       $
126     returnTc (AsPat bndr_id pat', lie_req, 
127               tvs, (name, bndr_id) `consBag` ids, lie_avail)
128
129 tcPat sig_fn WildPatIn pat_ty
130   = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
131
132 tcPat sig_fn (NegPatIn pat) pat_ty
133   = tcPat sig_fn (negate_lit pat) pat_ty
134   where
135     negate_lit (LitPatIn (HsInt  i)) = LitPatIn (HsInt  (-i))
136     negate_lit (LitPatIn (HsFrac f)) = LitPatIn (HsFrac (-f))
137     negate_lit _                     = panic "TcPat:negate_pat"
138
139 tcPat sig_fn (ParPatIn parend_pat) pat_ty
140   = tcPat sig_fn parend_pat pat_ty
141
142 tcPat sig_fn (SigPatIn pat sig) pat_ty
143   = tcHsType sig                                        `thenTc` \ sig_ty ->
144
145         -- Check that the signature isn't a polymorphic one, which
146         -- we don't permit (at present, anyway)
147     checkTc (isTauTy sig_ty) (polyPatSig sig_ty)        `thenTc_`
148
149     unifyTauTy pat_ty sig_ty    `thenTc_`
150     tcPat sig_fn pat sig_ty
151 \end{code}
152
153 %************************************************************************
154 %*                                                                      *
155 \subsection{Explicit lists and tuples}
156 %*                                                                      *
157 %************************************************************************
158
159 \begin{code}
160 tcPat sig_fn pat_in@(ListPatIn pats) pat_ty
161   = tcAddErrCtxt (patCtxt pat_in)               $
162     unifyListTy pat_ty                          `thenTc` \ elem_ty ->
163     tcPats sig_fn pats (repeat elem_ty)         `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
164     returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
165
166 tcPat sig_fn pat_in@(TuplePatIn pats boxed) pat_ty
167   = tcAddErrCtxt (patCtxt pat_in)       $
168
169     (if boxed
170      then unifyTupleTy        arity pat_ty
171      else unifyUnboxedTupleTy arity pat_ty)     `thenTc` \ arg_tys ->
172
173     tcPats sig_fn pats arg_tys                  `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
174
175         -- possibly do the "make all tuple-pats irrefutable" test:
176     let
177         unmangled_result = TuplePat pats' boxed
178
179         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
180         -- so that we can experiment with lazy tuple-matching.
181         -- This is a pretty odd place to make the switch, but
182         -- it was easy to do.
183
184         possibly_mangled_result
185           | opt_IrrefutableTuples && boxed = LazyPat unmangled_result
186           | otherwise                      = unmangled_result
187     in
188     returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
189   where
190     arity = length pats
191 \end{code}
192
193 %************************************************************************
194 %*                                                                      *
195 \subsection{Other constructors}
196 %*                                                                      *
197
198 %************************************************************************
199
200 \begin{code}
201 tcPat sig_fn pat@(ConPatIn name arg_pats) pat_ty
202   = tcConPat sig_fn pat name arg_pats pat_ty
203
204 tcPat sig_fn pat@(ConOpPatIn pat1 op _ pat2) pat_ty
205   = tcConPat sig_fn pat op [pat1, pat2] pat_ty
206 \end{code}
207
208
209 %************************************************************************
210 %*                                                                      *
211 \subsection{Records}
212 %*                                                                      *
213 %************************************************************************
214
215 \begin{code}
216 tcPat sig_fn pat@(RecPatIn name rpats) pat_ty
217   = tcAddErrCtxt (patCtxt pat)  $
218
219         -- Check the constructor itself
220     tcConstructor pat name pat_ty       `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
221     let
222         field_tys = zipEqual "tcPat" 
223                              (map fieldLabelName (dataConFieldLabels data_con))
224                              arg_tys
225     in
226
227         -- Check the fields
228     tc_fields field_tys rpats           `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
229
230     returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
231               lie_req,
232               listToBag ex_tvs `unionBags` tvs,
233               ids,
234               lie_avail1 `plusLIE` lie_avail2)
235
236   where
237     tc_fields field_tys []
238       = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
239
240     tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
241       | null matching_fields
242       = addErrTc (badFieldCon name field_label)         `thenNF_Tc_`
243         tc_fields field_tys rpats
244
245       | otherwise
246       = ASSERT( null extras )
247         tc_fields field_tys rpats       `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
248
249         tcLookupValue field_label       `thenNF_Tc` \ sel_id ->
250         tcPat sig_fn rhs_pat rhs_ty     `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
251
252         returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
253                   lie_req1 `plusLIE` lie_req2,
254                   tvs1 `unionBags` tvs2,
255                   ids1 `unionBags` ids2,
256                   lie_avail1 `plusLIE` lie_avail2)
257       where
258         matching_fields   = [ty | (f,ty) <- field_tys, f == field_label]
259         (rhs_ty : extras) = matching_fields
260 \end{code}
261
262 %************************************************************************
263 %*                                                                      *
264 \subsection{Non-overloaded literals}
265 %*                                                                      *
266 %************************************************************************
267
268 \begin{code}
269 tcPat sig_fn (LitPatIn lit@(HsChar _))       pat_ty = tcSimpleLitPat lit charTy       pat_ty
270 tcPat sig_fn (LitPatIn lit@(HsIntPrim _))    pat_ty = tcSimpleLitPat lit intPrimTy    pat_ty
271 tcPat sig_fn (LitPatIn lit@(HsCharPrim _))   pat_ty = tcSimpleLitPat lit charPrimTy   pat_ty
272 tcPat sig_fn (LitPatIn lit@(HsStringPrim _)) pat_ty = tcSimpleLitPat lit addrPrimTy   pat_ty
273 tcPat sig_fn (LitPatIn lit@(HsFloatPrim _))  pat_ty = tcSimpleLitPat lit floatPrimTy  pat_ty
274 tcPat sig_fn (LitPatIn lit@(HsDoublePrim _)) pat_ty = tcSimpleLitPat lit doublePrimTy pat_ty
275
276 tcPat sig_fn (LitPatIn lit@(HsLitLit s))     pat_ty = tcSimpleLitPat lit intTy pat_ty
277         -- This one looks weird!
278 \end{code}
279
280 %************************************************************************
281 %*                                                                      *
282 \subsection{Overloaded patterns: int literals and \tr{n+k} patterns}
283 %*                                                                      *
284 %************************************************************************
285
286 \begin{code}
287 tcPat sig_fn pat@(LitPatIn lit@(HsString str)) pat_ty
288   = unifyTauTy pat_ty stringTy                  `thenTc_` 
289     tcLookupValueByKey eqClassOpKey             `thenNF_Tc` \ sel_id ->
290     newMethod (PatOrigin pat) sel_id [stringTy] `thenNF_Tc` \ (lie, eq_id) ->
291     let
292         comp_op = HsApp (HsVar eq_id) (HsLitOut lit stringTy)
293     in
294     returnTc (NPat lit stringTy comp_op, lie, emptyBag, emptyBag, emptyLIE)
295
296
297 tcPat sig_fn pat@(LitPatIn lit@(HsInt i)) pat_ty
298   = tcOverloadedLitPat pat lit (OverloadedIntegral i) pat_ty
299
300 tcPat sig_fn pat@(LitPatIn lit@(HsFrac f)) pat_ty
301   = tcOverloadedLitPat pat lit (OverloadedFractional f) pat_ty
302
303
304 tcPat sig_fn pat@(NPlusKPatIn name lit@(HsInt i)) pat_ty
305   = tcVarPat sig_fn name pat_ty                         `thenTc` \ bndr_id ->
306     tcLookupValueByKey geClassOpKey             `thenNF_Tc` \ ge_sel_id ->
307     tcLookupValueByKey minusClassOpKey          `thenNF_Tc` \ minus_sel_id ->
308
309     newOverloadedLit origin
310                      (OverloadedIntegral i) pat_ty      `thenNF_Tc` \ (over_lit_expr, lie1) ->
311
312     newMethod origin ge_sel_id    [pat_ty]      `thenNF_Tc` \ (lie2, ge_id) ->
313     newMethod origin minus_sel_id [pat_ty]      `thenNF_Tc` \ (lie3, minus_id) ->
314
315     returnTc (NPlusKPat bndr_id lit pat_ty
316                         (SectionR (HsVar ge_id) over_lit_expr)
317                         (SectionR (HsVar minus_id) over_lit_expr),
318               lie1 `plusLIE` lie2 `plusLIE` lie3,
319               emptyBag, unitBag (name, bndr_id), emptyLIE)
320   where
321     origin = PatOrigin pat
322
323 tcPat sig_fn (NPlusKPatIn pat other) pat_ty
324   = panic "TcPat:NPlusKPat: not an HsInt literal"
325 \end{code}
326
327 %************************************************************************
328 %*                                                                      *
329 \subsection{Lists of patterns}
330 %*                                                                      *
331 %************************************************************************
332
333 Helper functions
334
335 \begin{code}
336 tcPats :: (Name -> Maybe TcId)  -- Info about signatures
337        -> [RenamedPat] -> [TcType]      -- Excess 'expected types' discarded
338        -> TcM s ([TcPat], 
339                  LIE,                           -- Required by n+k and literal pats
340                  Bag TcTyVar,
341                  Bag (Name, TcId),      -- Ids bound by the pattern
342                  LIE)                           -- Dicts bound by the pattern
343
344 tcPats sig_fn [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
345
346 tcPats sig_fn (ty:tys) (pat:pats)
347   = tcPat sig_fn ty pat         `thenTc` \ (pat',  lie_req1, tvs1, ids1, lie_avail1) ->
348     tcPats sig_fn tys pats      `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
349
350     returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
351               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
352               lie_avail1 `plusLIE` lie_avail2)
353 \end{code}
354
355 ------------------------------------------------------
356 \begin{code}
357 tcSimpleLitPat lit lit_ty pat_ty
358   = unifyTauTy pat_ty lit_ty    `thenTc_` 
359     returnTc (LitPat lit lit_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
360
361
362 tcOverloadedLitPat pat lit over_lit pat_ty
363   = newOverloadedLit (PatOrigin pat) over_lit pat_ty    `thenNF_Tc` \ (over_lit_expr, lie1) ->
364     tcLookupValueByKey eqClassOpKey                     `thenNF_Tc` \ eq_sel_id ->
365     newMethod origin eq_sel_id [pat_ty]                 `thenNF_Tc` \ (lie2, eq_id) ->
366
367     returnTc (NPat lit pat_ty (HsApp (HsVar eq_id)
368                                      over_lit_expr),
369               lie1 `plusLIE` lie2,
370               emptyBag, emptyBag, emptyLIE)
371   where
372     origin = PatOrigin pat
373 \end{code}
374
375 ------------------------------------------------------
376 \begin{code}
377 tcConstructor pat con_name pat_ty
378   =     -- Check that it's a constructor
379     tcLookupValue con_name              `thenNF_Tc` \ con_id ->
380     case isDataConId_maybe con_id of {
381         Nothing -> failWithTc (badCon con_id);
382         Just data_con ->
383
384         -- Instantiate it
385     let 
386         (tvs, theta, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
387              -- Ignore the theta; overloaded constructors only
388              -- behave differently when called, not when used for
389              -- matching.
390     in
391     tcInstTyVars (ex_tvs ++ tvs)        `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
392     let
393         ex_theta' = substTopTheta tenv ex_theta
394         arg_tys'  = map (substTopTy tenv) arg_tys
395
396         n_ex_tvs  = length ex_tvs
397         ex_tvs'   = take n_ex_tvs all_tvs'
398         result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
399     in
400     newDicts (PatOrigin pat) ex_theta'  `thenNF_Tc` \ (lie_avail, dicts) ->
401
402         -- Check overall type matches
403     unifyTauTy pat_ty result_ty         `thenTc_`
404
405     returnTc (data_con, ex_tvs', dicts, lie_avail, arg_tys')
406     }
407 \end{code}            
408
409 ------------------------------------------------------
410 \begin{code}
411 tcConPat sig_fn pat con_name arg_pats pat_ty
412   = tcAddErrCtxt (patCtxt pat)  $
413
414         -- Check the constructor itself
415     tcConstructor pat con_name pat_ty   `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
416
417         -- Check correct arity
418     let
419         con_arity  = dataConSourceArity data_con
420         no_of_args = length arg_pats
421     in
422     checkTc (con_arity == no_of_args)
423             (arityErr "Constructor" data_con con_arity no_of_args)      `thenTc_`
424
425         -- Check arguments
426     tcPats sig_fn arg_pats arg_tys'     `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
427
428     returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
429               lie_req,
430               listToBag ex_tvs' `unionBags` tvs,
431               ids,
432               lie_avail1 `plusLIE` lie_avail2)
433 \end{code}
434
435
436 %************************************************************************
437 %*                                                                      *
438 \subsection{Errors and contexts}
439 %*                                                                      *
440 %************************************************************************
441
442 \begin{code}
443 patCtxt pat = hang (ptext SLIT("In the pattern:")) 
444                  4 (ppr pat)
445
446 recordLabel field_label
447   = hang (hcat [ptext SLIT("When matching record field"), ppr field_label])
448          4 (hcat [ptext SLIT("with its immediately enclosing constructor")])
449
450 recordRhs field_label pat
451   = hang (ptext SLIT("In the record field pattern"))
452          4 (sep [ppr field_label, char '=', ppr pat])
453
454 badFieldCon :: Name -> Name -> SDoc
455 badFieldCon con field
456   = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
457           ptext SLIT("does not have field"), quotes (ppr field)]
458
459 polyPatSig :: TcType -> SDoc
460 polyPatSig sig_ty
461   = hang (ptext SLIT("Polymorphic type signature in pattern"))
462          4 (ppr sig_ty)
463 \end{code}
464