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