1 % (c) 2009-2025 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 % bmachine provides access to the currently loaded B-machine and all its subsidiary machines
6
7 :- module(bmachine,[bmachine_is_precompiled/0,
8 b_enumerated_sets_precompiled/0,
9 b_set_initial_machine/0,
10 b_set_empty_machine/0,
11 b_set_machine/3,
12 b_set_typed_machine/2,
13 b_load_eventb_project/1, % used for loading .eventb files
14 b_set_eventb_project_flat/3, % set an Event-B project from terms
15
16 % used for loading additional VisB/... defs
17 b_load_additional_definitions_file/1,
18 b_load_additional_definitions_from_list_of_facts/1,
19 b_load_additional_definitions_from_term/1,
20
21 get_full_b_machine/2,
22 full_b_machine/1,
23 get_full_b_machine_sha_hash/1, % get SHA hash of loaded and type-checked B machine
24 b_machine_is_loaded/0,
25
26 get_proven_invariant/2,
27 get_unproven_invariants/1,
28 get_invariant_list_with_proof_info/1,
29 load_additional_information/1,
30 %% generate_specialized_invariants/0, %% no longer exists
31 get_operation_info/2,
32 b_get_operation_description/2,
33 get_operation_description_template_expr/2,
34
35 b_load_machine_from_file/1, b_load_machine_from_file/2,
36 b_load_machine_probfile/1, b_load_machine_probfile/2,
37 b_load_machine_from_list_of_facts/2,
38 b_load_machine_from_term/2, % used for Alloy
39 b_machine_precompile/0, other_spec_precompile/0,
40 b_machine_reset/0,
41
42 b_machine_name/1,
43
44 b_get_all_used_filenames/1, b_get_main_filename/1,
45 add_additional_filename/2,
46 set_additional_filename_as_parsing_default/3, reset_filename_parsing_default/2,
47 b_get_main_filenumber/1, b_filenumber/4, portray_filenumbers/0,
48 get_machine_file_number/4,
49 b_absolute_file_name_relative_to_main_machine/2,
50 b_get_animated_sections/1,
51
52 b_get_machine_set/1, b_get_machine_set/2,
53 b_get_named_machine_set/2, b_get_named_machine_set/3,
54 b_get_disjoint_constants_of_type/3, b_get_constant_represented_inside_global_set/2,
55 b_get_machine_constants/1, b_get_machine_all_constants/1,
56 b_machine_has_constants/0, b_machine_has_constants_or_properties/0,
57 b_is_constant/2, b_is_constant/1, b_is_unused_constant/1,
58 get_constant_span/2,
59 b_machine_has_variables/0,
60 b_is_variable/1, b_is_variable/2,
61 b_get_constant_variable_description/2,
62 constant_variable_marked_as_memo/1, constant_variable_marked_as_expand/1,
63 b_get_machine_variables_in_original_order/1, b_get_machine_variables/1,
64 get_primed_machine_variables/1,
65 get_nr_of_machine_variables/1, get_nr_of_machine_constants/1,
66 b_get_all_used_identifiers/1, % Note: may contain var$0 instead of var for becomes_such
67 b_get_all_used_identifiers_in_section/2, % ditto
68 get_machine_identifiers/2, get_machine_identifiers_with_pp_type/2,
69 source_code_for_identifier/6,
70
71 b_get_properties_from_machine/1,
72 b_get_invariant_from_machine/1,
73 b_get_linking_invariant_from_machine/1,
74 b_machine_has_assertions/0,
75 b_get_static_assertions_from_machine/1, b_machine_has_static_assertions/0,
76 b_get_unproven_static_assertions_from_machine/1,
77 b_get_dynamic_assertions_from_machine/1, b_machine_has_dynamic_assertions/0,
78 b_get_unproven_dynamic_assertions_from_machine/1,
79 b_get_assertions_from_main_machine/2, b_main_machine_has_no_assertions/0,
80 b_machine_has_unproven_assertions/0, get_assertions_from_machine/2,
81 get_all_assertions_from_machine/1,
82 b_machine_has_proven_invariants/0,
83 b_get_assertions/3,
84 b_get_assertion_count/3,
85 is_discharged_assertion/1,
86
87 b_get_initialisation_from_machine/2,
88 b_safe_get_initialisation_from_machine/2, % raise error if no INIT clause
89 b_machine_has_operations/0,
90 b_get_machine_operation/4, b_get_machine_operation/6,
91 b_get_machine_operation_for_animation/4, % does some rewriting for ANY parameters
92 b_get_machine_operation_for_animation/6, % does some rewriting for ANY parameters for TopLevel=true
93 b_get_machine_operation_for_animation/7, % additional Pos parameter
94 b_get_promoted_machine_operations/1,
95 b_top_level_operation/1, b_top_level_feasible_operation/1,
96 b_is_initialisation_name/1,
97 b_is_operation_name/1, b_get_operation_pos/2,
98 b_get_machine_operation_parameter_types/2,
99 b_get_machine_operation_parameter_names/2,
100 b_get_machine_operation_parameter_names_for_animation/2,
101 b_get_machine_operation_result_names/2,
102 b_get_machine_operation_typed_parameters/2,
103 b_get_machine_operation_typed_parameters_for_animation/2,
104 b_get_machine_operation_typed_results/2,
105 b_get_machine_operation_signature/2,
106 b_machine_operation_names_in_reverse_order/1,
107 b_get_operation_variant/3,
108
109 b_get_machine_setscope/2,
110 b_get_machine_operation_max/2,
111 b_get_machine_goal/1,
112 b_set_machine_goal/1, b_set_machine_goal/2,
113 b_set_machine_searchscope/1, b_set_machine_searchscope/2,
114 b_set_parsed_typed_machine_goal/1, b_unset_machine_goal/0,
115 b_reset_machine_goal_from_DEFINITIONS/0,
116 b_parse_machine_expression_from_codes/2,
117 b_parse_machine_expression_from_codes_with_prob_ids/2,
118 b_parse_machine_expression_from_codes_with_prob_ids/3,
119 b_parse_machine_expression_from_codes_with_prob_ids/4,
120 b_parse_machine_expression_from_codes/5,
121 b_parse_machine_expression_from_codes/6,
122 b_parse_machine_subsitutions_from_codes/6,
123 b_parse_machine_formula/3, b_parse_machine_formula_from_codes/7,
124 b_parse_machine_predicate/2, b_parse_machine_predicate/3,
125 b_parse_optional_machine_predicate/2,
126 b_parse_machine_predicate_from_codes/3,
127 b_parse_machine_predicate_from_codes_open/5,
128 b_parse_machine_operation_pre_post_predicate/3, b_parse_machine_operation_pre_post_predicate/5,
129 get_machine_operation_additional_identifiers/2,
130
131 determine_type_of_formula/2, determine_type_of_formula/3,
132
133 parse_expression_raw_or_atom_with_prob_ids/2,
134
135 % a version where parsing and type checking are separate:
136 b_parse_wo_type_machine_predicate_from_codes_to_raw_expr/2,
137 b_type_check_raw_expr/4,
138
139 b_get_machine_searchscope/1,
140 b_get_machine_animation_function/2,
141 b_get_machine_heuristic_function/1,
142 b_get_machine_animation_expression/2,
143 b_get_machine_custom_edges_function/2,
144 b_get_machine_custom_nodes_function/2,
145 b_get_machine_custom_graph_function/2,
146 b_machine_temp_predicate/1,
147 %set_temp_predicate/2,
148 assert_temp_typed_predicate/1,
149 reset_temp_predicate/0,
150 add_additional_property/2, b_machine_additional_property/1,
151
152 get_animation_image/2, get_animation_image_source_file/2,
153 b_get_definition/5, b_get_definition_with_pos/6,
154 b_get_definition_string_from_machine/2, b_get_definition_string_from_machine/3,
155 b_definition_prefixed/5, b_sorted_b_definition_prefixed/4,
156 % get typed definitions without parameters:
157 b_get_typed_definition/3, b_get_typed_definition_with_error_list/5,
158 b_get_typed_predicate_definition/3,
159 b_get_typed_expression_definition/3, b_get_true_expression_definition/1,
160
161 b_nth1_invariant/3, % get nth invariant with used Ids
162 b_invariant_number_list/1,
163 b_specialized_invariant_for_op/2,
164 b_specialized_invariant_mask_for_op/2,
165 b_operation_preserves_full_invariant/1, b_operation_preserves_invariant/2,
166 tcltk_get_specialized_invariant_for_op/2, tcltk_get_specialized_invariants_for_ops/1,
167 b_get_operation_normalized_read_write_info/3, % used to be b_normalized_rwsets_for_op/3,
168 b_get_operation_unchanged_variables/2,
169 b_operation_cannot_modify_state/1,
170 b_operation_reads_output_variables/3,
171 b_get_operation_non_det_modifies/2,
172
173 b_extract_values_clause_assignment/3,
174
175 b_type_expression/5,b_type_expression_for_full_b_machine/6,
176 b_type_open_predicate/5,b_type_open_predicate_with_errors/4,
177 b_type_open_exists_predicate/3,
178 type_with_errors/4,
179
180 b_show_machine_representation_unicode/4, b_show_machine_representation/4,
181 b_get_internal_prolog_representation_as_codes/1,
182 b_write_machine_representation_to_file/2,
183 b_write_machine_representation_to_file/3,
184 b_write_eventb_machine_to_classicalb_to_file/1,
185 b_get_eventb_machine_as_classicalb_codes/3,
186 b_show_eventb_as_classicalb/2,
187
188 b_get_machine_refinement_hierarchy/1,
189 b_get_refined_machine/1, b_get_refined_machine_name/1, b_get_refined_ancestors_names/1,
190 b_get_machine_header_position/2,
191 b_get_model_type/1,
192 b_machine_statistics/2,
193
194 % More Proof Information:
195 discharged_guard_strengthening/4,
196
197 % Flow information
198 wp_untyped/3, clear_wp/0,
199 nonchanging_guard/2,
200 typecheck_predicates/4
201 ]).
202
203 :- use_module(library(lists)).
204 :- use_module(library(ordsets)).
205
206 :- use_module(self_check).
207 :- use_module(error_manager).
208 :- use_module(debug).
209 :- use_module(bmachine_construction,[check_machine/4,type_in_machine_l/6,type_open_predicate_with_quantifier/6]).
210 :- use_module(bsyntaxtree).
211 :- use_module(bmachine_structure,[get_section/3,write_section/4,get_section_texprs/3]).
212 :- use_module(parsercall).
213 :- use_module(tools).
214 :- use_module(translate,[translate_machine/3,translate_eventb_to_classicalb/3]).
215 :- use_module(bmachine_eventb,[check_event_b_project/4,is_eventb_additional_info/1]).
216 :- use_module(kernel_freetypes,[register_freetypes/1]).
217 :- use_module(b_machine_hierarchy).
218 :- use_module(kodkodsrc(kodkod), [replace_by_kodkod/3]).
219
220 :- use_module(b_global_sets,[find_inequal_global_set_identifiers/4,
221 b_get_prob_deferred_set_elements/2,
222 b_check_and_precompile_enumerated_sets/0,
223 b_check_and_precompile_deferred_sets/0,
224 b_check_and_precompile_global_set_symmetry/0]).
225
226 % for applying transformations on the machines
227 :- use_module(record_detection,[replace_sets_by_records/2]).
228 :- use_module(partition_detection,[detect_partitions/2]).
229
230 :- use_module(module_information,[module_info/2]).
231 :- module_info(group,ast).
232 :- module_info(description,'This module provides access to the various parts of the loaded B machine.').
233
234 :- set_prolog_flag(double_quotes, codes).
235
236 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
237 % bmachine: module for storing the currently loaded machine
238 % Contains predicates for getting (already typed) information about
239 % different parts of the machine
240 % many predicates are precompiled by b_precompile_machine/0, see below for
241 % details.
242
243 :- volatile bmachine_is_precompiled/0.
244 :- dynamic bmachine_is_precompiled/0. /* TRUE if the precompiled predicates have been set */
245
246 assert_bmachine_is_precompiled :-
247 (bmachine_is_precompiled -> true ; assertz(bmachine_is_precompiled), debug_println(4,bmachine_is_precompiled)).
248
249 :- volatile machine/2.
250 :- dynamic machine/2.
251 % there is only one main machine fact
252
253 % true if a machine is loaded
254 b_machine_is_loaded :- (machine(_,_) -> true).
255
256 get_full_b_machine(Name,Res) :-
257 (machine(Name,M) -> Res=M
258 ; ground(Name) -> add_error(bmachine,'No B machine with this name loaded:',Name), fail
259 ; add_error(bmachine,'No B machine loaded'), fail
260 ).
261
262 full_b_machine(machine(Name,M)) :- get_full_b_machine(Name,M).
263
264 :- use_module(extension('probhash/probhash'),[raw_sha_hash/2]).
265 get_full_b_machine_sha_hash(Hash) :- full_b_machine(FM), raw_sha_hash(FM,Hash).
266
267 b_set_machine(Main,Machines,Errors) :-
268 b_machine_reset,
269 ? check_machine(Main,Machines,M1,Errors1),!,
270 apply_machine_transformations(M1,ResultMachine),
271 ( no_real_perror_occurred(Errors1) ->
272 %% get_memory_used(M1), %%
273 assert_main_machine(ResultMachine)
274 %%, get_memory_used(M2),print_memory_used(M2), print_memory_used_difference(M1,M2),nl %%
275 ;
276 true),
277 Errors=Errors1.
278
279 assert_main_machine(X) :- %tools_printing:trace_print(X),nl,
280 nonvar(X), X=machine(A,B),
281 !,
282 assertz(machine(A,B)). %, print(machine_asserted),nl.
283 assert_main_machine(X) :- add_internal_error('Illegal format: ',assert_main_machine(X)),fail.
284
285 :- meta_predicate apply_transformation_step(*,2,*,*).
286 % apply some transformations on the machine that require global information
287 % (other local transformations can be found in ast_cleanup)
288 apply_machine_transformations -->
289 apply_transformation_step('record definition detection', replace_sets_by_records),
290 apply_transformation_step('partition detection', detect_partitions). % is this necessary?? done in ast_cleanup
291
292 apply_transformation_step(Name,Pred,In,Out) :-
293 ( call(Pred, In, Out) -> true
294 ;
295 ajoin(['applying ', Name, ' failed, skipping.'], Msg),
296 add_error(bmachine,Msg),
297 In=Out).
298
299 % try to translate (parts of) the properties to Kodkod
300 % if it succeeds, replace the translated predicates by
301 % calls to the Kodkod process
302 try_kodkod :-
303 get_preference(use_solver_on_load,kodkod),
304 b_get_machine_constants(Constants),
305 Constants = [_|_],!,
306 b_get_properties_from_machine(OldPredicate),
307 ( replace_by_kodkod(Constants,OldPredicate,NewPredicate) ->
308 retract(machine(N,OldMachine)),
309 retractall( b_get_properties_from_machine(_) ),
310 write_section(properties,NewPredicate,machine(N,OldMachine),NewMachine),
311 assertz( NewMachine ),
312 assertz( b_get_properties_from_machine(NewPredicate) )
313 ;
314 true).
315 try_kodkod.
316
317 :- use_module(bmachine_static_checks, [static_check_main_machine/1]).
318 % set a machine term as current machine, without calling type checking
319 % (used for Z translations)
320 b_set_typed_machine(M1,FromFile) :-
321 b_machine_clear,
322 static_check_main_machine(M1), % done by check_machine in b_set_machine above
323 apply_machine_transformations(M1,ResultMachine),
324 assert_main_machine(ResultMachine),
325 set_all_used_filenames([FromFile]).
326
327 b_set_eventb_project_flat(Models,Contextes,Proofs) :-
328 b_machine_clear,
329 set_animation_mode(b), set_animation_minor_mode(eventb),
330 analyse_eventb_hierarchy(Models,Contextes),
331 ( check_event_b_project(Models,Contextes,Proofs,M1) ->
332 apply_machine_transformations(M1,ResultMachine),
333 assert_main_machine(ResultMachine) % has the form machine/2
334 ;
335 % Note: if there are typecheck errors due to missing .ptm files for axiomatic operators it is not an internal error!
336 fail).
337
338 b_load_eventb_project(Filename) :-
339 read_eventb_project_from_file(Filename,Machines,Contexts,Proofs,Errors,Prefs),
340 (Errors=[] -> true ; add_error(b_load_eventb_project,'Errors in Event-B Package: ',Errors)),
341 set_stored_prefs(Prefs),
342 set_all_used_filenames([Filename]),
343 b_set_eventb_project_flat(Machines,Contexts,Proofs),
344 clear_wp,
345 (load_additional_information(Proofs) -> true ; add_error(b_load_eventb_project,'Failed to load proof information',Proofs)).
346 % generate_specialized_invariants.
347
348 read_eventb_project_from_file(Filename, Machines, Contexts, Proofs, Errors, Prefs) :-
349 open(Filename, read, Stream, [encoding(utf8)]),
350 call_cleanup(read_eventb_project_from_stream(Stream, Filename, LoadCommand, Prefs), close(Stream)),
351 (eventb_load_command(LoadCommand, Machines, Contexts, Proofs, Errors)
352 -> true
353 ; add_error_and_fail(b_load_eventb_project, 'This is not a valid EventB Project file:', Filename)
354 ).
355
356 read_eventb_project_from_stream(Stream, Filename, LC, Prefs) :-
357 safe_read(Stream, Filename, Term),
358 (Term == end_of_file
359 -> Prefs = []
360 ; process_eventb_project_term(Term, LC, Prefs, PrefsTail),
361 read_eventb_project_from_stream(Stream, Filename, LC, PrefsTail)
362 ).
363
364 safe_read(Stream,Filename,T) :-
365 catch(read(Stream,T), E, (
366 ajoin(['.eventb file "', Filename, '" is corrupted; exception occurred while reading:'],Msg),
367 add_error(safe_read,Msg,E),
368 T=end_of_file
369 )).
370
371 process_eventb_project_term(Term, _LC, Prefs, Prefs) :-
372 %tools_printing:nested_write_term_to_codes(Term,Cs), format('~s~n',[Cs]),
373 var(Term),
374 !,
375 add_warning(b_load_eventb_project, 'Bare variable term in Event-B project: ', Term).
376 process_eventb_project_term(package(LoadCommand), LC, Prefs, Prefs) :-
377 !,
378 (nonvar(LC)
379 -> add_error_and_fail(b_load_eventb_project, 'Duplicate package/1 term in Event-B project: ', package(LoadCommand))
380 ; LC = LoadCommand
381 ).
382 process_eventb_project_term(stored_preference(Pref,Val), _LC, [stored_preference(Pref,Val)|Prefs], Prefs) :- !.
383 process_eventb_project_term(emf_model(_Name,_Base64Xml), _LC, Prefs, Prefs) :- !. % not used
384 process_eventb_project_term(Term, _LC, Prefs, Prefs) :-
385 functor(Term, F, N),
386 add_warning(b_load_eventb_project, 'Unrecognized term in Event-B project: ', F/N).
387
388 eventb_load_command(LoadCommand, _, _, _, _) :- var(LoadCommand), !, fail.
389 eventb_load_command(load_event_b_project(Machines,Contexts,Proofs,Errors), Machines, Contexts, Proofs, Errors).
390 eventb_load_command(load_event_b_project(Machines,Contexts,Errors), Machines, Contexts, [], Errors) :-
391 print('% Deprecated EventB Project without Proof Info.'), nl.
392
393 set_stored_prefs([stored_preference(Pref,Val)|Prefs]) :-
394 printsilent(stored_preference(Pref,Val)), nls,
395 preferences:set_preference(Pref,Val),
396 set_stored_prefs(Prefs).
397 set_stored_prefs([]).
398
399 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
400 % Collect Proof Information from Event B
401
402 :- volatile discharged/3.
403 :- volatile discharged_theorem/3, wd_po/3, wp_untyped/3.
404 :- volatile nonchanging_guard/2, discharged_guard_strengthening/4.
405 :- dynamic discharged/3.
406 % discharged(Model,Event,Name) : invariant Name in model Model is preserved by Event (no matter which Event at which refinement level)
407 :- dynamic discharged_theorem/3.
408 :- dynamic wd_po/3.
409 :- dynamic wp_untyped/3.
410 :- dynamic nonchanging_guard/2.
411 :- dynamic discharged_guard_strengthening/4.
412
413 :- volatile b_specialized_invariant_for_op/2, b_operation_preserves_invariant/2.
414 :- dynamic b_specialized_invariant_for_op/2, b_operation_preserves_invariant/2.
415 :- volatile b_nth1_invariant/3, b_invariant_number_list/1,
416 b_specialized_invariant_mask_for_op/2, get_proven_invariant/2.
417 :- dynamic b_nth1_invariant/3, b_invariant_number_list/1, b_specialized_invariant_mask_for_op/2, get_proven_invariant/2.
418 :- volatile complete_discharged_info/0.
419 :- dynamic complete_discharged_info/0.
420
421
422 clear_wp :-
423 retractall( wp_untyped(_,_,_) ).
424 %retractall( wp_typed(_,_,_) ). only in flow.pl
425
426 load_additional_information([]) :- !.
427 load_additional_information([H|T]) :-
428 load_additional_information_fact(H),!,
429 load_additional_information(T).
430 load_additional_information([H|T]) :- !,
431 add_internal_error('Unknown additional info: ',load_additional_information_fact(H)),
432 load_additional_information(T).
433 load_additional_information(I) :- !,
434 add_internal_error('Additional info not a list: ',load_additional_information_fact(I)).
435
436 % old style proof info
437 load_additional_information_fact(discharged(Machine,Theorem)) :- % a discharged theorem
438 debug_println(9,discharged_theorem(Machine,old_style_proof_info,Theorem)),
439 assertz(discharged_theorem(Machine,invariant,Theorem)).
440 load_additional_information_fact(discharged(Machine,Event,Invariant)) :-
441 debug_println(9,discharged(Machine,Event,Invariant)),
442 assertz(discharged(Machine,Event,Invariant)).
443 load_additional_information_fact(Term) :- % theories are handled in bmachine_eventb.pl already
444 is_eventb_additional_info(Term).
445
446 % new style proof info po(Machine,Info,SourceList,Discharged)
447
448 load_additional_information_fact(po(Machine,'Invariant preservation',Source,true)) :- % invariant preservation
449 add_discharged_po_infos(Source,Machine).
450
451 load_additional_information_fact(po(Machine,'Invariant establishment',Source,true)) :- % invariant establishment
452 add_discharged_po_infos(Source,Machine).
453
454 load_additional_information_fact(po(Machine,Text,Source,Proven)) :- % invariant or theorem wd
455 ( Text = 'Well-definedness of Invariant'
456 ; Text = 'Well-definedness of Theorem'),
457 member(invariant(Invariant),Source),
458 debug_println(9,wd_po(Machine,Invariant,Proven)),
459 assertz(wd_po(Machine,Invariant,Proven)).
460 load_additional_information_fact(po(Machine,Text,Source,Proven)) :- % axiom or axiom theorem wd
461 ( Text = 'Well-definedness of Axiom'
462 ; Text = 'Well-definedness of Theorem'),
463 member(axiom(Axiom),Source),
464 debug_println(9,wd_axiom(Machine,Axiom,Proven)). % TO DO: assert and use
465 load_additional_information_fact(po(Machine,Text,Source,Proven)) :- % proven theorem as guard
466 Text = 'Well-definedness of Theorem',
467 member(guard(Grd),Source),
468 member(event(Evt),Source),
469 debug_println(9,wd_axiom(Machine,Evt/Grd,Proven)). % TO DO: assert and use
470 load_additional_information_fact(po(Machine,Text,Source,Proven)) :- % wd of action
471 Text = 'Well-definedness of action',
472 (member(action(ACT),Source) % probably the guard in the last event with discharged info ??
473 -> debug_println(9,wd_action(Machine,ACT,Proven)) % TO DO: assert and use, if false: discard proven invariants?!
474 ; format('Illegal Rodin PO source in ~w for ~w: ~w~n',[Machine,Text,Source])
475 ).
476 load_additional_information_fact(po(Machine,Text,Source,Proven)) :- % wd of guard
477 Text = 'Well-definedness of Guard',
478 (member(guard(GRD),Source) % probably the guard in the last event with discharged info ??
479 -> debug_println(9,wd_guard(Machine,GRD,Proven)) % TO DO: assert and use
480 ; format('Illegal Rodin PO source in ~w for ~w: ~w~n',[Machine,Text,Source])
481 ).
482 load_additional_information_fact(po(Machine,'Theorem',[invariant(Theorem)],true)) :- % a theorem
483 debug_println(9,discharged_theorem(Machine,invariant,Theorem)),
484 assertz(discharged_theorem(Machine,invariant,Theorem)).
485 load_additional_information_fact(po(Machine,'Theorem',[axiom(Theorem)],true)) :- % a theorem
486 debug_println(9,discharged_theorem(Machine,axiom,Theorem)),
487 assertz(discharged_theorem(Machine,axiom,Theorem)).
488 load_additional_information_fact(po(Machine,'Theorem',[guard(GuardTheorem),event(Event)],true)) :- % a theorem in a guard
489 debug_println(9,discharged_theorem(Machine,guard(Event),GuardTheorem)),
490 assertz(discharged_theorem(Machine,guard(Event),GuardTheorem)).
491
492 % stuff we don't yet care about
493 load_additional_information_fact(po(Machine,Text,Infos,Proven)) :-
494 ( Text = 'Guard strengthening (split)'
495 ; Text = 'Guard strengthening (merge)'
496 ; Text = 'Guard strengthening' ),
497 !,
498 (Proven=true, Infos = [event(AbsEvent),guard(Guard),event(ConcreteEvent)]
499 -> assertz(discharged_guard_strengthening(Machine,AbsEvent,Guard,ConcreteEvent)),
500 debug_println(19,discharged_guard_strengthening(Machine,AbsEvent,Guard,ConcreteEvent))
501 ; true
502 ).
503 load_additional_information_fact(po(_,'Variant of event',_,_)).
504 load_additional_information_fact(po(_,'Natural number variant of event',_,_)).
505 load_additional_information_fact(po(_,'Action simulation',_,_)).
506 load_additional_information_fact(po(_,'Feasibility of witness',_,_)).
507 load_additional_information_fact(po(_,'Feasibility of action',_,_)).
508 load_additional_information_fact(po(_,'Well-definedness of witness',_,_)).
509 load_additional_information_fact(po(_,'Well-definedness of variant',_,_)).
510 load_additional_information_fact(po(_,'Finiteness of variant',_,_)).
511 load_additional_information_fact(po(_,'Equality of common variables',_,_)).
512
513 load_additional_information_fact(po(_Machine,_Kind,_Source,false)). % ignore everything that is not proven
514
515 load_additional_information_fact(po(_Machine,_Kind,_Source,reviewed)). % ignore everything that is only reviewed
516
517 % ignore exporter version for now
518 % we are compatible to both versions 2 and 3 (added abstract constants)
519 load_additional_information_fact(exporter_version(V)) :- V=2 ; V=3.
520
521 % ignored because the pragmas are attached to the machine in load_event_b_project/4
522 load_additional_information_fact(pragma(_Type,_Source,_AttachedTo,_Content)).
523
524 load_additional_information_fact(wp(S,D,P)) :-
525 assertz( wp_untyped(S,D,P) ).
526
527 load_additional_information_fact(nonchanging_guard(E,P)) :-
528 typecheck_predicates(P,TypedPred,E,_),
529 assertz(nonchanging_guard(E,TypedPred)).
530
531 load_additional_information_fact(invariant(_I)). %ignore
532
533 typecheck_predicates([],[],_,_).
534 typecheck_predicates([H|T],[TH|TT],S,D) :-
535 (S='INITIALISATION' -> Scope1 = []; Scope1=[operation(S)]),
536 ((D='INITIALISATION';var(D)) -> Scope2 = Scope1; Scope2=[operation(D)|Scope1]),
537 Scope = [variables|Scope2],
538 b_type_expression(H,Scope, _, TH, _),
539 typecheck_predicates(T,TT,S,D).
540
541
542 add_discharged_po_infos(Source,Machine) :-
543 % Source = [event(A1),...,event(CurMachineEvent),invariant(Inv)]
544 % note that CurMachineEvent could be equal to A1; A1 can be split up into multiple events (one of which could have the same name as A1; see Ticket PROB-292)
545 get_bottom_event(Source,Event),
546 member(invariant(Invariant),Source),
547 debug_println(9,discharged(Machine,Event,Invariant)),
548 assertz(discharged(Machine,Event,Invariant)),
549 % TO DO: should we propagate info up to abstract events which are not split up or where all refinements preserve a certain invariant ??
550 fail.
551 add_discharged_po_infos(_Source,_Machine).
552
553 % get the last event entry in proof info source list
554 get_bottom_event(Source,Event) :-
555 (bottom_event(Source,'$NONE'(none),Event) -> true
556 ; add_error(bmachine,'Could not determine event for proof info: ',Source),fail).
557 bottom_event([],Ev,Ev) :- Ev \= '$NONE'(none).
558 bottom_event([event(E)|T],_,Res) :- !,bottom_event(T,E,Res).
559 bottom_event([_|T],E,Res) :- bottom_event(T,E,Res).
560
561 :- use_module(debug).
562
563 tcltk_get_specialized_invariants_for_ops(list(Res)) :-
564 findall([Name,InvHeader,TI | Tail],
565 ((b_top_level_operation(Name) ; Name='$initialise_machine'),
566 tcltk_get_specialized_invariant_for_op_single(Name,TI,NrUnProven),
567 tcltk_get_proven_invariant_for_op(Name,PI),
568 ajoin([' INVARIANT (',NrUnProven,')'],InvHeader),
569 (PI='none' -> Tail = ['END;']
570 ; Tail = [' NON-TRIVIAL PROVEN INVARIANT:', PI, 'END;']
571 )
572 ), Res).
573 tcltk_get_specialized_invariant_for_op_single(Event,TI,NrUnProven) :-
574 (b_specialized_invariant_for_op(Event,Invariant) ->
575 conjunction_to_list(Invariant,IL), length(IL,NrUnProven),
576 translate:translate_bexpression(Invariant,TI)
577 ; TI = 'not_simplified', NrUnProven='-').
578 tcltk_get_specialized_invariant_for_op(Event,list(TI)) :-
579 (b_specialized_invariant_for_op(Event,Invariant) ->
580 conjunction_to_list(Invariant,IL),
581 (IL=[] -> TI = ['fully_proven']
582 ; maplist(translate:translate_bexpression,IL,TI))
583 ; TI = ['not_simplified']).
584 tcltk_get_proven_invariant_for_op(Event,TI) :- % get non-trivially proven invariants
585 (get_proven_invariant(Event,Invariant), \+ is_truth(Invariant) ->
586 translate:translate_bexpression(Invariant,TI)
587 ; TI = 'none').
588
589
590 :- public b_nth1_invariant_calc/3.
591 b_nth1_invariant_calc(Nr,Invariant,UsedIds) :-
592 get_invariant_list_with_used_ids(IL,IL_Ids),
593 ? nth1(Nr,IL,Invariant),
594 nth1(Nr,IL_Ids,UsedIds).
595
596 % bmachine:b_nth1_invariant(Nr,Inv,Used), format('~nInvariant ~w over ~w~n',[Nr,Used]), translate:print_bexpr(Inv),nl,fail
597 % bmachine:b_specialized_invariant_mask_for_op(Op,Mask), format('Mask ~w : ~w~n',[Op,Mask]),fail
598
599 :- public b_invariant_number_list_calc/1.
600 b_invariant_number_list_calc(InvList) :-
601 findall(nth1_invariant(Nr),b_nth1_invariant(Nr,_,_),InvList).
602
603 % use proof information to compute subset of invariant that needs to be checked for operations
604
605 % one fact including the position of all unproven invariants
606 :- public b_specialized_invariant_mask_for_op_calc/2.
607 b_specialized_invariant_mask_for_op_calc(Event,Mask) :-
608 preferences:get_preference(use_po,true),
609 get_invariant_list_with_used_ids(IL,IL_Ids),
610 % Note: we can have interference with CSE here, as lazy_let_pred at top-level can merge several conjuncts (but CSE is now disabled for the invariant if PROOF_INFO = TRUE)
611 IL \= [], % otherwise: Invariant already trivial; no sense in keeping track of information
612 ? get_op_or_init_and_syntax_filter(Event,ProofInfoEventName,IL,IL_Ids,RIL),
613 exclude(is_proven_invariant(ProofInfoEventName),RIL,RL), % Warning !! The invariants are not all from Model; the discharged information could be for a proven invariant with the same label from another model, see examples/EventBPrologPackages/ProofDirected/TestR_label_reuse.eventb; this should now properly be dealt with by filter_proven_invariants
614 IL\=RL, /* something filtered out */
615 (RL=[]
616 -> Mask = [] % fully proven
617 ; findall(Nr,(nth1(Nr,IL,Inv),member(Inv,RL)),Mask)
618 ),
619 debug_println(4,b_specialized_invariant_mask_for_op(Event,Mask)).
620
621 % TODO: investigate whether we should pre-compute this or simply re-compute it as needed
622 :- public b_specialized_invariant_for_op_calc/2.
623 b_specialized_invariant_for_op_calc(Event,Invariant) :-
624 b_specialized_invariant_mask_for_op(Event,Mask),
625 findall(Inv,(member(Nr,Mask),b_nth1_invariant(Nr,Inv,_)),RL),
626 conjunct_predicates(RL,Invariant). %, print(simplified),nl,translate:print_bexpr(Invariant),nl.
627
628
629 get_op_or_init_and_syntax_filter('$initialise_machine','INITIALISATION',IL,_,IL). % INIT always sets all variables
630 get_op_or_init_and_syntax_filter(Event,Event,IL,IL_Ids,RIL) :-
631 ? b_is_operation_name(Event),
632 filter_syntactically_relevant_invariants(IL,IL_Ids,Event,RIL). % filter out all invariants not modified by Event
633
634 :- public b_operation_preserves_invariant_calc/2.
635 % check if an operation preserves the full invariant; according to proof information
636 b_operation_preserves_invariant_calc(Event,Preserved) :-
637 b_specialized_invariant_mask_for_op(Event,Mask),
638 (Mask=[] -> Preserved=full_invariant ; Preserved=partial_invariant).
639
640 b_operation_preserves_full_invariant(Op) :- b_specialized_invariant_mask_for_op(Op,[]).
641
642 :- public get_proven_invariant_calc/2.
643 % computes proven, relevant invariants (not trivial ones which are unaffected by Event) for main model
644 get_proven_invariant_calc(Event, Invariant) :-
645 preferences:get_preference(use_po,true),
646 b_machine_name(Model),
647 get_invariant_list_with_used_ids(IL,IL_Ids),
648 ? b_is_operation_name(Event),
649 %print(filter_syntactically_relevant_invariants(Event,Model)),debug:nl_time,
650 filter_syntactically_relevant_invariants(IL,IL_Ids,Event,RIL),
651 %print(select_proven_invariants(Event,Model)),debug:nl_time,
652 select_proven_invariants(RIL,Model,Event,RL),
653 %print(conjunct_predicates(Event,Model)),debug:nl_time,
654 conjunct_predicates(RL,Invariant).
655
656 get_invariant_list_with_used_ids(IL,IL_Ids) :-
657 b_get_invariant_from_machine(I),
658 conjunction_to_list_with_rodin_labels(I,IL),
659 maplist(find_id_uses_for_maplist,IL,IL_Ids).
660 find_id_uses_for_maplist(Inv,IDs) :- find_identifier_uses(Inv,[],IDs).
661
662 % get list of invariants with proof info (discharged(_)) added
663 get_invariant_list_with_proof_info(InvariantList) :-
664 findall(I,get_invariant_with_proof_status_calc(I,_),InvariantList).
665
666 :- use_module(probsrc(tools_lists),[count_occurences/2]).
667
668 % compute all invariants which are not fully proven for events (initialisation is not examined!):
669 get_unproven_invariants(UnProvenList) :-
670 findall(I,get_invariant_with_proof_status_calc(I,unproven),UnProvenList).
671
672 get_invariant_with_proof_status_calc(Invariant,Proven) :- % not precompiled at the moment
673 b_machine_name(Model),
674 b_get_invariant_from_machine(I),
675 conjunction_to_list_with_rodin_labels(I,IL), % ensure rodin labels are propagated down for proof info
676 member(Inv,IL),
677 findall(Status,invariant_proof_status_for_event(Inv,Model,_Event,Status),StatusList),
678 count_occurences(StatusList,Occs),
679 (member(unproven-_,Occs)
680 -> Proven=unproven
681 ; (debug_mode(on) -> print('INVARIANT proven for all events: '), translate:print_bexpr(Inv),nl ; true),
682 Proven=proven
683 ),
684 add_texpr_info_if_new(Inv,proof_status(Proven,Occs),Invariant).
685
686 %is_unproven_inv_for_model(_Invariant,_Model,_Event) :-
687 % preferences:get_preference(use_po,false),!. % information is used in bvisual2,...
688 invariant_proof_status_for_event(Invariant,Model,Event,Status) :-
689 ? b_is_operation_name(Event),
690 proof_status_for_inv2(Invariant,Model,Event,Status).
691
692 proof_status_for_inv2(Invariant,_,Event,unchanged) :-
693 \+ is_syntactically_relevant_invariant_for_event(Event,Invariant),!. % invariant unaffected by Event/Operation
694 proof_status_for_inv2(Invariant,Model,Event,proven) :-
695 is_proven_invariant_for_model(Model,Event,Invariant),!.
696 proof_status_for_inv2(_,_,_,unproven).
697
698
699 % filter_syntactically_relevant_invariants(+InvariantsList, +UsedIDs, +EventName, -RelevantItemsFromInvariantsList)
700 filter_syntactically_relevant_invariants(Invariants,IL_Ids,Event,Result) :-
701 get_operation_info(Event,SubstitutionInfo),
702 get_modifies_from_info(SubstitutionInfo,SortedModIds),
703 filter_syntactically_relevant_invariants2(Invariants,IL_Ids,SortedModIds,Result).
704 % noticeably faster than include, see e.g. public_examples/B/PerformanceTests/Generated/Generated4000.mch
705 %include(is_syntactically_relevant_inv(SortedModIds),Invariants,IL_Ids,Result).
706
707 is_syntactically_relevant_inv(SortedModIds,_Inv,IDs) :-
708 ord_intersect(SortedModIds,IDs).
709
710 filter_syntactically_relevant_invariants2([],_,_,[]).
711 filter_syntactically_relevant_invariants2([Inv|T],[IDs|TI],SortedModIds,R) :-
712 (is_syntactically_relevant_inv(SortedModIds,Inv,IDs)
713 -> R=[Inv|TR] ; R=TR),
714 filter_syntactically_relevant_invariants2(T,TI,SortedModIds,TR).
715
716 is_syntactically_relevant_invariant_for_event(Event,Inv) :-
717 get_operation_info(Event,SubstitutionInfo),
718 get_modifies_from_info(SubstitutionInfo,SortedModIds),
719 find_id_uses_for_maplist(Inv,IDs),
720 is_syntactically_relevant_inv(SortedModIds,_Inv,IDs).
721
722 get_modifies_from_info(SubstitutionInfo,SortedModIds) :-
723 ((memberchk(modifies(ModID),SubstitutionInfo) -> ground(ModID))
724 -> list_to_ord_set(ModID,SortedModIds) % is this necessary ?
725 ; SortedModIds=[]).
726
727 % filter_proven_invariants(+InvariantsList, +ModelName, +EventName, -RelevantItemsFromInvariantsList)
728 % this gets called during model checking time
729 is_proven_invariant(Event,E) :-
730 % print('Filter Check: '), print(Event), print(' : '),translate:print_bexpr(E),nl,
731 get_precise_rodin_model_and_name(E,Model,Name),
732 !,
733 discharged_invariant(Model,Name,Event),
734 % now check that if E is not always well-defined that there are no unproven WD proof obligations !
735 check_wd_discharged_inv_or_thm(E,Model,Name,Event). %% print('DISCHARGED'(Model,Event,Name)),nl.
736
737 check_wd_discharged_inv_or_thm(E,_,_,_) :- always_well_defined(E),!.
738 check_wd_discharged_inv_or_thm(_,Model,Name,_Event) :- wd_po(Model,Name,ProofStatus),!,
739 ProofStatus=true.
740 check_wd_discharged_inv_or_thm(_,Model,Name,Event) :-
741 % no WD_PO associated or stored
742 % TO DO: we could try ProB-WD prover; but this situation only happens with old-style exports; we could use add_message
743 format('% Assuming invariant/theorem ~w is well-defined for event ~w:~w (no WD PO found).~n',[Name,Model,Event]).
744
745 % select_proven_invariants(+InvariantsList, +ModelName, +EventName, -RelevantItemsFromInvariantsList)
746 select_proven_invariants(Invariants,Model,Event,Result) :-
747 include(is_proven_invariant_for_model(Model,Event),Invariants,Result).
748
749 % Note: different from is_proven_invariant; TO DO: merge (here we assume main model)
750 is_proven_invariant_for_model(MainModel,Event,E) :-
751 get_rodin_name(E,Name), % if we do not have a rodin position we consider this as not proved
752 (get_rodin_model_name(E,Model) -> true
753 ; debug_format(19,'Could not get Rodin model name for invariant (deprecated .eventb format): ~w~n',[Name]),
754 Model=MainModel,
755 fail % we have an old style .eventb file; safer to assume not proven as there can be clashes of labels
756 ),
757 discharged_invariant(Model,Name,Event).
758
759 is_discharged_assertion(Theorem) :-
760 if( get_precise_rodin_model_and_name(Theorem,Model,Name),
761 (discharged_theorem(Model,_,Name), % does not matter if invariant or axiom
762 check_wd_discharged_inv_or_thm(Theorem,Model,Name,assertion) ) % check that well-defined
763 , (animation_minor_mode(eventb),
764 (silent_mode(on) -> true
765 ; print('Could not get position information for theorem: '),
766 translate:print_bexpr(Theorem),nl,
767 get_texpr_pos(Theorem,POS),debug_println(19,get_texpr_pos(POS))
768 ),
769 fail)
770 ).
771
772 get_precise_rodin_model_and_name(Theorem,Model,Name) :-
773 get_texpr_pos(Theorem,Pos),
774 (Pos = rodinpos(Model,Name,_)
775 -> true % only accept new rodinpos information with three parameters !
776 % the old one with two parameters could lead to confusion as labels can be reused
777 % we also do not accept rodin_derived_context_pos(Model,_Context,Name); not sure if this would be sound
778 ).
779
780 % derived predicate
781 discharged_invariant(Model,InvariantName,Event) :-
782 % InvariantName from model Model is preserved by Event and any of its refinements
783 discharged(Model,Event,InvariantName).
784 discharged_invariant(Model,InvariantName,Event) :-
785 % InvariantName from model Model is preserved by Event and any of its refinements
786 also_discharged(Model,Event,InvariantName).
787
788 b_machine_has_proven_invariants :-
789 (discharged(_,_,_) -> true).
790
791 % complete the discharged/3 information: propagating information from abstract events
792 % down to refined top-level events
793 :- public complete_discharged_info/0.
794 :- public complete_discharged_info_calc/0.
795 complete_discharged_info_calc :- debug_println(4,'completing discharged info: '),
796 statistics(runtime,[Start,_]),
797 (complete_discharged_info2 -> true ; true),
798 statistics(runtime,[Stop,_]), T is Stop-Start, debug_print(4,T), debug_println(4,' ms').
799 :- volatile discharged2/2, also_discharged/3.
800 :- dynamic discharged2/2.
801 :- dynamic also_discharged/3.
802 discharged_info_exists :- discharged2(_,_),!.
803 complete_discharged_info2 :- retractall(also_discharged(_,_,_)),
804 retractall(discharged2(_,_)),
805 discharged(Model,Event,_), % find out which Model and Events are used in discharged info
806 \+ discharged2(Model,Event), %print(discharged(Model,Event)),nl,
807 assertz(discharged2(Model,Event)),fail.
808 complete_discharged_info2 :- discharged_info_exists,
809 b_get_animated_sections(Sections),
810 discharged2(Model,Event), % Event in Model was proven to preserve an invariant in Model
811 b_get_abstract_events(Event,RModel,AbstractEvents), % search for a refinement of Model where the same event exists
812 RModel \= Model,
813 % i.e., invariant Name was proven in an abstract Model for Event
814 \+ is_abstract_event_in_list(Event,Model,AbstractEvents), % this event is *NOT* a refinement of the proven one
815 debug_println(4,removing_discharged(Model,Event)),
816 retractall(discharged(Model,Event,_Name)),
817 member(model(Model),Sections), % only generate error message if the Model is also animated using b_get_animated_sections, see example EventBPrologPackages/ProofDirected/TestInvPreserv_M2_ko_mch.eventb
818 % (otherwise the refinement may well exist but has been filtered out by restricting the animation levels)
819 add_error(event_refinement,'An event does not refine an abstract event of the same name: ',Event:Model:RModel),
820 % This will could cause errors in the proof information usage !
821 %print(AbstractEvents),nl,
822 fail.
823 complete_discharged_info2 :- discharged_info_exists,
824 complete_discharged_info3(_Model,_Event,_Name).
825 complete_discharged_info3(InvNameModel,AbsEvent,Name) :-
826 b_get_abstract_events(EventInRefinement,_RefModel,AbstrEvents),
827 is_abstract_event_in_list(AbsEvent,InvNameModel,AbstrEvents), % Event in InvNameModel is an abstract event of EventInRefinement
828 %print(check(InvNameModel,Event, EventInRefinement,RefModel)),nl,
829 discharged(InvNameModel,AbsEvent,Name), % print(chck2(Model,Event,Name)),nl,
830 %InvNameModel:Name has been proven for AbsEvent *at all relevant* levels
831 \+ discharged(InvNameModel,EventInRefinement,Name),
832 \+ also_discharged(InvNameModel,EventInRefinement,Name),
833 % this invariant has not yet been marked as proven for EventInRefinement
834 debug_println(4,also_discharged_in_refinement(InvNameModel:Name,EventInRefinement,refined_from(AbsEvent))),
835 assertz(also_discharged(InvNameModel,EventInRefinement,Name)),
836 fail.
837
838 %abstract_event_of_calc(TopLevelEvent,RModel,Event,Model) :-
839 % b_get_abstract_events(TopLevelEvent,RModel,AbstrEvents),
840 % is_abstract_event_in_list(Event,Model,AbstrEvents) , print(abs(TopLevelEvent,RModel,Event,Model)),nl.
841
842 is_abstract_event_in_list(Event,Model,AbstractEvents) :-
843 member(b(rlevent(AEvent,AModel,_S,_P,_G,_Thm,_Act,_VW,_PW,_Unm,AbstractEvents2),_,_),AbstractEvents),
844 (Event=AEvent, Model=AModel;
845 is_abstract_event_in_list(Event,Model,AbstractEvents2)).
846
847 % get events that are refined by an event
848 b_get_abstract_events(Name,Section,AbsEvents) :-
849 b_get_machine_operation(Name,_R,_P,Body,_OType,_OpPos),
850 get_texpr_expr(Body,RLEVENT),
851 RLEVENT = rlevent(_Name,Section,_Stat,_Parameters,_Grd,_Thm,_Act,_VWit,_PWit,_Unmod,AbsEvents).
852
853 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
854
855 :- volatile b_operation_reads_output_variables/3, b_operation_cannot_modify_state/1.
856 :- dynamic b_operation_reads_output_variables/3, b_operation_cannot_modify_state/1.
857
858 % test if we have a query or skip operation which cannot modify the state
859 % (preconditions, assertions could still fail though !)
860 :- public b_operation_cannot_modify_state_calc/1.
861 b_operation_cannot_modify_state_calc(Event) :-
862 b_get_operation_normalized_read_write_info(Event,_ReadVariables,[]).
863
864 :- use_module(b_read_write_info, [get_accessed_vars/4]).
865 % check if classical B operation reads its output variables
866 :- public b_operation_reads_output_variables_calc/3.
867 b_operation_reads_output_variables_calc(Event,ReadOutputVariablesIds,ReadOutputTypedInfo) :-
868 ? b_get_machine_operation(Event,ResultTuple,_TParas,TBody,_OType,_Pos),
869 def_get_texpr_ids(ResultTuple,ResIds),
870 sort(ResIds,SResIds),
871 get_operation_info(Event,SubstitutionInfo),
872 member(reads_locals(Reads),SubstitutionInfo), % locals are either arguments or return output variables
873 ord_intersection(Reads,SResIds,ReadOutputVariablesIds),
874 ReadOutputVariablesIds \= [],
875 % now recompute the information based on TBody after ast_cleanup: typing predicates have been removed
876 get_accessed_vars(TBody,[],_,AllReadsAfterAstCleanup), % important to pass [] as local variables
877 ord_intersection(AllReadsAfterAstCleanup,ReadOutputVariablesIds,ReadOutputVariablesIds2),
878 ReadOutputVariablesIds2 \= [],
879 (get_preference(allow_operations_to_read_outputs,true), debug_mode(off) -> true
880 ; ajoin(['Operation ', Event, ' is possibly reading or not always assigning to output parameters: '],Msg),
881 add_message(bmachine,Msg,ReadOutputVariablesIds2,ResultTuple)
882 % Note: analysis is not always precise: /public_examples/B/NewSyntax/CallOperationInExprSimple2.mch
883 ),
884 findall(reads_result(Index,ID,Type),
885 (nth1(Index,ResultTuple,b(identifier(ID),Type,_)), ord_member(ID,ReadOutputVariablesIds2)),
886 ReadOutputTypedInfo).
887
888
889
890 :- volatile b_get_operation_normalized_read_write_info/3, b_get_operation_unchanged_variables/2.
891 :- dynamic b_get_operation_normalized_read_write_info/3, b_get_operation_unchanged_variables/2.
892
893
894 :- use_module(bsyntaxtree,[get_global_identifiers/1]).
895
896 :- public b_get_operation_normalized_read_write_info_calc/3.
897 /* compute Read and Written Variables by an operation */
898 b_get_operation_normalized_read_write_info_calc(Event,SortedReadVariables,SortedWrittenVariables) :-
899 get_global_identifiers(IS), % Note: find identifier uses was called before global sets precompiled
900 ? get_operation_info(Event,SubstitutionInfo),
901 (memberchk(modifies(WrittenVariables),SubstitutionInfo)
902 -> sort(WrittenVariables,SWV), % normally not necessary; just to be sure
903 ord_subtract(SWV,IS,SortedWrittenVariables)
904 ; print(no_modifies_info(Event)),nl,fail),
905 (memberchk(reads(ReadVariables),SubstitutionInfo)
906 -> sort(ReadVariables,SWR),
907 ord_subtract(SWR,IS,SortedReadVariables)
908 ; debug_println(9,no_reads_info(Event)),fail). % happens currently in Event-B !
909 %% , print(read_write_set(Event,ReadVariables,WrittenVariables)),nl.
910
911 :- public b_get_operation_unchanged_variables_calc/2.
912 b_get_operation_unchanged_variables_calc(Event,UnchangedVariables) :-
913 b_get_machine_variables(TVars),
914 def_get_texpr_ids(TVars,V),
915 sort(V,SAllVars),
916 ? b_get_operation_normalized_read_write_info(Event,_,WrittenVars),
917 ord_subtract(SAllVars,WrittenVars,UnchangedVariables).
918
919
920
921 :- volatile b_get_operation_non_det_modifies/2.
922 :- dynamic b_get_operation_non_det_modifies/2.
923 :- public b_get_operation_non_det_modifies_calc/2.
924 :- use_module(b_read_write_info,[get_nondet_modified_vars/3]).
925 % determine which variables are non-deterministically written by an operation
926 % note: this can depend on the parameters, hence show_eventb_any_arguments is relevant
927 b_get_operation_non_det_modifies_calc(OpName,NonDetModifies) :-
928 ? b_get_machine_operation_for_animation(OpName,Results,Parameters,Body),
929 append(Results,Parameters,TLocalVars),
930 get_texpr_ids(TLocalVars,LocalVars),
931 get_nondet_modified_vars(Body,LocalVars,NonDetModifies).
932 b_get_operation_non_det_modifies_calc('$initialise_machine',NonDetModifies) :-
933 b_get_initialisation_from_machine(Body,_),
934 get_nondet_modified_vars(Body,[],NonDetModifies),debug_println(19,init_not_det_modifies(NonDetModifies)).
935
936
937 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
938
939
940 :- volatile b_get_all_used_filenames/1, b_get_main_filename/1, b_get_main_filenumber/1.
941 :- dynamic b_get_all_used_filenames/1. % can be used, e.g., for second argument of pos info field
942 :- dynamic b_get_main_filename/1. % can be used in above list; there is also specfile:currently_opened_file
943 :- dynamic b_get_main_filenumber/1. % the number of the main_file in the b_get_all_used_filenames list (useful for pos information)
944 b_get_all_used_filenames([]).
945
946 % add an additional filename and obtain its number
947 add_additional_filename(Filename,ResNr) :- functor(Filename,unknown,_),!,
948 format('Unknown additional filename: ~w~n',[Filename]),
949 ResNr = -1.
950 add_additional_filename(Filename,ResNr) :-
951 b_get_all_used_filenames(Fs),
952 nth1(Nr,Fs,Filename),!,
953 ResNr=Nr.
954 add_additional_filename(Filename,ResNr) :-
955 retract(b_get_all_used_filenames(Fs)),
956 length(Fs,Len),
957 append(Fs,[Filename],NewFs),
958 assert(b_get_all_used_filenames(NewFs)),
959 ResNr is Len+1,
960 format('Registering new filename ~w with number ~w~n',[Filename,ResNr]).
961
962 % add additional filename and add as default for parsercalls
963 set_additional_filename_as_parsing_default(Filename,NewNr,OldNr) :-
964 add_additional_filename(Filename,NewNr),
965 set_default_filenumber(NewNr,OldNr).
966 reset_filename_parsing_default(NewNr,OldNr) :- % reset default filenumber back
967 reset_default_filenumber(NewNr,OldNr).
968
969 b_load_machine_from_file(Filename) :- b_load_machine_from_file(Filename,[]).
970 b_load_machine_from_file(Filename,Options) :-
971 (debug_mode(on)
972 -> get_parser_version(Version),
973 format('Java Parser Version: ~w~n',[Version]) % used to be called unconditionally to be sure to catch error if java or BParser.jar not available; but now we do not want the Java startup time unless really necessary
974 ; true),
975 b_reset_filenames_and_numbers,
976 debug_stats(loading(Filename)),
977 catch(load_b_machine_as_term(Filename,Machine,Options),
978 parse_errors(Errors),
979 (add_all_perrors_in_context_of_used_filenames(Errors,parse_error,error),fail)),
980 b_load_machine_from_term(Filename,Machine).
981
982
983 % add parse errors in context of current machine and its filenames
984 add_all_perrors_in_context_of_used_filenames(Errors,TypeOfError,ErrOrWarn) :- Errors\=[],
985 b_get_all_used_filenames(Filenames), Filenames \= [],
986 !,
987 add_all_perrors(Errors,Filenames,TypeOfError,ErrOrWarn).
988 add_all_perrors_in_context_of_used_filenames(Errors,TypeOfError,ErrOrWarn) :-
989 (Errors=[] -> true ; debug_println(19,'Unable to obtain filenames for parse errors, probably preparse_error')),
990 add_all_perrors(Errors,[],TypeOfError,ErrOrWarn).
991
992
993 % a way to load .prob files directly
994 b_load_machine_probfile(Filename) :- b_load_machine_probfile(Filename,[]).
995 b_load_machine_probfile(Filename,Options) :- b_reset_filenames_and_numbers,
996 load_b_machine_probfile_as_term(Filename,Options,Machine),
997 Machine = complete_machine(_MainName,_,Filenames),
998 Filenames = [BFilename|_], % assume first file is the main file
999 b_load_machine_from_term(BFilename,Machine).
1000
1001
1002 % a way to load form a list of Facts which would be found in the .prob file
1003 b_load_machine_from_list_of_facts(Filename,ListOfFacts) :- % Filename only used below for find_main_file_name and later to find out about position infos if they are in the main file or not
1004 load_b_machine_list_of_facts_as_term(ListOfFacts,Machine),
1005 b_load_machine_from_term(Filename,Machine).
1006
1007
1008 b_reset_filenames_and_numbers :-
1009 set_all_used_filenames([]),
1010 retractall(b_get_main_filename(_)),
1011 retractall(b_get_main_filenumber(_)),
1012 retractall(b_filenumber(_,_,_,_)).
1013
1014 set_all_used_filenames(AllFilenames) :-
1015 retractall(b_get_all_used_filenames(_)),
1016 assertz(b_get_all_used_filenames(AllFilenames)).
1017
1018
1019 b_load_machine_from_term(Filename,complete_machine(MainName,Machines,Filenames)) :-
1020 b_reset_filenames_and_numbers, % call in case we call this predicate directly from outside
1021 !,
1022 assertz(b_get_main_filename(Filename)),
1023 set_all_used_filenames(Filenames),
1024 store_filenumbers(Filenames),
1025 (find_main_file_name(Nr,Filenames,Filename) -> assertz(b_get_main_filenumber(Nr))
1026 ; ajoin(['Main filename ', Filename, ' does not appear in filenames list: '],Msg),
1027 add_warning(bmachine,Msg,Filenames)
1028 ),
1029 %print(find_main_file_name(Nr,Filenames,Filename)),nl,
1030 check_valid_machine_name(MainName),
1031 debug_stats(analyse_hierarchy(MainName,Filename)),
1032 (rewrite_complete_machine(MainName,Machines,Machines1) -> true ; Machines1 = Machines),
1033 (analyse_hierarchy(MainName,Machines1)
1034 -> true ; add_error(b_load_machine,'Analyse Hierarchy failed'),fail),
1035 debug_stats(type_check(MainName,Filename)),
1036 b_set_machine(MainName,Machines1,Errors), % Typechecking
1037 debug_stats(checked_machine(MainName,Filename)),
1038 add_all_perrors(Errors,Filenames,type_error), % TO DO: use type_check as source as this may also generate warnings
1039 no_real_perror_occurred(Errors).
1040 b_load_machine_from_term(F,X) :- add_internal_error('Illegal machine: ',b_load_machine_from_term(F,X)),
1041 fail.
1042
1043 rewrite_complete_machine(MainName,[DefMachine],[NewMachine]) :-
1044 DefMachine=definition_file(Pos,Defs),
1045 %print(defs(Defs)),nl,
1046 % Generate virtual abstract machine when loading a .def DEFINITION file
1047 debug_println(19,creating_virtual_abstract_machine_for_definition_file),
1048 Header = machine_header(Pos,MainName,[]),
1049 NewMachine = abstract_machine(Pos,machine(Pos),Header,[Defs]).
1050
1051 check_valid_machine_name(Name) :- atom(Name),atom_codes(Name,Codes),
1052 invalid_chars(Invalid),
1053 (member(C,Codes),ord_member(C,Invalid)
1054 -> ajoin(['Machine name ', Name, ' contains illegal character: '],Msg),
1055 atom_codes(IChar,[C]),
1056 add_warning(bmachine,Msg,IChar)
1057 ; true),
1058 !.
1059 check_valid_machine_name(Name) :- add_internal_error('Illegal machine name:',check_valid_machine_name(Name)).
1060
1061 invalid_chars(".").
1062
1063 :- use_module(tools_matching,[codes_to_lower_case/2]).
1064 find_main_file_name(Nr,_Filenames,File) :- safe_absolute_file_name(File,AF),
1065 tools:get_modulename_filename(AF,TAF), tools:get_filename_extension(AF,ExtF),
1066 (ExtF = prob
1067 -> when(nonvar(EXT), member(EXT,[mch,ref,imp,tla,rmch])) % any machine extension is ok for .prob file
1068 ; EXT =ExtF),
1069 (b_filenumber(TAF,EXT,Nr,_) -> true
1070 ; atom_codes(TAF,TAFCodes), codes_to_lower_case(TAFCodes,Low),
1071 b_filenumber(TAF2,EXT,Nr,_),
1072 atom_codes(TAF2,C2), codes_to_lower_case(C2,Low)
1073 -> ajoin(['Case mis-match between main filename ',TAF,' and stored filename: '],Msg),
1074 % can happen on some file-systems which are case-insensitive or when transferring .prob files from one OS to another
1075 add_message(bmachine,Msg,TAF2)
1076 ).
1077
1078
1079
1080 % remember as facts all B filenames, their extension and their number
1081 :- volatile b_filenumber/4.
1082 :- dynamic b_filenumber/4.
1083 store_filenumbers(Filenames) :- retractall(b_filenumber(_,_,_,_)),
1084 store_filenumbers(Filenames,1).
1085 store_filenumbers([],_).
1086 store_filenumbers([H|T],Nr) :-
1087 safe_absolute_file_name(H,AbsFname),tools:get_modulename_filename(AbsFname,ModuleName),
1088 tools:get_filename_extension(AbsFname,ExtF),
1089 assertz(b_filenumber(ModuleName,ExtF,Nr,AbsFname)),
1090 debug_println(9,b_filenumber(ModuleName,ExtF,Nr,AbsFname)),
1091 N1 is Nr+1,
1092 store_filenumbers(T,N1).
1093
1094 portray_filenumbers :-
1095 format('~w : ~w : ~w (~w)~n',['Nr','ext','Name','Full path']),
1096 b_filenumber(ModuleName,ExtF,Nr,AbsFname),
1097 format('~w : ~w : ~w (~w)~n',[Nr,ExtF,ModuleName,AbsFname]),
1098 fail.
1099 portray_filenumbers.
1100
1101 :- use_module(tools,[same_file_name/2]).
1102 get_machine_file_number(Name,Ext,Nr,File) :-
1103 if(b_filenumber(Name,Ext,Nr,File),
1104 true,
1105 (b_filenumber(StoredName,Ext,Nr,File),
1106 % on Windows the capitalisation of the stored name maybe different from the name in machine
1107 same_file_name(Name,StoredName)
1108 )).
1109
1110
1111 :- use_module(tools,[safe_absolute_file_name/3, get_parent_directory/2]).
1112 % open a file relateive to the main B file
1113 b_absolute_file_name_relative_to_main_machine(File,AbsFileName) :-
1114 b_get_main_filename(MainFileName),
1115 get_parent_directory(MainFileName,Directory),
1116 % in Jupyter: MainFileName does not exist; SICStus then treats it as a directory
1117 safe_absolute_file_name(File,AbsFileName,[relative_to(Directory)]).
1118
1119 % call to clear all data stored for machine
1120 b_machine_clear :-
1121 b_machine_reset,
1122 b_reset_filenames_and_numbers.
1123
1124 :- use_module(btypechecker,[reset_typechecker/0]).
1125 :- use_module(b_global_sets,[b_clear_global_set_type_definitions/0]).
1126 :- use_module(bmachine_construction,[reset_bmachine_construction/0]).
1127 b_machine_reset :- % print(b_machine_reset),nl,
1128 retractall(machine(_,_)),
1129 retractall(additional_configuration_machine(_,_)),
1130 retractall(discharged_theorem(_,_,_)),
1131 retractall(discharged_guard_strengthening(_,_,_,_)),
1132 retractall(discharged(_,_,_)),
1133 retractall(wd_po(_,_,_)),
1134 retractall(also_discharged(_,_,_)),
1135 reset_temp_predicate,
1136 retractall(b_machine_additional_property(_)),
1137 reset_typechecker,
1138 b_clear_global_set_type_definitions,
1139 reset_bmachine_construction,
1140 startup_precompiled. % change so that error messages generated if we call them
1141
1142 :- use_module(eventhandling,[register_event_listener/3]).
1143 :- register_event_listener(clear_specification,b_machine_clear,
1144 'Reset bmachine facts.').
1145
1146 % :- use_module(library(random)).
1147 :- use_module(preferences,[get_preference/2]).
1148
1149
1150
1151
1152 % precompiled
1153 :- volatile b_machine_name/1.
1154 :- dynamic b_machine_name/1.
1155 :- public b_machine_name_calc/1.
1156 b_machine_name_calc(Name) :-
1157 get_full_b_machine(Name,_).
1158
1159 b_get_animated_sections(Sections) :-
1160 get_section_from_current_machine(meta,MetaInfos),
1161 ( member(animated_sections(Sections), MetaInfos) -> true
1162 ; add_error(bmachine,'No animated sections available'), fail).
1163
1164 :- volatile b_get_named_machine_set/3.
1165 :- dynamic b_get_named_machine_set/3.
1166 :- public b_get_named_machine_set_calc/3.
1167 b_get_named_machine_set(Set,Members) :- b_get_named_machine_set(Set,_,Members).
1168 % precompiled: all enumerated sets with their elements (all in atomic form)
1169 b_get_named_machine_set_calc(Set,TExpr,Members) :-
1170 get_section_from_current_machine(enumerated_sets,Sets),
1171 get_section_from_current_machine(enumerated_elements,Elems),
1172 get_texpr_id(TExpr,Set),
1173 get_texpr_type(TExpr,set(Type)),
1174 get_texpr_type(TElem,Type),
1175 member(TExpr,Sets),
1176 findall(E, (member(TElem,Elems), get_texpr_id(TElem,E)), Members).
1177
1178 :- volatile b_enumerated_sets_precompiled/0.
1179 :- dynamic b_enumerated_sets_precompiled/0.
1180 :- public b_enumerated_sets_precompiled_calc/0.
1181 b_enumerated_sets_precompiled_calc :-
1182 b_check_and_precompile_enumerated_sets.
1183
1184 :- volatile b_get_machine_set/2.
1185 :- dynamic b_get_machine_set/2.
1186 :- public b_get_machine_set_calc/2.
1187 ?b_get_machine_set(Set) :- b_get_machine_set(Set,_).
1188 % precompiled: all deferred and enumerated sets (in atomic form)
1189 b_get_machine_set_calc(Set,TExpr) :-
1190 get_section_from_current_machine(deferred_sets,Sets),
1191 get_texpr_id(TExpr,Set),
1192 ? member(TExpr,Sets).
1193 b_get_machine_set_calc(Set,TExpr) :-
1194 b_get_named_machine_set(Set,TExpr,_).
1195
1196 :- volatile b_get_machine_constants/1, b_get_machine_all_constants/1, b_get_machine_variables/1, b_get_machine_variables_in_original_order/1, b_is_constant/2, b_is_variable/2, b_get_constant_variable_description/2.
1197 :- dynamic b_get_machine_constants/1, b_get_machine_all_constants/1, b_get_machine_variables/1, b_get_machine_variables_in_original_order/1, b_is_constant/2, b_is_variable/2, b_get_constant_variable_description/2.
1198 b_machine_has_constants :- b_get_machine_constants([_|_]).
1199 :- public b_get_machine_all_constants_calc/1.
1200 % precompiled: all constants (abstract and concrete) in typed form
1201 b_get_machine_all_constants_calc(Csts) :-
1202 findall(C,get_multi_sections([abstract_constants,concrete_constants],C),Csts).
1203 :- public b_get_machine_constants_calc/1.
1204 % precompiled: all constants (abstract and concrete) in typed form; except for constant_represented inside global set
1205 b_get_machine_constants_calc(Csts) :-
1206 findall(C,
1207 (get_multi_sections([abstract_constants,concrete_constants],C),
1208 get_texpr_id(C,CID),
1209 \+ b_get_constant_represented_inside_global_set(CID,_)), % ignore constants detected as enumerated set elements
1210 Csts).
1211
1212 b_machine_has_variables :- b_get_machine_variables([_|_]).
1213
1214 :- public b_get_machine_variables_in_original_order_calc/1.
1215 % precompiled: all variables (abstract and concrete) in typed form
1216 b_get_machine_variables_in_original_order_calc(Vars) :-
1217 findall(V,get_multi_sections([abstract_variables,concrete_variables],V),Vars).
1218
1219 :- public b_get_machine_variables_calc/1.
1220 % get variables in order suitable for ord_member and optimized update storing
1221 b_get_machine_variables_calc(SVars) :-
1222 b_get_machine_variables_in_original_order(Vars),
1223 sort(Vars,SVars).
1224
1225 get_nr_of_machine_variables(Nr) :- b_get_machine_variables(L), length(L,Nr).
1226 get_nr_of_machine_constants(Nr) :- b_get_machine_constants(L), length(L,Nr).
1227
1228 b_is_constant(C) :- b_is_constant(C,_).
1229 :- public b_is_constant_calc/2.
1230 % precompiled: all constants (abstract and concrete) in atomic form
1231 b_is_constant_calc(Cst,Type) :-
1232 b_get_machine_constants(Constants),
1233 get_texpr_id(Term,Cst),
1234 get_texpr_type(Term,Type),
1235 member(Term,Constants).
1236 b_is_variable(V) :- b_is_variable(V,_).
1237 :- public b_is_variable_calc/2.
1238 % precompiled: all variables (abstract and concrete) in atomic form
1239 b_is_variable_calc(Var,Type) :-
1240 b_get_machine_variables(Vars), % b_get_machine_variables_in_original_order
1241 get_texpr_id(Term,Var),
1242 get_texpr_type(Term,Type),
1243 member(Term,Vars).
1244 % look up elements in several sections of the machine
1245 get_multi_sections(Sections,Elem) :-
1246 ? member(Section,Sections),
1247 get_section_from_current_machine(Section,List),
1248 member(Elem,List).
1249
1250 :- public b_get_constant_variable_description_calc/2.
1251 % get value of description pragmas @desc for variables and constants:
1252 b_get_constant_variable_description_calc(ID,Desc) :-
1253 (b_get_machine_constants(L) ; b_get_machine_variables(L)),
1254 get_texpr_id(Term,ID),
1255 member(Term,L),
1256 get_texpr_description(Term,TDesc),
1257 (simplify_desc(TDesc,Desc) -> true ; TDesc=Desc).
1258
1259 :- use_module(probsrc(tools_strings), [atom_prefix/2]).
1260 simplify_desc(Compound,R) :- compound(Compound),!,
1261 add_error(simplify_desc,'Non-atomic description: ',Compound),
1262 R=Compound.
1263 simplify_desc(memoize,memo).
1264 simplify_desc(memoise,memo).
1265 simplify_desc('"memoize"',memo).
1266 simplify_desc('"memoise"',memo).
1267 simplify_desc('"expand"',expand).
1268 simplify_desc('"memo"',memo). % allow /*@desc "memo" */
1269 simplify_desc(Atom,memo) :- atom_prefix('"memo ',Atom). % allow /*@desc "memo ...additional text" */
1270
1271 % check if a constant or variable is annotated for memoization:
1272 constant_variable_marked_as_memo(ID) :- b_get_constant_variable_description(ID,memo).
1273
1274 % check if a constant or variable is annotated for expansion using @desc expand
1275 constant_variable_marked_as_expand(ID) :- b_get_constant_variable_description(ID,EXPAND), EXPAND=expand.
1276
1277
1278 :- volatile b_get_invariant_from_machine/1,
1279 b_get_linking_invariant_from_machine/1,
1280 b_get_properties_from_machine/1,
1281 b_get_static_assertions_from_machine/1,
1282 b_extract_values_clause_assignment/3,
1283 b_get_unproven_static_assertions_from_machine/1,
1284 b_get_dynamic_assertions_from_machine/1,
1285 b_get_unproven_dynamic_assertions_from_machine/1,
1286 b_get_assertions_from_main_machine/2,
1287 b_get_initialisation_from_machine/2,
1288 b_get_machine_operation/6,b_top_level_operation/1,
1289 b_get_machine_operation_for_animation/7,
1290 b_is_operation_name/1,
1291 b_get_promoted_machine_operations/1.
1292 :- dynamic b_get_invariant_from_machine/1,
1293 b_get_linking_invariant_from_machine/1,
1294 b_get_properties_from_machine/1,
1295 b_get_static_assertions_from_machine/1,
1296 b_extract_values_clause_assignment/3,
1297 b_get_unproven_static_assertions_from_machine/1,
1298 b_get_dynamic_assertions_from_machine/1,
1299 b_get_unproven_dynamic_assertions_from_machine/1,
1300 b_get_assertions_from_main_machine/2,
1301 b_get_initialisation_from_machine/2,
1302 b_get_machine_operation/6,b_top_level_operation/1,
1303 b_get_machine_operation_for_animation/7,
1304 b_is_operation_name/1,
1305 b_get_promoted_machine_operations/1.
1306
1307 :- public b_get_invariant_from_machine_calc/1.
1308 % precompiled: typed invariant (a predicate)
1309 b_get_invariant_from_machine_calc(Inv) :-
1310 get_section_from_current_machine(invariant,Inv).
1311
1312 :- public b_get_linking_invariant_from_machine_calc/1.
1313 % precompiled: typed linking invariant (a predicate)
1314 b_get_linking_invariant_from_machine_calc(Inv) :-
1315 get_section_from_current_machine(linking_invariant,Inv).
1316
1317 :- public b_get_properties_from_machine_calc/1.
1318 % precompiled: typed properties (a predicate)
1319 b_get_properties_from_machine_calc(SortedProp) :-
1320 get_section_from_current_machine(properties,Prop),
1321 (sort_properties(Prop,SortedProp) -> true %(Prop=SortedProp->true ; print(sorted(SortedProp)))
1322 ; add_error(sort_properties,'sort_properties failed: ',Prop),
1323 SortedProp=Prop).
1324
1325 sort_properties(Prop,SortedProp) :- % print(sort_properties),nl,statistics(runtime, [R1,_]),
1326 weigh_properties(Prop,1,_,[],SProp),
1327 % statistics(runtime, [R2,_]), RDiff is R2-R1,print(done_weigh(RDiff,SProp)),nl,
1328 sort(SProp,SSProp),
1329 % statistics(runtime, [R3,_]), RDiff2 is R3-R2,print(done_sort(RDiff2)),nl,
1330 remove_weights(SSProp,PropList),
1331 conjunct_predicates(PropList,SortedProp).
1332 % translate:print_bexpr(SortedProp).
1333
1334 remove_weights([],[]).
1335 remove_weights([prop(_W,_Nr,E)|T],[E|RT]) :- remove_weights(T,RT).
1336
1337 weigh_properties(Pred,Nr,ONr,InL,OutL) :-
1338 decompose_conjunct(Pred,LHS,RHS), % will propagate labels down to conjuncts LHS,RHS
1339 !,
1340 weigh_properties(LHS,Nr,N1,InL,L2),
1341 weigh_properties(RHS,N1,ONr,L2,OutL).
1342 weigh_properties(b(Pred,S,I),Nr,N1,T,[prop(Weight,Nr,b(Pred,S,I))|T]) :-
1343 N1 is Nr+1,
1344 (member(contains_wd_condition,I) -> Weight=32000 % do not move properties with WD info
1345 ; weigh_properties2(Pred,Weight)).
1346 % translate:print_bexpr(b(Pred,S,I)), print(' WEIGHT: '), print(Weight),nl
1347
1348 weigh_properties2(truth,W) :- !, W=1.
1349 weigh_properties2(falsity,W) :- !, W=1.
1350 weigh_properties2(equal(L,R),W) :- weigh_term(L,W1), !,
1351 ( weigh_term(R,W2) -> W is W1*W2
1352 ; W is 3200).
1353 % ; W is W1*20). %causes issue with ParityFunction test
1354 %weigh_properties2(equal(_,R),W) :- weigh_term(R,W2), !, W is W2*20.
1355 weigh_properties2(SOp,W) :- comparison(SOp,L,R),!,
1356 ( (weigh_term(L,W1), weigh_term(R,W2))
1357 -> W is 7+W1+W2 % try and give things like x>10 priority over x>y (to overcome CLP(FD) limitations)
1358 ; W=10).
1359 weigh_properties2(partition(LHS,RHS),W) :- weigh_term(LHS,W1), l_weigh_term(RHS,W2), !, W is W1*W2.
1360 weigh_properties2(not_equal(L,R),W) :- ((id(L),empty(R)) ; (id(R),empty(L))),!, W=1.
1361 weigh_properties2(not_equal(L,R),W) :- weigh_term(L,W1), weigh_term(R,W2),!,
1362 W is 20+W1*W2.
1363 weigh_properties2(_Rest,W) :- W=32000.
1364
1365 comparison(less(L,R),L,R).
1366 comparison(less_equal(L,R),L,R).
1367 comparison(greater(L,R),L,R).
1368 comparison(greater_equal(L,R),L,R).
1369
1370
1371 id(b(identifier(_),_,_)).
1372 empty(b(empty_set,_,_)).
1373 empty(b(empty_sequence,_,_)).
1374
1375 l_weigh_term([],0).
1376 l_weigh_term([H|T],R) :- l_weigh_term(T,TR), weigh_term(H,TH), R is TH+TR.
1377
1378 weigh_term(b(T,_,_),R) :- (weigh_term2(T,R) -> true ; fail). %R=20).
1379
1380 weigh_term2(value(_),1).
1381 weigh_term2(boolean_true,1).
1382 weigh_term2(boolean_false,1).
1383 weigh_term2(empty_set,1).
1384 weigh_term2(empty_sequence,1).
1385 weigh_term2(integer(_),1).
1386 weigh_term2(min_int,1).
1387 weigh_term2(max_int,1).
1388 weigh_term2(string(_),1).
1389 weigh_term2(real(_),1).
1390 weigh_term2(bool_set,2).
1391 weigh_term2(identifier(_),2).
1392 weigh_term2(set_extension(_),3).
1393 weigh_term2(integer_set(_),3).
1394 weigh_term2(interval(L,R),W) :- weigh_term(L,WL), weigh_term(R,WR), W is WL*WR.
1395
1396
1397
1398 b_machine_has_constants_or_properties :-
1399 (b_machine_has_constants -> true
1400 ; (b_get_properties_from_machine(Prop)), \+ is_truth(Prop)).
1401
1402 b_get_machine_operation_parameter_types(OpName,ParTypes) :-
1403 b_get_machine_operation_typed_parameters(OpName,Parameters),
1404 maplist(get_texpr_type,Parameters,ParTypes).
1405
1406 b_get_machine_operation_typed_parameters(Operation,Res) :-
1407 b_get_machine_operation_typed_parameters3(Operation,real_paras_only,Res).
1408 b_get_machine_operation_typed_parameters_for_animation(Operation,Res) :-
1409 b_get_machine_operation_typed_parameters3(Operation,for_animation,Res).
1410
1411 b_get_machine_operation_typed_parameters3(Operation,ForAnim,Res) :-
1412 if(b_get_machine_operation_typed_parameters_aux(Operation,ForAnim,Paras),Res=Paras,
1413 (add_internal_error('Cannot get paras: ',b_get_machine_operation_typed_parameters(Operation,ForAnim,Res)),fail)).
1414 % also recognises SETUP_CONSTANTS & INITIALISE_MACHINE
1415 b_get_machine_operation_typed_parameters_aux('$setup_constants',_,Constants) :-
1416 b_machine_has_constants_or_properties,
1417 b_get_machine_constants(Constants).
1418 b_get_machine_operation_typed_parameters_aux('$initialise_machine',_,Variables) :-
1419 b_get_machine_variables(Variables).
1420 b_get_machine_operation_typed_parameters_aux(OpName,real_paras_only,Parameters) :-
1421 b_get_machine_operation(OpName,_R,Parameters,_Body,_OType,_OpPos).
1422 b_get_machine_operation_typed_parameters_aux(OpName,for_animation,Parameters) :-
1423 b_get_machine_operation_for_animation(OpName,_R,Parameters,_Body).
1424
1425 b_get_machine_operation_parameter_names(OpName,ParaNames) :-
1426 b_get_machine_operation_parameter_names(OpName,real_paras_only,ParaNames).
1427 b_get_machine_operation_parameter_names_for_animation(OpName,ParaNames) :-
1428 b_get_machine_operation_parameter_names(OpName,for_animation,ParaNames).
1429
1430 b_get_machine_operation_parameter_names('@INITIALISATION',ForAnim,ParaNames) :- % for Tcl/Tk
1431 b_get_machine_operation_parameter_names('$initialise_machine',ForAnim,ParaNames).
1432 b_get_machine_operation_parameter_names('@PROPERTIES',ForAnim,ParaNames) :- % for Tcl/Tk
1433 b_get_machine_operation_parameter_names('$setup_constants',ForAnim,ParaNames).
1434 b_get_machine_operation_parameter_names(OpName,ForAnim,ParaNames) :-
1435 b_get_machine_operation_typed_parameters3(OpName,ForAnim,Parameters),
1436 get_texpr_ids(Parameters,ParaNames).
1437
1438 b_get_machine_operation_typed_results('$setup_constants',[]).
1439 b_get_machine_operation_typed_results('$initialise_machine',[]).
1440 b_get_machine_operation_typed_results(OpName,Results) :-
1441 b_get_machine_operation(OpName,Results,_Parameters,_Body,_OType,_OpPos).
1442
1443 b_get_machine_operation_result_names('$setup_constants',[]).
1444 b_get_machine_operation_result_names('$initialise_machine',[]).
1445 b_get_machine_operation_result_names(OpName,ResultNames) :-
1446 b_get_machine_operation(OpName,Results,_Parameters,_Body,_OType,_OpPos),
1447 get_texpr_ids(Results,ResultNames).
1448
1449 b_get_machine_operation(Name,Results,Parameters,Body) :-
1450 ? b_get_machine_operation(Name,Results,Parameters,Body,_OType,_OpPos).
1451
1452 :- public b_get_assertions_from_main_machine_calc/2.
1453 b_get_assertions_from_main_machine_calc(static,FProp) :-
1454 ((b_get_static_assertions_from_machine(Prop),
1455 exclude(is_not_main_assertion,Prop,FProp)) -> true
1456 ; add_error(bmachine,'b_get_assertions_from_main_machine_calc static fails'), FProp=[]).
1457 b_get_assertions_from_main_machine_calc(dynamic,FProp) :-
1458 ((b_get_dynamic_assertions_from_machine(Prop),
1459 exclude(is_not_main_assertion,Prop,FProp)) -> true
1460 ; add_error(bmachine,'b_get_assertions_from_main_machine_calc dynamic fails'), FProp=[]).
1461 is_not_main_assertion(Assertion) :-
1462 get_texpr_pos(Assertion,Pos),
1463 error_manager:position_is_not_in_main_file(Pos).
1464
1465 % get nr of assertions and nr of main assertions for static/dynamic
1466 b_get_assertion_count(StaticOrDynamic,NrAll,NrMain) :-
1467 ? b_get_assertions(all,StaticOrDynamic,A), length(A,NrAll),
1468 b_get_assertions_from_main_machine(StaticOrDynamic,MA),length(MA,NrMain).
1469
1470 b_get_assertions(main,Mode,Ass) :- !,
1471 b_get_assertions_from_main_machine(Mode,Ass).
1472 b_get_assertions(specific(Label),Mode,LabelAss) :- !,
1473 b_get_assertions(all,Mode,Ass),
1474 %maplist(get_texpr_label,Ass,Labels), print(labels(Labels)),nl,
1475 include(has_label(Label),Ass,LabelAss),
1476 (LabelAss=[] -> ajoin(['No ',Mode,' assertion has label: '],Msg),
1477 add_warning(b_get_assertions,Msg,Label) ; true).
1478 b_get_assertions(_,static,Ass) :- b_get_static_assertions_from_machine(Ass).
1479 b_get_assertions(_,dynamic,Ass) :- b_get_dynamic_assertions_from_machine(Ass).
1480 b_main_machine_has_no_assertions :-
1481 b_get_assertions_from_main_machine(static,[]),
1482 b_get_assertions_from_main_machine(dynamic,[]).
1483
1484
1485 %has_label(Label,Expr) :- get_texpr_label(Expr,Label1), format('Labels ~w =? ~w~n',[Label1,Label]), fail.
1486 has_label(Label,Expr) :- get_texpr_label(Expr,Label).
1487
1488 :- public b_get_static_assertions_from_machine_calc/1.
1489 % precompiled: typed assertions (a list of predicates)
1490 b_get_static_assertions_from_machine_calc(Prop) :-
1491 get_section_from_current_machine(assertions,Prop1),
1492 exclude(predicate_uses_variables,Prop1,Prop),!.
1493 b_get_static_assertions_from_machine_calc(Prop) :-
1494 add_error(bmachine,'b_get_static_assertions_from_machine_calc fails'), Prop=[].
1495
1496 :- dynamic b_machine_has_static_assertions/0.
1497 :- public b_machine_has_static_assertions_calc/0.
1498 b_machine_has_static_assertions_calc :-
1499 b_get_static_assertions_from_machine([_|_]).
1500
1501 :- public b_get_unproven_static_assertions_from_machine_calc/1.
1502 b_get_unproven_static_assertions_from_machine_calc(FAssertions) :-
1503 b_get_static_assertions_from_machine(Assertions),
1504 filter_out_proven_assertions(Assertions,FAssertions),!.
1505 b_get_unproven_static_assertions_from_machine_calc(Prop) :-
1506 add_error(bmachine,'b_get_unproven_static_assertions_from_machine_calc fails'), Prop=[].
1507
1508 filter_out_proven_assertions([],[]).
1509 filter_out_proven_assertions([A1|T],R) :-
1510 (is_discharged_assertion(A1)
1511 -> R = TR %, print('Proven: '), translate:print_bexpr(A1),nl
1512 ; R = [A1|TR]),
1513 filter_out_proven_assertions(T,TR).
1514
1515 :- public b_get_dynamic_assertions_from_machine_calc/1.
1516 b_get_dynamic_assertions_from_machine_calc(Prop) :-
1517 get_section_from_current_machine(assertions,Prop1),
1518 include(predicate_uses_variables,Prop1,Prop),!.
1519 b_get_dynamic_assertions_from_machine_calc(Prop) :-
1520 add_error(bmachine,'b_get_dynamic_assertions_from_machine_calc fails'), Prop=[].
1521
1522
1523 :- dynamic b_machine_has_dynamic_assertions/0.
1524 :- public b_machine_has_dynamic_assertions_calc/0.
1525 b_machine_has_dynamic_assertions_calc :-
1526 b_get_dynamic_assertions_from_machine([_|_]).
1527
1528 b_machine_has_assertions :- (b_machine_has_static_assertions -> true ; b_machine_has_dynamic_assertions).
1529
1530 b_machine_has_unproven_assertions :-
1531 b_get_unproven_dynamic_assertions_from_machine([_|_]) -> true
1532 ; b_get_unproven_static_assertions_from_machine([_|_]).
1533
1534
1535 get_all_assertions_from_machine(Assertions) :-
1536 findall(A,((SD=static;SD=dynamic),get_assertions_from_machine(SD,SS),member(A,SS)),Assertions).
1537
1538 get_assertions_from_machine(Type,Assertions) :-
1539 ( Type=(dynamic) ->
1540 (get_preference(use_po,true)
1541 -> b_get_unproven_dynamic_assertions_from_machine(Assertions)
1542 ; b_get_dynamic_assertions_from_machine(Assertions)
1543 )
1544 ; Type=(static) ->
1545 (get_preference(use_po,true)
1546 -> b_get_unproven_static_assertions_from_machine(Assertions)
1547 ; b_get_static_assertions_from_machine(Assertions)
1548 )
1549 ),
1550 Assertions = [_|_].
1551
1552 :- public b_get_unproven_dynamic_assertions_from_machine_calc/1.
1553 b_get_unproven_dynamic_assertions_from_machine_calc(FAssertions) :-
1554 b_get_dynamic_assertions_from_machine(Assertions),
1555 filter_out_proven_assertions(Assertions,FAssertions),!.
1556 b_get_unproven_dynamic_assertions_from_machine_calc(Prop) :-
1557 add_error(bmachine,'b_get_unproven_dynamic_assertions_from_machine_calc fails'), Prop=[].
1558
1559 predicate_uses_variables(Pred) :-
1560 b_get_machine_variables(Vars),
1561 get_texpr_ids(Vars,Ids),
1562 list_to_ord_set(Ids,OrdVars),
1563 find_identifier_uses(Pred,[],UsedVars),
1564 list_to_ord_set(UsedVars,OrdUsedVars),
1565 ord_intersect(OrdVars,OrdUsedVars).
1566
1567 :- public b_get_initialisation_from_machine_calc/2.
1568 % precompiled: typed initialisation (a substitution)
1569 b_get_initialisation_from_machine_calc(Init,OType) :-
1570 get_section_from_current_machine(initialisation,Init),
1571 ( get_texpr_expr(Init,rlevent(_Name,_Section,_Status,Params,_Guard,_Theorems,_Actions,_VWitnesses,_PWitnesses,_Unmod,_AbstractEvents)) ->
1572 get_operation_type(Init,'INITIALISATION',Params,OType)
1573 ;
1574 OType = classic).
1575 % precompiled: operations, Name is in atomic form, Results and Parameters are lists
1576 % of typed identifiers, Body is a typed substitution
1577
1578 b_safe_get_initialisation_from_machine(Init,OType) :-
1579 if(b_get_initialisation_from_machine(Init,OType),true,
1580 add_error(bmachine,'Machine has no INITIALISATION clause')).
1581
1582
1583 :- volatile b_machine_operation_names_in_reverse_order/1.
1584 :- dynamic b_machine_operation_names_in_reverse_order/1.
1585 % a list of operation names in reverse order; this way we can randomize the
1586 % generation of the successor states
1587 precompile_operation_names_in_reverse_order :-
1588 retractall(b_machine_operation_names_in_reverse_order(_)),
1589 ? b_get_machine_operation(Name,_Results,_Parameters,_Body,_OType,_OpPos),
1590 asserta(b_machine_operation_names_in_reverse_order(Name)),
1591 fail.
1592 precompile_operation_names_in_reverse_order.
1593
1594 :- use_module(specfile, [animation_minor_mode/1, classical_b_mode/0]).
1595 :- use_module(extrasrc(b_expression_sharing),[cse_optimize_substitution/2]).
1596 :- public b_get_machine_operation_calc/6.
1597 b_get_machine_operation_calc(Name,Results,Parameters,NewBody,OType,OpPos) :-
1598 %well_def_analyser:get_hyps_for_top_level_operations([],Hyps),
1599 is_ground(Name,NameGround),
1600 get_section_from_current_machine(operation_bodies,Ops),
1601 get_texpr_expr(Op,operation(TId,Results,Parameters,Body)),
1602 get_texpr_id(TId,op(Name)),
1603 ? member(Op,Ops),
1604 % remove choicepoints when name was ground
1605 (NameGround==ground -> !; true),
1606 get_operation_type(Op,Name,Parameters,OType),
1607 (get_texpr_pos(TId,OpPos) -> true ; OpPos = unknown),
1608 ( get_preference(use_common_subexpression_also_for_substitutions,true),
1609 get_preference(use_common_subexpression_elimination,true),
1610 \+ animation_minor_mode(eventb) % CSE_SUBST not yet available for Event-B
1611 -> debug_println(19,applying_cse_to(Name)),
1612 cse_optimize_substitution(Body,OpBody)
1613 ; OpBody = Body),
1614 NewBody=OpBody.
1615
1616 b_get_machine_operation_signature(Name,SignatureStr) :-
1617 b_get_machine_operation_calc(Name,Results,Parameters,_,_,_),
1618 get_texpr_ids(Parameters,PIds),
1619 ajoin_with_sep(PIds,',',Args),
1620 (Results = []
1621 -> ajoin([Name,'(',Args,')'],SignatureStr)
1622 ; get_texpr_ids(Results,RIds),
1623 ajoin_with_sep(RIds,',',Res),
1624 ajoin([Res,'<--',Name,'(',Args,')'],SignatureStr)
1625 ).
1626
1627 %well_def_analyser:transform_machine_operation(Name,Results,Parameters,OpBody,Hyps,[create_not_discharged_msg(message)],NewBody).
1628 get_operation_type([],_Name,_Parameters,classic).
1629 get_operation_type(Op,Name,Parameters,OType) :-
1630 get_texpr_info(Op,Info),
1631 ( member(eventb(_),Info) ->
1632 OType=eventb_operation(SortedChangeSet,Ps,OpPattern),
1633 member(modifies(ChangeSet),Info),!,
1634 sort(ChangeSet,SortedChangeSet), % maybe not necessary ?
1635 same_length(Parameters,Ps),
1636 OpPattern =.. [Name|Ps]
1637 ;
1638 OType=classic).
1639
1640 :- volatile get_operation_info/2, get_operation_description_template_expr/2.
1641 :- dynamic get_operation_info/2, get_operation_description_template_expr/2.
1642 :- public get_operation_info_calc/2, get_operation_description_template_expr_calc/2.
1643 % precompiled: operation infos
1644 get_operation_info_calc(OpName,Info1) :-
1645 get_section_from_current_machine(operation_bodies,Ops),
1646 create_texpr(operation(TId,_Results,_Parameters,_Body),_,Info1,TOp), % rlevent()
1647 get_texpr_id(TId,op(OpName)),
1648 ? member(TOp,Ops).
1649
1650 b_get_operation_description(OpName,Desc) :-
1651 get_operation_info(OpName,Infos),
1652 member(description(Desc),Infos).
1653
1654 % get a typed string expression that can compute an operation description (based on vars, paras, ...)
1655 get_operation_description_template_expr_calc(OpName,TemplateStringExpr) :-
1656 get_error_context(Context),
1657 call_cleanup(get_op_desc_template_expr_calc2(OpName,TemplateStringExpr),restore_error_context(Context)).
1658
1659 get_op_desc_template_expr_calc2(OpName,TemplateStringExpr) :-
1660 ? get_operation_info(OpName,Infos),
1661 member(description(Desc),Infos),
1662 (member(description_position(OpPos),Infos)
1663 -> true
1664 ; get_info_pos(Infos,OpPos)
1665 % Unfortunately this is the entire position from beginning of operation to desc label */
1666 ),
1667 atom(Desc),
1668 set_error_context(checking_context('Checking description template for operation: ',OpName)),
1669 transform_string_template(Desc,OpPos,RawTemplateExpr),
1670 %translate:print_raw_bexpr(RawTemplateExpr),nl,
1671 GenerateParseErrors=gen_parse_warnings_for(OpPos),
1672 get_machine_operation_typing_scope(OpName,Scope,[]),
1673 % it could be that the template uses abstract variables that are no longer accessible
1674 b_type_only(RawTemplateExpr,Scope,Type,TemplateStringExpr,GenerateParseErrors),
1675 (debug_mode(off) -> true
1676 ; format('Template description expression for operation ~w:~n ',[OpName]),
1677 translate:print_bexpr(TemplateStringExpr),nl
1678 ),
1679 (Type=string -> true ; add_internal_error('Not string type:',Type)).
1680
1681
1682 :- public b_top_level_operation_calc/1.
1683 % precompiled: operation names (in atomic form) of top-level operations (promoted operations)
1684 b_top_level_operation_calc(Name) :-
1685 is_ground(Name,NameGround),
1686 get_section_from_current_machine(promoted,Promoted),
1687 get_texpr_id(TId,op(Name)),
1688 ? member(TId,Promoted),
1689 (NameGround==ground -> !; true).
1690 :- public b_get_promoted_machine_operations_calc/1.
1691 b_get_promoted_machine_operations_calc(Ops) :-
1692 get_section_from_current_machine(promoted,Ops).
1693
1694 :- volatile b_top_level_feasible_operation/1.
1695 :- dynamic b_top_level_feasible_operation/1.
1696 :- public b_top_level_feasible_operation_calc/1.
1697 % filter out operations which are commented out statically by using 1=2 or similar in guard
1698 ?b_top_level_feasible_operation_calc(Name) :- b_top_level_operation(Name),
1699 b_get_machine_operation(Name,_,_,Body,_,_Pos),
1700 \+ infeasible_tsubst(Body).
1701 % TO DO: investigate how to link up with cbc feasibility analysis
1702
1703 infeasible_tsubst(b(S,_,_)) :- infeasible_subst(S).
1704 infeasible_subst(precondition(G,_)) :- is_falsity(G).
1705 infeasible_subst(select([b(select_when(G,_),_,_)])) :- is_falsity(G).
1706 infeasible_subst(any(_,G,_)) :- is_falsity(G).
1707
1708 % this succeeds not just for top-level operations
1709 %b_is_operation_name(Name) :- b_get_machine_operation(Name,_,_,_,_,_). is slower
1710 :- public b_is_operation_name_calc/1.
1711 b_is_operation_name_calc(Name) :-
1712 ? b_get_machine_operation(Name,_,_,_,_,_).
1713
1714 b_get_operation_pos(Name,Pos) :-
1715 ? b_get_machine_operation(Name,_,_,_,_,Pos).
1716
1717 b_get_operation_variant(Name,ConvOrAnt,Variant) :-
1718 b_get_machine_operation(Name,_,_,TBody),
1719 get_texpr_expr(TBody,Body),
1720 Body = rlevent(Name,_Section,Status,
1721 _Params,_Guard,_Theorems,_Actions,_VWitnesses,_PWitnesses,_Unmod,_AbstractEvents),
1722 % TO DO: look maybe higher up in refinement hierarchy
1723 get_texpr_expr(Status,S),
1724 functor(S,ConvOrAnt,1),
1725 (ConvOrAnt = convergent ; ConvOrAnt = anticipated),
1726 arg(1,S,Variant).
1727
1728 b_machine_has_operations :-
1729 (b_is_operation_name(_) -> true).
1730 % -----------------------------
1731
1732
1733 % the names of definitions which have a given Prefix,
1734 % Type is expression or predicate, Name is an atomic name
1735 b_definition_prefixed(Type,Prefix,Suffix,Name,Pos) :-
1736 safe_atom_chars(Prefix,PrefixChars,b_definition_prefixed1),
1737 append(PrefixChars,SuffixChars,FullChars),
1738 (ground(Suffix) -> safe_atom_chars(Suffix,SuffixChars,b_definition_prefixed2),
1739 safe_atom_chars(Name,FullChars,b_definition_prefixed3)
1740 ; true),
1741 ? b_get_definition_with_pos(Name,Type,Pos,_,_,_),
1742 safe_atom_chars(Name,FullChars,b_definition_prefixed4),
1743 safe_atom_chars(Suffix,SuffixChars,b_definition_prefixed5).
1744
1745 % TODO: should we also look for theory direct definitions for Event-B models?
1746 % :- use_module(bmachine_eventb,[stored_operator_direct_definition/8]).
1747 % stored_operator_direct_definition(Id,_Proj,_Thy,Parameters,_Def,_WD,_TP,_Kind),
1748 % or add auxiliary definition files for Event-B models
1749
1750
1751 % get definitions in alphabetical order of name:
1752 % predictable order is relevant for SVG_OBJECTS to know which objects are on top of each other
1753 b_sorted_b_definition_prefixed(Type,DEFPREFIX,DefName,DefPos) :-
1754 b_or_z_mode, % fail silently if we are not B/Z/TLA+/Alloy mode as machine not pre-compiled
1755 sorted_list_of_defs(Type,DEFPREFIX,SortedList),
1756 ? member(def(DefName,DefPos),SortedList).
1757 sorted_list_of_defs(Type,DEFPREFIX,SortedList) :-
1758 findall(def(DefName,DefPos),
1759 b_definition_prefixed(Type,DEFPREFIX,_Tail,DefName,DefPos),
1760 List),
1761 sort(List,SortedList).
1762
1763 :- use_module(bmachine_construction,[type_open_formula/8]).
1764 type_check_definitions :-
1765 temporary_set_preference(allow_untyped_identifiers,true_with_string_type,CHNG), % we may not have all identifiers visible
1766 get_error_context(Context),
1767 call_cleanup(type_check_definitions2,restore_error_context(Context)),
1768 reset_temporary_preference(allow_untyped_identifiers,CHNG).
1769 type_check_definitions2 :-
1770 get_preference(type_check_definitions,true),
1771 full_b_machine(Machine),
1772 b_get_definition_with_pos(Name,Type,DefPos,Args,RawExpr,_Deps),
1773 % TO DO: do not re-analyse definitions already analysed for ANIMATION_FUNCTION,...
1774 (Type = predicate ; Type=expression), % can we also allow substitutions ?
1775 debug_format(9,'Type checking DEFINITION ~w~n',[Name]),
1776 set_error_context(checking_context('Type checking DEFINITION: ',Name)),
1777 Scope = [variables], % prob_ids(visible),
1778 %type_with_errors(RawExpr,Scope,_,_TExpr),
1779 AllowNewIds=true,
1780 % TO DO: improve solution below, e.g., delete Args from visible variables or rename Args to fresh ids!
1781 (Args=[] -> RawExpr2=RawExpr
1782 ; Type=predicate -> RawExpr2 = exists(none,Args,conjunct(none,truth(none),RawExpr)) % wrap Args into quantifier, avoid clash with variables,... ; conjunct used to avoid warnings about body of exists
1783 ; RawExpr2=exists(none,Args,equal(none,RawExpr,RawExpr)) % TODO: better solution to avoid duplicating RawExpr
1784 ),
1785 (type_open_formula(RawExpr2,Scope,AllowNewIds,Machine,FType,Identifiers,_TPred,Errors) % maybe no need to run cleanup?
1786 -> Errors = [_|_],
1787 format('Error for DEFINITION ~w of type ~w over identifiers ~w~n',[Name,FType,Identifiers]),
1788 add_all_perrors_in_context_of_used_filenames(Errors,definition_type_error,error),
1789 fail
1790 % TO DO: check for local clashes?
1791 ; add_error(bmachine,'Type checking DEFINITION failed: ',Name,DefPos)
1792 ),
1793 fail.
1794 type_check_definitions2 :- debug_format(9,'Finished type checking DEFINITIONs~n',[]).
1795
1796 b_get_definition(Name,DefType,Args,RawExpr,Deps) :-
1797 ? b_get_definition_with_pos(Name,DefType,_DefPos,Args,RawExpr,Deps).
1798
1799 :- public portray_defs/0. % debugging utility
1800 portray_defs :-
1801 b_get_definition_with_pos(Name,DefType,DefPos,_Args,_RawExpr,_),
1802 add_message(bmachine,'DEFINITION: ',Name:DefType,DefPos),fail.
1803 portray_defs.
1804
1805 b_get_definition_with_pos(Name,DefType,DefPos,Args,RawExpr,Deps) :- %print(get_def(Name)),nl,
1806 get_section_from_current_machine(definitions,Defs),
1807 ? member(definition_decl(Name,DefType,DefPos,Args,RawExpr,Deps),Defs).
1808 b_get_definition_with_pos(Name,DefType,DefPos,Args,RawExpr,Deps) :- %print(get_def(Name)),nl,
1809 additional_configuration_machine(_MchName,Mch),
1810 get_section(definitions,Mch,Defs),
1811 member(definition_decl(Name,DefType,DefPos,Args,RawExpr,Deps),Defs).
1812 %flush_output,write(additional_def(Name,DefType,Deps)),nl,flush_output.
1813
1814
1815 :- use_module(input_syntax_tree,[raw_update_file_nrs/3]).
1816 :- volatile additional_configuration_machine/2.
1817 :- dynamic additional_configuration_machine/2.
1818 % load an additional definitions file for ViB configuration or CUSTOM_GRAPH features
1819 % useful for Event-B, ... models
1820 b_load_additional_definitions_file(File) :-
1821 Options=[],
1822 catch(load_b_machine_as_term(File,Machine,Options),
1823 parse_errors(Errors),
1824 (add_all_perrors_in_context_of_used_filenames(Errors,parse_error,error),fail)),
1825 b_load_additional_definitions_from_term(Machine).
1826
1827 b_load_additional_definitions_from_list_of_facts(ListOfFacts) :-
1828 load_b_machine_list_of_facts_as_term(ListOfFacts, Machine),
1829 b_load_additional_definitions_from_term(Machine).
1830
1831 b_load_additional_definitions_from_term(complete_machine(MainName, Machines, Filenames)) :-
1832 maplist(add_additional_filename,Filenames,NewNrs),
1833 member(definition_file(_,Defs),Machines),
1834 Defs = definitions(_Pos,_List),
1835 raw_update_file_nrs(Defs,NewNrs,NewDefs),
1836 bmachine_construction:extract_only_definitions(MainName,[NewDefs],DefsMachine,Errs),
1837 add_all_perrors_in_context_of_used_filenames(Errs,definition_type_error,error),
1838 retractall(additional_configuration_machine(MainName,_)),
1839 assert(additional_configuration_machine(MainName,DefsMachine)),
1840 b_machine_recompile_for_new_defs.
1841
1842
1843
1844
1845 % the next calls get typed definitions without parameters:
1846 % (To treat definitions with parameters one would have to add the parameters to the type environment, see type_check_definitions2)
1847 b_get_typed_predicate_definition(Name,Scope,ResTExpr) :-
1848 b_get_definition(Name,predicate,[],RawExpr,_Deps),
1849 type_with_errors_in_context(RawExpr,Scope,_,TExpr,machine_context,error),
1850 ResTExpr=TExpr. % Do unification after to not prevent generation of type errors.
1851 b_get_typed_expression_definition(Name,Scope,ResTExpr) :-
1852 b_get_definition(Name,expression,[],RawExpr,_Deps),
1853 type_with_errors_in_context(RawExpr,Scope,_,TExpr,machine_context,error),
1854 ResTExpr=TExpr. % Do unification after to not prevent generation of type errors, e.g., test 1691
1855 b_get_true_expression_definition(Name) :-
1856 b_get_typed_expression_definition(Name,[variables],PF),
1857 PF = b(boolean_true,boolean,_).
1858 %b_get_typed_subst_definition(Name,Scope,Parameters,TExpr) :-
1859 % temporary_set_preference(allow_local_operation_calls,true,CHNG),
1860 % b_get_definition(Name,substitution,Parameters,RawExpr,_Deps),
1861 % type_with_errors(RawExpr,[operation_bodies|Scope],_,TExpr), % need to remove variables to avoid clash warnings
1862 % reset_temporary_preference(allow_local_operation_calls,CHNG).
1863 b_get_typed_definition(Name,Scope,TExpr) :-
1864 ? b_get_definition(Name,_DefType,[],RawExpr,_Deps),
1865 type_with_errors_in_context(RawExpr,Scope,_,TExpr,machine_context,error).
1866
1867 % the following does not send errors to error_manager:
1868 b_get_typed_definition_with_error_list(Name,Scope,TExpr,ErrorsAndWarnings,Success) :-
1869 ? b_get_definition(Name,_DefType,[],RawExpr,_Deps),
1870 b_type_expression(RawExpr,Scope,_Type,TExpr,ErrorsAndWarnings),
1871 (no_real_perror_occurred(ErrorsAndWarnings) -> Success=true ; Success=false).
1872
1873 type_with_errors(RawExpr,Scope,Type,TExpr) :-
1874 type_with_errors_in_context(RawExpr,Scope,Type,TExpr,not_in_machine_context([]),error).
1875
1876
1877 type_with_errors_in_context(RawExpr,Scope,Type,TExpr,Context,ErrOrWarn) :- % print(scope(Scope)),nl,
1878 b_type_expression(RawExpr,Scope,Type,TExpr,Errors),!,
1879 (Context=not_in_machine_context(Filenames)
1880 -> add_all_perrors(Errors,Filenames,type_expression_error,ErrOrWarn) % [] for REPL, or JSON file for VisB
1881 ; add_all_perrors_in_context_of_used_filenames(Errors,type_expression_error,ErrOrWarn)
1882 ),
1883 no_real_perror_occurred(Errors). % check that we have no errors, just warnings
1884
1885 % here we do not add perrors; just fail
1886 type_without_errors(RawExpr,Scope,Type,TExpr) :-
1887 b_type_expression(RawExpr,Scope,Type,TExpr,Errors),!,
1888 no_real_perror_occurred(Errors).
1889
1890
1891 b_type_open_predicate_with_errors(OptionalQuantifier,RawPred,Scope,TPred) :-
1892 b_type_open_predicate(OptionalQuantifier,RawPred,Scope,TPred,Errors),
1893 add_all_perrors(Errors,[],type_expression_error),
1894 no_real_perror_occurred(Errors).
1895 b_type_open_predicate(OptionalQuantifier,RawPred,Scope,TPred,Errors) :-
1896 b_type_open_predicate_for_full_b_machine(_Machine,OptionalQuantifier,RawPred,Scope,TPred,Errors).
1897 b_type_open_predicate_for_full_b_machine(Machine,OptionalQuantifier,RawPred,Scope,TPred,Errors) :-
1898 (var(Machine) -> full_b_machine(Machine) ; true),
1899 replace_prob_set_elements_in_scope(Scope,Scope1),
1900 type_open_predicate_with_quantifier(OptionalQuantifier,RawPred,Scope1,Machine,TPred,Errors),!.
1901 b_type_open_exists_predicate(Raw,Typed,Errors) :-
1902 b_type_open_predicate(open(exists),Raw,[prob_ids(visible),variables],Typed,Errors).
1903
1904 b_type_expression(RawExpr,_Scope,Type,TExpr,Errors) :-
1905 b_type_literal(RawExpr,T,TE),!,
1906 Type=T,TExpr=TE,Errors=[].
1907 b_type_expression(RawExpr,Scope,Type,TExpr,Errors) :-
1908 b_type_expression_for_full_b_machine(_,RawExpr,Scope,Type,TExpr,Errors).
1909
1910 % type literals without setting up scope, ...
1911 % TODO: also use for type_in_machine_l
1912 b_type_literal(boolean_false(Pos),boolean,b(boolean_false,boolean,[nodeid(Pos)])).
1913 b_type_literal(boolean_true(Pos),boolean,b(boolean_true,boolean,[nodeid(Pos)])).
1914 b_type_literal(integer(Pos,Int),integer,b(integer(Int),integer,[nodeid(Pos)])).
1915 b_type_literal(real(Pos,R),real,b(real(R),real,[nodeid(Pos)])).
1916 b_type_literal(string(Pos,Atom),string,b(string(Atom),string,[nodeid(Pos)])).
1917
1918
1919 b_type_expression_for_full_b_machine(M,RawExpr,Scope,Type,TExpr,Errors) :-
1920 b_type_expressions_l(M,[RawExpr],Scope,[Type],[TExpr],Errors).
1921
1922 b_type_expressions_l(Machine,RawExprs,Scope,Types,TExprs,Errors) :-
1923 (var(Machine) -> full_b_machine(Machine) ; true),
1924 % in case you type check multiple expressions for a complex machine it is better to extract the machine once
1925 replace_prob_set_elements_in_scope(Scope,Scope1),
1926 % we need this, for example for tcltk_check_state_sequence_from_file, when deferred set elements written by TLC are in the file
1927 type_in_machine_l(RawExprs,Scope1,Machine,Types,TExprs,Errors),!.
1928
1929 replace_prob_set_elements_in_scope(Scope,Res) :- var(Scope),!,
1930 add_internal_error('Scope is a variable (use, e.g., [constants,variables,operation_bodies,...]):',replace_prob_set_elements_in_scope(Scope,Res)),
1931 Res=Scope.
1932 replace_prob_set_elements_in_scope(Scope,NewScope) :-
1933 ? ( select(prob_ids(AllOrVisible),Scope,identifier(Ids),NewScope) -> % replaces prob by deferred set element identifiers
1934 % for example if we have SETS PID then we would have PID1,... in Ids unless PID1 is known to be another identifier
1935 b_get_prob_deferred_set_elements(DefIDs,AllOrVisible),
1936 exclude(known_identifier,DefIDs,Ids) % exclude those ids that would clash
1937 % TO DO: add option to translate_identifiers using translate:keyword_to_id_cache
1938 ;
1939 Scope = NewScope).
1940
1941
1942 known_identifier(X) :- get_texpr_id(X,ID),
1943 (bmachine:b_is_constant(ID,_) ;
1944 bmachine:b_is_variable(ID,_)).
1945
1946 % ------------------------
1947
1948 % a generic predicate to find all kinds of identifiers
1949
1950 :- use_module(b_global_sets,[b_global_set/1, is_b_global_constant/3]).
1951 :- use_module(probsrc(kernel_freetypes),[registered_freetype/2, freetype_case_db/3]).
1952 :- use_module(probsrc(bmachine_eventb), [ stored_operator/2]).
1953 %! mode get_machine_identifiers(+Category, -ListOfIdentifiers)
1954 get_machine_identifiers(machines,MN) :-
1955 findall(FID, (b_filenumber(FID,Type,_,_),Type \= def),MN).
1956 get_machine_identifiers(definition_files,DFN) :-
1957 findall(FID, b_filenumber(FID,def,_,_),DFN).
1958 get_machine_identifiers(definitions,DN) :-
1959 findall(DefID,b_get_definition(DefID,_,_,_,_),DN).
1960 get_machine_identifiers(sets,Sets) :-
1961 findall(GS,b_global_set(GS),Sets).
1962 get_machine_identifiers(set_constants,Csts) :-
1963 findall(Cst,is_b_global_constant(_GS,_,Cst),Csts).
1964 get_machine_identifiers(constants,CN) :-
1965 b_get_machine_constants(Constants),
1966 get_texpr_ids(Constants,CN).
1967 get_machine_identifiers(freetypes,FN) :-
1968 findall(FID,((registered_freetype(F,_) ; freetype_case_db(F,_,_)),functor(F,FID,_)),FN).
1969 get_machine_identifiers(operators,FN) :-
1970 findall(Name,stored_operator(Name,_Kind),FN). % we could exclude Kind=datatype_definition, as listed in freetypes?
1971 get_machine_identifiers(variables,VN) :-
1972 b_get_machine_variables(Variables),
1973 get_texpr_ids(Variables,VN).
1974 get_machine_identifiers(operations,Ops) :-
1975 findall(Op,b_top_level_operation(Op),Ops).
1976
1977 get_machine_identifiers_with_pp_type(machines,MN) :-
1978 findall([FID,'Machine'], (b_filenumber(FID,Type,_,_),Type \= def),MN).
1979 get_machine_identifiers_with_pp_type(definition_files,DFN) :-
1980 findall([FID,'Definition file'], b_filenumber(FID,def,_,_),DFN).
1981 get_machine_identifiers_with_pp_type(definitions,DN) :-
1982 findall([DefID,DefType],b_get_definition(DefID,DefType,_,_,_),DN).
1983 get_machine_identifiers_with_pp_type(sets,Sets) :-
1984 findall([GS,GS],b_global_set(GS),Sets).
1985 get_machine_identifiers_with_pp_type(set_constants,Csts) :-
1986 findall([Cst,GS],is_b_global_constant(GS,_,Cst),Csts).
1987 get_machine_identifiers_with_pp_type(constants,CN) :-
1988 b_get_machine_constants(Constants),
1989 maplist(extract_id_and_pp_type,Constants,CN).
1990 %get_machine_identifiers_with_pp_type(freetypes,FN) :-
1991 % findall([FID,FID],((registered_freetype(F,_) ; freetype_case_db(F,_,_)),functor(F,FID,_)),FN).
1992 get_machine_identifiers_with_pp_type(operators,FN) :-
1993 findall([Name,''],stored_operator(Name,_Kind),FN). % we could exclude Kind=datatype_definition, as listed in freetypes?
1994 get_machine_identifiers_with_pp_type(variables,VN) :-
1995 b_get_machine_variables(Variables),
1996 maplist(extract_id_and_pp_type,Variables,VN).
1997 get_machine_identifiers_with_pp_type(operations,Ops) :-
1998 findall([Op,'Operation'],b_top_level_operation(Op),Ops).
1999
2000 :- use_module(bsyntaxtree,[get_texpr_id/2, get_texpr_type/2]).
2001 :- use_module(translate,[pretty_type/2]).
2002 extract_id_and_pp_type(TId,[Id,PPType]) :-
2003 get_texpr_id(TId,Id),
2004 get_texpr_type(TId,Type),
2005 pretty_type(Type,PPType).
2006
2007 :- use_module(b_global_sets,[b_global_deferred_set/1,all_elements_of_type/2]).
2008 :- use_module(input_syntax_tree,[get_raw_position_info/2]).
2009 % try and get source code for an identifier
2010 source_code_for_identifier(ID,constant,Type,OriginStr,OriginTerm,Source) :- b_is_constant(ID),!,
2011 get_constant_type_and_origin(ID,Type,OriginStr,OriginTerm),
2012 findall(Def,get_constant_definition(ID,Def),AllDefs),
2013 (AllDefs=[_|_] -> conjunct_predicates(AllDefs,Source)
2014 ; % try and find other type of predicates defining ID
2015 findall(Pred,get_constant_predicate(ID,Pred),AllPreds),
2016 conjunct_predicates(AllPreds,Source)).
2017 source_code_for_identifier(ID,variable,Type,OriginStr,OriginTerm,Source) :- b_is_variable(ID),!,
2018 get_variable_type_and_origin(ID,Type,OriginStr,OriginTerm),
2019 Source = b(truth,pred,[]). % TO DO: improve
2020 source_code_for_identifier(ID,Kind,Type,OriginStr,OriginTerm,Source) :- b_get_machine_set(ID,TID),!,
2021 (b_global_deferred_set(ID) -> Kind = deferred_set ; Kind = enumerated_set),
2022 Type = set(global(ID)),
2023 all_elements_of_type(ID,All),
2024 translate:translate_span_with_filename(TID,OriginStr), OriginTerm=TID,
2025 Source = b(equal(TID,b(value(All),Type,[])),pred,[]).
2026 source_code_for_identifier(ID,Kind,Type,OriginStr,OriginTerm,Source) :-
2027 global_set_element(ID,GID),!,
2028 (b_global_deferred_set(GID)
2029 -> Kind = deferred_set_element ; Kind = enumerated_set_element),
2030 b_get_machine_set(GID,TGID),
2031 Type = global(ID),
2032 all_elements_of_type(GID,All),
2033 translate:translate_span_with_filename(TGID,OriginStr), OriginTerm=TGID,
2034 Source = b(equal(TGID,b(value(All),set(Type),[])),pred,[]).
2035 source_code_for_identifier(ID,definition,Type,OriginStr,OriginTerm,Source) :-
2036 b_get_definition(ID,DefType,Args,RawExpr,_Deps),!,
2037 Type = DefType,
2038 % Definitions are only present in RAW form
2039 get_raw_position_info(RawExpr,PosInfo),
2040 translate:translate_span_with_filename(PosInfo,OriginStr), % the position info does not always seem to be valid (when coming from DEFINITION FILE) !??! TO DO fix
2041 OriginTerm=PosInfo,
2042 source_code_for_definition(DefType,ID,Args,RawExpr,Source).
2043 source_code_for_identifier(ID,file,Type,OriginStr,OriginTerm,b(string(Source),string,[])) :-
2044 b_filenumber(ID,Kind,_,Filename),
2045 extension_kind(Kind,Type),
2046 !,
2047 ajoin([Type,' ',ID],Source),
2048 OriginTerm =src_position_with_filename(1,0,0,Filename),
2049 OriginStr = Filename.
2050 source_code_for_identifier(ID,Kind,subst,OriginStr,OriginTerm,Source) :-
2051 b_find_operation(ID,Res,TParas,Body,OType),
2052 (OType=classic -> Kind = operation ; Kind=event),
2053 translate:translate_span_with_filename(Body,OriginStr),Body=OriginTerm,
2054 get_texpr_info(Body,Info),
2055 Source=b(operation(b(identifier(ID),subst,[]),Res,TParas,Body),subst,Info).
2056 source_code_for_identifier(ID,assertion,pred,OriginStr,OriginTerm,Assertion) :-
2057 b_get_assertions(all,_,Ass), member(Assertion,Ass),
2058 get_texpr_label(Assertion,ID), OriginTerm = Assertion,
2059 translate:translate_span_with_filename(Assertion,OriginStr).
2060 source_code_for_identifier(ID,invariant,pred,OriginStr,OriginTerm,Invariant) :-
2061 b_get_invariant_from_machine(C), conjunction_to_list(C,L), member(Invariant,L),
2062 get_texpr_label(Invariant,ID), OriginTerm = Invariant,
2063 translate:translate_span_with_filename(Invariant,OriginStr).
2064 % TO DO: look for invariant labels as ids ?
2065
2066 :- use_module(tools,[ split_last/4 ]).
2067 b_find_operation(ID,Res,TParas,Body,OType) :-
2068 b_get_machine_operation(ID,Res,TParas,Body,OType,_Pos).
2069 b_find_operation(ID,Res,TParas,Body,OType) :-
2070 b_get_machine_operation(ID2,Res,TParas,Body,OType,_Pos),
2071 split_last(ID2, '.', _, ID).
2072
2073 extension_kind(mch,'MACHINE').
2074 extension_kind(ref,'REFINEMENT').
2075 extension_kind(def,'DEFINITIONS FILE').
2076 extension_kind(imp,'IMPLEMENTATION').
2077
2078 source_code_for_definition(predicate,ID,_,RawExpr,Source) :-
2079 b_type_open_exists_predicate(RawExpr,Typed,Errors),
2080 (no_real_perror_occurred(Errors) -> true ; debug_println(9,errs(ID,Errors))),
2081 Source=Typed.
2082 source_code_for_definition(expression,ID,Args,RawExpr,Source) :-
2083 % TO DO: add parameters to avoid type errors; but we get Typed anyway
2084 b_type_expression(RawExpr,[prob_ids(visible),variables],Type,Typed,Errors),
2085 (no_real_perror_occurred(Errors) -> true ; debug_println(9,errs(ID,Args,Type,Errors))),
2086 Source=Typed.
2087 % TO DO: treate substitutions
2088 source_code_for_definition(DefType,ID,_Args,_RawExpr,Source) :-
2089 Source=b(identifier(ID),DefType,[]).
2090
2091 :- use_module(b_global_sets,[lookup_global_constant/2,prob_deferred_set_element/4]).
2092 global_set_element(ID,GlobalSetID) :- lookup_global_constant(ID,fd(_,GlobalSetID)).
2093 global_set_element(ID,GlobalSetID) :-
2094 prob_deferred_set_element(GlobalSetID,_Elem,ID,all).
2095
2096 get_constant_span(ID,Span) :-
2097 b_get_machine_constants(Constants),
2098 TID = b(identifier(ID),_,Span),
2099 member(TID,Constants).
2100
2101 get_constant_type_and_origin(ID,Type,OriginStr,OriginTerm) :-
2102 b_get_machine_constants(Constants),
2103 TID = b(identifier(ID),Type,_Infos),
2104 member(TID,Constants),
2105 % we could also use member(origin(Origin),Infos)
2106 translate:translate_span_with_filename(TID,OriginStr), OriginTerm=TID.
2107 get_variable_type_and_origin(ID,Type,OriginStr,OriginTerm) :-
2108 b_get_machine_variables(Vars),
2109 TID = b(identifier(ID),Type,_Infos),
2110 member(TID,Vars),
2111 % we could also use member(origin(Origin),Infos)
2112 translate:translate_span_with_filename(TID,OriginStr), OriginTerm=TID.
2113
2114 get_constant_definition(ID,FullDef) :-
2115 b_get_properties_from_machine(Prop),
2116 EqDef = b(equal(LHS,RHS),pred,_),
2117 member_in_conjunction_cse(FullDef,EqDef,Prop),
2118 (get_texpr_id(LHS,ID) ; get_texpr_id(RHS,ID)).
2119
2120 get_constant_predicate(ID,FullPred) :-
2121 b_get_properties_from_machine(Prop),
2122 member_in_conjunction_cse(FullPred,Pred,Prop),
2123 involves_id(Pred,ID).
2124 involves_id(ID,b(E,_,_)) :- involves_id_aux(E,ID).
2125 involves_id_aux(member(LHS,_),ID) :- get_texpr_id(LHS,ID).
2126 involves_id_aux(subset(LHS,_),ID) :- get_texpr_id(LHS,ID).
2127 involves_id_aux(subset_strict(LHS,_),ID) :- get_texpr_id(LHS,ID).
2128
2129 :- volatile b_get_machine_setscope/2.
2130 :- dynamic b_get_machine_setscope/2.
2131 :- public b_get_machine_setscope_calc/2.
2132 % precompiled: definitions of the form "scope_SET == Expr",
2133 % Set is the name of the Set, TExpr the typed expression
2134 b_get_machine_setscope_calc(Set,TExpr) :-
2135 ? b_definition_prefixed(expression, scope_, Set, Name,_),
2136 % TO DO: check if it is a SET
2137 ? b_get_typed_definition(Name,[constants],TExpr). % [constants] scope so that we have access to other definitions
2138
2139
2140 % get a specific MAX_OPERATIONS Value for an operation
2141 :- volatile b_get_machine_operation_max/2.
2142 :- dynamic b_get_machine_operation_max/2.
2143 :- public b_get_machine_operation_max_calc/2.
2144 % precompiled: definitions of the form "scope_SET == Expr",
2145 % Set is the name of the Set, TExpr the typed expression
2146 b_get_machine_operation_max_calc(Set,MaxOp) :-
2147 b_definition_prefixed(expression, 'MAX_OPERATIONS_', Set, Name,DefPos),
2148 (b_get_typed_definition(Name,[constants],DEF), % scope=constants allows to use other definitions
2149 DEF=b(integer(MaxOp),integer,_)
2150 % TO DO: check if it is an operation
2151 %, MaxOp >= 0 we now use negative numbers for randomised restart
2152 -> true
2153 ; add_warning(b_get_machine_operation_max_calc,'Definition must specify an integer (negative numbers means using randomised restart) ',Name,DefPos),
2154 fail
2155 ).
2156
2157 :- volatile b_get_machine_goal/1.
2158 :- dynamic b_get_machine_goal/1.
2159 :- public b_get_machine_goal_calc/1.
2160 % precompiled: definition of GOAL, a typed predicate
2161 b_get_machine_goal_calc(TPred) :- get_goal(TPred).
2162
2163 b_reset_machine_goal_from_DEFINITIONS :-
2164 get_goal(TPred),
2165 b_set_parsed_typed_machine_goal(TPred).
2166 get_goal(Goal) :-
2167 get_proz_settings(Settings),memberchk(goal(Goal),Settings),!.
2168 get_goal(Goal) :- % print(getting_goal),nl,
2169 get_texpr_type(Goal,pred),
2170 b_get_typed_predicate_definition('GOAL',[variables],Goal).
2171
2172 :- volatile b_get_machine_searchscope/1.
2173 :- dynamic b_get_machine_searchscope/1.
2174 :- public b_get_machine_searchscope_calc/1.
2175 % precompiled: definition of SCOPE, a typed predicate
2176 b_get_machine_searchscope_calc(TPred) :-
2177 get_texpr_type(TPred,pred),
2178 b_get_typed_definition('SCOPE',[variables],TPred).
2179
2180 :- volatile b_get_definition_string_from_machine/3.
2181 :- dynamic b_get_definition_string_from_machine/3.
2182 :- public b_get_definition_string_from_machine_calc/3.
2183 % precompiled: string definitions, Name == "String"
2184 b_get_definition_string_from_machine(Name,String) :-
2185 b_get_definition_string_from_machine(Name,_,String).
2186 b_get_definition_string_from_machine_calc(Name,Pos,String) :-
2187 b_get_definition(Name,expression,[],string(Pos,Str),_Deps),
2188 get_texpr_expr(TExpr,string(String)),
2189 type_with_errors_in_context(string(Pos,Str),[],_,TExpr,machine_context,warning).
2190
2191 get_animation_image(Nr,S) :-
2192 animation_minor_mode(z),
2193 get_proz_animation_function(_,_,Images),!,
2194 nth1(Nr,Images,S).
2195 get_animation_image(Nr,S) :- number(Nr),!,
2196 number_codes(Nr,TailCodes),
2197 /* ANIMATION_IMG */
2198 atom_codes(Def_Name,[65,78,73,77,65,84,73,79,78,95,73,77,71|TailCodes]),
2199 b_get_definition_string_from_machine(Def_Name,S).
2200 get_animation_image(Nr,S) :-
2201 b_get_definition_string_from_machine(Def_Name,S),
2202 /* ANIMATION_IMG */
2203 atom_codes(Def_Name,[65,78,73,77,65,84,73,79,78,95,73,77,71|TailCodes]),
2204 number_codes(Nr,TailCodes).
2205
2206 :- use_module(error_manager,[extract_file_number_and_name/3]).
2207 :- use_module(specfile,[b_or_z_mode/0]).
2208 get_animation_image_source_file(Nr,File) :- b_or_z_mode,
2209 % get source file where Animation image is defined; relevant for finding images
2210 b_get_definition_string_from_machine(Def_Name,Pos,_),
2211 atom_codes(Def_Name,[65,78,73,77,65,84,73,79,78,95,73,77,71|TailCodes]),
2212 number_codes(Nr,TailCodes),
2213 extract_file_number_and_name(Pos,_,File).
2214
2215 get_proz_animation_function(Function,Default,Images) :-
2216 get_proz_settings(Settings),
2217 memberchk(animation_function(Function,Default,Images),Settings).
2218 get_proz_settings(Settings) :-
2219 machine(_,Sections),memberchk(meta/Meta,Sections),
2220 memberchk(proz_settings(Settings),Meta).
2221
2222
2223 :- volatile b_get_machine_animation_function/2.
2224 :- dynamic b_get_machine_animation_function/2.
2225 :- public b_get_machine_animation_function_calc/2.
2226 :- use_module(tools,[safe_number_codes/2]).
2227 :- use_module(bsyntaxtree,[is_set_type/2]).
2228 % precompiled: definition of ANIMATION_FUNCTION, a typed expression
2229 b_get_machine_animation_function_calc(AFun,Nr) :-
2230 get_proz_animation_function(TFun,Default,_),!,
2231 ( Nr = -1, AFun = Default
2232 ; Nr = 0, TFun \= none, AFun=TFun
2233 ).
2234 b_get_machine_animation_function_calc(TFun,Nr) :-
2235 get_definition_with_nr_suffix("ANIMATION_FUNCTION",Nr,Def_Name),
2236 b_get_typed_expression_definition(Def_Name,[variables],TFun), % only type it afterwards; avoid throwing type errors for other definitions
2237 get_texpr_type(TFun,Type),
2238 (is_set_type(Type,couple(_,_)) -> true
2239 ; add_warning(b_get_machine_animation_function_calc,'Illegal type for ANIMATION_FUNCTION: ',Def_Name:Type,TFun),
2240 fail).
2241
2242
2243 :- volatile b_get_machine_heuristic_function/1.
2244 :- dynamic b_get_machine_heuristic_function/1.
2245 :- public b_get_machine_heuristic_function_calc/1.
2246 b_get_machine_heuristic_function_calc(TFun) :- %print(extracting_heuristic_fun(TFun)),nl,
2247 get_texpr_type(TFun,integer),
2248 b_get_typed_expression_definition('HEURISTIC_FUNCTION',[variables],TFun).
2249
2250 :- volatile b_get_machine_animation_expression/2.
2251 :- dynamic b_get_machine_animation_expression/2.
2252 :- public b_get_machine_animation_expression_calc/2.
2253 b_get_machine_animation_expression_calc(STR,AExpr) :- %print(extracting_heuristic_fun(TFun)),nl,
2254 ? useful_animation_expression(STR),
2255 b_get_typed_expression_definition(STR,[variables],AExpr).
2256 b_get_machine_animation_expression_calc(DefName,AExpr) :-
2257 b_definition_prefixed(_,'ANIMATION_EXPRESSION',_,DefName,_DefPos),
2258 b_get_typed_expression_definition(DefName,[variables],AExpr).
2259
2260 %useful_animation_expression('ANIMATION_EXPRESSION'). % for state viewer
2261 useful_animation_expression('GAME_PLAYER'). % for MCTS, should return "min" or "max"
2262 useful_animation_expression('GAME_OVER').
2263 useful_animation_expression('GAME_VALUE').
2264 useful_animation_expression('GAME_MCTS_RUNS').
2265 useful_animation_expression('GAME_MCTS_TIMEOUT').
2266 useful_animation_expression('GAME_MCTS_CACHE_LAST_TREE').
2267
2268
2269 % Custom nodes and edges for a custom graph representation of a state
2270 :- volatile b_get_machine_custom_nodes_function/2, b_get_machine_custom_edges_function/2,
2271 b_get_machine_custom_graph_function/2.
2272 :- dynamic b_get_machine_custom_nodes_function/2, b_get_machine_custom_edges_function/2,
2273 b_get_machine_custom_graph_function/2.
2274 :- public b_get_machine_custom_nodes_function_calc/2.
2275 b_get_machine_custom_nodes_function_calc(TFun,Nr) :-
2276 get_definition_with_nr_suffix("CUSTOM_GRAPH_NODES",Nr,Def_Name),
2277 b_get_typed_expression_definition(Def_Name,[variables],TFun).
2278 :- public b_get_machine_custom_edges_function_calc/2.
2279 b_get_machine_custom_edges_function_calc(TFun,Nr) :-
2280 get_definition_with_nr_suffix("CUSTOM_GRAPH_EDGES",Nr,Def_Name),
2281 b_get_typed_expression_definition(Def_Name,[variables],TFun).
2282 :- public b_get_machine_custom_graph_function_calc/2.
2283 b_get_machine_custom_graph_function_calc(TFun,Nr) :-
2284 get_definition_with_nr_suffix("CUSTOM_GRAPH",Nr,Def_Name), % single function for graph attributes, possibly edges and nodes
2285 b_get_typed_expression_definition(Def_Name,[variables],TFun).
2286
2287
2288 get_definition_with_nr_suffix(Prefix,Nr,Def_Name) :-
2289 ? b_get_definition(Def_Name,expression,[],_RawExpr,_Deps),
2290 atom_codes(Def_Name,AC),
2291 append(Prefix,TailCodes,AC),
2292 (TailCodes=[] -> Nr=0
2293 ; TailCodes = "_DEFAULT" -> Nr = -1
2294 ; safe_number_codes(Nr,TailCodes)).
2295
2296
2297 % ------------------------
2298
2299 :- volatile b_get_constant_represented_inside_global_set/2.
2300 :- dynamic b_get_constant_represented_inside_global_set/2.
2301
2302 :- public b_get_constant_represented_inside_global_set_calc/2.
2303 b_get_constant_represented_inside_global_set_calc(X,GlobalSetName) :-
2304 b_get_disjoint_constants_of_type(GlobalSetName, DisjointConstants,_),
2305 member(X,DisjointConstants). /* X will be integrated into the global_set */
2306
2307
2308 :- volatile b_get_disjoint_constants_of_type/3.
2309 :- dynamic b_get_disjoint_constants_of_type/3.
2310 :- public b_get_disjoint_constants_of_type_calc/3.
2311 b_get_disjoint_constants_of_type_calc(GlobalSetName, DisjointConstants, AllConstantsIDs) :-
2312 b_get_machine_all_constants(Constants), /* get all the constants */
2313 b_get_properties_from_machine(Properties),
2314 ? b_get_machine_set(GlobalSetName),
2315 \+ b_get_named_machine_set(GlobalSetName,_), % not an explicitly enumerated set
2316 find_constants_of_type(Constants,GlobalSetName,AllConstantsIDs,_GSConstants),
2317 find_inequal_global_set_identifiers(AllConstantsIDs,global(GlobalSetName),Properties,DisjointConstants),
2318 DisjointConstants \= [],
2319 debug_println(9,disjoint_enumerated_constants(GlobalSetName,DisjointConstants)).
2320 % TO DO: remove from Properties irrelevant conjuncts; sort AllConstantsIDs by having first those with max disequalities
2321
2322 find_constants_of_type([],_GS,[],[]) :- !.
2323 find_constants_of_type([b(identifier(ID),global(GS),INFO)|T], GS, [ID|IT],
2324 [b(identifier(ID),global(GS),INFO)|TT]) :- !,
2325 find_constants_of_type(T,GS,IT,TT).
2326 find_constants_of_type([b(_,_,_)|T], GS, IT, TT) :- !,
2327 find_constants_of_type(T,GS,IT,TT).
2328 find_constants_of_type(X,GS,_,_) :- print(find_constants_of_type_error(X,GS)),nl,fail.
2329
2330
2331 % ------------------------
2332 :- volatile b_get_all_used_identifiers_in_section/2.
2333 :- dynamic b_get_all_used_identifiers_in_section/2.
2334 :- public b_get_all_used_identifiers_in_section_calc/2.
2335
2336 % Note: may contain var$0 instead of var for becomes_such
2337 b_get_all_used_identifiers_in_section_calc(SECTION,Identifiers) :-
2338 full_b_machine(BMachine),
2339 ? member(SECTION,[constraints,properties,invariant,assertions,
2340 initialisation,operation_bodies]),
2341 findall(I, find_used_identifier_in_machine_section(BMachine,SECTION,I), Ids),
2342 %print(section_ids(SECTION,Ids)),nl,
2343 sort(Ids,Identifiers).
2344
2345 :- volatile b_get_all_used_identifiers/1.
2346 :- dynamic b_get_all_used_identifiers/1.
2347 :- public b_get_all_used_identifiers_calc/1.
2348 :- use_module(library(ordsets),[ord_union/2]).
2349 % Precompiled: b_get_all_used_identifiers_calc/1 returns a list of all
2350 % identifiers used in machine sections that contain expressions and predicates
2351 b_get_all_used_identifiers_calc(Identifiers) :-
2352 findall(I, b_get_all_used_identifiers_in_section(_,I), ListOfList),
2353 ord_union(ListOfList,Identifiers). % ,print(all(Identifiers)),nl.
2354
2355 find_used_identifier_in_machine_section(Machine,Sec,Identifier) :-
2356 % treat it like a list of expressions
2357 ? get_section_texprs(Sec,Machine,TExprs),
2358 % and find all identifiers in each expression
2359 ? member(TExpr,TExprs),
2360 find_identifier_uses(TExpr,[],Ids),
2361 ? member(Identifier,Ids).
2362
2363 :- volatile b_is_unused_constant/1.
2364 :- dynamic b_is_unused_constant/1.
2365 :- public b_is_unused_constant_calc/1.
2366 b_is_unused_constant_calc(UnusedConstant) :-
2367 findall(C,b_is_constant(C),CL), %b_get_machine_constants(Constants), gives typed ids
2368 CL\=[] ,sort(CL,Constants),
2369 b_get_all_used_identifiers_in_section(invariant,I1),
2370 b_get_all_used_identifiers_in_section(assertions,I2),
2371 b_get_all_used_identifiers_in_section(initialisation,I3),
2372 b_get_all_used_identifiers_in_section(operation_bodies,I4),
2373 % TODO: get constants used in VisB definitions
2374 ord_union([I1,I2,I3,I4],UsedIds),
2375 %print(used(UsedIds)),nl,
2376 ord_subtract(Constants,UsedIds,UnusedConstants),
2377 UnusedConstants\=[],
2378 (b_get_machine_variables([]) -> true
2379 ; length(UnusedConstants,NrUC),
2380 (silent_mode(on) -> true
2381 ; (NrUC>10,debug_mode(off),UnusedConstants=[C1,C2|_]) ->
2382 print_message_with_max_depth(unused_constants(NrUC,[C1,C2,'...']),500)
2383 ; print_message_with_max_depth(unused_constants(NrUC,UnusedConstants),500))
2384 ),
2385 member(UnusedConstant,UnusedConstants).
2386
2387
2388 % precompiled: Skel is the operation skeleton, SpecializedInv a typed predicate
2389 % (Skel,SpecializedInv) :-
2390 % b_get_machine_operation(Name,_Res,Params,_Body),
2391 % atom_concat('SIMPLIFIED_INV_OP_',Name,ASNC),
2392 % b_get_typed_definition(ASNC,[variables,identifiers(Params)],SpecializedInv),
2393 % length(Params,Len),
2394 % functor(Skel,Name,Len),
2395 % print(b_specialized_invariant_for_op(Skel)).
2396
2397
2398 get_section_from_current_machine(Section,Content) :-
2399 full_b_machine(BMachine),
2400 get_section(Section,BMachine,Content).
2401
2402 is_ground(X,R) :- ground(X),!,R=ground.
2403 is_ground(_,nonground).
2404
2405 b_set_empty_machine :- debug_println(9,setting_empty_machine),
2406 empty_machine(Main,Machines),
2407 b_set_machine(Main,Machines,[]).
2408
2409 b_get_machine_refinement_hierarchy(Hierarchy) :-
2410 \+ machine(_Name,_M),!,Hierarchy=[]. %No B Machine loaded
2411 b_get_machine_refinement_hierarchy(Hierarchy) :-
2412 get_section_from_current_machine(meta,Infos),
2413 member(hierarchy/Hierarchy,Infos),!.
2414
2415 b_get_refined_machine_name(Machine) :-
2416 b_get_machine_refinement_hierarchy([_Main,Machine|_Rest]).
2417 b_get_refined_ancestors_names(list(AncestorList)) :-
2418 b_get_machine_refinement_hierarchy([_Main|AncestorList]).
2419 b_get_refined_machine(M) :-
2420 get_section_from_current_machine(meta,Infos),
2421 member(refined_machine/M,Infos), !.
2422
2423
2424
2425 b_get_machine_header_position(MachName,Position) :-
2426 get_section_from_current_machine(meta,Infos),
2427 member(header_pos/HeaderPosList,Infos),
2428 % List with elements MachineName/PositionOfMachineHeader
2429 member(MachName/Position,HeaderPosList).
2430
2431 % model type can be system for Atelier-B Event-B
2432 b_get_model_type(M) :-
2433 get_section_from_current_machine(meta,Infos),
2434 member(model_type/M,Infos), !.
2435
2436 % TODO(DP,6.8.2008)
2437 :- volatile b_machine_temp_predicate/1.
2438 :- dynamic b_machine_temp_predicate/1.
2439
2440 %set_temp_predicate(CustomPredicate) :-
2441 % b_parse_machine_predicate(CustomPredicate,TypedPred),
2442 % assert_temp_typed_predicate(TypedPred).
2443 %
2444 %% set a temporary predicate as additional guard
2445 %set_temp_predicate(CustomPredicate,'$initialise_machine') :- !,set_temp_predicate(CustomPredicate).
2446 %set_temp_predicate(CustomPredicate,'$setup_constants') :- !,set_temp_predicate(CustomPredicate).
2447 %set_temp_predicate(CustomPredicate,OpName) :-
2448 % b_parse_machine_operation_pre_post_predicate(CustomPredicate,TypedPred, OpName,true),
2449 % assert_temp_typed_predicate(TypedPred).
2450
2451 % Note: it can be a good idea to use inline_prob_deferred_set_elements_into_bexpr/2 before:
2452 assert_temp_typed_predicate(TypedPred) :-
2453 reset_temp_predicate,
2454 assertz(b_machine_temp_predicate(TypedPred)).
2455
2456
2457 reset_temp_predicate :- retractall(b_machine_temp_predicate(_)).
2458
2459 :- volatile b_machine_additional_property/1.
2460 :- dynamic b_machine_additional_property/1.
2461
2462 % additional properties for set_up_constants
2463 % TO DO: check if there are constants/properties; otherwise raise warning
2464 add_additional_property(CustomPredicate,Description) :-
2465 format('Adding Property: ~w~n',[CustomPredicate]),
2466 b_parse_machine_predicate(CustomPredicate,TypedPred),
2467 add_texpr_info_if_new(TypedPred,description(Description),TP2),
2468 assertz(b_machine_additional_property(TP2)).
2469
2470 :- use_module(btypechecker, [unify_types_strict/2]).
2471 :- use_module(bsyntaxtree, [safe_create_texpr/4]).
2472 :- use_module(probsrc(translate), [pretty_type/2]).
2473
2474 :- public b_extract_values_clause_assignment_calc/3.
2475 b_extract_values_clause_assignment_calc(ID,Type,TVal) :-
2476 % extract equalities from VALUES clause
2477 get_section_from_current_machine(values,Values),
2478 member(b(values_entry(TID,TVal),_,Info),Values),
2479 get_texpr_id(TID,ID),
2480 get_texpr_type(TID,Type),
2481 debug_println(20,values_entry(ID,Type,TVal)),
2482 (b_is_constant(ID,OtherType),
2483 unify_types_strict(Type,OtherType)
2484 -> (member(description(_),Info) -> Info1=Info
2485 ; Info1=[description('from VALUES clause') | Info]),
2486 safe_create_texpr(equal(TID,TVal),pred,Info1,Equality),
2487 (debug_mode(off) -> true ; add_message(bmachine,'Adding property for VALUES: ',Equality,Equality)),
2488 assertz(b_machine_additional_property(Equality)),
2489 (b_extract_values_clause_assignment(ID,_,_)
2490 -> add_error(bmachine,'Multiple VALUES entries for constant: ',ID,TID)
2491 ; true)
2492 ; b_get_machine_set(ID) -> true % will be dealt with in b_global_sets for deferred sets
2493 ; b_get_constant_represented_inside_global_set(ID,_) ->
2494 add_message(bmachine,'Ignoring VALUES entry for constant (already detected as enumerated set element): ',ID,TID)
2495 ; lookup_global_constant(ID,fd(_,GSET)) ->
2496 ajoin(['Ignoring VALUES entry for element of enumerated set ',GSET,': '],Msg),
2497 add_message(bmachine,Msg,ID,TID)
2498 % TODO: detect case when this is a deferred set element not detected as (virtual) enumerated element
2499 ; b_is_constant(ID,OtherType) -> pretty_type(OtherType,OT), pretty_type(Type,TT),
2500 ajoin(['Cannot adapt value type ',TT,' to abstract type ',OT,', ignoring VALUES entry for: '],Msg),
2501 add_warning(bmachine,Msg,ID,TID)
2502 ; add_error(bmachine,'VALUES clause for unknown constant: ',ID,TID),
2503 fail
2504 ).
2505
2506
2507 % -------------------
2508
2509 :- use_module(specfile,[unset_animation_minor_modes/1,reset_animation_minor_modes/1]).
2510 :- use_module(translate,[set_unicode_mode/0, unset_unicode_mode/0, set_print_type_infos/1]).
2511 b_show_machine_representation_unicode(Rep,AdditionalInfo,UnsetMinorModes,Unicode) :-
2512 Unicode=true,!,
2513 set_unicode_mode,
2514 call_cleanup(b_show_machine_representation(Rep,AdditionalInfo,UnsetMinorModes,none),unset_unicode_mode).
2515 b_show_machine_representation_unicode(Rep,AdditionalInfo,UnsetMinorModes,_) :-
2516 b_show_machine_representation(Rep,AdditionalInfo,UnsetMinorModes,none).
2517
2518
2519 % AdditionalInfo=true means show additional information as comments (promoted, ...)
2520 % UnsetMinorModes will print in default classical B style
2521 % TypeInfos: none, needed or all
2522 b_show_machine_representation(Rep,AdditionalInfo,UnsetMinorModes,TypeInfos) :-
2523 full_b_machine(BMachine),
2524 (UnsetMinorModes==true -> unset_animation_minor_modes(L) ; L=[]),
2525 set_print_type_infos(TypeInfos),
2526 translate_machine(BMachine,Rep,AdditionalInfo),
2527 set_print_type_infos(none),
2528 (UnsetMinorModes==true -> reset_animation_minor_modes(L) ; true).
2529
2530 :- use_module(tools_printing,[nested_write_term_to_codes/2]).
2531 b_get_internal_prolog_representation_as_codes(Codes) :-
2532 full_b_machine(BMachine),
2533 nested_write_term_to_codes(BMachine,Codes).
2534
2535 :- use_module(tools,[get_tail_filename/2,split_filename/3,safe_atom_chars/3]).
2536 % TypingLevel = none, needed or all
2537 b_write_machine_representation_to_file(TypingLevel,PPFILE) :-
2538 b_write_machine_representation_to_file('$auto',TypingLevel,PPFILE).
2539 b_write_machine_representation_to_file('$auto',TypingLevel,PPFILE) :- !, % automatically infer machine name
2540 %get_full_b_machine(Name,M),
2541 get_tail_filename(PPFILE,Tail),
2542 split_filename(Tail,MachName,_Ext),
2543 b_write_machine_representation_to_file3(MachName,TypingLevel,PPFILE).
2544 b_write_machine_representation_to_file(MachName,TypingLevel,PPFILE) :-
2545 % provide explicit machine name; useful for diff checks
2546 b_write_machine_representation_to_file3(MachName,TypingLevel,PPFILE).
2547
2548 :- use_module(translate,[set_print_type_infos/1]).
2549 :- use_module(tools_files, [write_to_utf8_file_or_user_output/2]).
2550 b_write_machine_representation_to_file3(MachName,Level,PPFILE) :-
2551 debug_println(20,'% Pretty-Printing Internal Representation to File: '),
2552 debug_println(20,PPFILE),
2553 translate:set_print_type_infos(Level), % none, needed or all
2554 get_full_b_machine(_Name,M),
2555 (translate_machine_to_classicalb(MachName,M,Rep)
2556 -> translate:set_print_type_infos(none)
2557 ; add_internal_error('Translating machine failed: ',b_write_machine_representation_to_file3(MachName,Level,PPFILE)),
2558 set_print_type_infos(none),
2559 fail),
2560 write_to_utf8_file_or_user_output(PPFILE,Rep).
2561
2562 :- use_module(specfile).
2563 translate_machine_to_classicalb(MachName,M,Rep) :-
2564 temporary_set_preference(expand_avl_upto,-1,CHNG), % avoid printing sets using condensed #
2565 (animation_minor_mode(X)
2566 -> remove_animation_minor_mode,
2567 call_cleanup(translate_machine(machine(MachName,M),Rep,false), set_animation_minor_mode(X))
2568 ; translate_machine(machine(MachName,M),Rep,false)),
2569 reset_temporary_preference(expand_avl_upto,CHNG).
2570
2571 b_write_eventb_machine_to_classicalb_to_file(PPFILE) :-
2572 get_tail_filename(PPFILE,Tail),
2573 split_filename(Tail,MachName,_Ext),
2574 AdditionalInfo=true,
2575 b_get_eventb_machine_as_classicalb_codes(MachName,AdditionalInfo,Rep),
2576 write_to_utf8_file_or_user_output(PPFILE,Rep).
2577
2578 :- use_module(preferences,[temporary_set_preference/3,reset_temporary_preference/2]).
2579 b_get_eventb_machine_as_classicalb_codes(MachName,AdditionalInfo,Rep) :-
2580 full_b_machine(machine(Name,MachineBody)),
2581 (var(MachName) -> MachName=Name ; true),
2582 % limit abstract level to 0
2583 b_limit_abstract_level_to_zero(MachineBody,MachineBodyLevel0),
2584 temporary_set_preference(translate_print_typing_infos,true,CHNG),
2585 temporary_set_preference(translate_ids_to_parseable_format,true,CHNG2),
2586 temporary_set_preference(expand_avl_upto,-1,CHNG3), % avoid printing sets using condensed #
2587 (translate_eventb_to_classicalb(machine(MachName,MachineBodyLevel0),AdditionalInfo,Rep)
2588 -> reset_temporary_preference(translate_print_typing_infos,CHNG),
2589 reset_temporary_preference(translate_ids_to_parseable_format,CHNG2),
2590 reset_temporary_preference(expand_avl_upto,CHNG3)
2591 ; add_internal_error('Translating Event-B machine to Classical B failed: ',b_get_eventb_machine_as_classicalb_codes(MachName,AdditionalInfo,Rep)),
2592 reset_temporary_preference(translate_print_typing_infos,CHNG),
2593 reset_temporary_preference(translate_ids_to_parseable_format,CHNG2),
2594 reset_temporary_preference(expand_avl_upto,CHNG3),
2595 fail).
2596
2597 b_limit_abstract_level_to_zero(MachineBody,MachineBodyLevel0) :-
2598 maplist(b_set_to_level_zero,MachineBody,MachineBodyLevel0).
2599
2600 % TODO: set to level zero also the other events of the Event-B machine
2601 b_set_to_level_zero(initialisation/InitEvent,initialisation/InitEventLevelZero) :-
2602 get_texpr_expr(InitEvent,rlevent(Id,Sec,St,Par,Grd,Thms,Act,VW,PW,Ums,_Abs)),
2603 get_texpr_info(InitEvent,Info),
2604 create_texpr(rlevent(Id,Sec,St,Par,Grd,Thms,Act,VW,PW,Ums,[]),subst,Info,InitEventLevelZero).
2605 b_set_to_level_zero(X,X).
2606
2607 b_show_eventb_as_classicalb(Rep,AdditionalInfo) :-
2608 full_b_machine(BMachine),
2609 translate_eventb_to_classicalb(BMachine,AdditionalInfo,Rep).
2610
2611 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2612
2613 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2614 % precompilation: predicates are precompiled by calling the ..._calc predicate
2615
2616 :- use_module(state_packing).
2617 :- use_module(tools,[start_ms_timer/1,stop_ms_walltimer_with_msg/2]).
2618 :- use_module(rulesdslsrc(rule_validation),[setup_rules_extras/0]).
2619 % maybe this predicate should be directly called by b_load_machine
2620 b_machine_precompile :- debug_println(9,'Precompiling B Machine'),
2621 start_ms_timer(T1),
2622 get_full_b_machine(_,_),
2623 auto_precompile,
2624 (debug_mode(on) -> stop_ms_walltimer_with_msg(T1,'auto_precompile: ') ; true),
2625 precompile_operation_names_in_reverse_order,
2626 % TODO(DP, 14.8.2008): remove reference to b_global_sets
2627 start_ms_timer(T2),
2628 b_check_and_precompile_deferred_sets,
2629 (debug_mode(on) -> stop_ms_walltimer_with_msg(T2,'precompiling global sets: ') ; true),
2630 % Now done in bmachine_construction:clean_up_machine but not yet for Event-B:
2631 get_section_from_current_machine(freetypes,Freetypes),register_freetypes(Freetypes),
2632 auto_precompile_phase2,
2633 b_check_and_precompile_global_set_symmetry,
2634 state_packing:precompile_state_packing,
2635 do_machine_consistency_check,
2636 try_kodkod,
2637 (animation_minor_mode(rules_dsl) -> setup_rules_extras ; true),
2638 (debug_mode(on) -> stop_ms_walltimer_with_msg(T1,'complete precompiling B machine: ') ; true).
2639
2640 % recompile predicates which change when defs are loaded (e.g., CUSTOM_GRAPH or similar)
2641 b_machine_recompile_for_new_defs :-
2642 start_ms_timer(T1),
2643 auto_recompile_for_new_defs,
2644 (debug_mode(on) -> stop_ms_walltimer_with_msg(T1,'recompile for defs: ') ; true).
2645 auto_recompile_for_new_defs :-
2646 % failure-driven loop
2647 precompiled_predicate_no_error_when_not_precompiled(Pred/Arity), %print(precompile(Pred/Arity)),nl,
2648 auto_precompile2(Pred,Arity,Pattern),
2649 (Pattern -> true /* this pattern already asserted */
2650 ; assertz(Pattern)), fail.
2651 auto_recompile_for_new_defs.
2652
2653
2654
2655 other_spec_precompile :- retractall(bmachine_is_precompiled),
2656 /* call if you do not animate a B specification */
2657 is_precompiled_predicate(Pred/Arity),
2658 functor(Pattern,Pred,Arity),
2659 retractall(Pattern),
2660 (precompiled_predicate_no_error_when_not_precompiled(Pred/Arity)
2661 -> assertz( (Pattern :- fail ))
2662 ; assertz( (Pattern :- print_message('No B machine available for '),print_message(Pattern),fail) )
2663 ),
2664 fail.
2665 other_spec_precompile :-
2666 retractall(b_get_machine_constants(_)),
2667 assertz( b_get_machine_constants([]) ),
2668 retractall(b_get_machine_variables_in_original_order(_)),
2669 assertz( b_get_machine_variables_in_original_order([]) ),
2670 retractall(b_get_machine_variables(_)),
2671 assertz( b_get_machine_variables([]) ),
2672 retractall(b_get_static_assertions_from_machine(_)),
2673 assertz( b_get_static_assertions_from_machine([]) ),
2674 retractall(b_machine_has_static_assertions),
2675 retractall(b_get_unproven_static_assertions_from_machine(_)),
2676 assertz( b_get_unproven_static_assertions_from_machine([]) ),
2677 retractall(b_get_dynamic_assertions_from_machine(_)),
2678 assertz( b_get_dynamic_assertions_from_machine([]) ),
2679 retractall(b_machine_has_dynamic_assertions),
2680 retractall(b_get_unproven_dynamic_assertions_from_machine(_)),
2681 assertz( b_get_unproven_dynamic_assertions_from_machine([]) ),
2682 retractall( b_get_machine_searchscope(_) ),
2683 retractall( b_get_machine_goal(_) ),
2684 assert_bmachine_is_precompiled, debug_println(4,other_spec_precompile).
2685
2686 ?is_precompiled_predicate(P) :- precompiled_predicate(P).
2687 ?is_precompiled_predicate(P) :- precompiled_predicate_phase2(P).
2688
2689 % phase 1 precompilation: required by b_global_sets
2690 precompiled_predicate(b_machine_name/1).
2691 precompiled_predicate(b_get_named_machine_set/3).
2692 precompiled_predicate(b_enumerated_sets_precompiled/0).
2693 precompiled_predicate(b_get_properties_from_machine/1).
2694 precompiled_predicate(b_get_machine_all_constants/1).
2695 precompiled_predicate(b_get_machine_set/2).
2696 precompiled_predicate(b_get_disjoint_constants_of_type/3).
2697 precompiled_predicate(b_get_constant_represented_inside_global_set/2).
2698 precompiled_predicate(b_get_machine_constants/1).
2699 precompiled_predicate(b_get_machine_variables_in_original_order/1).
2700 precompiled_predicate(b_get_machine_variables/1).
2701 precompiled_predicate(b_get_invariant_from_machine/1).
2702 precompiled_predicate(b_get_linking_invariant_from_machine/1).
2703 precompiled_predicate(b_is_constant/2).
2704 precompiled_predicate(b_is_variable/2).
2705 precompiled_predicate(b_get_constant_variable_description/2).
2706 precompiled_predicate(b_get_static_assertions_from_machine/1).
2707 precompiled_predicate(b_machine_has_static_assertions/0).
2708 precompiled_predicate(b_get_unproven_static_assertions_from_machine/1).
2709 precompiled_predicate(b_get_dynamic_assertions_from_machine/1).
2710 precompiled_predicate(b_machine_has_dynamic_assertions/0).
2711 precompiled_predicate(b_get_unproven_dynamic_assertions_from_machine/1).
2712 precompiled_predicate(b_get_assertions_from_main_machine/2).
2713 precompiled_predicate(b_get_initialisation_from_machine/2).
2714 precompiled_predicate(b_get_machine_operation/6).
2715 precompiled_predicate(b_top_level_operation/1).
2716 precompiled_predicate(b_is_operation_name/1).
2717 precompiled_predicate(b_top_level_feasible_operation/1).
2718 precompiled_predicate(b_get_promoted_machine_operations/1).
2719 precompiled_predicate(get_operation_info/2).
2720 precompiled_predicate(b_get_machine_operation_for_animation/7).
2721 precompiled_predicate(get_operation_description_template_expr/2).
2722 precompiled_predicate(b_get_machine_goal/1).
2723 precompiled_predicate(b_get_machine_setscope/2).
2724 precompiled_predicate(b_get_machine_operation_max/2).
2725 precompiled_predicate(b_get_machine_searchscope/1).
2726 precompiled_predicate(b_get_definition_string_from_machine/3).
2727 precompiled_predicate(b_get_machine_animation_function/2).
2728 precompiled_predicate(b_get_machine_heuristic_function/1).
2729 precompiled_predicate(b_get_machine_animation_expression/2).
2730 precompiled_predicate(b_get_machine_custom_nodes_function/2).
2731 precompiled_predicate(b_get_machine_custom_edges_function/2).
2732 precompiled_predicate(b_get_machine_custom_graph_function/2).
2733 precompiled_predicate(complete_discharged_info/0). % just call it before calling b_specialized_invariant_for_op_calc !
2734 precompiled_predicate(get_proven_invariant/2).
2735 precompiled_predicate(b_nth1_invariant/3).
2736 precompiled_predicate(b_invariant_number_list/1).
2737 precompiled_predicate(b_specialized_invariant_mask_for_op/2).
2738 precompiled_predicate(b_specialized_invariant_for_op/2).
2739 precompiled_predicate(b_operation_preserves_invariant/2).
2740 precompiled_predicate(b_get_all_used_identifiers_in_section/2).
2741 precompiled_predicate(b_get_all_used_identifiers/1).
2742 precompiled_predicate(b_is_unused_constant/1).
2743 precompiled_predicate(b_extract_values_clause_assignment/3). % depends on b_is_constant/1
2744 precompiled_predicate(b_machine_statistics/2).
2745
2746 % require b_global_sets to be initialised
2747 precompiled_predicate_phase2(b_get_operation_normalized_read_write_info/3).
2748 precompiled_predicate_phase2(b_get_operation_unchanged_variables/2).
2749 precompiled_predicate_phase2(b_operation_cannot_modify_state/1).
2750 precompiled_predicate_phase2(b_operation_reads_output_variables/3).
2751 precompiled_predicate_phase2(b_get_operation_non_det_modifies/2).
2752
2753 % these functions sometimes get called also in csp mode; simply fail silently for those cases in other_spec_precompile
2754 % they also get recompiled when new definition file is added
2755 precompiled_predicate_no_error_when_not_precompiled(b_get_machine_animation_function/2).
2756 precompiled_predicate_no_error_when_not_precompiled(b_get_machine_heuristic_function/1).
2757 precompiled_predicate_no_error_when_not_precompiled(b_get_machine_animation_expression/2).
2758 precompiled_predicate_no_error_when_not_precompiled(b_get_machine_custom_nodes_function/2).
2759 precompiled_predicate_no_error_when_not_precompiled(b_get_machine_custom_edges_function/2).
2760 precompiled_predicate_no_error_when_not_precompiled(b_get_machine_custom_graph_function/2).
2761
2762 % on startup, all precompiled predicates yield error message
2763 startup_precompiled :- retractall(bmachine_is_precompiled),
2764 ? is_precompiled_predicate(Pred/Arity),
2765 functor(Pattern,Pred,Arity),
2766 retractall(Pattern),
2767 assertz( (Pattern :- add_error(bmachine,'B machine not precompiled for ',Pattern),fail) ),
2768 fail.
2769 startup_precompiled :- debug_println(4,startup_precompiled).
2770
2771 :- startup_precompiled.
2772
2773 % for each predicate in "precompiled_predicate", auto_precompile computes
2774 % all solutions by calling the predicate with an appended _calc
2775 auto_precompile :- % startup_precompiled,
2776 % failure-driven loop
2777 ? precompiled_predicate(Pred/Arity), %print(precompile(Pred/Arity)),nl,
2778 %statistics(walltime,[Tot,Delta]), format('Precompiling ~w/~w [~w ms (Delta ~w) ms]~n',[Pred,Arity,Tot,Delta]),
2779 ? auto_precompile2(Pred,Arity,Pattern),
2780 (Pattern -> true /* this pattern already asserted */
2781 ; assertz(Pattern)), fail.
2782 auto_precompile :-
2783 assert_bmachine_is_precompiled, debug_println(4,auto_precompile).
2784 auto_precompile_phase2 :-
2785 % failure-driven loop
2786 ? precompiled_predicate_phase2(Pred/Arity), %print(precompile(Pred/Arity)),nl,
2787 ? auto_precompile2(Pred,Arity,Pattern),
2788 (Pattern -> true /* this pattern already asserted */
2789 ; assertz(Pattern)), fail.
2790 auto_precompile_phase2.
2791
2792 % if the precompiled predicates is e.g. foo/2 then
2793 % Pattern=foo(A,B) and Call=foo_calc(A,B)
2794 auto_precompile2(Pred,Arity,Pattern) :-
2795 atom_concat(Pred,'_calc',CallFunctor),
2796 functor(Pattern,Pred,Arity),
2797 functor(Call,CallFunctor,Arity),
2798 unify_args(Arity,Call,Pattern),
2799 retractall(Pattern), % probably just removes clause added by startup_precompiled
2800 % the failure-driven loop for one predicate
2801 ? call(Call).
2802
2803 unify_args(0,_,_) :- !.
2804 unify_args(N,A,B) :-
2805 arg(N,A,Arg), arg(N,B,Arg),
2806 N1 is N-1, unify_args(N1,A,B).
2807
2808
2809 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2810 % set machine goal
2811
2812 b_set_machine_goal(Goal) :- b_set_machine_goal(Goal,false).
2813 b_set_machine_goal(Goal,WithDeferredSets) :-
2814 get_tc_scope(WithDeferredSets,Scope),
2815 b_parse_machine_predicate(Goal,Scope,TypedPred),
2816 b_set_parsed_typed_machine_goal(TypedPred).
2817
2818 b_set_parsed_typed_machine_goal(TypedPred) :-
2819 retractall(b_get_machine_goal(_)),
2820 assertz(b_get_machine_goal(TypedPred)).
2821
2822 b_unset_machine_goal :-
2823 retractall(b_get_machine_goal(_)).
2824
2825
2826 % get typechecking scope:
2827 get_tc_scope(with_deferred,Scope) :- !,
2828 Scope = [prob_ids(visible),variables,external_library(all_available_libraries)].
2829 % with external libraries we can use e.g. GET_IS_DET_OUTPUT("OpName")=FALSE
2830 get_tc_scope(with_deferred_and_primed,Scope) :- !,
2831 get_primed_machine_variables(PV), % this can be useful for visualisation, but will not work during mc
2832 Scope = [prob_ids(visible),identifier(PV),variables,external_library(all_available_libraries)].
2833 get_tc_scope(_,[variables]).
2834
2835 % set search_scope, restricting model checking to states which satisfy the SCOPE DEFINITION predicate
2836 b_set_machine_searchscope(Goal) :- b_set_machine_searchscope(Goal,with_deferred).
2837 b_set_machine_searchscope(Goal,WithDeferredSets) :-
2838 get_tc_scope(WithDeferredSets,Scope),
2839 b_parse_machine_predicate(Goal,Scope,TypedPred),
2840 b_set_parsed_typed_machine_searchscope(TypedPred).
2841 b_set_parsed_typed_machine_searchscope(TypedPred) :-
2842 retractall(b_get_machine_searchscope(_)),
2843 assertz(b_get_machine_searchscope(TypedPred)).
2844
2845 % also allow empty string, and #invariant and #not_invariant
2846 b_parse_optional_machine_predicate(TargetString,Target) :-
2847 is_empty_string(TargetString),!,create_texpr(truth,pred,[],Target).
2848 b_parse_optional_machine_predicate('#invariant',Invariant) :- !,
2849 b_get_invariant_from_machine(Invariant).
2850 b_parse_optional_machine_predicate('#not_invariant',TargetPredicate) :- !,
2851 b_get_invariant_from_machine(Invariant),
2852 bsyntaxtree:create_negation(Invariant,TargetPredicate).
2853 b_parse_optional_machine_predicate(TargetString,Target) :-
2854 b_parse_machine_predicate(TargetString,Target).
2855
2856 is_empty_string(Atom) :-
2857 atom_codes(Atom,Codes),
2858 is_empty_string2(Codes).
2859 is_empty_string2([]).
2860 is_empty_string2([32|Codes]) :- is_empty_string2(Codes).
2861
2862
2863 % parsing a string as predicate with deferred set elements
2864 b_parse_machine_predicate(Pred,TypedPred) :- b_parse_machine_predicate(Pred,[variables],TypedPred).
2865 b_parse_machine_predicate(Pred,Scope,TypedPred) :-
2866 atom_codes(Pred,Codes),
2867 b_parse_machine_predicate_from_codes(Codes,Scope,TypedPred).
2868 b_parse_machine_predicate_from_codes(Codes,Scope,TypedPred) :-
2869 b_parse_machine_predicate_from_codes2(Codes,[],Scope,TypedPred,closed).
2870 b_parse_machine_predicate_from_codes_open(OptionalQuantifier,Codes,Defs,Scope,TypedPred) :-
2871 b_parse_machine_predicate_from_codes2(Codes,Defs,Scope,TypedPred,open(OptionalQuantifier)).
2872
2873 b_parse_machine_predicate_from_codes2(Codes,Defs,Scope,TypedPred,Mode) :-
2874 debug_println(9,parse_predicate(Mode)),
2875 (Defs=[] -> true ; debug_println(9,'% Ignoring DEFINITIONS')),
2876 b_parse_wo_type_machine_predicate_from_codes_to_raw_expr(Codes,Parsed),
2877 %format('Raw Parsed AST = ~w~n',[Parsed]),
2878 b_type_check_raw_expr(Parsed,Scope,TypedPred,Mode).
2879
2880 check_codes(X) :- (X=[] ; X=[H|_], number(H)),!.
2881 check_codes(X) :- add_error(bmachine,'Error while parsing: not a code list: ',X),fail.
2882
2883 b_parse_wo_type_machine_predicate_from_codes_to_raw_expr(Codes,ParsedRaw) :-
2884 check_codes(Codes),
2885 catch(
2886 parse_predicate(Codes,ParsedRaw), % ,print(ParsedRaw),nl),
2887 Exception,
2888 ( Exception = parse_errors(Errors) -> %print(errors(Errors)),nl,
2889 add_all_perrors(Errors,[],parse_machine_predicate_error),fail
2890 ;
2891 add_error(bmachine,'Exception while parsing predicate: ',Exception),
2892 fail)).
2893
2894 b_type_check_raw_expr(ParsedRaw,Scope,TypedPred,Mode) :-
2895 debug_println(9,type_with_errors(ParsedRaw)),
2896 ( Mode == closed ->
2897 type_with_errors(ParsedRaw,Scope,pred,TypedPred)
2898 ; Mode = open(OptionalQuantifier) ->
2899 b_type_open_predicate_with_errors(OptionalQuantifier,ParsedRaw,Scope,TypedPred)).
2900
2901 % a flexible version: convert atom to codes, but also accept codes list
2902 flexible_atom_codes([],R) :- !, R=[].
2903 flexible_atom_codes(A,R) :- atom(A), !, atom_codes(A,R).
2904 flexible_atom_codes([H|T],List) :- !, List=[H|T].
2905 flexible_atom_codes(Other,List) :- add_internal_error('Not atom or codes list: ',flexible_atom_codes(Other,List)),
2906 List=Other.
2907
2908 b_parse_machine_operation_pre_post_predicate(AtomOrCodes,TypedPred,OpName) :-
2909 b_parse_machine_operation_pre_post_predicate(AtomOrCodes,[],TypedPred,OpName,true).
2910 b_parse_machine_operation_pre_post_predicate(AtomOrCodes,ExtraScope,TypedPred,OpName,GenerateParseErrors) :-
2911 flexible_atom_codes(AtomOrCodes,Codes),
2912 b_parse_predicate(Codes,Parsed,GenerateParseErrors),
2913 get_machine_operation_typing_scope(OpName,Scope,ExtraScope),
2914 b_type_only(Parsed,Scope,pred,TypedPred,GenerateParseErrors).
2915
2916 % Note: B and Event-B have different way of priming; this is aimed at classical B
2917 % and supposes predicate used together with execute_operation_by_predicate_in_state
2918 % in classical B x$0 refers to the value before a substitution (e.g., becomes_such)
2919 get_primed_machine_variables(Ids) :-
2920 b_get_machine_variables(Vars),
2921 maplist(prime_variable,Vars,Ids).
2922 :- use_module(btypechecker,[prime_atom0/2]). % add $0 at end of variable
2923 prime_variable(b(identifier(ID),T,I),b(identifier(PID),T,I)) :- prime_atom0(ID,PID).
2924
2925 is_initialisation_op('$setup_constants').
2926 is_initialisation_op('$initialise_machine').
2927
2928 % analog version to b_is_operation_name:
2929 b_is_initialisation_name('$initialise_machine').
2930
2931
2932 get_machine_operation_typing_scope(OpName,Scope,ExtraScope) :-
2933 ( get_machine_operation_additional_identifiers(OpName,V) -> true
2934 ; add_error_fail(get_machine_operation_typing_scope,'Unknown operation:', OpName)),
2935 Scope = [prob_ids(visible),identifier(V),variables,external_library(all_available_libraries)|ExtraScope].
2936
2937 % get additional ids to add to Scope for typing with identifier(V)
2938 get_machine_operation_additional_identifiers(OpName,V) :-
2939 is_initialisation_op(OpName),!, V=[].
2940 get_machine_operation_additional_identifiers(OpName,V) :-
2941 b_get_machine_operation_for_animation(OpName,Results,Paras,_),
2942 append(Paras,Results,PR), % b_get_machine_operation_typed_parameters
2943 get_primed_machine_variables(PV),
2944 append(PV,PR,V).
2945
2946 b_get_machine_operation_for_animation(Name,Results,Parameters,Body) :-
2947 ? b_get_machine_operation_for_animation(Name,Results,Parameters,Body,_OType,true).
2948 % interface predicate b_get_machine_operation_for_animation/6
2949 b_get_machine_operation_for_animation(Name,Results,Parameters,Body,OType,TopLevel) :-
2950 ? b_get_machine_operation_for_animation(Name,Results,Parameters,Body,OType,TopLevel,_OpPos).
2951
2952 :- public b_get_machine_operation_for_animation_calc/7.
2953 % adds some additional ANY parameters if preference is set
2954 b_get_machine_operation_for_animation_calc('$initialise_machine',[],Parameters,Body,OType,_TopLevel,OpPos) :-
2955 b_get_machine_variables(DeclaredVars), Parameters=DeclaredVars,
2956 OpPos = unknown, % TODO: improve
2957 b_get_initialisation_from_machine(Body,OType).
2958 b_get_machine_operation_for_animation_calc(Name,Results,Parameters,Body,OType,TopLevel,OpPos) :-
2959 get_preference(show_eventb_any_arguments,EVENTB),
2960 ? b_get_machine_operation(Name,Results,RealParameters,RealBody,OType,OpPos),
2961 % TO DO: check whether we should only keep b_top_level_operation(Name) in case TopLevel==true !
2962 %length(RealParameters,P), format('Get Mach Op ~w ; paras ~w ; EB ~w, TopLevel=~w~n',[Name,P,EVENTB,TopLevel]),
2963 ((Results=[_|_] ; RealParameters=[_|_] ; EVENTB=false)
2964 -> Parameters=RealParameters, Body=RealBody
2965 ; translate_any_into_parameters(RealBody,FakeParameters,FakeBody),
2966 length(FakeParameters,Len),
2967 (Len > 255
2968 -> add_message(bmachine,'Not adding any parameters to operation, max_arity (255) exceeded: ',Name:Len,OpPos),
2969 Parameters=RealParameters, Body=RealBody
2970 ; ( TopLevel=true, Parameters=FakeParameters, Body=FakeBody
2971 ; TopLevel=false, Parameters=RealParameters, Body=RealBody
2972 )
2973 )
2974 ; Parameters=RealParameters, Body=RealBody
2975 ).
2976
2977 % TO DO: limit to max_arity
2978 translate_any_into_parameters(b(E,Type,Info),Parameters,NewSubst) :-
2979 translate_any_into_parameters_aux(E,Type,Info,Parameters,NewSubst).
2980 translate_any_into_parameters_aux(any(Parameters,PreCond,ABody),Type,Info,Parameters,NewSubst) :-
2981 NewSubst=b(select([b(select_when(PreCond,ABody),Type,Info)]),Type,Info). % TO DO: go deeper ? (nested ANY ?)
2982 translate_any_into_parameters_aux(let(Parameters,Defs,LBody),Type,Info,Parameters,NewSubst) :-
2983 NewSubst=b(select([b(select_when(Defs,LBody),Type,Info)]),Type,Info). % TO DO: go deeper ? ANY could have been translated into several LETs ?
2984 translate_any_into_parameters_aux(lazy_let_subst(Id,IdExpr,Body),Type,Info,Parameters,NewSubst) :-
2985 NewSubst=b(lazy_let_subst(Id,IdExpr,NewInnerSubst),Type,Info),
2986 translate_any_into_parameters(Body,Parameters,NewInnerSubst).
2987
2988
2989 % add deferred set prob_ids and external libraries as well
2990 % ExtraScope could e.g. be [identifier(TypedIDLIst)]
2991 b_parse_machine_expression_from_codes_with_prob_ids(Codes,ExtraScope,TypedExpr,GenerateParseErrors) :-
2992 extend_typing_scope_for_stored_lets([prob_ids(visible),variables,
2993 external_library(all_available_libraries)|ExtraScope],
2994 Scope),
2995 b_parse_machine_expression_from_codes4(Codes,Scope,TypedExpr,GenerateParseErrors).
2996 b_parse_machine_expression_from_codes_with_prob_ids(Codes,ExtraScope,TypedExpr) :-
2997 b_parse_machine_expression_from_codes_with_prob_ids(Codes,ExtraScope,TypedExpr,true).
2998 b_parse_machine_expression_from_codes_with_prob_ids(Codes,TypedExpr) :-
2999 b_parse_machine_expression_from_codes_with_prob_ids(Codes,[],TypedExpr,true).
3000
3001 b_parse_machine_expression_from_codes(Codes,TypedExpr) :-
3002 b_parse_machine_expression_from_codes4(Codes,[variables],TypedExpr,true).
3003
3004 b_parse_machine_expression_from_codes4(Codes,Scope,TypedExpr,GenerateParseErrors) :-
3005 b_parse_machine_expression_from_codes(Codes,Scope,TypedExpr,_Type,GenerateParseErrors,Error),!,
3006 (Error=none -> true
3007 ; generate_parse_errors_for(GenerateParseErrors,Position,ErrOrWarn),
3008 add_msg_warn_or_err(ErrOrWarn,b_parse_machine_expression_from_codes,
3009 'Errors occured during parsing:', Error,Position),
3010 % format(user_error,'Parsing: ~s~n',[Codes]),
3011 fail).
3012
3013
3014 %b_parse_machine_expression_from_codes(Codes,TypedExpr) :-
3015 % b_parse_machine_expression_from_codes(Codes,TypedExpr,_Type,false,Error), Error=none.
3016
3017 b_parse_machine_expression_from_codes(Codes,Typed,Type,GenerateParseErrors,Error) :-
3018 b_parse_machine_expression_from_codes(Codes,[variables],
3019 Typed,Type,GenerateParseErrors,Error).
3020 b_parse_machine_expression_from_codes(Codes,Scope,
3021 Typed,Type,GenerateParseErrors,Error) :-
3022 b_parse_machine_formula_from_codes(expression,Codes,Scope,
3023 Typed,Type,GenerateParseErrors,Error).
3024
3025 % parse substitutions so as to allow operation calls; useful for REPL or trace files:
3026 b_parse_machine_subsitutions_from_codes(Codes,Scope,
3027 Typed,Type,GenerateParseErrors,Error) :-
3028 temporary_set_preference(allow_local_operation_calls,true,CHNG),
3029 call_cleanup(
3030 b_parse_machine_formula_from_codes(substitution,Codes,Scope,
3031 Typed,Type,GenerateParseErrors,Error),
3032 reset_temporary_preference(allow_local_operation_calls,CHNG)).
3033
3034 % a variant of b_parse_machine_predicate that allows also expressions
3035 b_parse_machine_formula(PredOrExpr,Scope,TypedPredOrExpr) :-
3036 atom_codes(PredOrExpr,Codes),
3037 b_parse_machine_formula_from_codes(formula,Codes,Scope,
3038 TypedPredOrExpr,_Type,true,Error), Error=none.
3039
3040 % Kind = expression, predicate, formula, substitution
3041 % GnerateParseErrors = true, false, type_errors_only, gen_parse_errors_for/2
3042 b_parse_machine_formula_from_codes(Kind,Codes,Scope,
3043 Typed,Type,GenerateParseErrors,Error) :-
3044 b_parse_only(Kind,Codes, ParsedAST, GenerateParseErrors, Error),
3045 %print(parsed(Parsed,Error)),nl,
3046 ( nonvar(Error) -> true /* either exception or parse error occured */
3047 ; generate_no_parse_errors(GenerateParseErrors), type_without_errors(ParsedAST,Scope,Type,Typed) -> Error=none
3048 ; b_type_only(ParsedAST,Scope,Type,Typed,GenerateParseErrors) -> Error=none
3049 ; Error=type_error).
3050
3051 % typing with or without errors, depending on GenerateParseErrors flag
3052 b_type_only(ParsedAST,Scope,Type,Typed,GenParseErrors) :-
3053 generate_parse_errors_for(GenParseErrors,_Pos,ErrOrWarn),!,
3054 % ParsedAST now contains filenumber for additional file
3055 type_with_errors_in_context(ParsedAST,Scope,Type,Typed,machine_context,ErrOrWarn).
3056 b_type_only(ParsedAST,Scope,Type,Typed,false) :- !,
3057 type_without_errors(ParsedAST,Scope,Type,Typed).
3058 b_type_only(ParsedAST,Scope,Type,Typed,_GenerateParseErrors) :-
3059 type_with_errors_in_context(ParsedAST,Scope,Type,Typed,no_machine_context([]),error).
3060
3061 % GenerateParseErrors can also provide context filename
3062 b_parse_predicate(Codes,ParsedAST,GenerateParseErrors) :-
3063 b_parse_only(predicate,Codes, ParsedAST, GenerateParseErrors,Error),
3064 Error=none.
3065
3066 b_parse_only(Kind,Codes, ParsedAST, _,Error) :- (Codes \= [] , Codes \= [_|_]),!,
3067 add_internal_error('Not a codes list: ',b_parse_only(Kind,Codes, ParsedAST, _, Error)),
3068 Error = internal_error.
3069 b_parse_only(Kind,Codes, ParsedAST, GenerateParseErrors,Error) :-
3070 generate_parse_errors_for(GenerateParseErrors,Position,ErrOrWarn),!,
3071 % we should generate errors in a particular file context
3072 (extract_file_number_and_name(Position,FileNr,Filename)
3073 -> Files=[Filename] ; FileNr = -1, Files=[]),
3074 (number(FileNr) -> NewFileNr=FileNr ; add_additional_filename(Filename,NewFileNr)),
3075 catch( parse_at_position_in_file(Kind,Codes,ParsedAST,Position,NewFileNr),
3076 Exception,
3077 ((Exception = parse_errors(Errors) ->
3078 add_all_perrors(Errors,Files,parse_machine_formula_error,ErrOrWarn),
3079 Error=parse_error
3080 ;
3081 ajoin(['Exception while parsing ',Kind,': '],Msg),
3082 add_msg_warn_or_err(ErrOrWarn,bmachine,Msg,Exception,Position),
3083 Error=exception))).
3084 b_parse_only(Kind,Codes, ParsedAST, _GenerateParseErrors,_Error) :-
3085 catch( parse(Kind,Codes,ParsedAST),
3086 Exception,
3087 (debug_println(19,parse_exception(Exception)),fail)).
3088
3089 %generate_type_errors_for(type_errors_only,unknown,[]).
3090 %generate_type_errors_for(GenerateParseErrors,Pos) :- generate_parse_errors_for(GenerateParseErrors,Pos).
3091
3092 generate_parse_errors_for(true,unknown,error).
3093 generate_parse_errors_for(gen_parse_errors_for(Pos),Pos,error).
3094 generate_parse_errors_for(gen_parse_warnings_for(Pos),Pos,warning).
3095
3096 generate_no_parse_errors(false).
3097
3098 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3099
3100 % a flexible parsing predicate, useful for dot and table tools to be called from
3101 % either probcli or prob2 with either atoms or with raw ASTs:
3102
3103 :- use_module(eval_let_store,[extend_typing_scope_for_stored_lets/2]).
3104 parse_expression_raw_or_atom_with_prob_ids(Expr,TypedExpr) :-
3105 extend_typing_scope_for_stored_lets([prob_ids(visible),variables,external_library(all_available_libraries)],Scope),
3106 parse_expression_raw_or_atom3(Expr,Scope,TypedExpr).
3107
3108 parse_expression_raw_or_atom3('$VARIABLES',_,TypedExpr) :- !,
3109 b_get_machine_variables(DeclaredVars),
3110 gen_couple_from_list(DeclaredVars,TypedExpr).
3111 parse_expression_raw_or_atom3(RawAST,Scope,TypedExpr) :- compound(RawAST),!, % allow to pass raw AST as well
3112 type_with_errors(RawAST,Scope,Type,TypedExpr),
3113 ((Type=pred ; Type=subst)
3114 -> add_error(parse_expression,'Expected expression formula but obtained: ',Type),fail
3115 ; true ).
3116 parse_expression_raw_or_atom3(VorE,Scope,TypedExpr) :-
3117 atom_codes(VorE,VorECodes),
3118 % to do: maybe support b_parse_machine_expression_from_codes_with_prob_ids
3119 b_parse_machine_expression_from_codes4(VorECodes,Scope,TypedExpr,true).
3120
3121 :- use_module(bsyntaxtree, [create_couple/3]).
3122 gen_couple_from_list([],string('NO VARIABLES')).
3123 gen_couple_from_list([TID],Res) :- !, Res=TID.
3124 gen_couple_from_list([TID|T],Couple) :-
3125 gen_couple_from_list(T,Rest),
3126 create_couple(TID,Rest,Couple).
3127
3128
3129 :- use_module(btypechecker,[prime_atom0/2]). % add $0 at end of variable
3130 :- use_module(bsyntaxtree, [find_typed_identifier_uses/2,get_texpr_id/2]).
3131 % compute requirements for evaluating formula
3132 % requires_nothing, requires_constants, requires_variables
3133 determine_type_of_formula(TypedExpr,Class) :-
3134 determine_type_of_formula(TypedExpr,_,Class).
3135 determine_type_of_formula(TypedExpr,Identifiers,Class) :-
3136 find_typed_identifier_uses(TypedExpr,Identifiers),
3137 determine_type_of_formula2(Identifiers,Class).
3138 determine_type_of_formula2([],Res) :- !, Res = requires_nothing.
3139 determine_type_of_formula2(Ids,Res) :-
3140 member(TID,Ids), get_texpr_id(TID,ID),
3141 (b_is_variable(ID,_) -> true
3142 ; prime_atom0(Original,ID),
3143 (b_is_variable(Original,_) -> true ; add_warning(bmachine,'Unknown primed variable: ',ID))
3144 ),
3145 !, Res = requires_variables.
3146 determine_type_of_formula2(Ids,Res) :-
3147 member(TID,Ids), get_texpr_id(TID,ID),
3148 b_is_constant(ID,_),
3149 !, Res = requires_constants.
3150 determine_type_of_formula2(_,requires_nothing).
3151 % only open, implicitly existentially quantified variables
3152 % also, TO DO: check that insert_before_substitution_variables / $0 variables are properly treated
3153 % TODO: there are external functions like ENABLED(.) which implicitly require a state with variables
3154
3155 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3156 % consistency check to spot some errors
3157 do_machine_consistency_check :-
3158 specfile:animation_mode(b), % TODO (dp,27.09.2012): this is just an ugly hack
3159 type_check_definitions,
3160 ? minor_mode_to_check,
3161 %debug:time(bmachine:all_operations_have_valid_read_modifies_infos).
3162 !,
3163 all_operations_have_valid_read_modifies_infos.
3164 do_machine_consistency_check.
3165
3166 % In future, all formalisms should provide the relevent data
3167 minor_mode_to_check :- animation_minor_mode(eventb),!.
3168 ?minor_mode_to_check :- classical_b_mode.
3169
3170 all_operations_have_valid_read_modifies_infos :-
3171 %findall(O,b_get_machine_operation(O,_,_,_,_),OpNames),
3172 %maplist(operation_has_valid_read_modifies_infos,OpNames).
3173 ? b_get_operation_pos(OpName,Pos),
3174 operation_has_valid_read_modifies_infos(OpName,Pos),fail.
3175 all_operations_have_valid_read_modifies_infos.
3176
3177 operation_has_valid_read_modifies_infos(OpName,Pos) :- % print(check(OpName)),nl,
3178 ( operation_has_valid_read_modifies_infos2(OpName,Pos) -> true
3179 ; add_failed_call_error(operation_has_valid_read_modifies_infos2(OpName,Pos))).
3180 operation_has_valid_read_modifies_infos2(OpName,Pos) :-
3181 b_get_operation_normalized_read_write_info(OpName,Reads,Writes),
3182 maplist(check_read(OpName,Pos),Reads),
3183 %print(operation(OpName,reads(Reads),writes(Writes))),nl,
3184 maplist(check_write(OpName,Pos),Writes).
3185
3186
3187 :- use_module(translate,[translate_span_with_filename/2]).
3188 :- use_module(bmachine_construction,[abstract_variable_removed_in/3]).
3189 check_read(OpName,Pos,Id) :-
3190 ( (check_is_var(Id); check_is_constant(Id) ; check_is_operation(Id)) -> true
3191 ; abstract_variable_removed_in(Id,Mch,TId) ->
3192 translate_span_with_filename(TId,SP),
3193 ajoin(['Operation reads invisible abstract variable `',Id,'` ',SP,', removed in ',Mch,':'],Msg),
3194 % this shows that in that refinement step we removed a variable without adapting an operation
3195 add_error(bmachine,Msg,OpName,Pos)
3196 ;
3197 ajoin(['Unknown identifier `',Id,'` in "reads" information of operation:'],Msg),
3198 add_internal_error(bmachine,Msg,OpName,Pos)).
3199 check_write(OpName,Pos,Id) :-
3200 ( check_is_var(Id) -> true
3201 ; abstract_variable_removed_in(Id,Mch,TId) ->
3202 translate_span_with_filename(TId,SP),
3203 ajoin(['Operation writes invisible abstract variable `',Id,'` ',SP,', removed in ',Mch,':'],Msg),
3204 % this shows that in that refinement step we removed a variable without adapting an operation
3205 add_error(bmachine,Msg,OpName,Pos)
3206 ;
3207 ajoin(['Unknown variable `',Id,'` in "modifies" information of operation:'],Msg),
3208 add_internal_error(bmachine,Msg,OpName,Pos)).
3209
3210 check_is_var(Id) :-
3211 b_is_variable(Id,_).
3212 %get_texpr_id(E,Id),
3213 %b_get_machine_variables(Vars),
3214 %memberchk(E,Vars).
3215 check_is_constant(Id) :- b_is_constant(Id,_).
3216 check_is_constant(Id) :- b_get_constant_represented_inside_global_set(Id,_).
3217 % b_get_machine_all_constants(Constants),
3218 % get_texpr_id(TId,Id),
3219 % memberchk(TId,Constants).
3220 check_is_constant(Id) :- b_get_machine_set(Id).
3221 check_is_constant(Id) :- b_get_named_machine_set(Id,_).
3222 check_is_constant(Id) :-
3223 b_get_named_machine_set(_,Elems),member(Id,Elems).
3224 %check_is_constant(Id) :- % add later when we deal FREETYPE section in classical B as in Z
3225 % kernel_freetypes:freetype_register_db(Id,_) ;
3226 % kernel_freetypes:freetype_case_db(Id,_,_).
3227
3228 check_is_operation(op(ID)) :-
3229 b_is_operation_name(ID), % TO DO: check that other predicates can deal with op(Id) infos
3230 get_preference(allow_operation_calls_in_expr,true).
3231
3232 % provide access to number of constants, ....:
3233
3234 :- volatile b_machine_statistics/2.
3235 :- dynamic b_machine_statistics/2.
3236 :- public b_machine_statistics_calc/2.
3237 b_machine_statistics_calc(files,Nr) :-
3238 b_get_all_used_filenames(L),length(L,Nr).
3239 b_machine_statistics_calc(deferred_sets,Nr) :-
3240 get_section_from_current_machine(deferred_sets,L),length(L,Nr).
3241 b_machine_statistics_calc(enumerated_sets,Nr) :-
3242 get_section_from_current_machine(enumerated_sets,L),length(L,Nr).
3243 b_machine_statistics_calc(definitions,Nr) :-
3244 get_section_from_current_machine(definitions,L),length(L,Nr).
3245 b_machine_statistics_calc(constants,Nr) :- b_get_machine_constants(L), length(L,Nr).
3246 b_machine_statistics_calc(variables,Nr) :- b_get_machine_variables(L), length(L,Nr).
3247 b_machine_statistics_calc(properties,Nr) :-
3248 b_get_properties_from_machine(C), conjunction_to_list(C,L),length(L,Nr).
3249 b_machine_statistics_calc(invariants,Nr) :-
3250 b_get_invariant_from_machine(C), conjunction_to_list(C,L),length(L,Nr).
3251 b_machine_statistics_calc(static_assertions,Nr) :-
3252 b_get_static_assertions_from_machine(L), length(L,Nr).
3253 b_machine_statistics_calc(dynamic_assertions,Nr) :-
3254 b_get_dynamic_assertions_from_machine(L), length(L,Nr).
3255 b_machine_statistics_calc(operations,Nr) :- findall(N,b_is_operation_name(N),L),length(L,Nr).
3256
3257 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3258 % default and initial machines
3259 b_set_initial_machine :-
3260 initial_machine(Main,Machines),
3261 b_set_machine(Main,Machines,[]).
3262
3263 initial_machine(phonebook,[M]) :-
3264 M = abstract_machine(none,machine(none),machine_header(none,phonebook,[]),Body),
3265 Body = [sets(none, [deferred_set(none,'Name'),
3266 deferred_set(none,'Code')]),
3267 definitions(none,[ScopeName,ScopeCode,TraceTest0]),
3268 variables(none, [identifier(none, db)]),
3269 invariant(none, member(none,
3270 identifier(none, db),
3271 partial_function(none,
3272 identifier(none, 'Name'),
3273 identifier(none, 'Code')))),
3274 initialisation(none,
3275 assign(none, [identifier(none, db)], [empty_set(none)])),
3276 operations(none, [Add,Lookup,Update,Reset])],
3277
3278 % definitions
3279 ScopeName = expression_definition(none,
3280 scope_Name,
3281 [],
3282 interval(none, integer(none, 1), integer(none, 3))),
3283 ScopeCode = expression_definition(none,
3284 scope_Code,
3285 [],
3286 interval(none, integer(none, 1), integer(none, 2))),
3287 TraceTest0 = expression_definition(none, trace_Test0, [], empty_sequence(none)),
3288
3289 % add operation
3290 Add = operation(none,
3291 identifier(none, add),
3292 [],
3293 [identifier(none,cc),identifier(none,nn)],
3294 precondition(none, AddPre, AddAssign)),
3295 AddPre = conjunct(none,
3296 conjunct(none,
3297 member(none, identifier(none,nn), identifier(none,'Name')),
3298 member(none, identifier(none,cc), identifier(none,'Code'))),
3299 not_member(none,
3300 identifier(none,nn),
3301 domain(none, identifier(none,db)))),
3302 AddAssign = assign(none,
3303 [identifier(none,db)],
3304 [union(none,
3305 identifier(none,db),
3306 set_extension(none,
3307 [couple(none,[identifier(none,nn),
3308 identifier(none,cc)])]))]),
3309
3310 % lookup operation
3311 Lookup = operation(none,
3312 identifier(none, lookup),
3313 [identifier(none, cc)],
3314 [identifier(none, nn)],
3315 precondition(none, LookupPre, LookupAssign)),
3316 LookupPre = member(none, identifier(none,nn), domain(none,identifier(none,db))),
3317 LookupAssign = assign(none,
3318 [identifier(none, cc)],
3319 [function(none, identifier(none, db), identifier(none, nn))]),
3320
3321 % update operation
3322 Update = operation(none,
3323 identifier(none, update),
3324 [],
3325 [identifier(none,nn),identifier(none,cc)],
3326 precondition(none, UpdatePre, UpdateAssign)),
3327 UpdatePre = conjunct(none,
3328 conjunct(none,
3329 member(none, identifier(none,nn), identifier(none,'Name')),
3330 member(none, identifier(none,cc), identifier(none,'Code'))),
3331 member(none,
3332 identifier(none,nn),
3333 domain(none, identifier(none,db)))),
3334 UpdateAssign = assign(none,
3335 [function(none, identifier(none,db), identifier(none,nn))],
3336 [identifier(none, cc)]),
3337
3338 % reset operation
3339 Reset = operation(none,
3340 identifier(none,reset),
3341 [],
3342 [],
3343 precondition(none, ResetPre, ResetAssign)),
3344 ResetPre = member(none,
3345 identifier(none, db),
3346 total_function(none, identifier(none,'Name'), identifier(none,'Code'))),
3347 ResetAssign = assign(none,[identifier(none,db)],[empty_set(none)]).
3348
3349 empty_machine(empty_machine,[M]) :-
3350 M = abstract_machine(none,machine(none),machine_header(none,empty_machine,[]),Body),
3351 Body = [].
3352
3353 % after transformation this gives
3354 % machine(empty_machine,[deferred_sets/[],enumerated_sets/[],enumerated_elements/[],parameters/[],internal_parameters/[],abstract_constants/[],concrete_constants/[],abstract_variables/[],concrete_variables/[],promoted/[],unpromoted/[],(constraints)/b(truth,pred,[]),properties/b(truth,pred,[initial]),invariant/b(truth,pred,[initial]),linking_invariant/b(truth,pred,[initial]),assertions/[],initialisation/b(skip,subst,[generated]),operation_bodies/[],definitions/[],used/[],freetypes/[],operators/[],values/[],meta/[model_type/machine,hierarchy/[empty_machine],header_pos/[empty_machine/none]]])
3355
3356 % Code to inspect sizes of operations:
3357 % findall(op(Sz,Op),(bmachine:b_get_machine_operation_for_animation(Op,_,_,Body,_,_Top), terms:term_size(Body,Sz)),L), sort(L,SL), print(SL),nl.