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