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