1 % (c) 2009-2026 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_eventb,[check_event_b_project/4
6 ,deferred_set_equality_without_enumeration_axioms/2
7 ,is_eventb_additional_info/1
8 ,raw_event/11
9 ,stored_operator_direct_definition/8 % stored operator defs, mainly for bvisual2
10 ,stored_operator/2 % a simpler form
11 ,some_operator_uses_reals/0 % true if some operator definitely uses reals
12 ,get_theory_mapping_targets/2 % for tools writing .ptm files, e.g. ProB for Rodin
13 %,get_operator_arity_from_callback/3 % not yet used
14 ]).
15
16 :- use_module(library(lists)).
17 :- use_module(library(ordsets)).
18 :- use_module(library(avl)).
19 :- use_module(library(codesio),[read_from_codes/2]).
20
21 :- use_module(error_manager).
22 :- use_module(tools,[remove_all/3,foldl/4,foldl/5,foldl/6,ajoin_with_sep/3,unique_id/2]).
23 :- use_module(self_check).
24 :- use_module(btypechecker).
25 :- use_module(b_ast_cleanup).
26 :- use_module(bsyntaxtree).
27 :- use_module(debug).
28 :- use_module(bmachine_construction).
29 :- use_module(preferences,[get_preference/2]).
30 :- use_module(input_syntax_tree,[extract_raw_identifiers/2,create_fresh_identifier/3]).
31 :- use_module(translate,[translate_bexpression/2]).
32 :- use_module(kernel_freetypes,[create_freetype_typeid/3]).
33 :- use_module(pragmas,[extract_pragmas_from_event_b_extensions/2,apply_pragmas_to_event_b_machine/3]).
34 :- use_module(input_syntax_tree,[map_over_raw_expr/3]).
35
36 :- use_module(module_information,[module_info/2]).
37 :- module_info(group,typechecker).
38 :- module_info(description,'This module contains the rules for loading a Event-B machine or context. ').
39
40 :- set_prolog_flag(double_quotes, codes).
41
42 :- use_module(specfile,[eventb_mode/0]).
43 deferred_set_equality_without_enumeration_axioms(Set,ExtSet) :-
44 eventb_mode,
45 deferred_set_eq_wo_enumeration_axioms(Set,ExtSet),
46 % there is a single equality Set = {id1,...,idn} and no partition or not enough disequalities
47 % quite often the user forgot to add those disequalities
48 \+ (deferred_set_eq_wo_enumeration_axioms(Set,ExtS2), ExtS2 \= ExtSet).
49
50 :- dynamic deferred_set_eq_wo_enumeration_axioms/2.
51
52 check_event_b_project(RawModels,RawContextes,Extensions,MachineWithPragmas) :-
53 retractall(deferred_set_eq_wo_enumeration_axioms(_,_)),
54 catch( check_event_b_project1(RawModels,RawContextes,Extensions,MachineWithPragmas),
55 typecheck_errors(Errors),
56 ( add_all_perrors(Errors), NoError=false )), % a cut here does not work !
57 !, NoError=true.
58 check_event_b_project(_,_,_,_) :-
59 add_internal_error('Checking Event-B Model failed; Please submit bug report.',check_event_b_project(_,_,_,_)),
60 fail.
61 check_event_b_project1([],RawContextes,Extensions,MachineWithPragmas) :-
62 !,
63 check_theory_extensions(Extensions,Freetypes,Ops,InitEnv), % Theories
64 check_contextes(InitEnv,RawContextes,Contextes),
65 convert_event_b(context,Freetypes,Ops,Contextes,[],[],Machine),
66 extract_pragmas_from_event_b_extensions(Extensions,Pragmas),
67 apply_pragmas_to_event_b_machine(Pragmas,Machine,MachineWithPragmas).
68 check_event_b_project1(RawModels,RawContextes,Extensions,MachineWithPragmas) :-
69 compute_animation_chain(RawModels,AnimationChain),
70 check_event_b_project2(RawModels,RawContextes,Extensions,
71 AnimationChain,Machine),
72 extract_pragmas_from_event_b_extensions(Extensions,Pragmas),
73 apply_pragmas_to_event_b_machine(Pragmas,Machine,MachineWithPragmas).
74
75 check_event_b_project2(RawModels,RawContextes,Extensions,AnimationChain,Machine) :-
76 RawModels=[event_b_model(_,Main,_)|_],
77 check_theory_extensions(Extensions,Freetypes,Ops,InitEnv), % related to Theory plugin
78 % generate type-checked contextes
79 check_contextes(InitEnv,RawContextes,Contextes),
80 % generate type-checked models
81 check_models(InitEnv,RawModels,Contextes,Models),
82 % merge all the constants/vars/predicates and events into one machine
83 convert_event_b(Main,Freetypes,Ops,Contextes,Models,AnimationChain,Machine).
84
85 % the filter chain contains the name of all models that
86 % should be contained in the animation
87 compute_animation_chain(Models,AnimationChain) :-
88 get_preference(number_skipped_refined_machines,NS), % TODO: also use it for constants if possible
89 get_preference(number_animated_abstractions,N),
90 debug_println(9,compute_animation_chain(N,skipping(NS))),
91 (NS=0 -> NonSkippedModels = Models
92 ; append_length(SkippedModels,NonSkippedModels,Models,NS),
93 NonSkippedModels = [_|_]
94 -> extract_model_names(SkippedModels,SkippedNames),
95 add_message(bmachine_eventb,'Skipping animation of refinement machines: ',SkippedNames)
96 ; last(Models,AnimatedModel),
97 NonSkippedModels = [AnimatedModel],
98 extract_model_names(NonSkippedModels,[AName]),
99 ajoin(['Cannot skip ',NS,' refinement machines; animating topmost machine only: '],Msg),
100 add_warning(bmachine_eventb,Msg,AName)
101 ),
102 length(NonSkippedModels,L),
103 N1 is min(N+1,L),
104 prefix_length(NonSkippedModels, AnimatedModels, N1),
105 extract_model_names(AnimatedModels,AnimationChain).
106 extract_model_names([],[]).
107 extract_model_names([event_b_model(_,Name,_)|MRest],[Name|NRest]) :-
108 extract_model_names(MRest,NRest).
109
110 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
111 % context
112
113 check_contextes(InitEnv,RawContextes,Contextes) :-
114 debug_println(9,'Checking Contextes'),
115 % make sure that a extended context is treated before
116 % the extending context
117 topological_sort(RawContextes,SortedContextes),
118 check_contextes2(SortedContextes,InitEnv,[],Contextes).
119 check_contextes2([],_,_,[]).
120 check_contextes2([RawContext|Rrest],InitEnv,PrevContextes,[Context|Crest]) :-
121 check_context(RawContext,InitEnv,PrevContextes,Context),
122 check_contextes2(Rrest,InitEnv,[Context|PrevContextes],Crest).
123
124 check_context(RawContext,InitEnv,PrevContextes,Context) :-
125 extract_ctx_sections(RawContext,Name,Extends,
126 RawSets,RawConstants,RawAbstractConstants,RawAxioms,RawTheorems),
127 Context = context(Name,Extends,Sets,Constants,AbstractConstants,Axioms,Theorems),
128
129 debug_format(9,'Checking context ~w~n',[Name]),
130 % create deferred sets
131 create_sets(RawSets,Name,Sets),
132 % and constants
133 IdInfos = [loc(Name,constants),section(Name)],
134 create_identifiers(RawConstants,IdInfos,Constants),
135 create_identifiers(RawAbstractConstants,IdInfos,AbstractConstants),
136
137 % with the constants and set of seen contextes,
138 create_ctx_env(Extends,PrevContextes,InitEnv,PrevEnv),
139 % and the sets and constants
140 add_unique_variables(Sets,PrevEnv,SetEnv),
141 add_unique_variables(Constants,SetEnv,EnvT),
142 add_unique_variables(AbstractConstants,EnvT,Env),
143
144 % now typecheck the axioms and theorems,
145 % this should determine the constant's types
146 debug_format(9,'Typechecking axioms and theorems for ~w~n',[Name]),
147 typecheck_together([RawAxioms,RawTheorems],Env,[Axioms,Theorems],axioms).
148
149 extract_ctx_sections(RawContext,Name,Extends,RawSets,RawConstants,RawAbstractConstants,RawAxioms,RawTheorems) :-
150 RawContext = event_b_context(_Pos,Name,Sections),
151 optional_rawmachine_section(extends,Sections,[],Extends),
152 optional_rawmachine_section(sets,Sections,[],RawSets),
153 optional_rawmachine_section(constants,Sections,[],RawConstants),
154 optional_rawmachine_section(abstract_constants,Sections,[],RawAbstractConstants),
155 optional_rawmachine_section(axioms,Sections,[],RawAxioms),
156 optional_rawmachine_section(theorems,Sections,[],RawTheorems).
157
158
159 create_sets([],_,[]).
160 create_sets([RawSet|RSrest],CtxName,[Set|Srest]) :-
161 ext2int_with_pragma(RawSet,deferred_set(SetName),_,set(global(SetName)),
162 identifier(SetName),[section(CtxName),given_set],Set),
163 create_sets(RSrest,CtxName,Srest).
164
165 create_identifiers([],_,[]).
166 create_identifiers([RawIdentifier|RIrest],Infos,[Identifier|Irest]) :-
167 ext2int_with_pragma(RawIdentifier,I,_,_,I,Infos,Identifier),
168 I=identifier(_),
169 create_identifiers(RIrest,Infos,Irest).
170
171 create_ctx_env(Extends, Contextes, Old, New) :-
172 % find all seen contextes (and their extended contextes,
173 % and again their extended contextes, ...)
174 transitive_contextes(Extends,Contextes,TransExt),
175 % and all variables of extended machines
176 add_env_vars_for_extended2(TransExt,Contextes,Old,New).
177 transitive_contextes(Extends,Contextes,All) :-
178 findall(E, transext(Extends,Contextes,E), All1), sort(All1, All).
179 ?transext(Extends,_,E) :- member(E,Extends).
180 transext(Extends,Contextes,E) :-
181 ? member(Name,Extends),
182 internal_context_extends(Context,Name,NewExtends),
183 ? member(Context,Contextes),
184 ? transext(NewExtends,Contextes,E).
185 % add_env_vars_for_extended2(Names,Contextes,OldEnv,NewEnv):
186 % Names: a list of the names of the contextes whose constants and sets
187 % should be added to the type environment
188 % Contextes: a list of all existing contextes
189 % OldEnv: the input environment
190 % NewEnv: the input environment plus the constants and sets
191 add_env_vars_for_extended2([],_,Env,Env).
192 add_env_vars_for_extended2([Name|Erest],Contextes,Old,New) :-
193 internal_context_sets(Context,Name,Sets),
194 internal_context_constants(Context,Name,Constants),
195 internal_context_abstract_constants(Context,Name,AbstractConstants),
196 ? member(Context,Contextes),!,
197 add_unique_variables(Sets,Old,Env1),
198 add_unique_variables(Constants,Env1,Env2),
199 add_unique_variables(AbstractConstants,Env2,Env),
200 add_env_vars_for_extended2(Erest,Contextes,Env,New).
201
202 % copy&paste from bmachine_construction
203 add_unique_variables([],Env,Env).
204 add_unique_variables([Var|Rest],Old,New) :-
205 def_get_texpr_id(Var,Name),
206 get_texpr_type(Var,Type),
207 get_texpr_info(Var,Infos),
208 ( env_lookup_type(Name,Old,_) ->
209 add_error(bmachine_eventb,'Identifier declared twice',Name),
210 fail
211 ; true),
212 env_store(Name,Type,Infos,Old,Env),
213 add_unique_variables(Rest,Env,New).
214
215 % add the primed (') versions of the variables to the
216 % type environment
217 add_primed_variables(Variables,OrigEnv,NewEnv) :-
218 prime_variables(Variables,Primed),
219 add_unique_variables(Primed,OrigEnv,NewEnv).
220
221
222 :- use_module(btypechecker,[prime_identifiers/2,prime_id/2,is_primed_id/1,prime_identifiers0/2]).
223
224 % add a prime (') to each typed identifier
225 prime_variables(V,PV) :- prime_identifiers(V,PV).
226 % add a prime (') to a typed identifier
227 %prime_variable(V,P) :- btypechecker:prime_identifier(V,P).
228
229
230 % unprime_id( ListoPrimedIds, CorrespondingIds, PossiblyPrimedID, UnprimedID)
231 unprime_id(AtomicIds0,AtomicIds,Id0,Id) :- nth1(N,AtomicIds0,Id0),!, nth1(N,AtomicIds,Id).
232 unprime_id(_,_,Id,Id).
233
234 check_for_errors(Errors) :-
235 % TO DO: extract and add warnings in list
236 Errors = [_|_],!,throw(typecheck_errors(Errors)).
237 check_for_errors([]).
238
239 typecheck_l(Untyped,Env,Type,Typed,Context) :-
240 all_same_type(Untyped,Type,Types),
241 btype_ground_dl(Untyped,Env,[],Types,Typed1,Errors,[]),
242 check_for_errors(Errors),
243 maplist(update_eventb_position_infos(Context),Typed1,Typed2),
244 clean_up_l_with_optimizations(Typed2,[],Typed,Context),!.
245 typecheck_l(Untyped,Env,Type,Typed,Context) :-
246 add_failed_call_error(typecheck_l(Untyped,Env,Type,Typed,Context)),fail.
247 all_same_type([],_,[]).
248 all_same_type([_|R],E,[E|T]) :- all_same_type(R,E,T).
249
250 typecheck(Untyped,Env,Type,Typed,Context) :-
251 typecheck_with_freevars(Untyped,Env,[],Type,Typed,Context).
252 typecheck_with_freevars(Untyped,Env,Freevars,Type,Typed,Context) :-
253 NonGroundExceptions = Freevars,
254 btype_ground_dl([Untyped],Env,NonGroundExceptions,[Type],[Typed1],Errors,[]),
255 update_eventb_position_infos(Context,Typed1,Typed2),
256 clean_up_pred_or_expr_with_path(Freevars,Typed2,Typed,Context),
257 check_for_errors(Errors).
258
259
260 :- use_module(probsrc(bsyntaxtree),[transform_bexpr/3, get_precise_rodin_name/2, get_rodin_model_name/2]).
261 :- public add_eventb_pos_aux/5.
262 add_eventb_pos_aux(Model,LabelName,Context,b(E,T,I),b(E,T,NewInfo)) :-
263 nonmember(nodeid(_),I),
264 NewInfo = [nodeid(rodin_derived_context_pos(Model,Context,LabelName))|I].
265 % TO DO: we could also try and improve ordinary rodinpos infos by adding context (useful if label names not unique)
266
267 % try and improve position information using the context
268 update_eventb_position_infos(Context,TE,Res) :-
269 get_rodin_model_name(TE,Model), get_precise_rodin_name(TE,LabelName),
270 transform_bexpr(add_eventb_pos_aux(Model,LabelName,Context),TE,NewTE),!,
271 Res=NewTE.
272 update_eventb_position_infos(Context,b(conjunct(A,B),pred,I),b(conjunct(A2,B2),pred,I)) :- !, % useful for guard labels
273 update_eventb_position_infos(Context,A,A2),
274 update_eventb_position_infos(Context,B,B2).
275 update_eventb_position_infos(_,TE,TE).
276
277
278 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
279 % models
280
281 check_models(InitEnv,RawModels,Contextes,Models) :-
282 debug_println(9,'CHECKING MODELS'),
283 topological_sort(RawModels,SortedModels),
284 check_models2(SortedModels,InitEnv,[],Contextes,Models).
285
286 check_models2([],_,_,_,[]).
287 check_models2([RawModel|RMrest],InitEnv,PrevModels,Contextes,[Model|Mrest]) :-
288 ? (check_model(RawModel,InitEnv,PrevModels,Contextes,Model) -> true
289 ; add_failed_call_error(check_model(RawModel,InitEnv,PrevModels,Contextes,Model)),
290 fail),
291 check_models2(RMrest,InitEnv,[Model|PrevModels],Contextes,Mrest).
292
293 check_model(RawModel,InitEnv,PrevModels,Contextes,Model) :-
294 extract_model_sections(RawModel,Name,Refines,Sees,
295 RawVariables,RawInvariant,
296 RawTheorems,RawVariant,RawEvents),
297 Model = model(Name,Refines,Sees,ConcreteVariables,NewVariables,Invariant,Theorems,Events),
298 get_refined_model(Refines,PrevModels,RefinedModel),
299
300 get_all_abstract_variables(Refines,PrevModels,AbstractionVariables),
301 length(PrevModels,Level),
302 IdInfos = [loc(Name,variables),section(Name),level(Level)],
303 create_identifiers(RawVariables,IdInfos,ConcreteVariables),
304 split_abstract_vars(AbstractionVariables,ConcreteVariables,
305 NewVariables,DroppedAbstractVars),
306
307 create_ctx_env(Sees,Contextes,InitEnv,CtxEnv),
308 add_unique_variables(ConcreteVariables,CtxEnv,ModelEnv),
309 add_unique_variables(DroppedAbstractVars,ModelEnv,InvEnv),
310 % add primed versions of the concrete variables to
311 % permit before-after predicates in the witnesses
312 add_primed_variables(ConcreteVariables,InvEnv,BeforeAfterEnv),
313
314 typecheck_together([RawInvariant,RawTheorems],InvEnv,[Invariant,Theorems],invariant),
315
316 typecheck_variant(RawVariant,InvEnv,Variant),
317
318 ? get_abstract_events(RefinedModel,AbstractEvents),
319
320 check_events(RawEvents,Name,ModelEnv,BeforeAfterEnv,InvEnv,
321 DroppedAbstractVars,ConcreteVariables,AbstractEvents,
322 NewVariables,Variant,Events).
323
324 % Context is just an information term about the context (axioms, ...)
325 typecheck_together(Raws,Env,Typed,Context) :-
326 maplist(same_length, Raws, Typed),
327 append(Raws,RawL), append(Typed,TypedL),
328 typecheck_l(RawL,Env,pred,TypedL,Context).
329
330 typecheck_variant(-, _Env, -) :- !.
331 typecheck_variant(RawVariant, Env, Variant) :-
332 typecheck(RawVariant, Env, Type, Variant,variant),
333 ( Type==integer -> true
334 ; functor(Type,set,1) -> true
335 ;
336 add_error(bmachine_eventb,'Invalid type of variant ',Type),
337 fail).
338
339 remove_linking_parts([],_AnimationChain,[]).
340 remove_linking_parts([Inv|Irest],AnimationChain,Invariants) :-
341 ( abstraction_var_occures(Inv,AnimationChain) ->
342 Invariants = RestInvariants
343 ;
344 Invariants = [Inv|RestInvariants]),
345 remove_linking_parts(Irest,AnimationChain,RestInvariants).
346
347 abstraction_var_occures(TExpr,AnimationChain) :-
348 get_texpr_expr(TExpr,identifier(_)),!,
349 get_texpr_section(TExpr,Section),
350 ? \+ member(Section,AnimationChain).
351 abstraction_var_occures(TExpr,AnimationChain) :-
352 syntaxtraversion(TExpr,_,_,_,Subs,_),
353 abstraction_var_occures_l(Subs,AnimationChain).
354 abstraction_var_occures_l([Sub|_],AnimationChain) :-
355 abstraction_var_occures(Sub,AnimationChain),!.
356 abstraction_var_occures_l([_|Srest],AnimationChain) :-
357 abstraction_var_occures_l(Srest,AnimationChain).
358
359 get_texpr_section(TExpr,Section) :-
360 ? get_texpr_info(TExpr,Info),member(section(Section),Info),!.
361
362 extract_model_sections(RawModel,Name,Refines,Sees,Variables,Invariant,Theorems,Variant,Events) :-
363 RawModel = event_b_model(_Pos,Name,Sections),
364 optional_rawmachine_section(refines,Sections,-,Refines),
365 optional_rawmachine_section(sees,Sections,[],Sees),
366 optional_rawmachine_section(variables,Sections,[],Variables),
367 optional_rawmachine_section(invariant,Sections,[],Invariant),
368 optional_rawmachine_section(theorems,Sections,[],Theorems),
369 optional_rawmachine_section(variant,Sections,-,Variant),
370 optional_rawmachine_section(events,Sections,[],Events).
371
372 %get_abstraction_variables(-,[]).
373 %get_abstraction_variables(Model,Variables) :-
374 % internal_model_vars(Model,_Name,Variables).
375
376 get_abstract_events(-,[]).
377 get_abstract_events(Model,Events) :- internal_model_events(Model,_Name,Events).
378
379 get_refined_model(-,_Models,-) :- !.
380 get_refined_model(Name,Models,Model) :-
381 internal_model(M,Name),
382 ( memberchk(M,Models) ->
383 M=Model
384 ;
385 add_error(bmachine_eventb,'Unable to find refined model ',Name),
386 fail).
387
388 split_abstract_vars(AbstractVars,ConcreteVars,NewVars,DroppedVars) :-
389 split_abstract_vars2(AbstractVars,ConcreteVars,DroppedVars),
390 find_new_variables(ConcreteVars,AbstractVars,NewVars).
391 split_abstract_vars2([],_,[]).
392 split_abstract_vars2([AbstractVar|AVrest],ConcreteVars,Dropped) :-
393 ? ( find_identifier_in_list(AbstractVar,ConcreteVars,ConcreteVar) ->
394 % Both variables have the same type
395 get_texpr_type(AbstractVar,Type),
396 get_texpr_type(ConcreteVar,Type),
397 Dropped = DroppedRest
398 ;
399 Dropped = [AbstractVar|DroppedRest]),
400 split_abstract_vars2(AVrest,ConcreteVars,DroppedRest).
401 find_new_variables([],_,[]).
402 find_new_variables([ConcreteVar|CVrest],AbstractVars,NewVars) :-
403 ( find_identifier_in_list(ConcreteVar,AbstractVars,_AbstractVar) -> NewVars = Nrest
404 ; NewVars = [ConcreteVar|Nrest]),
405 find_new_variables(CVrest,AbstractVars,Nrest).
406
407 % find_identifier_in_list(TypedIdToFind,List,Elem):
408 % search for a typed identifier Elem in List wich
409 % has the same id as TypedIdToFind, but type and informations
410 % may be different
411 find_identifier_in_list(TypedIdToFind,List,Found) :-
412 def_get_texpr_id(TypedIdToFind,Id),
413 get_texpr_id(Found,Id),
414 ? member(Found,List).
415
416 get_all_abstract_variables(Refines,AbstractModels,AbstractVariables) :-
417 get_all_abstract_variables2(Refines,AbstractModels,_EncounteredIds,AbstractVariables,[]).
418 get_all_abstract_variables2(-,_AbstractModels,EncounteredIds) -->
419 {!,empty_avl(EncounteredIds)}.
420 get_all_abstract_variables2(Name,AbstractModels,EncounteredIds) -->
421 {get_refined_model(Name,AbstractModels,Model),
422 internal_model_refines(Model,_,Refines)},
423 get_all_abstract_variables2(Refines,AbstractModels,EncounteredIdsAbs),
424 get_all_abstract_variables3(Model,EncounteredIdsAbs,EncounteredIds).
425 get_all_abstract_variables3(Model,EncounteredIdsIn,EncounteredIdsOut,
426 FoundVarsIn,FoundVarsOut) :-
427 internal_model_vars(Model,_,Vars),
428 extract_new_variables(Vars,EncounteredIdsIn,NewVars),
429 get_texpr_ids(NewVars,NewIds),
430 add_all_to_avl(NewIds,EncounteredIdsIn,EncounteredIdsOut),
431 add_all(NewVars,FoundVarsIn,FoundVarsOut).
432 add_all_to_avl([],Avl,Avl).
433 add_all_to_avl([H|T],In,Out) :-
434 avl_store(H,In,1,Inter),
435 add_all_to_avl(T,Inter,Out).
436 add_all([],L,L).
437 add_all([H|T],[H|L1],L2) :- add_all(T,L1,L2).
438 extract_new_variables([],_EncounteredIdsIn,[]).
439 extract_new_variables([Var|Vrest],EncounteredIds,NewVars) :-
440 get_texpr_id(Var,Id),
441 ( avl_fetch(Id,EncounteredIds) ->
442 NewVars = NewRest
443 ;
444 NewVars = [Var|NewRest]),
445 extract_new_variables(Vrest,EncounteredIds,NewRest).
446
447
448
449
450
451 check_events([],_ModelName,_Env,_GEnv,_InvEnv,_Dropped,_ConcreteVars,_AbstractEvents,_NewVars,_Variant,[]).
452 check_events([RawEvent|RawRest],ModelName,Env,GEnv,InvEnv,DroppedVars,ConcreteVars,AbstractEvents,NewVars,Variant,[Event|Erest]) :-
453 (check_event(RawEvent,ModelName,Env,GEnv,InvEnv,DroppedVars,ConcreteVars,AbstractEvents,NewVars,Variant,Event)
454 -> true
455 ; add_failed_call_error(check_event(RawEvent,ModelName,Env,GEnv,InvEnv,
456 DroppedVars,ConcreteVars,AbstractEvents,NewVars,Variant,Event))),
457 check_events(RawRest,ModelName,Env,GEnv,InvEnv,DroppedVars,ConcreteVars,AbstractEvents,NewVars,Variant,Erest).
458
459
460 check_event(RawEvent,ModelName,Env,GEnv,InvEnv,DroppedVars,ConcreteVars,AbstractEvents,NewVariables,Variant,
461 tc_event(EvName,ModelName,Status,TParameters,TGuard,TTheorems,MActions,
462 TVarWitnesses,TParamWitnesses,Unmodifiables,Refines,Desc) % type_checked internal event term
463 ) :-
464 raw_event(RawEvent,_,EvName,RawStatus,Refines,Params,Guards,Theorems,Actions,Witnesses,Desc),
465 check_status(RawStatus, Variant, Status, Refines, AbstractEvents, eventlocation(ModelName,EvName)),
466 get_abstract_parameters(Refines,AbstractEvents,AbstractParameters),
467 create_identifiers(Params,[loc(ModelName,event(EvName))],TParameters),
468 split_abstract_vars(AbstractParameters,TParameters,
469 _NewParameters,DroppedParameters1),
470 annotate_dropped_parameters(DroppedParameters1,Refines,AbstractEvents,DroppedParameters),
471 conjunct_guards(Guards,Guard), % TODO: we could see if the guards appear at the abstract level with same label and use the abstract machine name, see M2_test_extends_grd_labels
472 maplist(adapt_becomes_such,Actions,Actions1),
473 % add new parameters to the typing environments:
474 add_identifiers_to_environment(TParameters,Env,Subenv),
475 add_identifiers_to_environment(TParameters,GEnv,SubGenv),
476 add_identifiers_to_environment(TParameters,InvEnv,SubTheoremsEnv), % theorems can access dropped abstract variables; just like the invariant
477 typecheck(Guard,Subenv,pred,TGuard,event(EvName,guard)),
478 typecheck_l(Theorems,SubTheoremsEnv,pred,TTheorems,event(EvName,theorems)),
479 typecheck_l(Actions1,Subenv,subst,TActions,event(EvName,actions)),
480 check_witnesses(Witnesses,SubGenv,DroppedParameters,DroppedVars,TVarWitnesses,TParamWitnesses),
481 % add checks that some variables may not be modified, e.g
482 % if skip is refined
483 get_abstract_actions(Refines,AbstractEvents,AbstractActions),
484 add_modified_vars_to_actions(TActions,MActions1),
485 add_unmodified_assignments(AbstractActions,MActions1,ConcreteVars,MActions),
486 add_equality_check(MActions,AbstractActions,NewVariables,ConcreteVars,Unmodifiables).
487
488
489
490 % --------------
491
492 % add assignments of the form x:=x if a not dropped abstract variable
493 % is modified by the abstract event, but not the dropped event
494 add_unmodified_assignments(AbstractActions,ConcreteActions,ConcreteVars,NewActions) :-
495 get_modified_vars_of_actions(AbstractActions,AbstractModified),
496 get_modified_vars_of_actions(ConcreteActions,ConcreteModified),
497 remove_all(AbstractModified,ConcreteModified,OnlyAbstractModified),
498 findall( Var,
499 ( member(Id,OnlyAbstractModified), get_texpr_id(Var,Id), memberchk(Var,ConcreteVars)),
500 ToKeep),
501 ( ToKeep = [] -> NewActions = ConcreteActions
502 ; ToKeep = [_|_] ->
503 create_texpr(assign(ToKeep,ToKeep),subst,[],Action1),
504 add_modified_vars_to_action(Action1,Action),
505 NewActions = [Action|ConcreteActions]).
506
507 check_status(RawStatus, Variant, TConv, Refines, AbstractEvents, Location) :-
508 remove_pos(RawStatus,Status),
509 check_status2(Status, Variant, Refines, AbstractEvents, Location, Conv, Infos),
510 create_texpr(Conv, status, Infos, TConv).
511 check_status2(ordinary, _Variant, _Refines, _AbstractEvents, _Location, ordinary, []).
512 check_status2(convergent, _Variant, Refines, AbstractEvents, _Location, ordinary, [convergence_proved]) :-
513 % if the refined event is also convergent, we can (or must because the
514 % variant may be missing in the refinement) omit the check for decreasing the
515 % variant. We do this by treating the event as ordinary.
516 convergence_ensured_by_abstract_event(Refines, AbstractEvents),!.
517 check_status2(convergent, Variant, _Refines, _AbstractEvents, Location, convergent(RVariant), [convergence_proved]) :-
518 variant_must_be_set(Variant,Location,RVariant).
519 check_status2(anticipated, Variant, _Refines, _AbstractEvents, _Location, anticipated(RVariant), []) :-
520 get_variant(Variant,RVariant).
521
522 :- use_module(tools_strings,[ajoin/2]).
523 variant_must_be_set(-,Location,RVariant) :- !,
524 Location = eventlocation(Model,Name),
525 ajoin(['No variant defined for ', Name, ' in model ', Model],Msg),
526 add_error(bmachine_eventb,Msg),
527 get_variant(-,RVariant).
528 % removed fail to allow animation
529 variant_must_be_set(V,_,V).
530
531 % get_variant(ModelVariant,Variant) checks profides a default variant (0) if
532 % the model does not have a variant
533 get_variant(-,V) :- !, create_texpr(integer(0),integer,[default_variant],V).
534 get_variant(V,V).
535
536 convergence_ensured_by_abstract_event(Refines, AbstractEvents) :-
537 % find a refined event which status is convergent
538 internal_event_status(Event,Ref,Status),
539 get_texpr_info(Status,StatusInfo),
540 member(Event, AbstractEvents),
541 member(Ref, Refines),
542 member(convergence_proved,StatusInfo),!.
543
544 annotate_dropped_parameters([],_,_,[]).
545 annotate_dropped_parameters([P|PRest],Refines,AbstractEvents,[A|ARest]) :-
546 def_get_texpr_id(P,Id),
547 add_texpr_infos(P,[droppedby(DropList)],A),
548 findall(Event, event_drops_param(Event,Refines,AbstractEvents,Id), DropList),
549 annotate_dropped_parameters(PRest,Refines,AbstractEvents,ARest).
550 event_drops_param(Event,Refines,AbstractEvents,Id) :-
551 get_texpr_id(Pattern,Id),
552 member(Event,Refines),
553 get_event_parameters(Event,AbstractEvents,AbParams),
554 member(Pattern,AbParams).
555
556 get_abstract_parameters([],_,R) :- !,R=[].
557 get_abstract_parameters([Refines|Rest],Events,Params) :- !,
558 get_event_parameters(Refines,Events,LocalParams),
559 append(LocalParams,RestParams,Params),
560 get_abstract_parameters(Rest,Events,RestParams).
561 get_abstract_parameters(Refines,_,Params) :- add_error(get_abstract_parameters,'Illegal Refines List: ',Refines),
562 Params=[].
563 get_event_parameters(Refines,Events,Params) :-
564 internal_event_params(Event,Refines,Params),
565 ? member(Event,Events),!.
566
567 get_abstract_actions([],_,[]).
568 get_abstract_actions([Refines|Rest],Events,Actions) :-
569 get_event_action(Refines,Events,LocalActions),
570 append(LocalActions,RestActions,Actions),
571 get_abstract_actions(Rest,Events,RestActions).
572 get_event_action(Refines,Events,Actions) :-
573 internal_event_actions(Event,Refines,Actions),
574 ? member(Event,Events),!.
575
576 check_witnesses([],_Env,_DroppedParams,_DroppedVars,[],[]).
577 check_witnesses([Witness|Rest],Env,DroppedParams,DroppedVars,TVarWitnesses,TParamWitnesses) :-
578 check_witness(Witness,Env,DroppedParams,DroppedVars,TWitness,WType),
579 ( WType = droppedvar ->
580 TVarWitnesses = [TWitness|TWVRest],
581 TParamWitnesses = TWPRest
582 ; WType = droppedparam(_DropList) ->
583 TVarWitnesses = TWVRest,
584 TParamWitnesses = [TWitness|TWPRest]),
585 check_witnesses(Rest,Env,DroppedParams,DroppedVars,TWVRest,TWPRest).
586 check_witness(witness(_Pos,RawId,Pred),Env,DroppedParams,DroppedVars,TWitness,WType) :-
587 RawId = identifier(_,WitnessId),
588 get_witness_identifier(WitnessId,DroppedParams,DroppedVars,TId,Info,WType),
589 get_texpr_type(TId,Type),
590 env_store(WitnessId,Type,Info,Env,Subenv),
591 typecheck(Pred,Subenv,pred,TPred,witness),
592 create_texpr(witness(TId,TPred),witness,[],TWitness).
593 get_witness_identifier(PrimedId,_DroppedParams,DroppedVars,TPrimeId,[],droppedvar) :-
594 prime_id(Id,PrimedId),
595 get_texpr_id(TId,Id),
596 member(TId,DroppedVars),!,
597 prime_variables([TId],[TPrimeId]).
598 get_witness_identifier(Id,DroppedParams,_DroppedVars,TId,Info,droppedparam(DropList)) :-
599 get_texpr_id(TId,Id),
600 member(TId,DroppedParams),!,
601 get_texpr_info(TId,Info),
602 ? member(droppedby(DropList),Info),!.
603
604 conjunct_guards([],truth(none)).
605 conjunct_guards([H|T],Result) :- conjunct_guards2(T,H,Result).
606 conjunct_guards2([],G,G).
607 conjunct_guards2([H|T],G,Result) :- conjunct_guards2(T,conjunct(none,G,H),Result).
608
609 /*
610 parallel_actions(Actions,Pos,Action) :-
611 ( Actions = [] -> Action = skip(Pos)
612 ; Actions = [S] -> Action = S
613 ; Action = parallel(Pos,Actions)).
614 */
615
616 % eventb becomes_such uses primed identifiers: distinguish it from normal becomes_such
617 % ast_cleanup will translate it back to becomes_such, but with $0 instead of primes (so that it conforms to classical B)
618 adapt_becomes_such(becomes_such(Pos,Ids,Pred),evb2_becomes_such(Pos,Ids,Pred)) :- !.
619 adapt_becomes_such(Subst,Subst).
620
621 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
622 % convert B project to classical B machine
623
624 :- use_module(bmachine_structure,[create_machine/2]).
625
626 convert_event_b(Main,Freetypes,Ops,Contextes,Models,AnimationChain,Machine) :-
627 debug_println(9,'Converting to classical B'),
628 select_models(AnimationChain,Models,AnimatedModels),
629 % todo: access to private elements of bmachine_construction
630 create_machine(Main,Empty),
631 convert_event_b2(Freetypes,Ops,AnimatedModels,Contextes,AnimationChain,
632 Empty,Machine),!.
633 convert_event_b(Main,Freetypes,Ops,Contextes,Models,AnimationChain,Machine) :-
634 add_failed_call_error(convert_event_b(Main,Freetypes,Ops,Contextes,Models,AnimationChain,Machine)),
635 fail.
636 convert_event_b2(Freetypes,Ops,AnimatedModels,Contextes,AnimationChain) -->
637 append_to_section(freetypes,Freetypes),
638 %{format('Appending freetypes: ~w~n',[Freetypes])},
639 append_to_section(operators,Ops),
640 %{format('Appending operators: ~w~n',[Ops])},
641 create_constants(AnimatedModels,Contextes,AnimatedContextNames),
642 {append(AnimatedContextNames,AnimationChain,AnimatedSectionNames)},
643 create_variables(AnimatedModels,AnimatedSectionNames),
644 create_events(AnimatedModels,AnimatedSectionNames),
645 create_animated_section_info(AnimatedContextNames,AnimationChain).
646
647 create_animated_section_info(Contextes,Models) -->
648 {reverse(Models,FromAbstractToConcrete),
649 maplist(mark_as_model,FromAbstractToConcrete,MarkedModels),
650 maplist(mark_as_context,Contextes,MarkedContextes),
651 append(MarkedContextes,MarkedModels,Sections)},
652 append_to_section(meta,[animated_sections(Sections)]).
653
654 mark_as_model(Name,model(Name)).
655 mark_as_context(Name,context(Name)).
656
657 /*
658 get_operation_identifiers([],[]).
659 get_operation_identifiers([TExpr|Rest],[Id|IdRest]) :-
660 get_texpr_expr(TExpr,operation(Id,_,_,_)),
661 get_operation_identifiers(Rest,IdRest).
662 */
663
664 create_variables(Models,AnimatedSectionNames) -->
665 {collect_model_infos(Models,AnimatedSectionNames,Variables,Invariants,Theorems)},
666 append_to_section(abstract_variables,Variables),
667 conjunct_to_section(invariant,Invariants),
668 append_to_section(assertions,Theorems).
669
670 select_contexts([],_Contexts,[]).
671 select_contexts([Name|NRest],Contexts,[Context|CRest]) :-
672 internal_context(Context,Name),
673 memberchk(Context,Contexts),
674 select_contexts(NRest,Contexts,CRest).
675
676 select_models([],_Models,[]).
677 select_models([Name|NRest],Models,[Model|MRest]) :-
678 internal_model(Model,Name), memberchk(Model,Models),
679 select_models(NRest,Models,MRest).
680
681 % collect_model_infos(Models,Variables,Invariants,Theorems):
682 % collect all variables, invariants and theorems of the given models
683 collect_model_infos([],_,[],[],[]) :- !.
684 collect_model_infos(Models,AnimatedSectionNames,Vars,Invs,Thms) :-
685 collect_model_infos2(Models,AnimatedSectionNames,AllVars,Vars1,Invs,Thms),
686 % add to every variable the information in which models
687 % it is present
688 add_var_model_occurrences(Vars1,AllVars,Vars).
689 collect_model_infos2([],_,[],[],[],[]).
690 collect_model_infos2([Model|MRest],AnimatedSectionNames,Vars,NewVars,Invs,Thms) :-
691 internal_model_vars(Model,_,LVars), append(LVars,RVars,Vars),
692 % use only newly introduced variables of a model, to prevent
693 % double declarations
694 % in case of a limited animation chain, it is important to introduce
695 % all variables for the most abstract model
696 (MRest == [] -> LNewVars = LVars ; internal_model_newvars(Model,_,LNewVars)),
697 append(LNewVars,RNewVars,NewVars),
698 internal_model_invs(Model,_,LInvs1), append_stripped_predicates(LInvs1,AnimatedSectionNames,RInvs,Invs),
699 internal_model_thms(Model,_,LThms1), append_stripped_predicates(LThms1,AnimatedSectionNames,RThms,Thms),
700 collect_model_infos2(MRest,AnimatedSectionNames,RVars,RNewVars,RInvs,RThms).
701 add_var_model_occurrences([],_,[]).
702 add_var_model_occurrences([Var|Vrest],AllVars,[MVar|Mrest]) :-
703 add_var_model_occurrence(Var,AllVars,MVar),
704 add_var_model_occurrences(Vrest,AllVars,Mrest).
705 add_var_model_occurrence(Var,AllVars,MVar) :-
706 findall(Section,
707 ( find_identifier_in_list(Var,AllVars,M),
708 get_texpr_info(M,Infos),
709 member(section(Section),Infos)),
710 Sections),
711 reverse(Sections,FromAbstractToConcrete),
712 add_texpr_infos(Var,[occurrences(FromAbstractToConcrete)],MVar).
713 append_stripped_predicates(PredsIn,AnimatedSectionNames,RestPreds,Preds) :-
714 remove_linking_parts(PredsIn,AnimatedSectionNames,LPreds),
715 append(LPreds,RestPreds,Preds).
716
717 all_used_contextes(AnimatedModels,Contextes,Sees) :-
718 ( AnimatedModels = [] ->
719 all_context_names(Contextes,Sees)
720 ;
721 collect_sees(AnimatedModels,Sees)).
722 all_context_names([],[]).
723 all_context_names([Context|Crest],[Name|Nrest]) :-
724 internal_context(Context,Name),
725 all_context_names(Crest,Nrest).
726 collect_sees([],[]).
727 collect_sees([Model|MRest],Sees) :-
728 internal_model_sees(Model,_,LocalSees), append(LocalSees,RestSees,Sees),
729 collect_sees(MRest,RestSees).
730
731 create_constants(AnimatedModels,Contextes,AnimatedContextNames) -->
732 {all_used_contextes(AnimatedModels,Contextes,Sees),
733 get_constants(Sees,Contextes,DefSets,EnumSets,EnumElems,Constants,AbstractConstants,Axioms,Theorems,AnimatedContextNames)},
734 append_to_section(deferred_sets,DefSets),
735 append_to_section(enumerated_sets,EnumSets),
736 append_to_section(enumerated_elements,EnumElems),
737 append_to_section(concrete_constants,Constants),
738 append_to_section(abstract_constants,AbstractConstants),
739 conjunct_to_section(properties,Axioms),
740 append_to_section(assertions,Theorems).
741
742 get_constants(Sees,Contextes,DefSets,EnumSets,EnumElems,Constants,AbstractConstants,Axioms,Theorems,AllContextNames) :-
743 transitive_contextes(Sees,Contextes,AllContextNames),
744 select_contexts(AllContextNames,Contextes,AllContextes),
745 collect_context_infos(AllContextes,Sets,Constants1,AbstractConstants,Axioms1,Theorems),
746 enumerated_deferred_sets(Sets,Constants1,Axioms1,DefSets,Constants,Axioms,
747 EnumSets,EnumElems).
748
749 collect_context_infos([],[],[],[],[],[]).
750 collect_context_infos([context(Name,_Ex,LSets1,LCsts1,LAbsCsts1,LAxms,LThms)|Rest],Sets,Constants,AbstractConstants,Axioms,Theorems) :-
751 add_context_occurrences(LSets1,Name,LSets),
752 add_context_occurrences(LCsts1,Name,LCsts),
753 add_context_occurrences(LAbsCsts1,Name,LAbsCsts),
754 append(LSets,RSets,Sets),
755 append(LCsts,RCsts,Constants),
756 append(LAbsCsts,RAbsCsts,AbstractConstants),
757 append(LAxms,RAxms,Axioms),
758 append(LThms,RThms,Theorems),
759 collect_context_infos(Rest,RSets,RCsts,RAbsCsts,RAxms,RThms).
760 add_context_occurrences([],_,[]).
761 add_context_occurrences([Constant|Crest],Name,[CC|CCrest]) :-
762 add_texpr_infos(Constant,[occurrences([Name])],CC),
763 add_context_occurrences(Crest,Name,CCrest).
764
765
766 % merge the events and write them to a machine
767 create_events(AnimatedModels,AnimatedSectionNames) -->
768 {get_events(AnimatedModels,AnimatedSectionNames,Events,Initialisation,Promoted)},
769 append_to_section(operation_bodies,Events),
770 bmachine_construction:write_section(initialisation,Initialisation),
771 append_to_section(promoted,Promoted).
772
773 % merge the events of multiple refinement levels
774 get_events([],_,[],Initialisation,[]) :- !,
775 create_texpr(skip,subst,[],Initialisation).
776 get_events(AnimatedModels,AnimatedSectionNames,Events,Initialisation,Promoted) :-
777 get_events_to_animate(AnimatedModels,AnimEvents),
778 merge_refinement_levels(AnimEvents,AnimatedModels,AnimatedSectionNames,MergedEvents,Promoted1),
779 remove_initialisation(Promoted1,Promoted2),
780 add_op_parenthesis(Promoted2,Promoted),
781 select_initialisation(MergedEvents,PreOps,Initialisation),
782 create_operations(PreOps,Events).
783 remove_initialisation(In,Out) :-
784 get_texpr_id(Expr,'INITIALISATION'),
785 ? select(Expr,In,Out),!.
786 remove_initialisation(In,Out) :-
787 % add_error(check_event_b_project,'Model has no INITIALISATION'), %err msg already generated below
788 Out=In.
789 add_op_parenthesis([],[]).
790 add_op_parenthesis([Old|ORest],[New|NRest]) :-
791 def_get_texpr_id(Old,Id),
792 rename_bt(Old,[rename(Id,op(Id))],New),
793 add_op_parenthesis(ORest,NRest).
794
795 select_initialisation(In,Ops,Init) :-
796 ? select(eventop('INITIALISATION',Section,[],Init1,op([],[]),_),In,Ops),!,
797 add_texpr_infos(Init1,[eventb(Section)],Init).
798 select_initialisation(In,Ops,Init) :-
799 add_error(select_initialisation,'Model has no INITIALISATION'),
800 Init = b(skip,subst,[]), % replace skip by non-det assign
801 Ops=In.
802 create_operations([],[]).
803 create_operations([E|ERest],[O|ORest]) :-
804 create_operation(E,O),
805 create_operations(ERest,ORest).
806 create_operation(eventop(Name,Section,Parameters,Subst,Type,Refines),Operation) :-
807 create_texpr(identifier(op(Name)),Type,[],Id),
808 get_texpr_info(Subst,SubstInfo),
809 Mod=modifies(_),memberchk(Mod,SubstInfo),
810 Reads=reads(_),memberchk(Reads,SubstInfo),
811 (Refines == [] -> RefInfo = RestInfo ; RefInfo = [refines(Refines)|RestInfo]),
812 (extract_description(Subst,Desc) -> RestInfo = [description(Desc)] ; RestInfo=[]), % we could also do a findall
813 create_texpr(operation(Id,[],Parameters,Subst),Type,[eventb(Section),Mod,Reads|RefInfo],Operation).
814
815 :- use_module(probsrc(bsyntaxtree),[get_texpr_description/2]).
816 extract_description(Subst,Desc) :-
817 get_texpr_description(Subst,Desc).
818 extract_description(Subst,Desc) :- get_direct_abstract_event(Subst,ASubst),
819 extract_description(ASubst,Desc).
820
821 get_direct_abstract_event(b(RefLvlEvent,subst,_),AbsEvent) :-
822 RefLvlEvent = rlevent(_Name,_Sect,_Stat,_Paras,_Grd,_Thm,_Act,_VWit,_PWit,_Unmod,AbsEvents),
823 member(AbsEvent,AbsEvents).
824
825 get_events_to_animate([Model|_],Events) :- internal_model_events(Model,_,Events).
826
827 merge_refinement_levels([],_,_,[],[]).
828 merge_refinement_levels([Event|ERest],AnimModels,AnimatedSectionNames,[Merged|MRest],[Prom|PRest]) :-
829 merge_refinement_levels2(Event,AnimModels,AnimatedSectionNames,Merged,Prom),
830 merge_refinement_levels(ERest,AnimModels,AnimatedSectionNames,MRest,PRest).
831
832 merge_refinement_levels2(Event,AnimatedLevels,AnimatedSectionNames,
833 eventop(Name,Section,Parameters,Subst,OpType,Refines),Prom) :-
834 AnimatedLevels = [CurrentLevel|_Abstractions],
835 internal_model(CurrentLevel,Section),
836 internal_event_params(Event,Name,Parameters),
837 internal_event_refined(Event,Name,Refines),
838 %merge_parameters(Refines,Parameters,_Abstractions,MergedParameters),
839 merge_events_to_subst(Name,AnimatedLevels,AnimatedSectionNames,[],Subst1),
840 optimise_events(Subst1,Subst),
841 get_texpr_types(Parameters,Types),OpType = op(Types,[]),
842 create_texpr(identifier(Name),OpType,[],Prom).
843
844 gen_description_term(Desc,description(Desc)).
845
846 merge_events_to_subst(Name,[CurrentLevel|Abstractions],AnimatedSectionNames,RefinedParameters,TEvent) :-
847 create_texpr(RefLevelEvent,subst,[modifies(Vars),reads(Reads)|RestInfos],TEvent),
848 RefLevelEvent = rlevent(Name,Section,Status,Params,Guard,Theorems,Actions,
849 VWitnesses,PWitnesses,Unmodifiables,AbstractEvents),
850 InternalEvent = tc_event(Name,Section,Status,AllParams,Guard,Theorems,Actions,
851 VWitnesses1,PWitnesses1,Unmodifiables,Refines,Desc),
852 get_event_from_model(Name,CurrentLevel,InternalEvent),
853 strip_witnesses(VWitnesses1,AnimatedSectionNames,VWitnesses),
854 strip_witnesses(PWitnesses1,AnimatedSectionNames,PWitnesses),
855 remove_refined_parameters(AllParams,RefinedParameters,Params),
856 maplist(gen_description_term,Desc,RestInfos),
857 ( Abstractions = [] ->
858 AbstractEvents = []
859 ;
860 append(RefinedParameters,Params,NewRefinedParameters),
861 merge_events_to_subst_l(Refines,Abstractions,AnimatedSectionNames,NewRefinedParameters,AbstractEvents1),
862 normalise_merged_events(AbstractEvents1,AbstractEvents)
863 ),
864 collect_modified_vars(Actions,AbstractEvents,Vars),
865 collect_read_vars(Status,AllParams,Guard,Theorems,Actions,VWitnesses,PWitnesses,Unmodifiables,AbstractEvents,Reads).
866 merge_events_to_subst_l([],_,_,_,[]).
867 merge_events_to_subst_l([Name|NRest],Abstractions,AnimatedSectionNames,RefinedParameters,[TEvent|TRest]) :-
868 merge_events_to_subst(Name,Abstractions,AnimatedSectionNames,RefinedParameters,TEvent),
869 merge_events_to_subst_l(NRest,Abstractions,AnimatedSectionNames,RefinedParameters,TRest).
870
871 % removes a witness completely if the witnessed variable belongs
872 % to a refinement level that is not animated or removes part of the
873 % witness-predicate if references to not animated levels are made.
874 strip_witnesses([],_AnimatedSectionNames,[]).
875 strip_witnesses([Witness|WRest],AnimatedSectionNames,Result) :-
876 strip_witness(Witness,AnimatedSectionNames,StrippedWitness),
877 append(StrippedWitness,SWRest,Result),
878 strip_witnesses(WRest,AnimatedSectionNames,SWRest).
879 strip_witness(Witness,AnimatedSectionNames,StrippedWitness) :-
880 get_texpr_expr(Witness,witness(W,P)),
881 ( abstraction_var_occures(W,AnimatedSectionNames) ->
882 % The abstract variable is not animated, skip the complete witness
883 StrippedWitness = []
884 ;
885 conjunction_to_list(P,Preds),
886 remove_linking_parts(Preds,AnimatedSectionNames,SPreds),
887 conjunct_predicates(SPreds,SP),
888 get_texpr_type(Witness,Type),
889 get_texpr_info(Witness,Info),
890 create_texpr(witness(W,SP),Type,Info,TWitness),
891 StrippedWitness = [TWitness]).
892
893 remove_refined_parameters([],_RefinedParameters,[]).
894 remove_refined_parameters([Param|APRest],RefinedParameters,Parameters) :-
895 ( find_identifier_in_list(Param,RefinedParameters,_RefParam) ->
896 Parameters = PRest
897 ;
898 Parameters = [Param|PRest]),
899 remove_refined_parameters(APRest,RefinedParameters,PRest).
900
901 /* currently commented out :
902 merge_parameters([],Parameters,_Abstractions,Parameters).
903 merge_parameters([_|_],Parameters,[],Parameters) :- !.
904 merge_parameters([Refines|Rest],OldParameters,Abstractions,Parameters) :-
905 Abstractions = [Abstract|FurtherAbstractions],
906 get_event_from_model(Refines,Abstract,Event),
907 internal_event_params(Event,_,NewParameters),
908 internal_event_refined(Event,_,NewRefines),
909 add_unique_parameters(NewParameters,OldParameters,Parameters2),
910 merge_parameters(NewRefines,Parameters2,FurtherAbstractions,Parameters3),
911 merge_parameters(Rest,Parameters3,Abstractions,Parameters).
912 add_unique_parameters([],Parameters,Parameters).
913 add_unique_parameters([P|PRest],InParameters,OutParameters) :-
914 ( find_identifier_in_list(P,InParameters,_) ->
915 !,Parameters = InParameters
916 ;
917 Parameters = [P|InParameters]),
918 add_unique_parameters(PRest,Parameters,OutParameters).
919 */
920
921 get_event_from_model(Name,Model,Event) :-
922 internal_model_events(Model,_,Events),
923 internal_event(Event,Name),
924 ? member(Event,Events),!.
925
926 collect_modified_vars(Actions,Events,Vars) :-
927 get_modified_vars_of_actions(Actions,M1),
928 append_modified_vars_of_events(Events,M2),
929 append(M1,M2,M3),sort(M3,Vars).
930 get_modified_vars_of_actions([],[]).
931 get_modified_vars_of_actions([Action|Arest],Vars) :-
932 get_modified_vars_of_action(Action,Vlocal),
933 append(Vlocal,Vrest,Vars),
934 get_modified_vars_of_actions(Arest,Vrest).
935 get_modified_vars_of_action(Action,Vars) :-
936 get_texpr_info(Action,Infos),
937 ? member(modifies(Vars), Infos),!.
938
939 add_modified_vars_to_actions([],[]).
940 %add_modified_vars_to_actions([TAction|ARest],MRest) :-
941 % get_texpr_expr(TAction,skip),!, % remove skip actions % for Daniel: is this better than keeping them ??
942 % add_modified_vars_to_actions(ARest,MRest).
943 add_modified_vars_to_actions([TAction|ARest],[MAction|MRest]) :-
944 (add_modified_vars_to_action(TAction,MAction) ->true
945 ; add_internal_error('Call failed: ',add_modified_vars_to_action(TAction,MAction)),
946 MAction = TAction),
947 add_modified_vars_to_actions(ARest,MRest).
948 add_modified_vars_to_action(TAction,MAction) :-
949 get_lhs_ids(TAction,Vars),
950 maplist(prime_id,Vars,Primed),
951 add_texpr_infos(TAction,[assigned_after(Primed),modifies(Vars)],MAction).
952
953 get_lhs_ids(TAction,Ids) :-
954 get_lhs_tids(TAction,Vars),
955 get_texpr_ids(Vars,Ids).
956 get_lhs_tids(TAction,Vars) :-
957 get_texpr_expr(TAction,Action),
958 split_lhs_rhs(Action,Lhs,_),
959 extract_lhs_ids(Lhs,Vars).
960
961 split_lhs_rhs(skip,[],[]). % not needed as skip removed above
962 split_lhs_rhs(assign(Ids,Exprs),Ids,Exprs).
963 split_lhs_rhs(assign_single_id(Id,Expr),[Id],[Expr]).
964 split_lhs_rhs(becomes_element_of(Ids,Expr),Ids,[Expr]).
965 split_lhs_rhs(becomes_such(Ids,Pred),Ids,[Pred]).
966 split_lhs_rhs(evb2_becomes_such(Ids,Pred),Ids,[Pred]).
967 extract_lhs_ids([],[]).
968 extract_lhs_ids([TId|TRest],[Var|VRest]) :-
969 extract_lhs_id(TId,Var),
970 extract_lhs_ids(TRest,VRest).
971 extract_lhs_id(Id,Var) :-
972 get_texpr_id(Id,_),!,Var=Id.
973 extract_lhs_id(Func,Var) :-
974 get_texpr_expr(Func,function(Id,_)),
975 get_texpr_id(Id,Var).
976
977 append_modified_vars_of_events(Events,Vars) :-
978 append_modified_vars_of_events2(Events,Unsorted),
979 sort(Unsorted,Vars).
980 append_modified_vars_of_events2([],[]).
981 append_modified_vars_of_events2([TEvent|ERest],Vars) :-
982 get_modified_vars_of_event(TEvent,Local),
983 append(Local,VRest,Vars),
984 append_modified_vars_of_events2(ERest,VRest).
985 get_modified_vars_of_event(TEvent,Local) :-
986 get_texpr_info(TEvent,Info),
987 memberchk(modifies(Local),Info).
988
989 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
990 % get all the variables that are accessed in an event (cf also get_accessed_vars2 in b_read_write_info.pl)
991 collect_read_vars(Status,AllParams,Guard,Theorems,Actions,VWitnesses,PWitnesses,Unmodifiables,AbstractEvents,Reads) :-
992 find_variant_reads([],Status,VariantVars), % the variant cannot use params (!?)
993 get_texpr_ids(AllParams,Params), % access to parameters is not reading a variable
994 find_identifier_uses(Guard,Params,GrdVars),
995 find_identifier_uses_l(Theorems,Params,ThmVars),
996 find_identifier_uses_l(Unmodifiables,Params,UnmodVars), % for check_if_invalid_vars_are_modified we need read access
997 maplist(find_all_action_reads(Params),Actions,ActVars0), ord_union(ActVars0, ActVars),
998 maplist(find_all_witness_reads(Params),VWitnesses,VWitVars0), ord_union(VWitVars0,VWitVars),
999 maplist(find_all_witness_reads(Params),PWitnesses,PWitVars0), ord_union(PWitVars0,PWitVars),
1000 join_abstract_reads(AbstractEvents,AbstrVars),
1001 ord_union([VariantVars,GrdVars,ThmVars,UnmodVars,ActVars,VWitVars,PWitVars,AbstrVars],Reads).
1002
1003 find_variant_reads(Ignore,TVariant,Res) :-
1004 get_texpr_expr(TVariant,Variant),
1005 (find_variant_reads2(Variant,Ignore,Vars) -> Res=Vars
1006 ; add_internal_error('Illegal variant: ',find_variant_reads2(Variant,Ignore,_)),Res=[]).
1007 find_variant_reads2(convergent(TExpr),Ignore,Vars) :- find_identifier_uses(TExpr,Ignore,Vars).
1008 find_variant_reads2(anticipated(TExpr),Ignore,Vars) :- find_identifier_uses(TExpr,Ignore,Vars).
1009 find_variant_reads2(ordinary,_,[]).
1010
1011 %find_all_identifiers(Ignore,Expr,Vars) :-
1012 % find_identifier_uses(Expr,Ignore,Vars). % Just switch arguments to allow the use of maplist
1013 find_all_action_reads(Ignore,TAction,Res) :-
1014 get_texpr_expr(TAction,Action),
1015 (find_action_reads2(Action,Ignore,Vars) -> Res=Vars
1016 ; add_internal_error('Illegal action: ',find_action_reads2(Action,Ignore,_)),Res=[]).
1017 find_action_reads2(skip,_,Vars) :- Vars=[].
1018 find_action_reads2(assign(_,Exprs),Ignore,Vars) :- find_identifier_uses_l(Exprs,Ignore,Vars).
1019 find_action_reads2(assign_single_id(_,Expr),Ignore,Vars) :- find_identifier_uses(Expr,Ignore,Vars).
1020 find_action_reads2(becomes_element_of(_,Expr),Ignore,Vars) :- find_identifier_uses(Expr,Ignore,Vars).
1021 find_action_reads2(becomes_such(Ids,Pred),Ignore,Vars1) :-
1022 % all references to Ids are to the state after: not a read
1023 get_texpr_ids(Ids,AtomicIds),
1024 append(AtomicIds,Ignore,Ignore0),sort(Ignore0,Ignore1),
1025 find_identifier_uses(Pred,Ignore1,Vars),
1026 prime_identifiers0(Ids,Ids0), % Ids with $0 afterwards
1027 get_texpr_ids(Ids0,AtomicIds0),
1028 maplist(unprime_id(AtomicIds0,AtomicIds),Vars,Vars1).
1029 %find_action_reads2(evb2_becomes_such(Ids,Pred),Ignore,Vars) :-
1030 % prime_variables(Ids,PIds),get_texpr_ids(PIds,Primes),
1031 % append(Primes,Ignore,Ignore0),sort(Ignore0,Ignore1),
1032 % find_identifier_uses(Pred,Ignore1,Vars).
1033 find_all_witness_reads(Ignore,Witness,Vars) :-
1034 get_texpr_expr(Witness,witness(I,P)),
1035 get_texpr_id(I,Id),
1036 sort([Id|Ignore],Ignore2),
1037 find_identifier_uses(P,Ignore2,Vars1),
1038 % a small hack to remove the primed variables that refer to the after-state
1039 % without the need to put all variables in the Ingore list:
1040 exclude(is_primed_id,Vars1,Vars).
1041
1042 join_abstract_reads([],[]) :- !.
1043 join_abstract_reads(AbstractEvents,Reads) :-
1044 maplist(get_read_from_info,AbstractEvents,AbsReads),
1045 ord_union(AbsReads,ReadBySome),
1046 maplist(get_modifies_from_info,AbstractEvents,AbsModifies),
1047 ord_union(AbsModifies,ModifiedBySome),
1048 ord_intersection(AbsModifies,ModifiedByAll),
1049 ord_subtract(ModifiedBySome,ModifiedByAll,ModifiedByNotAll),
1050 ord_union(ReadBySome,ModifiedByNotAll,Reads).
1051 get_read_from_info(AbstrEvents,Reads) :-
1052 get_texpr_info(AbstrEvents,Info),memberchk(reads(Reads),Info).
1053 get_modifies_from_info(AbstrEvents,Modifies) :-
1054 get_texpr_info(AbstrEvents,Info),memberchk(modifies(Modifies),Info).
1055
1056 add_equality_check(Actions,AbstractActions,NewVars,Variables,Unmodifiables) :-
1057 get_modified_vars_of_actions(Actions,Modified),
1058 get_modified_vars_of_actions(AbstractActions,AbstractModified),
1059 unmodifiables(Modified,AbstractModified,NewVars,Variables,Unmodifiables).
1060 unmodifiables([],_AbstractModified,_NewVars,_Variables,[]).
1061 unmodifiables([UM|Modified],AbstractModified,NewVars,Variables,Unmodifiables) :-
1062 ? ( is_modifiable(UM,AbstractModified,NewVars) ->
1063 Unmodifiables = UMrest
1064 ;
1065 get_texpr_id(TUM,UM),
1066 member(TUM,Variables),!,
1067 Unmodifiables = [TUM|UMrest]),
1068 unmodifiables(Modified,AbstractModified,NewVars,Variables,UMrest).
1069 % the abstract event modifies it, so we can do it, too
1070 is_modifiable(UM,AbstractModified,_NewVars) :- member(UM,AbstractModified),!.
1071 % the variables is newly introduced, so we can modifiy it
1072 is_modifiable(UM,_AbstractModified,NewVars) :-
1073 ? get_texpr_id(TUM,UM), member(TUM,NewVars).
1074
1075 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1076 % normalising merged events means that if two refined events A and B
1077 % change a different set of variables then the event A gets an additional
1078 % assignment of the form x:=x with x as a variable that is changed in B
1079 % but not in A.
1080 % This can happen even though merged events have the same assignments because
1081 % they again can refine events that have different assignments.
1082
1083 % None or one refined event do not have to be normalised
1084 normalise_merged_events([],[]) :- !.
1085 normalise_merged_events([E],[E]) :- !.
1086 normalise_merged_events(Events,Normalised) :-
1087 append_modified_vars_of_events(Events,AllModifiedVars),
1088 find_typed_version_in_events(AllModifiedVars,Events,TypedVars),
1089 normalise_merged_events2(Events,AllModifiedVars,TypedVars,Normalised).
1090 normalise_merged_events2([],_AllModifiedVars,_TypedVars,[]).
1091 normalise_merged_events2([Event|Erest],AllModifiedVars,TypedVars,[Normalised|Nrest]) :-
1092 normalise_merged_event(Event,AllModifiedVars,TypedVars,Normalised),
1093 normalise_merged_events2(Erest,AllModifiedVars,TypedVars,Nrest).
1094 normalise_merged_event(Event,AllModifiedVars,TypedVars,Normalised) :-
1095 get_modified_vars_of_event(Event,Modified),
1096 remove_all(AllModifiedVars,Modified,MissingVars),
1097 add_missing_assignments(MissingVars,Event,AllModifiedVars,TypedVars,Normalised).
1098 add_missing_assignments([],Event,_,_,Event) :- !.
1099 add_missing_assignments(MissingVars,TEvent,AllModifiedVars,TypedVars,Normalised) :-
1100 get_texpr_expr(TEvent,Event),
1101 get_texpr_type(TEvent,Type),
1102 get_texpr_info(TEvent,Infos),
1103 selectchk(modifies(_),Infos,RestInfos), % TO DO: also add reads Information
1104 create_texpr(NewEvent,Type,[modifies(AllModifiedVars)|RestInfos],Normalised),
1105 Event = rlevent(Name,Sec,St,Prm,Grd,Thm,Actions,VWit,PWit,Unmod,AbsEvents),
1106 NewEvent = rlevent(Name,Sec,St,Prm,Grd,Thm,NewActions,VWit,PWit,Unmod,AbsEvents),
1107 append(Actions,NewAssignments,NewActions),
1108 create_missing_assignments(MissingVars,TypedVars,NewAssignments).
1109 create_missing_assignments([],_TypedVars,[]).
1110 create_missing_assignments([MissingVar|Mrest],TypedVars,[Assign|Arest]) :-
1111 create_missing_assignment(MissingVar,TypedVars,Assign),
1112 create_missing_assignments(Mrest,TypedVars,Arest).
1113 create_missing_assignment(Var,TypedVars,Assignment) :-
1114 get_texpr_id(TId,Var),
1115 memberchk(TId,TypedVars),
1116 prime_id(Var,Primed),
1117 create_texpr(assign([TId],[TId]),subst,[assigned_after(Primed),modifies(Var)],Assignment).
1118
1119 find_typed_version_in_events([],_Events,[]).
1120 find_typed_version_in_events([Name|Nrest],Events,[Typed|Trest]) :-
1121 find_typed_version_in_events2(Name,Events,Typed),
1122 find_typed_version_in_events(Nrest,Events,Trest).
1123 find_typed_version_in_events2(Name,Events,Typed) :-
1124 get_texpr_id(Typed,Name),
1125 member(Event,Events),
1126 get_texpr_expr(Event,rlevent(_Name,_Sec,_St,_Prm,_Grd,_Thm,Actions,_VWit,_PWit,_Unmod,AbsEvents)),
1127 find_typed_version_in_events3(Name,Actions,AbsEvents,Typed),!.
1128 find_typed_version_in_events3(_Name,Actions,_AbsEvents,Typed) :-
1129 member(Action,Actions),
1130 get_lhs_tids(Action,Vars),
1131 member(Typed,Vars),!.
1132 find_typed_version_in_events3(Name,_Actions,AbsEvents,Typed) :-
1133 find_typed_version_in_events2(Name,AbsEvents,Typed).
1134
1135 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1136 % optimisation of guards:
1137 % A guard in a refinement does not need to be evaluated in in an abstract event
1138 % again. This happens quite frequently, especially if "extends" is used.
1139 % The same applies for assignments: If in a refinement an action is performed,
1140 % we do not have to check if the same action can be performed in a more abstract
1141 % level.
1142 optimise_events(TEvent,NTEvent) :-
1143 empty_avl(Empty),
1144 optimise_events2(Empty,TEvent,NTEvent).
1145 optimise_events2(KnownElements,TEvent,NTEvent) :-
1146 create_texpr(Event,Type,Infos,TEvent),
1147 create_texpr(NewEvent,Type,Infos,NTEvent),
1148 Event = rlevent(Name,Section,Status,Params,OldGuard,OldTheorems,OldActions,
1149 VWitnesses,PWitnesses,Unmodifiables,OldAbstractEvents),
1150 NewEvent = rlevent(Name,Section,Status,Params,NewGuard,NewTheorems,NewActions,
1151 VWitnesses,PWitnesses,Unmodifiables,NewAbstractEvents),
1152 optimise_guards(OldGuard,OldTheorems,KnownElements,NewGuard,NewTheorems,KnownElements1),
1153 optimise_formulas(OldActions,KnownElements1,NewActions,NewKnownElements),
1154 maplist(optimise_events2(NewKnownElements),OldAbstractEvents,NewAbstractEvents).
1155 optimise_guards(OldGuard,OldTheorems,KnownElements,NewGuard,NewTheorems,NewKnownElements) :-
1156 conjunction_to_list(OldGuard,OldGuards),
1157 optimise_formulas(OldGuards,KnownElements,NewGuards,KnownElements1),
1158 % If no elements were removed, we just use the old guard
1159 (OldGuards=NewGuards -> OldGuard=NewGuard ; conjunct_predicates(NewGuards,NewGuard)),
1160 optimise_formulas(OldTheorems,KnownElements1,NewTheorems,NewKnownElements).
1161 % optimise_formulas(+AllFormulas,+KnownElements,-NewFormulas,-NewNormed)
1162 % AllFormulas: A list of formulas
1163 % KnownElementes: A list of normed versions of already encountered elements
1164 % NewFormulas: A sub-list of AllFormulas which are new (not in KnownElements)
1165 % NewKnownElements: The updated list of already encountered elements
1166 % If no formulas are removed, it is guaranteed that NewFormulas=AllFormulas
1167 optimise_formulas(AllFormulas,KnownElements,NewFormulas,NewKnownElements) :-
1168 % convert formulas to a list: Formula/Normed where Normed is a normalised form
1169 maplist(add_stripped_ast,AllFormulas,AllFormNormed),
1170 % remove the already known formulas
1171 exclude(is_duplicate_formula(KnownElements),AllFormNormed,NewFormNormed),
1172 % split the list [Form/Normed] into [Form] and [Normed]
1173 maplist(unzipslash,NewFormNormed,NewFormulas1,NewNormed),
1174 ( AllFormNormed = NewFormNormed -> % No formulas removed, keep everything as it is
1175 NewFormulas = AllFormulas
1176 ;
1177 NewFormulas = NewFormulas1
1178 ),
1179 foldl(add_to_known_elements,NewNormed,KnownElements,NewKnownElements).
1180 add_stripped_ast(Formula,Formula/Stripped) :-
1181 strip_and_norm_ast(Formula,Stripped).
1182 is_duplicate_formula(KnownElements,_Formula/Stripped) :-
1183 avl_fetch(Stripped,KnownElements). % remark: if some ast_cleanup operations introduce fresh identifiers (e.g., comp_result) then we may not detect formulas as identical here !
1184 unzipslash(A/B,A,B).
1185 add_to_known_elements(New,In,Out) :-
1186 avl_store(New,In,true,Out).
1187
1188 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1189 % internal event handling (just data structure)
1190 internal_event(tc_event(Name,_Section,_Status,_Params,_Grd,_Thm,_Act,_VWit,_PWit,_Unmod,_Ref,_),Name).
1191 internal_event_status(tc_event(Name,_Section,Status,_Params,_Grd,_Thm,_Act,_VWit,_PWit,_Unmod,_Ref,_),Name,Status).
1192 internal_event_params(tc_event(Name,_Section,_Status,Params,_Grd,_Thm,_Act,_VWit,_PWit,_Unmod,_Ref,_),Name,Params).
1193 %internal_event_guards(tc_event(Name,_Section,_Status,_Params,Grd,_Thm,_Act,_VWit,_PWit,_Unmod,_Ref,_),Name,Grd).
1194 internal_event_actions(tc_event(Name,_Section,_Status,_Params,_Grd,_Thm,Act,_VWit,_PWit,_Unmod,_Ref,_),Name,Act).
1195 internal_event_refined(tc_event(Name,_Section,_Status,_Params,_Grd,_Thm,_Act,_VWit,_PWit,_Unmod,Ref,_),Name,Ref).
1196 %internal_event_description(tc_event(_,_,_,_,_,_,_,_,_,_,_,DescList),Desc) :- member(Desc,DescList).
1197
1198 internal_context(context(Name,_Extends,_Sets,_Constants,_AbstractConstants,_Axioms,_Theorems),Name).
1199 internal_context_extends(context(Name,Extends,_Sets,_Constants,_AbstractConstants,_Axioms,_Theorems),Name,Extends).
1200 internal_context_sets(context(Name,_Extends,Sets,_Constants,_AbstractConstants,_Axioms,_Theorems),Name,Sets).
1201 internal_context_constants(context(Name,_Extends,_Sets,Constants,_AbstractConstants,_Axioms,_Theorems),Name,Constants).
1202 internal_context_abstract_constants(context(Name,_Extends,_Sets,_Constants,AbstractConstants,_Axioms,_Theorems),Name,AbstractConstants).
1203
1204 internal_model(model(Name,_Refines,_Sees,_Variables,_NewVariables,_Invariants,_Theorems,_Events),Name).
1205 internal_model_refines(model(Name,Refines,_Sees,_Variables,_NewVariables,_Invariants,_Theorems,_Events),Name,Refines).
1206 internal_model_sees(model(Name,_Refines,Sees,_Variables,_NewVariables,_Invariants,_Theorems,_Events),Name,Sees).
1207 internal_model_vars(model(Name,_Refines,_Sees,Variables,_NewVariables,_Invariants,_Theorems,_Events),Name,Variables).
1208 internal_model_newvars(model(Name,_Refines,_Sees,_Variables,NewVariables,_Invariants,_Theorems,_Events),Name,NewVariables).
1209 internal_model_invs(model(Name,_Refines,_Sees,_Variables,_NewVariables,Invariants,_Theorems,_Events),Name,Invariants).
1210 internal_model_thms(model(Name,_Refines,_Sees,_Variables,_NewVariables,_Invariants,Theorems,_Events),Name,Theorems).
1211 internal_model_events(model(Name,_Refines,_Sees,_Variables,_NewVariables,_Invariants,_Theorems,Events),Name,Events).
1212
1213 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1214 % analyse deferred sets and generate enumerated sets if possible
1215
1216
1217
1218
1219 %% :- include(bmachine_eventb_common).
1220 %% code below used to be in separate file, as there was the single-level and multi-level mode:
1221
1222
1223
1224 extract_name(event_b_model(_,Name,_Sections),Res) :- !, Res=Name.
1225 extract_name(event_b_context(_,Name,_Sections),Res) :- !, Res=Name.
1226 extract_name(MODEL,_) :- add_error(extract_name,'Could not extract model name: ',MODEL),fail.
1227
1228 extract_sections(event_b_model(_,_Name,Sections),Sections).
1229 extract_sections(event_b_context(_,_Name,Sections),Sections).
1230
1231 % topological sort
1232
1233 topological_sort(List,Sorted) :-
1234 get_dependencies(List,Dependencies),
1235 topolsort(Dependencies,[],SortedNames),
1236 get_sorted(SortedNames,List,Sorted),!.
1237 topological_sort(List,Sorted) :- add_failed_call_error(topological_sort(List,Sorted)),fail.
1238
1239 get_dependencies([],[]).
1240 get_dependencies([E|Rest],[dep(Name,Deps)|Drest]) :-
1241 extract_name(E,Name),
1242 findall(D,dependency(E,D),Deps1),
1243 sort(Deps1,Deps),
1244 get_dependencies(Rest,Drest).
1245
1246 dependency(Elem,Dependend) :-
1247 extract_sections(Elem,Sections),
1248 ( rawmachine_section(extends,Sections,Extends),
1249 member(Dependend,Extends)
1250 ; rawmachine_section(refines,Sections,Dependend)).
1251
1252 topolsort([],_,[]) :- !.
1253 topolsort(Deps,Fulfilled,[First|Rest]) :-
1254 ? select(dep(First,Before),Deps,Drest),
1255 is_sublist(Before,Fulfilled),!,
1256 sort([First|Fulfilled],NewFulfilled),
1257 topolsort(Drest,NewFulfilled,Rest).
1258 is_sublist([],_).
1259 is_sublist([H|T],[F|R]) :-
1260 (H=F -> is_sublist(T,R) ; is_sublist([H|T],R)).
1261
1262 get_sorted([],_,[]).
1263 get_sorted([Name|Nrest],Elems,[First|Srest]) :-
1264 ? member(First,Elems),
1265 extract_name(First,Name),!,
1266 get_sorted(Nrest,Elems,Srest).
1267
1268 % copy&paste from bmachine_construction
1269 rawmachine_section(Elem,List,Result) :-
1270 functor(Pattern,Elem,2),
1271 arg(2,Pattern,Result),
1272 ? member(Pattern,List),!.
1273
1274 optional_rawmachine_section(Elem,List,Default,Result) :-
1275 ( rawmachine_section(Elem,List,Result1) -> true
1276 ; Result1=Default),
1277 Result1=Result.
1278
1279 % ----------------------------------------
1280
1281
1282 % older versions of the .eventb files do not have a status included
1283 raw_event(event(Pos,Name,RawRefines,Params,Guards,Actions,Witnesses), % event/7
1284 Pos,Name,ordinary(none),Refines,Params,Guards,[],Actions,Witnesses,[]) :-
1285 (\+((RawRefines==[] ; RawRefines=[_|_]))
1286 -> add_error(b_machine_eventb,'Outdated .eventb format, ignoring refines:',RawRefines),
1287 Refines = []
1288 ; Refines=RawRefines).
1289 raw_event(event(Pos,Name,Status,Refines,Params,Guards,Actions,Witnesses), % event/8
1290 Pos,Name,Status,Refines,Params,Guards,[],Actions,Witnesses,[]).
1291 raw_event(event(Pos,Name,Status,Refines,Params,Guards,Theorems,Actions,Witnesses), % event/9
1292 Pos,Name,Status,Refines,Params,Guards,Theorems,Actions,Witnesses,[]).
1293 raw_event(description_event(_,Desc,Event),
1294 Pos,Name,Status,Refines,Params,Guards,Theorems,Actions,Witnesses,[DescText|TD]) :-
1295 unwrap_desc_pragma(Desc,DescText),
1296 raw_event(Event, Pos,Name,Status,Refines,Params,Guards,Theorems,Actions,Witnesses,TD),
1297 debug_format(19,'New style event ~w with description "~w"~n',[Name,DescText]).
1298
1299 % new parser now has specific position info here:
1300 unwrap_desc_pragma(description_text(_Pos,Desc),Res) :- !, Res=Desc.
1301 unwrap_desc_pragma(D,D).
1302
1303 % code common to bmachine_eventb.pl and bmachine_eventb_ml.pl
1304
1305 :- use_module(bmachine_structure,[select_section/5]).
1306 append_to_section(Section,List,Old,New) :-
1307 % todo: access to private elements of bmachine_construction
1308 select_section(Section,OldList,NewList,Old,New),
1309 append(OldList,List,NewList).
1310 conjunct_to_section(Section,Preds,Old,New) :-
1311 % todo: access to private elements of bmachine_construction
1312 select_section(Section,OldPred,NewPred,Old,New),
1313 conjunct_predicates([OldPred|Preds],NewPred).
1314
1315 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1316 % analyse Event-B deferred sets and generate enumerated sets if possible
1317
1318 enumerated_deferred_sets(Sets,Constants,Axioms,NewSets,NewConstants,NewAxioms,TSet,TElements) :-
1319 conjunct_predicates(Axioms,Axiom),
1320 conjunction_to_list(Axiom,Axiom2),
1321 enumerated_deferred_sets2(Sets,Constants,Axiom2,NewSets,NewConstants,NewAxioms,TSet,TElements).
1322
1323 enumerated_deferred_sets2([],Csts,Axioms,[],Csts,Axioms,[],[]).
1324 enumerated_deferred_sets2([Set|SetRest],Csts,Axioms,NewSets,NewCsts,NewAxioms,[TSet|TSetRest],TElementsAll) :-
1325 % case 1: the set is an enumerated set
1326 ? enumerated_deferred_set(Set,Csts,Axioms,ICsts,IAxioms,TSet,TElements),!,
1327 append(TElements,TElementsRest,TElementsAll),
1328 enumerated_deferred_sets2(SetRest,ICsts,IAxioms,NewSets,NewCsts,NewAxioms,TSetRest,TElementsRest).
1329 enumerated_deferred_sets2([Set|SetRest],Csts,Axioms,[Set|NewSets],NewCsts,NewAxioms,TSets,TElements) :-
1330 % case 2: the set is a normal deferred set
1331 enumerated_deferred_sets2(SetRest,Csts,Axioms,NewSets,NewCsts,NewAxioms,TSets,TElements).
1332
1333 enumerated_deferred_set(Set,Constants,Axioms,NewConstants,NewAxioms,Set,TElements) :-
1334 %% print(checking_for_enumerated_deferred_sets(Axioms)),nl,
1335 has_enumeration_axioms(Set,Elements,Axioms,NewAxioms),
1336 %% print(found_enumerated_set(Set)),nl, %%
1337 % remove Elem1,...,ElemN from the constants
1338 ? remove_constants(Elements,Constants,NewConstants),
1339 % add enumerated set information to the elements
1340 get_texpr_type(Set,SType),
1341 (SType=set(global(Type)) -> true
1342 ; add_error_and_fail(enumerated_deferred_set,'Unexpected Set: ',(Set:SType))),
1343 (typeset_enumerated(Elements,Type,TElements) -> true
1344 ; add_error_and_fail(enumerated_deferred_set,'Could not typeset: ',(Type,Elements))).
1345
1346
1347 has_enumeration_axioms(Set,Elements,AxiomsIn,AxiomsOut) :-
1348 ? has_partition_axioms(Set,Elements,AxiomsIn,AxiomsOut),!.
1349 has_enumeration_axioms(Set,Elements,AxiomsIn,AxiomsOut) :-
1350 % there in an axiom Set = {Elem1,...,ElemN}
1351 select_equal_extension_set_of_ids(Set,AxiomsIn,Axioms1,ExtSet,Elements),
1352 % check if all axioms needed for an enumeration are
1353 % present, and remove them
1354 % second case: All elements of the set are mutually unequal
1355
1356 % generate the unequalities we have to check for
1357 generate_unequals(Elements,Unequals),
1358 % check if they are all in the axioms, and remove them from the axioms
1359 (all_unequals_present(Unequals,Axioms1,AxiomsOut) -> true
1360 ; assertz(deferred_set_eq_wo_enumeration_axioms(Set,ExtSet)),
1361 write('Deferred set with equality but *not* recognized as enumerated set: '),
1362 translate:print_bexpr(Set), write(' = '), translate:print_bexpr(ExtSet),nl,
1363 fail
1364 ).
1365
1366 has_partition_axioms(Set,PartitionElements,AxiomsIn,AxiomsOut) :-
1367 % print(checking_for_enumeration_axioms(Set)),nl,
1368 % first case: A partion predicate is present with
1369 % all elements of the set as its arguments
1370 % ( e.g. partition(S,{a},{b},...) )
1371
1372 % create a pattern for the partition:
1373 get_texpr_id(Set,SetId),get_texpr_id(SetRef,SetId),
1374 create_texpr(partition(SetRef,Singletons),pred,_,Partition),
1375 % remove the partition from the axioms
1376 % print(looking_for_partition(SetId,Partition)),nl,nl,
1377 ? select(Partition,AxiomsIn,AxiomsOut1),
1378 %%print(found_partition(SetID,Partition)),nl,
1379 % check if all arguments are singletons and get the
1380 % singleton elements
1381 all_singletons(Singletons,PartitionElements,AxiomsOut1,AxiomsOut2,Recursive),
1382 (Recursive==true
1383 -> AxiomsOut=AxiomsIn /* then we still need the partition axioms */
1384 ; AxiomsOut=AxiomsOut2).
1385 %% ,print(all_singletons(Singletons)),nl.
1386 %% print(singletons(PartitionElements)),nl,
1387 % check if all arguments and the identifiers
1388 % of the set are the same
1389 % same_elements(Elements,PartitionElements).
1390
1391
1392 % all elements of a list are singletons, the second argument
1393 % returns the list of elements without the set around it
1394 all_singletons([],[],Ax,Ax,_).
1395 all_singletons([Set|SRest],[Expr|ERest],AxiomsIn,AxiomsOut,Recursive) :-
1396 get_texpr_expr(Set,set_extension([Expr])),!,
1397 all_singletons(SRest,ERest,AxiomsIn,AxiomsOut,Recursive).
1398 all_singletons([ID1|SRest],Result,AxiomsIn,AxiomsOut,Recursive) :-
1399 ID1 = b(identifier(_ID),set(global(_)),_Info),
1400 Recursive=true,
1401 % print(trying_to_look_for_recursive_partition(_ID)),nl, %%
1402 has_enumeration_axioms(ID1,PartitionElements,AxiomsIn,AxiomsOut1),
1403 % print(recursive_partition(ID,PartitionElements)),nl,
1404 append(PartitionElements,ERest,Result),
1405 all_singletons(SRest,ERest,AxiomsOut1,AxiomsOut,_).
1406
1407 % the two lists of typed identifiers have the same identifiers
1408 %same_elements(ElemsA,ElemsB) :-
1409 % get_texpr_ids(ElemsA,IdsA),sort(IdsA,A),
1410 % get_texpr_ids(ElemsB,IdsB),sort(IdsB,B),
1411 % A=B.
1412
1413 typeset_enumerated([],_Type,[]).
1414 typeset_enumerated([Elem|Erest],Type,[TElem|Trest]) :-
1415 create_texpr(identifier(Id),global(Type),Infos,Elem),
1416 create_texpr(identifier(Id),global(Type),[enumerated_set_element|Infos],TElem),
1417 typeset_enumerated(Erest,Type,Trest).
1418
1419 remove_constants([],Cst,Cst).
1420 remove_constants([TId|Erest],In,Out) :-
1421 get_texpr_id(TId,Id),
1422 get_texpr_id(Pattern,Id),
1423 ? select(Pattern,In,Env),
1424 ? remove_constants(Erest,Env,Out).
1425
1426 % find an equality Set = {id1,...,idk}
1427 select_equal_extension_set_of_ids(Set,In,Out,Ext,Elements) :-
1428 get_texpr_id(Set,SetId),
1429 get_texpr_id(Expr,SetId),
1430 create_texpr(set_extension(Elements),_,_,Ext),
1431 create_texpr(Equal,_,_,TEqual),
1432 ( Equal = equal(Expr,Ext); Equal = equal(Ext,Expr) ),
1433 ? select(TEqual,In,Out),!.
1434
1435 generate_unequals(Elements,Unequals) :-
1436 get_texpr_ids(Elements,Ids),
1437 findall(unequal(A,B),two_ids(Ids,A,B),Unequals).
1438 ?two_ids([A|Rest],A,B) :- member(B,Rest).
1439 ?two_ids([_|Rest],A,B) :- two_ids(Rest,A,B).
1440
1441 all_unequals_present([],Axioms,Axioms).
1442 all_unequals_present([unequal(A,B)|Rest],InAxioms,OutAxioms) :-
1443 remove_unequalities(InAxioms,A,B,IntAxioms,0,N), N>0,!, % at least one occurrence
1444 all_unequals_present(Rest,IntAxioms,OutAxioms).
1445
1446 remove_unequalities([],_,_,[],N,N).
1447 remove_unequalities([TAxiom|T],A,B,Rest,NrRemoved,R) :-
1448 get_texpr_id(AExpr,A), get_texpr_id(BExpr,B),
1449 get_texpr_expr(TAxiom,Axiom),
1450 is_unequality(Axiom,AExpr,BExpr),!, N1 is NrRemoved+1,
1451 remove_unequalities(T,A,B,Rest,N1,R).
1452 remove_unequalities([Axiom|T],A,B,[Axiom|TR],N,R) :- % not an unequality between A and B
1453 remove_unequalities(T,A,B,TR,N,R).
1454
1455 is_unequality(not_equal(A,B),A,B) :- !.
1456 is_unequality(not_equal(B,A),A,B) :- !.
1457 is_unequality(negation(TEqual),A,B) :-
1458 get_texpr_expr(TEqual,Equal),
1459 is_direct_equality(Equal,A,B).
1460 is_direct_equality(equal(A,B),A,B) :- !.
1461 is_direct_equality(equal(B,A),A,B) :- !.
1462
1463 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1464 % creating a type environment with information about theories inside
1465
1466 check_theory_extensions(Infos,Freetypes,Ops,TheoryEnv) :-
1467 findall( T, (member(T,Infos),is_eventb_additional_info(T)), Theories),
1468 default_theory_ops(InitialEnv),
1469 foldl(check_theory,Theories,FreetypesL,OpsL,InitialEnv,TheoryEnv),
1470 append(FreetypesL,Freetypes),
1471 append(OpsL,Ops).
1472 is_eventb_additional_info(Term) :-
1473 nonvar(Term),functor(Term,theory,Arity),
1474 memberchk(Arity,[3,4,5,7]).
1475 default_theory_ops(Env) :-
1476 env_empty(Empty),
1477 cond_operator(Id,Op),
1478 env_store_operator(Id,Op,Empty,Env).
1479 cond_operator('COND',bmachine_eventb:axiomatic_definition('COND',Params,DirectDef,[PT])) :-
1480 PT = '__IFTHENELSETYPE',
1481 TypeExpr = identifier(none,PT),
1482 Params = [argument('THEN',TypeExpr),
1483 argument('ELSE',TypeExpr),
1484 argument('IF',set_extension(none,[truth(none)]))],
1485 DirectDef = if_then_else(none,identifier(none,'IF'),
1486 identifier(none,'THEN'),identifier(none,'ELSE')).
1487 check_theory(Theory,Freetypes,Ops,Env,OutEnv) :-
1488 get_theory_name(Theory,Proj,Name),
1489 debug_format(19,'Checking theory ~w:~w~n',[Proj,Name]),
1490 (check_theory2(Theory,Env,_DefSets,Freetypes,Ops) -> true
1491 ; add_internal_error('Theory check failed:',Theory),fail),
1492 store_operator_list(Ops,Env,OutEnv),
1493 check_theory_axioms(Theory,OutEnv,_).
1494
1495 store_operator_list(Ops,Env,OutEnv) :-
1496 keys_and_values(Ops,Ids,Operators),
1497 foldl(env_store_operator,Ids,Operators,Env,OutEnv).
1498
1499 check_theory2(theory(PT,Datatypes,OP),Env,DefSets,Freetypes,Ops) :-
1500 % just to be backward-compatible to a version without axiomatic definitions
1501 check_theory2(theory(PT,Datatypes,OP,[]),Env,DefSets,Freetypes,Ops).
1502 check_theory2(theory(PT,Datatypes,OP,AxDefs),Env,DefSets,Freetypes,Ops) :-
1503 % just to be backward-compatible to a version without operator mapping
1504 % definitions
1505 check_theory2(theory(PT,Datatypes,OP,AxDefs,[]),Env,DefSets,Freetypes,Ops).
1506 check_theory2(theory(PT,Datatypes,OP,AxDefs,Mappings),Env,DefSets,Freetypes,Ops) :-
1507 check_theory2(theory(unknown,unknown,PT,Datatypes,OP,AxDefs,Mappings),Env,DefSets,Freetypes,Ops).
1508 check_theory2(theory(TheoryId,_Imported,TypeParameters,Datatypes,OP,AxDefs,Mappings),Env,DefSets,Freetypes,AllOps) :-
1509 %print_theory_axioms(TheoryId,TypeParameters,AxDefs),
1510 extract_freetypes(TheoryId,Env,Datatypes,Freetypes,FreetypeOps),
1511 (Mappings \= [_|_]
1512 -> generate_default_mappings(AxDefs,TheoryId,ML)
1513 ; debug_format(19,'Mappings in .ptm file: ~w~n',[Mappings]),
1514 ML=Mappings), % some older .eventb files seem to have none here, e.g., Theory/SumProduct_m1_mch.eventb
1515 debug_println(9,operator_mappings(ML)),
1516 findall(VirtualDefSet,unmapped_axiomatic_def_set(VirtualDefSet,AxDefs,ML),DefSets),
1517 maplist(store_virtual_deferred_set(TheoryId,TypeParameters),DefSets,DefSetOps),
1518 foldl(handle_mappings(TheoryId,TypeParameters),ML,MappedOpsL,OP/AxDefs,OP1/AxDefs1),
1519 append(MappedOpsL,MappedOps),
1520 maplist(store_operator(TheoryId,TypeParameters),OP1,DefinedOps),
1521 maplist(store_axiomatic_operator(TheoryId,TypeParameters),AxDefs1,AxOpsL),
1522 append(AxOpsL,AxOps),
1523 append([DefSetOps,FreetypeOps,MappedOps,DefinedOps,AxOps],AllOps1),
1524 % The operators are used for call-backs, a module prefix is mandatory
1525 maplist(prefix_with_module,AllOps1,AllOps).
1526
1527 unmapped_axiomatic_def_set(VirtualDefSet,AxDefs,ML) :-
1528 member(axiomatic_def_block(_AxDefId,AxTypes,_,_),AxDefs),
1529 member(VirtualDefSet,AxTypes), nonmember(tag(VirtualDefSet,_),ML).
1530
1531 % axiomatic blocks can contain new types; these seem to be just deferred sets (cf R0-MovingTrains_mch.eventb)
1532 store_virtual_deferred_set(TheoryId,TypeParameters,DefSet,Res) :- Parameters=[],RawWDCond=truth(none),
1533 ((DefSet='Real' ; DefSet='REAL') % in case no .ptm file exists, e.g., for Abrial's Real theory
1534 -> DirectDef=real_set(none),
1535 add_message(bmachine_eventb,'Translating axiomatic type to REAL: ',DefSet)
1536 ; DirectDef=string_set(none),
1537 add_message(bmachine_eventb,'Translating axiomatic type to STRING: ',DefSet)
1538 ), % TODO: translate to propert def. set!
1539 store_operator(TheoryId,TypeParameters,operator(DefSet,Parameters,RawWDCond,[DirectDef],[]),Res).
1540
1541 prefix_with_module(Id-Op,Id-(bmachine_eventb:Op)).
1542
1543 :- public print_theory_axioms/3.
1544 print_theory_axioms(TheoryId,TypeParameters,AxDefs) :- member(axiomatic_def_block(Id,Types,_OpDefsIn,Axioms),AxDefs),
1545 format('~nAxDef Block ~w (~w) in theory ~w (~w)~n',[Id,Types,TheoryId,TypeParameters]),
1546 translate:l_print_raw_bexpr(Axioms),
1547 fail.
1548 print_theory_axioms(_,_,_).
1549
1550
1551 check_theory_axioms(theory(TheoryId,_Imported,TypeParameters,_Datatypes,_OP,AxDefs,_Mappings),Env,TheoryAxioms) :-
1552 fail, % disabled; for tests 2295, 2379, 2382 there are unsupported axiomatic operators in the axioms
1553 maplist(create_deferred_set,TypeParameters,RawIds),
1554 create_sets(RawIds,TheoryId,Sets),
1555 add_unique_variables(Sets,Env,Env2),
1556 member(axiomatic_def_block(AxDefId,_Types,_OpDefsIn,RawAxioms),AxDefs),
1557 get_theory_name(TheoryId,Proj,Name), format('Typechecking block ~w in ~w:~w~n',[AxDefId,Proj,Name]),
1558 typecheck_l(RawAxioms,Env2,pred,TheoryAxioms,theory_axioms),
1559 translate:l_print_bexpr_or_subst(TheoryAxioms),nl,
1560 fail.
1561 check_theory_axioms(_,_Env,[]).
1562
1563 create_deferred_set(Atom,deferred_set(unknown,Atom)).
1564
1565 get_theory_name(theory_name(Project,TheoryName),ResP,ResN) :- !,
1566 ResP=Project, ResN=TheoryName.
1567 get_theory_name(Theory,ResP,ResN) :-
1568 functor(Theory,theory,_), arg(1,Theory,TN),!,
1569 get_theory_name(TN,ResP,ResN).
1570 get_theory_name(N,'','') :- format('Could not extract theory name: ~w~n',[N]).
1571
1572 store_operator(TheoryId,TypeParameters,operator(Id,Parameters,RawWDCond,DirectDef,RecursiveDef),Id-Op) :-
1573 store_operator2(TheoryId,TypeParameters,Id,DirectDef,RecursiveDef,Parameters,RawWDCond,TypeParameters,Op).
1574
1575 store_operator2(_,_,_,_,RecursiveDef,Parameters,_WD,TypeParameters,Op) :-
1576 RecursiveDef=[_|_],!,
1577 Op=recursive_operator(Parameters,RecursiveDef,TypeParameters).
1578 store_operator2(TheoryId,_,Id,[Def],_,Parameters,Raw_WDCond,TypeParameters,Op) :- !,
1579 %format('Storing direct definition operator ~w with WD: ~w~n',[Id,Raw_WDCond]),
1580 store_operator_definition(TheoryId,Id,Parameters,Def,Raw_WDCond,TypeParameters,direct_definition), % store for bvisual2
1581 Op=direct_definition(Parameters,Raw_WDCond,Def,TypeParameters).
1582 store_operator2(TheoryId,TypeParas,_Id,_,Parameters,_,_WD,_,Op) :-
1583 get_theory_name(TheoryId,Project,Theory),
1584 Op = unsupported_operator(Project,Theory,TypeParas,Parameters,
1585 'Only operators with direct or recursive definition are currently supported').
1586
1587 :- dynamic stored_operator_direct_definition/8.
1588 % store definition for bvisual2, ...; not used in typechecker or interpreter
1589 store_operator_definition(TheoryId,Id,Parameters,Def,Raw_WDCond,TypeParameters,Kind) :-
1590 get_theory_name(TheoryId,Proj,Theory),
1591 assertz(stored_operator_direct_definition(Id,Proj,Theory,Parameters,Def,Raw_WDCond,TypeParameters,Kind)).
1592
1593 reset_stored_defs :- retractall(stored_operator_direct_definition(_,_,_,_,_,_,_,_)),
1594 retractall(some_operator_uses_reals).
1595
1596 stored_operator(Id,Kind) :-
1597 stored_operator_direct_definition(Id,_,_,_,_,_,_,Kind).
1598
1599 :- dynamic some_operator_uses_reals/0.
1600 check_if_operator_expr_uses_reals(Raw) :-
1601 \+some_operator_uses_reals,
1602 raw_term_uses_reals(Raw),
1603 !,
1604 assert(some_operator_uses_reals). % this may be important for type checking later
1605 check_if_operator_expr_uses_reals(_).
1606
1607 raw_term_uses_reals(real_set(_)).
1608 raw_term_uses_reals(float_set(_)).
1609 raw_term_uses_reals(real(_,_)).
1610 raw_term_uses_reals(external_pred_call_auto(_,ExtFun,_)) :- ext_fun_uses_reals(ExtFun).
1611 raw_term_uses_reals(external_function_call_auto(_,ExtFun,_)) :- ext_fun_uses_reals(ExtFun).
1612 % TODO: detect more and detect nested usage
1613 :- use_module(external_functions, [external_fun_type/3]).
1614 ext_fun_uses_reals(ExtFun) :- external_fun_type(ExtFun,_,Types), member(R,Types),R==real.
1615
1616 :- use_module(eventhandling,[register_event_listener/3]).
1617 :- register_event_listener(clear_specification,reset_stored_defs,
1618 'Reset stored Event-B operators.').
1619
1620 % extract inductive data types as freetypes
1621 extract_freetypes(TheoryId,ParamEnv,DataTypes,Freetypes,FreetypeOps) :-
1622 maplist(extract_freetype(TheoryId,DataTypes,ParamEnv),DataTypes,Freetypes,FreetypeOpsL),
1623 append(FreetypeOpsL,FreetypeOps).
1624 extract_freetype(TheoryId,AllDataTypes,Env,
1625 datatype(Id,TypeParams,Constructors),
1626 freetype(FreetypeId,Cases),
1627 [Id-freetype_operator(FreetypeId,Types,TypeParams,Usage)|CaseOps]) :-
1628 debug_format(19,'Converting data type ~w with type parameters ~w to freetype~n',[Id,TypeParams]),
1629 foldl(add_datatype_to_env,AllDataTypes,Env,Env1),
1630 foldl(add_type_parameter,TypeParams,Types,Env1,ParamEnv),
1631 create_freetype_typeid(Id,Types,FreetypeId),
1632 Type = freetype(FreetypeId),
1633 extract_used_type_parameters(Constructors,TypeParams,Usage),
1634 %store_eventb_operator(Id,freetype_operator_as_identifier(Id),ParamEnv,ParamEnv2), % now done in add_datatype_to_env
1635 WD=truth(none),
1636 maplist(get_raw_id,TypeParams,TypeParaIds),
1637 store_operator_definition(TheoryId,Id,TypeParaIds,identifier(none,'Datatype'),WD,TypeParaIds,datatype_definition), % store for bvisual2
1638 maplist(extract_case(TheoryId,ParamEnv,Type,Types),Constructors,Cases,CaseOpsL),
1639 append(CaseOpsL,CaseOps).
1640 get_raw_id(identifier(_,ID),R) :- !, R=ID.
1641 get_raw_id(I,I).
1642
1643 add_datatype_to_env(datatype(Id,Params,_ConstructorList),In,Out) :-
1644 length(Params,NumberOfParams),
1645 functor(FreetypeId,Id,NumberOfParams),
1646 debug_format(19,'Generating freetype ~w/~w for inductive datatype from Rodin theory~n',[Id,NumberOfParams]),
1647 env_store(Id,set(freetype(FreetypeId)),[],In,In2),
1648 store_eventb_operator(Id,freetype_operator_as_identifier(Id),In2,Out).
1649
1650 add_type_parameter(TypeParam,Type,In,Out) :-
1651 extract_id(TypeParam,ParameterId),
1652 debug_format(19,'Generating paramater type ~w for Rodin theory~n',[ParameterId]),
1653 env_store(ParameterId,set(Type),[],In,Out).
1654 extract_id(identifier(_,Id),Id).
1655 % constructor without parameters
1656 extract_case(_TheoryId,_ParamEnv,freetype(TypeId),_Types, constructor(Id,[]),
1657 case(Id,constant([Id])),Ops) :- !,
1658 Ops=[Id-constructor_operator(TypeId,[])].
1659 % constructor with parameters
1660 extract_case(TheoryId,ParamEnv,Freetype,ParamTypes,constructor(Id,Destructors),
1661 case(Id,Type),
1662 [Id-constructor_operator(FreetypeId,Types)|DestructOps]) :-
1663 maplist(extract_destructor(TheoryId,ParamEnv,Freetype,ParamTypes,Id,Type),
1664 Destructors,Projections,TypesAndOps),
1665 maplist(split_type_and_op,TypesAndOps,Types,DestructOps),
1666 Freetype=freetype(FreetypeId),
1667 debug_format(19,'Generated constructor ~w ~w for freetype ~w~n',[Id,Types, FreetypeId]),
1668 combine_typelist_with_prj(Types,Type,Projections).
1669 extract_destructor(TheoryId,Env,freetype(FreetypeId),ParamTypes,Case,CType,
1670 destructor(Name,RawTypeExpr),Projection,Type-Name-Op) :-
1671 typecheck_with_freevars(RawTypeExpr,Env,ParamTypes,set(Type),_,destructor(FreetypeId)),
1672 Op = destructor_operator(Name,FreetypeId,Projection,Case,CType),
1673 debug_format(19,'Generated destructor ~w (type ~w) for case ~w of freetype ~w~n', [Name,Type, Case, FreetypeId]),
1674
1675 WD = truth(none),
1676 functor(FreetypeId,FF,_),
1677 ajoin(['Destructor for ', FF],InfoID),
1678 store_operator_definition(TheoryId,Name,[argument(Case,CType)],identifier(none,InfoID),WD,ParamTypes,
1679 destructor(FreetypeId,Type)).
1680
1681 split_type_and_op(Type-Name-Op,Type,Name-Op).
1682
1683
1684 :- assert_must_succeed(( combine_typelist_with_prj([a,b],T,P),
1685 T == couple(a,b), P == [[prj1],[prj2]] )).
1686 :- assert_must_succeed(( combine_typelist_with_prj([a,b,c],T,P),
1687 T == couple(a,couple(b,c)),
1688 P == [[prj1],[prj2,prj1],[prj2,prj2]] )).
1689 :- assert_must_succeed(( combine_typelist_with_prj([a,b,c,d],T,P),
1690 T == couple(couple(a,b),couple(c,d)),
1691 P == [[prj1,prj1],[prj1,prj2],[prj2,prj1],[prj2,prj2]] )).
1692 combine_typelist_with_prj([T],R,Projections) :- !,R=T,Projections=[[]].
1693 combine_typelist_with_prj(Types,couple(TypeL,TypeR),Projections) :-
1694 split_list_in_middle(Types,TypesLeft,TypesRight),
1695 same_length(TypesLeft,PrjLeft),same_length(TypesRight,PrjRight),
1696 append(PrjLeft,PrjRight,Projections),
1697 maplist(cons(prj1),PrjLeft1,PrjLeft),
1698 maplist(cons(prj2),PrjRight1,PrjRight),
1699 combine_typelist_with_prj(TypesLeft,TypeL,PrjLeft1),
1700 combine_typelist_with_prj(TypesRight,TypeR,PrjRight1).
1701 split_list_in_middle(List,Left,Right) :-
1702 length(List,N),
1703 Half is floor(N / 2),
1704 append_length(Left,Right,List,Half).
1705
1706 combine_exprlist_to_couple([T],R) :- !,T=R.
1707 combine_exprlist_to_couple(Exprs,R) :-
1708 split_list_in_middle(Exprs,ExprsLeft,ExprsRight),
1709 combine_exprlist_to_couple(ExprsLeft,TL),
1710 combine_exprlist_to_couple(ExprsRight,TR),
1711 get_texpr_types([TL,TR],[TypeL,TypeR]),
1712 create_texpr(couple(TL,TR),couple(TypeL,TypeR),[],R).
1713
1714 combine_exprlist_to_cprod([T],R) :- !,T=R.
1715 combine_exprlist_to_cprod(Exprs,R) :-
1716 split_list_in_middle(Exprs,ExprsLeft,ExprsRight),
1717 combine_exprlist_to_cprod(ExprsLeft,TL),
1718 combine_exprlist_to_cprod(ExprsRight,TR),
1719 get_texpr_types([TL,TR],[set(TypeL),set(TypeR)]),
1720 create_texpr(cartesian_product(TL,TR),set(couple(TypeL,TypeR)),[],R).
1721
1722 extract_used_type_parameters(Constructors,TypeParams,Usages) :-
1723 maplist(extract_id,TypeParams,TypeParamIds),
1724 convlist(used_type_parameters_of_constructor(TypeParamIds),Constructors,Usages).
1725 used_type_parameters_of_constructor(TypeParamIds,constructor(Id,Destructors),
1726 used_param_types(Id,UsedParamTypes,DestructorExprs)) :-
1727 maplist(destructor_expr,Destructors,DestructorExprs),
1728 maplist(used_type_parameters_of_destructor(TypeParamIds),
1729 DestructorExprs,UsedParamTypeL),
1730 UsedParamTypeL = [_|_], % store the information only for constructors that actually use
1731 % type parameters
1732 ord_union(UsedParamTypeL,UsedParamTypes).
1733 used_type_parameters_of_destructor(TypeParamIds,TypeExpr,UsedTypes) :-
1734 extract_raw_identifiers(TypeExpr,UsedIds),
1735 findall( N, (nth1(N,TypeParamIds,T),memberchk(T,UsedIds)), UsedTypes1),
1736 sort(UsedTypes1,UsedTypes).
1737 destructor_expr(destructor(_,Expr),Expr).
1738 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1739 % callback predicates for operators
1740
1741 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1742
1743 :- public unsupported_operator/13.
1744 % called by btypechecker:lookup_eventb_operator
1745 unsupported_operator(Project,Theory,_TypeParas,Params,_Msg,OpName,Args,Pos,_Env,ExPr,Result,TRin,TRout) :-
1746 match_args_and_params(Args,Params,NewArgs),
1747 get_typed_default_operator(OpName,NewArgs,ExPr,NewOpName,Result),!,
1748 add_default_operator_warning(OpName,NewOpName,Theory,Project,Pos),
1749 TRin=TRout.
1750 unsupported_operator(_,_,_,_Parameters,Msg,Id,_Args,Pos,_Env,ExPr,Result,TRin,TRout) :-
1751 delay_unsupported_operator_error(ExPr,Msg,Id,Result),!,
1752 % the operator can still be typed: the result type is fixed by the context where it is used
1753 % we only raise an error when the operator is evaluated (see external_functions)
1754 ajoin([Msg,'; the operator will raise an error when evaluated:'],Msg2),
1755 add_warning(bmachine_eventb,Msg2,Id,Pos),
1756 TRin=TRout.
1757 unsupported_operator(_,_,_,_Parameters,Msg,Id,_Args,Pos,_Env,ExPr,Result,TRin,TRout) :-
1758 %format('Unsupported ~w~n args:~w',[Id,_Args]),
1759 store_typecheck_error(Msg,Pos,TRin,TRout),
1760 failure_syntax_element(ExPr,Id,F,Type), % just to make sure that the result
1761 create_texpr(F,Type,[],Result). % is nonvar, to prevent later errors
1762 failure_syntax_element(expr,Id,identifier(Id),_).
1763 failure_syntax_element(pred,_Id,falsity,pred).
1764
1765 % create a placeholder for an operator that is not supported (e.g., an axiomatically defined operator
1766 % without .ptm mapping); its arguments are dropped, the result type is a fresh type variable which
1767 % is fixed by the context; evaluating the placeholder raises an error (see external_functions)
1768 delay_unsupported_operator_error(ExPr,Msg,Id,Result) :- var(ExPr),!,
1769 % extended_formula generated by btype_rewrite for function application syntax f(x) or an identifier:
1770 % we assume the operator is used as an expression
1771 ExPr=expr,
1772 delay_unsupported_operator_error(expr,Msg,Id,Result).
1773 delay_unsupported_operator_error(expr,Msg,Id,Result) :-
1774 create_texpr(string(Id),string,[],TId), create_texpr(string(Msg),string,[],TMsg),
1775 create_texpr(external_function_call('THEORY_OPERATOR_NOT_SUPPORTED',[TId,TMsg]),_Type,
1776 [was(extended_expr(Id))],Result).
1777 delay_unsupported_operator_error(pred,Msg,Id,Result) :-
1778 create_texpr(string(Id),string,[],TId), create_texpr(string(Msg),string,[],TMsg),
1779 create_texpr(external_pred_call('THEORY_PREDICATE_NOT_SUPPORTED',[TId,TMsg]),pred,
1780 [was(extended_pred(Id))],Result).
1781
1782 % in contrast to the default mappings handled earlier,
1783 % this code as access to the actual arguments and their types
1784 % and is called once for each use of the operator
1785 get_typed_default_operator(Op,[A,B],ExPr,NewOp,Result) :-
1786 get_texpr_type(A,TA), get_texpr_type(B,TB),
1787 (nonvar(TA) ; nonvar(TB)),
1788 binary_typed_operator_to_ast(Op,TA,TB,ExPr,NewOp,NewType),
1789 ResExpr =.. [NewOp,A,B],
1790 create_texpr(ResExpr,NewType,[],Result).
1791
1792
1793 binary_typed_operator_to_ast(Op,T,T,expr,NewOp,T) :- binary_expr_op(Op,T,NewOp).
1794 %binary_typed_operator_to_ast(Op,T,T,pred,NewOp,pred) :- binary_pred_op(Op,T,NewOp).
1795
1796 binary_expr_op(pow,integer,power_of).
1797 binary_expr_op(pow,real,power_of_real).
1798 binary_expr_op(power_of,integer,power_of).
1799 binary_expr_op(power_of,real,power_of_real).
1800 binary_expr_op(div,integer,floored_div).
1801 binary_expr_op(div,real,div_real).
1802
1803 %binary_pred_op('less',real,less_real).
1804
1805
1806 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1807
1808 :- use_module(probsrc(bsyntaxtree),[safe_create_texpr/4, is_truth/1,
1809 add_texpr_infos_if_new/3, conjunct_predicates_with_pos_info/3]).
1810 :- use_module(probsrc(bsyntaxtree_quantifiers),[create_z_let/6]).
1811
1812 % get params and type parameters from operator callback registered in the typechecker environment
1813 % for use by btypechecker:lookup_eventb_operator
1814 % it would be a bit cleaner to store infos separately from callback or get rid of the call back completely
1815 get_operator_arity_from_callback(direct_definition(Params,_WD,_DirectDef,_PT),direct_definition,Arity) :-
1816 length(Params,Arity).
1817 get_operator_arity_from_callback(axiomatic_definition(_TagName,Params,_DirectDef,_PT),axiomatic_definition,Arity) :-
1818 length(Params,Arity).
1819 get_operator_arity_from_callback(recursive_operator(Params,_Cases,_PT),recursive_operator,Arity) :-
1820 length(Params,Arity).
1821 get_operator_arity_from_callback(freetype_operator(_FId1,Types1,_PT,_Usage1),freetype_operator,Arity) :-
1822 length(Types1,Arity).
1823 get_operator_arity_from_callback(freetype_operator_as_identifier(_RecId),freetype_operator_as_identifier,0).
1824 get_operator_arity_from_callback(freetype_operator_as_function(_RecId,_RType),freetype_operator_as_function,1).
1825 get_operator_arity_from_callback(freetype_operator_as_set(_RecId),freetype_operator_as_function,0).
1826 get_operator_arity_from_callback(constructor_operator(_FId,_TP),constructor_operator,0).
1827 get_operator_arity_from_callback(destructor_operator(_Name,_FId,_Projections,_Case,_CType1),destructor_operator,1).
1828 get_operator_arity_from_callback(make_inductive_natural(_ArgId,_ZeroOp,_SuccOp),make_inductive_natural,1).
1829 get_operator_arity_from_callback(unsupported_operator(_Project,_Theory,_TP,Paras,_Msg),unsupported_operator,Len) :-
1830 length(Paras,Len).
1831
1832 %%%%%%%%%%%%%%%%%%
1833
1834 % Theory plug-in: direct definitions
1835 :- public direct_definition/12.
1836 % called by btypechecker:lookup_eventb_operator
1837 direct_definition(Params, % e.g. [argument(a,bool_set(none))]
1838 RawWD, % Raw AST of WD condition (currently only implicit WDs from body; not yet user-defined ones)
1839 DirectDef, % Raw AST of DirectDefinition Body, e.g., convert_bool(none,negation(none,equal(none,identifier(none,a),boolean_true(none))))
1840 PT,
1841 OpId, TArgs, Pos,
1842 Env, % environment of operators
1843 ExPr,Result,TRin,TRout) :-
1844 (Params,DirectDef) = (NewParams,NewDirectDefBody), %gen_fresh_params(Params,DirectDef,NewParams,NewDirectDefBody),
1845 apply_direct_definition(OpId,TArgs,NewParams,
1846 NewDirectDefBody,RawWD,
1847 PT,Env,Pos,TLetIds,TLetValues,
1848 TDef,InferredType,TWDPred,
1849 TRin,TRout),
1850 NewInfos = [nodeid(Pos),was(extended_expr(OpId))],
1851 (is_truth(TWDPred) -> add_texpr_infos_if_new(TDef,NewInfos,LetBody)
1852 ; get_preference(find_abort_values,false) -> LetBody=TDef % currently tests 1201, 2232 would fail
1853 % TODO: should we disable the inclusion of the WD condition for older .eventb files?
1854 ; InferredType=pred
1855 -> ajoin(['Well-definedness error for predicate operator ',OpId],MsgStr),
1856 TMsg = b(string(MsgStr),string,[]),
1857 safe_create_texpr(convert_bool(TWDPred),boolean,[nodeid(Pos)],WDBool), % we require an expression argument
1858 safe_create_texpr(external_pred_call('ASSERT_TRUE',[WDBool,TMsg]),pred,NewInfos,TAssert),
1859 conjunct_predicates_with_pos_info(TAssert,TDef,LetBody)
1860 ; ajoin(['Well-definedness error for expression operator ',OpId],MsgStr),
1861 safe_create_texpr(assertion_expression(TWDPred,MsgStr,TDef),InferredType,NewInfos,LetBody)
1862 ),
1863 %write(op(OpId,InferredType)),nl, translate:print_bexpr(LetBody),nl,
1864 create_z_let(ExPr,TLetIds,TLetValues,LetBody,NewInfos,Result).
1865
1866
1867 :- public axiomatic_definition/12.
1868 % just a "dummy" interface predicate for better pretty-printing of operators in translate_eventb_operator
1869 axiomatic_definition(_TagName, Params, DirectDef, PT,
1870 Id, TArgs, Pos, Env, ExPr,Result,TRin,TRout) :-
1871 direct_definition(Params, truth(none), DirectDef, PT, Id, TArgs, Pos, Env, ExPr,Result,TRin,TRout).
1872
1873 % Example: ddef([argument(R,pow_subset(none,identifier(none,T)))],seq(none,identifier(none,R)),[T],seq)
1874
1875 % this code not needed as we now systematically rename in create_z_let
1876 %:- use_module(input_syntax_tree,[raw_replace/3]).
1877 %gen_fresh_params(Params,DirectDef,NewParams,NewDirectDefBody) :-
1878 % maplist(alpha_rename,Params,NewParams,RenameList), %print(replaces(RenameList)),nl,
1879 % raw_replace(DirectDef,RenameList,NewDirectDefBody,unknown).
1880 %:- use_module(gensym,[gensym/2]).
1881 %alpha_rename(argument(OldID,Type),argument(FreshID,Type),replace(OldID,identifier(none,FreshID))) :-
1882 % gensym(OldID,FreshID).
1883
1884 % Args are the arguments of the operator where it is used
1885 % Params are the parameters in the operator definition
1886 apply_direct_definition(OpId,TArgs,Params,DirectDef,RawWD,PT,Env,_Pos,
1887 TLetIds,TLetValues,TDef,Type,TWDPred,TRin,TRout) :-
1888 match_args_and_params(TArgs,Params,NewTArgs),!, %TArgs are the concrete arguments in the operator call
1889 create_typed_ids(PT,ParametricTypes,TPT),
1890 add_identifiers_to_environment(TPT,Env,SubEnv),
1891 % type check the arguments given in the operator usage
1892 get_texpr_types(NewTArgs,ArgTypes),
1893 typecheck_arguments(Params,SubEnv,ArgTypes,TParams,TRin,TR2),
1894 % type check the direct definition of the operator. To do this we need the parameters of the operators
1895 % in the type environment. Their type is determined by the arguments of the operator call.
1896 add_identifiers_to_environment(TParams,SubEnv,DefEnv),
1897 btype(apply_direct_definition,DirectDef,DefEnv,Type,TDef,TR2,TR3),
1898 debug_format(9,'Inferred type of direct definition ~w application: ~w~n',[OpId,Type]),
1899 append(TParams,TPT,TLetIds),
1900 maplist(create_typeset,ParametricTypes,TypeValues),
1901 append(NewTArgs,TypeValues,TLetValues),
1902 btype(apply_direct_definition,RawWD,DefEnv,_PredType,TWDPred,TR3,TRout). % now type check WD predicate
1903 apply_direct_definition(OpId,TArgs,Arguments,_DirectDef,_WD,_PT,_Env,Pos,
1904 _TParams,_,_TDef,_,_TWD,TRin,TRout) :-
1905 length(TArgs,Len1),
1906 length(Arguments,Len2),
1907 write(targs(TArgs)),nl,
1908 write(args(Arguments)),nl,
1909 ajoin(['Wrong number of arguments (',Len1,') for call to operator ',OpId,
1910 ', expected ',Len2],Msg),
1911 store_typecheck_error(Msg,Pos,TRin,TRout).
1912
1913
1914 match_args_and_params(TArgs,Params,NewTArgs) :-
1915 same_length(TArgs,Params),!, NewTArgs=TArgs.
1916 match_args_and_params([TArg],Params,NewTArgs) :- % can happen when calling operator in REPL using maplets
1917 nested_couple_to_list(TArg,NewTArgs),
1918 same_length(NewTArgs,Params).
1919
1920 split_arg_and_typedef(argument(Id,TypeExpr),Id,TypeExpr).
1921 map_to_set_type(Type,set(Type)).
1922 typecheck_arguments(Params,Env,ArgTypes,TParams,TRin,TRout) :-
1923 % type check the parameters' type expressions of the operator definition, they should have the same type
1924 % as the arguments (except being a set)
1925 % E.g. an operator "o" has one argument "arg" and type expression "T**BOOL" (with T being a parameter type of the theory),
1926 % then for "o(5|->TRUE)" we have "couple(integer,boolean)" as the argument's type,
1927 % we add "T" to the type environment (with type set(_)),
1928 % then we type check the parameter expression "T**BOOL", expecting the type set(coule(integer,boolean)),
1929 % the type check results in T being of type set(integer).
1930 maplist(split_arg_and_typedef,Params,ParamIds,ParamTypeExprs),
1931 same_length(Params,ArgTypes),
1932 maplist(map_to_set_type,ArgTypes,SetArgTypes),
1933 btype_l(ParamTypeExprs,Env,SetArgTypes,_TParamTypeExprs,TRin,TRout),
1934 create_typed_ids(ParamIds,ArgTypes,TParams).
1935 create_typeset(Type,TExpr) :- create_texpr(typeset,Type,[],TExpr).
1936
1937
1938
1939 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1940 % Theory plug-in: Recursive operators
1941 :- public recursive_operator/11.
1942 % called by btypechecker:lookup_eventb_operator
1943 recursive_operator(Arguments,Cases,PT,
1944 Id,TArgs,Pos,Env,ExPr,Result,TRin,TRout) :-
1945 % parameter types
1946 create_typed_ids(PT,ParametricTypes,TPT),
1947 add_identifiers_to_environment(TPT,Env,Env1),
1948 maplist(create_typeset,ParametricTypes,LetValues), % needed for the LET
1949 typecheck_arguments(Arguments,Env1,ArgTypes,TParamIds,TRin,TR0),
1950 % TArgs: A,B,Cf
1951 % TArg: A|->B|->C
1952 get_freetype_operator_types(TArgs,ArgTypes,Id,Pos,TR0,TR1),
1953 create_couple(TArgs,TArg),
1954 length(TArgs,NumberOfArgs),OpInfo = [theory_operator(Id,NumberOfArgs)],
1955 unique_id("opresult.",ResultId),create_typed_id(ResultId,Type,TResultId),
1956 % TODO: infer ExPr if variable from extended_formula
1957 ( ExPr=expr -> % Result: Comp(x|->y|->z)
1958 % we need to append a result parameter in the comprehension set
1959 create_texpr(function(TCompSet,TArg),Type,OpInfo,InnerResult),
1960 append(TParamIds,[TResultId],CompSetIds),append(ArgTypes,[Type],CompSetTypes),
1961 % make sure that we do not run into an infinite loop
1962 store_eventb_operator(Id,freetype_operator_as_function(RecId,Type),Env1,Env2)
1963 ; ExPr=pred -> % Result: x|->y|->z : Comp
1964 create_texpr(member(TArg,TCompSet),pred,OpInfo,InnerResult),
1965 CompSetIds = TParamIds,ArgTypes=CompSetTypes,
1966 % make sure that we do not run into an infinite loop
1967 store_eventb_operator(Id,freetype_operator_as_set(RecId),Env1,Env2)
1968 ),
1969 couplise_list(CompSetTypes,CompSetType),
1970 % Comp: {i,r| Cond}
1971 create_recursive_compset(CompSetIds,Cond,set(CompSetType),[],RecId,TCompSet),
1972 % Params: a,b,c
1973 % i = a|->b|->c
1974 add_identifiers_to_environment(TParamIds,Env2,Subenv),
1975 foldl(recursive_operator_case(Subenv,TResultId),Cases,TCases,TR1,TRout),
1976 conjunct_predicates(TCases,Cond),
1977 create_z_let(ExPr,TPT,LetValues,InnerResult,OpInfo,Result).
1978
1979
1980 recursive_operator_case(Env,TResultId,case(ParamId,_,Expression,Formula),Cond,TRin,TRout) :-
1981 % Add free identifiers of case to environment
1982 extract_free_identifiers(Expression,TFreeIdentifiers,Env,Subenv),
1983 % IsCase => CaseCheck
1984 create_texpr(implication(IsCase,TCaseCheck),pred,[],Cond),
1985 % IsCase: ParamId = constructor(x,y,z)
1986 typecheck_parameter(ParamId,Env,TParamId),
1987 recop_create_is_case(Expression,Subenv,IsCase,TParamId,FT,Case,TRin,TR1),
1988 % CaseCheck: #x,y,z | Destruction & Predicate
1989 recop_create_in_case(Formula,TParamId,TResultId,Subenv,TFreeIdentifiers,FT,Case,TCaseCheck,TR1,TRout).
1990 extract_free_identifiers(typeof(_Pos,ExtExpr,_TypeExpr),TIds,In,Out) :-
1991 extract_free_identifiers(ExtExpr,TIds,In,Out).
1992 extract_free_identifiers(extended_expr(_Pos,_Case,Exprs,Preds),TIds,In,Out) :-
1993 append(Exprs,Preds,Ids),
1994 maplist(extract_free_identifier,Ids,TIds),
1995 add_identifiers_to_environment(TIds,In,Out).
1996 extract_free_identifier(identifier(_Pos,Id),TId) :-
1997 create_typed_id(Id,_,TId).
1998 typecheck_parameter(ParamId,Env,TParamId) :-
1999 env_lookup_type(ParamId,Env,ParamType),
2000 create_typed_id(ParamId,ParamType,TParamId).
2001 %env_store_type(Id,Type,In,Out) :-
2002 % % Version without Info field
2003 % env_store(Id,Type,[],In,Out).
2004 recop_create_is_case(typeof(_,Expr,_TypeExpr),Env,IsCase,TParamId,FT,Case,TRin,TRout) :-
2005 recop_create_is_case(Expr,Env,IsCase,TParamId,FT,Case,TRin,TRout).
2006 recop_create_is_case(Expression,Env,IsCase,TParamId,FT,Case,TRin,TRout) :-
2007 Expression = extended_expr(_,Case,_,_),
2008 get_texpr_type(TParamId,freetype(FT)),
2009 btype(recop_create_is_case,Expression,Env,freetype(FT),_TCons,TRin,TRout),
2010 create_texpr(freetype_case(FT,Case,TParamId),pred,[],IsCase).
2011 recop_create_in_case(Formula,TParamId,TResultId,Subenv,TFreeIdentifiers,FT,Case,Cond,TRin,TRout) :-
2012 % Predicate
2013 btype(recop_create_in_case,Formula,Subenv,Type,TFormula,TRin,TRout),
2014 ( Type=pred -> Predicate = TFormula
2015 ;
2016 get_texpr_types([TResultId,TFormula],[TypeA,TypeB]),
2017 unify_types_strict(TypeA,TypeB),
2018 create_texpr(equal(TResultId,TFormula),pred,[],Predicate)),
2019 % Destruction: x->y|->z = destructor(ParamId)
2020 ( TFreeIdentifiers = [] ->
2021 Cond = Predicate
2022 ; TFreeIdentifiers = [_|_] ->
2023 get_texpr_types(TFreeIdentifiers,FTypes),
2024 combine_typelist_with_prj(FTypes,FType,Projections),
2025 unique_id("destructed",DId),create_typed_id(DId,FType,TDId),
2026 create_texpr(freetype_destructor(FT,Case,TParamId),FType,[],Destructor),
2027 maplist(create_inner_let(TDId),Projections,TLetExpressions),
2028 create_z_let(pred,TFreeIdentifiers,TLetExpressions,Predicate,[],InnerLets),
2029 create_z_let(pred,[TDId], [Destructor], InnerLets,[],Cond)
2030 ).
2031
2032 create_inner_let(TOrig,Projections,TExpr) :-
2033 apply_projections(Projections,TOrig,TExpr).
2034
2035 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2036 % Theory plug-in: datatype sets
2037 :- public freetype_operator/12.
2038 % called by btypechecker:lookup_eventb_operator
2039 freetype_operator(FreetypeId1,Types1,TypeParams1,Usage1,
2040 Id,TArgs,Pos,Env,_ExPr,Result,TRin,TRout) :-
2041 % make a fresh copy to prevent that several instances of the freetype propagate
2042 % their types to each other (resulting in spurious typing errors)
2043 copy_term(freetype(FreetypeId1,Types1,TypeParams1,Usage1),
2044 freetype(FreetypeId, Types, TypeParams, Usage)),
2045 maplist(map_to_set_type,Types,SetTypes),
2046 get_freetype_operator_types(TArgs,SetTypes,Id,Pos,TRin,TRout),
2047 create_freetype_compset(TArgs,Id,FreetypeId,TypeParams,Usage,Env,Result).
2048 create_freetype_compset(TArgs,SetId,FreetypeId,TypeParams,Usage,Env,Result) :-
2049 find_constructors_with_complex_types(TArgs,Usage,Constructors),
2050 ( Constructors = [] ->
2051 create_texpr(freetype_set(FreetypeId),set(freetype(FreetypeId)),[],Result)
2052 ;
2053 create_freetype_compset2(TArgs,SetId,Constructors,FreetypeId,TypeParams,Env,Result)).
2054 create_freetype_compset2(TArgs,SetId,Constructors,FreetypeId,TypeParams,Env,Result) :-
2055 btypechecker:add_ext_variables(TypeParams,Env,TParams,Subenv,TRin,TRout),
2056 get_texpr_types(TParams,Types),get_texpr_types(TArgs,Types),
2057 Type=freetype(FreetypeId),
2058 create_texpr(identifier(freetype_element),Type,[],TId),
2059 do_prettyprint_freetype(FreetypeId,TArgs,PP),
2060 create_recursive_compset([TId],Let,set(Type),[freetype(PP)],RecId,Result),
2061 store_eventb_operator(SetId,freetype_operator_as_identifier(RecId),Subenv,Subenv2),
2062 foldl(create_cons_check(FreetypeId,Subenv2,TId),Constructors,Checks,TRin,TRout),
2063 conjunct_predicates(Checks,Cond),
2064 create_z_let(pred,TParams,TArgs,Cond,[],Let).
2065 create_cons_check(FreetypeId,Env,TId,cons(Case,Exprs),Check,TRin,TRout) :-
2066 btype_l(Exprs,Env,_Types,TExprs,TRin,TRout),
2067 combine_exprlist_to_cprod(TExprs,Set),
2068 get_texpr_type(Set,set(Type)),
2069 create_texpr(freetype_case(FreetypeId,Case,TId),pred,[],CheckCase),
2070 create_texpr(freetype_destructor(FreetypeId,Case,TId),Type,[],Value),
2071 create_texpr(member(Value,Set),pred,[],Membercheck),
2072 create_texpr(implication(CheckCase,Membercheck),pred,[],Check).
2073 % this is used to pretty-print the resulting comprehension set
2074 do_prettyprint_freetype(Id,Params,R) :-
2075 maplist(translate_bexpression,Params,Strs),
2076 ajoin_with_sep(Strs,',',S),
2077 functor(Id,I,_),
2078 ajoin([I,'(',S,')'],R).
2079
2080 find_constructors_with_complex_types(TArgs,Usage,Constructors) :-
2081 find_complex_type_params(TArgs,ComplexTP),
2082 findall(cons(Id,DestructorExprs),
2083 ( member(used_param_types(Id,UsedParamTypes,DestructorExprs),Usage),
2084 ord_intersect(UsedParamTypes,ComplexTP)),
2085 Constructors).
2086 % returns the indeces of the type arguments that are not only types
2087 find_complex_type_params(TArgs,ComplexTP) :-
2088 findall(N,(nth1(N,TArgs,TArg),\+ is_just_type(TArg)),ComplexTP1),
2089 sort(ComplexTP1,ComplexTP).
2090
2091 % a safe version of get_texpr_types which generates error message if it fails
2092 get_freetype_operator_types(TArgs,SetTypes,Id,Pos,TRin,TRout) :-
2093 (get_texpr_types(TArgs,SetTypes) -> TRin=TRout
2094 ; ajoin(['Arguments to freetype operator "',Id,'" have illegal type'],Msg),
2095 % should normally not happen; can currently happen when 'any' type used in registered freetype
2096 store_typecheck_error(Msg,Pos,TRin,TRout)).
2097
2098
2099 :- public freetype_operator_as_identifier/9.
2100 freetype_operator_as_identifier(RecId,Id,TArgs,Pos,_Env,_ExPr,Result,TRin,TRout) :-
2101 get_freetype_operator_types(TArgs,SetTypes,Id,Pos,TRin,TRout),
2102 maplist(map_to_set_type,Types,SetTypes),
2103 create_freetype_typeid(Id,Types,FreetypeId),
2104 create_recursion_ref(RecId,set(freetype(FreetypeId)),Result).
2105
2106 :- public freetype_operator_as_function/10.
2107 freetype_operator_as_function(RecId,RType,_Id,TArgs,_Pos,_Env,_ExPr,Result,TR,TR) :-
2108 create_couple(TArgs,TArg), get_texpr_type(TArg,Type),
2109 create_recursion_ref(RecId,set(couple(Type,RType)),TFunction),
2110 create_texpr(function(TFunction,TArg),RType,[],Result).
2111
2112 :- public freetype_operator_as_set/9.
2113 freetype_operator_as_set(RecId,_Id,TArgs,_Pos,_Env,_ExPr,Result,TR,TR) :-
2114 create_couple(TArgs,TArg), get_texpr_type(TArg,Type),
2115 create_recursion_ref(RecId,set(Type),TSet),
2116 create_texpr(member(TArg,TSet),pred,[],Result).
2117
2118 create_recursion_ref(RecId,Type,TId) :-
2119 create_texpr(identifier(RecId),Type,[for_recursion],TId).
2120
2121 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2122 % Theory plug-in: datatype constructors
2123 :- public constructor_operator/10. % TO DO: ensure by another mechanism that Spider detects that this is called
2124 % called by btypechecker:lookup_eventb_operator
2125 constructor_operator(FreetypeId1,[],Id,[],_Pos,_Env,_ExPr,Result,TRin,TRout) :-
2126 !, copy_term(FreetypeId1,FreetypeId),
2127 create_texpr(value(freeval(FreetypeId,Id,term(Id))),
2128 freetype(FreetypeId),[],Result),
2129 TRin = TRout.
2130 constructor_operator(FreetypeId1,ParamTypes1,
2131 Id,TArgs,Pos,_Env,_ExPr,Result,TRin,TRout) :-
2132 copy_term(constructor(FreetypeId1,ParamTypes1),constructor(FreetypeId,ParamTypes)),
2133 get_freetype_operator_types(TArgs,ParamTypes,Id,Pos,TRin,TRout),
2134 combine_exprlist_to_couple(TArgs,TArg),
2135 %format('Generated freetype constructor call ~w for Rodin theory datatype ~w~n',[Id,FreetypeId]),
2136 create_texpr(freetype_constructor(FreetypeId,Id,TArg),freetype(FreetypeId),[],Result).
2137
2138 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2139 % Theory plug-in: datatype destructors
2140 :- public destructor_operator/13. % TO DO: ensure by another mechanism that Spider detects that this is called
2141 % called by btypechecker:lookup_eventb_operator
2142 destructor_operator(OpName,FreetypeId1,Projections,Case,CType1,
2143 _Id,[TArg],_Pos,_Env,_ExPr,Result,TR,TR) :-
2144 copy_term(destructor(FreetypeId1,CType1),destructor(FreetypeId,CType)),
2145 get_texpr_type(TArg,freetype(FreetypeId)),
2146 debug_format(19,'Generated freetype destructor ~w call ~w for Rodin theory datatype ~w~n',[OpName,Case,FreetypeId]),
2147 create_texpr(freetype_destructor(FreetypeId,Case,TArg),CType,[],Destructed),
2148 apply_projections(Projections,Destructed,Result0),
2149 add_texpr_infos(Result0,[was(extended_expr(OpName))],Result).
2150
2151 % create an projection expression (or a combination of arbitrary many) to
2152 % access a part of a couple. The input is a list of prj1/prj2 atoms,
2153 % e.g. [prj1,prj1,prj2]: Take the first of the first of the second element.
2154 apply_projections(Projections,Expr,Result) :-
2155 reverse(Projections,Prjs),
2156 apply_projections1(Prjs,Expr,Result).
2157 apply_projections1([],Expr,Expr).
2158 apply_projections1([P|Rest],Expr,Result) :-
2159 get_texpr_type(Inner,couple(A,B)),
2160 apply_projections2(P,A,B,Result,Inner),
2161 apply_projections1(Rest,Expr,Inner).
2162 apply_projections2(prj1,A,_B,Result,Inner) :-
2163 create_texpr(first_of_pair(Inner),A,[],Result).
2164 apply_projections2(prj2,_A,B,Result,Inner) :-
2165 create_texpr(second_of_pair(Inner),B,[],Result).
2166
2167 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2168 % Theory plug-in: axiomatic definitions of operators
2169 store_axiomatic_operator(Id,TypeParas,axiomatic_def_block(_Id,_Types,OpDefs,_Axioms),Ops) :-
2170 % in case we do not recognize the operator, we store an error message
2171 % that is shown as soon the operator is used somewhere
2172 get_theory_name(Id,Project,Theory), % extract project and theory name
2173 maplist(store_axdef_error(Project,Theory,TypeParas),OpDefs,Ops).
2174 store_axdef_error(Project,Theory,TypeParas,
2175 opdef(Id,Arguments,_WD),Id-unsupported_operator(Project,Theory,TypeParas,Arguments,Msg)) :-
2176 % The opdef information from the Rodin export is missing the result type;
2177 % the typechecker gives the operator a fresh result type, fixed by the context where it is used,
2178 % and the error is only raised when the operator is evaluated (see unsupported_operator/13)
2179 length(Arguments,Len), %write(opdef(Id,Arguments)),nl,
2180 ajoin(['Axiomatic defined operator \"',Id,'\" of arity ', Len,' not recognized. Be sure to add a ',
2181 Theory,'.ptm file to your Theory project ',
2182 Project],Msg).
2183
2184 % generate default mappings for axiomatic operators in case no .ptm file is provided and the args match
2185 is_axiomatic_def(Id,Arguments,axiomatic_def_block(_Id,_Types,OpDefs,_Axioms)) :-
2186 member(opdef(Id,Arguments,_WD),OpDefs).
2187 is_axiomatic_def(Id,[],axiomatic_def_block(_Id,Types,_OpDefs,_Axioms)) :-
2188 member(Id,Types).
2189
2190 generate_default_mappings(AxDefs,TheoryId,DefMappings) :-
2191 findall(tag(OpName,NewOpName), (member(Block,AxDefs),
2192 is_axiomatic_def(OpName,Args,Block),
2193 default_operator(OpName,NewOpName,TheoryId,Args)), DefMappings).
2194
2195 default_operator(OpName,NewOpName,TheoryId,A) :-
2196 get_theory_name(TheoryId,Project,Theory),
2197 get_default_operator(OpName,NewOpName,A,Theory),
2198 add_default_operator_warning(OpName,NewOpName,Theory,Project,unknown).
2199 get_default_operator('\x211D\','REAL',Args,_) :- !,
2200 Args=[]. % Real unicode symbol, in .ptm file the Prolog internal name cannot use unicode
2201 get_default_operator('SUM','SIGMA',[argument(_,ArgT)],_) :- !,
2202 relation_to_integer_type(ArgT). % from StandardLibrary SUMandPRODUCT
2203 get_default_operator('PRODUCT','PI',[argument(_,ArgT)],_) :- !, relation_to_integer_type(ArgT).
2204 get_default_operator(cls,closure1,[argument(_,ArgT)],'closure') :- !,
2205 % from Standard Library theory "closure"; but it uses a direct_definition and this rewriting does not trigger!
2206 binary_relation_type(ArgT).
2207 get_default_operator(Name,NewName,[_,_],_) :- binary_external_function(Name,NewName),!.
2208 get_default_operator(Name,NewName,[_,_],_) :- binary_external_predicate(Name,NewName),!.
2209 get_default_operator(Name,Name,Args,_) :- default_operator_aux(Name,Args).
2210
2211 add_default_operator_warning(OpName,NewOpName,Theory,Project,Pos) :-
2212 ajoin(['operator "',OpName,'" internal {',NewOpName,'}'],Decl),
2213 (get_preference(auto_detect_theory_ops,true)
2214 -> MW = 'message'
2215 ; MW = 'warning set AUTO_DETECT_THEORY_MAPPING to TRUE or'
2216 ),
2217 ajoin(['Automatically translating axiomatic operator ',OpName,
2218 '; to get rid of this ', MW, ' add a ',
2219 Theory,'.ptm file to your Theory project ',
2220 Project, ' with this line: '],Msg),
2221 (get_preference(auto_detect_theory_ops,true)
2222 -> add_message(bmachine_eventb,Msg,Decl,Pos)
2223 ; add_warning(bmachine_eventb,Msg,Decl,Pos)
2224 ).
2225
2226 default_operator_aux(choose,Args) :- !, Args = [argument(_,pow_subset(_,_))].
2227 default_operator_aux(mu,Args) :- !, Args=[argument(_,pow_subset(_,_))].
2228 default_operator_aux(closure,[argument(_,ArgT)]) :- !,
2229 binary_relation_type(ArgT).
2230 default_operator_aux(closure1,[argument(_,ArgT)]) :- !,
2231 binary_relation_type(ArgT).
2232 default_operator_aux(OpName,[]) :- constant_operator_raw_term(OpName,_).
2233 default_operator_aux(OpName,[A1]) :- unary_operator_raw_term(OpName,A1,_).
2234 default_operator_aux(OpName,[A1,A2]) :-
2235 binary_operator_raw_term(OpName,A1,A2,_,_),
2236 \+ binary_expr_op(OpName,_,_). % we have typed default rules; delay decision until typing info is available
2237
2238
2239 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2240 % Theory plug-in: Tagged operators that can be replaced by internal constructs
2241 handle_mappings(TheoryId,PT,tag(Opname,Tag),Ops,OPin/AxDefsin,OPout/AxDefsOut) :- !,
2242 ( extract_operator(Opname,Operator,OPin/AxDefsin,OPout/AxDefsOut,Kind) ->
2243 (Tag=[_|_] -> debug_format(19,"Mapping Theory Operator ~s -> ~w~n",[Tag,Opname])
2244 ; debug_format(19,"Mapping Theory Operator ~w -> ~w~n",[Tag,Opname])),
2245 (store_operator_by_tag(Tag,Opname,Operator,TheoryId,PT,Ops,Kind)
2246 -> true
2247 ;
2248 ajoin(['Error mapping theory operator ',Opname,
2249 ' to ProB tag (the *.ptm file maybe incorrect or you need a newer version of ProB):'],Msg),
2250 add_error(bmachine_eventb,Msg,Tag))
2251 ;
2252 ajoin(['ProB theory mapping: operator ',Opname,' not found, mapping to ',Tag,' ignored.'],Msg),
2253 add_warning(bmachine_eventb,Msg),
2254 OPin/AxDefsin=OPout/AxDefsOut,Ops=[]
2255 ).
2256 handle_mappings(_TheoryID,_ParamTypes,Mapping,[],X,X) :-
2257 functor(Mapping,Functor,Arity),
2258 ajoin(['ProB theory mapping: unexpected entry of type ',Functor,'/',Arity,', entry ignored.'],Msg),
2259 add_error(bmachine_eventb,Msg).
2260
2261 extract_operator(Opname,Operator,OPin/AxDefs,OPout/AxDefs,Kind) :-
2262 % a regular non-axiomatic operator (direct definition or recursive definition):
2263 Operator = operator(Opname,_Parameters,_WD,DirectDef,_RecursiveDef),
2264 selectchk(Operator,OPin,OPout),!,
2265 % TODO: we could try and infer/store type of operator from Definition and check against axiomatic one
2266 (DirectDef=[] -> Kind='RECURSIVE-DEF-OVERRIDE' ; Kind = 'DIRECT-DEF-OVERRIDE'),
2267 debug_format(19,'Overriding non-axiomatic operator ~w with new definition from .ptm file~n',[Opname]).
2268 extract_operator(Opname,Operator,OP/AxDefsIn,OP/AxDefsOut,'AXIOMATIC-DEF') :-
2269 Operator = axdef(Opname,Parameters,WD,block(Id,Types,Axioms)), % block/3 does not seem to be used
2270 select(axiomatic_def_block(Id,Types,OpDefsIn,Axioms),AxDefsIn,
2271 axiomatic_def_block(Id,Types,OpDefsOut,Axioms),AxDefsOut),
2272 select(opdef(Opname,Parameters,WD),OpDefsIn,OpDefsOut),!.
2273 extract_operator(Opname,Operator,OP/AxDefsIn,OP/AxDefsOut,'AXIOMATIC-TYPE') :-
2274 % we treat a type of an axiomatic definition also as a potential operator that can be mapped
2275 Operator = axdef(Opname,[],WD,block(Id,TypesOut,Axioms)), WD=[],
2276 select(axiomatic_def_block(Id,TypesIn,OpDefs,Axioms),AxDefsIn,
2277 axiomatic_def_block(Id,TypesOut,OpDefs,Axioms),AxDefsOut),
2278 select(Opname,TypesIn,TypesOut),!.
2279
2280 % two versions are supported: The older one expects an atom Tag, the new one a string
2281 % The string version is then parsed as a Prolog term.
2282 % as of 2023 we also support the bexpr(RawExpr) tag generated from $Expr$ in the .ptm file
2283 store_operator_by_tag(Tag,Opname,Operator,TheoryID,PT,Ops,Kind) :-
2284 is_list(Tag),!, % A string
2285 append(Tag,".",Tag1), % read_from_codes/2 needs a full-stop at the end
2286 read_from_codes(Tag1,Term),
2287 store_operator_by_tag(Term,Opname,Operator,TheoryID,PT,Ops,Kind).
2288 store_operator_by_tag(Tag,Opname,Operator,TheoryID,PT,Ops,Kind) :-
2289 store_operator_by_tag1(Tag,Opname,Operator,PT,Ops),
2290 get_operator_parameters(Operator,Parameters),
2291 pretty_print_tag(Tag,PrettyTag),
2292 store_operator_definition(TheoryID,Opname,Parameters,
2293 function(none,identifier(none,Kind),[identifier(none,PrettyTag)]),truth(none),[],
2294 axiomatic). % for bvisual2: todo pass type params PT
2295
2296 :- use_module(translate,[translate_raw_bexpr_with_limit/3]).
2297 pretty_print_tag(bexpr(Raw),TS) :- translate_raw_bexpr_with_limit(Raw,100,TS),!. % TODO: unicode
2298 pretty_print_tag(Tag,Tag).
2299
2300 store_operator_by_tag1(Tag,Opname,Operator,PT,Ops) :-
2301 debug_format(19,'Storing tag ~w for operator ~w~n',[Tag,Opname]),
2302 % SIGMA or PI
2303 aggregation_operator(Tag,Functor),!,
2304 get_operator_parameters(Operator,Parameters),
2305 ( Parameters = [Arg] ->
2306 create_raw_aggregation_op(Functor,Arg,ClassicalBOp),
2307 Ops=[Opname-axiomatic_definition(Tag,[Arg],ClassicalBOp,PT)]
2308 ;
2309 parameter_error(Parameters,1,Opname),Ops=[]
2310 ).
2311 store_operator_by_tag1(mkinat,OpName,Operator,PT,Ops) :- !,
2312 store_operator_by_tag1(mkinat(iZero,iSucc),OpName,Operator,PT,Ops).
2313 store_operator_by_tag1(mkinat(ZeroOp,SuccOp),OpName,Operator,_PT,Ops) :- !,
2314 get_operator_parameters(Operator,Parameters),
2315 ( Parameters = [argument(Arg,_ArgType)] ->
2316 Ops=[OpName-make_inductive_natural(Arg,ZeroOp,SuccOp)]
2317 ;
2318 parameter_error(Parameters,1,OpName),Ops=[]
2319 ).
2320 store_operator_by_tag1(BOperator,Opname,Operator,PT,Ops) :-
2321 unary_operator_raw_term(BOperator,Arg1,Expr), !,
2322 check_if_operator_expr_uses_reals(Expr),
2323 get_operator_parameters(Operator,Parameters),
2324 ( Parameters = [argument(Arg1,_ArgType)] ->
2325 Ops=[Opname-axiomatic_definition(BOperator,Parameters,Expr,PT)]
2326 ; Parameters = [] -> % The Rodin theory operator is a constant without arguments
2327 Arg1='OpArg1',
2328 CArgs = [identifier(none,Arg1)],
2329 % try and generate lambda if we have an expression and relation for predicate
2330 % we assume they are all expressions:
2331 CurryExpr = lambda(none,CArgs,truth(none),Expr),
2332 % TODO: use ArgType1 in CurryExpr
2333 add_message(bmachine_eventb,'Lifting ProB unary operator to lambda expression (Rodin theory operator has no arguments): ',BOperator),
2334 Ops=[Opname-axiomatic_definition(BOperator,Parameters,CurryExpr,PT)]
2335 ;
2336 parameter_error(Parameters,1,Opname),Ops=[]
2337 ).
2338 store_operator_by_tag1(BOperator,Opname,Operator,PT,Ops) :-
2339 binary_operator_raw_term(BOperator,Arg1,Arg2,Expr,Kind), !,
2340 check_if_operator_expr_uses_reals(Expr),
2341 get_operator_parameters(Operator,Parameters),
2342 ( Parameters = [argument(Arg1,_ArgType1), argument(Arg2,_ArgType2)] ->
2343 Ops=[Opname-axiomatic_definition(BOperator,Parameters,Expr,PT)]
2344 ; Parameters = [] -> % The Rodin theory operator is a constant without arguments
2345 Arg1='OpArg1', Arg2='OpArg2',
2346 CArgs = [identifier(none,Arg1),identifier(none,Arg2)],
2347 % try and generate lambda if we have an expression and relation for predicate
2348 (Kind=expression
2349 -> CurryExpr = lambda(none,CArgs,truth(none),Expr)
2350 ; CurryExpr = comprehension_set(none,CArgs,Expr)
2351 ),
2352 % TODO: use ArgType1/2 in CurryExpr
2353 add_message(bmachine_eventb,'Lifting ProB binary operator to lambda expression (Rodin theory operator has no arguments): ',BOperator),
2354 Ops=[Opname-axiomatic_definition(BOperator,Parameters,CurryExpr,PT)]
2355 ;
2356 parameter_error(Parameters,2,Opname),Ops=[]
2357 ).
2358 store_operator_by_tag1(BOperator,Opname,Operator,PT,Ops) :-
2359 constant_operator_raw_term(BOperator,Expr), !,
2360 check_if_operator_expr_uses_reals(Expr),
2361 get_operator_parameters(Operator,Parameters),
2362 map_over_raw_expr(Expr,detect_external_fun_calls,RewrittenExpr),
2363 length(Parameters,NrParas),
2364 %format('Mapping operator ~w (~w paras: ~w) to: ',[Opname,NrParas,Parameters]), translate:print_raw_bexpr(RewrittenExpr),nl,
2365 ( Parameters = [] ->
2366 Ops=[Opname-axiomatic_definition(BOperator,Parameters,RewrittenExpr,PT)]
2367 ; can_be_predicate(RewrittenExpr,NrParas),
2368 maplist(argument_to_raw_id,Parameters,ParIds),
2369 couplise_raw_list(ParIds,ParCouple) ->
2370 % the operator is a predicate operator, in the .ptm file is a set comprehension defining it
2371 MembershipTest = member(none,ParCouple,RewrittenExpr),
2372 debug_println(19,created_membership_for_predicate_operator_call(Opname)),
2373 Ops=[Opname-axiomatic_definition(BOperator,Parameters,MembershipTest,PT)]
2374 ; % Create function application for set comprehensions / lambdas as parameters expected in Rodin
2375 can_be_function(RewrittenExpr,NrParas),
2376 maplist(argument_to_raw_id,Parameters,ParIds),
2377 couplise_raw_list(ParIds,ParCouple) ->
2378 Fapp = function(none,RewrittenExpr,ParCouple),
2379 debug_println(19,created_function_application_for_operator_call(Opname)),
2380 Ops=[Opname-axiomatic_definition(BOperator,Parameters,Fapp,PT)]
2381 ; %unreachable at the moment:
2382 parameter_error(Parameters,0,Opname),Ops=[]
2383 ).
2384
2385 argument_to_raw_id(argument(Arg,_),identifier(none,Arg)).
2386
2387 % TODO: maybe store/lookup type of operator and check if it is a predicate operator
2388 can_be_predicate(comprehension_set(_,Paras,_),NrParas) :-
2389 length(Paras,NrParas).
2390 can_be_predicate(symbolic_comprehension_set(Pos,Paras,B),NrParas) :-
2391 can_be_predicate(comprehension_set(Pos,Paras,B),NrParas).
2392 can_be_predicate(event_b_comprehension_set(Pos,Paras,B,_E),NrParas) :-
2393 can_be_predicate(comprehension_set(Pos,Paras,B),NrParas).
2394 can_be_predicate(symbolic_event_b_comprehension_set(Pos,Paras,B,E),NrParas) :-
2395 can_be_predicate(event_b_comprehension_set(Pos,Paras,B,E),NrParas).
2396
2397
2398 % TODO: check if NrParas compatible
2399 can_be_function(comprehension_set(_,_,_),_NrParas) :- !.
2400 can_be_function(lambda(_,_,_,_),_) :- !.
2401 can_be_function(symbolic_comprehension_set(_,_,_),_) :- !.
2402 can_be_function(event_b_comprehension_set(_,_,_),_NrParas) :- !.
2403 can_be_function(symbolic_event_b_comprehension_set(_,_,_,_),_) :- !.
2404 can_be_function(sequence_extension(_,_),_) :- !.
2405 can_be_function(E,_) :- functor(E,F,N), add_message(bmachine_eventb,'Attempting function application for:',F/N).
2406
2407 couplise_raw_list([Arg],Res) :- !, Res=Arg.
2408 couplise_raw_list([A,B],Res) :- !, Res=couple(none,A,B).
2409 couplise_raw_list([A,B|Rest],Result) :-
2410 couplise_raw_list([couple(A,B)|Rest],Result).
2411
2412
2413 :- use_module(external_functions, [get_external_function_type/3]).
2414 % traverse raw AST to detect calls to external functions which would not be visible in regular typechecking
2415 % these expressions come from the .ptm files where we want to be able to have access to external functions
2416 % TODO: also allow access to external predicates and external constants like REULER
2417 detect_external_fun_calls(function(Pos,TID,Args),external_function_call_auto(Pos,ID,NewArgs)) :-
2418 TID = identifier(_IdPos,ID),
2419 get_external_function_type(ID,ExpectedArgTypes,_OutputType), % TODO: check visible
2420 length(Args,Len),
2421 length(ExpectedArgTypes,ExtExpectedLen),
2422 (Len=ExtExpectedLen -> true
2423 ; parameter_error(Args,ExtExpectedLen,ID),fail),
2424 !,
2425 debug_println(19,detected_external_function_call(ID,Len)),
2426 map_over_args(Args,NewArgs). % we need to inspect tree of arguments as well, map_over_raw_expr works top-down
2427
2428 map_over_args([],[]).
2429 map_over_args([Arg1|T],[NewArg1|NT]) :- map_over_raw_expr(Arg1,detect_external_fun_calls,NewArg1),
2430 map_over_args(T,NT).
2431
2432
2433 % TO DO ternary operator ?? son/3 if_then_else
2434
2435 % construct a raw term with arguments for replacement in AST
2436 % first argument is functor name as it appears in the theory mapping file *.ptm
2437 binary_operator_raw_term(Functor,Arg1,Arg2,Term,Kind) :-
2438 binary_operator_to_ast(Functor,ASTFunctor,Kind), % TODO: return Kind
2439 Term =.. [ASTFunctor,none,identifier(none,Arg1),identifier(none,Arg2)].
2440 binary_operator_raw_term(Functor,Arg1,Arg2,Term,predicate) :-
2441 binary_external_predicate(Functor,ASTFunctor),
2442 Term = external_pred_call_auto(none, ASTFunctor, [identifier(none,Arg1),identifier(none,Arg2)]).
2443 binary_operator_raw_term(Functor,Arg1,Arg2,Term,expression) :-
2444 binary_external_function(Functor,ASTFunctor),
2445 Term = external_function_call_auto(none, ASTFunctor, [identifier(none,Arg1),identifier(none,Arg2)]).
2446
2447 binary_operator_to_ast(BOP,ASTFunctor,expression) :-
2448 binary_expr_operator_to_ast(BOP,ASTFunctor).
2449 binary_operator_to_ast(BOP,ASTFunctor,predicate) :-
2450 binary_pred_operator_to_ast(BOP,ASTFunctor).
2451 binary_expr_operator_to_ast('^',concat).
2452 binary_expr_operator_to_ast(concat,concat).
2453 %binary_expr_operator_to_ast(div,floored_div). % now dealt with in get_typed_default_operator
2454 binary_expr_operator_to_ast(floored_div,floored_div). % integer division rounding down, e.g. for a theory's div
2455 binary_expr_operator_to_ast(restrict_front,restrict_front).
2456 binary_expr_operator_to_ast(restrict_tail,restrict_tail).
2457 % binary tree operators
2458 binary_expr_operator_to_ast(arity,arity).
2459 binary_expr_operator_to_ast(bin,bin).
2460 binary_expr_operator_to_ast(const,const).
2461 binary_expr_operator_to_ast(father,father).
2462 binary_expr_operator_to_ast(rank,rank).
2463 binary_expr_operator_to_ast(subtree,subtree).
2464 % real operators
2465 binary_expr_operator_to_ast(rdiv,div_real).
2466 binary_expr_operator_to_ast(plus,add_real).
2467 binary_expr_operator_to_ast(power_of_real,power_of_real).
2468 binary_expr_operator_to_ast(power_of,power_of). % also in get_typed_default_operator
2469 binary_expr_operator_to_ast(pow,power_of). % ditto
2470 binary_expr_operator_to_ast(minus,minus_real).
2471 binary_expr_operator_to_ast(mul,multiplication_real).
2472 binary_expr_operator_to_ast(mult,multiplication_real).
2473 % real predicates:
2474 binary_pred_operator_to_ast(less,less_real).
2475 binary_pred_operator_to_ast(less_equal,less_equal_real).
2476 binary_pred_operator_to_ast('smr',less_real). % from Rodin Real Theory v.2.1
2477 binary_pred_operator_to_ast(leq,less_equal_real). % from Rodin Real Theory v.2.1
2478 % Note: there is currently no greater_real and greater_equal_real
2479
2480 binary_external_predicate('\x22D7\','RGT'). % 8919 - greater with dot
2481 binary_external_predicate(greater,'RGT').
2482 binary_external_predicate(greater_equal,'RGEQ').
2483 binary_external_predicate('\x22D6\','RLT'). % 8918 - less with dot
2484 %binary_external_predicate(less,'RLT').
2485 %binary_external_predicate(less_equal,'RLEQ').
2486 binary_external_predicate(geq,'RGEQ').
2487 %binary_external_predicate(leq,'RLEQ'). % from Rodin Real Theory v.2.1
2488 %binary_external_predicate(smr,'RLT'). % ditto
2489 binary_external_predicate(gtr,'RGT'). % ditto
2490 binary_external_predicate(inv,'RINV'). % ditto
2491 binary_external_predicate(FUN,FUN) :-
2492 treat_as_external_pred(FUN).
2493
2494 treat_as_external_pred('REQ').
2495 treat_as_external_pred('RGT').
2496 treat_as_external_pred('RGEQ').
2497 treat_as_external_pred('RLT').
2498 treat_as_external_pred('RLEQ').
2499 treat_as_external_pred('RNEQ').
2500
2501 treat_as_external_pred('LESS'). % Prolog term order
2502 treat_as_external_pred('LEQ_SYM_BREAK').
2503 treat_as_external_pred('STRING_IS_INT').
2504 treat_as_external_pred('STRING_IS_NUMBER').
2505 treat_as_external_pred('STRING_IS_DECIMAL').
2506 treat_as_external_pred('STRING_IS_ALPHANUMERIC'). % TODO: provide more external predicates
2507
2508 binary_external_function('\x2295\','RADD'). % Unicode + with circle
2509 binary_external_function('\x2296\','RSUB').
2510 binary_external_function('\x2297\','RMUL'). % has a pre-defined Rodin meaning as direct product
2511 binary_external_function('\x2298\','RDIV').
2512 binary_external_function('\x2299\','RMUL'). % dot with circle
2513 binary_external_function(FUN,FUN) :- visible_external_function(FUN,2),
2514 \+ treat_as_external_pred(FUN).
2515
2516 :- use_module(tools,[arg_is_number/2]).
2517 % Already parsed B expression:
2518 constant_operator_raw_term(bexpr(Tree),Tree).
2519 % some types not available in Event-B:
2520 constant_operator_raw_term('FLOAT',float_set(none)).
2521 constant_operator_raw_term('REAL',real_set(none)).
2522 constant_operator_raw_term('\x211D\',real_set(none)). % unicode Real symbol 8477 in decimal
2523 constant_operator_raw_term('STRING',string_set(none)).
2524 % direct encodings:
2525 %constant_operator_raw_term('RONE',real(none,'1.0')).
2526 %constant_operator_raw_term('RZERO',real(none,'1.0')).
2527 constant_operator_raw_term(empty_string,string(none,'')).
2528 constant_operator_raw_term('EMPTY_STRING',string(none,'')).
2529 % some synonyms:
2530 constant_operator_raw_term(zero,T) :- T = real(none,'0.0'). %constant_operator_raw_term('RZERO',T).
2531 constant_operator_raw_term(one,T) :- T = real(none,'1.0'). %constant_operator_raw_term('RONE',T).
2532 constant_operator_raw_term(two,T) :- T=real(none,'2.0').
2533 constant_operator_raw_term(pi,T) :- constant_operator_raw_term('RPI',T).
2534 constant_operator_raw_term(euler,T) :- constant_operator_raw_term('REULER',T).
2535 constant_operator_raw_term(Name,external_function_call_auto(none,Name,[])) :-
2536 visible_external_function(Name,0).
2537 constant_operator_raw_term(Atom,T) :-
2538 arg_is_number(Atom,Number),
2539 (integer(Number) -> T=integer(none,Number)
2540 ; atom(Atom), % otherwise we would need to convert it to an atom for the AST
2541 T=real(none,Atom)).
2542 % This case shouldn't be needed anymore.
2543 % The theorymapping library now parses formulas ahead of time
2544 % and sends the parsed AST in a bexpr/1 term.
2545 constant_operator_raw_term(Atom,Tree) :-
2546 atom(Atom), atom_codes(Atom,Codes),
2547 %format('Tag string: ~s~n',[Codes]),
2548 get_formula_codes(Codes,FCodes),
2549 %format('Stripped delimiter: ~s~n',[FCodes]),
2550 parsercall:parse_formula(FCodes,Tree).
2551 % TODO: allow B formulas also for binary/unary operators
2552
2553 get_formula_codes([Del|T],Codes) :- delimiter(Del),!,skip_last(T,Codes,Del). % strip leading and trailing delimiter
2554 skip_last([H],[],Last) :- !, Last=H.
2555 skip_last([H|T],[H|ST],Last) :- skip_last(T,ST,Last).
2556
2557 %delimiter(0'").
2558 delimiter(36). % dollar $
2559 %delimiter(39). % simple quote
2560
2561
2562 :- use_module(external_function_declarations,[external_function_library/4]).
2563 visible_external_function(Name,Arity) :-
2564 external_function_library(Name,Arity,expression,Lib),
2565 visible_lib(Lib).
2566
2567 visible_lib('LibraryMath.def').
2568 visible_lib('LibraryRandom.def').
2569 visible_lib('LibraryReals.def').
2570 visible_lib('LibraryStrings.def').
2571 visible_lib('CHOOSE.def').
2572 visible_lib('SCCS.def').
2573 visible_lib('SORT.def').
2574 visible_lib('LibraryBits.def').
2575
2576 % construct a raw term with argument for replacement in AST
2577 % first argument is functor name as it appears in the theory mapping file *.ptm
2578 unary_operator_raw_term(Functor,Arg,Term) :-
2579 unary_operator_to_ast(Functor,ASTFunctor),
2580 Term =.. [ASTFunctor,none,identifier(none,Arg)].
2581 unary_operator_raw_term(Functor,Arg,Term) :-
2582 unary_external_function(Functor,AstFunctor),
2583 Term = external_function_call_auto(none, AstFunctor, [identifier(none,Arg)]).
2584 unary_operator_to_ast(closure,reflexive_closure). % reflexive_closure corresponds to closure B operator !
2585 unary_operator_to_ast(closure1,closure).
2586 unary_operator_to_ast(conc,general_concat).
2587 unary_operator_to_ast(fnc,trans_function).
2588 unary_operator_to_ast(rel,trans_relation).
2589 unary_operator_to_ast(succ,successor). % also exist in Event-B
2590 unary_operator_to_ast(pred,predecessor). % also exist in Event-B
2591 unary_operator_to_ast(bool,convert_bool). % also exist in Event-B
2592 unary_operator_to_ast(id,identity). % exists in similar way in Event-B
2593 unary_operator_to_ast(union,general_union).
2594 unary_operator_to_ast(inter,general_intersection).
2595 % real operators
2596 unary_operator_to_ast(real,convert_real).
2597 unary_operator_to_ast(floor,convert_int_floor).
2598 unary_operator_to_ast(ceiling,convert_int_ceiling).
2599 unary_operator_to_ast(minus,unary_minus_real). % minus also maps to binary minus
2600 unary_operator_to_ast(max,max_real).
2601 unary_operator_to_ast(min,min_real).
2602 unary_operator_to_ast(F,F) :- unary_operator(F). % operators that have same name in B and AST
2603
2604
2605 unary_external_function(choose,'CHOOSE').
2606 unary_external_function(length,'STRING_LENGTH').
2607 unary_external_function(inv,'RINV').
2608 unary_external_function(Functor,Functor) :- visible_external_function(Functor,1).
2609
2610 % sequence operators
2611 unary_operator(seq).
2612 unary_operator(seq1).
2613 unary_operator(iseq).
2614 unary_operator(iseq1).
2615 unary_operator(perm).
2616 unary_operator(first).
2617 unary_operator(size).
2618 unary_operator(front).
2619 unary_operator(tail).
2620 unary_operator(rev).
2621 unary_operator(last).
2622 unary_operator(mu).
2623 % tree operators
2624 unary_operator(tree).
2625 unary_operator(btree).
2626 unary_operator(top).
2627 unary_operator(sons).
2628 unary_operator(bin).
2629 unary_operator(left).
2630 unary_operator(right).
2631 unary_operator(sizet).
2632 unary_operator(prefix).
2633 unary_operator(postfix).
2634 %unary_operator(infix). % not yet supported
2635 %unary_operator(mirror). % not yet supported
2636 % general operators
2637 unary_operator(min). % also exist in Event-B
2638 unary_operator(max). % also exist in Event-B
2639 unary_operator(domain).
2640 unary_operator(range).
2641 % z operators
2642 unary_operator(compaction).
2643 unary_operator(bag_items).
2644
2645 % in the SUMandPRODUCT theory provided on https://prob.hhu.de/w/index.php?title=Event-B_Theories
2646 % the SIGMA and PI operators work on relations TYPE <-> INTEGER
2647 % we actually create SIGMA(I,N).(I|->N:Arg | N) or PI
2648 % However, we now also support SIGMA and PI to work directly on integer sets
2649 aggregation_operator('SIGMA',general_sum).
2650 aggregation_operator('PI',general_product).
2651
2652 integer_set_type(pow_subset(_,integer_set(_))).
2653 relation_to_integer_type(pow_subset(_,cartesian_product(_,_,integer_set(_)))).
2654 binary_relation_type(pow_subset(_,cartesian_product(_,_A,_B))).
2655
2656
2657 create_raw_aggregation_op(Op,argument(Arg,ArgType),Result) :-
2658 integer_set_type(ArgType),!,
2659 % we have an operator acting directly on sets of integers
2660 % we translate it as SIGMA(N).(N:Arg|N)
2661 A = identifier(none,Arg), % User-given argument
2662 create_fresh_identifier('_agg_op1',[A],I1), % starting with _ ensures user cannot create such an id
2663 N = identifier(none,I1), % N is the integer to sum or multiply
2664 Pred = member(none,N,A), % I|->N : Arg
2665 Result =.. [Op,none,[N],Pred,N]. % SIGMA(I,N).(I|->N:Arg | N) (or PI)
2666 create_raw_aggregation_op(Op,argument(Arg,_ArgType),Result) :-
2667 % this construction will immediately wrap _agg_op1/2 inside Sigma or Pi, and thus _agg_op1/2 will not be visibile outside
2668 A = identifier(none,Arg), % User-given argument
2669 create_fresh_identifier('_agg_op1',[A],I1), % starting with _ ensures user cannot create such an id
2670 create_fresh_identifier('_agg_op2',[A],I2), % (in Camille at least)
2671 I = identifier(none,I1), % I is the (not used) index variable
2672 N = identifier(none,I2), % N is the integer to sum or multiply
2673 Pred = member(none,couple(none,I,N),A), % I|->N : Arg
2674 Result =.. [Op,none,[I,N],Pred,N]. % SIGMA(I,N).(I|->N:Arg | N) (or PI)
2675
2676 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2677 % Theory plug-in: what can be written in a .ptm file, for tools that help to write them
2678 % (e.g. ProB for Rodin, which creates .ptm files with suggestions for a theory's operators)
2679
2680 % get_theory_mapping_targets(-Targets,-Defaults)
2681 % Targets: sorted list of target(Tag,Arity,Kind,Category,Construct), one for each Tag that can be written
2682 % between { and } in a line operator "Op" internal {Tag} of a .ptm file, where
2683 % Arity is the number of arguments the theory's operator Op must have (0, 1 or 2),
2684 % Kind is expression or predicate (what Op is mapped to),
2685 % Category is b_operator, external_function, external_predicate, constant, aggregation or inductive_natural,
2686 % Construct is the construct ProB uses: an AST functor, an external function or predicate, or a value
2687 % (for information only).
2688 % Apart from these tags, a B formula can be written as {$Formula$}; for an operator with arguments
2689 % it must be a lambda expression or set comprehension.
2690 % Defaults: sorted list of default(Op,Arity,Tag,ArgType): the tag ProB uses for an axiomatic operator Op
2691 % with Arity arguments if there is no .ptm entry for it; ArgType is any, or integer or real if the
2692 % default needs arguments of this type (see get_default_operator/4 and get_typed_default_operator/5).
2693 % ProB may not use the default if the arguments do not fit (e.g. SIGMA needs a set of integers or
2694 % a relation to integers).
2695 :- assert_must_succeed((get_theory_mapping_targets(T,D),
2696 member(target(floored_div,2,expression,b_operator,floored_div),T),
2697 member(target('SIGMA',1,expression,aggregation,general_sum),T),
2698 \+ member(target('\x2295\',_,_,_,_),T), % unicode tags cannot be written in .ptm files
2699 member(default(div,2,floored_div,integer),D),
2700 member(default('\x2295\',2,'RADD',any),D))).
2701 get_theory_mapping_targets(Targets,Defaults) :-
2702 findall(target(Tag,Arity,Kind,Category,Construct),
2703 (mapping_target(Tag,Arity,Kind,Category,Construct), ascii_tag(Tag)),Ts),
2704 sort(Ts,Targets),
2705 findall(default(Op,Arity,Tag,ArgType),mapping_default(Op,Arity,Tag,ArgType),Ds),
2706 sort(Ds,Defaults).
2707
2708 % the tags, in the order store_operator_by_tag1/5 tries them
2709 mapping_target(Tag,1,expression,aggregation,Construct) :-
2710 aggregation_operator(Tag,Construct).
2711 mapping_target(mkinat,1,expression,inductive_natural,make_inductive_natural).
2712 mapping_target(Tag,1,expression,Category,Construct) :-
2713 mapping_unary_tag(Tag),
2714 once(unary_operator_raw_term(Tag,x,Term)),
2715 mapping_construct(Term,Category,Construct).
2716 mapping_target(Tag,2,Kind,Category,Construct) :-
2717 mapping_binary_tag(Tag),
2718 \+ mapping_unary_tag(Tag), % the unary mapping is used
2719 once(binary_operator_raw_term(Tag,x,y,Term,Kind)),
2720 mapping_construct(Term,Category,Construct),
2721 mapping_external_arity_ok(Category,Construct,2).
2722 mapping_target(Tag,0,expression,Category,Construct) :-
2723 mapping_constant_tag(Tag),
2724 \+ mapping_unary_tag(Tag), \+ mapping_binary_tag(Tag),
2725 once(constant_operator_raw_term(Tag,Term)),
2726 mapping_construct(Term,Category,Construct).
2727
2728 mapping_unary_tag(Tag) :-
2729 findall(T,(unary_operator_to_ast(T,_) ; unary_external_function(T,_)),Ts),
2730 sort(Ts,STs), member(Tag,STs), \+ aggregation_operator(Tag,_), Tag \= mkinat.
2731 mapping_binary_tag(Tag) :-
2732 findall(T,(binary_expr_operator_to_ast(T,_) ; binary_pred_operator_to_ast(T,_) ;
2733 binary_external_predicate(T,_) ; binary_external_function(T,_)),Ts),
2734 sort(Ts,STs), member(Tag,STs), \+ aggregation_operator(Tag,_), Tag \= mkinat.
2735 % the tags of constant_operator_raw_term/2 (it also accepts numbers and B formulas);
2736 % the unicode symbol for the reals is left out: it cannot be written as a tag
2737 mapping_constant_tag(Tag) :-
2738 member(Tag,['FLOAT','REAL','STRING',empty_string,'EMPTY_STRING',zero,one,two,pi,euler]).
2739 mapping_constant_tag(Tag) :-
2740 findall(T,visible_external_function(T,0),Ts),
2741 sort(Ts,STs), member(Tag,STs).
2742
2743 mapping_construct(external_function_call_auto(_,F,_),external_function,F) :- !.
2744 mapping_construct(external_pred_call_auto(_,F,_),external_predicate,F) :- !.
2745 mapping_construct(real(_,V),constant,V) :- !.
2746 mapping_construct(integer(_,V),constant,V) :- !.
2747 mapping_construct(string(_,V),constant,V) :- !.
2748 mapping_construct(Term,b_operator,F) :- functor(Term,F,_).
2749
2750 % e.g. some external predicates treated as binary only have one argument
2751 mapping_external_arity_ok(Category,F,Arity) :-
2752 (Category=external_function ; Category=external_predicate),
2753 get_external_function_type(F,ArgTypes,_),!,
2754 length(ArgTypes,Arity).
2755 mapping_external_arity_ok(_,_,_).
2756
2757 % the defaults of get_default_operator/4 and get_typed_default_operator/5
2758 mapping_default('\x211D\',0,'REAL',any).
2759 mapping_default('SUM',1,'SIGMA',any).
2760 mapping_default('PRODUCT',1,'PI',any).
2761 mapping_default(cls,1,closure1,any).
2762 mapping_default(Op,2,Tag,any) :-
2763 (binary_external_function(Op,Tag) ; binary_external_predicate(Op,Tag)),
2764 Op \= Tag,
2765 once(mapping_target(Tag,2,_,_,_)).
2766 mapping_default(Op,2,Tag,ArgType) :-
2767 binary_expr_op(Op,ArgType,NewOp),
2768 mapping_typed_default_tag(NewOp,Tag).
2769 mapping_default(Tag,Arity,Tag,any) :- % the operator has the name of a tag
2770 mapping_target(Tag,Arity,_,_,_), ascii_tag(Tag),
2771 \+ binary_expr_op(Tag,_,_),
2772 \+ (Arity=2, (binary_external_function(Tag,T2) ; binary_external_predicate(Tag,T2)), T2 \= Tag).
2773
2774 % tags such as the unicode symbols of binary_external_function/2 cannot be written in a .ptm file,
2775 % they are only names of operators which ProB maps by default
2776 ascii_tag(Tag) :- atom_codes(Tag,Codes), \+ (member(C,Codes), C > 127).
2777
2778 % the tags for the constructs of binary_expr_op/3
2779 mapping_typed_default_tag(floored_div,floored_div).
2780 mapping_typed_default_tag(div_real,rdiv).
2781 mapping_typed_default_tag(power_of,power_of).
2782 mapping_typed_default_tag(power_of_real,power_of_real).
2783
2784 parameter_error(RodinParameters,ExpectedByProB,Opname) :-
2785 length(RodinParameters,N),
2786 ajoin(['ProB theory mapping: ProB translation expects ',ExpectedByProB,' parameter(s) for operator ',
2787 Opname,' but Rodin definition has ',N],Msg),
2788 add_error(bmachine_eventb,Msg).
2789
2790 get_operator_parameters(operator(_Opname,Parameters,_WD,_DirectDef,_RecursiveDef),Parameters).
2791 get_operator_parameters(axdef(_Opname,Parameters,_WD,_Block),Parameters).
2792
2793 store_eventb_operator(Id,Op,Ein,Eout) :-
2794 env_store_operator(Id,bmachine_eventb:Op,Ein,Eout).
2795
2796
2797 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2798 % Operator for constructing inductive natural numbers (mkinat in Rodin .ptm theory mapping file)
2799 :- public make_inductive_natural/11.
2800 % called by btypechecker:lookup_eventb_operator
2801 make_inductive_natural(ArgId,ZeroOp,SuccOp,
2802 Id,[TParam],_Pos,Env,expr,Result,TRin,TRout) :-
2803 unique_id("opresult.",ResultId),
2804 create_typed_id(ResultId,NatType,TResult),
2805 create_typed_id(ArgId,integer,TArgId),
2806 % prepare environment:
2807 add_identifiers_to_environment([TArgId,TResult],Env,Env1),
2808 % we create a recursive function by using a (as recursive annotated) comprehension
2809 % set. We can refer to the compset with RecId.
2810 create_recursive_compset([TArgId,TResult],Cond,set(couple(integer,NatType)),[],RecId,TCompSet),
2811 % used for recursive call:
2812 env_store(RecId,set(couple(integer,NatType)),[],Env1,SubEnv),
2813 % just type iZero to retrieve its type:
2814 IZero=extended_expr(none,ZeroOp,[],[]),
2815 btype(make_inductive_natural,IZero,SubEnv,NatType,_,TRin,TR1),
2816 % Arg=0 => Result=iZero
2817 RawCase1=implication(none,
2818 equal(none,identifier(none,ArgId),integer(none,0)),
2819 equal(none,identifier(none,ResultId),IZero)),
2820 btype(make_inductive_natural,RawCase1,SubEnv,pred,Case1,TR1,TR2),
2821 % Arg>0 => Result=iSucc( recursive_call(Arg-1) )
2822 RawCase2=implication(none,
2823 greater(none,identifier(none,ArgId),integer(none,0)),
2824 equal(none,identifier(none,ResultId),extended_expr(none,SuccOp,[Minus1],[]))),
2825 Minus1=function(none,identifier(none,RecId),minus(none,identifier(none,ArgId),integer(none,1))),
2826 btype(make_inductive_natural,RawCase2,SubEnv,pred,Case2,TR2,TRout),
2827 % {Arg,Result | Arg=0=>Result=iZero & Arg>0=>Result=iSucc( RC(Arg-1) )}
2828 conjunct_predicates([Case1,Case2],Cond),
2829 % {Arg,Result | Arg=0=>Result=iZero & Arg>0=>Result=iSucc( RC(Arg-1) )}(TParam)
2830 create_texpr(function(TCompSet,TParam),NatType,[theory_operator(Id,1)],Result).