\end{code}
%************************************************************************
%* *
\subsection{Type-checking bindings}
%* *
%************************************************************************
@tcBindsAndThen@ typechecks a @HsBinds@. The "and then" part is because
it needs to know something about the {\em usage} of the things bound,
so that it can create specialisations of them. So @tcBindsAndThen@
takes a function which, given an extended environment, E, typechecks
the scope of the bindings returning a typechecked thing and (most
important) an LIE. It is this LIE which is then used as the basis for
specialising the things bound.
@tcBindsAndThen@ also takes a "combiner" which glues together the
bindings and the "thing" to make a new "thing".
The real work is done by @tcBindWithSigsAndThen@.
Recursive and non-recursive binds are handled in essentially the same
way: because of uniques there are no scoping issues left. The only
difference is that non-recursive bindings can bind primitive values.
Even for non-recursive binding groups we add typings for each binder
to the LVE for the following reason. When each individual binding is
checked the type of its LHS is unified with that of its RHS; and
type-checking the LHS of course requires that the binder is in scope.
At the top-level the LIE is sure to contain nothing but constant
dictionaries, which we resolve at the module level.
Note [Polymorphic recursion]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The game plan for polymorphic recursion in the code above is
* Bind any variable for which we have a type signature
to an Id with a polymorphic type. Then when type-checking
the RHSs we'll make a full polymorphic call.
This fine, but if you aren't a bit careful you end up with a horrendous
amount of partial application and (worse) a huge space leak. For example:
f :: Eq a => [a] -> [a]
f xs = ...f...
If we don't take care, after typechecking we get
f = /\a -> \d::Eq a -> let f' = f a d
in
\ys:[a] -> ...f'...
Notice the the stupid construction of (f a d), which is of course
identical to the function we're executing. In this case, the
polymorphic recursion isn't being used (but that's a very common case).
This can lead to a massive space leak, from the following top-level defn
(post-typechecking)
ff :: [Int] -> [Int]
ff = f Int dEqInt
Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
f' is another thunk which evaluates to the same thing... and you end
up with a chain of identical values all hung onto by the CAF ff.
ff = f Int dEqInt
= let f' = f Int dEqInt in \ys. ...f'...
= let f' = let f' = f Int dEqInt in \ys. ...f'...
in \ys. ...f'...
Etc.
NOTE: a bit of arity anaysis would push the (f a d) inside the (\ys...),
which would make the space leak go away in this case
Solution: when typechecking the RHSs we always have in hand the
*monomorphic* Ids for each binding. So we just need to make sure that
if (Method f a d) shows up in the constraints emerging from (...f...)
we just use the monomorphic Id. We achieve this by adding monomorphic Ids
to the "givens" when simplifying constraints. That's what the "lies_avail"
is doing.
Then we get
f = /\a -> \d::Eq a -> letrec
fm = \ys:[a] -> ...fm...
in
fm
\begin{code}

tcTopBinds::HsValBindsName->TcM(TcGblEnv,TcLclEnv)-- The TcGblEnv contains the new tcg_binds and tcg_spects-- The TcLclEnv has an extended type envt for the new bindingstcTopBinds(ValBindsOutbindssigs)=do{tcg_env<-getGblEnv;(binds',tcl_env)<-tcValBindsTopLevelbindssigsgetLclEnv;specs<-tcImpPragssigs-- SPECIALISE prags for imported Ids;let{tcg_env'=tcg_env{tcg_binds=foldr(unionBags.snd)(tcg_bindstcg_env)binds',tcg_imp_specs=specs++tcg_imp_specstcg_env}};return(tcg_env',tcl_env)}-- The top level bindings are flattened into a giant -- implicitly-mutually-recursive LHsBindstcTopBinds(ValBindsIn{})=panic"tcTopBinds"tcRecSelBinds::HsValBindsName->TcMTcGblEnvtcRecSelBinds(ValBindsOutbindssigs)=tcExtendGlobalValEnv[sel_id|L_(IdSigsel_id)<-sigs]$do{(rec_sel_binds,tcg_env)<-discardWarnings(tcValBindsTopLevelbindssigsgetGblEnv);lettcg_env'|isHsBoot(tcg_srctcg_env)=tcg_env|otherwise=tcg_env{tcg_binds=foldr(unionBags.snd)(tcg_bindstcg_env)rec_sel_binds}-- Do not add the code for record-selector bindings when -- compiling hs-boot files;returntcg_env'}tcRecSelBinds(ValBindsIn{})=panic"tcRecSelBinds"tcHsBootSigs::HsValBindsName->TcM[Id]-- A hs-boot file has only one BindGroup, and it only has type-- signatures in it. The renamer checked all thistcHsBootSigs(ValBindsOutbindssigs)=do{checkTc(nullbinds)badBootDeclErr;concat<$>mapM(addLocMtc_boot_sig)(filterisTypeLSigsigs)}wheretc_boot_sig(TypeSiglnamesty)=mapMflnameswheref(L_name)=do{sigma_ty<-tcHsSigType(FunSigCtxtname)ty;return(mkVanillaGlobalnamesigma_ty)}-- Notice that we make GlobalIds, not LocalIdstc_boot_sigs=pprPanic"tcHsBootSigs/tc_boot_sig"(pprs)tcHsBootSigsgroups=pprPanic"tcHsBootSigs"(pprgroups)badBootDeclErr::MsgDocbadBootDeclErr=ptext(sLit"Illegal declarations in an hs-boot file")------------------------tcLocalBinds::HsLocalBindsName->TcMthing->TcM(HsLocalBindsTcId,thing)tcLocalBindsEmptyLocalBindsthing_inside=do{thing<-thing_inside;return(EmptyLocalBinds,thing)}tcLocalBinds(HsValBinds(ValBindsOutbindssigs))thing_inside=do{(binds',thing)<-tcValBindsNotTopLevelbindssigsthing_inside;return(HsValBinds(ValBindsOutbinds'sigs),thing)}tcLocalBinds(HsValBinds(ValBindsIn{}))_=panic"tcLocalBinds"tcLocalBinds(HsIPBinds(IPBindsip_binds_))thing_inside=do{ipClass<-tcLookupClassipClassName;(given_ips,ip_binds')<-mapAndUnzipM(wrapLocSndM(tc_ip_bindipClass))ip_binds-- If the binding binds ?x = E, we must now -- discharge any ?x constraints in expr_lie-- See Note [Implicit parameter untouchables];(ev_binds,result)<-checkConstraints(IPSkolips)[]given_ipsthing_inside;return(HsIPBinds(IPBindsip_binds'ev_binds),result)}whereips=[ip|L_(IPBind(Leftip)_)<-ip_binds]-- I wonder if we should do these one at at time-- Consider ?x = 4-- ?y = ?x + 1tc_ip_bindipClass(IPBind(Leftip)expr)=do{ty<-newFlexiTyVarTyopenTypeKind;letp=mkStrLitTy$hsIPNameFSip;ip_id<-newDictipClass[p,ty];expr'<-tcMonoExprexprty;letd=toDictipClasspty`fmap`expr';return(ip_id,(IPBind(Rightip_id)d))}tc_ip_bind_(IPBind(Right{})_)=panic"tc_ip_bind"-- Coerces a `t` into a dictionry for `IP "x" t`.-- co : t -> IP "x" ttoDictipClassxty=caseunwrapNewTyCon_maybe(classTyConipClass)ofJust(_,_,ax)->HsWrap$WpCast$mkTcSymCo$mkTcAxInstCoax[x,ty]Nothing->panic"The dictionary for `IP` is not a newtype?"

\end{code}
Note [Implicit parameter untouchables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We add the type variables in the types of the implicit parameters
as untouchables, not so much because we really must not unify them,
but rather because we otherwise end up with constraints like this
Num alpha, Implic { wanted = alpha ~ Int }
The constraint solver solves alpha~Int by unification, but then
doesn't float that solved constraint out (it's not an unsolved
wanted). Result disaster: the (Num alpha) is again solved, this
time by defaulting. No no no.
However [Oct 10] this is all handled automatically by the
untouchable-range idea.
\begin{code}

tcValBinds::TopLevelFlag->[(RecFlag,LHsBindsName)]->[LSigName]->TcMthing->TcM([(RecFlag,LHsBindsTcId)],thing)tcValBindstop_lvlbindssigsthing_inside=do{-- Typecheck the signature(poly_ids,sig_fn)<-tcTySigssigs;letprag_fn=mkPragFunsigs(foldr(unionBags.snd)emptyBagbinds)-- Extend the envt right away with all -- the Ids declared with type signatures;(binds',thing)<-tcExtendIdEnvpoly_ids$tcBindGroupstop_lvlsig_fnprag_fnbindsthing_inside;return(binds',thing)}------------------------tcBindGroups::TopLevelFlag->TcSigFun->PragFun->[(RecFlag,LHsBindsName)]->TcMthing->TcM([(RecFlag,LHsBindsTcId)],thing)-- Typecheck a whole lot of value bindings,-- one strongly-connected component at a time-- Here a "strongly connected component" has the strightforward-- meaning of a group of bindings that mention each other, -- ignoring type signatures (that part comes later)tcBindGroups___[]thing_inside=do{thing<-thing_inside;return([],thing)}tcBindGroupstop_lvlsig_fnprag_fn(group:groups)thing_inside=do{(group',(groups',thing))<-tc_grouptop_lvlsig_fnprag_fngroup$tcBindGroupstop_lvlsig_fnprag_fngroupsthing_inside;return(group'++groups',thing)}------------------------tc_group::forallthing.TopLevelFlag->TcSigFun->PragFun->(RecFlag,LHsBindsName)->TcMthing->TcM([(RecFlag,LHsBindsTcId)],thing)-- Typecheck one strongly-connected component of the original program.-- We get a list of groups back, because there may -- be specialisations etc as welltc_grouptop_lvlsig_fnprag_fn(NonRecursive,binds)thing_inside-- A single non-recursive binding-- We want to keep non-recursive things non-recursive-- so that we desugar unlifted bindings correctly=do{(binds1,ids,closed)<-tcPolyBindstop_lvlsig_fnprag_fnNonRecursiveNonRecursive(bagToListbinds);thing<-tcExtendLetEnvclosedidsthing_inside;return([(NonRecursive,binds1)],thing)}tc_grouptop_lvlsig_fnprag_fn(Recursive,binds)thing_inside=-- To maximise polymorphism (assumes -XRelaxedPolyRec), we do a new -- strongly-connected-component analysis, this time omitting -- any references to variables with type signatures.do{traceTc"tc_group rec"(pprLHsBindsbinds);(binds1,_ids,thing)<-gosccs-- Here is where we should do bindInstsOfLocalFuns-- if we start having Methods again;return([(Recursive,binds1)],thing)}-- Rec them all togetherwheresccs::[SCC(LHsBindName)]sccs=stronglyConnCompFromEdgedVertices(mkEdgessig_fnbinds)go::[SCC(LHsBindName)]->TcM(LHsBindsTcId,[TcId],thing)go(scc:sccs)=do{(binds1,ids1,closed)<-tc_sccscc;(binds2,ids2,thing)<-tcExtendLetEnvclosedids1$gosccs;return(binds1`unionBags`binds2,ids1++ids2,thing)}go[]=do{thing<-thing_inside;return(emptyBag,[],thing)}tc_scc(AcyclicSCCbind)=tc_sub_groupNonRecursive[bind]tc_scc(CyclicSCCbinds)=tc_sub_groupRecursivebindstc_sub_group=tcPolyBindstop_lvlsig_fnprag_fnRecursive------------------------mkEdges::TcSigFun->LHsBindsName->[(LHsBindName,BKey,[BKey])]typeBKey=Int-- Just number off the bindingsmkEdgessig_fnbinds=[(bind,key,[key|n<-nameSetToList(bind_fvs(unLocbind)),Justkey<-[lookupNameEnvkey_mapn],no_sign])|(bind,key)<-keyd_binds]whereno_sig::Name->Boolno_sign=isNothing(sig_fnn)keyd_binds=bagToListbinds`zip`[0::BKey..]key_map::NameEnvBKey-- Which binding it comes fromkey_map=mkNameEnv[(bndr,key)|(L_bind,key)<-keyd_binds,bndr<-bindersOfHsBindbind]bindersOfHsBind::HsBindName->[Name]bindersOfHsBind(PatBind{pat_lhs=pat})=collectPatBinderspatbindersOfHsBind(FunBind{fun_id=L_f})=[f]bindersOfHsBind(AbsBinds{})=panic"bindersOfHsBind AbsBinds"bindersOfHsBind(VarBind{})=panic"bindersOfHsBind VarBind"------------------------tcPolyBinds::TopLevelFlag->TcSigFun->PragFun->RecFlag-- Whether the group is really recursive->RecFlag-- Whether it's recursive after breaking-- dependencies based on type signatures->[LHsBindName]->TcM(LHsBindsTcId,[TcId],TopLevelFlag)-- Typechecks a single bunch of bindings all together, -- and generalises them. The bunch may be only part of a recursive-- group, because we use type signatures to maximise polymorphism---- Returns a list because the input may be a single non-recursive binding,-- in which case the dependency order of the resulting bindings is-- important. -- -- Knows nothing about the scope of the bindingstcPolyBindstop_lvlsig_fnprag_fnrec_grouprec_tcbind_list=setSrcSpanloc$recoverM(recoveryCodebinder_namessig_fn)$do-- Set up main recover; take advantage of any type sigs{traceTc"------------------------------------------------"empty;traceTc"Bindings for {"(pprbinder_names)-- -- Instantiate the polytypes of any binders that have signatures-- -- (as determined by sig_fn), returning a TcSigInfo for each-- ; tc_sig_fn <- tcInstSigs sig_fn binder_names;dflags<-getDynFlags;type_env<-getLclTypeEnv;letplan=decideGeneralisationPlandflagstype_envbinder_namesbind_listsig_fn;traceTc"Generalisation plan"(pprplan);result@(tc_binds,poly_ids,_)<-caseplanofNoGen->tcPolyNoGensig_fnprag_fnrec_tcbind_listInferGenmncl->tcPolyInfermnclsig_fnprag_fnrec_tcbind_listCheckGensig->tcPolyChecksigprag_fnrec_tcbind_list-- Check whether strict bindings are ok-- These must be non-recursive etc, and are not generalised-- They desugar to a case expression in the end;checkStrictBindstop_lvlrec_groupbind_listtc_bindspoly_ids;traceTc"} End of bindings for"(vcat[pprbinder_names,pprrec_group,vcat[pprid<+>ppr(idTypeid)|id<-poly_ids]]);returnresult}wherebinder_names=collectHsBindListBindersbind_listloc=foldr1combineSrcSpans(mapgetLocbind_list)-- The mbinds have been dependency analysed and -- may no longer be adjacent; so find the narrowest-- span that includes them all------------------tcPolyNoGen::TcSigFun->PragFun->RecFlag-- Whether it's recursive after breaking-- dependencies based on type signatures->[LHsBindName]->TcM(LHsBindsTcId,[TcId],TopLevelFlag)-- No generalisation whatsoevertcPolyNoGentc_sig_fnprag_fnrec_tcbind_list=do{(binds',mono_infos)<-tcMonoBindstc_sig_fn(LetGblBndrprag_fn)rec_tcbind_list;mono_ids'<-mapMtc_mono_infomono_infos;return(binds',mono_ids',NotTopLevel)}wheretc_mono_info(name,_,mono_id)=do{mono_ty'<-zonkTcType(idTypemono_id)-- Zonk, mainly to expose unboxed types to checkStrictBinds;letmono_id'=setIdTypemono_idmono_ty';_specs<-tcSpecPragsmono_id'(prag_fnname);returnmono_id'}-- NB: tcPrags generates error messages for-- specialisation pragmas for non-overloaded sigs-- Indeed that is why we call it here!-- So we can safely ignore _specs------------------tcPolyCheck::TcSigInfo->PragFun->RecFlag-- Whether it's recursive after breaking-- dependencies based on type signatures->[LHsBindName]->TcM(LHsBindsTcId,[TcId],TopLevelFlag)-- There is just one binding, -- it binds a single variable,-- it has a signature,tcPolyChecksig@(TcSigInfo{sig_id=poly_id,sig_tvs=tvs_w_scoped,sig_theta=theta,sig_tau=tau,sig_loc=loc})prag_fnrec_tcbind_list=do{ev_vars<-newEvVarstheta;letskol_info=SigSkol(FunSigCtxt(idNamepoly_id))(mkPhiTythetatau)prag_sigs=prag_fn(idNamepoly_id);tvs<-mapM(skolemiseSigTv.snd)tvs_w_scoped;(ev_binds,(binds',[mono_info]))<-setSrcSpanloc$checkConstraintsskol_infotvsev_vars$tcExtendTyVarEnv2[(n,tv)|(Justn,tv)<-tvs_w_scoped]$tcMonoBinds(\_->Justsig)LetLclBndrrec_tcbind_list;spec_prags<-tcSpecPragspoly_idprag_sigs;poly_id<-addInlinePragspoly_idprag_sigs;let(_,_,mono_id)=mono_infoexport=ABE{abe_wrap=idHsWrapper,abe_poly=poly_id,abe_mono=mono_id,abe_prags=SpecPragsspec_prags}abs_bind=Lloc$AbsBinds{abs_tvs=tvs,abs_ev_vars=ev_vars,abs_ev_binds=ev_binds,abs_exports=[export],abs_binds=binds'}closed|isEmptyVarSet(tyVarsOfType(idTypepoly_id))=TopLevel|otherwise=NotTopLevel;return(unitBagabs_bind,[poly_id],closed)}------------------tcPolyInfer::Bool-- True <=> apply the monomorphism restriction->Bool-- True <=> free vars have closed types->TcSigFun->PragFun->RecFlag-- Whether it's recursive after breaking-- dependencies based on type signatures->[LHsBindName]->TcM(LHsBindsTcId,[TcId],TopLevelFlag)tcPolyInfermonoclosedtc_sig_fnprag_fnrec_tcbind_list=do{(((binds',mono_infos),untch),wanted)<-captureConstraints$captureUntouchables$tcMonoBindstc_sig_fnLetLclBndrrec_tcbind_list;letname_taus=[(name,idTypemono_id)|(name,_,mono_id)<-mono_infos];(qtvs,givens,mr_bites,ev_binds)<-simplifyInferclosedmononame_taus(untch,wanted);theta<-zonkTcThetaType(mapevVarPredgivens);exports<-checkNoErrs$mapM(mkExportprag_fnqtvstheta)mono_infos;loc<-getSrcSpanM;letpoly_ids=mapabe_polyexportsfinal_closed|closed&&notmr_bites=TopLevel|otherwise=NotTopLevelabs_bind=Lloc$AbsBinds{abs_tvs=qtvs,abs_ev_vars=givens,abs_ev_binds=ev_binds,abs_exports=exports,abs_binds=binds'};traceTc"Binding:"(pprfinal_closed$$ppr(poly_ids`zip`mapidTypepoly_ids));return(unitBagabs_bind,poly_ids,final_closed)-- poly_ids are guaranteed zonked by mkExport}--------------mkExport::PragFun->[TyVar]->TcThetaType-- Both already zonked->MonoBindInfo->TcM(ABExportId)-- mkExport generates exports with -- zonked type variables, -- zonked poly_ids-- The former is just because no further unifications will change-- the quantified type variables, so we can fix their final form-- right now.-- The latter is needed because the poly_ids are used to extend the-- type environment; see the invariant on TcEnv.tcExtendIdEnv -- Pre-condition: the qtvs and theta are already zonkedmkExportprag_fnqtvstheta(poly_name,mb_sig,mono_id)=do{mono_ty<-zonkTcType(idTypemono_id);letpoly_id=casemb_sigofNothing->mkLocalIdpoly_nameinferred_poly_tyJustsig->sig_idsig-- poly_id has a zonked type-- In the inference case (no signature) this stuff figures out-- the right type variables and theta to quantify over-- See Note [Impedence matching]my_tv_set=growThetaTyVarstheta(tyVarsOfTypemono_ty)my_tvs=filter(`elemVarSet`my_tv_set)qtvs-- Maintain original ordermy_theta=filter(quantifyPredmy_tv_set)thetainferred_poly_ty=mkSigmaTymy_tvsmy_thetamono_ty;poly_id<-addInlinePragspoly_idprag_sigs;spec_prags<-tcSpecPragspoly_idprag_sigs-- tcPrags requires a zonked poly_id;letsel_poly_ty=mkSigmaTyqtvsthetamono_ty;traceTc"mkExport: check sig"(pprpoly_name$$pprsel_poly_ty$$ppr(idTypepoly_id))-- Perform the impedence-matching and ambiguity check-- right away. If it fails, we want to fail now (and recover-- in tcPolyBinds). If we delay checking, we get an error cascade.-- Remember we are in the tcPolyInfer case, so the type envt is -- closed (unless we are doing NoMonoLocalBinds in which case all bets-- are off)-- See Note [Impedence matching];(wrap,wanted)<-addErrCtxtM(mk_msgpoly_id)$captureConstraints$tcSubTypeoriginsig_ctxtsel_poly_ty(idTypepoly_id);ev_binds<-simplifyAmbiguityCheckpoly_namewanted;return(ABE{abe_wrap=mkWpLet(EvBindsev_binds)<.>wrap,abe_poly=poly_id,abe_mono=mono_id,abe_prags=SpecPragsspec_prags})}whereinferred=isNothingmb_sigmk_msgpoly_idtidy_env=return(tidy_env',msg)wheremsg|inferred=hang(ptext(sLit"When checking that")<+>pp_name)2(ptext(sLit"has the inferred type")<+>pp_ty)$$ptext(sLit"Probable cause: the inferred type is ambiguous")|otherwise=hang(ptext(sLit"When checking that")<+>pp_name)2(ptext(sLit"has the specified type")<+>pp_ty)pp_name=quotes(pprpoly_name)pp_ty=quotes(pprtidy_ty)(tidy_env',tidy_ty)=tidyOpenTypetidy_env(idTypepoly_id)prag_sigs=prag_fnpoly_nameorigin=AmbigOriginpoly_namesig_ctxt=InfSigCtxtpoly_name

tcMonoBinds::TcSigFun->LetBndrSpec->RecFlag-- Whether the binding is recursive for typechecking purposes-- i.e. the binders are mentioned in their RHSs, and-- we are not rescued by a type signature->[LHsBindName]->TcM(LHsBindsTcId,[MonoBindInfo])tcMonoBindssig_fnno_genis_rec[Lb_loc(FunBind{fun_id=Lnm_locname,fun_infix=inf,fun_matches=matches,bind_fvs=fvs})]-- Single function binding, |NonRecursive<-is_rec-- ...binder isn't mentioned in RHS,Nothing<-sig_fnname-- ...with no type signature=-- In this very special case we infer the type of the-- right hand side first (it may have a higher-rank type)-- and *then* make the monomorphic Id for the LHS-- e.g. f = \(x::forall a. a->a) -> <body>-- We want to infer a higher-rank type for fsetSrcSpanb_loc$do{((co_fn,matches'),rhs_ty)<-tcInfer(tcMatchesFunnameinfmatches);mono_id<-newNoSigLetBndrno_gennamerhs_ty;return(unitBag(Lb_loc(FunBind{fun_id=Lnm_locmono_id,fun_infix=inf,fun_matches=matches',bind_fvs=fvs,fun_co_fn=co_fn,fun_tick=Nothing})),[(name,Nothing,mono_id)])}tcMonoBindssig_fnno_gen_binds=do{tc_binds<-mapM(wrapLocM(tcLhssig_fnno_gen))binds-- Bring the monomorphic Ids, into scope for the RHSs;letmono_info=getMonoBindInfotc_bindsrhs_id_env=[(name,mono_id)|(name,Nothing,mono_id)<-mono_info]-- A monomorphic binding for each term variable that lacks -- a type sig. (Ones with a sig are already in scope.);binds'<-tcExtendIdEnv2rhs_id_env$dotraceTc"tcMonoBinds"$vcat[pprn<+>pprid<+>ppr(idTypeid)|(n,id)<-rhs_id_env]mapM(wrapLocMtcRhs)tc_binds;return(listToBagbinds',mono_info)}-------------------------- tcLhs typechecks the LHS of the bindings, to construct the environment in which-- we typecheck the RHSs. Basically what we are doing is this: for each binder:-- if there's a signature for it, use the instantiated signature type-- otherwise invent a type variable-- You see that quite directly in the FunBind case.-- -- But there's a complication for pattern bindings:-- data T = MkT (forall a. a->a)-- MkT f = e-- Here we can guess a type variable for the entire LHS (which will be refined to T)-- but we want to get (f::forall a. a->a) as the RHS environment.-- The simplest way to do this is to typecheck the pattern, and then look up the-- bound mono-ids. Then we want to retain the typechecked pattern to avoid re-doing-- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn'tdataTcMonoBind-- Half completed; LHS done, RHS not done=TcFunBindMonoBindInfoSrcSpanBool(MatchGroupName)|TcPatBind[MonoBindInfo](LPatTcId)(GRHSsName)TcSigmaTypetypeMonoBindInfo=(Name,MaybeTcSigInfo,TcId)-- Type signature (if any), and-- the monomorphic bound thingstcLhs::TcSigFun->LetBndrSpec->HsBindName->TcMTcMonoBindtcLhssig_fnno_gen(FunBind{fun_id=Lnm_locname,fun_infix=inf,fun_matches=matches})|Justsig<-sig_fnname=do{mono_id<-newSigLetBndrno_gennamesig;return(TcFunBind(name,Justsig,mono_id)nm_locinfmatches)}|otherwise=do{mono_ty<-newFlexiTyVarTyopenTypeKind;mono_id<-newNoSigLetBndrno_gennamemono_ty;return(TcFunBind(name,Nothing,mono_id)nm_locinfmatches)}tcLhssig_fnno_gen(PatBind{pat_lhs=pat,pat_rhs=grhss})=do{lettc_patexp_ty=tcLetPatsig_fnno_genpatexp_ty$mapMlookup_info(collectPatBinderspat)-- After typechecking the pattern, look up the binder-- names, which the pattern has brought into scope.lookup_info::Name->TcMMonoBindInfolookup_infoname=do{mono_id<-tcLookupIdname;return(name,sig_fnname,mono_id)};((pat',infos),pat_ty)<-addErrCtxt(patMonoBindsCtxtpatgrhss)$tcInfertc_pat;return(TcPatBindinfospat'grhsspat_ty)}tcLhs__other_bind=pprPanic"tcLhs"(pprother_bind)-- AbsBind, VarBind impossible-------------------tcRhs::TcMonoBind->TcM(HsBindTcId)-- When we are doing pattern bindings, or multiple function bindings at a time-- we *don't* bring any scoped type variables into scope-- Wny not? They are not completely rigid.-- That's why we have the special case for a single FunBind in tcMonoBindstcRhs(TcFunBind(_,_,mono_id)locinfmatches)=do{traceTc"tcRhs: fun bind"(pprmono_id$$ppr(idTypemono_id));(co_fn,matches')<-tcMatchesFun(idNamemono_id)infmatches(idTypemono_id);return(FunBind{fun_id=Llocmono_id,fun_infix=inf,fun_matches=matches',fun_co_fn=co_fn,bind_fvs=placeHolderNames,fun_tick=Nothing})}tcRhs(TcPatBind_pat'grhsspat_ty)=do{traceTc"tcRhs: pat bind"(pprpat'$$pprpat_ty);grhss'<-addErrCtxt(patMonoBindsCtxtpat'grhss)$tcGRHSsPatgrhsspat_ty;return(PatBind{pat_lhs=pat',pat_rhs=grhss',pat_rhs_ty=pat_ty,bind_fvs=placeHolderNames,pat_ticks=(Nothing,[])})}---------------------getMonoBindInfo::[LocatedTcMonoBind]->[MonoBindInfo]getMonoBindInfotc_binds=foldr(get_info.unLoc)[]tc_bindswhereget_info(TcFunBindinfo___)rest=info:restget_info(TcPatBindinfos___)rest=infos++rest

\end{code}
%************************************************************************
%* *
Signatures
%* *
%************************************************************************
Type signatures are tricky. See Note [Signature skolems] in TcType
@tcSigs@ checks the signatures for validity, and returns a list of
{\em freshly-instantiated} signatures. That is, the types are already
split up, and have fresh type variables installed. All non-type-signature
"RenamedSigs" are ignored.
The @TcSigInfo@ contains @TcTypes@ because they are unified with
the variable's type, and after that checked to see whether they've
been instantiated.
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
- For multiple function bindings, unless Opt_RelaxedPolyRec is on
f :: forall a. a -> a
f = g
g :: forall b. b -> b
g = ...f...
Reason: we use mutable variables for 'a' and 'b', since they may
unify to each other, and that means the scoped type variable would
not stand for a completely rigid variable.
Currently, we simply make Opt_ScopedTypeVariables imply Opt_RelaxedPolyRec
Note [More instantiated than scoped]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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'.
We assume that the scoped ones are at the *front* of sig_tvs,
and remember the names from the original HsForAllTy in the TcSigFun.
Note [Signature skolems]
~~~~~~~~~~~~~~~~~~~~~~~~
When instantiating a type signature, we do so with either skolems or
SigTv meta-type variables depending on the use_skols boolean. This
variable is set True when we are typechecking a single function
binding; and False for pattern bindings and a group of several
function bindings.
Reason: in the latter cases, the "skolems" can be unified together,
so they aren't properly rigid in the type-refinement sense.
NB: unless we are doing H98, each function with a sig will be done
separately, even if it's mutually recursive, so use_skols will be True
Note [Only scoped tyvars are in the TyVarEnv]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We are careful to keep only the *lexically scoped* type variables in
the type environment. Why? After all, the renamer has ensured
that only legal occurrences occur, so we could put all type variables
into the type env.
But we want to check that two distinct lexically scoped type variables
do not map to the same internal type variable. So we need to know which
the lexically-scoped ones are... and at the moment we do that by putting
only the lexically scoped ones into the environment.
Note [Instantiate sig with fresh variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's vital to instantiate a type signature with fresh variables.
For example:
type T = forall a. [a] -> [a]
f :: T;
f = g where { g :: T; g = }
We must not use the same 'a' from the defn of T at both places!!
(Instantiation is only necessary because of type synonyms. Otherwise,
it's all cool; each signature has distinct type variables from the renamer.)
\begin{code}

tcTySigs::[LSigName]->TcM([TcId],TcSigFun)tcTySigshs_sigs=do{ty_sigs<-concat<$>checkNoErrs(mapAndRecoverMtcTySighs_sigs)-- No recovery from bad signatures, because the type sigs-- may bind type variables, so proceeding without them-- can lead to a cascade of errors-- ToDo: this means we fall over immediately if any type sig-- is wrong, which is over-conservative, see Trac bug #745;letenv=mkNameEnv[(idName(sig_idsig),sig)|sig<-ty_sigs];return(mapsig_idty_sigs,lookupNameEnvenv)}tcTySig::LSigName->TcM[TcSigInfo]tcTySig(Lloc(IdSigid))=do{sig<-instTcTySigFromIdlocid;return[sig]}tcTySig(Lloc(TypeSignames@(L_name1:_)hs_ty))=setSrcSpanloc$do{sigma_ty<-tcHsSigType(FunSigCtxtname1)hs_ty;mapM(instTcTySighs_tysigma_ty)(mapunLocnames)}tcTySig_=return[]instTcTySigFromId::SrcSpan->Id->TcMTcSigInfoinstTcTySigFromIdlocid=do{(tvs,theta,tau)<-tcInstTypeinst_sig_tyvars(idTypeid);return(TcSigInfo{sig_id=id,sig_loc=loc,sig_tvs=[(Nothing,tv)|tv<-tvs],sig_theta=theta,sig_tau=tau})}where-- Hack: in an instance decl we use the selector id as-- the template; but we do *not* want the SrcSpan on the Name of -- those type variables to refer to the class decl, rather to-- the instance decl inst_sig_tyvarstvs=tcInstSigTyVars(mapset_loctvs)set_loctv=setTyVarNametv(mkInternalName(nameUniquen)(nameOccNamen)loc)wheren=tyVarNametvinstTcTySig::LHsTypeName->TcType-- HsType and corresponding TcType->Name->TcMTcSigInfoinstTcTySighs_ty@(Lloc_)sigma_tyname=do{(inst_tvs,theta,tau)<-tcInstTypetcInstSigTyVarssigma_ty;return(TcSigInfo{sig_id=poly_id,sig_loc=loc,sig_tvs=zipEqual"instTcTySig"scoped_tvsinst_tvs,sig_theta=theta,sig_tau=tau})}wherepoly_id=mkLocalIdnamesigma_tyscoped_names=hsExplicitTvshs_ty(sig_tvs,_)=tcSplitForAllTyssigma_tyscoped_tvs::[MaybeName]scoped_tvs=mk_scopedscoped_namessig_tvsmk_scoped::[Name]->[TyVar]->[MaybeName]mk_scoped[]tvs=[Nothing|_<-tvs]mk_scoped(n:ns)(tv:tvs)|n==tyVarNametv=Justn:mk_scopednstvs|otherwise=Nothing:mk_scoped(n:ns)tvsmk_scoped(n:ns)[]=pprPanic"mk_scoped"(pprname$$ppr(n:ns)$$pprhs_ty$$pprsigma_ty)-------------------------------dataGeneralisationPlan=NoGen-- No generalisation, no AbsBinds|InferGen-- Implicit generalisation; there is an AbsBindsBool-- True <=> apply the MR; generalise only unconstrained type varsBool-- True <=> bindings mention only variables with closed types-- See Note [Bindings with closed types] in TcRnTypes|CheckGenTcSigInfo-- One binding with a signature-- Explicit generalisation; there is an AbsBinds-- A consequence of the no-AbsBinds choice (NoGen) is that there is-- no "polymorphic Id" and "monmomorphic Id"; there is just the oneinstanceOutputableGeneralisationPlanwherepprNoGen=ptext(sLit"NoGen")ppr(InferGenbc)=ptext(sLit"InferGen")<+>pprb<+>pprcppr(CheckGens)=ptext(sLit"CheckGen")<+>pprsdecideGeneralisationPlan::DynFlags->TcTypeEnv->[Name]->[LHsBindName]->TcSigFun->GeneralisationPlandecideGeneralisationPlandflagstype_envbndr_nameslbindssig_fn|bang_pat_binds=NoGen|Justsig<-one_funbind_with_sigbinds=CheckGensig|mono_local_binds=NoGen|otherwise=InferGenmono_restrictionclosed_flagwherebndr_set=mkNameSetbndr_namesbinds=mapunLoclbindsbang_pat_binds=anyisBangHsBindbinds-- Bang patterns must not be polymorphic,-- because we are going to force them-- See Trac #4498mono_restriction=xoptOpt_MonomorphismRestrictiondflags&&anyrestrictedbindsis_closed_ns::NameSet->Bool->Boolis_closed_nsnsb=foldNameSet((&&).is_closed_id)bns-- ns are the Names referred to from the RHS of this bindis_closed_id::Name->Bool-- See Note [Bindings with closed types] in TcRnTypesis_closed_idname|name`elemNameSet`bndr_set=True-- Ignore binders in this groups, of course|Justthing<-lookupNameEnvtype_envname=casethingofATcId{tct_closed=cl}->isTopLevelcl-- This is the key lineATyVar{}->False-- In-scope type variablesAGlobal{}->True-- are not closed!_->pprPanic"is_closed_id"(pprname)|otherwise=WARN(isInternalNamename,pprname)True-- The free-var set for a top level binding mentions-- imported things too, so that we can report unused imports-- These won't be in the local type env. -- Ditto class method etc from the current moduleclosed_flag=foldr(is_closed_ns.bind_fvs)Truebindsmono_local_binds=xoptOpt_MonoLocalBindsdflags&&notclosed_flagno_sign=isNothing(sig_fnn)-- With OutsideIn, all nested bindings are monomorphic-- except a single function binding with a signatureone_funbind_with_sig[FunBind{fun_id=v}]=sig_fn(unLocv)one_funbind_with_sig_=Nothing-- The Haskell 98 monomorphism resetrictionrestricted(PatBind{})=Truerestricted(VarBind{var_id=v})=no_sigvrestricted(FunBind{fun_id=v,fun_matches=m})=restricted_matchm&&no_sig(unLocv)restricted(AbsBinds{})=panic"isRestrictedGroup/unrestricted AbsBinds"restricted_match(MatchGroup(L_(Match[]__):_)_)=Truerestricted_match_=False-- No args => like a pattern binding-- Some args => a function binding-------------------checkStrictBinds::TopLevelFlag->RecFlag->[LHsBindName]->LHsBindsTcId->[Id]->TcM()-- Check that non-overloaded unlifted bindings are-- a) non-recursive,-- b) not top level, -- c) not a multiple-binding group (more or less implied by (a))checkStrictBindstop_lvlrec_grouporig_bindstc_bindspoly_ids|unlifted||bang_pat=do{checkTc(isNotTopLeveltop_lvl)(strictBindErr"Top-level"unliftedorig_binds);checkTc(isNonRecrec_group)(strictBindErr"Recursive"unliftedorig_binds);checkTc(allis_monomorphic(bagToListtc_binds))(polyBindErrorig_binds)-- data Ptr a = Ptr Addr#-- f x = let p@(Ptr y) = ... in ...-- Here the binding for 'p' is polymorphic, but does -- not mix with an unlifted binding for 'y'. You should-- use a bang pattern. Trac #6078.;checkTc(isSingletonorig_binds)(strictBindErr"Multiple"unliftedorig_binds)-- This should be a checkTc, not a warnTc, but as of GHC 6.11-- the versions of alex and happy available have non-conforming-- templates, so the GHC build fails if it's an error:;warnUnlifted<-woptMOpt_WarnLazyUnliftedBindings;warnTc(warnUnlifted&&notbang_pat&&lifted_pat)-- No outer bang, but it's a compound pattern-- E.g (I# x#) = blah-- Warn about this, but not about-- x# = 4# +# 1#-- (# a, b #) = ...(unliftedMustBeBangorig_binds)}|otherwise=traceTc"csb2"(pprpoly_ids)>>return()whereunlifted=anyis_unliftedpoly_idsbang_pat=any(isBangHsBind.unLoc)orig_bindslifted_pat=any(isLiftedPatBind.unLoc)orig_bindsis_unliftedid=casetcSplitForAllTys(idTypeid)of(_,rho)->isUnLiftedTyperhois_monomorphic(L_(AbsBinds{abs_tvs=tvs,abs_ev_vars=evs}))=nulltvs&&nullevsis_monomorphic_=TrueunliftedMustBeBang::[LHsBindName]->SDocunliftedMustBeBangbinds=hang(text"Pattern bindings containing unlifted types should use an outermost bang pattern:")2(vcat(mappprbinds))polyBindErr::[LHsBindName]->SDocpolyBindErrbinds=hang(ptext(sLit"You can't mix polymorphic and unlifted bindings"))2(vcat[vcat(mappprbinds),ptext(sLit"Probable fix: use a bang pattern")])strictBindErr::String->Bool->[LHsBindName]->SDocstrictBindErrflavourunliftedbinds=hang(textflavour<+>msg<+>ptext(sLit"aren't allowed:"))2(vcat(mappprbinds))wheremsg|unlifted=ptext(sLit"bindings for unlifted types")|otherwise=ptext(sLit"bang-pattern bindings")

-- This one is called on LHS, when pat and grhss are both Name -- and on RHS, when pat is TcId and grhss is still NamepatMonoBindsCtxt::OutputableBndrid=>LPatid->GRHSsName->SDocpatMonoBindsCtxtpatgrhss=hang(ptext(sLit"In a pattern binding:"))2(pprPatBindpatgrhss)