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