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(enumerated_set(_Pos,DID,_List),ID) :- atom(DID),!, ID=DID.
341 get_raw_identifier(description(_,_,RawID),ID) :- !,
342 get_raw_identifier(RawID,ID).
343 get_raw_identifier(Raw,Res) :- add_internal_error('Cannot get identifier:',Raw),Res='???'.
344
345 raw_identifier_member(ID,List) :- member(Raw,List), raw_id_is_identifier(Raw,_Pos,ID).
346
347 store_operations(MachName,Body) :-
348 get_opt_section(operations,Body,Operations),
349 findall(I,(member(Op,Operations),get_raw_operation_id_and_body(Op,I,_)),Ids),
350 assertz(machine_operations(MachName,Ids)),
351 findall(calls(I1,I2),(member(Op,Operations),get_raw_operation_call(Op,I1,I2)),Calls),
352 sort(Calls,SCalls),
353 debug_println(9,machine_operation_calls(MachName,SCalls)),
354 assertz(machine_operation_calls(MachName,SCalls)).
355
356 get_raw_operation_id_and_body(operation(_Pos,Id,_,_,Body),Id,Body).
357 get_raw_operation_id_and_body(refined_operation(_Pos,Id,_Results,_Args,_RefinesID,Body),Id,Body).
358 get_raw_operation_id_and_body(description_operation(_Pos,_,Op),Id,Body) :- get_raw_operation_id_and_body(Op,Id,Body).
359
360 % get operations called in body
361 get_raw_operation_call(Op,Id,CallsId) :-
362 get_raw_operation_id_and_body(Op,identifier(_,Id),Body),
363 get_raw_operation_call(Body,identifier(_,CallsId)).
364
365 :- use_module(debug,[debug_format/3]).
366 get_raw_operation_call(block(_,Body),ID) :- !, get_raw_operation_call(Body,ID).
367 get_raw_operation_call(precondition(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
368 get_raw_operation_call(assertion(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
369 get_raw_operation_call(witness_then(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
370 get_raw_operation_call(var(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
371 get_raw_operation_call(select_when(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
372 get_raw_operation_call(if_elsif(_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
373 get_raw_operation_call(let(_,_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
374 get_raw_operation_call(any(_,_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
375 get_raw_operation_call(case(_,_,_,_,_,Body),ID) :- !, get_raw_operation_call(Body,ID).
376 get_raw_operation_call(while(_,_Cond,Body,_,_),ID) :- !, get_raw_operation_call(Body,ID).
377 ?get_raw_operation_call(parallel(_,List),ID) :- !,member(A,List), get_raw_operation_call(A,ID).
378 ?get_raw_operation_call(sequence(_,List),ID) :- !,member(A,List), get_raw_operation_call(A,ID).
379 ?get_raw_operation_call(if(_,_Test,Then,List,Else),ID) :- !,member(A,[Then,Else|List]), get_raw_operation_call(A,ID).
380 get_raw_operation_call(select(_,_Cond,Body,List),ID) :- !,member(A,[Body|List]), get_raw_operation_call(A,ID).
381 ?get_raw_operation_call(select(_,_Cond,Body,List,Else),ID) :- !,member(A,[Body,Else|List]), get_raw_operation_call(A,ID).
382 ?get_raw_operation_call(choice(_,List),ID) :- !,member(A,List), get_raw_operation_call(A,ID).
383 get_raw_operation_call(choice_or(_,Body),ID) :- !, get_raw_operation_call(Body,ID).
384 get_raw_operation_call(operation_call(_,ID,_,_),ID) :- !.
385 get_raw_operation_call(skip(_),_) :- !, fail.
386 get_raw_operation_call(assign(_,_,_),_) :- !, fail.
387 get_raw_operation_call(becomes_element_of(_,_,_),_) :- !, fail.
388 get_raw_operation_call(becomes_such(_,_,_),_) :- !, fail.
389 get_raw_operation_call(definition(_,Name,_),_) :- !, % TO DO: improve
390 debug_format(19,'Ignoring operation calls in DEFINITION ~w for operation call diagram~n',[Name]),
391 % b_get_definition(Name,_DefType,_Args,DefBody,_Deps), not yet precompiled !
392 fail.
393 get_raw_operation_call(Subst,_) :- functor(Subst,F,N),print(uncovered_subst(F,N,Subst)),nl,fail.
394 % we also do not find operation calls in expressions
395
396 % avoid spurious uncovered_subst messages in a context where we are not sure we have a subst
397 try_get_raw_operation_call(conjunct(_,_),_) :- !,fail.
398 try_get_raw_operation_call(conjunct(_,_,_),_) :- !,fail.
399 try_get_raw_operation_call(disjunct(_,_,_),_) :- !,fail.
400 try_get_raw_operation_call(implication(_,_,_),_) :- !,fail.
401 try_get_raw_operation_call(equivalence(_,_,_),_) :- !,fail.
402 try_get_raw_operation_call(interval(_,_,_),_) :- !,fail.
403 try_get_raw_operation_call(integer(_,_),_) :- !,fail.
404 try_get_raw_operation_call(boolean_true(_),_) :- !,fail.
405 try_get_raw_operation_call(boolean_false(_),_) :- !,fail.
406 try_get_raw_operation_call(Body,ID) :- get_raw_operation_call(Body,ID).
407
408 get_raw_operation_call_id(OpBody,CalledId) :-
409 try_get_raw_operation_call(OpBody,identifier(_,CalledId)).
410
411 store_references(Name,Refines,Body,Machines) :-
412 get_refinements(Refines,Refs1),
413 get_references(Body,Refs2),
414 append(Refs1,Refs2,Refs),
415 assertz(machine_references(Name,Refs)),
416 follow_refs(Refs,Machines).
417
418 get_references(Body,Refs) :-
419 findrefs(Body,includes,Includes),
420 findrefs(Body,extends,Extends),
421 findrefs(Body,imports,Imports),
422 findusessees(Body,uses,Uses),
423 findusessees(Body,sees,Sees),
424 append([Includes,Imports,Extends,Uses,Sees],Refs).
425
426 get_refinements([],[]).
427 get_refinements([Name|NRest],[ref(refines,Name,'')|RRest]) :-
428 get_refinements(NRest,RRest).
429
430 findrefs(Body,Type,Refs) :-
431 get_opt_section(Type,Body,RawRefs),
432 findrefs2(RawRefs,Type,Refs).
433 findrefs2([],_Type,[]).
434 findrefs2([machine_reference(_Pos,R,_Params)|MRest],Type,[ref(Type,Name,Prefix)|RRest]) :-
435 bmachine_construction:split_prefix(R,Prefix,Name),
436 findrefs2(MRest,Type,RRest).
437
438 findusessees(Body,Type,Refs) :-
439 get_opt_section(Type,Body,RawRefs),
440 findusessees2(RawRefs,Type,Refs).
441 findusessees2([],_Type,[]).
442 findusessees2([identifier(_Pos,Name)|MRest],Type,[ref(Type,Name,'')|RRest]) :-
443 findusessees2(MRest,Type,RRest).
444
445 follow_refs([],_Machines).
446 follow_refs([ref(RefType,Name,_Prefix)|Rest],Machines) :-
447 analyse_machine(Name,Machines,RefType),
448 follow_refs(Rest,Machines).
449
450 get_parameters(machine_header(_Pos,_Name,Params),Params).
451
452 get_sets(Body,Sets) :-
453 get_opt_section(sets,Body,Sets).
454
455 get_identifiers([],_Body,[]).
456 get_identifiers([Sec|Rest],Body,Ids) :-
457 get_opt_section(Sec,Body,Ids1),
458 append(Ids1,IRest,Ids),
459 get_identifiers(Rest,Body,IRest).
460
461 get_opt_sections([],_Body,[]).
462 get_opt_sections([S|Srest],Body,Contents) :-
463 get_opt_section(S,Body,L),append(L,Rest,Contents),
464 get_opt_sections(Srest,Body,Rest).
465
466 get_opt_section(Sec,Body,Result) :-
467 ( get_raw_section(Sec,Body,Content) -> Result=Content; Result=[]).
468 get_raw_section(Sec,Body,Content) :- % look for Sec(_Pos,Content) in Body list
469 functor(Pattern,Sec,2),arg(2,Pattern,Content),
470 memberchk(Pattern,Body).
471
472 get_machine(Name,Machines,Type,Header,Refines,Body) :-
473 get_machine1(Name,Machines,_Machine,Type,Header,Refines,Body).
474 %get_raw_machine(Name,Machines,Machine) :-
475 % get_machine1(Name,Machines,Machine,_Type,_Header,_Refines,_Body).
476 get_machine1(Name,Machines,Machine,Type,Header,Refines,Body) :-
477 Header = machine_header(_Pos,Name,_Params),
478 ? member(Machine,Machines),
479 get_machine2(Machine,Type,Header,Refines,Body),!.
480 get_machine2(abstract_machine(_Pos,MS,Header,Body),TypeOfAbstractMachine,Header,[],Body) :-
481 get_abstract_machine_type(MS,TypeOfAbstractMachine).
482 get_machine2(refinement_machine(_Pos,Header,Refines,Body),refinement,Header,[Refines],Body).
483 get_machine2(implementation_machine(_Pos,Header,Refines,Body),implementation,Header,[Refines],Body).
484 get_machine2(generated(_Pos,Machine),A,B,C,D) :- % @generated Pragma used at top of file
485 get_machine2(Machine,A,B,C,D).
486 get_machine2(unit_alias(_Pos,_Name,_Alias,Machine),A,B,C,D) :-
487 get_machine2(Machine,A,B,C,D).
488
489 get_raw_machine_name(Machine,Name) :-
490 get_machine2(Machine,_,machine_header(_,Name,_),_,_).
491
492 get_abstract_machine_type(machine(_Pos2),R) :- !,R=abstract_machine.
493 get_abstract_machine_type(system(_Pos2),R) :- !,R=abstract_machine.
494 get_abstract_machine_type(model(_Pos2),R) :- !,R=abstract_model.
495 get_abstract_machine_type(X,R) :- atomic(X),!,
496 add_error(get_abstract_machine_type,'Your parser seems out-dated. Assuming abstract_machine: ',X),
497 R=abstract_machine.
498
499
500 get_values_id(values_entry(Pos,ID,_Val),identifier(Pos,ID)).
501 % Store the identifiers assigned to in VALUES clauses
502 store_values(Name,Body) :-
503 get_opt_section('values',Body,Values),!,
504 maplist(get_values_id,Values,ValuesIDs),
505 assertz(machine_values_identifiers(Name,ValuesIDs)).
506 store_values(_,_).
507
508 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
509
510 % write dot operation call graph
511 write_dot_op_hierarchy_to_file(File) :-
512 (get_preference(dot_event_hierarchy_horizontal,true) -> PageOpts=[rankdir/'LR'] ; PageOpts=[]),
513 gen_dot_graph(File,PageOpts,dot_operation_node,dot_op_calls_op,dot_no_same_rank,dot_subgraph(op_hierarchy)).
514
515
516 :- use_module(bmachine,[b_top_level_operation/1, b_top_level_feasible_operation/1]).
517 dot_operation_node(OpName,M,Desc,Shape,Style,Color) :-
518 machine_operations(M,Operations),
519 (machine_promotes_operations(M,Promotes) -> true ; Promotes=[]),
520 raw_identifier_member(OpName,Operations),
521 (b_top_level_feasible_operation(OpName) -> Color=lightgray
522 ; b_top_level_operation(OpName) -> Color='OldLace' % commented out operation
523 ; raw_identifier_member(OpName,Promotes) -> Color='gray98' % promoted but not to top_level
524 ; Color=white),
525 Desc=OpName, Shape=box, Style=filled.
526
527 dot_op_calls_op(Op1,Label,Op2,Color,Style) :- Style=solid, Color=steelblue,
528 Label = '', % TO DO: different colors for local operation calls, detect op calls in expressions?
529 machine_operation_calls(_,Operations),
530 member(calls(Op1,Op2),Operations).
531
532
533
534 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
535 % print hierarchy to dot file
536
537 maxlinelength(30).
538
539 :- use_module(tools_io).
540
541 % write hierarchy of machines, with inclusion/refinement links
542 write_dot_hierarchy_to_file(Filename) :-
543 findall(M,machine_type(M,_),Machines),
544 safe_open_file(Filename,write,S,[]),
545 ( print_header(S),
546 print_machines(S,1,Machines,Ids),
547 print_refs_for_dot(S,Ids,Ids),
548 print_footer(S)
549 -> true
550 ; add_internal_error('Command failed:',write_dot_hierarchy_to_file(Filename))
551 ),
552 close(S).
553
554 print_header(S) :-
555 write(S,'digraph module_hierarchy {\n'),
556 write(S,' graph [page="8.5, 11",ratio=fill,size="7.5,10"];\n').
557 print_footer(S) :-
558 write(S,'}\n').
559
560 print_machines(_S,_Nr,[],[]).
561 print_machines(S,Nr,[M|Machines],[id(M,Nr)|Ids]) :-
562 (print_machine(S,Nr,M) -> true
563 ; add_internal_error('Printing machine for hierarchy failed: ',print_machine(S,Nr,M))
564 ),
565 Nr2 is Nr + 1,
566 print_machines(S,Nr2,Machines,Ids).
567 print_machine(S,Nr,M) :-
568 write(S,' '),write(S,Nr),
569 (main_machine_name(M) ->
570 write(S,' [shape=record, style=bold, color=darkgreen, label=\"|{')
571 ; write(S,' [shape=record, color=steelblue, label=\"|{')),
572 print_machine_header(S,M),
573 machine_identifiers(M,_Params,Sets,AVars,CVars,AConsts,CConsts),
574 %print_hash(S,M),
575 print_sets(S,Sets),
576 print_identifiers(S,'VARIABLES',AVars),
577 print_identifiers(S,'CONCRETE VARIABLES',CVars),
578 print_identifiers(S,'ABSTRACT CONSTANTS',AConsts),
579 print_identifiers(S,'CONSTANTS',CConsts),
580 (machine_values_identifiers(M,VConsts)
581 -> print_identifiers(S,'VALUES',VConsts)
582 ; true),
583 ( machine_has_assertions(M) ->
584 get_specification_description(assertions,AssStr),
585 print_title(S,AssStr)
586 ; true
587 ),
588 (machine_promotes_operations(M,Promotes)
589 -> print_identifiers(S,'PROMOTES',Promotes) ; true),
590 machine_operations(M,Operations),
591 delete(Operations,identifier(_,'INITIALISATION'),Operations2),
592 exclude(is_refinining_event(M),Operations2,RefiningOperations),
593 include(is_refinining_event(M),Operations2,NewOperations),
594 ((RefiningOperations=[] ; NewOperations=[])
595 -> get_specification_description(operations,OpStr),
596 print_identifiers(S,OpStr,Operations2)
597 ; print_identifiers(S,'EVENTS (refining)',RefiningOperations),
598 print_identifiers(S,'EVENTS (new)',NewOperations)
599 ),
600
601 write(S,'}|\"];\n').
602
603 is_refinining_event(M,identifier(_,Event)) :- (refines_event(M,Event,_,_) -> true).
604
605 %print_hash(S,M) :- machine_hash(M,Digest),!,print_title(S,'Digest'),
606 % maplist(format(S,'~16r'),Digest),write(S,'\\n').
607 %print_hash(_S,_M).
608
609 %get_machine_colour(M,steelblue) :- main_machine_name(M),!.
610 %get_machine_colour(_M,steelblue).
611
612 print_machine_header(S,M) :-
613 machine_type(M,Type),
614 get_machine_type_keyw(Type,P),
615 write(S,P),write(S,' '),
616 write(S,M),
617 (machine_package_directory(M,Dir), machine_package_directory(_M2,D2), D2 \= Dir
618 -> format(S,' (~w)',[Dir]) % show the name of the directory; probably the package pragma was used
619 ; true),
620 write(S,'\\n').
621 get_machine_type_keyw(abstract_machine,'MACHINE').
622 get_machine_type_keyw(abstract_model,'MODEL').
623 get_machine_type_keyw(refinement,'REFINEMENT').
624 get_machine_type_keyw(implementation,'IMPLEMENTATION').
625 get_machine_type_keyw(context,'CONTEXT').
626
627 print_sets(_,[]) :- !.
628 print_sets(S,Sets) :-
629 write(S,'|SETS\\n'),
630 print_sets2(Sets,S).
631 print_sets2([],_).
632 print_sets2([Set|Rest],S) :-
633 print_set(Set,S),
634 write(S,'\\n'),
635 print_sets2(Rest,S).
636 print_set(description(_Pos,_Desc,Raw),S) :- print_set(Raw,S).
637 print_set(deferred_set(_Pos,Name),S) :-
638 write_id(S,Name).
639 print_set(enumerated_set(_Pos,Name,List),S) :-
640 write_id(S,Name),write(S,' = \\{'),
641 maxlinelength(Max),
642 preferences:get_preference(dot_hierarchy_max_ids,MaxIdsToPrint),
643 print_set_elements(List,S,Max,MaxIdsToPrint),
644 write(S,'\\}').
645 print_set_elements([],_,_,_).
646 print_set_elements([RawID],S,_LenSoFar,_) :-
647 raw_id_is_identifier(RawID,_,Name),
648 !,write_id(S,Name).
649 print_set_elements([RawID,B|Rest],S,LenSoFar,MaxIdsToPrint) :-
650 raw_id_is_identifier(RawID,_,Name),
651 dec_atom_length(LenSoFar,Name,NewLen),
652 (NewLen<0 -> maxlinelength(NL0),NL is NL0-1,write(S,'\\n ') ; NL is NewLen-1),
653 write_id(S,Name),write(S,','),
654 M1 is MaxIdsToPrint-1,
655 (M1 < 1, Rest \= []
656 -> write(S,'...,'),
657 last([B|Rest],Last), print_set_elements([Last],S,NL,M1)
658 ; print_set_elements([B|Rest],S,NL,M1)
659 ).
660
661 :- use_module(tools,[string_escape/2]).
662 % write identifier and escape it for dot
663 write_id(S,Name) :- string_escape(Name,EName), write(S,EName).
664
665 dec_atom_length(Prev,Atom,New) :- atom_length(Atom,Len),
666 New is Prev-Len.
667
668 print_title(S,Title) :-
669 write(S,'|'),
670 write(S,Title),write(S,'\\n').
671 print_identifiers(_S,_,[]) :- !.
672 print_identifiers(S,Title,List) :-
673 print_title(S,Title),
674 preferences:get_preference(dot_hierarchy_max_ids,MaxIdsToPrint), % how many do we print overall; -1 means print all of them
675 print_identifiers2(List,0,_,S,MaxIdsToPrint).
676 print_identifiers2([],Count,Count,_,_MaxIdsToPrint).
677 print_identifiers2([RawID|Rest],Count,NCount,S,MaxIdsToPrint) :-
678 get_raw_identifier(RawID,Name),
679 (MaxIdsToPrint = 0,Rest\=[]
680 -> length(Rest,Len), RN is Len+1,
681 format(S,' (~w more)',[RN])
682 ; MaxIdsToPrint1 is MaxIdsToPrint-1,
683 print_identifier(Name,Count,ICount,S),
684 (Rest = [] -> true; write(S,',')),
685 print_identifiers2(Rest,ICount,NCount,S,MaxIdsToPrint1)
686 ).
687 print_identifier(Name,Count,NewCount,S) :-
688 atom_codes(Name,Codes),
689 length(Codes,Length),
690 NewCount1 is Count+Length,
691 maxlinelength(Max),
692 ( Count == 0 -> NewCount1=NewCount
693 ; NewCount1 =< Max -> NewCount1=NewCount
694 ; NewCount=0,write(S,'\\n')),
695 write_id(S,Name).
696
697 print_refs_for_dot(_S,[],_).
698 print_refs_for_dot(S,[id(M,Nr)|Rest],Ids) :-
699 machine_references(M,Refs),
700 filter_redundant_refs(Refs,Refs,UsefulRefs),
701 print_refs2(UsefulRefs,M,Nr,Ids,S),
702 print_refs_for_dot(S,Rest,Ids).
703 print_refs2([],_,_,_,_).
704 print_refs2([ref(Type,Dest,_Prefix)|Rest],M,Nr,Ids,S) :-
705 member(id(Dest,DestNr),Ids),!,
706 get_ref_type(Type,Ref,Dir), !,
707 (Dir=reverse ->
708 format(S,' ~w -> ~w ~w;~n',[DestNr,Nr,Ref])
709 ; format(S,' ~w -> ~w ~w;~n',[Nr,DestNr,Ref])
710 ),
711 print_refs2(Rest,M,Nr,Ids,S).
712 get_ref_type(includes,'[label=\"INCLUDES\",color=navyblue]',normal).
713 get_ref_type(imports,'[label=\"IMPORTS\",color=navyblue]',normal).
714 get_ref_type(extends,'[label=\"EXTENDS\",color=navyblue]',normal).
715 get_ref_type(uses,'[label=\"USES\",color=navyblue,style=dashed]',normal).
716 get_ref_type(sees,'[label=\"SEES\",color=navyblue,style=dashed]',normal).
717 %get_ref_type(sees,'[label=\"SEES\",color=navyblue,style=dashed,dir=back]',reverse).
718 %get_ref_type(refines,'[label=\"REFINES\",color=navyblue,style=bold,dir=back]',reverse).
719 get_ref_type(refines,'[label=\"REFINEMENT\",color=navyblue,style=bold]',reverse). % reverse so that abstract machines are shown on top
720 get_ref_type(UNKNOWN,'[label=\"UNKNOWN\",color=navyblue]',normal) :- add_internal_error('Unknown : ',get_ref_type(UNKNOWN,_,_)).
721
722 get_ref_type_name(includes,'INCLUDES').
723 get_ref_type_name(imports,'IMPORTS').
724 get_ref_type_name(extends,'EXTENDS').
725 get_ref_type_name(uses,'USES').
726 get_ref_type_name(sees,'SEES').
727 get_ref_type_name(refines,'REFINEMENT').
728 get_ref_type_name(main,'MACHINE').
729 get_ref_type_name(UNKNOWN,UNKNOWN).
730
731
732 % remove redundant references (has to be done after analyse_eventb_machine has asserted all facts)
733 filter_redundant_refs([],_,[]).
734 filter_redundant_refs([ref(sees,Dest,_)|T],All,R) :-
735 machine_type(Dest,context),
736 member(ref(sees,Other,_),All),
737 machine_references(Other,Refs),
738 member(ref(extends,Dest,_),Refs), % Dest already seen by other seen context;
739 % Note: Rodin export contains transitive sees relation;
740 % if the user had included Dest in the sees clause we would have a warning "Redundant seen context"
741 !,
742 %format(user_output,'Redundant sees of ~w (~w)~n',[Dest,Other]),
743 filter_redundant_refs(T,All,R).
744 filter_redundant_refs([H|T],All,[H|R]) :-
745 filter_redundant_refs(T,All,R).
746
747 /************************************************************************/
748 /* The same for Event-B */
749 /************************************************************************/
750
751 analyse_eventb_hierarchy(Machines,Contextes) :-
752 reset_hierarchy,
753 get_eventb_name(Machines,Contextes,MainName),
754 assertz(main_machine_name(MainName)),
755 ? maplist(analyse_eventb_machine,Machines),
756 analyse_eventb_refinement_types(Machines),
757 ? maplist(analyse_eventb_context,Contextes),!.
758 analyse_eventb_hierarchy(Machines,Contextes) :-
759 add_internal_error('Analyzing Event-B Hierarchy Failed: ',analyse_eventb_hierarchy(Machines,Contextes)).
760
761 get_eventb_name([MainMachine|_AbstractMachines],_Contextes,Name) :-
762 event_b_model(MainMachine,Name,_),!.
763 get_eventb_name(_Machines,[MainContext|_AbstractContextes],Name) :-
764 event_b_context(MainContext,Name,_).
765
766 event_b_model(event_b_model(_,Name,Sections),Name,Sections).
767 event_b_context(event_b_context(_,Name,Sections),Name,Sections).
768
769 analyse_eventb_machine(Machine) :-
770 event_b_model(Machine,Name,Sections),
771 % print(analyzing(Name)),nl,
772 ( memberchk(refines(_,RName),Sections) -> Type=refinement, RRefs=[ref(refines,RName,'')]
773 ; Type=abstract_model, RRefs=[], RName='$none'),
774 get_identifiers([variables],Sections,Vars),
775 get_sees_context_refs(Sections,SRefs),
776 append(RRefs,SRefs,Refs),
777 get_events(Name,Sections,Events,RName),
778 store_eventb_hash(Name,Machine),
779 assertz(machine_type(Name,Type)),
780 assertz(machine_identifiers(Name,[],[],Vars,[],[],[])),
781 assertz(machine_references(Name,Refs)),
782 assertz(machine_operations(Name,Events)),
783 assertz(machine_operation_calls(Name,[])), % Event-B events cannot call other events
784 ? assert_if_has_theorems(Name,Sections).
785
786
787 % analyze which kinds of refinments we have between events
788 analyse_eventb_refinement_types([]).
789 analyse_eventb_refinement_types([RefMachine,AbsMachine|_]) :-
790 event_b_model(RefMachine,RefName,RefSections),
791 memberchk(refines(_,AbsName),RefSections),
792 event_b_model(AbsMachine,AbsName,AbsSections),
793 get_opt_section(events,RefSections,RawEvents),
794 get_opt_section(events,AbsSections,AbsRawEvents),
795 ? member(RawEvent,RawEvents),
796 bmachine_eventb:raw_event(RawEvent,_,RefEvName,_St1,Ref,_Prm1,RefGrd,_Thm1,RefAct,_Wit1,_Desc1),
797 Ref = [AbsEvName],
798 ? member(AbsRawEvent,AbsRawEvents),
799 bmachine_eventb:raw_event(AbsRawEvent,_,AbsEvName,_St2,_,_Prm2,AbsGrd,_Thm2,AbsAct,_Wit2,_Desc2),
800 check_raw_prefix(AbsGrd,RefGrd,SameGuard),
801 check_raw_prefix(AbsAct,RefAct,SameAct),
802 %% format('~nEvent refinement change ~w (~w) -> ~w (~w) guard: ~w, action: ~w~n',[RefEvName,RefName,AbsEvName,AbsName,SameGuard,SameAct]),
803 %print(rawgrd(RefGrd,AbsGrd)), nl, print(rawact(RefAct,AbsAct)),nl,
804 assertz(event_refinement_change(RefName,RefEvName,AbsName,AbsEvName,SameGuard,SameAct)),
805 fail.
806 analyse_eventb_refinement_types([_|T]) :- analyse_eventb_refinement_types(T).
807
808 check_raw_prefix([],[],Res) :- !, Res=unchanged.
809 check_raw_prefix([],[_|_],Res) :- !, Res=extends. % the refinement has some more actions/guards
810 check_raw_prefix([Abs|AT],[Ref|RT],Result) :- same_raw_expression(Abs,Ref),!,
811 check_raw_prefix(AT,RT,Result).
812 check_raw_prefix(_,_,refines).
813
814 % TO DO: check if we have a more complete version of this predicate; to do: handle @desc description/3 terms
815 same_raw_expression(identifier(_,A),RHS) :- !, RHS=identifier(_,B), A=B.
816 same_raw_expression(equal(_,A,B),RHS) :- !, RHS=equal(_,A2,B2), same_raw_expression(A,A2), same_raw_expression(B,B2).
817 same_raw_expression(assign(_,A1,A2),RHS) :- !, RHS=assign(_,B1,B2),
818 maplist(same_raw_expression,A1,B1), maplist(same_raw_expression,A2,B2).
819 same_raw_expression(A,B) :- atomic(A),!, A=B.
820 same_raw_expression(A,B) :- A =.. [F,_|AA], % print(match(F,AA)),nl,
821 B=.. [F,_|BB], maplist(same_raw_expression,AA,BB).
822
823
824
825 get_sees_context_refs(Sections,SRefs) :-
826 get_opt_section(sees,Sections,Seen),
827 findall(ref(sees,I,''),member(I,Seen),SRefs).
828
829 :- use_module(bmachine_eventb,[raw_event/11]).
830 get_events(Name,Sections,Events,AbsMachineName) :-
831 get_opt_section(events,Sections,RawEvents),
832 compute_event_refines(Name,RawEvents,AbsMachineName),
833 findall( identifier(Pos,EvName),
834 ( member(RawEvent,RawEvents),
835 raw_event(RawEvent,Pos,EvName,_St,_Rf,_Prm,_Grd,_Thm,_Act,_Wit,_Desc) ),
836 Events).
837
838 % TO DO: detect when an event extends another one without changing it
839 compute_event_refines(MachineName,RawEvents,AbsMachineName) :-
840 ? member(RawEvent,RawEvents),
841 bmachine_eventb:raw_event(RawEvent,_Pos,EvName,_St,Refines,_Prm,_Grd,_Thm,_Act,_Wit,_Desc),
842 member(RefEvent,Refines),
843 % print(refines(MachineName,EvName,AbsMachineName,RefEvent)),nl,
844 assertz(refines_event(MachineName,EvName,AbsMachineName,RefEvent)),
845 fail.
846 compute_event_refines(_,_,_).
847
848
849 % try and get the name of the machine we refine
850 %machine_refines(Machine,AbsMachine) :- machine_references(Machine,Refs), member(ref(refines,AbsMachine,_),Refs).
851
852 analyse_eventb_context(Context) :-
853 event_b_context(Context,Name,Sections),
854 get_identifiers([constants],Sections,ConcreteConstants),
855 get_identifiers([abstract_constants],Sections,AbstractConstants),
856 append([ConcreteConstants,AbstractConstants],AllConstants),
857 get_sets(Sections,Sets),
858 get_extends_refs(Sections,Refs),
859 store_eventb_hash(Name,Context),
860 assertz(machine_type(Name,context)),
861 assertz(machine_identifiers(Name,[],Sets,[],[],[],AllConstants)),
862 assertz(machine_references(Name,Refs)),
863 assertz(machine_operations(Name,[])),
864 assertz(machine_operation_calls(Name,[])),
865 maplist(assert_raw_id_with_position(concrete_constant),ConcreteConstants),
866 maplist(assert_raw_id_with_position(abstract_constant),AbstractConstants),
867 ? assert_if_has_theorems(Name,Sections).
868
869 get_extends_refs(Sections,Refs) :-
870 get_opt_section(extends,Sections,Extended),
871 findall(ref(extends,E,''),member(E,Extended),Refs).
872
873 assert_if_has_theorems(Name,Sections) :-
874 get_opt_section(theorems,Sections,[_|_]),
875 assertz(machine_has_assertions(Name)).
876 assert_if_has_theorems(_Name,_Sections).
877
878
879 % compute a hash based on constants and properties
880 properties_hash(MachineName,Hash) :-
881 properties_hash_cached(MachineName,Hash1),!,
882 Hash=Hash1.
883 properties_hash(MachineName,Hash) :-
884 compute_properties_hash(MachineName,Hash1),
885 assertz(properties_hash_cached(MachineName,Hash1)),
886 Hash=Hash1.
887 compute_properties_hash(Name,Hash) :-
888 raw_machine(Name,Machine),
889 get_machine(Name,[Machine],_Type,_Header,_Refines,Body),
890 extract_sorted_np_sets(Body,Sets),
891 extract_sorted_np_constants(Body,Constants),
892 extract_np_properties(Body,Properties),
893 extract_used_np_definitions_from_properties(Body,Definitions),
894 ToHash = [Sets,Constants,Properties,Definitions],
895 raw_sha_hash(ToHash,Hash).
896 % save_properties_hash(Name,ToHash,Hash).
897
898 extract_sorted_np_sets(Body,Sets) :-
899 get_sets(Body,PosSets),
900 remove_raw_position_info(PosSets,UnsortedSets),
901 sort(UnsortedSets,Sets).
902 extract_sorted_np_constants(Body,Constants) :-
903 get_opt_sections([constants,concrete_constants,abstract_constants],Body,PosConstants),
904 remove_raw_position_info(PosConstants,UnsortedConstants),
905 sort(UnsortedConstants,Constants).
906 extract_np_properties(Body,Properties) :-
907 get_opt_section(properties,Body,PosProperties),
908 remove_raw_position_info(PosProperties,Properties).
909 extract_used_np_definitions_from_properties(Body,Definitions) :-
910 get_opt_section(properties,Body,Properties),
911 extract_used_np_definitions(Properties,Body,Definitions,_).
912 extract_used_np_definitions(RawSyntax,Body,Definitions,PosDefinitions) :-
913 extract_raw_identifiers(RawSyntax,UsedIds),
914 all_definition_ids(Body,AllDefs),
915 ord_intersection(UsedIds,AllDefs,UsedDefNames),
916 transitive_used_definitions(UsedDefNames,AllUsedDefs),
917 findall( definition(none,Name,Args,DefBody),
918 ( member(Name,AllUsedDefs),b_get_definition(Name,_DefType,Args,DefBody,_Deps)),
919 PosDefinitions),
920 maplist(remove_raw_position_info,PosDefinitions,Definitions).
921 all_definition_ids(Body,Ids) :-
922 get_opt_section(definitions,Body,Definitions),
923 convlist(get_definition_name,Definitions,Ids1),
924 sort(Ids1,Ids).
925 transitive_used_definitions(Defs,TransDefs) :-
926 findall( D, reachable_definition(Defs,D), TD1),
927 sort(TD1,TransDefs).
928 reachable_definition(Defs,D) :-
929 member(N,Defs),
930 ( D=N
931 ; b_get_definition(N,_DefType,_Args,_Body,Deps),
932 reachable_definition(Deps,D)).
933
934
935 /* just for debugging:
936 save_properties_hash(MachineName,ToHash,Hash) :-
937 main_machine_name(Main),
938 open('/home/plagge/hashes.pl',append,S),
939 writeq(S,hash(Main,MachineName,ToHash,Hash)),
940 write(S,'.\n'),
941 close(S).
942 */
943
944 % ---------------------------
945 :- dynamic event_info/3.
946 analyze_extends_relation :-
947 retractall(event_info(_,_,_)),
948 bmachine:b_get_machine_operation(_Name,_Results,_RealParameters,TBody,_OType,_OpPos),
949 treat_event_body(TBody),fail.
950 analyze_extends_relation.
951
952 treat_event_body(TBody) :-
953 rlevent_info(TBody,EventName,Machine,Status,AbstractEvents),
954 % format('Event ~w:~w ~w~n',[Machine,EventName,Status]),
955 assertz(event_info(Machine,EventName,Status)),
956 maplist(treat_event_body,AbstractEvents).
957
958 :- use_module(bsyntaxtree,[get_texpr_expr/2]).
959 rlevent_info(TBody,EventName,Machine,FStatus,AbstractEvents) :-
960 get_texpr_expr(TBody,Event),
961 Event = rlevent(EventName,Machine,TStatus,_Params,_Guard,_Theorems,_Actions,_VWit,_PWit,_Unmod,AbstractEvents),
962 bsyntaxtree:get_texpr_expr(TStatus,Status), %ordinary, convergent, anticipated
963 functor(Status,FStatus,_).
964
965
966 % write the event refinement hierarchy to a dot file
967 % (currently) only makes sense for Event-B models
968
969 :- use_module(preferences,[get_preference/2]).
970 :- use_module(tools_strings,[ajoin/2, ajoin_with_sep/3]).
971
972 :- public dot_refinement_node_new/4.
973 % variation for: use_new_dot_attr_pred
974 dot_refinement_node_new(event_refinement,M:Ev,M,[label/Desc,shape/Shape,tooltip/Tooltip|T1]) :-
975 dot_event_node(M:Ev,M,Desc,Shape,Style,Color),
976 (Style=none -> T1=T2 ; T1=[style/Style|T2]),
977 (Color=none -> T2=[] ; T2=[color/Color]),
978 (event_info(M,Ev,Status) -> true ; Status=unknown),
979 (event_refinement_change(M,Ev,AbsName,AbsEvName,SameGuard,SameAct)
980 -> ajoin(['Event ',Ev,' in ',M,
981 '\n status: ',Status,
982 '\n refines ',AbsEvName,' in ',AbsName,
983 '\n guard: ',SameGuard,
984 '\n action: ',SameAct], Tooltip)
985 ; ajoin(['Event ',Ev,' in ',M,
986 '\n status: ',Status], Tooltip)).
987 dot_refinement_node_new(variable_refinement(With),M:Var,M,[label/Desc,shape/Shape,color/Color,tooltip/Tooltip|T1]) :-
988 (With=with_constants -> machine_ids(M,Vars) ; machine_variables(M,Vars)),
989 member(Var,Vars),
990 Desc=Var,
991 (id_exists_in_abstraction(M,Anc,Var)
992 -> get_preference(dot_event_hierarchy_unchanged_event_colour,Color), T1=[style/filled],
993 Shape = rect, % we could use plain; makes kept events smaller
994 ajoin(['Variable kept from abstraction ',Anc],Tooltip)
995 ; machine_type(M,context), machine_sets(M,Sets), member(Var,Sets) ->
996 get_preference(dot_event_hierarchy_refines_colour,Color), T1=[style/'rounded,filled'],
997 Shape = rect,
998 ajoin(['New set in ',M],Tooltip)
999 ; machine_type(M,context) -> % it must be a constant
1000 get_preference(dot_event_hierarchy_new_event_colour,Color), T1=[style/rounded],
1001 Shape = rect,
1002 ajoin(['New constant in ',M],Tooltip)
1003 ; get_preference(dot_event_hierarchy_new_event_colour,Color), T1=[],
1004 Shape = rect,
1005 ajoin(['New variable in ',M],Tooltip)
1006 ).
1007 %dot_refinement_node_new(variable_refinement(_),C:Cst,M,[label/Desc,shape/rect,color/Color,tooltip/Desc|T1]) :-
1008 % new_seen_context(M,C), machine_constants(C,Csts), member(Cst,Csts),
1009 % Desc=Cst, T1=[style/rounded], get_preference(dot_event_hierarchy_extends_colour,Color).
1010
1011 % the node ide is M:Ev as Ev can and usually does occur multiple times
1012 dot_event_node(M:Ev,M,Desc,Shape,Style,Color) :-
1013 findall(showev(M,Ev),event_to_show(M,Ev),List), sort(List,SList),
1014 member(showev(M,Ev),SList),
1015 (event_info(M,Ev,Status) -> true ; Status=unknown),
1016 (event_refinement_change(M,Ev,_,_,SameGuard,SameAction)
1017 -> true ; SameGuard=unknown, SameAction=unknown),
1018 (SameGuard=SameAction, SameGuard \= unknown -> ajoin([Ev,'\\n(',SameAction,')'],Ev2)
1019 ; SameGuard=unchanged ,SameAction=extends-> ajoin([Ev,'\\n(same grd, extends act)'],Ev2)
1020 ; SameGuard=unchanged -> ajoin([Ev,'\\n(same grd)'],Ev2)
1021 ; SameGuard=extends,SameAction=unchanged -> ajoin([Ev,'\\n(same act, extends grd)'],Ev2)
1022 ; SameAction=unchanged -> ajoin([Ev,'\\n(same act)'],Ev2)
1023 ; SameGuard=extends -> ajoin([Ev,'\\n(extends grd)'],Ev2)
1024 ; SameAction=extends -> ajoin([Ev,'\\n(extends act)'],Ev2)
1025 ; Ev2=Ev),
1026 (Status = convergent -> ajoin([Ev2,' (<)'],Desc)
1027 ; Status = anticipated -> ajoin([Ev2, ' (<=)'],Desc)
1028 ; Desc=Ev2),
1029 % format(user_output,'event ~w, status:~w, same guard:~w, same action:~w~n',[Ev,Status,SameGuard,SameAction]),
1030 dot_get_color_style(M,Ev,Status,SameGuard,SameAction,Shape,Color,Style).
1031
1032 event_to_show(M,Ev) :- machine_operations(M,Evs),
1033 raw_identifier_member(Ev,Evs), Ev \= 'INITIALISATION'.
1034 event_to_show(M,Ev) :-
1035 event_refinement_change(M,Ev,_,_,_,_), % for events that disappear, i.e., are not refined until bottom level
1036 Ev \= 'INITIALISATION'.
1037
1038
1039 dot_get_color_style(M,Ev,_Status,_,_,box,Color,Style) :- \+ refines_event(M,Ev,_,_),!,
1040 get_preference(dot_event_hierarchy_new_event_colour,Color), Style=none.
1041 dot_get_color_style(M,Ev,_,SameGuard,SameAction,box,Color,Style) :-
1042 refines_event(M,Ev,_,Ev2), dif(Ev2,Ev),!, % changes name
1043 ((SameGuard,SameAction)=(unchanged,unchanged)
1044 -> get_preference(dot_event_hierarchy_rename_unchanged_event_colour,Color)
1045 ; get_preference(dot_event_hierarchy_rename_event_colour,Color)), Style=filled.
1046 dot_get_color_style(_M,_Ev,_,unchanged,unchanged,plain,Color,Style) :- % keeps name and adds no guard or action
1047 !,
1048 get_preference(dot_event_hierarchy_unchanged_event_colour,Color), Style=filled.
1049 dot_get_color_style(_M,_Ev,_,_,unchanged,box,Color,Style) :- % keeps name and adds no action, but modifies guard
1050 !,
1051 get_preference(dot_event_hierarchy_grd_strengthening_event_colour,Color), Style=filled.
1052 dot_get_color_style(_M,_Ev,_,unchanged,_,box,Color,Style) :- % keeps name and adds action but keeps guard
1053 !,
1054 get_preference(dot_event_hierarchy_grd_keeping_event_colour,Color), Style=filled.
1055 dot_get_color_style(_M,_Ev,_,_,_,box,Color,Style) :- % keeps name but adds or modifies
1056 % TO DO: distinguish extends from refines
1057 get_preference(dot_event_hierarchy_refines_colour,Color), Style=filled.
1058
1059 :- public dot_refines_event/4.
1060 % dot transition predicate for event and variable refinement hierarchy diagram
1061 dot_refines_event(event_refinement,M2:Ev2,M1:Ev1,[label/Label,color/Color,style/Style]) :-
1062 Label = '', % TO DO: detect refine, extends, identical
1063 refines_event(M1,Ev1,M2,Ev2),
1064 Ev1 \= 'INITIALISATION',
1065 (event_refinement_change(M1,Ev1,_,_,SameGuard,SameAct)
1066 -> arrow_style(SameGuard,SameAct,Style,ColPref), get_preference(ColPref,Color)
1067 ; Style=solid, Color=red % should not happen
1068 ).
1069 dot_refines_event(variable_refinement(With),M1:Var,M2:Var2,[label/Label,color/Color,style/Style|T1]) :-
1070 get_preference(dot_event_hierarchy_edge_colour,Color),
1071 (With=with_constants -> machine_ids(M2,Vars2) ; machine_variables(M2,Vars2)),
1072 if((member(Var,Vars2),
1073 id_exists_in_abstraction(M2,M1,Var)),
1074 (Label='',Var2=Var,Style=dashed, T1=[]),
1075 (% no variable of M2 exists in M1
1076 refines_or_extends_machine(M2,M1),
1077 machine_ids(M1,[Var|_]), % get first variable of M1
1078 Vars2=[Var2|_], Style=dotted, % add virtual edge to first variable of M2 if no variable is kept
1079 get_dot_cluster_name(M1,M1C), get_dot_cluster_name(M2,M2C),
1080 T1 = [ltail/M1C, lhead/M2C],
1081 (machine_type(M2,context) -> Label='extends' ; Label='')
1082 )
1083 ).
1084 dot_refines_event(variable_refinement(with_constants),M1:Var1,M2:Cst2,[label/Label,color/Color,style/Style|T1]) :- Label='sees',
1085 Color=gray80, Style=solid,
1086 new_seen_context(M1,M2),
1087 machine_ids(M1,[Var1|_]),
1088 machine_ids(M2,[Cst2|_]),
1089 get_dot_cluster_name(M1,M1C), get_dot_cluster_name(M2,M2C),
1090 T1 = [ltail/M1C, lhead/M2C, dir/forward].
1091
1092 arrow_style(unchanged,unchanged,Style,ColPref) :- !,
1093 Style=arrowhead(none,solid), ColPref=dot_event_hierarchy_extends_colour.
1094 arrow_style(refines,_,Style,ColPref) :- !, Style=solid, ColPref=dot_event_hierarchy_edge_colour.
1095 arrow_style(_,refines,Style,ColPref) :- !, Style=solid, ColPref=dot_event_hierarchy_edge_colour.
1096 %arrow_style(_,_,Style) :- Style = arrowhead(vee,arrowtail(box,solid)). % we have extends
1097 arrow_style(_,_,Style,dot_event_hierarchy_extends_colour) :- Style = arrowhead(vee,solid). % we have extends
1098
1099
1100 %dot_same_rank(SameRankVals) :- machine_operations(M,Evs),
1101 % findall(M:Ev,raw_identifier_member(Ev,Evs),SameRankVals).
1102
1103 dot_subgraph(Kind,sub_graph_with_attributes(M,Attrs), filled,Colour) :-
1104 get_preference(dot_event_hierarchy_machine_colour,MColour),
1105 Attrs = [label/Label, tooltip/ToolTip],
1106 machine_operations(M,Ops),
1107 (Kind=event_refinement -> Ops=[_|_] ; true),
1108 (machine_type(M,context) -> IDS = 'csts', Colour=gray90
1109 ; IDS = 'vars', Colour=MColour),
1110 (machine_ids(M,Vars)
1111 -> length(Vars,V),
1112 findall(C,new_seen_context(M,C),NewC),
1113 split_list(id_exists_in_abstraction(M),Vars,_Old,NewVars),
1114 length(NewVars,NewNr),
1115 findall(Del,(var_exists_in_abstraction(M,Del), nonmember(Del,Vars)),DelVars),
1116 length(DelVars,DelNr),
1117 (Kind=event_refinement, get_preference(dot_hierarchy_show_extra_detail,false)
1118 -> Label=M
1119 ; ajoin([M,'\\n#',IDS,'=',V, ' (+',NewNr,',-', DelNr,')'],Label)
1120 ),
1121 ajoin_with_sep(NewVars,',',NV),
1122 ajoin_with_sep(DelVars,',',DV),
1123 ajoin_with_sep(NewC,',',NC),
1124 ajoin(['machine ',M,'\\n#',IDS,'=',V, ' (+',NewNr,',-', DelNr,')',
1125 '\\nnew sees=',NC,
1126 '\\nnew ',IDS,'=',NV,
1127 '\\ndel ',IDS,'=',DV],ToolTip)
1128 ; Label=M, ToolTip=M).
1129
1130 machine_variables(M,Vars) :- machine_identifiers(M,_Params,_Sets,AVars,CVars,_AConsts,_CConsts),
1131 append(CVars,AVars,RVars), % for Event-B: CVars=[]
1132 maplist(get_raw_identifier,RVars,Vars).
1133 %machine_constants(M,Consts) :- machine_identifiers(M,_Params,_Sets,_AVars,_CVars,AConsts,CConsts),
1134 % append(CConsts,AConsts,Raw),
1135 % maplist(get_raw_identifier,Raw,Consts).
1136 machine_ids(M,Vars) :- machine_identifiers(M,_Params,Sets,AVars,CVars,AConsts,CConsts),
1137 append([Sets,CConsts,CVars,AConsts,AVars],RVars),
1138 maplist(get_raw_identifier,RVars,Vars).
1139 machine_sets(M,Vars) :- machine_identifiers(M,_,Sets,_,_,_,_),
1140 maplist(get_raw_identifier,Sets,Vars).
1141
1142 var_exists_in_abstraction(M,Var) :-
1143 var_exists_in_abstraction(M,_Anc,Var).
1144 var_exists_in_abstraction(M,Anc,Var) :-
1145 refines_machine(M,Anc),
1146 machine_variables(Anc,AncVars),
1147 member(Var,AncVars).
1148
1149 refines_machine(M,Anc) :-
1150 machine_references(M,Refs),
1151 member(ref(refines,Anc,_),Refs).
1152
1153 % variable or constant exists in abstraction
1154 id_exists_in_abstraction(M,Var) :-
1155 id_exists_in_abstraction(M,_Anc,Var).
1156 id_exists_in_abstraction(M,Anc,Var) :-
1157 refines_or_extends_machine(M,Anc),
1158 machine_ids(Anc,AncVars),
1159 member(Var,AncVars).
1160
1161 refines_or_extends_machine(M,Anc) :-
1162 machine_references(M,Refs),
1163 (member(ref(refines,Anc,_),Refs) -> true ; member(ref(extends,Anc,_),Refs)).
1164
1165 new_seen_context(M,Context) :- machine_references(M,Refs),
1166 member(ref(sees,Context,_),Refs),
1167 \+ (member(ref(refines,Anc,_),Refs),
1168 sees_context(Anc,Context)).
1169
1170 sees_context(M,Context) :- machine_references(M,Refs), member(ref(sees,Context,_),Refs).
1171
1172
1173 write_dot_event_hierarchy_to_file(File) :-
1174 write_dot_ref_hierarchy_to_file(event_refinement,File).
1175 write_dot_variable_hierarchy_to_file(File) :-
1176 (get_preference(dot_hierarchy_show_extra_detail,false) -> With=no_constants ; With=with_constants),
1177 write_dot_ref_hierarchy_to_file(variable_refinement(With),File).
1178 write_dot_ref_hierarchy_to_file(Kind,File) :-
1179 analyze_extends_relation,
1180 (get_preference(dot_event_hierarchy_horizontal,true)
1181 -> PageOpts=[compound/true,rankdir/'LR',no_page_size]
1182 ; PageOpts=[compound/true]),
1183 gen_dot_graph(File,PageOpts,
1184 use_new_dot_attr_pred(b_machine_hierarchy:dot_refinement_node_new(Kind)),
1185 use_new_dot_attr_pred(b_machine_hierarchy:dot_refines_event(Kind)),
1186 dot_no_same_rank,dot_subgraph(Kind)).
1187 %gen_dot_graph(File,PageOpts,dot_event_node,dot_refines_event,dot_no_same_rank,dot_subgraph).