123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887(************************************************************************)(* * The Coq Proof Assistant / The Coq Development Team *)(* v * Copyright INRIA, CNRS and contributors *)(* <O___,, * (see version control and CREDITS file for authors & dates) *)(* \VV/ **************************************************************)(* // * This file is distributed under the terms of the *)(* * GNU Lesser General Public License Version 2.1 *)(* * (see LICENSE file for the text of the license) *)(************************************************************************)openPpopenCErrorsopenUtilopenNamesopenNameopsopenTermopsopenConstropenContextopenNamegenopenEnvironopenEvdopenEConstropenVarsopenReductionopenReductionopsopenTacredopenPretype_errorsopenEvarutilopenUnificationopenTactypesopenLogic(******************************************************************)(* Clausal environments *)typeclausenv={env:env;evd:evar_map;templval:constrfreelisted;templtyp:constrfreelisted;cache:Reductionops.meta_instance_subst;}letmk_clausenvenvevdtemplvaltempltyp={env;evd;templval;templtyp;cache=create_meta_instance_substevd;}letupdate_clenv_evdclenvevd=mk_clausenvclenv.envevdclenv.templvalclenv.templtypletcl_envce=ce.envletcl_sigmace=ce.evdletclenv_termclenvc=meta_instanceclenv.envclenv.cachecletclenv_meta_typeclenvmv=letty=tryEvd.meta_ftypeclenv.evdmvwithNot_found->anomaly(str"unknown meta ?"++str(Nameops.string_of_metamv)++str".")inmeta_instanceclenv.envclenv.cachetyletclenv_valueclenv=meta_instanceclenv.envclenv.cacheclenv.templvalletclenv_typeclenv=meta_instanceclenv.envclenv.cacheclenv.templtypletclenv_hnf_constrcet=hnf_constr(cl_envce)(cl_sigmace)tletclenv_get_type_ofcec=Retyping.get_type_of(cl_envce)(cl_sigmace)cexceptionNotExtensibleClauseletclenv_push_prodcl=lettyp=whd_all(cl_envcl)(cl_sigmacl)(clenv_typecl)inletrecclrectyp=matchEConstr.kindcl.evdtypwith|Cast(t,_,_)->clrect|Prod(na,t,u)->letmv=new_meta()inletdep=not(noccurn(cl_sigmacl)1u)inletna'=ifdepthenna.binder_nameelseAnonymousinlete'=meta_declaremvt~name:na'cl.evdinletconcl=ifdepthensubst1(mkMetamv)uelseuinletdef=applist(cl.templval.rebus,[mkMetamv])in{templval=mk_freelisteddef;templtyp=mk_freelistedconcl;evd=e';env=cl.env;cache=create_meta_instance_subste'}|_->raiseNotExtensibleClauseinclrectyp(* Instantiate the first [bound] products of [t] with metas (all products if
[bound] is [None]; unfold local defs *)(** [clenv_environments sigma n t] returns [sigma',lmeta,ccl] where
[lmetas] is a list of metas to be applied to a proof of [t] so that
it produces the unification pattern [ccl]; [sigma'] is [sigma]
extended with [lmetas]; if [n] is defined, it limits the size of
the list even if [ccl] is still a product; otherwise, it stops when
[ccl] is not a product; example: if [t] is [forall x y, x=y -> y=x]
and [n] is [None], then [lmetas] is [Meta n1;Meta n2;Meta n3] and
[ccl] is [Meta n1=Meta n2]; if [n] is [Some 1], [lmetas] is [Meta n1]
and [ccl] is [forall y, Meta n1=y -> y=Meta n1] *)letclenv_environmentsevdboundt=letopenEConstrinletopenVarsinletrecclrec(e,metas)nt=matchn,EConstr.kindevdtwith|(Some0,_)->(e,List.revmetas,t)|(n,Cast(t,_,_))->clrec(e,metas)nt|(n,Prod(na,t1,t2))->letmv=new_meta()inletdep=not(noccurnevd1t2)inletna'=ifdepthenna.binder_nameelseAnonymousinlete'=meta_declaremvt1~name:na'einclrec(e',(mkMetamv)::metas)(Option.map((+)(-1))n)(ifdepthen(subst1(mkMetamv)t2)elset2)|(n,LetIn(na,b,_,t))->clrec(e,metas)n(subst1bt)|(n,_)->(e,List.revmetas,t)inclrec(evd,[])boundtletmk_clenv_from_envenvsigman(c,cty)=letevd=clear_metassigmainlet(evd,args,concl)=clenv_environmentsevdnctyin{templval=mk_freelisted(applist(c,args));templtyp=mk_freelistedconcl;evd=evd;env=env;cache=create_meta_instance_substevd}letmk_clenv_from_nglsn(c,cty)=letenv=Proofview.Goal.envglsinletsigma=Tacmach.New.projectglsinmk_clenv_from_envenvsigman(c,cty)letmk_clenv_fromgls=mk_clenv_from_nglsNone(******************************************************************)(* [mentions clenv mv0 mv1] is true if mv1 is defined and mentions
* mv0, or if one of the free vars on mv1's freelist mentions
* mv0 *)letmentionsclenvmv0=letrecmenrecmv1=Int.equalmv0mv1||letmlist=trymatchmeta_opt_fvalueclenv.evdmv1with|Some(b,_)->b.freemetas|None->Metaset.emptywithNot_found->Metaset.emptyinMetaset.existsmenrecmlistinmenrecleterror_incompatible_instclenvmv=letna=meta_nameclenv.evdmvinmatchnawithNameid->user_err~hdr:"clenv_assign"(str"An incompatible instantiation has already been found for "++Id.printid)|_->anomaly~label:"clenv_assign"(Pp.str"non dependent metavar already assigned.")(* TODO: replace by clenv_unify (mkMeta mv) rhs ? *)letclenv_assignmvrhsclenv=letrhs_fls=mk_freelistedrhsinifMetaset.exists(mentionsclenvmv)rhs_fls.freemetasthenuser_errPp.(str"clenv_assign: circularity in unification");tryifmeta_definedclenv.evdmvthenifnot(EConstr.eq_constrclenv.evd(fst(meta_fvalueclenv.evdmv)).rebusrhs)thenerror_incompatible_instclenvmvelseclenvelseletst=(Conv,TypeNotProcessed)inupdate_clenv_evdclenv(meta_assignmv(rhs_fls.rebus,st)clenv.evd)withNot_found->user_errPp.(str"clenv_assign: undefined meta")(* [clenv_dependent hyps_only clenv]
* returns a list of the metavars which appear in the template of clenv,
* and which are dependent, This is computed by taking the metavars of the
* template in right-to-left order, and collecting the metavars which appear
* in their types, and adding in all the metavars appearing in the
* type of clenv.
* If [hyps_only] then metavariables occurring in the concl are _excluded_
* If [iter] is also set then all metavariables *recursively* occurring
* in the concl are _excluded_
Details of the strategies used for computing the set of unresolved
dependent metavariables
We typically have a clause of the form
lem(?T:Type,?T,?U:Type,?V:Type,?x:?T,?y:?U,?z:?V,?H:hyp(?x,?z)) :concl(?y,?z)
Then, we compute:
A = the set of all unresolved metas
C = the set of metas occurring in concl (here ?y, ?z)
C* = the recursive closure of C wrt types (here ?y, ?z, ?U, ?V)
D = the set of metas occurring in a type of meta (here ?x, ?T, ?z, ?U, ?V)
NL = the set of duplicated metas even if non dependent (here ?T)
(we make the assumption that duplicated metas have internal dependencies)
Then, for the "apply"-style tactic (hyps_only), missing metas are
A inter ((D minus C) union NL)
for the optimized "apply"-style tactic (taking in care, f_equal style
lemma, from 2/8/10, Coq > 8.3), missing metas are
A inter (( D minus C* ) union NL)
for the "elim"-style tactic, missing metas are
A inter (D union C union NL)
In any case, we respect the order given in A.
*)letclenv_metas_in_type_of_metaclenvmv=(mk_freelisted(meta_instanceclenv.envclenv.cache(meta_ftypeclenv.evdmv))).freemetasletdependent_in_type_of_metasclenvmvs=List.fold_right(funmv->Metaset.union(clenv_metas_in_type_of_metaclenvmv))mvsMetaset.emptyletdependent_closureclenvmvs=letrecauxmvsacc=Metaset.fold(funmvdeps->letmetas_of_meta_type=clenv_metas_in_type_of_metaclenvmvinauxmetas_of_meta_type(Metaset.uniondepsmetas_of_meta_type))mvsaccinauxmvsmvsletclenv_dependent_genhyps_only?(iter=true)clenv=letall_undefined=undefined_metasclenv.evdinletdeps_in_concl=(mk_freelisted(clenv_typeclenv)).freemetasinletdeps_in_hyps=dependent_in_type_of_metasclenvall_undefinedinletdeps_in_concl=ifhyps_only&&iterthendependent_closureclenvdeps_in_conclelsedeps_in_conclinList.filter(funmv->ifhyps_onlythenMetaset.memmvdeps_in_hyps&¬(Metaset.memmvdeps_in_concl)elseMetaset.memmvdeps_in_hyps||Metaset.memmvdeps_in_concl)all_undefinedletclenv_missingce=clenv_dependent_gentrueceletclenv_dependentce=clenv_dependent_genfalsece(******************************************************************)(* Instantiate metas that create beta/iota redexes *)letmeta_reducible_instanceenvevdb=letfm=b.freemetasinletfoldmvaccu=letfvalue=trymeta_opt_fvalueevdmvwithNot_found->Noneinmatchfvaluewith|None->accu|Some(g,(_,s))->Metamap.addmv(g.rebus,s)accuinletmetas=Metaset.foldfoldfmMetamap.emptyinletrecirecu=letu=whd_betaiotaenvEvd.emptyu(* FIXME *)inmatchEConstr.kindevduwith|Case(ci,u,pms,p,iv,c,bl)whenEConstr.isMetaevd(strip_outer_castevdc)->letm=destMetaevd(strip_outer_castevdc)in(matchtryletg,s=Metamap.findmmetasinletis_coerce=matchswithCoerceToType->true|_->falseinifisConstructevdg||notis_coercethenSomegelseNonewithNot_found->Nonewith|Someg->irec(mkCase(ci,u,pms,p,iv,g,bl))|None->leton_ctx(na,c)=(na,irecc)inmkCase(ci,u,Array.mapirecpms,on_ctxp,iv,c,Array.mapon_ctxbl))|App(f,l)whenEConstr.isMetaevd(strip_outer_castevdf)->letm=destMetaevd(strip_outer_castevdf)in(matchtryletg,s=Metamap.findmmetasinletis_coerce=matchswithCoerceToType->true|_->falseinifisLambdaevdg||notis_coercethenSomegelseNonewithNot_found->Nonewith|Someg->irec(mkApp(g,l))|None->mkApp(f,Array.mapirecl))|Metam->(tryletg,s=Metamap.findmmetasinletis_coerce=matchswithCoerceToType->true|_->falseinifnotis_coercethenirecgelseuwithNot_found->u)|Proj(p,c)whenisMetaevdc||isCastevdc&&isMetaevd(pi1(destCastevdc))(* What if two nested casts? *)->letm=trydestMetaevdcwithDestKO->destMetaevd(pi1(destCastevdc))(* idem *)in(matchtryletg,s=Metamap.findmmetasinletis_coerce=matchswithCoerceToType->true|_->falseinifisConstructevdg||notis_coercethenSomegelseNonewithNot_found->Nonewith|Someg->irec(mkProj(p,g))|None->mkProj(p,c))|_->EConstr.mapevdirecuinifMetaset.is_emptyfmthen(* nf_betaiota? *)b.rebuselseirecb.rebusletclenv_unify?(flags=default_unify_flags())cv_pbt1t2clenv=update_clenv_evdclenv(w_unify~flagsclenv.envclenv.evdcv_pbt1t2)letclenv_unify_meta_types?(flags=default_unify_flags())clenv=update_clenv_evdclenv(w_unify_meta_types~flags:flagsclenv.envclenv.evd)letclenv_unique_resolver_gen?(flags=default_unify_flags())clenvconcl=ifisMetaclenv.evd(fst(decompose_app_vectclenv.evd(whd_noredclenv.envclenv.evdclenv.templtyp.rebus)))thenclenv_unifyCUMUL~flags(clenv_typeclenv)concl(clenv_unify_meta_types~flagsclenv)elseclenv_unifyCUMUL~flags(meta_reducible_instanceclenv.envclenv.evdclenv.templtyp)conclclenvletclenv_unique_resolver?flagsclenvgl=letconcl=Proofview.Goal.conclglinclenv_unique_resolver_gen?flagsclenvconclletadjust_meta_sourceevdmv=function|loc,Evar_kinds.VarInstanceid->letrecmatch_namecl=matchEConstr.kindevdc,lwith|Lambda({binder_name=Nameid},_,c),a::lwhenEConstr.eq_constrevda(mkMetamv)->Someid|Lambda(_,_,c),a::l->match_namecl|_->Nonein(* This is very ad hoc code so that an evar inherits the name of the binder
in situations like "ex_intro (fun x => P) ?ev p" *)letf=function(mv',(Cltyp(_,t)|Clval(_,_,t)))->ifMetaset.memmvt.freemetasthenletf,l=decompose_appevdt.rebusinmatchEConstr.kindevdfwith|Metamv''->(matchmeta_opt_fvalueevdmv''with|Some(c,_)->match_namec.rebusl|None->None)|_->NoneelseNoneinletid=tryList.find_mapf(Evd.meta_listevd)withNot_found->idinloc,Evar_kinds.VarInstanceid|src->src(* [clenv_pose_metas_as_evars clenv dep_mvs]
* For each dependent evar in the clause-env which does not have a value,
* pose a value for it by constructing a fresh evar. We do this in
* left-to-right order, so that every evar's type is always closed w.r.t.
* metas.
* Node added 14/4/08 [HH]: before this date, evars were collected in
clenv_dependent by collect_metas in the fold_constr order which is
(almost) the left-to-right order of dependencies in term. However,
due to K-redexes, collect_metas was sometimes missing some metas.
The call to collect_metas has been replaced by a call to
undefined_metas, but then the order was the one of definition of
the metas (numbers in increasing order) which is _not_ the
dependency order when a clenv_fchain occurs (because clenv_fchain
plugs a term with a list of consecutive metas in place of a - a priori -
arbitrary metavariable belonging to another sequence of consecutive metas:
e.g., clenv_fchain may plug (H ?1 ?2) at the position ?6 of
(nat_ind ?3 ?4 ?5 ?6), leading to a dependency order 3<4<5<1<2).
To ensure the dependency order, we check that the type of each meta
to pose is already meta-free, otherwise we postpone the transformation,
hoping that no cycle may happen.
Another approach could have been to use decimal numbers for metas so that
in the example above, (H ?1 ?2) would have been renumbered (H ?6.1 ?6.2)
then making the numeric order match the dependency order.
*)letclenv_pose_metas_as_evarsclenvdep_mvs=letrecfoldclenv=function|[]->clenv|mv::mvs->letty=clenv_meta_typeclenvmvin(* Postpone the evar-ization if dependent on another meta *)(* This assumes no cycle in the dependencies - is it correct ? *)ifoccur_metaclenv.evdtythenfoldclenv(mvs@[mv])elseletsrc=evar_source_of_metamvclenv.evdinletsrc=adjust_meta_sourceclenv.evdmvsrcinletevd=clenv.evdinlet(evd,evar)=new_evar(cl_envclenv)evd~srctyinletclenv=clenv_assignmvevar{clenvwithevd=evd}infoldclenvmvsinfoldclenvdep_mvs(******************************************************************)(* [clenv_fchain mv clenv clenv']
*
* Resolves the value of "mv" (which must be undefined) in clenv to be
* the template of clenv' be the value "c", applied to "n" fresh
* metavars, whose types are chosen by destructing "clf", which should
* be a clausale forme generated from the type of "c". The process of
* resolution can cause unification of already-existing metavars, and
* of the fresh ones which get created. This operation is a composite
* of operations which pose new metavars, perform unification on
* terms, and make bindings.
Otherwise said, from
[clenv] = [env;sigma;metas |- c:T]
[clenv'] = [env';sigma';metas' |- d:U]
[mv] = [mi] of type [Ti] in [metas]
then, if the unification of [Ti] and [U] produces map [rho], the
chaining is [env';sigma';rho'(metas),rho(metas') |- c:rho'(T)] for
[rho'] being [rho;mi:=d].
In particular, it assumes that [env'] and [sigma'] extend [env] and [sigma].
*)letfchain_flags()={(default_unify_flags())withallow_K_in_toplevel_higher_order_unification=true}letclenv_fchain?with_univs?(flags=fchain_flags())mvclenvnextclenv=(* Add the metavars of [nextclenv] to [clenv], with their name-environment *)letevd=meta_merge?with_univsnextclenv.evdclenv.evdinletclenv'={templval=clenv.templval;templtyp=clenv.templtyp;evd;env=nextclenv.env;cache=create_meta_instance_substevd}in(* unify the type of the template of [nextclenv] with the type of [mv] *)letclenv''=clenv_unify~flagsCUMUL(clenv_termclenv'nextclenv.templtyp)(clenv_meta_typeclenv'mv)clenv'in(* assign the metavar *)letclenv'''=clenv_assignmv(clenv_termclenv'nextclenv.templval)clenv''inclenv'''(***************************************************************)(* Bindings *)(* [clenv_independent clenv]
* returns a list of metavariables which appear in the term cval,
* and which are not dependent. That is, they do not appear in
* the types of other metavars which are in cval, nor in the type
* of cval, ctyp. *)letclenv_independentclenv=letmvs=collect_metasclenv.evd(clenv_valueclenv)inletctyp_mvs=(mk_freelisted(clenv_typeclenv)).freemetasinletdeps=Metaset.union(dependent_in_type_of_metasclenvmvs)ctyp_mvsinList.filter(funmv->not(Metaset.memmvdeps))mvsletqhyp_eqh1h2=matchh1,h2with|NamedHypn1,NamedHypn2->Id.equaln1n2|AnonHypi1,AnonHypi2->Int.equali1i2|_->falseletcheck_bindingsbl=matchList.duplicatesqhyp_eq(List.map(fun{CAst.v=x}->fstx)bl)with|NamedHyps::_->user_err(str"The variable "++Id.prints++str" occurs more than once in binding list.");|AnonHypn::_->user_err(str"The position "++intn++str" occurs more than once in binding list.")|[]->()letexplain_no_such_bound_variableevdid=letfoldl(n,clb)=letna=matchclbwith|Cltyp(na,_)->na|Clval(na,_,_)->nainifna!=AnonymousthenName.get_idna::lelselinletmvl=List.fold_leftfold[](Evd.meta_listevd)inuser_err~hdr:"Evd.meta_with_name"(str"No such bound variable "++Id.printid++(ifmvl==[]thenstr" (no bound variables at all in the expression)."else(str" (possible name"++str(ifList.lengthmvl==1then" is: "else"s are: ")++pr_enumId.printmvl++str").")))letmeta_with_nameevdid=letna=Nameidinletfold(l1,l2asl)(n,clb)=let(na',def)=matchclbwith|Cltyp(na,_)->(na,false)|Clval(na,_,_)->(na,true)inifName.equalnana'thenifdefthen(n::l1,l2)else(n::l1,n::l2)elselinlet(mvl,mvnodef)=List.fold_leftfold([],[])(Evd.meta_listevd)inmatchmvnodef,mvlwith|_,[]->explain_no_such_bound_variableevdid|([n],_|_,[n])->n|_->user_err~hdr:"Evd.meta_with_name"(str"Binder name \""++Id.printid++strbrk"\" occurs more than once in clause.")letmeta_of_binderclauselocmvs=function|NamedHyps->meta_with_nameclause.evds|AnonHypn->tryList.nthmvs(n-1)with(Failure_|Invalid_argument_)->user_err(str"No such binder.")leterror_already_definedb=matchbwith|NamedHypid->user_err(str"Binder name \""++Id.printid++str"\" already defined with incompatible value.")|AnonHypn->anomaly(str"Position "++intn++str" already defined.")letclenv_unify_binding_typeclenvctu=ifisMetaclenv.evd(fst(decompose_app_vectclenv.evd(whd_noredclenv.envclenv.evdu)))then(* Not enough information to know if some subtyping is needed *)CoerceToType,clenv,celse(* Enough information so as to try a coercion now *)tryletevd,c=w_coerce_to_type(cl_envclenv)clenv.evdctuinTypeProcessed,{clenvwithevd=evd},cwith|PretypeError(_,_,ActualTypeNotCoercible(_,_,(NotClean_|ConversionFailed_)))ase->raisee|ewhenprecatchable_exceptione->TypeNotProcessed,clenv,cletclenv_assign_bindingclenvkc=letk_typ=clenv_hnf_constrclenv(clenv_meta_typeclenvk)inletc_typ=nf_betaiotaclenv.envclenv.evd(clenv_get_type_ofclenvc)inletstatus,clenv',c=clenv_unify_binding_typeclenvcc_typk_typinupdate_clenv_evdclenv'(meta_assignk(c,(Conv,status))clenv'.evd)letclenv_match_argsblclenv=ifList.is_emptyblthenclenvelseletmvs=clenv_independentclenvincheck_bindingsbl;List.fold_left(funclenv{CAst.loc;v=(b,c)}->letk=meta_of_binderclenvlocmvsbinifmeta_definedclenv.evdkthenifEConstr.eq_constrclenv.evd(fst(meta_fvalueclenv.evdk)).rebuscthenclenvelseerror_already_definedbelseclenv_assign_bindingclenvkc)clenvblexceptionNoSuchBindingletclenv_constrain_last_bindingcclenv=letall_mvs=collect_metasclenv.evdclenv.templval.rebusinletk=tryList.lastall_mvswithFailure_->raiseNoSuchBindinginclenv_assign_bindingclenvkcleterror_not_right_number_missing_argumentsn=user_err(strbrk"Not the right number of missing arguments (expected "++intn++str").")letclenv_constrain_dep_argshyps_onlyblclenv=ifList.is_emptyblthenclenvelseletocclist=clenv_dependent_genhyps_onlyclenvinifInt.equal(List.lengthocclist)(List.lengthbl)thenList.fold_left2clenv_assign_bindingclenvocclistblelseifhyps_onlythen(* Tolerance for compatibility <= 8.3 *)letocclist'=clenv_dependent_genhyps_only~iter:falseclenvinifInt.equal(List.lengthocclist')(List.lengthbl)thenList.fold_left2clenv_assign_bindingclenvocclist'blelseerror_not_right_number_missing_arguments(List.lengthocclist)elseerror_not_right_number_missing_arguments(List.lengthocclist)(* This function put casts around metavariables whose type could not be
* inferred by the refiner, that is head of applications, predicates and
* subject of Cases.
* Does check that the casted type is closed. Anyway, the refiner would
* fail in this case... *)letclenv_cast_metaclenv=letreccrecu=matchEConstr.kindclenv.evduwith|App_|Case_->crec_hdu|Cast(c,_,_)whenisMetaclenv.evdc->u|Proj(p,c)->mkProj(p,crec_hdc)|_->EConstr.mapclenv.evdcrecuandcrec_hdu=matchEConstr.kindclenv.evd(strip_outer_castclenv.evdu)with|Metamv->(tryletb=Typing.meta_typeclenv.envclenv.evdmvinassert(not(occur_metaclenv.evdb));ifoccur_metaclenv.evdbthenuelsemkCast(mkMetamv,DEFAULTcast,b)withNot_found->u)|App(f,args)->mkApp(crec_hdf,Array.mapcrecargs)|Case(ci,u,pms,p,iv,c,br)->(* FIXME: we only change c because [p] is always a lambda and [br] is
most of the time??? *)mkCase(ci,u,pms,p,iv,crec_hdc,br)|Proj(p,c)->mkProj(p,crec_hdc)|_->uincrecletclenv_pose_dependent_evars?(with_evars=false)clenv=letdep_mvs=clenv_dependentclenvinletenv,sigma=clenv.env,clenv.evdinifnot(List.is_emptydep_mvs)&¬with_evarsthenraise(RefinerError(env,sigma,UnresolvedBindings(List.map(meta_nameclenv.evd)dep_mvs)));clenv_pose_metas_as_evarsclenvdep_mvsletclenv_refine?(with_evars=false)?(with_classes=true)clenv=Proofview.Goal.enterbeginfungl->letclenv=clenv_pose_dependent_evars~with_evarsclenvinletevd'=ifwith_classesthenletevd'=Typeclasses.resolve_typeclasses~filter:Typeclasses.all_evars~fail:(notwith_evars)clenv.envclenv.evdin(* After an apply, all the subgoals including those dependent shelved ones are in
the hands of the user and resolution won't be called implicitely on them. *)Typeclasses.make_unresolvables(funx->true)evd'elseclenv.evdinletclenv=update_clenv_evdclenvevd'inProofview.tclTHEN(Proofview.Unsafe.tclEVARS(Evd.clear_metasevd'))(refiner~check:falseEConstr.Unsafe.(to_constr(clenv_cast_metaclenv(clenv_valueclenv))))endopenUnificationletdft=default_unify_flagsletres_pf?with_evars?(with_classes=true)?(flags=dft())clenv=Proofview.Goal.enterbeginfungl->letclenv=clenv_unique_resolver~flagsclenvglinclenv_refine?with_evars~with_classesclenvend(* [unifyTerms] et [unify] ne semble pas gérer les Meta, en
particulier ne semblent pas vérifier que des instances différentes
d'une même Meta sont compatibles. D'ailleurs le "fst" jette les metas
provenant de w_Unify. (Utilisé seulement dans prolog.ml) *)letfail_quick_core_unif_flags={modulo_conv_on_closed_terms=SomeTransparentState.full;use_metas_eagerly_in_conv_on_closed_terms=false;use_evars_eagerly_in_conv_on_closed_terms=false;modulo_delta=TransparentState.empty;modulo_delta_types=TransparentState.full;check_applied_meta_types=false;use_pattern_unification=false;use_meta_bound_pattern_unification=true;(* ? *)allowed_evars=Evarsolve.AllowedEvars.all;restrict_conv_on_strict_subterms=false;(* ? *)modulo_betaiota=false;modulo_eta=true;}letfail_quick_unif_flags={core_unify_flags=fail_quick_core_unif_flags;merge_unify_flags=fail_quick_core_unif_flags;subterm_unify_flags=fail_quick_core_unif_flags;allow_K_in_toplevel_higher_order_unification=false;resolve_evars=false}(* let unifyTerms m n = walking (fun wc -> fst (w_Unify CONV m n [] wc)) *)letunify?(flags=fail_quick_unif_flags)m=Proofview.Goal.enterbeginfungl->letenv=Tacmach.New.pf_envglinletn=Tacmach.New.pf_conclglinletevd=clear_metas(Tacmach.New.projectgl)intryletevd'=w_unifyenvevdCONV~flagsmninProofview.Unsafe.tclEVARSADVANCEevd'withewhenCErrors.noncriticale->letinfo=Exninfo.reify()inProofview.tclZERO~infoeend(****************************************************************)(* Clausal environment for an application *)letmake_clenv_binding_genhyps_onlynenvsigma(c,t)=function|ImplicitBindingslargs->letclause=mk_clenv_from_envenvsigman(c,t)inclenv_constrain_dep_argshyps_onlylargsclause|ExplicitBindingslbind->lett=rename_bound_vars_as_displayedsigmaId.Set.empty[]tinletclause=mk_clenv_from_envenvsigman(c,t)inclenv_match_argslbindclause|NoBindings->mk_clenv_from_envenvsigman(c,t)letmake_clenv_binding_applyenvsigman=make_clenv_binding_gentruenenvsigmaletmake_clenv_bindingenvsigma=make_clenv_binding_genfalseNoneenvsigma(****************************************************************)(* Pretty-print *)letpr_clenvclenv=h(str"TEMPL: "++Termops.Internal.print_constr_envclenv.envclenv.evdclenv.templval.rebus++str" : "++Termops.Internal.print_constr_envclenv.envclenv.evdclenv.templtyp.rebus++fnl()++pr_evar_map(Some2)clenv.envclenv.evd)(****************************************************************)(** Evar version of mk_clenv *)typehole={hole_evar:EConstr.constr;hole_type:EConstr.types;hole_deps:bool;hole_name:Name.t;}typeclause={cl_holes:holelist;cl_concl:EConstr.types;}letmake_evar_clauseenvsigma?lent=letopenEConstrinletopenVarsinletbound=matchlenwith|None->-1|Somen->assert(0<=n);nin(* FIXME: do the renaming online *)lett=rename_bound_vars_as_displayedsigmaId.Set.empty[]tinletrecclrec(sigma,holes)instnt=ifn=0then(sigma,holes,t)elsematchEConstr.kindsigmatwith|Cast(t,_,_)->clrec(sigma,holes)instnt|Prod(na,t1,t2)->(* Share the evar instances as we are living in the same context *)letinst,ctx,args,subst=matchinstwith|None->(* Dummy type *)letctx,_,args,subst=push_rel_context_to_named_contextenvsigmamkPropinSome(ctx,args,subst),ctx,args,subst|Some(ctx,args,subst)->inst,ctx,args,substinlet(sigma,ev)=new_pure_evar~typeclass_candidate:falsectxsigma(csubst_substsubstt1)inletev=mkEvar(ev,args)inletdep=not(noccurnsigma1t2)inlethole={hole_evar=ev;hole_type=t1;hole_deps=dep;(* We fix it later *)hole_name=na.binder_name;}inlett2=ifdepthensubst1evt2elset2inclrec(sigma,hole::holes)inst(predn)t2|LetIn(na,b,_,t)->clrec(sigma,holes)instn(subst1bt)|_->(sigma,holes,t)inlet(sigma,holes,t)=clrec(sigma,[])Noneboundtinletholes=List.revholesinletclause={cl_concl=t;cl_holes=holes}in(sigma,clause)letexplain_no_such_bound_variableholesid=letfoldhaccu=matchh.hole_namewith|Anonymous->accu|Nameid->id::accuinletmvl=List.fold_rightfoldholes[]inletexpl=matchmvlwith|[]->str" (no bound variables at all in the expression)."|[id]->str"(possible name is: "++Id.printid++str")."|_->str"(possible names are: "++pr_enumId.printmvl++str")."inuser_err(str"No such bound variable "++Id.printid++expl)letevar_with_nameholesid=letmaph=matchh.hole_namewith|Anonymous->None|Nameid'->ifId.equalidid'thenSomehelseNoneinlethole=List.map_filtermapholesinmatchholewith|[]->explain_no_such_bound_variableholesid|[h]->h.hole_evar|_->user_err(str"Binder name \""++Id.printid++str"\" occurs more than once in clause.")letevar_of_binderholes=function|NamedHyps->evar_with_nameholess|AnonHypn->tryletnondeps=List.filter(funhole->nothole.hole_deps)holesinleth=List.nthnondeps(predn)inh.hole_evarwithewhenCErrors.noncriticale->user_err(str"No such binder.")letdefine_with_typesigmaenvevc=letopenEConstrinlett=Retyping.get_type_ofenvsigmaevinletty=Retyping.get_type_ofenvsigmacinletj=Environ.make_judgectyinlet(sigma,j,_trace)=Coercion.inh_conv_coerce_to~program_mode:falsetrueenvsigmajtinlet(ev,_)=destEvarsigmaevinletsigma=Evd.defineevj.Environ.uj_valsigmainsigmaletsolve_evar_clauseenvsigmahyp_onlyclause=function|NoBindings->sigma|ImplicitBindingslargs->letopenEConstrinletfoldholesh=ifh.hole_depsthen(* Some subsequent term uses the hole *)let(ev,_)=destEvarsigmah.hole_evarinletis_dephole=occur_evarsigmaevhole.hole_typeinletin_hyp=List.existsis_depholesinletin_ccl=occur_evarsigmaevclause.cl_conclinletdep=ifhyp_onlythenin_hyp&¬in_cclelsein_hyp||in_cclinleth={hwithhole_deps=dep}inh::holeselse(* The hole does not occur anywhere *)h::holesinletholes=List.fold_leftfold[](List.revclause.cl_holes)inletmaph=ifh.hole_depsthenSomeh.hole_evarelseNoneinletevs=List.map_filtermapholesinletlen=List.lengthevsinifInt.equallen(List.lengthlargs)thenletfoldsigmaevarg=define_with_typesigmaenvevarginletsigma=List.fold_left2foldsigmaevslargsinsigmaelseerror_not_right_number_missing_argumentslen|ExplicitBindingslbind->let()=check_bindingslbindinletfoldsigma{CAst.v=(binder,c)}=letev=evar_of_binderclause.cl_holesbinderindefine_with_typesigmaenvevcinletsigma=List.fold_leftfoldsigmalbindinsigma