Make rebindable do-notation behave as advertised
[ghc-hetmet.git] / compiler / typecheck / TcPat.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 TcPat: Typechecking patterns
7
8 \begin{code}
9 {-# OPTIONS -w #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 module TcPat ( tcLetPat, tcLamPat, tcLamPats, tcProcPat, tcOverloadedLit,
17                addDataConStupidTheta, badFieldCon, polyPatSig ) where
18
19 #include "HsVersions.h"
20
21 import {-# SOURCE #-}   TcExpr( tcSyntaxOp, tcInferRho)
22
23 import HsSyn
24 import TcHsSyn
25 import TcRnMonad
26 import Inst
27 import Id
28 import Var
29 import CoreFVs
30 import Name
31 import TcSimplify
32 import TcEnv
33 import TcMType
34 import TcType
35 import VarSet
36 import TcUnify
37 import TcHsType
38 import TysWiredIn
39 import TcGadt
40 import Type
41 import Coercion
42 import StaticFlags
43 import TyCon
44 import DataCon
45 import DynFlags
46 import PrelNames
47 import BasicTypes hiding (SuccessFlag(..))
48 import SrcLoc
49 import ErrUtils
50 import Util
51 import Maybes
52 import Outputable
53 import FastString
54 \end{code}
55
56
57 %************************************************************************
58 %*                                                                      *
59                 External interface
60 %*                                                                      *
61 %************************************************************************
62
63 \begin{code}
64 tcLetPat :: (Name -> Maybe TcRhoType)
65          -> LPat Name -> BoxySigmaType 
66          -> TcM a
67          -> TcM (LPat TcId, a)
68 tcLetPat sig_fn pat pat_ty thing_inside
69   = do  { let init_state = PS { pat_ctxt = LetPat sig_fn, 
70                                 pat_reft = emptyRefinement,
71                                 pat_eqs  = False }
72         ; (pat', ex_tvs, res) <- tc_lpat pat pat_ty init_state (\ _ -> thing_inside)
73
74         -- Don't know how to deal with pattern-bound existentials yet
75         ; checkTc (null ex_tvs) (existentialExplode pat)
76
77         ; return (pat', res) }
78
79 -----------------
80 tcLamPats :: [LPat Name]                                -- Patterns,
81           -> [BoxySigmaType]                            --   and their types
82           -> BoxyRhoType                                -- Result type,
83           -> ((Refinement, BoxyRhoType) -> TcM a)       --   and the checker for the body
84           -> TcM ([LPat TcId], a)
85
86 -- This is the externally-callable wrapper function
87 -- Typecheck the patterns, extend the environment to bind the variables,
88 -- do the thing inside, use any existentially-bound dictionaries to 
89 -- discharge parts of the returning LIE, and deal with pattern type
90 -- signatures
91
92 --   1. Initialise the PatState
93 --   2. Check the patterns
94 --   3. Apply the refinement to the environment and result type
95 --   4. Check the body
96 --   5. Check that no existentials escape
97
98 tcLamPats pats tys res_ty thing_inside
99   = tc_lam_pats LamPat (zipEqual "tcLamPats" pats tys)
100                 (emptyRefinement, res_ty) thing_inside
101
102 tcLamPat :: LPat Name -> BoxySigmaType 
103          -> (Refinement,BoxyRhoType)            -- Result type
104          -> ((Refinement,BoxyRhoType) -> TcM a) -- Checker for body, given its result type
105          -> TcM (LPat TcId, a)
106
107 tcProcPat = tc_lam_pat ProcPat
108 tcLamPat  = tc_lam_pat LamPat
109
110 tc_lam_pat ctxt pat pat_ty res_ty thing_inside
111   = do  { ([pat'],thing) <- tc_lam_pats ctxt [(pat, pat_ty)] res_ty thing_inside
112         ; return (pat', thing) }
113
114 -----------------
115 tc_lam_pats :: PatCtxt
116             -> [(LPat Name,BoxySigmaType)]
117             -> (Refinement,BoxyRhoType)                 -- Result type
118             -> ((Refinement,BoxyRhoType) -> TcM a)      -- Checker for body, given its result type
119             -> TcM ([LPat TcId], a)
120 tc_lam_pats ctxt pat_ty_prs (reft, res_ty) thing_inside 
121   =  do { let init_state = PS { pat_ctxt = ctxt, pat_reft = reft, pat_eqs = False }
122
123         ; (pats', ex_tvs, res) <- tcMultiple tc_lpat_pr pat_ty_prs init_state $ \ pstate' ->
124                                   refineEnvironment (pat_reft pstate') (pat_eqs pstate') $
125                                   if (pat_eqs pstate' && (not $ isRigidTy res_ty))
126                                      then failWithTc (nonRigidResult res_ty)
127                                      else thing_inside (pat_reft pstate', res_ty)
128
129         ; let tys = map snd pat_ty_prs
130         ; tcCheckExistentialPat pats' ex_tvs tys res_ty
131
132         ; returnM (pats', res) }
133
134
135 -----------------
136 tcCheckExistentialPat :: [LPat TcId]            -- Patterns (just for error message)
137                       -> [TcTyVar]              -- Existentially quantified tyvars bound by pattern
138                       -> [BoxySigmaType]        -- Types of the patterns
139                       -> BoxyRhoType            -- Type of the body of the match
140                                                 -- Tyvars in either of these must not escape
141                       -> TcM ()
142 -- NB: we *must* pass "pats_tys" not just "body_ty" to tcCheckExistentialPat
143 -- For example, we must reject this program:
144 --      data C = forall a. C (a -> Int) 
145 --      f (C g) x = g x
146 -- Here, result_ty will be simply Int, but expected_ty is (C -> a -> Int).
147
148 tcCheckExistentialPat pats [] pat_tys body_ty
149   = return ()   -- Short cut for case when there are no existentials
150
151 tcCheckExistentialPat pats ex_tvs pat_tys body_ty
152   = addErrCtxtM (sigPatCtxt pats ex_tvs pat_tys body_ty)        $
153     checkSigTyVarsWrt (tcTyVarsOfTypes (body_ty:pat_tys)) ex_tvs
154
155 data PatState = PS {
156         pat_ctxt :: PatCtxt,
157         pat_reft :: Refinement, -- Binds rigid TcTyVars to their refinements
158         pat_eqs  :: Bool        -- <=> there are GADT equational constraints 
159                                 --     for refinement 
160   }
161
162 data PatCtxt 
163   = LamPat 
164   | ProcPat                             -- The pattern in (proc pat -> ...)
165                                         --      see Note [Arrows and patterns]
166   | LetPat (Name -> Maybe TcRhoType)    -- Used for let(rec) bindings
167
168 patSigCtxt :: PatState -> UserTypeCtxt
169 patSigCtxt (PS { pat_ctxt = LetPat _ }) = BindPatSigCtxt
170 patSigCtxt other                        = LamPatSigCtxt
171 \end{code}
172
173
174
175 %************************************************************************
176 %*                                                                      *
177                 Binders
178 %*                                                                      *
179 %************************************************************************
180
181 \begin{code}
182 tcPatBndr :: PatState -> Name -> BoxySigmaType -> TcM TcId
183 tcPatBndr (PS { pat_ctxt = LetPat lookup_sig }) bndr_name pat_ty
184   | Just mono_ty <- lookup_sig bndr_name
185   = do  { mono_name <- newLocalName bndr_name
186         ; boxyUnify mono_ty pat_ty
187         ; return (Id.mkLocalId mono_name mono_ty) }
188
189   | otherwise
190   = do  { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
191         ; mono_name <- newLocalName bndr_name
192         ; return (Id.mkLocalId mono_name pat_ty') }
193
194 tcPatBndr (PS { pat_ctxt = _lam_or_proc }) bndr_name pat_ty
195   = do  { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
196                 -- We have an undecorated binder, so we do rule ABS1,
197                 -- by unboxing the boxy type, forcing any un-filled-in
198                 -- boxes to become monotypes
199                 -- NB that pat_ty' can still be a polytype:
200                 --      data T = MkT (forall a. a->a)
201                 --      f t = case t of { MkT g -> ... }
202                 -- Here, the 'g' must get type (forall a. a->a) from the
203                 -- MkT context
204         ; return (Id.mkLocalId bndr_name pat_ty') }
205
206
207 -------------------
208 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, LHsBinds TcId)
209 bindInstsOfPatId id thing_inside
210   | not (isOverloadedTy (idType id))
211   = do { res <- thing_inside; return (res, emptyLHsBinds) }
212   | otherwise
213   = do  { (res, lie) <- getLIE thing_inside
214         ; binds <- bindInstsOfLocalFuns lie [id]
215         ; return (res, binds) }
216
217 -------------------
218 unBoxPatBndrType  ty name = unBoxArgType ty (ptext SLIT("The variable") <+> quotes (ppr name))
219 unBoxWildCardType ty      = unBoxArgType ty (ptext SLIT("A wild-card pattern"))
220 unBoxViewPatType  ty pat  = unBoxArgType ty (ptext SLIT("The view pattern") <+> ppr pat)
221
222 unBoxArgType :: BoxyType -> SDoc -> TcM TcType
223 -- In addition to calling unbox, unBoxArgType ensures that the type is of ArgTypeKind; 
224 -- that is, it can't be an unboxed tuple.  For example, 
225 --      case (f x) of r -> ...
226 -- should fail if 'f' returns an unboxed tuple.
227 unBoxArgType ty pp_this
228   = do  { ty' <- unBox ty       -- Returns a zonked type
229
230         -- Neither conditional is strictly necesssary (the unify alone will do)
231         -- but they improve error messages, and allocate fewer tyvars
232         ; if isUnboxedTupleType ty' then
233                 failWithTc msg
234           else if isSubArgTypeKind (typeKind ty') then
235                 return ty'
236           else do       -- OpenTypeKind, so constrain it
237         { ty2 <- newFlexiTyVarTy argTypeKind
238         ; unifyType ty' ty2
239         ; return ty' }}
240   where
241     msg = pp_this <+> ptext SLIT("cannot be bound to an unboxed tuple")
242 \end{code}
243
244
245 %************************************************************************
246 %*                                                                      *
247                 The main worker functions
248 %*                                                                      *
249 %************************************************************************
250
251 Note [Nesting]
252 ~~~~~~~~~~~~~~
253 tcPat takes a "thing inside" over which the pattern scopes.  This is partly
254 so that tcPat can extend the environment for the thing_inside, but also 
255 so that constraints arising in the thing_inside can be discharged by the
256 pattern.
257
258 This does not work so well for the ErrCtxt carried by the monad: we don't
259 want the error-context for the pattern to scope over the RHS. 
260 Hence the getErrCtxt/setErrCtxt stuff in tc_lpats.
261
262 \begin{code}
263 --------------------
264 type Checker inp out =  forall r.
265                           inp
266                        -> PatState
267                        -> (PatState -> TcM r)
268                        -> TcM (out, [TcTyVar], r)
269
270 tcMultiple :: Checker inp out -> Checker [inp] [out]
271 tcMultiple tc_pat args pstate thing_inside
272   = do  { err_ctxt <- getErrCtxt
273         ; let loop pstate []
274                 = do { res <- thing_inside pstate
275                      ; return ([], [], res) }
276
277               loop pstate (arg:args)
278                 = do { (p', p_tvs, (ps', ps_tvs, res)) 
279                                 <- tc_pat arg pstate $ \ pstate' ->
280                                    setErrCtxt err_ctxt $
281                                    loop pstate' args
282                 -- setErrCtxt: restore context before doing the next pattern
283                 -- See note [Nesting] above
284                                 
285                      ; return (p':ps', p_tvs ++ ps_tvs, res) }
286
287         ; loop pstate args }
288
289 --------------------
290 tc_lpat_pr :: (LPat Name, BoxySigmaType)
291            -> PatState
292            -> (PatState -> TcM a)
293            -> TcM (LPat TcId, [TcTyVar], a)
294 tc_lpat_pr (pat, ty) = tc_lpat pat ty
295
296 tc_lpat :: LPat Name 
297         -> BoxySigmaType
298         -> PatState
299         -> (PatState -> TcM a)
300         -> TcM (LPat TcId, [TcTyVar], a)
301 tc_lpat (L span pat) pat_ty pstate thing_inside
302   = setSrcSpan span               $
303     maybeAddErrCtxt (patCtxt pat) $
304     do  { let mb_reft = refineType (pat_reft pstate) pat_ty
305               pat_ty' = case mb_reft of { Just (_, ty') -> ty'; Nothing -> pat_ty }
306
307                 -- Make sure the result type reflects the current refinement
308                 -- We must do this here, so that it correctly ``sees'' all
309                 -- the refinements to the left.  Example:
310                 -- Suppose C :: forall a. T a -> a -> Foo
311                 -- Pattern      C a p1 True
312                 -- So p1 might refine 'a' to True, and the True 
313                 -- pattern had better see it.
314
315         ; (pat', tvs, res) <- tc_pat pstate pat pat_ty' thing_inside
316         ; let final_pat = case mb_reft of
317                                 Nothing     -> pat'
318                                 Just (co,_) -> CoPat (WpCo co) pat' pat_ty
319         ; return (L span final_pat, tvs, res) }
320
321 --------------------
322 tc_pat  :: PatState
323         -> Pat Name 
324         -> BoxySigmaType        -- Fully refined result type
325         -> (PatState -> TcM a)  -- Thing inside
326         -> TcM (Pat TcId,       -- Translated pattern
327                 [TcTyVar],      -- Existential binders
328                 a)              -- Result of thing inside
329
330 tc_pat pstate (VarPat name) pat_ty thing_inside
331   = do  { id <- tcPatBndr pstate name pat_ty
332         ; (res, binds) <- bindInstsOfPatId id $
333                           tcExtendIdEnv1 name id $
334                           (traceTc (text "binding" <+> ppr name <+> ppr (idType id))
335                            >> thing_inside pstate)
336         ; let pat' | isEmptyLHsBinds binds = VarPat id
337                    | otherwise             = VarPatOut id binds
338         ; return (pat', [], res) }
339
340 tc_pat pstate (ParPat pat) pat_ty thing_inside
341   = do  { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
342         ; return (ParPat pat', tvs, res) }
343
344 tc_pat pstate (BangPat pat) pat_ty thing_inside
345   = do  { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
346         ; return (BangPat pat', tvs, res) }
347
348 -- There's a wrinkle with irrefutable patterns, namely that we
349 -- must not propagate type refinement from them.  For example
350 --      data T a where { T1 :: Int -> T Int; ... }
351 --      f :: T a -> Int -> a
352 --      f ~(T1 i) y = y
353 -- It's obviously not sound to refine a to Int in the right
354 -- hand side, because the arugment might not match T1 at all!
355 --
356 -- Nor should a lazy pattern bind any existential type variables
357 -- because they won't be in scope when we do the desugaring
358 --
359 -- Note [Hopping the LIE in lazy patterns]
360 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
361 -- In a lazy pattern, we must *not* discharge constraints from the RHS
362 -- from dictionaries bound in the pattern.  E.g.
363 --      f ~(C x) = 3
364 -- We can't discharge the Num constraint from dictionaries bound by
365 -- the pattern C!  
366 --
367 -- So we have to make the constraints from thing_inside "hop around" 
368 -- the pattern.  Hence the getLLE and extendLIEs later.
369
370 tc_pat pstate lpat@(LazyPat pat) pat_ty thing_inside
371   = do  { (pat', pat_tvs, (res,lie)) 
372                 <- tc_lpat pat pat_ty pstate $ \ _ ->
373                    getLIE (thing_inside pstate)
374                 -- Ignore refined pstate', revert to pstate
375         ; extendLIEs lie
376         -- getLIE/extendLIEs: see Note [Hopping the LIE in lazy patterns]
377
378         -- Check no existentials
379         ; if (null pat_tvs) then return ()
380           else lazyPatErr lpat pat_tvs
381
382         -- Check that the pattern has a lifted type
383         ; pat_tv <- newBoxyTyVar liftedTypeKind
384         ; boxyUnify pat_ty (mkTyVarTy pat_tv)
385
386         ; return (LazyPat pat', [], res) }
387
388 tc_pat pstate (WildPat _) pat_ty thing_inside
389   = do  { pat_ty' <- unBoxWildCardType pat_ty   -- Make sure it's filled in with monotypes
390         ; res <- thing_inside pstate
391         ; return (WildPat pat_ty', [], res) }
392
393 tc_pat pstate (AsPat (L nm_loc name) pat) pat_ty thing_inside
394   = do  { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
395         ; (pat', tvs, res) <- tcExtendIdEnv1 name bndr_id $
396                               tc_lpat pat (idType bndr_id) pstate thing_inside
397             -- NB: if we do inference on:
398             --          \ (y@(x::forall a. a->a)) = e
399             -- we'll fail.  The as-pattern infers a monotype for 'y', which then
400             -- fails to unify with the polymorphic type for 'x'.  This could 
401             -- perhaps be fixed, but only with a bit more work.
402             --
403             -- If you fix it, don't forget the bindInstsOfPatIds!
404         ; return (AsPat (L nm_loc bndr_id) pat', tvs, res) }
405
406 tc_pat pstate (orig@(ViewPat expr pat _)) overall_pat_ty thing_inside 
407   = do  { -- morally, expr must have type
408          -- `forall a1...aN. OPT' -> B` 
409          -- where overall_pat_ty is an instance of OPT'.
410          -- Here, we infer a rho type for it,
411          -- which replaces the leading foralls and constraints
412          -- with fresh unification variables.
413          (expr',expr'_inferred) <- tcInferRho expr
414          -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
415        ; let expr'_expected = \ pat_ty -> (mkFunTy overall_pat_ty pat_ty)
416          -- tcSubExp: expected first, offered second
417          -- returns coercion
418          -- 
419          -- NOTE: this forces pat_ty to be a monotype (because we use a unification 
420          -- variable to find it).  this means that in an example like
421          -- (view -> f)    where view :: _ -> forall b. b
422          -- we will only be able to use view at one instantation in the
423          -- rest of the view
424         ; (expr_coerc, pat_ty) <- tcInfer $ \ pat_ty -> 
425                 tcSubExp ViewPatOrigin (expr'_expected pat_ty) expr'_inferred
426
427          -- pattern must have pat_ty
428        ; (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
429          -- this should get zonked later on, but we unBox it here
430          -- so that we do the same checks as above
431         ; annotation_ty <- unBoxViewPatType overall_pat_ty orig        
432         ; return (ViewPat (mkLHsWrap expr_coerc expr') pat' annotation_ty, tvs, res) }
433
434 -- Type signatures in patterns
435 -- See Note [Pattern coercions] below
436 tc_pat pstate (SigPatIn pat sig_ty) pat_ty thing_inside
437   = do  { (inner_ty, tv_binds) <- tcPatSig (patSigCtxt pstate) sig_ty pat_ty
438         ; (pat', tvs, res) <- tcExtendTyVarEnv2 tv_binds $
439                               tc_lpat pat inner_ty pstate thing_inside
440         ; return (SigPatOut pat' inner_ty, tvs, res) }
441
442 tc_pat pstate pat@(TypePat ty) pat_ty thing_inside
443   = failWithTc (badTypePat pat)
444
445 ------------------------
446 -- Lists, tuples, arrays
447 tc_pat pstate (ListPat pats _) pat_ty thing_inside
448   = do  { (elt_ty, coi) <- boxySplitListTy pat_ty
449         ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
450                                                 pats pstate thing_inside
451         ; return (mkCoPatCoI coi (ListPat pats' elt_ty) pat_ty, pats_tvs, res) }
452
453 tc_pat pstate (PArrPat pats _) pat_ty thing_inside
454   = do  { (elt_ty, coi) <- boxySplitPArrTy pat_ty
455         ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
456                                                 pats pstate thing_inside 
457         ; ifM (null pats) (zapToMonotype pat_ty)  -- c.f. ExplicitPArr in TcExpr
458         ; return (mkCoPatCoI coi (PArrPat pats' elt_ty) pat_ty, pats_tvs, res) }
459
460 tc_pat pstate (TuplePat pats boxity _) pat_ty thing_inside
461   = do  { let tc = tupleTyCon boxity (length pats)
462         ; (arg_tys, coi) <- boxySplitTyConApp tc pat_ty
463         ; (pats', pats_tvs, res) <- tcMultiple tc_lpat_pr (pats `zip` arg_tys)
464                                                pstate thing_inside
465
466         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
467         -- so that we can experiment with lazy tuple-matching.
468         -- This is a pretty odd place to make the switch, but
469         -- it was easy to do.
470         ; let pat_ty'          = mkTyConApp tc arg_tys
471                                      -- pat_ty /= pat_ty iff coi /= IdCo
472               unmangled_result = TuplePat pats' boxity pat_ty'
473               possibly_mangled_result
474                 | opt_IrrefutableTuples && 
475                   isBoxed boxity            = LazyPat (noLoc unmangled_result)
476                 | otherwise                 = unmangled_result
477
478         ; ASSERT( length arg_tys == length pats )      -- Syntactically enforced
479           return (mkCoPatCoI coi possibly_mangled_result pat_ty, pats_tvs, res) 
480         }
481
482 ------------------------
483 -- Data constructors
484 tc_pat pstate pat_in@(ConPatIn (L con_span con_name) arg_pats) pat_ty thing_inside
485   = do  { data_con <- tcLookupDataCon con_name
486         ; let tycon = dataConTyCon data_con
487         ; tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside }
488
489 ------------------------
490 -- Literal patterns
491 tc_pat pstate (LitPat simple_lit) pat_ty thing_inside
492   = do  { let lit_ty = hsLitType simple_lit
493         ; coi <- boxyUnify lit_ty pat_ty
494                         -- coi is of kind: lit_ty ~ pat_ty
495         ; res <- thing_inside pstate
496         ; span <- getSrcSpanM
497                         -- pattern coercions have to
498                         -- be of kind: pat_ty ~ lit_ty
499                         -- hence, sym coi
500         ; returnM (mkCoPatCoI (mkSymCoI coi) (LitPat simple_lit) pat_ty, 
501                    [], res) }
502
503 ------------------------
504 -- Overloaded patterns: n, and n+k
505 tc_pat pstate pat@(NPat over_lit mb_neg eq) pat_ty thing_inside
506   = do  { let orig = LiteralOrigin over_lit
507         ; lit'    <- tcOverloadedLit orig over_lit pat_ty
508         ; eq'     <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
509         ; mb_neg' <- case mb_neg of
510                         Nothing  -> return Nothing      -- Positive literal
511                         Just neg ->     -- Negative literal
512                                         -- The 'negate' is re-mappable syntax
513                             do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
514                                ; return (Just neg') }
515         ; res <- thing_inside pstate
516         ; returnM (NPat lit' mb_neg' eq', [], res) }
517
518 tc_pat pstate pat@(NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
519   = do  { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
520         ; let pat_ty' = idType bndr_id
521               orig    = LiteralOrigin lit
522         ; lit' <- tcOverloadedLit orig lit pat_ty'
523
524         -- The '>=' and '-' parts are re-mappable syntax
525         ; ge'    <- tcSyntaxOp orig ge    (mkFunTys [pat_ty', pat_ty'] boolTy)
526         ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
527
528         -- The Report says that n+k patterns must be in Integral
529         -- We may not want this when using re-mappable syntax, though (ToDo?)
530         ; icls <- tcLookupClass integralClassName
531         ; instStupidTheta orig [mkClassPred icls [pat_ty']]     
532     
533         ; res <- tcExtendIdEnv1 name bndr_id (thing_inside pstate)
534         ; returnM (NPlusKPat (L nm_loc bndr_id) lit' ge' minus', [], res) }
535
536 tc_pat _ _other_pat _ _ = panic "tc_pat"        -- ConPatOut, SigPatOut, VarPatOut
537 \end{code}
538
539
540 %************************************************************************
541 %*                                                                      *
542         Most of the work for constructors is here
543         (the rest is in the ConPatIn case of tc_pat)
544 %*                                                                      *
545 %************************************************************************
546
547 [Pattern matching indexed data types]
548 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
549 Consider the following declarations:
550
551   data family Map k :: * -> *
552   data instance Map (a, b) v = MapPair (Map a (Pair b v))
553
554 and a case expression
555
556   case x :: Map (Int, c) w of MapPair m -> ...
557
558 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
559 worker/wrapper types for MapPair are
560
561   $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
562   $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
563
564 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
565 :R123Map, which means the straight use of boxySplitTyConApp would give a type
566 error.  Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
567 boxySplitTyConApp with the family tycon Map instead, which gives us the family
568 type list {(Int, c), w}.  To get the correct split for :R123Map, we need to
569 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
570 (provided by tyConFamInst_maybe together with the family tycon).  This
571 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
572 the split arguments for the representation tycon :R123Map as {Int, c, w}
573
574 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion 
575
576   Co123Map a b v :: {Map (a, b) v :=: :R123Map a b v}
577
578 moving between representation and family type into account.  To produce type
579 correct Core, this coercion needs to be used to case the type of the scrutinee
580 from the family to the representation type.  This is achieved by
581 unwrapFamInstScrutinee using a CoPat around the result pattern.
582
583 Now it might appear seem as if we could have used the existing GADT type
584 refinement infrastructure of refineAlt and friends instead of the explicit
585 unification and CoPat generation.  However, that would be wrong.  Why?  The
586 whole point of GADT refinement is that the refinement is local to the case
587 alternative.  In contrast, the substitution generated by the unification of
588 the family type list and instance types needs to be propagated to the outside.
589 Imagine that in the above example, the type of the scrutinee would have been
590 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
591 substitution [x -> (a, b), v -> w].  In contrast to GADT matching, the
592 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
593 alternatives of the case expression, whereas in the GADT case it might vary
594 between alternatives.
595
596 In fact, if we have a data instance declaration defining a GADT, eq_spec will
597 be non-empty and we will get a mixture of global instantiations and local
598 refinement from a single match.  This neatly reflects that, as soon as we
599 have constrained the type of the scrutinee to the required type index, all
600 further type refinement is local to the alternative.
601
602 \begin{code}
603 --      Running example:
604 -- MkT :: forall a b c. (a:=:[b]) => b -> c -> T a
605 --       with scrutinee of type (T ty)
606
607 tcConPat :: PatState -> SrcSpan -> DataCon -> TyCon 
608          -> BoxySigmaType       -- Type of the pattern
609          -> HsConPatDetails Name -> (PatState -> TcM a)
610          -> TcM (Pat TcId, [TcTyVar], a)
611 tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside
612   = do  { let (univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _) = dataConFullSig data_con
613               skol_info  = PatSkol data_con
614               origin     = SigOrigin skol_info
615               full_theta = eq_theta ++ dict_theta
616
617           -- Instantiate the constructor type variables [a->ty]
618           -- This may involve doing a family-instance coercion, and building a wrapper
619         ; (ctxt_res_tys, coi) <- boxySplitTyConAppWithFamily tycon pat_ty
620         ; let pat_ty' = mkTyConApp tycon ctxt_res_tys
621                                      -- pat_ty /= pat_ty iff coi /= IdCo
622               wrap_res_pat res_pat
623                 = mkCoPatCoI coi (unwrapFamInstScrutinee tycon ctxt_res_tys res_pat) pat_ty
624
625           -- Add the stupid theta
626         ; addDataConStupidTheta data_con ctxt_res_tys
627
628         ; ex_tvs' <- tcInstSkolTyVars skol_info ex_tvs  -- Get location from monad,
629                                                         -- not from ex_tvs
630         ; let tenv     = zipTopTvSubst (univ_tvs ++ ex_tvs)
631                                        (ctxt_res_tys ++ mkTyVarTys ex_tvs')
632               arg_tys' = substTys tenv arg_tys
633
634         ; if null ex_tvs && null eq_spec && null full_theta
635           then do {     -- The common case; no class bindings etc (see Note [Arrows and patterns])
636                     (arg_pats', inner_tvs, res) <- tcConArgs data_con arg_tys' 
637                                                                arg_pats pstate thing_inside
638                   ; let res_pat = ConPatOut { pat_con = L con_span data_con, 
639                                               pat_tvs = [], pat_dicts = [], pat_binds = emptyLHsBinds,
640                                               pat_args = arg_pats', pat_ty = pat_ty' }
641
642                     ; return (wrap_res_pat res_pat, inner_tvs, res) }
643
644           else do       -- The general case, with existential, and local equality constraints
645         { let eq_spec' = substEqSpec tenv eq_spec
646               theta'   = substTheta  tenv full_theta
647               ctxt     = pat_ctxt pstate
648         ; checkTc (case ctxt of { ProcPat -> False; other -> True })
649                   (existentialProcPat data_con)
650         ; co_vars <- newCoVars eq_spec' -- Make coercion variables
651         ; traceTc (text "tcConPat: refineAlt")
652         ; pstate' <- refineAlt data_con pstate ex_tvs' co_vars pat_ty
653         ; traceTc (text "tcConPat: refineAlt done!")
654         
655         ; ((arg_pats', inner_tvs, res), lie_req) <- getLIE $
656                 tcConArgs data_con arg_tys' arg_pats pstate' thing_inside
657
658         ; loc <- getInstLoc origin
659         ; dicts <- newDictBndrs loc theta'
660         ; dict_binds <- tcSimplifyCheckPat loc co_vars (pat_reft pstate') 
661                            ex_tvs' dicts lie_req
662
663         ; let res_pat = ConPatOut { pat_con = L con_span data_con, 
664                                     pat_tvs = ex_tvs' ++ co_vars,
665                                     pat_dicts = map instToVar dicts, 
666                                     pat_binds = dict_binds,
667                                     pat_args = arg_pats', pat_ty = pat_ty' }
668         ; return (wrap_res_pat res_pat, ex_tvs' ++ inner_tvs, res)
669         } }
670   where
671     -- Split against the family tycon if the pattern constructor 
672     -- belongs to a family instance tycon.
673     boxySplitTyConAppWithFamily tycon pat_ty =
674       traceTc traceMsg >>
675       case tyConFamInst_maybe tycon of
676         Nothing                   -> boxySplitTyConApp tycon pat_ty
677         Just (fam_tycon, instTys) -> 
678           do { (scrutinee_arg_tys, coi) <- boxySplitTyConApp fam_tycon pat_ty
679              ; (_, freshTvs, subst) <- tcInstTyVars (tyConTyVars tycon)
680              ; boxyUnifyList (substTys subst instTys) scrutinee_arg_tys
681              ; return (freshTvs, coi)
682              }
683       where
684         traceMsg = sep [ text "tcConPat:boxySplitTyConAppWithFamily:" <+>
685                          ppr tycon <+> ppr pat_ty
686                        , text "  family instance:" <+> 
687                          ppr (tyConFamInst_maybe tycon)
688                        ]
689
690     -- Wraps the pattern (which must be a ConPatOut pattern) in a coercion
691     -- pattern if the tycon is an instance of a family.
692     --
693     unwrapFamInstScrutinee :: TyCon -> [Type] -> Pat Id -> Pat Id
694     unwrapFamInstScrutinee tycon args pat
695       | Just co_con <- tyConFamilyCoercion_maybe tycon 
696 --      , not (isNewTyCon tycon)       -- newtypes are explicitly unwrapped by
697                                      -- the desugarer
698           -- NB: We can use CoPat directly, rather than mkCoPat, as we know the
699           --     coercion is not the identity; mkCoPat is inconvenient as it
700           --     wants a located pattern.
701       = CoPat (WpCo $ mkTyConApp co_con args)       -- co fam ty to repr ty
702               (pat {pat_ty = mkTyConApp tycon args})    -- representation type
703               pat_ty                                    -- family inst type
704       | otherwise
705       = pat
706
707
708 tcConArgs :: DataCon -> [TcSigmaType]
709           -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
710
711 tcConArgs data_con arg_tys (PrefixCon arg_pats) pstate thing_inside
712   = do  { checkTc (con_arity == no_of_args)     -- Check correct arity
713                   (arityErr "Constructor" data_con con_arity no_of_args)
714         ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
715         ; (arg_pats', tvs, res) <- tcMultiple tcConArg pats_w_tys
716                                               pstate thing_inside 
717         ; return (PrefixCon arg_pats', tvs, res) }
718   where
719     con_arity  = dataConSourceArity data_con
720     no_of_args = length arg_pats
721
722 tcConArgs data_con arg_tys (InfixCon p1 p2) pstate thing_inside
723   = do  { checkTc (con_arity == 2)      -- Check correct arity
724                   (arityErr "Constructor" data_con con_arity 2)
725         ; let [arg_ty1,arg_ty2] = arg_tys       -- This can't fail after the arity check
726         ; ([p1',p2'], tvs, res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
727                                               pstate thing_inside
728         ; return (InfixCon p1' p2', tvs, res) }
729   where
730     con_arity  = dataConSourceArity data_con
731
732 tcConArgs data_con other_args (InfixCon p1 p2) pstate thing_inside
733   = pprPanic "tcConArgs" (ppr data_con) -- InfixCon always has two arguments
734
735 tcConArgs data_con arg_tys (RecCon (HsRecFields rpats dd)) pstate thing_inside
736   = do  { (rpats', tvs, res) <- tcMultiple tc_field rpats pstate thing_inside
737         ; return (RecCon (HsRecFields rpats' dd), tvs, res) }
738   where
739     tc_field :: Checker (HsRecField FieldLabel (LPat Name)) (HsRecField TcId (LPat TcId))
740     tc_field (HsRecField field_lbl pat pun) pstate thing_inside
741       = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
742            ; (pat', tvs, res) <- tcConArg (pat, pat_ty) pstate thing_inside
743            ; return (HsRecField sel_id pat' pun, tvs, res) }
744
745     find_field_ty :: FieldLabel -> TcM (Id, TcType)
746     find_field_ty field_lbl
747         = case [ty | (f,ty) <- field_tys, f == field_lbl] of
748
749                 -- No matching field; chances are this field label comes from some
750                 -- other record type (or maybe none).  As well as reporting an
751                 -- error we still want to typecheck the pattern, principally to
752                 -- make sure that all the variables it binds are put into the
753                 -- environment, else the type checker crashes later:
754                 --      f (R { foo = (a,b) }) = a+b
755                 -- If foo isn't one of R's fields, we don't want to crash when
756                 -- typechecking the "a+b".
757            [] -> do { addErrTc (badFieldCon data_con field_lbl)
758                     ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
759                     ; return (error "Bogus selector Id", bogus_ty) }
760
761                 -- The normal case, when the field comes from the right constructor
762            (pat_ty : extras) -> 
763                 ASSERT( null extras )
764                 do { sel_id <- tcLookupField field_lbl
765                    ; return (sel_id, pat_ty) }
766
767     field_tys :: [(FieldLabel, TcType)]
768     field_tys = zip (dataConFieldLabels data_con) arg_tys
769         -- Don't use zipEqual! If the constructor isn't really a record, then
770         -- dataConFieldLabels will be empty (and each field in the pattern
771         -- will generate an error below).
772
773 tcConArg :: Checker (LPat Name, BoxySigmaType) (LPat Id)
774 tcConArg (arg_pat, arg_ty) pstate thing_inside
775   = tc_lpat arg_pat arg_ty pstate thing_inside
776         -- NB: the tc_lpat will refine pat_ty if necessary
777         --     based on the current pstate, which may include
778         --     refinements from peer argument patterns to the left
779 \end{code}
780
781 \begin{code}
782 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
783 -- Instantiate the "stupid theta" of the data con, and throw 
784 -- the constraints into the constraint set
785 addDataConStupidTheta data_con inst_tys
786   | null stupid_theta = return ()
787   | otherwise         = instStupidTheta origin inst_theta
788   where
789     origin = OccurrenceOf (dataConName data_con)
790         -- The origin should always report "occurrence of C"
791         -- even when C occurs in a pattern
792     stupid_theta = dataConStupidTheta data_con
793     tenv = zipTopTvSubst (dataConUnivTyVars data_con) inst_tys
794     inst_theta = substTheta tenv stupid_theta
795 \end{code}
796
797 Note [Arrows and patterns]
798 ~~~~~~~~~~~~~~~~~~~~~~~~~~
799 (Oct 07) Arrow noation has the odd property that it involves "holes in the scope". 
800 For example:
801   expr :: Arrow a => a () Int
802   expr = proc (y,z) -> do
803           x <- term -< y
804           expr' -< x
805
806 Here the 'proc (y,z)' binding scopes over the arrow tails but not the
807 arrow body (e.g 'term').  As things stand (bogusly) all the
808 constraints from the proc body are gathered together, so constraints
809 from 'term' will be seen by the tcPat for (y,z).  But we must *not*
810 bind constraints from 'term' here, becuase the desugarer will not make
811 these bindings scope over 'term'.
812
813 The Right Thing is not to confuse these constraints together. But for
814 now the Easy Thing is to ensure that we do not have existential or
815 GADT constraints in a 'proc', and to short-cut the constraint
816 simplification for such vanilla patterns so that it binds no
817 constraints. Hence the 'fast path' in tcConPat; but it's also a good
818 plan for ordinary vanilla patterns to bypass the constraint
819 simplification step.
820
821
822 %************************************************************************
823 %*                                                                      *
824                 Type refinement
825 %*                                                                      *
826 %************************************************************************
827
828 \begin{code}
829 refineAlt :: DataCon            -- For tracing only
830           -> PatState 
831           -> [TcTyVar]          -- Existentials
832           -> [CoVar]            -- Equational constraints
833           -> BoxySigmaType      -- Pattern type
834           -> TcM PatState
835
836 refineAlt con pstate ex_tvs [] pat_ty
837   | null $ dataConEqTheta con
838   = return pstate       -- Common case: no equational constraints
839
840 refineAlt con pstate ex_tvs co_vars pat_ty
841   = do  { opt_gadt <- doptM Opt_GADTs   -- No type-refinement unless GADTs are on
842         ; if (not opt_gadt) then return pstate
843           else do 
844
845         { checkTc (isRigidTy pat_ty) (nonRigidMatch con)
846         -- We are matching against a GADT constructor with non-trivial
847         -- constraints, but pattern type is wobbly.  For now we fail.
848         -- We can make sense of this, however:
849         -- Suppose MkT :: forall a b. (a:=:[b]) => b -> T a
850         --      (\x -> case x of { MkT v -> v })
851         -- We can infer that x must have type T [c], for some wobbly 'c'
852         -- and translate to
853         --      (\(x::T [c]) -> case x of
854         --                        MkT b (g::([c]:=:[b])) (v::b) -> v `cast` sym g
855         -- To implement this, we'd first instantiate the equational
856         -- constraints with *wobbly* type variables for the existentials;
857         -- then unify these constraints to make pat_ty the right shape;
858         -- then proceed exactly as in the rigid case
859
860                 -- In the rigid case, we perform type refinement
861         ; case gadtRefine (pat_reft pstate) ex_tvs co_vars of {
862             Failed msg     -> failWithTc (inaccessibleAlt msg) ;
863             Succeeded reft -> do { traceTc trace_msg
864                                  ; return (pstate { pat_reft = reft, pat_eqs = (pat_eqs pstate || not (null $ dataConEqTheta con)) }) }
865                     -- DO NOT refine the envt right away, because we 
866                     -- might be inside a lazy pattern.  Instead, refine pstate
867                 where
868                     
869                     trace_msg = text "refineAlt:match" <+> 
870                                 vcat [ ppr con <+> ppr ex_tvs,
871                                        ppr [(v, tyVarKind v) | v <- co_vars],
872                                        ppr reft]
873         } } }
874 \end{code}
875
876
877 %************************************************************************
878 %*                                                                      *
879                 Overloaded literals
880 %*                                                                      *
881 %************************************************************************
882
883 In tcOverloadedLit we convert directly to an Int or Integer if we
884 know that's what we want.  This may save some time, by not
885 temporarily generating overloaded literals, but it won't catch all
886 cases (the rest are caught in lookupInst).
887
888 \begin{code}
889 tcOverloadedLit :: InstOrigin
890                  -> HsOverLit Name
891                  -> BoxyRhoType
892                  -> TcM (HsOverLit TcId)
893 tcOverloadedLit orig lit@(HsIntegral i fi _) res_ty
894   | not (fi `isHsVar` fromIntegerName)  -- Do not generate a LitInst for rebindable syntax.  
895         -- Reason: If we do, tcSimplify will call lookupInst, which
896         --         will call tcSyntaxName, which does unification, 
897         --         which tcSimplify doesn't like
898         -- ToDo: noLoc sadness
899   = do  { integer_ty <- tcMetaTy integerTyConName
900         ; fi' <- tcSyntaxOp orig fi (mkFunTy integer_ty res_ty)
901         ; return (HsIntegral i (HsApp (noLoc fi') (nlHsLit (HsInteger i integer_ty))) res_ty) }
902
903   | Just expr <- shortCutIntLit i res_ty 
904   = return (HsIntegral i expr res_ty)
905
906   | otherwise
907   = do  { expr <- newLitInst orig lit res_ty
908         ; return (HsIntegral i expr res_ty) }
909
910 tcOverloadedLit orig lit@(HsFractional r fr _) res_ty
911   | not (fr `isHsVar` fromRationalName) -- c.f. HsIntegral case
912   = do  { rat_ty <- tcMetaTy rationalTyConName
913         ; fr' <- tcSyntaxOp orig fr (mkFunTy rat_ty res_ty)
914                 -- Overloaded literals must have liftedTypeKind, because
915                 -- we're instantiating an overloaded function here,
916                 -- whereas res_ty might be openTypeKind. This was a bug in 6.2.2
917                 -- However this'll be picked up by tcSyntaxOp if necessary
918         ; return (HsFractional r (HsApp (noLoc fr') (nlHsLit (HsRat r rat_ty))) res_ty) }
919
920   | Just expr <- shortCutFracLit r res_ty 
921   = return (HsFractional r expr res_ty)
922
923   | otherwise
924   = do  { expr <- newLitInst orig lit res_ty
925         ; return (HsFractional r expr res_ty) }
926
927 tcOverloadedLit orig lit@(HsIsString s fr _) res_ty
928   | not (fr `isHsVar` fromStringName)   -- c.f. HsIntegral case
929   = do  { str_ty <- tcMetaTy stringTyConName
930         ; fr' <- tcSyntaxOp orig fr (mkFunTy str_ty res_ty)
931         ; return (HsIsString s (HsApp (noLoc fr') (nlHsLit (HsString s))) res_ty) }
932
933   | Just expr <- shortCutStringLit s res_ty 
934   = return (HsIsString s expr res_ty)
935
936   | otherwise
937   = do  { expr <- newLitInst orig lit res_ty
938         ; return (HsIsString s expr res_ty) }
939
940 newLitInst :: InstOrigin -> HsOverLit Name -> BoxyRhoType -> TcM (HsExpr TcId)
941 newLitInst orig lit res_ty      -- Make a LitInst
942   = do  { loc <- getInstLoc orig
943         ; res_tau <- zapToMonotype res_ty
944         ; new_uniq <- newUnique
945         ; let   lit_nm   = mkSystemVarName new_uniq FSLIT("lit")
946                 lit_inst = LitInst {tci_name = lit_nm, tci_lit = lit, 
947                                     tci_ty = res_tau, tci_loc = loc}
948         ; extendLIE lit_inst
949         ; return (HsVar (instToId lit_inst)) }
950 \end{code}
951
952
953 %************************************************************************
954 %*                                                                      *
955                 Note [Pattern coercions]
956 %*                                                                      *
957 %************************************************************************
958
959 In principle, these program would be reasonable:
960         
961         f :: (forall a. a->a) -> Int
962         f (x :: Int->Int) = x 3
963
964         g :: (forall a. [a]) -> Bool
965         g [] = True
966
967 In both cases, the function type signature restricts what arguments can be passed
968 in a call (to polymorphic ones).  The pattern type signature then instantiates this
969 type.  For example, in the first case,  (forall a. a->a) <= Int -> Int, and we
970 generate the translated term
971         f = \x' :: (forall a. a->a).  let x = x' Int in x 3
972
973 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
974 And it requires a significant amount of code to implement, becuase we need to decorate
975 the translated pattern with coercion functions (generated from the subsumption check 
976 by tcSub).  
977
978 So for now I'm just insisting on type *equality* in patterns.  No subsumption. 
979
980 Old notes about desugaring, at a time when pattern coercions were handled:
981
982 A SigPat is a type coercion and must be handled one at at time.  We can't
983 combine them unless the type of the pattern inside is identical, and we don't
984 bother to check for that.  For example:
985
986         data T = T1 Int | T2 Bool
987         f :: (forall a. a -> a) -> T -> t
988         f (g::Int->Int)   (T1 i) = T1 (g i)
989         f (g::Bool->Bool) (T2 b) = T2 (g b)
990
991 We desugar this as follows:
992
993         f = \ g::(forall a. a->a) t::T ->
994             let gi = g Int
995             in case t of { T1 i -> T1 (gi i)
996                            other ->
997             let gb = g Bool
998             in case t of { T2 b -> T2 (gb b)
999                            other -> fail }}
1000
1001 Note that we do not treat the first column of patterns as a
1002 column of variables, because the coerced variables (gi, gb)
1003 would be of different types.  So we get rather grotty code.
1004 But I don't think this is a common case, and if it was we could
1005 doubtless improve it.
1006
1007 Meanwhile, the strategy is:
1008         * treat each SigPat coercion (always non-identity coercions)
1009                 as a separate block
1010         * deal with the stuff inside, and then wrap a binding round
1011                 the result to bind the new variable (gi, gb, etc)
1012
1013
1014 %************************************************************************
1015 %*                                                                      *
1016 \subsection{Errors and contexts}
1017 %*                                                                      *
1018 %************************************************************************
1019
1020 \begin{code}
1021 patCtxt :: Pat Name -> Maybe Message    -- Not all patterns are worth pushing a context
1022 patCtxt (VarPat _)  = Nothing
1023 patCtxt (ParPat _)  = Nothing
1024 patCtxt (AsPat _ _) = Nothing
1025 patCtxt pat         = Just (hang (ptext SLIT("In the pattern:")) 
1026                                4 (ppr pat))
1027
1028 -----------------------------------------------
1029
1030 existentialExplode pat
1031   = hang (vcat [text "My brain just exploded.",
1032                 text "I can't handle pattern bindings for existentially-quantified constructors.",
1033                 text "Instead, use a case-expression, or do-notation, to unpack the constructor.",
1034                 text "In the binding group for"])
1035         4 (ppr pat)
1036
1037 sigPatCtxt pats bound_tvs pat_tys body_ty tidy_env 
1038   = do  { pat_tys' <- mapM zonkTcType pat_tys
1039         ; body_ty' <- zonkTcType body_ty
1040         ; let (env1,  tidy_tys)    = tidyOpenTypes tidy_env (map idType show_ids)
1041               (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
1042               (env3, tidy_body_ty) = tidyOpenType  env2 body_ty'
1043         ; return (env3,
1044                  sep [ptext SLIT("When checking an existential match that binds"),
1045                       nest 4 (vcat (zipWith ppr_id show_ids tidy_tys)),
1046                       ptext SLIT("The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
1047                       ptext SLIT("The body has type:") <+> ppr tidy_body_ty
1048                 ]) }
1049   where
1050     bound_ids = collectPatsBinders pats
1051     show_ids = filter is_interesting bound_ids
1052     is_interesting id = any (`elemVarSet` varTypeTyVars id) bound_tvs
1053
1054     ppr_id id ty = ppr id <+> dcolon <+> ppr ty
1055         -- Don't zonk the types so we get the separate, un-unified versions
1056
1057 badFieldCon :: DataCon -> Name -> SDoc
1058 badFieldCon con field
1059   = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
1060           ptext SLIT("does not have field"), quotes (ppr field)]
1061
1062 polyPatSig :: TcType -> SDoc
1063 polyPatSig sig_ty
1064   = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
1065        2 (ppr sig_ty)
1066
1067 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
1068
1069 existentialProcPat :: DataCon -> SDoc
1070 existentialProcPat con
1071   = hang (ptext SLIT("Illegal constructor") <+> quotes (ppr con) <+> ptext SLIT("in a 'proc' pattern"))
1072        2 (ptext SLIT("Proc patterns cannot use existentials or GADTs"))
1073
1074 lazyPatErr pat tvs
1075   = failWithTc $
1076     hang (ptext SLIT("A lazy (~) pattern cannot bind existential type variables"))
1077        2 (vcat (map pprSkolTvBinding tvs))
1078
1079 nonRigidMatch con
1080   =  hang (ptext SLIT("GADT pattern match in non-rigid context for") <+> quotes (ppr con))
1081         2 (ptext SLIT("Tell GHC HQ if you'd like this to unify the context"))
1082
1083 nonRigidResult res_ty
1084   =  hang (ptext SLIT("GADT pattern match with non-rigid result type") <+> quotes (ppr res_ty))
1085         2 (ptext SLIT("Tell GHC HQ if you'd like this to unify the context"))
1086
1087 inaccessibleAlt msg
1088   = hang (ptext SLIT("Inaccessible case alternative:")) 2 msg
1089 \end{code}