1 % (c) 2009-2025 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(bmachine_construction,[reset_bmachine_construction/0,
6 check_machine/4,
7 type_in_machine_l/6,
8 type_open_predicate_with_quantifier/6,
9 get_constructed_machine_name/2, get_constructed_machine_name_and_filenumber/3,
10 type_open_formula/8,
11 create_scope/6, % create type-checking scope
12 filter_linking_invariant/3,
13 machine_promotes_operations/2,
14 machine_hides_unpromoted_operation/4,
15 external_procedure_used/1,
16 abstract_variable_removed_in/3,
17 dummy_machine_name/2]).
18
19 :- use_module(module_information,[module_info/2]).
20 :- module_info(group,typechecker).
21 :- module_info(description,'This module contains the rules for loading, including, seeing, etc. B machines, scope of constants, variables, parameters, etc.').
22
23 :- use_module(library(lists)).
24 :- use_module(library(avl)).
25
26 :- use_module(self_check).
27 :- use_module(tools).
28 :- use_module(error_manager).
29 :- use_module(debug).
30 :- use_module(preferences).
31
32 :- use_module(btypechecker).
33 :- use_module(b_ast_cleanup).
34 :- use_module(bsyntaxtree).
35 :- use_module(bmachine_structure).
36 :- use_module(pragmas).
37 :- use_module(b_global_sets,[register_enumerated_sets/2]).
38
39 :- use_module(bmachine_static_checks).
40 :- use_module(tools_lists,[ord_member_nonvar_chk/2, remove_dups_keep_order/2]).
41
42 :- use_module(translate,[print_machine/1]).
43
44
45 :- set_prolog_flag(double_quotes, codes).
46
47 %maximum_type_errors(100).
48
49 :- dynamic debug_machine/0.
50 :- dynamic abstract_variable_removed_in/3.
51
52 :- use_module(pref_definitions,[b_get_important_preferences_from_raw_machine/2]).
53 set_important_prefs_from_machine(Main,Machines) :-
54 find_machine(Main,Machines,_MType,_Header,RawMachine),
55 ? get_raw_model_type(Main,Machines,RawModelType),!,
56 b_get_important_preferences_from_raw_machine(RawMachine,RawModelType),
57 check_important_annotions_from_machine(RawMachine).
58
59 check_important_annotions_from_machine(RawMachine) :-
60 ? member(definitions(_Pos,Defs),RawMachine),
61 member(expression_definition(DPOS,'PROB_REQUIRED_VERSION',[],RawValue),Defs),!,
62 (RawValue = string(VPos,Version)
63 -> add_message(bmachine_construction,'Checking PROB_REQUIRED_VERSION: ',Version,VPos),
64 (check_version(Version,VPos) -> true ; true)
65 ; add_warning(bmachine_construction,'PROB_REQUIRED_VERSION must provide a version number string.','',DPOS)
66 ).
67 check_important_annotions_from_machine(_).
68
69 :- use_module(version,[compare_against_current_version/2,full_version_str/1]).
70 check_version(VersAtom,DPOS) :- atom_codes(VersAtom,Codes),
71 split_chars(Codes,".",VCNrs),
72 maplist(codes_to_number(DPOS),VCNrs,VNrs),
73 compare_against_current_version(VNrs,Result),
74 (Result = current_older
75 -> full_version_str(Cur),
76 ajoin(['This model requires at newer version of ProB than ',Cur,'. Download at least version: '],Msg),
77 add_warning(prob_too_old,Msg,VersAtom,DPOS)
78 ; true).
79
80 codes_to_number(DPOS,C,A) :-
81 catch(number_codes(A,C), error(syntax_error(_N),_),
82 (atom_codes(AA,C),
83 add_warning(bmachine_construction,'Illegal part of version number (use only numbers separated by dots): ',AA,DPOS),fail)).
84
85 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
86
87 :- use_module(preferences,[temporary_set_preference/3,reset_temporary_preference/2]).
88
89 % typecheck complete machines (incl. includes)
90 check_machine(MainName,MachinesMayContainGenerated,Result,FinalErrors) :-
91 clear_warnings,
92 debug_println(9,checking_machine(MainName)),
93 temporary_set_preference(perform_stricter_static_checks,true,CHNG),
94 strip_global_pragmas(MachinesMayContainGenerated,Machines,_WasGenerated), % TODO: is generated still used?
95 set_important_prefs_from_machine(MainName,Machines), % set important prefs before type-checking,...
96 check_main_machine_file_origin(MainName,Machines),
97 % we need to find all SEES/USES declarations, because all references
98 % refer to the same machine and that has to be included exactly once.
99 find_uses(Machines,GlobalUses,NotIncluded,Errors,E1),
100 % if a seen/used machine was not included, we include it by constructing
101 % a dummy machine that extends the seen/used machine and the origional main machine
102 extend_not_included_uses(NotIncluded,MainName,NewMainName,Machines,IMachines),
103 % figure out the right order of machines, so that each machine is
104 % type-checked before a dependend machine is loaded
105 machine_order(IMachines,Order),
106 assert_machine_order(Order),
107 % expand (= type-check + includes) machines in the given order
108 expand_machines(Order,IMachines,GlobalUses,[],Results1,E1,E2),
109 % until now, the initialisation section consists of a list of init(MachineName,Substitution)
110 % fold_initialisation merges those to one substitution, respecting the dependencies
111 % between the machines
112 maplist(fold_initialisation(Order),Results1,Results),
113 % find main machine
114 memberchk(machine(NewMainName,MainMachine),Results), %nl,print('MAIN:'),nl,print_machine(MainMachine),
115 % if the main machine has parameters, we convert them to global sets resp. constants
116 convert_parameters_to_global_sets(E2,[],MainMachine,Result1),
117 % add some additional informations about the machine
118 add_machine_infos(MainName,Machines,Results,Result1,Result),
119 ( debug_machine -> print_machine(Result); true),
120 %% comment in to pretty print all machines:
121 %( member(machine(Name,Mchx),Results), format('~n*** Machine ~w~n',[Name]), print_machine(Mchx),nl,fail ; true),
122 % finalize the list of errors, remove duplicates
123 sort(Errors,FinalErrors),
124 % output warnings
125 show_warnings,
126 % run static checks on the resulting machine
127 static_check_main_machine(Result),
128 reset_temporary_preference(perform_stricter_static_checks,CHNG).
129 check_machine(Main,_,Result,FinalErrors) :-
130 add_internal_error('Internal error: Checking the machine failed: ',
131 check_machine(Main,_,Result,FinalErrors)),
132 fail.
133
134 strip_global_pragmas([],[],false).
135 strip_global_pragmas([generated(POS,M)|Ms],MachinesOut,true) :- !, % @generated pragma used at top of file
136 assertz(pragmas:global_pragma(generated,POS)),
137 strip_global_pragmas([M|Ms],MachinesOut,_).
138 strip_global_pragmas([unit_alias(_,Alias,Content,M)|Ms],MachinesOut,true) :- !,
139 assertz(pragmas:global_pragma(unit_alias,[Alias|Content])),
140 strip_global_pragmas([M|Ms],MachinesOut,_).
141 strip_global_pragmas([M|Ms],[M|SMs],WasGenerated) :-
142 strip_global_pragmas(Ms,SMs,WasGenerated).
143
144 fold_initialisation(Order,machine(Name,Sections),machine(Name,NewSections)) :-
145 select_section(initialisation,List,Subst,Sections,NewSections),
146 maplist(extract_init_substitutions(List),Order,LSubstitutions),
147 append(LSubstitutions,Substitutions),
148 create_init_sequence(Substitutions,Subst).
149 extract_init_substitutions(Unsorted,Name,Substitutions) :-
150 convlist(unzip_init(Name),Unsorted,Substitutions). % keep inits for Name
151 unzip_init(Name,init(Name,Subst),Subst).
152 create_init_sequence([],Subst) :- !, create_texpr(skip,subst,[generated],Subst).
153 create_init_sequence([I],I) :- !.
154 create_init_sequence(L,Sequence) :-
155 (L = [First|_], get_texpr_info(First,AllInfos), extract_pos_infos(AllInfos,Pos) -> true ; Pos=[]),
156 % TODO: try and merge first and last position info
157 (get_preference(allow_overriding_initialisation,true),
158 override_initialisation_sequence(L,NL)
159 -> NewList=NL ; NewList=L),
160 create_texpr(sequence(NewList),subst,[initial_sequence|Pos],Sequence).
161
162 :- use_module(b_read_write_info,[get_accessed_vars/4]).
163 % override initialisation sequence, remove unnecessary earlier assignments (which may time-out, ...)
164 % in future we may inline equalities into becomes_such that, e.g., x :: S ; x := 1 --> x :: X /\ {1}
165 % currently x :: S ; x := 1 gets simplified to skip ; x := 1
166 override_initialisation_sequence(List,NewList) :-
167 append(Prefix,[Last],List),
168 Prefix = [_|_], % there are some earlier initialisation statements to simplify
169 get_accessed_vars(Last,[],LIds,Read),
170 ord_intersection(LIds,Read,RWIds),
171 (RWIds = []
172 -> true
173 ; add_warning(b_machine_construction,'Initialisation (override) statement reads written variables:',RWIds,Last)
174 ),
175 process_override(Last,Prefix, NewLast, SPrefix),
176 append(SPrefix,[NewLast],NewList).
177
178
179 process_override(b(parallel(List),subst,Info), Prefix,
180 b(parallel(NewList),subst,Info), NewPrefix) :- !,
181 l_process_override(List,Prefix,NewList,NewPrefix).
182 process_override(Subst, Prefix, NewSubst, NewPrefix) :-
183 create_after_pred(Subst,AfterPred),
184 get_accessed_vars(Subst,[],Ids,Read),
185 % write(after_pred(Ids, read(Read))),nl, translate:print_bexpr(AfterPred),nl,
186 ord_intersection(Read,Ids,RWIds),
187 (RWIds=[]
188 -> maplist(try_simplify_init_stmt(Ids,AfterPred,Keep),Prefix,NewPrefix),
189 !,
190 (Keep==merged_override_stmt
191 -> NewSubst = b(skip,subst,[was(Subst)])
192 ; NewSubst = Subst
193 )
194 ; add_warning(b_machine_construction,'Initialisation statement reads written variables:',RWIds,Subst),
195 fail % we actually have a before after predicate which may modify RWIds
196 ).
197 process_override(Subst, Prefix , Subst, Prefix) :- add_message(b_machine_construction,'Keeping: ',Subst,Subst).
198
199 l_process_override([],Prefix,[],Prefix).
200 l_process_override([H|List],Prefix,[H1|NewList],NewPrefix) :-
201 process_override(H,Prefix,H1,Prefix1),
202 l_process_override(List,Prefix1,NewList,NewPrefix).
203
204 :- use_module(library(ordsets)).
205 simplify_init_stmt(b(parallel(List),subst,I),OverrideIds,AfterPred,Keep,b(parallel(SList),subst,I)) :- !,
206 maplist(try_simplify_init_stmt(OverrideIds,AfterPred,Keep),List,SList).
207 simplify_init_stmt(Assign,OverrideIds,AfterPred,Keep,NewSubst) :-
208 get_accessed_vars(Assign,[],AssignIds,_Read),
209 (ord_subset(OverrideIds,AssignIds),
210 merge_statement(Assign,AssignIds,AfterPred,NewSubst),
211 Keep = merged_override_stmt
212 -> % we need to remove the override assign, if it is non-det.
213 add_message(b_machine_construction,'Adapting initialisation due to override: ',NewSubst,Assign)
214 ; ord_subset(AssignIds,OverrideIds)
215 % The assignment is useless, will be completely overriden
216 -> NewSubst = b(skip,subst,[was(Assign)]),
217 add_message(b_machine_construction,'Removing initialisation due to override: ',Assign,Assign),
218 Keep = keep_override_stmt
219 ).
220 % TODO: we could simplify IF-THEN-ELSE, ... and other constructs
221
222 % Note: the merging assumes the initialisation before the override assigns each overriden variable only once
223 try_simplify_init_stmt(OverrideIds,AfterPred,Keep,Stmt,NewStmt) :-
224 (simplify_init_stmt(Stmt,OverrideIds,AfterPred,Keep,N)
225 -> NewStmt=N ; NewStmt=Stmt).
226
227 merge_statement(b(Subst,subst,Info),AssignIds,AfterPred,b(NewSubst,subst,Info)) :-
228 merge_stmt_aux(Subst,AssignIds,AfterPred,NewSubst).
229
230 merge_stmt_aux(becomes_such(Ids,Pred),_AssignIds,AfterPred,becomes_such(Ids,NewPred)) :-
231 conjunct_predicates([AfterPred,Pred],NewPred).
232 merge_stmt_aux(becomes_element_of(Ids,Set),_,AfterPred2,becomes_such(Ids,NewPred)) :-
233 create_couple(Ids,Couple),
234 safe_create_texpr(member(Couple,Set),pred,AfterPred1),
235 conjunct_predicates([AfterPred1,AfterPred2],NewPred).
236
237 create_after_pred(b(Subst,subst,Info),Pred) :- create_after_pred_aux(Subst,Info,Pred).
238
239 create_after_pred_aux(assign_single_id(Id,RHS),Info,b(equal(Id,RHS),pred,Info)).
240 create_after_pred_aux(assign(LHS,RHS),_Info,Conj) :- % TODO: split assignments so that we can individually apply preds
241 maplist(create_equality,LHS,RHS,Eqs),
242 conjunct_predicates(Eqs,Conj).
243 % the following two are non-deterministic; hence we need to remove the substitutions
244 % in case we have managed to merge them into an earlier becomes_such,... (otherwise we may do a second non-det incompatible choice)
245 create_after_pred_aux(becomes_element_of(Id,Set),Info,b(member(Couple,Set),pred,Info)) :-
246 create_couple(Id,Couple).
247 create_after_pred_aux(becomes_such(_,Pred),_Info,Pred).
248
249
250 % -------------------------
251
252 add_machine_infos(MainName,Machines,CheckedMachines,Old,New) :-
253 ? get_raw_model_type(MainName,Machines,RawModelType), functor(RawModelType,ModelType,_), % argument is position
254 % model type could be machine or system (or model ?)
255 !,
256 append_to_section(meta,[model_type/ModelType,hierarchy/Hierarchy,header_pos/HeaderPosList],Old,NewT),
257 get_refinement_hierarchy(MainName,Machines,Hierarchy),
258 find_machine_header_positions(Machines,HeaderPosList),
259 add_refined_machine(Hierarchy,CheckedMachines,NewT,New).
260 get_refinement_hierarchy(Main,Machines,[Main|Abstractions]) :-
261 ( find_refinement(Machines,Main,Abstract) ->
262 get_refinement_hierarchy(Abstract,Machines,Abstractions)
263 ;
264 Abstractions = []).
265 find_refinement([M|Rest],Name,Abstract) :-
266 ( get_constructed_machine_name(M,Name) ->
267 refines(M,Abstract)
268 ;
269 find_refinement(Rest,Name,Abstract)).
270
271 find_machine_header_positions(Machines,SRes) :-
272 Header = machine_header(Pos,_Nm,_Paras),
273 findall(Name/Pos,find_machine(Name,Machines,_Type,Header,_Sections),Res),
274 sort(Res,SRes).
275
276 :- use_module(specfile,[animation_minor_mode/1]).
277 % check whether the main machine has filenumber 1; if not something strange is going on.
278 % an example can be found in prob_examples/public_examples/B/ErrorMachines/IllegalSeesIncludes/WrongNameM1.mch
279 check_main_machine_file_origin(MainName,Machines) :-
280 ? member(M,Machines), get_machine_parameters(M,MainName,_,Position),
281 !,
282 (Position = none -> true
283 ; get_nr_name(Position,Number,Name)
284 -> (Number=1 -> true
285 ; ajoin(['Main machine name ',MainName,' overriden by machine in file ',Number,' :'],Msg),
286 add_error(bmachine_construction,Msg,Name,Position))
287 ; add_error(bmachine_construction,'Could not extract file number and name:',Position)
288 ).
289 check_main_machine_file_origin(MainName,_) :-
290 add_error(bmachine_construction,'Could not extract file number and name for main machine:',MainName).
291 get_nr_name(none,Nr,Name) :- !, Nr=1,Name=none.
292 get_nr_name(1,Nr,Name) :- !, Nr=1,Name=none. % TLA mode, animation_minor_mode(tla) not yet set and positions are numbers
293 get_nr_name(Position,Number,Name) :- extract_file_number_and_name(Position,Number,Name).
294
295 add_refined_machine([_Main,Refined|_],Machines,Old,New) :-
296 member(machine(Refined,Body),Machines),!,
297 append_to_section(meta,[refined_machine/Body],Old,New).
298 add_refined_machine(_,_,M,M). % not refining
299
300 convert_parameters_to_global_sets(Ein,Eout) -->
301 % extract and remove parameters and constraints
302 select_section(parameters,PP,[]),
303 select_section(internal_parameters,IP,[]),
304 {create_texpr(truth,pred,[],Truth)},
305 select_section(constraints,C,Truth),
306 % split parameters into sets and scalars
307 { split_list(is_set_parameter,PP,Sets,Scalars),
308 foldl(type_set_parameter,Sets,Ein,Eout) },
309 % put the sets to the deferred sets
310 append_to_section(deferred_sets,Sets),
311 % and the scalars to the constants
312 append_to_section(concrete_constants,Scalars),
313 append_to_section(concrete_constants,IP),
314 % the scalars should be typed by constraints,
315 % so move the constraints to the properties
316 select_section(properties,OldProps,NewProps),
317 {conjunct_predicates([C,OldProps],NewProps)}.
318 is_set_parameter(TExpr) :-
319 % upper case identifiers denote set parameters, otherwise scalars
320 get_texpr_id(TExpr,Name),is_upper_case(Name).
321 type_set_parameter(TExpr,Ein,Eout) :-
322 get_texpr_id(TExpr,Name),
323 get_texpr_type(TExpr,Type),
324 get_texpr_pos(TExpr,Pos),
325 % we directly type the deferred set
326 unify_types_werrors(set(global(Name)),Type,Pos,'PARAMETER',Ein,Eout).
327
328
329 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
330 % included machines
331
332 expand_machines([],_,_,M,M,Errors,Errors).
333 expand_machines([M|Rest],Machines,GlobalUses,Typed,Result,Ein,Eout) :-
334 ? ( expand_machine(M,Machines,GlobalUses,Typed,New,Ein,E1) -> true
335 ; add_error(bmachine_construction,'Expansion of machine failed:',M),fail),
336 expand_machines(Rest,Machines,GlobalUses,[machine(M,New)|Typed],Result,E1,Eout).
337
338 % resolve all includes and typecheck the machine
339 % expand_machine(Name,Machines,TypeChecked,Expanded) :
340 % Name of the Machine to expand
341 % Machines contains the list of all loaded machines
342 % TypeChecked contains the list of all expanded machines so far
343 % Expanded is the resulting machine
344 expand_machine(Name,Machines,GlobalUses,TypeChecked,Expanded,Ein,Eout) :-
345 debug_format(9,'~nExpanding machine ~w~n',[Name]),
346 % find the machine in the list
347 find_machine(Name,Machines,MType,Header,RawMachineWithPragmas),
348 % remove pragmas for later reattachment
349 strip_machine_section_pragmas(RawMachineWithPragmas,RawMachine,_Pragmas),
350 % look for abstract machine
351 get_abstractions(Name,Machines,TypeChecked,Abstractions),
352 % merge all used and seen machines
353 ? use_and_see_machines(RawMachine,TypeChecked,SeenRefs),
354 % merge all included machines into one machine
355 include_machines(RawMachine, TypeChecked, GlobalUses, Includes, Parameters, Included, Promotes),
356 % Parameters contains now a list of parameters for each included machine
357 % Included contains now a machine that represents all included machines
358 % their parameters are renamed to internal_parameters
359 append([Abstractions,Included,SeenRefs],RefMachines),
360 % typecheck this machine
361 debug_stats(type_machine(Name)),
362 ? type_machine(Header,Name,MType,RawMachine,RefMachines,TypedLocal,RefMachines2,Ein,Err1),
363 % merge included and including machine
364 debug_stats(merge_included_machines(Name)),
365 merge_included_machines(Name,TypedLocal,Included,Promotes,Expanded2,Err1,Err2),
366 % add some predicates that state the equivalence between arguments
367 % in the include statement and the parameters of the included machine
368 add_link_constraints(Includes,MType,Parameters,RefMachines2,Expanded2,Expanded3,Err2,Err3),
369 % put together refinement and abstraction.
370 ? merge_refinement_and_abstraction(Name,Expanded3,[ref(local,TypedLocal)|RefMachines2],Expanded4,Err3,Eout),
371 % merge used machines, will also prefix
372 debug_stats(merge_used_machines(Name)),
373 merge_used_machines(Included,Expanded4,Expanded5),
374 % clean up the syntax tree
375 debug_stats(clean_up_machine(Name)),
376 clean_up_machine(Expanded5,RefMachines2,Expanded),
377 debug_stats(finished_clean_up_and_expand_machine(Name)).
378
379 strip_machine_section_pragmas(RawMachineWithPragmas,RawMachine,Pragmas) :-
380 selectchk(units(_Pos,RealVariables,Pragmas),RawMachineWithPragmas,TRawMachine), !,
381 RawMachine = [RealVariables|TRawMachine].
382 strip_machine_section_pragmas(Machine,Machine,[]).
383
384 merge_included_machines(Name, TypedLocal, RefMachines, Promotes, Merged, Ein, Eout) :-
385 (Promotes=[] -> true ; assertz(machine_promotes_operations(Name,Promotes))),
386 include(is_included_ref,RefMachines,Included),
387 create_machine(Name,Empty),
388 % move the included operations into the promoted or unpromoted section
389 move_operations(Included,Promotes,Included2,Ein,Eout),
390 LocalAndIncluded = [ref(local,TypedLocal)|Included2],
391 % TODO: make sure that the constants of two instances of the same machine do not repeat (check what should be done for distinct machines with same identifiers)
392 concat_sections_of_refs([identifiers,initialisation,operation_bodies,
393 assertions,used,values],LocalAndIncluded,Empty,Merged1),
394 conjunct_sections_of_refs([constraints,properties,invariant],LocalAndIncluded,Merged1,Merged2),
395 concat_section_of_simple_lists(freetypes,LocalAndIncluded,Merged2,Merged3),
396 get_section(definitions,TypedLocal,Defs),
397 write_section(definitions,Defs,Merged3,Merged).
398 is_included_ref(ref(included,_)).
399
400 concat_section_of_simple_lists(Sec,References,In,Out) :-
401 maplist(extract_machine_from_ref,References,Machines),
402 sort_machines_by_global_order(Machines,OMachines),
403 foldl(concat_section_of_simple_lists2(Sec),OMachines,In,Out).
404 concat_section_of_simple_lists2(Sec,Machine,In,Out) :-
405 get_section(Sec,In,Orig),
406 get_section(Sec,Machine,List),
407 append(Orig,List,NewList),
408 write_section(Sec,NewList,In,Out).
409
410 merge_used_machines(RefMachines,Old,New) :-
411 % get all included machines from the references
412 convlist(ref_to_included_machine,RefMachines,Included),
413 foldl(merge_used_machines2,Included,Old,New).
414 merge_used_machines2(Included,Old,New) :-
415 get_section(used,Included,IncludedUse),
416 (IncludedUse = [] -> New = Old ; rename_used(IncludedUse,Old,New)).
417 ref_to_included_machine(ref(included,Inc),Inc).
418
419 % will add prefixes to identifiers
420 rename_used(IncludedUse,Old,New) :-
421 %print(renaming(IncludedUse)),nl,
422 expand_shortcuts([properties,invariant, assertions,
423 initialisation,operation_bodies],Sections), % TO DO: also traverse GOAL ? should we later apply this at the REPL level as well ? should we apply it to other DEFINITIONS ?
424 foldl(rename_used_sec(IncludedUse),Sections,Old,New).
425 rename_used_sec(IncludedUse,Sec,Old,New) :-
426 select_section_texprs(Sec,TExprs,NewTExprs,Old,New),
427 rename_used2_l(TExprs,IncludedUse,NewTExprs).
428
429 rename_used2(TExpr,IncludedUse,NewTExpr) :-
430 get_texpr_expr(TExpr,operation(Id,Params,Results,Subst)),!,
431 rename_used2_l(Params,IncludedUse,NParams),
432 rename_used2_l(Results,IncludedUse,NResults),
433 rename_used2(Subst,IncludedUse,NSubst),
434 get_texpr_type(TExpr,Type),
435 get_texpr_info(TExpr,Info),
436 selectchk(modifies(MIn),Info,Info1),selectchk(reads(RIn),Info1,RestInfo),
437 rename_used_ids(MIn,IncludedUse,MOut),
438 rename_used_ids(RIn,IncludedUse,ROut),
439 create_texpr(operation(Id,NParams,NResults,NSubst),Type,[modifies(MOut),reads(ROut)|RestInfo],
440 NewTExpr).
441 rename_used2(TExpr,IncludedUse,NewTExpr) :-
442 % rename identifier by adding machine prefix M.id
443 get_texpr_id(TExpr,_), % result is also Id (always ??)
444 get_texpr_info(TExpr,Info),
445 ? member(usesee(Name,Id,_Mode),Info),
446 ? member(includeduse(Name,Id,NewTExpr),IncludedUse), % This seems to reuse position information from includeduse list for all identifiers !! TO DO: check this
447 % we now rename Id to Name.Id
448 !. %, print(ren_id(Name,Id)),nl.
449 rename_used2(TExpr,IncludedUse,NTExpr1) :-
450 remove_bt(TExpr,Expr,NExpr,NTExpr),
451 syntaxtransformation_for_renaming(Expr,Subs,_,NSubs,NExpr),!,
452 rename_used2_l(Subs,IncludedUse,NSubs),
453 rename_infos(NTExpr,IncludedUse,NTExpr1).
454 rename_used2(TExpr,IncludedUse,NTExpr) :-
455 add_internal_error('Rename failed: ',rename_used2(TExpr,IncludedUse,NTExpr)),
456 NTExpr = TExpr.
457
458 % update infos, e.g., read/modifies for while loops
459 rename_infos(b(E,T,I),List,b(E,T,NI)) :- maplist(rename_info(List),I,NI).
460
461 rename_info(IncludeUseList,Info,NewInfo) :- info_field_contains_ids(Info,I,NewInfo,SNI),!,
462 maplist(rename_usage_info(IncludeUseList),I,NI), sort(NI,SNI).
463 rename_info(_,I,I).
464
465 info_field_contains_ids(reads(I),I,reads(SNI),SNI).
466 info_field_contains_ids(modifies(I),I,modifies(SNI),SNI).
467 info_field_contains_ids(non_det_modifies(I),I,non_det_modifies(SNI),SNI).
468 info_field_contains_ids(modifies_locals(I),I,modifies_locals(SNI),SNI).
469 info_field_contains_ids(reads_locals(I),I,reads_locals(SNI),SNI).
470 info_field_contains_ids(used_ids(I),I,used_ids(SNI),SNI).
471
472 rename_usage_info(IncludeUseList,ID,NewID) :-
473 ? (member(includeduse(_,ID,NewTExpr),IncludeUseList) -> get_texpr_id(NewTExpr,NewID) ; NewID = ID).
474
475
476 rename_used2_l([],_,R) :- !, R=[].
477 rename_used2_l([T|Rest],IncludedUse,[NT|NRest]) :-
478 rename_used2(T,IncludedUse,NT), !,
479 rename_used2_l(Rest,IncludedUse,NRest).
480 rename_used2_l(X,Y,Z) :- add_internal_error('Rename failed: ', rename_used2_l(X,Y,Z)),Z=X.
481
482 rename_used_ids(InIds,IncludedUse,OutIds) :-
483 maplist(rename_used_ids2(IncludedUse),InIds,OutIds).
484 rename_used_ids2(IncludedUse,InId,OutId) :-
485 memberchk(includeduse(_,InId,TOutId),IncludedUse),!,
486 get_texpr_id(TOutId,OutId).
487 rename_used_ids2(_IncludedUse,Id,Id).
488
489 get_abstractions(CName,Machines,TypedMachines,[ref(abstraction,Abstraction)]) :-
490 ? refines(M,AName),
491 get_constructed_machine_name(M,CName),
492 memberchk(M,Machines),!,
493 memberchk(machine(AName,Abstraction),TypedMachines).
494 get_abstractions(_,_,_,[]).
495
496 get_includes_and_promotes(Sections,M,Includes,Promotes) :-
497 optional_rawmachine_section(includes,Sections,[],Includes1),
498 optional_rawmachine_section(imports,Sections,[],Imports),
499 optional_rawmachine_section(extends,Sections,[],Extends),
500 optional_rawmachine_section(promotes,Sections,[],Promotes1),
501 append([Includes1,Extends,Imports],Includes),
502 maplist(expand_extends(M),Extends,Promotes2),
503 append([Promotes1|Promotes2],Promotes).
504 expand_extends(Machines,machine_reference(_,Ref,_),Promotes) :-
505 split_prefix(Ref,Prefix,Name),
506 memberchk(machine(Name,Body),Machines),
507 get_section(promoted,Body,Promoted),
508 prefix_identifiers(Promoted,Prefix,Renamings),
509 rename_bt_l(Promoted,Renamings,TPromotes),
510 maplist(add_nonpos,TPromotes,Promotes).
511 add_nonpos(TId,identifier(none,Id)) :-
512 get_texpr_id(TId,op(Id)).
513
514 move_operations([],Promotes,[],Ein,Eout) :-
515 foldl(add_promotes_not_found_error,Promotes,Ein,Eout).
516 move_operations([ref(_,IncMachine)|IncRest],Promotes,[ref(included,NewIncMachine)|RefRest],Ein,Eout) :-
517 move_operations2(IncMachine,Promotes,NewIncMachine,RestPromotes),
518 move_operations(IncRest,RestPromotes,RefRest,Ein,Eout).
519 move_operations2(Included,Promotes,Result,RestPromotes) :-
520 select_section(promoted,IncOperations,Promoted,Included,Included1),
521 select_section(unpromoted,OldUnpromoted,Unpromoted,Included1,Result),
522 filter_promoted(IncOperations,Promotes,Promoted,NewUnpromoted,RestPromotes),
523 append(OldUnpromoted,NewUnpromoted,Unpromoted).
524 filter_promoted([],Promotes,[],[],Promotes).
525 filter_promoted([TExpr|OpsRest],Promotes,Promoted,Unpromoted,RestPromotes) :-
526 get_texpr_id(TExpr,op(P)),
527 ? ( select(identifier(_,P),Promotes,RestPromotes1) ->
528 !,Promoted = [TExpr|RestPromoted],
529 Unpromoted = RestUnpromoted
530 ;
531 RestPromotes1 = Promotes,
532 Promoted = RestPromoted,
533 Unpromoted = [TExpr|RestUnpromoted]),
534 filter_promoted(OpsRest,RestPromotes1,RestPromoted,RestUnpromoted,RestPromotes).
535 add_promotes_not_found_error(identifier(Pos,Id),[error(Msg,Pos)|E],E) :-
536 ajoin(['Promoted operation ',Id,' not found'],Msg).
537
538 find_machine(Name,Machines,Type,Header,Sections) :-
539 Header = machine_header(_,Name,_),
540 ? ( (member(abstract_machine(_,_ModelType,Header,Sections),Machines),
541 Type=machine)
542 ; (member(refinement_machine(_,Header,_Abstract,Sections),Machines),
543 Type=refinement)
544 ; (member(implementation_machine(_,Header,_Abstract,Sections),Machines),
545 Type=implementation)),
546 !.
547
548 include_machines(RawMachine, TypeChecked, GlobalUses, Includes, Parameters, Included, Promotes) :-
549 get_includes_and_promotes(RawMachine,TypeChecked,Includes,Promotes),
550 maplist(include_machine(TypeChecked, GlobalUses), Includes, Parameters, Singles),
551 remove_duplicate_set_inclusions(Singles,Singles1),
552 % duplicate constants inclusion is handled currently in concat_section_contents via section_can_have_duplicates
553 % create refs
554 maplist(create_ref,Singles1,Included).
555 create_ref(IncMachine,ref(included,IncMachine)).
556
557 % it is possible that a deferred or enumerated set is declared in an included machine
558 % that is included more than once. We remove all but one occurrences.
559 remove_duplicate_set_inclusions([],[]).
560 remove_duplicate_set_inclusions([M],[M]) :- !.
561 remove_duplicate_set_inclusions([M|Rest],[M|CleanedRest]) :-
562 get_section(deferred_sets,M,DSets),
563 get_section(enumerated_sets,M,ESets),
564 get_section(enumerated_elements,M,EElements),
565 append([DSets,ESets,EElements],Identifiers),
566 sort(Identifiers,SortedIds),
567 maplist(remove_duplicate_sets2(SortedIds),Rest,Rest2),
568 remove_duplicate_set_inclusions(Rest2,CleanedRest).
569 remove_duplicate_sets2(Identifiers,M,Cleaned) :-
570 remove_duplicate_sets_section(deferred_sets,Identifiers,M,M1),
571 remove_duplicate_sets_section(enumerated_sets,Identifiers,M1,M2),
572 remove_duplicate_sets_section(enumerated_elements,Identifiers,M2,Cleaned).
573 remove_duplicate_sets_section(Section,Identifiers,In,Out) :-
574 select_section(Section,Old,New,In,Out),
575 %get_texpr_ids(Identifiers,II),format('Removing duplicates ~w = ~w~n',[Section,II]),
576 exclude(element_is_duplicate(Identifiers),Old,New).
577
578 element_is_duplicate(Identifiers,TId) :-
579 get_texpr_id(TId,Name),
580 get_texpr_type(TId,Type),
581 get_texpr_id(ToRemove,Name),
582 get_texpr_type(ToRemove,Type),
583 ord_member_nonvar_chk(ToRemove,Identifiers),
584 get_texpr_info(TId,InfosA),
585 get_texpr_info(ToRemove,InfosB),
586 member(def(Sec,File),InfosA),
587 member(def(Sec,File),InfosB),
588 debug_format(5,'Removed duplicate included identifier: ~w~n',[Name]),
589 !.
590
591 include_machine(TypeChecked,GlobalUses,machine_reference(_Pos,FullRef,_Args),
592 parameters(FullRef,Parameters), TM) :-
593 split_prefix(FullRef,Prefix,Name),
594 % TM1 is the already typechecked included machine:
595 ? member(machine(Name,TM1),TypeChecked),!,
596 debug_println(9,including_machine(Name)),
597 % TM2 is a fresh copy, so we prevent unification of the parameter types:
598 (get_section(parameters,TM1,[]) -> TM2=TM1
599 ; copy_term(TM1,TM2) % this can be expensive; only copy if there are parameters
600 ),
601 % If the included machine is used somewhere, we store the identifiers
602 % to enable joining the different references later:
603 include_usings(Name,GlobalUses,TM2,TM3),
604 % TM3 is typechecked and all internal variables are renamed with a prefix
605 hide_private_information(Name,FullRef,TM3,TM4),
606 % TM4 is typechecked, and if it was referenced with a prefix (e.g. INCLUDES p.M2)
607 % all variables are prefixed
608 %print(prefixing(Prefix)),nl,
609 prefix_machine(Prefix,TM4,TM5),
610 % We need the parameters later to state their equivalence to the arguments
611 get_section(parameters,TM5,Parameters),
612 % We move the parameters to the internal parameters, because the resulting
613 % machine has only the parameters of the including machine.
614 parameters_to_internal(TM5,TM).
615
616 include_usings(Name,GlobalUses,Old,New) :-
617 ? ( member(usemch(Name,Prefix,_Kind,_FromMch,_Pos),GlobalUses) ->
618 add_machine_prefix(Name,Prefix,FullName),
619 store_usage_info(Old,FullName,UsedInfo),
620 append_to_section(used,UsedInfo,Old,New)
621 ;
622 Old = New).
623 % returns a list of which identifiers are used in the machine
624 % for each identifier, we have a trible includeuse(Name,Id,TExpr)
625 % where Name is the name of the used machine, Id is the
626 % original ID and TExpr is the currently used reference to this
627 % identifier
628 store_usage_info(Machine,Name,UsedInfo) :-
629 expand_shortcuts([identifiers],IdSections),
630 foldl(store_usage_info2(Machine,Name),IdSections,UsedInfo,[]).
631 store_usage_info2(Machine,Name,Sec,I,O) :-
632 get_section(Sec,Machine,Content),
633 foldl(store_usage_info3(Name),Content,I,O).
634 store_usage_info3(Name,TId,[includeduse(Name,Id,TId)|L],L) :-
635 get_texpr_id(TId,Id).
636
637 % conjunct sections that contain predicates (CONSTRAINTS, PROPERTIES, INVARIANT)
638 conjunct_sections_of_refs(Sections1,References,Old,New) :-
639 expand_shortcuts(Sections1,Sections),
640 maplist(extract_machine_from_ref,References,Machines),
641 sort_machines_by_global_order(Machines,OMachines),
642 foldl(conjunct_sections2(OMachines),Sections,Old,New).
643 conjunct_sections2(Machines,Section,Old,New) :-
644 % Section is constraints,properties,invariant, ...
645 write_section(Section,NewContent,Old,New), % prepare new section
646 get_section_of_machines(Machines,Section,Preds),
647 %maplist(get_machine_name,Machines,Ns),print(got_sections(Section,Ns)),nl,
648 %translate:l_print_bexpr_or_subst(Preds),nl,
649 conjunct_predicates(Preds,NewContent).
650
651
652 % merge sections that contain a list of expressions/formulas like identifiers, assertions, ...
653 concat_sections_of_refs(Sections1,References,Old,New) :-
654 maplist(extract_machine_from_ref,References,Machines),
655 maplist(create_tag_by_reference,References,Tags),
656 sort_machines_by_global_order(Machines,Tags,OMachines,STags),
657 % should we only sort for some sections, e.g., assertions
658 % for each machine, create a tag where the expression comes from
659 concat_sections(Sections1,OMachines,STags,Old,New).
660
661 extract_machine_from_ref(ref(_,M),M).
662
663 create_tag_by_reference(ref(local,_Machine),[]) :- !.
664 create_tag_by_reference(ref(RefType,Machine),[RefType/Name]) :-
665 get_machine_name(Machine,Name).
666
667 concat_sections(Sections1,Machines,Tags,Old,New) :-
668 expand_shortcuts(Sections1,Sections),
669 foldl(concat_section2(Machines,Tags),Sections,Old,New).
670 concat_section2(Machines,Tags,Section,Old,New) :-
671 write_section(Section,NewContent,Old,New),
672 maplist(get_tagged_lsection_of_machine(Section),Machines,Tags,Contents),
673 concat_section_contents(Section,Contents,NewContent).
674
675 concat_section_contents(_,[SingleContent],Res) :- !, Res=SingleContent. % no need to remove_dups
676 concat_section_contents(Section,Contents,NewContent) :-
677 append(Contents,ConcContents),
678 (section_can_have_duplicates(Section)
679 -> remove_dup_tids_keep_order(ConcContents,NewContent)
680 ; NewContent=ConcContents).
681
682 % remove_dups version which keeps order of original elements
683 % and works with typed identifiers
684 % used if a machine is seen multiple times with different prefixes for e.g. constants
685 % see Section 7.26 of Atelier-B handbook:
686 % nom des éléments énumérés et des constantes de MSees, sans le préfixe de
687 % renommage, si plusieurs instances de machines sont vues, les noms des
688 % données ne doivent pas être répétés,
689 remove_dup_tids_keep_order([],[]).
690 remove_dup_tids_keep_order([H|T],[H|Res]) :- empty_avl(E),
691 get_texpr_id(H,ID),avl_store(ID,E,true,A1),
692 rem_dups3(T,A1,Res).
693
694 rem_dups3([],_,[]).
695 rem_dups3([H|T],AVL,Res) :-
696 get_texpr_id(H,ID),
697 (avl_fetch(ID,AVL) -> rem_dups3(T,AVL,Res)
698 ; Res=[H|TRes],
699 avl_store(ID,AVL,true,AVL1),
700 rem_dups3(T,AVL1,TRes)).
701
702 % see issue PROB-403
703 section_can_have_duplicates(X) :- section_can_be_included_multiple_times_nonprefixed(X).
704 % should we also remove duplicates in PROPERTIES section ? cf. machines used in test 1857
705
706
707 get_tagged_lsection_of_machine(Section,Machine,Tags,TaggedContent) :-
708 get_section(Section,Machine,Content),
709 (Tags=[] -> TaggedContent=Content ; maplist(tag_with_origin(Tags),Content,TaggedContent)).
710
711 tag_with_origin(Origins,TExpr,TaggedExpr) :-
712 change_info_of_expression_or_init(TExpr,Info,TaggedInfo,TaggedExpr),
713 % add a new origin to the old tag or if not existent, add a new info field
714 ( Origins = [] -> TaggedInfo = Info
715 ; selectchk(origin(Orest),Info,origin(Onew),TaggedInfo) -> append(Origins,Orest,Onew)
716 ; TaggedInfo = [origin(Origins)|Info]).
717 % the substitutions in the initialisation are additionally wrapped by an init/2 term
718 % a small hack to work with those too.
719 % TODO: this became a very ugly hack -- redo!
720 change_info_of_expression_or_init(init(A,OExpr),Old,New,init(A,NExpr)) :-
721 !,change_info_of_expression_or_init(OExpr,Old,New,NExpr).
722 % ignore the info for includeduse/3 completely
723 change_info_of_expression_or_init(includeduse(A,B,C),[],_,includeduse(A,B,C)) :- !.
724 change_info_of_expression_or_init(freetype(FTypeId,Cases),[],_,freetype(FTypeId,Cases)) :- !.
725 change_info_of_expression_or_init(OExpr,Old,New,NExpr) :-
726 create_texpr(Expr,Type,Old,OExpr),!,
727 create_texpr(Expr,Type,New,NExpr).
728 change_info_of_expression_or_init(OExpr,Old,New,NExpr) :-
729 add_internal_error('Illegal typed expression:',change_info_of_expression_or_init(OExpr,Old,New,NExpr)),
730 Old=[], NExpr=OExpr.
731
732 % adds a prefix to all variables and promoted operations
733 prefix_machine('',TM,TM) :- !.
734 prefix_machine(Prefix,Old,New) :-
735 debug_println(5,prefixing_machine(Prefix)),
736 expand_shortcuts([variables,promoted], RenamedIdentiferSections),
737 get_all_identifiers(RenamedIdentiferSections,Old,Identifiers),
738 prefix_identifiers(Identifiers,Prefix,Renamings),
739 find_relevant_sections(RenamedIdentiferSections,[machine],Sections1),
740 append(RenamedIdentiferSections,Sections1,Sections),
741 rename_in_sections(Sections,Renamings,Old,M),
742 rename_includeduse(M,Renamings,New).
743 rename_includeduse(Old,Renamings,New) :-
744 select_section(used,OldContent,NewContent,Old,New),
745 maplist(rename_includeduse2(Renamings),OldContent,NewContent).
746 rename_includeduse2(Renamings,includeduse(M,N,TExpr),includeduse(M,N,NExpr)) :-
747 rename_bt(TExpr,Renamings,NExpr).
748
749 get_all_identifiers(Sections1,M,Identifiers) :-
750 expand_shortcuts(Sections1,Sections),
751 maplist(get_all_identifiers2(M),Sections,LIdentifiers),
752 append(LIdentifiers,Identifiers).
753 get_all_identifiers2(M,Sec,Identifiers) :-
754 get_section(Sec,M,Identifiers).
755
756 % hide all parameters and unpromoted operations
757 hide_private_information(MachName,Prefix,Machine,NewMachine) :-
758 get_section(parameters,Machine,Params),
759 get_section(unpromoted,Machine,UnPromoted),
760 append(Params,UnPromoted,ToHide),
761 %debug_println(9,hide_private(Prefix,ToHide)),
762 ( ToHide = [] -> NewMachine=Machine
763 ;
764 debug_format(9,'Hiding private parameters ~w and unpromoted operations ~w of machine ~w~n',
765 [Params,UnPromoted,MachName]),
766 maplist(store_hides_operation_info(MachName,Prefix),UnPromoted),
767 prefix_identifiers(ToHide,Prefix,Renamings),
768 % we have to do the renaming in promoted operations, too, because
769 % those operations might use the renamed parameters and their reads/modifies
770 % info must be updated
771 rename_in_sections([parameters,promoted,unpromoted],Renamings,Machine,Machine1),
772 rename_includeduse(Machine1,Renamings,Machine2),
773 % now find sections that can see parameters,operations:
774 rename_relevant_sections([parameters,operations],Renamings,Machine2,NewMachine)
775 ).
776
777 % store information about which operations got renamed:
778 store_hides_operation_info(MachName,Prefix,TExpr) :- Prefix \= '',
779 prefix_identifier(Prefix,TExpr,rename(op(Old),op(New))),
780 get_texpr_pos(TExpr,Pos),
781 !,
782 debug_format(19,'Hiding unpromoted operation ~w in machine ~w, new name: ~w~n',[Old,MachName,New]),
783 assertz(machine_hides_unpromoted_operation(Old,MachName,New,Pos)).
784 store_hides_operation_info(_,_,_).
785
786 prefix_identifiers(Identifiers,'',Identifiers) :- !.
787 prefix_identifiers(Old,Prefix,New) :-
788 maplist(prefix_identifier(Prefix),Old,New).
789 prefix_identifier(Prefix,TExpr,rename(Old,New)) :-
790 get_texpr_expr(TExpr,identifier(Old)),
791 (Old=op(OI) -> New=op(NI) ; OI=Old,NI=New),
792 ajoin([Prefix,'.',OI],NI). % , print(rename(Old,New)),nl.
793
794 parameters_to_internal(M1,M2) :-
795 select_section(internal_parameters,OldParams,Params,M1,M3),
796 select_section(parameters,NewParams,[],M3,M2),
797 append(OldParams,NewParams,Params).
798
799 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
800 % uses and sees relations
801 find_uses(Machines,GlobalUses,NotIncludedWoDups,Ein,Eout) :-
802 findall(usemch(UsedMch,UPrefix,Kind,FromMchName,Pos),
803 use_usage(Machines,Pos,Kind,UsedMch,UPrefix,FromMchName), UnsortedUses),
804 sort(UnsortedUses,Uses),
805 check_include_use(Uses,Machines,NotIncluded,Ein,Eout),
806 remove_duplicate_uses(NotIncluded,NotIncludedWoDups),
807 GlobalUses = Uses. %maplist(remove_prefix,Uses,GlobalUses).
808
809 remove_prefix(usemch(U,_,_,_,_),U).
810 same_usemch(usemch(U,P,_,_,_),usemch(U,P,_,_,_)). % use same machine with same prefix
811
812 % remove duplicate uses: a non-included/imported machine can be seen in many places;
813 % we only need to add it later once the dummy machine
814 remove_duplicate_uses([],R) :- !, R=[].
815 remove_duplicate_uses([USE|T],Res) :-
816 remove_dup_aux(T,USE,Res).
817 remove_dup_aux([],USE,[USE]).
818 remove_dup_aux([USE|T],PREVUSE,Res) :-
819 (same_usemch(USE,PREVUSE) -> remove_dup_aux(T,PREVUSE,Res)
820 ; Res = [PREVUSE|TR], remove_dup_aux(T,USE,TR)).
821
822
823 % check_include_use/5 checks if the used machines are included in any machine
824 % check_include_use(+Uses,+Machines,-NotIncluded,Ein,Eout)
825 % Uses: The list of machine names that are used
826 % Machines: The list of machines
827 % NotIncluded: The list of used machines (their names) that are not included
828 % Ein/Eout: The errors (as difference-list)
829 check_include_use([],_,[],Errors,Errors).
830 check_include_use([USEMCH|Rest],Machines,NotIncluded,Ein,Eout) :-
831 USEMCH = usemch(UsedMach,UsePrefix,Kind,FromMchName,Pos),
832 findall(i(MachName,UsePrefix,IPos),include_usage(Machines,UsedMach,UsePrefix,MachName,IPos),Inc),
833 ( Inc=[] -> NotIncluded = [USEMCH|RestNotIncluded], Ein=E1,
834 (debug_mode(off) -> true
835 ; add_machine_prefix(UsedMach,UsePrefix,FullName),
836 ajoin(['machine ',Kind, ' in ', FromMchName,
837 ' not included/imported anywhere else (will create dummy top-level machine to include it): '],Msg),
838 add_message(bmachine_construction,Msg,FullName,Pos)
839 )
840 ; Inc=[_] -> NotIncluded = RestNotIncluded, Ein=E1
841 ; Inc=[i(_M1,_,Pos1),i(_M2,_,Pos2)|_],
842 NotIncluded = RestNotIncluded,
843 translate_span(Pos1,PS1),
844 translate_span(Pos2,PS2),
845 (UsePrefix = ''
846 -> ajoin([Kind,' machine ',UsedMach,' is included more than once: ',PS1,' and ',PS2],Msg)
847 ; ajoin([Kind,' machine ',UsedMach,' is included more than once with prefix ',UsePrefix,
848 ': ',PS1,' and ',PS2],Msg)
849 ),
850 Ein = [error(Msg,Pos)|E1]
851 ),
852 check_include_use(Rest,Machines,RestNotIncluded,E1,Eout).
853 % extend_not_included_uses(+Uses,+Main,-Name,+Machines,-AllMachines):
854 % Create a dummy machine that extends the main machine and extends or includes
855 % all seen/used machines that are not included if such machines exist.
856 % In case of refinement this is done for the whole refinement chain.
857 % Uses: List of machine names and prefix usemch/2 of the machines that are used/seen but not included
858 % Main: The name of the main machine
859 % Name: The name of the generated dummy machine (or Main if no dummy machine is generated)
860 % Machines: List of all specified Machines
861 % AllMachines: List of all Machines + the new dummy machine(s)
862 extend_not_included_uses([],Main,Main,Machines,Machines) :- !.
863 extend_not_included_uses(Uses,Main,NewMainName,Machines,AllMachines) :-
864 get_refinement_hierarchy(Main,Machines,RefChain),
865 maplist(extend_not_included_uses2(Uses,Machines),RefChain,NewMachines),
866 append(NewMachines,Machines,AllMachines),
867 dummy_machine_name(Main,NewMainName),
868 debug_format(19,'Creating dummy machine called ~w for main machine~n',[NewMainName]).
869 extend_not_included_uses2(Uses,Machines,Name,DummyMachine) :-
870 debug_format(19,'Creating dummy subsidiary machine for refined machine ~w~n',[Name]),
871 create_dummy_machine(Name,Machines,Parameters,DummyParameters,Sections,DummyMachine),
872 IncludeMain = machine_reference(none,Name,Parameters),
873 ( get_preference(seen_machines_included,true) ->
874 % extend just the main machine, include the used/seen machines
875 References = [extends(none,[IncludeMain]),includes(none,UReferences)]
876 ;
877 % extends the main machine and all used/seen machines
878 References = [extends(none,[IncludeMain|UReferences])]),
879 maplist(find_using(Machines),Uses,UReferences,LUParameters),
880 append([Parameters|LUParameters],DummyParameters),
881 copy_raw_definitions(Name,Machines,OptDefs),
882 % we store a flag "is_dummy" in the machine because we have a special case
883 % later, see type_constraints/7.
884 append([References,[is_dummy],OptDefs],Sections).
885 create_dummy_machine(Name,Machines,Parameters,DummyParameters,Sections,DummyMachine) :-
886 dummy_machine_name(Name,DummyName),
887 ? get_raw_model_type(Name,Machines,ModelType),
888 !,
889 Header = machine_header(_,Name,Parameters),
890 DummyHeader = machine_header(none,DummyName,DummyParameters),
891 ? member(Machine,Machines),
892 ? generate_raw_machine(Header,DummyHeader,ModelType,Sections,Machine,DummyMachine),!.
893
894 generate_raw_machine(OldHeader,NewHeader,_,NewSections,
895 abstract_machine(_, ModelType,OldHeader,_),
896 abstract_machine(none,ModelType,NewHeader,NewSections)).
897 generate_raw_machine(OldHeader,NewHeader,ModelType,NewSections,
898 refinement_machine(_, OldHeader,_Abstract, _),
899 abstract_machine(none,ModelType,NewHeader,NewSections)).
900 generate_raw_machine(OldHeader,NewHeader,ModelType,NewSections,
901 implementation_machine(_, OldHeader,_Abstract, _),
902 abstract_machine(none,ModelType,NewHeader,NewSections)).
903
904 dummy_machine_name(Name,DummyName) :-
905 atom_concat('MAIN_MACHINE_FOR_',Name,DummyName).
906
907 add_machine_prefix(UsedMch,'',Name) :- !, UsedMch=Name.
908 add_machine_prefix(UsedMch,UsePrefix,Name) :- ajoin([UsePrefix,'.',UsedMch],Name).
909
910 find_using(Machines,usemch(UsedMch,UsePrefix,_,_,_),machine_reference(none,Name,Arguments),Arguments) :-
911 % was using(U).U TODO: pass and use UsePrefix
912 ajoin([UsedMch,'.',UsedMch],Name0),
913 add_machine_prefix(Name0,UsePrefix,Name),
914 ? member(M,Machines), get_machine_parameters(M,UsedMch,Params,_),!,
915 maplist(add_use_param,Params,Arguments).
916 add_use_param(identifier(_,Param),identifier(none,Name)) :-
917 ( is_upper_case(Param) ->
918 ajoin(['Useparam(',Param,')'],Name)
919 ;
920 ajoin(['useparam(',Param,')'],Name)).
921
922 % copy_raw_definitions(+Name,+Machines,-OptDefs):
923 % Get the definitions section from a raw (untyped) machine
924 % Name: Name of the machine
925 % Machines: List of Machines
926 % OptDefs: [] if no definitions are present or [Def] if a definition section Def is present
927 copy_raw_definitions(Name,Machines,OptDefs) :-
928 ? get_constructed_machine_name_and_body(M,Name,_,Sections),
929 memberchk(M,Machines),!,
930 Def = definitions(_,_),
931 ( memberchk(Def,Sections) ->
932 OptDefs = [Def]
933 ;
934 OptDefs = []).
935
936 add_def_dependency_information(DefsIn,DefsOut,Ein,Eout) :-
937 extract_def_name_set(DefsIn,DefNames,DN),
938 maplist(add_def_dep(DN),DefsIn,Defs1),
939 check_for_cyclic_def_dependency(Defs1,DefNames,DefsOut,Ein,Eout).
940
941 extract_def_name_set(Defs,DefNames,DN) :-
942 maplist(get_def_name,Defs,DefNames),
943 maplist(to_mapset_entry,DefNames,DN1),
944 list_to_avl(DN1,DN).
945
946 get_def_name(Def,Name) :- arg(1,Def,Name).
947 get_def_pos(Def,Pos) :- arg(3,Def,Pos).
948 get_def_dependencies(Def,Dependencies) :- arg(6,Def,Dependencies).
949 to_mapset_entry(Name,Name-true).
950
951 add_def_dep(DN,In,Out) :-
952 analyse_definition_dependencies(In,DN,Deps),
953 In = definition_decl(Name,DefType,Pos,Args,RawExpr),
954 Out = definition_decl(Name,DefType,Pos,Args,RawExpr,Deps).
955
956 check_for_cyclic_def_dependency(Defs,DefNames,DefsOut,Ein,Eout) :-
957 % check if we have a cyclic definition:
958 create_definitions_avl(Defs,DefsAvl),
959 search_for_cyclic_definition(DefNames,DefsAvl,[],Pos,RCycle),!,
960 % if we have found a cyclic definition, generate an error message, ...
961 reverse(RCycle,Cycle),add_arrows(Cycle,Msg0),
962 ajoin(['Found cyclic definitions: '|Msg0],Msg),
963 Ein = [error(Msg,Pos)|E1],
964 % ... remove the definitions in the cycle (to prevent later infinite loops) ...
965 exclude(definition_in_list(Cycle),Defs,Defs1),
966 % ... and check the remaining definitions.
967 check_for_cyclic_def_dependency(Defs1,DefNames,DefsOut,E1,Eout).
968 check_for_cyclic_def_dependency(Defs,_DefNames,Defs,E,E).
969 add_arrows([E],[E]) :- !.
970 add_arrows([E|Erest],[E,'->'|Arest]) :- add_arrows(Erest,Arest).
971 definition_in_list(List,Def) :-
972 get_def_name(Def,Name),memberchk(Name,List).
973
974 create_definitions_avl(Defs,DefsAvl) :-
975 maplist(split_def_name,Defs,Entries),
976 list_to_avl(Entries,DefsAvl).
977 split_def_name(Def,Name-Def) :- get_def_name(Def,Name).
978
979
980 % just a depth-first search to find a cycle
981 search_for_cyclic_definition(DefNames,Definitions,Visited,Pos,Cycle) :-
982 ? member(Name,DefNames),avl_fetch(Name,Definitions,Definition),
983 get_def_pos(Definition,Pos),
984 ( memberchk(Name,Visited) ->
985 Cycle = [Name|Visited]
986 ;
987 get_def_dependencies(Definition,Dependencies),
988 search_for_cyclic_definition(Dependencies,Definitions,[Name|Visited],_,Cycle)
989 ).
990
991 :- assert_must_succeed((
992 list_to_avl([def1-true,def2-true,def3-true,def4-true],DefNames),
993 analyse_definition_dependencies(
994 conjunct(none,
995 equals(none,
996 identifier(none,x),
997 identifier(none,def1)),
998 equals(none,
999 definition(none,def4,
1000 [function(none,
1001 identifier(none,def3),
1002 integer(none,5))]),
1003 identifier(y))),DefNames,Defs),
1004 Defs==[def1,def3,def4]
1005 )).
1006 % analyse_definition_dependencies(+Expr,+DefinitionNames,Deps):
1007 % Expr: raw (i.e. untyped) expression to analyse
1008 % DN: AVL set (i.e. mapping from elements to 'true') of the names of the definitions
1009 % This is needed to decide if an identifier is a reference to a definition
1010 % Deps: A list of used definitions (a list of their names)
1011 analyse_definition_dependencies(Expr,DN,Deps) :-
1012 analyse_definition_dependencies2(Expr,DN,Unsorted,[]),
1013 sort(Unsorted,Deps).
1014 analyse_definition_dependencies2(VAR,_DN) --> {var(VAR)},!,
1015 {add_internal_error('Variable DEFINITION expression in',analyse_definition_dependencies)}.
1016 analyse_definition_dependencies2([Expr|Rest],DN) -->
1017 !, analyse_definition_dependencies2(Expr,DN),
1018 analyse_definition_dependencies2(Rest,DN).
1019 analyse_definition_dependencies2(definition(_Pos,Name,Args),DN) -->
1020 !,[Name],analyse_definition_dependencies2(Args,DN).
1021 analyse_definition_dependencies2(identifier(_Pos,Name),DN) -->
1022 {avl_fetch(Name,DN),!},[Name].
1023 analyse_definition_dependencies2(Expr,DN) -->
1024 { compound(Expr),functor(Expr,_Functor,Arity),!},
1025 analyse_definition_dependencies_arg(2,Arity,Expr,DN).
1026 analyse_definition_dependencies2(_Expr,_DN) --> [].
1027
1028 analyse_definition_dependencies_arg(I,Arity,Expr,DN) -->
1029 { I =< Arity,!,arg(I,Expr,Arg),I2 is I+1 },
1030 analyse_definition_dependencies2(Arg,DN),
1031 analyse_definition_dependencies_arg(I2,Arity,Expr,DN).
1032 analyse_definition_dependencies_arg(_I,_Arity,_Expr,_DN) --> [].
1033
1034
1035 :- use_module(tools_positions, [get_position_filenumber/2]).
1036
1037 get_constructed_machine_name(MachineTerm,Name) :- get_constructed_machine_name_and_body(MachineTerm,Name,_Pos,_).
1038 % name and pos; pos can be used for filenumber
1039 get_constructed_machine_name_and_filenumber(MachineTerm,Name,Filenumber) :-
1040 get_constructed_machine_name_and_body(MachineTerm,Name,Pos,_),
1041 (get_position_filenumber(Pos,FN) -> Filenumber=FN ; Filenumber=unknown).
1042 get_constructed_machine_name_and_body(abstract_machine(_,_ModelType,machine_header(Pos,Name,_),Body),Name,Pos,Body).
1043 get_constructed_machine_name_and_body(refinement_machine(_,machine_header(Pos,Name,_),_Abstract,Body),Name,Pos,Body).
1044 get_constructed_machine_name_and_body(implementation_machine(_,machine_header(Pos,Name,_),_Abstract,Body),Name,Pos,Body).
1045
1046 refines(refinement_machine(_,machine_header(_,_Name,_),Abstract,_Body),Abstract).
1047 refines(implementation_machine(_,machine_header(_,_Name,_),Abstract,_Body),Abstract).
1048
1049 get_machine_parameters(abstract_machine(Pos,_ModelType,machine_header(_,Name,Parameters),_),Name,Parameters,Pos).
1050 get_machine_parameters(refinement_machine(Pos,machine_header(_,Name,Parameters),_,_),Name,Parameters,Pos).
1051 get_machine_parameters(implementation_machine(Pos,machine_header(_,Name,Parameters),_,_),Name,Parameters,Pos).
1052
1053 get_raw_model_type(Main,Machines,ModelType) :-
1054 ? get_constructed_machine_name_and_body(M,Main,_,_),
1055 memberchk(M,Machines),
1056 ( refines(M,RefName) ->
1057 ? get_raw_model_type(RefName,Machines,ModelType)
1058 ;
1059 M = abstract_machine(_,ModelType,_,_)).
1060
1061 some_machine_name_body(Machines,M,Name,Body) :-
1062 ? member(M,Machines),
1063 get_constructed_machine_name_and_body(M,Name,_,Body).
1064
1065 use_usage(Machines,Pos,Kind,UsedMch,UsePrefix,FromMchName) :-
1066 ? some_machine_name_body(Machines,_,FromMchName,Body),
1067 ? ( member(sees(Pos,R),Body),Kind=seen
1068 ; member(uses(Pos,R),Body),Kind=used),
1069 ? member(identifier(_,PrefixUse),R),
1070 split_prefix(PrefixUse,UsePrefix,UsedMch).
1071 % include_usage/4 checks if there is any machine in Machines that
1072 % includes/extends/imports the used machine
1073 % include_usage(+Machines,+Use,-Name):
1074 % Machines: The list of machines
1075 % UsedMch: The name of the used machine
1076 % UsePrefix: the prefix with which the machine is used
1077 % Name: The name of the machine that imports the used machine
1078 % include_usage/4 fails if there is not such an import
1079 include_usage(Machines,UsedMch,UsePrefix,MachName,Pos) :-
1080 ? some_machine_name_body(Machines,_,MachName,Body),
1081 ? ( member(includes(_,R),Body)
1082 ; member(extends(_,R), Body)
1083 ; member(imports(_,R), Body)),
1084 ? member(machine_reference(Pos,PrefixRef,_),R),
1085 % The name could be prefixed, we need it without prefix:
1086 split_prefix(PrefixRef,UsePrefix,UsedMch).
1087
1088 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1089 % uses and sees clauses
1090
1091 % returns a list of references to used and seen machines
1092 % the machines contain only identifier sections and
1093 % the identifier are prefixed accordingly
1094 % all identifier are marked as coming from a seen/used machine
1095 use_and_see_machines(Sections,Machines,References) :-
1096 get_uses_and_sees(Sections,Uses,Sees),
1097 maplist(use_or_see_machine(used,Machines),Uses,Used),
1098 ? maplist(use_or_see_machine(seen,Machines),Sees,Seen),
1099 append(Used,Seen,References).
1100
1101 % get uses and sees sections from the untyped machines
1102 get_uses_and_sees(Sections,Uses,Sees) :-
1103 get_uses_or_sees2(sees,Sections,Sees),
1104 get_uses_or_sees2(uses,Sections,Uses).
1105 get_uses_or_sees2(Mode,Sections,US) :-
1106 optional_rawmachine_section(Mode,Sections,[],US1),
1107 findall(I,member(identifier(_,I),US1),US).
1108
1109 use_or_see_machine(Mode,TypedMachines,Ref,ref(Mode,Result)) :-
1110 split_prefix(Ref,Prefix,Name),
1111 memberchk(machine(Name,Typed),TypedMachines),
1112 create_machine(Name,Empty),
1113 ? use_sections([sets],Mode,'',Name,Typed,Empty,M1),
1114 ? use_sections([constants,variables,promoted],Mode,Prefix,Name,Typed,M1,Result).
1115 use_sections(Sections,Mode,Prefix,MName,Typed,Old,New) :-
1116 expand_shortcuts(Sections,AllSections),
1117 ? foldl(use_section(Mode,Prefix,MName,Typed),AllSections,Old,New).
1118 use_section(Mode,Prefix,MName,Machine,Section,OldM,NewM) :-
1119 ? get_section_texprs(Section,Machine,Identifiers),
1120 write_section(Section,NewIds,OldM,NewM),
1121 ( Prefix='' ->
1122 Ids1=Identifiers
1123 ;
1124 prefix_identifiers(Identifiers,Prefix,Renamings),
1125 rename_bt_l(Identifiers,Renamings,Ids1)),
1126 maplist(add_use_info_to_identifier(Mode,MName),Ids1,NewIds).
1127 add_use_info_to_identifier(Mode,Name,TExpr,New) :-
1128 get_texpr_id(TExpr,PId), get_texpr_type(TExpr,Type),
1129 get_texpr_id(New,PId), get_texpr_type(New,Type),
1130 split_prefix(PId,_Prefix,Id),
1131 get_texpr_info(TExpr,Info),
1132 get_texpr_info(New,[usesee(Name,Id,Mode)|Info]).
1133
1134
1135 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1136 % add a section to the machine that describes the linking of
1137 % parameters and arguments
1138 add_link_constraints(Includes,MType,Parameters,RefMachines,Old,New,Ein,Eout) :-
1139 AllRefMachines = [ref(local,Old)|RefMachines],
1140 extract_parameter_types(RefMachines,NonGroundExceptions),
1141 foldl(add_link_section(MType,Parameters,AllRefMachines,NonGroundExceptions),
1142 Includes,Links/Ein,[]/Eout), % TO DO: Daniel check if [] is correct here
1143 %print(conjunct_predicates(Links,Link)),nl,
1144 conjunct_predicates(Links,Link),
1145 select_section(constraints,OConstraints,NConstraints,Old,New),
1146 conjunct_predicates([Link,OConstraints],NConstraints).
1147 add_link_section(MType,Parameters,RefMachines,NonGroundExceptions,
1148 machine_reference(Pos,Ref,Args),Links/Ein,RLinks/Eout) :-
1149 visible_env(MType,includes,RefMachines,Env,Ein,E1),
1150 memberchk(parameters(Ref,TParameters),Parameters),
1151 ( same_length(TParameters, Args) ->
1152 get_texpr_types(TParameters,Types),
1153 btype_ground_dl(Args,Env,NonGroundExceptions,Types,TArgs,E1,Eout),
1154 maplist(create_plink_equality,TParameters,TArgs,LLinks)
1155 ;
1156 E1 = [error('wrong number of machine arguments',Pos)|Eout],
1157 LLinks = []),
1158 append(LLinks,RLinks,Links).
1159 create_plink_equality(P,A,E) :-
1160 create_texpr(equal(P,A),pred,[parameterlink],E).
1161
1162 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1163 % type machines
1164
1165 type_machine(Header,Name,MType,RawMachine,RefMachines,TypedMachine,NewRefMachines,Ein,Eout) :-
1166 Header = machine_header(_,Name,_),
1167 create_machine(Name,Empty),
1168 % (optional) definitions
1169 extract_definitions(RawMachine,Empty,DefsOnly,Ein,E0),
1170 debug_stats(extracted_definitions(Name)),
1171 % create the identifiers that will be typed,
1172 % Local will contain the identifier sections
1173 create_id_sections(Header,RawMachine,Name,DefsOnly,Local),
1174 debug_stats(created_identifier_sections(Name)),
1175 ? create_freetypes(RawMachine,MType,RefMachines,Local,Local1,E0,E1),
1176 % in case of a refinement, check if all newly defined operations are refinements
1177 link_to_refinement(MType,Name,RawMachine,RefMachines,Local1,Local2,E1,E2),
1178 % extract types that can be variables
1179 debug_stats(created_link_to_refinement(Name)),
1180 extract_parameter_types([ref(local,Local2)|RefMachines],NonGroundExceptions),
1181 % check for a VALUES clause. They are a little bit tricky because they can replace
1182 % already defined deferred sets by integers or other deferred sets
1183 process_values_section(MType,RawMachine,NonGroundExceptions,
1184 Local2/E2/RefMachines,Local3/E3/NewRefMachines),
1185 % type-check the other sections (properties, invariant, operation_bodies, etc)
1186 type_sections(RawMachine,MType,[ref(local,Local3)|NewRefMachines],NonGroundExceptions,
1187 Name,E3,Eout,Local3,TypedMachine).
1188
1189 % extract definitions from a definition file
1190 extract_only_definitions(MainName,RawMachine,DefsOnlyMachine,FinalErrors) :-
1191 create_machine(MainName,Empty),
1192 extract_definitions(RawMachine,Empty,DefsOnlyMachine,Errors,[]),
1193 sort(Errors,FinalErrors),
1194 add_all_perrors(FinalErrors).
1195
1196 extract_definitions(RawMachine,In,Out,Ein,Eout) :-
1197 optional_rawmachine_section(definitions,RawMachine,[],AllDefinitions),
1198 write_section(definitions,Definitions,In,Out),
1199 % remove all references to definition files from definitions
1200 exclude(is_file_definition,AllDefinitions,Definitions1),
1201 % replace expression_definition(...) by defintion(expression,...), etc.
1202 change_definition_style(Definitions1,Definitions2),
1203 % analyse dependencies
1204 add_def_dependency_information(Definitions2,Definitions3,Ein,Eout),
1205 % replace external function definitions by calls to the external function
1206 replace_external_declarations(Definitions3,Definitions).
1207
1208 is_file_definition(file_definition(_Pos,_Filename)).
1209
1210 change_definition_style(DefsIn,DefsOut) :-
1211 maplist(change_definition_style2,DefsIn,DefsOut).
1212 change_definition_style2(conversion(Pos,InnerDef),definition_decl(Name,DefType,InnerPos,Args,conversion(Pos,RawExpr))) :-
1213 change_definition_style2(InnerDef,definition_decl(Name,DefType,InnerPos,Args,RawExpr)).
1214 change_definition_style2(Def,definition_decl(Name,DefType,Pos,Args,RawExpr)) :-
1215 Def =.. [Functor,Pos,Name,Args,RawExpr],
1216 maplist(check_def_argument(Name,Pos),Args),
1217 map_def_functor(Functor,DefType).
1218 map_def_functor(expression_definition,expression).
1219 map_def_functor(substitution_definition,substitution).
1220 map_def_functor(predicate_definition,predicate).
1221
1222 % check formal arguments of definitions , e.g., here xx in square2 is not an identifier: xx == 20; square2(xx) == xx*xx
1223 check_def_argument(_,_,identifier(_,_)) :- !.
1224 check_def_argument(DefName,DefPos,definition(_,ID,_)) :- !,
1225 tools:ajoin(['Formal parameter ', ID, ' is a definition call in Definition: '],Msg),
1226 add_error(bmachine_construction,Msg,DefName,DefPos).
1227 check_def_argument(DefName,DefPos,FP) :- !,
1228 tools:ajoin(['Formal parameter ', FP, ' is not an identifier in Definition: '],Msg),
1229 add_error(bmachine_construction,Msg,DefName,DefPos).
1230
1231 replace_external_declarations(Definitions,NewDefs) :-
1232 split_list(is_external_declaration,Definitions,ExtFunctionDecls,RestDefs),
1233 foldl(replace_external_declaration,ExtFunctionDecls,RestDefs,NewDefs).
1234 is_external_declaration(definition_decl(DefName,expression,_Pos,_Params,_Def,_Dependencies)) :-
1235 ? external_name(DefName,ExtType,_ExpectedDefType,_ExtCall,FunName),
1236 debug_format(4,'external ~w declared: ~w~n', [ExtType,FunName]).
1237 external_name(DefName,_,_,_,_) :-
1238 \+ atom(DefName),!,
1239 add_internal_error('Non-atomic DEFINITION id:',DefName),fail.
1240 external_name(DefName,function,expression,external_function_call,FunName) :-
1241 atom_concat('EXTERNAL_FUNCTION_',FunName,DefName).
1242 external_name(DefName,predicate,predicate,external_pred_call,FunName) :-
1243 atom_concat('EXTERNAL_PREDICATE_',FunName,DefName).
1244 external_name(DefName,substitution,substitution,external_subst_call,FunName) :-
1245 atom_concat('EXTERNAL_SUBSTITUTION_',FunName,DefName).
1246
1247 replace_external_declaration(definition_decl(DefName,expression,DefPos,TypeParams,Decl,_Deps),In,Out) :-
1248 OldDefinition = definition_decl(FunName,ExpectedDefType,Pos,FunParams,FunDef,Deps),
1249 NewDefinition = definition_decl(FunName,ExpectedDefType,Pos,FunParams,ExtCall,Deps),
1250 ? ( external_name(DefName,_ExtType,ExpectedDefType,ExtCallFunctor,FunName),
1251 ExtCall =.. [ExtCallFunctor,Pos,FunName,FunParams,FunDef,
1252 rewrite_protected(TypeParams),rewrite_protected(Decl)],
1253 selectchk(OldDefinition,In,NewDefinition,Out) ->
1254 assert_external_procedure_used(FunName)
1255 ; external_name(DefName,ExpectedKind,_,_,FunName),
1256 selectchk(definition_decl(FunName,OtherDefType,_OtherPos,_,_,_),In,_,_),!,
1257 % definition found for different type of external function
1258 ajoin(['No DEFINITION associated with external ',ExpectedKind,
1259 ' (but definition as ',OtherDefType,' exists):'],Msg),
1260 add_error(replace_external_declaration,Msg,DefName,DefPos), Out=In
1261 ; external_name(DefName,ExpectedKind,_,_,FunName) ->
1262 % no definition found for external function
1263 ajoin(['No DEFINITION associated with external ',ExpectedKind,':'],Msg),
1264 add_error(replace_external_declaration,Msg,DefName,DefPos), Out=In
1265 ; % no definition found for external function
1266 ajoin(['No DEFINITION associated with:'],Msg),
1267 add_error(replace_external_declaration,Msg,DefName,DefPos), Out=In
1268 ).
1269
1270 :- use_module(external_function_declarations,
1271 [external_function_library/2, safe_external_function_library/2,
1272 get_external_function_definition/3]).
1273 % store external definitions of a given library in the type environment, e.g. for debugging in Repl or VisB
1274 % Library could be "LibraryStrings.def"
1275
1276 store_ext_defs(Library,In,Out) :-
1277 (Library = all_available_libraries
1278 -> findall(extfun(Id,Lib),external_function_library(Id,Lib),Ids)
1279 ; Library = safe_available_libraries
1280 -> findall(extfun(Id,Lib),safe_external_function_library(Id,Lib),Ids)
1281 ; findall(extfun(Id,Library),external_function_library(Id,Library),Ids)
1282 ),
1283 (Ids=[] -> add_warning(store_ext_defs,'No external functions found for library: ',Library) ; true),
1284 foldl(store_ext_def,Ids,In,Out).
1285
1286 store_ext_def(extfun(Id,Library),In,Out) :- env_lookup_type(Id,In,_),!,
1287 debug_println(4,not_storing_ext_def(Id,Library)), % already imported from stdlib or user has other definition
1288 Out=In.
1289 store_ext_def(extfun(FunName,Library),In,Out) :-
1290 ? get_external_function_definition(FunName,Library,DEFINITION),!,
1291 debug_println(4,storing_ext_def(FunName,Library)),
1292 env_store(FunName,DEFINITION,[loc('automatically included',Library,definitions)],In,Out).
1293 store_ext_def(extfun(Id,_),In,Out) :-
1294 add_internal_error('Cannot add external definition: ',Id),
1295 Out=In.
1296
1297
1298 % store which machine promotes which operations
1299 :- dynamic machine_promotes_operations/2, machine_hides_unpromoted_operation/4, machine_global_order/1.
1300
1301 reset_bmachine_construction :-
1302 retractall(machine_promotes_operations(_,_)),
1303 retractall(machine_hides_unpromoted_operation(_,_,_,_)),
1304 retractall(abstract_variable_removed_in(_,_,_)),
1305 retractall(machine_global_order(_)),
1306 reset_external_procedure_used.
1307
1308
1309 % maybe this information should be stored somewhere else ??
1310 :- dynamic external_procedure_used/1.
1311 reset_external_procedure_used :- retractall(external_procedure_used(_)).
1312 assert_external_procedure_used(FunName) :-
1313 (external_procedure_used(FunName) -> true ; assertz(external_procedure_used(FunName))).
1314
1315 link_to_refinement(machine,_,_RawMachine,_RefMachines,Local,Local,Errors,Errors).
1316 link_to_refinement(refinement,Name,RawMachine,RefMachines,Local,NewLocal,Ein,Eout) :-
1317 link_to_refinement(implementation,Name,RawMachine,RefMachines,Local,NewLocal,Ein,Eout).
1318 link_to_refinement(implementation,Name,RawMachine,RefMachines,Local,NewLocal,Ein,Eout) :-
1319 link_to_refinement2(implementation,Name,RawMachine,RefMachines,Local,NewLocal,Ein,Eout).
1320 link_to_refinement2(_MType,Name,RawMachine,RefMachines,Local,NewLocal,Ein,Eout) :-
1321 memberchk(ref(abstraction,AbstractMachine),RefMachines),
1322 copy_constraints(Local,AbstractMachine,NewLocal,Ein,E1),
1323 type_vars_in_refinement(AbstractMachine,NewLocal),
1324 type_refinement_operations(Name,RawMachine,AbstractMachine,NewLocal,E1,Eout).
1325
1326 copy_constraints(Local,AbstractMachine,NewLocal,Ein,Eout) :-
1327 get_section(parameters,Local,LocalParameters),
1328 get_section(parameters,AbstractMachine,AbstractParameters),
1329 check_if_equal_identifiers(LocalParameters,AbstractParameters,Ein,Eout,Local),
1330 get_section(constraints,AbstractMachine,Constraints),
1331 write_section(constraints,Constraints,Local,NewLocal).
1332 check_if_equal_identifiers(Local,Abstract,Ein,Eout,LocalMachine) :-
1333 ( same_length(Local,Abstract) ->
1334 foldl(check_if_equal_identifiers2,Local,Abstract,Ein,Eout)
1335 ;
1336 get_texpr_ids(Abstract,AIDs),
1337 get_machine_name(LocalMachine,MachName),
1338 ajoin(['Refinement ',MachName,' must have same Parameters ', AIDs,' as abstract Machine'],Msg),
1339 Ein = [error(Msg,none)|Eout]
1340 ).
1341 check_if_equal_identifiers2(LParam,AParam,Ein,Eout) :-
1342 get_texpr_id(LParam,LName),
1343 get_texpr_id(AParam,AName),
1344 ( LName = AName ->
1345 % type in refinement is the same as in the abstraction
1346 get_texpr_type(LParam,Type),
1347 get_texpr_type(AParam,Type),
1348 Ein=Eout
1349 ;
1350 get_texpr_pos(LParam,Pos),
1351 ajoin(['Parameter ',LName,' of refinement machine must be ',
1352 AName,' like in the abstract machine'],Msg),
1353 Ein = [error(Msg,Pos)|Eout]
1354 ).
1355
1356 % in case of a refinement, give variables the same type as in the abstract machine
1357 % the same for constants
1358 type_vars_in_refinement(AbstractMachine,ConcreteMachine) :-
1359 pass_type(AbstractMachine,[abstract_variables,concrete_variables],
1360 ConcreteMachine,[abstract_variables,concrete_variables]),
1361 pass_type(AbstractMachine,[abstract_constants,concrete_constants],
1362 ConcreteMachine,[abstract_constants,concrete_constants]).
1363
1364 % pass the type from variables in Sections1 of Machine1 to
1365 % the variables of the same name in Sections2 of Machine2
1366 % Machine1,Machine2: a machine
1367 % Sections1, Sections2: a list of section names
1368 pass_type(Machine1,Sections1,Machine2,Sections2) :-
1369 get_sections_and_append(Sections1,Machine1,Vars1),
1370 get_sections_and_append(Sections2,Machine2,Vars2),
1371 maplist(pass_type2(Vars2),Vars1).
1372 get_sections_and_append([],_M,[]).
1373 get_sections_and_append([Sec|RestSections],M,R) :-
1374 get_section(Sec,M,L), append(L,Rest,R),
1375 get_sections_and_append(RestSections,M,Rest).
1376 pass_type2(DstVariables,SrcVariable) :-
1377 get_texpr_id(SrcVariable,Id),
1378 get_texpr_id(DstVariable,Id),
1379 ( memberchk(DstVariable,DstVariables) ->
1380 get_texpr_type(DstVariable,Type),
1381 get_texpr_type(SrcVariable,Type)
1382 ;
1383 true).
1384
1385
1386 % in case of a refinement, check if the defined operations are already defined
1387 % in the abstract machine and copy that type.
1388 type_refinement_operations(MName,RawMachine,AbstractMachine,Local,Ein,Eout) :-
1389 get_operation_identifiers(RawMachine,Operations),
1390 type_refinement_operations2(Operations,MName,Local,AbstractMachine,Ein,Eout).
1391 type_refinement_operations2([],_,_,_AbstractMachine,Errors,Errors).
1392 type_refinement_operations2([Op|Rest],MName,M,AbstractMachine,Ein,Eout) :-
1393 get_abstract_operation_name_wo_infos(Op,AOp),
1394 %print(treating_refines_operation(Op,AOp)),nl,
1395 get_texpr_pos(Op,Pos),
1396 % look up the abstract definition
1397 get_abstract_op(AOp,MName,AbstractMachine,Pos,Ein,E1),
1398 % store the type in the identifier section
1399 copy_texpr_wo_info(Op,SOp),
1400 ( get_section(promoted,M,Operations),
1401 memberchk(SOp, Operations) -> true
1402 ; get_section(unpromoted,M,Operations), % this is probably a LOCAL_OPERATION
1403 memberchk(SOp, Operations) -> true
1404 ; add_error(btypechecker,'Could not find operation for type checking:',Op),fail
1405 ),
1406 % do the rest
1407 type_refinement_operations2(Rest,MName,M,AbstractMachine,E1,Eout).
1408 % looks up the type of the operator in an abstract machine
1409 get_abstract_op(Op,_,Abstraction,_,Errors,Errors) :-
1410 % look for the operation in promoted and unpromoted
1411 ? ( get_section(promoted,Abstraction,AbstractOps), member(Op,AbstractOps)
1412 ; get_section(unpromoted,Abstraction,AbstractOps), member(Op,AbstractOps) ),
1413 % forget alternatives
1414 !.
1415 get_abstract_op(Op,_,_Abstraction,_Pos,Errors,Errors) :-
1416 % we might allow new operations
1417 get_preference(allow_new_ops_in_refinement,true),!, % ALLOW_NEW_OPERATIONS_IN_REFINEMENT
1418 get_texpr_type(Op,op(_,_)).
1419 get_abstract_op(Op,MName,AbstractMachine,Pos,[warning(Msg,Pos)|Eout],Eout) :-
1420 % in case we do not find the operation, store an error
1421 get_texpr_id(Op,op(Id)),
1422 get_machine_name(AbstractMachine,Name),
1423 ajoin(['operation ', Id, ' from ', MName, ' is not defined in the abstract machine ',Name,
1424 ' (set ALLOW_NEW_OPERATIONS_IN_REFINEMENT to TRUE to allow this)'], Msg).
1425 % copy a typed expression without the additional information (just expression and type)
1426 copy_texpr_wo_info(A,B) :-
1427 % copy the expression and type, the additional information may be different
1428 get_texpr_expr(A,Expr),get_texpr_expr(B,Expr),
1429 get_texpr_type(A,Type),get_texpr_type(B,Type).
1430
1431 get_abstract_operation_name_wo_infos(b(_,Type,Infos),Res) :-
1432 memberchk(refines_operation(RefID),Infos),!, % renaming occurs:
1433 Res = b(identifier(op(RefID)),Type,_).
1434 get_abstract_operation_name_wo_infos(ID,Copy) :- copy_texpr_wo_info(ID,Copy).
1435
1436 create_id_sections(Header,RawMachine,Name) -->
1437 create_id_sections_header(Header),
1438 %{print(created_header(Name)),nl},
1439 create_set_sections(RawMachine,Name),
1440 %{print(created_set(Name)),nl},
1441 create_constants_sections(RawMachine),
1442 %{print(created_constants(Name)),nl},
1443 create_variables_sections(RawMachine),
1444 %{print(created_variables(Name)),nl},
1445 create_operations_sections(RawMachine,Name).
1446
1447 extract_parameter_types(MachineRefs,ParameterTypes) :-
1448 maplist(extract_parameter_types2,MachineRefs,ParameterTypesL),
1449 append(ParameterTypesL,ParameterTypes).
1450 extract_parameter_types2(ref(_,Machine),ParameterTypes) :-
1451 get_section(parameters,Machine,VisibleParams),
1452 get_section(internal_parameters,Machine,InternalParams),
1453 append(VisibleParams,InternalParams,Params),
1454 include(is_a_parameter_set,Params,ParameterSets),
1455 maplist(get_texpr_set_type,ParameterSets,ParameterTypes).
1456 is_a_parameter_set(TExpr) :-
1457 get_texpr_info(TExpr,Info),
1458 memberchk(parameter_set,Info).
1459
1460 type_sections(RawMachine,MachineType,RefMachines,NonGroundExceptions,Name,Ein,Eout) -->
1461 {debug_stats('TYPING CONSTRAINTS'(Name))},
1462 type_constraints(MachineType,Name,RawMachine,RefMachines,NonGroundExceptions,Ein,E1),
1463 % Maybe the VALUES section must be moved up later because it may be used to
1464 % substitute types (e.g. deferred sets to integers) for later use
1465 {debug_stats('TYPING PROPERTIES'(Name))},
1466 type_section_with_single_predicate(properties,Name,[constants],MachineType,RawMachine,RefMachines,NonGroundExceptions,E1,E2),
1467 {debug_stats('TYPING INVARIANT'(Name))},
1468 type_section_with_single_predicate(invariant,Name,[variables],MachineType,RawMachine,RefMachines,NonGroundExceptions,E2,E3),
1469 {debug_stats('TYPING ASSERTIONS'(Name))},
1470 type_section_with_predicate_list(assertions,[],MachineType,RawMachine,RefMachines,NonGroundExceptions,E3,E4),
1471 {debug_stats('TYPING INITIALISATION'(Name))},
1472 type_initialisation_section(RawMachine,Name,MachineType,RefMachines,NonGroundExceptions,E4,E5),
1473 {debug_stats('TYPING OPERATIONS'(Name))},
1474 type_operations_section(RawMachine,MachineType,RefMachines,NonGroundExceptions,E5,Eout),
1475 {debug_stats('FINISHED TYPING SECTIONS'(Name))}.
1476
1477 % skip this section, it is copied from the abstract machine and
1478 % does not need to be typed again
1479 type_constraints(refinement,_,_RawMachine,_RefMachines,_NonGroundExceptions,Errors,Errors) --> !.
1480 type_constraints(implementation,_,_RawMachine,_RefMachines,_NonGroundExceptions,Errors,Errors) --> !.
1481 type_constraints(machine,Name,RawMachine,RefMachines,NonGroundExceptions,Ein,Eout) -->
1482 % if the machine is a dummy machine (in presence of a not included seen or used
1483 % machine), we must omit the check that the (lower case) parameters are all typed.
1484 % We can assume that they are properly typed by the included machine.
1485 {(is_dummy_machine(RawMachine) -> IdsToType = [] ; IdsToType = [parameters])},
1486 type_section_with_single_predicate(constraints,Name,IdsToType,machine,
1487 RawMachine,RefMachines,NonGroundExceptions,Ein,Eout).
1488
1489 ?is_dummy_machine(RawMachine) :- member(is_dummy,RawMachine),!.
1490
1491 % Header: Parameters
1492 create_id_sections_header(machine_header(_,_,Parameters),Old,New) :-
1493 write_section(parameters,TParams,Old,New),
1494 maplist(create_id_section_parameter,Parameters,TParams).
1495 create_id_section_parameter(Param,TParam) :-
1496 Expr=identifier(Name),
1497 ext2int_with_pragma(Param,Expr,_,Type,Expr,[ParameterType],TParam),
1498 ( is_upper_case(Name) ->
1499 ParameterType = parameter_set,
1500 Type = set(_)
1501 ;
1502 ParameterType = parameter_scalar).
1503 is_upper_case(Name) :- \+ atom(Name),!, add_internal_error('Illegal call:', is_upper_case(Name)),fail.
1504 is_upper_case(Name) :- atom_codes(Name,[C|_]),
1505 memberchk(C,"ABCDEFGHIJKLMNOPQRSTUVWXYZ").
1506
1507 % Body: Sets
1508 create_set_sections(Sections,MachineName) -->
1509 write_section(deferred_sets,DeferredSets),
1510 write_section(enumerated_sets,EnumeratedSets),
1511 write_section(enumerated_elements,EnumeratedElements),
1512 {optional_rawmachine_section(sets,Sections,[],Sets),
1513 split_list(is_deferred_set_element,Sets,RawDeferredSets,RawEnumeratedSets),
1514 maplist(create_deferred_set_section(MachineName),RawDeferredSets,DeferredSets),
1515 maplist(create_enumerated_set_section(Sections,MachineName),
1516 RawEnumeratedSets,EnumeratedSets,LEnumeratedElements),
1517 append(LEnumeratedElements,EnumeratedElements)}.
1518 is_deferred_set_element(AstElem) :- has_functor(AstElem,deferred_set,_).
1519 create_deferred_set_section(MachineName,DS,TExpr) :-
1520 unwrap_opt_description(DS,deferred_set(Pos,I),TInfos),
1521 Infos = [given_set,def(deferred_set,MachineName)|TInfos],
1522 create_global_id(I,Pos,Infos,TExpr).
1523 create_enumerated_set_section(Sections,MachineName,ES,TExpr,Elements) :-
1524 unwrap_opt_description(ES,EnumSetList,TInfos),
1525 create_enum_set_aux(EnumSetList,Sections,MachineName,TInfos,TExpr,Elements).
1526
1527 create_global_id(identifier(_,Id),Pos,Infos,TExpr) :- !,
1528 add_warning(bmachine_construction,'Identifier unexpectedly not atomic: ',Id,Pos), % happened e.g. in ANTLR parser
1529 create_identifier(Id,Pos,set(global(Id)),Infos,TExpr).
1530 create_global_id(Id,Pos,Infos,TExpr) :- !,
1531 create_identifier(Id,Pos,set(global(Id)),Infos,TExpr).
1532
1533 create_enum_set_aux(enumerated_set(Pos,I,Elems),_,MachineName,TInfos,TExpr,Elements) :- !,
1534 % regular case I = {Elems1, ...}
1535 Infos = [given_set,def(enumerated_set,MachineName)|TInfos],
1536 create_global_id(I,Pos,Infos,TExpr),
1537 maplist(create_enum_set_element(I,MachineName),Elems,Elements).
1538 create_enum_set_aux(enumerated_set_via_def(Pos,I,ElemsDEF),Sections,MachineName,TInfos,TExpr,Elements) :- !,
1539 % we have the case I = ElemsDEF and DEFINITIONS ElemsDEF == {Elems1, ...}
1540 Infos = [given_set,def(enumerated_set,MachineName)|TInfos],
1541 create_global_id(I,Pos,Infos,TExpr),
1542 (optional_rawmachine_section(definitions,Sections,[],Defs),
1543 member(expression_definition(DPos,ElemsDEF,Paras,DefBody),Defs)
1544 -> (Paras \= []
1545 -> add_error(bmachine_construction,
1546 'DEFINITION for enumerated set elements must not have parameters:',ElemsDEF,DPos),
1547 Elements=[]
1548 ; DefBody = set_extension(_,Elems),
1549 maplist(create_enum_set_element(I,MachineName),Elems,Elements)
1550 -> true
1551 ; add_error(bmachine_construction,
1552 'DEFINITION for enumerated set elements must be of the form {El1,El2,...}:',ElemsDEF,DPos),
1553 Elements=[]
1554 )
1555 ; add_error(bmachine_construction,'No DEFINITION for enumerated set elements found:',ElemsDEF,Pos),
1556 Elements=[]
1557 ).
1558 create_enum_set_aux(E,_,_,_,_,_) :- add_internal_error('Illegal enumerated set:',E),fail.
1559
1560
1561 % deal with optional description(Pos,Desc,A) wrapper
1562 has_functor(description(_,_Desc,A),Functor,Arity) :- !, functor(A,Functor,Arity).
1563 has_functor(A,Functor,Arity) :- functor(A,Functor,Arity).
1564
1565 % remove description wrapper and generate info field
1566 unwrap_opt_description(Pragma,Res,Infos) :-
1567 unwrap_pragma(Pragma,Expr,I),!, Res=Expr,Infos=I.
1568 unwrap_opt_description(A,A,[]).
1569
1570
1571 create_enum_set_element(Id,MachineName,Ext,Elem) :-
1572 (Id=identifier(none,RID)
1573 -> Type=global(RID), add_warning(bmachine_construction,'Unexpected non-atomic global set id: ',RID)
1574 ; Type=global(Id)),
1575 ext2int_with_pragma(Ext,Expr,_Pos,Type,Expr,[enumerated_set_element,def(enumerated_element,MachineName)],Elem).
1576
1577 create_identifier(Id,Pos,Type,Infos,TExpr) :-
1578 create_texpr(identifier(Id),Type,[nodeid(Pos)|Infos],TExpr).
1579
1580 % Constants
1581 create_constants_sections(RawMachine) -->
1582 create_section_identifiers(constants,concrete_constants,RawMachine),
1583 create_section_identifiers(abstract_constants,abstract_constants,RawMachine).
1584 % Variables
1585 create_variables_sections(RawMachine) -->
1586 create_section_identifiers(concrete_variables,concrete_variables,RawMachine),
1587 create_section_identifiers(variables,abstract_variables,RawMachine).
1588
1589 % Freetypes: Treat them as additional constants, plus add entries in the "freetypes"
1590 % section of the resulting machine
1591 create_freetypes(RawMachine,MType,RefMachines,Old,New,Ein,Eout) :-
1592 optional_rawmachine_section(freetypes,RawMachine,[],RawFreetypes),
1593 ? create_freetypes2(RawFreetypes,MType,[ref(local,Old)|RefMachines],Old,New,Ein,Eout).
1594 create_freetypes2([],_MType,_RefMachines,M,M,E,E) :- !.
1595 create_freetypes2(RawFreetypes,MType,RefMachines,Old,New,Ein,Eout) :-
1596 % we need the NonGroundExceptions for type checking
1597 extract_parameter_types(RefMachines,NonGroundExceptions),
1598 % create identifiers in the constants section
1599 ? maplist(create_ids_for_freetype,RawFreetypes,IdsFreetypes),
1600 % we just combined the results to keep the numbers of arguments low (too much for maplist)
1601 maplist(split_ft,IdsFreetypes,IdentifiersL,Freetypes),
1602 append(IdentifiersL,Identifiers),
1603 % create properties for each freetype
1604 foldl(create_properties_for_freetype(MType,RefMachines,NonGroundExceptions,Identifiers),
1605 RawFreetypes,IdsFreetypes,PropertiesL,Ein,Eout),
1606 conjunct_predicates(PropertiesL,Properties),
1607 (debug_mode(off) -> true
1608 ; format('Created PROPERTIES for FREETYPES:~n',[]), translate:nested_print_bexpr(Properties),nl),
1609 append_to_section(abstract_constants,Identifiers,Old,Inter),
1610 conjunct_to_section(properties,Properties,Inter,Inter2),
1611 write_section(freetypes,Freetypes,Inter2,New).
1612
1613 split_ft(ft(Ids,Freetype),Ids,Freetype).
1614
1615
1616 create_ids_for_freetype(FT,ft([TId|TCons],freetype(Id,Cases))) :-
1617 is_freetype_declaration(FT,_Pos,Id,_TypeParams,Constructors),
1618 !,
1619 create_typed_id_with_given_set_info(Id,set(freetype(Id)),TId),
1620 ? maplist(create_ids_for_constructor(Id),Constructors,TCons,Cases).
1621 create_ids_for_freetype(FT,_) :-
1622 add_internal_error('Illegal freetype term:',create_ids_for_freetype(FT,_)),fail.
1623
1624 % add given_set info so that is_just_type3 can detect this as a type
1625 create_typed_id_with_given_set_info(IDName,Type,b(identifier(IDName),Type,[given_set])).
1626
1627 % deconstruct a .prob Prolog encoding of a freetype declaration
1628 % new versions of parser generate freetype parameters
1629 is_freetype_declaration(freetype(Pos,Id,Constructors),Pos,Id,[],Constructors).
1630 is_freetype_declaration(freetype(Pos,Id,TypeParams,Constructors),Pos,Id,TypeParams,Constructors) :-
1631 (TypeParams=[] -> true ; add_warning(bmachine_construction,'Not yet supporting freetype parameters:',Id,Pos)).
1632
1633 create_ids_for_constructor(Id,constructor(_Pos,Name,_Arg),TCons,case(Name,Type)) :-
1634 create_typed_id(Name,set(couple(Type,freetype(Id))),TCons).
1635 create_ids_for_constructor(Id,element(_Pos,Name),TCons,case(Name,constant([Name]))) :-
1636 create_typed_id(Name,freetype(Id),TCons).
1637
1638 create_properties_for_freetype(MType,RefMachines,NonGroundExceptions, AllFTIdentifiers,
1639 FREETYPE,ft(Ids,_Freetypes),Properties,Ein,Eout) :-
1640 is_freetype_declaration(FREETYPE,_Pos,Id,_TypeParams,Constructors),
1641 debug_format(9,'Processing freetype ~w (one of ~w)~n',[Id,AllFTIdentifiers]),
1642 % The freetype type
1643 FType = freetype(Id),
1644 % We use the standard type environment of properties...
1645 visible_env(MType,properties,RefMachines,CEnv,Ein,E1),
1646 % ...plus the identifiers of the free type (type name and constructor names)
1647 add_identifiers_to_environment(Ids,CEnv,FEnv0),
1648 % ...plus the identifiers of all free type names (will overwrite Id, but not a problem)
1649 % Note: instead of adding all freetype ids, we could just add the ones preceding Id
1650 add_identifiers_to_environment(AllFTIdentifiers,FEnv0,FEnv),
1651 % We generate a comprehension set for all elements
1652 create_typed_id(Id,set(FType),TId),
1653 create_texpr(equal(TId,TComp),pred,[],FDef),
1654 unique_typed_id("_freetype_arg",FType,Element),
1655 create_recursive_compset([Element],ECond,set(FType),[],RecId,TComp),
1656 create_typed_id(RecId,set(FType),TRecId),
1657 % For each constructor, we generate a definition and a condition for the
1658 % comprehension set above
1659 foldl(create_properties_for_constructor(Id,FEnv,Element,TRecId,NonGroundExceptions),
1660 Constructors,Defs,Conds,E1,Eout),
1661 conjunct_predicates(Conds,ECond),
1662 conjunct_predicates([FDef|Defs],Properties).
1663
1664 /* create_properties_for_constructor(+Env,+Element,+RecId,+NGE,+Constructor,-Def,-Cond,Ein,Eout)
1665 Env: Type environment
1666 Element: A typed identifier "e" that is used in the definition of the freetype set:
1667 ft = {e | e has_freetype_constructor x => e:...}
1668 RecId: The typed identifier that can be used to refer to the freetype set (ft in the
1669 example above
1670 NGE: "Non ground exceptions", needed for type checking when having a parametrized machine
1671 Constructor: The constructor expression as it comes from the parser
1672 (constructor(Pos,Name,ArgSet) or element(Pos,Name))
1673 Def: The predicate that defines the constant for the constructor,
1674 e.g. "cons = {i,o | i:NAT & o = freetype(cons,i)}"
1675 Cond: The predicate that checks the argument of a freetype in the freetype set
1676 (That would be the part "e:..." in the example above.
1677 Ein,Eout: Used for type checker errors
1678 */
1679 create_properties_for_constructor(FID,Env,Element,RecId,NonGroundExceptions,
1680 Constructor,Def,Cond,Ein,Eout) :-
1681 constructor_name(Constructor,Name),
1682 env_lookup_type(Name,Env,CType),
1683 create_properties_for_constructor2(Constructor,Env,NonGroundExceptions,FID,
1684 Element,RecId,CDef,Cond,Ein,Eout),
1685 get_texpr_type(CDef,CType),
1686 create_typed_id(Name,CType,CId),
1687 create_texpr(equal(CId,CDef),pred,[],Def).
1688 constructor_name(element(_Pos,Name),Name).
1689 constructor_name(constructor(_Pos,Name,_Domain),Name).
1690 create_properties_for_constructor2(element(_Pos,Name),_Env,_NonGroundExceptions,FID,
1691 _Element,_RecId,CDef,Cond,Ein,Ein) :-
1692 create_texpr(value(freeval(FID,Name,term(Name))),freetype(FID),[],CDef),
1693 create_texpr(truth,pred,[],Cond).
1694 create_properties_for_constructor2(constructor(_Pos,Name,RArg),Env,NonGroundExceptions,
1695 FID,Element,RecId,CDef,Cond,Ein,Eout) :-
1696 % First, type check the given set of the domain:
1697 btype_ground_dl([RArg],Env,NonGroundExceptions,[set(DType)],[TDomain],Ein,Eout),
1698 % then create the RHS of "c = {i,o | i:Domain & o=freetype_constructor(Name,i)}"
1699 create_definition_for_constructor(Name,TDomain,FID,CDef),
1700 % The check in the freetype comprehension set is of the form
1701 % e "of_freetype_case" Name => "content_of"(e) : Domain
1702 create_texpr(implication(IsCase,DomainTest),pred,[],Cond),
1703 create_texpr(freetype_case(FID,Name,Element),pred,[],IsCase),
1704 create_texpr(freetype_destructor(FID,Name,Element),DType,[],Content),
1705 % all references to the freetype itself are replaced by the recursive reference
1706 replace_id_by_expr(TDomain,FID,RecId,TDomain2),
1707 create_texpr(member(Content,TDomain2),pred,[],DomainTest).
1708
1709 :- use_module(bsyntaxtree,[get_texpr_set_type/2]).
1710
1711 /* The constructor is a function to the freetype, defined with a comprehension set:
1712 The general form is "c = {i,o | i:Domain & o=freetype_constructor(Name,i)}"
1713 create_definition_for_constructor(+Name,+DType,+FID,-CType,-CDef) :-
1714 Name: Name of the constructor
1715 TDomain: The user-specified domain
1716 FID: The name of the free type
1717 CDef: The RHS of the definition "Name = CDef"
1718 */
1719 create_definition_for_constructor(Name,TDomain,FID,CDef) :-
1720 % get the type of the domain:
1721 get_texpr_set_type(TDomain,DType),
1722 % create argument and result identifiers:
1723 unique_typed_id("_constr_arg",DType,TArgId), % was constructor_arg and constructor_res
1724 unique_typed_id("_constr_res",freetype(FID),TResId),
1725 % The comprehension set as a whole
1726 CType = set(couple(DType,freetype(FID))),
1727 create_texpr(comprehension_set([TArgId,TResId],Pred),CType,
1728 [prob_annotation('SYMBOLIC')],CDef),
1729 create_texpr(conjunct(DomainCheck,Construction),pred,[],Pred),
1730 % "i:Domain"
1731 create_texpr(member(TArgId,TDomain),pred,[],DomainCheck),
1732 % "o=freetype_constructor(i)
1733 create_texpr(freetype_constructor(FID,Name,TArgId),freetype(FID),[],FreetypeCons),
1734 create_texpr(equal(TResId,FreetypeCons),pred,[],Construction).
1735
1736 % Operations
1737 create_operations_sections(RawMachine,Name,Old,New) :-
1738 write_section(promoted,PromotedOperationIds,Old,New0),
1739 get_operation_identifiers(RawMachine,operations,OperationIdentifiers),
1740 (allow_local_or_expr_op_calls,
1741 get_operation_identifiers(RawMachine,local_operations,LocOpIDs),
1742 LocOpIDs \= []
1743 -> append_to_section(unpromoted,LocOpIDs,New0,New),
1744 % Now remove all LOCAL_OPERATIONS from the promoted ones
1745 % see for example prob_examples/examples/B/ClearSy/RoboSim/SRanger_case_Jul25/logic_i.imp
1746 exclude(duplicate_local_operation_id(Name,LocOpIDs),OperationIdentifiers,PromotedOperationIds)
1747 ; New = New0, PromotedOperationIds = OperationIdentifiers
1748 ).
1749
1750 % check if a LOCAL_OPERATION is already declared in the OPERATIONS section:
1751 % in this case: we use the operation body defined in the OPERATIONS section, but remove it from the promoted list
1752 duplicate_local_operation_id(Name,OpIds,TID) :-
1753 get_texpr_id(TID,op(OpID)),
1754 member(TID2,OpIds),
1755 get_texpr_id(TID2,op(OpID)),!,
1756 debug_println(9,duplicate_local_operation_id(OpID,Name)).
1757
1758 get_operation_identifiers(RawMachine,OperationIdentifiers) :-
1759 get_operation_identifiers(RawMachine,operations,OperationIdentifiers).
1760 get_operation_identifiers(RawMachine,SECTION,OperationIdentifiers) :-
1761 optional_rawmachine_section(SECTION,RawMachine,[],Ops),
1762 maplist(extract_operation_identifier,Ops,OperationIdentifiers).
1763 extract_operation_identifier(Ext,TId) :-
1764 remove_pos(Ext, operation(ExtId,_,_,_)),!,
1765 ext2int_with_pragma(ExtId,identifier(I),_,op(_,_),identifier(op(I)),Infos,TId),
1766 operation_infos(Infos).
1767 extract_operation_identifier(Ext,TId) :-
1768 remove_pos(Ext, refined_operation(ExtId,_,_,RefinesOp,_)),!,
1769 ext2int_with_pragma(ExtId,identifier(I),_,op(_,_),identifier(op(I)),[refines_operation(RefinesOp)|Infos],TId),
1770 operation_infos(Infos).
1771 extract_operation_identifier(Ext,TId) :-
1772 remove_pos(Ext, description_operation(_Desc,RealOp)),!,
1773 extract_operation_identifier(RealOp,TId).
1774 extract_operation_identifier(Ext,_) :- add_internal_error('Unknown operation node:',Ext),fail.
1775
1776 % VALUES section:
1777 % process_values_section(MachineType,RawMachine,NonGroundExceptions,Min/Ein/RefMIn,Mout/Eout/RefMOut):
1778 % Type-check the VALUES section and change the type of valuated deferred sets, if necessary
1779 % MachineType, RawMachine, NonGroundExceptions: as usual, see other comments
1780 % Min/Mout: The currently constructed machine
1781 % Ein/Eout: The difference list of errors
1782 % RefMin/RefMout: The list of already typechecked machines. These typechecked machines can be
1783 % altered by this predicate because if a deferred set is valuated by an integer set or
1784 % other deferred set, all occurrences of the original type are replaced by the new type,
1785 % even for the already typed machines.
1786 process_values_section(MachineType,RawMachine,NonGroundExceptions,Min/Ein/RefMIn,Mout/Eout/RefMOut) :-
1787 optional_rawmachine_section(values,RawMachine,[],RawValues),
1788 process_values_section_aux(RawValues,MachineType,NonGroundExceptions,
1789 Min/Ein/RefMIn,Mout/Eout/RefMOut).
1790 process_values_section_aux([],_MachineType,_NonGroundExceptions,In,Out) :- !,In=Out.
1791 process_values_section_aux(RawValues,MachineType,NonGroundExceptions,
1792 Min/Ein/RefMin,Mout/Eout/RefMout) :-
1793 debug_stats('TYPING VALUES'),
1794 type_values_section(MachineType,RawValues,RefMin,NonGroundExceptions,Min/Ein,Mout/Eout),
1795 % will be added as additional_property in bmachine
1796 RefMin=RefMout.
1797
1798 type_values_section(MachineType,RawValues,RefMachines,NonGroundExceptions,Min/Ein,Mout/Eout) :-
1799 write_section(values,Values,Min,Mout),
1800 visible_env(MachineType,values_expression,RefMachines,Env,Ein,E1),
1801 % We have to pass an environment that can be modified because in each
1802 % valuation the previously valuated constants can be used.
1803 foldl(extract_values_entry(NonGroundExceptions),RawValues,Values,Env/E1,_ResultingEnv/Eout).
1804
1805 extract_values_entry(NonGroundExceptions, values_entry(POS,ValueID,ValueExpr), Entry,
1806 EnvIn/Ein,EnvOut/Eout) :-
1807 % TODO: There seem to be a lot of additional constraints for valuations in VALUES that are not
1808 % yet handled here
1809 btype_ground_dl([ValueExpr],EnvIn,NonGroundExceptions,[Type],[TExpr],Ein,Eout),
1810 clean_up(TExpr,[],CTExpr), % ensure we remove things like mult_or_cart/2
1811 create_identifier(ValueID,POS,Type,[valuated_constant],TypedID),
1812 create_texpr(values_entry(TypedID,CTExpr),values_entry,[nodeid(POS)],Entry),
1813 debug_println(9,valued_constant(ValueID)),
1814 EnvOut=EnvIn.
1815 %add_identifiers_to_environment([TypedID],EnvIn,EnvOut). % ideally we should register the new type of TypedID
1816 % However: ProB can currently only process VALUES clauses where the type does not change
1817
1818 % type_section_with_single_predicate(+Sec,+Name,+SectionsToType,+MachineType,+Sections,
1819 % +RefMachines,+NonGroundExceptions,+Ein,-Eout,+Old,-New):
1820 % Type a section such as INVARIANT, PROPERTIES, CONSTRAINTS with a single predicate
1821 % Sec: section name in the raw (untyped) machine (e.g. invariant)
1822 % Name: name of machine from which this section comes
1823 % SectionsToType: list of section names that contain identifiers that must be typed
1824 % by this predicate (e.g. all variables must be typed by the invariant)
1825 % MachineType: machine type (machine, refinement, ...)
1826 % Sections: list of sections representing the raw (untyped) machine
1827 % RefMachines: list of already typed machines
1828 % NonGroundExceptions: list of types that may be not ground because the concrete type
1829 % is determinded by machine parameter
1830 % Ein/Eout: difference list of errors
1831 % Old/New: the new typed section is added (by conjunction) to the machine
1832 type_section_with_single_predicate(Sec,Name,SectionsToType,MachineType,Sections,
1833 RefMachines,NonGroundExceptions,Ein,Eout,Old,New) :-
1834 optional_rawmachine_section(Sec,Sections,truth(none),Predicate),
1835 ( Predicate = truth(_) ->
1836 % even if there is no content, we must check if all identifiers are typed
1837 check_if_all_ids_are_typed(SectionsToType,RefMachines,NonGroundExceptions,Ein,Eout),
1838 Old=New
1839 ;
1840 get_machine_infos(Sections,Infos),
1841 toplevel_raw_predicate_sanity_check(Sec,Name,Predicate,Infos),
1842 type_predicates(Sec,SectionsToType,MachineType,[Predicate],RefMachines,NonGroundExceptions,
1843 [Typed],Ein,Eout),
1844 conjunct_to_section(Sec,Typed,Old,New)
1845 ),
1846 !.
1847 type_section_with_single_predicate(Sec,Name,SectsToType,MchType,_,_,_,_,_,_,_) :-
1848 add_internal_error('type_section_with_single_predicate failed',
1849 type_section_with_single_predicate(Sec,Name,SectsToType,MchType,_,_,_,_,_,_,_)),
1850 fail.
1851
1852 % get some infos relevant for sanity check:
1853 get_machine_infos(Sections,Infos) :-
1854 ((rawmachine_section_exists(concrete_variables,Sections) ; rawmachine_section_exists(abstract_variables,Sections))
1855 -> Infos = [has_variables|I1] ; Infos = I1),
1856 ((rawmachine_section_exists(concrete_constants,Sections) ; rawmachine_section_exists(abstract_constants,Sections))
1857 -> I1 = [has_constants] ; I1 = []).
1858
1859 % Type a section with multiple predicates, such as ASSERTIONS
1860 type_section_with_predicate_list(Sec,SectionsToType,MachineType,Sections,
1861 RefMachines,NonGroundExceptions,Ein,Eout,Old,New) :-
1862 write_section(Sec,Typed,Old,New),
1863 optional_rawmachine_section(Sec,Sections,[],Predicates),
1864 type_predicates(Sec,SectionsToType,MachineType,Predicates,RefMachines,NonGroundExceptions,Typed,Ein,Eout),
1865 !.
1866 type_section_with_predicate_list(Sec,SectsToType,MchType,Sects,RefMchs,NonGrndExc,Ein,Eout,Old,New) :-
1867 add_internal_error('type_section_with_predicate_list failed',
1868 type_section_with_predicate_list(Sec,SectsToType,MchType,Sects,RefMchs,NonGrndExc,Ein,Eout,Old,New)),
1869 fail.
1870
1871
1872 type_predicates(_Sec,SectionsToType,_MachineType,[],RefMachines,NonGroundExceptions,Typed,Ein,Eout) :-
1873 !,Typed=[],
1874 check_if_all_ids_are_typed(SectionsToType,RefMachines,NonGroundExceptions,Ein,Eout).
1875 type_predicates(Sec,SectionsToType,MachineType,Predicates,RefMachines,NonGroundExceptions,Typed,Ein,Eout) :-
1876 visible_env(MachineType, Sec, RefMachines, Env, Ein, E1),
1877 same_length(Predicates,Types),maplist(is_pred_type,Types),
1878 btype_ground_dl_in_section(Sec,Predicates,Env,NonGroundExceptions,Types,Typed1,E1,E2),
1879 mark_with_section(Sec,Typed1,Typed),
1880 check_if_all_ids_are_typed(SectionsToType,RefMachines,NonGroundExceptions,E2,Eout),
1881 (no_perrors_occured(Ein,Eout)
1882 -> perform_post_static_check(Typed) % only run if no type errors, it makes use of find_typed_identifier_uses
1883 ; true
1884 ).
1885
1886 no_perrors_occured(Ein,Eout) :- Ein==Eout,!.
1887 no_perrors_occured([H|T],Eout) :- nonvar(H),not_a_perror(H),no_perrors_occured(T,Eout).
1888
1889 not_a_perror(warning(_,_)).
1890 % other possible values: error(Msg,Pos), internal_error(Msg,Pos); see get_perror/2
1891
1892 % check if the identifiers that should be typed by this section are completly typed
1893 check_if_all_ids_are_typed([],_RefMachines,_NonGroundExceptions,Ein,Eout) :- !,Ein=Eout.
1894 check_if_all_ids_are_typed(SectionsToType,RefMachines,NonGroundExceptions,Ein,Eout) :-
1895 memberchk(ref(local,Local),RefMachines),
1896 get_all_identifiers(SectionsToType,Local,IdentifiersToType),
1897 check_ground_types_dl(IdentifiersToType, NonGroundExceptions, Ein, Eout).
1898
1899
1900 mark_with_section(Sec,In,Out) :-
1901 maplist(mark_with_section2(Sec),In,Out).
1902 mark_with_section2(Sec,In,Out) :-
1903 remove_bt(In,conjunct(A,B),conjunct(NA,NB),Out),!,
1904 mark_with_section2(Sec,A,NA), mark_with_section2(Sec,B,NB).
1905 mark_with_section2(Sec,In,Out) :-
1906 add_texpr_infos(In,[section(Sec)],Out).
1907
1908 type_initialisation_section(Sections,Name,MType,RefMachines,NonGroundExceptions,Ein,Eout,Old,New) :-
1909 write_section(initialisation,Initialisation,Old,New),
1910 ( rawmachine_section(initialisation,Sections,Init) ->
1911 visible_env(MType, initialisation, RefMachines, InitEnv, Ein, E1),
1912 btype_ground_dl([Init],InitEnv,NonGroundExceptions,[subst],[TypedInit],E1,Eout),
1913 Initialisation=[init(Name,TypedInit)]
1914 ;
1915 Ein=Eout,
1916 Initialisation=[]).
1917
1918 :- use_module(library(ugraphs)).
1919
1920 type_operations_section(Sections,MType,RefMachines,NonGroundExceptions,Ein,Eout,Old,New) :-
1921 write_section(operation_bodies,Operations,Old,New),
1922 visible_env(MType, operation_bodies, RefMachines, Env, Ein, E1),
1923 optional_rawmachine_section(operations,Sections,[],Ops1),
1924 optional_rawmachine_section(local_operations,Sections,[], Ops2),
1925 exclude(duplicate_local_operation(Ops1),Ops2,FOps2),
1926 append(FOps2,Ops1,Ops),
1927 topological_sort(Ops,Env,SOps),
1928 (debug_mode(off) -> true ; length(SOps,NrOps),debug_stats(finished_topological_sorting(NrOps))),
1929 same_length(SOps,Types), maplist(is_op_type,Types),
1930 ? btype_ground_dl(SOps,Env,NonGroundExceptions,Types,Operations,E1,Eout),!.
1931
1932 % check if a LOCAL_OPERATION also exists as a regular operation; if so we can ignore it and
1933 % just use the full operation; see also duplicate_local_operation_id above
1934 duplicate_local_operation(NonLocalOps,LocalOperation) :-
1935 raw_op_id(LocalOperation,OpName),
1936 member(NonLocalOp,NonLocalOps),
1937 raw_op_id(NonLocalOp,OpName), % we found a non-local operation with the same name
1938 !,
1939 raw_op_pos(LocalOperation,LPos),
1940 raw_op_pos(NonLocalOp,NPos),
1941 translate_span(NPos,PS2),
1942 ajoin(['Ignoring LOCAL_OPERATION already defined in OPERATIONS section ',PS2,': '],Msg),
1943 add_message(bmachine_construction,Msg,OpName,LPos).
1944
1945
1946 allow_local_or_expr_op_calls :-
1947 (get_preference(allow_local_operation_calls,true) -> true
1948 ; get_preference(allow_operation_calls_in_expr,true)).
1949 % at the moment ProB allows local calls inside expressions, independently of the allow_local_operation_calls preference
1950
1951 % perform a topological sort of the operations: treat called operation before calling operation
1952 % only relevant when allow_local_operation_calls is set to true
1953 topological_sort(Ops,Env,SortedOps) :-
1954 allow_local_or_expr_op_calls,
1955 findall(OtherID-ID, (member(Op,Ops),op_calls_op(Op,Env,ID,OtherID)),Edges),
1956 % print(edges(Edges)),nl,
1957 % TO DO: maybe only store edges where OtherID also appears in Ops (i.e., call within same machine)
1958 Edges \= [],
1959 !,
1960 findall(ID,(member(operation(_,RawID,_,_,_),Ops),raw_id(RawID,ID)),Vertices), %print(vertices(Vertices)),nl,
1961 vertices_edges_to_ugraph(Vertices,Edges,Graph),
1962 (top_sort(Graph,Sorted)
1963 -> sort_ops(Sorted,Ops,SortedOps)
1964 ; get_preference(allow_operation_calls_in_expr,true) ->
1965 add_warning(topological_sort,'Mutual recursion or cycle in the (local) operation call graph, this may cause problems computing reads information: ',Edges),
1966 SortedOps=Ops
1967 % not necessarily a problem, because operations called in expressions are not allowed to modify the state
1968 % TODO: however, we may have an issue with computing reads information correctly for mutual recursion !?
1969 % direct recursion should be ok
1970 ; add_error(topological_sort,'Cycle in the (local) operation call graph: ',Edges),
1971 SortedOps=Ops).
1972 topological_sort(Ops,_,Ops).
1973
1974 sort_ops([],Ops,Ops). % Ops should be []
1975 sort_ops([OpID|T],Ops,Res) :-
1976 raw_op_id(Op1,OpID),
1977 (select(Op1,Ops,TOps)
1978 -> Res = [Op1|TSOps], sort_ops(T,TOps,TSOps)
1979 ; % operation from another machine
1980 % print(could_not_find(OpID,Ops)),nl,
1981 sort_ops(T,Ops,Res)
1982 ).
1983
1984 is_op_type(op(_,_)).
1985 is_pred_type(pred).
1986
1987 % compute which other operations are directly called
1988 op_calls_op(operation(_,RawID,_,_,RawBody),Env,ID,OtherID) :- raw_id(RawID,ID),
1989 raw_body_calls_operation(RawBody,ID,Env,OtherID).
1990
1991 raw_body_calls_operation(RawBody,ID,Env,OtherID) :-
1992 raw_member(OpCall,RawBody),
1993 raw_op_call(OpCall,ID,Env,RawOtherID), raw_id(RawOtherID,OtherID).
1994
1995 raw_op_call(operation_call(_,RawOtherID,_,_),_,_, RawOtherID).
1996 raw_op_call(operation_call_in_expr(_,RawOtherID,_),ID,_, RawOtherID) :-
1997 \+ raw_id(RawOtherID,ID). % we do not look at direct recursion: it poses no problem for computing reads/writes info
1998 raw_op_call(function(_,RawOtherID,_), ID, Env, RawOtherID) :- % function calls possibly not yet translated to operation_call_in_expr
1999 get_preference(allow_operation_calls_in_expr,true),
2000 \+ raw_id(RawOtherID,ID), % direct recursion ok
2001 btypechecker:is_operation_call(RawOtherID,Env).
2002 raw_op_call(identifier(Pos,OtherID), ID, Env, RawOtherID) :- % possible operation call in expr without arguments
2003 OtherID \= ID, % direct recursion ok
2004 get_preference(allow_operation_calls_in_expr,true),
2005 RawOtherID = identifier(Pos,OtherID),
2006 btypechecker:is_operation_call(RawOtherID,Env).
2007
2008
2009 raw_op_id(operation(_,RawID,_,_,_RawBody),ID) :- raw_id(RawID,ID).
2010 raw_id(identifier(_,ID),ID).
2011 raw_op_pos(operation(Pos,_RawID,_,_,_RawBody),Pos).
2012
2013 % a utility function to work on the raw AST Functor(POS,Arg1,...,Argn)
2014 % this will not be able to look inside DEFINITIONS !
2015 % TO DO: deal with more raw substitutions which have list arguments
2016 raw_member(X,X).
2017 raw_member(X,parallel(_,List)) :- !, member(Term,List), raw_member(X,Term).
2018 raw_member(X,sequence(_,List)) :- !, member(Term,List), raw_member(X,Term).
2019 raw_member(X,[H|T]) :- !, (raw_member(X,H) ; raw_member(X,T)).
2020 raw_member(X,Term) :- compound(Term), Term =.. [_Functor,_Pos|Args],
2021 member(A,Args), raw_member(X,A).
2022
2023
2024 create_section_identifiers(Section,DestSection,RawMachine,Old,New) :-
2025 write_section(DestSection,Vars,Old,New),
2026 optional_rawmachine_section(Section,RawMachine,[],Identifiers),
2027 create_section_ids2(Identifiers,[],Vars,DestSection,New).
2028
2029 create_section_ids2([],_,[],_,_).
2030 create_section_ids2([Ext|Rest],Infos,Res,DestSection,MachSections) :-
2031 expand_definition_to_variable_list(Ext,MachSections,List),!,
2032 append(List,Rest,NewList),
2033 create_section_ids2(NewList,Infos,Res,DestSection,MachSections).
2034 create_section_ids2([Ext|Rest],Infos,Res,DestSection,MachSections) :-
2035 create_section_id(Ext,Infos,DestSection,TId),
2036 ( TId = error(Msg,Term,Pos) ->
2037 Res = TRest, add_error(bmachine_construction,Msg,Term,Pos)
2038 ;
2039 Res = [TId|TRest]),
2040 create_section_ids2(Rest,Infos,TRest,DestSection,MachSections).
2041 create_section_id(Ext,Infos,DestSection,TId) :-
2042 (unwrap_pragma(Ext,Ext2,PragmaInfos) -> append(PragmaInfos,Infos,FullInfos)
2043 ; Ext2=Ext, FullInfos=Infos),
2044 I=identifier(_),
2045 ( ext2int(Ext2,I,_Pos,_Type,I,FullInfos,TId) ->
2046 true
2047 ; Ext2 = definition(POSINFO,ID,_) ->
2048 TId = error('Trying to use DEFINITION name as identifier: ',
2049 (ID,within(DestSection)), POSINFO)
2050 ;
2051 TId = error('Illegal identifier: ',
2052 (Ext2,within(DestSection)), Ext2)
2053 ).
2054
2055 % support using DEFINITIONS which are variable lists;
2056 % currently for ProB parser you need to write VARS == (x,y,..) for Atelier-B: VARS == x,y,..
2057 expand_definition_to_variable_list(definition(_POSINFO,ID,_),MachSections,List) :-
2058 get_section(definitions,MachSections,Defs),
2059 member(definition_decl(ID,expression,_InnerPos,[],RawExpr,_Deps),Defs),
2060 extract_identifier_list(RawExpr,List,[]).
2061
2062 % convert a raw tuple into a raw identifier list:
2063 extract_identifier_list(identifier(Pos,ID)) --> [identifier(Pos,ID)].
2064 extract_identifier_list(couple(_,List)) -->
2065 extract_identifier_list(List).
2066 extract_identifier_list([]) --> [].
2067 extract_identifier_list([H|T]) --> extract_identifier_list(H), extract_identifier_list(T).
2068
2069
2070 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2071 % sort the machines topologically
2072
2073 % can be used to store the result:
2074 assert_machine_order(Order) :-
2075 retractall(machine_global_order(_)),
2076 debug_print(9,machine_global_order(Order)),
2077 assertz(machine_global_order(Order)).
2078
2079 get_mach_position(Order,M,Ref,Pos-mch(M,Ref)) :-
2080 get_machine_name(M,Name),
2081 ? (nth1(Pos,Order,Name) -> true
2082 ; add_internal_error('Unknown machine:',Name:Order),
2083 Pos=0).
2084 get_machine(_-mch(M,_),M). % re-extract info after sorting
2085 get_reference(_-mch(_,R),R).
2086
2087 :- use_module(library(samsort),[samkeysort/2]).
2088 sort_machines_by_global_order(Machines,SortedMachines) :-
2089 sort_machines_by_global_order(Machines,_,SortedMachines,_).
2090 sort_machines_by_global_order(Machines,Refs,SortedMachines,SortedRefs) :-
2091 machine_global_order(Order),
2092 maplist(get_mach_position(Order),Machines,Refs,KM), % add position so that sorting works
2093 samkeysort(KM,SKM), % for test 925 it is important to keep duplicates and not use sort/2
2094 maplist(get_machine,SKM,SortedMachines),
2095 maplist(get_reference,SKM,SortedRefs),!.
2096 %maplist(get_machine_name,Sorted,SNs),print(sorted(SNs)),nl.
2097 sort_machines_by_global_order(M,R,M,R) :-
2098 add_internal_error('Sorting machines failed:',M).
2099
2100 % perform the actual computation:
2101 machine_order(Machines,Order) :-
2102 machine_dependencies(Machines,Dependencies),
2103 topsort(Dependencies,Order).
2104
2105 % sort the machines topologically
2106 topsort(Deps,Sorted) :-
2107 topsort2(Deps,[],Sorted).
2108 topsort2([],_,[]) :- !.
2109 topsort2(Deps,Known,Sorted) :-
2110 split_list(all_deps_known(Known),Deps,DAvailable,DNotAvailable),
2111 DAvailable = [_|_], % we have new machines available whose dependencies are all known
2112 !,
2113 maplist(dep_name,DAvailable,Available),
2114 append(Available,Known,NewKnown),
2115 append(Available,Rest,Sorted),
2116 topsort2(DNotAvailable,NewKnown,Rest).
2117 topsort2(Deps,_Known,_) :-
2118 member(dep(Name,NameDeps),Deps),
2119 add_error(bmachine_construction,'Could not resolve machine dependencies for: ',Name:depends_on(NameDeps)),
2120 fail.
2121
2122 ?all_deps_known(K,dep(_Name,Deps)) :- sort(Deps,DS),sort(K,KS),subseq0(KS,DS),!.
2123 dep_name(dep(Name,_Deps),Name).
2124
2125 % find dependencies between machines
2126 machine_dependencies(Machines,Dependencies) :-
2127 maplist(machine_dependencies2,Machines,Deps),
2128 sort(Deps,Dependencies).
2129 machine_dependencies2(M,dep(Name,Deps)) :-
2130 get_constructed_machine_name_and_body(M,Name,_,Body),
2131 findall(Ref,
2132 (refines(M,Ref);machine_reference(Body,Ref)),
2133 Deps).
2134
2135 machine_reference(MachineBody,Ref) :-
2136 ? ( member(sees(_,R),MachineBody)
2137 ; member(uses(_,R),MachineBody) ),
2138 ? member(identifier(_,PrefixRef),R),
2139 split_prefix(PrefixRef,_,Ref).
2140 machine_reference(MachineBody,Ref) :-
2141 ? ( member(includes(_,R),MachineBody)
2142 ? ; member(extends(_,R),MachineBody)
2143 ; member(imports(_,R),MachineBody) ),
2144 ? member(machine_reference(_,PrefixRef,_),R),
2145 split_prefix(PrefixRef,_,Ref).
2146
2147 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2148 % refinements
2149 merge_refinement_and_abstraction(Name,Concrete,RefMachines,Result,Ein,Eout) :-
2150 memberchk(ref(abstraction,Abstraction),RefMachines),
2151 append_sections([sets,concrete_constants,concrete_variables],Abstraction,Concrete,M1),
2152 append_if_new(abstract_constants,Abstraction,M1,M2),
2153 get_section(properties,Abstraction,AbstractProperties),
2154 conjunct_to_section(properties,AbstractProperties,M2,M3),
2155 % now get current invariant Invariant and filter out gluing/linking invariant
2156 % (the linking invariant talks about variables which no longer exist; hence we cannot check it anymore)
2157 select_section(invariant,Invariant,FullConcreteInvariant,M3,M4),
2158 write_section(linking_invariant,LinkingInvariant,M4,Merged),
2159 % we now also copy from the abstraction those invariants which are still valid
2160 get_machine_sorted_variables(Abstraction,SortedAbsVars),
2161 get_machine_sorted_variables(Concrete,SortedConcrVars),
2162 assert_removed_abs_vars(SortedAbsVars,SortedConcrVars,Name),
2163 get_section(invariant,Abstraction,AbstractInvariant),
2164 filter_abstract_invariant(AbstractInvariant,SortedConcrVars,AbsInvariantStillValid),
2165 filter_linking_invariant(Invariant,LinkingInvariant,ConcreteInvariant),
2166 conjunct_predicates([AbsInvariantStillValid,ConcreteInvariant],FullConcreteInvariant),
2167 propagate_abstract_operations(Abstraction,Merged,RefMachines,Result,Ein,Eout).
2168 merge_refinement_and_abstraction(_,Machine,_,Machine,Errors,Errors).
2169
2170 :- use_module(probsrc(bsyntaxtree), [same_id/3]).
2171 assert_removed_abs_vars([],_,_).
2172 assert_removed_abs_vars([TID1|H],[],Name) :- !,
2173 assert_abstract_variable_removed_in(Name,TID1),
2174 assert_removed_abs_vars(H,[],Name).
2175 assert_removed_abs_vars([TID1|T1],[TID2|T2],Name) :- same_id(TID1,TID2,_),!,
2176 assert_removed_abs_vars(T1,T2,Name).
2177 assert_removed_abs_vars([TID1|T1],[TID2|T2],Name) :- TID1 @< TID2,!,
2178 assert_abstract_variable_removed_in(Name,TID1),
2179 assert_removed_abs_vars(T1,[TID2|T2],Name).
2180 assert_removed_abs_vars([TID1|T1],[_|T2],Name) :- % TID2 added in Name
2181 assert_removed_abs_vars([TID1|T1],T2,Name).
2182
2183
2184 assert_abstract_variable_removed_in(Name,TID) :-
2185 get_texpr_id(TID,ID),
2186 ajoin(['Variable ',ID,' removed in refinement machine: '],Msg),
2187 add_debug_message(bmachine_construction,Msg,Name,TID),
2188 assertz(abstract_variable_removed_in(ID,Name,TID)).
2189
2190
2191 % append sections from abstract machine to concrete machine:
2192 append_sections(Sections,AbsMachine,Old,New) :-
2193 expand_shortcuts(Sections,AllSections),
2194 append_sections2(AllSections,AbsMachine,Old,New).
2195 append_sections2([],_,M,M).
2196 append_sections2([Section|Rest],AbsMachine,Old,New) :-
2197 get_section(Section,AbsMachine,Content),
2198 append_to_section3(Section,Content,Old,Inter),
2199 append_sections2(Rest,AbsMachine,Inter,New).
2200
2201 append_to_section3(Section,Content,Old,Inter) :- section_can_have_duplicates(Section),!,
2202 append_to_section_and_remove_dups(Section,Content,Old,Inter).
2203 append_to_section3(Section,Content,Old,Inter) :- append_to_section(Section,Content,Old,Inter).
2204
2205 :- assert_must_succeed((create_machine(abs,EA), create_machine(conc,EB),
2206 write_section(abstract_constants,[b(identifier(x),integer,[some_info])],EA,A),
2207 write_section(abstract_constants,[b(identifier(x),integer,[other_info]),
2208 b(identifier(y),integer,[info])],EB,B),
2209 append_if_new(abstract_constants,A,B,ResultM),
2210 get_section(abstract_constants,ResultM,ResultConst),
2211 ResultConst==[b(identifier(x),integer,[other_info]),
2212 b(identifier(y),integer,[info])]
2213 )).
2214
2215 append_if_new(Section,Machine,In,Out) :-
2216 get_section(Section,Machine,Content),
2217 select_section(Section,Old,New,In,Out),
2218 get_texpr_ids(Old,ExistingIds),
2219 exclude(is_in_existing_ids(ExistingIds),Content,NewElements),
2220 append(Old,NewElements,New).
2221 is_in_existing_ids(ExistingIds,TId) :-
2222 get_texpr_id(TId,Id),
2223 memberchk(Id,ExistingIds).
2224
2225 % filter linking and concrete invariant
2226 filter_linking_invariant(Invariant,Linking,Concrete) :-
2227 split_conjuncts(Invariant,Predicates),
2228 split_list(contains_abstraction_refs,Predicates,Linkings,Concretes),
2229 conjunct_predicates(Linkings,Linking),
2230 conjunct_predicates(Concretes,Concrete).
2231
2232
2233 % contains_abstraction_refs can be used on predicates of the current machine: the abstraction info field has been computed for this machine
2234 contains_abstraction_refs(TExpr) :-
2235 syntaxtraversion(TExpr,_,_,Infos,Subs,_),
2236 ( memberchk(abstraction,Infos) % This info field comes from the last argument of visibility/6
2237 -> true
2238 ? ; member(Sub,Subs),
2239 contains_abstraction_refs(Sub)).
2240
2241 % Determine which part of the abstract invariant can be imported into the refinement machine
2242 % TODO: should this be applied to WHILE loop INVARIANTS?
2243 filter_abstract_invariant(AbsInvariant,SortedConcrVars,ConcreteInv) :-
2244 split_conjuncts(AbsInvariant,Predicates),
2245 filter_abs_invs(Predicates,SortedConcrVars,Concretes),
2246 conjunct_predicates(Concretes,ConcreteInv). %, print('COPY: '), translate:print_bexpr(Concrete),nl.
2247 :- use_module(translate,[translate_bexpression/2]).
2248
2249 filter_abs_invs([],_,[]).
2250 filter_abs_invs([TExpr|TInv],SortedConcrVars,Res) :-
2251 ? contains_abstract_variables2(SortedConcrVars,TExpr,Cause),!,
2252 (silent_mode(on) -> true
2253 ; translate_bexpression(Cause,ID),
2254 ajoin(['Discarding abstract INVARIANT (requires variable `',ID,'`): '],Msg),
2255 add_message(bmachine_construction,Msg,TExpr,Cause)
2256 ),
2257 (adapt_invariant(SortedConcrVars,TExpr,NewTExpr)
2258 -> Res = [NewTExpr|TRes],
2259 add_message(bmachine_construction,'Replaced abstract INVARIANT by: ',NewTExpr,Cause)
2260 ; Res=TRes
2261 ),
2262 filter_abs_invs(TInv,SortedConcrVars,TRes).
2263 filter_abs_invs([TExpr|TInv],SortedConcrVars,[TExpr|TRes]) :-
2264 filter_abs_invs(TInv,SortedConcrVars,TRes).
2265
2266 contains_abstract_variables2(SortedConcrVars,TExpr,Cause) :-
2267 syntaxtraversion(TExpr,Expr,Type,Infos,Subs,_),
2268 ( memberchk(loc(_,_Mch,abstract_variables),Infos) % are there other things that pose problems: abstract_constants ?
2269 -> %print('Abs: '),translate:print_bexpr(TExpr),nl, print(SortedConcrVars),nl,
2270 Cause=TExpr,
2271 \+ ord_member_nonvar_chk(b(Expr,Type,_),SortedConcrVars) % otherwise variable is re-introduced with same type
2272 % in some Event-B models: VARIABLES keyword is used and in refinement VARIABLES are re-listed
2273 % TO DO: check what happens when variable not immediately re-introduced
2274 ? ; member(Sub,Subs),
2275 contains_abstract_variables2(SortedConcrVars,Sub,Cause)
2276 ).
2277
2278 % try and keep part of invariant, e.g., if f:ABS-->Ran translate to f: TYPE +-> Ran
2279 adapt_invariant(SortedConcrVars,b(member(LHS,RHS),pred,I),b(member(LHS,NewRHS),pred,I)) :-
2280 \+ contains_abstract_variables2(SortedConcrVars,LHS,_),
2281 adapt_to_concrete_superset(RHS,SortedConcrVars,NewRHS),
2282 \+ get_texpr_expr(NewRHS,typeset). % not really useful
2283
2284 adapt_to_concrete_superset(b(E,Type,Info),SortedConcrVars,b(NewE,Type,Info)) :-
2285 adapt_super2(E,SortedConcrVars,NewE). % TODO: adapt info fields?
2286 adapt_to_concrete_superset(b(_E,Type,_Info),_SortedConcrVars,b(typeset,Type,[])).
2287 % Range of function remains concrete, Domain is abstract and no longer available:
2288 adapt_super2(PFUN,SortedConcrVars,partial_function(NewDom,RAN)) :-
2289 is_fun(PFUN,partial,DOM,RAN),
2290 \+ contains_abstract_variables2(SortedConcrVars,RAN,_),
2291 adapt_to_concrete_superset(DOM,SortedConcrVars,NewDom).
2292 adapt_super2(TFUN,SortedConcrVars,partial_function(NewDom,RAN)) :-
2293 is_fun(TFUN,total,DOM,RAN),
2294 \+ contains_abstract_variables2(SortedConcrVars,RAN,_),
2295 adapt_to_concrete_superset(DOM,SortedConcrVars,NewDom).
2296 % Domain of function remains concrete, Range is abstract and no longer available:
2297 adapt_super2(PFUN,SortedConcrVars,partial_function(DOM,NewRan)) :-
2298 is_fun(PFUN,partial,DOM,RAN),
2299 \+ contains_abstract_variables2(SortedConcrVars,DOM,_),
2300 adapt_to_concrete_superset(RAN,SortedConcrVars,NewRan).
2301 adapt_super2(TFUN,SortedConcrVars,total_function(DOM,NewRan)) :-
2302 is_fun(TFUN,total,DOM,RAN),
2303 \+ contains_abstract_variables2(SortedConcrVars,DOM,_),
2304 adapt_to_concrete_superset(RAN,SortedConcrVars,NewRan).
2305 adapt_super2(FUN,SortedConcrVars,partial_function(NewDom,NewRan)) :-
2306 is_fun(FUN,_,DOM,RAN),
2307 adapt_to_concrete_superset(DOM,SortedConcrVars,NewDom),
2308 adapt_to_concrete_superset(RAN,SortedConcrVars,NewRan).
2309 % TODO: more cases, intersection(ABS,CONCR) -> CONCR, cartesian_product
2310
2311 is_fun(partial_function(DOM,RAN),partial,DOM,RAN).
2312 is_fun(partial_injection(DOM,RAN),partial,DOM,RAN).
2313 is_fun(partial_surjection(DOM,RAN),partial,DOM,RAN).
2314 is_fun(partial_bijection(DOM,RAN),partial,DOM,RAN).
2315 is_fun(total_function(DOM,RAN),total,DOM,RAN).
2316 is_fun(total_injection(DOM,RAN),total,DOM,RAN).
2317 is_fun(total_surjection(DOM,RAN),total,DOM,RAN).
2318 is_fun(total_bijection(DOM,RAN),total,DOM,RAN).
2319
2320 % ---------------------
2321
2322 get_machine_sorted_variables(Machine,SortedAllVars) :-
2323 get_section(abstract_variables,Machine,AbsVars),
2324 get_section(concrete_variables,Machine,ConcVars),
2325 append(ConcVars,AbsVars,AllVars),
2326 sort(AllVars,SortedAllVars).
2327
2328 split_conjuncts(Expr,List) :-
2329 split_conjuncts2(Expr,List,[]).
2330 split_conjuncts2(Expr) -->
2331 {get_texpr_expr(Expr,conjunct(A,B)),!},
2332 split_conjuncts2(A),
2333 split_conjuncts2(B).
2334 split_conjuncts2(Expr) --> [Expr].
2335
2336 % copy the abstract operations or re-use their preconditions
2337 % TODO: think about copying Initialisation?
2338 propagate_abstract_operations(Abstract,Concrete,RefMachines,Result,Ein,Eout) :-
2339 get_section(promoted,Abstract,APromoted),
2340 get_section(operation_bodies,Abstract,ABodies),
2341 % signature: select_section(SecName,OldContent,NewContent,OldMachine,NewMachine)
2342 select_section(promoted,CPromotedIn,CPromotedOut,Concrete,Concrete2),
2343 select_section(operation_bodies,CBodiesIn,CBodiesOut,Concrete2,Result),
2344 propagate_aops(APromoted,ABodies,RefMachines,CPromotedIn,CBodiesIn,CPromotedOut,CBodiesOut,Ein,Eout).
2345 propagate_aops([],_ABodies,_RefMachines,CPromoted,CBodies,CPromoted,CBodies,Errors,Errors).
2346 propagate_aops([APromoted|ApRest],ABodies,RefMachines,CPromotedIn,CBodiesIn,CPromotedOut,CBodiesOut,Ein,Eout) :-
2347 get_operation(APromoted,ABodies,AbstractOp),
2348 def_get_texpr_id(APromoted,op(APromotedOpName)),
2349 copy_texpr_wo_info(APromoted,CProm),
2350 ? ( member(CProm,CPromotedIn) ->
2351 debug_format(19,'Refining promoted abstract operation ~w to refinement machine.~n',[APromotedOpName]),
2352 extract_concrete_preconditions(AbstractOp,RefMachines,Pre),
2353 change_operation(APromoted,ConcreteOpOld,ConcreteOpNew,CBodiesIn,CBodiesRest),
2354 add_precondition(Pre,ConcreteOpOld,ConcreteOpNew), % propagate PRE down to concrete operation
2355 CPromotedIn = CPromotedRest,
2356 Ein = E1
2357 % TO DO: do not copy if event is refined at least once with renaming !
2358 ; is_refined_by_some_event(APromotedOpName,CPromotedIn,ConcreteOpName) ->
2359 debug_format(19,'Not copying abstract operation ~w to refinement machine, as it is refined by ~w.~n',[APromotedOpName,ConcreteOpName]),
2360 CPromotedRest=CPromotedIn, CBodiesRest=CBodiesIn,
2361 E1=Ein
2362 ;
2363 debug_format(19,'Copying abstract operation ~w to refinement machine, as it is not refined.~n',[APromotedOpName]),
2364 % TO DO: check that this is also the right thing to do for Atelier-B Event-B
2365 % TO DO: check that the variables are also still there
2366 check_copied_operation(APromoted,AbstractOp,RefMachines,Ein,E1),
2367 append(CPromotedIn,[APromoted],CPromotedRest),
2368 append(CBodiesIn,[AbstractOp],CBodiesRest)
2369 ),
2370 propagate_aops(ApRest,ABodies,RefMachines,CPromotedRest,CBodiesRest,CPromotedOut,CBodiesOut,E1,Eout).
2371
2372 is_refined_by_some_event(AbstractName,CPromotedList,ConcreteName) :-
2373 ? member(TID,CPromotedList),
2374 get_texpr_info(TID,Infos),
2375 memberchk(refines_operation(AbstractName),Infos),
2376 def_get_texpr_id(TID,ConcreteName).
2377
2378 get_operation(TId,Bodies,Operation) :-
2379 select_operation(TId,Bodies,Operation,_BodiesRest).
2380 change_operation(TId,OldOp,NewOp,OldBodies,[NewOp|NewBodies]) :-
2381 select_operation(TId,OldBodies,OldOp,NewBodies).
2382 select_operation(TId,Bodies,Operation,BodiesRest) :-
2383 copy_texpr_wo_info(TId,OpId),
2384 get_texpr_expr(Operation,operation(OpId,_,_,_)),
2385 ? select(Operation,Bodies,BodiesRest),!.
2386
2387 extract_concrete_preconditions(Op,RefMachines,FPre) :-
2388 extract_preconditions_op(Op,Pre),
2389 extract_op_arguments(Op,Args),
2390 conjunction_to_list(Pre,Pres),
2391 % todo: check the "machine" parameter
2392 visible_env(machine,operation_bodies,RefMachines,Env1,_Errors,[]),
2393 store_variables(Args,Env1,Env),
2394 filter_predicates_with_unknown_identifiers(Pres,Env,FPres),
2395 conjunct_predicates(FPres,FPre).
2396
2397 extract_op_arguments(Op,Params) :-
2398 get_texpr_expr(Op,operation(_,_,Params,_)).
2399
2400 extract_preconditions_op(OpExpr,Pre) :-
2401 get_texpr_expr(OpExpr,operation(_,_,_,Subst)),
2402 extract_preconditions(Subst,Pres,_),
2403 conjunct_predicates(Pres,Pre).
2404 extract_preconditions(TExpr,Pres,Inner) :-
2405 get_texpr_expr(TExpr,Expr),
2406 extract_preconditions2(Expr,TExpr,Pres,Inner).
2407 extract_preconditions2(precondition(Pre,Subst),_,[Pre|Pres],Inner) :- !,
2408 extract_preconditions(Subst,Pres,Inner).
2409 extract_preconditions2(block(Subst),_,Pres,Inner) :- !,
2410 extract_preconditions(Subst,Pres,Inner).
2411 extract_preconditions2(_,Inner,[],Inner).
2412
2413 :- use_module(btypechecker,[prime_atom0/2]).
2414 filter_predicates_with_unknown_identifiers([],_Env,[]).
2415 filter_predicates_with_unknown_identifiers([Pred|Prest],Env,Result) :-
2416 ( find_unknown_identifier(Pred,Env,_Id) ->
2417 !,Result = Rrest
2418 ;
2419 Result = [Pred|Rrest]),
2420 filter_predicates_with_unknown_identifiers(Prest,Env,Rrest).
2421 find_unknown_identifier(Pred,Env,Id) :-
2422 get_texpr_id(Pred,Id),!,
2423 \+ env_lookup_type(Id,Env,_),
2424 (atom(Id),prime_atom0(UnprimedId,Id)
2425 -> % we have an identifier with $0 at end
2426 \+ env_lookup_type(UnprimedId,Env,_) % check unprimed identifier also unknown
2427 ; true).
2428 find_unknown_identifier(Pred,Env,Id) :-
2429 syntaxtraversion(Pred,_,_,_,Subs,Names),
2430 store_variables(Names,Env,Subenv),
2431 find_unknown_identifier_l(Subs,Subenv,Id).
2432 find_unknown_identifier_l([S|_],Env,Id) :-
2433 find_unknown_identifier(S,Env,Id),!.
2434 find_unknown_identifier_l([_|Rest],Env,Id) :-
2435 find_unknown_identifier_l(Rest,Env,Id).
2436
2437 :- use_module(library(ordsets),[ord_union/3]).
2438 % we add a precondition to an existing operation
2439 % Note: we need to update the reads info computed by the type checker (compute_accessed_vars_infos_for_operation)
2440 add_precondition(b(truth,_,_),Old,New) :- !, Old=New.
2441 add_precondition(Pre,b(Old,T,I),b(New,T,I2)) :-
2442 Old=operation(Id,Res,Params,Subst),
2443 New=operation(Id,Res,Params,NewSubst),
2444 extract_preconditions(Subst,OldPres,Inner),
2445 conjunct_predicates([Pre|OldPres],NewPre),
2446 create_texpr(precondition(NewPre,Inner),subst,[],NewSubst),
2447 ? (select(reads(OldReads),I,I1) % we do not have to update modifies(.), non_det_modifies(.), reads_locals(.),...
2448 -> I2=[reads(NewReads)|I1],
2449 get_texpr_ids(Params,Ignore),
2450 find_identifier_uses(Pre,Ignore,PreUsedIds),
2451 ord_union(PreUsedIds,OldReads,NewReads)
2452 ; add_internal_error('No reads info for operation: ',add_precondition(Pre,b(Old,T,I),b(New,T,I2))),
2453 I2=I).
2454
2455
2456
2457 check_copied_operation(OpRef,Op,RefMachines,Ein,Eout) :-
2458 % todo: check the "refinement" parameter
2459 visible_env(refinement,operation_bodies,RefMachines,Env1,_Errors,[]),
2460 get_texpr_id(OpRef,OpId),get_texpr_type(OpRef,OpType),
2461 env_store(OpId,OpType,[],Env1,Env),
2462 findall(U, find_unknown_identifier(Op,Env,U), Unknown1),
2463 ( Unknown1=[] -> Ein=Eout
2464 ;
2465 sort(Unknown1,Unknown),
2466 op(OpName) = OpId,
2467 join_ids(Unknown,IdList),
2468 (Unknown = [_] -> Plural=[]; Plural=['s']),
2469 append([['Operation ',OpName,
2470 ' was copied from abstract machine but the identifier'],
2471 Plural,
2472 [' '],
2473 IdList,
2474 [' cannot be seen anymore']],Msgs),
2475 ajoin(Msgs,Msg), Ein = [error(Msg,none)|Eout]
2476 ).
2477 join_ids([I],[Msg]) :- !,opname(I,Msg).
2478 join_ids([A|Rest],[Msg,','|Mrest]) :- opname(A,Msg),join_ids(Rest,Mrest).
2479 opname(op(Id),Id) :- !.
2480 opname(Id,Id).
2481
2482 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2483 % split an identifier into a (possible empty) prefix and the name itself
2484 % e.g. split_prefix('path.to.machine', 'path.to', 'machine').
2485 split_prefix(Term,Prefix,Main) :-
2486 one_arg_term(Functor,Arg,Term),!,
2487 one_arg_term(Functor,MArg,Main),
2488 split_prefix(Arg,Prefix,MArg).
2489 split_prefix(PR,Prefix,Main) :-
2490 safe_atom_chars(PR,Chars,split_prefix1),
2491 split_prefix2(Chars,Chars,[],CPrefix,CMain),
2492 safe_atom_chars(Main,CMain,split_prefix2),
2493 safe_atom_chars(Prefix,CPrefix,split_prefix3).
2494 split_prefix2([],Main,_,[],Main).
2495 split_prefix2([C|Rest],Previous,PrefBefore,Prefix,Main) :-
2496 ( C='.' ->
2497 append(PrefBefore,RestPrefix,Prefix),
2498 split_prefix2(Rest,Rest,[C],RestPrefix,Main)
2499 ;
2500 append(PrefBefore,[C],NextPref),
2501 split_prefix2(Rest,Previous,NextPref,Prefix,Main)).
2502
2503 rawmachine_section(Elem,List,Result) :- %
2504 functor(Pattern,Elem,2),
2505 arg(2,Pattern,Result),
2506 ? select(Pattern,List,Rest),!,
2507 (functor(Pattern2,Elem,2),member(Pattern2,Rest)
2508 -> arg(1,Pattern2,Pos),
2509 add_error(bmachine_construction,'Multiple sections for: ',Elem,Pos)
2510 ; true).
2511
2512 optional_rawmachine_section(Elem,List,Default,Result) :-
2513 ( rawmachine_section(Elem,List,Result1) -> true
2514 ; Result1=Default),
2515 Result1=Result.
2516
2517 one_arg_term(Functor,Arg,Term) :- %print(one_arg_term(Functor,Arg,Term)),nl,
2518 functor(Term,Functor,1),arg(1,Term,Arg).
2519
2520 % check if a rawmachine section list has a given section
2521 rawmachine_section_exists(Elem,List) :- %
2522 functor(Pattern,Elem,2),
2523 ? (member(Pattern,List) -> true).
2524
2525 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2526 % visibility rules
2527
2528 % the visibility/5 predicate declares what a part of a machine can see
2529 % visibility(MType, Scope, Section, Access, Info) means:
2530 % In a machine of type MType (machine, refinement, implementation),
2531 % an expression in a Section (like invariant) can see
2532 % the identifiers in the Access sections. Access is a list of
2533 % sections, where shortcuts are allowed (see shortcut/2, e.g., shortcut(operations,[unpromoted,promoted]).).
2534 % Scope defines where (in relation to the Section)
2535 % the section in Access are (local: same machine, included: in an
2536 % included machine, etc.)
2537 % Info is a list of additional information that is added to each
2538 % identifier in the environment to build up. E.g. in an operation
2539 % definition, constants are marked readonly.
2540 visibility(machine, local, constraints, [parameters],[]).
2541 visibility(machine, local, includes, [parameters,sets,constants],[]).
2542 visibility(machine, local, properties, [sets,constants],[]).
2543 visibility(machine, local, invariant, [parameters,sets,constants,variables],[]).
2544 visibility(machine, local, operation_bodies, [parameters,sets,constants],[readonly]).
2545 visibility(machine, local, operation_bodies, [operations],Info) :- Info =[readonly,dontcall].
2546 % an operation to be readonly: means we cannot assign to it; but the operation itself can change variables
2547 % for allow_operation_calls_in_expr=true we check that operation is inquiry in type checker
2548 % (get_preference(allow_operation_calls_in_expr,true) -> Info = [inquiry]
2549 % ; Info =[readonly,dontcall] ). % we check in btype(operation_call_in_expr)
2550 visibility(machine, local, operation_bodies, [variables],[]).
2551 ?visibility(machine, local, initialisation, Access,[not_initialised|Info]) :- visibility(machine,local,operation_bodies,Access,Info).
2552
2553 visibility(machine, Scope, assertions, [Allow],[inquiry|DC]) :-
2554 (Scope = local -> Allow=operations, DC=[dontcall] ; Allow=promoted, DC=[]),
2555 get_preference(allow_operation_calls_in_expr,true). % if we allow calling operations in expressions
2556 visibility(machine, Scope, invariant, [promoted],[inquiry]) :-
2557 Scope \= local, % do not allow calling local operations in invariant; their correctness relies on the invariant
2558 get_preference(allow_operation_calls_in_expr,true).
2559
2560 visibility(machine, included, properties, [sets,constants],[]).
2561 visibility(machine, included, invariant, [sets,constants,variables],[]).
2562 visibility(machine, included, operation_bodies, [sets,constants,variables],[readonly]).
2563 visibility(machine, included, operation_bodies, [promoted],Info) :- Info = [readonly].
2564 % for allow_operation_calls_in_expr=true we check that operation is inquiry in type checker
2565 % (get_preference(allow_operation_calls_in_expr,true) -> Info = [inquiry] ; Info=[readonly]).
2566 %visibility(machine, included, initialisation, [sets,constants,variables,promoted],[readonly]).
2567 visibility(machine, included, initialisation, [sets,constants,promoted],[readonly]).
2568 visibility(machine, included, initialisation, [variables],Info) :-
2569 (get_preference(allow_overriding_initialisation,true)
2570 -> Info = [] % allow overriding INITIALISATION / making it more concrete
2571 ; Info = [readonly]). % default Atelier-B semantics
2572
2573 visibility(machine, used, properties, [sets,constants],[]).
2574 visibility(machine, used, invariant, [parameters,sets,constants,variables],[]).
2575 visibility(machine, used, operation_bodies, [parameters,sets,constants,variables],[readonly]).
2576 visibility(machine, used, initialisation, [parameters,sets,constants,variables],[readonly]).
2577 visibility(machine, used, operation_bodies, [operations],[inquiry]) :-
2578 get_preference(allow_operation_calls_for_uses,true). %% added by leuschel, allowed in Schneider Book
2579 % but not allowed by Atelier-B; see test 2135
2580
2581 visibility(machine, seen, includes, [sets,constants],[]).
2582 visibility(machine, seen, properties, [sets,constants],[]).
2583 visibility(machine, seen, invariant, [sets,constants],[]).
2584 visibility(machine, seen, operation_bodies, [sets,constants,variables],[readonly]).
2585 visibility(machine, seen, initialisation, [sets,constants,variables],[readonly]).
2586 visibility(machine, seen, operation_bodies, [operations],[inquiry]). %% added by leuschel, allow query operation
2587
2588 visibility(refinement, local, Section, Access, Info) :-
2589 Section \= assertions, % assertions are handled below
2590 ? visibility(machine, local, Section, Access, Info).
2591
2592 visibility(refinement, abstraction, includes, [sets,concrete_constants],[]).
2593 visibility(refinement, abstraction, properties, [sets,constants],[]).
2594 visibility(refinement, abstraction, invariant, [sets,constants,concrete_variables],[]).
2595 visibility(refinement, abstraction, invariant, [abstract_variables],[abstraction]).
2596 visibility(refinement, abstraction, operation_bodies, [sets,concrete_constants],[readonly]).
2597 visibility(refinement, abstraction, operation_bodies, [concrete_variables],[]).
2598
2599 visibility(refinement, included, properties, [sets,constants],[]).
2600 visibility(refinement, included, invariant, [sets,constants,variables],[]).
2601 visibility(refinement, included, operation_bodies, [sets,constants,variables,promoted],[re]). % What is re ??? TO DO: investigate
2602
2603 visibility(refinement, seen, includes, [sets,constants],[]).
2604 visibility(refinement, seen, properties, [sets,constants],[]).
2605 visibility(refinement, seen, invariant, [sets,constants],[]).
2606 visibility(refinement, seen, operation_bodies, [sets,constants,variables],[readonly]).
2607 visibility(refinement, seen, operation_bodies, [operations],[inquiry]).
2608
2609 visibility(refinement, Ref, initialisation, Access, [not_initialised|Info]) :-
2610 ? visibility(refinement,Ref,operation_bodies,Access,Info).
2611
2612 % assertions have same visibility as invariant
2613 visibility(MType, Ref, assertions, Part, Access) :-
2614 ? visibility(MType,Ref,invariant,Part,Access).
2615
2616 visibility(implementation, Ref, Section, Part, Access) :-
2617 visibility(refinement, Ref, Section, Part, Access).
2618 visibility(implementation, local, values_expression, [concrete_constants,sets],[]). % seems to have no effect (yet); see ArrayValuationAImp
2619 visibility(implementation, included, values_expression, [concrete_constants,sets],[]).
2620 visibility(implementation, seen, values_expression, [concrete_constants,sets],[]).
2621 visibility(implementation, abstraction,values_expression, [concrete_constants,sets],[]).
2622
2623 % For predicates over pre- and post-states
2624 visibility(MType, Rev, prepost, Access, Info) :-
2625 ? visibility(MType, Rev, invariant, Access, Info).
2626 visibility(MType, Rev, prepost, Access, [primed,poststate|Info]) :-
2627 ? visibility(MType, Rev, invariant, Access, Info).
2628
2629 % add error messages for some common mistakes (access to parameters in the properties)
2630 visibility(machine, local, properties, [parameters], [error('a parameter cannot be accessed in the PROPERTIES section')]).
2631 % the following rule should be helpful for the user, but additionally it also
2632 % provides a mechanism to re-introduce abstract variables in the INVARIANT
2633 % section of a while loop (to enable this, an identifier is also marked with "abstraction")
2634 % in the predicate allow_access_to_abstract_var
2635 visibility(refinement, abstraction, operation_bodies, [abstract_variables],
2636 [error('illegal access to an abstract variable in an operation'),abstraction]).
2637 visibility(refinement, abstraction, operation_bodies, [abstract_constants],
2638 [error('illegal access to an abstract constant in an operation (only allowed in WHILE INVARIANT or ASSERT)'),abstraction]).
2639
2640
2641 % lookups up all identifier sections that are accessible from
2642 % the given section, removes all shortcuts and removes
2643 % duplicate entries
2644 %
2645 % Returns a list of vis(Section,Info) where Section is the
2646 % identifier section that can be seen with Info as a list
2647 % of additional information
2648 expanded_visibility(MType, Ref, Part, Access) :-
2649 findall(vis(Section,Infos),
2650 ( visibility(MType,Ref,Part,Sections1,Infos),
2651 expand_shortcuts(Sections1,Sections),
2652 member(Section,Sections)),
2653 Access1),
2654 sort(Access1,Access).
2655 %format('MType=~w, Ref=~w, Part=~w~n Vis=~w~n',[MType,Ref,Part,Access]).
2656
2657 % visible_env/6 creates a type environment for a certain
2658 % part of a machine by looking up which identifier should
2659 % be visible from there and what additional information should
2660 % be added (e.g. to restrict access to read-only)
2661 %
2662 % The visibility/6 facts are used to define which identifier are visible
2663 %
2664 % MType: machine type (machine, refinement, ...)
2665 % Part: part of the machine for which the environment should be created
2666 % RefMachines: referred machines that are already typed
2667 % Env: The created environment
2668 % Errors: errors might be added if multiple variables with the same identifier
2669 % are declared
2670 visible_env(MType, Part, RefMachines, Env, Err_in, Err_out) :-
2671 env_empty(Init),
2672 visible_env(MType, Part, RefMachines, Init, Env, Err_in, Err_out).
2673 % visible_env/7 is like visible_env/6, but an initial environment
2674 % can be given in "In"
2675 visible_env(MType, Part, RefMachines, In, Out, Err_in, Err_out) :-
2676 foldl(visible_env2(MType,Part),RefMachines,In/Err_in,Out/Err_out).
2677 visible_env2(MType,Part,extended_local_ref(Machine),InEnvErr,OutEnvErr) :- !,
2678 Scope=local,
2679 get_machine_name(Machine,MName),
2680 %format('adding identifiers from machine ~w for scope ~w~n',[MName,Scope]),
2681 get_section(definitions,Machine,Defs),
2682 foldl(env_add_def(MName),Defs,InEnvErr,InEnvErr2),
2683 (bmachine:additional_configuration_machine(_MchName,AddMachine),
2684 get_section(definitions,AddMachine,AdditionalDefs)
2685 -> foldl(env_add_def(MName),AdditionalDefs,InEnvErr2,InterEnvErr)
2686 ; InterEnvErr = InEnvErr2
2687 ),
2688 expanded_visibility(MType, Scope, Part, Access),
2689 foldl(create_vis_env(Scope,MName,Machine),Access,InterEnvErr,OutEnvErr).
2690 visible_env2(MType,Part,ref(Scope,Machine),InEnvErr,OutEnvErr) :-
2691 get_machine_name(Machine,MName),
2692 %format('adding identifiers from machine ~w for scope ~w~n',[MName,Scope]),
2693 ( Scope == local ->
2694 get_section(definitions,Machine,Defs),
2695 %nl,print(adding_defs(Defs)),nl,nl,
2696 foldl(env_add_def(MName),Defs,InEnvErr,InterEnvErr)
2697 ;
2698 InEnvErr=InterEnvErr),
2699 expanded_visibility(MType, Scope, Part, Access),
2700 foldl(create_vis_env(Scope,MName,Machine),Access,InterEnvErr,OutEnvErr).
2701 env_add_def(MName,definition_decl(Name,PType,Pos,Params,Body,_Deps),InEnvErr,OutEnvErr) :-
2702 Type = definition(PType,Params,Body),
2703 Info = [nodeid(Pos),loc(local,MName,definitions)],
2704 create_texpr(identifier(Name),Type,Info,TExpr),
2705 add_unique_variable(TExpr,InEnvErr,OutEnvErr),!.
2706 env_add_def(MName,Def,EnvErr,EnvErr) :-
2707 add_internal_error('Cannot deal with DEFINITION: ',env_add_def(MName,Def)).
2708
2709 create_vis_env(Scope,MName,IDS,vis(Section,Infos),InEnvErr,OutEnvErr) :-
2710 get_section(Section,IDS,Identifiers1),
2711 % get_texpr_ids(Identifiers1,II),format('Got identifiers for ~w:~w = ~w~n',[MName,Section,II]),
2712 (Section=freetypes
2713 -> generate_free_type_ids(Identifiers1,Identifiers2)
2714 ; Identifiers2=Identifiers1),
2715 maplist(add_infos_to_identifier([loc(Scope,MName,Section)|Infos]),Identifiers2,Identifiers),
2716 l_add_unique_variables(Identifiers,InEnvErr,OutEnvErr).
2717
2718 % optimized version of foldl(add_unique_variable,Identifiers,InEnvErr,OutEnvErr).
2719 l_add_unique_variables([],Env,Env).
2720 l_add_unique_variables([ID|T],InEnvErr,OutEnvErr) :-
2721 add_unique_variable(ID,InEnvErr,IntEnv),
2722 l_add_unique_variables(T,IntEnv,OutEnvErr).
2723
2724 % freetypes: generate IDs for Z freetype section
2725 % The classical B FREETYPE section is dealt with in another place (TODO: unify this)
2726 generate_free_type_ids([freetype(FTypeId,Cases)|T],[b(identifier(FTypeId),set(freetype(FTypeId)),[])|FT]) :- !,
2727 findall(b(identifier(CaseID),CaseType,[]),
2728 (member(case(CaseID,ArgType),Cases), gen_freecase_type(ArgType,FTypeId,CaseType)),
2729 FT, FT2),
2730 %write(generated_freetype_cases(FT)),nl,
2731 generate_free_type_ids(T,FT2).
2732 generate_free_type_ids(T,T).
2733
2734 gen_freecase_type(ArgType,FTypeId,Type) :- nonvar(ArgType), ArgType=constant(_),!, Type = freetype(FTypeId).
2735 gen_freecase_type(ArgType,FTypeId,set(couple(ArgType,freetype(FTypeId)))).
2736
2737 add_unique_variable(Var1,Old/Err_in,New/Err_out) :-
2738 optionally_rewrite_id(Var1,Var),
2739 get_texpr_id(Var,Id),
2740 get_texpr_type(Var,Type),
2741 get_texpr_info(Var,InfosOfNew),!,
2742 ( env_lookup_type(Id,Old,_) ->
2743 % we have a collision of two identifiers
2744 handle_collision(Var,Id,Type,Old,InfosOfNew,New,Err_in,Err_out)
2745 ;
2746 % no collision, just introduce the new identifier
2747 env_store(Id,Type,InfosOfNew,Old,New),
2748 %btypechecker:portray_env(New),nl,
2749 Err_in=Err_out
2750 ).
2751 add_unique_variable(Var,Env/Err,Env/Err) :- print(Var),nl,
2752 ( Var = b(definition(DEFNAME,_),_,INFO) ->
2753 add_error(add_unique_variable,'DEFINITION used in place of Identifier: ',DEFNAME,INFO)
2754 ; Var = b(description(Txt,_),_,INFO) ->
2755 add_error(add_unique_variable,'Unsupported @desc pragma: ',Txt,INFO)
2756 ;
2757 add_error(add_unique_variable,'Expected Identifier, but got: ',Var,Var)
2758 ).
2759
2760 add_infos_to_identifier(NewInfos,In,Out) :-
2761 add_texpr_infos(In,NewInfos,Out).
2762
2763 % get the ID of the variable, prime it if the infos contain "primed"
2764 optionally_rewrite_id(Var,NewVar) :-
2765 get_texpr_info(Var,InfosIn),
2766 ( selectchk(primed,InfosIn,InfosOut) ->
2767 get_texpr_id(Var,Id1),
2768 get_texpr_type(Var,Type),
2769 atom_concat(Id1,'\'',Id),
2770 create_texpr(identifier(Id),Type,InfosOut,NewVar)
2771 ;
2772 Var = NewVar).
2773
2774 :- use_module(translate,[translate_span/2]).
2775 % in case of a collision, we have three options:
2776 % - overwrite the old identifier,
2777 % - ignore the new identifier or
2778 % - generate an error message
2779 handle_collision(Var,Name,Type,OldEnv,InfosOfNew,NewEnv,Ein,Eout) :-
2780 env_lookup_infos(Name,OldEnv,InfosOfExisting),
2781 %btypechecker:portray_env(OldEnv),nl,
2782 ( collision_precedence(Name,InfosOfExisting,InfosOfNew) ->
2783 % this identifier should be ignored
2784 OldEnv = NewEnv,
2785 Ein = Eout
2786 ; collision_precedence(Name,InfosOfNew,InfosOfExisting) ->
2787 % the existing should be overwritten
2788 env_store(Name,Type,InfosOfNew,OldEnv,NewEnv),
2789 Ein = Eout
2790 ;
2791 % generate error and let the environment unchanged
2792 (Name = op(IName) -> Kind='Operation identifier'; Name=IName, Kind='Identifier'),
2793 get_texpr_pos(Var,Pos1),
2794 safe_get_info_pos(InfosOfExisting,Pos2),
2795 ( double_inclusion_allowed(Name,Pos1,Pos2,InfosOfExisting)
2796 -> %print(double_inclusion_of_id_allowed(Name,Type,Pos1,OldEnv,InfosOfExisting)),nl,
2797 OldEnv=NewEnv,
2798 Ein=Eout
2799 ; (better_pos(Pos2,Pos1), \+ better_pos(Pos1,Pos2)
2800 -> Pos = Pos2, translate_span(Pos1,PS1)
2801 ; Pos = Pos1,
2802 PS1='' % Pos1 is already part of error span
2803 ),
2804 translate_span(Pos2,PS2),
2805 translate_inclusion_path(InfosOfExisting,Path2),
2806 get_texpr_info(Var,Info1), translate_inclusion_path(Info1,Path1),
2807 %ajoin(['Identifier \'', IName, '\' declared twice at (Line:Col[:File]) ', PS1, Path1, ' and ', PS2, Path2],Msg),
2808 ajoin([Kind,' \'', IName, '\'', PS1, Path1, ' already declared at ', PS2, Path2],Msg),
2809 %format(user_error,'*** ~w~n',[Msg]),trace,
2810 Ein = [error(Msg,Pos)|Eout],
2811 OldEnv = NewEnv
2812 )
2813 ).
2814
2815
2816 % example identifier: %b(identifier(aa),integer,[loc(seen,M2,concrete_constants),readonly,usesee(M2,aa,seen),origin([included/M1]),nodeid(pos(18,2,2,11,2,13))])
2817
2818 % try and infer inclusion path of identifier from Infos
2819 translate_inclusion_path(Infos,Str) :- member(loc(How,Machine,Section),Infos),!,
2820 (member(origin(Path),Infos) -> get_origin_path(Path,T) ; T=[')']),
2821 ajoin([' (', How,' from ', Section, ' section of ', Machine |T],Str).
2822 translate_inclusion_path(_,'').
2823
2824 get_origin_path([How/Machine|T],[', ', How,' from ',Machine|TRes]) :- !,
2825 get_origin_path(T,TRes).
2826 get_origin_path(_,[')']).
2827
2828
2829 % SEE ISSUE PROB-403, test 1857
2830 % Correct behaviour related to multiple instantiation is specified in
2831 % B Reference Manual (AtelierB 4.2.1), 8.3 B Project/Instantiating and renaming.
2832 % => Constants and Sets defined in machines instantiated multiple times CAN be used in the including machine with their original (non-prefixed names).
2833 % Note: this code did lead to the constants being added multiple times; this has been fixed in concat_section_contents
2834 double_inclusion_allowed(Name,Pos1,Pos2,InfosOfExisting) :-
2835 %print(check_double_inclusion(Name,Pos1,Pos2,InfosOfExisting)),nl,
2836 Pos1==Pos2,
2837 %print(chk(InfosOfExisting)),nl,
2838 member(loc(LOC,_,Section),InfosOfExisting),
2839 %print(try(LOC,Section)),nl,
2840 section_can_be_included_multiple_times_nonprefixed(Section),
2841 % check that we are in a context of an included machine identifier:
2842 (inclusion_directive(LOC,Name,Pos2)
2843 -> true
2844 ; %LOC is probably local
2845 member(origin([INCL/_MACHINE|_]),InfosOfExisting),
2846 inclusion_directive(INCL,Name,Pos2)
2847 ).
2848
2849 inclusion_directive(included,_,_).
2850 inclusion_directive(used,_,_).
2851 inclusion_directive(seen,_,_). % imports ??
2852 inclusion_directive(abstraction,Name,Pos) :- % probably not allowed by Atelier-B
2853 (debug_mode(off) -> true
2854 ; add_message(bmachine_construction,'Allowing double inclusion from abstraction of: ',Name,Pos)).
2855
2856 section_can_be_included_multiple_times_nonprefixed(abstract_constants).
2857 section_can_be_included_multiple_times_nonprefixed(concrete_constants).
2858 section_can_be_included_multiple_times_nonprefixed(sets).
2859 section_can_be_included_multiple_times_nonprefixed(enumerated_sets).
2860 section_can_be_included_multiple_times_nonprefixed(enumerated_elements).
2861 section_can_be_included_multiple_times_nonprefixed(deferred_sets). % added 2.12.2022
2862 section_can_be_included_multiple_times_nonprefixed(constants). % shortcut
2863
2864
2865 % decide which position info is better: prefer info in main file (highlighting)
2866 :- use_module(bmachine,[b_get_main_filenumber/1]).
2867 better_pos(Pos,_) :- get_position_filenumber(Pos,Filenumber),
2868 b_get_main_filenumber(Filenumber).
2869 better_pos(_,none).
2870
2871 safe_get_info_pos(Info,Pos) :- (get_info_pos(Info,Pos) -> true ; Pos=none).
2872
2873 % collision_precedence/3 decides if the first variable takes
2874 % precedence over the second in case of a collision
2875 % the decision is made by the additional information of both
2876 % variables
2877 collision_precedence(_Name,PreferredVarInfos,DroppedVarInfos) :-
2878 % in case of a re-introduced variable from the abstraction,
2879 % we prefer the concrete variable to the abstract one.
2880 ? is_abstraction(DroppedVarInfos,PreferredVarInfos),!.
2881 collision_precedence(_Name,PreferredVarInfos,DroppedVarInfos) :-
2882 % We are checking an Event-B model with multi-level support
2883 % and have the same variable in two different refinement levels.
2884 % Then the one in the more refined module takes precedence
2885 member(level(L1),PreferredVarInfos),
2886 member(level(L2),DroppedVarInfos),
2887 % Level 0 is the abstract level, level 1 the first refinement, etc.
2888 L1 > L2,!.
2889 collision_precedence(Name,PreferredVarInfos,DroppedVarInfos) :-
2890 % A local definition takes precedence over a non-local identifier
2891 % TODO:
2892 member(loc(local,_DefMachine,definitions),PreferredVarInfos),
2893 member(loc(_,_VarMachine,Section),DroppedVarInfos),
2894 Section \= definitions,!,
2895 (preferences:get_preference(warn_if_definition_hides_variable,true)
2896 % default is true; we could also check clash_strict_checks
2897 -> get_id_kind(Section,HiddenIdKind),
2898 (get_info_pos(PreferredVarInfos,Pos1), Pos1 \= none,
2899 get_info_pos(DroppedVarInfos,Pos2), Pos2 \= none
2900 -> translate:translate_span(Pos1,Pos1Str), translate:translate_span(Pos2,Pos2Str),
2901 ajoin(['Warning: DEFINITION of ', Name, ' at ', Pos1Str,
2902 ' hides ',HiddenIdKind,' with same name at ', Pos2Str, '.'], Msg)
2903 ; ajoin(['Warning: DEFINITION of ', Name, ' hides ',HiddenIdKind,' with same name.'], Msg),
2904 Pos1 = unknown
2905 ),
2906 store_warning(Msg,Pos1) % TO DO: add position info
2907 ; true
2908 ).
2909 % TO DO: allow identical DEFINITIONS ?
2910
2911 % translate section name into a name for the identifier
2912 get_id_kind(abstract_constants,'constant').
2913 get_id_kind(concrete_constants,'constant').
2914 get_id_kind(parameters,'parameter').
2915 get_id_kind(deferred_sets,'deferred set').
2916 get_id_kind(enumerated_sets,'enumerated set').
2917 get_id_kind(enumerated_elements,'enumerated set element').
2918 get_id_kind(freetypes,'freetype').
2919 get_id_kind(promoted,'operation').
2920 % TODO: complete and use in other places
2921 get_id_kind(_SectionName,'variable').
2922
2923
2924 % is_abstraction/2 tries to find out if (in case of a name clash of
2925 % two variables) the second variable is just the re-introduced abstract
2926 % variable in a refinement.
2927 % InfosAbs is the list of information about the abstract variable
2928 % InfosConc is the list of information about the concrete variable
2929 is_abstraction(InfosAbs,InfosConc) :-
2930 % one variable is an abstract variable, introduced in the abstraction
2931 ? member(loc(abstraction,_,abstract_variables),InfosAbs),
2932 % the other is either an abstract or concrete variable,
2933 ? member(VarType,[abstract_variables,concrete_variables]),
2934 % introduced either locally or in an included machine
2935 ? member(Scope,[local,included]),
2936 ? member(loc(Scope,_,VarType),InfosConc).
2937 % and the same for constants:
2938 is_abstraction(InfosAbs,InfosConc) :-
2939 % one variable is an abstract variable, introduced in the abstraction
2940 member(loc(abstraction,_,abstract_constants),InfosAbs),
2941 % the other is either an abstract or concrete variable,
2942 member(VarType,[abstract_constants,concrete_constants]),
2943 % introduced either locally or in an included machine
2944 member(Scope,[local,included]),
2945 member(loc(Scope,_,VarType),InfosConc).
2946
2947 % shortcuts for sections, to ease the use of typical combinations of
2948 % sections
2949 shortcut(all_parameters,[parameters,internal_parameters]).
2950 shortcut(sets,[deferred_sets,enumerated_sets,enumerated_elements|T]) :-
2951 (animation_minor_mode(M), (M=z ; M=eventb)
2952 -> T = [freetypes]
2953 ; T = []). % The FREETYPES section in classical B is unfortunately dealt with differently and
2954 % we currently have errors if add the freetypes section here
2955 shortcut(constants,[abstract_constants,concrete_constants]).
2956 shortcut(variables,[abstract_variables,concrete_variables]).
2957 shortcut(operations,[unpromoted,promoted]).
2958 shortcut(identifiers,[all_parameters,sets,constants,variables,operations]).
2959
2960 expand_shortcuts(Sections,Expanded) :-
2961 foldl(expand_shortcut,Sections,Expanded,[]).
2962 expand_shortcut(Section,Sections,RSections) :-
2963 ( shortcut(Section,Expanded) ->
2964 foldl(expand_shortcut,Expanded,Sections,RSections)
2965 ; valid_section(Section) ->
2966 Sections = [Section|RSections]
2967 ;
2968 add_internal_error('invalid section',expand_shortcut(Section,Sections,RSections)),fail).
2969
2970 % find sections that can see given sections
2971 find_relevant_sections(RSecs,MTypes,Result) :-
2972 expand_shortcuts(RSecs,Sections),
2973 findall(R,
2974 ( member(MType,MTypes),
2975 visibility(MType,local,R,SAccess,_),
2976 expand_shortcuts(SAccess,Access),
2977 member(S,Sections),
2978 member(S,Access),
2979 valid_section(R)),
2980 Result1),
2981 sort(Result1,Result).
2982
2983
2984 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2985 % renaming
2986
2987 rename_relevant_sections(DefSecs,Renamings,Machine,New) :-
2988 find_relevant_sections(DefSecs,[machine],Relevant),
2989 rename_in_sections(Relevant,Renamings,Machine,New).
2990 rename_in_sections([],_,M,M).
2991 rename_in_sections([Section|Rest],Renamings,Old,New) :-
2992 select_section_texprs(Section,OTExprs,NTExprs,Old,Inter),
2993 rename_bt_l(OTExprs,Renamings,NTExprs),
2994 rename_in_sections(Rest,Renamings,Inter,New).
2995
2996 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2997 :- use_module(kernel_freetypes,[register_freetypes/1]).
2998 % cleaning up machine
2999 clean_up_machine(In,RefMachines,Out) :-
3000 extract_parameter_types([ref(local,In)|RefMachines],NonGroundExceptions),
3001 clean_up_machine2(NonGroundExceptions,In,Out).
3002 clean_up_machine2(NonGroundExceptions) -->
3003 get_section_content(enumerated_sets,Enum),
3004 get_section_content(enumerated_elements,Elems),
3005 {register_enumerated_sets(Enum,Elems)}, % register name of enumerated sets, e.g., to detect finite in ast_cleanup
3006 get_section_content(freetypes,Freetypes),
3007 {register_freetypes(Freetypes)}, % so that info is available in ast_cleanup for eval_set_extension
3008 clean_up_section(constraints,NonGroundExceptions),
3009 clean_up_section(properties,NonGroundExceptions),
3010 clean_up_section(invariant,NonGroundExceptions),
3011 clean_up_section(initialisation,NonGroundExceptions),
3012 clean_up_section(assertions,NonGroundExceptions),
3013 clean_up_section(operation_bodies,NonGroundExceptions).
3014 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
3015 :- if(environ(prob_safe_mode,true)).
3016 clean_up_section(Section,NonGroundExceptions,In,Out) :-
3017 select_section_texprs(Section,Old,New,In,Out),
3018 %format('Cleaning up and optimizing section ~w~n',[Section]), %maplist(check_ast,Old), % this will raise errors
3019 clean_up_l_with_optimizations(Old,NonGroundExceptions,New,Section),
3020 %format('Checking result of clean_up section ~w~n',[Section]),
3021 maplist(check_ast(true),New),
3022 formatsilent('Finished checking section ~w~n',[Section]).
3023 :- else.
3024 clean_up_section(Section,NonGroundExceptions,In,Out) :-
3025 % debug_stats(cleaning_up(Section)),
3026 select_section_texprs(Section,Old,New,In,Out),
3027 clean_up_l_with_optimizations(Old,NonGroundExceptions,New,Section).
3028 :- endif.
3029
3030 get_section_content(SecName,SectionContent,Mch,Mch) :- get_section(SecName,Mch,SectionContent).
3031
3032 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3033 % type expressions in context of an already type-checked machine
3034 % TO DO: maybe do some performance optimisations for identifiers, values, ... to avoid creating scope, see formula_typecheck2_for_eval optimisation
3035 % b_type_literal does it in bmachine before calling type_in_machine_l
3036 type_in_machine_l(Exprs,Scope,Machine,Types,TExprs,Errors) :-
3037 MType = machine,
3038 create_scope_if_necessary(Exprs,Scope,MType,Machine,Env,Errors,E1), % this can be expensive for big B machines
3039 %runtime_profiler:profile_single_call(create_scope,unknown,
3040 % bmachine_construction:create_scope(Scope,MType,Machine,Env,Errors,E1)),
3041 btype_ground_dl(Exprs,Env,[],Types,TExprUncleans,E1,[]),
3042 perform_post_static_check(TExprUncleans),
3043 ? maplist(clean_up_pred_or_expr([]),TExprUncleans,TExprs).
3044
3045 % detect a few common expressions which do not require creating a scope of all the identifiers
3046 create_scope_if_necessary([E],_Scope,MType,Machine,Env,Ein,Eout) :- raw_expr_wo_ids(E),!,
3047 create_scope([],MType,Machine,Env,Ein,Eout).
3048 create_scope_if_necessary(_Exprs,Scope,MType,Machine,Env,Ein,Eout) :-
3049 create_scope(Scope,MType,Machine,Env,Ein,Eout).
3050
3051 % a few common raw ASTs which do not refer to identifiers
3052 raw_expr_wo_ids(falsity(_)).
3053 raw_expr_wo_ids(truth(_)).
3054 raw_expr_wo_ids(empty_set(_)).
3055 raw_expr_wo_ids(equal(_,A,B)) :- raw_expr_wo_ids(A), raw_expr_wo_ids(B).
3056 raw_expr_wo_ids(not_equal(_,A,B)) :- raw_expr_wo_ids(A), raw_expr_wo_ids(B).
3057 raw_expr_wo_ids(interval(_,A,B)) :- raw_expr_wo_ids(A), raw_expr_wo_ids(B).
3058 raw_expr_wo_ids(add(_,A,B)) :- raw_expr_wo_ids(A), raw_expr_wo_ids(B).
3059 raw_expr_wo_ids(minus_or_set_subtract(_,A,B)) :- raw_expr_wo_ids(A), raw_expr_wo_ids(B).
3060 raw_expr_wo_ids(mult_or_cart(_,A,B)) :- raw_expr_wo_ids(A), raw_expr_wo_ids(B).
3061 raw_expr_wo_ids(unary_minus(_,A)) :- raw_expr_wo_ids(A).
3062 raw_expr_wo_ids(boolean_true(_)).
3063 raw_expr_wo_ids(boolean_false(_)).
3064 raw_expr_wo_ids(bool_set(_)).
3065 raw_expr_wo_ids(integer(_,_)).
3066 raw_expr_wo_ids(real(_,_)).
3067 raw_expr_wo_ids(string(_,_)).
3068
3069
3070 % note prob_ids(visible), external_library(all_available_libraries) scope is expanded somewhere else
3071 create_scope(pre_expanded_scope(PEnv,Errors),_MType,_Machine,Env,Ein,Eout) :-
3072 !, % already pre-expanded
3073 Env=PEnv, append(Errors,Eout, Ein).
3074 create_scope(Scope,MType,Machine,Env,Ein,Eout) :-
3075 env_empty(Init),
3076 add_theory_operators(Machine,Init,WithOperators),
3077 foldl(create_scope2(MType,Machine),Scope,WithOperators/Ein,Env/Eout).
3078 add_theory_operators(Machine,Ein,Eout) :-
3079 get_section(operators,Machine,Operators),
3080 keys_and_values(Operators,Ids,Ops),
3081 foldl(env_store_operator,Ids,Ops,Ein,Eout).
3082 create_scope2(MType,Machine,Scope,In/Ein,Out/Eout) :-
3083 ( Scope = constants ->
3084 visible_env(MType,properties,[ref(local,Machine)],In,Out,Ein,Eout)
3085 ; Scope = variables ->
3086 visible_env(MType,invariant,[ref(local,Machine)],In,Out,Ein,Eout)
3087 ; Scope = variables_and_additional_defs ->
3088 visible_env(MType,invariant,[extended_local_ref(Machine)],In,Out,Ein,Eout)
3089 ; Scope = assertions_scope_and_additional_defs ->
3090 visible_env(MType,assertions,[extended_local_ref(Machine)],In,Out,Ein,Eout)
3091 ; Scope = prepost ->
3092 visible_env(MType,prepost,[ref(local,Machine)],In,Out,Ein,Eout)
3093 ; Scope = operation_bodies ->
3094 visible_env(MType,operation_bodies,[ref(local,Machine)],In,Out,Ein,Eout)
3095 ; Scope = operation(Op) ->
3096 create_operation_scope(Op,Machine,In,Out), Ein=Eout
3097 ; Scope = env(ExplicitEnv) ->
3098 ExplicitEnv = Out, Ein=Eout
3099 ; Scope = identifier(Ids) ->
3100 store_variables(Ids,In,Out), Ein=Eout
3101 ; Scope = external_library(LibName) % be sure to make these last to avoid duplication errors
3102 -> store_ext_defs(LibName,In,Out), Ein=Eout
3103 ;
3104 add_error(bmachine_construction, 'invalid scope', Scope),fail).
3105 create_operation_scope(Op,Machine,In,Out) :-
3106 get_section(operation_bodies,Machine,OpBodies),
3107 get_texpr_id(OpId,op(Op)),
3108 get_texpr_expr(TOp,operation(OpId,Results,Params,_)),
3109 ( member(TOp,OpBodies) ->
3110 append(Results,Params,LocalVariables),
3111 store_variables(LocalVariables,In,Out)
3112 ;
3113 ajoin(['operation \'',Op,'\' not found for building scope'], Msg),
3114 add_error(bmachine_construction,Msg),fail).
3115 store_variables(Ids,In,Out) :- foldl(store_variable,Ids,In,Out).
3116 store_variable(Id,In,Out) :-
3117 get_texpr_id(Id,Name),get_texpr_type(Id,Type),
3118 env_store(Name,Type,[],In,Out).
3119
3120 type_open_predicate_with_quantifier(OptionalOuterQuantifier,Predicate,Scope,Machine,TResult,Errors) :-
3121 type_open_formula(Predicate,Scope,false,Machine,pred,Identifiers,TPred,Errors),
3122 ( Identifiers = [] ->
3123 TResult = TPred
3124 ; OptionalOuterQuantifier=forall ->
3125 create_forall(Identifiers,TPred,TResult)
3126 ; OptionalOuterQuantifier=no_quantifier ->
3127 TResult = TPred
3128 ; % OptionalOuterQuantifier=exists
3129 %perform_do_not_enumerate_analysis(Identifiers,TPred,'EXISTS',Span,TPred2), % now done by apply_kodkod_or_other_optimisations
3130 create_exists(Identifiers,TPred,TResult)
3131 ).
3132
3133 type_open_formula(Raw,Scope,AllowOpenIdsinExpressions,Machine,Type,Identifiers,Result,Errors) :-
3134 create_scope_if_necessary([Raw],Scope,machine,Machine,Env1,Errors,E1),
3135 ( Identifiers==[] -> Mode=closed, Env1=Env
3136 ; Mode=open, openenv(Env1,Env)),
3137 btype_ground_dl([Raw],Env,[],[Type],[TExprUnclean],E1,E2),
3138 ( Mode=closed -> true
3139 ;
3140 openenv_identifiers(Env,Identifiers), % TODO: treat theory operators ?
3141 check_ground_types_dl(Identifiers,[],E2,E3)
3142 ),
3143 %print(type_open_formula(Identifiers,TExprUnclean)),nl,
3144 mark_outer_quantifier_ids(TExprUnclean,TExprUnclean2),
3145 perform_post_static_check([TExprUnclean2]),
3146 clean_up_pred_or_expr([],TExprUnclean2,TResult), % TODO: only run if requested
3147 ( Identifiers = [] -> % no newly introduced identifiers, no problem
3148 E3 = []
3149 ; Type = pred -> % newly introduced identifiers in a predicate - ok
3150 E3 = []
3151 ; AllowOpenIdsinExpressions=true -> % we explicitly allow open ids in expressions
3152 E3 = []
3153 ; % newly introduced identifiers in expression make no sense
3154 % (is that so?)
3155 foldl(add_unknown_identifier_error,Identifiers,E3,[])
3156 ),
3157 Result = TResult.
3158 add_unknown_identifier_error(TId,[error(Msg,Pos)|E],E) :-
3159 get_texpr_id(TId,Id),
3160 ajoin(['Unknown identifier ',Id,'.'],Msg),
3161 % TO DO: generate fuzzy match and possible completions message
3162 get_texpr_pos(TId,Pos).
3163
3164 % mark outermost identfiers so that they don't get optimized away
3165 % e.g., ensure that we print the solution for something like #(y2,x2).(x2 : 0..10 & y2 : 0..10 & x2 = 10 & y2 = 10)
3166 mark_outer_quantifier_ids(b(exists(IDS,Pred),pred,Info),Res) :-
3167 maplist(mark_id,IDS,MIDS),!,
3168 Res = b(exists(MIDS,Pred),pred,Info).
3169 mark_outer_quantifier_ids(b(let_predicate(IDS,Exprs,Pred),pred,Info),Res) :-
3170 maplist(mark_id,IDS,MIDS),!,
3171 Res = b(let_predicate(MIDS,Exprs,Pred),pred,Info).
3172 mark_outer_quantifier_ids(b(forall(IDS,LHS,RHS),pred,Info),Res) :-
3173 maplist(mark_id,IDS,MIDS),!,
3174 Res = b(forall(MIDS,LHS,RHS),pred,Info).
3175 mark_outer_quantifier_ids(X,X).
3176
3177 mark_id(b(identifier(ID),TYPE,INFO),b(identifier(ID),TYPE,[do_not_optimize_away|INFO])).
3178
3179 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3180
3181 % some additional static checks; they should be run only once before ast_cleanup runs
3182 % TO DO: move maybe some of the exists/forall checks here; would be simpler and not require removed_typing inspection
3183
3184 :- use_module(bsyntaxtree,[map_over_typed_bexpr/2]).
3185 perform_post_static_check([Typed|_]) :- %print(t(Typed)),nl,
3186 preferences:get_preference(disprover_mode,false),
3187 map_over_typed_bexpr(post_static_check,Typed),
3188 fail.
3189 perform_post_static_check([_|T]) :- !, perform_post_static_check(T).
3190 perform_post_static_check(_).
3191
3192 post_static_check(b(E,T,I)) :-
3193 %bsyntaxtree:check_infos(I,post_static_check),
3194 post_static_check_aux(E,T,I).
3195
3196 :- use_module(bsyntaxtree,[find_identifier_uses/3, is_a_disjunct_or_implication/4]).
3197 :- use_module(library(ordsets),[ord_subtract/3]).
3198 % should detect patterns like { zz | # r__1, q__1, zz . ( ...)}
3199 % {x,z|z=1}[{TRUE}] = {1}
3200 % %x.(1=1|1)(TRUE) = 1
3201 post_static_check_aux(lambda(Ids,Body,Expr),_T,Info) :-
3202 get_texpr_ids(Ids,AtomicIds), sort(AtomicIds,SortedIds),
3203 find_identifier_uses(Body,[],UsedIds1),
3204 find_identifier_uses(Expr,[],UsedIds2), % relevant for tests 1106, 1264, 1372, 1622 to also look at Expr
3205 ord_subtract(SortedIds,UsedIds1,S2),
3206 ord_subtract(S2,UsedIds2,UnusedIds), UnusedIds \= [],
3207 add_warning_with_info('Condition of lambda does not use these identifiers: ',UnusedIds,Body,Info).
3208 post_static_check_aux(comprehension_set(Ids,Body),_T,Info) :-
3209 get_texpr_ids(Ids,AtomicIds), sort(AtomicIds,SortedIds),
3210 find_identifier_uses(Body,[],UsedIds),
3211 ord_subtract(SortedIds,UsedIds,UnusedIds), UnusedIds \= [],
3212 add_warning_with_info('Body of comprehension set does not use these identifiers: ',UnusedIds,Body,Info).
3213 post_static_check_aux(exists(Ids,P),_T,Info) :-
3214 is_a_disjunct_or_implication(P,Type,_Q,_R),
3215 exists_body_warning(Ids,P,Info,Type).
3216
3217 % see also check_implication_inside_exists ast cleanup rule
3218 exists_body_warning(_,_,_,_) :- animation_minor_mode(X),(X=eventb ; X=tla),!.
3219 exists_body_warning(Ids,P,I,Type) :-
3220 ajoin(['Body of existential quantifier is a(n) ',Type,
3221 ' (not allowed by Atelier-B): '],Msg),
3222 add_warning_with_info(Msg,b(exists(Ids,P),pred,I),P,I).
3223
3224
3225
3226 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3227 % Warnings
3228
3229 :- use_module(bsyntaxtree,[contains_info_pos/1]).
3230 add_warning_with_info(Msg1,Msg2,P,Info) :-
3231 (contains_info_pos(Info) -> Pos=Info ; Pos=P),
3232 add_warning(bmachine_construction,Msg1,Msg2,Pos).
3233
3234 :- dynamic warnings/2.
3235 clear_warnings :-
3236 retractall( warnings(_,_) ).
3237 show_warnings :-
3238 warnings(Warning,Span),
3239 add_warning(bmachine_construction, Warning,'',Span),
3240 fail.
3241 show_warnings.
3242
3243
3244 store_warning(Warning,Span) :-
3245 (warnings(Warning,Span) -> true ; assertz(warnings(Warning,Span))).