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 :- module(b_machine_hierarchy,[analyse_hierarchy/2
6 ,analyse_eventb_hierarchy/2
7 ,main_machine_name/1 % find out name of main machine
8 ,machine_name/1 % can be used to find out machine names
9 ,machine_type/2 % machine_type(Name, R) - get the type
10 % (abstract_machine, abstract_model, refinement, implementation) for the machine named Name
11 ,machine_references/2 % get a list of references and the type of the reference.
12 % Example: if A refines B, then machine_references('A',X) returns X= [ref(refines'B','')].
13 % The last argument in ref/3 is the prefix
14 ,machine_identifiers/7 % gets Params,Sets,Abstract Variables,Concrete Variables,Abstract Constants and Concrete
15 % Constants for a machine. Abstract constants/Variables are introduced in the machine
16 % using the ABSTRACT_VARAIABLES/ABSTARCT_CONSTANTS keyword. The concrete versions
17 % analogously via CONCRETE_VARAIBLES,CONCRETE_CONSTANTS
18 % Example output for
19 % MACHINE xx(T,u)
20 % CONSTRAINTS u:T
21 % SETS A; B={foo, bar}
22 % CONCRETE_CONSTANTS cc
23 % PROPERTIES cc:B
24 % ABSTRACT_VARIABLES xx
25 % CONCRETE_VARIABLES yy
26 % INVARIANT
27 % xx:INT &
28 % yy : T
29 % INITIALISATION xx,yy:= ({1|->2};{2|->4})(1), u
30 % END
31 %
32 % machine_identifiers(A,B,C,D,E,F,G).
33 % A = xx,
34 % B = [identifier(pos(4,1,1,12,1,12),'T'),identifier(pos(5,1,1,14,1,14),u)],
35 % C = [deferred_set(pos(11,1,3,6,3,6),'A'),enumerated_set(pos(12,1,3,9,3,20),'B',[identifier(pos(13,1,3,12,3,14),foo),identifier(pos(14,1,3,17,3,19),bar)])],
36 % D = [identifier(pos(22,1,6,20,6,21),xx)],
37 % E = [identifier(pos(24,1,7,20,7,21),yy)],
38 % F = [],
39 % G = [identifier(pos(16,1,4,20,4,21),cc)]
40 , get_machine_identifier_names/7 % a version returning atomic identifier names
41 , machine_has_constants/1 % check if machine has some constants
42 , get_machine_short_desc/2
43 ,abstract_constant/2, concrete_constant/2
44 ,possibly_abstract_constant/1
45 ,machine_operations/2 % machine_operations(M, Ops) gets the names of the Operations defined in Machine M
46 ,machine_operation_calls/2
47 ,machine_hash/2 % stores a hash value for the machine
48 ,properties_hash/2 % computes a hash over the constants and properties
49 ,operation_hash/3 % computes a hash for the operation in a machine
50 ,write_dot_hierarchy_to_file/1
51 ,write_dot_op_hierarchy_to_file/1
52 ,write_dot_event_hierarchy_to_file/1
53 ,write_dot_variable_hierarchy_to_file/1
54 ,get_machine_inclusion_graph/3
55 ,get_machine_topological_order/1
56 ,print_machine_topological_order/0
57 ]).
58
59 :- use_module(library(lists)).
60 :- use_module(library(ordsets)).
61 :- use_module(bmachine,[b_get_definition/5, get_machine_file_number/4]).
62 :- use_module(bmachine_construction).
63 :- use_module(debug).
64 :- use_module(self_check).
65 :- use_module(specfile,[get_specification_description/2]).
66 :- use_module(extension('probhash/probhash'),[raw_sha_hash/2]).
67 :- use_module(input_syntax_tree).
68 :- use_module(dotsrc(dot_graph_generator), [gen_dot_graph/6, dot_no_same_rank/1,
69 use_new_dot_attr_pred/7, get_dot_cluster_name/2]).
70
71 :- use_module(value_persistance,[cache_is_activated/0]).
72 :- use_module(probsrc(tools),[split_list/4]).
73
74 :- use_module(module_information,[module_info/2]).
75 :- module_info(group,ast).
76 :- module_info(description,'This module provides functionality to visualize the dependencies of a B machine (include and sees relations, etc.).').
77
78 :- volatile
79 main_machine_name/1,
80 machine_type/2,
81 machine_package_directory/2,
82 machine_references/2,
83 machine_identifiers/7,
84 machine_operations/2,
85 machine_operation_calls/2,
86 machine_values_identifiers/2,
87 refines_event/4,
88 machine_has_assertions/1,
89 raw_machine/2,
90 machine_hash_cached/2,
91 properties_hash_cached/2, operation_hash_cached/3,
92 basic_operation_hash/4,
93 event_refinement_change/6.
94 :- dynamic
95 main_machine_name/1,
96 machine_type/2,
97 machine_package_directory/2,
98 machine_references/2,
99 machine_identifiers/7,
100 machine_operations/2,
101 machine_operation_calls/2,
102 machine_values_identifiers/2,
103 refines_event/4,
104 machine_has_assertions/1,
105 raw_machine/2,
106 machine_hash_cached/2,
107 properties_hash_cached/2, operation_hash_cached/3,
108 basic_operation_hash/4,
109 event_refinement_change/6.
110 :- volatile abstract_constant/2, concrete_constant/2.
111 :- dynamic abstract_constant/2.
112 :- dynamic concrete_constant/2.
113
114 :- use_module(specfile,[animation_minor_mode/1]).
115 possibly_abstract_constant(ID) :-
116 (abstract_constant(ID,_) ; animation_minor_mode(eventb),concrete_constant(ID,_) ).
117
118 reset_hierarchy :-
119 retract_all(main_machine_name/1),
120 retract_all(machine_type/2),
121 retract_all(machine_package_directory/2),
122 retract_all(machine_references/2),
123 retract_all(machine_identifiers/7),
124 retract_all(abstract_constant/2),
125 retract_all(concrete_constant/2),
126 retract_all(machine_operations/2),
127 retract_all(machine_operation_calls/2),
128 retract_all(machine_values_identifiers/2),
129 retract_all(refines_event/4),
130 retract_all(machine_has_assertions/1),
131 retract_all(machine_hash_cached/2),
132 retract_all(raw_machine/2),
133 retract_all(properties_hash_cached/2),
134 retract_all(operation_hash_cached/3),
135 retract_all(basic_operation_hash/4),
136 retract_all(event_refinement_change/6).
137
138 machine_name(Name) :- machine_type(Name,_).
139
140 :- use_module(eventhandling,[register_event_listener/3]).
141 :- register_event_listener(clear_specification,reset_hierarchy,
142 'Reset B Machine Hierarchy Facts.').
143
144 retract_all(Functor/Arity) :-
145 functor(Pattern,Functor,Arity),
146 retractall(Pattern).
147
148 analyse_hierarchy(Main,Machines) :- (var(Main) ; var(Machines)),!,
149 add_internal_error('Illegal call:',analyse_hierarchy(Main,Machines)).
150 analyse_hierarchy(Main,Machines) :-
151 reset_hierarchy,
152 assertz(main_machine_name(Main)),
153 analyse_machine(Main,Machines,main).
154
155 :- use_module(error_manager).
156 :- use_module(tools_strings,[ajoin/2]).
157 :- use_module(bmachine,[b_filenumber/4]).
158 :- public analyse_machine/3.
159 analyse_machine(Name,_Machines,_) :-
160 % machine already analysed
161 machine_type(Name,_),!.
162 analyse_machine(Name,Machines,_) :-
163 debug:debug_println(19,analysing_machine(Name)),
164 get_machine(Name,Machines,Type,Header,Refines,Body),
165 !,
166 ( cache_is_activated -> % we need the machines stored for later analysis
167 assert_all_machines(Machines)
168 ; true),
169 assertz(machine_type(Name,Type)),
170 (get_machine_parent_directory(Name,Dir) -> assertz(machine_package_directory(Name,Dir)) ; true),
171 ( get_raw_section(assertions,Body,_) ->
172 assertz(machine_has_assertions(Name))
173 ; true),
174 store_identifiers(Name,Header,Body),
175 store_operations(Name,Body),
176 store_values(Name,Body),
177 store_references(Name,Refines,Body,Machines).
178 analyse_machine(Name,Machines,RefType) :-
179 get_machine_file_number(Name,_Ext,Nr,File),
180 get_ref_type_name(RefType,Clause),
181 !,
182 ( member(M,Machines),get_constructed_machine_name_and_filenumber(M,OtherName,Nr)
183 -> ajoin(['Cannot use B machine "',Name,'" within ', Clause,
184 ' clause. Rename machine "', OtherName,'" to "', Name, '" in file: '],Msg)
185 ; findall(MN,b_filenumber(MN,_,_,_),List),
186 ajoin(['Cannot find B machine "',Name,'" within ', Clause,
187 ' clause (available: ',List,'). Check that machine name matches filename in: '],Msg)
188 ),
189 add_error_fail(invalid_machine_reference,Msg,File).
190 analyse_machine(Name,_Machines,_RefType) :-
191 bmachine:portray_filenumbers,
192 add_error_fail(invalid_machine_reference,
193 'Could not find machine in parsed machine list (check that your machine names match your filenames): ',Name).
194
195 :- use_module(tools,[get_parent_directory_name/2]).
196 get_machine_parent_directory(Name,DirName) :-
197 % try and get parent directory name; useful to distinguish different packages when using package pragma
198 get_machine_file_number(Name,_Ext,_Nr,File),
199 get_parent_directory_name(File,DirName).
200
201
202 % store the un-typed input syntax tree for later analysis
203 assert_all_machines(Machines) :-
204 (raw_machine(_,_)
205 -> true % machines already asserted
206 ; maplist(assert_raw_machine,Machines)).
207 assert_raw_machine(Machine) :-
208 get_raw_machine_name(Machine,Name),
209 (raw_machine(Name,_) -> add_warning(b_machine_hierarchy,'Raw machine already exists: ',Name) ; true),
210 assertz( raw_machine(Name,Machine) ).
211
212 machine_has_constants(MachName) :-
213 machine_identifiers(MachName,_,_,_,_,AConsts,CConsts),
214 (AConsts=[] -> CConsts = [_|_] ; true).
215
216 get_machine_short_desc(MachName,Text) :-
217 machine_identifiers(MachName,Params,Sets,AVars,CVars,AConsts,CConsts),
218 length(Params,PL), length(Sets,SL), length(AVars,AVL), length(CVars,CVL), VL is AVL+CVL,
219 length(AConsts,ACL), length(CConsts,CCL), CL is ACL+CCL,
220 (machine_operations(MachName,Ops), length(Ops,OL) -> true ; OL=0),
221 ajoin(['SETS:',SL,' CONSTANTS:',CL,' VARIABLES:',VL, ' PARAMETERS:',PL, ' OPERATIONS:',OL],Text).
222
223 store_identifiers(Name,Header,Body) :-
224 get_parameters(Header,Params),
225 get_sets(Body,Sets),
226 get_identifiers([abstract_variables,variables],Body,AVars),
227 get_identifiers([concrete_variables],Body,CVars),
228 get_identifiers([abstract_constants],Body,AConsts),
229 get_identifiers([concrete_constants,constants],Body,CConsts), % fixed abstract -> concrete
230 assertz(machine_identifiers(Name,Params,Sets,AVars,CVars,AConsts,CConsts)),
231 maplist(assert_raw_id_with_position(abstract_constant),AConsts),
232 maplist(assert_raw_id_with_position(concrete_constant),CConsts).
233
234
235 raw_id_is_identifier2(description(_Pos,_Desc,Raw),ID) :- !, raw_id_is_identifier2(Raw,ID).
236 raw_id_is_identifier2(deferred_set(_,ID),ID) :- !.
237 raw_id_is_identifier2(enumerated_set(_,ID,_Elements),ID) :- !.
238 raw_id_is_identifier2(Raw,ID) :- raw_id_is_identifier(Raw,_,ID).
239
240 get_machine_identifier_names(Name,Params,Sets,AVars,CVars,AConsts,CConsts) :-
241 machine_identifiers(Name,RawParams,RawSets,RawAVars,RawCVars,RawAConsts,RawCConsts),
242 maplist(raw_id_is_identifier2,RawParams,Params),
243 maplist(raw_id_is_identifier2,RawSets,Sets),
244 maplist(raw_id_is_identifier2,RawAVars,AVars),
245 maplist(raw_id_is_identifier2,RawCVars,CVars),
246 maplist(raw_id_is_identifier2,RawAConsts,AConsts),
247 maplist(raw_id_is_identifier2,RawCConsts,CConsts).
248
249
250 machine_hash(Name,Hash) :-
251 machine_hash_cached(Name,Hash1),!,Hash=Hash1.
252 machine_hash(Name,Hash) :-
253 compute_machine_hash(Name,Hash1),
254 assertz( machine_hash_cached(Name,Hash1) ),
255 Hash=Hash1.
256 compute_machine_hash(Name,Digest) :-
257 if(raw_machine(Name,Machine),
258 raw_sha_hash(Machine,Digest),
259 add_error_and_fail(compute_machine_hash,'Machine does not exist or has not been processed:',Name)
260 ).
261
262 :- use_module(pathes_extensions_db, [compile_time_unavailable_extension/2]).
263 :- if(\+ compile_time_unavailable_extension(probhash_extension, _)).
264 store_eventb_hash(Name,ContextMachTerm) :-
265 raw_sha_hash(ContextMachTerm,Digest),
266 assertz(machine_hash_cached(Name,Digest)).
267 :- else.
268 store_eventb_hash(Name,_) :-
269 assertz( (machine_hash_cached(Name,_) :-
270 add_error(b_machine_hierarchy,'prob_hash_extension not available for: ',Name),fail) ).
271 :- endif.
272
273 :- use_module(tools_strings,[get_hex_bytes/2]).
274 operation_hash(MachName,OpName,Hash) :-
275 operation_hash_cached(MachName,OpName,Hash1),!,Hash=Hash1.
276 operation_hash(MachName,OpName,Hash) :-
277 computed_basic_operation_hashes,
278 basic_operation_hash(OpName,MachName,Hash1,OpCalls),
279 (OpCalls = []
280 -> FinalHash=Hash1 % no recursive call of other operations
281 ; maplist(get_basic_op_hash,OpCalls,OpDigests),
282 raw_sha_hash(op(Hash1,OpDigests),FinalHash) % also include hash of called operations
283 ),
284 assertz( operation_hash_cached(MachName,OpName,FinalHash) ),
285 get_hex_bytes(FinalHash,Hex),
286 debug_format(19,'value caching: operation ~w in machine ~w has hash: ~s~n',[OpName,MachName,Hex]),
287 Hash=FinalHash.
288
289 get_basic_op_hash(OpName,Digest) :-
290 basic_operation_hash(OpName,_MachName,Digest,_OpCalls).
291
292 % compute basic hash, without taking recursive operation calls into account
293 computed_basic_operation_hashes :-
294 basic_operation_hash(_,_,_,_),!. % already computed
295 computed_basic_operation_hashes :-
296 get_raw_machine_operation_hash(MachName,OpName,Digest,OpCalls),
297 (basic_operation_hash(OpName,_,_,_)
298 -> add_warning(computed_basic_operation_hashes,'Multiple hashes for operation: ',OpName)
299 ; true),
300 assertz(basic_operation_hash(OpName,MachName,Digest,OpCalls)),
301 get_hex_bytes(Digest,Hex),
302 debug_format(19,'value caching: basic operation hash ~w in machine ~w: ~s (calls ~w)~n',
303 [OpName,MachName,Hex,OpCalls]),
304 fail.
305 computed_basic_operation_hashes.
306
307 % first computed basic, independent operation hashes:
308 % only look up used definitions, but not yet called operations
309 get_raw_machine_operation_hash(MachName,OpName,Digest,SOpCalls) :-
310 raw_machine(MachName,Machine),
311 get_machine(MachName,[Machine],_Type,_Header,_Refines,MachBody),
312 get_opt_section(operations,MachBody,Operations),
313 Op = operation(_,identifier(_,OpName),_,_,_),
314 member(Op,Operations),
315 get_raw_operation_id_and_body(Op,identifier(_,OpName),OpBody),
316 extract_used_np_definitions(Op,MachBody,UsedDefinitions,DefsWithPos),
317 remove_raw_position_info(Op,RawOperation),
318 raw_sha_hash(op(RawOperation,UsedDefinitions),Digest),
319 findall(Id, (get_raw_operation_call_id(OpBody,Id) % extract op calls in body of operation
320 ; get_def_body(Def,DefsWithPos), get_raw_operation_call_id(Def,Id) % extract op calls in definitions
321 ),
322 OpCalls),
323 sort(OpCalls,SOpCalls).
324
325 get_def_body(Body,Defs) :- member(definition(_,_DefName,_,Body),Defs).
326
327
328 :- use_module(debug,[debug_println/2]).
329 assert_raw_id_with_position(PredFunctor,Rid) :-
330 (raw_id_is_identifier(Rid,Pos,ID)
331 -> true
332 ; peel_desc(Rid,PRid), PRid = definition(Pos,ID,_)
333 -> add_error(illegal_definition_use,'Definition cannot be used as identifier here: ',ID,Pos)
334 ; add_error_fail(assert_raw_id_with_position,'Not identifier: ',Rid)
335 ),
336 Fact =.. [PredFunctor,ID,Pos],
337 assertz(Fact), debug_println(9,Fact).
338
339 raw_id_is_identifier(identifier(Pos,ID),Pos,ID).
340 raw_id_is_identifier(unit(_,_,identifier(Pos,ID)),Pos,ID).
341 raw_id_is_identifier(new_unit(_,_,identifier(Pos,ID)),Pos,ID).
342 raw_id_is_identifier(inferred_unit(_,_,identifier(Pos,ID)),Pos,ID).
343 raw_id_is_identifier(inferredunit(_,_,identifier(Pos,ID)),Pos,ID). % the (new?) parser seems to generate the wrong pragma in the .prob file; TO DO: investigate
344 raw_id_is_identifier(description(_,_,RawID),Pos,ID) :-
345 raw_id_is_identifier(RawID,Pos,ID).
346
347 peel_desc(description(_,_,E),R) :- !, peel_desc(E,R).
348 peel_desc(R,R).
349
350 get_raw_identifier(Raw,Res) :- raw_id_is_identifier(Raw,_Pos,Id),!, Res=Id.
351 get_raw_identifier(definition(_Pos,DID,[]),ID) :- % see also expand_definition_to_variable_list
352 atom(DID),!,
353 ajoin([DID,'(DEFINITION)'],ID).
354 get_raw_identifier(deferred_set(_Pos,DID),ID) :- atom(DID),!, ID=DID.
355 get_raw_identifier(enumerated_set(_Pos,DID,_List),ID) :- atom(DID),!, ID=DID.
356 get_raw_identifier(description(_,_,RawID),ID) :- !,
357 get_raw_identifier(RawID,ID).
358 get_raw_identifier(Raw,Res) :- add_internal_error('Cannot get identifier:',Raw),Res='???'.
359
360 raw_identifier_member(ID,List) :- member(Raw,List), raw_id_is_identifier(Raw,_Pos,ID).
361
362 store_operations(MachName,Body) :-
363 get_opt_section(operations,Body,Operations),
364 findall(I,(member(Op,Operations),get_raw_operation_id_and_body(Op,I,_)),Ids),
365 assertz(machine_operations(MachName,Ids)),
366 findall(calls(I1,I2),(member(Op,Operations),get_raw_operation_call(Op,I1,I2)),Calls),
367 sort(Calls,SCalls),
368 debug_println(9,machine_operation_calls(MachName,SCalls)),
369 assertz(machine_operation_calls(MachName,SCalls)).
370
371 get_raw_operation_id_and_body(operation(_Pos,Id,_,_,Body),Id,Body).
372 get_raw_operation_id_and_body(refined_operation(_Pos,Id,_Results,_Args,_RefinesID,Body),Id,Body).
373 get_raw_operation_id_and_body(description_operation(_Pos,_,Op),Id,Body) :- get_raw_operation_id_and_body(Op,Id,Body).
374
375 % get operations called in body
376 get_raw_operation_call(Op,Id,CallsId) :-
377 get_raw_operation_id_and_body(Op,identifier(_,Id),Body),
378 get_raw_operation_call(Body,identifier(_,CallsId)).
379
380 :- use_module(debug,[debug_format/3]).
381 get_raw_operation_call(block(_,Body),ID) :- !, get_raw_operation_call(Body,ID).
382 get_raw_operation_call(precondition(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
383 get_raw_operation_call(assertion(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
384 get_raw_operation_call(witness_then(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
385 get_raw_operation_call(var(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
386 get_raw_operation_call(select_when(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
387 get_raw_operation_call(if_elsif(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
388 get_raw_operation_call(let(_,_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
389 get_raw_operation_call(any(_,_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
390 get_raw_operation_call(case(_,_,_,_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
391 get_raw_operation_call(while(_,_Cond,Body,_,_),ID) :- !, get_raw_operation_call(Body,ID).
392 get_raw_operation_call(parallel(_,List),ID) :- !,member(A,List), get_raw_operation_call(A,ID).
393 get_raw_operation_call(sequence(_,List),ID) :- !,member(A,List), get_raw_operation_call(A,ID).
394 get_raw_operation_call(if(_,_Test,Then,List,Else),ID) :- !,member(A,[Then,Else|List]), get_raw_operation_call(A,ID).
395 get_raw_operation_call(select(_,_Cond,Body,List),ID) :- !,member(A,[Body|List]), get_raw_operation_call(A,ID).
396 get_raw_operation_call(select(_,_Cond,Body,List,Else),ID) :- !,member(A,[Body,Else|List]), get_raw_operation_call(A,ID).
397 get_raw_operation_call(choice(_,List),ID) :- !,member(A,List), get_raw_operation_call(A,ID).
398 get_raw_operation_call(choice_or(_,Body),ID) :- !, get_raw_operation_call(Body,ID).
399 get_raw_operation_call(operation_call(_,ID,_,_),ID) :- !.
400 get_raw_operation_call(skip(_),_) :- !, fail.
401 get_raw_operation_call(assign(_,_,_),_) :- !, fail.
402 get_raw_operation_call(becomes_element_of(_,_,_),_) :- !, fail.
403 get_raw_operation_call(becomes_such(_,_,_),_) :- !, fail.
404 get_raw_operation_call(definition(_,Name,_),_) :- !, % TO DO: improve
405 debug_format(19,'Ignoring operation calls in DEFINITION ~w for operation call diagram~n',[Name]),
406 % b_get_definition(Name,_DefType,_Args,DefBody,_Deps), not yet precompiled !
407 fail.
408 get_raw_operation_call(Subst,_) :- functor(Subst,F,N),print(uncovered_subst(F,N,Subst)),nl,fail.
409 % we also do not find operation calls in expressions
410
411 :- use_module(input_syntax_tree,[raw_operator_term/1, raw_literal_term/1, raw_special_set_term/1]).
412 % avoid spurious uncovered_subst messages in a context where we are not sure we have a subst
413 try_get_raw_operation_call(Term,_) :- raw_literal_term(Term),!, fail.
414 try_get_raw_operation_call(Term,_) :- raw_operator_term(Term),!, fail.
415 try_get_raw_operation_call(Term,_) :- raw_special_set_term(Term),!, fail.
416 try_get_raw_operation_call(Term,_) :- functor(Term,F,_), definitely_not_subst(F),!, fail.
417 try_get_raw_operation_call(Body,ID) :- get_raw_operation_call(Body,ID).
418
419 % definitely expression:
420 definitely_not_subst(let_expression).
421 definitely_not_subst(let_predicate).
422 % definitely predicate:
423 definitely_not_subst(external_function_call).
424 definitely_not_subst(external_pred_call).
425
426 get_raw_operation_call_id(OpBody,CalledId) :-
427 try_get_raw_operation_call(OpBody,identifier(_,CalledId)).
428
429 store_references(Name,Refines,Body,Machines) :-
430 get_refinements(Refines,Refs1),
431 get_references(Body,Refs2),
432 append(Refs1,Refs2,Refs),
433 assertz(machine_references(Name,Refs)),
434 follow_refs(Refs,Machines).
435
436 get_references(Body,Refs) :-
437 findrefs(Body,includes,Includes),
438 findrefs(Body,extends,Extends),
439 findrefs(Body,imports,Imports),
440 findusessees(Body,uses,Uses),
441 findusessees(Body,sees,Sees),
442 append([Includes,Imports,Extends,Uses,Sees],Refs).
443
444 get_refinements([],[]).
445 get_refinements([Name|NRest],[ref(refines,Name,'')|RRest]) :-
446 get_refinements(NRest,RRest).
447
448 findrefs(Body,Type,Refs) :-
449 get_opt_section(Type,Body,RawRefs),
450 findrefs2(RawRefs,Type,Refs).
451 findrefs2([],_Type,[]).
452 findrefs2([MID|MRest],Type,[ref(Type,Name,Prefix)|RRest]) :-
453 get_machine_id(MID,FullName), % should be machine_reference
454 bmachine_construction:split_prefix(FullName,Prefix,Name),
455 findrefs2(MRest,Type,RRest).
456
457 findusessees(Body,Type,Refs) :-
458 get_opt_section(Type,Body,RawRefs),
459 findusessees2(RawRefs,Type,Refs).
460 findusessees2([],_Type,[]).
461 findusessees2([MID|MRest],Type,[ref(Type,Name,Prefix)|RRest]) :-
462 get_machine_id(MID,FullName), % should be machine_reference
463 % USE and SEES do not have machine_reference in AST but identifier
464 bmachine_construction:split_prefix(FullName,Prefix,Name),
465 findusessees2(MRest,Type,RRest).
466
467 get_machine_id(identifier(_Pos,FN),FullName) :- !, FullName=FN.
468 get_machine_id(machine_reference(_Pos,FN,_Params),FullName) :- !, FullName=FN.
469 get_machine_id(Other,_) :- add_internal_error('Illegal machine id: ',get_machine_id(Other,_)),fail.
470
471 :- use_module(probsrc(tools),[split_atom/3]).
472 follow_refs([],_Machines).
473 follow_refs([ref(RefType,Name,_Prefix)|Rest],Machines) :-
474 analyse_machine(Name,Machines,RefType),
475 follow_refs(Rest,Machines).
476
477 get_parameters(machine_header(_Pos,_Name,Params),Params).
478
479 get_sets(Body,Sets) :-
480 get_opt_section(sets,Body,Sets).
481
482 get_identifiers([],_Body,[]).
483 get_identifiers([Sec|Rest],Body,Ids) :-
484 get_opt_section(Sec,Body,Ids1),
485 append(Ids1,IRest,Ids),
486 get_identifiers(Rest,Body,IRest).
487
488 get_opt_sections([],_Body,[]).
489 get_opt_sections([S|Srest],Body,Contents) :-
490 get_opt_section(S,Body,L),append(L,Rest,Contents),
491 get_opt_sections(Srest,Body,Rest).
492
493 get_opt_section(Sec,Body,Result) :-
494 ( get_raw_section(Sec,Body,Content) -> Result=Content; Result=[]).
495 get_raw_section(Sec,Body,Content) :- % look for Sec(_Pos,Content) in Body list
496 functor(Pattern,Sec,2),arg(2,Pattern,Content),
497 memberchk(Pattern,Body).
498
499 get_machine(Name,Machines,Type,Header,Refines,Body) :-
500 get_machine1(Name,Machines,_Machine,Type,Header,Refines,Body).
501 %get_raw_machine(Name,Machines,Machine) :-
502 % get_machine1(Name,Machines,Machine,_Type,_Header,_Refines,_Body).
503 get_machine1(Name,Machines,Machine,Type,Header,Refines,Body) :-
504 Header = machine_header(_Pos,Name,_Params),
505 member(Machine,Machines),
506 get_machine2(Machine,Type,Header,Refines,Body),!.
507 get_machine2(abstract_machine(_Pos,MS,Header,Body),TypeOfAbstractMachine,Header,[],Body) :-
508 get_abstract_machine_type(MS,TypeOfAbstractMachine).
509 get_machine2(refinement_machine(_Pos,Header,Refines,Body),refinement,Header,[Refines],Body).
510 get_machine2(implementation_machine(_Pos,Header,Refines,Body),implementation,Header,[Refines],Body).
511 get_machine2(generated(_Pos,Machine),A,B,C,D) :- % @generated Pragma used at top of file
512 get_machine2(Machine,A,B,C,D).
513 get_machine2(unit_alias(_Pos,_Name,_Alias,Machine),A,B,C,D) :-
514 get_machine2(Machine,A,B,C,D).
515
516 get_raw_machine_name(Machine,Name) :-
517 get_machine2(Machine,_,machine_header(_,Name,_),_,_).
518
519 get_abstract_machine_type(machine(_Pos2),R) :- !,R=abstract_machine.
520 get_abstract_machine_type(system(_Pos2),R) :- !,R=abstract_machine.
521 get_abstract_machine_type(model(_Pos2),R) :- !,R=abstract_model.
522 get_abstract_machine_type(X,R) :- atomic(X),!,
523 add_error(get_abstract_machine_type,'Your parser seems out-dated. Assuming abstract_machine: ',X),
524 R=abstract_machine.
525
526
527 get_values_id(values_entry(Pos,ID,_Val),identifier(Pos,ID)).
528 % Store the identifiers assigned to in VALUES clauses
529 store_values(Name,Body) :-
530 get_opt_section('values',Body,Values),!,
531 maplist(get_values_id,Values,ValuesIDs),
532 assertz(machine_values_identifiers(Name,ValuesIDs)).
533 store_values(_,_).
534
535 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
536
537 % write dot operation call graph
538 write_dot_op_hierarchy_to_file(File) :-
539 (get_preference(dot_event_hierarchy_horizontal,true) -> PageOpts=[rankdir/'LR'] ; PageOpts=[]),
540 gen_dot_graph(File,PageOpts,dot_operation_node,dot_op_calls_op,dot_no_same_rank,dot_subgraph(op_hierarchy)).
541
542
543 :- use_module(bmachine,[b_top_level_operation/1, b_top_level_feasible_operation/1]).
544 dot_operation_node(OpName,M,Desc,Shape,Style,Color) :-
545 machine_operations(M,Operations),
546 (machine_promotes_operations(M,Promotes) -> true ; Promotes=[]),
547 raw_identifier_member(OpName,Operations),
548 (b_top_level_feasible_operation(OpName) -> Color=lightgray
549 ; b_top_level_operation(OpName) -> Color='OldLace' % commented out operation
550 ; raw_identifier_member(OpName,Promotes) -> Color='gray98' % promoted but not to top_level
551 ; Color=white),
552 Desc=OpName, Shape=box, Style=filled.
553
554 dot_op_calls_op(Op1,Label,Op2,Color,Style) :- Style=solid, Color=steelblue,
555 Label = '', % TO DO: different colors for local operation calls, detect op calls in expressions?
556 machine_operation_calls(_,Operations),
557 member(calls(Op1,Op2),Operations).
558
559
560
561 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
562 % print hierarchy to dot file
563
564 maxlinelength(30).
565
566 :- use_module(tools_io).
567
568 % write hierarchy of machines, with inclusion/refinement links
569 write_dot_hierarchy_to_file(Filename) :-
570 findall(M,machine_type(M,_),Machines),
571 safe_open_file(Filename,write,S,[]),
572 ( print_header(S),
573 print_machines(S,1,Machines,Ids),
574 print_refs_for_dot(S,Ids,Ids),
575 print_footer(S)
576 -> true
577 ; add_internal_error('Command failed:',write_dot_hierarchy_to_file(Filename))
578 ),
579 close(S).
580
581 print_header(S) :-
582 write(S,'digraph module_hierarchy {\n'),
583 write(S,' graph [page="8.5, 11",ratio=fill,size="7.5,10"];\n').
584 print_footer(S) :-
585 write(S,'}\n').
586
587 print_machines(_S,_Nr,[],[]).
588 print_machines(S,Nr,[M|Machines],[id(M,Nr)|Ids]) :-
589 (print_machine(S,Nr,M) -> true
590 ; add_internal_error('Printing machine for hierarchy failed: ',print_machine(S,Nr,M))
591 ),
592 Nr2 is Nr + 1,
593 print_machines(S,Nr2,Machines,Ids).
594 print_machine(S,Nr,M) :-
595 write(S,' '),write(S,Nr),
596 (main_machine_name(M) ->
597 write(S,' [shape=record, style=bold, color=darkgreen, label=\"|{')
598 ; write(S,' [shape=record, color=steelblue, label=\"|{')),
599 print_machine_header(S,M),
600 machine_identifiers(M,_Params,Sets,AVars,CVars,AConsts,CConsts),
601 %print_hash(S,M),
602 print_sets(S,Sets),
603 print_identifiers(S,'VARIABLES',AVars),
604 print_identifiers(S,'CONCRETE VARIABLES',CVars),
605 print_identifiers(S,'ABSTRACT CONSTANTS',AConsts),
606 print_identifiers(S,'CONSTANTS',CConsts),
607 (machine_values_identifiers(M,VConsts)
608 -> print_identifiers(S,'VALUES',VConsts)
609 ; true),
610 ( machine_has_assertions(M) ->
611 get_specification_description(assertions,AssStr),
612 print_title(S,AssStr)
613 ; true
614 ),
615 (machine_promotes_operations(M,Promotes)
616 -> print_identifiers(S,'PROMOTES',Promotes) ; true),
617 machine_operations(M,Operations),
618 delete(Operations,identifier(_,'INITIALISATION'),Operations2),
619 exclude(is_refinining_event(M),Operations2,RefiningOperations),
620 include(is_refinining_event(M),Operations2,NewOperations),
621 ((RefiningOperations=[] ; NewOperations=[])
622 -> get_specification_description(operations,OpStr),
623 print_identifiers(S,OpStr,Operations2)
624 ; print_identifiers(S,'EVENTS (refining)',RefiningOperations),
625 print_identifiers(S,'EVENTS (new)',NewOperations)
626 ),
627
628 write(S,'}|\"];\n').
629
630 is_refinining_event(M,identifier(_,Event)) :- (refines_event(M,Event,_,_) -> true).
631
632 %print_hash(S,M) :- machine_hash(M,Digest),!,print_title(S,'Digest'),
633 % maplist(format(S,'~16r'),Digest),write(S,'\\n').
634 %print_hash(_S,_M).
635
636 %get_machine_colour(M,steelblue) :- main_machine_name(M),!.
637 %get_machine_colour(_M,steelblue).
638
639 print_machine_header(S,M) :-
640 machine_type(M,Type),
641 get_machine_type_keyw(Type,P),
642 write(S,P),write(S,' '),
643 write(S,M),
644 (machine_package_directory(M,Dir), machine_package_directory(_M2,D2), D2 \= Dir
645 -> format(S,' (~w)',[Dir]) % show the name of the directory; probably the package pragma was used
646 ; true),
647 write(S,'\\n').
648 get_machine_type_keyw(abstract_machine,'MACHINE').
649 get_machine_type_keyw(abstract_model,'MODEL').
650 get_machine_type_keyw(refinement,'REFINEMENT').
651 get_machine_type_keyw(implementation,'IMPLEMENTATION').
652 get_machine_type_keyw(context,'CONTEXT').
653
654 print_sets(_,[]) :- !.
655 print_sets(S,Sets) :-
656 write(S,'|SETS\\n'),
657 print_sets2(Sets,S).
658 print_sets2([],_).
659 print_sets2([Set|Rest],S) :-
660 print_set(Set,S),
661 write(S,'\\n'),
662 print_sets2(Rest,S).
663 print_set(description(_Pos,_Desc,Raw),S) :- print_set(Raw,S).
664 print_set(deferred_set(_Pos,Name),S) :-
665 write_id(S,Name).
666 print_set(enumerated_set(_Pos,Name,List),S) :-
667 write_id(S,Name),write(S,' = \\{'),
668 maxlinelength(Max),
669 preferences:get_preference(dot_hierarchy_max_ids,MaxIdsToPrint),
670 print_set_elements(List,S,Max,MaxIdsToPrint),
671 write(S,'\\}').
672 print_set_elements([],_,_,_).
673 print_set_elements([RawID],S,_LenSoFar,_) :-
674 raw_id_is_identifier(RawID,_,Name),
675 !,write_id(S,Name).
676 print_set_elements([RawID,B|Rest],S,LenSoFar,MaxIdsToPrint) :-
677 raw_id_is_identifier(RawID,_,Name),
678 dec_atom_length(LenSoFar,Name,NewLen),
679 (NewLen<0 -> maxlinelength(NL0),NL is NL0-1,write(S,'\\n ') ; NL is NewLen-1),
680 write_id(S,Name),write(S,','),
681 M1 is MaxIdsToPrint-1,
682 (M1 < 1, Rest \= []
683 -> write(S,'...,'),
684 last([B|Rest],Last), print_set_elements([Last],S,NL,M1)
685 ; print_set_elements([B|Rest],S,NL,M1)
686 ).
687
688 :- use_module(tools,[string_escape/2]).
689 % write identifier and escape it for dot
690 write_id(S,Name) :- string_escape(Name,EName), write(S,EName).
691
692 dec_atom_length(Prev,Atom,New) :- atom_length(Atom,Len),
693 New is Prev-Len.
694
695 print_title(S,Title) :-
696 write(S,'|'),
697 write(S,Title),write(S,'\\n').
698 print_identifiers(_S,_,[]) :- !.
699 print_identifiers(S,Title,List) :-
700 print_title(S,Title),
701 preferences:get_preference(dot_hierarchy_max_ids,MaxIdsToPrint), % how many do we print overall; -1 means print all of them
702 print_identifiers2(List,0,_,S,MaxIdsToPrint).
703 print_identifiers2([],Count,Count,_,_MaxIdsToPrint).
704 print_identifiers2([RawID|Rest],Count,NCount,S,MaxIdsToPrint) :-
705 get_raw_identifier(RawID,Name),
706 (MaxIdsToPrint = 0,Rest\=[]
707 -> length(Rest,Len), RN is Len+1,
708 format(S,' (~w more)',[RN])
709 ; MaxIdsToPrint1 is MaxIdsToPrint-1,
710 print_identifier(Name,Count,ICount,S),
711 (Rest = [] -> true; write(S,',')),
712 print_identifiers2(Rest,ICount,NCount,S,MaxIdsToPrint1)
713 ).
714 print_identifier(Name,Count,NewCount,S) :-
715 atom_codes(Name,Codes),
716 length(Codes,Length),
717 NewCount1 is Count+Length,
718 maxlinelength(Max),
719 ( Count == 0 -> NewCount1=NewCount
720 ; NewCount1 =< Max -> NewCount1=NewCount
721 ; NewCount=0,write(S,'\\n')),
722 write_id(S,Name).
723
724 % print machine inclusion references for dot graph
725 print_refs_for_dot(_S,[],_).
726 print_refs_for_dot(S,[id(M,Nr)|Rest],Ids) :-
727 machine_references(M,Refs),
728 filter_redundant_refs(Refs,Refs,UsefulRefs),
729 print_refs2(UsefulRefs,M,Nr,Ids,S),
730 print_refs_for_dot(S,Rest,Ids).
731 print_refs2([],_,_,_,_).
732 print_refs2([ref(Type,Dest,Prefix)|Rest],M,Nr,Ids,S) :-
733 member(id(Dest,DestNr),Ids),!,
734 get_ref_type_name(Type,RefName),
735 (Prefix='' -> Label=RefName ; ajoin([RefName,' (',Prefix,')'],Label)),
736 get_ref_type(Type,Col,Style,Dir), !, % TO DO: add prefix info
737 (Dir=reverse ->
738 format(S,' ~w -> ~w [label=\"~w\",color=~w,style=\"~w\"];~n',[DestNr,Nr,Label,Col,Style])
739 ; format(S,' ~w -> ~w [label=\"~w\",color=~w,style=\"~w\"];~n',[Nr,DestNr,Label,Col,Style])
740 ),
741 print_refs2(Rest,M,Nr,Ids,S).
742 get_ref_type(includes,navyblue,'',normal).
743 get_ref_type(imports,navyblue,'',normal).
744 get_ref_type(extends,navyblue,'',normal).
745 get_ref_type(uses,navyblue,dashed,normal).
746 get_ref_type(sees,navyblue,dashed,normal).
747 get_ref_type(refines,navyblue,bold,reverse). % reverse so that abstract machines are shown on top
748 get_ref_type(UNKNOWN,red,bold,normal) :-
749 add_internal_error('Unknown : ',get_ref_type(UNKNOWN,_,_,_)).
750
751 get_ref_type_name(includes,'INCLUDES').
752 get_ref_type_name(imports,'IMPORTS').
753 get_ref_type_name(extends,'EXTENDS').
754 get_ref_type_name(uses,'USES').
755 get_ref_type_name(sees,'SEES').
756 get_ref_type_name(refines,'REFINEMENT').
757 get_ref_type_name(main,'MACHINE').
758 get_ref_type_name(UNKNOWN,UNKNOWN).
759
760
761 % remove redundant references (has to be done after analyse_eventb_machine has asserted all facts)
762 filter_redundant_refs([],_,[]).
763 filter_redundant_refs([ref(sees,Dest,_)|T],All,R) :-
764 machine_type(Dest,context),
765 member(ref(sees,Other,_),All),
766 machine_references(Other,Refs),
767 member(ref(extends,Dest,_),Refs), % Dest already seen by other seen context;
768 % Note: Rodin export contains transitive sees relation;
769 % if the user had included Dest in the sees clause we would have a warning "Redundant seen context"
770 !,
771 %format(user_output,'Redundant sees of ~w (~w)~n',[Dest,Other]),
772 filter_redundant_refs(T,All,R).
773 filter_redundant_refs([H|T],All,[H|R]) :-
774 filter_redundant_refs(T,All,R).
775
776 /************************************************************************/
777 /* The same for Event-B */
778 /************************************************************************/
779
780 analyse_eventb_hierarchy(Machines,Contextes) :-
781 reset_hierarchy,
782 get_eventb_name(Machines,Contextes,MainName),
783 assertz(main_machine_name(MainName)),
784 maplist(analyse_eventb_machine,Machines),
785 analyse_eventb_refinement_types(Machines),
786 maplist(analyse_eventb_context,Contextes),!.
787 analyse_eventb_hierarchy(Machines,Contextes) :-
788 add_internal_error('Analyzing Event-B Hierarchy Failed: ',analyse_eventb_hierarchy(Machines,Contextes)).
789
790 get_eventb_name([MainMachine|_AbstractMachines],_Contextes,Name) :-
791 event_b_model(MainMachine,Name,_),!.
792 get_eventb_name(_Machines,[MainContext|_AbstractContextes],Name) :-
793 event_b_context(MainContext,Name,_).
794
795 event_b_model(event_b_model(_,Name,Sections),Name,Sections).
796 event_b_context(event_b_context(_,Name,Sections),Name,Sections).
797
798 analyse_eventb_machine(Machine) :-
799 event_b_model(Machine,Name,Sections),
800 % print(analyzing(Name)),nl,
801 ( memberchk(refines(_,RName),Sections) -> Type=refinement, RRefs=[ref(refines,RName,'')]
802 ; Type=abstract_model, RRefs=[], RName='$none'),
803 get_identifiers([variables],Sections,Vars),
804 get_sees_context_refs(Sections,SRefs),
805 append(RRefs,SRefs,Refs),
806 get_events(Name,Sections,Events,RName),
807 store_eventb_hash(Name,Machine),
808 assertz(machine_type(Name,Type)),
809 assertz(machine_identifiers(Name,[],[],Vars,[],[],[])),
810 assertz(machine_references(Name,Refs)),
811 assertz(machine_operations(Name,Events)),
812 assertz(machine_operation_calls(Name,[])), % Event-B events cannot call other events
813 assert_if_has_theorems(Name,Sections).
814
815
816 % analyze which kinds of refinments we have between events
817 analyse_eventb_refinement_types([]).
818 analyse_eventb_refinement_types([RefMachine,AbsMachine|_]) :-
819 event_b_model(RefMachine,RefName,RefSections),
820 memberchk(refines(_,AbsName),RefSections),
821 event_b_model(AbsMachine,AbsName,AbsSections),
822 get_opt_section(events,RefSections,RawEvents),
823 get_opt_section(events,AbsSections,AbsRawEvents),
824 member(RawEvent,RawEvents),
825 bmachine_eventb:raw_event(RawEvent,_,RefEvName,_St1,Ref,_Prm1,RefGrd,_Thm1,RefAct,_Wit1,_Desc1),
826 Ref = [AbsEvName],
827 member(AbsRawEvent,AbsRawEvents),
828 bmachine_eventb:raw_event(AbsRawEvent,_,AbsEvName,_St2,_,_Prm2,AbsGrd,_Thm2,AbsAct,_Wit2,_Desc2),
829 check_raw_prefix(AbsGrd,RefGrd,SameGuard),
830 check_raw_prefix(AbsAct,RefAct,SameAct),
831 %% format('~nEvent refinement change ~w (~w) -> ~w (~w) guard: ~w, action: ~w~n',[RefEvName,RefName,AbsEvName,AbsName,SameGuard,SameAct]),
832 %print(rawgrd(RefGrd,AbsGrd)), nl, print(rawact(RefAct,AbsAct)),nl,
833 assertz(event_refinement_change(RefName,RefEvName,AbsName,AbsEvName,SameGuard,SameAct)),
834 fail.
835 analyse_eventb_refinement_types([_|T]) :- analyse_eventb_refinement_types(T).
836
837 check_raw_prefix([],[],Res) :- !, Res=unchanged.
838 check_raw_prefix([],[_|_],Res) :- !, Res=extends. % the refinement has some more actions/guards
839 check_raw_prefix([Abs|AT],[Ref|RT],Result) :- same_raw_expression(Abs,Ref),!,
840 check_raw_prefix(AT,RT,Result).
841 check_raw_prefix(_,_,refines).
842
843 % TO DO: check if we have a more complete version of this predicate; to do: handle @desc description/3 terms
844 same_raw_expression(identifier(_,A),RHS) :- !, RHS=identifier(_,B), A=B.
845 same_raw_expression(equal(_,A,B),RHS) :- !, RHS=equal(_,A2,B2), same_raw_expression(A,A2), same_raw_expression(B,B2).
846 same_raw_expression(assign(_,A1,A2),RHS) :- !, RHS=assign(_,B1,B2),
847 maplist(same_raw_expression,A1,B1), maplist(same_raw_expression,A2,B2).
848 same_raw_expression(A,B) :- atomic(A),!, A=B.
849 same_raw_expression(A,B) :- A =.. [F,_|AA], % print(match(F,AA)),nl,
850 B=.. [F,_|BB], maplist(same_raw_expression,AA,BB).
851
852
853
854 get_sees_context_refs(Sections,SRefs) :-
855 get_opt_section(sees,Sections,Seen),
856 findall(ref(sees,I,''),member(I,Seen),SRefs).
857
858 :- use_module(bmachine_eventb,[raw_event/11]).
859 get_events(Name,Sections,Events,AbsMachineName) :-
860 get_opt_section(events,Sections,RawEvents),
861 compute_event_refines(Name,RawEvents,AbsMachineName),
862 findall( identifier(Pos,EvName),
863 ( member(RawEvent,RawEvents),
864 raw_event(RawEvent,Pos,EvName,_St,_Rf,_Prm,_Grd,_Thm,_Act,_Wit,_Desc) ),
865 Events).
866
867 % TO DO: detect when an event extends another one without changing it
868 compute_event_refines(MachineName,RawEvents,AbsMachineName) :-
869 member(RawEvent,RawEvents),
870 bmachine_eventb:raw_event(RawEvent,_Pos,EvName,_St,Refines,_Prm,_Grd,_Thm,_Act,_Wit,_Desc),
871 member(RefEvent,Refines),
872 % print(refines(MachineName,EvName,AbsMachineName,RefEvent)),nl,
873 assertz(refines_event(MachineName,EvName,AbsMachineName,RefEvent)),
874 fail.
875 compute_event_refines(_,_,_).
876
877
878 % try and get the name of the machine we refine
879 %machine_refines(Machine,AbsMachine) :- machine_references(Machine,Refs), member(ref(refines,AbsMachine,_),Refs).
880
881 analyse_eventb_context(Context) :-
882 event_b_context(Context,Name,Sections),
883 get_identifiers([constants],Sections,ConcreteConstants),
884 get_identifiers([abstract_constants],Sections,AbstractConstants),
885 append([ConcreteConstants,AbstractConstants],AllConstants),
886 get_sets(Sections,Sets),
887 get_extends_refs(Sections,Refs),
888 store_eventb_hash(Name,Context),
889 assertz(machine_type(Name,context)),
890 assertz(machine_identifiers(Name,[],Sets,[],[],[],AllConstants)),
891 assertz(machine_references(Name,Refs)),
892 assertz(machine_operations(Name,[])),
893 assertz(machine_operation_calls(Name,[])),
894 maplist(assert_raw_id_with_position(concrete_constant),ConcreteConstants),
895 maplist(assert_raw_id_with_position(abstract_constant),AbstractConstants),
896 assert_if_has_theorems(Name,Sections).
897
898 get_extends_refs(Sections,Refs) :-
899 get_opt_section(extends,Sections,Extended),
900 findall(ref(extends,E,''),member(E,Extended),Refs).
901
902 assert_if_has_theorems(Name,Sections) :-
903 get_opt_section(theorems,Sections,[_|_]),
904 assertz(machine_has_assertions(Name)).
905 assert_if_has_theorems(_Name,_Sections).
906
907
908 % compute a hash based on constants and properties
909 properties_hash(MachineName,Hash) :-
910 properties_hash_cached(MachineName,Hash1),!,
911 Hash=Hash1.
912 properties_hash(MachineName,Hash) :-
913 compute_properties_hash(MachineName,Hash1),
914 assertz(properties_hash_cached(MachineName,Hash1)),
915 Hash=Hash1.
916 compute_properties_hash(Name,Hash) :-
917 raw_machine(Name,Machine),
918 get_machine(Name,[Machine],_Type,_Header,_Refines,Body),
919 extract_sorted_np_sets(Body,Sets),
920 extract_sorted_np_constants(Body,Constants),
921 extract_np_properties(Body,Properties),
922 extract_used_np_definitions_from_properties(Body,Definitions),
923 ToHash = [Sets,Constants,Properties,Definitions],
924 raw_sha_hash(ToHash,Hash).
925 % save_properties_hash(Name,ToHash,Hash).
926
927 extract_sorted_np_sets(Body,Sets) :-
928 get_sets(Body,PosSets),
929 remove_raw_position_info(PosSets,UnsortedSets),
930 sort(UnsortedSets,Sets).
931 extract_sorted_np_constants(Body,Constants) :-
932 get_opt_sections([constants,concrete_constants,abstract_constants],Body,PosConstants),
933 remove_raw_position_info(PosConstants,UnsortedConstants),
934 sort(UnsortedConstants,Constants).
935 extract_np_properties(Body,Properties) :-
936 get_opt_section(properties,Body,PosProperties),
937 remove_raw_position_info(PosProperties,Properties).
938 extract_used_np_definitions_from_properties(Body,Definitions) :-
939 get_opt_section(properties,Body,Properties),
940 extract_used_np_definitions(Properties,Body,Definitions,_).
941 extract_used_np_definitions(RawSyntax,Body,Definitions,PosDefinitions) :-
942 extract_raw_identifiers(RawSyntax,UsedIds),
943 all_definition_ids(Body,AllDefs),
944 ord_intersection(UsedIds,AllDefs,UsedDefNames),
945 transitive_used_definitions(UsedDefNames,AllUsedDefs),
946 findall( definition(none,Name,Args,DefBody),
947 ( member(Name,AllUsedDefs),b_get_definition(Name,_DefType,Args,DefBody,_Deps)),
948 PosDefinitions),
949 maplist(remove_raw_position_info,PosDefinitions,Definitions).
950 all_definition_ids(Body,Ids) :-
951 get_opt_section(definitions,Body,Definitions),
952 convlist(get_definition_name,Definitions,Ids1),
953 sort(Ids1,Ids).
954 transitive_used_definitions(Defs,TransDefs) :-
955 findall( D, reachable_definition(Defs,D), TD1),
956 sort(TD1,TransDefs).
957 reachable_definition(Defs,D) :-
958 member(N,Defs),
959 ( D=N
960 ; b_get_definition(N,_DefType,_Args,_Body,Deps),
961 reachable_definition(Deps,D)).
962
963
964 /* just for debugging:
965 save_properties_hash(MachineName,ToHash,Hash) :-
966 main_machine_name(Main),
967 open('/home/plagge/hashes.pl',append,S),
968 writeq(S,hash(Main,MachineName,ToHash,Hash)),
969 write(S,'.\n'),
970 close(S).
971 */
972
973 % ---------------------------
974 :- dynamic event_info/3.
975 analyze_extends_relation :-
976 retractall(event_info(_,_,_)),
977 bmachine:b_get_machine_operation(_Name,_Results,_RealParameters,TBody,_OType,_OpPos),
978 treat_event_body(TBody),fail.
979 analyze_extends_relation.
980
981 treat_event_body(TBody) :-
982 rlevent_info(TBody,EventName,Machine,Status,AbstractEvents),
983 % format('Event ~w:~w ~w~n',[Machine,EventName,Status]),
984 assertz(event_info(Machine,EventName,Status)),
985 maplist(treat_event_body,AbstractEvents).
986
987 :- use_module(bsyntaxtree,[get_texpr_expr/2]).
988 rlevent_info(TBody,EventName,Machine,FStatus,AbstractEvents) :-
989 get_texpr_expr(TBody,Event),
990 Event = rlevent(EventName,Machine,TStatus,_Params,_Guard,_Theorems,_Actions,_VWit,_PWit,_Unmod,AbstractEvents),
991 bsyntaxtree:get_texpr_expr(TStatus,Status), %ordinary, convergent, anticipated
992 functor(Status,FStatus,_).
993
994
995 % write the event refinement hierarchy to a dot file
996 % (currently) only makes sense for Event-B models
997
998 :- use_module(preferences,[get_preference/2]).
999 :- use_module(tools_strings,[ajoin/2, ajoin_with_sep/3]).
1000
1001 :- public dot_refinement_node_new/4.
1002 % variation for: use_new_dot_attr_pred
1003 dot_refinement_node_new(event_refinement,M:Ev,M,[label/Desc,shape/Shape,tooltip/Tooltip|T1]) :-
1004 dot_event_node(M:Ev,M,Desc,Shape,Style,Color),
1005 (Style=none -> T1=T2 ; T1=[style/Style|T2]),
1006 (Color=none -> T2=[] ; T2=[color/Color]),
1007 (event_info(M,Ev,Status) -> true ; Status=unknown),
1008 (event_refinement_change(M,Ev,AbsName,AbsEvName,SameGuard,SameAct)
1009 -> ajoin(['Event ',Ev,' in ',M,
1010 '\n status: ',Status,
1011 '\n refines ',AbsEvName,' in ',AbsName,
1012 '\n guard: ',SameGuard,
1013 '\n action: ',SameAct], Tooltip)
1014 ; ajoin(['Event ',Ev,' in ',M,
1015 '\n status: ',Status], Tooltip)).
1016 dot_refinement_node_new(variable_refinement(With),M:Var,M,[label/Desc,shape/Shape,color/Color,tooltip/Tooltip|T1]) :-
1017 (With=with_constants -> machine_ids(M,Vars) ; machine_variables(M,Vars)),
1018 member(Var,Vars),
1019 Desc=Var,
1020 (id_exists_in_abstraction(M,Anc,Var)
1021 -> get_preference(dot_event_hierarchy_unchanged_event_colour,Color), T1=[style/filled],
1022 Shape = rect, % we could use plain; makes kept events smaller
1023 ajoin(['Variable kept from abstraction ',Anc],Tooltip)
1024 ; machine_type(M,context), machine_sets(M,Sets), member(Var,Sets) ->
1025 get_preference(dot_event_hierarchy_refines_colour,Color), T1=[style/'rounded,filled'],
1026 Shape = rect,
1027 ajoin(['New set in ',M],Tooltip)
1028 ; machine_type(M,context) -> % it must be a constant
1029 get_preference(dot_event_hierarchy_new_event_colour,Color), T1=[style/rounded],
1030 Shape = rect,
1031 ajoin(['New constant in ',M],Tooltip)
1032 ; get_preference(dot_event_hierarchy_new_event_colour,Color), T1=[],
1033 Shape = rect,
1034 ajoin(['New variable in ',M],Tooltip)
1035 ).
1036 %dot_refinement_node_new(variable_refinement(_),C:Cst,M,[label/Desc,shape/rect,color/Color,tooltip/Desc|T1]) :-
1037 % new_seen_context(M,C), machine_constants(C,Csts), member(Cst,Csts),
1038 % Desc=Cst, T1=[style/rounded], get_preference(dot_event_hierarchy_extends_colour,Color).
1039
1040 % the node ide is M:Ev as Ev can and usually does occur multiple times
1041 dot_event_node(M:Ev,M,Desc,Shape,Style,Color) :-
1042 findall(showev(M,Ev),event_to_show(M,Ev),List), sort(List,SList),
1043 member(showev(M,Ev),SList),
1044 (event_info(M,Ev,Status) -> true ; Status=unknown),
1045 (event_refinement_change(M,Ev,_,_,SameGuard,SameAction)
1046 -> true ; SameGuard=unknown, SameAction=unknown),
1047 (SameGuard=SameAction, SameGuard \= unknown -> ajoin([Ev,'\\n(',SameAction,')'],Ev2)
1048 ; SameGuard=unchanged ,SameAction=extends-> ajoin([Ev,'\\n(same grd, extends act)'],Ev2)
1049 ; SameGuard=unchanged -> ajoin([Ev,'\\n(same grd)'],Ev2)
1050 ; SameGuard=extends,SameAction=unchanged -> ajoin([Ev,'\\n(same act, extends grd)'],Ev2)
1051 ; SameAction=unchanged -> ajoin([Ev,'\\n(same act)'],Ev2)
1052 ; SameGuard=extends -> ajoin([Ev,'\\n(extends grd)'],Ev2)
1053 ; SameAction=extends -> ajoin([Ev,'\\n(extends act)'],Ev2)
1054 ; Ev2=Ev),
1055 (Status = convergent -> ajoin([Ev2,' (<)'],Desc)
1056 ; Status = anticipated -> ajoin([Ev2, ' (<=)'],Desc)
1057 ; Desc=Ev2),
1058 % format(user_output,'event ~w, status:~w, same guard:~w, same action:~w~n',[Ev,Status,SameGuard,SameAction]),
1059 dot_get_color_style(M,Ev,Status,SameGuard,SameAction,Shape,Color,Style).
1060
1061 event_to_show(M,Ev) :- machine_operations(M,Evs),
1062 raw_identifier_member(Ev,Evs), Ev \= 'INITIALISATION'.
1063 event_to_show(M,Ev) :-
1064 event_refinement_change(M,Ev,_,_,_,_), % for events that disappear, i.e., are not refined until bottom level
1065 Ev \= 'INITIALISATION'.
1066
1067
1068 dot_get_color_style(M,Ev,_Status,_,_,box,Color,Style) :- \+ refines_event(M,Ev,_,_),!,
1069 get_preference(dot_event_hierarchy_new_event_colour,Color), Style=none.
1070 dot_get_color_style(M,Ev,_,SameGuard,SameAction,box,Color,Style) :-
1071 refines_event(M,Ev,_,Ev2), dif(Ev2,Ev),!, % changes name
1072 ((SameGuard,SameAction)=(unchanged,unchanged)
1073 -> get_preference(dot_event_hierarchy_rename_unchanged_event_colour,Color)
1074 ; get_preference(dot_event_hierarchy_rename_event_colour,Color)), Style=filled.
1075 dot_get_color_style(_M,_Ev,_,unchanged,unchanged,plain,Color,Style) :- % keeps name and adds no guard or action
1076 !,
1077 get_preference(dot_event_hierarchy_unchanged_event_colour,Color), Style=filled.
1078 dot_get_color_style(_M,_Ev,_,_,unchanged,box,Color,Style) :- % keeps name and adds no action, but modifies guard
1079 !,
1080 get_preference(dot_event_hierarchy_grd_strengthening_event_colour,Color), Style=filled.
1081 dot_get_color_style(_M,_Ev,_,unchanged,_,box,Color,Style) :- % keeps name and adds action but keeps guard
1082 !,
1083 get_preference(dot_event_hierarchy_grd_keeping_event_colour,Color), Style=filled.
1084 dot_get_color_style(_M,_Ev,_,_,_,box,Color,Style) :- % keeps name but adds or modifies
1085 % TO DO: distinguish extends from refines
1086 get_preference(dot_event_hierarchy_refines_colour,Color), Style=filled.
1087
1088 :- public dot_refines_event/4.
1089 % dot transition predicate for event and variable refinement hierarchy diagram
1090 dot_refines_event(event_refinement,M2:Ev2,M1:Ev1,[label/Label,color/Color,style/Style]) :-
1091 Label = '', % TO DO: detect refine, extends, identical
1092 refines_event(M1,Ev1,M2,Ev2),
1093 Ev1 \= 'INITIALISATION',
1094 (event_refinement_change(M1,Ev1,_,_,SameGuard,SameAct)
1095 -> arrow_style(SameGuard,SameAct,Style,ColPref), get_preference(ColPref,Color)
1096 ; Style=solid, Color=red % should not happen
1097 ).
1098 dot_refines_event(variable_refinement(With),M1:Var,M2:Var2,[label/Label,color/Color,style/Style|T1]) :-
1099 get_preference(dot_event_hierarchy_edge_colour,Color),
1100 (With=with_constants -> machine_ids(M2,Vars2) ; machine_variables(M2,Vars2)),
1101 if((member(Var,Vars2),
1102 id_exists_in_abstraction(M2,M1,Var)),
1103 (Label='',Var2=Var,Style=dashed, T1=[]),
1104 (% no variable of M2 exists in M1
1105 refines_or_extends_machine(M2,M1),
1106 machine_ids(M1,[Var|_]), % get first variable of M1
1107 Vars2=[Var2|_], Style=dotted, % add virtual edge to first variable of M2 if no variable is kept
1108 get_dot_cluster_name(M1,M1C), get_dot_cluster_name(M2,M2C),
1109 T1 = [ltail/M1C, lhead/M2C],
1110 (machine_type(M2,context) -> Label='extends' ; Label='')
1111 )
1112 ).
1113 dot_refines_event(variable_refinement(with_constants),M1:Var1,M2:Cst2,[label/Label,color/Color,style/Style|T1]) :- Label='sees',
1114 Color=gray80, Style=solid,
1115 new_seen_context(M1,M2),
1116 machine_ids(M1,[Var1|_]),
1117 machine_ids(M2,[Cst2|_]),
1118 get_dot_cluster_name(M1,M1C), get_dot_cluster_name(M2,M2C),
1119 T1 = [ltail/M1C, lhead/M2C, dir/forward].
1120
1121 arrow_style(unchanged,unchanged,Style,ColPref) :- !,
1122 Style=arrowhead(none,solid), ColPref=dot_event_hierarchy_extends_colour.
1123 arrow_style(refines,_,Style,ColPref) :- !, Style=solid, ColPref=dot_event_hierarchy_edge_colour.
1124 arrow_style(_,refines,Style,ColPref) :- !, Style=solid, ColPref=dot_event_hierarchy_edge_colour.
1125 %arrow_style(_,_,Style) :- Style = arrowhead(vee,arrowtail(box,solid)). % we have extends
1126 arrow_style(_,_,Style,dot_event_hierarchy_extends_colour) :- Style = arrowhead(vee,solid). % we have extends
1127
1128
1129 %dot_same_rank(SameRankVals) :- machine_operations(M,Evs),
1130 % findall(M:Ev,raw_identifier_member(Ev,Evs),SameRankVals).
1131
1132 dot_subgraph(Kind,sub_graph_with_attributes(M,Attrs), filled,Colour) :-
1133 get_preference(dot_event_hierarchy_machine_colour,MColour),
1134 Attrs = [label/Label, tooltip/ToolTip],
1135 machine_operations(M,Ops),
1136 (Kind=event_refinement -> Ops=[_|_] ; true),
1137 (machine_type(M,context) -> IDS = 'csts', Colour=gray90
1138 ; IDS = 'vars', Colour=MColour),
1139 (machine_ids(M,Vars)
1140 -> length(Vars,V),
1141 findall(C,new_seen_context(M,C),NewC),
1142 split_list(id_exists_in_abstraction(M),Vars,_Old,NewVars),
1143 length(NewVars,NewNr),
1144 findall(Del,(var_exists_in_abstraction(M,Del), nonmember(Del,Vars)),DelVars),
1145 length(DelVars,DelNr),
1146 (Kind=event_refinement, get_preference(dot_hierarchy_show_extra_detail,false)
1147 -> Label=M
1148 ; ajoin([M,'\\n#',IDS,'=',V, ' (+',NewNr,',-', DelNr,')'],Label)
1149 ),
1150 ajoin_with_sep(NewVars,',',NV),
1151 ajoin_with_sep(DelVars,',',DV),
1152 ajoin_with_sep(NewC,',',NC),
1153 ajoin(['machine ',M,'\\n#',IDS,'=',V, ' (+',NewNr,',-', DelNr,')',
1154 '\\nnew sees=',NC,
1155 '\\nnew ',IDS,'=',NV,
1156 '\\ndel ',IDS,'=',DV],ToolTip)
1157 ; Label=M, ToolTip=M).
1158
1159 machine_variables(M,Vars) :- machine_identifiers(M,_Params,_Sets,AVars,CVars,_AConsts,_CConsts),
1160 append(CVars,AVars,RVars), % for Event-B: CVars=[]
1161 maplist(get_raw_identifier,RVars,Vars).
1162 %machine_constants(M,Consts) :- machine_identifiers(M,_Params,_Sets,_AVars,_CVars,AConsts,CConsts),
1163 % append(CConsts,AConsts,Raw),
1164 % maplist(get_raw_identifier,Raw,Consts).
1165 machine_ids(M,Vars) :- machine_identifiers(M,_Params,Sets,AVars,CVars,AConsts,CConsts),
1166 append([Sets,CConsts,CVars,AConsts,AVars],RVars),
1167 maplist(get_raw_identifier,RVars,Vars).
1168 machine_sets(M,Vars) :- machine_identifiers(M,_,Sets,_,_,_,_),
1169 maplist(get_raw_identifier,Sets,Vars).
1170
1171 var_exists_in_abstraction(M,Var) :-
1172 var_exists_in_abstraction(M,_Anc,Var).
1173 var_exists_in_abstraction(M,Anc,Var) :-
1174 refines_machine(M,Anc),
1175 machine_variables(Anc,AncVars),
1176 member(Var,AncVars).
1177
1178 refines_machine(M,Anc) :-
1179 machine_references(M,Refs),
1180 member(ref(refines,Anc,_),Refs).
1181
1182 % variable or constant exists in abstraction
1183 id_exists_in_abstraction(M,Var) :-
1184 id_exists_in_abstraction(M,_Anc,Var).
1185 id_exists_in_abstraction(M,Anc,Var) :-
1186 refines_or_extends_machine(M,Anc),
1187 machine_ids(Anc,AncVars),
1188 member(Var,AncVars).
1189
1190 refines_or_extends_machine(M,Anc) :-
1191 machine_references(M,Refs),
1192 (member(ref(refines,Anc,_),Refs) -> true ; member(ref(extends,Anc,_),Refs)).
1193
1194 new_seen_context(M,Context) :- machine_references(M,Refs),
1195 member(ref(sees,Context,_),Refs),
1196 \+ (member(ref(refines,Anc,_),Refs),
1197 sees_context(Anc,Context)).
1198
1199 sees_context(M,Context) :- machine_references(M,Refs), member(ref(sees,Context,_),Refs).
1200
1201
1202 write_dot_event_hierarchy_to_file(File) :-
1203 write_dot_ref_hierarchy_to_file(event_refinement,File).
1204 write_dot_variable_hierarchy_to_file(File) :-
1205 (get_preference(dot_hierarchy_show_extra_detail,false) -> With=no_constants ; With=with_constants),
1206 write_dot_ref_hierarchy_to_file(variable_refinement(With),File).
1207 write_dot_ref_hierarchy_to_file(Kind,File) :-
1208 analyze_extends_relation,
1209 (get_preference(dot_event_hierarchy_horizontal,true)
1210 -> PageOpts=[compound/true,rankdir/'LR',no_page_size]
1211 ; PageOpts=[compound/true]),
1212 gen_dot_graph(File,PageOpts,
1213 use_new_dot_attr_pred(b_machine_hierarchy:dot_refinement_node_new(Kind)),
1214 use_new_dot_attr_pred(b_machine_hierarchy:dot_refines_event(Kind)),
1215 dot_no_same_rank,dot_subgraph(Kind)).
1216 %gen_dot_graph(File,PageOpts,dot_event_node,dot_refines_event,dot_no_same_rank,dot_subgraph).
1217
1218 % --------------------
1219
1220 reference_link(FromMachine,DestMachine) :-
1221 machine_references(FromMachine,Refs),
1222 filter_redundant_refs(Refs,Refs,UsefulRefs),
1223 member(ref(_Type,DestMachine,_Prefix),UsefulRefs).
1224
1225 :- use_module(library(ugraphs),[vertices_edges_to_ugraph/3, top_sort/2, transitive_closure/2,
1226 min_paths/3, min_path/5, neighbours/3, del_vertices/3]).
1227
1228 % b_machine_hierarchy:get_machine_topological_order(V)
1229 % get machine in topological order of inclusion
1230 get_machine_topological_order(SortedVertices) :-
1231 get_machine_inclusion_graph(_Vertices,_Edges,Graph),
1232 top_sort(Graph,SortedVertices).
1233
1234 % get machine inclusion graph in format for ugraphs (unweighted graphs) library
1235 get_machine_inclusion_graph(Vertices,Edges,Graph) :-
1236 findall(Mach,machine_name(Mach),Vertices),
1237 findall(From-To,reference_link(From,To),Edges),
1238 vertices_edges_to_ugraph(Vertices, Edges, Graph).
1239
1240 print_machine_topological_order :-
1241 format('Topological sorting of B machine references~n',[]),
1242 get_machine_inclusion_graph(Vertices,Edges,Graph),
1243 length(Vertices,LenV),format(' * number of machines: ~w~n',[LenV]),
1244 length(Edges,LenE), format(' * number of reference links: ~w~n',[LenE]),
1245 top_sort(Graph,SortedVertices),
1246 main_machine_name(Main),
1247 %min_paths(Main,Graph,MinPaths),
1248 transitive_closure(Graph,TGraph),
1249 maplist(top_print_machine(Main,Graph,TGraph),SortedVertices),
1250 greedy_cover(Main,Graph,TGraph,GreedyCover), length(GreedyCover,GLen),
1251 format(' * sufficient includes (~w) to cover all machines: ~w~n',[GLen,GreedyCover]).
1252
1253 top_print_machine(Main,Graph,TGraph,M) :-
1254 (machine_references(M,Refs) -> length(Refs,Len) ; Len=0),
1255 neighbours(M,TGraph,N), length(N,Len2),
1256 format(' ~w has ~w direct references and ~w indirect ones~n',[M,Len,Len2]),
1257 min_path(Main, M, Graph, Path, Length),
1258 format(' inclusion length ~w: ~w~n',[Length,Path]).
1259
1260 greedy_cover(Main,Graph,TGraph,GreedyCover) :-
1261 neighbours(Main,Graph,TopLevelIncludes),
1262 greedy_cover(TopLevelIncludes,TGraph,GreedyCover).
1263
1264 % compute a list of included machines which cover all required inclusions
1265 % we try to make this inclusion minimal, using a greedy algorithm
1266 greedy_cover([],_TGraph,Cover) :- !, Cover=[].
1267 greedy_cover(RemainingIncludes,TGraph, GreedyCover) :-
1268 findall(candidate(NrCovered,Machine),
1269 (member(Machine,RemainingIncludes),
1270 neighbours(Machine,TGraph,N), length(N,NrCovered)), Cands),
1271 (max_member(candidate(MaxNrCov,NextChoice),Cands) % pick the machine covering the most other ones
1272 ->
1273 (MaxNrCov =< 0
1274 -> GreedyCover = [] % everything is included already
1275 ; GreedyCover = [NextChoice|TGreedyCover],
1276 select(NextChoice,RemainingIncludes,Rem2), % this include is no longer available
1277 neighbours(NextChoice,TGraph,NowCovered),
1278 del_vertices(TGraph, [NextChoice|NowCovered], TGraph2), % delete all machines included by NextChoice
1279 greedy_cover(Rem2,TGraph2,TGreedyCover)
1280 )
1281 ; GreedyCover = [] % everything is included already; no node appears in the graph anymore
1282 ).
1283