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