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