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