Super-monster patch implementing the new typechecker -- at last
[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, TcSigFun, TcSigInfo(..)
10              , tcPat, tcPats, newLetBndr
11              , addDataConStupidTheta, badFieldCon, polyPatSig ) where
12
13 #include "HsVersions.h"
14
15 import {-# SOURCE #-}   TcExpr( tcSyntaxOp, tcInferRho)
16
17 import HsSyn
18 import TcHsSyn
19 import TcRnMonad
20 import Inst
21 import Id
22 import Var
23 import Name
24 import TcEnv
25 import TcMType
26 import TcType
27 import TcUnify
28 import TcHsType
29 import TysWiredIn
30 import Coercion
31 import StaticFlags
32 import TyCon
33 import DataCon
34 import VarSet   ( emptyVarSet )
35 import PrelNames
36 import BasicTypes hiding (SuccessFlag(..))
37 import DynFlags
38 import SrcLoc
39 import ErrUtils
40 import Util
41 import Outputable
42 import FastString
43 import Control.Monad
44 \end{code}
45
46
47 %************************************************************************
48 %*                                                                      *
49                 External interface
50 %*                                                                      *
51 %************************************************************************
52
53 \begin{code}
54 tcLetPat :: (Name -> Maybe TcSigInfo)
55          -> Bool     -- True <=> monomorphic
56          -> LPat Name -> TcSigmaType 
57          -> TcM a
58          -> TcM (LPat TcId, a)
59 tcLetPat sig_fn is_mono pat pat_ty thing_inside
60   = tc_lpat pat pat_ty penv thing_inside 
61   where
62     penv = PE { pe_res_tvs = emptyVarSet, pe_lazy = True
63               , pe_ctxt = LetPat sig_fn is_mono }
64
65 -----------------
66 tcPats :: HsMatchContext Name
67        -> [LPat Name]            -- Patterns,
68        -> [TcSigmaType]          --   and their types
69        -> TcRhoType              -- Result type,
70        -> TcM a                  --   and the checker for the body
71        -> TcM ([LPat TcId], a)
72
73 -- This is the externally-callable wrapper function
74 -- Typecheck the patterns, extend the environment to bind the variables,
75 -- do the thing inside, use any existentially-bound dictionaries to 
76 -- discharge parts of the returning LIE, and deal with pattern type
77 -- signatures
78
79 --   1. Initialise the PatState
80 --   2. Check the patterns
81 --   3. Check the body
82 --   4. Check that no existentials escape
83
84 tcPats ctxt pats pat_tys res_ty thing_inside
85   = tc_lpats penv pats pat_tys thing_inside
86   where
87     penv = PE { pe_res_tvs = tyVarsOfTypes (res_ty : pat_tys)
88               , pe_lazy = False
89               , pe_ctxt = LamPat ctxt }
90
91 tcPat :: HsMatchContext Name
92       -> LPat Name -> TcSigmaType 
93       -> TcRhoType             -- Result type
94       -> TcM a                 -- Checker for body, given
95                                -- its result type
96       -> TcM (LPat TcId, a)
97 tcPat ctxt pat pat_ty res_ty thing_inside
98   = tc_lpat pat pat_ty penv thing_inside
99   where
100     penv = PE { pe_res_tvs = tyVarsOfTypes [res_ty, pat_ty]
101               , pe_lazy = False
102               , pe_ctxt = LamPat ctxt }
103    
104
105 -----------------
106 data PatEnv
107   = PE { pe_res_tvs :: TcTyVarSet       
108                    -- For existential escape check; see Note [Existential check]
109                    -- Nothing <=> inside a "~"
110                    -- Just tvs <=> unification tvs free in the result
111                    --              (which should be made untouchable in
112                    --               any existentials we encounter in the pattern)
113
114        , pe_lazy :: Bool        -- True <=> lazy context, so no existentials allowed
115        , pe_ctxt :: PatCtxt     -- Context in which the whole pattern appears
116     }
117
118 data PatCtxt
119   = LamPat   -- Used for lambdas, case etc
120        (HsMatchContext Name) 
121
122   | LetPat   -- Used only for let(rec) bindings
123              -- See Note [Let binders]
124        TcSigFun   -- Tells type sig if any
125        Bool       -- True <=> no generalisation of this let
126                                         
127 makeLazy :: PatEnv -> PatEnv
128 makeLazy penv = penv { pe_lazy = True }
129
130 patSigCtxt :: PatEnv -> UserTypeCtxt
131 patSigCtxt (PE { pe_ctxt = LetPat {} }) = BindPatSigCtxt
132 patSigCtxt (PE { pe_ctxt = LamPat {} }) = LamPatSigCtxt
133
134 ---------------
135 type TcSigFun = Name -> Maybe TcSigInfo
136
137 data TcSigInfo
138   = TcSigInfo {
139         sig_id     :: TcId,         --  *Polymorphic* binder for this value...
140
141         sig_scoped :: [Name],       -- Scoped type variables
142                 -- 1-1 correspondence with a prefix of sig_tvs
143                 -- However, may be fewer than sig_tvs; 
144                 -- see Note [More instantiated than scoped]
145         sig_tvs    :: [TcTyVar],    -- Instantiated type variables
146                                     -- See Note [Instantiate sig]
147
148         sig_theta  :: TcThetaType,  -- Instantiated theta
149
150         sig_tau    :: TcSigmaType,  -- Instantiated tau
151                                     -- See Note [sig_tau may be polymorphic]
152
153         sig_loc    :: SrcSpan       -- The location of the signature
154     }
155
156 instance Outputable TcSigInfo where
157     ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
158         = ppr id <+> ptext (sLit "::") <+> ppr tyvars <+> pprThetaArrow theta <+> ppr tau
159 \end{code}
160
161 Note [sig_tau may be polymorphic]
162 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
163 Note that "sig_tau" might actually be a polymorphic type,
164 if the original function had a signature like
165    forall a. Eq a => forall b. Ord b => ....
166 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
167 It happens, too!  See Note [Polymorphic methods] in TcClassDcl.
168
169 Note [Let binders]
170 ~~~~~~~~~~~~~~~~~~
171 eg   x :: Int
172      y :: Bool
173      (x,y) = e
174
175 ...more notes to add here..
176
177
178 Note [Existential check]
179 ~~~~~~~~~~~~~~~~~~~~~~~~
180 Lazy patterns can't bind existentials.  They arise in two ways:
181   * Let bindings      let { C a b = e } in b
182   * Twiddle patterns  f ~(C a b) = e
183 The pe_res_tvs field of PatEnv says whether we are inside a lazy
184 pattern (perhaps deeply)
185
186 If we aren't inside a lazy pattern then we can bind existentials,
187 but we need to be careful about "extra" tyvars. Consider
188     (\C x -> d) : pat_ty -> res_ty
189 When looking for existential escape we must check that the existential
190 bound by C don't unify with the free variables of pat_ty, OR res_ty
191 (or of course the environment).   Hence we need to keep track of the 
192 res_ty free vars.
193
194
195 %************************************************************************
196 %*                                                                      *
197                 Binders
198 %*                                                                      *
199 %************************************************************************
200
201 \begin{code}
202 tcPatBndr :: PatEnv -> Name -> TcSigmaType -> TcM (CoercionI, TcId)
203 -- (coi, xp) = tcPatBndr penv x pat_ty
204 -- Then coi : pat_ty ~ typeof(xp)
205 --
206 tcPatBndr (PE { pe_ctxt = LetPat lookup_sig no_gen}) bndr_name pat_ty
207   | Just sig <- lookup_sig bndr_name
208   = do { bndr_id <- if no_gen then return (sig_id sig)
209                     else do { mono_name <- newLocalName bndr_name
210                             ; return (Id.mkLocalId mono_name (sig_tau sig)) }
211        ; coi <- unifyPatType (idType bndr_id) pat_ty
212        ; return (coi, bndr_id) }
213       
214   | otherwise
215   = do { bndr_id <- newLetBndr no_gen bndr_name pat_ty
216        ; return (IdCo pat_ty, bndr_id) }
217
218 tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty
219   = do { bndr <- mkLocalBinder bndr_name pat_ty
220        ; return (IdCo pat_ty, bndr) }
221
222 newLetBndr :: Bool -> Name -> TcType -> TcM TcId
223 -- In the polymorphic case (no_gen = False), generate a "monomorphic version" 
224 --    of the Id; the original name will be bound to the polymorphic version
225 --    by the AbsBinds
226 -- In the monomorphic case there is no AbsBinds, and we use the original
227 --    name directly
228 newLetBndr no_gen name ty
229   | no_gen    = mkLocalBinder name ty
230   | otherwise = do { mono_name <- newLocalName name
231                    ; mkLocalBinder mono_name ty }
232
233 -----------------
234 mkLocalBinder :: Name -> TcType -> TcM TcId
235 mkLocalBinder name ty
236   = do { checkUnboxedTuple ty $ 
237             ptext (sLit "The variable") <+> quotes (ppr name)
238        ; return (Id.mkLocalId name ty) }
239
240 checkUnboxedTuple :: TcType -> SDoc -> TcM ()
241 -- Check for an unboxed tuple type
242 --      f = (# True, False #)
243 -- Zonk first just in case it's hidden inside a meta type variable
244 -- (This shows up as a (more obscure) kind error 
245 --  in the 'otherwise' case of tcMonoBinds.)
246 checkUnboxedTuple ty what
247   = do { zonked_ty <- zonkTcTypeCarefully ty
248        ; checkTc (not (isUnboxedTupleType zonked_ty))
249                  (unboxedTupleErr what zonked_ty) }
250
251 -------------------
252 {- Only needed if we re-add Method constraints 
253 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, TcEvBinds)
254 bindInstsOfPatId id thing_inside
255   | not (isOverloadedTy (idType id))
256   = do { res <- thing_inside; return (res, emptyTcEvBinds) }
257   | otherwise
258   = do  { (res, lie) <- getConstraints thing_inside
259         ; binds <- bindLocalMethods lie [id]
260         ; return (res, binds) }
261 -}
262 \end{code}
263
264 Note [Polymorphism and pattern bindings]
265 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
266 When is_mono holds we are not generalising
267 But the signature can still be polymoprhic!
268      data T = MkT (forall a. a->a)
269      x :: forall a. a->a
270      MkT x = <rhs>
271 So the no_gen flag decides whether the pattern-bound variables should
272 have exactly the type in the type signature (when not generalising) or
273 the instantiated version (when generalising)
274
275 %************************************************************************
276 %*                                                                      *
277                 The main worker functions
278 %*                                                                      *
279 %************************************************************************
280
281 Note [Nesting]
282 ~~~~~~~~~~~~~~
283 tcPat takes a "thing inside" over which the pattern scopes.  This is partly
284 so that tcPat can extend the environment for the thing_inside, but also 
285 so that constraints arising in the thing_inside can be discharged by the
286 pattern.
287
288 This does not work so well for the ErrCtxt carried by the monad: we don't
289 want the error-context for the pattern to scope over the RHS. 
290 Hence the getErrCtxt/setErrCtxt stuff in tcMultiple
291
292 \begin{code}
293 --------------------
294 type Checker inp out =  forall r.
295                           inp
296                        -> PatEnv
297                        -> TcM r
298                        -> TcM (out, r)
299
300 tcMultiple :: Checker inp out -> Checker [inp] [out]
301 tcMultiple tc_pat args penv thing_inside
302   = do  { err_ctxt <- getErrCtxt
303         ; let loop _ []
304                 = do { res <- thing_inside
305                      ; return ([], res) }
306
307               loop penv (arg:args)
308                 = do { (p', (ps', res)) 
309                                 <- tc_pat arg penv $ 
310                                    setErrCtxt err_ctxt $
311                                    loop penv args
312                 -- setErrCtxt: restore context before doing the next pattern
313                 -- See note [Nesting] above
314                                 
315                      ; return (p':ps', res) }
316
317         ; loop penv args }
318
319 --------------------
320 tc_lpat :: LPat Name 
321         -> TcSigmaType
322         -> PatEnv
323         -> TcM a
324         -> TcM (LPat TcId, a)
325 tc_lpat (L span pat) pat_ty penv thing_inside
326   = setSrcSpan span               $
327     maybeAddErrCtxt (patCtxt pat) $
328     do  { (pat', res) <- tc_pat penv pat pat_ty thing_inside
329         ; return (L span pat', res) }
330
331 tc_lpats :: PatEnv
332          -> [LPat Name] -> [TcSigmaType]
333          -> TcM a       
334          -> TcM ([LPat TcId], a)
335 tc_lpats penv pats tys thing_inside 
336   =  tcMultiple (\(p,t) -> tc_lpat p t) 
337                 (zipEqual "tc_lpats" pats tys)
338                 penv thing_inside 
339
340 --------------------
341 tc_pat  :: PatEnv
342         -> Pat Name 
343         -> TcSigmaType  -- Fully refined result type
344         -> TcM a                -- Thing inside
345         -> TcM (Pat TcId,       -- Translated pattern
346                 a)              -- Result of thing inside
347
348 tc_pat penv (VarPat name) pat_ty thing_inside
349   = do  { (coi, id) <- tcPatBndr penv name pat_ty
350         ; res <- tcExtendIdEnv1 name id thing_inside
351         ; return (mkHsWrapPatCoI coi (VarPat id) pat_ty, res) }
352
353 {- Need this if we re-add Method constraints 
354         ; (res, binds) <- bindInstsOfPatId id $
355                           tcExtendIdEnv1 name id $
356                           (traceTc (text "binding" <+> ppr name <+> ppr (idType id))
357                            >> thing_inside)
358         ; let pat' | isEmptyTcEvBinds binds = VarPat id
359                    | otherwise              = VarPatOut id binds
360         ; return (mkHsWrapPatCoI coi pat' pat_ty, res) }
361 -}
362
363 tc_pat penv (ParPat pat) pat_ty thing_inside
364   = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
365         ; return (ParPat pat', res) }
366
367 tc_pat penv (BangPat pat) pat_ty thing_inside
368   = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
369         ; return (BangPat pat', res) }
370
371 tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside
372   = do  { (pat', (res, pat_ct)) 
373                 <- tc_lpat pat pat_ty (makeLazy penv) $ 
374                    getConstraints thing_inside
375                 -- Ignore refined penv', revert to penv
376
377         ; emitConstraints pat_ct
378         -- getConstraints/extendConstraintss: see Note [Hopping the LIE in lazy patterns]
379
380         -- Check there are no unlifted types under the lazy pattern
381         ; when (any (isUnLiftedType . idType) $ collectPatBinders pat') $
382                lazyUnliftedPatErr lpat
383
384         -- Check that the expected pattern type is itself lifted
385         ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
386         ; _ <- unifyType pat_ty pat_ty'
387
388         ; return (LazyPat pat', res) }
389
390 tc_pat _ p@(QuasiQuotePat _) _ _
391   = pprPanic "Should never see QuasiQuotePat in type checker" (ppr p)
392
393 tc_pat _ (WildPat _) pat_ty thing_inside
394   = do  { checkUnboxedTuple pat_ty $
395                ptext (sLit "A wild-card pattern")
396         ; res <- thing_inside 
397         ; return (WildPat pat_ty, res) }
398
399 tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
400   = do  { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
401         ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
402                          tc_lpat pat (idType bndr_id) penv thing_inside
403             -- NB: if we do inference on:
404             --          \ (y@(x::forall a. a->a)) = e
405             -- we'll fail.  The as-pattern infers a monotype for 'y', which then
406             -- fails to unify with the polymorphic type for 'x'.  This could 
407             -- perhaps be fixed, but only with a bit more work.
408             --
409             -- If you fix it, don't forget the bindInstsOfPatIds!
410         ; return (mkHsWrapPatCoI coi (AsPat (L nm_loc bndr_id) pat') pat_ty, res) }
411
412 tc_pat penv vpat@(ViewPat expr pat _) overall_pat_ty thing_inside 
413   = do  { checkUnboxedTuple overall_pat_ty $
414                ptext (sLit "The view pattern") <+> ppr vpat
415
416          -- Morally, expr must have type `forall a1...aN. OPT' -> B` 
417          -- where overall_pat_ty is an instance of OPT'.
418          -- Here, we infer a rho type for it,
419          -- which replaces the leading foralls and constraints
420          -- with fresh unification variables.
421         ; (expr',expr'_inferred) <- tcInferRho expr
422
423          -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
424          -- NOTE: this forces pat_ty to be a monotype (because we use a unification 
425          -- variable to find it).  this means that in an example like
426          -- (view -> f)    where view :: _ -> forall b. b
427          -- we will only be able to use view at one instantation in the
428          -- rest of the view
429         ; (expr_coi, pat_ty) <- tcInfer $ \ pat_ty -> 
430                 unifyPatType expr'_inferred (mkFunTy overall_pat_ty pat_ty)
431
432          -- pattern must have pat_ty
433         ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside
434
435         ; return (ViewPat (mkLHsWrapCoI expr_coi expr') pat' overall_pat_ty, res) }
436
437 -- Type signatures in patterns
438 -- See Note [Pattern coercions] below
439 tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
440   = do  { (inner_ty, tv_binds, wrap) <- tcPatSig (patSigCtxt penv) sig_ty pat_ty
441         ; (pat', res) <- tcExtendTyVarEnv2 tv_binds $
442                          tc_lpat pat inner_ty penv thing_inside
443
444         ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
445
446 tc_pat _ pat@(TypePat _) _ _
447   = failWithTc (badTypePat pat)
448
449 ------------------------
450 -- Lists, tuples, arrays
451 tc_pat penv (ListPat pats _) pat_ty thing_inside
452   = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy pat_ty
453         ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
454                                      pats penv thing_inside
455         ; return (mkHsWrapPat coi (ListPat pats' elt_ty) pat_ty, res) 
456         }
457
458 tc_pat penv (PArrPat pats _) pat_ty thing_inside
459   = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTy pat_ty
460         ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
461                                      pats penv thing_inside 
462         ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
463         }
464
465 tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
466   = do  { let tc = tupleTyCon boxity (length pats)
467         ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc) pat_ty
468         ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
469
470         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
471         -- so that we can experiment with lazy tuple-matching.
472         -- This is a pretty odd place to make the switch, but
473         -- it was easy to do.
474         ; let pat_ty'          = mkTyConApp tc arg_tys
475                                      -- pat_ty /= pat_ty iff coi /= IdCo
476               unmangled_result = TuplePat pats' boxity pat_ty'
477               possibly_mangled_result
478                 | opt_IrrefutableTuples && 
479                   isBoxed boxity            = LazyPat (noLoc unmangled_result)
480                 | otherwise                 = unmangled_result
481
482         ; ASSERT( length arg_tys == length pats )      -- Syntactically enforced
483           return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
484         }
485
486 ------------------------
487 -- Data constructors
488 tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
489   = tcConPat penv con pat_ty arg_pats thing_inside
490
491 ------------------------
492 -- Literal patterns
493 tc_pat _ (LitPat simple_lit) pat_ty thing_inside
494   = do  { let lit_ty = hsLitType simple_lit
495         ; coi <- unifyPatType lit_ty pat_ty
496                 -- coi is of kind: pat_ty ~ lit_ty
497         ; res <- thing_inside 
498         ; return ( mkHsWrapPatCoI coi (LitPat simple_lit) pat_ty 
499                  , res) }
500
501 ------------------------
502 -- Overloaded patterns: n, and n+k
503 tc_pat _ (NPat over_lit mb_neg eq) pat_ty thing_inside
504   = do  { let orig = LiteralOrigin over_lit
505         ; lit'    <- newOverloadedLit orig over_lit pat_ty
506         ; eq'     <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
507         ; mb_neg' <- case mb_neg of
508                         Nothing  -> return Nothing      -- Positive literal
509                         Just neg ->     -- Negative literal
510                                         -- The 'negate' is re-mappable syntax
511                             do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
512                                ; return (Just neg') }
513         ; res <- thing_inside 
514         ; return (NPat lit' mb_neg' eq', res) }
515
516 tc_pat penv (NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
517   = do  { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
518         ; let pat_ty' = idType bndr_id
519               orig    = LiteralOrigin lit
520         ; lit' <- newOverloadedLit orig lit pat_ty'
521
522         -- The '>=' and '-' parts are re-mappable syntax
523         ; ge'    <- tcSyntaxOp orig ge    (mkFunTys [pat_ty', pat_ty'] boolTy)
524         ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
525         ; let pat' = NPlusKPat (L nm_loc bndr_id) lit' ge' minus'
526
527         -- The Report says that n+k patterns must be in Integral
528         -- We may not want this when using re-mappable syntax, though (ToDo?)
529         ; icls <- tcLookupClass integralClassName
530         ; instStupidTheta orig [mkClassPred icls [pat_ty']]     
531     
532         ; res <- tcExtendIdEnv1 name bndr_id thing_inside
533         ; return (mkHsWrapPatCoI coi pat' pat_ty, res) }
534
535 tc_pat _ _other_pat _ _ = panic "tc_pat"        -- ConPatOut, SigPatOut, VarPatOut
536
537 ----------------
538 unifyPatType :: TcType -> TcType -> TcM CoercionI
539 -- In patterns we want a coercion from the
540 -- context type (expected) to the actual pattern type
541 -- But we don't want to reverse the args to unifyType because
542 -- that controls the actual/expected stuff in error messages
543 unifyPatType actual_ty expected_ty
544   = do { coi <- unifyType actual_ty expected_ty
545        ; return (mkSymCoI coi) }
546 \end{code}
547
548 Note [Hopping the LIE in lazy patterns]
549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
550 In a lazy pattern, we must *not* discharge constraints from the RHS
551 from dictionaries bound in the pattern.  E.g.
552         f ~(C x) = 3
553 We can't discharge the Num constraint from dictionaries bound by
554 the pattern C!  
555
556 So we have to make the constraints from thing_inside "hop around" 
557 the pattern.  Hence the getConstraints and emitConstraints.
558
559 The same thing ensures that equality constraints in a lazy match
560 are not made available in the RHS of the match. For example
561         data T a where { T1 :: Int -> T Int; ... }
562         f :: T a -> Int -> a
563         f ~(T1 i) y = y
564 It's obviously not sound to refine a to Int in the right
565 hand side, because the arugment might not match T1 at all!
566
567 Finally, a lazy pattern should not bind any existential type variables
568 because they won't be in scope when we do the desugaring
569
570
571 %************************************************************************
572 %*                                                                      *
573         Most of the work for constructors is here
574         (the rest is in the ConPatIn case of tc_pat)
575 %*                                                                      *
576 %************************************************************************
577
578 [Pattern matching indexed data types]
579 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
580 Consider the following declarations:
581
582   data family Map k :: * -> *
583   data instance Map (a, b) v = MapPair (Map a (Pair b v))
584
585 and a case expression
586
587   case x :: Map (Int, c) w of MapPair m -> ...
588
589 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
590 worker/wrapper types for MapPair are
591
592   $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
593   $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
594
595 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
596 :R123Map, which means the straight use of boxySplitTyConApp would give a type
597 error.  Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
598 boxySplitTyConApp with the family tycon Map instead, which gives us the family
599 type list {(Int, c), w}.  To get the correct split for :R123Map, we need to
600 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
601 (provided by tyConFamInst_maybe together with the family tycon).  This
602 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
603 the split arguments for the representation tycon :R123Map as {Int, c, w}
604
605 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion 
606
607   Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
608
609 moving between representation and family type into account.  To produce type
610 correct Core, this coercion needs to be used to case the type of the scrutinee
611 from the family to the representation type.  This is achieved by
612 unwrapFamInstScrutinee using a CoPat around the result pattern.
613
614 Now it might appear seem as if we could have used the previous GADT type
615 refinement infrastructure of refineAlt and friends instead of the explicit
616 unification and CoPat generation.  However, that would be wrong.  Why?  The
617 whole point of GADT refinement is that the refinement is local to the case
618 alternative.  In contrast, the substitution generated by the unification of
619 the family type list and instance types needs to be propagated to the outside.
620 Imagine that in the above example, the type of the scrutinee would have been
621 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
622 substitution [x -> (a, b), v -> w].  In contrast to GADT matching, the
623 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
624 alternatives of the case expression, whereas in the GADT case it might vary
625 between alternatives.
626
627 RIP GADT refinement: refinements have been replaced by the use of explicit
628 equality constraints that are used in conjunction with implication constraints
629 to express the local scope of GADT refinements.
630
631 \begin{code}
632 --      Running example:
633 -- MkT :: forall a b c. (a~[b]) => b -> c -> T a
634 --       with scrutinee of type (T ty)
635
636 tcConPat :: PatEnv -> Located Name 
637          -> TcRhoType           -- Type of the pattern
638          -> HsConPatDetails Name -> TcM a
639          -> TcM (Pat TcId, a)
640 tcConPat penv (L con_span con_name) pat_ty arg_pats thing_inside
641   = do  { data_con <- tcLookupDataCon con_name
642         ; let tycon = dataConTyCon data_con
643                   -- For data families this is the representation tycon
644               (univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _)
645                 = dataConFullSig data_con
646
647           -- Instantiate the constructor type variables [a->ty]
648           -- This may involve doing a family-instance coercion, 
649           -- and building a wrapper 
650         ; (wrap, ctxt_res_tys) <- matchExpectedPatTy (matchExpectedConTy tycon) pat_ty
651
652           -- Add the stupid theta
653         ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
654
655         ; checkExistentials ex_tvs penv 
656         ; let skol_info = case pe_ctxt penv of
657                             LamPat mc -> PatSkol data_con mc
658                             LetPat {} -> UnkSkol -- Doesn't matter
659         ; ex_tvs' <- tcInstSkolTyVars skol_info ex_tvs  
660                      -- Get location from monad, not from ex_tvs
661
662         ; let pat_ty' = mkTyConApp tycon ctxt_res_tys
663               -- pat_ty' is type of the actual constructor application
664               -- pat_ty' /= pat_ty iff coi /= IdCo
665               
666               tenv     = zipTopTvSubst (univ_tvs     ++ ex_tvs)
667                                        (ctxt_res_tys ++ mkTyVarTys ex_tvs')
668               arg_tys' = substTys tenv arg_tys
669               full_theta = eq_theta ++ dict_theta
670
671         ; if null ex_tvs && null eq_spec && null full_theta
672           then do { -- The common case; no class bindings etc 
673                     -- (see Note [Arrows and patterns])
674                     (arg_pats', res) <- tcConArgs data_con arg_tys' 
675                                                   arg_pats penv thing_inside
676                   ; let res_pat = ConPatOut { pat_con = L con_span data_con, 
677                                               pat_tvs = [], pat_dicts = [], 
678                                               pat_binds = emptyTcEvBinds,
679                                               pat_args = arg_pats', 
680                                               pat_ty = pat_ty' }
681
682                   ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
683
684           else do   -- The general case, with existential, 
685                     -- and local equality constraints
686         { let eq_preds = [mkEqPred (mkTyVarTy tv, ty) | (tv, ty) <- eq_spec]
687               theta'   = substTheta tenv (eq_preds ++ full_theta)
688                            -- order is *important* as we generate the list of
689                            -- dictionary binders from theta'
690               no_equalities = not (any isEqPred theta')
691
692         ; gadts_on <- doptM Opt_GADTs
693         ; checkTc (no_equalities || gadts_on)
694                   (ptext (sLit "A pattern match on a GADT requires -XGADTs"))
695                   -- Trac #2905 decided that a *pattern-match* of a GADT
696                   -- should require the GADT language flag
697
698         ; given <- newEvVars theta'
699         ; let free_tvs = pe_res_tvs penv
700                 -- Since we have done checkExistentials,
701                 -- pe_res_tvs can only be Just at this point
702                 --
703                 -- Nor do we need pat_ty, because we've put all the
704                 -- unification variables in right at the start when
705                 -- initialising the PatEnv; and the pattern itself
706                 -- only adds skolems.
707
708         ; (ev_binds, (arg_pats', res))
709              <- checkConstraints skol_info free_tvs ex_tvs' given $
710                 tcConArgs data_con arg_tys' arg_pats penv thing_inside
711
712         ; let res_pat = ConPatOut { pat_con   = L con_span data_con, 
713                                     pat_tvs   = ex_tvs',
714                                     pat_dicts = given,
715                                     pat_binds = ev_binds,
716                                     pat_args  = arg_pats', 
717                                     pat_ty    = pat_ty' }
718         ; return (mkHsWrapPat wrap res_pat pat_ty, res)
719         } }
720
721 ----------------------------
722 matchExpectedPatTy :: (TcRhoType -> TcM (CoercionI, a))
723                     -> TcRhoType -> TcM (HsWrapper, a) 
724 -- See Note [Matching polytyped patterns]
725 -- Returns a wrapper : pat_ty ~ inner_ty
726 matchExpectedPatTy inner_match pat_ty
727   | null tvs && null theta
728   = do { (coi, res) <- inner_match pat_ty
729        ; return (coiToHsWrapper (mkSymCoI coi), res) }
730          -- The Sym is because the inner_match returns a coercion
731          -- that is the other way round to matchExpectedPatTy
732
733   | otherwise
734   = do { (_, tys, subst) <- tcInstTyVars tvs
735        ; wrap1 <- instCall PatOrigin tys (substTheta subst theta)
736        ; (wrap2, arg_tys) <- matchExpectedPatTy inner_match (substTy subst tau)
737        ; return (wrap2 <.> wrap1 , arg_tys) }
738   where
739     (tvs, theta, tau) = tcSplitSigmaTy pat_ty
740
741 ----------------------------
742 matchExpectedConTy :: TyCon      -- The TyCon that this data 
743                                  -- constructor actually returns
744                    -> TcRhoType  -- The type of the pattern
745                    -> TcM (CoercionI, [TcSigmaType])
746 -- See Note [Matching constructor patterns]
747 -- Returns a coercion : T ty1 ... tyn ~ pat_ty
748 -- This is the same way round as matchExpectedListTy etc
749 -- but the other way round to matchExpectedPatTy
750 matchExpectedConTy data_tc pat_ty
751   | Just (fam_tc, fam_args, co_tc) <- tyConFamInstSig_maybe data_tc
752          -- Comments refer to Note [Matching constructor patterns]
753          -- co_tc :: forall a. T [a] ~ T7 a
754   = do { (_, tys, subst) <- tcInstTyVars (tyConTyVars data_tc)
755              -- tys = [ty1,ty2]
756
757        ; coi1 <- unifyType (mkTyConApp fam_tc (substTys subst fam_args)) pat_ty
758              -- coi1 : T (ty1,ty2) ~ pat_ty
759
760        ; let coi2 = ACo (mkTyConApp co_tc tys)
761              -- coi2 : T (ty1,ty2) ~ T7 ty1 ty2
762
763        ; return (mkTransCoI (mkSymCoI coi2) coi1, tys) }
764
765   | otherwise
766   = matchExpectedTyConApp data_tc pat_ty
767              -- coi : T tys ~ pat_ty
768 \end{code}
769
770 Noate [
771 Note [Matching constructor patterns]
772 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
773 Suppose (coi, tys) = matchExpectedConType data_tc pat_ty
774
775  * In the simple case, pat_ty = tc tys
776
777  * If pat_ty is a polytype, we want to instantiate it
778    This is like part of a subsumption check.  Eg
779       f :: (forall a. [a]) -> blah
780       f [] = blah
781
782  * In a type family case, suppose we have
783           data family T a
784           data instance T (p,q) = A p | B q
785        Then we'll have internally generated
786               data T7 p q = A p | B q
787               axiom coT7 p q :: T (p,q) ~ T7 p q
788  
789        So if pat_ty = T (ty1,ty2), we return (coi, [ty1,ty2]) such that
790            coi = coi2 . coi1 : T7 t ~ pat_ty
791            coi1 : T (ty1,ty2) ~ pat_ty
792            coi2 : T7 ty1 ty2 ~ T (ty1,ty2)
793
794    For families we do all this matching here, not in the unifier,
795    because we never want a whisper of the data_tycon to appear in
796    error messages; it's a purely internal thing
797
798 \begin{code}
799 tcConArgs :: DataCon -> [TcSigmaType]
800           -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
801
802 tcConArgs data_con arg_tys (PrefixCon arg_pats) penv thing_inside
803   = do  { checkTc (con_arity == no_of_args)     -- Check correct arity
804                   (arityErr "Constructor" data_con con_arity no_of_args)
805         ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
806         ; (arg_pats', res) <- tcMultiple tcConArg pats_w_tys
807                                               penv thing_inside 
808         ; return (PrefixCon arg_pats', res) }
809   where
810     con_arity  = dataConSourceArity data_con
811     no_of_args = length arg_pats
812
813 tcConArgs data_con arg_tys (InfixCon p1 p2) penv thing_inside
814   = do  { checkTc (con_arity == 2)      -- Check correct arity
815                   (arityErr "Constructor" data_con con_arity 2)
816         ; let [arg_ty1,arg_ty2] = arg_tys       -- This can't fail after the arity check
817         ; ([p1',p2'], res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
818                                               penv thing_inside
819         ; return (InfixCon p1' p2', res) }
820   where
821     con_arity  = dataConSourceArity data_con
822
823 tcConArgs data_con arg_tys (RecCon (HsRecFields rpats dd)) penv thing_inside
824   = do  { (rpats', res) <- tcMultiple tc_field rpats penv thing_inside
825         ; return (RecCon (HsRecFields rpats' dd), res) }
826   where
827     tc_field :: Checker (HsRecField FieldLabel (LPat Name)) (HsRecField TcId (LPat TcId))
828     tc_field (HsRecField field_lbl pat pun) penv thing_inside
829       = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
830            ; (pat', res) <- tcConArg (pat, pat_ty) penv thing_inside
831            ; return (HsRecField sel_id pat' pun, res) }
832
833     find_field_ty :: FieldLabel -> TcM (Id, TcType)
834     find_field_ty field_lbl
835         = case [ty | (f,ty) <- field_tys, f == field_lbl] of
836
837                 -- No matching field; chances are this field label comes from some
838                 -- other record type (or maybe none).  As well as reporting an
839                 -- error we still want to typecheck the pattern, principally to
840                 -- make sure that all the variables it binds are put into the
841                 -- environment, else the type checker crashes later:
842                 --      f (R { foo = (a,b) }) = a+b
843                 -- If foo isn't one of R's fields, we don't want to crash when
844                 -- typechecking the "a+b".
845            [] -> do { addErrTc (badFieldCon data_con field_lbl)
846                     ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
847                     ; return (error "Bogus selector Id", bogus_ty) }
848
849                 -- The normal case, when the field comes from the right constructor
850            (pat_ty : extras) -> 
851                 ASSERT( null extras )
852                 do { sel_id <- tcLookupField field_lbl
853                    ; return (sel_id, pat_ty) }
854
855     field_tys :: [(FieldLabel, TcType)]
856     field_tys = zip (dataConFieldLabels data_con) arg_tys
857         -- Don't use zipEqual! If the constructor isn't really a record, then
858         -- dataConFieldLabels will be empty (and each field in the pattern
859         -- will generate an error below).
860
861 tcConArg :: Checker (LPat Name, TcSigmaType) (LPat Id)
862 tcConArg (arg_pat, arg_ty) penv thing_inside
863   = tc_lpat arg_pat arg_ty penv thing_inside
864 \end{code}
865
866 \begin{code}
867 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
868 -- Instantiate the "stupid theta" of the data con, and throw 
869 -- the constraints into the constraint set
870 addDataConStupidTheta data_con inst_tys
871   | null stupid_theta = return ()
872   | otherwise         = instStupidTheta origin inst_theta
873   where
874     origin = OccurrenceOf (dataConName data_con)
875         -- The origin should always report "occurrence of C"
876         -- even when C occurs in a pattern
877     stupid_theta = dataConStupidTheta data_con
878     tenv = mkTopTvSubst (dataConUnivTyVars data_con `zip` inst_tys)
879          -- NB: inst_tys can be longer than the univ tyvars
880          --     because the constructor might have existentials
881     inst_theta = substTheta tenv stupid_theta
882 \end{code}
883
884 Note [Arrows and patterns]
885 ~~~~~~~~~~~~~~~~~~~~~~~~~~
886 (Oct 07) Arrow noation has the odd property that it involves 
887 "holes in the scope". For example:
888   expr :: Arrow a => a () Int
889   expr = proc (y,z) -> do
890           x <- term -< y
891           expr' -< x
892
893 Here the 'proc (y,z)' binding scopes over the arrow tails but not the
894 arrow body (e.g 'term').  As things stand (bogusly) all the
895 constraints from the proc body are gathered together, so constraints
896 from 'term' will be seen by the tcPat for (y,z).  But we must *not*
897 bind constraints from 'term' here, becuase the desugarer will not make
898 these bindings scope over 'term'.
899
900 The Right Thing is not to confuse these constraints together. But for
901 now the Easy Thing is to ensure that we do not have existential or
902 GADT constraints in a 'proc', and to short-cut the constraint
903 simplification for such vanilla patterns so that it binds no
904 constraints. Hence the 'fast path' in tcConPat; but it's also a good
905 plan for ordinary vanilla patterns to bypass the constraint
906 simplification step.
907
908 %************************************************************************
909 %*                                                                      *
910                 Note [Pattern coercions]
911 %*                                                                      *
912 %************************************************************************
913
914 In principle, these program would be reasonable:
915         
916         f :: (forall a. a->a) -> Int
917         f (x :: Int->Int) = x 3
918
919         g :: (forall a. [a]) -> Bool
920         g [] = True
921
922 In both cases, the function type signature restricts what arguments can be passed
923 in a call (to polymorphic ones).  The pattern type signature then instantiates this
924 type.  For example, in the first case,  (forall a. a->a) <= Int -> Int, and we
925 generate the translated term
926         f = \x' :: (forall a. a->a).  let x = x' Int in x 3
927
928 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
929 And it requires a significant amount of code to implement, becuase we need to decorate
930 the translated pattern with coercion functions (generated from the subsumption check 
931 by tcSub).  
932
933 So for now I'm just insisting on type *equality* in patterns.  No subsumption. 
934
935 Old notes about desugaring, at a time when pattern coercions were handled:
936
937 A SigPat is a type coercion and must be handled one at at time.  We can't
938 combine them unless the type of the pattern inside is identical, and we don't
939 bother to check for that.  For example:
940
941         data T = T1 Int | T2 Bool
942         f :: (forall a. a -> a) -> T -> t
943         f (g::Int->Int)   (T1 i) = T1 (g i)
944         f (g::Bool->Bool) (T2 b) = T2 (g b)
945
946 We desugar this as follows:
947
948         f = \ g::(forall a. a->a) t::T ->
949             let gi = g Int
950             in case t of { T1 i -> T1 (gi i)
951                            other ->
952             let gb = g Bool
953             in case t of { T2 b -> T2 (gb b)
954                            other -> fail }}
955
956 Note that we do not treat the first column of patterns as a
957 column of variables, because the coerced variables (gi, gb)
958 would be of different types.  So we get rather grotty code.
959 But I don't think this is a common case, and if it was we could
960 doubtless improve it.
961
962 Meanwhile, the strategy is:
963         * treat each SigPat coercion (always non-identity coercions)
964                 as a separate block
965         * deal with the stuff inside, and then wrap a binding round
966                 the result to bind the new variable (gi, gb, etc)
967
968
969 %************************************************************************
970 %*                                                                      *
971 \subsection{Errors and contexts}
972 %*                                                                      *
973 %************************************************************************
974
975 {-   This was used to improve the error message from 
976      an existential escape. Need to think how to do this.
977
978 sigPatCtxt :: [LPat Var] -> [Var] -> [TcType] -> TcType -> TidyEnv
979            -> TcM (TidyEnv, SDoc)
980 sigPatCtxt pats bound_tvs pat_tys body_ty tidy_env 
981   = do  { pat_tys' <- mapM zonkTcType pat_tys
982         ; body_ty' <- zonkTcType body_ty
983         ; let (env1,  tidy_tys)    = tidyOpenTypes tidy_env (map idType show_ids)
984               (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
985               (env3, tidy_body_ty) = tidyOpenType  env2 body_ty'
986         ; return (env3,
987                  sep [ptext (sLit "When checking an existential match that binds"),
988                       nest 2 (vcat (zipWith ppr_id show_ids tidy_tys)),
989                       ptext (sLit "The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
990                       ptext (sLit "The body has type:") <+> ppr tidy_body_ty
991                 ]) }
992   where
993     bound_ids = collectPatsBinders pats
994     show_ids = filter is_interesting bound_ids
995     is_interesting id = any (`elemVarSet` varTypeTyVars id) bound_tvs
996
997     ppr_id id ty = ppr id <+> dcolon <+> ppr ty
998         -- Don't zonk the types so we get the separate, un-unified versions
999 -}
1000
1001 \begin{code}
1002 patCtxt :: Pat Name -> Maybe Message    -- Not all patterns are worth pushing a context
1003 patCtxt (VarPat _)  = Nothing
1004 patCtxt (ParPat _)  = Nothing
1005 patCtxt (AsPat _ _) = Nothing
1006 patCtxt pat         = Just (hang (ptext (sLit "In the pattern:")) 
1007                          2 (ppr pat))
1008
1009 -----------------------------------------------
1010 checkExistentials :: [TyVar] -> PatEnv -> TcM ()
1011           -- See Note [Arrows and patterns]
1012 checkExistentials [] _                                 = return ()
1013 checkExistentials _ (PE { pe_ctxt = LetPat {}})        = failWithTc existentialLetPat
1014 checkExistentials _ (PE { pe_ctxt = LamPat ProcExpr }) = failWithTc existentialProcPat
1015 checkExistentials _ (PE { pe_lazy = True })            = failWithTc existentialLazyPat
1016 checkExistentials _ _                                  = return ()
1017
1018 existentialLazyPat :: SDoc
1019 existentialLazyPat
1020   = hang (ptext (sLit "An existential or GADT data constructor cannot be used"))
1021        2 (ptext (sLit "inside a lazy (~) pattern"))
1022
1023 existentialProcPat :: SDoc
1024 existentialProcPat 
1025   = ptext (sLit "Proc patterns cannot use existential or GADT data constructors")
1026
1027 existentialLetPat :: SDoc
1028 existentialLetPat
1029   = vcat [text "My brain just exploded",
1030           text "I can't handle pattern bindings for existential or GADT data constructors.",
1031           text "Instead, use a case-expression, or do-notation, to unpack the constructor."]
1032
1033 badFieldCon :: DataCon -> Name -> SDoc
1034 badFieldCon con field
1035   = hsep [ptext (sLit "Constructor") <+> quotes (ppr con),
1036           ptext (sLit "does not have field"), quotes (ppr field)]
1037
1038 polyPatSig :: TcType -> SDoc
1039 polyPatSig sig_ty
1040   = hang (ptext (sLit "Illegal polymorphic type signature in pattern:"))
1041        2 (ppr sig_ty)
1042
1043 badTypePat :: Pat Name -> SDoc
1044 badTypePat pat = ptext (sLit "Illegal type pattern") <+> ppr pat
1045
1046 lazyUnliftedPatErr :: OutputableBndr name => Pat name -> TcM ()
1047 lazyUnliftedPatErr pat
1048   = failWithTc $
1049     hang (ptext (sLit "A lazy (~) pattern cannot contain unlifted types:"))
1050        2 (ppr pat)
1051
1052 unboxedTupleErr :: SDoc -> Type -> SDoc
1053 unboxedTupleErr what ty
1054   = hang (what <+> ptext (sLit "cannot have an unboxed tuple type:"))
1055        2 (ppr ty)
1056 \end{code}