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