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