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