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