Merge master into the ghc-new-co branch
[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 tc_pat _ pat@(TypePat _) _ _
462   = failWithTc (badTypePat pat)
463
464 ------------------------
465 -- Lists, tuples, arrays
466 tc_pat penv (ListPat pats _) pat_ty thing_inside
467   = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTy pat_ty
468         ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
469                                      pats penv thing_inside
470         ; return (mkHsWrapPat coi (ListPat pats' elt_ty) pat_ty, res) 
471         }
472
473 tc_pat penv (PArrPat pats _) pat_ty thing_inside
474   = do  { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTy pat_ty
475         ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
476                                      pats penv thing_inside 
477         ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
478         }
479
480 tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
481   = do  { let tc = tupleTyCon boxity (length pats)
482         ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConApp tc) pat_ty
483         ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
484
485         -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
486         -- so that we can experiment with lazy tuple-matching.
487         -- This is a pretty odd place to make the switch, but
488         -- it was easy to do.
489         ; let pat_ty'          = mkTyConApp tc arg_tys
490                                      -- pat_ty /= pat_ty iff coi /= IdCo
491               unmangled_result = TuplePat pats' boxity pat_ty'
492               possibly_mangled_result
493                 | opt_IrrefutableTuples && 
494                   isBoxed boxity            = LazyPat (noLoc unmangled_result)
495                 | otherwise                 = unmangled_result
496
497         ; ASSERT( length arg_tys == length pats )      -- Syntactically enforced
498           return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
499         }
500
501 ------------------------
502 -- Data constructors
503 tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
504   = tcConPat penv con pat_ty arg_pats thing_inside
505
506 ------------------------
507 -- Literal patterns
508 tc_pat _ (LitPat simple_lit) pat_ty thing_inside
509   = do  { let lit_ty = hsLitType simple_lit
510         ; coi <- unifyPatType lit_ty pat_ty
511                 -- coi is of kind: pat_ty ~ lit_ty
512         ; res <- thing_inside 
513         ; return ( mkHsWrapPatCo coi (LitPat simple_lit) pat_ty 
514                  , res) }
515
516 ------------------------
517 -- Overloaded patterns: n, and n+k
518 tc_pat _ (NPat over_lit mb_neg eq) pat_ty thing_inside
519   = do  { let orig = LiteralOrigin over_lit
520         ; lit'    <- newOverloadedLit orig over_lit pat_ty
521         ; eq'     <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
522         ; mb_neg' <- case mb_neg of
523                         Nothing  -> return Nothing      -- Positive literal
524                         Just neg ->     -- Negative literal
525                                         -- The 'negate' is re-mappable syntax
526                             do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
527                                ; return (Just neg') }
528         ; res <- thing_inside 
529         ; return (NPat lit' mb_neg' eq', res) }
530
531 tc_pat penv (NPlusKPat (L nm_loc name) lit ge minus) pat_ty thing_inside
532   = do  { (coi, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
533         ; let pat_ty' = idType bndr_id
534               orig    = LiteralOrigin lit
535         ; lit' <- newOverloadedLit orig lit pat_ty'
536
537         -- The '>=' and '-' parts are re-mappable syntax
538         ; ge'    <- tcSyntaxOp orig ge    (mkFunTys [pat_ty', pat_ty'] boolTy)
539         ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
540         ; let pat' = NPlusKPat (L nm_loc bndr_id) lit' ge' minus'
541
542         -- The Report says that n+k patterns must be in Integral
543         -- We may not want this when using re-mappable syntax, though (ToDo?)
544         ; icls <- tcLookupClass integralClassName
545         ; instStupidTheta orig [mkClassPred icls [pat_ty']]     
546     
547         ; res <- tcExtendIdEnv1 name bndr_id thing_inside
548         ; return (mkHsWrapPatCo coi pat' pat_ty, res) }
549
550 tc_pat _ _other_pat _ _ = panic "tc_pat"        -- ConPatOut, SigPatOut
551
552 ----------------
553 unifyPatType :: TcType -> TcType -> TcM Coercion
554 -- In patterns we want a coercion from the
555 -- context type (expected) to the actual pattern type
556 -- But we don't want to reverse the args to unifyType because
557 -- that controls the actual/expected stuff in error messages
558 unifyPatType actual_ty expected_ty
559   = do { coi <- unifyType actual_ty expected_ty
560        ; return (mkSymCo coi) }
561 \end{code}
562
563 Note [Hopping the LIE in lazy patterns]
564 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
565 In a lazy pattern, we must *not* discharge constraints from the RHS
566 from dictionaries bound in the pattern.  E.g.
567         f ~(C x) = 3
568 We can't discharge the Num constraint from dictionaries bound by
569 the pattern C!  
570
571 So we have to make the constraints from thing_inside "hop around" 
572 the pattern.  Hence the captureConstraints and emitConstraints.
573
574 The same thing ensures that equality constraints in a lazy match
575 are not made available in the RHS of the match. For example
576         data T a where { T1 :: Int -> T Int; ... }
577         f :: T a -> Int -> a
578         f ~(T1 i) y = y
579 It's obviously not sound to refine a to Int in the right
580 hand side, because the arugment might not match T1 at all!
581
582 Finally, a lazy pattern should not bind any existential type variables
583 because they won't be in scope when we do the desugaring
584
585
586 %************************************************************************
587 %*                                                                      *
588         Most of the work for constructors is here
589         (the rest is in the ConPatIn case of tc_pat)
590 %*                                                                      *
591 %************************************************************************
592
593 [Pattern matching indexed data types]
594 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
595 Consider the following declarations:
596
597   data family Map k :: * -> *
598   data instance Map (a, b) v = MapPair (Map a (Pair b v))
599
600 and a case expression
601
602   case x :: Map (Int, c) w of MapPair m -> ...
603
604 As explained by [Wrappers for data instance tycons] in MkIds.lhs, the
605 worker/wrapper types for MapPair are
606
607   $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
608   $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
609
610 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
611 :R123Map, which means the straight use of boxySplitTyConApp would give a type
612 error.  Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
613 boxySplitTyConApp with the family tycon Map instead, which gives us the family
614 type list {(Int, c), w}.  To get the correct split for :R123Map, we need to
615 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
616 (provided by tyConFamInst_maybe together with the family tycon).  This
617 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
618 the split arguments for the representation tycon :R123Map as {Int, c, w}
619
620 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion 
621
622   Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
623
624 moving between representation and family type into account.  To produce type
625 correct Core, this coercion needs to be used to case the type of the scrutinee
626 from the family to the representation type.  This is achieved by
627 unwrapFamInstScrutinee using a CoPat around the result pattern.
628
629 Now it might appear seem as if we could have used the previous GADT type
630 refinement infrastructure of refineAlt and friends instead of the explicit
631 unification and CoPat generation.  However, that would be wrong.  Why?  The
632 whole point of GADT refinement is that the refinement is local to the case
633 alternative.  In contrast, the substitution generated by the unification of
634 the family type list and instance types needs to be propagated to the outside.
635 Imagine that in the above example, the type of the scrutinee would have been
636 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
637 substitution [x -> (a, b), v -> w].  In contrast to GADT matching, the
638 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
639 alternatives of the case expression, whereas in the GADT case it might vary
640 between alternatives.
641
642 RIP GADT refinement: refinements have been replaced by the use of explicit
643 equality constraints that are used in conjunction with implication constraints
644 to express the local scope of GADT refinements.
645
646 \begin{code}
647 --      Running example:
648 -- MkT :: forall a b c. (a~[b]) => b -> c -> T a
649 --       with scrutinee of type (T ty)
650
651 tcConPat :: PatEnv -> Located Name 
652          -> TcRhoType           -- Type of the pattern
653          -> HsConPatDetails Name -> TcM a
654          -> TcM (Pat TcId, a)
655 tcConPat penv (L con_span con_name) pat_ty arg_pats thing_inside
656   = do  { data_con <- tcLookupDataCon con_name
657         ; let tycon = dataConTyCon data_con
658                   -- For data families this is the representation tycon
659               (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _)
660                 = dataConFullSig data_con
661
662           -- Instantiate the constructor type variables [a->ty]
663           -- This may involve doing a family-instance coercion, 
664           -- and building a wrapper 
665         ; (wrap, ctxt_res_tys) <- matchExpectedPatTy (matchExpectedConTy tycon) pat_ty
666
667           -- Add the stupid theta
668         ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
669
670         ; checkExistentials ex_tvs penv 
671         ; ex_tvs' <- tcInstSuperSkolTyVars ex_tvs
672                      -- Get location from monad, not from ex_tvs
673
674         ; let pat_ty' = mkTyConApp tycon ctxt_res_tys
675               -- pat_ty' is type of the actual constructor application
676               -- pat_ty' /= pat_ty iff coi /= IdCo
677               
678               tenv     = zipTopTvSubst (univ_tvs     ++ ex_tvs)
679                                        (ctxt_res_tys ++ mkTyVarTys ex_tvs')
680               arg_tys' = substTys tenv arg_tys
681
682         ; if null ex_tvs && null eq_spec && null theta
683           then do { -- The common case; no class bindings etc 
684                     -- (see Note [Arrows and patterns])
685                     (arg_pats', res) <- tcConArgs data_con arg_tys' 
686                                                   arg_pats penv thing_inside
687                   ; let res_pat = ConPatOut { pat_con = L con_span data_con, 
688                                               pat_tvs = [], pat_dicts = [], 
689                                               pat_binds = emptyTcEvBinds,
690                                               pat_args = arg_pats', 
691                                               pat_ty = pat_ty' }
692
693                   ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
694
695           else do   -- The general case, with existential, 
696                     -- and local equality constraints
697         { let theta'   = substTheta tenv (eqSpecPreds eq_spec ++ theta)
698                            -- order is *important* as we generate the list of
699                            -- dictionary binders from theta'
700               no_equalities = not (any isEqPred theta')
701               skol_info = case pe_ctxt penv of
702                             LamPat mc -> PatSkol data_con mc
703                             LetPat {} -> UnkSkol -- Doesn't matter
704  
705         ; gadts_on <- xoptM Opt_GADTs
706         ; checkTc (no_equalities || gadts_on)
707                   (ptext (sLit "A pattern match on a GADT requires -XGADTs"))
708                   -- Trac #2905 decided that a *pattern-match* of a GADT
709                   -- should require the GADT language flag
710
711         ; given <- newEvVars theta'
712         ; (ev_binds, (arg_pats', res))
713              <- checkConstraints skol_info ex_tvs' given $
714                 tcConArgs data_con arg_tys' arg_pats penv thing_inside
715
716         ; let res_pat = ConPatOut { pat_con   = L con_span data_con, 
717                                     pat_tvs   = ex_tvs',
718                                     pat_dicts = given,
719                                     pat_binds = ev_binds,
720                                     pat_args  = arg_pats', 
721                                     pat_ty    = pat_ty' }
722         ; return (mkHsWrapPat wrap res_pat pat_ty, res)
723         } }
724
725 ----------------------------
726 matchExpectedPatTy :: (TcRhoType -> TcM (Coercion, a))
727                     -> TcRhoType -> TcM (HsWrapper, a) 
728 -- See Note [Matching polytyped patterns]
729 -- Returns a wrapper : pat_ty ~ inner_ty
730 matchExpectedPatTy inner_match pat_ty
731   | null tvs && null theta
732   = do { (coi, res) <- inner_match pat_ty
733        ; return (coToHsWrapper (mkSymCo coi), res) }
734          -- The Sym is because the inner_match returns a coercion
735          -- that is the other way round to matchExpectedPatTy
736
737   | otherwise
738   = do { (_, tys, subst) <- tcInstTyVars tvs
739        ; wrap1 <- instCall PatOrigin tys (substTheta subst theta)
740        ; (wrap2, arg_tys) <- matchExpectedPatTy inner_match (TcType.substTy subst tau)
741        ; return (wrap2 <.> wrap1 , arg_tys) }
742   where
743     (tvs, theta, tau) = tcSplitSigmaTy pat_ty
744
745 ----------------------------
746 matchExpectedConTy :: TyCon      -- The TyCon that this data 
747                                  -- constructor actually returns
748                    -> TcRhoType  -- The type of the pattern
749                    -> TcM (Coercion, [TcSigmaType])
750 -- See Note [Matching constructor patterns]
751 -- Returns a coercion : T ty1 ... tyn ~ pat_ty
752 -- This is the same way round as matchExpectedListTy etc
753 -- but the other way round to matchExpectedPatTy
754 matchExpectedConTy data_tc pat_ty
755   | Just (fam_tc, fam_args, co_tc) <- tyConFamInstSig_maybe data_tc
756          -- Comments refer to Note [Matching constructor patterns]
757          -- co_tc :: forall a. T [a] ~ T7 a
758   = do { (_, tys, subst) <- tcInstTyVars (tyConTyVars data_tc)
759              -- tys = [ty1,ty2]
760
761        ; coi1 <- unifyType (mkTyConApp fam_tc (substTys subst fam_args)) pat_ty
762              -- coi1 : T (ty1,ty2) ~ pat_ty
763
764        ; let coi2 = mkAxInstCo co_tc tys
765              -- coi2 : T (ty1,ty2) ~ T7 ty1 ty2
766
767        ; return (mkTransCo (mkSymCo coi2) coi1, tys) }
768
769   | otherwise
770   = matchExpectedTyConApp data_tc pat_ty
771              -- coi : T tys ~ pat_ty
772 \end{code}
773
774 Note [Matching constructor patterns]
775 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
776 Suppose (coi, tys) = matchExpectedConType data_tc pat_ty
777
778  * In the simple case, pat_ty = tc tys
779
780  * If pat_ty is a polytype, we want to instantiate it
781    This is like part of a subsumption check.  Eg
782       f :: (forall a. [a]) -> blah
783       f [] = blah
784
785  * In a type family case, suppose we have
786           data family T a
787           data instance T (p,q) = A p | B q
788        Then we'll have internally generated
789               data T7 p q = A p | B q
790               axiom coT7 p q :: T (p,q) ~ T7 p q
791  
792        So if pat_ty = T (ty1,ty2), we return (coi, [ty1,ty2]) such that
793            coi = coi2 . coi1 : T7 t ~ pat_ty
794            coi1 : T (ty1,ty2) ~ pat_ty
795            coi2 : T7 ty1 ty2 ~ T (ty1,ty2)
796
797    For families we do all this matching here, not in the unifier,
798    because we never want a whisper of the data_tycon to appear in
799    error messages; it's a purely internal thing
800
801 \begin{code}
802 tcConArgs :: DataCon -> [TcSigmaType]
803           -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
804
805 tcConArgs data_con arg_tys (PrefixCon arg_pats) penv thing_inside
806   = do  { checkTc (con_arity == no_of_args)     -- Check correct arity
807                   (arityErr "Constructor" data_con con_arity no_of_args)
808         ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
809         ; (arg_pats', res) <- tcMultiple tcConArg pats_w_tys
810                                               penv thing_inside 
811         ; return (PrefixCon arg_pats', res) }
812   where
813     con_arity  = dataConSourceArity data_con
814     no_of_args = length arg_pats
815
816 tcConArgs data_con arg_tys (InfixCon p1 p2) penv thing_inside
817   = do  { checkTc (con_arity == 2)      -- Check correct arity
818                   (arityErr "Constructor" data_con con_arity 2)
819         ; let [arg_ty1,arg_ty2] = arg_tys       -- This can't fail after the arity check
820         ; ([p1',p2'], res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
821                                               penv thing_inside
822         ; return (InfixCon p1' p2', res) }
823   where
824     con_arity  = dataConSourceArity data_con
825
826 tcConArgs data_con arg_tys (RecCon (HsRecFields rpats dd)) penv thing_inside
827   = do  { (rpats', res) <- tcMultiple tc_field rpats penv thing_inside
828         ; return (RecCon (HsRecFields rpats' dd), res) }
829   where
830     tc_field :: Checker (HsRecField FieldLabel (LPat Name)) (HsRecField TcId (LPat TcId))
831     tc_field (HsRecField field_lbl pat pun) penv thing_inside
832       = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
833            ; (pat', res) <- tcConArg (pat, pat_ty) penv thing_inside
834            ; return (HsRecField sel_id pat' pun, res) }
835
836     find_field_ty :: FieldLabel -> TcM (Id, TcType)
837     find_field_ty field_lbl
838         = case [ty | (f,ty) <- field_tys, f == field_lbl] of
839
840                 -- No matching field; chances are this field label comes from some
841                 -- other record type (or maybe none).  As well as reporting an
842                 -- error we still want to typecheck the pattern, principally to
843                 -- make sure that all the variables it binds are put into the
844                 -- environment, else the type checker crashes later:
845                 --      f (R { foo = (a,b) }) = a+b
846                 -- If foo isn't one of R's fields, we don't want to crash when
847                 -- typechecking the "a+b".
848            [] -> do { addErrTc (badFieldCon data_con field_lbl)
849                     ; bogus_ty <- newFlexiTyVarTy liftedTypeKind
850                     ; return (error "Bogus selector Id", bogus_ty) }
851
852                 -- The normal case, when the field comes from the right constructor
853            (pat_ty : extras) -> 
854                 ASSERT( null extras )
855                 do { sel_id <- tcLookupField field_lbl
856                    ; return (sel_id, pat_ty) }
857
858     field_tys :: [(FieldLabel, TcType)]
859     field_tys = zip (dataConFieldLabels data_con) arg_tys
860         -- Don't use zipEqual! If the constructor isn't really a record, then
861         -- dataConFieldLabels will be empty (and each field in the pattern
862         -- will generate an error below).
863
864 tcConArg :: Checker (LPat Name, TcSigmaType) (LPat Id)
865 tcConArg (arg_pat, arg_ty) penv thing_inside
866   = tc_lpat arg_pat arg_ty penv thing_inside
867 \end{code}
868
869 \begin{code}
870 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
871 -- Instantiate the "stupid theta" of the data con, and throw 
872 -- the constraints into the constraint set
873 addDataConStupidTheta data_con inst_tys
874   | null stupid_theta = return ()
875   | otherwise         = instStupidTheta origin inst_theta
876   where
877     origin = OccurrenceOf (dataConName data_con)
878         -- The origin should always report "occurrence of C"
879         -- even when C occurs in a pattern
880     stupid_theta = dataConStupidTheta data_con
881     tenv = mkTopTvSubst (dataConUnivTyVars data_con `zip` inst_tys)
882          -- NB: inst_tys can be longer than the univ tyvars
883          --     because the constructor might have existentials
884     inst_theta = substTheta tenv stupid_theta
885 \end{code}
886
887 Note [Arrows and patterns]
888 ~~~~~~~~~~~~~~~~~~~~~~~~~~
889 (Oct 07) Arrow noation has the odd property that it involves 
890 "holes in the scope". For example:
891   expr :: Arrow a => a () Int
892   expr = proc (y,z) -> do
893           x <- term -< y
894           expr' -< x
895
896 Here the 'proc (y,z)' binding scopes over the arrow tails but not the
897 arrow body (e.g 'term').  As things stand (bogusly) all the
898 constraints from the proc body are gathered together, so constraints
899 from 'term' will be seen by the tcPat for (y,z).  But we must *not*
900 bind constraints from 'term' here, becuase the desugarer will not make
901 these bindings scope over 'term'.
902
903 The Right Thing is not to confuse these constraints together. But for
904 now the Easy Thing is to ensure that we do not have existential or
905 GADT constraints in a 'proc', and to short-cut the constraint
906 simplification for such vanilla patterns so that it binds no
907 constraints. Hence the 'fast path' in tcConPat; but it's also a good
908 plan for ordinary vanilla patterns to bypass the constraint
909 simplification step.
910
911 %************************************************************************
912 %*                                                                      *
913                 Note [Pattern coercions]
914 %*                                                                      *
915 %************************************************************************
916
917 In principle, these program would be reasonable:
918         
919         f :: (forall a. a->a) -> Int
920         f (x :: Int->Int) = x 3
921
922         g :: (forall a. [a]) -> Bool
923         g [] = True
924
925 In both cases, the function type signature restricts what arguments can be passed
926 in a call (to polymorphic ones).  The pattern type signature then instantiates this
927 type.  For example, in the first case,  (forall a. a->a) <= Int -> Int, and we
928 generate the translated term
929         f = \x' :: (forall a. a->a).  let x = x' Int in x 3
930
931 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
932 And it requires a significant amount of code to implement, becuase we need to decorate
933 the translated pattern with coercion functions (generated from the subsumption check 
934 by tcSub).  
935
936 So for now I'm just insisting on type *equality* in patterns.  No subsumption. 
937
938 Old notes about desugaring, at a time when pattern coercions were handled:
939
940 A SigPat is a type coercion and must be handled one at at time.  We can't
941 combine them unless the type of the pattern inside is identical, and we don't
942 bother to check for that.  For example:
943
944         data T = T1 Int | T2 Bool
945         f :: (forall a. a -> a) -> T -> t
946         f (g::Int->Int)   (T1 i) = T1 (g i)
947         f (g::Bool->Bool) (T2 b) = T2 (g b)
948
949 We desugar this as follows:
950
951         f = \ g::(forall a. a->a) t::T ->
952             let gi = g Int
953             in case t of { T1 i -> T1 (gi i)
954                            other ->
955             let gb = g Bool
956             in case t of { T2 b -> T2 (gb b)
957                            other -> fail }}
958
959 Note that we do not treat the first column of patterns as a
960 column of variables, because the coerced variables (gi, gb)
961 would be of different types.  So we get rather grotty code.
962 But I don't think this is a common case, and if it was we could
963 doubtless improve it.
964
965 Meanwhile, the strategy is:
966         * treat each SigPat coercion (always non-identity coercions)
967                 as a separate block
968         * deal with the stuff inside, and then wrap a binding round
969                 the result to bind the new variable (gi, gb, etc)
970
971
972 %************************************************************************
973 %*                                                                      *
974 \subsection{Errors and contexts}
975 %*                                                                      *
976 %************************************************************************
977
978 {-   This was used to improve the error message from 
979      an existential escape. Need to think how to do this.
980
981 sigPatCtxt :: [LPat Var] -> [Var] -> [TcType] -> TcType -> TidyEnv
982            -> TcM (TidyEnv, SDoc)
983 sigPatCtxt pats bound_tvs pat_tys body_ty tidy_env 
984   = do  { pat_tys' <- mapM zonkTcType pat_tys
985         ; body_ty' <- zonkTcType body_ty
986         ; let (env1,  tidy_tys)    = tidyOpenTypes tidy_env (map idType show_ids)
987               (env2, tidy_pat_tys) = tidyOpenTypes env1 pat_tys'
988               (env3, tidy_body_ty) = tidyOpenType  env2 body_ty'
989         ; return (env3,
990                  sep [ptext (sLit "When checking an existential match that binds"),
991                       nest 2 (vcat (zipWith ppr_id show_ids tidy_tys)),
992                       ptext (sLit "The pattern(s) have type(s):") <+> vcat (map ppr tidy_pat_tys),
993                       ptext (sLit "The body has type:") <+> ppr tidy_body_ty
994                 ]) }
995   where
996     bound_ids = collectPatsBinders pats
997     show_ids = filter is_interesting bound_ids
998     is_interesting id = any (`elemVarSet` varTypeTyVars id) bound_tvs
999
1000     ppr_id id ty = ppr id <+> dcolon <+> ppr ty
1001         -- Don't zonk the types so we get the separate, un-unified versions
1002 -}
1003
1004 \begin{code}
1005 maybeWrapPatCtxt :: Pat Name -> (TcM a -> TcM b) -> TcM a -> TcM b
1006 -- Not all patterns are worth pushing a context
1007 maybeWrapPatCtxt pat tcm thing_inside 
1008   | not (worth_wrapping pat) = tcm thing_inside
1009   | otherwise                = addErrCtxt msg $ tcm $ popErrCtxt thing_inside
1010                                -- Remember to pop before doing thing_inside
1011   where
1012    worth_wrapping (VarPat {}) = False
1013    worth_wrapping (ParPat {}) = False
1014    worth_wrapping (AsPat {})  = False
1015    worth_wrapping _           = True
1016    msg = hang (ptext (sLit "In the pattern:")) 2 (ppr pat)
1017
1018 -----------------------------------------------
1019 checkExistentials :: [TyVar] -> PatEnv -> TcM ()
1020           -- See Note [Arrows and patterns]
1021 checkExistentials [] _                                 = return ()
1022 checkExistentials _ (PE { pe_ctxt = LetPat {}})        = failWithTc existentialLetPat
1023 checkExistentials _ (PE { pe_ctxt = LamPat ProcExpr }) = failWithTc existentialProcPat
1024 checkExistentials _ (PE { pe_lazy = True })            = failWithTc existentialLazyPat
1025 checkExistentials _ _                                  = return ()
1026
1027 existentialLazyPat :: SDoc
1028 existentialLazyPat
1029   = hang (ptext (sLit "An existential or GADT data constructor cannot be used"))
1030        2 (ptext (sLit "inside a lazy (~) pattern"))
1031
1032 existentialProcPat :: SDoc
1033 existentialProcPat 
1034   = ptext (sLit "Proc patterns cannot use existential or GADT data constructors")
1035
1036 existentialLetPat :: SDoc
1037 existentialLetPat
1038   = vcat [text "My brain just exploded",
1039           text "I can't handle pattern bindings for existential or GADT data constructors.",
1040           text "Instead, use a case-expression, or do-notation, to unpack the constructor."]
1041
1042 badFieldCon :: DataCon -> Name -> SDoc
1043 badFieldCon con field
1044   = hsep [ptext (sLit "Constructor") <+> quotes (ppr con),
1045           ptext (sLit "does not have field"), quotes (ppr field)]
1046
1047 polyPatSig :: TcType -> SDoc
1048 polyPatSig sig_ty
1049   = hang (ptext (sLit "Illegal polymorphic type signature in pattern:"))
1050        2 (ppr sig_ty)
1051
1052 badTypePat :: Pat Name -> SDoc
1053 badTypePat pat = ptext (sLit "Illegal type pattern") <+> ppr pat
1054
1055 lazyUnliftedPatErr :: OutputableBndr name => Pat name -> TcM ()
1056 lazyUnliftedPatErr pat
1057   = failWithTc $
1058     hang (ptext (sLit "A lazy (~) pattern cannot contain unlifted types:"))
1059        2 (ppr pat)
1060
1061 unboxedTupleErr :: SDoc -> Type -> SDoc
1062 unboxedTupleErr what ty
1063   = hang (what <+> ptext (sLit "cannot have an unboxed tuple type:"))
1064        2 (ppr ty)
1065 \end{code}