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