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