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