[project @ 2004-09-30 10:35:15 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, tcPats, PatCtxt(..), badFieldCon, polyPatSig ) where
8
9 #include "HsVersions.h"
10
11 import HsSyn            ( Pat(..), LPat, HsConDetails(..), HsLit(..), HsOverLit(..), 
12                           HsExpr(..), LHsBinds, emptyLHsBinds, isEmptyLHsBinds )
13 import HsUtils
14 import TcHsSyn          ( TcId, hsLitType )
15 import TcRnMonad
16 import Inst             ( InstOrigin(..),
17                           newMethodFromName, newOverloadedLit, newDicts,
18                           instToId, tcInstStupidTheta, tcSyntaxName
19                         )
20 import Id               ( Id, idType, mkLocalId )
21 import Name             ( Name )
22 import TcSimplify       ( tcSimplifyCheck, bindInstsOfLocalFuns )
23 import TcEnv            ( newLocalName, tcExtendIdEnv1, tcExtendTyVarEnv,
24                           tcLookupClass, tcLookupDataCon, tcLookupId )
25 import TcMType          ( newTyFlexiVarTy, arityErr, tcSkolTyVars, isRigidType )
26 import TcType           ( TcType, TcTyVar, TcSigmaType, TcTauType, zipTopTvSubst,
27                           SkolemInfo(PatSkol), isSkolemTyVar, pprSkolemTyVar, 
28                           mkTyVarTys, mkClassPred, mkTyConApp, isOverloadedTy )
29 import Kind             ( argTypeKind, liftedTypeKind )
30 import TcUnify          ( tcSubPat, Expected(..), zapExpectedType, 
31                           zapExpectedTo, zapToListTy, zapToTyConApp )  
32 import TcHsType         ( UserTypeCtxt(..), TcSigInfo( sig_tau ), TcSigFun, tcHsPatSigType )
33 import TysWiredIn       ( stringTy, parrTyCon, tupleTyCon )
34 import Unify            ( MaybeErr(..), tcRefineTys, tcMatchTys )
35 import Type             ( substTys, substTheta )
36 import CmdLineOpts      ( opt_IrrefutableTuples )
37 import TyCon            ( TyCon )
38 import DataCon          ( DataCon, dataConTyCon, isVanillaDataCon, dataConInstOrigArgTys,
39                           dataConFieldLabels, dataConSourceArity, dataConSig )
40 import PrelNames        ( eqStringName, eqName, geName, negateName, minusName, 
41                           integralClassName )
42 import BasicTypes       ( isBoxed )
43 import SrcLoc           ( Located(..), noLoc, unLoc )
44 import ErrUtils         ( Message )
45 import Outputable
46 import FastString
47 \end{code}
48
49
50 %************************************************************************
51 %*                                                                      *
52                 External interface
53 %*                                                                      *
54 %************************************************************************
55
56 Note [Nesting]
57
58 tcPat takes a "thing inside" over which the patter scopes.  This is partly
59 so that tcPat can extend the environment for the thing_inside, but also 
60 so that constraints arising in the thing_inside can be discharged by the
61 pattern.
62
63 This does not work so well for the ErrCtxt carried by the monad: we don't
64 want the error-context for the pattern to scope over the RHS. 
65 Hence the getErrCtxt/setErrCtxt stuff in tcPat.
66
67 \begin{code}
68 tcPat   :: PatCtxt
69         -> LPat Name -> Expected TcSigmaType
70         -> TcM a                -- Thing inside
71         -> TcM (LPat TcId,      -- Translated pattern
72                 [TcTyVar],      -- Existential binders
73                 a)              -- Result of thing inside
74
75 tcPat ctxt pat exp_ty thing_inside
76   = do  { err_ctxt <- getErrCtxt
77         ; maybeAddErrCtxt (patCtxt (unLoc pat)) $
78             tc_lpat ctxt pat exp_ty $
79               setErrCtxt err_ctxt thing_inside }
80         -- Restore error context before doing thing_inside
81         -- See note [Nesting] above
82
83 --------------------
84 tcPats  :: PatCtxt
85         -> [LPat Name] 
86         -> [Expected TcSigmaType]       -- Excess types discarded
87         -> TcM a
88         -> TcM ([LPat TcId], [TcTyVar], a)
89
90 tcPats ctxt [] _ thing_inside
91   = do  { res <- thing_inside
92         ; return ([], [], res) }
93
94 tcPats ctxt (p:ps) (ty:tys) thing_inside
95   = do  { (p', p_tvs, (ps', ps_tvs, res)) 
96                 <- tcPat ctxt p ty $
97                    tcPats ctxt ps tys thing_inside
98         ; return (p':ps', p_tvs ++ ps_tvs, res) }
99
100 --------------------
101 tcCheckPats :: PatCtxt
102             -> [LPat Name] -> [TcSigmaType]
103             -> TcM a 
104             -> TcM ([LPat TcId], [TcTyVar], a)
105 tcCheckPats ctxt pats tys thing_inside  -- A trivial wrapper
106   = tcPats ctxt pats (map Check tys) thing_inside
107 \end{code}
108
109
110 %************************************************************************
111 %*                                                                      *
112                 Binders
113 %*                                                                      *
114 %************************************************************************
115
116 \begin{code}
117 data PatCtxt = LamPat Bool | LetPat TcSigFun
118         -- True <=> we are checking the case expression, 
119         --              so can do full-blown refinement
120         -- False <=> inferring, do no refinement
121
122 -------------------
123 tcPatBndr :: PatCtxt -> Name -> Expected TcSigmaType -> TcM TcId
124 tcPatBndr (LamPat _) bndr_name pat_ty
125   = do  { pat_ty' <- zapExpectedType pat_ty argTypeKind
126                 -- If pat_ty is Expected, this returns the appropriate
127                 -- SigmaType.  In Infer mode, we create a fresh type variable.
128                 -- Note the SigmaType: we can get
129                 --      data T = MkT (forall a. a->a)
130                 --      f t = case t of { MkT g -> ... }
131                 -- Here, the 'g' must get type (forall a. a->a) from the
132                 -- MkT context
133         ; return (mkLocalId bndr_name pat_ty') }
134
135 tcPatBndr (LetPat lookup_sig) bndr_name pat_ty
136   | Just sig <- lookup_sig bndr_name
137   = do  { let mono_ty = sig_tau sig
138         ; mono_name <- newLocalName bndr_name
139         ; tcSubPat mono_ty pat_ty
140         ; return (mkLocalId mono_name mono_ty) }
141
142   | otherwise
143   = do  { mono_name <- newLocalName bndr_name
144         ; pat_ty' <- zapExpectedType pat_ty argTypeKind
145         ; return (mkLocalId mono_name pat_ty') }
146
147
148 -------------------
149 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, LHsBinds TcId)
150 bindInstsOfPatId id thing_inside
151   | not (isOverloadedTy (idType id))
152   = do { res <- thing_inside; return (res, emptyLHsBinds) }
153   | otherwise
154   = do  { (res, lie) <- getLIE thing_inside
155         ; binds <- bindInstsOfLocalFuns lie [id]
156         ; return (res, binds) }
157 \end{code}
158
159
160 %************************************************************************
161 %*                                                                      *
162                 tc_pat: the main worker function
163 %*                                                                      *
164 %************************************************************************
165
166 \begin{code}
167 tc_lpat :: PatCtxt
168         -> LPat Name -> Expected TcSigmaType
169         -> TcM a                -- Thing inside
170         -> TcM (LPat TcId,      -- Translated pattern
171                 [TcTyVar],      -- Existential binders
172                 a)              -- Result of thing inside
173
174 tc_lpat ctxt (L span pat) pat_ty thing_inside
175   = setSrcSpan span $ 
176         -- It's OK to keep setting the SrcSpan; 
177         -- it just overwrites the previous value
178     do  { (pat', tvs, res) <- tc_pat ctxt pat pat_ty thing_inside
179         ; return (L span pat', tvs, res) }
180
181 ---------------------
182 tc_pat ctxt (VarPat name) pat_ty thing_inside
183   = do  { id <- tcPatBndr ctxt name pat_ty
184         ; (res, binds) <- bindInstsOfPatId id $
185                           tcExtendIdEnv1 name id $
186                           (traceTc (text "binding" <+> ppr name <+> ppr (idType id))
187                            >> thing_inside)
188         ; let pat' | isEmptyLHsBinds binds = VarPat id
189                    | otherwise             = VarPatOut id binds
190         ; return (pat', [], res) }
191
192 tc_pat ctxt (ParPat pat) pat_ty thing_inside
193   = do  { (pat', tvs, res) <- tc_lpat ctxt pat pat_ty thing_inside
194         ; return (ParPat pat', tvs, res) }
195
196 -- There's a wrinkle with irrefuatable patterns, namely that we
197 -- must not propagate type refinement from them.  For example
198 --      data T a where { T1 :: Int -> T Int; ... }
199 --      f :: T a -> Int -> a
200 --      f ~(T1 i) y = y
201 -- It's obviously not sound to refine a to Int in the right
202 -- hand side, because the arugment might not match T1 at all!
203 --
204 -- Nor should a lazy pattern bind any existential type variables
205 -- because they won't be in scope when we do the desugaring
206 tc_pat ctxt lpat@(LazyPat pat) pat_ty thing_inside
207   = do  { reft <- getTypeRefinement
208         ; (pat', pat_tvs, res) <- tc_lpat ctxt pat pat_ty $
209                                   setTypeRefinement reft thing_inside
210         ; if (null pat_tvs) then return ()
211           else lazyPatErr lpat pat_tvs
212         ; return (LazyPat pat', [], res) }
213
214 tc_pat ctxt (WildPat _) pat_ty thing_inside
215   = do  { pat_ty' <- zapExpectedType pat_ty argTypeKind
216         -- Note argTypeKind, so that
217         --      f _ = 3
218         -- is rejected when f applied to an unboxed tuple
219         -- However, this means that 
220         --      (case g x of _ -> ...)
221         -- is rejected g returns an unboxed tuple, which is perhpas
222         -- annoying.  I suppose we could pass the context into tc_pat...
223         ; res <- thing_inside
224         ; return (WildPat pat_ty', [], res) }
225
226 tc_pat ctxt (AsPat (L nm_loc name) pat) pat_ty thing_inside
227   = do  { bndr_id <- setSrcSpan nm_loc (tcPatBndr ctxt name pat_ty)
228         ; (pat', tvs, res) <- tcExtendIdEnv1 name bndr_id $
229                               tc_lpat ctxt pat (Check (idType bndr_id)) thing_inside
230             -- NB: if we do inference on:
231             --          \ (y@(x::forall a. a->a)) = e
232             -- we'll fail.  The as-pattern infers a monotype for 'y', which then
233             -- fails to unify with the polymorphic type for 'x'.  This could 
234             -- perhaps be fixed, but only with a bit more work.
235             --
236             -- If you fix it, don't forget the bindInstsOfPatIds!
237         ; return (AsPat (L nm_loc bndr_id) pat', tvs, res) }
238
239 tc_pat ctxt (SigPatIn pat sig) pat_ty thing_inside
240   = do  {       -- See Note [Pattern coercions] below
241           (sig_tvs, sig_ty) <- tcHsPatSigType PatSigCtxt sig
242         ; tcSubPat sig_ty pat_ty
243         ; (pat', tvs, res) <- tcExtendTyVarEnv sig_tvs $
244                               tc_lpat ctxt pat (Check sig_ty) thing_inside
245         ; return (SigPatOut pat' sig_ty, tvs, res) }
246
247 tc_pat ctxt pat@(TypePat ty) pat_ty thing_inside
248   = failWithTc (badTypePat pat)
249
250 ------------------------
251 -- Lists, tuples, arrays
252 tc_pat ctxt (ListPat pats _) pat_ty thing_inside
253   = do  { elem_ty <- zapToListTy pat_ty
254         ; (pats', pats_tvs, res) <- tcCheckPats ctxt pats (repeat elem_ty) thing_inside
255         ; return (ListPat pats' elem_ty, pats_tvs, res) }
256
257 tc_pat ctxt (PArrPat pats _) pat_ty thing_inside
258   = do  { [elem_ty] <- zapToTyConApp parrTyCon pat_ty
259         ; (pats', pats_tvs, res) <- tcCheckPats ctxt pats (repeat elem_ty) thing_inside
260         ; return (PArrPat pats' elem_ty, pats_tvs, res) }
261
262 tc_pat ctxt (TuplePat pats boxity) pat_ty thing_inside
263   = do  { let arity = length pats
264               tycon = tupleTyCon boxity arity
265         ; arg_tys <- zapToTyConApp tycon pat_ty
266         ; (pats', pats_tvs, res) <- tcCheckPats ctxt pats arg_tys thing_inside
267
268         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
269         -- so that we can experiment with lazy tuple-matching.
270         -- This is a pretty odd place to make the switch, but
271         -- it was easy to do.
272         ; let unmangled_result = TuplePat pats' boxity
273               possibly_mangled_result
274                 | opt_IrrefutableTuples && isBoxed boxity = LazyPat (noLoc unmangled_result)
275                 | otherwise                               = unmangled_result
276
277         ; ASSERT( length arg_tys == arity )     -- Syntactically enforced
278           return (possibly_mangled_result, pats_tvs, res) }
279
280 ------------------------
281 -- Data constructors
282 tc_pat ctxt pat_in@(ConPatIn (L con_span con_name) arg_pats) pat_ty thing_inside
283   = do  { data_con <- tcLookupDataCon con_name
284         ; let tycon = dataConTyCon data_con
285         ; ty_args <- zapToTyConApp tycon pat_ty
286         ; (pat', tvs, res) <- tcConPat ctxt data_con tycon ty_args arg_pats thing_inside
287         ; return (pat', tvs, res) }
288
289
290 ------------------------
291 -- Literal patterns
292 tc_pat ctxt pat@(LitPat lit@(HsString _)) pat_ty thing_inside
293   = do  {       -- Strings are mapped to NPatOuts, which have a guard expression
294           zapExpectedTo pat_ty stringTy
295         ; eq_id <- tcLookupId eqStringName
296         ; res <- thing_inside
297         ; returnM (NPatOut lit stringTy (nlHsVar eq_id `HsApp` nlHsLit lit), [], res) }
298
299 tc_pat ctxt (LitPat simple_lit) pat_ty thing_inside
300   = do  {       -- All other simple lits
301           zapExpectedTo pat_ty (hsLitType simple_lit)
302         ; res <- thing_inside
303         ; returnM (LitPat simple_lit, [], res) }
304
305 ------------------------
306 -- Overloaded patterns: n, and n+k
307 tc_pat ctxt pat@(NPatIn over_lit mb_neg) pat_ty thing_inside
308   = do  { pat_ty' <- zapExpectedType pat_ty liftedTypeKind
309         ; let origin = LiteralOrigin over_lit
310         ; pos_lit_expr <- newOverloadedLit origin over_lit pat_ty'
311         ; eq <- newMethodFromName origin pat_ty' eqName 
312         ; lit_expr <- case mb_neg of
313                         Nothing  -> returnM pos_lit_expr        -- Positive literal
314                         Just neg ->     -- Negative literal
315                                         -- The 'negate' is re-mappable syntax
316                             do { (_, neg_expr) <- tcSyntaxName origin pat_ty' 
317                                                                (negateName, HsVar neg)
318                                ; returnM (mkHsApp (noLoc neg_expr) pos_lit_expr) }
319
320         ; let   -- The literal in an NPatIn is always positive...
321                 -- But in NPatOut, the literal is used to find identical patterns
322                 --      so we must negate the literal when necessary!
323                 lit' = case (over_lit, mb_neg) of
324                          (HsIntegral i _,   Nothing) -> HsInteger i pat_ty'
325                          (HsIntegral i _,   Just _)  -> HsInteger (-i) pat_ty'
326                          (HsFractional f _, Nothing) -> HsRat f pat_ty'
327                          (HsFractional f _, Just _)  -> HsRat (-f) pat_ty'
328
329         ; res <- thing_inside
330         ; returnM (NPatOut lit' pat_ty' (HsApp (nlHsVar eq) lit_expr), [], res) }
331
332 tc_pat ctxt pat@(NPlusKPatIn (L nm_loc name) lit@(HsIntegral i _) minus_name) pat_ty thing_inside
333   = do  { bndr_id <- setSrcSpan nm_loc (tcPatBndr ctxt name pat_ty)
334         ; let pat_ty' = idType bndr_id
335               origin = LiteralOrigin lit
336         ; over_lit_expr <- newOverloadedLit origin lit pat_ty'
337         ; ge <- newMethodFromName origin pat_ty' geName
338
339         -- The '-' part is re-mappable syntax
340         ; (_, minus_expr) <- tcSyntaxName origin pat_ty' (minusName, HsVar minus_name)
341
342         -- The Report says that n+k patterns must be in Integral
343         -- We may not want this when using re-mappable syntax, though (ToDo?)
344         ; icls <- tcLookupClass integralClassName
345         ; dicts <- newDicts origin [mkClassPred icls [pat_ty']] 
346         ; extendLIEs dicts
347     
348         ; res <- tcExtendIdEnv1 name bndr_id thing_inside
349         ; returnM (NPlusKPatOut (L nm_loc bndr_id) i 
350                                 (SectionR (nlHsVar ge) over_lit_expr)
351                                 (SectionR (noLoc minus_expr) over_lit_expr),
352                    [], res) }
353 \end{code}
354
355
356 %************************************************************************
357 %*                                                                      *
358         Most of the work for constructors is here
359         (the rest is in the ConPatIn case of tc_pat)
360 %*                                                                      *
361 %************************************************************************
362
363 \begin{code}
364 tcConPat :: PatCtxt -> DataCon -> TyCon -> [TcTauType] 
365          -> HsConDetails Name (LPat Name) -> TcM a
366          -> TcM (Pat TcId, [TcTyVar], a)
367 tcConPat ctxt data_con tycon ty_args arg_pats thing_inside
368   | isVanillaDataCon data_con
369   = do  { let arg_tys = dataConInstOrigArgTys data_con ty_args
370         ; tcInstStupidTheta data_con ty_args
371         ; traceTc (text "tcConPat" <+> vcat [ppr data_con, ppr ty_args, ppr arg_tys])
372         ; (arg_pats', tvs, res) <- tcConArgs ctxt data_con arg_pats arg_tys thing_inside
373         ; return (ConPatOut data_con [] [] emptyLHsBinds 
374                             arg_pats' (mkTyConApp tycon ty_args),
375                   tvs, res) }
376
377   | otherwise   -- GADT case
378   = do  { let (tvs, theta, arg_tys, _, res_tys) = dataConSig data_con
379         ; span <- getSrcSpanM
380         ; let rigid_info = PatSkol data_con span
381         ; tvs' <- tcSkolTyVars rigid_info tvs
382         ; let tv_tys'  = mkTyVarTys tvs'
383               tenv     = zipTopTvSubst tvs tv_tys'
384               theta'   = substTheta tenv theta
385               arg_tys' = substTys tenv arg_tys
386               res_tys' = substTys tenv res_tys
387         ; dicts <- newDicts (SigOrigin rigid_info) theta'
388         ; tcInstStupidTheta data_con tv_tys'
389
390         -- Do type refinement!
391         ; traceTc (text "tcGadtPat" <+> vcat [ppr data_con, ppr tvs', ppr arg_tys', ppr res_tys', 
392                                               text "ty-args:" <+> ppr ty_args ])
393         ; refineAlt ctxt data_con tvs' ty_args res_tys' $ do    
394
395         { ((arg_pats', inner_tvs, res), lie_req) 
396                 <- getLIE (tcConArgs ctxt data_con arg_pats arg_tys' thing_inside)
397
398         ; dict_binds <- tcSimplifyCheck doc tvs' dicts lie_req
399
400         ; return (ConPatOut data_con 
401                             tvs' (map instToId dicts) dict_binds
402                             arg_pats' (mkTyConApp tycon ty_args),
403                   tvs' ++ inner_tvs, res) } }
404   where
405     doc = ptext SLIT("existential context for") <+> quotes (ppr data_con)
406
407 tcConArgs :: PatCtxt -> DataCon 
408            -> HsConDetails Name (LPat Name) -> [TcSigmaType]
409            -> TcM a
410            -> TcM (HsConDetails TcId (LPat Id), [TcTyVar], a)
411
412 tcConArgs ctxt data_con (PrefixCon arg_pats) arg_tys thing_inside
413   = do  { checkTc (con_arity == no_of_args)     -- Check correct arity
414                   (arityErr "Constructor" data_con con_arity no_of_args)
415         ; (arg_pats', tvs, res) <- tcCheckPats ctxt arg_pats arg_tys thing_inside
416         ; return (PrefixCon arg_pats', tvs, res) }
417   where
418     con_arity  = dataConSourceArity data_con
419     no_of_args = length arg_pats
420
421 tcConArgs ctxt data_con (InfixCon p1 p2) arg_tys thing_inside
422   = do  { checkTc (con_arity == 2)      -- Check correct arity
423                   (arityErr "Constructor" data_con con_arity 2)
424         ; ([p1',p2'], tvs, res) <- tcCheckPats ctxt [p1,p2] arg_tys thing_inside
425         ; return (InfixCon p1' p2', tvs, res) }
426   where
427     con_arity  = dataConSourceArity data_con
428
429 tcConArgs ctxt data_con (RecCon rpats) arg_tys thing_inside
430   = do  { (rpats', tvs, res) <- tc_fields rpats thing_inside
431         ; return (RecCon rpats', tvs, res) }
432   where
433     tc_fields :: [(Located Name, LPat Name)] -> TcM a
434               -> TcM ([(Located TcId, LPat TcId)], [TcTyVar], a)
435     tc_fields [] thing_inside
436       = do { res <- thing_inside
437            ; return ([], [], res) }
438
439     tc_fields (rpat : rpats) thing_inside
440       = do { (rpat', tvs1, (rpats', tvs2, res)) 
441                 <- tc_field rpat (tc_fields rpats thing_inside)
442            ; return (rpat':rpats', tvs1 ++ tvs2, res) }
443
444     tc_field (field_lbl, pat) thing_inside
445       = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
446            ; (pat', tvs, res) <- tcPat ctxt pat (Check pat_ty) thing_inside
447            ; return ((sel_id, pat'), tvs, res) }
448
449     find_field_ty field_lbl
450         = case [ty | (f,ty) <- field_tys, f == field_lbl] of
451
452                 -- No matching field; chances are this field label comes from some
453                 -- other record type (or maybe none).  As well as reporting an
454                 -- error we still want to typecheck the pattern, principally to
455                 -- make sure that all the variables it binds are put into the
456                 -- environment, else the type checker crashes later:
457                 --      f (R { foo = (a,b) }) = a+b
458                 -- If foo isn't one of R's fields, we don't want to crash when
459                 -- typechecking the "a+b".
460            [] -> do { addErrTc (badFieldCon data_con field_lbl)
461                     ; bogus_ty <- newTyFlexiVarTy liftedTypeKind
462                     ; return (error "Bogus selector Id", bogus_ty) }
463
464                 -- The normal case, when the field comes from the right constructor
465            (pat_ty : extras) -> 
466                 ASSERT( null extras )
467                 do { sel_id <- tcLookupId field_lbl
468                    ; return (sel_id, pat_ty) }
469
470     field_tys = zip (dataConFieldLabels data_con) arg_tys
471         -- Don't use zipEqual! If the constructor isn't really a record, then
472         -- dataConFieldLabels will be empty (and each field in the pattern
473         -- will generate an error below).
474 \end{code}
475
476
477 %************************************************************************
478 %*                                                                      *
479                 Type refinement
480 %*                                                                      *
481 %************************************************************************
482
483 \begin{code}
484 refineAlt :: PatCtxt -> DataCon
485             -> [TcTyVar]        -- Freshly bound type variables
486             -> [TcType]         -- Types from the scrutinee (context)
487             -> [TcType]         -- Types from the pattern
488             -> TcM a -> TcM a
489 refineAlt ctxt con ex_tvs ctxt_tys pat_tys thing_inside 
490   = do  { old_subst <- getTypeRefinement
491         ; let refiner | can_i_refine ctxt = tcRefineTys
492                       | otherwise         = tcMatchTys
493         ; case refiner ex_tvs old_subst pat_tys ctxt_tys of
494                 Failed msg -> failWithTc (inaccessibleAlt msg)
495                 Succeeded new_subst -> do
496         { traceTc (text "refineTypes:match" <+> ppr con <+> ppr new_subst)
497         ; setTypeRefinement new_subst thing_inside } }
498
499   where
500     can_i_refine (LamPat can_refine) = can_refine
501     can_i_refine other_ctxt          = False
502 \end{code}
503
504 %************************************************************************
505 %*                                                                      *
506                 Note [Pattern coercions]
507 %*                                                                      *
508 %************************************************************************
509
510 In principle, these program would be reasonable:
511         
512         f :: (forall a. a->a) -> Int
513         f (x :: Int->Int) = x 3
514
515         g :: (forall a. [a]) -> Bool
516         g [] = True
517
518 In both cases, the function type signature restricts what arguments can be passed
519 in a call (to polymorphic ones).  The pattern type signature then instantiates this
520 type.  For example, in the first case,  (forall a. a->a) <= Int -> Int, and we
521 generate the translated term
522         f = \x' :: (forall a. a->a).  let x = x' Int in x 3
523
524 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
525 And it requires a significant amount of code to implement, becuase we need to decorate
526 the translated pattern with coercion functions (generated from the subsumption check 
527 by tcSub).  
528
529 So for now I'm just insisting on type *equality* in patterns.  No subsumption. 
530
531 Old notes about desugaring, at a time when pattern coercions were handled:
532
533 A SigPat is a type coercion and must be handled one at at time.  We can't
534 combine them unless the type of the pattern inside is identical, and we don't
535 bother to check for that.  For example:
536
537         data T = T1 Int | T2 Bool
538         f :: (forall a. a -> a) -> T -> t
539         f (g::Int->Int)   (T1 i) = T1 (g i)
540         f (g::Bool->Bool) (T2 b) = T2 (g b)
541
542 We desugar this as follows:
543
544         f = \ g::(forall a. a->a) t::T ->
545             let gi = g Int
546             in case t of { T1 i -> T1 (gi i)
547                            other ->
548             let gb = g Bool
549             in case t of { T2 b -> T2 (gb b)
550                            other -> fail }}
551
552 Note that we do not treat the first column of patterns as a
553 column of variables, because the coerced variables (gi, gb)
554 would be of different types.  So we get rather grotty code.
555 But I don't think this is a common case, and if it was we could
556 doubtless improve it.
557
558 Meanwhile, the strategy is:
559         * treat each SigPat coercion (always non-identity coercions)
560                 as a separate block
561         * deal with the stuff inside, and then wrap a binding round
562                 the result to bind the new variable (gi, gb, etc)
563
564
565 %************************************************************************
566 %*                                                                      *
567 \subsection{Errors and contexts}
568 %*                                                                      *
569 %************************************************************************
570
571 \begin{code}
572 patCtxt :: Pat Name -> Maybe Message    -- Not all patterns are worth pushing a context
573 patCtxt (VarPat _)  = Nothing
574 patCtxt (ParPat _)  = Nothing
575 patCtxt (AsPat _ _) = Nothing
576 patCtxt pat         = Just (hang (ptext SLIT("When checking the pattern:")) 
577                                4 (ppr pat))
578
579 badFieldCon :: DataCon -> Name -> SDoc
580 badFieldCon con field
581   = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
582           ptext SLIT("does not have field"), quotes (ppr field)]
583
584 polyPatSig :: TcType -> SDoc
585 polyPatSig sig_ty
586   = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
587          4 (ppr sig_ty)
588
589 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
590
591 lazyPatErr pat tvs
592   = failWithTc $
593     hang (ptext SLIT("A lazy (~) pattern connot bind existential type variables"))
594        2 (vcat (map get tvs))
595   where
596    get tv = ASSERT( isSkolemTyVar tv ) pprSkolemTyVar tv
597
598 inaccessibleAlt msg
599   = hang (ptext SLIT("Inaccessible case alternative:")) 2 msg
600 \end{code}