Tiny refactor
[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         ; unless (null pat_tvs) $ lazyPatErr lpat pat_tvs
369
370         -- Check that the pattern has a lifted type
371         ; pat_tv <- newBoxyTyVar liftedTypeKind
372         ; boxyUnify pat_ty (mkTyVarTy pat_tv)
373
374         ; return (LazyPat pat', [], res) }
375
376 tc_pat _ p@(QuasiQuotePat _) _ _
377   = pprPanic "Should never see QuasiQuotePat in type checker" (ppr p)
378
379 tc_pat pstate (WildPat _) pat_ty thing_inside
380   = do  { pat_ty' <- unBoxWildCardType pat_ty   -- Make sure it's filled in with monotypes
381         ; res <- thing_inside pstate
382         ; return (WildPat pat_ty', [], res) }
383
384 tc_pat pstate (AsPat (L nm_loc name) pat) pat_ty thing_inside
385   = do  { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
386         ; (pat', tvs, res) <- tcExtendIdEnv1 name bndr_id $
387                               tc_lpat pat (idType bndr_id) pstate thing_inside
388             -- NB: if we do inference on:
389             --          \ (y@(x::forall a. a->a)) = e
390             -- we'll fail.  The as-pattern infers a monotype for 'y', which then
391             -- fails to unify with the polymorphic type for 'x'.  This could 
392             -- perhaps be fixed, but only with a bit more work.
393             --
394             -- If you fix it, don't forget the bindInstsOfPatIds!
395         ; return (AsPat (L nm_loc bndr_id) pat', tvs, res) }
396
397 tc_pat pstate (orig@(ViewPat expr pat _)) overall_pat_ty thing_inside 
398   = do  { -- morally, expr must have type
399          -- `forall a1...aN. OPT' -> B` 
400          -- where overall_pat_ty is an instance of OPT'.
401          -- Here, we infer a rho type for it,
402          -- which replaces the leading foralls and constraints
403          -- with fresh unification variables.
404          (expr',expr'_inferred) <- tcInferRho expr
405          -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
406        ; let expr'_expected = \ pat_ty -> (mkFunTy overall_pat_ty pat_ty)
407          -- tcSubExp: expected first, offered second
408          -- returns coercion
409          -- 
410          -- NOTE: this forces pat_ty to be a monotype (because we use a unification 
411          -- variable to find it).  this means that in an example like
412          -- (view -> f)    where view :: _ -> forall b. b
413          -- we will only be able to use view at one instantation in the
414          -- rest of the view
415         ; (expr_coerc, pat_ty) <- tcInfer $ \ pat_ty -> 
416                 tcSubExp ViewPatOrigin (expr'_expected pat_ty) expr'_inferred
417
418          -- pattern must have pat_ty
419        ; (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
420          -- this should get zonked later on, but we unBox it here
421          -- so that we do the same checks as above
422         ; annotation_ty <- unBoxViewPatType overall_pat_ty orig        
423         ; return (ViewPat (mkLHsWrap expr_coerc expr') pat' annotation_ty, tvs, res) }
424
425 -- Type signatures in patterns
426 -- See Note [Pattern coercions] below
427 tc_pat pstate (SigPatIn pat sig_ty) pat_ty thing_inside
428   = do  { (inner_ty, tv_binds, coi) <- tcPatSig (patSigCtxt pstate) sig_ty 
429                                                                     pat_ty
430         ; unless (isIdentityCoI coi) $ 
431             failWithTc (badSigPat pat_ty)
432         ; (pat', tvs, res) <- tcExtendTyVarEnv2 tv_binds $
433                               tc_lpat pat inner_ty pstate thing_inside
434         ; return (SigPatOut pat' inner_ty, tvs, res) }
435
436 tc_pat _ pat@(TypePat _) _ _
437   = failWithTc (badTypePat pat)
438
439 ------------------------
440 -- Lists, tuples, arrays
441 tc_pat pstate (ListPat pats _) pat_ty thing_inside
442   = do  { (elt_ty, coi) <- boxySplitListTy pat_ty
443         ; let scoi = mkSymCoI coi
444         ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
445                                                 pats pstate thing_inside
446         ; return (mkCoPatCoI scoi (ListPat pats' elt_ty) pat_ty, pats_tvs, res) 
447         }
448
449 tc_pat pstate (PArrPat pats _) pat_ty thing_inside
450   = do  { (elt_ty, coi) <- boxySplitPArrTy pat_ty
451         ; let scoi = mkSymCoI coi
452         ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
453                                                 pats pstate thing_inside 
454         ; when (null pats) (zapToMonotype pat_ty >> return ())  -- c.f. ExplicitPArr in TcExpr
455         ; return (mkCoPatCoI scoi (PArrPat pats' elt_ty) pat_ty, pats_tvs, res)
456         }
457
458 tc_pat pstate (TuplePat pats boxity _) pat_ty thing_inside
459   = do  { let tc = tupleTyCon boxity (length pats)
460         ; (arg_tys, coi) <- boxySplitTyConApp tc pat_ty
461         ; let scoi = mkSymCoI coi
462         ; (pats', pats_tvs, res) <- tcMultiple tc_lpat_pr (pats `zip` arg_tys)
463                                                pstate thing_inside
464
465         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
466         -- so that we can experiment with lazy tuple-matching.
467         -- This is a pretty odd place to make the switch, but
468         -- it was easy to do.
469         ; let pat_ty'          = mkTyConApp tc arg_tys
470                                      -- pat_ty /= pat_ty iff coi /= IdCo
471               unmangled_result = TuplePat pats' boxity pat_ty'
472               possibly_mangled_result
473                 | opt_IrrefutableTuples && 
474                   isBoxed boxity            = LazyPat (noLoc unmangled_result)
475                 | otherwise                 = unmangled_result
476
477         ; ASSERT( length arg_tys == length pats )      -- Syntactically enforced
478           return (mkCoPatCoI scoi possibly_mangled_result pat_ty, pats_tvs, res)
479         }
480
481 ------------------------
482 -- Data constructors
483 tc_pat pstate (ConPatIn (L con_span con_name) arg_pats) pat_ty thing_inside
484   = do  { data_con <- tcLookupDataCon con_name
485         ; let tycon = dataConTyCon data_con
486         ; tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside }
487
488 ------------------------
489 -- Literal patterns
490 tc_pat pstate (LitPat simple_lit) pat_ty thing_inside
491   = do  { let lit_ty = hsLitType simple_lit
492         ; coi <- boxyUnify lit_ty pat_ty
493                         -- coi is of kind: lit_ty ~ pat_ty
494         ; res <- thing_inside pstate
495                         -- pattern coercions have to
496                         -- be of kind: pat_ty ~ lit_ty
497                         -- hence, sym coi
498         ; return (mkCoPatCoI (mkSymCoI coi) (LitPat simple_lit) pat_ty, 
499                    [], res) }
500
501 ------------------------
502 -- Overloaded patterns: n, and n+k
503 tc_pat pstate (NPat over_lit mb_neg eq) pat_ty thing_inside
504   = do  { let orig = LiteralOrigin over_lit
505         ; lit'    <- tcOverloadedLit orig over_lit pat_ty
506         ; eq'     <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
507         ; mb_neg' <- case mb_neg of
508                         Nothing  -> return Nothing      -- Positive literal
509                         Just neg ->     -- Negative literal
510                                         -- The 'negate' is re-mappable syntax
511                             do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
512                                ; return (Just neg') }
513         ; res <- thing_inside pstate
514         ; return (NPat lit' mb_neg' eq', [], res) }
515
516 tc_pat pstate (NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
517   = do  { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
518         ; let pat_ty' = idType bndr_id
519               orig    = LiteralOrigin lit
520         ; lit' <- tcOverloadedLit orig lit pat_ty'
521
522         -- The '>=' and '-' parts are re-mappable syntax
523         ; ge'    <- tcSyntaxOp orig ge    (mkFunTys [pat_ty', pat_ty'] boolTy)
524         ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
525
526         -- The Report says that n+k patterns must be in Integral
527         -- We may not want this when using re-mappable syntax, though (ToDo?)
528         ; icls <- tcLookupClass integralClassName
529         ; instStupidTheta orig [mkClassPred icls [pat_ty']]     
530     
531         ; res <- tcExtendIdEnv1 name bndr_id (thing_inside pstate)
532         ; return (NPlusKPat (L nm_loc bndr_id) lit' ge' minus', [], res) }
533
534 tc_pat _ _other_pat _ _ = panic "tc_pat"        -- ConPatOut, SigPatOut, VarPatOut
535 \end{code}
536
537
538 %************************************************************************
539 %*                                                                      *
540         Most of the work for constructors is here
541         (the rest is in the ConPatIn case of tc_pat)
542 %*                                                                      *
543 %************************************************************************
544
545 [Pattern matching indexed data types]
546 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
547 Consider the following declarations:
548
549   data family Map k :: * -> *
550   data instance Map (a, b) v = MapPair (Map a (Pair b v))
551
552 and a case expression
553
554   case x :: Map (Int, c) w of MapPair m -> ...
555
556 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
557 worker/wrapper types for MapPair are
558
559   $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
560   $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
561
562 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
563 :R123Map, which means the straight use of boxySplitTyConApp would give a type
564 error.  Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
565 boxySplitTyConApp with the family tycon Map instead, which gives us the family
566 type list {(Int, c), w}.  To get the correct split for :R123Map, we need to
567 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
568 (provided by tyConFamInst_maybe together with the family tycon).  This
569 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
570 the split arguments for the representation tycon :R123Map as {Int, c, w}
571
572 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion 
573
574   Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
575
576 moving between representation and family type into account.  To produce type
577 correct Core, this coercion needs to be used to case the type of the scrutinee
578 from the family to the representation type.  This is achieved by
579 unwrapFamInstScrutinee using a CoPat around the result pattern.
580
581 Now it might appear seem as if we could have used the previous GADT type
582 refinement infrastructure of refineAlt and friends instead of the explicit
583 unification and CoPat generation.  However, that would be wrong.  Why?  The
584 whole point of GADT refinement is that the refinement is local to the case
585 alternative.  In contrast, the substitution generated by the unification of
586 the family type list and instance types needs to be propagated to the outside.
587 Imagine that in the above example, the type of the scrutinee would have been
588 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
589 substitution [x -> (a, b), v -> w].  In contrast to GADT matching, the
590 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
591 alternatives of the case expression, whereas in the GADT case it might vary
592 between alternatives.
593
594 RIP GADT refinement: refinements have been replaced by the use of explicit
595 equality constraints that are used in conjunction with implication constraints
596 to express the local scope of GADT refinements.
597
598 \begin{code}
599 --      Running example:
600 -- MkT :: forall a b c. (a~[b]) => b -> c -> T a
601 --       with scrutinee of type (T ty)
602
603 tcConPat :: PatState -> SrcSpan -> DataCon -> TyCon 
604          -> BoxySigmaType       -- Type of the pattern
605          -> HsConPatDetails Name -> (PatState -> TcM a)
606          -> TcM (Pat TcId, [TcTyVar], a)
607 tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside
608   = do  { let (univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _)
609                 = dataConFullSig data_con
610               skol_info  = PatSkol data_con
611               origin     = SigOrigin skol_info
612               full_theta = eq_theta ++ dict_theta
613
614           -- Instantiate the constructor type variables [a->ty]
615           -- This may involve doing a family-instance coercion, and building a
616           -- wrapper 
617         ; (ctxt_res_tys, coi, unwrap_ty) <- boxySplitTyConAppWithFamily tycon 
618                                                                         pat_ty
619         ; let sym_coi = mkSymCoI coi  -- boxy split coercion oriented wrongly
620               pat_ty' = mkTyConApp tycon ctxt_res_tys
621                                       -- pat_ty' /= pat_ty iff coi /= IdCo
622               
623               wrap_res_pat res_pat = mkCoPatCoI sym_coi uwScrut pat_ty
624                 where
625                   uwScrut = unwrapFamInstScrutinee tycon ctxt_res_tys
626                                                    unwrap_ty res_pat
627
628           -- Add the stupid theta
629         ; addDataConStupidTheta data_con ctxt_res_tys
630
631         ; ex_tvs' <- tcInstSkolTyVars skol_info ex_tvs  
632                      -- Get location from monad, not from ex_tvs
633
634         ; let tenv     = zipTopTvSubst (univ_tvs ++ ex_tvs)
635                                        (ctxt_res_tys ++ mkTyVarTys ex_tvs')
636               arg_tys' = substTys tenv arg_tys
637
638         ; if null ex_tvs && null eq_spec && null full_theta
639           then do { -- The common case; no class bindings etc 
640                     -- (see Note [Arrows and patterns])
641                     (arg_pats', inner_tvs, res) <- tcConArgs data_con arg_tys' 
642                                                     arg_pats pstate thing_inside
643                   ; let res_pat = ConPatOut { pat_con = L con_span data_con, 
644                                               pat_tvs = [], pat_dicts = [], 
645                                               pat_binds = emptyLHsBinds,
646                                               pat_args = arg_pats', 
647                                               pat_ty = pat_ty' }
648
649                     ; return (wrap_res_pat res_pat, inner_tvs, res) }
650
651           else do   -- The general case, with existential, and local equality 
652                     -- constraints
653         { checkTc (notProcPat (pat_ctxt pstate))
654                   (existentialProcPat data_con)
655                   -- See Note [Arrows and patterns]
656
657           -- Need to test for rigidity if *any* constraints in theta as class
658           -- constraints may have superclass equality constraints.  However,
659           -- we don't want to check for rigidity if we got here only because
660           -- ex_tvs was non-null.
661 --        ; unless (null theta') $
662           -- FIXME: AT THE MOMENT WE CHEAT!  We only perform the rigidity test
663           --   if we explicitly or implicitly (by a GADT def) have 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               no_equalities = not (any isEqPred theta')
670               pstate' | no_equalities = pstate
671                       | otherwise     = pstate { pat_eqs = True }
672
673         ; gadts_on <- doptM Opt_GADTs
674         ; checkTc (no_equalities || gadts_on)
675                   (ptext (sLit "A pattern match on a GADT requires -XGADTs"))
676                   -- Trac #2905 decided that a *pattern-match* of a GADT
677                   -- should require the GADT language flag
678
679         ; unless no_equalities $ checkTc (isRigidTy pat_ty) $
680                                  nonRigidMatch (pat_ctxt pstate) data_con
681
682         ; ((arg_pats', inner_tvs, res), lie_req) <- getLIE $
683                 tcConArgs data_con arg_tys' arg_pats pstate' thing_inside
684
685         ; loc <- getInstLoc origin
686         ; dicts <- newDictBndrs loc theta'
687         ; dict_binds <- tcSimplifyCheckPat loc ex_tvs' dicts lie_req
688
689         ; let res_pat = ConPatOut { pat_con = L con_span data_con, 
690                                     pat_tvs = ex_tvs',
691                                     pat_dicts = map instToVar dicts, 
692                                     pat_binds = dict_binds,
693                                     pat_args = arg_pats', pat_ty = pat_ty' }
694         ; return (wrap_res_pat res_pat, ex_tvs' ++ inner_tvs, res)
695         } }
696   where
697     -- Split against the family tycon if the pattern constructor 
698     -- belongs to a family instance tycon.
699     boxySplitTyConAppWithFamily tycon pat_ty =
700       traceTc traceMsg >>
701       case tyConFamInst_maybe tycon of
702         Nothing                   -> 
703           do { (scrutinee_arg_tys, coi1) <- boxySplitTyConApp tycon pat_ty
704              ; return (scrutinee_arg_tys, coi1, pat_ty)
705              }
706         Just (fam_tycon, instTys) -> 
707           do { (scrutinee_arg_tys, coi1) <- boxySplitTyConApp fam_tycon pat_ty
708              ; (_, freshTvs, subst) <- tcInstTyVars (tyConTyVars tycon)
709              ; let instTys' = substTys subst instTys
710              ; cois <- boxyUnifyList instTys' scrutinee_arg_tys
711              ; let coi = if isIdentityCoI coi1
712                          then  -- pat_ty was splittable
713                                -- => boxyUnifyList had real work to do
714                            mkTyConAppCoI fam_tycon instTys' cois
715                          else  -- pat_ty was not splittable
716                                -- => scrutinee_arg_tys are fresh tvs and
717                                --    boxyUnifyList just instantiated those
718                            coi1
719              ; return (freshTvs, coi, mkTyConApp fam_tycon instTys')
720                                       -- this is /= pat_ty 
721                                       -- iff cois is non-trivial
722              }
723       where
724         traceMsg = sep [ text "tcConPat:boxySplitTyConAppWithFamily:" <+>
725                          ppr tycon <+> ppr pat_ty
726                        , text "  family instance:" <+> 
727                          ppr (tyConFamInst_maybe tycon)
728                        ]
729
730     -- Wraps the pattern (which must be a ConPatOut pattern) in a coercion
731     -- pattern if the tycon is an instance of a family.
732     --
733     unwrapFamInstScrutinee :: TyCon -> [Type] -> Type -> Pat Id -> Pat Id
734     unwrapFamInstScrutinee tycon args unwrap_ty pat
735       | Just co_con <- tyConFamilyCoercion_maybe tycon 
736 --      , not (isNewTyCon tycon)       -- newtypes are explicitly unwrapped by
737                                      -- the desugarer
738           -- NB: We can use CoPat directly, rather than mkCoPat, as we know the
739           --     coercion is not the identity; mkCoPat is inconvenient as it
740           --     wants a located pattern.
741       = CoPat (WpCast $ mkTyConApp co_con args)       -- co fam ty to repr ty
742               (pat {pat_ty = mkTyConApp tycon args})    -- representation type
743               unwrap_ty                                 -- family inst type
744       | otherwise
745       = pat
746
747 tcConArgs :: DataCon -> [TcSigmaType]
748           -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
749
750 tcConArgs data_con arg_tys (PrefixCon arg_pats) pstate thing_inside
751   = do  { checkTc (con_arity == no_of_args)     -- Check correct arity
752                   (arityErr "Constructor" data_con con_arity no_of_args)
753         ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
754         ; (arg_pats', tvs, res) <- tcMultiple tcConArg pats_w_tys
755                                               pstate thing_inside 
756         ; return (PrefixCon arg_pats', tvs, res) }
757   where
758     con_arity  = dataConSourceArity data_con
759     no_of_args = length arg_pats
760
761 tcConArgs data_con arg_tys (InfixCon p1 p2) pstate thing_inside
762   = do  { checkTc (con_arity == 2)      -- Check correct arity
763                   (arityErr "Constructor" data_con con_arity 2)
764         ; let [arg_ty1,arg_ty2] = arg_tys       -- This can't fail after the arity check
765         ; ([p1',p2'], tvs, res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
766                                               pstate thing_inside
767         ; return (InfixCon p1' p2', tvs, res) }
768   where
769     con_arity  = dataConSourceArity data_con
770
771 tcConArgs data_con arg_tys (RecCon (HsRecFields rpats dd)) pstate thing_inside
772   = do  { (rpats', tvs, res) <- tcMultiple tc_field rpats pstate thing_inside
773         ; return (RecCon (HsRecFields rpats' dd), tvs, res) }
774   where
775     tc_field :: Checker (HsRecField FieldLabel (LPat Name)) (HsRecField TcId (LPat TcId))
776     tc_field (HsRecField field_lbl pat pun) pstate thing_inside
777       = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
778            ; (pat', tvs, res) <- tcConArg (pat, pat_ty) pstate thing_inside
779            ; return (HsRecField sel_id pat' pun, tvs, res) }
780
781     find_field_ty :: FieldLabel -> TcM (Id, TcType)
782     find_field_ty field_lbl
783         = case [ty | (f,ty) <- field_tys, f == field_lbl] of
784
785                 -- No matching field; chances are this field label comes from some
786                 -- other record type (or maybe none).  As well as reporting an
787                 -- error we still want to typecheck the pattern, principally to
788                 -- make sure that all the variables it binds are put into the
789                 -- environment, else the type checker crashes later:
790                 --      f (R { foo = (a,b) }) = a+b
791                 -- If foo isn't one of R's fields, we don't want to crash when
792                 -- typechecking the "a+b".
793            [] -> do { addErrTc (badFieldCon data_con field_lbl)
794                     ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
795                     ; return (error "Bogus selector Id", bogus_ty) }
796
797                 -- The normal case, when the field comes from the right constructor
798            (pat_ty : extras) -> 
799                 ASSERT( null extras )
800                 do { sel_id <- tcLookupField field_lbl
801                    ; return (sel_id, pat_ty) }
802
803     field_tys :: [(FieldLabel, TcType)]
804     field_tys = zip (dataConFieldLabels data_con) arg_tys
805         -- Don't use zipEqual! If the constructor isn't really a record, then
806         -- dataConFieldLabels will be empty (and each field in the pattern
807         -- will generate an error below).
808
809 tcConArg :: Checker (LPat Name, BoxySigmaType) (LPat Id)
810 tcConArg (arg_pat, arg_ty) pstate thing_inside
811   = tc_lpat arg_pat arg_ty pstate thing_inside
812 \end{code}
813
814 \begin{code}
815 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
816 -- Instantiate the "stupid theta" of the data con, and throw 
817 -- the constraints into the constraint set
818 addDataConStupidTheta data_con inst_tys
819   | null stupid_theta = return ()
820   | otherwise         = instStupidTheta origin inst_theta
821   where
822     origin = OccurrenceOf (dataConName data_con)
823         -- The origin should always report "occurrence of C"
824         -- even when C occurs in a pattern
825     stupid_theta = dataConStupidTheta data_con
826     tenv = mkTopTvSubst (dataConUnivTyVars data_con `zip` inst_tys)
827          -- NB: inst_tys can be longer than the univ tyvars
828          --     because the constructor might have existentials
829     inst_theta = substTheta tenv stupid_theta
830 \end{code}
831
832 Note [Arrows and patterns]
833 ~~~~~~~~~~~~~~~~~~~~~~~~~~
834 (Oct 07) Arrow noation has the odd property that it involves "holes in the scope". 
835 For example:
836   expr :: Arrow a => a () Int
837   expr = proc (y,z) -> do
838           x <- term -< y
839           expr' -< x
840
841 Here the 'proc (y,z)' binding scopes over the arrow tails but not the
842 arrow body (e.g 'term').  As things stand (bogusly) all the
843 constraints from the proc body are gathered together, so constraints
844 from 'term' will be seen by the tcPat for (y,z).  But we must *not*
845 bind constraints from 'term' here, becuase the desugarer will not make
846 these bindings scope over 'term'.
847
848 The Right Thing is not to confuse these constraints together. But for
849 now the Easy Thing is to ensure that we do not have existential or
850 GADT constraints in a 'proc', and to short-cut the constraint
851 simplification for such vanilla patterns so that it binds no
852 constraints. Hence the 'fast path' in tcConPat; but it's also a good
853 plan for ordinary vanilla patterns to bypass the constraint
854 simplification step.
855
856
857 %************************************************************************
858 %*                                                                      *
859                 Overloaded literals
860 %*                                                                      *
861 %************************************************************************
862
863 In tcOverloadedLit we convert directly to an Int or Integer if we
864 know that's what we want.  This may save some time, by not
865 temporarily generating overloaded literals, but it won't catch all
866 cases (the rest are caught in lookupInst).
867
868 \begin{code}
869 tcOverloadedLit :: InstOrigin
870                  -> HsOverLit Name
871                  -> BoxyRhoType
872                  -> TcM (HsOverLit TcId)
873 tcOverloadedLit orig lit@(OverLit { ol_val = val, ol_rebindable = rebindable
874                                   , ol_witness = meth_name }) res_ty
875   | rebindable
876         -- Do not generate a LitInst for rebindable syntax.  
877         -- Reason: If we do, tcSimplify will call lookupInst, which
878         --         will call tcSyntaxName, which does unification, 
879         --         which tcSimplify doesn't like
880         -- ToDo: noLoc sadness
881   = do  { hs_lit <- mkOverLit val
882         ; let lit_ty = hsLitType hs_lit
883         ; fi' <- tcSyntaxOp orig meth_name (mkFunTy lit_ty res_ty)
884                 -- Overloaded literals must have liftedTypeKind, because
885                 -- we're instantiating an overloaded function here,
886                 -- whereas res_ty might be openTypeKind. This was a bug in 6.2.2
887                 -- However this'll be picked up by tcSyntaxOp if necessary
888         ; let witness = HsApp (noLoc fi') (noLoc (HsLit hs_lit))
889         ; return (lit { ol_witness = witness, ol_type = res_ty }) }
890
891   | Just expr <- shortCutLit val res_ty 
892   = return (lit { ol_witness = expr, ol_type = res_ty })
893
894   | otherwise
895   = do  { loc <- getInstLoc orig
896         ; res_tau <- zapToMonotype res_ty
897         ; new_uniq <- newUnique
898         ; let   lit_nm   = mkSystemVarName new_uniq (fsLit "lit")
899                 lit_inst = LitInst {tci_name = lit_nm, tci_lit = lit, 
900                                     tci_ty = res_tau, tci_loc = loc}
901                 witness = HsVar (instToId lit_inst)
902         ; extendLIE lit_inst
903         ; return (lit { ol_witness = witness, ol_type = res_ty }) }
904 \end{code}
905
906
907 %************************************************************************
908 %*                                                                      *
909                 Note [Pattern coercions]
910 %*                                                                      *
911 %************************************************************************
912
913 In principle, these program would be reasonable:
914         
915         f :: (forall a. a->a) -> Int
916         f (x :: Int->Int) = x 3
917
918         g :: (forall a. [a]) -> Bool
919         g [] = True
920
921 In both cases, the function type signature restricts what arguments can be passed
922 in a call (to polymorphic ones).  The pattern type signature then instantiates this
923 type.  For example, in the first case,  (forall a. a->a) <= Int -> Int, and we
924 generate the translated term
925         f = \x' :: (forall a. a->a).  let x = x' Int in x 3
926
927 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
928 And it requires a significant amount of code to implement, becuase we need to decorate
929 the translated pattern with coercion functions (generated from the subsumption check 
930 by tcSub).  
931
932 So for now I'm just insisting on type *equality* in patterns.  No subsumption. 
933
934 Old notes about desugaring, at a time when pattern coercions were handled:
935
936 A SigPat is a type coercion and must be handled one at at time.  We can't
937 combine them unless the type of the pattern inside is identical, and we don't
938 bother to check for that.  For example:
939
940         data T = T1 Int | T2 Bool
941         f :: (forall a. a -> a) -> T -> t
942         f (g::Int->Int)   (T1 i) = T1 (g i)
943         f (g::Bool->Bool) (T2 b) = T2 (g b)
944
945 We desugar this as follows:
946
947         f = \ g::(forall a. a->a) t::T ->
948             let gi = g Int
949             in case t of { T1 i -> T1 (gi i)
950                            other ->
951             let gb = g Bool
952             in case t of { T2 b -> T2 (gb b)
953                            other -> fail }}
954
955 Note that we do not treat the first column of patterns as a
956 column of variables, because the coerced variables (gi, gb)
957 would be of different types.  So we get rather grotty code.
958 But I don't think this is a common case, and if it was we could
959 doubtless improve it.
960
961 Meanwhile, the strategy is:
962         * treat each SigPat coercion (always non-identity coercions)
963                 as a separate block
964         * deal with the stuff inside, and then wrap a binding round
965                 the result to bind the new variable (gi, gb, etc)
966
967
968 %************************************************************************
969 %*                                                                      *
970 \subsection{Errors and contexts}
971 %*                                                                      *
972 %************************************************************************
973
974 \begin{code}
975 patCtxt :: Pat Name -> Maybe Message    -- Not all patterns are worth pushing a context
976 patCtxt (VarPat _)  = Nothing
977 patCtxt (ParPat _)  = Nothing
978 patCtxt (AsPat _ _) = Nothing
979 patCtxt pat         = Just (hang (ptext (sLit "In the pattern:")) 
980                                4 (ppr pat))
981
982 -----------------------------------------------
983
984 existentialExplode :: LPat Name -> SDoc
985 existentialExplode pat
986   = hang (vcat [text "My brain just exploded.",
987                 text "I can't handle pattern bindings for existential or GADT data constructors.",
988                 text "Instead, use a case-expression, or do-notation, to unpack the constructor.",
989                 text "In the binding group for"])
990         4 (ppr pat)
991
992 sigPatCtxt :: [LPat Var] -> [Var] -> [TcType] -> TcType -> TidyEnv
993            -> TcM (TidyEnv, SDoc)
994 sigPatCtxt pats bound_tvs pat_tys body_ty tidy_env 
995   = do  { pat_tys' <- mapM zonkTcType pat_tys
996         ; body_ty' <- zonkTcType body_ty
997         ; let (env1,  tidy_tys)    = tidyOpenTypes tidy_env (map idType show_ids)
998               (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
999               (env3, tidy_body_ty) = tidyOpenType  env2 body_ty'
1000         ; return (env3,
1001                  sep [ptext (sLit "When checking an existential match that binds"),
1002                       nest 4 (vcat (zipWith ppr_id show_ids tidy_tys)),
1003                       ptext (sLit "The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
1004                       ptext (sLit "The body has type:") <+> ppr tidy_body_ty
1005                 ]) }
1006   where
1007     bound_ids = collectPatsBinders pats
1008     show_ids = filter is_interesting bound_ids
1009     is_interesting id = any (`elemVarSet` varTypeTyVars id) bound_tvs
1010
1011     ppr_id id ty = ppr id <+> dcolon <+> ppr ty
1012         -- Don't zonk the types so we get the separate, un-unified versions
1013
1014 badFieldCon :: DataCon -> Name -> SDoc
1015 badFieldCon con field
1016   = hsep [ptext (sLit "Constructor") <+> quotes (ppr con),
1017           ptext (sLit "does not have field"), quotes (ppr field)]
1018
1019 polyPatSig :: TcType -> SDoc
1020 polyPatSig sig_ty
1021   = hang (ptext (sLit "Illegal polymorphic type signature in pattern:"))
1022        2 (ppr sig_ty)
1023
1024 badSigPat :: TcType -> SDoc
1025 badSigPat pat_ty = ptext (sLit "Pattern signature must exactly match:") <+> 
1026                    ppr pat_ty
1027
1028 badTypePat :: Pat Name -> SDoc
1029 badTypePat pat = ptext (sLit "Illegal type pattern") <+> ppr pat
1030
1031 existentialProcPat :: DataCon -> SDoc
1032 existentialProcPat con
1033   = hang (ptext (sLit "Illegal constructor") <+> quotes (ppr con) <+> ptext (sLit "in a 'proc' pattern"))
1034        2 (ptext (sLit "Proc patterns cannot use existentials or GADTs"))
1035
1036 lazyPatErr :: Pat name -> [TcTyVar] -> TcM ()
1037 lazyPatErr _ tvs
1038   = failWithTc $
1039     hang (ptext (sLit "A lazy (~) pattern cannot match existential or GADT data constructors"))
1040        2 (vcat (map pprSkolTvBinding tvs))
1041
1042 nonRigidMatch :: PatCtxt -> DataCon -> SDoc
1043 nonRigidMatch ctxt con
1044   =  hang (ptext (sLit "GADT pattern match in non-rigid context for") <+> quotes (ppr con))
1045         2 (ptext (sLit "Probable solution: add a type signature for") <+> what ctxt)
1046   where
1047      what (APat (FunRhs f _)) = quotes (ppr f)
1048      what (APat CaseAlt)      = ptext (sLit "the scrutinee of the case expression")
1049      what (APat LambdaExpr )  = ptext (sLit "the lambda expression")
1050      what (APat (StmtCtxt _)) = ptext (sLit "the right hand side of a do/comprehension binding")
1051      what _other              = ptext (sLit "something")
1052
1053 nonRigidResult :: PatCtxt -> Type -> TcM a
1054 nonRigidResult ctxt res_ty
1055   = do  { env0 <- tcInitTidyEnv
1056         ; let (env1, res_ty') = tidyOpenType env0 res_ty
1057               msg = hang (ptext (sLit "GADT pattern match with non-rigid result type")
1058                                 <+> quotes (ppr res_ty'))
1059                          2 (ptext (sLit "Solution: add a type signature for")
1060                                   <+> what ctxt )
1061         ; failWithTcM (env1, msg) }
1062   where
1063      what (APat (FunRhs f _)) = quotes (ppr f)
1064      what (APat CaseAlt)      = ptext (sLit "the entire case expression")
1065      what (APat LambdaExpr)   = ptext (sLit "the lambda exression")
1066      what (APat (StmtCtxt _)) = ptext (sLit "the entire do/comprehension expression")
1067      what _other              = ptext (sLit "something")
1068 \end{code}