Merge branch 'master' of http://darcs.haskell.org/ghc into ghc-generics
[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 Util
40 import Outputable
41 import FastString
42 import Control.Monad
43 \end{code}
44
45
46 %************************************************************************
47 %*                                                                      *
48                 External interface
49 %*                                                                      *
50 %************************************************************************
51
52 \begin{code}
53 tcLetPat :: TcSigFun -> LetBndrSpec
54          -> LPat Name -> TcSigmaType 
55          -> TcM a
56          -> TcM (LPat TcId, a)
57 tcLetPat sig_fn no_gen pat pat_ty thing_inside
58   = tc_lpat pat pat_ty penv thing_inside 
59   where
60     penv = PE { pe_lazy = True
61               , pe_ctxt = LetPat sig_fn no_gen }
62
63 -----------------
64 tcPats :: HsMatchContext Name
65        -> [LPat Name]            -- Patterns,
66        -> [TcSigmaType]          --   and their types
67        -> TcM a                  --   and the checker for the body
68        -> TcM ([LPat TcId], a)
69
70 -- This is the externally-callable wrapper function
71 -- Typecheck the patterns, extend the environment to bind the variables,
72 -- do the thing inside, use any existentially-bound dictionaries to 
73 -- discharge parts of the returning LIE, and deal with pattern type
74 -- signatures
75
76 --   1. Initialise the PatState
77 --   2. Check the patterns
78 --   3. Check the body
79 --   4. Check that no existentials escape
80
81 tcPats ctxt pats pat_tys thing_inside
82   = tc_lpats penv pats pat_tys thing_inside
83   where
84     penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt }
85
86 tcPat :: HsMatchContext Name
87       -> LPat Name -> TcSigmaType 
88       -> TcM a                 -- Checker for body, given
89                                -- its result type
90       -> TcM (LPat TcId, a)
91 tcPat ctxt pat pat_ty thing_inside
92   = tc_lpat pat pat_ty penv thing_inside
93   where
94     penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt }
95    
96
97 -----------------
98 data PatEnv
99   = PE { pe_lazy :: Bool        -- True <=> lazy context, so no existentials allowed
100        , pe_ctxt :: PatCtxt     -- Context in which the whole pattern appears
101        }
102
103 data PatCtxt
104   = LamPat   -- Used for lambdas, case etc
105        (HsMatchContext Name) 
106
107   | LetPat   -- Used only for let(rec) bindings
108              -- See Note [Let binders]
109        TcSigFun        -- Tells type sig if any
110        LetBndrSpec     -- True <=> no generalisation of this let
111
112 data LetBndrSpec 
113   = LetLclBndr            -- The binder is just a local one;
114                           -- an AbsBinds will provide the global version
115
116   | LetGblBndr TcPragFun  -- There isn't going to be an AbsBinds;
117                           -- here is the inline-pragma information
118
119 makeLazy :: PatEnv -> PatEnv
120 makeLazy penv = penv { pe_lazy = True }
121
122 patSigCtxt :: PatEnv -> UserTypeCtxt
123 patSigCtxt (PE { pe_ctxt = LetPat {} }) = BindPatSigCtxt
124 patSigCtxt (PE { pe_ctxt = LamPat {} }) = LamPatSigCtxt
125
126 ---------------
127 type TcPragFun = Name -> [LSig Name]
128 type TcSigFun  = Name -> Maybe TcSigInfo
129
130 data TcSigInfo
131   = TcSigInfo {
132         sig_id     :: TcId,         --  *Polymorphic* binder for this value...
133
134         sig_scoped :: [Name],       -- Scoped type variables
135                 -- 1-1 correspondence with a prefix of sig_tvs
136                 -- However, may be fewer than sig_tvs; 
137                 -- see Note [More instantiated than scoped]
138         sig_tvs    :: [TcTyVar],    -- Instantiated type variables
139                                     -- See Note [Instantiate sig]
140
141         sig_theta  :: TcThetaType,  -- Instantiated theta
142
143         sig_tau    :: TcSigmaType,  -- Instantiated tau
144                                     -- See Note [sig_tau may be polymorphic]
145
146         sig_loc    :: SrcSpan       -- The location of the signature
147     }
148
149 instance Outputable TcSigInfo where
150     ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
151         = ppr id <+> ptext (sLit "::") <+> ppr tyvars <+> pprThetaArrowTy theta <+> ppr tau
152 \end{code}
153
154 Note [sig_tau may be polymorphic]
155 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
156 Note that "sig_tau" might actually be a polymorphic type,
157 if the original function had a signature like
158    forall a. Eq a => forall b. Ord b => ....
159 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
160 It happens, too!  See Note [Polymorphic methods] in TcClassDcl.
161
162 Note [Let binders]
163 ~~~~~~~~~~~~~~~~~~
164 eg   x :: Int
165      y :: Bool
166      (x,y) = e
167
168 ...more notes to add here..
169
170
171 Note [Existential check]
172 ~~~~~~~~~~~~~~~~~~~~~~~~
173 Lazy patterns can't bind existentials.  They arise in two ways:
174   * Let bindings      let { C a b = e } in b
175   * Twiddle patterns  f ~(C a b) = e
176 The pe_lazy field of PatEnv says whether we are inside a lazy
177 pattern (perhaps deeply)
178
179 If we aren't inside a lazy pattern then we can bind existentials,
180 but we need to be careful about "extra" tyvars. Consider
181     (\C x -> d) : pat_ty -> res_ty
182 When looking for existential escape we must check that the existential
183 bound by C don't unify with the free variables of pat_ty, OR res_ty
184 (or of course the environment).   Hence we need to keep track of the 
185 res_ty free vars.
186
187
188 %************************************************************************
189 %*                                                                      *
190                 Binders
191 %*                                                                      *
192 %************************************************************************
193
194 \begin{code}
195 tcPatBndr :: PatEnv -> Name -> TcSigmaType -> TcM (Coercion, TcId)
196 -- (coi, xp) = tcPatBndr penv x pat_ty
197 -- Then coi : pat_ty ~ typeof(xp)
198 --
199 tcPatBndr (PE { pe_ctxt = LetPat lookup_sig no_gen}) bndr_name pat_ty
200   | Just sig <- lookup_sig bndr_name
201   = do { bndr_id <- newSigLetBndr no_gen bndr_name sig
202        ; coi <- unifyPatType (idType bndr_id) pat_ty
203        ; return (coi, bndr_id) }
204       
205   | otherwise
206   = do { bndr_id <- newNoSigLetBndr no_gen bndr_name pat_ty
207        ; return (mkReflCo pat_ty, bndr_id) }
208
209 tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty
210   = do { bndr <- mkLocalBinder bndr_name pat_ty
211        ; return (mkReflCo pat_ty, bndr) }
212
213 ------------
214 newSigLetBndr :: LetBndrSpec -> Name -> TcSigInfo -> TcM TcId
215 newSigLetBndr LetLclBndr name sig
216   = do { mono_name <- newLocalName name
217        ; mkLocalBinder mono_name (sig_tau sig) }
218 newSigLetBndr (LetGblBndr prags) name sig
219   = addInlinePrags (sig_id sig) (prags name)
220
221 ------------
222 newNoSigLetBndr :: LetBndrSpec -> 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 newNoSigLetBndr LetLclBndr name ty 
229   =do  { mono_name <- newLocalName name
230        ; mkLocalBinder mono_name ty }
231 newNoSigLetBndr (LetGblBndr prags) name ty 
232   = do { id <- mkLocalBinder name ty
233        ; addInlinePrags id (prags name) }
234
235 ----------
236 addInlinePrags :: TcId -> [LSig Name] -> TcM TcId
237 addInlinePrags poly_id prags
238   = tc_inl inl_sigs
239   where
240     inl_sigs = filter isInlineLSig prags
241     tc_inl [] = return poly_id
242     tc_inl (L loc (InlineSig _ prag) : other_inls)
243        = do { unless (null other_inls) (setSrcSpan loc warn_dup_inline)
244             ; return (poly_id `setInlinePragma` prag) }
245     tc_inl _ = panic "tc_inl"
246
247     warn_dup_inline = warnPrags poly_id inl_sigs $
248                       ptext (sLit "Duplicate INLINE pragmas for")
249
250 warnPrags :: Id -> [LSig Name] -> SDoc -> TcM ()
251 warnPrags id bad_sigs herald
252   = addWarnTc (hang (herald <+> quotes (ppr id))
253                   2 (ppr_sigs bad_sigs))
254   where
255     ppr_sigs sigs = vcat (map (ppr . getLoc) sigs)
256
257 -----------------
258 mkLocalBinder :: Name -> TcType -> TcM TcId
259 mkLocalBinder name ty
260   = do { checkUnboxedTuple ty $ 
261             ptext (sLit "The variable") <+> quotes (ppr name)
262        ; return (Id.mkLocalId name ty) }
263
264 checkUnboxedTuple :: TcType -> SDoc -> TcM ()
265 -- Check for an unboxed tuple type
266 --      f = (# True, False #)
267 -- Zonk first just in case it's hidden inside a meta type variable
268 -- (This shows up as a (more obscure) kind error 
269 --  in the 'otherwise' case of tcMonoBinds.)
270 checkUnboxedTuple ty what
271   = do { zonked_ty <- zonkTcTypeCarefully ty
272        ; checkTc (not (isUnboxedTupleType zonked_ty))
273                  (unboxedTupleErr what zonked_ty) }
274
275 -------------------
276 {- Only needed if we re-add Method constraints 
277 bindInstsOfPatId :: TcId -> TcM a -> TcM (a, TcEvBinds)
278 bindInstsOfPatId id thing_inside
279   | not (isOverloadedTy (idType id))
280   = do { res <- thing_inside; return (res, emptyTcEvBinds) }
281   | otherwise
282   = do  { (res, lie) <- captureConstraints thing_inside
283         ; binds <- bindLocalMethods lie [id]
284         ; return (res, binds) }
285 -}
286 \end{code}
287
288 Note [Polymorphism and pattern bindings]
289 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
290 When is_mono holds we are not generalising
291 But the signature can still be polymoprhic!
292      data T = MkT (forall a. a->a)
293      x :: forall a. a->a
294      MkT x = <rhs>
295 So the no_gen flag decides whether the pattern-bound variables should
296 have exactly the type in the type signature (when not generalising) or
297 the instantiated version (when generalising)
298
299 %************************************************************************
300 %*                                                                      *
301                 The main worker functions
302 %*                                                                      *
303 %************************************************************************
304
305 Note [Nesting]
306 ~~~~~~~~~~~~~~
307 tcPat takes a "thing inside" over which the pattern scopes.  This is partly
308 so that tcPat can extend the environment for the thing_inside, but also 
309 so that constraints arising in the thing_inside can be discharged by the
310 pattern.
311
312 This does not work so well for the ErrCtxt carried by the monad: we don't
313 want the error-context for the pattern to scope over the RHS. 
314 Hence the getErrCtxt/setErrCtxt stuff in tcMultiple
315
316 \begin{code}
317 --------------------
318 type Checker inp out =  forall r.
319                           inp
320                        -> PatEnv
321                        -> TcM r
322                        -> TcM (out, r)
323
324 tcMultiple :: Checker inp out -> Checker [inp] [out]
325 tcMultiple tc_pat args penv thing_inside
326   = do  { err_ctxt <- getErrCtxt
327         ; let loop _ []
328                 = do { res <- thing_inside
329                      ; return ([], res) }
330
331               loop penv (arg:args)
332                 = do { (p', (ps', res)) 
333                                 <- tc_pat arg penv $ 
334                                    setErrCtxt err_ctxt $
335                                    loop penv args
336                 -- setErrCtxt: restore context before doing the next pattern
337                 -- See note [Nesting] above
338                                 
339                      ; return (p':ps', res) }
340
341         ; loop penv args }
342
343 --------------------
344 tc_lpat :: LPat Name 
345         -> TcSigmaType
346         -> PatEnv
347         -> TcM a
348         -> TcM (LPat TcId, a)
349 tc_lpat (L span pat) pat_ty penv thing_inside
350   = setSrcSpan span $
351     do  { (pat', res) <- maybeWrapPatCtxt pat (tc_pat penv pat pat_ty)
352                                           thing_inside
353         ; return (L span pat', res) }
354
355 tc_lpats :: PatEnv
356          -> [LPat Name] -> [TcSigmaType]
357          -> TcM a       
358          -> TcM ([LPat TcId], a)
359 tc_lpats penv pats tys thing_inside 
360   =  tcMultiple (\(p,t) -> tc_lpat p t) 
361                 (zipEqual "tc_lpats" pats tys)
362                 penv thing_inside 
363
364 --------------------
365 tc_pat  :: PatEnv
366         -> Pat Name 
367         -> TcSigmaType  -- Fully refined result type
368         -> TcM a                -- Thing inside
369         -> TcM (Pat TcId,       -- Translated pattern
370                 a)              -- Result of thing inside
371
372 tc_pat penv (VarPat name) pat_ty thing_inside
373   = do  { (coi, id) <- tcPatBndr penv name pat_ty
374         ; res <- tcExtendIdEnv1 name id thing_inside
375         ; return (mkHsWrapPatCo coi (VarPat id) pat_ty, res) }
376
377 tc_pat penv (ParPat pat) pat_ty thing_inside
378   = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
379         ; return (ParPat pat', res) }
380
381 tc_pat penv (BangPat pat) pat_ty thing_inside
382   = do  { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
383         ; return (BangPat pat', res) }
384
385 tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside
386   = do  { (pat', (res, pat_ct)) 
387                 <- tc_lpat pat pat_ty (makeLazy penv) $ 
388                    captureConstraints thing_inside
389                 -- Ignore refined penv', revert to penv
390
391         ; emitConstraints pat_ct
392         -- captureConstraints/extendConstraints: 
393         --   see Note [Hopping the LIE in lazy patterns]
394
395         -- Check there are no unlifted types under the lazy pattern
396         ; when (any (isUnLiftedType . idType) $ collectPatBinders pat') $
397                lazyUnliftedPatErr lpat
398
399         -- Check that the expected pattern type is itself lifted
400         ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
401         ; _ <- unifyType pat_ty pat_ty'
402
403         ; return (LazyPat pat', res) }
404
405 tc_pat _ p@(QuasiQuotePat _) _ _
406   = pprPanic "Should never see QuasiQuotePat in type checker" (ppr p)
407
408 tc_pat _ (WildPat _) pat_ty thing_inside
409   = do  { checkUnboxedTuple pat_ty $
410                ptext (sLit "A wild-card pattern")
411         ; res <- thing_inside 
412         ; return (WildPat pat_ty, res) }
413
414 tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
415   = do  { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
416         ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
417                          tc_lpat pat (idType bndr_id) penv thing_inside
418             -- NB: if we do inference on:
419             --          \ (y@(x::forall a. a->a)) = e
420             -- we'll fail.  The as-pattern infers a monotype for 'y', which then
421             -- fails to unify with the polymorphic type for 'x'.  This could 
422             -- perhaps be fixed, but only with a bit more work.
423             --
424             -- If you fix it, don't forget the bindInstsOfPatIds!
425         ; return (mkHsWrapPatCo coi (AsPat (L nm_loc bndr_id) pat') pat_ty, res) }
426
427 tc_pat penv vpat@(ViewPat expr pat _) overall_pat_ty thing_inside 
428   = do  { checkUnboxedTuple overall_pat_ty $
429                ptext (sLit "The view pattern") <+> ppr vpat
430
431          -- Morally, expr must have type `forall a1...aN. OPT' -> B` 
432          -- where overall_pat_ty is an instance of OPT'.
433          -- Here, we infer a rho type for it,
434          -- which replaces the leading foralls and constraints
435          -- with fresh unification variables.
436         ; (expr',expr'_inferred) <- tcInferRho expr
437
438          -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
439          -- NOTE: this forces pat_ty to be a monotype (because we use a unification 
440          -- variable to find it).  this means that in an example like
441          -- (view -> f)    where view :: _ -> forall b. b
442          -- we will only be able to use view at one instantation in the
443          -- rest of the view
444         ; (expr_coi, pat_ty) <- tcInfer $ \ pat_ty -> 
445                 unifyPatType expr'_inferred (mkFunTy overall_pat_ty pat_ty)
446
447          -- pattern must have pat_ty
448         ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside
449
450         ; return (ViewPat (mkLHsWrapCo expr_coi expr') pat' overall_pat_ty, res) }
451
452 -- Type signatures in patterns
453 -- See Note [Pattern coercions] below
454 tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
455   = do  { (inner_ty, tv_binds, wrap) <- tcPatSig (patSigCtxt penv) sig_ty pat_ty
456         ; (pat', res) <- tcExtendTyVarEnv2 tv_binds $
457                          tc_lpat pat inner_ty penv thing_inside
458
459         ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
460
461 ------------------------
462 -- Lists, tuples, arrays
463 tc_pat penv (ListPat pats _) pat_ty thing_inside
464   = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy pat_ty
465         ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
466                                      pats penv thing_inside
467         ; return (mkHsWrapPat coi (ListPat pats' elt_ty) pat_ty, res) 
468         }
469
470 tc_pat penv (PArrPat pats _) pat_ty thing_inside
471   = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTy pat_ty
472         ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
473                                      pats penv thing_inside 
474         ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
475         }
476
477 tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
478   = do  { let tc = tupleTyCon boxity (length pats)
479         ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc) pat_ty
480         ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
481
482         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
483         -- so that we can experiment with lazy tuple-matching.
484         -- This is a pretty odd place to make the switch, but
485         -- it was easy to do.
486         ; let pat_ty'          = mkTyConApp tc arg_tys
487                                      -- pat_ty /= pat_ty iff coi /= IdCo
488               unmangled_result = TuplePat pats' boxity pat_ty'
489               possibly_mangled_result
490                 | opt_IrrefutableTuples && 
491                   isBoxed boxity            = LazyPat (noLoc unmangled_result)
492                 | otherwise                 = unmangled_result
493
494         ; ASSERT( length arg_tys == length pats )      -- Syntactically enforced
495           return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
496         }
497
498 ------------------------
499 -- Data constructors
500 tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
501   = tcConPat penv con pat_ty arg_pats thing_inside
502
503 ------------------------
504 -- Literal patterns
505 tc_pat _ (LitPat simple_lit) pat_ty thing_inside
506   = do  { let lit_ty = hsLitType simple_lit
507         ; coi <- unifyPatType lit_ty pat_ty
508                 -- coi is of kind: pat_ty ~ lit_ty
509         ; res <- thing_inside 
510         ; return ( mkHsWrapPatCo coi (LitPat simple_lit) pat_ty 
511                  , res) }
512
513 ------------------------
514 -- Overloaded patterns: n, and n+k
515 tc_pat _ (NPat over_lit mb_neg eq) pat_ty thing_inside
516   = do  { let orig = LiteralOrigin over_lit
517         ; lit'    <- newOverloadedLit orig over_lit pat_ty
518         ; eq'     <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
519         ; mb_neg' <- case mb_neg of
520                         Nothing  -> return Nothing      -- Positive literal
521                         Just neg ->     -- Negative literal
522                                         -- The 'negate' is re-mappable syntax
523                             do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
524                                ; return (Just neg') }
525         ; res <- thing_inside 
526         ; return (NPat lit' mb_neg' eq', res) }
527
528 tc_pat penv (NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
529   = do  { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
530         ; let pat_ty' = idType bndr_id
531               orig    = LiteralOrigin lit
532         ; lit' <- newOverloadedLit orig lit pat_ty'
533
534         -- The '>=' and '-' parts are re-mappable syntax
535         ; ge'    <- tcSyntaxOp orig ge    (mkFunTys [pat_ty', pat_ty'] boolTy)
536         ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
537         ; let pat' = NPlusKPat (L nm_loc bndr_id) lit' ge' minus'
538
539         -- The Report says that n+k patterns must be in Integral
540         -- We may not want this when using re-mappable syntax, though (ToDo?)
541         ; icls <- tcLookupClass integralClassName
542         ; instStupidTheta orig [mkClassPred icls [pat_ty']]     
543     
544         ; res <- tcExtendIdEnv1 name bndr_id thing_inside
545         ; return (mkHsWrapPatCo coi pat' pat_ty, res) }
546
547 tc_pat _ _other_pat _ _ = panic "tc_pat"        -- ConPatOut, SigPatOut
548
549 ----------------
550 unifyPatType :: TcType -> TcType -> TcM Coercion
551 -- In patterns we want a coercion from the
552 -- context type (expected) to the actual pattern type
553 -- But we don't want to reverse the args to unifyType because
554 -- that controls the actual/expected stuff in error messages
555 unifyPatType actual_ty expected_ty
556   = do { coi <- unifyType actual_ty expected_ty
557        ; return (mkSymCo coi) }
558 \end{code}
559
560 Note [Hopping the LIE in lazy patterns]
561 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
562 In a lazy pattern, we must *not* discharge constraints from the RHS
563 from dictionaries bound in the pattern.  E.g.
564         f ~(C x) = 3
565 We can't discharge the Num constraint from dictionaries bound by
566 the pattern C!  
567
568 So we have to make the constraints from thing_inside "hop around" 
569 the pattern.  Hence the captureConstraints and emitConstraints.
570
571 The same thing ensures that equality constraints in a lazy match
572 are not made available in the RHS of the match. For example
573         data T a where { T1 :: Int -> T Int; ... }
574         f :: T a -> Int -> a
575         f ~(T1 i) y = y
576 It's obviously not sound to refine a to Int in the right
577 hand side, because the arugment might not match T1 at all!
578
579 Finally, a lazy pattern should not bind any existential type variables
580 because they won't be in scope when we do the desugaring
581
582
583 %************************************************************************
584 %*                                                                      *
585         Most of the work for constructors is here
586         (the rest is in the ConPatIn case of tc_pat)
587 %*                                                                      *
588 %************************************************************************
589
590 [Pattern matching indexed data types]
591 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
592 Consider the following declarations:
593
594   data family Map k :: * -> *
595   data instance Map (a, b) v = MapPair (Map a (Pair b v))
596
597 and a case expression
598
599   case x :: Map (Int, c) w of MapPair m -> ...
600
601 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
602 worker/wrapper types for MapPair are
603
604   $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
605   $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
606
607 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
608 :R123Map, which means the straight use of boxySplitTyConApp would give a type
609 error.  Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
610 boxySplitTyConApp with the family tycon Map instead, which gives us the family
611 type list {(Int, c), w}.  To get the correct split for :R123Map, we need to
612 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
613 (provided by tyConFamInst_maybe together with the family tycon).  This
614 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
615 the split arguments for the representation tycon :R123Map as {Int, c, w}
616
617 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion 
618
619   Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
620
621 moving between representation and family type into account.  To produce type
622 correct Core, this coercion needs to be used to case the type of the scrutinee
623 from the family to the representation type.  This is achieved by
624 unwrapFamInstScrutinee using a CoPat around the result pattern.
625
626 Now it might appear seem as if we could have used the previous GADT type
627 refinement infrastructure of refineAlt and friends instead of the explicit
628 unification and CoPat generation.  However, that would be wrong.  Why?  The
629 whole point of GADT refinement is that the refinement is local to the case
630 alternative.  In contrast, the substitution generated by the unification of
631 the family type list and instance types needs to be propagated to the outside.
632 Imagine that in the above example, the type of the scrutinee would have been
633 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
634 substitution [x -> (a, b), v -> w].  In contrast to GADT matching, the
635 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
636 alternatives of the case expression, whereas in the GADT case it might vary
637 between alternatives.
638
639 RIP GADT refinement: refinements have been replaced by the use of explicit
640 equality constraints that are used in conjunction with implication constraints
641 to express the local scope of GADT refinements.
642
643 \begin{code}
644 --      Running example:
645 -- MkT :: forall a b c. (a~[b]) => b -> c -> T a
646 --       with scrutinee of type (T ty)
647
648 tcConPat :: PatEnv -> Located Name 
649          -> TcRhoType           -- Type of the pattern
650          -> HsConPatDetails Name -> TcM a
651          -> TcM (Pat TcId, a)
652 tcConPat penv (L con_span con_name) pat_ty arg_pats thing_inside
653   = do  { data_con <- tcLookupDataCon con_name
654         ; let tycon = dataConTyCon data_con
655                   -- For data families this is the representation tycon
656               (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _)
657                 = dataConFullSig data_con
658
659           -- Instantiate the constructor type variables [a->ty]
660           -- This may involve doing a family-instance coercion, 
661           -- and building a wrapper 
662         ; (wrap, ctxt_res_tys) <- matchExpectedPatTy (matchExpectedConTy tycon) pat_ty
663
664           -- Add the stupid theta
665         ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
666
667         ; checkExistentials ex_tvs penv 
668         ; ex_tvs' <- tcInstSuperSkolTyVars ex_tvs
669                      -- Get location from monad, not from ex_tvs
670
671         ; let pat_ty' = mkTyConApp tycon ctxt_res_tys
672               -- pat_ty' is type of the actual constructor application
673               -- pat_ty' /= pat_ty iff coi /= IdCo
674               
675               tenv     = zipTopTvSubst (univ_tvs     ++ ex_tvs)
676                                        (ctxt_res_tys ++ mkTyVarTys ex_tvs')
677               arg_tys' = substTys tenv arg_tys
678
679         ; if null ex_tvs && null eq_spec && null theta
680           then do { -- The common case; no class bindings etc 
681                     -- (see Note [Arrows and patterns])
682                     (arg_pats', res) <- tcConArgs data_con arg_tys' 
683                                                   arg_pats penv thing_inside
684                   ; let res_pat = ConPatOut { pat_con = L con_span data_con, 
685                                               pat_tvs = [], pat_dicts = [], 
686                                               pat_binds = emptyTcEvBinds,
687                                               pat_args = arg_pats', 
688                                               pat_ty = pat_ty' }
689
690                   ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
691
692           else do   -- The general case, with existential, 
693                     -- and local equality constraints
694         { let theta'   = substTheta tenv (eqSpecPreds eq_spec ++ theta)
695                            -- order is *important* as we generate the list of
696                            -- dictionary binders from theta'
697               no_equalities = not (any isEqPred theta')
698               skol_info = case pe_ctxt penv of
699                             LamPat mc -> PatSkol data_con mc
700                             LetPat {} -> UnkSkol -- Doesn't matter
701  
702         ; gadts_on <- xoptM Opt_GADTs
703         ; checkTc (no_equalities || gadts_on)
704                   (ptext (sLit "A pattern match on a GADT requires -XGADTs"))
705                   -- Trac #2905 decided that a *pattern-match* of a GADT
706                   -- should require the GADT language flag
707
708         ; given <- newEvVars theta'
709         ; (ev_binds, (arg_pats', res))
710              <- checkConstraints skol_info ex_tvs' given $
711                 tcConArgs data_con arg_tys' arg_pats penv thing_inside
712
713         ; let res_pat = ConPatOut { pat_con   = L con_span data_con, 
714                                     pat_tvs   = ex_tvs',
715                                     pat_dicts = given,
716                                     pat_binds = ev_binds,
717                                     pat_args  = arg_pats', 
718                                     pat_ty    = pat_ty' }
719         ; return (mkHsWrapPat wrap res_pat pat_ty, res)
720         } }
721
722 ----------------------------
723 matchExpectedPatTy :: (TcRhoType -> TcM (Coercion, a))
724                     -> TcRhoType -> TcM (HsWrapper, a) 
725 -- See Note [Matching polytyped patterns]
726 -- Returns a wrapper : pat_ty ~ inner_ty
727 matchExpectedPatTy inner_match pat_ty
728   | null tvs && null theta
729   = do { (coi, res) <- inner_match pat_ty
730        ; return (coToHsWrapper (mkSymCo coi), res) }
731          -- The Sym is because the inner_match returns a coercion
732          -- that is the other way round to matchExpectedPatTy
733
734   | otherwise
735   = do { (_, tys, subst) <- tcInstTyVars tvs
736        ; wrap1 <- instCall PatOrigin tys (substTheta subst theta)
737        ; (wrap2, arg_tys) <- matchExpectedPatTy inner_match (TcType.substTy subst tau)
738        ; return (wrap2 <.> wrap1 , arg_tys) }
739   where
740     (tvs, theta, tau) = tcSplitSigmaTy pat_ty
741
742 ----------------------------
743 matchExpectedConTy :: TyCon      -- The TyCon that this data 
744                                  -- constructor actually returns
745                    -> TcRhoType  -- The type of the pattern
746                    -> TcM (Coercion, [TcSigmaType])
747 -- See Note [Matching constructor patterns]
748 -- Returns a coercion : T ty1 ... tyn ~ pat_ty
749 -- This is the same way round as matchExpectedListTy etc
750 -- but the other way round to matchExpectedPatTy
751 matchExpectedConTy data_tc pat_ty
752   | Just (fam_tc, fam_args, co_tc) <- tyConFamInstSig_maybe data_tc
753          -- Comments refer to Note [Matching constructor patterns]
754          -- co_tc :: forall a. T [a] ~ T7 a
755   = do { (_, tys, subst) <- tcInstTyVars (tyConTyVars data_tc)
756              -- tys = [ty1,ty2]
757
758        ; coi1 <- unifyType (mkTyConApp fam_tc (substTys subst fam_args)) pat_ty
759              -- coi1 : T (ty1,ty2) ~ pat_ty
760
761        ; let coi2 = mkAxInstCo co_tc tys
762              -- coi2 : T (ty1,ty2) ~ T7 ty1 ty2
763
764        ; return (mkTransCo (mkSymCo coi2) coi1, tys) }
765
766   | otherwise
767   = matchExpectedTyConApp data_tc pat_ty
768              -- coi : T tys ~ pat_ty
769 \end{code}
770
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 maybeWrapPatCtxt :: Pat Name -> (TcM a -> TcM b) -> TcM a -> TcM b
1003 -- Not all patterns are worth pushing a context
1004 maybeWrapPatCtxt pat tcm thing_inside 
1005   | not (worth_wrapping pat) = tcm thing_inside
1006   | otherwise                = addErrCtxt msg $ tcm $ popErrCtxt thing_inside
1007                                -- Remember to pop before doing thing_inside
1008   where
1009    worth_wrapping (VarPat {}) = False
1010    worth_wrapping (ParPat {}) = False
1011    worth_wrapping (AsPat {})  = False
1012    worth_wrapping _           = True
1013    msg = hang (ptext (sLit "In the pattern:")) 2 (ppr pat)
1014
1015 -----------------------------------------------
1016 checkExistentials :: [TyVar] -> PatEnv -> TcM ()
1017           -- See Note [Arrows and patterns]
1018 checkExistentials [] _                                 = return ()
1019 checkExistentials _ (PE { pe_ctxt = LetPat {}})        = failWithTc existentialLetPat
1020 checkExistentials _ (PE { pe_ctxt = LamPat ProcExpr }) = failWithTc existentialProcPat
1021 checkExistentials _ (PE { pe_lazy = True })            = failWithTc existentialLazyPat
1022 checkExistentials _ _                                  = return ()
1023
1024 existentialLazyPat :: SDoc
1025 existentialLazyPat
1026   = hang (ptext (sLit "An existential or GADT data constructor cannot be used"))
1027        2 (ptext (sLit "inside a lazy (~) pattern"))
1028
1029 existentialProcPat :: SDoc
1030 existentialProcPat 
1031   = ptext (sLit "Proc patterns cannot use existential or GADT data constructors")
1032
1033 existentialLetPat :: SDoc
1034 existentialLetPat
1035   = vcat [text "My brain just exploded",
1036           text "I can't handle pattern bindings for existential or GADT data constructors.",
1037           text "Instead, use a case-expression, or do-notation, to unpack the constructor."]
1038
1039 badFieldCon :: DataCon -> Name -> SDoc
1040 badFieldCon con field
1041   = hsep [ptext (sLit "Constructor") <+> quotes (ppr con),
1042           ptext (sLit "does not have field"), quotes (ppr field)]
1043
1044 polyPatSig :: TcType -> SDoc
1045 polyPatSig sig_ty
1046   = hang (ptext (sLit "Illegal polymorphic type signature in pattern:"))
1047        2 (ppr sig_ty)
1048
1049 lazyUnliftedPatErr :: OutputableBndr name => Pat name -> TcM ()
1050 lazyUnliftedPatErr pat
1051   = failWithTc $
1052     hang (ptext (sLit "A lazy (~) pattern cannot contain unlifted types:"))
1053        2 (ppr pat)
1054
1055 unboxedTupleErr :: SDoc -> Type -> SDoc
1056 unboxedTupleErr what ty
1057   = hang (what <+> ptext (sLit "cannot have an unboxed tuple type:"))
1058        2 (ppr ty)
1059 \end{code}