{-
(c) The University of Glasgow 2006-2012
(c) The GRASP Project, Glasgow University, 1992-2002
-}{-# LANGUAGE CPP #-}{-# LANGUAGE TypeFamilies #-}moduleTcSigs(TcSigInfo(..),TcIdSigInfo(..),TcIdSigInst,TcPatSynInfo(..),TcSigFun,isPartialSig,hasCompleteSig,tcIdSigName ,tcSigInfoName ,completeSigPolyId_maybe ,tcTySigs ,tcUserTypeSig ,completeSigFromId ,tcInstSig ,TcPragEnv ,emptyPragEnv ,lookupPragEnv ,extendPragEnv ,mkPragEnv ,tcSpecPrags ,tcSpecWrapper ,tcImpPrags ,addInlinePrags )where#include "HsVersions.h"
importGhcPreludeimportHsSynimportTcHsType importTcRnTypesimportTcRnMonad importTcTypeimportTcMType importTcValidity (checkValidType )importTcUnify (tcSkolemise ,unifyType )importInst (topInstantiate )importTcEnv (tcLookupId )importTcEvidence(HsWrapper,(<.>))importType(mkTyVarBinders)importDynFlagsimportVar(TyVar,tyVarKind)importId(Id,idName,idType,idInlinePragma,setInlinePragma,mkLocalId)importPrelNames(mkUnboundName)importBasicTypesimportBag(foldrBag)importModule(getModule)importNameimportNameEnvimportOutputableimportSrcLocimportUtil(singleton)importMaybes(orElse)importData.Maybe(mapMaybe)importControl.Monad(unless){- -------------------------------------------------------------
 Note [Overview of type signatures]
----------------------------------------------------------------
Type signatures, including partial signatures, are jolly tricky,
especially on value bindings. Here's an overview.
 f :: forall a. [a] -> [a]
 g :: forall b. _ -> b
 f = ...g...
 g = ...f...
* HsSyn: a signature in a binding starts off as a TypeSig, in
 type HsBinds.Sig
* When starting a mutually recursive group, like f/g above, we
 call tcTySig on each signature in the group.
* tcTySig: Sig -> TcIdSigInfo
 - For a /complete/ signature, like 'f' above, tcTySig kind-checks
 the HsType, producing a Type, and wraps it in a CompleteSig, and
 extend the type environment with this polymorphic 'f'.
 - For a /partial/signature, like 'g' above, tcTySig does nothing
 Instead it just wraps the pieces in a PartialSig, to be handled
 later.
* tcInstSig: TcIdSigInfo -> TcIdSigInst
 In tcMonoBinds, when looking at an individual binding, we use
 tcInstSig to instantiate the signature forall's in the signature,
 and attribute that instantiated (monomorphic) type to the
 binder. You can see this in TcBinds.tcLhsId.
 The instantiation does the obvious thing for complete signatures,
 but for /partial/ signatures it starts from the HsSyn, so it
 has to kind-check it etc: tcHsPartialSigType. It's convenient
 to do this at the same time as instantiation, because we can
 make the wildcards into unification variables right away, raather
 than somehow quantifying over them. And the "TcLevel" of those
 unification variables is correct because we are in tcMonoBinds.
Note [Scoped tyvars]
~~~~~~~~~~~~~~~~~~~~
The -XScopedTypeVariables flag brings lexically-scoped type variables
into scope for any explicitly forall-quantified type variables:
 f :: forall a. a -> a
 f x = e
Then 'a' is in scope inside 'e'.
However, we do *not* support this
 - For pattern bindings e.g
 f :: forall a. a->a
 (f,g) = e
Note [Binding scoped type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The type variables *brought into lexical scope* by a type signature
may be a subset of the *quantified type variables* of the signatures,
for two reasons:
* With kind polymorphism a signature like
 f :: forall f a. f a -> f a
 may actually give rise to
 f :: forall k. forall (f::k -> *) (a:k). f a -> f a
 So the sig_tvs will be [k,f,a], but only f,a are scoped.
 NB: the scoped ones are not necessarily the *inital* ones!
* Even aside from kind polymorphism, there may be more instantiated
 type variables than lexically-scoped ones. For example:
 type T a = forall b. b -> (a,b)
 f :: forall c. T c
 Here, the signature for f will have one scoped type variable, c,
 but two instantiated type variables, c' and b'.
However, all of this only applies to the renamer. The typechecker
just puts all of them into the type environment; any lexical-scope
errors were dealt with by the renamer.
-}{- *********************************************************************
* *
 Utility functions for TcSigInfo
* *
********************************************************************* -}tcIdSigName::TcIdSigInfo->NametcIdSigName (CompleteSig{sig_bndr=id })=idNameid tcIdSigName(PartialSig{psig_name=n })=n tcSigInfoName::TcSigInfo->NametcSigInfoName (TcIdSigidsi )=tcIdSigName idsi tcSigInfoName(TcPatSynSigtpsi )=patsig_nametpsi completeSigPolyId_maybe::TcSigInfo->MaybeTcIdcompleteSigPolyId_maybe sig |TcIdSigsig_info <-sig ,CompleteSig{sig_bndr=id }<-sig_info =Justid |otherwise=Nothing{- *********************************************************************
* *
 Typechecking user signatures
* *
********************************************************************* -}tcTySigs::[LSigGhcRn]->TcM([TcId],TcSigFun)tcTySigs hs_sigs =checkNoErrs $do{-- Fail if any of the signatures is duff-- Hence mapAndReportM-- See Note [Fail eagerly on bad signatures]ty_sigs_s <-mapAndReportM tcTySig hs_sigs ;letty_sigs =concatty_sigs_s poly_ids =mapMaybecompleteSigPolyId_maybe ty_sigs -- The returned [TcId] are the ones for which we have-- a complete type signature.-- See Note [Complete and partial type signatures]env =mkNameEnv[(tcSigInfoName sig ,sig )|sig <-ty_sigs ];return(poly_ids ,lookupNameEnvenv )}tcTySig::LSigGhcRn->TcM[TcSigInfo]tcTySig (L_(IdSig_id ))=do{letctxt =FunSigCtxt(idNameid )False-- False: do not report redundant constraints-- The user has no control over the signature!sig =completeSigFromId ctxt id ;return[TcIdSigsig ]}tcTySig(Lloc (TypeSig_names sig_ty ))=setSrcSpan loc $do{sigs <-sequence[tcUserTypeSig loc sig_ty (Justname )|L_name <-names ];return(mapTcIdSigsigs )}tcTySig(Lloc (PatSynSig_names sig_ty ))=setSrcSpan loc $do{tpsigs <-sequence[tcPatSynSig name sig_ty |L_name <-names ];return(mapTcPatSynSigtpsigs )}tcTySig_=return[]tcUserTypeSig::SrcSpan->LHsSigWcTypeGhcRn->MaybeName->TcMTcIdSigInfo-- A function or expression type signature-- Returns a fully quantified type signature; even the wildcards-- are quantified with ordinary skolems that should be instantiated---- The SrcSpan is what to declare as the binding site of the-- any skolems in the signature. For function signatures we-- use the whole `f :: ty' signature; for expression signatures-- just the type part.---- Just n => Function type signature name :: type-- Nothing => Expression type signature <expr> :: typetcUserTypeSig loc hs_sig_ty mb_name |isCompleteHsSig hs_sig_ty =do{sigma_ty <-tcHsSigWcType ctxt_F hs_sig_ty ;traceTc "tcuser"(pprsigma_ty );return$CompleteSig{sig_bndr=mkLocalIdname sigma_ty ,sig_ctxt=ctxt_T ,sig_loc=loc }}-- Location of the <type> in f :: <type>-- Partial sig with wildcards|otherwise=return(PartialSig{psig_name=name ,psig_hs_ty=hs_sig_ty ,sig_ctxt=ctxt_F ,sig_loc=loc })wherename =casemb_name ofJustn ->n Nothing->mkUnboundName(mkVarOcc"<expression>")ctxt_F =casemb_name ofJustn ->FunSigCtxtn FalseNothing->ExprSigCtxtctxt_T =casemb_name ofJustn ->FunSigCtxtn TrueNothing->ExprSigCtxtcompleteSigFromId::UserTypeCtxt->Id->TcIdSigInfo-- Used for instance methods and record selectorscompleteSigFromId ctxt id =CompleteSig{sig_bndr=id ,sig_ctxt=ctxt ,sig_loc=getSrcSpanid }isCompleteHsSig::LHsSigWcTypeGhcRn->Bool-- ^ If there are no wildcards, return a LHsSigTypeisCompleteHsSig (HsWC{hswc_ext=wcs ,hswc_body=HsIB{hsib_body=hs_ty }})=nullwcs &&no_anon_wc hs_ty isCompleteHsSig(HsWC_(XHsImplicitBndrs_))=panic"isCompleteHsSig"isCompleteHsSig(XHsWildCardBndrs_)=panic"isCompleteHsSig"no_anon_wc::LHsTypeGhcRn->Boolno_anon_wc lty =go lty wherego (L_ty )=casety ofHsWildCardTy_->FalseHsAppTy_ty1 ty2 ->go ty1 &&go ty2 HsAppKindTy_ty ki ->go ty &&go ki HsFunTy_ty1 ty2 ->go ty1 &&go ty2 HsListTy_ty ->go ty HsTupleTy__tys ->gos tys HsSumTy_tys ->gos tys HsOpTy_ty1 _ty2 ->go ty1 &&go ty2 HsParTy_ty ->go ty HsIParamTy__ty ->go ty HsKindSig_ty kind ->go ty &&go kind HsDocTy_ty _->go ty HsBangTy__ty ->go ty HsRecTy_flds ->gos $map(cd_fld_type.unLoc)flds HsExplicitListTy__tys ->gos tys HsExplicitTupleTy_tys ->gos tys HsForAllTy{hst_bndrs=bndrs ,hst_body=ty }->no_anon_wc_bndrs bndrs &&go ty HsQualTy{hst_ctxt=L_ctxt ,hst_body=ty }->gos ctxt &&go ty HsSpliceTy_(HsSpliced__(HsSplicedTyty ))->go $LnoSrcSpanty HsSpliceTy{}->TrueHsTyLit{}->TrueHsTyVar{}->TrueHsStarTy{}->TrueXHsType{}->True-- Core type, which does not have any wildcardgos =allgo no_anon_wc_bndrs::[LHsTyVarBndrGhcRn]->Boolno_anon_wc_bndrs ltvs =all(go .unLoc)ltvs wherego (UserTyVar__)=Truego(KindedTyVar__ki )=no_anon_wc ki go(XTyVarBndr{})=panic"no_anon_wc_bndrs"{- Note [Fail eagerly on bad signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If a type signature is wrong, fail immediately:
 * the type sigs may bind type variables, so proceeding without them
 can lead to a cascade of errors
 * the type signature might be ambiguous, in which case checking
 the code against the signature will give a very similar error
 to the ambiguity error.
ToDo: this means we fall over if any top-level type signature in the
module is wrong, because we typecheck all the signatures together
(see TcBinds.tcValBinds). Moreover, because of top-level
captureTopConstraints, only insoluble constraints will be reported.
We typecheck all signatures at the same time because a signature
like f,g :: blah might have f and g from different SCCs.
So it's a bit awkward to get better error recovery, and no one
has complained!
-}{- *********************************************************************
* *
 Type checking a pattern synonym signature
* *
************************************************************************
Note [Pattern synonym signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pattern synonym signatures are surprisingly tricky (see #11224 for example).
In general they look like this:
 pattern P :: forall univ_tvs. req_theta
 => forall ex_tvs. prov_theta
 => arg1 -> .. -> argn -> res_ty
For parsing and renaming we treat the signature as an ordinary LHsSigType.
Once we get to type checking, we decompose it into its parts, in tcPatSynSig.
* Note that 'forall univ_tvs' and 'req_theta =>'
 and 'forall ex_tvs' and 'prov_theta =>'
 are all optional. We gather the pieces at the top of tcPatSynSig
* Initially the implicitly-bound tyvars (added by the renamer) include both
 universal and existential vars.
* After we kind-check the pieces and convert to Types, we do kind generalisation.
Note [solveEqualities in tcPatSynSig]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's important that we solve /all/ the equalities in a pattern
synonym signature, because we are going to zonk the signature to
a Type (not a TcType), in TcPatSyn.tc_patsyn_finish, and that
fails if there are un-filled-in coercion variables mentioned
in the type (#15694).
The best thing is simply to use solveEqualities to solve all the
equalites, rather than leaving them in the ambient constraints
to be solved later. Pattern synonyms are top-level, so there's
no problem with completely solving them.
(NB: this solveEqualities wraps newImplicitTKBndrs, which itself
does a solveLocalEqualities; so solveEqualities isn't going to
make any further progress; it'll just report any unsolved ones,
and fail, as it should.)
-}tcPatSynSig::Name->LHsSigTypeGhcRn->TcMTcPatSynInfo-- See Note [Pattern synonym signatures]-- See Note [Recipe for checking a signature] in TcHsTypetcPatSynSig name sig_ty |HsIB{hsib_ext=implicit_hs_tvs ,hsib_body=hs_ty }<-sig_ty ,(univ_hs_tvs ,hs_req ,hs_ty1 )<-splitLHsSigmaTyInvishs_ty ,(ex_hs_tvs ,hs_prov ,hs_body_ty )<-splitLHsSigmaTyInvishs_ty1 =do{traceTc "tcPatSynSig 1"(pprsig_ty );(implicit_tvs ,(univ_tvs ,(ex_tvs ,(req ,prov ,body_ty ))))<-pushTcLevelM_ $solveEqualities $-- See Note [solveEqualities in tcPatSynSig]bindImplicitTKBndrs_Skol implicit_hs_tvs $bindExplicitTKBndrs_Skol univ_hs_tvs $bindExplicitTKBndrs_Skol ex_hs_tvs $do{req <-tcHsContext hs_req ;prov <-tcHsContext hs_prov ;body_ty <-tcHsOpenType hs_body_ty -- A (literal) pattern can be unlifted;-- e.g. pattern Zero <- 0# (#12094);return(req ,prov ,body_ty )};letungen_patsyn_ty =build_patsyn_type []implicit_tvs univ_tvs req ex_tvs prov body_ty -- Kind generalisation;kvs <-kindGeneralize ungen_patsyn_ty ;traceTc "tcPatSynSig"(pprungen_patsyn_ty )-- These are /signatures/ so we zonk to squeeze out any kind-- unification variables. Do this after kindGeneralize which may-- default kind variables to *.;implicit_tvs <-zonkAndScopedSort implicit_tvs ;univ_tvs <-mapMzonkTyCoVarKind univ_tvs ;ex_tvs <-mapMzonkTyCoVarKind ex_tvs ;req <-zonkTcTypes req ;prov <-zonkTcTypes prov ;body_ty <-zonkTcType body_ty -- Skolems have TcLevels too, though they're used only for debugging.-- If you don't do this, the debugging checks fail in TcPatSyn.-- Test case: patsyn/should_compile/T13441{-
 ; tclvl <- getTcLevel
 ; let env0 = mkEmptyTCvSubst $ mkInScopeSet $ mkVarSet kvs
 (env1, implicit_tvs') = promoteSkolemsX tclvl env0 implicit_tvs
 (env2, univ_tvs') = promoteSkolemsX tclvl env1 univ_tvs
 (env3, ex_tvs') = promoteSkolemsX tclvl env2 ex_tvs
 req' = substTys env3 req
 prov' = substTys env3 prov
 body_ty' = substTy env3 body_ty
-};letimplicit_tvs' =implicit_tvs univ_tvs' =univ_tvs ex_tvs' =ex_tvs req' =req prov' =prov body_ty' =body_ty -- Now do validity checking;checkValidType ctxt $build_patsyn_type kvs implicit_tvs' univ_tvs' req' ex_tvs' prov' body_ty' -- arguments become the types of binders. We thus cannot allow-- levity polymorphism here;let(arg_tys ,_)=tcSplitFunTysbody_ty' ;mapM_(checkForLevPoly empty)arg_tys ;traceTc "tcTySig }"$vcat[text"implicit_tvs"<+>ppr_tvs implicit_tvs' ,text"kvs"<+>ppr_tvs kvs ,text"univ_tvs"<+>ppr_tvs univ_tvs' ,text"req"<+>pprreq' ,text"ex_tvs"<+>ppr_tvs ex_tvs' ,text"prov"<+>pprprov' ,text"body_ty"<+>pprbody_ty' ];return(TPSI{patsig_name=name ,patsig_implicit_bndrs=mkTyVarBindersInferredkvs ++mkTyVarBindersSpecifiedimplicit_tvs' ,patsig_univ_bndrs=univ_tvs' ,patsig_req=req' ,patsig_ex_bndrs=ex_tvs' ,patsig_prov=prov' ,patsig_body_ty=body_ty' })}wherectxt =PatSynCtxtname build_patsyn_type kvs imp univ req ex prov body =mkInvForAllTyskvs $mkSpecForAllTys(imp ++univ )$mkPhiTyreq $mkSpecForAllTysex $mkPhiTyprov $body tcPatSynSig_(XHsImplicitBndrs_)=panic"tcPatSynSig"ppr_tvs::[TyVar]->SDocppr_tvs tvs =braces(vcat[pprtv <+>dcolon<+>ppr(tyVarKindtv )|tv <-tvs ]){- *********************************************************************
* *
 Instantiating user signatures
* *
********************************************************************* -}tcInstSig::TcIdSigInfo->TcMTcIdSigInst-- Instantiate a type signature; only used with plan InferGentcInstSig sig @(CompleteSig{sig_bndr=poly_id ,sig_loc=loc })=setSrcSpan loc $-- Set the binding site of the tyvarsdo{(tv_prs ,theta ,tau )<-tcInstType newMetaTyVarTyVars poly_id -- See Note [Pattern bindings and complete signatures];return(TISI{sig_inst_sig=sig ,sig_inst_skols=tv_prs ,sig_inst_wcs=[],sig_inst_wcx=Nothing,sig_inst_theta=theta ,sig_inst_tau=tau })}tcInstSighs_sig @(PartialSig{psig_hs_ty=hs_ty ,sig_ctxt=ctxt ,sig_loc=loc })=setSrcSpan loc $-- Set the binding site of the tyvarsdo{traceTc "Staring partial sig {"(pprhs_sig );(wcs ,wcx ,tv_names ,tvs ,theta ,tau )<-tcHsPartialSigType ctxt hs_ty -- Clone the quantified tyvars-- Reason: we might have f, g :: forall a. a -> _ -> a-- and we want it to behave exactly as if there were-- two separate signatures. Cloning here seems like-- the easiest way to do so, and is very similar to-- the tcInstType in the CompleteSig case-- See #14643;(subst ,tvs' )<-newMetaTyVarTyVars tvs -- Why newMetaTyVarTyVars? See TcBinds-- Note [Quantified variables in partial type signatures];lettv_prs =tv_names `zip`tvs' inst_sig =TISI{sig_inst_sig=hs_sig ,sig_inst_skols=tv_prs ,sig_inst_wcs=wcs ,sig_inst_wcx=wcx ,sig_inst_theta=substTysUncheckedsubst theta ,sig_inst_tau=substTyUncheckedsubst tau };traceTc "End partial sig }"(pprinst_sig );returninst_sig }{- Note [Pattern bindings and complete signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
 data T a = MkT a a
 f :: forall a. a->a
 g :: forall b. b->b
 MkT f g = MkT (\x->x) (\y->y)
Here we'll infer a type from the pattern of 'T a', but if we feed in
the signature types for f and g, we'll end up unifying 'a' and 'b'
So we instantiate f and g's signature with TyVarTv skolems
(newMetaTyVarTyVars) that can unify with each other. If too much
unification takes place, we'll find out when we do the final
impedance-matching check in TcBinds.mkExport
See Note [Signature skolems] in TcType
None of this applies to a function binding with a complete
signature, which doesn't use tcInstSig. See TcBinds.tcPolyCheck.
-}{- *********************************************************************
* *
 Pragmas and PragEnv
* *
********************************************************************* -}typeTcPragEnv =NameEnv[LSigGhcRn]emptyPragEnv::TcPragEnv emptyPragEnv =emptyNameEnvlookupPragEnv::TcPragEnv ->Name->[LSigGhcRn]lookupPragEnv prag_fn n =lookupNameEnvprag_fn n `orElse`[]extendPragEnv::TcPragEnv ->(Name,LSigGhcRn)->TcPragEnv extendPragEnv prag_fn (n ,sig )=extendNameEnv_Acc(:)singletonprag_fn n sig ---------------mkPragEnv::[LSigGhcRn]->LHsBindsGhcRn->TcPragEnv mkPragEnv sigs binds =foldl'extendPragEnv emptyNameEnvprs whereprs =mapMaybeget_sig sigs get_sig::LSigGhcRn->Maybe(Name,LSigGhcRn)get_sig (Ll (SpecSigx lnm @(L_nm )ty inl ))=Just(nm ,Ll $SpecSigx lnm ty (add_arity nm inl ))get_sig(Ll (InlineSigx lnm @(L_nm )inl ))=Just(nm ,Ll $InlineSigx lnm (add_arity nm inl ))get_sig(Ll (SCCFunSigx st lnm @(L_nm )str ))=Just(nm ,Ll $SCCFunSigx st lnm str )get_sig_=Nothingadd_arity n inl_prag -- Adjust inl_sat field to match visible arity of function|Inline<-inl_inlineinl_prag -- add arity only for real INLINE pragmas, not INLINABLE=caselookupNameEnvar_env n ofJustar ->inl_prag {inl_sat=Justar }Nothing->WARN(True,text"mkPragEnv no arity"<+>pprn)-- There really should be a binding for every INLINE pragmainl_prag |otherwise=inl_prag -- ar_env maps a local to the arity of its definitionar_env::NameEnvArityar_env =foldrBaglhsBindArity emptyNameEnvbinds lhsBindArity::LHsBindGhcRn->NameEnvArity->NameEnvAritylhsBindArity (L_(FunBind{fun_id=id ,fun_matches=ms }))env =extendNameEnvenv (unLocid )(matchGroupArityms )lhsBindArity_env =env -- PatBind/VarBind-----------------addInlinePrags::TcId->[LSigGhcRn]->TcMTcIdaddInlinePrags poly_id prags_for_me |inl @(L_prag ):inls <-inl_prags =do{traceTc "addInlinePrag"(pprpoly_id $$pprprag );unless(nullinls )(warn_multiple_inlines inl inls );return(poly_id `setInlinePragma`prag )}|otherwise=returnpoly_id whereinl_prags =[Lloc prag |Lloc (InlineSig__prag )<-prags_for_me ]warn_multiple_inlines _[]=return()warn_multiple_inlinesinl1 @(Lloc prag1 )(inl2 @(L_prag2 ):inls )|inlinePragmaActivationprag1 ==inlinePragmaActivationprag2 ,noUserInlineSpec(inlinePragmaSpecprag1 )=-- Tiresome: inl1 is put there by virtue of being in a hs-boot loop-- and inl2 is a user NOINLINE pragma; we don't want to complainwarn_multiple_inlines inl2 inls |otherwise=setSrcSpan loc $addWarnTc NoReason(hang(text"Multiple INLINE pragmas for"<+>pprpoly_id )2(vcat(text"Ignoring all but the first":mappp_inl (inl1 :inl2 :inls ))))pp_inl (Lloc prag )=pprprag <+>parens(pprloc ){- *********************************************************************
* *
 SPECIALISE pragmas
* *
************************************************************************
Note [Handling SPECIALISE pragmas]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The basic idea is this:
 foo :: Num a => a -> b -> a
 {-# SPECIALISE foo :: Int -> b -> Int #-}
We check that
 (forall a b. Num a => a -> b -> a)
 is more polymorphic than
 forall b. Int -> b -> Int
(for which we could use tcSubType, but see below), generating a HsWrapper
to connect the two, something like
 wrap = /\b. <hole> Int b dNumInt
This wrapper is put in the TcSpecPrag, in the ABExport record of
the AbsBinds.
 f :: (Eq a, Ix b) => a -> b -> Bool
 {-# SPECIALISE f :: (Ix p, Ix q) => Int -> (p,q) -> Bool #-}
 f = <poly_rhs>
From this the typechecker generates
 AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
 SpecPrag (wrap_fn :: forall a b. (Eq a, Ix b) => XXX
 -> forall p q. (Ix p, Ix q) => XXX[ Int/a, (p,q)/b ])
From these we generate:
 Rule: forall p, q, (dp:Ix p), (dq:Ix q).
 f Int (p,q) dInt ($dfInPair dp dq) = f_spec p q dp dq
 Spec bind: f_spec = wrap_fn <poly_rhs>
Note that
 * The LHS of the rule may mention dictionary *expressions* (eg
 $dfIxPair dp dq), and that is essential because the dp, dq are
 needed on the RHS.
 * The RHS of f_spec, <poly_rhs> has a *copy* of 'binds', so that it
 can fully specialise it.
From the TcSpecPrag, in DsBinds we generate a binding for f_spec and a RULE:
 f_spec :: Int -> b -> Int
 f_spec = wrap<f rhs>
 RULE: forall b (d:Num b). f b d = f_spec b
The RULE is generated by taking apart the HsWrapper, which is a little
delicate, but works.
Some wrinkles
1. We don't use full-on tcSubType, because that does co and contra
 variance and that in turn will generate too complex a LHS for the
 RULE. So we use a single invocation of skolemise /
 topInstantiate in tcSpecWrapper. (Actually I think that even
 the "deeply" stuff may be too much, because it introduces lambdas,
 though I think it can be made to work without too much trouble.)
2. We need to take care with type families (#5821). Consider
 type instance F Int = Bool
 f :: Num a => a -> F a
 {-# SPECIALISE foo :: Int -> Bool #-}
 We *could* try to generate an f_spec with precisely the declared type:
 f_spec :: Int -> Bool
 f_spec = <f rhs> Int dNumInt |> co
 RULE: forall d. f Int d = f_spec |> sym co
 but the 'co' and 'sym co' are (a) playing no useful role, and (b) are
 hard to generate. At all costs we must avoid this:
 RULE: forall d. f Int d |> co = f_spec
 because the LHS will never match (indeed it's rejected in
 decomposeRuleLhs).
 So we simply do this:
 - Generate a constraint to check that the specialised type (after
 skolemiseation) is equal to the instantiated function type.
 - But *discard* the evidence (coercion) for that constraint,
 so that we ultimately generate the simpler code
 f_spec :: Int -> F Int
 f_spec = <f rhs> Int dNumInt
 RULE: forall d. f Int d = f_spec
 You can see this discarding happening in
3. Note that the HsWrapper can transform *any* function with the right
 type prefix
 forall ab. (Eq a, Ix b) => XXX
 regardless of XXX. It's sort of polymorphic in XXX. This is
 useful: we use the same wrapper to transform each of the class ops, as
 well as the dict. That's what goes on in TcInstDcls.mk_meth_spec_prags
-}tcSpecPrags::Id->[LSigGhcRn]->TcM[LTcSpecPrag]-- Add INLINE and SPECIALSE pragmas-- INLINE prags are added to the (polymorphic) Id directly-- SPECIALISE prags are passed to the desugarer via TcSpecPrags-- Pre-condition: the poly_id is zonked-- Reason: required by tcSubExptcSpecPrags poly_id prag_sigs =do{traceTc "tcSpecPrags"(pprpoly_id <+>pprspec_sigs );unless(nullbad_sigs )warn_discarded_sigs ;pss <-mapAndRecoverM (wrapLocM (tcSpecPrag poly_id ))spec_sigs ;return$concatMap(\(Ll ps )->map(Ll )ps )pss }wherespec_sigs =filterisSpecLSigprag_sigs bad_sigs =filteris_bad_sig prag_sigs is_bad_sig s =not(isSpecLSigs ||isInlineLSigs ||isSCCFunSigs )warn_discarded_sigs =addWarnTc NoReason(hang(text"Discarding unexpected pragmas for"<+>pprpoly_id )2(vcat(map(ppr.getLoc)bad_sigs )))--------------tcSpecPrag::TcId->SigGhcRn->TcM[TcSpecPrag]tcSpecPrag poly_id prag @(SpecSig_fun_name hs_tys inl )-- See Note [Handling SPECIALISE pragmas]---- The Name fun_name in the SpecSig may not be the same as that of the poly_id-- Example: SPECIALISE for a class method: the Name in the SpecSig is-- for the selector Id, but the poly_id is something like $cop-- However we want to use fun_name in the error message, since that is-- what the user wrote (#8537)=addErrCtxt (spec_ctxt prag )$do{warnIf (not(isOverloadedTypoly_ty ||isInlinePragmainl ))(text"SPECIALISE pragma for non-overloaded function"<+>quotes(pprfun_name ))-- Note [SPECIALISE pragmas];spec_prags <-mapMtc_one hs_tys ;traceTc "tcSpecPrag"(pprpoly_id $$nest2(vcat(mappprspec_prags )));returnspec_prags }wherename =idNamepoly_id poly_ty =idTypepoly_id spec_ctxt prag =hang(text"In the SPECIALISE pragma")2(pprprag )tc_one hs_ty =do{spec_ty <-tcHsSigType (FunSigCtxtname False)hs_ty ;wrap <-tcSpecWrapper (FunSigCtxtname True)poly_ty spec_ty ;return(SpecPragpoly_id wrap inl )}tcSpecPrag_prag =pprPanic"tcSpecPrag"(pprprag )--------------tcSpecWrapper::UserTypeCtxt->TcType->TcType->TcMHsWrapper-- A simpler variant of tcSubType, used for SPECIALISE pragmas-- See Note [Handling SPECIALISE pragmas], wrinkle 1tcSpecWrapper ctxt poly_ty spec_ty =do{(sk_wrap ,inst_wrap )<-tcSkolemise ctxt spec_ty $\_spec_tau ->do{(inst_wrap ,tau )<-topInstantiate orig poly_ty ;_<-unifyType Nothingspec_tau tau -- Deliberately ignore the evidence-- See Note [Handling SPECIALISE pragmas],-- wrinkle (2);returninst_wrap };return(sk_wrap <.>inst_wrap )}whereorig =SpecPragOriginctxt --------------tcImpPrags::[LSigGhcRn]->TcM[LTcSpecPrag]-- SPECIALISE pragmas for imported thingstcImpPrags prags =do{this_mod <-getModule;dflags <-getDynFlags;if(not_specialising dflags )thenreturn[]elsedo{pss <-mapAndRecoverM (wrapLocM tcImpSpec )[Lloc (name ,prag )|(Lloc prag @(SpecSig_(L_name )__))<-prags ,not(nameIsLocalOrFromthis_mod name )];return$concatMap(\(Ll ps )->map(Ll )ps )pss }}where-- Ignore SPECIALISE pragmas for imported things-- when we aren't specialising, or when we aren't generating-- code. The latter happens when Haddocking the base library;-- we don't want complaints about lack of INLINABLE pragmasnot_specialising dflags |not(goptOpt_Specialisedflags )=True|otherwise=casehscTargetdflags ofHscNothing->TrueHscInterpreted->True_other ->FalsetcImpSpec::(Name,SigGhcRn)->TcM[TcSpecPrag]tcImpSpec (name ,prag )=do{id <-tcLookupId name ;unless(isAnyInlinePragma(idInlinePragmaid ))(addWarnTc NoReason(impSpecErr name ));tcSpecPrag id prag }impSpecErr::Name->SDocimpSpecErr name =hang(text"You cannot SPECIALISE"<+>quotes(pprname ))2(vcat[text"because its definition has no INLINE/INLINABLE pragma",parens$sep[text"or its defining module"<+>quotes(pprmod ),text"was compiled without -O"]])wheremod =nameModulename 

AltStyle によって変換されたページ (->オリジナル) /