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