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