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