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