1 % Heinrich Heine Universitaet Duesseldorf
2 % (c) 2025-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(sequent_prover_exports,[export_proof_for_current_state/2, export_proof/4,
6 pretty_print_pos/1]).
7
8 :- use_module(probsrc(module_information),[module_info/2]).
9 :- module_info(group,sequent_prover).
10 :- module_info(description,'This module provides export functionality for traces created by the sequent_prover.').
11
12 :- use_module(library(lists)).
13 :- use_module(library(aggregate),[forall/2]).
14
15 :- meta_predicate with_forced_rodin_mode(0).
16
17 :- use_module(probsrc(error_manager)).
18 :- use_module(probsrc(gensym),[gensym/2]).
19 :- use_module(probsrc(specfile),[animation_minor_mode/1,get_operation_description_for_transition_id/3]).
20 :- use_module(probsrc(state_space),[get_state_id_trace/1,history/1,op_trace_ids/1,transition/4,visited_expression/2]).
21 :- use_module(probsrc(system_call),[get_temporary_filename/2]).
22 :- use_module(probsrc(translate),[translate_bexpression_to_unicode/2,transform_raw/2,with_translation_mode/2]).
23 :- use_module(probsrc(tools),[ajoin/2,ajoin_with_sep/3,get_filename_extension/2,list_difference/3,read_string_from_file/2]).
24 :- use_module(probsrc(tools_commands),[gen_dot_output/4,valid_dot_output_format/1]).
25 :- use_module(wdsrc(well_def_hyps),[normalize_expression/2,normalize_predicate/2]).
26
27 :- use_module(sequent_prover,[cont_length/2,get_continuations/2,parse_input/3,used_identifiers/2]).
28 :- use_module(prover_utils,[translate_norm_expr_term_no_limit/2,translate_norm_expr_term/2]).
29
30 export_proof_for_current_state(Mode,File) :-
31 get_state_id_trace(StateIds),
32 op_trace_ids(TransIds),
33 reverse(TransIds,RTransIds),
34 export_proof(Mode,File,StateIds,RTransIds).
35
36 export_proof(Mode,File,StateIds,TransIds) :-
37 animation_minor_mode(sequent_prover), !,
38 get_filename_extension(File,Ext),
39 (Ext=Mode -> true
40 ; ajoin(['file extension ',Ext,' does not match the proof export mode: '],Msg),
41 add_warning(sequent_prover_exports,Msg,Mode)),
42 export_proof2(Mode,File,StateIds,TransIds).
43 export_proof(_,_,_,_) :-
44 add_error(sequent_prover_exports,'Proof export is only available in sequent prover mode.'), fail.
45
46 export_proof2(html,File,StateIds,TransIds) :- !, generate_proof_html_export(File,StateIds,TransIds).
47 export_proof2(bpr, File,StateIds,TransIds) :- !, generate_proof_bpr_rodin_export(File,StateIds,TransIds).
48 export_proof2(Mode,File,StateIds,TransIds) :-
49 valid_dot_output_format(Mode), !,
50 write_proof_tree_to_file(Mode,File,StateIds,TransIds).
51 export_proof2(Mode,_,_,_) :-
52 add_error(sequent_prover_exports,'unrecognised file extension for proof export: ',Mode), fail.
53
54 %%%%%%%%% BUILD THE PROOF TREE %%%%%%%%%
55 :- dynamic proof_node/4, proof_edge/5, proof_tree/2.
56 % proof_node(ContinuationId,sequent(Hyps,Goal),Info,DotAttrList).
57 % proof_edge(PrevId,DestId,TransId,ActTerm,Label).
58 :- dynamic current_node/1, continuation/2. % auxiliary predicates used during proof tree generation
59 % continuation(ContinuationSequent,IdWhereThisContinuationWasAdded).
60
61 build_proof_tree(StateIds,TransIds) :- proof_tree(StateIds,TransIds), !. % proof tree already created
62 build_proof_tree(StateIds,TransIds) :-
63 retractall(proof_node(_,_,_,_)),
64 retractall(proof_edge(_,_,_,_,_)),
65 retractall(proof_tree(_,_)),
66 retractall(continuation(_,_)),
67 retractall(current_node(_)),
68 build_proof_tree_aux(StateIds,TransIds),
69 assertz(proof_tree(StateIds,TransIds)).
70
71 :- use_module(library(codesio),[write_to_codes/2]).
72 build_proof_tree_aux([],_).
73 build_proof_tree_aux([_StateId],_).
74 build_proof_tree_aux([PrevId,StateId|ST],[TransId|TT]) :-
75 transition(PrevId,Act,TransId,StateId),
76 Act=skip_to_cont, !, % ignore skips (just a reordering of continuations, not visible in the proof tree)
77 build_proof_tree_aux([StateId|ST],TT).
78 build_proof_tree_aux([PrevId,StateId|ST],[TransId|TT]) :-
79 transition(PrevId,Act,TransId,StateId),
80 visited_expression(StateId,State),
81 State=state(success(SNr),_), !, % proof succeeded
82 visited_expression(PrevId,PrevState),
83 (PrevState=state(PrevSequent,_Info)
84 -> PrevSequent=sequent(PVHyps,PVGoal,_)
85 ; PrevState=root),
86 (retract(continuation(sequent(PVHyps,PVGoal),ContID)) % previous sequent has been registered as continuation before
87 -> PrevNode=ContID
88 ; (current_node(PrevNode) -> true ; PrevNode=root)),
89 (get_operation_description_for_transition_id(PrevId,TransId,EdgeLabel) -> true ; write_to_codes(Act,CAct), atom_codes(EdgeLabel,CAct)),
90 assert_node_with_edge(PrevNode,success(SNr),[],TransId,[shape/triangle,style/filled,fillcolor/'#99BF38'],Act,EdgeLabel,GenID),
91 set_current_node(GenID),
92 build_proof_tree_aux([StateId|ST],TT).
93 build_proof_tree_aux([PrevId,StateId|ST],[TransId|TT]) :-
94 transition(PrevId,Act,TransId,StateId), % TODO: is there a way to obtain this directly from the history?
95 visited_expression(PrevId,PrevState), visited_expression(StateId,state(Sequent,NxtInfo)),
96 (PrevState=state(PrevSequent,Info)
97 -> PrevSequent=sequent(PVHyps,PVGoal,_), cont_length(PrevSequent,PrevLen)
98 ; PrevState=root, PrevLen=0, Info=NxtInfo), % for root use next info (important for des_hyps)
99 Sequent=sequent(Hyps,Goal,_),
100
101 (retract(continuation(sequent(PVHyps,PVGoal),ContID)) % previous sequent has been registered as continuation before
102 -> PrevNode=ContID
103 ; (current_node(PrevNode) -> true ; PrevNode=root)),
104
105 (get_operation_description_for_transition_id(PrevId,TransId,EdgeLabel) -> true ; write_to_codes(Act,CAct), atom_codes(EdgeLabel,CAct)),
106
107 cont_length(Sequent,Len),
108 (PrevLen>Len % sequent has been proven by the current transition and disappeared
109 -> assert_node_with_edge(PrevNode,success(-1),Info,TransId,[shape/triangle,style/filled,fillcolor/'#99BF38'],Act,EdgeLabel,_GenID)
110 ; assert_node_with_edge(PrevNode,sequent(Hyps,Goal),Info,TransId,[shape/box],Act,EdgeLabel,GenID),
111 assertz(continuation(sequent(Hyps,Goal),GenID)), % store position of current node
112 set_current_node(GenID)
113 ),
114
115 get_continuations(Sequent,Conts),
116 forall(member(Cont,Conts),assert_new_continuation(Cont,PrevNode,Info,TransId,Act,EdgeLabel)),
117 build_proof_tree_aux([StateId|ST],TT).
118
119 assert_node_with_edge(PrevNode,Sequent,Info,TransId,NodeAttr,Act,EdgeLabel,GenID) :-
120 gensym('seq_prov_',GenID),
121 assertz(proof_node(GenID,Sequent,Info,NodeAttr)),
122 assertz(proof_edge(PrevNode,GenID,TransId,Act,EdgeLabel)).
123
124 assert_new_continuation(Cont,_,_,_,_,_) :-
125 continuation(Cont,_ID), !. % is already registered
126 % TODO: what happens if the same continuation occurs more than once?
127 assert_new_continuation(Cont,PrevNode,Info,TransId,Act,EdgeLabel) :-
128 assert_node_with_edge(PrevNode,Cont,Info,TransId,[shape/box],Act,EdgeLabel,CID),
129 assertz(continuation(Cont,CID)).
130
131 set_current_node(ID) :-
132 retractall(current_node(_)),
133 assertz(current_node(ID)).
134
135 %%%%%%%%% END BUILD THE PROOF TREE %%%%%%%%%
136
137 %%%%%%%%% HELPER PREDICATES FOR SEQUENT_PROVER STATES %%%%%%%%%
138 pretty_hyps(sequent(Hyps,_),PHyps) :- maplist(translate_norm_expr_term,Hyps,PHyps).
139 pretty_goal(sequent(_,Goal),PGoal) :- translate_norm_expr_term(Goal,PGoal).
140
141
142 %%%%%%%%% BEGIN PROOF TREE DOT GRAPH %%%%%%%%%
143 :- use_module(dotsrc(dot_graph_generator), [gen_dot_graph/6,use_new_dot_attr_pred/7]).
144 generate_proof_tree_graph(File,StateIds,TransIds) :-
145 (animation_minor_mode(sequent_prover) -> true
146 ; add_error_and_fail(sequent_prover_exports,'Cannot create proof tree visualisation, not in sequent prover mode (load a .pl PO file exported by the ProB Rodin Plugin)','')),
147 build_proof_tree(StateIds,TransIds),
148 proof_tree_title_attrs(TitleAttrs),
149 gen_dot_graph(File,
150 [graph_name/proof_tree, no_page_size, fontname/'Helvetica', nodesep/0.3, ranksep/0.35,
151 node_defaults/[fontname/'Helvetica', fontsize/11, shape/box, style/'rounded,filled',
152 fillcolor/white, color/gray55, margin/'0.12,0.06'],
153 edge_defaults/[fontname/'Helvetica', fontsize/9, color/'#606060', fontcolor/'#404040', arrowsize/0.7]
154 | TitleAttrs],
155 use_new_dot_attr_pred(sequent_prover_exports:proof_tree_graph_node_predicate),
156 use_new_dot_attr_pred(sequent_prover_exports:proof_tree_graph_trans_predicate),
157 dot_no_same_rank,dot_no_subgraph).
158
159 proof_tree_title_attrs([label/Title, labelloc/t, fontsize/TFS]) :-
160 get_preference(dot_print_graph_title,true), !,
161 get_preference(dot_title_font_size,TFS),
162 (xtl_main_file_name(POFile), POFile \= ''
163 -> tools:get_tail_filename(POFile,Tail), ajoin(['Proof tree - ',Tail],Title)
164 ; Title = 'Proof tree').
165 proof_tree_title_attrs([]).
166
167 proof_legend(Text,Order,[legend/Text, legend_order/Order]) :- get_preference(dot_print_legend,true), !.
168 proof_legend(_,_,[]).
169
170 :- public proof_tree_graph_node_predicate/3.
171 proof_tree_graph_node_predicate(root,none,[shape/invhouse, label/'Select PO', fillcolor/'#ECEFF1', color/'#607D8B',
172 fontcolor/'#37474F', tooltip/'Start: selection of the proof obligation']).
173 proof_tree_graph_node_predicate(NodeId,none,[id/NodeId, label/htmllabel(Label), fillcolor/'#C8E6C9', color/'#2E7D32',
174 fontcolor/'#1B5E20', tooltip/'Sequent proven' | Legend]) :-
175 proof_node(NodeId,success(_),_,_),
176 Label = '<✓ proven>',
177 proof_legend('proven',10,Legend).
178 proof_tree_graph_node_predicate(NodeId,none,[id/NodeId, label/htmllabel(Label), tooltip/Tooltip | Attrs]) :-
179 proof_node(NodeId,Sequent,_,_),
180 Sequent\=success(_), NodeId\=root,
181 (proof_edge(PrevNode,NodeId,_,_,_), proof_node(PrevNode,PrevSequent,_,_)
182 -> true
183 ; PrevSequent=none), % first sequent: nothing to compare with
184 build_html_dot_label(PrevSequent,Sequent,Label),
185 (proof_edge(NodeId,_,_,_,_)
186 -> Attrs=Legend, proof_legend('sequent (changes in bold orange)',20,Legend),
187 Tooltip='Sequent: hypotheses above the line, goal below'
188 ; Attrs=[color/'#C77700', penwidth/2 | Legend], proof_legend('open sequent (not yet proven)',30,Legend),
189 Tooltip='Open sequent: not yet proven'). % leaf which is not proven
190
191 build_html_dot_label(PrevSequent,Sequent,Label) :-
192 pretty_hyps(Sequent,PHyps),
193 (PrevSequent=none -> PPrevHyps=PHyps, PPrevGoal=none ; pretty_hyps(PrevSequent,PPrevHyps), pretty_goal(PrevSequent,PPrevGoal)),
194 pred_changed(PHyps,PPrevHyps,ChangedPHyps),
195 (ChangedPHyps=[]
196 -> HypLabel='<TR><TD ALIGN="LEFT"><FONT COLOR="#909090"><I>no hypotheses</I></FONT></TD></TR>' % no hyps
197 ; maplist(label_for_pred,ChangedPHyps,HypLabels),
198 ajoin(HypLabels,HypLabel)),
199 pretty_goal(Sequent,PGoal),
200 (PPrevGoal=none -> Changed=goal ; PPrevGoal=PGoal -> Changed=goal ; Changed=changed_goal),
201 label_for_pred(pred_line(PGoal,Changed),GoalLabel),
202 ajoin(['<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="1">', HypLabel, '<HR/>', GoalLabel, '</TABLE>>'],Label).
203
204 label_for_pred(pred_line(Pred,Changed),PredLabel) :-
205 tools:html_escape(Pred,EPred),
206 pred_line_style(Changed,Pre,Post),
207 ajoin(['<TR><TD ALIGN="LEFT">',Pre,EPred,Post,'</TD></TR>'],PredLabel).
208
209 pred_line_style(changed,'<FONT COLOR="#C25E00"><B>','</B></FONT>').
210 pred_line_style(changed_goal,'<FONT COLOR="#C25E00"><B>⊢ ','</B></FONT>').
211 pred_line_style(goal,'<B>⊢ ','</B>').
212 pred_line_style(not_changed,'<FONT COLOR="#606060">','</FONT>').
213
214 pred_changed([],_,[]).
215 pred_changed([Hyp|HT],PrevHyps,[pred_line(Hyp,Changed)|RT]) :-
216 (selectchk(Hyp,PrevHyps,NPrevHyps)
217 -> Changed=not_changed
218 ; Changed=changed, NPrevHyps=PrevHyps),
219 pred_changed(HT,NPrevHyps,RT).
220
221 :- public proof_tree_graph_trans_predicate/3.
222 proof_tree_graph_trans_predicate(PrevId,SuccId,[label/Label, tooltip/Label]) :-
223 proof_edge(PrevId,SuccId,_TransId,_Act,Label).
224
225 write_proof_tree_to_file(Mode,File,StateIds,TransIds) :-
226 get_temporary_filename('_dot_proof_tree.dot',DotFile),
227 generate_proof_tree_graph(DotFile,StateIds,TransIds),
228 gen_dot_output(DotFile,dot,Mode,File).
229 %%%%%%%%% END PROOF TREE DOT GRAPH %%%%%%%%%
230
231 %%%%%%%%% BEGIN PROOF TREE HTML EXPORT %%%%%%%%%
232 :- dynamic proof_html_export_template_file_codes/2.
233
234 assert_from_template(Filename) :-
235 absolute_file_name(seqproversrc(Filename), Absolute, []),
236 read_string_from_file(Absolute,String),
237 assertz(proof_html_export_template_file_codes(Filename,String)).
238
239 write_proof_html_export_template(HtmlFile,Stream) :-
240 proof_html_export_template_file_codes(HtmlFile,Codes),
241 format(Stream,'~s~n',[Codes]).
242
243 :- assert_from_template('proof_html_export_header.html').
244 :- assert_from_template('proof_html_export_footer.html').
245
246 % TODO: maybe highlight selected step in SVG; allow to select a step by clicking in the proof tree
247 :- use_module(probsrc(preferences),[get_preference/2]).
248 :- use_module(probsrc(xtl_interface),[xtl_main_file_name/1]).
249 generate_proof_html_export(File,StateIds,TransIds) :-
250 (animation_minor_mode(sequent_prover) -> true
251 ; add_error_and_fail(sequent_prover_exports,'Cannot create proof export, not in sequent prover mode (load a .pl PO file exported by the ProB Rodin Plugin)','')),
252 build_proof_tree(StateIds,TransIds), % important for step_list
253 retractall(trans_id_done(_)),
254 retractall(html_step_nr(_)),
255 assertz(html_step_nr(1)),
256
257 tools_io:safe_open_file(File,write,Stream,[encoding(utf8)]),
258 write_proof_html_export_template('proof_html_export_header.html',Stream),
259 xtl_main_file_name(POFile),
260 (proof_edge(root,_,_,_,POLabel)
261 -> format(Stream,' <div>Proof Trace Export for <b>~w</b> from <pre>~w</pre></div>~n',[POLabel,POFile])
262 ; format(Stream,' <div>Proof Trace Export from ~w</div>~n',[POFile])),
263 format(Stream,' <hr/>~n',[]),
264 format(Stream,' <div id="boxContainer" style="display: flex; width: 100%; position:fixed; height: 90vh;">~n',[]),
265 format(Stream,' <div id="stepListBox" style="width: 30%; display: flex; flex-direction: column;">~n',[]),
266 gen_step_list(Stream,TransIds),
267 write_generation_info(Stream),
268 format(Stream,' </div>~n',[]),
269 format(Stream,' <div id="divider" class="divider"> </div>~n',[]),
270 format(Stream,' <div id="treeBox" style="width: 66.5%; height: 97%; margin-left: 5px;">~n',[]),
271 format(Stream,' <div class="box-caption">Proof Tree</div>~n',[]),
272 format(Stream,' <div text-align="left" id="proof_tree_svg_outer_container" class="svg-outer-container">~n',[]),
273 format(Stream,' <div text-align="left" id="proof_tree_svg_inner_container" class="svg-inner-container">~n',[]),
274 write_proof_tree_svg_to_stream(Stream,StateIds,TransIds), % generate proof tree dot graph (with ProB dot preferences)
275 format(Stream,' </div>~n',[]),
276 format(Stream,' </div>~n',[]),
277 format(Stream,' <button id="btnResetScale" class="visualisation-button" onclick="resetScale()">Reset View</button>~n',[]),
278 format(Stream,' </div>~n',[]), % close tree box
279 format(Stream,' </div>~n',[]), % close box container
280 write_proof_html_export_template('proof_html_export_footer.html',Stream),
281 close(Stream).
282
283 :- use_module(probsrc(tools_io),[write_file_to_stream/2]).
284 write_proof_tree_svg_to_stream(Stream,StateIds,TransIds) :-
285 get_temporary_filename('_dot_proof_tree.svg',SvgFile),
286 write_proof_tree_to_file(svg,SvgFile,StateIds,TransIds),
287 write_file_to_stream(SvgFile,Stream).
288
289 :- dynamic trans_id_done/1, html_step_nr/1.
290 gen_step_list(Stream,TransIds) :-
291 format(Stream,' <div class="box-caption" style="display: flex; justify-content: space-between;">Proof Steps~n',[]),
292 format(Stream,' <div>~n',[]),
293 format(Stream,' <button class="step-button" onclick="selectPrevStep()">< Previous Step</button>~n',[]),
294 format(Stream,' <button class="step-button" onclick="selectNextStep()">Next Step ></button>~n',[]),
295 format(Stream,' <button class="step-button" onclick="runAll()">Run Steps</button>~n',[]),
296 format(Stream,' </div>~n',[]),
297 format(Stream,' </div>~n',[]),
298 format(Stream,' <div class="step-list">~n',[]),
299 gen_step_list_entry(Stream,TransIds),
300 format(Stream,' </div>~n',[]).
301 gen_step_list_entry(Stream,TransIds) :-
302 member(TransId,TransIds),
303 proof_edge(PrevId,_Id,TransId,_,Label),
304 \+ PrevId=root,
305 \+ trans_id_done(TransId),
306 findall(Id,proof_edge(_,Id,TransId,_,_),SuccIds),
307 ajoin_with_sep([PrevId|SuccIds],'\',\'',IDList),
308 format(Stream,' <div class="step-header green" onclick="focusSequents(\'trans_~w\',[\'~w\'])">~n',[TransId,IDList]),
309 retract(html_step_nr(SNr)),
310 NSNr is SNr+1,
311 assertz(html_step_nr(NSNr)),
312 format(Stream,' <b>~w. ~w</b>~n',[SNr,Label]),
313 format(Stream,' </div>~n',[]),
314 % TODO: here we could display more proof step details in the table (then an icon for extended/not-extended would be nice):
315 format(Stream,' <div class="step-content" id="trans_~w">~n',[TransId]),
316 % format(Stream,' <b>_TODO_</b>~n',[]),
317 format(Stream,' </div>~n',[]),
318 assertz(trans_id_done(TransId)),
319 fail.
320 gen_step_list_entry(_,_).
321
322 :- use_module(library(system),[datime/1]).
323 :- use_module(probsrc(tools_strings),[number_codes_min_length/3]).
324 :- use_module(probsrc(version),[version_str/1,revision/1]).
325 write_generation_info(Stream) :-
326 version_str(VStr), revision(VRev),
327 format(Stream,' <div style="color: grey; font-size: 0.7rem;"><br>ProB Version: ~w (~w)~n',[VStr,VRev]),
328 datime(datime(Yr,Mon,Day,Hr,Min,_Sec)),
329 number_codes_min_length(Mon,2,MonC), number_codes_min_length(Min,2,MinC),
330 format(Stream,' <br>Generated on ~w/~s/~w at ~w:~s</div>~n',[Day,MonC,Yr,Hr,MinC]).
331 %%%%%%%%% END PROOF TREE HTML EXPORT %%%%%%%%%
332
333 % TODO: bpr_import? difficult as some details can be left out to the bpo file
334 %%%%%%%%% BEGIN PROOF TREE RODIN BPR EXPORT %%%%%%%%%
335 :- dynamic predicate_id_count/1, expression_id_count/1, rule_id_count/1.
336 :- dynamic prPred/3, prExpr/3, prIdent/2, prReas/2.
337
338 generate_proof_bpr_rodin_export(File,StateIds,TransIds) :-
339 (animation_minor_mode(sequent_prover)
340 -> add_message(sequent_prover_exports,'The BPR Rodin proof export is experimental and may contain errors!')
341 ; add_error_and_fail(sequent_prover_exports,'Cannot create proof export, not in sequent prover mode (load a .pl PO file exported by the ProB Rodin Plugin)','')),
342 build_proof_tree(StateIds,TransIds),
343 retractall(prPred(_,_,_)),
344 retractall(prExpr(_,_,_)),
345 retractall(prIdent(_,_)),
346 retractall(prReas(_,_)),
347 retractall(predicate_id_count(_)),
348 retractall(expression_id_count(_)),
349 retractall(rule_id_count(_)),
350 assertz(predicate_id_count(0)),
351 assertz(expression_id_count(0)),
352 assertz(rule_id_count(0)),
353 tools_io:safe_open_file(File,write,Stream,[encoding(utf8)]),
354 generate_bpr_to_stream(Stream,StateIds,TransIds),
355 % TODO: handle existing BPR file: replace only one proof, add (one/multiple) proofs to the file, ...
356 close(Stream).
357
358 % general idea of the translation: each proof_edge becomes a prRule, with a prAnte for each proof_node (continuation)
359 generate_bpr_to_stream(Stream,StateIds,TransIds) :-
360 format(Stream,'<?xml version="1.0" encoding="UTF-8" standalone="no"?>~n',[]),
361 format(Stream,'<org.eventb.core.prFile version="1">~n',[]),
362 (TransIds\=[] -> generate_bpr_proof_tree(Stream,StateIds,TransIds) ; true),
363 format(Stream,'</org.eventb.core.prFile>~n',[]), flush_output(Stream).
364
365 :- use_module(sequent_prover,[get_scope/3,po_nr_label/2,normalised_hyps/3,normalised_goal/3]).
366 generate_bpr_proof_tree(Stream,StateIds,TransIds) :-
367 StateIds=[root,S1|_], TransIds=[T1|_],
368 transition(root,start_xtl_system,T1,S1), % extract first state to determine selected PO
369 visited_expression(S1,state(sequent(NormHyps,NormGoal,success(PONr)),Info)),
370
371 member(des_hyps(DesHyps),Info),
372 append(DesHyps,NormHyps,AllHyps),
373 get_scope([NormGoal|AllHyps],Info,[identifier(Ids)]),
374 forall(member(Id,Ids),assert_identifier(Id)), % register global IDs known in the initial step (including goal)
375
376 po_nr_label(PONr,POLabel),
377 normalised_hyps(POLabel,RawPreds,NormPreds),
378 normalised_goal(POLabel,RawGoal,NormGoal),
379 get_prob_normalisation_rewrites(RawPreds,NormPreds,HypRewrites),
380 get_prob_normalisation_rewrites([RawGoal],[NormGoal],GoalRewr),
381 (GoalRewr=[hyp_action(rewrite,G1,G2)] -> true ; assert_hyp_predicate(NormGoal,G1), G1=G2), % rewrite goal if necessary
382
383 proof_edge(root,FirstNode,_,_,_),
384 format_indent(Stream,'<org.eventb.core.prProof name="~w" org.eventb.core.confidence="1000" org.eventb.core.prFresh="" org.eventb.core.prGoal="" org.eventb.core.prHyps="" org.eventb.core.psManual="true">~n',[POLabel],1),
385 format_indent(Stream,'<org.eventb.core.lang name="L"/>~n',[],2),
386 (HypRewrites=[]
387 -> write_proof_rule(Stream,FirstNode,2) % no ProB AST normalisation
388 ; assert_rule_index('org.eventb.core.seqprover.review',RID), % TODO: disable normalisation/add as reasoner?
389 format_indent(Stream,'<org.eventb.core.prRule name="~w" org.eventb.core.confidence="1000" org.eventb.core.prDisplay="ProB AST normalisation" org.eventb.core.prGoal="~w" org.eventb.core.prHyps="">~n',[RID,G1],2),
390 get_next_rule_comment(FirstNode,CommentCodes),
391 format_indent(Stream,'<org.eventb.core.prAnte name="\'" org.eventb.core.comment="~s" org.eventb.core.prGoal="~w">~n',[CommentCodes,G2],3),
392 write_hyp_actions(Stream,HypRewrites,0,4),
393 write_proof_rule(Stream,FirstNode,4),
394 format_indent(Stream,'</org.eventb.core.prAnte>~n',[],3),
395 format_indent(Stream,'</org.eventb.core.prRule>~n',[],2)),
396
397 findall('$'(Id),member(b(identifier(Id),_,_),Ids),IdsOfFirstStep),
398 write_identifiers(Stream,global,IdsOfFirstStep,2),
399 write_predicate_mapping(Stream,2),
400 write_expression_mapping(Stream,2),
401 write_reasoner_mapping(Stream,2),
402 format_indent(Stream,'</org.eventb.core.prProof>~n',[],1).
403
404 write_proof_rule(Stream,FromNode,Indent) :-
405 proof_edge(FromNode,_,_,Act,Desc), !, % generate only one prRule
406 get_rule_reasoner(Act,ReasID,RID,Conf), % TODO: add option to use without Rodin reasoner IDs?
407 proof_node(FromNode,sequent(Hyps,Goal),_,_),
408 get_hyp_ids(Act,Hyps,HypIds),
409 get_expr_ids(Act,ExprIds),
410 get_pred_ids(Act,PredIds),
411 % TODO: is it useful to print enum sets?, e.g. org.eventb.core.prSets="Beverages" (but works without)
412 get_goal_id(Act,ReasID,Goal,GoalStr),
413 xml_attribute_escape_atom(Desc,EDesc),
414 format_indent(Stream,'<org.eventb.core.prRule name="~w" org.eventb.core.confidence="~w" org.eventb.core.prDisplay="~s" ~w org.eventb.core.prHyps="~w">~n',[RID,Conf,EDesc,GoalStr,HypIds],Indent),
415 write_proof_rule2(Stream,FromNode,ReasID,ExprIds,PredIds,Indent).
416 write_proof_rule(_,_,_). % write nothing, this is an open antecedent without rule
417 write_proof_rule2(Stream,FromNode,_,_,_,Indent) :-
418 proof_edge(FromNode,NextNode,_,Act,_Desc),
419 proof_node(FromNode,sequent(Hyps,_Goal),FromInfo,_),
420 (member(des_hyps(DesHyps),FromInfo) -> true ; DesHyps=[]),
421 (proof_node(NextNode,sequent(NHyps,_NGoal),_,_)
422 -> compute_hyp_actions_for_rule(DesHyps,Hyps,NHyps,HypActions0),
423 adapt_hyp_actions_for_rule(Act,HypActions0,HypActions)
424 ; HypActions=[]), % for success(_)
425 AnteIndent is Indent+1,
426 write_antecedant(Stream,FromNode,NextNode,HypActions,AnteIndent),
427 fail.
428 write_proof_rule2(Stream,_,_,prExprRef(RefType,ExprIds),_,Indent) :- % RefType can be exprs or subst, ... depending on the rule
429 ExprIds \= [],
430 ajoin_with_sep(ExprIds,',',SepExprIds),
431 AnteIndent is Indent+1,
432 format_indent(Stream,'<org.eventb.core.prExprRef name=".~w" org.eventb.core.prRef="~w"/>~n',[RefType,SepExprIds],AnteIndent),
433 fail.
434 write_proof_rule2(Stream,_,_,_,prPredRef(RefType,PredIds),Indent) :-
435 PredIds \= [],
436 ajoin_with_sep(PredIds,',',SepPredIds),
437 AnteIndent is Indent+1,
438 format_indent(Stream,'<org.eventb.core.prPredRef name=".~w" org.eventb.core.prRef="~w"/>~n',[RefType,SepPredIds],AnteIndent),
439 fail.
440 write_proof_rule2(Stream,_,ReasID,_,_,Indent) :-
441 rule_requires_pos(ReasID,PosNr),
442 AnteIndent is Indent+1,
443 format_indent(Stream,'<org.eventb.core.prString name=".pos" org.eventb.core.prSValue="~w"/>~n',[PosNr],AnteIndent),
444 fail.
445 write_proof_rule2(Stream,_,_,_,_,Indent) :- format_indent(Stream,'</org.eventb.core.prRule>~n',[],Indent).
446
447 % prRule WITHOUT org.eventb.core.prHyps="" (null hyps) is not valid!
448 get_hyp_ids(and_l(Pred),_,HypIds) :- !, assert_hyp_predicate(Pred,HypIds). % provide only the affected Hyp, then the rule expects a forward_inf as first rewrite
449 get_hyp_ids(and_r,_,HypIds) :- !, HypIds=''. % AND_R expects null hyps
450 get_hyp_ids(eq(_,L,R),_,HypIds) :- !, assert_hyp_predicate(equal(L,R),HypIds). % provide the exact hypId
451 get_hyp_ids(imp_case(Pred),_,HypIds) :- !, assert_hyp_predicate(Pred,HypIds). % provide only the affected Hyp
452 get_hyp_ids(simplify_goal(_),_,HypIds) :- !, HypIds=''.
453 get_hyp_ids(simplify_hyp(_,Hyp),_,HypIds) :- !, assert_hyp_predicate(Hyp,HypIds).
454 get_hyp_ids(Rule,Hyps,HypIds) :-
455 rule_with_hyp_inst(Rule,HypNr,_), !,
456 nth1(HypNr,Hyps,ForallHyp),
457 assert_hyp_predicate(ForallHyp,HypIds).
458 get_hyp_ids(_,Hyps,SepHypIds) :-
459 maplist(assert_hyp_predicate,Hyps,HypIds),
460 ajoin_with_sep(HypIds,',',SepHypIds).
461
462 get_expr_ids(Rule,ExprIds) :-
463 rule_with_expr(Rule,Expr,Kind), !,
464 parse_input(Expr,Rule,TExpr),
465 normalize_expression(TExpr,NormExpr),
466 assert_expression(NormExpr,ExprId),
467 ExprIds = prExprRef(Kind,[ExprId]).
468 get_expr_ids(Rule,ExprIds) :-
469 RName='DERIV_DOM_TOTALREL'(DomExpr),
470 (Rule=simplify_hyp(RName,_) ; Rule=simplify_goal(RName)), !,
471 assert_expression(DomExpr,ExprId), % value of the domain.
472 ExprIds = prExprRef(subst,[ExprId]).
473 get_expr_ids(_,prExprRef(none,[])).
474
475 % TODO: add more rules with user input
476 rule_with_expr(exists_inst(Inst),Expr,Kind) :- !, Expr=Inst, Kind=exprs.
477 rule_with_expr(Rule,Expr,Kind) :- rule_with_hyp_inst(Rule,_,Inst), !, Expr=Inst, Kind=exprs.
478 rule_with_expr(Rule,Expr,Kind) :- rule_with_pfun_input(Rule,PFun), !, Expr=PFun, Kind=expr.
479
480 rule_with_hyp_inst(forall_inst(HypNr,Inst),HypNr,Inst).
481 rule_with_hyp_inst(forall_inst_mp(HypNr,Inst),HypNr,Inst).
482 rule_with_hyp_inst(forall_inst_mt(HypNr,Inst),HypNr,Inst).
483
484 % extensions of the PFunSetInputReasoner
485 rule_with_pfun_input(fin_fun_dom_r(PFun),PFun).
486 rule_with_pfun_input(fin_fun_img_r(PFun),PFun).
487 rule_with_pfun_input(fin_fun_ran_r(PFun),PFun).
488 rule_with_pfun_input(fin_fun1_r(PFun),PFun).
489 rule_with_pfun_input(fin_fun2_r(PFun),PFun).
490
491 get_pred_ids(Rule,PredIds) :-
492 rule_with_pred(Rule,Pred,Kind), !,
493 parse_input(Pred,Rule,TPred),
494 normalize_predicate(TPred,NormPred),
495 sequent_prover:translate_finite_expr(NormPred,NewPred),
496 assert_hyp_predicate(NewPred,PredId),
497 PredIds = prPredRef(Kind,[PredId]).
498 get_pred_ids(_,prPredRef(none,[])).
499
500 rule_with_pred(add_hyp(Hyp),Pred,Kind) :- !, Pred=Hyp, Kind=pred.
501 rule_with_pred(distinct_case(P),Pred,Kind) :- !, Pred=P, Kind=pred.
502
503 % prRule WITH org.eventb.core.prGoal="" is not a valid null goal!
504 get_goal_id(cntr,_,_,GoalStr) :- !, GoalStr=''. % CNTR produces null goal
505 get_goal_id(imp_case(_),_,_,GoalStr) :- !, GoalStr=''. % is goal independent
506 get_goal_id(simplify_hyp(_,_),ReasID,_,GoalStr) :- \+ rodin_review_reasoner(ReasID), !, GoalStr=''. % is goal independent if not reviewed
507 get_goal_id(_,_,Goal,GoalStr) :-
508 assert_hyp_predicate(Goal,GID), % should already be registered, get ID only
509 ajoin(['org.eventb.core.prGoal="',GID,'"'],GoalStr).
510
511 rodin_review_reasoner('org.eventb.core.seqprover.review').
512
513 rule_requires_pos('org.eventb.core.seqprover.ri',''). % TODO: extend list
514 rule_requires_pos('org.eventb.core.seqprover.riUniversal','').
515 rule_requires_pos('org.eventb.core.seqprover.rmL2','').
516 rule_requires_pos('org.eventb.core.seqprover.rn','').
517 rule_requires_pos('org.eventb.core.seqprover.setEqlRewrites','').
518 rule_requires_pos('org.eventb.core.seqprover.totalDom:2','1'). % always 1?
519
520 compute_hyp_actions_for_rule(_,[],[],Res) :- !, Res=[].
521 compute_hyp_actions_for_rule(DesHyps,[],[NewHyp|NT],Res) :-
522 !, % there are new hyps after the existing ones -> SELECT or new_hyp
523 select_hyp(DesHyps,NewHyp,Act),
524 compute_hyp_actions_for_rule(DesHyps,[],NT,Acts),
525 Res=[Act|Acts].
526 compute_hyp_actions_for_rule(_,PrevHyps,CurHyps,HypActs) :-
527 select(DesHyp,PrevHyps,CurHyps), !, % one hypothesis has been removed -> DESELECT
528 deselect_hyp(DesHyp,Act),
529 HypActs=[Act].
530 compute_hyp_actions_for_rule(DesHyps,PrevHyps,CurHyps,HypActs) :-
531 append(PrevHyps,AddHyps,CurHyps), !, % only new hypotheses have been added -> SELECT or new_hyp
532 maplist(select_hyp(DesHyps),AddHyps,HypActs).
533 compute_hyp_actions_for_rule(DesHyps,[PHyp|PT],[CHyp|CT],HypActs) :-
534 PHyp\=CHyp, !,
535 (PT=[NHyp|_], CT=[NHyp|_] % hyp has been rewritten; after that, the sequent is the same -> REWRITE
536 -> rewrite_hyp(PHyp,CHyp,Act0), HypActs=[Act0|HypActs1],
537 compute_hyp_actions_for_rule(DesHyps,PT,CT,HypActs1)
538 ; (PT=[CHyp|_] % previous hyp has been deselected and replaced (next prev hyp is the current) -> DESELECT
539 -> deselect_hyp(PHyp,Act1), HypActs=[Act1|HypActs1],
540 compute_hyp_actions_for_rule(DesHyps,PT,[CHyp|CT],HypActs1)
541 ; deselect_hyp(PHyp,Act2), select_hyp(DesHyps,CHyp,Act3), HypActs=[Act2,Act3|HypActs1],
542 compute_hyp_actions_for_rule(DesHyps,PT,CT,HypActs1))
543 % last row changed: we cannot determine if the action is a REWRITE -> first DESELECT previous hyp, than SELECT (or new_hyp) the current hyp
544 ).
545 compute_hyp_actions_for_rule(DesHyps,[PHyp|PT],[CHyp|CT],Acts) :-
546 PHyp=CHyp, % hyps are the same, no action
547 compute_hyp_actions_for_rule(DesHyps,PT,CT,Acts).
548
549 % Important: an action is only applicable if the EXACT hypothesis exists in the current step in Rodin! Otherwise, the action fails silently.
550 deselect_hyp(Hyp,hyp_action(deselect,HypID,HypID)) :- assert_hyp_predicate(Hyp,HypID). % TODO check Hyp is member of selected Hyps?
551 rewrite_hyp(Hyp1,Hyp2,hyp_action(rewrite,Hyp1ID,Hyp2ID)) :- % TODO check Hyp is member of de/selected Hyps?
552 assert_hyp_predicate(Hyp1,Hyp1ID),
553 assert_hyp_predicate(Hyp2,Hyp2ID).
554 select_hyp(DesHyps,Hyp,hyp_action(Act,HypID,HypID)) :-
555 (member(Hyp,DesHyps) -> Act=select ; Act=new_hyp), % check that hyp to be selected is in the set of deselected hyps, otherwise it must be added as a new hyp
556 assert_hyp_predicate(Hyp,HypID). % SELECT can fail if hyp is not available, but new_hyp is always ok (but then Rodin does not display the selection in the proof step details)
557
558 % adapt some hyp actions for rules that expect special actions:
559 adapt_hyp_actions_for_rule(_,[],Res) :- !, Res=[].
560 adapt_hyp_actions_for_rule(and_l(_),OldActs,NewActs) :- !, % expects a rewrite as first action for the selected conjunction
561 OldActs=[hyp_action(deselect,Des,Des),hyp_action(new_hyp,N1,N1),hyp_action(new_hyp,N2,N2)],
562 ajoin([N1,',',N2],Rewr),
563 NewActs=[hyp_action(rewrite,Des,Rewr),hyp_action(select,Rewr,Rewr)].
564 adapt_hyp_actions_for_rule(eq(_,_,_),OldActs,NewActs) :- !, % replace rewrites by forwards infs
565 maplist(replace_rewrite_forward_inf,OldActs,NewActs).
566 % TODO this does not cover the case if the rewritten hyps are at the end of the hyp list -> DESELECT + new_hyp (but this is also accepted by Rodin)
567 adapt_hyp_actions_for_rule(simplify_hyp(Rule,Hyp),OldActs,NewActs) :-
568 remove_membership_id(Rule), % expects a rewrite as first action
569 OldActs\=[hyp_action(rewrite,_,_)|_], !, % no replacement required if the first hyp action is already a rewrite
570 assert_hyp_predicate(Hyp,HypId),
571 member(hyp_action(deselect,HypId,HypId),OldActs), % HypId is previous hyp
572 findall(N,member(hyp_action(new_hyp,N,N),OldActs),InfHyps), % all new inferred hyps, may contain other new hyps (is ok)
573 ajoin_with_sep(InfHyps,',',SepInfHyps),
574 % replace new_hyp + deselect by rewrite + select
575 NewActs=[hyp_action(rewrite,HypId,SepInfHyps),hyp_action(select,SepInfHyps,SepInfHyps)].
576 adapt_hyp_actions_for_rule(RuleTerm,[HypAct|HT],[HypAct|NH]) :-
577 adapt_hyp_actions_for_rule(RuleTerm,HT,NH).
578
579 replace_rewrite_forward_inf(hyp_action(rewrite,H1,H2),Res) :- !, Res=hyp_action(forward_inf,H1,H2).
580 replace_rewrite_forward_inf(Act,Act).
581 % in Java: if hideOriginal: rewrite, else: forward_inf
582
583 write_antecedant(_,_,Node,_,_) :- proof_node(Node,success(_),_,_), !.
584 write_antecedant(Stream,FromNode,Node,HypActions,Indent) :-
585 proof_node(Node,sequent(Hyps,Goal),Info,_),
586 get_scope([Goal|Hyps],Info,[identifier(Ids)]),
587 (FromNode \= root
588 -> proof_node(FromNode,sequent(FromHyps,FromGoal),FromInfo,_),
589 get_scope([FromGoal|FromHyps],FromInfo,[identifier(FromIds)]),
590 list_difference(Ids,FromIds,NewIds) % find new IDs in scope, e.g. after all_r (free a variable of forall)
591 ; NewIds=[]),
592 forall(member(Hyp,Hyps),assert_hyp_predicate(Hyp,_)),
593 assert_hyp_predicate(Goal,GName),
594 findall(NewHyp,member(hyp_action(new_hyp,NewHyp,_),HypActions),NewHypIds),
595 ajoin_with_sep(NewHypIds,',',SepNewHypIds),
596 get_next_rule_comment(Node,CommentCodes),
597 format_indent(Stream,'<org.eventb.core.prAnte name="~w" org.eventb.core.comment="~s" org.eventb.core.prGoal="~w" org.eventb.core.prHyps="~w">~n',[Node,CommentCodes,GName,SepNewHypIds],Indent),
598 % each prAnte of the same prRule must have a different name, TODO: check if prAnte name can really be arbitrary
599 NIndent is Indent+1,
600 write_hyp_actions(Stream,HypActions,0,NIndent),
601 write_proof_rule(Stream,Node,NIndent),
602 forall(member(Id,NewIds),assert_identifier(Id)),
603 findall('$'(NewId),member(b(identifier(NewId),_,_),NewIds),NewIdsForPrint),
604 write_identifiers(Stream,local,NewIdsForPrint,NIndent), % add new free identifiers in the corresponding prAnte, expected e.g. for all_r
605 % TODO: check purpose of org.eventb.core.prFresh=""
606 format_indent(Stream,'</org.eventb.core.prAnte>~n',[],Indent).
607
608 get_next_rule_comment(FromNode,EDesc) :-
609 proof_edge(FromNode,_,_,_,Desc), !,
610 xml_attribute_escape_atom(Desc,EDesc).
611 get_next_rule_comment(_,[]).
612
613 write_hyp_actions(_,[],_,_).
614 write_hyp_actions(Stream,[hyp_action(new_hyp,_,_)|T],Nr,Indent) :- !, write_hyp_actions(Stream,T,Nr,Indent). % ignore new_hyps, these are added as prHyps
615 write_hyp_actions(Stream,[HypAct|T],Nr,Indent) :-
616 write_hyp_action(Stream,HypAct,Nr,Indent),
617 NNr is Nr+1, % number is important for the order of actions, e.g. REWRITE0, SELECT1, FORWARD_INF2, DESELECT3, ...
618 write_hyp_actions(Stream,T,NNr,Indent).
619
620 write_hyp_action(Stream,hyp_action(deselect,I1,_),Nr,Indent) :- !,
621 format_indent(Stream,'<org.eventb.core.prHypAction name="DESELECT~w" org.eventb.core.prHyps="~w"/>~n',[Nr,I1],Indent).
622 write_hyp_action(Stream,hyp_action(forward_inf,I1,I2),Nr,Indent) :- !, % TODO: clarify purpose
623 format_indent(Stream,'<org.eventb.core.prHypAction name="FORWARD_INF~w" org.eventb.core.prHyps="~w" org.eventb.core.prInfHyps="~w"/>~n',[Nr,I1,I2],Indent).
624 write_hyp_action(Stream,hyp_action(hide,I1,_),Nr,Indent) :- !, % TODO: difference to deselect?
625 format_indent(Stream,'<org.eventb.core.prHypAction name="HIDE~w" org.eventb.core.prHyps="~w"/>~n',[Nr,I1],Indent).
626 write_hyp_action(Stream,hyp_action(rewrite,I1,I2),Nr,Indent) :- !,
627 format_indent(Stream,'<org.eventb.core.prHypAction name="REWRITE~w" org.eventb.core.prHidden="~w" org.eventb.core.prHyps="" org.eventb.core.prInfHyps="~w"/>~n',[Nr,I1,I2],Indent). % !! fails without empty prHyps !!
628 write_hyp_action(Stream,hyp_action(select,I1,_),Nr,Indent) :- !,
629 format_indent(Stream,'<org.eventb.core.prHypAction name="SELECT~w" org.eventb.core.prHyps="~w"/>~n',[Nr,I1],Indent).
630 write_hyp_action(Stream,hyp_action(show,I1,_),Nr,Indent) :- !, % TODO: difference to select?
631 format_indent(Stream,'<org.eventb.core.prHypAction name="SHOW~w" org.eventb.core.prHyps="~w"/>~n',[Nr,I1],Indent).
632
633 get_rule_reasoner(Act,ReasID,RID,Conf) :-
634 rule_reasoner(Act,ReasID,Conf),
635 assert_rule_index(ReasID,RID).
636
637 rule_reasoner(Act,ReasID,Conf) :-
638 rodin_rule_reasoner(Act,SeqProvID), !,
639 ajoin(['org.eventb.core.seqprover.',SeqProvID],ReasID),
640 Conf=100. % is UNCERTAIN_MAX, will trigger replay
641 % TODO: same for ML/PP (but the call in Rodin differs from ours; all vs. selected hyps)
642 rule_reasoner(ml,ReasID,Conf) :- !, ReasID='com.clearsy.atelierb.provers.core.externalML:1', Conf=100.
643 rule_reasoner(prob_disprover,ReasID,Conf) :- !, ReasID='de.prob.eventb.disprover.core.disproverReasoner', Conf=100.
644 rule_reasoner(_,'org.eventb.core.seqprover.review',1000). % review reasoner as fallback, TODO: should be confidence 500
645
646 % TODO complete list
647 rodin_rule_reasoner(add_hyp(_),cut).
648 rodin_rule_reasoner(all_r,allI).
649 rodin_rule_reasoner(and_l(_),conjF).
650 rodin_rule_reasoner(and_r,'conj:0').
651 rodin_rule_reasoner(auto_mh,autoImpF).
652 rodin_rule_reasoner(card_empty_interv,cardUpTo).
653 rodin_rule_reasoner(card_interv,cardUpTo).
654 rodin_rule_reasoner(case(_),disjE).
655 rodin_rule_reasoner(cntr,contrHyps).
656 rodin_rule_reasoner(contradict_l(_),contrL1).
657 rodin_rule_reasoner(contradict_r,contrL1).
658 rodin_rule_reasoner(dbl_hyp,mngHyp).
659 rodin_rule_reasoner(def_expn_step(_),exponentiationStep).
660 rodin_rule_reasoner(deriv_equal_card,cardComparison).
661 rodin_rule_reasoner(deriv_ge_card,cardComparison).
662 rodin_rule_reasoner(deriv_gt_card,cardComparison).
663 rodin_rule_reasoner(deriv_le_card,cardComparison).
664 rodin_rule_reasoner(deriv_lt_card,cardComparison).
665 rodin_rule_reasoner(deriv_equal_interv_l,derivEqualInterv).
666 rodin_rule_reasoner(dis_binter_l,'funInterImg:1').
667 rodin_rule_reasoner(dis_binter_r,'funInterImg:1').
668 rodin_rule_reasoner(dis_setminus_l,'funSetMinusImg:1').
669 rodin_rule_reasoner(dis_setminus_r,'funSetMinusImg:1').
670 rodin_rule_reasoner(distinct_case,doCase).
671 rodin_rule_reasoner(eq(lr,_,_),'eqL2:1').
672 rodin_rule_reasoner(eq(rl,_,_),'heL2:1').
673 rodin_rule_reasoner(eqv(lr,_,_),eqvLR).
674 rodin_rule_reasoner(eqv(rl,_,_),eqvRL).
675 rodin_rule_reasoner(exists_inst(_),exI).
676 rodin_rule_reasoner(false_hyp,falseHyp).
677 rodin_rule_reasoner(fin_binter_r,finiteInter).
678 rodin_rule_reasoner(fin_bunion_r,finiteUnion).
679 rodin_rule_reasoner(fin_compset_r,finiteCompset).
680 rodin_rule_reasoner(fin_fun_dom_r(_),'finiteFunDom:0').
681 rodin_rule_reasoner(fin_fun_img_r(_),'finiteFunRelImg:0').
682 rodin_rule_reasoner(fin_fun_ran_r(_),'finiteFunRan:0').
683 rodin_rule_reasoner(fin_fun1_r(_),'finiteFunction:0').
684 rodin_rule_reasoner(fin_fun2_r(_),'finiteFunConv:0').
685 rodin_rule_reasoner(fin_ge_0,finitePositive).
686 rodin_rule_reasoner(fin_kinter_r,finiteInter).
687 rodin_rule_reasoner(fin_kunion_r,finiteUnion).
688 rodin_rule_reasoner(fin_l_lower_bound,finiteHypBoundedGoal). % two rules in Rodin: L/R
689 rodin_rule_reasoner(fin_l_upper_bound,finiteHypBoundedGoal). % two rules in Rodin: L/R
690 rodin_rule_reasoner(fin_lt_0,finiteNegative).
691 rodin_rule_reasoner(fin_qinter_r,finiteInter).
692 rodin_rule_reasoner(fin_qunion_r,finiteUnion).
693 rodin_rule_reasoner(fin_rel_img_r,finiteRelImg).
694 rodin_rule_reasoner(fin_rel_r,'finiteRelation:0').
695 rodin_rule_reasoner(fin_rel_dom_r,finiteDom).
696 rodin_rule_reasoner(fin_rel_ran_r,finiteRan).
697 rodin_rule_reasoner(fin_setminus_r,finiteSetMinus).
698 rodin_rule_reasoner(fin_subseteq_r(_),'finiteSet:0').
699 rodin_rule_reasoner(forall_inst(_,_),allD).
700 rodin_rule_reasoner(forall_inst_mp(_,_),'allmpD:0').
701 rodin_rule_reasoner(forall_inst_mt(_,_),'allmtD:0').
702 rodin_rule_reasoner(fun_goal,isFunGoal).
703 rodin_rule_reasoner(fun_image_goal,funImgGoal).
704 rodin_rule_reasoner(hm(_),'mt:2').
705 rodin_rule_reasoner(hyp,hyp).
706 rodin_rule_reasoner(hyp_or,hypOr).
707 rodin_rule_reasoner(imp_and_l(_),impAndRewrites).
708 rodin_rule_reasoner(imp_case(_),impCase).
709 rodin_rule_reasoner(imp_or_l(_),impOrRewrites).
710 rodin_rule_reasoner(imp_r,impI).
711 rodin_rule_reasoner(lower_bound_l,finiteMin).
712 rodin_rule_reasoner(lower_bound_r,finiteMin).
713 rodin_rule_reasoner(mh(_),'impE:2').
714 rodin_rule_reasoner(mon_deselect(_),mngHyp).
715 rodin_rule_reasoner(neg_in,'negEnum:0'). % two rules in Rodin: L/R
716 rodin_rule_reasoner(one_point_l,'onePointRule:2').
717 rodin_rule_reasoner(one_point_r,'onePointRule:2').
718 rodin_rule_reasoner(ov_l,'funOvr:1').
719 rodin_rule_reasoner(ov_r,'funOvr:1').
720 rodin_rule_reasoner(ov_setenum_l,'funOvr:1').
721 rodin_rule_reasoner(ov_setenum_r,'funOvr:1').
722 rodin_rule_reasoner(reselect_hyp(_),mngHyp).
723 rodin_rule_reasoner(sim_dprod_l,funDprodImg).
724 rodin_rule_reasoner(sim_dprod_r,funDprodImg).
725 rodin_rule_reasoner(sim_fcomp_l,funCompImg).
726 rodin_rule_reasoner(sim_fcomp_r,funCompImg).
727 rodin_rule_reasoner(sim_rel_image_l,funSingletonImg).
728 rodin_rule_reasoner(sim_rel_image_r,funSingletonImg).
729 rodin_rule_reasoner(sim_ov_pfun,mapOvrG).
730 rodin_rule_reasoner(sim_ov_rel,mapOvrG).
731 rodin_rule_reasoner(sim_ov_tfun,mapOvrG).
732 rodin_rule_reasoner(sim_ov_trel,mapOvrG).
733 rodin_rule_reasoner(simplify_goal(R),RID) :- rewrite_rule_id(R,RID).
734 rodin_rule_reasoner(simplify_hyp(R,_),RID) :- rewrite_rule_id(R,RID).
735 rodin_rule_reasoner(true_goal,trueGoal).
736 rodin_rule_reasoner(upper_bound_l,finiteMax).
737 rodin_rule_reasoner(upper_bound_r,finiteMax).
738 rodin_rule_reasoner(xst_l,exF).
739
740 rewrite_rule_id('DEF_BCOMP',bcompDefRewrites).
741 rewrite_rule_id('DEF_EQUAL_CARD', cardDefRewrites).
742 rewrite_rule_id('DEF_EQUAL_FUN_IMAGE', equalFunImgDefRewrites).
743 rewrite_rule_id('DEF_EQUAL_MIN', minMaxDefRewrites).
744 rewrite_rule_id('DEF_EQUAL_MAX', minMaxDefRewrites).
745 rewrite_rule_id('DEF_EQV', eqvRewrites).
746 rewrite_rule_id('DEF_FINITE', finiteDefRewrites).
747 rewrite_rule_id('DEF_OR', disjToImplRewrites).
748 rewrite_rule_id('DEF_OVERL', relOvrRewrites).
749 rewrite_rule_id('DEF_PARTITION', partitionRewrites).
750 rewrite_rule_id('DEF_SPECIAL_NOT_EQUAL', rn).
751 rewrite_rule_id('DEF_SUBSET', sir).
752 rewrite_rule_id('DEF_SUBSETEQ', ri). % removeInclusionRewriter
753 rewrite_rule_id('DERIV_DOM_TOTALREL'(_), 'totalDom:2').
754 rewrite_rule_id('DERIV_EQUAL', setEqlRewrites).
755 rewrite_rule_id('DERIV_FCOMP_DOMRES', domCompRewrites).
756 rewrite_rule_id('DERIV_FCOMP_DOMSUB', domCompRewrites).
757 rewrite_rule_id('DERIV_FCOMP_RANRES', ranCompRewrites).
758 rewrite_rule_id('DERIV_FCOMP_RANSUB', ranCompRewrites).
759 rewrite_rule_id('DERIV_IMP', doubleImplGoalRewrites).
760 rewrite_rule_id('DERIV_IMP_IMP', doubleImplHypRewrites).
761 rewrite_rule_id('DERIV_NOT_EXISTS', rn).
762 rewrite_rule_id('DERIV_NOT_FORALL', rn).
763 rewrite_rule_id('DERIV_NOT_IMP', rn).
764 rewrite_rule_id('DERIV_RELIMAGE_FCOMP', compImgRewrites).
765 rewrite_rule_id('DERIV_SUBSETEQ', riUniversal).
766 rewrite_rule_id('DERIV_SUBSETEQ_SETMINUS_L', inclusionSetMinusLeftRewrites).
767 rewrite_rule_id('DERIV_SUBSETEQ_SETMINUS_R', inclusionSetMinusRightRewrites).
768 rewrite_rule_id('DERIV_TYPE_SETMINUS_BINTER', setMinusRewrites).
769 rewrite_rule_id('DERIV_TYPE_SETMINUS_BUNION', setMinusRewrites).
770 rewrite_rule_id('DERIV_TYPE_SETMINUS_SETMINUS', setMinusRewrites).
771 rewrite_rule_id('DISTRI_AND_OR', andOrDistRewrites).
772 rewrite_rule_id('DISTRI_BINTER_BUNION', unionInterDistRewrites).
773 rewrite_rule_id('DISTRI_BUNION_BINTER', unionInterDistRewrites).
774 rewrite_rule_id('DISTRI_CONVERSE_BUNION', convRewrites).
775 rewrite_rule_id('DISTRI_DOMRES_BINTER', 'domDistLeftRewrites:0'). % TODO: split our rule in L/R, Rodin uses separate reasoner for right: domDistRightRewrites
776 rewrite_rule_id('DISTRI_DOMRES_BUNION', 'domDistLeftRewrites:0'). % TODO: ditto, two rules in Rodin: L/R
777 rewrite_rule_id('DISTRI_DOMSUB_BINTER_L', 'domDistLeftRewrites:0').
778 rewrite_rule_id('DISTRI_DOMSUB_BINTER_R', domDistRightRewrites).
779 rewrite_rule_id('DISTRI_DOMSUB_BUNION_L', 'domDistLeftRewrites:0').
780 rewrite_rule_id('DISTRI_DOMSUB_BUNION_R', domDistRightRewrites).
781 rewrite_rule_id('DISTRI_DOM_BUNION', domRanUnionDistRewrites).
782 rewrite_rule_id('DISTRI_FCOMP_BUNION', compUnionDistRewrites). % two rules in Rodin: L/R
783 rewrite_rule_id('DISTRI_NOT_AND', rn).
784 rewrite_rule_id('DISTRI_NOT_OR', rn).
785 rewrite_rule_id('DISTRI_IMP_AND', impAndRewrites).
786 rewrite_rule_id('DISTRI_IMP_OR', impOrRewrites).
787 rewrite_rule_id('DISTRI_OR_AND', andOrDistRewrites).
788 rewrite_rule_id('DISTRI_RAN_BUNION', domRanUnionDistRewrites).
789 rewrite_rule_id('DISTRI_RANSUB_BINTER_L', ranDistLeftRewrites).
790 rewrite_rule_id('DISTRI_RANSUB_BINTER_R', 'ranDistRightRewrites:0').
791 rewrite_rule_id('DISTRI_RANSUB_BUNION_L', ranDistLeftRewrites).
792 rewrite_rule_id('DISTRI_RANSUB_BUNION_R', 'ranDistRightRewrites:0').
793 rewrite_rule_id('DISTRI_RANRES_BINTER', ranDistLeftRewrites). % TODO: split our rule in L/R, Rodin uses separate reasoner for right: ranDistRightRewrites
794 rewrite_rule_id('DISTRI_RANRES_BUNION', ranDistLeftRewrites). % TODO: ditto
795 rewrite_rule_id('DISTRI_RELIMAGE_BUNION_L', relImgUnionLeftRewrites).
796 rewrite_rule_id('DISTRI_RELIMAGE_BUNION_R', relImgUnionRightRewrites).
797 rewrite_rule_id('SIMP_EQUAL_CARD', equalCardRewrites).
798 rewrite_rule_id('SIMP_FUNIMAGE_DOMRES', 'funImgSimplifies:0').
799 rewrite_rule_id('SIMP_FUNIMAGE_DOMSUB', 'funImgSimplifies:0').
800 rewrite_rule_id('SIMP_FUNIMAGE_PPROD', funPprodImg).
801 rewrite_rule_id('SIMP_FUNIMAGE_RANRES', 'funImgSimplifies:0').
802 rewrite_rule_id('SIMP_FUNIMAGE_RANSUB', 'funImgSimplifies:0').
803 rewrite_rule_id('SIMP_FUNIMAGE_SETMINUS', 'funImgSimplifies:0').
804 rewrite_rule_id('SIMP_LIT_CARD_UPTO', cardUpTo).
805 rewrite_rule_id('SIMP_MINUS_UNMINUS', 'arithRewrites:1').
806 rewrite_rule_id('SIMP_MULTI_ARITHREL_PLUS_PLUS', 'arithRewrites:1').
807 rewrite_rule_id('SIMP_MULTI_ARITHREL_PLUS_L', 'arithRewrites:1').
808 rewrite_rule_id('SIMP_MULTI_ARITHREL_PLUS_R', 'arithRewrites:1').
809 rewrite_rule_id('SIMP_MULTI_ARITHREL_MINUS_MINUS_L', 'arithRewrites:1').
810 rewrite_rule_id('SIMP_MULTI_ARITHREL_MINUS_MINUS_R', 'arithRewrites:1').
811 rewrite_rule_id('SIMP_MULTI_MINUS_PLUS_L', 'arithRewrites:1').
812 rewrite_rule_id('SIMP_MULTI_MINUS_PLUS_PLUS', 'arithRewrites:1').
813 rewrite_rule_id('SIMP_MULTI_MINUS_PLUS_R', 'arithRewrites:1').
814 rewrite_rule_id('SIMP_MULTI_PLUS_MINUS', 'arithRewrites:1').
815 rewrite_rule_id('SIMP_NOT_NOT', rn).
816 rewrite_rule_id('SIMP_TYPE_EQUAL_EMPTY', 'typeRewrites:1').
817 rewrite_rule_id('SIMP_TYPE_IN', 'typeRewrites:1').
818 rewrite_rule_id('SIMP_TYPE_SUBSETEQ', 'typeRewrites:1').
819 rewrite_rule_id('SIMP_TYPE_SUBSET_L', 'typeRewrites:1').
820 % TODO: PredicateSimplifier.java
821
822 :- use_module(probsrc(bsyntaxtree),[flatten_conjunctions/2]).
823 get_prob_normalisation_rewrites([],[],[]).
824 get_prob_normalisation_rewrites([InitPred|IT],[NormPred|NT],Rewrites) :-
825 % important: must use correctly nested conjuncts with parentheses (otherwise Rodin recognises them as a different predicate)
826 transform_raw(InitPred,TInitPred),
827 with_forced_rodin_mode(translate_bexpression_to_unicode(TInitPred,PInitPred)),
828 translate_norm_expr_term_no_limit(NormPred,PNormPred),
829 (PInitPred = PNormPred
830 -> assert_hyp_predicate(NormPred,_), Rewrites=RT % predicate is the same after normalisation -> no rewrite
831 ; assert_hyp_predicate_init_rewrite(IName,PInitPred),
832 assert_hyp_predicate(NormPred,NName),
833 Rewrites=[hyp_action(rewrite,IName,NName)|RT]), % register rewrite
834 get_prob_normalisation_rewrites(IT,NT,RT).
835
836 assert_hyp_predicate(Hyp,Name) :- with_forced_rodin_mode(translate_norm_expr_term_no_limit(Hyp,Pred)), prPred(_,Name,Pred), !. % predicate already exists
837 assert_hyp_predicate(Hyp,Name) :-
838 retract(predicate_id_count(C)),
839 ajoin([p,C],Name),
840 NextC is C+1,
841 with_forced_rodin_mode(translate_norm_expr_term_no_limit(Hyp,Pred)),
842 assertz(prPred(Hyp,Name,Pred)),
843 assertz(predicate_id_count(NextC)).
844
845 assert_expression(Expr,Name) :- with_forced_rodin_mode(translate_norm_expr_term_no_limit(Expr,PExpr)), prExpr(_,Name,PExpr), !. % expression already exists
846 assert_expression(Expr,Name) :-
847 retract(expression_id_count(C)),
848 ajoin([e,C],Name),
849 NextC is C+1,
850 with_forced_rodin_mode(translate_norm_expr_term_no_limit(Expr,PExpr)),
851 assertz(prExpr(Expr,Name,PExpr)),
852 assertz(expression_id_count(NextC)).
853
854 with_forced_rodin_mode(Call) :-
855 translate:set_force_eventb_mode, % for printing special unicodes for <+, <<->>, <<->, <->>, which we do not want to appear in the state visualisation
856 call_cleanup(Call, translate:unset_force_eventb_mode).
857
858 assert_hyp_predicate_init_rewrite(Name,PHyp) :- prPred(_,Name,PHyp), !. % predicate already exists
859 assert_hyp_predicate_init_rewrite(Name,PHyp) :-
860 retract(predicate_id_count(C)),
861 ajoin([p,C],Name),
862 NextC is C+1,
863 assertz(prPred(Name,Name,PHyp)),
864 assertz(predicate_id_count(NextC)).
865
866 assert_rule_index(ReasonerID,RuleIndex) :- prReas(RuleIndex,ReasonerID), !.
867 assert_rule_index(ReasonerID,RuleIndex) :-
868 retract(rule_id_count(C)),
869 ajoin([r,C],RuleIndex),
870 NextC is C+1,
871 assertz(prReas(RuleIndex,ReasonerID)),
872 assertz(rule_id_count(NextC)).
873
874 assert_identifier(b(identifier(Id),Type,_)) :-
875 prIdent(Id,Type), !,
876 findall(Type1,(prIdent(Id,Type1),Type1\=any),Types),
877 (Types=[Type] -> true
878 ; add_error(generate_proof_bpr_rodin_export,type_mismatch_for_prIdent(Id,Types,Type)), fail).
879 assert_identifier(b(identifier(Id),Type,_)) :-
880 assertz(prIdent(Id,Type)).
881
882 % Global=global: retract globalIDs after print to avoid printing them for all predicates/expressions
883 write_identifiers(Stream,Global,Ids,Indent) :-
884 member('$'(Id),Ids),
885 (Global=global -> retract(prIdent(Id,Type)) ; prIdent(Id,Type)),
886 Type\=any, % TODO: get rid of any types here (that's because the type check failed, e.g. for x : {})
887 with_translation_mode(unicode,translate:pretty_normalized_type(Type,PType)),
888 xml_attribute_escape_atom(PType,EType),
889 format_indent(Stream,'<org.eventb.core.prIdent name="~w" org.eventb.core.type="~s"/>~n',[Id,EType],Indent),
890 fail.
891 write_identifiers(_,_,_,_).
892
893 write_predicate_mapping(Stream,Indent) :-
894 prPred(Hyp,Name,Pred),
895 used_identifiers(Hyp,Ids), sort(Ids,SIds),
896 xml_attribute_escape_atom(Pred,EPred),
897 format_indent(Stream,'<org.eventb.core.prPred name="~w" org.eventb.core.predicate="~s">~n',[Name,EPred],Indent),
898 NIndent is Indent+1,
899 write_identifiers(Stream,local,SIds,NIndent),
900 format_indent(Stream,'</org.eventb.core.prPred>~n',[],Indent),
901 fail.
902 write_predicate_mapping(_,_).
903
904 write_expression_mapping(Stream,Indent) :-
905 prExpr(Expr,Name,PrettyExpr),
906 used_identifiers(Expr,Ids), sort(Ids,SIds),
907 xml_attribute_escape_atom(PrettyExpr,EExpr),
908 format_indent(Stream,'<org.eventb.core.prExpr name="~w" org.eventb.core.expression="~s">~n',[Name,EExpr],Indent),
909 NIndent is Indent+1,
910 write_identifiers(Stream,local,SIds,NIndent),
911 format_indent(Stream,'</org.eventb.core.prExpr>~n',[],Indent),
912 fail.
913 write_expression_mapping(_,_).
914
915 write_reasoner_mapping(Stream,Indent) :-
916 prReas(Name,RID),
917 format_indent(Stream,'<org.eventb.core.prReas name="~w" org.eventb.core.prRID="~w"/>~n',[Name,RID],Indent),
918 fail.
919 write_reasoner_mapping(_,_).
920
921 :- use_module(probsrc(tools),[xml_attribute_escape/2]).
922 xml_attribute_escape_atom(A,EC) :- \+ atom(A),!,
923 add_internal_error('Not an atom: ',xml_attribute_escape_atom(A,EC)), EC='??'.
924 xml_attribute_escape_atom(A,EC) :- atom_codes(A,C), xml_attribute_escape(C,EC).
925
926 indent_ws(_Stream,X) :- X<1,!.
927 indent_ws(Stream,X) :- format(Stream,' ',[]), X1 is X-1, indent_ws(Stream,X1).
928
929 format_indent(S,A,L,I) :- indent_ws(S,I), format(S,A,L).
930 %%%%%%%%% END PROOF TREE RODIN BPR EXPORT %%%%%%%%%
931
932 %%%%%%%%% BEGIN PRETTY PRINT %%%%%%%%%
933 :- use_module(probsrc(xtl_interface),[get_disprover_po/6]).
934 pretty_print_pos(PP) :-
935 findall(po(Lbl,G,AH,SH,Status), get_disprover_po(Lbl,_Ctx,G,AH,SH,Status), POs),
936 pp_po(POs,PP,[]).
937
938 pp_po([]) --> [].
939 pp_po([po(POLabel,RawGoal,RawAllHyps,RawSelHyps,RodinStatus)|PT]) -->
940 {atom_codes(POLabel,CLabel), atom_codes(RodinStatus,CStatus)}, CLabel, " (", CStatus, ")\n",
941 "\x2550\\x2550\\x2550\\x2550\\x2550\\x2550\\x2550\\x2550\\n",
942 pp_hyps(RawAllHyps,RawSelHyps),
943 " \x2500\\x2500\\x2500\\x2500\\x2500\\x2500\\x2500\\x2500\\x2500\\x2500\\x2500\\x2500\\x2500\\x2500\\x2500\\x2500\\n",
944 " ", translate:pp_raw_formula(RawGoal), "\n\n\n",
945 pp_po(PT).
946
947 pp_hyps([],_) --> [].
948 pp_hyps([RawHyp|AT],SelHyps) -->
949 ({member(RawHyp,SelHyps)} -> " \x2714\ " ; " "),
950 translate:pp_raw_formula(RawHyp), "\n",
951 pp_hyps(AT,SelHyps).
952 %%%%%%%%% END PRETTY PRINT %%%%%%%%%