[project @ 2001-01-25 17:54:24 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, 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, newClassDicts
19                         )
20 import Id               ( mkVanillaId )
21 import Name             ( Name )
22 import FieldLabel       ( fieldLabelName )
23 import TcEnv            ( tcLookupClass, tcLookupDataCon, tcLookupGlobalId )
24 import TcType           ( TcType, TcTyVar, tcInstTyVars, newTyVarTy )
25 import TcMonoType       ( tcHsSigType )
26 import TcUnify          ( unifyTauTy, unifyListTy, unifyTupleTy )
27
28 import CmdLineOpts      ( opt_IrrefutableTuples )
29 import DataCon          ( dataConSig, dataConFieldLabels, 
30                           dataConSourceArity
31                         )
32 import Type             ( isTauTy, mkTyConApp, mkClassPred, liftedTypeKind )
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        ( eqStringName, eqName, geName, cCallableClassName )
39 import BasicTypes       ( isBoxed )
40 import Bag
41 import Outputable
42 \end{code}
43
44
45 %************************************************************************
46 %*                                                                      *
47 \subsection{Variable patterns}
48 %*                                                                      *
49 %************************************************************************
50
51 \begin{code}
52 -- This is the right function to pass to tcPat when 
53 -- we're looking at a lambda-bound pattern, 
54 -- so there's no polymorphic guy to worry about
55 tcMonoPatBndr binder_name pat_ty = returnTc (mkVanillaId binder_name pat_ty)
56 \end{code}
57
58
59 %************************************************************************
60 %*                                                                      *
61 \subsection{Typechecking patterns}
62 %*                                                                      *
63 %************************************************************************
64
65 \begin{code}
66 tcPat :: (Name -> TcType -> TcM TcId)   -- How to construct a suitable (monomorphic)
67                                         -- Id for variables found in the pattern
68                                         -- The TcType is the expected type, see note below
69       -> RenamedPat
70
71       -> TcType         -- Expected type derived from the context
72                         --      In the case of a function with a rank-2 signature,
73                         --      this type might be a forall type.
74                         --      INVARIANT: if it is, the foralls will always be visible,
75                         --      not hidden inside a mutable type variable
76
77       -> TcM (TcPat, 
78                 LIE,                    -- Required by n+k and literal pats
79                 Bag TcTyVar,    -- TyVars bound by the pattern
80                                         --      These are just the existentially-bound ones.
81                                         --      Any tyvars bound by *type signatures* in the
82                                         --      patterns are brought into scope before we begin.
83                 Bag (Name, TcId),       -- Ids bound by the pattern, along with the Name under
84                                         --      which it occurs in the pattern
85                                         --      The two aren't the same because we conjure up a new
86                                         --      local name for each variable.
87                 LIE)                    -- Dicts or methods [see below] bound by the pattern
88                                         --      from existential constructor patterns
89 \end{code}
90
91
92 %************************************************************************
93 %*                                                                      *
94 \subsection{Variables, wildcards, lazy pats, as-pats}
95 %*                                                                      *
96 %************************************************************************
97
98 \begin{code}
99 tcPat tc_bndr pat@(TypePatIn ty) pat_ty
100   = failWithTc (badTypePat pat)
101
102 tcPat tc_bndr (VarPatIn name) pat_ty
103   = tc_bndr name pat_ty         `thenTc` \ bndr_id ->
104     returnTc (VarPat bndr_id, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
105
106 tcPat tc_bndr (LazyPatIn pat) pat_ty
107   = tcPat tc_bndr pat pat_ty            `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
108     returnTc (LazyPat pat', lie_req, tvs, ids, lie_avail)
109
110 tcPat tc_bndr pat_in@(AsPatIn name pat) pat_ty
111   = tc_bndr name pat_ty                 `thenTc` \ bndr_id ->
112     tcPat tc_bndr pat pat_ty            `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
113     tcAddErrCtxt (patCtxt pat_in)       $
114     returnTc (AsPat bndr_id pat', lie_req, 
115               tvs, (name, bndr_id) `consBag` ids, lie_avail)
116
117 tcPat tc_bndr WildPatIn pat_ty
118   = returnTc (WildPat pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
119
120 tcPat tc_bndr (ParPatIn parend_pat) pat_ty
121   = tcPat tc_bndr parend_pat pat_ty
122
123 tcPat tc_bndr (SigPatIn pat sig) pat_ty
124   = tcHsSigType sig                                     `thenTc` \ sig_ty ->
125
126         -- Check that the signature isn't a polymorphic one, which
127         -- we don't permit (at present, anyway)
128     checkTc (isTauTy sig_ty) (polyPatSig sig_ty)        `thenTc_`
129
130     unifyTauTy pat_ty sig_ty    `thenTc_`
131     tcPat tc_bndr pat sig_ty
132 \end{code}
133
134 %************************************************************************
135 %*                                                                      *
136 \subsection{Explicit lists and tuples}
137 %*                                                                      *
138 %************************************************************************
139
140 \begin{code}
141 tcPat tc_bndr pat_in@(ListPatIn pats) pat_ty
142   = tcAddErrCtxt (patCtxt pat_in)               $
143     unifyListTy pat_ty                          `thenTc` \ elem_ty ->
144     tcPats tc_bndr pats (repeat elem_ty)        `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
145     returnTc (ListPat elem_ty pats', lie_req, tvs, ids, lie_avail)
146
147 tcPat tc_bndr pat_in@(TuplePatIn pats boxity) pat_ty
148   = tcAddErrCtxt (patCtxt pat_in)       $
149
150     unifyTupleTy boxity arity pat_ty            `thenTc` \ arg_tys ->
151     tcPats tc_bndr pats arg_tys                 `thenTc` \ (pats', lie_req, tvs, ids, lie_avail) ->
152
153         -- possibly do the "make all tuple-pats irrefutable" test:
154     let
155         unmangled_result = TuplePat pats' boxity
156
157         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
158         -- so that we can experiment with lazy tuple-matching.
159         -- This is a pretty odd place to make the switch, but
160         -- it was easy to do.
161
162         possibly_mangled_result
163           | opt_IrrefutableTuples && isBoxed boxity = LazyPat unmangled_result
164           | otherwise                               = unmangled_result
165     in
166     returnTc (possibly_mangled_result, lie_req, tvs, ids, lie_avail)
167   where
168     arity = length pats
169 \end{code}
170
171 %************************************************************************
172 %*                                                                      *
173 \subsection{Other constructors}
174 %*                                                                      *
175
176 %************************************************************************
177
178 \begin{code}
179 tcPat tc_bndr pat@(ConPatIn name arg_pats) pat_ty
180   = tcConPat tc_bndr pat name arg_pats pat_ty
181
182 tcPat tc_bndr pat@(ConOpPatIn pat1 op _ pat2) pat_ty
183   = tcConPat tc_bndr pat op [pat1, pat2] pat_ty
184 \end{code}
185
186
187 %************************************************************************
188 %*                                                                      *
189 \subsection{Records}
190 %*                                                                      *
191 %************************************************************************
192
193 \begin{code}
194 tcPat tc_bndr pat@(RecPatIn name rpats) pat_ty
195   = tcAddErrCtxt (patCtxt pat)  $
196
197         -- Check the constructor itself
198     tcConstructor pat name pat_ty       `thenTc` \ (data_con, ex_tvs, dicts, lie_avail1, arg_tys) ->
199     let
200         -- Don't use zipEqual! If the constructor isn't really a record, then
201         -- dataConFieldLabels will be empty (and each field in the pattern
202         -- will generate an error below).
203         field_tys = zip (map fieldLabelName (dataConFieldLabels data_con))
204                         arg_tys
205     in
206
207         -- Check the fields
208     tc_fields field_tys rpats           `thenTc` \ (rpats', lie_req, tvs, ids, lie_avail2) ->
209
210     returnTc (RecPat data_con pat_ty ex_tvs dicts rpats',
211               lie_req,
212               listToBag ex_tvs `unionBags` tvs,
213               ids,
214               lie_avail1 `plusLIE` lie_avail2)
215
216   where
217     tc_fields field_tys []
218       = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
219
220     tc_fields field_tys ((field_label, rhs_pat, pun_flag) : rpats)
221       = tc_fields field_tys rpats       `thenTc` \ (rpats', lie_req1, tvs1, ids1, lie_avail1) ->
222
223         (case [ty | (f,ty) <- field_tys, f == field_label] of
224
225                 -- No matching field; chances are this field label comes from some
226                 -- other record type (or maybe none).  As well as reporting an
227                 -- error we still want to typecheck the pattern, principally to
228                 -- make sure that all the variables it binds are put into the
229                 -- environment, else the type checker crashes later:
230                 --      f (R { foo = (a,b) }) = a+b
231                 -- If foo isn't one of R's fields, we don't want to crash when
232                 -- typechecking the "a+b".
233            [] -> addErrTc (badFieldCon name field_label)        `thenNF_Tc_` 
234                  newTyVarTy liftedTypeKind                      `thenNF_Tc_` 
235                  returnTc (error "Bogus selector Id", pat_ty)
236
237                 -- The normal case, when the field comes from the right constructor
238            (pat_ty : extras) -> 
239                 ASSERT( null extras )
240                 tcLookupGlobalId field_label                    `thenNF_Tc` \ sel_id ->
241                 returnTc (sel_id, pat_ty)
242         )                                                       `thenTc` \ (sel_id, pat_ty) ->
243
244         tcPat tc_bndr rhs_pat pat_ty    `thenTc` \ (rhs_pat', lie_req2, tvs2, ids2, lie_avail2) ->
245
246         returnTc ((sel_id, rhs_pat', pun_flag) : rpats',
247                   lie_req1 `plusLIE` lie_req2,
248                   tvs1 `unionBags` tvs2,
249                   ids1 `unionBags` ids2,
250                   lie_avail1 `plusLIE` lie_avail2)
251 \end{code}
252
253 %************************************************************************
254 %*                                                                      *
255 \subsection{Literals}
256 %*                                                                      *
257 %************************************************************************
258
259 \begin{code}
260 tcPat tc_bndr (LitPatIn lit@(HsLitLit s _)) pat_ty 
261         -- cf tcExpr on LitLits
262   = tcLookupClass cCallableClassName            `thenNF_Tc` \ cCallableClass ->
263     newDicts (LitLitOrigin (_UNPK_ s))
264              [mkClassPred cCallableClass [pat_ty]]      `thenNF_Tc` \ dicts ->
265     returnTc (LitPat (HsLitLit s pat_ty) pat_ty, mkLIE dicts, emptyBag, emptyBag, emptyLIE)
266
267 tcPat tc_bndr pat@(LitPatIn lit@(HsString _)) pat_ty
268   = unifyTauTy pat_ty stringTy                  `thenTc_` 
269     tcLookupGlobalId eqStringName               `thenNF_Tc` \ eq_id ->
270     returnTc (NPat lit stringTy (HsVar eq_id `HsApp` HsLit lit), 
271               emptyLIE, emptyBag, emptyBag, emptyLIE)
272
273 tcPat tc_bndr (LitPatIn simple_lit) pat_ty
274   = unifyTauTy pat_ty (simpleHsLitTy simple_lit)                `thenTc_` 
275     returnTc (LitPat simple_lit pat_ty, emptyLIE, emptyBag, emptyBag, emptyLIE)
276
277 tcPat tc_bndr pat@(NPatIn over_lit) pat_ty
278   = newOverloadedLit (PatOrigin pat) over_lit pat_ty    `thenNF_Tc` \ (over_lit_expr, lie1) ->
279     tcLookupGlobalId eqName                             `thenNF_Tc` \ eq_sel_id ->
280     newMethod origin eq_sel_id [pat_ty]                 `thenNF_Tc` \ eq ->
281
282     returnTc (NPat lit' pat_ty (HsApp (HsVar (instToId eq)) over_lit_expr),
283               lie1 `plusLIE` unitLIE eq,
284               emptyBag, emptyBag, emptyLIE)
285   where
286     origin = PatOrigin pat
287     lit' = case over_lit of
288                 HsIntegral i   _ -> HsInteger i
289                 HsFractional f _ -> HsRat f pat_ty
290 \end{code}
291
292 %************************************************************************
293 %*                                                                      *
294 \subsection{n+k patterns}
295 %*                                                                      *
296 %************************************************************************
297
298 \begin{code}
299 tcPat tc_bndr pat@(NPlusKPatIn name lit@(HsIntegral i _) minus) pat_ty
300   = tc_bndr name pat_ty                         `thenTc` \ bndr_id ->
301     tcLookupGlobalId minus                      `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' = substClasses 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     newClassDicts (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