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