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