1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237(************************************************************************)(* * 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) *)(************************************************************************)(** This files defines the basic mechanism of proofs: the [proofview]
type is the state which tactics manipulate (a global state for
existential variables, together with the list of goals), and the type
['a tactic] is the (abstract) type of tactics modifying the proof
state and returning a value of type ['a]. *)openPpopenUtilopenProofview_monadopenContext.Named.Declaration(** Main state of tactics *)typeproofview=Proofview_monad.proofview(* evar env
* proofs (under construction).
* statements that are being proved. *)typeentry=(Environ.named_context_val*EConstr.constr*EConstr.types)list(** Returns a stylised view of a proofview for use by, for instance,
ide-s. *)(* spiwack: the type of [proofview] will change as we push more
refined functions to ide-s. This would be better than spawning a
new nearly identical function every time. Hence the generic name. *)(* In this version: returns the list of focused goals together with
the [evar_map] context. *)letproofviewp=List.mapdrop_statep.comb,p.solutionletcompactel({solution}aspv)=letnfc=Evarutil.nf_evarsolutioncinletnf0c=EConstr.(to_constr~abort_on_undefined_evars:falsesolution(of_constrc))inletnf_hypshyps=Environ.map_named_val(fund->map_constrnf0d)hypsinletsize=Evd.fold(fun__i->i+1)solution0inletnew_el=List.map(fun(hyps,t,ty)->nf_hypshyps,nft,nfty)elinletpruned_solution=Evd.drop_all_definedsolutioninletapply_subst_einfo_ei=Evd.map_evar_infonfeiinletnew_solution=Evd.raw_map_undefinedapply_subst_einfopruned_solutioninletnew_size=Evd.fold(fun__i->i+1)new_solution0inFeedback.msg_info(Pp.str(Printf.sprintf"Evars: %d -> %d\n"sizenew_size));new_el,{pvwithsolution=new_solution;}(** {6 Starting and querying a proof view} *)typetelescope=|TNilofEvd.evar_map|TConsofEnviron.env*Evd.evar_map*EConstr.types*(Evd.evar_map->EConstr.constr->telescope)letmap_telescope_evdf=function|TNilsigma->TNil(fsigma)|TCons(env,sigma,ty,g)->TCons(env,(fsigma),ty,g)letdependent_init=(* Goals don't have a source location. *)letsrc=Loc.tag@@Evar_kinds.GoalEvarin(* Main routine *)letrecaux=function|TNilsigma->[],{solution=sigma;comb=[]}|TCons(env,sigma,typ,t)->let(sigma,econstr)=Evarutil.new_evarenvsigma~src~typeclass_candidate:falsetypinlet(gl,_)=EConstr.destEvarsigmaeconstrinletret,{solution=sol;comb=comb}=aux(tsigmaeconstr)inletentry=(Environ.named_context_valenv,econstr,typ)::retinentry,{solution=sol;comb=with_empty_stategl::comb}infunt->lett=map_telescope_evdEvd.push_future_goalstinletentry,v=auxtin(* The created goal are not to be shelved. *)let_goals,solution=Evd.pop_future_goalsv.solutioninentry,{vwithsolution}letinit=letrecauxsigma=function|[]->TNilsigma|(env,g)::l->TCons(env,sigma,g,(funsigma_->auxsigmal))infunsigmal->dependent_init(auxsigmal)letinitial_goalsinitial=initialletfinished=function|{comb=[]}->true|_->falseletreturn{solution=defs}=defsletreturn_constr{solution=defs}c=Evarutil.nf_evardefscletpartial_proofentrypv=CList.map(return_constrpv)(CList.mappi2entry)(** {6 Focusing commands} *)(** A [focus_context] represents the part of the proof view which has
been removed by a focusing action, it can be used to unfocus later
on. *)(* First component is a reverse list of the goals which come before
and second component is the list of the goals which go after (in
the expected order). *)typefocus_context=goal_with_statelist*goal_with_statelist(** Returns a stylised view of a focus_context for use by, for
instance, ide-s. *)(* spiwack: the type of [focus_context] will change as we push more
refined functions to ide-s. This would be better than spawning a
new nearly identical function every time. Hence the generic name. *)(* In this version: the goals in the context, as a "zipper" (the first
list is in reversed order). *)letfocus_context(left,right)=(List.mapdrop_stateleft,List.mapdrop_stateright)(** This (internal) function extracts a sublist between two indices,
and returns this sublist together with its context: if it returns
[(a,(b,c))] then [a] is the sublist and [(rev b) @ a @ c] is the
original list. The focused list has length [j-i-1] and contains
the goals from number [i] to number [j] (both included) the first
goal of the list being numbered [1]. [focus_sublist i j l] raises
[IndexOutOfRange] if [i > length l], or [j > length l] or [j <
i]. *)letfocus_sublistijl=let(left,sub_right)=CList.goto(i-1)linlet(sub,right)=tryCList.chop(j-i+1)sub_rightwithFailure_->raiseCList.IndexOutOfRangein(sub,(left,right))(** Inverse operation to the previous one. *)letunfocus_sublist(left,right)s=CList.rev_appendleft(s@right)(** [focus i j] focuses a proofview on the goals from index [i] to
index [j] (inclusive, goals are indexed from [1]). I.e. goals
number [i] to [j] become the only focused goals of the returned
proofview. It returns the focused proofview, and a context for
the focus stack. *)letfocusijsp=let(new_comb,(left,right))=focus_sublistijsp.combin({spwithcomb=new_comb},(left,right))letcleared_aliasevdg=letevk=drop_stateginletstate=get_stateginOption.map(fung->goal_with_stategstate)(Evarutil.advanceevdevk)(** [undefined defs l] is the list of goals in [l] which are still
unsolved (after advancing cleared goals). Note that order matters. *)letundefined_evarsdefsl=letfoldevk(seen,ansasaccu)=matchEvarutil.advancedefsevkwith|None->accu|Someevk->ifEvar.Set.memevkseenthenaccuelse(Evar.Set.addevkseen,evk::ans)insnd@@List.fold_rightfoldl(Evar.Set.empty,[])letundefineddefsl=letfoldgl(seen,ansasaccu)=matchcleared_aliasdefsglwith|None->accu|Somegl->letevk=drop_stateglinifEvar.Set.memevkseenthenaccuelse(Evar.Set.addevkseen,gl::ans)insnd@@List.fold_rightfoldl(Evar.Set.empty,[])(** Unfocuses a proofview with respect to a context. *)letunfocus(left,right)sp={spwithcomb=undefinedsp.solution(unfocus_sublist(left,right)sp.comb)}letwith_empty_state=Proofview_monad.with_empty_stateletdrop_state=Proofview_monad.drop_stateletgoal_with_state=Proofview_monad.goal_with_state(** {6 The tactic monad} *)(** - Tactics are objects which apply a transformation to all the
subgoals of the current view at the same time. By opposition to
the old vision of applying it to a single goal. It allows tactics
such as [shelve_unifiable], tactics to reorder the focused goals,
or global automation tactic for dependent subgoals (instantiating
an evar has influences on the other goals of the proof in
progress, not being able to take that into account causes the
current eauto tactic to fail on some instances where it could
succeed). Another benefit is that it is possible to write tactics
that can be executed even if there are no focused goals.
- Tactics form a monad ['a tactic], in a sense a tactic can be
seen as a function (without argument) which returns a value of
type 'a and modifies the environment (in our case: the view).
Tactics of course have arguments, but these are given at the
meta-level as OCaml functions. Most tactics in the sense we are
used to return [()], that is no really interesting values. But
some might pass information around. The tactics seen in Coq's
Ltac are (for now at least) only [unit tactic], the return values
are kept for the OCaml toolkit. The operation or the monad are
[Proofview.tclUNIT] (which is the "return" of the tactic monad)
[Proofview.tclBIND] (which is the "bind") and [Proofview.tclTHEN]
(which is a specialized bind on unit-returning tactics).
- Tactics have support for full-backtracking. Tactics can be seen
having multiple success: if after returning the first success a
failure is encountered, the tactic can backtrack and use a second
success if available. The state is backtracked to its previous
value, except the non-logical state defined in the {!NonLogical}
module below.
*)(* spiwack: as far as I'm aware this doesn't really relate to
F. Kirchner and C. Muñoz. *)moduleProof=Logical(** type of tactics:
tactics can
- access the environment,
- report unsafe status, shelved goals and given up goals
- access and change the current [proofview]
- backtrack on previous changes of the proofview *)type+'atactic='aProof.t(** Applies a tactic to the current proofview. *)letapply~name~polyenvtsp=letopenLogic_monadinletans=Proof.repr(Proof.runtP.{trace=false;name;poly}(sp,env))inletans=Logic_monad.NonLogical.runansinmatchanswith|Nil(e,info)->Exninfo.iraise(TacticFailuree,info)|Cons((r,(state,_),status,info),_)->r,state,status,Trace.to_treeinfo(** {7 Monadic primitives} *)(** Unit of the tactic monad. *)lettclUNIT=Proof.return(** Bind operation of the tactic monad. *)lettclBIND=Proof.(>>=)(** Interprets the ";" (semicolon) of Ltac. As a monadic operation,
it's a specialized "bind". *)lettclTHEN=Proof.(>>)(** [tclIGNORE t] has the same operational content as [t], but drops
the returned value. *)lettclIGNORE=Proof.ignoremoduleMonad=Proof(** {7 Failure and backtracking} *)(** [tclZERO e] fails with exception [e]. It has no success. *)lettclZERO?(info=Exninfo.null)e=ifnot(CErrors.noncriticale)thenCErrors.anomaly(Pp.str"tclZERO receiving critical error: "++CErrors.printe);Proof.zero(e,info)(** [tclOR t1 t2] behaves like [t1] as long as [t1] succeeds. Whenever
the successes of [t1] have been depleted and it failed with [e],
then it behaves as [t2 e]. In other words, [tclOR] inserts a
backtracking point. *)lettclOR=Proof.plus(** [tclORELSE t1 t2] is equal to [t1] if [t1] has at least one
success or [t2 e] if [t1] fails with [e]. It is analogous to
[try/with] handler of exception in that it is not a backtracking
point. *)lettclORELSEt1t2=letopenLogic_monadinletopenProofinsplitt1>>=function|Nile->t2e|Cons(a,t1')->plus(returna)t1'(** [tclIFCATCH a s f] is a generalisation of {!tclORELSE}: if [a]
succeeds at least once then it behaves as [tclBIND a s] otherwise,
if [a] fails with [e], then it behaves as [f e]. *)lettclIFCATCHasf=letopenLogic_monadinletopenProofinsplita>>=function|Nile->fe|Cons(x,a')->plus(sx)(fune->(a'e)>>=funx'->(sx'))(** [tclONCE t] behave like [t] except it has at most one success:
[tclONCE t] stops after the first success of [t]. If [t] fails
with [e], [tclONCE t] also fails with [e]. *)lettclONCE=Proof.onceexceptionMoreThanOneSuccesslet_=CErrors.register_handlerbeginfunction|MoreThanOneSuccess->Some(Pp.str"This tactic has more than one success.")|_->Noneend(** [tclEXACTLY_ONCE e t] succeeds as [t] if [t] has exactly one
success. Otherwise it fails. The tactic [t] is run until its first
success, then a failure with exception [e] is simulated. It [t]
yields another success, then [tclEXACTLY_ONCE e t] fails with
[MoreThanOneSuccess] (it is a user error). Otherwise,
[tclEXACTLY_ONCE e t] succeeds with the first success of
[t]. Notice that the choice of [e] is relevant, as the presence of
further successes may depend on [e] (see {!tclOR}). *)lettclEXACTLY_ONCEet=letopenLogic_monadinletopenProofinsplitt>>=function|Nil(e,info)->tclZERO~infoe|Cons(x,k)->letinfo=Exninfo.nullinProof.split(k(e,Exninfo.null))>>=function|Nil_->tclUNITx|_->tclZERO~infoMoreThanOneSuccess(** [tclCASE t] wraps the {!Proofview_monad.Logical.split} primitive. *)type'acase=|FailofExninfo.iexn|Nextof'a*(Exninfo.iexn->'atactic)lettclCASEt=letopenLogic_monadinletmap=function|Nile->Faile|Cons(x,t)->Next(x,t)inProof.mapmap(Proof.splitt)lettclBREAK=Proof.break(** {7 Focusing tactics} *)exceptionNoSuchGoalsofintlet_=CErrors.register_handlerbeginfunction|NoSuchGoalsn->Some(str"No such "++str(String.pluraln"goal")++str".")|_->Noneend(** [tclFOCUS ?nosuchgoal i j t] applies [t] in a context where
only the goals numbered [i] to [j] are focused (the rest of the goals
is restored at the end of the tactic). If the range [i]-[j] is not
valid, then it [tclFOCUS_gen nosuchgoal i j t] is [nosuchgoal]. *)lettclFOCUS?nosuchgoalijt=letnosuchgoal~info=Option.default(tclZERO~info(NoSuchGoals(j+1-i)))nosuchgoalinletopenProofinPv.get>>=funinitial->trylet(focused,context)=focusijinitialinPv.setfocused>>t>>=funresult->Pv.modify(funnext->unfocuscontextnext)>>returnresultwithCList.IndexOutOfRangeasexn->let_,info=Exninfo.captureexninnosuchgoal~infolettclTRYFOCUSijt=tclFOCUS~nosuchgoal:(tclUNIT())ijtlettclFOCUSLIST?(nosuchgoal=tclZERO(NoSuchGoals0))lt=letopenProofinComb.get>>=funcomb->letn=CList.lengthcombinletok(i,j)=1<=i&&i<=j&&j<=ninifnot(CList.for_allokl)thennosuchgoalelsematchlwith|[]->nosuchgoal|(mi,_)::_->(* Get the left-most goal to focus. This goal won't move, and we
will then place all the other goals to focus to the right. *)letmi=CList.fold_left(funm(i,_)->minmi)milin(* [CList.goto] returns a zipper, so that
[(rev left) @ sub_right = comb]. *)letleft,sub_right=CList.goto(mi-1)combinletpx_=CList.exists(fun(i,j)->i<=x+mi&&x+mi<=j)linletsub,right=CList.partitionipsub_rightinletmj=mi-1+CList.lengthsubinComb.set(CList.rev_appendleft(sub@right))>>tclFOCUSmimjt(** Like {!tclFOCUS} but selects a single goal by name. *)lettclFOCUSID?(nosuchgoal=tclZERO(NoSuchGoals1))idt=letopenProofinPv.get>>=funinitial->tryletev=Evd.evar_keyidinitial.solutionintryletcomb=CList.mapdrop_stateinitial.combinletn=CList.indexEvar.equalevcombin(* goal is already under focus *)let(focused,context)=focusnninitialinPv.setfocused>>t>>=funresult->Pv.modify(funnext->unfocuscontextnext)>>returnresultwithNot_found->(* otherwise, save current focus and work purely on the shelve *)Comb.set[with_empty_stateev]>>t>>=funresult->Comb.get>>=fungls'->Comb.setinitial.comb>>letgls'=CList.filter_map(funev'->letev'=drop_stateev'in(* if ev' is still undefined, leave it on its original shelf *)if(Evar.equalevev')thenNoneelseSomeev')gls'inPv.modify(funpv->{pvwithsolution=Evd.shelvepv.solution(undefined_evarspv.solutiongls')})>>returnresultwithNot_found->nosuchgoal(** {7 Dispatching on goals} *)exceptionSizeMismatchofint*intlet_=CErrors.register_handlerbeginfunction|SizeMismatch(i,j)->letopenPpinSome(str"Incorrect number of goals"++spc()++str"(expected "++inti++str(String.plurali" tactic")++str", was given "++intj++str").")|_->Noneend(** A variant of [Monad.List.iter] where we iter over the focused list
of goals. The argument tactic is executed in a focus comprising
only of the current goal, a goal which has been solved by side
effect is skipped. The generated subgoals are concatenated in
order. *)letiter_goali=letopenProofinComb.get>>=funinitial->Proof.List.fold_leftbeginfun(subgoalsascur)goal->Solution.get>>=funstep->matchcleared_aliasstepgoalwith|None->returncur|Somegoal->Comb.set[goal]>>igoal>>Proof.map(funcomb->comb::subgoals)Comb.getend[]initial>>=funsubgoals->Solution.get>>=funevd->Comb.setCList.(undefinedevd(flatten(revsubgoals)))(** List iter but allocates a list of results *)letmap_goali=letrev=List.revin(* hem... Proof masks List... *)letopenProofinComb.get>>=funinitial->Proof.List.fold_leftbeginfun(acc,subgoalsascur)goal->Solution.get>>=funstep->matchcleared_aliasstepgoalwith|None->returncur|Somegoal->Comb.set[goal]>>igoal>>=funres->Proof.map(funcomb->comb::subgoals)Comb.get>>=funx->return(res::acc,x)end([],[])initial>>=fun(results_rev,subgoals)->Solution.get>>=funevd->Comb.setCList.(undefinedevd(flatten(revsubgoals)))>>return(revresults_rev)(** A variant of [Monad.List.fold_left2] where the first list is the
list of focused goals. The argument tactic is executed in a focus
comprising only of the current goal, a goal which has been solved
by side effect is skipped. The generated subgoals are concatenated
in order. *)letfold_left2_goalisl=letopenProofinPv.get>>=funinitial->leterr=return()>>=fun()->(* Delay the computation of list lengths. *)tclZERO(SizeMismatch(CList.lengthinitial.comb,CList.lengthl))inProof.List.fold_left2errbeginfun((r,subgoals)ascur)goala->Solution.get>>=funstep->matchcleared_aliasstepgoalwith|None->returncur|Somegoal->Comb.set[goal]>>igoalar>>=funr->Proof.map(funcomb->(r,comb::subgoals))Comb.getend(s,[])initial.combl>>=fun(r,subgoals)->Solution.get>>=funevd->Comb.setCList.(undefinedevd(flatten(revsubgoals)))>>returnr(** Dispatch tacticals are used to apply a different tactic to each
goal under focus. They come in two flavours: [tclDISPATCH] takes a
list of [unit tactic]-s and build a [unit tactic]. [tclDISPATCHL]
takes a list of ['a tactic] and returns an ['a list tactic].
They both work by applying each of the tactic in a focus
restricted to the corresponding goal (starting with the first
goal). In the case of [tclDISPATCHL], the tactic returns a list of
the same size as the argument list (of tactics), each element
being the result of the tactic executed in the corresponding goal.
When the length of the tactic list is not the number of goal,
raises [SizeMismatch (g,t)] where [g] is the number of available
goals, and [t] the number of tactics passed.
[tclDISPATCHGEN join tacs] generalises both functions as the
successive results of [tacs] are stored in reverse order in a
list, and [join] is used to convert the result into the expected
form. *)lettclDISPATCHGEN0jointacs=matchtacswith|[]->beginletopenProofinComb.get>>=function|[]->tclUNIT(join[])|comb->tclZERO(SizeMismatch(CList.lengthcomb,0))end|[tac]->beginletopenProofinPv.get>>=function|{comb=[goal];solution}->beginmatchcleared_aliassolutiongoalwith|None->tclUNIT(join[])|Some_->Proof.map(funres->join[res])tacend|{comb}->tclZERO(SizeMismatch(CList.lengthcomb,1))end|_->letiter_tcur=Proof.map(funy->y::cur)tinletans=fold_left2_goaliter[]tacsinProof.mapjoinanslettclDISPATCHGENjointacs=letbrancht=InfoL.tag(Info.DBranch)tinlettacs=CList.mapbranchtacsinInfoL.tag(Info.Dispatch)(tclDISPATCHGEN0jointacs)lettclDISPATCHtacs=tclDISPATCHGENignoretacslettclDISPATCHLtacs=tclDISPATCHGENCList.revtacs(** [extend_to_list startxs rx endxs l] builds a list
[startxs @ [rx,...,rx] @ endxs] of the same length as [l]. Raises
[SizeMismatch] if [startxs @ endxs] is already longer than [l]. *)letextend_to_liststartxsrxendxsl=(* spiwack: I use [l] essentially as a natural number *)letrecduplicateacc=function|[]->acc|_::rest->duplicate(rx::acc)restinletrectailto_matchrest=matchrest,to_matchwith|[],_::_->raise(SizeMismatch(0,0))(* placeholder *)|_::rest,_::to_match->tailto_matchrest|_,[]->duplicateendxsrestinletreccopyprefrest=matchrest,prefwith|[],_::_->raise(SizeMismatch(0,0))(* placeholder *)|_::rest,a::pref->a::(copyprefrest)|_,[]->tailendxsrestincopystartxsl(** [tclEXTEND b r e] is a variant of {!tclDISPATCH}, where the [r]
tactic is "repeated" enough time such that every goal has a tactic
assigned to it ([b] is the list of tactics applied to the first
goals, [e] to the last goals, and [r] is applied to every goal in
between). *)lettclEXTENDtacs1rtactacs2=letopenProofinComb.get>>=funcomb->trylettacs=extend_to_listtacs1rtactacs2combintclDISPATCHtacswithSizeMismatch_->tclZERO(SizeMismatch(CList.lengthcomb,(CList.lengthtacs1)+(CList.lengthtacs2)))(* spiwack: failure occurs only when the number of goals is too
small. Hence we can assume that [rtac] is replicated 0 times for
any error message. *)(** [tclEXTEND [] tac []]. *)lettclINDEPENDENTtac=letopenProofinPv.get>>=funinitial->matchinitial.combwith|[]->tclUNIT()|[_]->tac|_->lettac=InfoL.tag(Info.DBranch)tacinInfoL.tag(Info.Dispatch)(iter_goal(fun_->tac))lettclINDEPENDENTLtac=letopenProofinPv.get>>=funinitial->matchinitial.combwith|[]->tclUNIT[]|[_]->tac>>=funx->return[x]|_->lettac=InfoL.tag(Info.DBranch)tacinInfoL.tag(Info.Dispatch)(map_goal(fun_->tac))(** {7 Goal manipulation} *)(** Shelves all the goals under focus. *)letshelve=letopenProofinComb.get>>=funinitial->Comb.set[]>>InfoL.leaf(Info.Tactic(fun()->Pp.str"shelve"))>>letinitial=CList.mapdrop_stateinitialinPv.modify(funpv->{pvwithsolution=Evd.shelvepv.solutioninitial})letshelve_goalsl=letopenProofinComb.get>>=funinitial->letcomb=CList.filter(fung->not(CList.mem(drop_stateg)l))initialinComb.setcomb>>InfoL.leaf(Info.Tactic(fun()->Pp.str"shelve_goals"))>>Pv.modify(funpv->{pvwithsolution=Evd.shelvepv.solutionl})(** [depends_on sigma src tgt] checks whether the goal [src] appears
as an existential variable in the definition of the goal [tgt] in
[sigma]. *)letdepends_onsigmasrctgt=letevi=Evd.find_undefinedsigmatgtinEvar.Set.memsrc(Evd.evars_of_filtered_evar_infosigma(Evarutil.nf_evar_infosigmaevi))letunifiable_delayedgl=CList.exists(fun(tgt,lazyevs)->not(Evar.equalgtgt)&&Evar.Set.memgevs)lletfree_evarssigmal=letcache=Evarutil.create_undefined_evars_cache()inletmapev=(* Computes the set of evars appearing in the hypotheses, the conclusion or
the body of the evar_info [evi]. Note: since we want to use it on goals,
the body is actually supposed to be empty. *)letEvarInfoevi=Evd.findsigmaevinletfevs=lazy(Evarutil.filtered_undefined_evars_of_evar_info~cachesigmaevi)in(ev,fevs)inList.mapmaplletfree_evars_with_statesigmal=letcache=Evarutil.create_undefined_evars_cache()inletmapev=(* Computes the set of evars appearing in the hypotheses, the conclusion or
the body of the evar_info [evi]. Note: since we want to use it on goals,
the body is actually supposed to be empty. *)letev=drop_stateevinletEvarInfoevi=Evd.findsigmaevinletfevs=lazy(Evarutil.filtered_undefined_evars_of_evar_info~cachesigmaevi)in(ev,fevs)inList.mapmapl(** [unifiable sigma g l] checks whether [g] appears in another
subgoal of [l]. The list [l] may contain [g], but it does not
affect the result. *)letunifiable_delayed_with_statesigmagl=letg=drop_stateginunifiable_delayedglletunifiablesigmagl=letl=free_evarssigmalinunifiable_delayedgl(** [partition_unifiable sigma l] partitions [l] into a pair [(u,n)]
where [u] is composed of the unifiable goals, i.e. the goals on
whose definition other goals of [l] depend, and [n] are the
non-unifiable goals. *)letpartition_unifiablesigmal=letfevs=free_evars_with_statesigmalinCList.partition(fung->unifiable_delayed_with_statesigmagfevs)l(** Shelves the unifiable goals under focus, i.e. the goals which
appear in other goals under focus (the unfocused goals are not
considered). *)letshelve_unifiable_informative=letopenProofinPv.get>>=funinitial->let(u,n)=partition_unifiableinitial.solutioninitial.combinComb.setn>>InfoL.leaf(Info.Tactic(fun()->Pp.str"shelve_unifiable"))>>letu=CList.mapdrop_stateuinPv.modify(funpv->{pvwithsolution=Evd.shelvepv.solutionu})>>tclUNITuletshelve_unifiable=letopenProofinshelve_unifiable_informative>>=fun_->tclUNIT()(** [guard_no_unifiable] returns the list of unifiable goals if some
goals are unifiable (see {!shelve_unifiable}) in the current focus. *)letguard_no_unifiable=letopenProofinPv.get>>=funinitial->let(u,n)=partition_unifiableinitial.solutioninitial.combinmatchuwith|[]->tclUNITNone|gls->letl=CList.map(fung->Evd.dependent_evar_ident(drop_stateg)initial.solution)glsinletl=CList.map(funid->Names.Nameid)lintclUNIT(Somel)(** [unshelve l p] moves all the goals in [l] from the shelf and put them at
the end of the focused goals of p, if they are still undefined after [advance] *)letunshelvelp=letsolution=Evd.unshelvep.solutionlinletl=List.mapwith_empty_statelin(* advance the goals in case of clear *)letl=undefinedp.solutionlin{comb=p.comb@l;solution}letfilter_shelffpv={pvwithsolution=Evd.filter_shelffpv.solution}letmark_in_evm~goalevdevars=letevd=ifgoalthenletmarkevdcontent=letEvarInfoinfo=Evd.findevdcontentinletsource=matchEvd.evar_sourceinfowith(* Two kinds for goal evars:
- GoalEvar (morally not dependent)
- VarInstance (morally dependent of some name).
This is a heuristic for naming these evars. *)|loc,(Evar_kinds.QuestionMark{Evar_kinds.qm_name=Names.Nameid}|Evar_kinds.ImplicitArg(_,(_,Someid),_))->loc,Evar_kinds.VarInstanceid|_,(Evar_kinds.VarInstance_|Evar_kinds.GoalEvar)asx->x|loc,_->loc,Evar_kinds.GoalEvarinEvd.update_sourceevdcontentsourceinCList.fold_leftmarkevdevarselseevdinlettcs=Evd.get_typeclass_evarsevdinletevset=Evar.Set.of_listevarsinEvd.set_typeclass_evarsevd(Evar.Set.difftcsevset)letwith_shelftac=letopenProofinPv.get>>=funpv->let{solution}=pvinPv.set{pvwithsolution=Evd.push_shelf@@Evd.push_future_goalssolution}>>tac>>=funans->Pv.get>>=funnpv->let{solution=sigma}=npvinletgls,sigma=Evd.pop_shelfsigmain(* The pending future goals are necessarily coming from legacy tactics *)(* and thus considered as to shelve, as in Proof.run_tactic *)(* TODO: is it still relevant since the removal of the compat layer? *)letfgl,sigma=Evd.pop_future_goalssigmain(* Ensure we mark and return only unsolved goals *)letgls'=CList.rev_append(Evd.FutureGoals.combfgl)glsinletgls'=undefined_evarssigmagls'inletsigma=mark_in_evm~goal:falsesigmagls'inletnpv={npvwithsolution=sigma}inPv.setnpv>>tclUNIT(gls',ans)(** [goodmod p m] computes the representative of [p] modulo [m] in the
interval [[0,m-1]].*)letgoodmodpm=ifm=0then0elseletp'=pmodmin(* if [n] is negative [n mod l] is negative of absolute value less
than [l], so [(n mod l)+l] is the representative of [n] in the
interval [[0,l-1]].*)ifp'<0thenp'+melsep'letcyclen=letopenProofinInfoL.leaf(Info.Tactic(fun()->Pp.(str"cycle "++intn)))>>Comb.modifybeginfuninitial->letl=CList.lengthinitialinletn'=goodmodnlinlet(front,rear)=CList.chopn'initialinrear@frontendletswapij=letopenProofinInfoL.leaf(Info.Tactic(fun()->Pp.(hov2(str"swap"++spc()++inti++spc()++intj))))>>Comb.modifybeginfuninitial->letl=CList.lengthinitialinleti=ifi>0theni-1elseiandj=ifj>0thenj-1elsejinleti=goodmodilandj=goodmodjlinCList.map_ibeginfunkx->matchkwith|kwhenInt.equalki->CList.nthinitialj|kwhenInt.equalkj->CList.nthinitiali|_->xend0initialendletrevgoals=letopenProofinInfoL.leaf(Info.Tactic(fun()->Pp.str"revgoals"))>>Comb.modifyCList.revletnumgoals=letopenProofinComb.get>>=funcomb->return(CList.lengthcomb)(** {7 Access primitives} *)lettclEVARMAP=Solution.getlettclENV=Env.get(** {7 Put-like primitives} *)letemit_side_effectseffx={xwithsolution=Evd.emit_side_effectseffx.solution}lettclEFFECTSeff=letopenProofinreturn()>>=fun()->(* The Global.env should be taken at exec time *)Env.set(Global.env())>>Pv.modify(funinitial->emit_side_effectseffinitial)letmark_as_unsafe=Status.putfalse(** Gives up on the goal under focus. Reports an unsafe status. Proofs
with given up goals cannot be closed. *)letgive_upevspv=letsolution=List.fold_left(funsigmaev->Evd.give_up(drop_stateev)sigma)pv.solutionevsin{pvwithsolution}letgive_up=letopenProofinComb.get>>=funinitial->Comb.set[]>>mark_as_unsafe>>InfoL.leaf(Info.Tactic(fun()->Pp.str"give_up"))>>Pv.modify(give_upinitial)(** {7 Control primitives} *)moduleProgress=structleteq_constrevdextended_evd=Evarutil.eq_constr_univs_test~evd~extended_evd(** equality function on hypothesis contexts *)leteq_named_context_valsigma1sigma2ctx1ctx2=letr_eq__=true(* ignore relevances *)inletc1=EConstr.named_context_of_valctx1andc2=EConstr.named_context_of_valctx2inleteq_named_declarationd1d2=matchd1,d2with|LocalAssum(i1,t1),LocalAssum(i2,t2)->Context.eq_annotNames.Id.equalr_eqi1i2&&eq_constrsigma1sigma2t1t2|LocalDef(i1,c1,t1),LocalDef(i2,c2,t2)->Context.eq_annotNames.Id.equalr_eqi1i2&&eq_constrsigma1sigma2c1c2&&eq_constrsigma1sigma2t1t2|_->falsein(* NB: can't use List.equal because it shortcuts on physical equality *)List.for_all2eqeq_named_declarationc1c2leteq_evar_body(typea1a2)sigma1sigma2(b1:a1Evd.evar_body)(b2:a2Evd.evar_body)=letopenEvdinmatchb1,b2with|Evar_empty,Evar_empty->true|Evar_definedt1,Evar_definedt2->eq_constrsigma1sigma2t1t2|_->falseleteq_evar_concl(typea1a2)sigma1sigma2(e1:a1Evd.evar_info)(e2:a2Evd.evar_info)=letopenEvdinmatchEvd.evar_bodye1,Evd.evar_bodye2with|Evar_empty,Evar_empty->eq_constrsigma1sigma2(Evd.evar_concle1)(Evd.evar_concle2)|Evar_defined_,Evar_defined_->true|_->falseleteq_evar_infosigma1sigma2ei1ei2=eq_evar_conclsigma1sigma2ei1ei2&&eq_named_context_valsigma1sigma2(Evd.evar_hypsei1)(Evd.evar_hypsei2)&&eq_evar_bodysigma1sigma2(Evd.evar_bodyei1)(Evd.evar_bodyei2)letfast_eq_evar_body(typea1a2)(e1:a1Evd.evar_info)(e2:a2Evd.evar_info)=letopenEvdinmatchEvd.evar_bodye1,Evd.evar_bodye2with|Evar_empty,Evar_empty->true|Evar_defined_,Evar_defined_->true|_->falseletfast_eq_named_context_valctx1ctx2=letr_eq__=true(* ignore relevances *)inletc1=EConstr.named_context_of_valctx1inletc2=EConstr.named_context_of_valctx2inleteq_named_declarationd1d2=matchd1,d2with|LocalAssum(i1,_),LocalAssum(i2,_)->Context.eq_annotNames.Id.equalr_eqi1i2|LocalDef(i1,_,_),LocalDef(i2,_,_)->Context.eq_annotNames.Id.equalr_eqi1i2|_->falseinList.for_all2eqeq_named_declarationc1c2letfast_eq_evar_infoei1ei2=fast_eq_evar_bodyei1ei2&&fast_eq_named_context_val(Evd.evar_hypsei1)(Evd.evar_hypsei2)(** Equality function on goals *)letgoal_equal~evd~extended_evdevarextended_evar=letEvarInfoevi=Evd.findevdevarinletEvarInfoextended_evi=Evd.findextended_evdextended_evariniffast_eq_evar_infoeviextended_evitheneq_evar_infoevdextended_evdeviextended_evielsefalseendlettclPROGRESSt=letopenProofinPv.get>>=funinitial->t>>=funres->Pv.get>>=funfinal->(* [*_test] test absence of progress. [quick_test] is approximate
whereas [exhaustive_test] is complete. *)letquick_test=initial.solution==final.solution&&initial.comb==final.combinlettest=quick_test||(CList.same_lengthinitial.combfinal.comb&&Util.List.for_all2eqbeginfunif->Progress.goal_equal~evd:initial.solution~extended_evd:final.solution(drop_statei)(drop_statef)endinitial.combfinal.comb)inifnottestthentclUNITreselseletinfo=Exninfo.reify()intclZERO~info(CErrors.UserErrorPp.(str"Failed to progress."))let_=CErrors.register_handlerbeginfunction|Logic_monad.Tac_Timeout->Some(Pp.str"[Proofview.tclTIMEOUT] Tactic timeout!")|_->NoneendlettclTIMEOUTFnt=letopenProofin(* spiwack: as one of the monad is a continuation passing monad, it
doesn't force the computation to be threaded inside the underlying
(IO) monad. Hence I force it myself by asking for the evaluation of
a dummy value first, lest [timeout] be called when everything has
already been computed. *)lett=Proof.lift(Logic_monad.NonLogical.return())>>tinProof.get>>=funinitial->Proof.current>>=funenvvar->Proof.liftbeginletopenLogic_monad.NonLogicalintimeoutn(Proof.repr(Proof.runtenvvarinitial))>>=funr->matchrwith|None->return(Util.Inr(Logic_monad.Tac_Timeout,Exninfo.null))|Some(Logic_monad.Nile)->return(Util.Inre)|Some(Logic_monad.Cons(r,_))->return(Util.Inlr)end>>=function|Util.Inl(res,s,m,i)->Proof.sets>>Proof.putm>>Proof.update(fun_->i)>>returnres|Util.Inr(e,info)->tclZERO~infoelettclTIMEOUTnt=tclTIMEOUTF(float_of_intn)tlettclTIMEst=letpr_timet1t2nmsg=letmsg=ifn=0thenstrmsgelsestr(msg^" after ")++intn++str(String.pluraln" backtracking")inFeedback.msg_info(str"Tactic call"++pr_optstrs++str" ran for "++System.fmt_time_differencet1t2++str" "++surroundmsg)inletrecauxnt=letopenProofintclUNIT()>>=fun()->lettstart=System.get_time()inProof.splitt>>=letopenLogic_monadinfunction|Nil(e,info)->beginlettend=System.get_time()inpr_timetstarttendn"failure";tclZERO~infoeend|Cons(x,k)->lettend=System.get_time()inpr_timetstarttendn"success";tclOR(tclUNITx)(fune->aux(n+1)(ke))inaux0tlettclProofInfo=letopenProofinLogical.current>>=funP.{name;poly}->tclUNIT(name,poly)(** {7 Unsafe primitives} *)moduleUnsafe=structlet(>>=)=tclBINDlettclEVARSevd=Pv.modify(funps->{pswithsolution=evd})lettclNEWGOALS?(before=false)gls=Pv.modifybeginfunstep->letgls=undefinedstep.solutionglsinletcomb=ifbeforethengls@step.combelsestep.comb@glsin{stepwithcomb}endlettclNEWSHELVEDgls=Pv.modifybeginfunstep->letgls=undefined_evarsstep.solutionglsin{stepwithsolution=Evd.shelvestep.solutiongls}endlettclGETSHELF=tclEVARMAP>>=funsigma->tclUNIT@@Evd.shelfsigmalettclSETENV=Env.setlettclGETGOALS=Comb.getlettclSETGOALS=Comb.setlettclEVARSADVANCEevd=Pv.modify(funps->{solution=evd;comb=undefinedevdps.comb})lettclEVARUNIVCONTEXTctx=Pv.modify(funps->{pswithsolution=Evd.set_universe_contextps.solutionctx})letpush_future_goalsp={pwithsolution=Evd.push_future_goalsp.solution}letmark_as_goalsevdcontent=mark_in_evm~goal:trueevdcontentletadvance=Evarutil.advanceletundefined=undefinedletmark_unresolvablesevmevs=mark_in_evm~goal:falseevmevsletmark_as_unresolvablespevs={pwithsolution=mark_in_evm~goal:falsep.solutionevs}letupdate_sigma_univsugraphpv={pvwithsolution=Evd.update_sigma_univsugraphpv.solution}endmoduleUnsafeRepr=Proof.Unsafelet(>>=)=tclBIND(** {6 Goal-dependent tactics} *)letcatchable_exception=function|Logic_monad.Exception_->false|e->CErrors.noncriticalemoduleGoal=structtypet={env:Environ.env;sigma:Evd.evar_map;concl:EConstr.constr;state:StateStore.t;self:Evar.t;(* for compatibility with old-style definitions *)}letstate{state=state}=stateletenv{env}=envletsigma{sigma}=sigmalethyps{env}=EConstr.named_contextenvletconcl{concl}=conclletgmake_withinfoenvsigmagoalstate={env=Environ.reset_with_named_context(Evd.evar_filtered_hypsinfo)env;sigma=sigma;concl=Evd.evar_conclinfo;state=state;self=goal}letgmakeenvsigmagoal=letstate=get_stategoalinletgoal=drop_stategoalinletinfo=Evd.find_undefinedsigmagoalingmake_withinfoenvsigmagoalstateletenterf=letfgl=InfoL.tag(Info.DBranch)(fgl)inInfoL.tag(Info.Dispatch)beginiter_goalbeginfungoal->Env.get>>=funenv->tclEVARMAP>>=funsigma->tryf(gmakeenvsigmagoal)withewhencatchable_exceptione->let(e,info)=Exninfo.captureeintclZERO~infoeendendletenter_one?(__LOC__=__LOC__)f=letopenProofinComb.get>>=function|[goal]->beginEnv.get>>=funenv->tclEVARMAP>>=funsigma->tryf(gmakeenvsigmagoal)withewhencatchable_exceptione->let(e,info)=Exninfo.captureeintclZERO~infoeend|_->CErrors.anomalyPp.(str__LOC__++str" enter_one")letgoals=Pv.get>>=funstep->letsigma=step.solutioninletmapgoal=matchcleared_aliassigmagoalwith|None->None(* ppedrot: Is this check really necessary? *)|Somegoal->letoinfo=Evd.find_undefinedsigma(drop_stategoal)inletgl=Env.get>>=funenv->tclEVARMAP>>=funsigma->letstate=get_stategoalinletgoal=drop_stategoalinletEvarInfoinfo=Evd.findsigmagoalinletgoal={env=Environ.reset_with_named_context(Evd.evar_filtered_hypsinfo)env;sigma=sigma;concl=Evd.evar_concloinfo;state=state;self=goal;}intclUNITgoalinSomeglintclUNIT(CList.map_filtermapstep.comb)letunsolved{self=self}=tclEVARMAP>>=funsigma->tclUNIT(not(Option.is_empty(Evarutil.advancesigmaself)))(* compatibility *)letgoal{self=self}=selfend(** {6 Trace} *)moduleTrace=structletrecord_info_trace=InfoL.record_traceletlogm=InfoL.leaf(Info.Msgm)letname_tacticmt=InfoL.tag(Info.Tacticm)tletpr_infoenvsigma?(lvl=0)info=assert(lvl>=0);Info.(printenvsigma(collapselvlinfo))end(** {6 Non-logical state} *)moduleNonLogical=Logic_monad.NonLogicallettclLIFT=Proof.liftlettclCHECKINTERRUPT=tclLIFT(NonLogical.makeControl.check_for_interrupt)letwrap_exceptionsf=tryf()withewhencatchable_exceptione->let(e,info)=Exninfo.captureeintclZERO~infoe(** {7 Notations} *)moduleNotations=structlet(>>=)=tclBINDlet(<*>)=tclTHENlet(<+>)t1t2=tclORt1(fun_->t2)end