Add NOINLINE for hs-boot functions
[ghc.git] / compiler / typecheck / TcPat.hs
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
9 {-# LANGUAGE CPP, RankNTypes #-}
10
11 module TcPat ( tcLetPat, TcSigFun
12 , TcPragEnv, lookupPragEnv, emptyPragEnv
13 , TcSigInfo(..), TcPatSynInfo(..)
14 , findScopedTyVars, isPartialSig
15 , completeSigPolyId, completeSigPolyId_maybe
16 , LetBndrSpec(..), addInlinePrags
17 , tcPat, tcPats, newNoSigLetBndr
18 , addDataConStupidTheta, badFieldCon, polyPatSig ) where
19
20 #include "HsVersions.h"
21
22 import {-# SOURCE #-} TcExpr( tcSyntaxOp, tcInferRho)
23
24 import HsSyn
25 import TcHsSyn
26 import TcRnMonad
27 import Inst
28 import Id
29 import Var
30 import Name
31 import NameSet
32 import NameEnv
33 import TcEnv
34 import TcMType
35 import TcValidity( arityErr )
36 import TcType
37 import TcUnify
38 import TcHsType
39 import TysWiredIn
40 import TcEvidence
41 import TyCon
42 import DataCon
43 import PatSyn
44 import ConLike
45 import PrelNames
46 import BasicTypes hiding (SuccessFlag(..))
47 import DynFlags
48 import SrcLoc
49 import Util
50 import Outputable
51 import FastString
52 import Maybes( orElse )
53 import Control.Monad
54
55 {-
56 ************************************************************************
57 * *
58 External interface
59 * *
60 ************************************************************************
61 -}
62
63 tcLetPat :: TcSigFun -> LetBndrSpec
64 -> LPat Name -> TcSigmaType
65 -> TcM a
66 -> TcM (LPat TcId, a)
67 tcLetPat sig_fn no_gen pat pat_ty thing_inside
68 = tc_lpat pat pat_ty penv thing_inside
69 where
70 penv = PE { pe_lazy = True
71 , pe_ctxt = LetPat sig_fn no_gen }
72
73 -----------------
74 tcPats :: HsMatchContext Name
75 -> [LPat Name] -- Patterns,
76 -> [TcSigmaType] -- and their types
77 -> TcM a -- and the checker for the body
78 -> TcM ([LPat TcId], a)
79
80 -- This is the externally-callable wrapper function
81 -- Typecheck the patterns, extend the environment to bind the variables,
82 -- do the thing inside, use any existentially-bound dictionaries to
83 -- discharge parts of the returning LIE, and deal with pattern type
84 -- signatures
85
86 -- 1. Initialise the PatState
87 -- 2. Check the patterns
88 -- 3. Check the body
89 -- 4. Check that no existentials escape
90
91 tcPats ctxt pats pat_tys thing_inside
92 = tc_lpats penv pats pat_tys thing_inside
93 where
94 penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt }
95
96 tcPat :: HsMatchContext Name
97 -> LPat Name -> TcSigmaType
98 -> TcM a -- Checker for body, given
99 -- its result type
100 -> TcM (LPat TcId, a)
101 tcPat ctxt pat pat_ty thing_inside
102 = tc_lpat pat pat_ty penv thing_inside
103 where
104 penv = PE { pe_lazy = False, pe_ctxt = LamPat ctxt }
105
106
107 -----------------
108 data PatEnv
109 = PE { pe_lazy :: Bool -- True <=> lazy context, so no existentials allowed
110 , pe_ctxt :: PatCtxt -- Context in which the whole pattern appears
111 }
112
113 data PatCtxt
114 = LamPat -- Used for lambdas, case etc
115 (HsMatchContext Name)
116
117 | LetPat -- Used only for let(rec) pattern bindings
118 -- See Note [Typing patterns in pattern bindings]
119 TcSigFun -- Tells type sig if any
120 LetBndrSpec -- True <=> no generalisation of this let
121
122 data LetBndrSpec
123 = LetLclBndr -- The binder is just a local one;
124 -- an AbsBinds will provide the global version
125
126 | LetGblBndr TcPragEnv -- Generalisation plan is NoGen, so there isn't going
127 -- to be an AbsBinds; So we must bind the global version
128 -- of the binder right away.
129 -- Oh, and here is the inline-pragma information
130
131 makeLazy :: PatEnv -> PatEnv
132 makeLazy penv = penv { pe_lazy = True }
133
134 inPatBind :: PatEnv -> Bool
135 inPatBind (PE { pe_ctxt = LetPat {} }) = True
136 inPatBind (PE { pe_ctxt = LamPat {} }) = False
137
138 ---------------
139 type TcPragEnv = NameEnv [LSig Name]
140 type TcSigFun = Name -> Maybe TcSigInfo
141
142 emptyPragEnv :: TcPragEnv
143 emptyPragEnv = emptyNameEnv
144
145 lookupPragEnv :: TcPragEnv -> Name -> [LSig Name]
146 lookupPragEnv prag_fn n = lookupNameEnv prag_fn n `orElse` []
147
148 data TcSigInfo
149 = TcSigInfo {
150 sig_name :: Name, -- The binder name of the type signature. When
151 -- sig_id = Just id, then sig_name = idName id.
152
153 sig_poly_id :: Maybe TcId,
154 -- Just f <=> the type signature had no wildcards, so the precise,
155 -- complete polymorphic type is known. In that case,
156 -- f is the polymorphic Id, with that type
157
158 -- Nothing <=> the type signature is partial (i.e. includes one or more
159 -- wildcards). In this case it doesn't make sense to give
160 -- the polymorphic Id, because we are going to /infer/ its
161 -- type, so we can't make the polymorphic Id ab-initio
162 --
163 -- See Note [Complete and partial type signatures]
164
165 sig_tvs :: [(Maybe Name, TcTyVar)],
166 -- Instantiated type and kind variables
167 -- Just n <=> this skolem is lexically in scope with name n
168 -- See Note [Binding scoped type variables]
169
170 sig_nwcs :: [(Name, TcTyVar)],
171 -- Instantiated wildcard variables
172 -- If sig_poly_id = Just f, then sig_nwcs must be empty
173
174 sig_extra_cts :: Maybe SrcSpan,
175 -- Just loc <=> An extra-constraints wildcard was present
176 -- at location loc
177 -- e.g. f :: (Eq a, _) => a -> a
178 -- Any extra constraints inferred during
179 -- type-checking will be added to the sig_theta.
180 -- If sig_poly_id = Just f, sig_extra_cts must be Nothing
181
182 sig_theta :: TcThetaType, -- Instantiated theta
183 sig_tau :: TcSigmaType, -- Instantiated tau
184 -- See Note [sig_tau may be polymorphic]
185
186 sig_loc :: SrcSpan, -- The location of the signature
187
188 sig_warn_redundant :: Bool -- True <=> report redundant constraints
189 -- when typechecking the value binding
190 -- for this type signature
191 -- This is usually True, but False for
192 -- * Record selectors (not important here)
193 -- * Class and instance methods. Here the code may legitimately
194 -- be more polymorphic than the signature generated from the
195 -- class declaration
196 }
197 | TcPatSynInfo TcPatSynInfo
198
199 data TcPatSynInfo
200 = TPSI {
201 patsig_name :: Name,
202 patsig_tau :: TcSigmaType,
203 patsig_ex :: [TcTyVar],
204 patsig_prov :: TcThetaType,
205 patsig_univ :: [TcTyVar],
206 patsig_req :: TcThetaType
207 }
208
209 findScopedTyVars -- See Note [Binding scoped type variables]
210 :: LHsType Name -- The HsType
211 -> TcType -- The corresponding Type:
212 -- uses same Names as the HsType
213 -> [TcTyVar] -- The instantiated forall variables of the Type
214 -> [(Maybe Name, TcTyVar)] -- In 1-1 correspondence with the instantiated vars
215 findScopedTyVars hs_ty sig_ty inst_tvs
216 = zipWith find sig_tvs inst_tvs
217 where
218 find sig_tv inst_tv
219 | tv_name `elemNameSet` scoped_names = (Just tv_name, inst_tv)
220 | otherwise = (Nothing, inst_tv)
221 where
222 tv_name = tyVarName sig_tv
223
224 scoped_names = mkNameSet (hsExplicitTvs hs_ty)
225 (sig_tvs,_) = tcSplitForAllTys sig_ty
226
227 instance NamedThing TcSigInfo where
228 getName TcSigInfo{ sig_name = name } = name
229 getName (TcPatSynInfo tpsi) = patsig_name tpsi
230
231
232 instance Outputable TcSigInfo where
233 ppr (TcSigInfo { sig_name = name, sig_poly_id = mb_poly_id, sig_tvs = tyvars
234 , sig_theta = theta, sig_tau = tau })
235 = maybe (ppr name) ppr mb_poly_id <+> dcolon <+>
236 vcat [ pprSigmaType (mkSigmaTy (map snd tyvars) theta tau)
237 , ppr (map fst tyvars) ]
238 ppr (TcPatSynInfo tpsi) = text "TcPatSynInfo" <+> ppr tpsi
239
240 instance Outputable TcPatSynInfo where
241 ppr (TPSI{ patsig_name = name}) = ppr name
242
243 isPartialSig :: TcSigInfo -> Bool
244 isPartialSig (TcSigInfo { sig_poly_id = Nothing }) = True
245 isPartialSig _ = False
246
247 -- Helper for cases when we know for sure we have a complete type
248 -- signature, e.g. class methods.
249 completeSigPolyId :: TcSigInfo -> TcId
250 completeSigPolyId (TcSigInfo { sig_poly_id = Just id }) = id
251 completeSigPolyId _ = panic "completeSigPolyId"
252
253 completeSigPolyId_maybe :: TcSigInfo -> Maybe TcId
254 completeSigPolyId_maybe (TcSigInfo { sig_poly_id = mb_id }) = mb_id
255 completeSigPolyId_maybe (TcPatSynInfo {}) = Nothing
256
257 {-
258 Note [Binding scoped type variables]
259 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
260 The type variables *brought into lexical scope* by a type signature may
261 be a subset of the *quantified type variables* of the signatures, for two reasons:
262
263 * With kind polymorphism a signature like
264 f :: forall f a. f a -> f a
265 may actually give rise to
266 f :: forall k. forall (f::k -> *) (a:k). f a -> f a
267 So the sig_tvs will be [k,f,a], but only f,a are scoped.
268 NB: the scoped ones are not necessarily the *inital* ones!
269
270 * Even aside from kind polymorphism, tere may be more instantiated
271 type variables than lexically-scoped ones. For example:
272 type T a = forall b. b -> (a,b)
273 f :: forall c. T c
274 Here, the signature for f will have one scoped type variable, c,
275 but two instantiated type variables, c' and b'.
276
277 The function findScopedTyVars takes
278 * hs_ty: the original HsForAllTy
279 * sig_ty: the corresponding Type (which is guaranteed to use the same Names
280 as the HsForAllTy)
281 * inst_tvs: the skolems instantiated from the forall's in sig_ty
282 It returns a [(Maybe Name, TcTyVar)], in 1-1 correspondence with inst_tvs
283 but with a (Just n) for the lexically scoped name of each in-scope tyvar.
284
285 Note [sig_tau may be polymorphic]
286 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
287 Note that "sig_tau" might actually be a polymorphic type,
288 if the original function had a signature like
289 forall a. Eq a => forall b. Ord b => ....
290 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
291 It happens, too! See Note [Polymorphic methods] in TcClassDcl.
292
293 Note [Existential check]
294 ~~~~~~~~~~~~~~~~~~~~~~~~
295 Lazy patterns can't bind existentials. They arise in two ways:
296 * Let bindings let { C a b = e } in b
297 * Twiddle patterns f ~(C a b) = e
298 The pe_lazy field of PatEnv says whether we are inside a lazy
299 pattern (perhaps deeply)
300
301 If we aren't inside a lazy pattern then we can bind existentials,
302 but we need to be careful about "extra" tyvars. Consider
303 (\C x -> d) : pat_ty -> res_ty
304 When looking for existential escape we must check that the existential
305 bound by C don't unify with the free variables of pat_ty, OR res_ty
306 (or of course the environment). Hence we need to keep track of the
307 res_ty free vars.
308
309 Note [Complete and partial type signatures]
310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
311 A type signature is partial when it contains one or more wildcards
312 (= type holes). The wildcard can either be:
313 * A (type) wildcard occurring in sig_theta or sig_tau. These are
314 stored in sig_nwcs.
315 f :: Bool -> _
316 g :: Eq _a => _a -> _a -> Bool
317 * Or an extra-constraints wildcard, stored in sig_extra_cts:
318 h :: (Num a, _) => a -> a
319
320 A type signature is a complete type signature when there are no
321 wildcards in the type signature, i.e. iff sig_nwcs is empty and
322 sig_extra_cts is Nothing.
323
324 ************************************************************************
325 * *
326 Binders
327 * *
328 ************************************************************************
329 -}
330
331 tcPatBndr :: PatEnv -> Name -> TcSigmaType -> TcM (TcCoercion, TcId)
332 -- (coi, xp) = tcPatBndr penv x pat_ty
333 -- Then coi : pat_ty ~ typeof(xp)
334 --
335 tcPatBndr (PE { pe_ctxt = LetPat lookup_sig no_gen}) bndr_name pat_ty
336 -- See Note [Typing patterns in pattern bindings]
337 | LetGblBndr prags <- no_gen
338 , Just sig <- lookup_sig bndr_name
339 , Just poly_id <- sig_poly_id sig
340 = do { bndr_id <- addInlinePrags poly_id (lookupPragEnv prags bndr_name)
341 ; traceTc "tcPatBndr(gbl,sig)" (ppr bndr_id $$ ppr (idType bndr_id))
342 ; co <- unifyPatType (idType bndr_id) pat_ty
343 ; return (co, bndr_id) }
344
345 | otherwise
346 = do { bndr_id <- newNoSigLetBndr no_gen bndr_name pat_ty
347 ; traceTc "tcPatBndr(no-sig)" (ppr bndr_id $$ ppr (idType bndr_id))
348 ; return (mkTcNomReflCo pat_ty, bndr_id) }
349
350 tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty
351 = return (mkTcNomReflCo pat_ty, mkLocalId bndr_name pat_ty)
352
353 ------------
354 newNoSigLetBndr :: LetBndrSpec -> Name -> TcType -> TcM TcId
355 -- In the polymorphic case (no_gen = LetLclBndr), generate a "monomorphic version"
356 -- of the Id; the original name will be bound to the polymorphic version
357 -- by the AbsBinds
358 -- In the monomorphic case (no_gen = LetBglBndr) there is no AbsBinds, and we
359 -- use the original name directly
360 newNoSigLetBndr LetLclBndr name ty
361 =do { mono_name <- newLocalName name
362 ; return (mkLocalId mono_name ty) }
363 newNoSigLetBndr (LetGblBndr prags) name ty
364 = addInlinePrags (mkLocalId name ty) (lookupPragEnv prags name)
365
366 ----------
367 addInlinePrags :: TcId -> [LSig Name] -> TcM TcId
368 addInlinePrags poly_id prags
369 | inl@(L _ prag) : inls <- inl_prags
370 = do { traceTc "addInlinePrag" (ppr poly_id $$ ppr prag)
371 ; unless (null inls) (warn_multiple_inlines inl inls)
372 ; return (poly_id `setInlinePragma` prag) }
373 | otherwise
374 = return poly_id
375 where
376 inl_prags = [L loc prag | L loc (InlineSig _ prag) <- prags]
377
378 warn_multiple_inlines _ [] = return ()
379
380 warn_multiple_inlines inl1@(L loc prag1) (inl2@(L _ prag2) : inls)
381 | inlinePragmaActivation prag1 == inlinePragmaActivation prag2
382 , isEmptyInlineSpec (inlinePragmaSpec prag1)
383 = -- Tiresome: inl1 is put there by virtue of being in a hs-boot loop
384 -- and inl2 is a user NOINLINE pragma; we don't want to complain
385 warn_multiple_inlines inl2 inls
386 | otherwise
387 = setSrcSpan loc $
388 addWarnTc (hang (ptext (sLit "Multiple INLINE pragmas for") <+> ppr poly_id)
389 2 (vcat (ptext (sLit "Ignoring all but the first")
390 : map pp_inl (inl1:inl2:inls))))
391
392 pp_inl (L loc prag) = ppr prag <+> parens (ppr loc)
393
394 {-
395 Note [Typing patterns in pattern bindings]
396 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
397 Suppose we are typing a pattern binding
398 pat = rhs
399 Then the PatCtxt will be (LetPat sig_fn let_bndr_spec).
400
401 There can still be signatures for the binders:
402 data T = MkT (forall a. a->a) Int
403 x :: forall a. a->a
404 y :: Int
405 MkT x y = <rhs>
406
407 Two cases, dealt with by the LetPat case of tcPatBndr
408
409 * If we are generalising (generalisation plan is InferGen or
410 CheckGen), then the let_bndr_spec will be LetLclBndr. In that case
411 we want to bind a cloned, local version of the variable, with the
412 type given by the pattern context, *not* by the signature (even if
413 there is one; see Trac #7268). The mkExport part of the
414 generalisation step will do the checking and impedance matching
415 against the signature.
416
417 * If for some some reason we are not generalising (plan = NoGen), the
418 LetBndrSpec will be LetGblBndr. In that case we must bind the
419 global version of the Id, and do so with precisely the type given
420 in the signature. (Then we unify with the type from the pattern
421 context type.
422
423
424 ************************************************************************
425 * *
426 The main worker functions
427 * *
428 ************************************************************************
429
430 Note [Nesting]
431 ~~~~~~~~~~~~~~
432 tcPat takes a "thing inside" over which the pattern scopes. This is partly
433 so that tcPat can extend the environment for the thing_inside, but also
434 so that constraints arising in the thing_inside can be discharged by the
435 pattern.
436
437 This does not work so well for the ErrCtxt carried by the monad: we don't
438 want the error-context for the pattern to scope over the RHS.
439 Hence the getErrCtxt/setErrCtxt stuff in tcMultiple
440 -}
441
442 --------------------
443 type Checker inp out = forall r.
444 inp
445 -> PatEnv
446 -> TcM r
447 -> TcM (out, r)
448
449 tcMultiple :: Checker inp out -> Checker [inp] [out]
450 tcMultiple tc_pat args penv thing_inside
451 = do { err_ctxt <- getErrCtxt
452 ; let loop _ []
453 = do { res <- thing_inside
454 ; return ([], res) }
455
456 loop penv (arg:args)
457 = do { (p', (ps', res))
458 <- tc_pat arg penv $
459 setErrCtxt err_ctxt $
460 loop penv args
461 -- setErrCtxt: restore context before doing the next pattern
462 -- See note [Nesting] above
463
464 ; return (p':ps', res) }
465
466 ; loop penv args }
467
468 --------------------
469 tc_lpat :: LPat Name
470 -> TcSigmaType
471 -> PatEnv
472 -> TcM a
473 -> TcM (LPat TcId, a)
474 tc_lpat (L span pat) pat_ty penv thing_inside
475 = setSrcSpan span $
476 do { (pat', res) <- maybeWrapPatCtxt pat (tc_pat penv pat pat_ty)
477 thing_inside
478 ; return (L span pat', res) }
479
480 tc_lpats :: PatEnv
481 -> [LPat Name] -> [TcSigmaType]
482 -> TcM a
483 -> TcM ([LPat TcId], a)
484 tc_lpats penv pats tys thing_inside
485 = ASSERT2( equalLength pats tys, ppr pats $$ ppr tys )
486 tcMultiple (\(p,t) -> tc_lpat p t)
487 (zipEqual "tc_lpats" pats tys)
488 penv thing_inside
489
490 --------------------
491 tc_pat :: PatEnv
492 -> Pat Name
493 -> TcSigmaType -- Fully refined result type
494 -> TcM a -- Thing inside
495 -> TcM (Pat TcId, -- Translated pattern
496 a) -- Result of thing inside
497
498 tc_pat penv (VarPat name) pat_ty thing_inside
499 = do { (co, id) <- tcPatBndr penv name pat_ty
500 ; res <- tcExtendIdEnv1 name id thing_inside
501 ; return (mkHsWrapPatCo co (VarPat id) pat_ty, res) }
502
503 tc_pat penv (ParPat pat) pat_ty thing_inside
504 = do { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
505 ; return (ParPat pat', res) }
506
507 tc_pat penv (BangPat pat) pat_ty thing_inside
508 = do { (pat', res) <- tc_lpat pat pat_ty penv thing_inside
509 ; return (BangPat pat', res) }
510
511 tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside
512 = do { (pat', (res, pat_ct))
513 <- tc_lpat pat pat_ty (makeLazy penv) $
514 captureConstraints thing_inside
515 -- Ignore refined penv', revert to penv
516
517 ; emitConstraints pat_ct
518 -- captureConstraints/extendConstraints:
519 -- see Note [Hopping the LIE in lazy patterns]
520
521 -- Check there are no unlifted types under the lazy pattern
522 ; when (any (isUnLiftedType . idType) $ collectPatBinders pat') $
523 lazyUnliftedPatErr lpat
524
525 -- Check that the expected pattern type is itself lifted
526 ; pat_ty' <- newFlexiTyVarTy liftedTypeKind
527 ; _ <- unifyType pat_ty pat_ty'
528
529 ; return (LazyPat pat', res) }
530
531 tc_pat _ (WildPat _) pat_ty thing_inside
532 = do { res <- thing_inside
533 ; return (WildPat pat_ty, res) }
534
535 tc_pat penv (AsPat (L nm_loc name) pat) pat_ty thing_inside
536 = do { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
537 ; (pat', res) <- tcExtendIdEnv1 name bndr_id $
538 tc_lpat pat (idType bndr_id) penv thing_inside
539 -- NB: if we do inference on:
540 -- \ (y@(x::forall a. a->a)) = e
541 -- we'll fail. The as-pattern infers a monotype for 'y', which then
542 -- fails to unify with the polymorphic type for 'x'. This could
543 -- perhaps be fixed, but only with a bit more work.
544 --
545 -- If you fix it, don't forget the bindInstsOfPatIds!
546 ; return (mkHsWrapPatCo co (AsPat (L nm_loc bndr_id) pat') pat_ty, res) }
547
548 tc_pat penv (ViewPat expr pat _) overall_pat_ty thing_inside
549 = do {
550 -- Morally, expr must have type `forall a1...aN. OPT' -> B`
551 -- where overall_pat_ty is an instance of OPT'.
552 -- Here, we infer a rho type for it,
553 -- which replaces the leading foralls and constraints
554 -- with fresh unification variables.
555 ; (expr',expr'_inferred) <- tcInferRho expr
556
557 -- next, we check that expr is coercible to `overall_pat_ty -> pat_ty`
558 -- NOTE: this forces pat_ty to be a monotype (because we use a unification
559 -- variable to find it). this means that in an example like
560 -- (view -> f) where view :: _ -> forall b. b
561 -- we will only be able to use view at one instantation in the
562 -- rest of the view
563 ; (expr_co, pat_ty) <- tcInfer $ \ pat_ty ->
564 unifyType expr'_inferred (mkFunTy overall_pat_ty pat_ty)
565
566 -- pattern must have pat_ty
567 ; (pat', res) <- tc_lpat pat pat_ty penv thing_inside
568
569 ; return (ViewPat (mkLHsWrapCo expr_co expr') pat' overall_pat_ty, res) }
570
571 -- Type signatures in patterns
572 -- See Note [Pattern coercions] below
573 tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside
574 = do { (inner_ty, tv_binds, nwc_binds, wrap) <- tcPatSig (inPatBind penv)
575 sig_ty pat_ty
576 ; (pat', res) <- tcExtendTyVarEnv2 (tv_binds ++ nwc_binds) $
577 tc_lpat pat inner_ty penv thing_inside
578 ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) }
579
580 ------------------------
581 -- Lists, tuples, arrays
582 tc_pat penv (ListPat pats _ Nothing) pat_ty thing_inside
583 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTyR pat_ty
584 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
585 pats penv thing_inside
586 ; return (mkHsWrapPat coi (ListPat pats' elt_ty Nothing) pat_ty, res)
587 }
588
589 tc_pat penv (ListPat pats _ (Just (_,e))) pat_ty thing_inside
590 = do { list_pat_ty <- newFlexiTyVarTy liftedTypeKind
591 ; e' <- tcSyntaxOp ListOrigin e (mkFunTy pat_ty list_pat_ty)
592 ; (coi, elt_ty) <- matchExpectedPatTy matchExpectedListTyR list_pat_ty
593 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
594 pats penv thing_inside
595 ; return (mkHsWrapPat coi (ListPat pats' elt_ty (Just (pat_ty,e'))) list_pat_ty, res)
596 }
597
598 tc_pat penv (PArrPat pats _) pat_ty thing_inside
599 = do { (coi, elt_ty) <- matchExpectedPatTy matchExpectedPArrTyR pat_ty
600 ; (pats', res) <- tcMultiple (\p -> tc_lpat p elt_ty)
601 pats penv thing_inside
602 ; return (mkHsWrapPat coi (PArrPat pats' elt_ty) pat_ty, res)
603 }
604
605 tc_pat penv (TuplePat pats boxity _) pat_ty thing_inside
606 = do { let tc = tupleTyCon boxity (length pats)
607 ; (coi, arg_tys) <- matchExpectedPatTy (matchExpectedTyConAppR tc) pat_ty
608 ; (pats', res) <- tc_lpats penv pats arg_tys thing_inside
609
610 ; dflags <- getDynFlags
611
612 -- Under flag control turn a pattern (x,y,z) into ~(x,y,z)
613 -- so that we can experiment with lazy tuple-matching.
614 -- This is a pretty odd place to make the switch, but
615 -- it was easy to do.
616 ; let
617 unmangled_result = TuplePat pats' boxity arg_tys
618 -- pat_ty /= pat_ty iff coi /= IdCo
619 possibly_mangled_result
620 | gopt Opt_IrrefutableTuples dflags &&
621 isBoxed boxity = LazyPat (noLoc unmangled_result)
622 | otherwise = unmangled_result
623
624 ; ASSERT( length arg_tys == length pats ) -- Syntactically enforced
625 return (mkHsWrapPat coi possibly_mangled_result pat_ty, res)
626 }
627
628 ------------------------
629 -- Data constructors
630 tc_pat penv (ConPatIn con arg_pats) pat_ty thing_inside
631 = tcConPat penv con pat_ty arg_pats thing_inside
632
633 ------------------------
634 -- Literal patterns
635 tc_pat _ (LitPat simple_lit) pat_ty thing_inside
636 = do { let lit_ty = hsLitType simple_lit
637 ; co <- unifyPatType lit_ty pat_ty
638 -- coi is of kind: pat_ty ~ lit_ty
639 ; res <- thing_inside
640 ; return ( mkHsWrapPatCo co (LitPat simple_lit) pat_ty
641 , res) }
642
643 ------------------------
644 -- Overloaded patterns: n, and n+k
645 tc_pat _ (NPat (L l over_lit) mb_neg eq) pat_ty thing_inside
646 = do { let orig = LiteralOrigin over_lit
647 ; lit' <- newOverloadedLit orig over_lit pat_ty
648 ; eq' <- tcSyntaxOp orig eq (mkFunTys [pat_ty, pat_ty] boolTy)
649 ; mb_neg' <- case mb_neg of
650 Nothing -> return Nothing -- Positive literal
651 Just neg -> -- Negative literal
652 -- The 'negate' is re-mappable syntax
653 do { neg' <- tcSyntaxOp orig neg (mkFunTy pat_ty pat_ty)
654 ; return (Just neg') }
655 ; res <- thing_inside
656 ; return (NPat (L l lit') mb_neg' eq', res) }
657
658 tc_pat penv (NPlusKPat (L nm_loc name) (L loc lit) ge minus) pat_ty thing_inside
659 = do { (co, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)
660 ; let pat_ty' = idType bndr_id
661 orig = LiteralOrigin lit
662 ; lit' <- newOverloadedLit orig lit pat_ty'
663
664 -- The '>=' and '-' parts are re-mappable syntax
665 ; ge' <- tcSyntaxOp orig ge (mkFunTys [pat_ty', pat_ty'] boolTy)
666 ; minus' <- tcSyntaxOp orig minus (mkFunTys [pat_ty', pat_ty'] pat_ty')
667 ; let pat' = NPlusKPat (L nm_loc bndr_id) (L loc lit') ge' minus'
668
669 -- The Report says that n+k patterns must be in Integral
670 -- We may not want this when using re-mappable syntax, though (ToDo?)
671 ; icls <- tcLookupClass integralClassName
672 ; instStupidTheta orig [mkClassPred icls [pat_ty']]
673
674 ; res <- tcExtendIdEnv1 name bndr_id thing_inside
675 ; return (mkHsWrapPatCo co pat' pat_ty, res) }
676
677 tc_pat _ _other_pat _ _ = panic "tc_pat" -- ConPatOut, SigPatOut
678
679 ----------------
680 unifyPatType :: TcType -> TcType -> TcM TcCoercion
681 -- In patterns we want a coercion from the
682 -- context type (expected) to the actual pattern type
683 -- But we don't want to reverse the args to unifyType because
684 -- that controls the actual/expected stuff in error messages
685 unifyPatType actual_ty expected_ty
686 = do { coi <- unifyType actual_ty expected_ty
687 ; return (mkTcSymCo coi) }
688
689 {-
690 Note [Hopping the LIE in lazy patterns]
691 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
692 In a lazy pattern, we must *not* discharge constraints from the RHS
693 from dictionaries bound in the pattern. E.g.
694 f ~(C x) = 3
695 We can't discharge the Num constraint from dictionaries bound by
696 the pattern C!
697
698 So we have to make the constraints from thing_inside "hop around"
699 the pattern. Hence the captureConstraints and emitConstraints.
700
701 The same thing ensures that equality constraints in a lazy match
702 are not made available in the RHS of the match. For example
703 data T a where { T1 :: Int -> T Int; ... }
704 f :: T a -> Int -> a
705 f ~(T1 i) y = y
706 It's obviously not sound to refine a to Int in the right
707 hand side, because the argument might not match T1 at all!
708
709 Finally, a lazy pattern should not bind any existential type variables
710 because they won't be in scope when we do the desugaring
711
712
713 ************************************************************************
714 * *
715 Most of the work for constructors is here
716 (the rest is in the ConPatIn case of tc_pat)
717 * *
718 ************************************************************************
719
720 [Pattern matching indexed data types]
721 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
722 Consider the following declarations:
723
724 data family Map k :: * -> *
725 data instance Map (a, b) v = MapPair (Map a (Pair b v))
726
727 and a case expression
728
729 case x :: Map (Int, c) w of MapPair m -> ...
730
731 As explained by [Wrappers for data instance tycons] in MkIds.hs, the
732 worker/wrapper types for MapPair are
733
734 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
735 $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
736
737 So, the type of the scrutinee is Map (Int, c) w, but the tycon of MapPair is
738 :R123Map, which means the straight use of boxySplitTyConApp would give a type
739 error. Hence, the smart wrapper function boxySplitTyConAppWithFamily calls
740 boxySplitTyConApp with the family tycon Map instead, which gives us the family
741 type list {(Int, c), w}. To get the correct split for :R123Map, we need to
742 unify the family type list {(Int, c), w} with the instance types {(a, b), v}
743 (provided by tyConFamInst_maybe together with the family tycon). This
744 unification yields the substitution [a -> Int, b -> c, v -> w], which gives us
745 the split arguments for the representation tycon :R123Map as {Int, c, w}
746
747 In other words, boxySplitTyConAppWithFamily implicitly takes the coercion
748
749 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
750
751 moving between representation and family type into account. To produce type
752 correct Core, this coercion needs to be used to case the type of the scrutinee
753 from the family to the representation type. This is achieved by
754 unwrapFamInstScrutinee using a CoPat around the result pattern.
755
756 Now it might appear seem as if we could have used the previous GADT type
757 refinement infrastructure of refineAlt and friends instead of the explicit
758 unification and CoPat generation. However, that would be wrong. Why? The
759 whole point of GADT refinement is that the refinement is local to the case
760 alternative. In contrast, the substitution generated by the unification of
761 the family type list and instance types needs to be propagated to the outside.
762 Imagine that in the above example, the type of the scrutinee would have been
763 (Map x w), then we would have unified {x, w} with {(a, b), v}, yielding the
764 substitution [x -> (a, b), v -> w]. In contrast to GADT matching, the
765 instantiation of x with (a, b) must be global; ie, it must be valid in *all*
766 alternatives of the case expression, whereas in the GADT case it might vary
767 between alternatives.
768
769 RIP GADT refinement: refinements have been replaced by the use of explicit
770 equality constraints that are used in conjunction with implication constraints
771 to express the local scope of GADT refinements.
772 -}
773
774 -- Running example:
775 -- MkT :: forall a b c. (a~[b]) => b -> c -> T a
776 -- with scrutinee of type (T ty)
777
778 tcConPat :: PatEnv -> Located Name
779 -> TcRhoType -- Type of the pattern
780 -> HsConPatDetails Name -> TcM a
781 -> TcM (Pat TcId, a)
782 tcConPat penv con_lname@(L _ con_name) pat_ty arg_pats thing_inside
783 = do { con_like <- tcLookupConLike con_name
784 ; case con_like of
785 RealDataCon data_con -> tcDataConPat penv con_lname data_con
786 pat_ty arg_pats thing_inside
787 PatSynCon pat_syn -> tcPatSynPat penv con_lname pat_syn
788 pat_ty arg_pats thing_inside
789 }
790
791 tcDataConPat :: PatEnv -> Located Name -> DataCon
792 -> TcRhoType -- Type of the pattern
793 -> HsConPatDetails Name -> TcM a
794 -> TcM (Pat TcId, a)
795 tcDataConPat penv (L con_span con_name) data_con pat_ty arg_pats thing_inside
796 = do { let tycon = dataConTyCon data_con
797 -- For data families this is the representation tycon
798 (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _)
799 = dataConFullSig data_con
800 header = L con_span (RealDataCon data_con)
801
802 -- Instantiate the constructor type variables [a->ty]
803 -- This may involve doing a family-instance coercion,
804 -- and building a wrapper
805 ; (wrap, ctxt_res_tys) <- matchExpectedPatTy (matchExpectedConTy tycon) pat_ty
806
807 -- Add the stupid theta
808 ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys
809
810 ; checkExistentials ex_tvs penv
811 ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX
812 (zipTopTvSubst univ_tvs ctxt_res_tys) ex_tvs
813 -- Get location from monad, not from ex_tvs
814
815 ; let -- pat_ty' = mkTyConApp tycon ctxt_res_tys
816 -- pat_ty' is type of the actual constructor application
817 -- pat_ty' /= pat_ty iff coi /= IdCo
818
819 arg_tys' = substTys tenv arg_tys
820
821 ; traceTc "tcConPat" (vcat [ ppr con_name, ppr univ_tvs, ppr ex_tvs, ppr eq_spec
822 , ppr ex_tvs', ppr ctxt_res_tys, ppr arg_tys' ])
823 ; if null ex_tvs && null eq_spec && null theta
824 then do { -- The common case; no class bindings etc
825 -- (see Note [Arrows and patterns])
826 (arg_pats', res) <- tcConArgs (RealDataCon data_con) arg_tys'
827 arg_pats penv thing_inside
828 ; let res_pat = ConPatOut { pat_con = header,
829 pat_tvs = [], pat_dicts = [],
830 pat_binds = emptyTcEvBinds,
831 pat_args = arg_pats',
832 pat_arg_tys = ctxt_res_tys,
833 pat_wrap = idHsWrapper }
834
835 ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
836
837 else do -- The general case, with existential,
838 -- and local equality constraints
839 { let theta' = substTheta tenv (eqSpecPreds eq_spec ++ theta)
840 -- order is *important* as we generate the list of
841 -- dictionary binders from theta'
842 no_equalities = not (any isEqPred theta')
843 skol_info = case pe_ctxt penv of
844 LamPat mc -> PatSkol (RealDataCon data_con) mc
845 LetPat {} -> UnkSkol -- Doesn't matter
846
847 ; gadts_on <- xoptM Opt_GADTs
848 ; families_on <- xoptM Opt_TypeFamilies
849 ; checkTc (no_equalities || gadts_on || families_on)
850 (text "A pattern match on a GADT requires the" <+>
851 text "GADTs or TypeFamilies language extension")
852 -- Trac #2905 decided that a *pattern-match* of a GADT
853 -- should require the GADT language flag.
854 -- Re TypeFamilies see also #7156
855
856 ; given <- newEvVars theta'
857 ; (ev_binds, (arg_pats', res))
858 <- checkConstraints skol_info ex_tvs' given $
859 tcConArgs (RealDataCon data_con) arg_tys' arg_pats penv thing_inside
860
861 ; let res_pat = ConPatOut { pat_con = header,
862 pat_tvs = ex_tvs',
863 pat_dicts = given,
864 pat_binds = ev_binds,
865 pat_args = arg_pats',
866 pat_arg_tys = ctxt_res_tys,
867 pat_wrap = idHsWrapper }
868 ; return (mkHsWrapPat wrap res_pat pat_ty, res)
869 } }
870
871 tcPatSynPat :: PatEnv -> Located Name -> PatSyn
872 -> TcRhoType -- Type of the pattern
873 -> HsConPatDetails Name -> TcM a
874 -> TcM (Pat TcId, a)
875 tcPatSynPat penv (L con_span _) pat_syn pat_ty arg_pats thing_inside
876 = do { let (univ_tvs, ex_tvs, prov_theta, req_theta, arg_tys, ty) = patSynSig pat_syn
877
878 ; (subst, univ_tvs') <- tcInstTyVars univ_tvs
879
880 ; checkExistentials ex_tvs penv
881 ; (tenv, ex_tvs') <- tcInstSuperSkolTyVarsX subst ex_tvs
882 ; let ty' = substTy tenv ty
883 arg_tys' = substTys tenv arg_tys
884 prov_theta' = substTheta tenv prov_theta
885 req_theta' = substTheta tenv req_theta
886
887 ; wrap <- coToHsWrapper <$> unifyType ty' pat_ty
888 ; traceTc "tcPatSynPat" (ppr pat_syn $$
889 ppr pat_ty $$
890 ppr ty' $$
891 ppr ex_tvs' $$
892 ppr prov_theta' $$
893 ppr req_theta' $$
894 ppr arg_tys')
895
896 ; prov_dicts' <- newEvVars prov_theta'
897
898 ; let skol_info = case pe_ctxt penv of
899 LamPat mc -> PatSkol (PatSynCon pat_syn) mc
900 LetPat {} -> UnkSkol -- Doesn't matter
901
902 ; req_wrap <- instCall PatOrigin (mkTyVarTys univ_tvs') req_theta'
903 ; traceTc "instCall" (ppr req_wrap)
904
905 ; traceTc "checkConstraints {" Outputable.empty
906 ; (ev_binds, (arg_pats', res))
907 <- checkConstraints skol_info ex_tvs' prov_dicts' $
908 tcConArgs (PatSynCon pat_syn) arg_tys' arg_pats penv thing_inside
909
910 ; traceTc "checkConstraints }" (ppr ev_binds)
911 ; let res_pat = ConPatOut { pat_con = L con_span $ PatSynCon pat_syn,
912 pat_tvs = ex_tvs',
913 pat_dicts = prov_dicts',
914 pat_binds = ev_binds,
915 pat_args = arg_pats',
916 pat_arg_tys = mkTyVarTys univ_tvs',
917 pat_wrap = req_wrap }
918 ; return (mkHsWrapPat wrap res_pat pat_ty, res) }
919
920 ----------------------------
921 downgrade :: (TcRhoType -> TcM (TcCoercionN, a))
922 -> TcRhoType -> TcM (TcCoercionR, a)
923 downgrade f a = do { (co,res) <- f a; return (mkTcSubCo co, res) }
924
925 matchExpectedListTyR :: TcRhoType -> TcM (TcCoercionR, TcRhoType)
926 matchExpectedListTyR = downgrade matchExpectedListTy
927 matchExpectedPArrTyR :: TcRhoType -> TcM (TcCoercionR, TcRhoType)
928 matchExpectedPArrTyR = downgrade matchExpectedPArrTy
929 matchExpectedTyConAppR :: TyCon -> TcRhoType -> TcM (TcCoercionR, [TcSigmaType])
930 matchExpectedTyConAppR tc = downgrade (matchExpectedTyConApp tc)
931
932 ----------------------------
933 matchExpectedPatTy :: (TcRhoType -> TcM (TcCoercionR, a))
934 -> TcRhoType -> TcM (HsWrapper, a)
935 -- See Note [Matching polytyped patterns]
936 -- Returns a wrapper : pat_ty ~R inner_ty
937 matchExpectedPatTy inner_match pat_ty
938 | null tvs && null theta
939 = do { (co, res) <- inner_match pat_ty -- 'co' is Representational
940 ; traceTc "matchExpectedPatTy" (ppr pat_ty $$ ppr co $$ ppr (isTcReflCo co))
941 ; return (coToHsWrapperR (mkTcSymCo co), res) }
942 -- The Sym is because the inner_match returns a coercion
943 -- that is the other way round to matchExpectedPatTy
944
945 | otherwise
946 = do { (subst, tvs') <- tcInstTyVars tvs
947 ; wrap1 <- instCall PatOrigin (mkTyVarTys tvs') (substTheta subst theta)
948 ; (wrap2, arg_tys) <- matchExpectedPatTy inner_match (TcType.substTy subst tau)
949 ; return (wrap2 <.> wrap1, arg_tys) }
950 where
951 (tvs, theta, tau) = tcSplitSigmaTy pat_ty
952
953 ----------------------------
954 matchExpectedConTy :: TyCon -- The TyCon that this data
955 -- constructor actually returns
956 -> TcRhoType -- The type of the pattern
957 -> TcM (TcCoercionR, [TcSigmaType])
958 -- See Note [Matching constructor patterns]
959 -- Returns a coercion : T ty1 ... tyn ~ pat_ty
960 -- This is the same way round as matchExpectedListTy etc
961 -- but the other way round to matchExpectedPatTy
962 matchExpectedConTy data_tc pat_ty
963 | Just (fam_tc, fam_args, co_tc) <- tyConFamInstSig_maybe data_tc
964 -- Comments refer to Note [Matching constructor patterns]
965 -- co_tc :: forall a. T [a] ~ T7 a
966 = do { (subst, tvs') <- tcInstTyVars (tyConTyVars data_tc)
967 -- tys = [ty1,ty2]
968
969 ; traceTc "matchExpectedConTy" (vcat [ppr data_tc,
970 ppr (tyConTyVars data_tc),
971 ppr fam_tc, ppr fam_args])
972 ; co1 <- unifyType (mkTyConApp fam_tc (substTys subst fam_args)) pat_ty
973 -- co1 : T (ty1,ty2) ~N pat_ty
974
975 ; let tys' = mkTyVarTys tvs'
976 co2 = mkTcUnbranchedAxInstCo Representational co_tc tys'
977 -- co2 : T (ty1,ty2) ~R T7 ty1 ty2
978
979 ; return (mkTcSymCo co2 `mkTcTransCo` mkTcSubCo co1, tys') }
980
981 | otherwise
982 = matchExpectedTyConAppR data_tc pat_ty
983 -- coi : T tys ~R pat_ty
984
985 {-
986 Note [Matching constructor patterns]
987 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
988 Suppose (coi, tys) = matchExpectedConType data_tc pat_ty
989
990 * In the simple case, pat_ty = tc tys
991
992 * If pat_ty is a polytype, we want to instantiate it
993 This is like part of a subsumption check. Eg
994 f :: (forall a. [a]) -> blah
995 f [] = blah
996
997 * In a type family case, suppose we have
998 data family T a
999 data instance T (p,q) = A p | B q
1000 Then we'll have internally generated
1001 data T7 p q = A p | B q
1002 axiom coT7 p q :: T (p,q) ~ T7 p q
1003
1004 So if pat_ty = T (ty1,ty2), we return (coi, [ty1,ty2]) such that
1005 coi = coi2 . coi1 : T7 t ~ pat_ty
1006 coi1 : T (ty1,ty2) ~ pat_ty
1007 coi2 : T7 ty1 ty2 ~ T (ty1,ty2)
1008
1009 For families we do all this matching here, not in the unifier,
1010 because we never want a whisper of the data_tycon to appear in
1011 error messages; it's a purely internal thing
1012 -}
1013
1014 tcConArgs :: ConLike -> [TcSigmaType]
1015 -> Checker (HsConPatDetails Name) (HsConPatDetails Id)
1016
1017 tcConArgs con_like arg_tys (PrefixCon arg_pats) penv thing_inside
1018 = do { checkTc (con_arity == no_of_args) -- Check correct arity
1019 (arityErr "constructor" con_like con_arity no_of_args)
1020 ; let pats_w_tys = zipEqual "tcConArgs" arg_pats arg_tys
1021 ; (arg_pats', res) <- tcMultiple tcConArg pats_w_tys
1022 penv thing_inside
1023 ; return (PrefixCon arg_pats', res) }
1024 where
1025 con_arity = conLikeArity con_like
1026 no_of_args = length arg_pats
1027
1028 tcConArgs con_like arg_tys (InfixCon p1 p2) penv thing_inside
1029 = do { checkTc (con_arity == 2) -- Check correct arity
1030 (arityErr "constructor" con_like con_arity 2)
1031 ; let [arg_ty1,arg_ty2] = arg_tys -- This can't fail after the arity check
1032 ; ([p1',p2'], res) <- tcMultiple tcConArg [(p1,arg_ty1),(p2,arg_ty2)]
1033 penv thing_inside
1034 ; return (InfixCon p1' p2', res) }
1035 where
1036 con_arity = conLikeArity con_like
1037
1038 tcConArgs con_like arg_tys (RecCon (HsRecFields rpats dd)) penv thing_inside
1039 = do { (rpats', res) <- tcMultiple tc_field rpats penv thing_inside
1040 ; return (RecCon (HsRecFields rpats' dd), res) }
1041 where
1042 tc_field :: Checker (LHsRecField FieldLabel (LPat Name))
1043 (LHsRecField TcId (LPat TcId))
1044 tc_field (L l (HsRecField field_lbl pat pun)) penv thing_inside
1045 = do { (sel_id, pat_ty) <- wrapLocFstM find_field_ty field_lbl
1046 ; (pat', res) <- tcConArg (pat, pat_ty) penv thing_inside
1047 ; return (L l (HsRecField sel_id pat' pun), res) }
1048
1049 find_field_ty :: FieldLabel -> TcM (Id, TcType)
1050 find_field_ty field_lbl
1051 = case [ty | (f,ty) <- field_tys, f == field_lbl] of
1052
1053 -- No matching field; chances are this field label comes from some
1054 -- other record type (or maybe none). If this happens, just fail,
1055 -- otherwise we get crashes later (Trac #8570), and similar:
1056 -- f (R { foo = (a,b) }) = a+b
1057 -- If foo isn't one of R's fields, we don't want to crash when
1058 -- typechecking the "a+b".
1059 [] -> failWith (badFieldCon con_like field_lbl)
1060
1061 -- The normal case, when the field comes from the right constructor
1062 (pat_ty : extras) ->
1063 ASSERT( null extras )
1064 do { sel_id <- tcLookupField field_lbl
1065 ; return (sel_id, pat_ty) }
1066
1067 field_tys :: [(FieldLabel, TcType)]
1068 field_tys = case con_like of
1069 RealDataCon data_con -> zip (dataConFieldLabels data_con) arg_tys
1070 -- Don't use zipEqual! If the constructor isn't really a record, then
1071 -- dataConFieldLabels will be empty (and each field in the pattern
1072 -- will generate an error below).
1073 PatSynCon{} -> []
1074
1075 conLikeArity :: ConLike -> Arity
1076 conLikeArity (RealDataCon data_con) = dataConSourceArity data_con
1077 conLikeArity (PatSynCon pat_syn) = patSynArity pat_syn
1078
1079 tcConArg :: Checker (LPat Name, TcSigmaType) (LPat Id)
1080 tcConArg (arg_pat, arg_ty) penv thing_inside
1081 = tc_lpat arg_pat arg_ty penv thing_inside
1082
1083 addDataConStupidTheta :: DataCon -> [TcType] -> TcM ()
1084 -- Instantiate the "stupid theta" of the data con, and throw
1085 -- the constraints into the constraint set
1086 addDataConStupidTheta data_con inst_tys
1087 | null stupid_theta = return ()
1088 | otherwise = instStupidTheta origin inst_theta
1089 where
1090 origin = OccurrenceOf (dataConName data_con)
1091 -- The origin should always report "occurrence of C"
1092 -- even when C occurs in a pattern
1093 stupid_theta = dataConStupidTheta data_con
1094 tenv = mkTopTvSubst (dataConUnivTyVars data_con `zip` inst_tys)
1095 -- NB: inst_tys can be longer than the univ tyvars
1096 -- because the constructor might have existentials
1097 inst_theta = substTheta tenv stupid_theta
1098
1099 {-
1100 Note [Arrows and patterns]
1101 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1102 (Oct 07) Arrow noation has the odd property that it involves
1103 "holes in the scope". For example:
1104 expr :: Arrow a => a () Int
1105 expr = proc (y,z) -> do
1106 x <- term -< y
1107 expr' -< x
1108
1109 Here the 'proc (y,z)' binding scopes over the arrow tails but not the
1110 arrow body (e.g 'term'). As things stand (bogusly) all the
1111 constraints from the proc body are gathered together, so constraints
1112 from 'term' will be seen by the tcPat for (y,z). But we must *not*
1113 bind constraints from 'term' here, because the desugarer will not make
1114 these bindings scope over 'term'.
1115
1116 The Right Thing is not to confuse these constraints together. But for
1117 now the Easy Thing is to ensure that we do not have existential or
1118 GADT constraints in a 'proc', and to short-cut the constraint
1119 simplification for such vanilla patterns so that it binds no
1120 constraints. Hence the 'fast path' in tcConPat; but it's also a good
1121 plan for ordinary vanilla patterns to bypass the constraint
1122 simplification step.
1123
1124 ************************************************************************
1125 * *
1126 Note [Pattern coercions]
1127 * *
1128 ************************************************************************
1129
1130 In principle, these program would be reasonable:
1131
1132 f :: (forall a. a->a) -> Int
1133 f (x :: Int->Int) = x 3
1134
1135 g :: (forall a. [a]) -> Bool
1136 g [] = True
1137
1138 In both cases, the function type signature restricts what arguments can be passed
1139 in a call (to polymorphic ones). The pattern type signature then instantiates this
1140 type. For example, in the first case, (forall a. a->a) <= Int -> Int, and we
1141 generate the translated term
1142 f = \x' :: (forall a. a->a). let x = x' Int in x 3
1143
1144 From a type-system point of view, this is perfectly fine, but it's *very* seldom useful.
1145 And it requires a significant amount of code to implement, because we need to decorate
1146 the translated pattern with coercion functions (generated from the subsumption check
1147 by tcSub).
1148
1149 So for now I'm just insisting on type *equality* in patterns. No subsumption.
1150
1151 Old notes about desugaring, at a time when pattern coercions were handled:
1152
1153 A SigPat is a type coercion and must be handled one at at time. We can't
1154 combine them unless the type of the pattern inside is identical, and we don't
1155 bother to check for that. For example:
1156
1157 data T = T1 Int | T2 Bool
1158 f :: (forall a. a -> a) -> T -> t
1159 f (g::Int->Int) (T1 i) = T1 (g i)
1160 f (g::Bool->Bool) (T2 b) = T2 (g b)
1161
1162 We desugar this as follows:
1163
1164 f = \ g::(forall a. a->a) t::T ->
1165 let gi = g Int
1166 in case t of { T1 i -> T1 (gi i)
1167 other ->
1168 let gb = g Bool
1169 in case t of { T2 b -> T2 (gb b)
1170 other -> fail }}
1171
1172 Note that we do not treat the first column of patterns as a
1173 column of variables, because the coerced variables (gi, gb)
1174 would be of different types. So we get rather grotty code.
1175 But I don't think this is a common case, and if it was we could
1176 doubtless improve it.
1177
1178 Meanwhile, the strategy is:
1179 * treat each SigPat coercion (always non-identity coercions)
1180 as a separate block
1181 * deal with the stuff inside, and then wrap a binding round
1182 the result to bind the new variable (gi, gb, etc)
1183
1184
1185 ************************************************************************
1186 * *
1187 \subsection{Errors and contexts}
1188 * *
1189 ************************************************************************
1190 -}
1191
1192 maybeWrapPatCtxt :: Pat Name -> (TcM a -> TcM b) -> TcM a -> TcM b
1193 -- Not all patterns are worth pushing a context
1194 maybeWrapPatCtxt pat tcm thing_inside
1195 | not (worth_wrapping pat) = tcm thing_inside
1196 | otherwise = addErrCtxt msg $ tcm $ popErrCtxt thing_inside
1197 -- Remember to pop before doing thing_inside
1198 where
1199 worth_wrapping (VarPat {}) = False
1200 worth_wrapping (ParPat {}) = False
1201 worth_wrapping (AsPat {}) = False
1202 worth_wrapping _ = True
1203 msg = hang (ptext (sLit "In the pattern:")) 2 (ppr pat)
1204
1205 -----------------------------------------------
1206 checkExistentials :: [TyVar] -> PatEnv -> TcM ()
1207 -- See Note [Arrows and patterns]
1208 checkExistentials [] _ = return ()
1209 checkExistentials _ (PE { pe_ctxt = LetPat {}}) = failWithTc existentialLetPat
1210 checkExistentials _ (PE { pe_ctxt = LamPat ProcExpr }) = failWithTc existentialProcPat
1211 checkExistentials _ (PE { pe_lazy = True }) = failWithTc existentialLazyPat
1212 checkExistentials _ _ = return ()
1213
1214 existentialLazyPat :: SDoc
1215 existentialLazyPat
1216 = hang (ptext (sLit "An existential or GADT data constructor cannot be used"))
1217 2 (ptext (sLit "inside a lazy (~) pattern"))
1218
1219 existentialProcPat :: SDoc
1220 existentialProcPat
1221 = ptext (sLit "Proc patterns cannot use existential or GADT data constructors")
1222
1223 existentialLetPat :: SDoc
1224 existentialLetPat
1225 = vcat [text "My brain just exploded",
1226 text "I can't handle pattern bindings for existential or GADT data constructors.",
1227 text "Instead, use a case-expression, or do-notation, to unpack the constructor."]
1228
1229 badFieldCon :: ConLike -> Name -> SDoc
1230 badFieldCon con field
1231 = hsep [ptext (sLit "Constructor") <+> quotes (ppr con),
1232 ptext (sLit "does not have field"), quotes (ppr field)]
1233
1234 polyPatSig :: TcType -> SDoc
1235 polyPatSig sig_ty
1236 = hang (ptext (sLit "Illegal polymorphic type signature in pattern:"))
1237 2 (ppr sig_ty)
1238
1239 lazyUnliftedPatErr :: OutputableBndr name => Pat name -> TcM ()
1240 lazyUnliftedPatErr pat
1241 = failWithTc $
1242 hang (ptext (sLit "A lazy (~) pattern cannot contain unlifted types:"))
1243 2 (ppr pat)