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