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