Complete the evidence generation for GADTs
[ghc-hetmet.git] / compiler / typecheck / TcPat.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcPat]{Typechecking patterns}
5
6 \begin{code}
7 module TcPat ( tcLetPat, tcLamPat, tcLamPats, tcOverloadedLit,
8                addDataConStupidTheta, badFieldCon, polyPatSig ) where
9
10 #include "HsVersions.h"
11
12 import {-# SOURCE #-}   TcExpr( tcSyntaxOp )
13 import HsSyn            ( Pat(..), LPat, HsConDetails(..), HsLit(..), HsOverLit(..), HsExpr(..),
14                           mkCoPat, idCoercion,
15                           LHsBinds, emptyLHsBinds, isEmptyLHsBinds, 
16                           collectPatsBinders, nlHsLit )
17 import TcHsSyn          ( TcId, hsLitType )
18 import TcRnMonad
19 import Inst             ( InstOrigin(..), shortCutFracLit, shortCutIntLit, 
20                           newDictBndrs, instToId, instStupidTheta, isHsVar
21                         )
22 import Id               ( Id, idType, mkLocalId )
23 import CoreFVs          ( idFreeTyVars )
24 import Name             ( Name, mkSystemVarName )
25 import TcSimplify       ( tcSimplifyCheck, bindInstsOfLocalFuns )
26 import TcEnv            ( newLocalName, tcExtendIdEnv1, tcExtendTyVarEnv2,
27                           tcLookupClass, tcLookupDataCon, refineEnvironment,
28                           tcLookupField, tcMetaTy )
29 import TcMType          ( newFlexiTyVarTy, arityErr, tcInstSkolTyVars, 
30 +                         newCoVars, zonkTcType )
31 import TcType           ( TcType, TcTyVar, TcSigmaType, TcRhoType, BoxyType,
32                           SkolemInfo(PatSkol), 
33                           BoxySigmaType, BoxyRhoType, argTypeKind, typeKind,
34                           pprSkolTvBinding, isRigidTy, tcTyVarsOfTypes, 
35                           zipTopTvSubst, isArgTypeKind, isUnboxedTupleType,
36                           mkTyVarTys, mkClassPred, isOverloadedTy, substEqSpec,
37                           mkFunTy, mkFunTys, tidyOpenType, tidyOpenTypes )
38 import VarSet           ( elemVarSet )
39 import {- Kind parts of -} 
40        Type             ( liftedTypeKind )
41 import TcUnify          ( boxySplitTyConApp, boxySplitListTy, unBox,
42                           zapToMonotype, boxyUnify, checkSigTyVarsWrt,
43                           unifyType )
44 import TcHsType         ( UserTypeCtxt(..), tcPatSig )
45 import TysWiredIn       ( boolTy, parrTyCon, tupleTyCon )
46 import Type             ( substTys, substTheta )
47 import StaticFlags      ( opt_IrrefutableTuples )
48 import TyCon            ( TyCon, FieldLabel )
49 import DataCon          ( DataCon, dataConTyCon, dataConFullSig, dataConName,
50                           dataConFieldLabels, dataConSourceArity, 
51                           dataConStupidTheta, dataConUnivTyVars )
52 import PrelNames        ( integralClassName, fromIntegerName, integerTyConName, 
53                           fromRationalName, rationalTyConName )
54 import BasicTypes       ( isBoxed )
55 import SrcLoc           ( Located(..), SrcSpan, noLoc )
56 import ErrUtils         ( Message )
57 import Util             ( zipEqual )
58 import Maybes           ( MaybeErr(..) )
59 import Outputable
60 import FastString
61 \end{code}
62
63
64 %************************************************************************
65 %*                                                                      *
66                 External interface
67 %*                                                                      *
68 %************************************************************************
69
70 \begin{code}
71 tcLetPat :: (Name -> Maybe TcRhoType)
72          -> LPat Name -> BoxySigmaType 
73          -> TcM a
74          -> TcM (LPat TcId, a)
75 tcLetPat sig_fn pat pat_ty thing_inside
76   = do  { let init_state = PS { pat_ctxt = LetPat sig_fn, 
77                                 pat_reft = emptyRefinement }
78         ; (pat', ex_tvs, res) <- tc_lpat pat pat_ty init_state (\ _ -> thing_inside)
79
80         -- Don't know how to deal with pattern-bound existentials yet
81         ; checkTc (null ex_tvs) (existentialExplode pat)
82
83         ; return (pat', res) }
84
85 -----------------
86 tcLamPats :: [LPat Name]                                -- Patterns,
87           -> [BoxySigmaType]                            --   and their types
88           -> BoxyRhoType                                -- Result type,
89           -> ((Refinement, BoxyRhoType) -> TcM a)       --   and the checker for the body
90           -> TcM ([LPat TcId], a)
91
92 -- This is the externally-callable wrapper function
93 -- Typecheck the patterns, extend the environment to bind the variables,
94 -- do the thing inside, use any existentially-bound dictionaries to 
95 -- discharge parts of the returning LIE, and deal with pattern type
96 -- signatures
97
98 --   1. Initialise the PatState
99 --   2. Check the patterns
100 --   3. Apply the refinement to the environment and result type
101 --   4. Check the body
102 --   5. Check that no existentials escape
103
104 tcLamPats pats tys res_ty thing_inside
105   = tc_lam_pats (zipEqual "tcLamPats" pats tys)
106                 (emptyRefinement, res_ty) thing_inside
107
108 tcLamPat :: LPat Name -> BoxySigmaType 
109          -> (Refinement,BoxyRhoType)            -- Result type
110          -> ((Refinement,BoxyRhoType) -> TcM a) -- Checker for body, given its result type
111          -> TcM (LPat TcId, a)
112 tcLamPat pat pat_ty res_ty thing_inside
113   = do  { ([pat'],thing) <- tc_lam_pats [(pat, pat_ty)] res_ty thing_inside
114         ; return (pat', thing) }
115
116 -----------------
117 tc_lam_pats :: [(LPat Name,BoxySigmaType)]
118             -> (Refinement,BoxyRhoType)                 -- Result type
119             -> ((Refinement,BoxyRhoType) -> TcM a)      -- Checker for body, given its result type
120             -> TcM ([LPat TcId], a)
121 tc_lam_pats pat_ty_prs (reft, res_ty) thing_inside 
122   =  do { let init_state = PS { pat_ctxt = LamPat, pat_reft = reft }
123
124         ; (pats', ex_tvs, res) <- tcMultiple tc_lpat_pr pat_ty_prs init_state $ \ pstate' ->
125                                   refineEnvironment (pat_reft pstate') $
126                                   thing_inside (pat_reft pstate', res_ty)
127
128         ; let tys = map snd pat_ty_prs
129         ; tcCheckExistentialPat pats' ex_tvs tys res_ty
130
131         ; returnM (pats', res) }
132
133
134 -----------------
135 tcCheckExistentialPat :: [LPat TcId]            -- Patterns (just for error message)
136                       -> [TcTyVar]              -- Existentially quantified tyvars bound by pattern
137                       -> [BoxySigmaType]        -- Types of the patterns
138                       -> BoxyRhoType            -- Type of the body of the match
139                                                 -- Tyvars in either of these must not escape
140                       -> TcM ()
141 -- NB: we *must* pass "pats_tys" not just "body_ty" to tcCheckExistentialPat
142 -- For example, we must reject this program:
143 --      data C = forall a. C (a -> Int) 
144 --      f (C g) x = g x
145 -- Here, result_ty will be simply Int, but expected_ty is (C -> a -> Int).
146
147 tcCheckExistentialPat pats [] pat_tys body_ty
148   = return ()   -- Short cut for case when there are no existentials
149
150 tcCheckExistentialPat pats ex_tvs pat_tys body_ty
151   = addErrCtxtM (sigPatCtxt (collectPatsBinders pats) ex_tvs pat_tys body_ty)   $
152     checkSigTyVarsWrt (tcTyVarsOfTypes (body_ty:pat_tys)) ex_tvs
153
154 data PatState = PS {
155         pat_ctxt :: PatCtxt,
156         pat_reft :: Refinement  -- Binds rigid TcTyVars to their refinements
157   }
158
159 data PatCtxt 
160   = LamPat 
161   | LetPat (Name -> Maybe TcRhoType)    -- Used for let(rec) bindings
162
163 patSigCtxt :: PatState -> UserTypeCtxt
164 patSigCtxt (PS { pat_ctxt = LetPat _ }) = BindPatSigCtxt
165 patSigCtxt other                        = LamPatSigCtxt
166 \end{code}
167
168
169
170 %************************************************************************
171 %*                                                                      *
172                 Binders
173 %*                                                                      *
174 %************************************************************************
175
176 \begin{code}
177 tcPatBndr :: PatState -> Name -> BoxySigmaType -> TcM TcId
178 tcPatBndr (PS { pat_ctxt = LamPat }) bndr_name pat_ty
179   = do  { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
180                 -- We have an undecorated binder, so we do rule ABS1,
181                 -- by unboxing the boxy type, forcing any un-filled-in
182                 -- boxes to become monotypes
183                 -- NB that pat_ty' can still be a polytype:
184                 --      data T = MkT (forall a. a->a)
185                 --      f t = case t of { MkT g -> ... }
186                 -- Here, the 'g' must get type (forall a. a->a) from the
187                 -- MkT context
188         ; return (mkLocalId bndr_name pat_ty') }
189
190 tcPatBndr (PS { pat_ctxt = LetPat lookup_sig }) bndr_name pat_ty
191   | Just mono_ty <- lookup_sig bndr_name
192   = do  { mono_name <- newLocalName bndr_name
193         ; boxyUnify mono_ty pat_ty
194         ; return (mkLocalId mono_name mono_ty) }
195
196   | otherwise
197   = do  { pat_ty' <- unBoxPatBndrType pat_ty bndr_name
198         ; mono_name <- newLocalName bndr_name
199         ; return (mkLocalId mono_name pat_ty') }
200
201
202 -------------------
203 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, LHsBinds TcId)
204 bindInstsOfPatId id thing_inside
205   | not (isOverloadedTy (idType id))
206   = do { res <- thing_inside; return (res, emptyLHsBinds) }
207   | otherwise
208   = do  { (res, lie) <- getLIE thing_inside
209         ; binds <- bindInstsOfLocalFuns lie [id]
210         ; return (res, binds) }
211
212 -------------------
213 unBoxPatBndrType  ty name = unBoxArgType ty (ptext SLIT("The variable") <+> quotes (ppr name))
214 unBoxWildCardType ty      = unBoxArgType ty (ptext SLIT("A wild-card pattern"))
215
216 unBoxArgType :: BoxyType -> SDoc -> TcM TcType
217 -- In addition to calling unbox, unBoxArgType ensures that the type is of ArgTypeKind; 
218 -- that is, it can't be an unboxed tuple.  For example, 
219 --      case (f x) of r -> ...
220 -- should fail if 'f' returns an unboxed tuple.
221 unBoxArgType ty pp_this
222   = do  { ty' <- unBox ty       -- Returns a zonked type
223
224         -- Neither conditional is strictly necesssary (the unify alone will do)
225         -- but they improve error messages, and allocate fewer tyvars
226         ; if isUnboxedTupleType ty' then
227                 failWithTc msg
228           else if isArgTypeKind (typeKind ty') then
229                 return ty'
230           else do       -- OpenTypeKind, so constrain it
231         { ty2 <- newFlexiTyVarTy argTypeKind
232         ; unifyType ty' ty2
233         ; return ty' }}
234   where
235     msg = pp_this <+> ptext SLIT("cannot be bound to an unboxed tuple")
236 \end{code}
237
238
239 %************************************************************************
240 %*                                                                      *
241                 The main worker functions
242 %*                                                                      *
243 %************************************************************************
244
245 Note [Nesting]
246 ~~~~~~~~~~~~~~
247 tcPat takes a "thing inside" over which the patter scopes.  This is partly
248 so that tcPat can extend the environment for the thing_inside, but also 
249 so that constraints arising in the thing_inside can be discharged by the
250 pattern.
251
252 This does not work so well for the ErrCtxt carried by the monad: we don't
253 want the error-context for the pattern to scope over the RHS. 
254 Hence the getErrCtxt/setErrCtxt stuff in tc_lpats.
255
256 \begin{code}
257 --------------------
258 type Checker inp out =  forall r.
259                           inp
260                        -> PatState
261                        -> (PatState -> TcM r)
262                        -> TcM (out, [TcTyVar], r)
263
264 tcMultiple :: Checker inp out -> Checker [inp] [out]
265 tcMultiple tc_pat args pstate thing_inside
266   = do  { err_ctxt <- getErrCtxt
267         ; let loop pstate []
268                 = do { res <- thing_inside pstate
269                      ; return ([], [], res) }
270
271               loop pstate (arg:args)
272                 = do { (p', p_tvs, (ps', ps_tvs, res)) 
273                                 <- tc_pat arg pstate $ \ pstate' ->
274                                    setErrCtxt err_ctxt $
275                                    loop pstate' args
276                 -- setErrCtxt: restore context before doing the next pattern
277                 -- See note [Nesting] above
278                                 
279                      ; return (p':ps', p_tvs ++ ps_tvs, res) }
280
281         ; loop pstate args }
282
283 --------------------
284 tc_lpat_pr :: (LPat Name, BoxySigmaType)
285            -> PatState
286            -> (PatState -> TcM a)
287            -> TcM (LPat TcId, [TcTyVar], a)
288 tc_lpat_pr (pat, ty) = tc_lpat pat ty
289
290 tc_lpat :: LPat Name 
291         -> BoxySigmaType
292         -> PatState
293         -> (PatState -> TcM a)
294         -> TcM (LPat TcId, [TcTyVar], a)
295 tc_lpat (L span pat) pat_ty pstate thing_inside
296   = setSrcSpan span               $
297     maybeAddErrCtxt (patCtxt pat) $
298     do  { let (coercion, pat_ty') = refineType (pat_reft pstate) pat_ty
299                 -- Make sure the result type reflects the current refinement
300                 -- We must do this here, so that it correctly ``sees'' all
301                 -- the refinements to the left.  Example:
302                 -- Suppose C :: forall a. T a -> a -> Foo
303                 -- Pattern      C a p1 True
304                 -- So p1 might refine 'a' to True, and the True 
305                 -- pattern had better see it.
306
307         ; (pat', tvs, res) <- tc_pat pstate pat pat_ty' thing_inside
308         ; return (mkCoPat coercion (L span pat') pat_ty, tvs, res) }
309
310 --------------------
311 tc_pat  :: PatState
312         -> Pat Name -> BoxySigmaType    -- Fully refined result type
313         -> (PatState -> TcM a)  -- Thing inside
314         -> TcM (Pat TcId,       -- Translated pattern
315                 [TcTyVar],      -- Existential binders
316                 a)              -- Result of thing inside
317
318 tc_pat pstate (VarPat name) pat_ty thing_inside
319   = do  { id <- tcPatBndr pstate name pat_ty
320         ; (res, binds) <- bindInstsOfPatId id $
321                           tcExtendIdEnv1 name id $
322                           (traceTc (text "binding" <+> ppr name <+> ppr (idType id))
323                            >> thing_inside pstate)
324         ; let pat' | isEmptyLHsBinds binds = VarPat id
325                    | otherwise             = VarPatOut id binds
326         ; return (pat', [], res) }
327
328 tc_pat pstate (ParPat pat) pat_ty thing_inside
329   = do  { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
330         ; return (ParPat pat', tvs, res) }
331
332 tc_pat pstate (BangPat pat) pat_ty thing_inside
333   = do  { (pat', tvs, res) <- tc_lpat pat pat_ty pstate thing_inside
334         ; return (BangPat pat', tvs, res) }
335
336 -- There's a wrinkle with irrefutable patterns, namely that we
337 -- must not propagate type refinement from them.  For example
338 --      data T a where { T1 :: Int -> T Int; ... }
339 --      f :: T a -> Int -> a
340 --      f ~(T1 i) y = y
341 -- It's obviously not sound to refine a to Int in the right
342 -- hand side, because the arugment might not match T1 at all!
343 --
344 -- Nor should a lazy pattern bind any existential type variables
345 -- because they won't be in scope when we do the desugaring
346 tc_pat pstate lpat@(LazyPat pat) pat_ty thing_inside
347   = do  { (pat', pat_tvs, res) <- tc_lpat pat pat_ty pstate $ \ _ ->
348                                   thing_inside pstate
349                                         -- Ignore refined pstate',
350                                         -- revert to pstate
351         -- Check no existentials
352         ; if (null pat_tvs) then return ()
353           else lazyPatErr lpat pat_tvs
354
355         -- Check that the pattern has a lifted type
356         ; pat_tv <- newBoxyTyVar liftedTypeKind
357         ; boxyUnify pat_ty (mkTyVarTy pat_tv)
358
359         ; return (LazyPat pat', [], res) }
360
361 tc_pat pstate (WildPat _) pat_ty thing_inside
362   = do  { pat_ty' <- unBoxWildCardType pat_ty   -- Make sure it's filled in with monotypes
363         ; res <- thing_inside pstate
364         ; return (WildPat pat_ty', [], res) }
365
366 tc_pat pstate (AsPat (L nm_loc name) pat) pat_ty thing_inside
367   = do  { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
368         ; (pat', tvs, res) <- tcExtendIdEnv1 name bndr_id $
369                               tc_lpat pat (idType bndr_id) pstate thing_inside
370             -- NB: if we do inference on:
371             --          \ (y@(x::forall a. a->a)) = e
372             -- we'll fail.  The as-pattern infers a monotype for 'y', which then
373             -- fails to unify with the polymorphic type for 'x'.  This could 
374             -- perhaps be fixed, but only with a bit more work.
375             --
376             -- If you fix it, don't forget the bindInstsOfPatIds!
377         ; return (AsPat (L nm_loc bndr_id) pat', tvs, res) }
378
379 -- Type signatures in patterns
380 -- See Note [Pattern coercions] below
381 tc_pat pstate (SigPatIn pat sig_ty) pat_ty thing_inside
382   = do  { (inner_ty, tv_binds) <- tcPatSig (patSigCtxt pstate) sig_ty pat_ty
383         ; (pat', tvs, res) <- tcExtendTyVarEnv2 tv_binds $
384                               tc_lpat pat inner_ty pstate thing_inside
385         ; return (SigPatOut pat' inner_ty, tvs, res) }
386
387 tc_pat pstate pat@(TypePat ty) pat_ty thing_inside
388   = failWithTc (badTypePat pat)
389
390 ------------------------
391 -- Lists, tuples, arrays
392 tc_pat pstate (ListPat pats _) pat_ty thing_inside
393   = do  { elt_ty <- boxySplitListTy pat_ty
394         ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
395                                                 pats pstate thing_inside
396         ; return (ListPat pats' elt_ty, pats_tvs, res) }
397
398 tc_pat pstate (PArrPat pats _) pat_ty thing_inside
399   = do  { [elt_ty] <- boxySplitTyConApp parrTyCon pat_ty
400         ; (pats', pats_tvs, res) <- tcMultiple (\p -> tc_lpat p elt_ty)
401                                                 pats pstate thing_inside 
402         ; ifM (null pats) (zapToMonotype pat_ty)        -- c.f. ExplicitPArr in TcExpr
403         ; return (PArrPat pats' elt_ty, pats_tvs, res) }
404
405 tc_pat pstate (TuplePat pats boxity _) pat_ty thing_inside
406   = do  { arg_tys <- boxySplitTyConApp (tupleTyCon boxity (length pats)) pat_ty
407         ; (pats', pats_tvs, res) <- tcMultiple tc_lpat_pr (pats `zip` arg_tys)
408                                                pstate thing_inside
409
410         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
411         -- so that we can experiment with lazy tuple-matching.
412         -- This is a pretty odd place to make the switch, but
413         -- it was easy to do.
414         ; let unmangled_result = TuplePat pats' boxity pat_ty
415               possibly_mangled_result
416                 | opt_IrrefutableTuples && isBoxed boxity = LazyPat (noLoc unmangled_result)
417                 | otherwise                               = unmangled_result
418
419         ; ASSERT( length arg_tys == length pats )       -- Syntactically enforced
420           return (possibly_mangled_result, pats_tvs, res) }
421
422 ------------------------
423 -- Data constructors
424 tc_pat pstate pat_in@(ConPatIn (L con_span con_name) arg_pats) pat_ty thing_inside
425   = do  { data_con <- tcLookupDataCon con_name
426         ; let tycon = dataConTyCon data_con
427         ; tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside }
428
429 ------------------------
430 -- Literal patterns
431 tc_pat pstate (LitPat simple_lit) pat_ty thing_inside
432   = do  { boxyUnify (hsLitType simple_lit) pat_ty
433         ; res <- thing_inside pstate
434         ; returnM (LitPat simple_lit, [], res) }
435
436 ------------------------
437 -- Overloaded patterns: n, and n+k
438 tc_pat pstate pat@(NPat over_lit mb_neg eq _) pat_ty thing_inside
439   = do  { let orig = LiteralOrigin over_lit
440         ; lit'    <- tcOverloadedLit orig over_lit pat_ty
441         ; eq'     <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
442         ; mb_neg' <- case mb_neg of
443                         Nothing  -> return Nothing      -- Positive literal
444                         Just neg ->     -- Negative literal
445                                         -- The 'negate' is re-mappable syntax
446                             do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
447                                ; return (Just neg') }
448         ; res <- thing_inside pstate
449         ; returnM (NPat lit' mb_neg' eq' pat_ty, [], res) }
450
451 tc_pat pstate pat@(NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
452   = do  { bndr_id <- setSrcSpan nm_loc (tcPatBndr pstate name pat_ty)
453         ; let pat_ty' = idType bndr_id
454               orig    = LiteralOrigin lit
455         ; lit' <- tcOverloadedLit orig lit pat_ty'
456
457         -- The '>=' and '-' parts are re-mappable syntax
458         ; ge'    <- tcSyntaxOp orig ge    (mkFunTys [pat_ty', pat_ty'] boolTy)
459         ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
460
461         -- The Report says that n+k patterns must be in Integral
462         -- We may not want this when using re-mappable syntax, though (ToDo?)
463         ; icls <- tcLookupClass integralClassName
464         ; instStupidTheta orig [mkClassPred icls [pat_ty']]     
465     
466         ; res <- tcExtendIdEnv1 name bndr_id (thing_inside pstate)
467         ; returnM (NPlusKPat (L nm_loc bndr_id) lit' ge' minus', [], res) }
468
469 tc_pat _ _other_pat _ _ = panic "tc_pat"        -- DictPat, ConPatOut, SigPatOut, VarPatOut
470 \end{code}
471
472
473 %************************************************************************
474 %*                                                                      *
475         Most of the work for constructors is here
476         (the rest is in the ConPatIn case of tc_pat)
477 %*                                                                      *
478 %************************************************************************
479
480 \begin{code}
481 --      Running example:
482 -- MkT :: forall a b c. (a:=:[b]) => b -> c -> T a
483 --       with scrutinee of type (T ty)
484
485 tcConPat :: PatState -> SrcSpan -> DataCon -> TyCon 
486          -> BoxySigmaType       -- Type of the pattern
487          -> HsConDetails Name (LPat Name) -> (PatState -> TcM a)
488          -> TcM (Pat TcId, [TcTyVar], a)
489 tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside
490   = do  { span <- getSrcSpanM   -- Span for the whole pattern
491         ; let (univ_tvs, ex_tvs, eq_spec, theta, arg_tys) = dataConFullSig data_con
492               skol_info = PatSkol data_con span
493               origin    = SigOrigin skol_info
494
495           -- Instantiate the constructor type variables [a->ty]
496         ; ctxt_res_tys <- boxySplitTyConApp tycon pat_ty
497         ; ex_tvs' <- tcInstSkolTyVars skol_info ex_tvs
498         ; let tenv     = zipTopTvSubst (univ_tvs ++ ex_tvs)
499                                       (ctxt_res_tys ++ mkTyVarTys ex_tvs')
500               eq_spec' = substEqSpec tenv eq_spec
501               theta'   = substTheta  tenv theta
502               arg_tys' = substTys    tenv arg_tys
503
504         ; co_vars <- newCoVars eq_spec' -- Make coercion variables
505         ; pstate' <- refineAlt data_con pstate ex_tvs co_vars pat_ty
506
507         ; ((arg_pats', inner_tvs, res), lie_req) <- getLIE $
508                 tcConArgs data_con arg_tys' arg_pats pstate' thing_inside
509
510         ; loc <- getInstLoc origin
511         ; dicts <- newDictBndrs loc theta'
512         ; dict_binds <- tcSimplifyCheck doc ex_tvs' dicts lie_req
513
514         ; addDataConStupidTheta origin data_con ctxt_res_tys
515
516         ; return (ConPatOut { pat_con = L con_span data_con, 
517                               pat_tvs = ex_tvs' ++ co_vars,
518                               pat_dicts = map instToId dicts, pat_binds = dict_binds,
519                               pat_args = arg_pats', pat_ty = pat_ty },
520                   ex_tvs' ++ inner_tvs, res) 
521         }
522   where
523     doc = ptext SLIT("existential context for") <+> quotes (ppr data_con)
524
525 tcConArgs :: DataCon -> [TcSigmaType]
526           -> Checker (HsConDetails Name (LPat Name)) (HsConDetails Id (LPat Id))
527
528 tcConArgs data_con arg_tys (PrefixCon arg_pats) pstate thing_inside
529   = do  { checkTc (con_arity == no_of_args)     -- Check correct arity
530                   (arityErr "Constructor" data_con con_arity no_of_args)
531         ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
532         ; (arg_pats', tvs, res) <- tcMultiple tcConArg pats_w_tys
533                                               pstate thing_inside 
534         ; return (PrefixCon arg_pats', tvs, res) }
535   where
536     con_arity  = dataConSourceArity data_con
537     no_of_args = length arg_pats
538
539 tcConArgs data_con [arg_ty1,arg_ty2] (InfixCon p1 p2) pstate thing_inside
540   = do  { checkTc (con_arity == 2)      -- Check correct arity
541                   (arityErr "Constructor" data_con con_arity 2)
542         ; ([p1',p2'], tvs, res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
543                                               pstate thing_inside
544         ; return (InfixCon p1' p2', tvs, res) }
545   where
546     con_arity  = dataConSourceArity data_con
547
548 tcConArgs data_con arg_tys (RecCon rpats) pstate thing_inside
549   = do  { (rpats', tvs, res) <- tcMultiple tc_field rpats pstate thing_inside
550         ; return (RecCon rpats', tvs, res) }
551   where
552     tc_field :: Checker (Located Name, LPat Name) (Located TcId, LPat TcId)
553     tc_field (field_lbl, pat) pstate thing_inside
554       = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
555            ; (pat', tvs, res) <- tcConArg (pat, pat_ty) pstate thing_inside
556            ; return ((sel_id, pat'), tvs, res) }
557
558     find_field_ty :: FieldLabel -> TcM (Id, TcType)
559     find_field_ty field_lbl
560         = case [ty | (f,ty) <- field_tys, f == field_lbl] of
561
562                 -- No matching field; chances are this field label comes from some
563                 -- other record type (or maybe none).  As well as reporting an
564                 -- error we still want to typecheck the pattern, principally to
565                 -- make sure that all the variables it binds are put into the
566                 -- environment, else the type checker crashes later:
567                 --      f (R { foo = (a,b) }) = a+b
568                 -- If foo isn't one of R's fields, we don't want to crash when
569                 -- typechecking the "a+b".
570            [] -> do { addErrTc (badFieldCon data_con field_lbl)
571                     ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
572                     ; return (error "Bogus selector Id", bogus_ty) }
573
574                 -- The normal case, when the field comes from the right constructor
575            (pat_ty : extras) -> 
576                 ASSERT( null extras )
577                 do { sel_id <- tcLookupField field_lbl
578                    ; return (sel_id, pat_ty) }
579
580     field_tys :: [(FieldLabel, TcType)]
581     field_tys = zip (dataConFieldLabels data_con) arg_tys
582         -- Don't use zipEqual! If the constructor isn't really a record, then
583         -- dataConFieldLabels will be empty (and each field in the pattern
584         -- will generate an error below).
585
586 tcConArg :: Checker (LPat Name, BoxySigmaType) (LPat Id)
587 tcConArg (arg_pat, arg_ty) pstate thing_inside
588   = tc_lpat arg_pat arg_ty pstate thing_inside
589         -- NB: the tc_lpat will refine pat_ty if necessary
590         --     based on the current pstate, which may include
591         --     refinements from peer argument patterns to the left
592 \end{code}
593
594 \begin{code}
595 addDataConStupidTheta :: InstOrigin -> DataCon -> [TcType] -> TcM ()
596 -- Instantiate the "stupid theta" of the data con, and throw 
597 -- the constraints into the constraint set
598 addDataConStupidTheta origin data_con inst_tys
599   | null stupid_theta = return ()
600   | otherwise         = instStupidTheta origin inst_theta
601   where
602     stupid_theta = dataConStupidTheta data_con
603     tenv = zipTopTvSubst (dataConUnivTyVars data_con) inst_tys
604     inst_theta = substTheta tenv stupid_theta
605 \end{code}
606
607
608 %************************************************************************
609 %*                                                                      *
610                 Type refinement
611 %*                                                                      *
612 %************************************************************************
613
614 \begin{code}
615 refineAlt :: DataCon            -- For tracing only
616           -> PatState 
617           -> [TcTyVar]          -- Existentials
618           -> [CoVar]            -- Equational constraints
619           -> BoxySigmaType      -- Pattern type
620           -> TcM PatState
621
622 refineAlt con pstate ex_tvs [] pat_ty
623   = return pstate       -- Common case: no equational constraints
624
625 refineAlt con pstate ex_tvs co_vars pat_ty
626   | not (isRigidTy pat_ty)
627   = failWithTc (nonRigidMatch con)
628         -- We are matching against a GADT constructor with non-trivial
629         -- constraints, but pattern type is wobbly.  For now we fail.
630         -- We can make sense of this, however:
631         -- Suppose MkT :: forall a b. (a:=:[b]) => b -> T a
632         --      (\x -> case x of { MkT v -> v })
633         -- We can infer that x must have type T [c], for some wobbly 'c'
634         -- and translate to
635         --      (\(x::T [c]) -> case x of
636         --                        MkT b (g::([c]:=:[b])) (v::b) -> v `cast` sym g
637         -- To implement this, we'd first instantiate the equational
638         -- constraints with *wobbly* type variables for the existentials;
639         -- then unify these constraints to make pat_ty the right shape;
640         -- then proceed exactly as in the rigid case
641
642   | otherwise   -- In the rigid case, we perform type refinement
643   = case gadtRefine (pat_reft pstate) ex_tvs co_vars of {
644             Failed msg     -> failWithTc (inaccessibleAlt msg) ;
645             Succeeded reft -> do { traceTc trace_msg
646                                  ; return (pstate { pat_reft = reft }) }
647                     -- DO NOT refine the envt right away, because we 
648                     -- might be inside a lazy pattern.  Instead, refine pstate
649                 where
650                     
651                     trace_msg = text "refineAlt:match" <+> ppr con <+> ppr reft
652         }
653 \end{code}
654
655
656 %************************************************************************
657 %*                                                                      *
658                 Overloaded literals
659 %*                                                                      *
660 %************************************************************************
661
662 In tcOverloadedLit we convert directly to an Int or Integer if we
663 know that's what we want.  This may save some time, by not
664 temporarily generating overloaded literals, but it won't catch all
665 cases (the rest are caught in lookupInst).
666
667 \begin{code}
668 tcOverloadedLit :: InstOrigin
669                  -> HsOverLit Name
670                  -> BoxyRhoType
671                  -> TcM (HsOverLit TcId)
672 tcOverloadedLit orig lit@(HsIntegral i fi) res_ty
673   | not (fi `isHsVar` fromIntegerName)  -- Do not generate a LitInst for rebindable syntax.  
674         -- Reason: If we do, tcSimplify will call lookupInst, which
675         --         will call tcSyntaxName, which does unification, 
676         --         which tcSimplify doesn't like
677         -- ToDo: noLoc sadness
678   = do  { integer_ty <- tcMetaTy integerTyConName
679         ; fi' <- tcSyntaxOp orig fi (mkFunTy integer_ty res_ty)
680         ; return (HsIntegral i (HsApp (noLoc fi') (nlHsLit (HsInteger i integer_ty)))) }
681
682   | Just expr <- shortCutIntLit i res_ty 
683   = return (HsIntegral i expr)
684
685   | otherwise
686   = do  { expr <- newLitInst orig lit res_ty
687         ; return (HsIntegral i expr) }
688
689 tcOverloadedLit orig lit@(HsFractional r fr) res_ty
690   | not (fr `isHsVar` fromRationalName) -- c.f. HsIntegral case
691   = do  { rat_ty <- tcMetaTy rationalTyConName
692         ; fr' <- tcSyntaxOp orig fr (mkFunTy rat_ty res_ty)
693                 -- Overloaded literals must have liftedTypeKind, because
694                 -- we're instantiating an overloaded function here,
695                 -- whereas res_ty might be openTypeKind. This was a bug in 6.2.2
696                 -- However this'll be picked up by tcSyntaxOp if necessary
697         ; return (HsFractional r (HsApp (noLoc fr') (nlHsLit (HsRat r rat_ty)))) }
698
699   | Just expr <- shortCutFracLit r res_ty 
700   = return (HsFractional r expr)
701
702   | otherwise
703   = do  { expr <- newLitInst orig lit res_ty
704         ; return (HsFractional r expr) }
705
706 newLitInst :: InstOrigin -> HsOverLit Name -> BoxyRhoType -> TcM (HsExpr TcId)
707 newLitInst orig lit res_ty      -- Make a LitInst
708   = do  { loc <- getInstLoc orig
709         ; res_tau <- zapToMonotype res_ty
710         ; new_uniq <- newUnique
711         ; let   lit_nm   = mkSystemVarName new_uniq FSLIT("lit")
712                 lit_inst = LitInst lit_nm lit res_tau loc
713         ; extendLIE lit_inst
714         ; return (HsVar (instToId lit_inst)) }
715 \end{code}
716
717
718 %************************************************************************
719 %*                                                                      *
720                 Note [Pattern coercions]
721 %*                                                                      *
722 %************************************************************************
723
724 In principle, these program would be reasonable:
725         
726         f :: (forall a. a->a) -> Int
727         f (x :: Int->Int) = x 3
728
729         g :: (forall a. [a]) -> Bool
730         g [] = True
731
732 In both cases, the function type signature restricts what arguments can be passed
733 in a call (to polymorphic ones).  The pattern type signature then instantiates this
734 type.  For example, in the first case,  (forall a. a->a) <= Int -> Int, and we
735 generate the translated term
736         f = \x' :: (forall a. a->a).  let x = x' Int in x 3
737
738 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
739 And it requires a significant amount of code to implement, becuase we need to decorate
740 the translated pattern with coercion functions (generated from the subsumption check 
741 by tcSub).  
742
743 So for now I'm just insisting on type *equality* in patterns.  No subsumption. 
744
745 Old notes about desugaring, at a time when pattern coercions were handled:
746
747 A SigPat is a type coercion and must be handled one at at time.  We can't
748 combine them unless the type of the pattern inside is identical, and we don't
749 bother to check for that.  For example:
750
751         data T = T1 Int | T2 Bool
752         f :: (forall a. a -> a) -> T -> t
753         f (g::Int->Int)   (T1 i) = T1 (g i)
754         f (g::Bool->Bool) (T2 b) = T2 (g b)
755
756 We desugar this as follows:
757
758         f = \ g::(forall a. a->a) t::T ->
759             let gi = g Int
760             in case t of { T1 i -> T1 (gi i)
761                            other ->
762             let gb = g Bool
763             in case t of { T2 b -> T2 (gb b)
764                            other -> fail }}
765
766 Note that we do not treat the first column of patterns as a
767 column of variables, because the coerced variables (gi, gb)
768 would be of different types.  So we get rather grotty code.
769 But I don't think this is a common case, and if it was we could
770 doubtless improve it.
771
772 Meanwhile, the strategy is:
773         * treat each SigPat coercion (always non-identity coercions)
774                 as a separate block
775         * deal with the stuff inside, and then wrap a binding round
776                 the result to bind the new variable (gi, gb, etc)
777
778
779 %************************************************************************
780 %*                                                                      *
781 \subsection{Errors and contexts}
782 %*                                                                      *
783 %************************************************************************
784
785 \begin{code}
786 patCtxt :: Pat Name -> Maybe Message    -- Not all patterns are worth pushing a context
787 patCtxt (VarPat _)  = Nothing
788 patCtxt (ParPat _)  = Nothing
789 patCtxt (AsPat _ _) = Nothing
790 patCtxt pat         = Just (hang (ptext SLIT("In the pattern:")) 
791                                4 (ppr pat))
792
793 -----------------------------------------------
794
795 existentialExplode pat
796   = hang (vcat [text "My brain just exploded.",
797                 text "I can't handle pattern bindings for existentially-quantified constructors.",
798                 text "In the binding group for"])
799         4 (ppr pat)
800
801 sigPatCtxt bound_ids bound_tvs pat_tys body_ty tidy_env 
802   = do  { pat_tys' <- mapM zonkTcType pat_tys
803         ; body_ty' <- zonkTcType body_ty
804         ; let (env1,  tidy_tys)    = tidyOpenTypes tidy_env (map idType show_ids)
805               (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
806               (env3, tidy_body_ty) = tidyOpenType  env2 body_ty'
807         ; return (env3,
808                  sep [ptext SLIT("When checking an existential match that binds"),
809                       nest 4 (vcat (zipWith ppr_id show_ids tidy_tys)),
810                       ptext SLIT("The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
811                       ptext SLIT("The body has type:") <+> ppr tidy_body_ty
812                 ]) }
813   where
814     show_ids = filter is_interesting bound_ids
815     is_interesting id = any (`elemVarSet` idFreeTyVars id) bound_tvs
816
817     ppr_id id ty = ppr id <+> dcolon <+> ppr ty
818         -- Don't zonk the types so we get the separate, un-unified versions
819
820 badFieldCon :: DataCon -> Name -> SDoc
821 badFieldCon con field
822   = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
823           ptext SLIT("does not have field"), quotes (ppr field)]
824
825 polyPatSig :: TcType -> SDoc
826 polyPatSig sig_ty
827   = hang (ptext SLIT("Illegal polymorphic type signature in pattern:"))
828          4 (ppr sig_ty)
829
830 badTypePat pat = ptext SLIT("Illegal type pattern") <+> ppr pat
831
832 lazyPatErr pat tvs
833   = failWithTc $
834     hang (ptext SLIT("A lazy (~) pattern connot bind existential type variables"))
835        2 (vcat (map pprSkolTvBinding tvs))
836
837 nonRigidMatch con
838   =  hang (ptext SLIT("GADT pattern match in non-rigid context for") <+> quotes (ppr con))
839         2 (ptext SLIT("Tell GHC HQ if you'd like this to unify the context"))
840
841 inaccessibleAlt msg
842   = hang (ptext SLIT("Inaccessible case alternative:")) 2 msg
843 \end{code}