[project @ 2001-03-13 14:58:25 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
19                         )
20 import Id               ( mkLocalId )
21 import Name             ( Name )
22 import FieldLabel       ( fieldLabelName )
23 import TcEnv            ( tcLookupClass, tcLookupDataCon, tcLookupGlobalId, tcLookupSyntaxId )
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, substTheta )
34 import TysPrim          ( charPrimTy, intPrimTy, floatPrimTy,
35                           doublePrimTy, addrPrimTy
36                         )
37 import TysWiredIn       ( charTy, stringTy, intTy, integerTy )
38 import PrelNames        ( minusName, 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 (mkLocalId 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)) pat_ty
300   = tc_bndr name pat_ty                         `thenTc` \ bndr_id ->
301         -- The '-' part is re-mappable syntax
302     tcLookupSyntaxId minusName                  `thenNF_Tc` \ minus_sel_id ->
303     tcLookupGlobalId geName                     `thenNF_Tc` \ ge_sel_id ->
304     newOverloadedLit origin lit pat_ty          `thenNF_Tc` \ (over_lit_expr, lie1) ->
305     newMethod origin ge_sel_id    [pat_ty]      `thenNF_Tc` \ ge ->
306     newMethod origin minus_sel_id [pat_ty]      `thenNF_Tc` \ minus ->
307
308     returnTc (NPlusKPat bndr_id i pat_ty
309                         (SectionR (HsVar (instToId ge)) over_lit_expr)
310                         (SectionR (HsVar (instToId minus)) over_lit_expr),
311               lie1 `plusLIE` mkLIE [ge,minus],
312               emptyBag, unitBag (name, bndr_id), emptyLIE)
313   where
314     origin = PatOrigin pat
315 \end{code}
316
317 %************************************************************************
318 %*                                                                      *
319 \subsection{Lists of patterns}
320 %*                                                                      *
321 %************************************************************************
322
323 Helper functions
324
325 \begin{code}
326 tcPats :: (Name -> TcType -> TcM TcId)  -- How to deal with variables
327        -> [RenamedPat] -> [TcType]              -- Excess 'expected types' discarded
328        -> TcM ([TcPat], 
329                  LIE,                           -- Required by n+k and literal pats
330                  Bag TcTyVar,
331                  Bag (Name, TcId),      -- Ids bound by the pattern
332                  LIE)                           -- Dicts bound by the pattern
333
334 tcPats tc_bndr [] tys = returnTc ([], emptyLIE, emptyBag, emptyBag, emptyLIE)
335
336 tcPats tc_bndr (ty:tys) (pat:pats)
337   = tcPat tc_bndr ty pat                `thenTc` \ (pat',  lie_req1, tvs1, ids1, lie_avail1) ->
338     tcPats tc_bndr tys pats     `thenTc` \ (pats', lie_req2, tvs2, ids2, lie_avail2) ->
339
340     returnTc (pat':pats', lie_req1 `plusLIE` lie_req2,
341               tvs1 `unionBags` tvs2, ids1 `unionBags` ids2, 
342               lie_avail1 `plusLIE` lie_avail2)
343 \end{code}
344
345 ------------------------------------------------------
346 \begin{code}
347 simpleHsLitTy :: HsLit -> TcType
348 simpleHsLitTy (HsCharPrim c)   = charPrimTy
349 simpleHsLitTy (HsStringPrim s) = addrPrimTy
350 simpleHsLitTy (HsInt i)        = intTy
351 simpleHsLitTy (HsInteger i)    = integerTy
352 simpleHsLitTy (HsIntPrim i)    = intPrimTy
353 simpleHsLitTy (HsFloatPrim f)  = floatPrimTy
354 simpleHsLitTy (HsDoublePrim d) = doublePrimTy
355 simpleHsLitTy (HsChar c)       = charTy
356 simpleHsLitTy (HsString str)   = stringTy
357 \end{code}
358
359
360 ------------------------------------------------------
361 \begin{code}
362 tcConstructor pat con_name pat_ty
363   =     -- Check that it's a constructor
364     tcLookupDataCon con_name            `thenNF_Tc` \ data_con ->
365
366         -- Instantiate it
367     let 
368         (tvs, _, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig data_con
369              -- Ignore the theta; overloaded constructors only
370              -- behave differently when called, not when used for
371              -- matching.
372     in
373     tcInstTyVars (ex_tvs ++ tvs)        `thenNF_Tc` \ (all_tvs', ty_args', tenv) ->
374     let
375         ex_theta' = substTheta tenv ex_theta
376         arg_tys'  = map (substTy tenv) arg_tys
377
378         n_ex_tvs  = length ex_tvs
379         ex_tvs'   = take n_ex_tvs all_tvs'
380         result_ty = mkTyConApp tycon (drop n_ex_tvs ty_args')
381     in
382     newDicts (PatOrigin pat) ex_theta'  `thenNF_Tc` \ dicts ->
383
384         -- Check overall type matches
385     unifyTauTy pat_ty result_ty         `thenTc_`
386
387     returnTc (data_con, ex_tvs', map instToId dicts, mkLIE dicts, arg_tys')
388 \end{code}            
389
390 ------------------------------------------------------
391 \begin{code}
392 tcConPat tc_bndr pat con_name arg_pats pat_ty
393   = tcAddErrCtxt (patCtxt pat)  $
394
395         -- Check the constructor itself
396     tcConstructor pat con_name pat_ty   `thenTc` \ (data_con, ex_tvs', dicts, lie_avail1, arg_tys') ->
397
398         -- Check correct arity
399     let
400         con_arity  = dataConSourceArity data_con
401         no_of_args = length arg_pats
402     in
403     checkTc (con_arity == no_of_args)
404             (arityErr "Constructor" data_con con_arity no_of_args)      `thenTc_`
405
406         -- Check arguments
407     tcPats tc_bndr arg_pats arg_tys'    `thenTc` \ (arg_pats', lie_req, tvs, ids, lie_avail2) ->
408
409     returnTc (ConPat data_con pat_ty ex_tvs' dicts arg_pats',
410               lie_req,
411               listToBag ex_tvs' `unionBags` tvs,
412               ids,
413               lie_avail1 `plusLIE` lie_avail2)
414 \end{code}
415
416
417 %************************************************************************
418 %*                                                                      *
419 \subsection{Errors and contexts}
420 %*                                                                      *
421 %************************************************************************
422
423 \begin{code}
424 patCtxt pat = hang (ptext SLIT("In the pattern:")) 
425                  4 (ppr pat)
426
427 badFieldCon :: Name -> Name -> SDoc
428 badFieldCon con field
429   = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
430           ptext SLIT("does not have field"), quotes (ppr field)]
431
432 polyPatSig :: TcType -> SDoc
433 polyPatSig sig_ty
434   = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
435          4 (ppr sig_ty)
436
437 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
438 \end{code}
439