Refactor TcRnMonad.mapAndRecoverM
[ghc.git] / compiler / typecheck / TcSigs.hs
1 {-
2 (c) The University of Glasgow 2006-2012
3 (c) The GRASP Project, Glasgow University, 1992-2002
4
5 -}
6
7 {-# LANGUAGE CPP #-}
8 {-# LANGUAGE TypeFamilies #-}
9
10 module TcSigs(
11 TcSigInfo(..),
12 TcIdSigInfo(..), TcIdSigInst,
13 TcPatSynInfo(..),
14 TcSigFun,
15
16 isPartialSig, hasCompleteSig, tcIdSigName, tcSigInfoName,
17 completeSigPolyId_maybe,
18
19 tcTySigs, tcUserTypeSig, completeSigFromId,
20 tcInstSig,
21
22 TcPragEnv, emptyPragEnv, lookupPragEnv, extendPragEnv,
23 mkPragEnv, tcSpecPrags, tcSpecWrapper, tcImpPrags, addInlinePrags
24 ) where
25
26 #include "HsVersions.h"
27
28 import GhcPrelude
29
30 import HsSyn
31 import TcHsType
32 import TcRnTypes
33 import TcRnMonad
34 import TcType
35 import TcMType
36 import TcValidity ( checkValidType )
37 import TcUnify( tcSkolemise, unifyType )
38 import Inst( topInstantiate )
39 import TcEnv( tcLookupId )
40 import TcEvidence( HsWrapper, (<.>) )
41 import Type( mkTyVarBinders )
42
43 import DynFlags
44 import Var ( TyVar, tyVarKind )
45 import VarSet
46 import VarEnv ( mkInScopeSet )
47 import Id ( Id, idName, idType, idInlinePragma, setInlinePragma, mkLocalId )
48 import PrelNames( mkUnboundName )
49 import BasicTypes
50 import Bag( foldrBag )
51 import Module( getModule )
52 import Name
53 import NameEnv
54 import Outputable
55 import SrcLoc
56 import Util( singleton )
57 import Maybes( orElse )
58 import Data.Maybe( mapMaybe )
59 import Control.Monad( unless )
60
61
62 {- -------------------------------------------------------------
63 Note [Overview of type signatures]
64 ----------------------------------------------------------------
65 Type signatures, including partial signatures, are jolly tricky,
66 especially on value bindings. Here's an overview.
67
68 f :: forall a. [a] -> [a]
69 g :: forall b. _ -> b
70
71 f = ...g...
72 g = ...f...
73
74 * HsSyn: a signature in a binding starts off as a TypeSig, in
75 type HsBinds.Sig
76
77 * When starting a mutually recursive group, like f/g above, we
78 call tcTySig on each signature in the group.
79
80 * tcTySig: Sig -> TcIdSigInfo
81 - For a /complete/ signature, like 'f' above, tcTySig kind-checks
82 the HsType, producing a Type, and wraps it in a CompleteSig, and
83 extend the type environment with this polymorphic 'f'.
84
85 - For a /partial/signature, like 'g' above, tcTySig does nothing
86 Instead it just wraps the pieces in a PartialSig, to be handled
87 later.
88
89 * tcInstSig: TcIdSigInfo -> TcIdSigInst
90 In tcMonoBinds, when looking at an individual binding, we use
91 tcInstSig to instantiate the signature forall's in the signature,
92 and attribute that instantiated (monomorphic) type to the
93 binder. You can see this in TcBinds.tcLhsId.
94
95 The instantiation does the obvious thing for complete signatures,
96 but for /partial/ signatures it starts from the HsSyn, so it
97 has to kind-check it etc: tcHsPartialSigType. It's convenient
98 to do this at the same time as instantiation, because we can
99 make the wildcards into unification variables right away, raather
100 than somehow quantifying over them. And the "TcLevel" of those
101 unification variables is correct because we are in tcMonoBinds.
102
103
104 Note [Scoped tyvars]
105 ~~~~~~~~~~~~~~~~~~~~
106 The -XScopedTypeVariables flag brings lexically-scoped type variables
107 into scope for any explicitly forall-quantified type variables:
108 f :: forall a. a -> a
109 f x = e
110 Then 'a' is in scope inside 'e'.
111
112 However, we do *not* support this
113 - For pattern bindings e.g
114 f :: forall a. a->a
115 (f,g) = e
116
117 Note [Binding scoped type variables]
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
119 The type variables *brought into lexical scope* by a type signature
120 may be a subset of the *quantified type variables* of the signatures,
121 for two reasons:
122
123 * With kind polymorphism a signature like
124 f :: forall f a. f a -> f a
125 may actually give rise to
126 f :: forall k. forall (f::k -> *) (a:k). f a -> f a
127 So the sig_tvs will be [k,f,a], but only f,a are scoped.
128 NB: the scoped ones are not necessarily the *inital* ones!
129
130 * Even aside from kind polymorphism, there may be more instantiated
131 type variables than lexically-scoped ones. For example:
132 type T a = forall b. b -> (a,b)
133 f :: forall c. T c
134 Here, the signature for f will have one scoped type variable, c,
135 but two instantiated type variables, c' and b'.
136
137 However, all of this only applies to the renamer. The typechecker
138 just puts all of them into the type environment; any lexical-scope
139 errors were dealt with by the renamer.
140
141 -}
142
143
144 {- *********************************************************************
145 * *
146 Utility functions for TcSigInfo
147 * *
148 ********************************************************************* -}
149
150 tcIdSigName :: TcIdSigInfo -> Name
151 tcIdSigName (CompleteSig { sig_bndr = id }) = idName id
152 tcIdSigName (PartialSig { psig_name = n }) = n
153
154 tcSigInfoName :: TcSigInfo -> Name
155 tcSigInfoName (TcIdSig idsi) = tcIdSigName idsi
156 tcSigInfoName (TcPatSynSig tpsi) = patsig_name tpsi
157
158 completeSigPolyId_maybe :: TcSigInfo -> Maybe TcId
159 completeSigPolyId_maybe sig
160 | TcIdSig sig_info <- sig
161 , CompleteSig { sig_bndr = id } <- sig_info = Just id
162 | otherwise = Nothing
163
164
165 {- *********************************************************************
166 * *
167 Typechecking user signatures
168 * *
169 ********************************************************************* -}
170
171 tcTySigs :: [LSig GhcRn] -> TcM ([TcId], TcSigFun)
172 tcTySigs hs_sigs
173 = checkNoErrs $ -- See Note [Fail eagerly on bad signatures]
174 do { ty_sigs_s <- mapAndRecoverM tcTySig hs_sigs
175 ; let ty_sigs = concat ty_sigs_s
176 poly_ids = mapMaybe completeSigPolyId_maybe ty_sigs
177 -- The returned [TcId] are the ones for which we have
178 -- a complete type signature.
179 -- See Note [Complete and partial type signatures]
180 env = mkNameEnv [(tcSigInfoName sig, sig) | sig <- ty_sigs]
181 ; return (poly_ids, lookupNameEnv env) }
182
183 tcTySig :: LSig GhcRn -> TcM [TcSigInfo]
184 tcTySig (L _ (IdSig _ id))
185 = do { let ctxt = FunSigCtxt (idName id) False
186 -- False: do not report redundant constraints
187 -- The user has no control over the signature!
188 sig = completeSigFromId ctxt id
189 ; return [TcIdSig sig] }
190
191 tcTySig (L loc (TypeSig _ names sig_ty))
192 = setSrcSpan loc $
193 do { sigs <- sequence [ tcUserTypeSig loc sig_ty (Just name)
194 | L _ name <- names ]
195 ; return (map TcIdSig sigs) }
196
197 tcTySig (L loc (PatSynSig _ names sig_ty))
198 = setSrcSpan loc $
199 do { tpsigs <- sequence [ tcPatSynSig name sig_ty
200 | L _ name <- names ]
201 ; return (map TcPatSynSig tpsigs) }
202
203 tcTySig _ = return []
204
205
206 tcUserTypeSig :: SrcSpan -> LHsSigWcType GhcRn -> Maybe Name
207 -> TcM TcIdSigInfo
208 -- A function or expression type signature
209 -- Returns a fully quantified type signature; even the wildcards
210 -- are quantified with ordinary skolems that should be instantiated
211 --
212 -- The SrcSpan is what to declare as the binding site of the
213 -- any skolems in the signature. For function signatures we
214 -- use the whole `f :: ty' signature; for expression signatures
215 -- just the type part.
216 --
217 -- Just n => Function type signature name :: type
218 -- Nothing => Expression type signature <expr> :: type
219 tcUserTypeSig loc hs_sig_ty mb_name
220 | isCompleteHsSig hs_sig_ty
221 = do { sigma_ty <- tcHsSigWcType ctxt_F hs_sig_ty
222 ; return $
223 CompleteSig { sig_bndr = mkLocalId name sigma_ty
224 , sig_ctxt = ctxt_T
225 , sig_loc = loc } }
226 -- Location of the <type> in f :: <type>
227
228 -- Partial sig with wildcards
229 | otherwise
230 = return (PartialSig { psig_name = name, psig_hs_ty = hs_sig_ty
231 , sig_ctxt = ctxt_F, sig_loc = loc })
232 where
233 name = case mb_name of
234 Just n -> n
235 Nothing -> mkUnboundName (mkVarOcc "<expression>")
236 ctxt_F = case mb_name of
237 Just n -> FunSigCtxt n False
238 Nothing -> ExprSigCtxt
239 ctxt_T = case mb_name of
240 Just n -> FunSigCtxt n True
241 Nothing -> ExprSigCtxt
242
243
244
245 completeSigFromId :: UserTypeCtxt -> Id -> TcIdSigInfo
246 -- Used for instance methods and record selectors
247 completeSigFromId ctxt id
248 = CompleteSig { sig_bndr = id
249 , sig_ctxt = ctxt
250 , sig_loc = getSrcSpan id }
251
252 isCompleteHsSig :: LHsSigWcType GhcRn -> Bool
253 -- ^ If there are no wildcards, return a LHsSigType
254 isCompleteHsSig (HsWC { hswc_ext = wcs }) = null wcs
255 isCompleteHsSig (XHsWildCardBndrs _) = panic "isCompleteHsSig"
256
257 {- Note [Fail eagerly on bad signatures]
258 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
259 If a type signature is wrong, fail immediately:
260
261 * the type sigs may bind type variables, so proceeding without them
262 can lead to a cascade of errors
263
264 * the type signature might be ambiguous, in which case checking
265 the code against the signature will give a very similar error
266 to the ambiguity error.
267
268 ToDo: this means we fall over if any type sig
269 is wrong (eg at the top level of the module),
270 which is over-conservative
271 -}
272
273 {- *********************************************************************
274 * *
275 Type checking a pattern synonym signature
276 * *
277 ************************************************************************
278
279 Note [Pattern synonym signatures]
280 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
281 Pattern synonym signatures are surprisingly tricky (see Trac #11224 for example).
282 In general they look like this:
283
284 pattern P :: forall univ_tvs. req_theta
285 => forall ex_tvs. prov_theta
286 => arg1 -> .. -> argn -> res_ty
287
288 For parsing and renaming we treat the signature as an ordinary LHsSigType.
289
290 Once we get to type checking, we decompose it into its parts, in tcPatSynSig.
291
292 * Note that 'forall univ_tvs' and 'req_theta =>'
293 and 'forall ex_tvs' and 'prov_theta =>'
294 are all optional. We gather the pieces at the top of tcPatSynSig
295
296 * Initially the implicitly-bound tyvars (added by the renamer) include both
297 universal and existential vars.
298
299 * After we kind-check the pieces and convert to Types, we do kind generalisation.
300
301 Note [solveEqualities in tcPatSynSig]
302 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
303 It's important that we solve /all/ the equalities in a pattern
304 synonym signature, because we are going to zonk the signature to
305 a Type (not a TcType), in TcPatSyn.tc_patsyn_finish, and that
306 fails if there are un-filled-in coercion variables mentioned
307 in the type (Trac #15694).
308
309 The best thing is simply to use solveEqualities to solve all the
310 equalites, rather than leaving them in the ambient constraints
311 to be solved later. Pattern synonyms are top-level, so there's
312 no problem with completely solving them.
313
314 (NB: this solveEqualities wraps tcImplicitTKBndrs, which itself
315 does a solveLocalEqualities; so solveEqualities isn't going to
316 make any further progress; it'll just report any unsolved ones,
317 and fail, as it should.)
318 -}
319
320 tcPatSynSig :: Name -> LHsSigType GhcRn -> TcM TcPatSynInfo
321 -- See Note [Pattern synonym signatures]
322 -- See Note [Recipe for checking a signature] in TcHsType
323 tcPatSynSig name sig_ty
324 | HsIB { hsib_ext = implicit_hs_tvs
325 , hsib_body = hs_ty } <- sig_ty
326 , (univ_hs_tvs, hs_req, hs_ty1) <- splitLHsSigmaTy hs_ty
327 , (ex_hs_tvs, hs_prov, hs_body_ty) <- splitLHsSigmaTy hs_ty1
328 = do { traceTc "tcPatSynSig 1" (ppr sig_ty)
329 ; (implicit_tvs, (univ_tvs, (ex_tvs, (req, prov, body_ty))))
330 <- solveEqualities $
331 -- See Note [solveEqualities in tcPatSynSig]
332 tcImplicitTKBndrs skol_info implicit_hs_tvs $
333 tcExplicitTKBndrs skol_info univ_hs_tvs $
334 tcExplicitTKBndrs skol_info ex_hs_tvs $
335 do { req <- tcHsContext hs_req
336 ; prov <- tcHsContext hs_prov
337 ; body_ty <- tcHsOpenType hs_body_ty
338 -- A (literal) pattern can be unlifted;
339 -- e.g. pattern Zero <- 0# (Trac #12094)
340 ; return (req, prov, body_ty) }
341
342 ; let ungen_patsyn_ty = build_patsyn_type [] implicit_tvs univ_tvs req
343 ex_tvs prov body_ty
344
345 -- Kind generalisation
346 ; kvs <- kindGeneralize ungen_patsyn_ty
347 ; traceTc "tcPatSynSig" (ppr ungen_patsyn_ty)
348
349 -- These are /signatures/ so we zonk to squeeze out any kind
350 -- unification variables. Do this after kindGeneralize which may
351 -- default kind variables to *.
352 ; implicit_tvs <- mapM zonkTyCoVarKind implicit_tvs
353 ; univ_tvs <- mapM zonkTyCoVarKind univ_tvs
354 ; ex_tvs <- mapM zonkTyCoVarKind ex_tvs
355 ; req <- zonkTcTypes req
356 ; prov <- zonkTcTypes prov
357 ; body_ty <- zonkTcType body_ty
358
359 -- Skolems have TcLevels too, though they're used only for debugging.
360 -- If you don't do this, the debugging checks fail in TcPatSyn.
361 -- Test case: patsyn/should_compile/T13441
362 ; tclvl <- getTcLevel
363 ; let env0 = mkEmptyTCvSubst $ mkInScopeSet $ mkVarSet kvs
364 (env1, implicit_tvs') = promoteSkolemsX tclvl env0 implicit_tvs
365 (env2, univ_tvs') = promoteSkolemsX tclvl env1 univ_tvs
366 (env3, ex_tvs') = promoteSkolemsX tclvl env2 ex_tvs
367 req' = substTys env3 req
368 prov' = substTys env3 prov
369 body_ty' = substTy env3 body_ty
370
371 -- Now do validity checking
372 ; checkValidType ctxt $
373 build_patsyn_type kvs implicit_tvs' univ_tvs' req' ex_tvs' prov' body_ty'
374
375 -- arguments become the types of binders. We thus cannot allow
376 -- levity polymorphism here
377 ; let (arg_tys, _) = tcSplitFunTys body_ty'
378 ; mapM_ (checkForLevPoly empty) arg_tys
379
380 ; traceTc "tcTySig }" $
381 vcat [ text "implicit_tvs" <+> ppr_tvs implicit_tvs'
382 , text "kvs" <+> ppr_tvs kvs
383 , text "univ_tvs" <+> ppr_tvs univ_tvs'
384 , text "req" <+> ppr req'
385 , text "ex_tvs" <+> ppr_tvs ex_tvs'
386 , text "prov" <+> ppr prov'
387 , text "body_ty" <+> ppr body_ty' ]
388 ; return (TPSI { patsig_name = name
389 , patsig_implicit_bndrs = mkTyVarBinders Inferred kvs ++
390 mkTyVarBinders Specified implicit_tvs'
391 , patsig_univ_bndrs = univ_tvs'
392 , patsig_req = req'
393 , patsig_ex_bndrs = ex_tvs'
394 , patsig_prov = prov'
395 , patsig_body_ty = body_ty' }) }
396 where
397 ctxt = PatSynCtxt name
398 skol_info = SigTypeSkol ctxt
399
400 build_patsyn_type kvs imp univ req ex prov body
401 = mkInvForAllTys kvs $
402 mkSpecForAllTys (imp ++ univ) $
403 mkFunTys req $
404 mkSpecForAllTys ex $
405 mkFunTys prov $
406 body
407 tcPatSynSig _ (XHsImplicitBndrs _) = panic "tcPatSynSig"
408
409 ppr_tvs :: [TyVar] -> SDoc
410 ppr_tvs tvs = braces (vcat [ ppr tv <+> dcolon <+> ppr (tyVarKind tv)
411 | tv <- tvs])
412
413
414 {- *********************************************************************
415 * *
416 Instantiating user signatures
417 * *
418 ********************************************************************* -}
419
420
421 tcInstSig :: TcIdSigInfo -> TcM TcIdSigInst
422 -- Instantiate a type signature; only used with plan InferGen
423 tcInstSig sig@(CompleteSig { sig_bndr = poly_id, sig_loc = loc })
424 = setSrcSpan loc $ -- Set the binding site of the tyvars
425 do { (tv_prs, theta, tau) <- tcInstType newMetaTyVarTyVars poly_id
426 -- See Note [Pattern bindings and complete signatures]
427
428 ; return (TISI { sig_inst_sig = sig
429 , sig_inst_skols = tv_prs
430 , sig_inst_wcs = []
431 , sig_inst_wcx = Nothing
432 , sig_inst_theta = theta
433 , sig_inst_tau = tau }) }
434
435 tcInstSig sig@(PartialSig { psig_hs_ty = hs_ty
436 , sig_ctxt = ctxt
437 , sig_loc = loc })
438 = setSrcSpan loc $ -- Set the binding site of the tyvars
439 do { (wcs, wcx, tv_names, tvs, theta, tau) <- tcHsPartialSigType ctxt hs_ty
440
441 -- Clone the quantified tyvars
442 -- Reason: we might have f, g :: forall a. a -> _ -> a
443 -- and we want it to behave exactly as if there were
444 -- two separate signatures. Cloning here seems like
445 -- the easiest way to do so, and is very similar to
446 -- the tcInstType in the CompleteSig case
447 -- See Trac #14643
448 ; let in_scope = mkInScopeSet $ closeOverKinds $ unionVarSets
449 [ mkVarSet (map snd wcs)
450 , maybe emptyVarSet tyCoVarsOfType wcx
451 , mkVarSet tvs
452 , tyCoVarsOfTypes theta
453 , tyCoVarsOfType tau ]
454 -- the in_scope is a bit bigger than nec'y, but too big is always
455 -- safe
456 empty_subst = mkEmptyTCvSubst in_scope
457 ; (subst, tvs') <- instSkolTyCoVarsX mk_sig_tv empty_subst tvs
458 ; let tv_prs = tv_names `zip` tvs'
459
460 ; return (TISI { sig_inst_sig = sig
461 , sig_inst_skols = tv_prs
462 , sig_inst_wcs = wcs
463 , sig_inst_wcx = wcx
464 , sig_inst_theta = substTys subst theta
465 , sig_inst_tau = substTy subst tau
466 }) }
467 where
468 mk_sig_tv old_name kind
469 = do { uniq <- newUnique
470 ; newTyVarTyVar (setNameUnique old_name uniq) kind }
471 -- Why newTyVarTyVar? See TcBinds
472 -- Note [Quantified variables in partial type signatures]
473
474
475 {- Note [Pattern bindings and complete signatures]
476 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
477 Consider
478 data T a = MkT a a
479 f :: forall a. a->a
480 g :: forall b. b->b
481 MkT f g = MkT (\x->x) (\y->y)
482 Here we'll infer a type from the pattern of 'T a', but if we feed in
483 the signature types for f and g, we'll end up unifying 'a' and 'b'
484
485 So we instantiate f and g's signature with TyVarTv skolems
486 (newMetaTyVarTyVars) that can unify with each other. If too much
487 unification takes place, we'll find out when we do the final
488 impedance-matching check in TcBinds.mkExport
489
490 See Note [Signature skolems] in TcType
491
492 None of this applies to a function binding with a complete
493 signature, which doesn't use tcInstSig. See TcBinds.tcPolyCheck.
494 -}
495
496 {- *********************************************************************
497 * *
498 Pragmas and PragEnv
499 * *
500 ********************************************************************* -}
501
502 type TcPragEnv = NameEnv [LSig GhcRn]
503
504 emptyPragEnv :: TcPragEnv
505 emptyPragEnv = emptyNameEnv
506
507 lookupPragEnv :: TcPragEnv -> Name -> [LSig GhcRn]
508 lookupPragEnv prag_fn n = lookupNameEnv prag_fn n `orElse` []
509
510 extendPragEnv :: TcPragEnv -> (Name, LSig GhcRn) -> TcPragEnv
511 extendPragEnv prag_fn (n, sig) = extendNameEnv_Acc (:) singleton prag_fn n sig
512
513 ---------------
514 mkPragEnv :: [LSig GhcRn] -> LHsBinds GhcRn -> TcPragEnv
515 mkPragEnv sigs binds
516 = foldl' extendPragEnv emptyNameEnv prs
517 where
518 prs = mapMaybe get_sig sigs
519
520 get_sig :: LSig GhcRn -> Maybe (Name, LSig GhcRn)
521 get_sig (L l (SpecSig x lnm@(L _ nm) ty inl))
522 = Just (nm, L l $ SpecSig x lnm ty (add_arity nm inl))
523 get_sig (L l (InlineSig x lnm@(L _ nm) inl))
524 = Just (nm, L l $ InlineSig x lnm (add_arity nm inl))
525 get_sig (L l (SCCFunSig x st lnm@(L _ nm) str))
526 = Just (nm, L l $ SCCFunSig x st lnm str)
527 get_sig _ = Nothing
528
529 add_arity n inl_prag -- Adjust inl_sat field to match visible arity of function
530 | Inline <- inl_inline inl_prag
531 -- add arity only for real INLINE pragmas, not INLINABLE
532 = case lookupNameEnv ar_env n of
533 Just ar -> inl_prag { inl_sat = Just ar }
534 Nothing -> WARN( True, text "mkPragEnv no arity" <+> ppr n )
535 -- There really should be a binding for every INLINE pragma
536 inl_prag
537 | otherwise
538 = inl_prag
539
540 -- ar_env maps a local to the arity of its definition
541 ar_env :: NameEnv Arity
542 ar_env = foldrBag lhsBindArity emptyNameEnv binds
543
544 lhsBindArity :: LHsBind GhcRn -> NameEnv Arity -> NameEnv Arity
545 lhsBindArity (L _ (FunBind { fun_id = id, fun_matches = ms })) env
546 = extendNameEnv env (unLoc id) (matchGroupArity ms)
547 lhsBindArity _ env = env -- PatBind/VarBind
548
549
550 -----------------
551 addInlinePrags :: TcId -> [LSig GhcRn] -> TcM TcId
552 addInlinePrags poly_id prags_for_me
553 | inl@(L _ prag) : inls <- inl_prags
554 = do { traceTc "addInlinePrag" (ppr poly_id $$ ppr prag)
555 ; unless (null inls) (warn_multiple_inlines inl inls)
556 ; return (poly_id `setInlinePragma` prag) }
557 | otherwise
558 = return poly_id
559 where
560 inl_prags = [L loc prag | L loc (InlineSig _ _ prag) <- prags_for_me]
561
562 warn_multiple_inlines _ [] = return ()
563
564 warn_multiple_inlines inl1@(L loc prag1) (inl2@(L _ prag2) : inls)
565 | inlinePragmaActivation prag1 == inlinePragmaActivation prag2
566 , noUserInlineSpec (inlinePragmaSpec prag1)
567 = -- Tiresome: inl1 is put there by virtue of being in a hs-boot loop
568 -- and inl2 is a user NOINLINE pragma; we don't want to complain
569 warn_multiple_inlines inl2 inls
570 | otherwise
571 = setSrcSpan loc $
572 addWarnTc NoReason
573 (hang (text "Multiple INLINE pragmas for" <+> ppr poly_id)
574 2 (vcat (text "Ignoring all but the first"
575 : map pp_inl (inl1:inl2:inls))))
576
577 pp_inl (L loc prag) = ppr prag <+> parens (ppr loc)
578
579
580 {- *********************************************************************
581 * *
582 SPECIALISE pragmas
583 * *
584 ************************************************************************
585
586 Note [Handling SPECIALISE pragmas]
587 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
588 The basic idea is this:
589
590 foo :: Num a => a -> b -> a
591 {-# SPECIALISE foo :: Int -> b -> Int #-}
592
593 We check that
594 (forall a b. Num a => a -> b -> a)
595 is more polymorphic than
596 forall b. Int -> b -> Int
597 (for which we could use tcSubType, but see below), generating a HsWrapper
598 to connect the two, something like
599 wrap = /\b. <hole> Int b dNumInt
600 This wrapper is put in the TcSpecPrag, in the ABExport record of
601 the AbsBinds.
602
603
604 f :: (Eq a, Ix b) => a -> b -> Bool
605 {-# SPECIALISE f :: (Ix p, Ix q) => Int -> (p,q) -> Bool #-}
606 f = <poly_rhs>
607
608 From this the typechecker generates
609
610 AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
611
612 SpecPrag (wrap_fn :: forall a b. (Eq a, Ix b) => XXX
613 -> forall p q. (Ix p, Ix q) => XXX[ Int/a, (p,q)/b ])
614
615 From these we generate:
616
617 Rule: forall p, q, (dp:Ix p), (dq:Ix q).
618 f Int (p,q) dInt ($dfInPair dp dq) = f_spec p q dp dq
619
620 Spec bind: f_spec = wrap_fn <poly_rhs>
621
622 Note that
623
624 * The LHS of the rule may mention dictionary *expressions* (eg
625 $dfIxPair dp dq), and that is essential because the dp, dq are
626 needed on the RHS.
627
628 * The RHS of f_spec, <poly_rhs> has a *copy* of 'binds', so that it
629 can fully specialise it.
630
631
632
633 From the TcSpecPrag, in DsBinds we generate a binding for f_spec and a RULE:
634
635 f_spec :: Int -> b -> Int
636 f_spec = wrap<f rhs>
637
638 RULE: forall b (d:Num b). f b d = f_spec b
639
640 The RULE is generated by taking apart the HsWrapper, which is a little
641 delicate, but works.
642
643 Some wrinkles
644
645 1. We don't use full-on tcSubType, because that does co and contra
646 variance and that in turn will generate too complex a LHS for the
647 RULE. So we use a single invocation of skolemise /
648 topInstantiate in tcSpecWrapper. (Actually I think that even
649 the "deeply" stuff may be too much, because it introduces lambdas,
650 though I think it can be made to work without too much trouble.)
651
652 2. We need to take care with type families (Trac #5821). Consider
653 type instance F Int = Bool
654 f :: Num a => a -> F a
655 {-# SPECIALISE foo :: Int -> Bool #-}
656
657 We *could* try to generate an f_spec with precisely the declared type:
658 f_spec :: Int -> Bool
659 f_spec = <f rhs> Int dNumInt |> co
660
661 RULE: forall d. f Int d = f_spec |> sym co
662
663 but the 'co' and 'sym co' are (a) playing no useful role, and (b) are
664 hard to generate. At all costs we must avoid this:
665 RULE: forall d. f Int d |> co = f_spec
666 because the LHS will never match (indeed it's rejected in
667 decomposeRuleLhs).
668
669 So we simply do this:
670 - Generate a constraint to check that the specialised type (after
671 skolemiseation) is equal to the instantiated function type.
672 - But *discard* the evidence (coercion) for that constraint,
673 so that we ultimately generate the simpler code
674 f_spec :: Int -> F Int
675 f_spec = <f rhs> Int dNumInt
676
677 RULE: forall d. f Int d = f_spec
678 You can see this discarding happening in
679
680 3. Note that the HsWrapper can transform *any* function with the right
681 type prefix
682 forall ab. (Eq a, Ix b) => XXX
683 regardless of XXX. It's sort of polymorphic in XXX. This is
684 useful: we use the same wrapper to transform each of the class ops, as
685 well as the dict. That's what goes on in TcInstDcls.mk_meth_spec_prags
686 -}
687
688 tcSpecPrags :: Id -> [LSig GhcRn]
689 -> TcM [LTcSpecPrag]
690 -- Add INLINE and SPECIALSE pragmas
691 -- INLINE prags are added to the (polymorphic) Id directly
692 -- SPECIALISE prags are passed to the desugarer via TcSpecPrags
693 -- Pre-condition: the poly_id is zonked
694 -- Reason: required by tcSubExp
695 tcSpecPrags poly_id prag_sigs
696 = do { traceTc "tcSpecPrags" (ppr poly_id <+> ppr spec_sigs)
697 ; unless (null bad_sigs) warn_discarded_sigs
698 ; pss <- mapAndRecoverM (wrapLocM (tcSpecPrag poly_id)) spec_sigs
699 ; return $ concatMap (\(L l ps) -> map (L l) ps) pss }
700 where
701 spec_sigs = filter isSpecLSig prag_sigs
702 bad_sigs = filter is_bad_sig prag_sigs
703 is_bad_sig s = not (isSpecLSig s || isInlineLSig s || isSCCFunSig s)
704
705 warn_discarded_sigs
706 = addWarnTc NoReason
707 (hang (text "Discarding unexpected pragmas for" <+> ppr poly_id)
708 2 (vcat (map (ppr . getLoc) bad_sigs)))
709
710 --------------
711 tcSpecPrag :: TcId -> Sig GhcRn -> TcM [TcSpecPrag]
712 tcSpecPrag poly_id prag@(SpecSig _ fun_name hs_tys inl)
713 -- See Note [Handling SPECIALISE pragmas]
714 --
715 -- The Name fun_name in the SpecSig may not be the same as that of the poly_id
716 -- Example: SPECIALISE for a class method: the Name in the SpecSig is
717 -- for the selector Id, but the poly_id is something like $cop
718 -- However we want to use fun_name in the error message, since that is
719 -- what the user wrote (Trac #8537)
720 = addErrCtxt (spec_ctxt prag) $
721 do { warnIf (not (isOverloadedTy poly_ty || isInlinePragma inl))
722 (text "SPECIALISE pragma for non-overloaded function"
723 <+> quotes (ppr fun_name))
724 -- Note [SPECIALISE pragmas]
725 ; spec_prags <- mapM tc_one hs_tys
726 ; traceTc "tcSpecPrag" (ppr poly_id $$ nest 2 (vcat (map ppr spec_prags)))
727 ; return spec_prags }
728 where
729 name = idName poly_id
730 poly_ty = idType poly_id
731 spec_ctxt prag = hang (text "In the SPECIALISE pragma") 2 (ppr prag)
732
733 tc_one hs_ty
734 = do { spec_ty <- tcHsSigType (FunSigCtxt name False) hs_ty
735 ; wrap <- tcSpecWrapper (FunSigCtxt name True) poly_ty spec_ty
736 ; return (SpecPrag poly_id wrap inl) }
737
738 tcSpecPrag _ prag = pprPanic "tcSpecPrag" (ppr prag)
739
740 --------------
741 tcSpecWrapper :: UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
742 -- A simpler variant of tcSubType, used for SPECIALISE pragmas
743 -- See Note [Handling SPECIALISE pragmas], wrinkle 1
744 tcSpecWrapper ctxt poly_ty spec_ty
745 = do { (sk_wrap, inst_wrap)
746 <- tcSkolemise ctxt spec_ty $ \ _ spec_tau ->
747 do { (inst_wrap, tau) <- topInstantiate orig poly_ty
748 ; _ <- unifyType Nothing spec_tau tau
749 -- Deliberately ignore the evidence
750 -- See Note [Handling SPECIALISE pragmas],
751 -- wrinkle (2)
752 ; return inst_wrap }
753 ; return (sk_wrap <.> inst_wrap) }
754 where
755 orig = SpecPragOrigin ctxt
756
757 --------------
758 tcImpPrags :: [LSig GhcRn] -> TcM [LTcSpecPrag]
759 -- SPECIALISE pragmas for imported things
760 tcImpPrags prags
761 = do { this_mod <- getModule
762 ; dflags <- getDynFlags
763 ; if (not_specialising dflags) then
764 return []
765 else do
766 { pss <- mapAndRecoverM (wrapLocM tcImpSpec)
767 [L loc (name,prag)
768 | (L loc prag@(SpecSig _ (L _ name) _ _)) <- prags
769 , not (nameIsLocalOrFrom this_mod name) ]
770 ; return $ concatMap (\(L l ps) -> map (L l) ps) pss } }
771 where
772 -- Ignore SPECIALISE pragmas for imported things
773 -- when we aren't specialising, or when we aren't generating
774 -- code. The latter happens when Haddocking the base library;
775 -- we don't want complaints about lack of INLINABLE pragmas
776 not_specialising dflags
777 | not (gopt Opt_Specialise dflags) = True
778 | otherwise = case hscTarget dflags of
779 HscNothing -> True
780 HscInterpreted -> True
781 _other -> False
782
783 tcImpSpec :: (Name, Sig GhcRn) -> TcM [TcSpecPrag]
784 tcImpSpec (name, prag)
785 = do { id <- tcLookupId name
786 ; unless (isAnyInlinePragma (idInlinePragma id))
787 (addWarnTc NoReason (impSpecErr name))
788 ; tcSpecPrag id prag }
789
790 impSpecErr :: Name -> SDoc
791 impSpecErr name
792 = hang (text "You cannot SPECIALISE" <+> quotes (ppr name))
793 2 (vcat [ text "because its definition has no INLINE/INLINABLE pragma"
794 , parens $ sep
795 [ text "or its defining module" <+> quotes (ppr mod)
796 , text "was compiled without -O"]])
797 where
798 mod = nameModule name