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