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