1 % (c) 2009-2024 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html
4
5 :- module(b_ast_cleanup, [clean_up/3, clean_up_pred/3,
6 clean_up_pred_or_expr/3,
7 clean_up_pred_or_expr_with_path/4, % provide initial path, used for eventb context infos
8 clean_up_l_wo_optimizations/4,
9 clean_up_l_with_optimizations/4,
10 check_used_ids_info/4, recompute_used_ids_info/2,
11 definitely_not_empty_and_finite/1, definitely_infinite/1, % TO DO: move to another module
12 get_unique_id/2,
13 predicate_level_optimizations/2,
14 perform_do_not_enumerate_analysis/5,
15 has_top_level_wd_condition/1]).
16
17 :- use_module(module_information,[module_info/2]).
18 :- module_info(group,typechecker).
19 :- module_info(description,'This module implements transformations/simplifications on the AST.').
20
21 :- set_prolog_flag(double_quotes, codes). % relevant for detecting prob-ignore, test 2151 on SWI
22
23 :- use_module(tools, [safe_atom_chars/3,exact_member/2,foldl/4,filter/4]).
24 :- use_module(tools_lists, [length_less/2]).
25 :- use_module(error_manager).
26 :- use_module(debug).
27 :- use_module(self_check).
28 :- use_module(bsyntaxtree).
29 :- use_module(translate,[print_bexpr/1, translate_span/2, get_definition_context_from_span/2]).
30 :- use_module(btypechecker, [unify_types_strict/2]).
31 :- use_module(preferences,[get_preference/2]).
32 :- use_module(custom_explicit_sets,[convert_to_avl/2]).
33 :- use_module(prob_rewrite_rules(b_ast_cleanup_rewrite_rules),[rewrite_rule_with_rename/7]).
34 :- use_module(b_enumeration_order_analysis, [find_do_not_enumerate_variables/4]).
35 :- use_module(performance_messages,[perfmessage/2]).
36 :- use_module(b_operation_guards,[get_operation_propositional_guards/6]).
37
38 :- use_module(library(lists)).
39 :- use_module(library(ordsets)).
40 :- use_module(library(system), [environ/2]).
41
42 % entry point for cleaning up predicates; ensures that global, predicate-level optimizations also applied
43 clean_up_pred(Expr,NonGroundExceptions,CleanedUpExpr) :-
44 clean_up(Expr,NonGroundExceptions,CExpr),
45 (get_texpr_type(CExpr,pred)
46 -> predicate_level_optimizations(CExpr,CleanedUpExpr)
47 ; add_internal_error('Not predicate: ',clean_up_pred(Expr,NonGroundExceptions,CleanedUpExpr)),
48 CleanedUpExpr = CExpr).
49
50 % Warning: arguments swapped with clean_up for maplist !
51 clean_up_pred_or_expr(NonGroundExceptions,Expr,CleanedUpExpr) :-
52 ? clean_up_pred_or_expr_with_path(NonGroundExceptions,Expr,CleanedUpExpr,[]).
53 clean_up_pred_or_expr_with_path(NonGroundExceptions,Expr,CleanedUpExpr,Path) :-
54 clean_up_init(NonGroundExceptions,Expr,Expr1),
55 ? clean_up_aux(Expr1,NonGroundExceptions,CExpr,Path),
56 (get_texpr_type(CExpr,pred)
57 -> predicate_level_optimizations(CExpr,CleanedUpExpr,Path)
58 ; CleanedUpExpr = CExpr).
59
60 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
61
62 % clean up some code afterwards
63 clean_up(Expr,NonGroundExceptions,CExpr) :- % clean-up with init
64 clean_up_init(NonGroundExceptions,Expr,Expr1),
65 clean_up_aux(Expr1,NonGroundExceptions,CExpr,[]).
66 clean_up_aux(Expr1,NonGroundExceptions,CExpr,Path) :- % performs no init
67 (preferences:get_preference(normalize_ast,true)
68 -> cleanups(normalize,Expr1,[],Expr2,Path)
69 ; Expr2=Expr1),
70 cleanups(pre,Expr2,[],TPExpr,Path),
71 remove_bt(TPExpr,PExpr,LExpr,TLExpr),
72 ? syntaxtransformation(PExpr,Subs,_,NewSubs,LExpr),
73 functor(PExpr,F,N),
74 % recursively clean up sub-expressions
75 ? clean_up_l(Subs,NonGroundExceptions,NewSubs,F/N,1,Path),
76 cleanups(post,TLExpr,[],CExpr,Path).
77 %, tools_printing:print_term_summary(cleaned_up(CExpr)),nl.
78
79 % just run post-phase
80 %cleanups_post(Expr,CleanedupExpr) :- cleanups(post,Expr,[],CleanedupExpr,[]).
81
82 clean_up_init(NonGroundExceptions,Expr,Expr1) :-
83 % ensure that WD info is available also for pre phase
84 % and normalise record types: todo: use NonGroundExceptions in normalise_record_types
85 ? (transform_bexpr(b_ast_cleanup:compute_wd_info_and_norm_record_types(NonGroundExceptions),Expr,Expr1) -> true
86 ; add_internal_error('Call failed:',clean_up_init(NonGroundExceptions,Expr,Expr1)), Expr1=Expr).
87
88 :- use_module(kernel_records,[normalise_record_types/4]).
89 :- use_module(bsyntaxtree,[transform_bexpr/3]).
90 compute_wd_info_and_norm_record_types(NonGroundExceptions,b(E,Type0,I),b(E,Type2,NInfo)) :-
91 %normalise_record_types(Type,NonGroundExceptions,NType,_),
92 ? (nonmember(contains_wd_condition,I),is_possibly_undefined(E)
93 -> NInfo = [contains_wd_condition|I]
94 ; NInfo = I),
95 (NonGroundExceptions = do_not_ground_types -> Type2=Type0
96 ; ground_type_to_any(Type0,NonGroundExceptions),
97 normalise_record_types(Type0,NonGroundExceptions,Type1,HasRecords),
98 (HasRecords == true -> Type2=Type1 ; Type2=Type0)
99 ).
100
101
102 :- use_module(library(ordsets),[ord_nonmember/2, ord_add_element/3]).
103 % apply the clean-up rules to an expression until all
104 % applicable rules are processed
105 % cleanups(Phase,Expr,AppliedRules,Result,Path):
106 % Phase: pre or post or normalize
107 % Expr: the expression to clean up
108 % AppliedRules: a sorted list of clean up rules that have been already applied
109 % and must only be apply once ("single" mode)
110 % Result: the cleaned-up expression
111 % Path: list of outer functors leading to this expression; can be used to decide about applicability of rules
112 cleanups(Phase,Expr,AppliedRules,Result,Path) :-
113 %% print(cleanups(Phase,Expr,AppliedRules,Result,Path)),nl,
114 % set up co-routines that ensure that "Rule" is not applied if
115 % is in the list AppliedRules
116 start_profile_rule(RuleInfos),
117 assure_single_rules(AppliedRules,Mode,Rule),
118 ? ( cleanup_phase(Phase,Expr,NExpr,Mode/Rule,Path) -> % try to apply a rule (matching the current phase)
119 ( Mode==single -> ord_add_element(AppliedRules,Rule,AppRules) % if the rule is marked as "single", we add to the list of already applied rules
120 ; Mode==multi -> AppRules = AppliedRules % if "multi", we do not add it to the list, the rule might be applied more than once
121 ; add_error_fail(b_ast_cleanup,'Unexpected rule mode ',Mode)
122 ),
123 stop_profile_rule(Rule,Mode,Phase,Expr,RuleInfos),
124 %(NExpr=b(_,_,I),bsyntaxtree:check_infos(I,Rule) -> true ; true),
125 cleanups(Phase,NExpr,AppRules,Result,Path) % continue recursively with the new expression
126 ; % if no rule matches anymore,
127 Result = Expr, % we leave the expression unmodified
128 Mode=multi, Rule=none). % and unblock the co-routine (see assure_single_rules/3)
129
130
131 :- if(environ(prob_safe_mode,true)).
132 start_profile_rule([R1,W1]) :- statistics(runtime,[R1,_]),statistics(walltime,[W1,_]).
133 stop_profile_rule(Rule,Mode,Phase,Expr,[R1,W1]) :-
134 statistics(runtime,[R2,_]),statistics(walltime,[W2,_]), DeltaW is W2-W1, DeltaR is R2-R1,
135 (DeltaW < 20 -> true ; format('Firing AST cleanup rule ~w (mode:~w) in phase ~w took ~w ms (~w ms walltime)~n',[Rule,Mode,Phase,DeltaR,DeltaW]), translate:print_span(Expr),nl),
136 runtime_profiler:register_profiler_runtime(Rule,unknown,DeltaR,DeltaW).
137 %%% print(fired_rule(Rule,Mode,Phase)),nl, translate:print_bexpr_or_subst(Expr), print(' ===> '),nl, translate:print_bexpr_or_subst(NExpr),nl, print_ast(NExpr),nl, %% COMMENT IN TO SEE applied RULES <---------------
138 %(map_over_typed_bexpr(b_ast_cleanup:check_valid_result,NExpr) -> true ; true), % comment in to check output after every firing of a rule
139 :- else.
140 start_profile_rule(_).
141 stop_profile_rule(_,_,_,_,_).
142 :- endif.
143
144 %check_valid_result(b(xexists([b(identifier(msgXX),integer,_)|_],_),pred,Infos)) :- nonmember(allow_to_lift_exists,Infos),print(missing_info),nl,trace,fail.
145
146 assure_single_rules([],_Mode,_Rule) :- !.
147 assure_single_rules(AppliedRules,Mode,Rule) :-
148 assure_single_rules2(AppliedRules,Mode,Rule).
149 :- block assure_single_rules2(?,-,?),assure_single_rules2(?,?,-).
150 assure_single_rules2(_AppliedRules,_,none) :- !.
151 assure_single_rules2(_AppliedRules,multi,_) :- !.
152 assure_single_rules2(AppliedRules,_,Rule) :-
153 % typically AppliedRules not very long; would also do: \+ member(Rule, AppliedRules).
154 ord_nonmember(Rule,AppliedRules).
155
156 cleanup_phase(Phase,OTExpr,NTExpr,Mode/Rule,Path) :-
157 create_texpr(OExpr,OType,OInfo,OTExpr),
158 check_generated_info(OInfo,entry,Path),
159 create_texpr(NExpr,NType,NInfo,NTExpr),
160 ? cleanup_phase2(Phase,OExpr,OType,OInfo,NExpr,NType,NInfo,Mode/Rule,Path),
161 check_generated_info(NInfo,Rule,Path).
162 cleanup_phase2(normalize,OExpr,OType,OInfo,NExpr,NType,NInfo,Mode/Rule,_Path) :-
163 decompose_rule(Mode_Rule,Mode,Rule),
164 cleanup_normalize(OExpr,OType,OInfo,NExpr,NType,NInfo,Mode_Rule),
165 (debug_mode(off) -> true
166 ; print('Rewritten: '), print_bexpr(b(OExpr,OType,OInfo)),nl,
167 print(' Into: '), print_bexpr(b(NExpr,NType,NInfo)),nl
168 ).
169 cleanup_phase2(pre,OExpr,OType,OInfo,NExpr,NType,NInfo,Mode/Rule,Path) :-
170 decompose_rule(Mode_Rule,Mode,Rule),
171 ? cleanup_pre_with_path(OExpr,OType,OInfo,NExpr,NType,NInfo,Mode_Rule,Path).
172 cleanup_phase2(post,OExpr,OType,OInfo,NExpr,NType,NInfo,Mode/Rule,Path) :-
173 decompose_rule(Mode_Rule,Mode,Rule),
174 ? cleanup_post_with_path(OExpr,OType,OInfo,NExpr,NType,NInfo,Mode_Rule,Path).
175 % check_ast(b(NExpr,NType,NInfo)),nl.
176
177 :- block decompose_rule(-,?,?).
178 decompose_rule(Mode_Rule,Mode,Rule) :-
179 (functor(Mode_Rule,'/',2)
180 -> Mode_Rule = Mode/Rule
181 ; add_internal_error('Illegal cleanup rule, missing mode: ',Mode_Rule),fail).
182
183 check_generated_info(Info,Rule,Path) :-
184 get_preference(prob_safe_mode,true),
185 (select(used_ids(_),Info,I1) -> member(used_ids(_),I1)),!,
186 format('Illegal used ids generated by ~w within ~w~n Infos=~w~n',[Rule,Path,Info]),
187 add_internal_error('Illegal Info generated by rule: ',Rule),
188 fail.
189 check_generated_info(_,_,_).
190
191 clean_up_l_wo_optimizations(Rest,NonGroundExceptions,CRest,SectionName) :-
192 maplist(clean_up_init(NonGroundExceptions),Rest,Rest1),
193 clean_up_l(Rest1,NonGroundExceptions,CRest,top_level(SectionName),1,[]).
194 clean_up_l([],_,[],_Functor,_Nr,_Path).
195 clean_up_l([Expr|Rest],NonGroundExceptions,[CExpr|CRest],Functor,ArgNr,Path) :-
196 ? clean_up_aux(Expr,NonGroundExceptions,CExpr,[path_arg(Functor,ArgNr)|Path]),
197 A1 is ArgNr+1,
198 ? clean_up_l(Rest,NonGroundExceptions,CRest,Functor,A1,Path).
199
200
201 % MAIN ENTRY POINT for b_machine_construction, bmachine_eventb, proz
202 % same as clean_up_l but also applies predicate_level_optimizations
203 % Context is just the name of the section/context in which the optimizations are run
204 clean_up_l_with_optimizations(Rest,NonGroundExceptions,CRest,Context) :-
205 %clean_up_l(Rest,NonGroundExceptions,CRest,top_level,1,[]).
206 ? (clean_up_l_with_opt(Rest,NonGroundExceptions,CleanedUpRest,top_level(Context),1,[]) -> CRest=CleanedUpRest
207 ; add_internal_error('Call failed:',clean_up_l_with_optimizations(Rest,NonGroundExceptions,CRest,Context)),
208 CRest=Rest
209 ).
210 clean_up_l_with_opt([],_,[],_Functor,_Nr,_Path).
211 clean_up_l_with_opt([Expr|Rest],NonGroundExceptions,[CExpr|CRest],Functor,ArgNr,Path) :-
212 %print('Cleaning up: '),translate:print_bexpr_or_subst(Expr),nl,
213 clean_up_init(NonGroundExceptions,Expr,Expr1),
214 ? clean_up_pred_or_expr_with_path(NonGroundExceptions,Expr1,CExpr,[path_arg(Functor,ArgNr)|Path]),
215 A1 is ArgNr+1,
216 ? clean_up_l_with_opt(Rest,NonGroundExceptions,CRest,Functor,A1,Path).
217
218 :- use_module(specfile,[animation_mode/1, animation_minor_mode/1]).
219 % cleanup_pre(OldExpr,OldType,OldInfo,NewExpr,NewType,NewInfo,Mode/Rule)
220
221 % optional normalization rules
222 % These rules are now generated using the prob_rule_compiler
223 %cleanup_normalize(empty_sequence,Type,Info,empty_set,Type,Info, multi/apply_normalization_rule(empty_sequence)). % rule probably not useful as empty_sequence converted to value([])?
224 cleanup_normalize(Expr,Type,Info,NewExpr,NewType,NewInfo, multi/apply_normalization_rule(Rule)) :-
225 b_ast_cleanup_rewrite_rules:normalization_rule_with_rename(Expr,Type,Info,NewExpr,NewType,NewInfo,Rule),
226 (debug_mode(off) -> true
227 ; format('Use rewrite_rule_normalize ~w~n',[Rule]),
228 print_bexpr(b(NewExpr,NewType,NewInfo)),nl
229 ),
230 (ground(NewExpr) -> true
231 ; print(not_ground_rewrite(Rule,Type,Info)),nl,
232 write(Expr),nl, write(' --> '),nl, write(NewExpr),nl,
233 fail).
234
235 never_transform_or_optimise(boolean_false).
236 never_transform_or_optimise(boolean_true).
237 %never_transform_or_optimise(bool_set).
238 never_transform_or_optimise(empty_set).
239 never_transform_or_optimise(empty_sequence). % except for normalization (cf above)
240 never_transform_or_optimise(falsity).
241 %never_transform_or_optimise(max_int).
242 %never_transform_or_optimise(min_int).
243 never_transform_or_optimise(truth).
244 never_transform_or_optimise(identifier(_)).
245 never_transform_or_optimise(integer(_)).
246 never_transform_or_optimise(real(_)).
247 never_transform_or_optimise(string(_)).
248 never_transform_or_optimise(value(_)) :- preferences:preference(normalize_ast, false).
249
250
251 % first check for a few expressions that never need to be optimised, rewritten:
252 cleanup_pre_with_path(E,_,_,_,_,_,_,_) :- never_transform_or_optimise(E),!,fail.
253 % TO DO: think about enabling the following clause
254 cleanup_pre_with_path(exists(AllIds,P),pred,I,exists(AllIds,P),pred,NewI,single/annotate_toplevel_exists,Path) :-
255 % mark the exists inside {paras| #(AllIds).(P)} as allowed to be lifted; relevant for test 1945 (although delayed semi_lifting in b_test_exists_wo_expansion also solves performance issue)
256 Path = [H|_], % TODO: also deal with lambda and other quantifications
257 H=path_arg(comprehension_set/2,1),
258 % % TO DO: add some conditions under which we allow to lift
259 get_preference(data_validation_mode,true), % TODO: check if we cannot enable this more generally
260 (debug_mode(off) -> true ; add_message(b_ast_cleanup,'Marking exists for lifting: ',AllIds,I)),
261 add_info_if_new(I,allow_to_lift_exists,NewI).
262 % mark existential quantifier as outermost: no need to delay it in b_interpreter:b_test_exists_wo_expansion
263 cleanup_pre_with_path(OExpr,OType,OInfo,NExpr,NType,NInfo,Mode_Rule,_) :-
264 ? cleanup_pre(OExpr,OType,OInfo,NExpr,NType,NInfo,Mode_Rule).
265
266 % Now cleanup_pre rules that do not require path:
267
268 cleanup_pre(block(TS),subst,_,Subst,subst,Info,multi/remove_block) :-
269 !,get_texpr_expr(TS,Subst),get_texpr_info(TS,Info).
270 % replace finite by truth
271 cleanup_pre(finite(S),pred,I,truth,pred,[was(finite(S))|I],multi/remove_finite) :-
272 % preferences:get_preference(disprover_mode,false), % keep finite in disprover goals
273 get_texpr_type(S,Type),
274 (typing_tools:is_provably_finite_type(Type) -> true
275 % ; is_infinite_ground_type(Type) -> fail
276 % ; print(no_longer_assuming_finite(Type)),nl,b_global_sets:portray_global_sets,nl,fail
277 ),!. % add_message(ast,'Removed : ',b(finite(S),pred,I),I).
278 /*
279 cleanup_pre(domain(SETC),Type,I,
280 comprehension_set(DomainIds,NewPred),Type,I,multi/dom_let_pred) :-
281 get_texpr_expr(SETC,comprehension_set(CompIds,CompPred)),
282 get_domain_range_ids(CompIds,DomainIds,[RangeId]),
283 get_texpr_ids(CompIds,UnsortedIds), sort(UnsortedIds,Blacklist),
284 conjunction_to_list(CompPred,Preds),
285 select_equality(TId,Preds,Blacklist,Expr,Rest,_UsedIds,check_well_definedness),
286 same_id(TId,RangeId,_),
287 !,
288 LetIds = [RangeId], Exprs = [Expr],
289 conjunct_predicates(Rest,RestPred),
290 NewPred = b(let_predicate(LetIds,Exprs,RestPred),pred,[generated(domain)]),
291 print('Translated dom({...,x|x=E&...}) into: '),
292 print_bexpr(b(comprehension_set(DomainIds,NewPred),Type,[])),nl.
293 */
294 /* strangely enough: this does not seem to buy anything:
295 cleanup_pre(domain(SETC),Type,I,
296 let_expression(LetIds,Exprs,NewExpr),Type,[generated(domain)|I],multi/dom_let_expr) :-
297 get_texpr_expr(SETC,comprehension_set(CompIds,CompPred)),
298 get_domain_range_ids(CompIds,DomainIds,[RangeId]),
299 get_texpr_ids(CompIds,UnsortedIds), sort(UnsortedIds,Blacklist),
300 conjunction_to_list(CompPred,Preds),
301 select_equality(TId,Preds,Blacklist,Expr,Rest,_UsedIds,check_well_definedness),
302 same_id(TId,RangeId,_),
303 !,
304 LetIds = [RangeId], Exprs = [Expr],
305 conjunct_predicates(Rest,RestPred),
306 get_texpr_info(SETC,CInfo),
307 NewExpr = b(comprehension_set(DomainIds,RestPred),Type,CInfo),
308 print('Translated dom({...,x|x=E&...}) into: '), print_bexpr(b(let_expression(LetIds,Exprs,NewExpr),Type,[])),nl.
309 */
310 % exchange quantified union by generalized union
311 cleanup_pre(QUANT,Type,I,
312 let_expression(LetIds,Exprs,NewExpr),Type,[generated(QuantOP)|I],multi/quant_union_inter_let) :-
313 get_preference(optimize_ast,true),
314 quantified_set_operator(QUANT,QuantOP,AllIds,Pred,Expr),
315 conjunction_to_nontyping_list(Pred,Preds),
316 % The ids are needed to build a "black list"
317 get_sorted_ids(AllIds,Ids),
318 find_one_point_rules(AllIds,Preds,Ids,LetIds,Exprs,RestIds,NewPreds),
319 % only succeed if we found at least one id which can be rewritten as let
320 LetIds = [_ID1|_],
321 !,
322 (RestIds=[],NewPreds=[] -> NewExpr=Expr
323 % UNION(x).(x=E|Expr) --> LET x BE x=E in Expr END
324 ; RestIds = [] -> conjunct_predicates_with_pos_info(NewPreds,NewPred),
325 % UNION(x).(x=E & NewPred|Expr) --> LET x BE x=E in IF NewPRED THEN Expr ELSE {} END END
326 NewExpr = b(if_then_else(NewPred,Expr,b(empty_set,Type,[])),Type,I)
327 ; conjunct_predicates_with_pos_info(NewPreds,NewPred),
328 quantified_set_operator(NewQUANT,QuantOP,RestIds,NewPred,Expr),
329 NewExpr = b(NewQUANT,Type,I)
330 ),
331 (debug_mode(off) -> true
332 ; print('Translated UNION/INTER into: '), print_bexpr(b(let_expression(LetIds,Exprs,NewExpr),Type,[])),nl).
333 cleanup_pre(quantified_union(Ids,Pred,Expr),Type,I,DomCOMPSET,Type,I,multi/quant_union_into_comprehension) :-
334 singleton_set_extension(Expr,CoupleExpr),
335 nested_couple_to_list(CoupleExpr,List), % we have UNION(..).(...| { A |-> B }) --> List = [A,B]
336 match_ids(List,Ids,AllIds,RestIds),
337 (RestIds = []
338 -> true % UNION(x,y).(x:INTEGER & y=x+1|{x|->y}) --> {x,y| x:INTEGER & y=x+1} = %x.(...).
339 ; % UNION(y,x,z).(x:INTEGER & y=x+1|{x|->y}) --> dom({x,y,z| x:INTEGER & y=x+1})
340 % used to fail test 1101; check on List relevant for test 2359
341 List = [_,_|_] % at least two ids, otherwise use quant_union translation below: ran( %(Ids).(Pred|One) )
342 ),
343 COMPSET = comprehension_set(AllIds,Pred),
344 generate_dom_for_ids(RestIds,COMPSET,Type,I,TDomCOMPSET), % add one dom(.) construct per ID that is projected away
345 (debug_mode(off) -> true
346 ; print('Translated UNION over identifier couples into: '), print_bexpr(TDomCOMPSET),nl),
347 % check_ast(TDomCOMPSET), will complain about redundant typing as we are still in pre phase
348 TDomCOMPSET = b(DomCOMPSET,Type,_).
349 cleanup_pre(quantified_union(Ids,Pred,Expr),Type,I,Res,Type,[was(quantified_union)|I],multi/quant_union_symbolic) :-
350 memberchk(prob_annotation('SYMBOLIC'),I),
351 % UNION(Ids).(Pred|Expr) --> {u| #Ids.(Pred & u:Expr)}
352 get_texpr_set_type(Expr,IdType),
353 !,
354 get_unique_id_inside('__UNION__',Pred,Expr,FRESHID),
355 NewTID = b(identifier(FRESHID),IdType,[]),
356 safe_create_texpr(member(NewTID,Expr),pred,Member),
357 create_exists_opt(Ids,[Pred,Member],Exists),
358 Res = comprehension_set([NewTID],Exists),
359 (debug_mode(off) -> true ; print('UNION @symbolic: '), print_bexpr(b(Res,Type,I)),nl).
360 % exchange quantified union by generalized union
361 cleanup_pre(quantified_union(Ids,Pred,Expr),Type,I,Res,Type,I,multi/quant_union) :-
362 !,
363 ((get_preference(convert_comprehension_sets_into_closures,false), % for test 1101: UNION is a form of let and forces computation at the moment; translating it into a construct without union means that it may be kept symbolic
364 singleton_set_extension(Expr,One) %, debug:bisect(Expr,[1,1,1,1,1,1,1])) % [1,1,1,1,1,1,1] slow; 1,1,0 1,1,1,0 fast
365 )
366 % UNION(Ids).(Pred|{One}) --> ran( %(Ids).(Pred|One) )
367 -> quantified_set_op(Ids,Pred,One,quantified_union,I,TRes),
368 get_texpr_expr(TRes,Res),
369 (debug_mode(off) -> true ; print('UNION - SINGLETON: '), print_bexpr(TRes),nl)
370 ;
371 % UNION(Ids).(Pred|Expr) --> union( ran( %(Ids).(Pred|Expr) ) )
372 quantified_set_op(Ids,Pred,Expr,quantified_union,I,Set),
373 Res = general_union(Set)
374 ).
375 %alternate encoding:
376 %cleanup_pre(quantified_union(Ids,Pred,Expr),Type,I,Set,Type,I,multi/quant_union) :-
377 %poses problem to test 614, 1101
378 % !,quantified_union_op(Ids,Pred,Expr,Type,Set).
379 % exchange quantified intersection by generalized intersection
380 cleanup_pre(quantified_intersection(Ids,Pred,Expr),Type,I,general_intersection(Set),Type,I,multi/quant_inter) :-
381 !,quantified_set_op(Ids,Pred,Expr,quantified_intersection,I,Set).
382 cleanup_pre(function(FUN,Argument),Type,I,Result,Type,I2,RULE) :-
383 ? cleanup_pre_function(FUN,Argument,Type,I,Result,I2,RULE).
384 cleanup_pre(first_projection(A,B),Type,I,Set,Type,[was(prj1),prob_annotation('SYMBOLIC')|I],multi/first_projection) :-
385 !,create_projection_set(A,B,first,Set).
386 cleanup_pre(second_projection(A,B),Type,I,Set,Type,[was(prj2),prob_annotation('SYMBOLIC')|I],multi/second_projection) :-
387 !,create_projection_set(A,B,second,Set).
388 cleanup_pre(event_b_first_projection(Rel),Type,I,Set,Type,[prob_annotation('SYMBOLIC')|I],multi/ev_first_projection) :-
389 !,create_event_b_projection_set(Rel,first,Set).
390 cleanup_pre(event_b_second_projection(Rel),Type,I,Set,Type,[prob_annotation('SYMBOLIC')|I],multi/ev_second_projection) :-
391 !,create_event_b_projection_set(Rel,second,Set).
392 cleanup_pre(event_b_first_projection_v2,Type,I,Set,Type,[prob_annotation('SYMBOLIC')|I],multi/ev2_first_projection) :-
393 !,create_event_b_projection_set_v2(Type,first,Set).
394 cleanup_pre(event_b_second_projection_v2,Type,I,Set,Type,[prob_annotation('SYMBOLIC')|I],multi/ev2_second_projection) :-
395 !,create_event_b_projection_set_v2(Type,second,Set).
396 cleanup_pre(image(Fun,SONE),T,I,Res,T,I,multi/succ_pred_image_optimisation) :-
397 singleton_set_extension(SONE,One), % succ[{h}] --> {h+1} and pred[{h}] --> {h-1} ; useful for alloy2b
398 precompute_pred_succ_function_call(Fun,One,FunOneRes),
399 !,
400 Res = set_extension([b(FunOneRes,integer,I)]).
401 cleanup_pre(union(Lambda1,Lambda2),T,I,lambda(TIDs1,TPred,TVal),T,I,multi/combine_lambdas_if_then_else) :-
402 Lambda1 = b(lambda(TIDs1,TPred1,TValue1),_,_), get_texpr_ids(TIDs1,Ids),
403 Lambda2 = b(lambda(TIDs2,TPred2,TValue2),_,_), get_texpr_ids(TIDs2,Ids),
404 % %x.(P & Cond1 | Val1) \/ %x.(P & not(Cond1) | Val2) ==> %x.(P| IF Cond1 THEN Val1 ELSE Val2 END)
405 conjunction_to_list(TPred1,L1),
406 conjunction_to_list(TPred2,L2),
407 append(Front1,[Last1],L1),
408 append(Front2,[Last2],L2),
409 maplist(same_texpr,Front1,Front2),
410 is_negation_of(Last1,Last2),
411 conjunct_predicates_with_pos_info(Front1,TPred),
412 get_texpr_type(TValue1,TV),
413 safe_create_texpr(if_then_else(Last1,TValue1,TValue2),TV,[],TVal),
414 (debug_mode(off) -> true
415 ; format('Union of lambdas converted to if-then-else: ',[]),
416 translate:print_bexpr(b(lambda(TIDs1,TPred,TVal),T,I)),nl
417 ).
418 cleanup_pre(event_b_comprehension_set(Ids,Expr,Pred),T,I,NewExpression,T,
419 [was(event_b_comprehension_set)|I],multi/ev_compset) :-
420 rewrite_event_b_comprehension_set(Ids,Expr,Pred, T, NewExpression).
421 cleanup_pre(domain_restriction(A,B),T,I,identity(A),T,I,multi/event_b_to_normal_identity1) :-
422 /* translate S <| id into id(S) */
423 is_event_b_identity(B).
424 cleanup_pre(range_restriction(B,A),T,I,identity(A),T,I,multi/event_b_to_normal_identity2) :-
425 /* translate id |> S into id(S) */
426 is_event_b_identity(B).
427 % what about translating id(TOTAL TYPE) into event_b_identity ??
428 cleanup_pre(ring(A,B),T,I,composition(B,A),T,I,multi/ring_composition). % replace backward composition by forward compositoin
429 cleanup_pre(less_equal(A,B),pred,I,less_equal_real(A,B),pred,I,multi/remove_ambiguous_leq_real) :-
430 get_texpr_type(A,real).
431 cleanup_pre(greater_equal(A,B),pred,I,less_equal_real(B,A),pred,I,multi/remove_ambiguous_geq_real) :-
432 get_texpr_type(A,real).
433 cleanup_pre(less(A,B),pred,I,less_real(A,B),pred,I,multi/remove_ambiguous_lt_real) :-
434 get_texpr_type(A,real).
435 cleanup_pre(greater(A,B),pred,I,less_real(B,A),pred,I,multi/remove_ambiguous_gt_real) :-
436 get_texpr_type(A,real).
437 cleanup_pre(unary_minus(A),real,I,unary_minus_real(A),real,I,multi/remove_ambiguous_unary_minus_real).
438 cleanup_pre(power_of(A,B),real,I,power_of_real(A,TB),real,I,multi/remove_ambiguous_unary_minus_real) :-
439 get_texpr_type(A,real),
440 safe_create_texpr(convert_real(B),real,[],TB). % TO DO: add pos
441 cleanup_pre(max(A),real,I,max_real(A),real,I,multi/remove_ambiguous_unary_max_real).
442 cleanup_pre(min(A),real,I,min_real(A),real,I,multi/remove_ambiguous_unary_min_real).
443 cleanup_pre(add(A,B),real,I,add_real(A,B),real,I,multi/remove_ambiguous_add_real).
444 cleanup_pre(div(A,B),real,I,div_real(A,B),real,I,multi/remove_ambiguous_div_real).
445 cleanup_pre(minus_or_set_subtract(A,B),integer,I,minus(A,B),integer,I,multi/remove_ambiguous_minus_int).
446 cleanup_pre(minus_or_set_subtract(A,B),real,I,minus_real(A,B),real,I,multi/remove_ambiguous_minus_real).
447 cleanup_pre(minus_or_set_subtract(A,B),Type,I,set_subtraction(A,B),Type,I,multi/remove_abiguous_minus_set) :-
448 is_set_type(Type,_).
449 cleanup_pre(mult_or_cart(A,B),integer,I,multiplication(A,B),integer,I,multi/remove_ambiguous_times_int).
450 cleanup_pre(mult_or_cart(A,B),real,I,multiplication_real(A,B),real,I,multi/remove_ambiguous_times_real).
451 cleanup_pre(mult_or_cart(A,B),Type,I,cartesian_product(A,B),Type,I,multi/remove_ambiguous_times_set) :-
452 is_set_type(Type,_).
453 cleanup_pre(E,T,Iin,E,T,Iout,multi/remove_rodinpos) :- % we use multi but can per construction only be applied once
454 selectchk(nodeid(rodinpos(_,[],_)),Iin,Iout). % remove rodinpos information with Name=[]
455 cleanup_pre(partition(X,[Set]),pred,I,equal(X,Set),pred,I,multi/remove_partition_one_element) :-
456 !,
457 % partition(X,Set) <=> X=Set
458 (debug_mode(off) -> true ;
459 print('Introducing equality for partition: '),
460 print_bexpr(X), print(' = '), print_bexpr(Set),nl).
461 cleanup_pre(case(Expression,CASES,Else),subst,I,NewSubst,subst,I,single/rewrite_case_to_if_then_else) :-
462 % translate CASE E OF EITHER e1 THEN ... ---> LET case_expr BE case_expr=E IN IF case_expr=e1 THEN ...
463 get_texpr_type(Expression,EType), get_texpr_info(Expression,EInfo),
464 ExprID = b(identifier(EID),EType,EInfo),
465 (get_texpr_id(Expression,EID)
466 -> NewSubst = if(IFLISTE) % no LET necessary
467 ; NewSubst = let([ExprID],Equal,b(if(IFLISTE),subst,I)),
468 get_unique_id_inside('case_expr',b(case(Expression,CASES,Else),subst,I),EID),
469 safe_create_texpr(equal(ExprID,Expression),pred,Equal)
470 ),
471 (maplist(gen_if_elsif(ExprID),CASES,IFLIST)
472 -> (get_texpr_expr(Else,skip) -> IFLISTE = IFLIST
473 ; TRUTH = b(truth,pred,[]), get_texpr_info(Else,EI),
474 append(IFLIST,[b(if_elsif(TRUTH,Else),subst,EI)],IFLISTE)
475 ),
476 (debug_mode(off) -> true
477 ; print('Translating CASE to IF-THEN-ELSE: '), print_bexpr(Expression),nl
478 %,translate:print_subst(b(NewSubst,subst,[])),nl
479 )
480 ; add_internal_error('Translation of CASE to IF-THEN-ELSE failed: ',CASES),fail
481 ).
482 cleanup_pre(exists(AllIds,Body),pred,I0,NewP1,pred,NewI,single/components_partition_exists) :-
483 get_preference(optimize_ast,true),
484 nonmember(partitioned_exists,I0), % avoid re-computing components on something that is already partitioned
485 Simplify=no_cleanup_and_simplify, % avoid loops
486 % Warning: the next call may make use of existing used_ids infos; if they are wrong we may have a problem!
487 b_interpreter_components:construct_optimized_exists(AllIds,Body,NewPred,Simplify,NrC),
488 (NrC = 1 % just one component; perform no change to avoid re-ordering ids, ... ; see test 510
489 -> NewP1=exists(AllIds,Body), NewI=I0
490 ; get_texpr_ids(AllIds,Ids), sort(Ids,SortedIds),
491 add_important_infos_to_exists_conjuncts(NewPred,I0,SortedIds, b(NewP1,pred,NewI)),
492 % important e.g. for test 1945; in particular allow_to_lift_exists
493 % Note: construct_optimized_exists can lift unrelated inner exists out (/ClearSy/2023/perf_0704/rule_genz.mch)
494 (debug_mode(on), NewP1 \= exists(_,_)
495 -> format('PARTITIONED EXISTS:~n ',[]), translate:nested_print_bexpr(b(NewP1,pred,NewI)),nl ; true)
496 ).
497 cleanup_pre(exists(AllIds,P),pred,I,NewP1,pred,I,single/factor_out) :- % REDUNDANT with rule above ??
498 conjunction_to_nontyping_list(P,Preds),
499 % move things which do not depend on AllIds outside
500 % transform, e.g., #(x).(y>2 & x=y) --> y>2 & #(x).(x=y)
501 get_preference(optimize_ast,true),
502 create_exists_opt(AllIds,Preds,b(NewP1,pred,_I),Modified),
503 %(Modified = true -> print(exists(AllIds)),nl,print_bexpr(b(NewP1,pred,_I)),nl),
504 % the rule will fire again on the newly generated sub predicate ! -> fix ?
505 Modified=true.% check if anything modified; otherwise don't fire rule
506
507 cleanup_pre(exists(AllIds,P),pred,Info0,NewP,pred,INew,multi/remove_single_use_equality) :-
508 % remove existentially quantified variables which are defined by an equation and are used only once
509 % e.g., Z1...Z4 in not(#(X,Y,Z,Z1,Z2,Z3,Z4).(X:INTEGER & X*Y=Z1 & Z1*Z = Z2 & Z*X = Z3 & Z3*Y = Z4 & Z2 /= Z4))
510 get_preference(optimize_ast,true),
511 (length_less(AllIds,100) -> true % otherwise the code becomes quite inefficient at the moment
512 ; perfmessage('Large existential quantifier, performing limited optimizations',Info0),
513 fail),
514 conjunction_to_list(P,Preds),
515 CheckWellDef=no_check,
516 ? select_equality(TId,Preds,[],_,IDEXPR,RestPreds,_,CheckWellDef),
517 get_texpr_id(TId,ID),
518 ? select(TIdE,AllIds,RestIds), get_texpr_id(TIdE,ID),
519 can_be_optimized_away(TIdE),
520 \+ occurs_in_expr(ID,IDEXPR), % we cannot inline #x.(x=y+x & ...)
521 always_defined_full_check_or_disprover_mode(IDEXPR), % otherwise we may remove WD issue by removing ID if Count=0 or move earlier/later if count=1
522 single_usage_identifier(ID,RestPreds,Count), % we could also remove if Expr is simple
523 (Count=0 -> debug_println(19,unused_equality_id(ID)),
524 PL=RestPreds
525 ; % Count should be 1
526 conjunct_predicates_with_pos_info(RestPreds,RestPred),
527 replace_id_by_expr(RestPred,ID,IDEXPR,E2),
528 conjunction_to_list(E2,PL)
529 ),
530 create_exists_opt(RestIds,PL,TNewP), % no need to computed used ids yet; we could do this:
531 %conjunct_predicates_with_pos_info(PL,PP), safe_create_texpr(exists(RestIds,PP),pred,TNewP),
532 (debug_mode(off) -> true
533 ; format('Remove existentially quantified identifier with single usage: ~w (count: ~w)~n',[ID,Count]), print_bexpr(IDEXPR),nl),
534 TNewP = b(NewP,pred,INew),!.
535 cleanup_pre(exists(AllIds,P),pred,I,let_predicate(LetIds,Exprs,NewP),pred,INew,multi/exists_to_let) :-
536 % rewrite predicates of the form #x.(x=E & P(x)) into (LET x==E IN P(x))
537 % side condition for #(ids).(id=E & P(ids)): no identifiers of ids occur in E
538 get_preference(optimize_ast,true),
539 conjunction_to_nontyping_list(P,Preds), % TO DO: avoid recomputing again (see line in clause above)
540 % The ids are needed to build a "black list"
541 get_sorted_ids(AllIds,Ids),
542 find_one_point_rules(AllIds,Preds,Ids,LetIds,Exprs,RestIds,NewPreds),
543 % no_check is not ok in the context of existential quantification and reification:
544 % #x.(1:dom(f) & x=f(1) & P) --> LET x=f(1) IN 1:dom(f) & P END
545 % it is not ok if the whole predicate gets reified in b_intepreter_check !! Hence we use always_defined_full_check_or_disprover_mode; see Well_def_1.9.0_b5 in private_examples
546 % only succeed if we found at least one id which can be rewritten as let
547 LetIds = [ID1|_],
548 !,
549 (atomic(ID1) -> add_internal_error(cleanup_pre,unwrapped_let_identifier(ID1)), INew=I
550 ; get_texpr_ids(LetIds,AtomicIDs),
551 remove_used_ids_from_info(AtomicIDs,I,INew)
552 ), % probably not necessary ?!
553 % see also the annotate_toplevel_exists rule above which adds allow_to_lift_exists; relevant, e.g., for test 1945
554 (member(allow_to_lift_exists,I) -> AddInfos=[allow_to_lift_exists] ; AddInfos=[]),
555 create_exists_opt(RestIds,NewPreds,AddInfos,NewP,_Modified),
556 (debug_mode(off) -> true
557 ; format('Extracted LET over ~w from exists (rest: ~w):~n ',[AtomicIDs,RestIds]),
558 translate:print_bexpr(b(let_predicate(LetIds,Exprs,NewP),pred,I)),nl
559 ).
560 % now the same LET extraction but for universal quantification:
561 cleanup_pre(forall(AllIds,P,Rhs),pred,I,let_predicate(LetIds,Exprs,NewP),pred,I,multi/forall_to_let) :-
562 get_preference(optimize_ast,true),
563 conjunction_to_nontyping_list(P,Preds),
564 % The ids are needed to build a "black list"
565 get_sorted_ids(AllIds,Ids),
566 check_forall_lhs_rhs(P,Rhs,I,Ids),
567 find_one_point_rules(AllIds,Preds,Ids,LetIds,Exprs,RestIds,NewPreds),
568 % only succeed if we found at least one id which can be rewritten as let
569 LetIds = [ID1|_],!,
570 (atomic(ID1) -> add_internal_error(cleanup_pre,unwrapped_let_identifier(ID1)) ; true),
571 conjunct_predicates_with_pos_info(NewPreds,NewLhs),
572 create_implication(NewLhs,Rhs,NewForallBody),
573 create_forall(RestIds,NewForallBody,NewP),
574 (debug_mode(on) -> print('Introduced let in forall: '), print(LetIds),nl ; true).
575 % warning: used_identifier information not yet computed; translate may generate warnings
576 cleanup_pre(exists(AllIds,P),pred,I0,NewPE,pred,NewI,multi/exists_remove_typing) :-
577 (is_a_conjunct(P,Typing,Q) ; is_an_implication(P,Typing,Q)),
578 % TRUE & Q == TRUE => Q == Q
579 is_typing_predicate(Typing),
580 % remove typing so that other exists rules can fire
581 % we run as cleanup_pre: the other simplifications which remove typing have not run yet
582 % such typing conjuncts typicially come from Rodin translations
583 create_exists_opt(AllIds,[Q],b(NewPE,_,I1)),
584 add_important_info_from_super_expression(I0,I1,I2), % we could also copy node_id(_) from I0 ?
585 add_removed_typing_info(I2,NewI).
586 cleanup_pre(exists(AllIds,P),pred,I,disjunct(NewP1,NewP2),pred,I,single/partition_exists_implication) :-
587 is_a_disjunct_or_implication(P,_Type,Q,R),
588 /* note that even if R is only well-defined in case Q is false; it is ok to seperate this out
589 into two existential quantifiers: #x.(x=0 or 1/x=10) is ok to transform into #x.(x=0) or #x.(1/x=10) */
590 % this slows down test 1452, Cylinders, 'inv3/WD'; TO DO:investigate
591 create_exists_opt(AllIds,[Q],NewP1), % print('Q: '),print_bexpr(NewP1),nl,
592 create_exists_opt(AllIds,[R],NewP2). %, print('R: '),print_bexpr(NewP2),nl.
593 cleanup_pre(exists([B],P),pred,I,truth,pred,I,single/tautology_exists_min_max) :-
594 % ∃b·∀x0·(x0 ∈ FINITE ⇒ b ≤ x0) == TRUE : WD condition from Rodin for max; similar for min (TODO: check min)
595 B = b(identifier(ID1),integer,_),
596 get_texpr_expr(P,forall([X0],Left,Right)),
597 X0 = b(identifier(ID2),integer,_),
598 get_texpr_expr(Left,member(X1,FiniteSet)),
599 get_texpr_id(X1,ID2),
600 Right = b(COMP,pred,_),
601 (COMP = less_equal(B2,X2) ; COMP = greater_equal(B2,X2)),
602 get_texpr_id(B2,ID1), get_texpr_id(X2,ID2),
603 definitely_finite(FiniteSet),
604 (debug_mode(off) -> true ; format('Removing WD condition for min/max exists over ~w :',[ID1]), translate:print_bexpr(P),nl).
605 cleanup_pre(forall(AllIds,P,Rhs),pred,I,NewPred,pred,I,multi/forall_to_post_let) :-
606 % translate something like !(x,y).(y:1..100 & x=y*y => x<=y) into !(y).(y : 1 .. 100 => (#(x).( (x)=(y * y) & x <= y)))
607 post_let_forall(AllIds,P,Rhs,NewPred,modification),
608 !,
609 (debug_mode(on) -> print('POST LET INTRODUCTION: '), print_bexpr(b(NewPred,pred,[])),nl ; true).
610 cleanup_pre(set_extension(List),Type,I, Res,Type,I, single/eval_set_extension) :-
611 extension_should_be_evaluated(List), % partially redundant wrt read_raw_simple_values in btypechecker !
612 % TODO: move to cleanup_pre_with_path and path scope info to evaluate_set_extension
613 !,
614 (evaluate_set_extension(List,EvaluatedList),
615 convert_to_avl(EvaluatedList,AVL)
616 % evaluate simple explicit set extensions: avoid storing & traversing position info & AST
617 -> (debug_mode(on) -> print('EVAL SET EXTENSION: '), translate:print_bvalue(AVL),nl ; true),
618 Res=value(AVL)
619 ; %add_message(eval_set_extension,'Could not pre-evaluate Set-Extension:',List,I),
620 Res=set_extension(List)). % just add eval_set_extension as fired
621 cleanup_pre(sequence_extension(List),Type,I, Res,Type,I, single/eval_seq_extension) :-
622 extension_should_be_evaluated(List),
623 !,
624 ( evaluate_seq_extension_to_avl(List,AVL)
625 % evaluate simple explicit set extensions: avoid storing & traversing position info & AST
626 -> (debug_mode(on) -> print('EVAL SEQUENCE EXTENSION: '), translate:print_bvalue(AVL),nl ; true),
627 Res=value(AVL)
628 ; Res=sequence_extension(List)). % just add eval_seq_extension as fired
629 cleanup_pre(set_extension(List),Type,I, set_extension(NList),Type,I, single/remove_pos) :-
630 remove_position_info_from_list(List,I,NList),!.
631 cleanup_pre(sequence_extension(List),Type,I, sequence_extension(NList),Type,I, single/remove_pos) :-
632 remove_position_info_from_list(List,I,NList),!.
633 cleanup_pre(if(List),Type,I, if(NList),Type,I, single/remove_if_elsif_pos) :-
634 % the pos info is not used for individual if_elsif entries; some models contain very large if-then-else constructs
635 maplist(remove_top_levelposition_info,List,NList),!.
636 %cleanup_pre(concat(A,B),string,I,Res,string,I,multi/concat_assoc_reorder) :-
637 % A = b(concat(A1,A2),string,I1),
638 % !, % reorder STRING concats for better efficiency, can only occur when allow_sequence_operators_on_strings is true
639 % % TO DO: extract information I2B from A2 and B
640 % Res = concat(A1,b(concat(A2,B),string,I2B)).
641 cleanup_pre(typeset,SType,I,Expr,SType,I,multi/remove_typeset) :- !,
642 % used, e.g., in test 1205 for recursive Event-B operator definition
643 ( ground(SType) ->
644 (is_set_type(SType,Type),
645 create_maximal_type_set(Type,b(MaxExpr,_,_)) -> Expr=MaxExpr
646 ; is_set_type(SType,Type) ->
647 add_error_and_fail(b_ast_cleanup,'Creating type expression for typeset failed: ',Type)
648 ;
649 add_error_and_fail(b_ast_cleanup,'Creating type expression for typeset failed, type is not a set: ',SType)
650 )
651 ; add_error_and_fail(b_ast_cleanup,'Non-ground type for typeset expression: ',SType)).
652 cleanup_pre(integer_set(S),Type,I,Expr,Type,[was(integer_set(S))|I],multi/remove_integer_set) :- !,
653 translate_integer_set(S,I,Expr),
654 (debug_mode(off) -> true
655 ; format('Rewrite ~w to: ',[S]),
656 print_bexpr(b(Expr,integer,I)),nl).
657 % should we move the rewrite_rules to normalize ??
658 cleanup_pre(Expr,Type,Info,NewExpr,NewType,NewInfo, multi/apply_rewrite_rule(Rule)) :-
659 rewrite_rule_with_rename(Expr,Type,Info,NewExpr,NewType,NewInfo,Rule), % from b_ast_cleanup_rewrite_rules
660 (debug_mode(off) -> true
661 ; format('Use rewrite_rule ~w~n',[Rule]),
662 print_bexpr(b(NewExpr,NewType,NewInfo)),nl),
663 (ground(NewExpr) -> true ; print(not_ground_rewrite(NewExpr)),nl,fail).
664 % 'x > y' to 'y < x'
665 cleanup_pre(greater(Lhs,Rhs), pred, I, less(Rhs,Lhs), pred, [was(greater(Lhs,Rhs))|I], single/normalize_greater) :-
666 preferences:get_preference(normalize_ast, true).
667 % 'x >= y' to 'y <= x'
668 cleanup_pre(greater_equal(Lhs,Rhs), pred, I, less_equal(Rhs,Lhs), pred, [was(greater_equal(Lhs,Rhs))|I], single/normalize_greater_equal) :-
669 preferences:get_preference(normalize_ast, true).
670 % 'x - y' to 'x + -y'
671 cleanup_pre(minus(Lhs,Rhs), integer, I, add(Lhs,b(unary_minus(Rhs),integer,[])), integer, [was(minus(Lhs,Rhs))|I], single/normalize_minus) :-
672 preferences:get_preference(normalize_ast, true).
673 cleanup_pre(value(CLOSURE), Type, I, comprehension_set(TIDs,B), Type, I, single/normalize_value_closure) :-
674 nonvar(CLOSURE), CLOSURE=closure(P,T,B),
675 preferences:get_preference(normalize_ast, true),
676 maplist(create_typed_id,P,T,TIDs).
677 cleanup_pre(comprehension_set(TIDs,Body), Type, I, union(Set1,Set2), Type,I, single/extract_union) :-
678 preferences:get_preference(normalize_ast, true),
679 is_a_disjunct(Body,B1,B2), % should we also detect set difference, should we detect common prefix typing
680 % {x| P or Q} ==> {x|P} \/ {x|Q}
681 % such closure values are created by symbolic union, relevant for JSON trace replay for test 281
682 safe_create_texpr(comprehension_set(TIDs,B1),Type,I,Set1),
683 safe_create_texpr(comprehension_set(TIDs,B2),Type,I,Set2).
684 cleanup_pre(external_function_call('ASSERT_EXPR',[BOOL,MSG,EXPR]), Type, I,
685 assertion_expression(Pred,MsgStr,EXPR), Type,I, single/detect_assertion_expression) :-
686 % translate ASSERT_EXPR back to assertion_expression; dual to way it is printed in pretty printer
687 get_pred_from_bool(BOOL,Pred),
688 get_string(MSG,MsgStr).
689 cleanup_pre(external_pred_call(PRED,ARGS), pred, I,
690 EQ, pred,I, single/rewrite_external_pred_to_bool_function) :-
691 preferences:get_preference(normalize_ast,true),
692 synonym_for_external_predicate(PRED,FUNC),
693 % replace PRED(ARGS) by bool(FUNC(ARGS)=TRUE) as external functions can always be used wo DEFINITIONS
694 safe_create_texpr(external_function_call(FUNC,ARGS),boolean,[],FUNCALL),
695 EQ = equal(FUNCALL,b(boolean_true,boolean,[])),
696 (debug_mode(off) -> true ; print('REWRITTEN external predicate call to '), print_bexpr(FUNCALL),nl).
697
698
699 % Cleanup PRE for function calls:
700 % In reply to PROB-240: Check if arguments of Prj1/2 are types only using is_just_type:
701 cleanup_pre_function(TProjection,Argument,_Type,I,Result,I,multi/projection_call) :-
702 get_texpr_expr(TProjection,Projection),
703 cleanup_function_projection(Projection,Argument,I,Result),
704 !.
705 cleanup_pre_function(Lambda,Argument,Type,I,NewContextExpr,I,multi/lambda_guard1) :-
706 get_preference(optimize_ast,true),
707 get_texpr_expr(Lambda,LambdaExpr),
708 is_lambda_in_context(LambdaExpr,Type,TIds,TPre,TVal,NewContextExpr,NewExpr,LocalIds),
709 (is_just_typing_pred(TPre)
710 -> TPre1 = b(truth,pred,[]), % relevant for replace count below
711 get_texpr_expr(TVal,AssertionExpr)
712 ; TPre1=TPre,
713 AssertionExpr = assertion_expression(TPre1,ErrMsg,TVal)
714 ),
715 get_texpr_ids(TIds,Ids),
716 nested_couple_to_list(Argument,ArgList),
717 % translate %x.(TPre|TVal)(arg) -> LET x BE x=arg IN ASSERT_EXPR(TPre,Msg,TVal) END
718 same_length(ArgList,TIds),
719 \+ some_id_occurs_in_expr(LocalIds,Argument), % would trigger here LET x BE x=1+1 IN %y.(y:0..x|y+x+x) END (x) = res & x=0
720 ( same_ids_and_types(ArgList,TIds)
721 -> % lambda argument names and provided arguments are identical
722 NewExpr = AssertionExpr % no LET has to be introduced; relevant e.g. for rule_sgc335.mch
723 ; \+ ( sort(Ids,SIds),
724 some_id_occurs_in_expr(SIds,Argument)
725 %,format('Not inlining lambda, parameter id ~w occurs in : ',[Id]), print_bexpr(Argument),nl
726 %, add_message(ast_cleanup,'Not inlining parameter: ',Id,I)
727 ), % otherwise name clash and we would need a LET that can treat LET x BE x=x+1
728 TAssertionExpr = b(AssertionExpr,Type,I),
729 NewExpr = let_expression(TIds,ArgList,TAssertionExpr)
730 ; Ids = [Id1], ArgList = [Arg1] ->
731 %TODO: safely treat multiple args and things like (%(x,v).(x:INTEGER|x*v)(v|->v))=100
732 % In this case we need to substitute all args in one go
733 replace_id_by_expr_with_count(TPre1,Id1,Arg1,TPre2,Count1),
734 replace_id_by_expr_with_count(TVal,Id1,Arg1,TVal2,Count2),
735 Count is Count1+Count2,
736 is_replace_id_by_expr_ok(Arg1,Id1,Count,lambda_guard1),
737 NewExpr = assertion_expression(TPre2,ErrMsg,TVal2)
738 ),
739 % simplify_let will remove simple let expressions and vars used only once
740 % we used to call replace_ids_by_args in all cases, but this can duplicate arguments
741 % not replacing did lead to test 1284 taking very long, 191 seconds instead of 0.3 for 192 states
742 !,
743 ajoin_with_sep(Ids,',',IdsAtom),
744 get_texpr_info(Lambda,LambdaInfo), translate_span(LambdaInfo,LSpan),
745 (get_definition_context_from_span(LambdaInfo,LSpan2)
746 -> ajoin(['lambda function %(',IdsAtom,') ',LSpan,' (', LSpan2,
747 ') called outside of domain, condition false: '],ErrMsg)
748 ; ajoin(['lambda function %(',IdsAtom,') ',LSpan,
749 ' called outside of domain, condition false: '],ErrMsg)),
750 (debug_mode(off) -> true
751 ; add_message(ast_cleanup,'INLINED function application for: ',Ids,I),
752 translate:nested_print_bexpr(b(NewExpr,Type,I)),nl
753 ).
754 cleanup_pre_function(Fun,Arg,integer,I,ArithOp,I,multi/succ_pred_optimisation) :-
755 precompute_pred_succ_function_call(Fun,Arg,ArithOp).
756 /* cleanup_pre(event_b_comprehension_set([ID],ID,Pred),T,I,comprehension_set([Result],NewPred),T,
757 [was(event_b_comprehension_set)|I],multi/ev_compset_single_id) :-
758 % Event_B_Comprehension with a single ID which is also the expression
759 % TO DO: expand for multiple IDs
760 !,
761 Result = ID, NewPred=Pred. */
762 % Detect if_then_else; also done in cleanup_post (in pre we may be able to detect IF-THEN-ELSE before CSE has inserted lazy_lets
763 cleanup_pre_function(IFT,DUMMYARG,_Type,Info,if_then_else(IFPRED,THEN,ELSE),Info,multi/function_if_then_else) :-
764 is_if_then_else(IFT,pre,DUMMYARG,IFPRED,THEN,ELSE),
765 (debug_mode(off) -> true
766 ; print('% Recognised if-then-else expression (pre): IF '), print_bexpr(IFPRED),
767 print(' THEN '),print_bexpr(THEN), print(' ELSE '), print_bexpr(ELSE),nl
768 ).
769
770 % check if we detect a lambda or a lambda wrapped inside let_expressions
771 % e.g., LET one BE one=1 IN LET two BE two=2 IN %(x).(x:INTEGER|x+one+one+two+two)END END(y) = 7
772 % NewType: by moving the function application into the LETs the type of the LETs need to be adapted
773 is_lambda_in_context(let_expression(LetIds,Exprs,b(Lambda,_OldType,Info)),NewType,TIds,TPred,TValue,
774 let_expression(LetIds,Exprs,b(InnerCtxt,NewType,Info)),Hole,NewLocalIds) :- !,
775 is_lambda_in_context(Lambda,NewType,TIds,TPred,TValue,InnerCtxt,Hole,LocalIds),
776 get_texpr_ids(LetIds,Ids),
777 sort(Ids,SIds),
778 ord_union(SIds,LocalIds,NewLocalIds).
779 is_lambda_in_context(Lambda,_NewType,TIds,TPred,TValue,Context,ReplacementHole,[]) :-
780 Context=ReplacementHole,
781 is_lambda(Lambda, TIds, TPred,TValue).
782
783 :- use_module(closures,[is_lambda_closure/7, is_lambda_comprehension_set/4]).
784 is_lambda(lambda(TIds,TPred,TValue), TIds, TPred,TValue) :- !.
785 is_lambda(event_b_comprehension_set([TId],Expr,TPred), [TId], TPred, TValue) :- !,
786 % rewrite_event_b_comprehension_set does not seem to get called before the function/lambda rule is applied
787 % {ID.ID|->Val | PRed}
788 Expr = b(couple(LHS,RHS),_,_),
789 same_texpr(LHS,TId),
790 TValue=RHS.
791 is_lambda(value(Closure),[TId],TPred,TValue) :- !, nonvar(Closure), Closure = closure(Args,Types,Body),
792 is_lambda_closure(Args,Types,Body, [OtherID], [OtherType], TPred, TValue),
793 create_typed_id(OtherID,OtherType,TId). % TODO: accept lambdas with more than one argument TId
794 is_lambda(CompSet,TIds,Pred,Val) :- CompSet=comprehension_set(_,_),
795 is_lambda_comprehension_set(b(CompSet,any,[]),TIds,Pred,Val).
796 is_just_typing_pred(b(member(_,B),pred,_)) :- is_just_type(B). % would be removed by remove_type_member rule
797
798
799 :- use_module(external_function_declarations,[synonym_for_external_predicate/2]).
800
801 get_string(b(string(S),_,_),S).
802 get_string(b(value(V),_,_),S) :- nonvar(V), V=string(Str), atom(Str), S=Str.
803 % translate a boolean value into a predicate:
804 get_pred_from_bool(b(convert_bool(P),_,_),Pred) :- !, Pred=P.
805 get_pred_from_bool(BOOL,b(equal(BOOL,BTRUE),pred,[])) :- BTRUE = b(boolean_true,boolean,[]).
806
807 translate_integer_set('NAT',I,interval(b(integer(0),integer,I),b(max_int,integer,I))).
808 translate_integer_set('NAT1',I,interval(b(integer(1),integer,I),b(max_int,integer,I))).
809 translate_integer_set('INT',I,interval(b(min_int,integer,I),b(max_int,integer,I))).
810 %translate_integer_set('INTEGER',I,comprehension_set([b(identifier('_zzzz_unary'),integer,I)],
811 % b(truth,pred,[prob_annotation('SYMBOLIC')|I]))).
812 %translate_integer_set('NATURAL',I,comprehension_set([b(identifier('_zzzz_unary'),integer,I)],
813 % b(greater_equal(b(identifier('_zzzz_unary'),integer,I),
814 % b(integer(0),integer,I)),pred,[prob_annotation('SYMBOLIC')|I]))).
815 %translate_integer_set('NATURAL1',I,comprehension_set([b(identifier('_zzzz_unary'),integer,I)],
816 % b(greater_equal(b(identifier('_zzzz_unary'),integer,I),
817 % b(integer(1),integer,I)),pred,[prob_annotation('SYMBOLIC')|I]))).
818
819 % detect if an expression is equivalent to an integer set, does not check for interval yet
820 is_integer_set(integer_set(S),S).
821 is_integer_set(comprehension_set([b(identifier(ID),integer,_)],b(B,_,_)),S) :-
822 ? is_integer_set_constraint_pred(B,ID,S).
823 is_integer_set_constraint_pred(truth,_,'INTEGER').
824 is_integer_set_constraint_pred(Expr,ID,Set) :-
825 is_greater_equal(Expr,b(identifier(ID),integer,_),TNr),
826 get_integer(TNr,Nr),
827 (Nr=0 -> Set='NATURAL' ; Nr=1 -> Set='NATURAL1').
828 is_integer_set_constraint_pred(Expr,ID,Set) :-
829 is_greater(Expr,b(identifier(ID),integer,_),TNr),
830 get_integer(TNr,Nr),
831 (Nr = -1 -> Set='NATURAL' ; Nr=0 -> Set='NATURAL1').
832
833 is_greater_equal(greater_equal(A,B),A,B).
834 is_greater_equal(less_equal(B,A),A,B).
835 is_greater(greater(A,B),A,B).
836 is_greater(less(B,A),A,B).
837
838 is_inf_integer_set_with_lower_bound(b(X,_,_),Bound) :- is_integer_set(X,N),
839 (N='NATURAL' -> Bound=0 ; N='NATURAL1' -> Bound=1).
840
841
842
843 is_subset(subset(A,B),A,B).
844 is_subset(member(A,b(pow_subset(B),_,_)),A,B). % x : POW(T) <=> x <: T
845
846 % tool to translate CASE values to Test predicates for IF-THEN-ELSE
847 gen_if_elsif(CaseID,b(case_or(ListOfValues, Body),_,I),
848 b(if_elsif(Test,Body),subst,I)) :-
849 get_texpr_type(CaseID,T),
850 SEXT = b(set_extension(ListOfValues),set(T),I),
851 Test = b(member(CaseID,SEXT),pred,I).
852
853 % the case below happens frequently in data validation:
854 remove_position_info_from_list(List,I,NList) :-
855 member(nodeid(pos(C,FilePos,Line,From,Line,To)),I),
856 To-From > 1000, % the entire set/sequence extension is on one large line
857 length(List,Len), Len>100, % it has many elements
858 % we replace all position infos by the same top-level position info (enabling sharing)
859 maplist(remove_position_info(nodeid(pos(C,FilePos,Line,From,Line,To))),List,NList),
860 (debug_mode(off) -> true
861 ; format('SIMPLIFY POSITION INFO IN SET/SEQUENCE EXTENSION: line # ~w, length ~w~n',[Line,Len])).
862 remove_position_info(NI,b(Expr,Type,Infos),b(NExpr,Type,NewInfos)) :-
863 syntaxtransformation(Expr,Subs,_Names,NSubs,NExpr),
864 (select(nodeid(pos(_,_FilePos,_,_,_,_)),Infos,NT) -> NewInfos=[NI|NT] ; NewInfos=Infos),
865 maplist(remove_position_info(NI),Subs,NSubs).
866
867 :- use_module(bsyntaxtree,[delete_pos_info/2]).
868 % just remove position infos from top-lefel
869 remove_top_levelposition_info(b(Expr,Type,Infos),b(Expr,Type,NewInfos)) :-
870 delete_pos_info(Infos,NewInfos). % TODO: maybe remove other useless infos
871
872 % rules for function application of various projection functions
873 cleanup_function_projection(first_projection(A,B),Argument,I,Result) :-
874 gen_assertion_expression(A,B,Argument,first_of_pair(Argument),first,I,Result).
875 cleanup_function_projection(second_projection(A,B),Argument,I,Result) :-
876 gen_assertion_expression(A,B,Argument,second_of_pair(Argument),second,I,Result).
877 cleanup_function_projection(event_b_second_projection(A),Argument,_I,Result) :- % old style Rodin projection
878 check_is_just_type(A),Result = first_of_pair(Argument).
879 cleanup_function_projection(event_b_second_projection(A),Argument,_I,Result) :- % old style Rodin projection
880 check_is_just_type(A),Result = second_of_pair(Argument).
881 cleanup_function_projection(event_b_first_projection_v2,Argument,_I,Result) :- Result = first_of_pair(Argument).
882 cleanup_function_projection(event_b_second_projection_v2,Argument,_I,Result) :- Result = second_of_pair(Argument).
883
884 check_is_just_type(_A) :- preferences:get_preference(ignore_prj_types,true),!.
885 check_is_just_type(A) :- (is_just_type(A) -> true ; debug_println(9,not_type_for_prj(A)),fail).
886
887 :- use_module(bsyntaxtree,[get_texpr_set_type/2]).
888 gen_assertion_expression(A,B,_Argument,ProjExpr,_ProjType,_I,Result) :-
889 check_is_just_type(A),check_is_just_type(B),
890 !,
891 Result = ProjExpr.
892 % TO DO: add simplification rule for couple(x,y) : A*B with A or B being just types
893 gen_assertion_expression(A,B,Argument,ProjExpr,ProjType,Info,Result) :-
894 create_cartesian_product(A,B,CartAB),
895 safe_create_texpr(member(Argument,CartAB),pred,MemCheck),
896 ErrMsg = 'projection function called outside of domain: ', % TO DO: provide better user message with Argument result
897 (ProjType == first -> get_texpr_set_type(A,TT) ; get_texpr_set_type(B,TT)), %%
898 %get_texpr_pos_infos(Argument,Info), % add position infos
899 extract_pos_infos(Info,PosInfo),
900 safe_create_texpr(ProjExpr,TT,PosInfo,TProjExpr),
901 Result = assertion_expression(MemCheck,ErrMsg,TProjExpr).
902 :- use_module(bsyntaxtree,[is_set_type/2]).
903 create_cartesian_product(A,B,CartAB) :-
904 get_texpr_types([A,B],[STA,STB]),
905 is_set_type(STA,TypeA), is_set_type(STB,TypeB),
906 safe_create_texpr(cartesian_product(A,B),set(couple(TypeA,TypeB)),CartAB).
907
908
909 % rewriting Event-B comprehension sets into classical B style ones
910 rewrite_event_b_comprehension_set(IDs,CoupleExpr,Pred, _T, NewExpression) :-
911 % detect lambda expressions in classical B style
912 nested_couple_to_list(CoupleExpr,List),
913 check_ids(IDs,List,Expr),!,
914 NewExpression = lambda(IDs,Pred,Expr).
915 rewrite_event_b_comprehension_set(IDList,CoupleExpr,Pred, _T, NewExpression) :-
916 % Event_B_Comprehension with a several IDs which are also used as the couple expression
917 nested_couple_to_list(CoupleExpr,List),
918 List = IDList,
919 !,
920 NewExpression = comprehension_set(IDList,Pred).
921 rewrite_event_b_comprehension_set(Ids,Expr,Pred, T, NewExpression) :-
922 NewExpression = comprehension_set([Result],NewPred),
923 unify_types_strict(T,set(Type)),
924 % print(event_b_comprehension_set(Ids,Expr,Pred)),nl,
925 (select(Expr,Ids,RestIds)
926 -> % the Expr is an identifier which is part of Ids: we can avoid complicated translation below
927 % example {f,n•n:INT & f:1..n-->Digit|f} --translated-> {f|#(n).(n:INT & f:1..n-->Digit)}
928 % print(remove(Expr,RestIds)),nl,
929 ExPred=Pred, Result=Expr
930 ; get_unique_id_inside('__comp_result__',Pred,Expr,ResultId),
931 create_texpr(identifier(ResultId),Type,[],Result),
932 safe_create_texpr(equal(Result,Expr),pred,Equal),
933 conjunct_predicates_with_pos_info(Pred,Equal,ExPred), % put Equal after Pred for WD; used to be other order!
934 RestIds=Ids
935 ),
936 create_exists(RestIds,ExPred,NewPred). %, print(done_rewrite_event_b_comprehension_set),nl, print_bexpr(NewPred),nl.
937
938 check_ids([],[CoupleExpr],CoupleExpr). % we terminate with a single expression
939 check_ids([ID|T],[CoupleExprID|CT],Rest) :-
940 same_id(ID,CoupleExprID,_),
941 check_ids(T,CT,Rest).
942
943
944 evaluate_seq_extension_to_avl(List,AVL) :-
945 evaluate_set_extension(List,EvaluatedList),
946 convert_set_to_seq(EvaluatedList,1,ESeq),
947 convert_to_avl(ESeq,AVL).
948
949 evaluate_set_extension([],[]).
950 evaluate_set_extension([H|List],[EH|EvaluatedList]) :-
951 eval_set_extension_element(H,EH),
952 evaluate_set_extension(List,EvaluatedList).
953
954 extension_should_be_evaluated(List) :-
955 %preferences:has_default_value(use_solver_on_load), % Kodkod could not translate booleans back; now it can; check if we still need this
956 preferences:get_preference(optimize_ast,true),
957 List \= [],
958 List = [_|ListT], ListT \= []. % do not do this for singleton sets so as not to prevent triggering of other rules
959
960 :- use_module(kernel_reals,[construct_real/2, construct_negative_real/2]).
961 % construct a value term for a simple AST element:
962 eval_set_extension_element(b(E,T,_I),EE) :-
963 (eval_set_extension_aux(E,EE) -> true
964 ; eval_set_extension_typed_aux(E,T,EE)
965 %; print('eval_set_extension failed: '),tools_printing:print_term_summary(E),nl,translate:print_span(_I),nl,fail
966 ).
967 eval_set_extension_aux(boolean_false,pred_false).
968 eval_set_extension_aux(boolean_true,pred_true).
969 eval_set_extension_aux(couple(A,B),(EA,EB)) :- eval_set_extension_element(A,EA), eval_set_extension_element(B,EB).
970 eval_set_extension_aux(integer(I),int(I)).
971 eval_set_extension_aux(real(Atom),Real) :- construct_real(Atom,Real).
972 eval_set_extension_aux(unary_minus(b(Val,_,_)),Res) :- eval_set_ext_minus(Val,Res).
973 eval_set_extension_aux(string(S),string(S)).
974 eval_set_extension_aux(empty_set,[]).
975 eval_set_extension_aux(empty_sequence,[]).
976 eval_set_extension_aux(value(V),V).
977 eval_set_extension_aux(rec(Fields),rec(EF)) :- eval_set_extension_fields(Fields,EF).
978 %eval_set_extension_aux(interval(A,B),...) :- ...
979 % to convert enumerated set elements identifier(_) we would need to know quantified identifiers in scope
980 eval_set_extension_aux(set_extension(List),AVL) :-
981 evaluate_set_extension(List,EvaluatedList),
982 convert_to_avl(EvaluatedList,AVL).
983 eval_set_extension_aux(sequence_extension(List),AVL) :-
984 evaluate_seq_extension_to_avl(List,AVL).
985
986 eval_set_extension_typed_aux(identifier(ID),global(Type),FDVal) :-
987 preferences:preference(optimize_enum_set_elems,true), %TODO: we need to pass scope info and get rid of this preference
988 b_global_sets:lookup_global_constant(ID,FDVal), % may not yet be fully precompiled, hence we rely on pre_register_enumerated_set_with_elems
989 FDVal = fd(_,Type). % just check that the type matches, in case ID is a local name with different type
990 %eval_set_extension_typed_aux(E,T,_) :- print(uncov(E,T)),nl,nl,fail.
991
992
993 eval_set_ext_minus(integer(I),int(R)) :- R is -I.
994 eval_set_ext_minus(real(Atom),Real) :- construct_negative_real(Atom,Real).
995
996 eval_set_extension_fields([],[]).
997 eval_set_extension_fields([field(Name,V)|T],[field(Name,EV)|ET]) :- eval_set_extension_element(V,EV),
998 eval_set_extension_fields(T,ET).
999
1000 convert_set_to_seq([],_,[]).
1001 convert_set_to_seq([H|T],N,[(int(N),H)|CT]) :- N1 is N+1, convert_set_to_seq(T,N1,CT).
1002
1003
1004 post_let_forall(AllIds,P,Rhs,NewPred,modification) :-
1005 conjunction_to_list(P,Preds), reverse(Preds,RPreds),
1006 ? select_equality(TId,RPreds,[],_,Expr,RRest,UsedIds,no_check),
1007 ? select(TId,AllIds,RestIds),
1008 get_texpr_id(TId,Id),
1009 \+ member(Id,UsedIds), % not a recursive equality
1010 reverse(RRest,Rest),
1011 conjunct_predicates_with_pos_info(Rest,RestPred),
1012 \+ occurs_in_expr(Id,RestPred),
1013 !,
1014 NewRhs = b(let_predicate([TId],[Expr],Rhs),pred,[]),
1015 post_let_forall(RestIds,RestPred,NewRhs,NewPred,_).
1016 post_let_forall(AllIds,P,Rhs,NewPred, no_modification) :-
1017 create_implication(P,Rhs,NewForallBody),
1018 create_forall(AllIds,NewForallBody,NewP),
1019 get_texpr_expr(NewP,NewPred).
1020
1021
1022 is_interval(b(interval(A,B),_,_),A,B).
1023 is_interval(b(value(V),set(_),_),A,B) :- nonvar(V), V=closure(P,T,B),
1024 custom_explicit_sets:is_interval_closure(P,T,B,LOW,UP), integer(LOW),integer(UP),
1025 A=b(integer(LOW),integer,[]),
1026 B=b(integer(UP),integer,[]).
1027
1028 % a more flexible version, also detecting singleton set extension
1029 ?is_interval_or_singleton(I,A,B) :- is_interval(I,A,B),!.
1030 is_interval_or_singleton(b(set_extension([A]),set(integer),_),A,A).
1031
1032
1033
1034 % create a lambda expression for a projection
1035 create_projection_set(A,B,_Switch,Res) :-
1036 (definitely_empty_set(A) ; definitely_empty_set(B)),!,
1037 Res = empty_set.
1038 create_projection_set(A,B,Switch,lambda(Ids,SPred,Expr)) :- % generate lambda to be able to use function(lambda) rule
1039 Ids = [TArg1,TArg2],
1040 ( Switch==first -> Expr = TArg1
1041 ; Switch==second -> Expr = TArg2),
1042 get_texpr_type(A,TA1), unify_types_strict(TA1,set(Type1)),
1043 get_texpr_type(B,TB2), unify_types_strict(TB2,set(Type2)),
1044 ? (contains_no_ids(A,B) -> Arg1 = '_zzzz_unary', Arg2 = '_zzzz_binary' % avoid generating fresh ids; relevant for test 1313 and ticket PROB-346
1045 % TO DO: check whether _zzzz_unary/binary are actually used; we should avoid generating fresh ids whenever possible (otherwise syntactically identical formulas become different)
1046 ; get_unique_id_inside('_prj_arg1__',A,B,Arg1),
1047 get_unique_id_inside('_prj_arg2__',A,B,Arg2)),
1048 create_texpr(identifier(Arg1),Type1,[generated(Switch)],TArg1),
1049 create_texpr(identifier(Arg2),Type2,[generated(Switch)],TArg2),
1050 safe_create_texpr(member(TArg1,A),pred,MembA),
1051 safe_create_texpr(member(TArg2,B),pred,MembB),
1052 conjunct_predicates([MembA,MembB],Pred), SPred=Pred.
1053 % bsyntaxtree:mark_bexpr_as_symbolic(Pred,SPred). % TO DO: put mark code into another module; maybe only mark as symbolic if types large enough ??
1054
1055 ?contains_no_ids(A,B) :- contains_no_ids(A), contains_no_ids(B).
1056 ?contains_no_ids(b(E,_,_)) :- contains_no_ids_aux(E).
1057 contains_no_ids_aux(bool_set).
1058 contains_no_ids_aux(X) :- is_integer_set(X,_). % comprehension set may contain ids, but not visible to outside
1059 contains_no_ids_aux(mult_or_cart(A,B)) :- contains_no_ids(A),contains_no_ids(B).
1060 contains_no_ids_aux(relations(A,B)) :- contains_no_ids(A),contains_no_ids(B).
1061 contains_no_ids_aux(pow_subset(A)) :- contains_no_ids(A).
1062 contains_no_ids_aux(pow1_subset(A)) :- contains_no_ids(A).
1063 contains_no_ids_aux(real_set).
1064 contains_no_ids_aux(string_set).
1065 contains_no_ids_aux(interval(A,B)) :- contains_no_ids(A),contains_no_ids(B).
1066 % TO DO: add more
1067
1068 create_event_b_projection_set(Rel,Switch,lambda(Ids,SPred,Expr)) :-
1069 Ids = [TArg1,TArg2],
1070 ( Switch==first -> Expr = TArg1
1071 ; Switch==second -> Expr = TArg2),
1072 get_texpr_type(Rel,RT),unify_types_strict(RT,set(couple(Type1,Type2))),
1073 get_unique_id_inside('_prj_arg1__',Rel,Arg1),
1074 get_unique_id_inside('_prj_arg2__',Rel,Arg2),
1075 create_texpr(identifier(Arg1),Type1,[generated(Switch)],TArg1),
1076 create_texpr(identifier(Arg2),Type2,[generated(Switch)],TArg2),
1077 create_texpr(couple(TArg1,TArg2),couple(Type1,Type2),[],Couple),
1078 safe_create_texpr(member(Couple,Rel),pred,Member),
1079 SPred=Member.
1080 %bsyntaxtree:mark_bexpr_as_symbolic(Pred,SPred).
1081
1082 create_event_b_projection_set_v2(RelType,Switch,comprehension_set(Ids,SPred)) :-
1083 % we are generating {p1,p2,lambda | lambda=p1/p2}
1084 Ids = [TArg1,TArg2,TArg3],
1085 ( Switch==first -> ResultExpr = TArg1, Type1 = Type3
1086 ; Switch==second -> ResultExpr = TArg2, Type2 = Type3),
1087 unify_types_strict(RelType,set(couple(couple(Type1,Type2),T3))),
1088 (T3==Type3 -> true ; add_error(create_event_b_projection_set,'Unexpected return type: ',T3)),
1089 Arg1 = '_zzzz_unary',
1090 Arg2 = '_zzzz_binary',
1091 Arg3 = '_lambda_result_', % the comprehension set contains no other expressions: no clash possible
1092 create_texpr(identifier(Arg1),Type1,[generated(Switch)],TArg1),
1093 create_texpr(identifier(Arg2),Type2,[generated(Switch)],TArg2),
1094 create_texpr(identifier(Arg3),Type3,[lambda_result(Arg3),generated(Switch)],TArg3),
1095 safe_create_texpr(equal(TArg3,ResultExpr),pred,[prob_annotation('LAMBDA-EQUALITY')],Equal),
1096 SPred=Equal.
1097 % bsyntaxtree:mark_bexpr_as_symbolic(Pred,SPred).
1098 %,print(Pred),nl.
1099
1100 :- use_module(btypechecker,[couplise_list/2,prime_identifiers/2,prime_identifiers0/2, prime_atom0/2]).
1101 % create a comprehension set for quantified union or intersection UNION(x).(P|E) = ran(%x.(P|E))
1102 % TO DO: translate UNION into UNION(x).(P|E) = dom({r,x|P & r:E}) = ran({x,r|P & r:E}) which is considerably faster
1103 % also works for e.g., UNION(x).(x:1..2|{x+y}) = 12..13
1104 %quantified_union_op(Ids,Pred,Expr,SetType,Res) :- is_set_type(SetType,Type),
1105 % !,
1106 % Info = [generated(quantified_union)],
1107 % get_unique_id_inside('_zzzz_unary',Pred,Expr,FRESHID), % also include Expr !
1108 % NewID = b(identifier(FRESHID),Type,[]), %fresh
1109 % append(Ids,[NewID],NewIds),
1110 % safe_create_texpr(member(NewID,Expr),pred,[],Member),
1111 % conjunct_predicates([Pred,Member],Body),
1112 % get_texpr_types(NewIds,Types),couplise_list(Types,TupleType),
1113 % safe_create_texpr(comprehension_set(NewIds,Body),set(TupleType),Info,ComprSet),
1114 % Res = range(ComprSet).
1115 % %safe_create_texpr(range(ComprSet),set(set(Type)),Info,Set), print_bexpr(Set),nl.
1116 %quantified_union_op(Ids,Pred,Expr,SetType,Set) :-
1117 % add_internal_error('Could not translate quantified UNION operator: ',quantified_union_op(Ids,Pred,Expr,SetType,Set)),
1118 % fail.
1119
1120 % create a comprehension set for quantified union or intersection INTER(x).(P|E) = inter(ran(%x.(P|E)))
1121 % UNION could be treated by quantified_union_op above
1122 quantified_set_op(Ids,Pred,Expr,Loc,OuterInfos,Set) :-
1123 create_range_lambda(Ids,Pred,Expr,Loc,OuterInfos,Set),
1124 !. % , print(quantified),nl,print_bexpr(Set),nl.
1125 quantified_set_op(Ids,Pred,Expr,Loc,OuterInfos,Set) :-
1126 add_internal_error('Could not translate quantified set operator: ',
1127 quantified_set_op(Ids,Pred,Expr,Loc,OuterInfos,Set)),
1128 fail.
1129
1130 create_range_lambda(Ids,Pred,Expr,Loc,OuterInfos,Set) :-
1131 Info = [generated(Loc)|OuterInfos],
1132 get_texpr_types(Ids,Types),couplise_list(Types,ArgType),
1133 get_texpr_type(Expr,ExprType),
1134 safe_create_texpr(lambda(Ids,Pred,Expr),set(couple(ArgType,ExprType)),Info,Lambda),
1135 safe_create_texpr(range(Lambda),set(ExprType),Info,Set).
1136
1137
1138 quantified_set_operator(quantified_union(AllIds,Pred,Expr),quantified_union,AllIds,Pred,Expr).
1139 quantified_set_operator(quantified_intersection(AllIds,Pred,Expr),quantified_intersection,AllIds,Pred,Expr).
1140
1141 % match_ids(List1,List2, AllIds,Rest) find all ids in List1 in List2; ids in List2 not in List1 are put in Rest
1142 match_ids([],List,List,List).
1143 ?match_ids([TID|T],List,[TID2|T2],Rest) :- select(TID2,List,L2),
1144 same_id(TID,TID2,_),!,
1145 match_ids(T,L2,T2,Rest).
1146
1147 % generate dom(.) operators for TypedIds which have to be projected away
1148 generate_dom_for_ids([],E,T,I,b(E,T,I)).
1149 generate_dom_for_ids([TID|Ts],E,T,I,Res) :- T = set(T1),
1150 get_texpr_type(TID,TIDType),
1151 generate_dom_for_ids(Ts,E,set(couple(T1,TIDType)),I,DE),
1152 safe_create_texpr(domain(DE),T,Res).
1153
1154 :- use_module(tools_strings,[ajoin/2,ajoin_with_sep/3]).
1155 % we ensure that this check is only done once, for user machines,... not for generated formulas
1156 check_forall_lhs_rhs(_,_,_,_) :- preferences:get_preference(perform_stricter_static_checks,false),!.
1157 check_forall_lhs_rhs(_,_,_,_) :- preferences:get_preference(disprover_mode,true),!.
1158 check_forall_lhs_rhs(_,_,_,_) :- animation_minor_mode(eventb),!. % typing predicates get removed it seems
1159 ?check_forall_lhs_rhs(_,_,I,_) :- member(removed_typing,I),!. % means that typing was possibly removed
1160 ?check_forall_lhs_rhs(Lhs,_,_,_) :- member_in_conjunction(PC,Lhs),
1161 ? get_texpr_info(PC,PI),member(II,PI),
1162 removed_typing(II),!. % it was something else; does not seem to detect all removed conjunctions, hence we also check I above
1163 check_forall_lhs_rhs(P,_,I,Ids) :- find_identifier_uses_if_necessary(P,[],LhsUsed),
1164 ord_subtract(Ids,LhsUsed,NotDefined),
1165 NotDefined=[_|_],
1166 ajoin_with_sep(NotDefined,',',S),
1167 translate:translate_bexpression(P,PS),
1168 ajoin(['Left-hand side "', PS, '" of forall does not define identifier(s): '],Msg),
1169 add_warning(bmachine_static_checks,Msg,S,I),
1170 fail.
1171 check_forall_lhs_rhs(_,Rhs,I,Ids) :-
1172 find_identifier_uses_if_necessary(Rhs,[],RhsUsed),
1173 (ord_intersect(Ids,RhsUsed) -> true
1174 ; ajoin_with_sep(Ids,',',S),
1175 add_warning(bmachine_static_checks,'Right-hand side of forall does not use identifiers: ',S,I)
1176 ).
1177 removed_typing(removed_typing). removed_typing(was(_)).
1178
1179 :- use_module(kernel_records,[normalise_record_type/2]).
1180 :- use_module(library(lists),[last/2]).
1181
1182 % first the rules that require the path:
1183 cleanup_post_with_path(assign([b(identifier(ID),TYPE,INFO)],[EXPR]),subst,I,
1184 assign_single_id(b(identifier(ID),TYPE,INFO),EXPR),subst,I,single/assign_single_id,Path) :-
1185 \+ animation_minor_mode(eventb), % there is no support in the Event-B interpreter for assign_single_id yet
1186 ? (simple_expression(EXPR) % the assign_single_id is not guarded by a waitflag; EXPR should not be too expensive too calculate
1187 -> true
1188 ; % if we are in an unguarded context; then we do not need to guard EXPR by waitflag anyway
1189 ? maplist(unguarded,Path)
1190 ),
1191 !,
1192 (debug_level_active_for(4) -> format('Single Assignment to ~w~n',[ID])
1193 %translate:print_subst(b(assign([b(identifier(ID),TYPE,INFO)],[EXPR]),subst,I)),nl
1194 ; true).
1195 cleanup_post_with_path(any(Ids,Pred,Subst),subst,Info,any(Ids,Pred,NewSubst),subst,NewInfo,multi/remove_useless_assign,_Path) :-
1196 get_preference(optimize_ast,true),
1197 member_in_conjunction(b(equal(TID1,TID2),pred,_),Pred),
1198 get_texpr_id(TID1,ID1),
1199 get_texpr_id(TID2,ID2), % we have an equality of the form x=x' (as generated by TLA2B)
1200 delete_assignment(Subst,TID3,TID4,NewSubst),
1201 get_texpr_id(TID4,ID4), get_texpr_id(TID3,ID3),
1202 ( c(ID1,ID2) = c(ID3,ID4) ; c(ID1,ID2) = c(ID4,ID3)), % we have an assignment x:=x' or x':=x
1203 % the cleanup rule recompute_accessed_vars below recomputes the info fields for enclosing operations! get_accessed_vars is currently called before ast_cleanup
1204 ajoin([ID3,' := ',ID4],Assign),
1205 add_hint_message(remove_useless_assign,'Removing useless assignment: ',Assign,Info),
1206 (member(removed_useless_assign,Info) -> NewInfo=Info ; NewInfo=[removed_useless_assign|Info]).
1207 cleanup_post_with_path(operation(TName,Res,Params,TBody),Type,Info,
1208 operation(TName,Res,Params,NewTBody),Type,NewInfos,single/recompute_accessed_vars,_Path) :-
1209 TBody=b(Body,subst,BInfos),
1210 select(removed_useless_assign,BInfos,NewBInfos),
1211 btypechecker:compute_accessed_vars_infos_for_operation(TName,Res,Params,TBody,Modifies,_,_,NewRWInfos),
1212 debug_format(19,'Recomputing read/write infos for ~w (~w)~n',[TName,Modifies]),
1213 update_infos(NewRWInfos,Info,NewInfos),
1214 NewTBody=b(Body,subst,NewBInfos).
1215 cleanup_post_with_path(any(Ids,Pred,Subst),subst,I,Result,subst,[generated|I],single/transform_any_into_let,Path) :-
1216 (last(Path,path_arg(top_level(_),_))
1217 /* do not remove top-level ANY if show_eventb_any_arguments is true; see, e.g., test 1271 */
1218 -> preferences:preference(show_eventb_any_arguments,false) ; true),
1219 conjunction_to_list(Pred,Preds),
1220 get_sorted_ids(Ids,BlacklistIds),
1221 find_one_point_rules(Ids,Preds,BlacklistIds,LetIDs,Exprs,RestIds,RestPreds),
1222 LetIDs \= [],
1223 maplist(create_equality,LetIDs,Exprs,LetDefs),
1224 % print(found_lets(LetIDs,RestIds,RestPred)),nl,print(Path),nl,
1225 conjunct_predicates_with_pos_info(LetDefs,LetDefPred),
1226 (RestIds = [], RestPreds=[] % complete ANY can be translated to LET
1227 -> Result = let(LetIDs,LetDefPred,Body), Body = Subst
1228 ? ; split_predicates(RestPreds,Ids,RestUsingIds,RestNotUsingIds),
1229 conjunct_predicates_with_pos_info(RestPreds,RestPred),
1230 % print('USING: '), print_bexpr(RestUsingIds),nl, print('NOT USING: '), print_bexpr(RestNotUsingIds),nl,
1231 (RestIds = []
1232 -> (is_truth(RestUsingIds)
1233 % RestPred does not use the LET identifiers; move outside of the LET !
1234 -> Result = select([b(select_when(RestPred,SelectBody),subst,[generated|I])]),
1235 SelectBody = b(let(LetIDs,LetDefPred,Subst),subst,[generated|I])
1236 ; is_truth(RestNotUsingIds)
1237 % RestPred uses LET identifiers in all conjuncts; move inside LET
1238 -> Result = let(LetIDs,LetDefPred,LetBody),
1239 LetBody = b(select([b(select_when(RestPred,Subst),subst,[])]),subst,[generated|I])
1240 ;
1241 % we would need to generate an outer and inner select; transformation probably not worth it
1242 fail
1243 )
1244 ; is_truth(RestUsingIds)
1245 % RestPred does not use LET identifiers move outside of LET
1246 -> Result = any(RestIds,RestPred,SelectBody),
1247 SelectBody = b(let(LetIDs,LetDefPred,Subst),subst,[generated|I])
1248 ; is_truth(RestNotUsingIds)
1249 % RestPred uses LET identifiers in all conjuncts; move inside LET
1250 -> Result = let(LetIDs,LetDefPred,LetBody),
1251 LetBody = b(any(RestIds,RestPred,Subst),subst,I)
1252 ;
1253 % we would need to generate an outer and inner any; transformation probably not worth it
1254 fail
1255 )
1256 ),
1257 !. %,translate:print_subst(b(Result,subst,[])),nl.
1258 cleanup_post_with_path(operation(TName,Res,Params,Body),Type,Info,
1259 operation(TName,Res,Params,NewBody),Type,Info,single/lts_min_guard_splitting,Path) :-
1260 (get_preference(ltsmin_guard_splitting,true) ; \+ get_preference(pge,off)), % equivalent to pge_algo:is_pge_opt_on),
1261 Path = [path_arg(top_level(operation_bodies),_)], % only apply at top-level and TO DO: only for top-most machine !!
1262 % TO DO: also apply for Event-B models
1263 get_texpr_id(TName,Name),
1264 (get_operation_propositional_guards(Name,Res,Params,Body,Guards,RestBody)
1265 -> true
1266 ; add_warning(ltsmin_guard_splitting,'Cannot extract guard for:',Name),fail),
1267 Guards \= [],
1268 conjunct_predicates_with_pos_info(Guards,G),
1269 get_texpr_info(Body,BInfo),
1270 NewBody = b(precondition(G,RestBody),subst,[prob_annotation('LTSMIN-GUARD')|BInfo]), % a SELECT would be more appropriate
1271 (debug_mode(off) -> true
1272 ; format('Extracting LTS Min guard for ~w~n',[Name]),translate:print_subst(NewBody),nl).
1273 cleanup_post_with_path(exists(Ids,B),Type,OInfo,exists(Ids,B),Type,NInfo,single/invalidate_used_ids,_Path) :-
1274 delete(OInfo,used_ids(_),NInfo). % the changes done by cleanups, e.g, removing unused predicates can affect used_ids
1275 cleanup_post_with_path(forall(Ids,LHS,RHS),Type,OInfo,forall(Ids,LHS,RHS),Type,NInfo,single/invalidate_used_ids,_Path) :-
1276 delete(OInfo,used_ids(_),NInfo). % ditto
1277 cleanup_post_with_path(OExpr,OType,OInfo,NExpr,NType,NInfo,Mode/Rule,Path) :-
1278 get_preference(optimize_ast,true),
1279 cleanup_post_ne_with_path(OExpr,OType,OInfo,NExpr,NType,NInfo,Mode/Rule,Path).
1280 cleanup_post_with_path(OExpr,OType,OInfo,NExpr,NType,NInfo,Mode/Rule,_Path) :-
1281 ? cleanup_post_essential(OExpr,OType,OInfo,NExpr,NType,NInfo,Mode/Rule).
1282
1283 % delete an assignment from a substitution
1284 delete_assignment(b(assign(LHS,RHS),subst,Info),ID,IDRHS,b(RES,subst,Info)) :-
1285 nth1(Pos,LHS,ID,RestLHS),
1286 nth1(Pos,RHS,IDRHS,RestRHS),
1287 (RestLHS = [] -> RES = skip ; RES = assign(RestLHS,RestRHS)).
1288 % TO DO: also deal with parallel and possibly other constructs assign_single_id,...
1289
1290 %unguarded(path_arg(sequence/1,1)). % first argument of sequence is not guarded
1291 ?unguarded(path_arg(X,_)) :- unguarded_aux(X).
1292 unguarded_aux(top_level(_)).
1293 unguarded_aux(operation/4).
1294 unguarded_aux(parallel/1).
1295 unguarded_aux(var/2).
1296 unguarded_aux(let/3).
1297 % what about choice/2 ??
1298
1299 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
1300
1301
1302 % ---------------------
1303
1304 % now the rules which do not need the Path
1305
1306 % first check for a few expressions that never need to be optimised, rewritten:
1307 cleanup_post_essential(E,_,_,_,_,_,_) :- never_transform_or_optimise(E),!,fail.
1308
1309 cleanup_post_essential(Expr,Type,I,Expr,Type,I2,single/remove_erroneous_info_field) :-
1310 \+ ground(I),!,
1311 functor(Expr,F,_N),
1312 add_internal_error('Information field not ground: ',I:F),
1313 I2=[].
1314 cleanup_post_essential(comprehension_set(Ids,E),Type,I,comprehension_set(Ids,E),Type,I,single/sanity_check) :-
1315 get_preference(prob_safe_mode,true),
1316 get_texpr_ids(Ids,UnsortedIds),sort(UnsortedIds,SIds),
1317 \+ same_length(UnsortedIds,SIds),
1318 add_error(cleanup_post,'Identifier clash in comprehension set: ',UnsortedIds),
1319 print(E),nl,
1320 fail.
1321
1322
1323 cleanup_post_essential(lambda(Ids,Pred,Expr),Type,I,
1324 comprehension_set(CompIds,CompPred),Type,NewInfo,multi/remove_lambda) :- !,
1325 unify_types_strict(Type,set(couple(_ArgType,ResType))),
1326 get_unique_id_inside('_lambda_result_',Pred,Expr,ResultId),
1327 def_get_texpr_id(Result,ResultId),
1328 get_texpr_type(Result,ResType),
1329 get_texpr_info(Result,[lambda_result(ResultId)]),
1330 append(Ids,[Result],CompIds),
1331 get_texpr_expr(Equal,equal(Result,Expr)),
1332 get_texpr_type(Equal,pred),
1333 extract_important_info_from_subexpression(Expr,EqInfo), % mark equality with wd condition if Expr has wd condition
1334 (member(prob_annotation('SYMBOLIC'),EqInfo)
1335 -> % something like %p.(p : BOOL|%t.(t : NATURAL|t .. t + 7))
1336 (debug_mode(off) -> true
1337 ; write('Marking lambda as symbolic because result is symbolic: '),print_bexpr(Expr),nl),
1338 add_info_if_new(I,prob_annotation('SYMBOLIC'),NewInfo)
1339 ? ; infinite_or_symbolic_domain_for_lambda(Ids,Pred,Kind)
1340 -> % something like %t.(t : NATURAL|t .. t + 7)
1341 (debug_mode(off) -> true
1342 ; get_texpr_ids(Ids,AIds),
1343 format('Marking lambda over ~w as symbolic because the domain is ~w: ',[AIds,Kind]),
1344 print_bexpr(Pred),nl),
1345 add_info_if_new(I,prob_annotation('SYMBOLIC'),NewInfo)
1346 ; NewInfo = I),
1347 get_texpr_info(Equal,[prob_annotation('LAMBDA-EQUALITY')|EqInfo]),
1348 conjunct_predicates_with_pos_info(Pred,Equal,CompPred0),
1349 add_texpr_infos(CompPred0,[prob_annotation('LAMBDA')],CompPred). % checked e.g. in is_converted_lambda_closure
1350 %print_bexpr(b(comprehension_set(CompIds,CompPred),Type,NewInfo)),nl.
1351
1352 cleanup_post_essential(reflexive_closure(Rel),Type,I, UNION,Type,NewInfo,multi/remove_reflexive_closure) :- !,
1353 NewInfo = [was(reflexive_closure)|I],
1354 safe_create_texpr(closure(Rel),Type,I,CL),
1355 UNION = union(b(event_b_identity,Type,IdInfo), CL), % closure(R) = id \/ closure1(R)
1356 (is_infinite_ground_type(Type) -> IdInfo = [prob_annotation('SYMBOLIC')|I] ; IdInfo =I),
1357 (debug_mode(on) -> print('Rewriting closure to: '), print_bexpr(b(UNION,Type,[])),nl ; true).
1358 cleanup_post_essential(evb2_becomes_such(Ids,Pred),subst,I,becomes_such(Ids,Pred2),subst,I,multi/ev2_becomes_such) :-
1359 % we translate a Classical-B becomes_such with id -> id$0, id' -> id
1360 % classical B: Dec = BEGIN level : (level>=0 & level> level$0-5 & level < level$0) END
1361 % Event-B: level'>= 0, level' > level-5 ...
1362 !,
1363 prime_identifiers(Ids,PIds),
1364 maplist(gen_rename,PIds,Ids,RenameList1), % id' -> id
1365 prime_identifiers0(Ids,PIds0),
1366 maplist(gen_rename,Ids,PIds0,RenameList2), % id -> id$0
1367 append(RenameList1,RenameList2,RenameList),
1368 rename_bt(Pred,RenameList,Pred2),
1369 (debug_mode(off) -> true
1370 ; format('Converting Event-B becomes_such: ',[]), print_bexpr(Pred2),nl).
1371 cleanup_post_essential(successor,Type,I,Compset,Type,[was(successor)|I],multi/successor) :- !,
1372 % translation of succ
1373 pred_succ_compset(add,Compset).
1374 cleanup_post_essential(rev(A),string,I,ExtFunCall,string,[was(rev)|I],multi/rev_for_string) :- !,
1375 % translation of rev for STRINGs, this can only occur when allow_sequence_operators_on_strings is true
1376 ExtFunCall = external_function_call('STRING_REV',[A]).
1377 cleanup_post_essential(concat(A,B),string,I,ExtFunCall,string,[was(concat)|I],multi/concat_for_string) :- !,
1378 % translation of concat (^) for STRINGs, can only occur when allow_sequence_operators_on_strings is true
1379 construct_string_append(A,B,ExtFunCall).
1380 cleanup_post_essential(general_concat(A),string,I,ExtFunCall,string,[was(general_concat)|I],multi/concat_for_string) :-
1381 !, % translation of conc for seq(STRING) --> STRING, can only occur when allow_sequence_operators_on_strings is true
1382 ExtFunCall = external_function_call('STRING_CONC',[A]).
1383 cleanup_post_essential(size(A),integer,I,ExtFunCall,integer,[was(A)|I],multi/concat_for_string) :-
1384 get_texpr_type(A,string),!,
1385 % translation of size for STRING, this can only occur when allow_sequence_operators_on_strings is true
1386 ExtFunCall = external_function_call('STRING_LENGTH',[A]).
1387 cleanup_post_essential(predecessor,Type,I,Compset,Type,[was(predecessor)|I],multi/predecessor) :- !,
1388 % translation of pred
1389 pred_succ_compset(minus,Compset).
1390 cleanup_post_essential(becomes_such(Ids1,Pred),subst,I,becomes_such(Ids2,Pred),subst,I,single/becomes_such) :- !,
1391 annotate_becomes_such_vars(Ids1,Pred,Ids2).
1392 cleanup_post_essential(Expr,Type,I,Expr,Type,[contains_wd_condition|I],multi/possibly_undefined) :-
1393 % multi: rule can only be applied once anyway, no need to check
1394 nonmember(contains_wd_condition,I),
1395 % print(' - CHECK WD: '), print_bexpr(Expr),nl, %%
1396 is_possibly_undefined(Expr),!,
1397 %% print('CONTAINS WD: '), print_bexpr(Expr),nl, %%
1398 %(translate:translate_bexpression(Expr,'{min(xunits)}') -> trace ; true),
1399 true.
1400 % if a substitution has a sub-expression that is a substitution with that refers to the original
1401 % value of a variable, we mark this substitution, too.
1402
1403 % If the substitution of an operation contains a while whose invariant contains references x$0
1404 % to the original value of a variable x, we must insert a LET substitution to preserve the original value.
1405 cleanup_post_essential(operation(Id,Results,Args,Body),Type,I,operation(Id,Results,Args,NewBody),Type,I,single/refers_to_old_state_let) :-
1406 get_texpr_info(Body,BodyInfo),
1407 memberchk(refers_to_old_state(References),BodyInfo),!,
1408 create_equalities_for_let(References,Ids,Equalities),
1409 conjunct_predicates_with_pos_info(Equalities,P),
1410 insert_let(Body,Ids,P,NewBody).
1411 cleanup_post_essential(Subst,subst,I,Subst,subst,NI,single/refers_to_old_state) :-
1412 safe_syntaxelement_det(Subst,Subs,_,_,_),
1413 % check if a child contains the refers_to_old_state flag
1414 findall(Reference, (member(Sub,Subs),
1415 get_texpr_info(Sub,SubInfo),
1416 memberchk(refers_to_old_state(References),SubInfo),
1417 member(Reference,References)), ReferedIds),
1418 ReferedIds \= [],
1419 !,
1420 sort(ReferedIds,SortedIds),
1421 NI = [refers_to_old_state(SortedIds)|I].
1422
1423 cleanup_post_essential(let_predicate([],[],TExpr),Type,Iin,Expr,Type,Iout,multi/remove_let_predicate) :- !,
1424 % same as above, just for predicates
1425 get_texpr_expr(TExpr,Expr),
1426 get_texpr_info(TExpr,I),
1427 % The next is done to prevent removing position information (in case of Event-B invariants)
1428 (nonmember(nodeid(_),I), member(nodeid(P),Iin) -> Iout = [nodeid(P)|I] ; Iout = I).
1429
1430
1431 cleanup_post_essential(OExpr,OType,OInfo,NExpr,NType,NInfo,Mode/Rule) :-
1432 get_preference(optimize_ast,true),
1433 ? cleanup_post(OExpr,OType,OInfo,NExpr,NType,NInfo,Mode/Rule).
1434
1435 % moved these rule below the simplifciation rules above to avoid re-computing used_id infos
1436 cleanup_post_essential(forall(Ids,Lhs,Rhs),pred,IOld,Res,pred,INew,single/forall_used_identifier) :-
1437 reconstruct_forall(Ids,Lhs,Rhs,IOld, b(Res,pred,INew)).
1438 cleanup_post_essential(exists(Ids,P),pred,IOld,exists(Ids,NP),pred,ResInfo,single/exists_used_identifier) :-
1439 inner_predicate_level_optimizations(P,NP),
1440 add_used_identifier_info(Ids,NP,IOld,INew0),
1441 add_used_ids_defined_by_equality(Ids,NP,INew0,INew),
1442 %print('* POST => '),print_bexpr(b(exists(Ids,NP),pred,INew)),nl,
1443 %print(' INFO=> '),print(INew),nl,
1444 % TO DO: also compute which identifiers are worth waiting for; do not wait for res in #x.(x:E & ... & res=min(f(x)))
1445 add_removed_typing_info(INew,ResInfo).
1446 cleanup_post_essential(Construct,Type,I,NewConstruct,Type,I,single/detect_partitions) :-
1447 contains_predicate(Construct,Type,Pred,NewConstruct,NewPred),!, % something like a select or other substitution
1448 predicate_level_optimizations(Pred,NewPred).
1449 cleanup_post_essential(Construct,Type,I,NewConstruct,Type,I,single/detect_partitions2) :-
1450 contains_predicates(Construct,Type,Preds,NewConstruct,NewPreds),!,
1451 maplist(predicate_level_optimizations,Preds,NewPreds) % TO DO: do CSE together (in some cases) !
1452 . %, (Preds=NewPreds -> true ; print('Found partitions: '), translate:print_subst(b(NewConstruct,Type,I)),nl).
1453
1454 construct_inner_forall(Ids,LHS,RHS,OldInfo,Res) :-
1455 delete(OldInfo,used_ids(_),I1), % we construct a changed forall construct; old used_ids info possibly incorrect
1456 reconstruct_forall(Ids,LHS,RHS,I1,Res).
1457 % use when in cleanup_post you construct a forall which will not be at the top-level
1458 % (meaning that the above essential rules will not run)
1459 reconstruct_forall(Ids,LHS,RHS,OldInfo, b(Res,pred,NewInfo)) :-
1460 inner_predicate_level_optimizations(LHS,NLhs),
1461 inner_predicate_level_optimizations(RHS,NRhs),
1462 construct_forall_opt(Ids,NLhs,NRhs,OldInfo, Res,NewInfo).
1463
1464 construct_forall_opt(IDs,NLhs,NRhs,Info, Res,NewInfo) :-
1465 (is_truth(NRhs) ; is_falsity(NLhs)),!,
1466 add_hint_message(remove_useless_assign,'Removing useless universal quantification','',Info),
1467 Res= truth, NewInfo = [was(forall(IDs,NLhs,NRhs))|Info].
1468 % TO DO: is the following rule useful ?: will require adapting test 510 output file
1469 % triggers e.g. for test 1447
1470 %construct_forall_opt([TID],LHS,RHS,Info, Res,NewInfo) :- % !x. (x:SetA => x:SetB) ---> SetA <: SetB
1471 % is_valid_id_member_check(LHS,TID,SetA), is_valid_id_member_check(RHS,TID,SetB),
1472 % !,
1473 % (debug_mode(off) -> true
1474 % ; format('Replacing forall ~w by subset: ',[TID]), print_bexpr(b(subset(SetA,SetB),pred,Info)),nl
1475 % ),
1476 % Res = subset(SetA,SetB), NewInfo = [was(forall)|Info].
1477 construct_forall_opt(Ids,NLhs,NRhs,OldInfo, forall(Ids,NLhs,NRhs),ResInfo) :-
1478 conjunct_predicates([NLhs,NRhs],P),
1479 add_used_identifier_info(Ids,P,OldInfo,Info),
1480 add_removed_typing_info(Info,ResInfo).
1481
1482 add_removed_typing_info(Info,ResInfo) :-
1483 (memberchk(removed_typing,Info) -> ResInfo = Info ; ResInfo = [removed_typing|Info]).
1484
1485 disjoint_ids(Ids1,Ids2) :-
1486 get_texpr_ids(Ids1,I1), sort(I1,SI1),
1487 get_texpr_ids(Ids2,I2), sort(I2,SI2),
1488 ord_disjoint(SI1,SI2).
1489
1490
1491 % translate concat(^) of strings:
1492 construct_string_append(A,B,ExtCall) :-
1493 is_string_conc_or_append(A,List,InfoA), !, % nested concat -> translate to STRING_CONC to enable optimisations
1494 append(List,[B],NewList),
1495 ExtCall = external_function_call('STRING_CONC',[S]),
1496 get_texpr_info(B,IB),merge_info(InfoA,IB,Info),
1497 S = b(sequence_extension(NewList),seq(string),Info).
1498 construct_string_append(A,B,external_function_call('STRING_APPEND',[A,B])).
1499
1500 is_string_conc_or_append(b(external_function_call(F,FArgs),_,Info),Args,Info) :-
1501 (F='STRING_APPEND' -> Args = FArgs
1502 ; F='STRING_CONC',
1503 FArgs = b(sequence_extension(SArgs),_,_)
1504 -> Args = SArgs).
1505
1506 % ---------------------
1507
1508 % non-essential post cleanup rules; only applied when optimize_ast is TRUE
1509
1510 % WITH PATH:
1511
1512 cleanup_post_ne_with_path(member(E,b(image(Rel,SONE),TypeImg,InfoImg)),pred,I,member(Couple,Rel),pred,I,multi/replace_image_by_member,Path) :-
1513 % x : Rel[{One}] => One|->x : Rel
1514 Path \= [path_arg(forall/3,1)|_], % not LHS of a forall
1515 %% do not do this if it is the LHS of a forall: !(aus2).( aus2 : helper[{mm}] => RHS) (as we no longer can apply the optimized set treatment for forall
1516 singleton_set_extension(SONE,One),
1517 %% Rel \= b(inverse(_),_,_), %% TO DO: maybe exclude this; here user maybe wants to explicitly compute image ?
1518 !,
1519 create_couple(One,E,Couple),
1520 (debug_mode(off) -> true
1521 ; print('Member of Image: '),print_bexpr(b(member(E,b(image(Rel,SONE),TypeImg,InfoImg)),pred,I)),nl,
1522 print(' replaced by: '),print_bexpr(b(member(Couple,Rel),pred,I)),nl
1523 ).
1524
1525
1526 % WITHOUT PATH:
1527
1528 cleanup_post(conjunct(b(truth,pred,I1),b(B,pred,I2)),pred,I0,B,pred,NewI,multi/remove_truth_conj1) :- !,
1529 include_important_info_from_removed_pred(I1,I2,I3), % ensure was,... information propagated
1530 add_important_info_from_super_expression(I0,I3,NewI).
1531 cleanup_post(conjunct(b(A,pred,I2),b(truth,pred,I1)),pred,I0,A,pred,NewI,multi/remove_truth_conj2) :- !,
1532 include_important_info_from_removed_pred(I1,I2,I3),
1533 add_important_info_from_super_expression(I0,I3,NewI).
1534 cleanup_post(conjunct(b(falsity,pred,I1),b(_,_,I2)),pred,I0,falsity,pred,NewI,multi/simplify_falsity_conj1) :- !,
1535 include_important_info_from_removed_pred(I2,I1,I3),
1536 add_important_info_from_super_expression(I0,I3,NewI).
1537 cleanup_post(conjunct(LHS,b(falsity,pred,I2)),pred,I0,falsity,pred,NewI,multi/simplify_falsity_conj2) :-
1538 always_well_defined_or_wd_reorderings_allowed(LHS), % we can only improve WD here,
1539 % also checks allow_improving_wd_mode preference
1540 !, % Note: ProB would treat falsity first anyway; so in principle this could be done always for solving
1541 get_texpr_info(LHS,I1),
1542 include_important_info_from_removed_pred(I1,I2,I3),
1543 add_important_info_from_super_expression(I0,I3,NewI).
1544 % we use FInfo: in case it has a was(.) field, e.g., for pretty printing and unsat core generation and unsatCore.groovy test
1545 cleanup_post(conjunct(AA,BB),pred,I,Res,pred,I,multi/modus_ponens) :-
1546 Impl = b(implication(A,B),pred,_),
1547 ((AA,BB) = (Impl,A2) ; (BB,AA) = (Impl,A2)),
1548 same_texpr(A,A2),
1549 % arises e.g., for predicates such as IF x:0..3 THEN y=2 ELSE 1=0 END ; works with simplify_falsity_impl3 rule
1550 % rewrite (A=>B) & A into (A&B)
1551 !,
1552 (debug_mode(off) -> true ; print('Modus Ponens: '),print_bexpr(A), print(' => '), print_bexpr(B),nl),
1553 Res = conjunct(A,B).
1554 %cleanup_post(conjunct(TLHS,P1),pred,_,LHS,pred,Info,multi/duplicate_pred) :-
1555 % % TO DO: implement an efficient version of this; currently very slow e.g. for test 293
1556 % b_interpreter:member_conjunct(P2,TLHS,_),
1557 % same_texpr(P1,P2),
1558 % TLHS = b(LHS,pred,Info),
1559 % print('remove_duplicate: '), print_bexpr(P1),nl.
1560 cleanup_post(conjunct(LHS,b(Comparison1,pred,_)),pred,I0,Result,pred,RInfo,multi/detect_interval1) :-
1561 % X <= UpBound & X >= LowBound <=> X : UpBound .. LowBound (particularly useful when CLPFD FALSE, causes problem with test 1771)
1562 % Note: x>18 & y<1024 & x<20 & y>1020 now works, it is bracketed ((()) & y>1020)
1563 get_preference(use_clpfd_solver,false),
1564 \+ data_validation_mode, % this rule may lead to additional enumerations
1565 get_leq_comparison(Comparison1,X,UpBound),
1566 ? select_conjunct(b(Comparison2,_,_),LHS,Prefix,Suffix),
1567 get_geq_comparison(Comparison2,X2,LowBound),
1568 same_texpr(X,X2),
1569 (always_well_defined_or_disprover_mode(UpBound)
1570 -> true
1571 ; % as we may move valuation earlier, we have to be careful
1572 % we check if Comparison2 is last conjunct; x=7 & x:8..(1/0) raises no WD error in ProB
1573 Suffix=[]
1574 ),
1575 !,
1576 create_interval_member(X,LowBound,UpBound,Member),
1577 append(Prefix,[Member|Suffix],ResultList),
1578 conjunct_predicates(ResultList,TResult),
1579 TResult = b(Result,pred,I1),
1580 add_important_info_from_super_expression(I0,I1,RInfo),
1581 (debug_mode(off) -> true ; print(' Detected interval membership (1): '),print_bexpr(b(Result,pred,RInfo)),nl).
1582 cleanup_post(conjunct(LHS,b(Comparison1,pred,_)),pred,I0,Result,pred,RInfo,multi/detect_interval2) :-
1583 % X >= LowBound & X <= UpBound <=> X : UpBound .. LowBound
1584 get_preference(use_clpfd_solver,false),
1585 \+ data_validation_mode, % this rule may lead to additional enumerations
1586 get_geq_comparison(Comparison1,X,LowBound),
1587 ? select_conjunct(b(Comparison2,_,_),LHS,Prefix,Suffix),
1588 get_leq_comparison(Comparison2,X2,UpBound),
1589 same_texpr(X,X2),
1590 (always_well_defined_or_disprover_mode(LowBound)
1591 -> true
1592 ; % as we may move valuation earlier, we have to be careful
1593 % we check if Comparison2 is last conjunct; x=7 & x:8..(1/0) raises no WD error in ProB
1594 Suffix=[]
1595 ),
1596 !,
1597 create_interval_member(X,LowBound,UpBound,Member),
1598 append(Prefix,[Member|Suffix],ResultList),
1599 conjunct_predicates(ResultList,TResult),
1600 TResult = b(Result,pred,I1),
1601 add_important_info_from_super_expression(I0,I1,RInfo),
1602 (debug_mode(off) -> true ; print(' Detected interval membership (2): '),print_bexpr(b(Result,pred,RInfo)),nl).
1603
1604 cleanup_post(disjunct(b(truth,pred,I1),_),pred,I0,truth,pred,I,multi/simplify_truth_disj1) :- !,
1605 add_important_info_from_super_expression(I0,I1,I).
1606 cleanup_post(disjunct(b(A,pred,I1),b(falsity,pred,_)),pred,I0,A,pred,I,multi/remove_falsity_disj1) :- !,
1607 add_important_info_from_super_expression(I0,I1,I).
1608 cleanup_post(disjunct(b(falsity,pred,_),b(B,pred,I1)),pred,I0,B,pred,I,multi/remove_falsity_disj2) :- !,
1609 add_important_info_from_super_expression(I0,I1,I).
1610 cleanup_post(disjunct(Expr1,b(truth,pred,I1)),pred,I0,truth,pred,I,multi/simplify_truth_disj2) :-
1611 always_well_defined_or_wd_reorderings_allowed(Expr1), !, % we can only improve WD here
1612 add_important_info_from_super_expression(I0,I1,I).
1613 cleanup_post(disjunct(Equality1,Equality2),pred,I,New,pred,I,multi/rewrite_disjunct_to_member1) :-
1614 ? identifier_equality(Equality2,ID,_,Expr2),
1615 always_well_defined_or_disprover_mode(Expr2),
1616 get_texpr_type(Expr2,Type2),
1617 type_contains_no_sets(Type2), % we do not want to generate sets of sets, or worse sets with infinite sets (x=NATURAL1 or ...) which cannot be converted to AVL
1618 ? identifier_equality(Equality1,ID,TID,Expr1),
1619 % Rewrite (ID = Expr1 or ID = Expr2) into ID: {Expr1,Expr2} ; good if FD information can be extracted for ID
1620 % But: can be bad for reification, in particular when set extension cannot be computed fully
1621 % TO DO: also deal with ID : {Values} and more general extraction of more complicated disjuncts
1622 % TO DO: also apply for implication (e.g., ID /= E1 => ID=E2)
1623 !,
1624 construct_set_extension(Expr1,Expr2,SetX),
1625 New=member(TID,SetX),
1626 (debug_mode(off) -> true
1627 ; format('Rewrite disjunct (1) ~w: ',[ID]),print_bexpr(SetX),nl).
1628 cleanup_post(disjunct(LHS1,LHS2),pred,I,New,pred,I,multi/rewrite_disjunct_to_member2) :-
1629 ? id_member_of_set_extension(LHS2,ID,TID1,LExpr2), % also detects equalities
1630 get_texpr_type(TID1,Type),
1631 get_preference(use_clpfd_solver,true),type_contains_fd_index(Type), % merging is potentially useful
1632 maplist(always_well_defined_or_disprover_mode,LExpr2), % TODO: check that merging makes sense, e.g., definite FD values or simple identfiiers
1633 id_member_of_set_extension(LHS1,ID,TID,LExpr1),
1634 % Rewrite (ID : {Expr1,...} or ID : {Expr2,...} into ID: {Expr1,Expr2}
1635 l_construct_set_extension(LExpr1,LExpr2,SetX),
1636 New=member(TID,SetX),
1637 (debug_mode(off) -> true
1638 ; format('Rewrite disjunct (2) ~w: ',[ID]),print_bexpr(SetX),nl).
1639 cleanup_post(disjunct(P1,NegP1),pred,Info,truth,pred,Info,multi/tautology_disjunction) :-
1640 % P1 or not(P1) == truth (was created by Rodin for WD)
1641 (get_texpr_expr(NegP1,negation(P1bis)) -> same_texpr(P1,P1bis)
1642 ; get_texpr_expr(P1,negation(NP1)) -> same_texpr(NP1,NegP1)),
1643 (debug_mode(off) -> true
1644 ; format('Detected useless disjunction (tautology): ',[]),print_bexpr(b(disjunct(P1,NegP1),pred,Info)),nl).
1645 cleanup_post(disjunct(CEquality1,CEquality2),pred,IOld,New,pred,INew,multi/factor_common_pred_in_disjunction) :-
1646 % (x=2 & y=3) or (x=2 & y=4) -> x=2 & (y=3 or y=4) to improve constraint propagation
1647 ? factor_disjunct(CEquality1,CEquality2,IOld,New,INew),
1648 (debug_mode(off) -> true
1649 ; format('Factor disjunct: ',[]),print_bexpr(b(New,pred,INew)),nl).
1650 cleanup_post(implication(b(truth,pred,_),b(B,pred,I1)),pred,I0,B,pred,I,multi/remove_truth_impl1) :- !,
1651 add_important_info_from_super_expression(I0,I1,I).
1652 cleanup_post(implication(b(falsity,pred,I1),_),pred,I0,truth,pred,I,multi/simplify_falsity_impl1) :- !,
1653 add_important_info_from_super_expression(I0,I1,I).
1654 cleanup_post(implication(_,b(truth,pred,I1)),pred,I0,truth,pred,I,multi/simplify_truth_impl2) :- !,
1655 add_important_info_from_super_expression(I0,I1,I).
1656 cleanup_post(implication(P,b(falsity,pred,_)),pred,I,NotP,pred,[was(implication)|I],multi/simplify_falsity_impl3) :- !,
1657 create_negation(P,TNotP),
1658 (debug_mode(off) -> true ; print_bexpr(P), print(' => FALSE simplified'),nl),
1659 get_texpr_expr(TNotP,NotP).
1660 % TO DO: is the following rule useful ?:
1661 %cleanup_post(implication(A,b(implication(B,C),pred,_)),pred,IOld,
1662 % implication(AB,C),pred,IOld,single/replace_implication_by_and) :-
1663 % % (A => B => C <==> (A & B) => C
1664 % conjunct_predicates([A,B],AB),
1665 % (debug_mode(off) -> true ; print('Simplifying double implication: '), print_bexpr(b(implication(AB,C),pred,IOld)),nl).
1666 cleanup_post(equivalence(b(truth,pred,_),b(B,pred,I1)),pred,I0,B,pred,I,multi/remove_truth_equiv1) :- !,
1667 add_important_info_from_super_expression(I0,I1,I).
1668 cleanup_post(equivalence(b(A,pred,I),b(truth,pred,I1)),pred,I0,A,pred,I,multi/remove_truth_equiv2) :- !,
1669 add_important_info_from_super_expression(I0,I1,I).
1670 % TO DO: more rules for implication/equivalence to introduce negations (A <=> FALSITY ---> not(A)) ?
1671 % detect certain tautologies/inconsistencies
1672 cleanup_post(lazy_let_pred(_ID,_,b(Sub,pred,I1)),pred,I0,Sub,pred,I,multi/remove_lazy_let_pred) :-
1673 (Sub=truth ; Sub=falsity), !,
1674 add_important_info_from_super_expression(I0,I1,I).
1675 cleanup_post(IFTHENELSE,T,_,Res,T,[was(ifthenelse)|NI],single/remove_if_then_else) :-
1676 explicit_if_then_else(IFTHENELSE,IF,THEN,ELSE),
1677 (is_falsity(IF) -> b(Res,_,NI)=ELSE
1678 ; is_truth(IF) -> b(Res,_,NI)=THEN
1679 ),
1680 (debug_mode(off) -> true
1681 ; print('Simplified IF-THEN-ELSE: '), print_bexpr(IF),nl).
1682 cleanup_post(member(X,B),pred,I,truth,pred,[was(member(X,B))|I],multi/remove_type_member) :-
1683 is_just_type(B),
1684 nonmember(label(_),I), % the user has explicitly labeled this conjunct
1685 !. % print('REMOVE: '),print_bexpr(b(member(X,B),pred,[])),nl, print(I),nl.
1686 %cleanup_post(member(X,SET),pred,I,greater_equal(X,TBound),pred,[was(member(X,SET))|I],multi/remove_type_member) :-
1687 % disabled at the moment: we need to adapt test 1383, 767, 1703, 1003
1688 % is_inf_integer_set_with_lower_bound(SET,Bound),
1689 % Replace x:NATURAL by x>=0 and x:NATURAL1 by x>=1 ; is usually much more efficient
1690 % note : removes virtual timeout in test 290
1691 % !,
1692 % TBound = b(integer(Bound),integer,[]), print('REPLACE: '),print_bexpr(b(member(X,SET),pred,I)),nl, print_bexpr(b(greater_equal(X,TBound),pred,I)),nl.
1693 cleanup_post(not_member(X,B),pred,I,falsity,pred,[was(not_member(X,B))|I],multi/remove_type_not_member) :-
1694 is_just_type(B),
1695 nonmember(label(_),I), % the user has explicitly labeled this conjunct
1696 !.
1697 cleanup_post(member(X,TSet),pred,I,equal(X,One),pred,I,multi/remove_member_one_element_set) :-
1698 singleton_set_extension(TSet,One),
1699 !,
1700 % X:{One} <=> X=One
1701 true. %,print('Introducing equality: '),print_bexpr(X), print(' = '), print_bexpr(One),nl.
1702 cleanup_post(member(X,b(Set,_,_)),pred,I,not_equal(X,One),pred,I,multi/remove_member_setdiff) :-
1703 Set = set_subtraction(MaximalSet,SONE),
1704 singleton_set_extension(SONE,One),
1705 definitely_maximal_set(MaximalSet),
1706 !, % x : INTEGER-{One} <=> x/=One
1707 (debug_mode(off) -> true
1708 ; print('Replacing member of set_subtraction: '), print_bexpr(MaximalSet), print(' - '), print_bexpr(SONE),nl).
1709 cleanup_post(not_member(X,TSet),pred,I,not_equal(X,One),pred,I,multi/remove_member_one_element_set) :-
1710 singleton_set_extension(TSet,One),
1711 !,
1712 % X/:{One} <=> X/=One
1713 true.
1714 cleanup_post(member(E,b(fin_subset(E2),_,_)),pred,I,finite(E),pred,I,multi/introduce_finite) :-
1715 (same_texpr(E,E2); is_just_type(E2)),!. % print(introduce(finite(E))),nl.
1716 cleanup_post(not_member(E,b(fin_subset(E2),_,_)),pred,I,NotFinite,pred,I,multi/introduce_not_finite) :-
1717 (same_texpr(E,E2); is_just_type(E2)),!,
1718 create_negation(b(finite(E),pred,I),TNotP), get_texpr_expr(TNotP,NotFinite).
1719 /* do we want need this rule ?:
1720 clenaup_post(member(b(couple(A,B),couple(TA,TB),IC),ID),pred,I,equal(A,B),pred,I,multi/replace_member_id) :-
1721 is_is_event_b_identity(ID), !.
1722 */
1723 cleanup_post(member(b(couple(A,B),couple(TA,TB),IC),b(reverse(Rel),_,_)),pred,I,member(ICouple,Rel),pred,I,multi/remove_reverse) :- !,
1724 % (A,B) : Rel~ ===> (B,A) : Rel
1725 % can be detrimental for performance when A is known and B is not and Rel is large
1726 \+ data_validation_mode,
1727 (debug_mode(off) -> true ; print('Removed inverse (~): '),print_bexpr(Rel),nl),
1728 ICouple = b(couple(B,A),couple(TB,TA),IC).
1729 cleanup_post(member(LHS,ITE),pred,I,Result,pred,I,multi/member_if_then_else) :-
1730 get_texpr_expr(ITE,if_then_else(IFPRED,THEN,ELSE)),
1731 (definitely_empty_set(ELSE)
1732 -> A=THEN, P = IFPRED
1733 ; definitely_empty_set(THEN)
1734 -> A=ELSE, create_negation(IFPRED,P)
1735 ),
1736 % x: IF P THEN A ELSE {} END --> P & x:A
1737 % x: IF P THEN {} ELSE A END --> not(P) & x:A
1738 % appears in some generated Caval machines
1739 % x: IF a=TRUE THEN {11} ELSE {} END & x>11 can now be solved deterministically
1740 MEM = b(member(LHS,A),pred,I),
1741 conjunct_predicates([P,MEM],TR),
1742 (debug_mode(off) -> true ; print('Replace member of if-then-else by: '),print_bexpr(TR),nl),
1743 get_texpr_expr(TR,Result).
1744 cleanup_post(member(LHS,Comprehension),pred,I,Result,pred,NewInfo,multi/remove_member_comprehension) :-
1745 Comprehension = b(ComprSet,_,_),
1746 is_comprehension_set(ComprSet,[TID],Body),
1747 get_texpr_id(TID,ID),
1748 % LHS:{x|P(x)} ==> P(LHS)
1749 replace_id_by_expr_with_count(Body,ID,LHS,TResult,Count),
1750 % rewrite could duplicate LHS: not an issue in CSE mode; optimization relevant in normalize_ast mode
1751 ? is_replace_id_by_expr_ok(LHS,ID,Count,remove_member_comprehension),
1752 !,
1753 % could introduce LET if necessary because ID occurs multiple times (Count>1)
1754 get_texpr_expr(TResult,Result),
1755 get_texpr_info(TResult,I1),
1756 add_important_info_from_super_expression(I,I1,NewInfo),
1757 (debug_mode(off) -> true ; print('Remove element of comprehension_set: '),print_bexpr(Comprehension),nl,
1758 format(' rewriting to (~w): ',[Count]),print_bexpr(TResult),nl).
1759 cleanup_post(not_member(LHS,Comprehension),pred,I,Result,pred,I,multi/remove_not_member_comprehension) :-
1760 Comprehension = b(ComprSet,_,_),
1761 is_comprehension_set(ComprSet,[TID],Body),
1762 get_texpr_id(TID,ID),
1763 % LHS/:{x|P(x)} ==> not(P(LHS))
1764 replace_id_by_expr_with_count(Body,ID,LHS,TResult,Count),
1765 % rewrite could duplicate LHS: not an issue in CSE mode; optimization relevant in normalize_ast mode
1766 ? is_replace_id_by_expr_ok(LHS,ID,Count,remove_not_member_comprehension),
1767 !,
1768 Result = negation(TResult),
1769 (debug_mode(off) -> true ; print('Remove not element of comprehension_set: '),print_bexpr(Comprehension),nl,
1770 format(' rewriting to (~w): not(',[Count]),print_bexpr(TResult),print(')'),nl).
1771 cleanup_post(comprehension_set(Ids,Body),Type,I,NewExpr,Type,I2,Rule) :-
1772 ? cleanup_comprehension_set(Ids,Body,Type,I,NewExpr,I2,Rule),
1773 !.
1774 cleanup_post(subset(A,B),pred,I,truth,pred,[was(subset(A,B))|I],multi/remove_type_subset) :-
1775 is_just_type(B),
1776 nonmember(label(_),I), % the user has explicitly labeled this conjunct
1777 !.
1778 cleanup_post(not_subset(A,B),pred,I,falsity,pred,[was(not_subset(A,B))|I],multi/remove_type_not_subset) :-
1779 is_just_type(B),
1780 nonmember(label(_),I), % the user has explicitly labeled this conjunct
1781 !.
1782 cleanup_post(SUB,pred,I,NewPred,pred,[generated_conjunct|I],multi/replace_subset_by_element) :-
1783 is_subset(SUB,A,B),
1784 is_set_extension(A,List),
1785 !, % for sequence extension we don't need this as the interpreter knows exactly the cardinality of a sequence_extension ?
1786 % applying rule {x1,x2,...} <: B <=> x1:B & x2:B & ...
1787 maplist(gen_member_predicates(B),List,Conjuncts),
1788 conjunct_predicates(Conjuncts,TNewPred),
1789 % print('detected subset-member rule: '),print_bexpr(TNewPred),nl,
1790 get_texpr_expr(TNewPred,NewPred).
1791 cleanup_post(SUB,pred,I,NewPred,pred,[generated_conjunct|I],multi/replace_union_subset) :-
1792 is_subset(SUB,A,B),
1793 % mark conjunct as generated: used e.g. by flatten_conjunct in predicate_evaluator
1794 get_texpr_expr(A,union(_,_)),!,
1795 % applying rule A1 \/ A2 <: B <=> A1 <: B & A2 <: B
1796 % could be detrimental if checking that something is an element of B is expensive
1797 extract_unions(A,As),
1798 findall(Subi,(member(Ai,As),safe_create_texpr(subset(Ai,B),pred,I,Subi)),Conj), % we could try and re-run clean-up ? safe_create_texpr will ensure WD info set
1799 conjunct_predicates(Conj,TNewPred),
1800 get_texpr_expr(TNewPred,NewPred).
1801 cleanup_post(Comp,pred,I,SComp,pred,I,multi/simplify_cse_comparison) :-
1802 % simplify comparison operations; can result in improved constraint propagation
1803 % e.g., ia + CSE1 * 2 > ia + fa <=> CSE1 * 2 > fa for Setlog/prob-ttf/qsee-TransmitMemoryDumpOk21_SP_3.prob
1804 comparison(Comp,A,B,SComp,SA,SB),
1805 simplify_comparison_terms(A,B,SA,SB),!,
1806 (debug_mode(off) -> true
1807 ; print('Simplified: '),print_bexpr(b(Comp,pred,I)),
1808 print(' <=> '),print_bexpr(b(SComp,pred,I)),nl).
1809 cleanup_post(EMPTYSET,T,I,empty_set,T,[was(EMPTYSET)|I],multi/detect_emptyset) :- EMPTYSET \= empty_set,
1810 definitely_empty_set(b(EMPTYSET,T,I)),
1811 (debug_mode(off) -> true
1812 ; print('Detected empty set: '), print_bexpr(b(EMPTYSET,T,I)),nl).
1813 cleanup_post(equal(A,B),pred,I,truth,pred,[was(equal(A,B))|I],multi/remove_equality) :-
1814 same_texpr(A,B),always_well_defined_or_disprover_mode(A),!. % ,print(removed_equal(A,B)),nl.
1815 cleanup_post(equal(A,B),pred,I,equal(A2,B2),pred,I,multi/simplify_equality) :-
1816 simplify_equality(A,B,A2,B2).
1817 cleanup_post(not_equal(A,B),pred,I,not_equal(A2,B2),pred,I,multi/simplify_inequality) :-
1818 simplify_equality(A,B,A2,B2).
1819 cleanup_post(equal(A,B),pred,I,falsity,pred,[was(equal(A,B))|I],multi/remove_equality_false) :-
1820 different_texpr_values(A,B),!. %,print(removed_equal_false(A,B)),nl.
1821 cleanup_post(equal(A,B),pred,I,greater(Low,Up),pred,I,multi/remove_equality) :-
1822 % Low..Up = {} <=> Low>Up % is also handled by constraint solver; but other simplifications can apply here
1823 ? (definitely_empty_set(B), is_interval(A,Low,Up) ;
1824 definitely_empty_set(A), is_interval(B,Low,Up)),!,
1825 (debug_mode(off) -> true
1826 ; print('Simplified: '), print_bexpr(b(equal(A,B),pred,I)), print(' <=> '),
1827 print_bexpr(b(greater(Low,Up),pred,I)),nl).
1828 cleanup_post(CardGt0Expr,pred,I,not_equal(X,EmptySet),pred,I,multi/remove_cardgt0) :-
1829 get_geq_comparison(CardGt0Expr,Card,One),
1830 % card(P) > 0 -> P\={} if wd guaranteed; also rewrites card(P) >= 1
1831 Card = b(card(X),integer,_), get_integer(One,1),
1832 finite_set_or_disprover_mode(X), % as we keep X, it is sufficient for X to be finite for the rule to be ok
1833 get_texpr_type(X,TX), get_texpr_info(One,I0),
1834 EmptySet = b(empty_set,TX,I0),!,
1835 (debug_mode(off) -> true ; print('Removed card(.) > 0 for set: '), print_bexpr(X), nl).
1836 cleanup_post(CardEq0Expr,pred,I,equal(X,EmptySet),pred,I,multi/remove_cardeq0) :-
1837 is_equality(b(CardEq0Expr,pred,I),Card,Zero),
1838 % card(P) = 0 -> P={} if wd guaranteed
1839 Card = b(card(X),integer,_), get_integer(Zero,0),
1840 finite_set_or_disprover_mode(X),
1841 get_texpr_type(X,TX), get_texpr_info(Zero,I0),
1842 EmptySet = b(empty_set,TX,I0),!,
1843 (debug_mode(off) -> true ; print('Removed card(.) = 0 for set: '), print_bexpr(X), nl).
1844 cleanup_post(CardLt1Expr,pred,I,equal(X,EmptySet),pred,I,multi/remove_cardlt1) :-
1845 get_leq_comparison(CardLt1Expr,Card,Zero),
1846 % card(P) <= 0 -> P={} if wd guaranteed; TODO: also detect card(P) < 1
1847 Card = b(card(X),integer,_), get_integer(Zero,0),
1848 finite_set_or_disprover_mode(X),
1849 get_texpr_type(X,TX), get_texpr_info(Zero,I0),
1850 EmptySet = b(empty_set,TX,I0),!,
1851 (debug_mode(off) -> true ; print('Removed card(.) <= 0 for set: '), print_bexpr(X), nl).
1852 cleanup_post(member(Card,Natural),pred,I,truth,pred,I,multi/remove_card_natural) :-
1853 % card(P) : NATURAL -> truth if wd guaranteed
1854 Card = b(card(X),integer,_),
1855 is_integer_set(Natural,'NATURAL'),
1856 always_well_defined_or_disprover_mode(Card),
1857 !,
1858 (debug_mode(off) -> true ; print('Removed card(.):NATURAL for set: '), print_bexpr(X), nl).
1859 cleanup_post(not_equal(A,B),pred,I,less_equal(Low,Up),pred,I,multi/remove_equality) :-
1860 % Low..Up \= {} <=> Low<=Up % is also handled by constraint solver; but other simplifications can apply here
1861 ? (definitely_empty_set(B), is_interval(A,Low,Up) ;
1862 definitely_empty_set(A), is_interval(B,Low,Up)),!,
1863 (debug_mode(off) -> true
1864 ; print('Simplified: '), print_bexpr(b(equal(A,B),pred,I)), print(' <=> '),
1865 print_bexpr(b(less_equal(Low,Up),pred,I)),nl).
1866 cleanup_post(equal(A,B),pred,I,equal(A,RLet),pred,I,single/detect_recursion) :-
1867 % "A" should be an identifier
1868 get_texpr_id(A,ID),
1869 % check if some side conditions are fulfilled where the recursion detection can be enabled
1870 recursion_detection_enabled(A,B,I),
1871 % A must be recursively used in B:
1872 find_recursive_usage(B,ID),
1873 % TO DO: also find mutual recursion !
1874 debug_println(9,recursion_detected(ID)),
1875 !, % create an recursive_let where the body is annotated to be symbolic
1876 get_texpr_type(B,Type), add_texpr_infos(B,[prob_annotation('SYMBOLIC')],B2),
1877 mark_recursion(B2,ID,B3),
1878 %print(marked_recursion(ID)),nl,
1879 safe_create_texpr(recursive_let(A,B3),Type,RLet).
1880 cleanup_post(recursive_let(TID,TBody),T,_,Body,T,I2,single/remove_recursive_let) :- get_texpr_id(TID,ID),
1881 \+ occurs_in_expr(ID,TBody),
1882 debug_println(19,removing_recursive_let(ID)), % required for test 1225
1883 TBody = b(Body,_,I2).
1884 cleanup_post(equal(A,B),pred,Info1,ResultExpr,pred,Info3,multi/simplify_bool_true_false) :-
1885 % simplify bool(X)=TRUE -> X and bool(X)=FALSE -> not(X)
1886 ( get_texpr_expr(A,convert_bool(X)), get_texpr_boolean(B,BOOLVAL)
1887 ;
1888 get_texpr_boolean(A,BOOLVAL),get_texpr_expr(B,convert_bool(X))
1889 ),
1890 get_texpr_info(X,Info2),
1891 add_important_info_from_super_expression(Info1,Info2,Info3),
1892 (BOOLVAL = boolean_true -> get_texpr_expr(X,ResultExpr) ;
1893 BOOLVAL = boolean_false -> create_negation(X,TNX), get_texpr_expr(TNX,ResultExpr)),
1894 !,
1895 (debug_mode(off) -> true
1896 ; format('Simplifying bool(.)=~w to ',[BOOLVAL]),translate:print_bexpr(b(ResultExpr,pred,Info3)),nl).
1897 %cleanup_post(equal(A,B),pred,Info1,equal(REL,CartProd),pred,Info1,multi/simplify_image) :-
1898 % cannot be applied yet; SETS not precompiled yet !
1899 % A = b(image(REL,SetExt),_,_),
1900 % % REL[{OneEl}] = B ----> REL = {OneEl}*B if OneEl is the only possible value
1901 % % such signature appear in Alloy generated code
1902 % SetExt = b(set_extension([_]),set(global(GlobalSetName)),_),
1903 % %bmachine:b_get_named_machine_set_calc(GlobalSetName,_,[_]),
1904 % b_global_set_cardinality(Type,1), % cannot be called yet; global sets not precompiled
1905 % !,
1906 % get_texpr_type(REL,RelType),
1907 % safe_create_texpr(cartesian_product(SetExt,B),RelType,CartProd),
1908 % format('Translating image for singleton set'), print_bexpr(b(equal(REL,CartProd),pred,[])),nl.
1909 cleanup_post(not_equal(A,B),pred,I,falsity,pred,[was(not_equal(A,B))|I],multi/remove_disequality) :-
1910 same_texpr(A,B),always_well_defined_or_disprover_mode(A),!. % ,print(removed_not_equal(A,B)),nl.
1911 % sometimes one uses & TRUE=TRUE to finish off guards, invariants, ...
1912 % exchange lambda expressions by a comprehension set
1913 % TO DO: also add rule for bool(X)=FALSE -> not(X)
1914 cleanup_post(not_equal(A,B),pred,I,truth,pred,[was(not_equal(A,B))|I],multi/remove_disequality_false) :-
1915 different_texpr_values(A,B),!. % ,print(removed_not_equal_false(A,B)),nl.
1916 cleanup_post(not_equal(A,B),pred,I,NewP,pred,[was(not_equal(A,B))|I],multi/not_disjoint_disequality) :-
1917 /* Set1 /\ Set2 /= {} <===> #(zz).(zz:Set1 & zz:Set2) */
1918 preferences:preference(use_smt_mode,true), /* currently this rewriting makes test 1112 fail; TO DO: investigate */
1919 definitely_empty_set(B),
1920 get_texpr_expr(A,intersection(Set1,Set2)),!,
1921 get_texpr_type(Set1,Set1Type), unify_types_strict(Set1Type,set(T)),
1922 ID = b(identifier('_zzzz_unary'),T,[generated]),
1923 ESet1 = b(member(ID,Set1),pred,[]),
1924 ESet2 = b(member(ID,Set2),pred,[]),
1925 create_exists_opt([ID],[ESet1,ESet2],NewPredicate),
1926 (debug_mode(off) -> true
1927 ; print('Transformed not disjoint disequality: '),print_bexpr(NewPredicate),nl),
1928 get_texpr_expr(NewPredicate,NewP).
1929 cleanup_post(equal(b(intersection(A,B),_,_),Empty),pred,I,not_equal(El1,El2),pred,[was(intersection)|I],multi/detect_not_equal) :-
1930 % {El1} /\ {El2} = {} --> El1 \= El2 (disjoint sets)
1931 singleton_set_extension(A,El1),
1932 singleton_set_extension(B,El2),
1933 definitely_empty_set(Empty).
1934 cleanup_post(equal(b(intersection(A,B),_,_),Empty),pred,I,NewDisequality,pred,[was(intersection)|I],multi/detect_disjoint_set_extensions) :-
1935 % {El1,...} /\ {El2,...} = {} --> El1 \= El2 & .... (disjoint sets)
1936 get_texpr_expr(A,set_extension(Els1)), length(Els1,Len1), Len1 < 20,
1937 get_texpr_expr(B,set_extension(Els2)), length(Els2,Len2), Len2 < 20,
1938 Len1 * Len2 < 100,
1939 definitely_empty_set(Empty),
1940 maplist(simple_expression,Els1), % avoid duplication of computation
1941 maplist(simple_expression,Els2), % ditto
1942 findall(NotEqual, (member(A1,Els1),member(B1,Els2),safe_create_texpr(not_equal(A1,B1),pred,NotEqual)),
1943 NotEquals),
1944 conjunct_predicates(NotEquals,TRes),
1945 (debug_mode(off) -> true
1946 ; write('Expanding disjoint set constraint: '),translate:print_bexpr(TRes),nl
1947 ),
1948 get_texpr_expr(TRes,NewDisequality).
1949 cleanup_post(greater(A,B),pred,I,Res,pred,[was(greater(A,B))|I],multi/eval_greater) :-
1950 get_integer(A,IA), get_integer(B,IB),
1951 (IA>IB -> Res = truth ; Res=falsity).
1952 cleanup_post(less(A,B),pred,I,Res,pred,[was(less(A,B))|I],multi/eval_less) :-
1953 get_integer(A,IA), get_integer(B,IB),
1954 (IA<IB -> Res = truth ; Res=falsity).
1955 cleanup_post(greater_equal(A,B),pred,I,Res,pred,[was(greater_equal(A,B))|I],multi/eval_greater_equal) :-
1956 get_integer(A,IA), get_integer(B,IB),
1957 (IA >= IB -> Res = truth ; Res=falsity).
1958 cleanup_post(less_equal(A,B),pred,I,Res,pred,[was(less_equal(A,B))|I],multi/eval_less_equal) :-
1959 get_integer(A,IA), get_integer(B,IB),
1960 (IA =< IB -> Res = truth ; Res=falsity).
1961 cleanup_post(negation(A),pred,I,falsity,pred,[was(negation(A))|I],multi/remove_negation_truth) :-
1962 is_truth(A),!. % ,print(negation(A)),nl.
1963 cleanup_post(negation(A),pred,I,truth,pred,[was(negation(A))|I],multi/remove_negation_falsity) :-
1964 is_falsity(A),!. % ,print(negation(A)),nl.
1965 cleanup_post(convert_bool(A),boolean,I,Res,boolean,I,multi/remove_convert_bool) :-
1966 (is_truth(A) -> Res = boolean_true
1967 ; is_falsity(A) -> Res = boolean_false
1968 ; is_equality(A,LHS,BoolTRUE), get_texpr_boolean(BoolTRUE,boolean_true) % bool(LHS=TRUE) --> LHS
1969 -> get_texpr_expr(LHS,Res)
1970 ; A=not_equal(LHS,BoolFALSE), get_texpr_boolean(BoolFALSE,boolean_false) % bool(LHS/=FALSE) --> LHS
1971 -> get_texpr_expr(LHS,Res)
1972 ),!.
1973 cleanup_post(assertion_expression(Cond,_ErrMsg,Expr),_T,I0,BE,TE,IE,multi/remove_assertion_expression) :-
1974 is_truth(Cond),!,
1975 Expr = b(BE,TE,I1),
1976 add_important_info_from_super_expression(I0,I1,IE).
1977 cleanup_post(card(INTERVAL), T, I, Res, T, I, single/card_of_interval) :-
1978 % e.g., card(1..4) -> 4
1979 ? is_interval(INTERVAL, LowerBound, UpperBound),
1980 get_integer(LowerBound, L),
1981 number(L),
1982 get_integer(UpperBound, U),
1983 number(U),
1984 (L > U -> Card = 0 ; Card is 1+(U - L)),
1985 !,
1986 Res = integer(Card).
1987 cleanup_post(member(Empty,TPow),T,I,Res,T,I,single/empty_set_in_pow_subset) :-
1988 definitely_empty_set(Empty), % useful for z3 integration to prevent powerset constraint
1989 TPow = b(POW,_,_),
1990 (POW=pow_subset(_) -> RT=truth
1991 ; POW=fin_subset(_) -> RT=truth
1992 ; POW=pow1_subset(_) -> RT=falsity
1993 ; POW=fin1_subset(_) -> RT=falsity),
1994 always_well_defined_or_disprover_mode(TPow),
1995 !,
1996 Res = RT.
1997 cleanup_post(card(Empty),T,I,Res,T,I,single/card_singleton_set) :-
1998 Empty = b(empty_set,_,_), % useful for z3 integration to prevent cardinality constraint
1999 !,
2000 Res = integer(0).
2001 cleanup_post(card(SONE),T,I,Res,T,I,single/card_singleton_set) :-
2002 singleton_set_extension(SONE,One), % card({One}) = 1 ; useful for alloy2b
2003 always_well_defined_or_disprover_mode(One),
2004 !,
2005 Res = integer(1).
2006 cleanup_post(cartesian_product(A,B),T,I,Res,T,I,single/cartesian_product_to_pair) :-
2007 singleton_set_extension(A,El1),
2008 singleton_set_extension(B,El2), % {A}*{B} -> {A|->B} ; happens in Alloy translations a lot
2009 !,
2010 get_texpr_type(El1,T1), get_texpr_type(El2,T2),
2011 safe_create_texpr(couple(El1,El2),couple(T1,T2),Pair),
2012 Res = set_extension([Pair]).
2013 cleanup_post(image(Fun,Empty),T,I,empty_set,T,I,multi/image_empty_optimisation) :-
2014 definitely_empty_set(Empty),
2015 always_well_defined_or_wd_improvements_allowed(Fun),
2016 !,
2017 (debug_mode(off) -> true
2018 ; add_message(ast_cleanup,'Removing unnecessary image of empty set: ',Fun,I)).
2019 cleanup_post(union(A,B),T,I,Res,T,[add_element_to_set|I],multi/add_element_to_set) :- % multi: cycle check done in info field
2020 ? \+ member(add_element_to_set,I),
2021 ( singleton_set_extension(B,_El) -> Res = union(A,B)
2022 ; singleton_set_extension(A,_El) -> Res = union(B,A)),
2023 !. %,print(detected_add_singleton_element(_El)),nl.
2024 cleanup_post(union(A,B),T,I,Res,T,I,multi/union_empty_set) :-
2025 ( definitely_empty_set(A) -> get_texpr_expr(B,Res) % {} \/ B = B
2026 ; definitely_empty_set(B) -> get_texpr_expr(A,Res) % A \/ {} = A
2027 ),
2028 !.
2029 cleanup_post(intersection(A,B),T,I,empty_set,T,I,multi/intersection_empty_set) :-
2030 ( definitely_empty_set(A) -> true % A /\ {} = {}
2031 ; definitely_empty_set(B) -> true % {} /\ B = {}
2032 ),
2033 !.
2034 cleanup_post(set_subtraction(A,B),T,I,Res,T,I,multi/intersection_empty_set) :-
2035 ( definitely_empty_set(A) -> Res=empty_set % {} - B = {}
2036 ; definitely_empty_set(B) -> get_texpr_expr(A,Res) % A - {} = A
2037 ),
2038 !.
2039 cleanup_post(general_union(SetExt),Type,I0,Res,Type,Info,multi/general_union_set_extension) :- % union_generalized
2040 % union({a,b,c,...}) = a \/ b \/ c ...
2041 SetExt = b(set_extension(LIST),_,I1),
2042 add_important_info_from_super_expression(I0,I1,Info),
2043 % no need to apply rule if already transformed into avl in cleanup_pre, hence we do not call is_set_extension
2044 construct_union_from_list(LIST,Type,Info,TRes),
2045 !,
2046 (debug_mode(on) -> print('translated_general_union: '), print_bexpr(TRes),nl ; true),
2047 get_texpr_expr(TRes,Res).
2048 cleanup_post(general_intersection(SetExt),Type,I0,Res,Type,Info,multi/general_inter_set_extension) :- % inter_generalized
2049 % inter({a,b,c,...}) = a /\ b /\ c ...
2050 SetExt = b(set_extension(LIST),_,I1),
2051 add_important_info_from_super_expression(I0,I1,Info),
2052 % no need to apply rule if already transformed into avl in cleanup_pre, hence we do not call is_set_extension
2053 construct_inter_from_list(LIST,Type,Info,TRes),
2054 !,
2055 (debug_mode(on) -> print('translated_general_intersection: '), print_bexpr(TRes),nl ; true),
2056 get_texpr_expr(TRes,Res).
2057 cleanup_post(SUB,pred,I0,FORALL,pred,FInfo,multi/general_union_subset) :-
2058 is_subset(SUB,UNION,T),
2059 % union(S) <: T ===> !x.(x:S => x <: T)
2060 % currently: subsets of T may be generated, but it does not propagate well to S
2061 UNION = b(general_union(S),_,_),
2062 !,
2063 get_unique_id_inside('_zzzz_unary',S,T,ID),
2064 get_texpr_type(S,SType), is_set_type(SType,IDType),
2065 TID = b(identifier(ID),IDType,[generated]),
2066 safe_create_texpr(member(TID,S),pred,LHS),
2067 safe_create_texpr(subset(TID,T),pred,RHS),
2068 create_implication(LHS,RHS,NewForallBody),
2069 create_forall([TID],NewForallBody,TFORALL),
2070 TFORALL = b(FORALL,pred,I1),
2071 add_important_info_from_super_expression(I0,I1,FInfo),
2072 % see test 1854, and ProZ ROZ/model.tex
2073 (debug_mode(on) -> print('translated_general_union subset: '), print_bexpr(TFORALL),nl ; true).
2074 cleanup_post(size(Seq),integer,Info,Res,integer,Info,multi/size_append) :-
2075 get_texpr_expr(Seq,concat(A,B)),
2076 % size(A^B) = size(A)+size(B) useful e.g. for test 1306
2077 !,
2078 Res = add(b(size(A),integer,Info),b(size(B),integer,Info)).
2079 cleanup_post(concat(A,B),Type,I0,Seq,Type,[was(concat)|NewInfo],multi/concat_empty) :-
2080 ( definitely_empty_set(A) -> b(Seq,_,I1)=B
2081 ; definitely_empty_set(B) -> b(Seq,_,I1)=A
2082 ),!,
2083 add_important_info_from_super_expression(I0,I1,NewInfo).
2084 cleanup_post(concat(A,B),Type,I0,Seq,Type,[was(concat)|I0],multi/concat_singleton_seq) :-
2085 ( is_singleton_sequence(B,Element) -> Seq = insert_tail(A,Element)
2086 ; is_singleton_sequence(A,Element) -> Seq = insert_front(Element,B)
2087 ),!,
2088 debug_format(19,'Concat with singleton sequence detected~n',[]).
2089 cleanup_post(E,integer,I,Res,integer,[was(Operator)|I],multi/constant_expression) :-
2090 pre_compute_static_int_expression(E,Result),!,
2091 functor(E,Operator,_),
2092 % format('Precomputed: ~w for ',[Result]), translate:print_bexpr(b(E,integer,[])),nl,
2093 Res = integer(Result).
2094 cleanup_post(min(Interval),integer,I0,Res,integer,Info,multi/eval_min_interval) :-
2095 is_interval_or_singleton(Interval,Low,Up),
2096 get_integer(Low,L), number(L),
2097 get_integer(Up,U), number(U), L =< U, % non-empty interval
2098 debug_println(5,simplified_min_interval(L,U,L)),
2099 Res = integer(L), get_texpr_info(Low,I1),
2100 add_important_info_from_super_expression(I0,I1,Info).
2101 cleanup_post(max(Interval),integer,I0,Res,integer,Info,multi/eval_max_interval) :-
2102 is_interval_or_singleton(Interval,Low,Up),
2103 get_integer(Low,L), number(L),
2104 get_integer(Up,U), number(U), L =< U, % non-empty interval
2105 debug_println(5,simplified_max_interval(L,U,U)),
2106 Res = integer(U), get_texpr_info(Low,I1),
2107 add_important_info_from_super_expression(I0,I1,Info).
2108 cleanup_post(first(Seq),Type,I0,Res,Type,Info,multi/first_seq_extension) :-
2109 is_sequence_extension(Seq,List), List = [First|Rest],
2110 (Rest == [] -> true ; preferences:get_preference(disprover_mode,true)), % we may remove WD issue otherwise (TO DO: check if Rest contains any problematic elements)
2111 !,
2112 First = b(Res,Type,I1),
2113 add_important_info_from_super_expression(I0,I1,Info).
2114 cleanup_post(last(Seq),Type,I0,Res,Type,Info,multi/first_seq_extension) :-
2115 is_sequence_extension(Seq,List), List = [First|Rest],
2116 (Rest == [] -> true ; preferences:get_preference(disprover_mode,true)), % we may remove WD issue otherwise (TO DO: check if list contains any problematic elements)
2117 !,
2118 last([First|Rest],b(Res,Type,I1)),
2119 add_important_info_from_super_expression(I0,I1,Info).
2120 cleanup_post(function(Fun,Arg),Type,Info,New,Type,NewInfo,Rule) :-
2121 cleanup_post_function(Fun,Arg,Type,Info,New,NewInfo,Rule).
2122 cleanup_post(range(SETC),Type,I, comprehension_set(RangeIds2,NewCompPred),Type,I,single/range_setcompr) :-
2123 % translate ran({x1,...xn|P}) into {xn| #(x1,...).(P)} ; particularly interesting if x1... contains large datavalues (e.g., C_02_001.mch from test 1131)
2124 get_texpr_expr(SETC,comprehension_set(CompIds,CompPred)),
2125 get_domain_range_ids(CompIds,DomainIds,RangeIds), % print(range(CompIds,DomainIds,RangeIds)),nl,
2126 %\+((member(ID,RangeIds),get_texpr_id(ID,'_lambda_result_'))), % for test 612; maybe disable optimisation if memory consumption of variables small
2127 !, % TO DO: also detect patterns such as dom(dom( or ran(ran( ... [Done ??]
2128 ? rename_lambda_result_id(RangeIds,CompPred,RangeIds2,CompPred1),
2129 rename_lambda_result_id(DomainIds,CompPred1,DomainIds2,CompPred2),
2130 create_outer_exists_for_dom_range(DomainIds2,CompPred2,NewCompPred), % will mark the exists; so that during expansion we will treat it differently for enumeration
2131 (debug_mode(off) -> true
2132 ; print('Encode range as existential quantification: '), print_bexpr(NewCompPred),nl).
2133 cleanup_post(domain(SETC),Type,I, comprehension_set(DomainIds2,NewCompPred),Type,I,single/domain_setcompr) :-
2134 % translate dom({x1,...xn|P}) into {x1,..| #(xn).(P)} ; particularly interesting if xn contains large datavalues
2135 % used to fail test 306 ; fixed by allow_to_lift_exists annotation
2136 \+ data_validation_mode, % sometimes this optimisation is counter-productive for data_validation, problem: test 1945
2137 get_texpr_expr(SETC,comprehension_set(CompIds,CompPred)),
2138 get_domain_range_ids(CompIds,DomainIds,RangeIds), % print(domain(CompIds,DomainIds,RangeIds)),nl,
2139 % \+ (member(ID,CompIds),get_texpr_id(ID,'_lambda_result_')),
2140 % WE HAVE TO BE CAREFUL if xn = LAMBDA_RESULT ; TO DO rename like above for range
2141 % example from test 292: rel(fnc({x,y|x:1..10 & y:1..x})) = {x,y|x:1..10 & y:1..x}
2142 %\+ data_validation_mode, % test 1945 fails with WD errors if we disable this rule
2143 !,
2144 % TO DO: detect when closure is lambda; e.g., for e.g. dom(pred) = INTEGER in test 292 : split(CompIds,Args,Types), closures:is_lambda_value_domain_closure(Args,Types,B, DomainValue, _),; currently create_exists_opt deals with most of this
2145 rename_lambda_result_id(DomainIds,CompPred,DomainIds2,CompPred1),
2146 rename_lambda_result_id(RangeIds,CompPred1,RangeIds2,CompPred2),
2147 create_outer_exists_for_dom_range(RangeIds2,CompPred2,NewCompPred),
2148 (debug_mode(off) -> true
2149 ; get_texpr_ids(DomainIds,DIS), get_texpr_ids(RangeIds,RIS),
2150 ajoin(['Encode domain over ',DIS,' as existential quantification over ',RIS,' : '],Msg),
2151 add_message(ast_cleanup,Msg,NewCompPred,I)).
2152 cleanup_post(domain(SETC),Type,I, comprehension_set(DomainIds,RestPred),Type,I,single/domain_setcompr) :-
2153 % translate dom({x1,...xn|P & xn=E}) into {x1,..| P} ; particularly interesting if xn contains large datavalues
2154 get_texpr_expr(SETC,comprehension_set(CompIds,CompPred)),
2155 get_domain_range_ids(CompIds,DomainIds,RangeIds), % print(domain(CompIds,DomainIds,RangeIds)),nl,
2156 ? \+ (member(ID,CompIds),get_texpr_id(ID,'_lambda_result_')),
2157 conjunction_to_list(CompPred,Preds),
2158 RangeIds = [TId],
2159 get_sorted_ids(RangeIds,Blacklist),
2160 select_equality(TId,Preds,Blacklist,_Eq,_Expr,RestPreds,_,check_well_definedness), % We could do check_well_definedness only if preference set
2161 conjunct_predicates_with_pos_info(RestPreds,RestPred),
2162 not_occurs_in_predicate(Blacklist,RestPred),
2163 !,
2164 % TO DO: use create_optimized exists; also treat inner existential quantification and merge
2165 (debug_mode(off) -> true
2166 ; write('Encode domain of lambda abstraction: '),print_bexpr(RestPred),nl).
2167 cleanup_post(precondition(TP,TS),subst,I0,S,subst,Info,multi/remove_triv_precondition) :-
2168 % remove trivial preconditions
2169 get_texpr_expr(TP,truth),!,
2170 get_texpr_expr(TS,S),get_texpr_info(TS,I1),
2171 add_important_info_from_super_expression(I0,I1,Info).
2172 cleanup_post(external_function_call('ENUM',[TA]),T,I,A,T,[prob_annotation('ENUM')|I],single/process_ENUM) :-
2173 (debug_mode(on) -> format(' Processing ENUM (~w): ',[T]),translate:print_bexpr(TA),nl ; true),
2174 % TO DO: do not process in DEFINITION of ENUM in LibraryProB.def
2175 get_texpr_expr(TA,A).
2176 cleanup_post(comprehension_set(TIds,Body),T,I1,comprehension_set(TIds,Body2),T,I1,single/detect_lambda_result_auto) :-
2177 get_texpr_info(Body,BI),
2178 (TIds=[_,_,_|_] % check if at least three ids
2179 -> true % for example useful here: {x,y,v| x:INTEGER & y:INTEGER & #z.(z=x+1 & x = y*y & v=z*z & y:1..10)} it could be useful to detect x as DO_NOT_ENUMERATE; currently we only enable this analysis for four ids at least
2180 ; nonmember(prob_annotation('LAMBDA'),BI) % it is a lambda with one argument, no use to do analysis
2181 ),
2182 perform_do_not_enumerate_analysis(TIds,Body,'SET COMPREHENSION',I1,Body2).
2183 cleanup_post(comprehension_set(Ids1,E1),T,I,comprehension_set(Ids2,E2),T,I,multi/detect_lambda_result_user_ann) :-
2184 get_texpr_expr(DNE,external_pred_call('DO_NOT_ENUMERATE',[TID])),
2185 get_texpr_id(TID,ID),
2186 member_in_conjunction(DNE,E1),
2187 NewInfo = prob_annotation('DO_NOT_ENUMERATE'(ID)), % similar to lambda_result
2188 E1 = b(PRED,pred,I1),
2189 nonmember(NewInfo,I1),
2190 get_texpr_id(TID,ID),
2191 nth1(Pos,Ids1,TID1,Rest),
2192 add_texpr_infos(TID1,[NewInfo],TID2),
2193 nth1(Pos,Ids2,TID2,Rest),
2194 add_message(detect_lambda_result,'Annotating comprehension set identifier with DO_NOT_ENUMERATE: ',ID,I1),
2195 E2 = b(PRED,pred,[NewInfo|I1]).
2196 cleanup_post(record_field(b(rec(Fields),TR,IR),Field),T,I,FieldVal,T,I, single/remove_field_access) :-
2197 always_well_defined_or_disprover_mode(b(rec(Fields),TR,IR)),
2198 member(field(Field,TFieldVal),Fields),!,
2199 (debug_mode(off) -> true ; add_message(remove_field_access,'Remove static field access: ',Field,I)), % cf test 1294
2200 get_texpr_expr(TFieldVal,FieldVal).
2201 cleanup_post(sequence([S1,b(sequence(S2),subst,_)]),subst,I,sequence([S1|S2]),subst,I, single/flatten_sequence2) :-
2202 debug_println(9,flatten_sequence2). % do we need something for longer sequences?
2203 cleanup_post(sequence([b(sequence(S1),subst,_)|S2]),subst,I,sequence(NewSeq),subst,I, single/flatten_sequence1) :-
2204 append(S1,S2,NewSeq),
2205 % avoid maybe calling filter_useless_subst_in_sequence again
2206 debug_println(9,flatten_sequence1).
2207 cleanup_post(sequence(S1),subst,I,sequence(S2),subst,I, single/remove_useless_subst_in_seuence) :-
2208 get_preference(useless_code_elimination,true),
2209 filter_useless_subst_in_sequence(S1,Change,S2), debug_println(filter_sequence(9,Change)).
2210 cleanup_post(sequence(Statements),subst,I,Result,subst,I, single/sequence_to_multi_assign) :-
2211 % merge sequence of assignments if possible
2212 merge_assignments(Statements,Merge,New), Merge==merged,
2213 construct_sequence(New,Result).
2214 % nl,print('Merged: '),translate:print_subst(b(Result,subst,I)),nl,nl.
2215 cleanup_post(parallel(Statements),subst,I,Result,subst,I, single/parallel_to_multi_assign) :-
2216 % this merges multiple assignments into a single one: advantage: only one waitflag set up
2217 % should probably not be done in INITIALISATION
2218 % print(parallel(Statements)),nl,trace,
2219 extract_assignments(Statements,LHS,RHS,Rest,Nr), % print(extracted(Nr,LHS)),nl,
2220 Nr>1,!,
2221 (debug_mode(on) ->
2222 print('Parallel to Assignment: '), translate:print_subst(b(parallel(Statements),subst,I)),nl
2223 ; true),
2224 (Rest == [] -> Result = assign(LHS,RHS)
2225 ; Result = parallel([b(assign(LHS,RHS),subst,[])|Rest])).
2226 %translate:print_subst(b(Result,subst,I)),nl.
2227 cleanup_post(select([CHOICE|Rest]),subst,I0,S,subst,Info,single/remove_select) :-
2228 Rest = [], % SELECT can have multiple true branches
2229 CHOICE=b(select_when(TRUTH,Subst),subst,_),
2230 is_truth(TRUTH),!,
2231 debug_println(19,'Removing useless SELECT'),
2232 get_texpr_expr(Subst,S),get_texpr_info(Subst,I1),
2233 add_hint_message(remove_select,'Removing useless SELECT','',I1),
2234 add_important_info_from_super_expression(I0,I1,Info).
2235 cleanup_post(select([CHOICE|Rest],_ELSE),subst,OldInfo,Res,subst,I,single/remove_select_else) :-
2236 CHOICE=b(select_when(TRUTH,Subst),subst,_),
2237 is_truth(TRUTH),!,
2238 (Rest = [] % completely useless SELECT
2239 -> add_hint_message(remove_select_else,'Removing useless SELECT','',OldInfo),
2240 get_texpr_expr(Subst,Res),get_texpr_info(Subst,I1),
2241 add_important_info_from_super_expression(OldInfo,I1,I)
2242 ; add_hint_message(remove_select_else,'Removing useless SELECT ELSE branch','',OldInfo),
2243 Res = select([CHOICE|Rest]), I=OldInfo).
2244 cleanup_post(let_expression([],[],TExpr),Type,I0,Expr,Type,I,multi/remove_let_expression) :- !,
2245 % remove trivial let expressions without any introduced identifiers
2246 % this rule makes only sense in combination with the next rule which removes
2247 % simple let identifiers
2248 get_texpr_expr(TExpr,Expr),
2249 get_texpr_info(TExpr,I1),
2250 add_important_info_from_super_expression(I0,I1,I).
2251 cleanup_post(let([],Pred,TExpr),Type,I0,Expr,Type,I,multi/remove_let) :- is_truth(Pred),!,
2252 % remove trivial let expressions without any introduced identifiers
2253 % this rule makes only sense in combination with the next rule which removes
2254 % simple let identifiers
2255 get_texpr_expr(TExpr,Expr),
2256 get_texpr_info(TExpr,I1),
2257 add_important_info_from_super_expression(I0,I1,I).
2258 cleanup_post(let_expression(TIds,Exprs,Expr),Type,I,
2259 let_expression(NIds,NExprs,NExpr),Type,I,multi/remove_let_expression2) :-
2260 ? simplify_let(TIds,Exprs,Expr,NIds,NExprs,NExpr),!,
2261 %format('~n Simplified Let ~w --> ~w~n',[TIds,NIds]),
2262 true.
2263 cleanup_post(let_predicate(TIds,Exprs,Body),Type,I,
2264 let_predicate(NIds,NExprs,NBody),Type,I,multi/remove_let_predicate2) :-
2265 ? simplify_let(TIds,Exprs,Body,NIds,NExprs,NBody),!,
2266 %format('~n Simplified Let ~w --> ~w~n',[TIds,NIds]),
2267 (is_truth(NBody) -> print(useless_let),nl,nl ; true).
2268 cleanup_post(let_predicate(TIds,Exprs,Body),Type,I,
2269 NewExpr,Type,NewI,single/useless_let_message_or_removal) :-
2270 is_truth(Body),
2271 nonmember(useless_let,I),
2272 get_texpr_ids(TIds,Ids),
2273 TE=b(let_predicate(TIds,Exprs,Body),Type,I),
2274 (always_well_defined_or_wd_improvements_allowed(TE)
2275 -> NewExpr = truth, delete(I,contains_wd_condition,NewI),
2276 (always_well_defined_or_disprover_mode(TE)
2277 -> true
2278 ; add_message(b_ast_cleanup,'Removing useless existentially quantified variables: ',Ids,TIds)
2279 )
2280 ; NewExpr = let_predicate(TIds,Exprs,Body), NewI=[useless_let|I],
2281 TIds= [TID1|_], get_texpr_info(TID1,BInfo),
2282 nonmember(generated_exists_parameter,BInfo),
2283 % otherwise this was generated programmatically, e.g., in get_operation_enabling_condition, see test 625
2284 (nonmember(allow_to_lift_exists,I) -> true % ditto, e.g., by create_outer_exists_for_dom_range, see test 1945
2285 ; get_preference(data_validation_mode,true)),
2286 add_message(b_ast_cleanup,'Useless existentially quantified variables: ',Ids,TIds)
2287 ).
2288 % was disabled because simplify_let_subst also replaced in RHS of assignments
2289 % but now we check that a LET/ANY variable cannot be assigned to statically
2290 % so it should be safe now to replace simple equalities:
2291 cleanup_post(let(Ids,Pred,Subst),Type,I,
2292 let(NIds,NPred,NSubst),Type,I,multi/remove_let_subst2) :-
2293 simplify_let_subst(Ids,Pred,Subst,NIds,NPred,NSubst),! ,
2294 true. % translate:print_subst(b(let(NIds,NPred,NSubst),subst,[])),nl.
2295 /* this is not used currently; as the generic code's performance has been improved
2296 and better propagation is ensured by b_compute_arith_expression which (partially) instantiates its argument (known to be an integer)
2297 cleanup_post(ArithPredicate,pred,Info,ArithPredicate,pred,NewInfo,single/add_arith_pred_info) :-
2298 comparison(ArithPredicate,LHS,RHS,_,_,_),
2299 \+ clpfd_arith_integer_expression(LHS),
2300 \+ clpfd_arith_integer_expression(RHS),
2301 !,
2302 % store the information that there is no use in doing b_compute_arith_expression special treatment
2303 NewInfo = [no_clpfd_arith_integer_expression|Info].
2304 */
2305
2306 cleanup_post(forall([ID],LHS,RHS),pred,IOld,Res,pred,IOld,single/expand_forall_set_extension) :-
2307 % expand !x.(x:{a,b,...} => RHS) into conjunction
2308 % can be useful e.g. for KODKOD when we pick an element from a set of sets
2309 \+ preferences:has_default_value(use_solver_on_load), % prob, used to be only enabled in Kodkod mode
2310 % TO DO: enable always; but maybe check that set_extension can be computed (which eval_set_extension will do) to avoid duplicating checks (!y.(y:{v,w} => expensive_pred) + what if v=w
2311 nonmember(do_not_optimize_away,IOld),
2312 get_texpr_expr(LHS,member(ID2,Set)),
2313 same_texpr(ID,ID2),
2314 is_set_extension(Set,SList),
2315 get_texpr_id(ID,AID),
2316 debug_format(19,'Expanding forall ~w ',[AID]),
2317 findall(C, (member(SEL,SList),replace_id_by_expr(RHS,AID,SEL,C)),Conjuncts),
2318 conjunct_predicates_with_pos_info(Conjuncts,ExpandedForAll),
2319 (silent_mode(on) -> true ; print_bexpr(ExpandedForAll),nl),
2320 get_texpr_expr(ExpandedForAll,Res).
2321 cleanup_post(forall(Ids1,LHS,RHS),pred,IOld,
2322 forall(Ids,NewLHS,NewRHS),pred,INew,multi/merge_forall) :-
2323 is_truth(LHS),
2324 RHS = b(forall(Ids2,NewLHS,NewRHS),pred,_),
2325 %((member(b(identifier(_),Type,_),Ids1), is_infinite_ground_type(Type)) -> true), % could be useful for tests 1441, 1447 ??
2326 (disjoint_ids(Ids1,Ids2)
2327 -> append(Ids1,Ids2,Ids),
2328 % !x.(truth => !y.(P=>Q) <==> !(x,y).(P=>Q)
2329 (debug_mode(off) -> true ; format('Merging forall ~w: ',[Ids]), print_bexpr(NewLHS),nl),
2330 add_removed_typing_info(IOld,INew)
2331 ; \+ preferences:get_preference(disprover_mode,true),
2332 translate:translate_bexpression(b(forall(Ids1,LHS,RHS),pred,IOld),PS),
2333 add_warning(b_ast_cleanup,'Variable clash in nested universal quantification: ',PS,IOld),
2334 fail
2335 ).
2336 cleanup_post(forall(Ids,LHS,RHS),pred,IOld,
2337 implication(Outer,FORALL),pred,IOld,single/detect_global_preds_forall1) :-
2338 % !x.(P(x) & Q => R(x) <==> Q => !x.(P(x) => R(x))
2339 % TO DO: maybe we should not lift things like printf, ... ?
2340 bsyntaxtree:detect_global_predicates(Ids,LHS,Outer,Inner),
2341 (debug_mode(off) -> true ; format('Lifting predicate (lhs) of forall ~w: ',[Ids]), print_bexpr(Outer),nl),
2342 construct_inner_forall(Ids,Inner,RHS,IOld,FORALL).
2343 % TO DO: implement similar lifting rules for exists(Ids,P)
2344 cleanup_post(forall(Ids,LHS,RHS),pred,IOld,
2345 conjunct(Outer,FORALL),pred,IOld,single/detect_global_preds_forall2) :-
2346 is_truth(LHS),
2347 % !x.(truth => Q & R(x) <==> Q & !x.(truth => R(x))
2348 bsyntaxtree:detect_global_predicates(Ids,RHS,Outer,Inner),
2349 (debug_mode(off) -> true ; format('Lifting predicate (rhs &) of forall ~w: ',[Ids]), print_bexpr(Outer),nl),
2350 construct_inner_forall(Ids,LHS,Inner,IOld, FORALL). % print_bexpr(FORALL),nl,nl.
2351 cleanup_post(forall(Ids,LHS,RHS),pred,IOld,
2352 implication(Outer,FORALL),pred,IOld,single/detect_global_preds_forall3) :-
2353 is_truth(LHS),
2354 RHS = b(implication(RHS1,RHS2),pred,_),
2355 % !x.(truth => (Q & R(x) => S(x)) <==> Q => !x.(truth => R(x) => S(x))
2356 bsyntaxtree:detect_global_predicates(Ids,RHS1,Outer,Inner),
2357 create_implication(Inner,RHS2,NewRHS),
2358 (debug_mode(off) -> true ; format('Lifting predicate (rhs =>) of forall ~w: ',[Ids]), print_bexpr(Outer),nl),
2359 construct_inner_forall(Ids,LHS,NewRHS,IOld, FORALL).
2360 cleanup_post(forall([TID1,TID2|OTHER],LHS,RHS),pred,IOld,
2361 forall([TID1,TID2|OTHER],NewLHS,RHS),pred,[prob_symmetry(ID1,ID2)|IOld],single/symmetry_detection) :-
2362 % DETECT Symmetries such as !(x,y).(x /= y => x=TRUE or y=TRUE)
2363 % !(x2,y).(x2 /= y & x2:s & y:s => x2=aa or y=aa)
2364 % f:1..n --> 1..(n-1) & !(x,y).(x/=y &x:dom(f) & y:1..n => f(x) /= f(y)) & n=9 (runtime 1 sec -> 0.78 sec)
2365 get_texpr_type(TID1,T), get_texpr_type(TID2,T),
2366 \+ preferences:get_preference(use_solver_on_load,kodkod), % e.g., Kodkod cannot properly deal with LEQ_SYM_BREAK, treats it like truth
2367 preferences:get_preference(use_static_symmetry_detection,true),
2368 sym_break_supported_type(T), % LEQ_SYM_BREAK not yet fully functional with SET types; TO DO: fix
2369 get_texpr_id(TID1,ID1), get_texpr_id(TID2,ID2),
2370 nonmember(prob_symmetry(ID1,ID2),IOld),
2371 rename_bt(LHS,[rename(ID1,ID2),rename(ID2,ID1)],LHS2),
2372 same_norm_texpr(LHS,LHS2),
2373 rename_bt(RHS,[rename(ID1,ID2),rename(ID2,ID1)],RHS2),
2374 same_norm_texpr(RHS,RHS2),
2375 construct_sym_break(T,TID1,TID2,LHS,SYMBREAK),
2376 conjunct_predicates_with_pos_info(LHS,SYMBREAK,NewLHS),
2377 (debug_mode(off) -> true
2378 ; format('SYMMETRY BREAKING FORALL: !(~w,~w).(',[ID1,ID2]),print_bexpr(NewLHS),
2379 print(' => '), print_bexpr(RHS),print(')'),nl).
2380 cleanup_post(forall(AllIds,P,Rhs),pred,I,NewPred,pred,INew,multi/forall_splitting) :-
2381 AllIds = [TID1|TRestIDs], TRestIDs = [_|_], % TO DO: maybe not require that TID1 is the first id
2382 get_preference(use_clpfd_solver,true), % with CLPFD false: maybe more likely to reduce performance
2383 % NOTE: we could destroy symmetry reduction detection if TRestIDs = [TID2], but we run after symmetry detection
2384 % !(x,y,...).(x:SET & RestPred => Rhs) == !x.(x:SET => !(y,..).(RestPred => Rhs))
2385 conjunction_to_list(P,[MEM|RestPreds]),
2386 is_membership(MEM,TID,Set),
2387 same_id(TID1,TID,ID),
2388 \+ definitely_infinite(Set), % prevent !(x,y).(x:NATURAL & x<10 & y :1..x => x+y<20)
2389 %\+ known_set(Set), % rewriting makes sense if Set is not fully known and will be instantiated during solving
2390 % used to prevent known sets, but rewriting also useful for known sets (QueensWithEvents_ForallTest2b)
2391 get_sorted_ids(TRestIDs,RestIDs),
2392 not_occurs_in_predicate(RestIDs,Set),
2393 NewPred = forall([TID1],MEM,InnerForall),
2394 conjunct_predicates_with_pos_info(RestPreds,InnerForallLhs),
2395 construct_inner_forall(TRestIDs,InnerForallLhs,Rhs,I,InnerForall),
2396 !,
2397 delete(I,used_ids(_),I1), % should in principle still be ok at outer level; but just be sure
2398 add_removed_typing_info(I1,INew),
2399 (debug_mode(on) -> format('FORALL SPLITTING ~w (from ~w) for better propagation: ',[ID,RestIDs]),
2400 print_bexpr(b(NewPred,pred,INew)),nl
2401 ; true).
2402 cleanup_post(exists([TID],MemPred),pred,IOld,
2403 Res,pred,IOld, single/replace_exists_by_not_empty) :-
2404 % simplify #ID.(ID:E) <=> E /= {}
2405 % simplify #ID.(ID:E1 & ID:E2) <=> E1 /\ E2 /= {} , etc...
2406 % important e.g. for y:20..30000000000 & not(#x.(x:1..10 & x:8..y))
2407 ? is_valid_id_member_check(MemPred,TID,E),
2408 !,
2409 (definitely_not_empty_set(E) -> Res= truth
2410 ; get_texpr_type(E,Type), EmptySet=b(empty_set,Type,[]),
2411 Res = not_equal(E,EmptySet)),
2412 (debug_mode(off) -> true
2413 ; get_texpr_id(TID,ID),
2414 format('Removing existential quantifier: ~w~n',[ID]),
2415 print_bexpr(b(Res,pred,IOld)),nl).
2416 cleanup_post(exists([TID],b(NotMemPred,_,_)),pred,IOld,
2417 not_equal(E,TypeExpr),pred,IOld, single/replace_exists_by_not_full) :-
2418 % simplify #ID.(ID/:E) <=> E /= FullType
2419 % important e.g. for y:7..30000000000 & not(#x.(x /: 1..y))
2420 is_not_member(NotMemPred,MID,E),
2421 same_id(TID,MID,SID),
2422 % + check that MID does not occur in E
2423 \+ occurs_in_expr(SID,E),
2424 get_texpr_type(E,SType),
2425 is_set_type(SType,Type),
2426 create_maximal_type_set(Type,TypeExpr), % Note: no longer introduces identifiers but value(.) results
2427 !,
2428 (debug_mode(off) -> true
2429 ; format('Removing existential quantifier: ~w~n',[SID]),
2430 print_bexpr(b(not_equal(E,TypeExpr),pred,IOld)),nl).
2431 cleanup_post(exists([TID],b(Pred,_,_)),pred,IOld,
2432 truth,pred,IOld, single/replace_exists_by_truth) :-
2433 b_interpreter_check:arithmetic_op(Pred,_Op,X,Y),
2434 ( (same_id(TID,X,SID), \+ occurs_in_expr(SID,Y), always_well_defined_or_disprover_mode(Y)) ;
2435 (same_id(TID,Y,SID), \+ occurs_in_expr(SID,X), always_well_defined_or_disprover_mode(X))
2436 ),
2437 !, % we have a formula of the form #SID.(SID > Expr); provided Expr is well-defined, this is always true
2438 (debug_mode(off) -> true
2439 ; format('Removing existential quantifier: ~w~n',[SID]),
2440 print_bexpr(b(Pred,pred,[])),nl).
2441 cleanup_post(exists([TID1,TID2|OTHER],RHS),pred,IOld,
2442 exists([TID1,TID2|OTHER],NewRHS),pred,[prob_symmetry(ID1,ID2)|IOld],single/symmetry_detection) :-
2443 % DETECT Symmetries such as #(x,y).(x /= y & (x=TRUE or y=TRUE))
2444 % #(x2,y).(x2 /= y & x2:s & y:s & x2=aa or y=aa)
2445 get_texpr_type(TID1,T), get_texpr_type(TID2,T),
2446 \+ preferences:get_preference(use_solver_on_load,kodkod),
2447 preferences:get_preference(use_static_symmetry_detection,true),
2448 sym_break_supported_type(T), % LESS not yet fully functional with SET types; TO DO: fix
2449 get_texpr_id(TID1,ID1), get_texpr_id(TID2,ID2),
2450 nonmember(prob_symmetry(ID1,ID2),IOld),
2451 ? \+(contains_equality(TID1,TID2,RHS)), % IDs are already equal; no use in sym breaking
2452 rename_bt(RHS,[rename(ID1,ID2),rename(ID2,ID1)],RHS2),
2453 same_norm_texpr(RHS,RHS2),
2454 construct_sym_break(T,TID1,TID2,RHS,SYMBREAK),
2455 conjunct_predicates_with_pos_info(RHS,SYMBREAK,NewRHS),
2456 (debug_mode(off) -> true
2457 ; format('SYMMETRY BREAKING EXISTS: #(~w,~w).(',[ID1,ID2]),print_bexpr(NewRHS),print(')'),nl).
2458 cleanup_post(Expr,T,I1,NewExpr,T,I1,single/detect_lambda_result_quant_auto) :-
2459 construct_for_find_do_not_enumerate(Expr,KIND,TIds,Body,NewExpr,NewBody),
2460 perform_do_not_enumerate_analysis(TIds,Body,KIND,I1,NewBody).
2461 % sort args of commutative operators by term size
2462 cleanup_post(Expr, Type, I, NExpr, Type, NI, single/normalize_commutative_args) :-
2463 preferences:get_preference(normalize_ast_sort_commutative, true),
2464 sort_commutative_args(Expr, I, NExpr, NI).
2465 %,(NExpr=Expr -> true ; print('COMMUTE: '), translate:print_bexpr(b(Expr,Type,I)),nl, print(' TO: '), translate:print_bexpr(b(NExpr,Type,NI)),nl).
2466 %% COMMENT IN NEXT LINE TO CHECK validity of AST per NODE (helps find bugs)
2467 %%cleanup_post(Expr,pred,I,Expr,pred,I,single/checked) :- check_ast(true,b(Expr,pred,I)),fail.
2468 %%
2469 cleanup_post(Expr, pred, I, Expr, pred, [DI|I], single/detect_prob_ignore) :-
2470 ? get_info_labels(I,Labels), member(Label,Labels),
2471 is_prob_ignore_label(Label),
2472 !,
2473 DI=description('prob-ignore'), % detected by info_has_ignore_pragma/1
2474 nonmember(DI,I),
2475 add_message(detect_prob_ignore,'Detected prob-ignore label: ',Label,I).
2476
2477 is_prob_ignore_label(Label) :-
2478 atom_codes(Label,Cs),
2479 IGNORE = [112,114,111,98,DASH,105,103,110,111,114,101|_],
2480 % used to be: append("prob-ignore",_,IGNORE), but Rodin editor sometimes puts Dash 8722 rather than 45 in label
2481 suffix(Cs,IGNORE), % accept prob-ignore somewhere in the label
2482 member(DASH,[45, 8722, 95, 46, 32, 126, 61, 43, 35]). % "--_. ~=+#"
2483 % used to call reverse and match "erongi-borp"
2484
2485 cleanup_post_function(Override,X,_Type,I0,Res,Info,multi/function_override) :-
2486 preferences:get_preference(disprover_mode,true), % only applied in Disprover mode as it can remove WD problem; TO DO make it also applicable in normal mode
2487 get_texpr_expr(Override,overwrite(_F,SEXt)),
2488 SEXt = b(set_extension(LIST),_,_),
2489 member(b(couple(From,To),_,_),LIST),
2490 same_texpr(From,X),
2491 % ( F <+ { ... X|->To ...}) (X) ==> To
2492 %print_bexpr(b(function(Override,X),Type,_I)), print(' ==> '), print_bexpr(To),nl,
2493 !,
2494 get_texpr_expr(To,Res),
2495 get_texpr_info(To,I1),
2496 add_important_info_from_super_expression(I0,I1,Info).
2497 cleanup_post_function(Override,X,Type,Info,Res,Info,multi/function_override_ifte) :-
2498 preferences:get_preference(disprover_mode,true), % only applied in Disprover mode as it can remove WD
2499 % TO DO: should we do this generally? or simply deal with overwrite symbolically always?
2500 get_texpr_expr(Override,overwrite(F,SEXt)),
2501 SEXt = b(set_extension([Couple]),_,_),
2502 Couple = b(couple(From,To),_,_),
2503 % (f <+ {A|->B}) (x) -> if_then_else(x=A,B,f(x)) ; avoids having to explicitly compute f<+{A|->B}
2504 Res = if_then_else(EqXFrom,To,FX),
2505 safe_create_texpr(equal(X,From),pred,EqXFrom),
2506 safe_create_function_call(F,X,Type,Info,FX).
2507 cleanup_post_function(SEXt,ARG,_Type,I0,Res,Info,multi/function_set_extension) :-
2508 SEXt = b(set_extension(LIST),_,ListInfos), % TO DO: also support b(value(avl_set(A)),_,_)
2509 eval_set_extension_element(ARG,Value),
2510 ? select(b(couple(LHS,RHS),_,_),LIST,REST),
2511 (member(contains_wd_condition,ListInfos) % then we could remove WD problem, e.g., r = {1|->2, 2|-> 1/0}(1)
2512 -> (preferences:preference(find_abort_values,false) ;
2513 preferences:get_preference(disprover_mode,true))
2514 ; true),
2515 eval_set_extension_element(LHS,Value), %nl,print(found(RHS)),nl,
2516 % WE NEED TO Check that all LHS can be compared against ARG
2517 \+ member((b(couple(LHS2,_),_,_),REST),eval_set_extension_element(LHS2,Value)), % no other potential match
2518 \+ member((b(couple(LHS3,_),_,_),LIST), \+ eval_set_extension_element(LHS3,_)), % all left-hand-sides can be evaluated
2519 !, get_texpr_expr(RHS,Res), get_texpr_info(RHS,I1),
2520 add_important_info_from_super_expression(I0,I1,Info).
2521 % Detect if_then_else in format as printed by pp_expr2(if_then_else( ....)...) or as generated by B2TLA:
2522 cleanup_post_function(IFT,DUMMYARG,_Type,Info,if_then_else(IFPRED,THEN,ELSE),Info,multi/function_if_then_else) :-
2523 is_if_then_else(IFT,post,DUMMYARG,IFPRED,THEN,ELSE),
2524 (debug_mode(off) -> true
2525 ; print('% Recognised if-then-else expression: IF '), print_bexpr(IFPRED),
2526 print(' THEN '),print_bexpr(THEN), print(' ELSE '),print_bexpr(ELSE),nl
2527 ).
2528 cleanup_post_function(Composition,X,Type,Info,NewExpr,Info,multi/function_composition) :-
2529 (data_validation_mode ;
2530 get_preference(convert_comprehension_sets_into_closures,true)
2531 % there it can make a big difference in particular since relational composition (rel_composition_wf -> rel_compose_with_inf_fun case) was not fully symbolic; see Systerel data validation examples
2532 ),
2533 % (F;G)(X) --> G(F(X)) (F;G;H)(X) --> H(G(F(X))) ...
2534 peel_rel_composition(Composition,Type,Info,X,Result,Level),
2535 Level>0,
2536 Result = b(NewExpr,_,_),
2537 %check_ast(Result), % <---
2538 (debug_mode(off) -> true
2539 ; format('Function application of COMPOSITION (Nesting: ~w) translated to: ',[Level]),print_bexpr(Result),nl).
2540 cleanup_post_function(Fun,Arg,_Type,Info,function(Fun,Arg),NewInfo,single/function_inversion_annotation) :-
2541 data_validation_mode, % TODO: activate in general
2542 limited_propagation(Arg),
2543 NewInfo = [prob_annotation('INVERSION_PENALTY')|Info],
2544 (debug_mode(off) -> true
2545 ; add_message(ast_cleanup,'Function application not suited for propagation from result to argument: ',Arg,Info)).
2546
2547 % statically detect whether there is potential for propagating result values onto these expressions
2548 limited_propagation(b(Expr,_,_)) :- limited_prop_aux(Expr).
2549 limited_prop_aux(function(_,_)). % we need to propagate through at least one more function call
2550 limited_prop_aux(composition(_,_)). % argument is a function, composed of two other functions
2551 limited_prop_aux(iteration(_,_)).
2552 limited_prop_aux(record_field(Rec,_)) :- limited_propagation(Rec). % we only know part of the record; TODO: add a penalty even if Rec allows propagation
2553 %limited_prop_aux(external_function_call(_,_)). % MU probably ok, for other funs it depends
2554 limited_prop_aux(couple(A,B)) :-
2555 (limited_propagation(A)
2556 -> % back propagation on A not useful,
2557 (limited_propagation(B) -> true % back propagation on both arguments is not useful
2558 ; is_constant(B) % B is a constant and could only filter (if TRY_FIND_ABORT / find_abort_values false)
2559 )
2560 ; is_constant(A), limited_propagation(B) % what if both are a constant ?
2561 ).
2562 limited_prop_aux(minus(A,B)) :- (limited_propagation(A) -> true ; limited_propagation(B)).
2563 limited_prop_aux(add(A,B)) :- (limited_propagation(A) -> true ; limited_propagation(B)).
2564 limited_prop_aux(div(A,B)) :- (limited_propagation(A) -> true ; limited_propagation(B)).
2565 limited_prop_aux(multiplication(A,B)) :- (limited_propagation(A) -> true ; limited_propagation(B)).
2566 limited_prop_aux(let_expression(_,_,C)) :- limited_propagation(C).
2567 % TODO: detect more cases where propagating from result of function application to argument is of limited value
2568 % sequence operators: insert_tail, first, last, ..., sequence_extension (cf test 2387)
2569
2570 is_constant(b(C,_,_)) :- is_const_aux(C).
2571 is_const_aux(boolean_false).
2572 is_const_aux(boolean_true).
2573 is_const_aux(couple(A,B)) :- is_constant(A),is_constant(B).
2574 is_const_aux(empty_set).
2575 is_const_aux(empty_sequence).
2576 is_const_aux(integer(_)).
2577 is_const_aux(real(_)).
2578 is_const_aux(string(_)).
2579 % not covered yet: value(_) and record(_)
2580
2581
2582 % detect comprehension set or closure values
2583 is_comprehension_set(comprehension_set(TypedIds,Body),TypedIds,Body).
2584 is_comprehension_set(value(Closure),TypedIds,Body) :- nonvar(Closure),
2585 Closure = closure(P,T,Body),
2586 \+ custom_explicit_sets:is_interval_closure_or_integerset(Closure,_,_), % this is already a value
2587 % TO DO: also detect simple member closures like seq(0..1)
2588 maplist(create_typed_id,P,T,TypedIds).
2589
2590 cleanup_comprehension_set([TID],b(member(LHS,TSet),pred,_),Type,I,Set,I2,multi/remove_useless_comprehension_set) :-
2591 get_texpr_id(TID,ID),
2592 get_texpr_id(LHS,ID),
2593 % {ID|ID:Set} ==> Set
2594 not_occurs_in_expr(ID,TSet),
2595 TSet=b(Set,Type,I2),
2596 !,
2597 add_hint_message(remove_useless_comprehension_set,'Removing useless comprehension set over: ',ID,I).
2598 cleanup_comprehension_set([TID],Body,_Type,I,NewExpr,NewInfo,single/detect_seq_comprehension_set) :-
2599 get_texpr_id(TID,ID),
2600 % {ID | #LenID. (ID : 1..LenID --> Set)} ==> seq(Set)
2601 % {ID | #LenID. (ID : 1..LenID >-> Set)} ==> iseq(Set)
2602 get_texpr_expr(Body,exists([TLen],TIBody)),
2603 get_texpr_id(TLen,LenID), LenID \= ID,
2604 get_texpr_expr(TIBody,IBody),
2605 get_member(IBody,LenID,ISet,TID2,FUNCTION),
2606 get_texpr_id(TID2,ID),
2607 get_seq_fun_aux(FUNCTION,ISet,Interval,SeqTypeSet),
2608 get_texpr_expr(Interval,interval(ONE,TLen2)),
2609 get_texpr_id_with_offset(TLen2,LenID,Offset), % LenID or something like LenID-1
2610 get_integer(ONE,StartingIndex),!,
2611 (StartingIndex = 1, Offset=0 % TODO: check if a negative offset is always ok for all Seq Types
2612 -> add_hint_message(detect_seq_comprehension_set,'Detecting sequence operator: ',ID,I),
2613 NewExpr = SeqTypeSet, NewInfo=I
2614 ; % we have something sequence like but with indexes not starting at 1, maybe at 0
2615 % e.g. {ID | #LenID. (ID : 0..LenID-1 --> Set)}; happens in Soton/UML-B drone model
2616 add_hint_message(detect_seq_comprehension_set,'Marking sequence like operator as symbolic, indexes are not starting at 1: ',ID,I),
2617 NewExpr = comprehension_set([TID],Body),
2618 %add_texpr_infos(Body,[prob_annotation('SYMBOLIC')],Body2),
2619 add_info_if_new(I,prob_annotation('SYMBOLIC'),NewInfo)
2620 ).
2621 % {RANGE_LAMBDA__|#x.(x : dom(F) & RANGE_LAMBDA__ = F(x))} --> ran(F) // generated by TLC4B -> TLA2B
2622 % TO DO: detect {R|R:INTEGER & #D.(D|->R:F)} as ran(F)
2623 cleanup_comprehension_set([TID],Body, _Type, I, range(Func), I, multi/detect_tla_range_comprehension_set) :-
2624 Body = b(exists([DomTID],EBody),pred,_),
2625 EBody = b(conjunct(LHS,RHS),pred,_),
2626 is_membership(LHS,DomTID1,b(domain(Func),_,_)),
2627 same_id(DomTID,DomTID1,_),
2628 is_equality(RHS,TID1,FunCall),
2629 FunCall = b(function(Func1,DomTID2),_,_),
2630 same_id(TID,TID1,_),
2631 same_id(DomTID,DomTID2,_),
2632 same_texpr(Func,Func1),
2633 always_well_defined_or_disprover_mode(FunCall), % we could also allow TLA minor mode
2634 add_hint_message(detect_tla_range_comprehension_set,'Detected range set-comprehension: ',Func,I).
2635 cleanup_comprehension_set([TID],Pred,Type,I,
2636 struct(b(rec(NewFieldSets),record(FieldTypes),I)),
2637 I,single/simplify_record) :-
2638 % {r|r'a : 1..1000 & r'b : 1..100 & r:struct(a:INTEGER,b:NAT,c:BOOL)} --> struct(a:1..1000,b:1..100,c:BOOL)
2639 % these kind of set comprehensions are generated by ProZ, see ROZ example model.tex test 1858
2640 % TO DO: maybe generalise this optimisation: currently it only works if all predicates can be assimilated into struct expression
2641 TID = b(identifier(ID),record(FieldTypes),_),
2642 conjunction_to_list(Pred,PL),
2643 l_update_record_field_membership(PL,ID,[],FieldSetsOut),
2644 maplist(construct_field_sets(FieldSetsOut),FieldTypes,NewFieldSets),
2645 (debug_mode(off) -> true
2646 ; print('Detected Record set comprehension: '),
2647 print_bexpr(b(struct(b(rec(NewFieldSets),record(FieldTypes),I)),Type,I)),nl).
2648 cleanup_comprehension_set(Ids1,E,_Type,I,comprehension_set(Ids2,E2),I,single/detect_lambda) :-
2649 preferences:get_preference(detect_lambdas,true),
2650 % used to lead to *** Enumerating lambda result warnings for test 1162, not anymore
2651 % does not yet detect: f = {x,y|x:NATURAL & (x> 1 &y=x+2)} & res = f[3..4]
2652 E = b(conjunct(LHS,Equality),pred,Info),
2653 nonmember(prob_annotation('LAMBDA'),Info), % not already processed
2654 ? identifier_equality(Equality,ID,TID1,Expr1),
2655 last(Ids1,TID), get_texpr_id(TID,ID),
2656 not_occurs_in_expr(ID,Expr1),
2657 not_occurs_in_predicate([ID],LHS),
2658 !,
2659 get_texpr_info(Equality,EqInfo),
2660 get_unique_id_inside('_lambda_result_',LHS,Expr1,ResultId), % currently the info field lambda_result is not enough: several parts of the ProB kernel match on the identifier name '_lambda_result_'
2661 TID1 = b(identifier(_),Type1,Info1),
2662 add_texpr_infos(b(identifier(ResultId),Type1,Info1),[lambda_result(ResultId),lambda_result_id_was(ID)],TID2),
2663 Equality2 = b(equal(TID2,Expr1),pred,[prob_annotation('LAMBDA-EQUALITY')|EqInfo]),
2664 E2 = b(conjunct(LHS,Equality2),pred,[prob_annotation('LAMBDA')|Info]),
2665 append(Ids0,[_],Ids1),
2666 append(Ids0,[TID2],Ids2),
2667 % code exists which is simpler, but has disadvantage of losing position info for equality
2668 (debug_mode(off) -> true ; format('Lambda using ~w detected: ',[ID]),print_bexpr(E2),nl).
2669
2670
2671 % extract membership for ID and detect optional restrictions for Length identfier LenID
2672 get_member(conjunct(TA,TB),LenID,ISet,TID2,FUNCTION) :-
2673 get_texpr_expr(TA,A), % detect LenId : NATURAL(1)
2674 get_mem_of_integerset(A,LenID,ISet), % TO DO: detect LenID>0, or LenID /=0
2675 get_texpr_expr(TB,B),
2676 get_member1(B,TID2,FUNCTION).
2677 get_member(IBody,_,'NATURAL',TID2,F) :- get_member1(IBody,TID2,F).
2678 get_member1(member(TID2,b(FUNCTION,_,_)),TID2,FUNCTION).
2679
2680 get_mem_of_integerset(member(TID2,b(SET,_,_)),LenID,ISet) :- !,
2681 get_texpr_id(TID2,LenID),
2682 is_integer_set(SET,ISet).
2683 get_mem_of_integerset(Pred,LenID,ISet) :-
2684 is_integer_set_constraint_pred(Pred,LenID,ISet).
2685
2686
2687 get_texpr_id_with_offset(Expr,ID,0) :- get_texpr_id(Expr,ID).
2688 get_texpr_id_with_offset(b(add(TID,Expr),integer,_),ID,Offset) :-
2689 get_texpr_id(TID,ID), get_integer(Expr,Offset).
2690 get_texpr_id_with_offset(b(minus(TID,Expr),integer,_),ID,NegOffset) :-
2691 get_texpr_id(TID,ID), get_integer(Expr,Offset), NegOffset is -Offset.
2692
2693 get_seq_fun_aux(total_function(Interval,TargetSet),'NATURAL',Interval,seq(TargetSet)).
2694 get_seq_fun_aux(total_function(Interval,TargetSet),'NATURAL1',Interval,seq1(TargetSet)).
2695 get_seq_fun_aux(total_injection(Interval,TargetSet),'NATURAL',Interval,iseq(TargetSet)).
2696 get_seq_fun_aux(total_injection(Interval,TargetSet),'NATURAL1',Interval,iseq1(TargetSet)).
2697 get_seq_fun_aux(total_bijection(Interval,TargetSet),'NATURAL',Interval,perm(TargetSet)).
2698 get_seq_fun_aux(total_bijection(Interval,TargetSet),'NATURAL1',Interval,perm(TargetSet)) :-
2699 definitely_not_empty_set(TargetSet).
2700
2701 % --------------------------------
2702
2703 construct_for_find_do_not_enumerate(exists(TIds,Pred),'EXISTS',TIds,Pred,exists(TIds,Pred2),Pred2).
2704 construct_for_find_do_not_enumerate(any(TIds,Pred,Body),'ANY',TIds,Pred,any(TIds,Pred2,Body),Pred2) :-
2705 data_validation_mode. % as we do not examine Body of the Any, we do not know if there are additional constraints on TIds in the body
2706 % tests where ANYs would be annotated 471, 565, 808, 1196, 1489, 1850
2707
2708 % try and perform analysis for a body of either exists, any or set_comprehension
2709 perform_do_not_enumerate_analysis(TIds,Body,KIND,Span,NewBody) :-
2710 get_preference(perform_enumeration_order_analysis,true),
2711 get_texpr_info(Body,BI),
2712 nonmember(prob_annotation('DO_NOT_ENUMERATE'(_)),BI), % analysis was already performed or manually annotated
2713 find_do_not_enumerate_variables(TIds,Body,SortedVs,DelayVsInOrder),
2714 !,
2715 findall(prob_annotation('DELAY_ENUMERATION'(PosNr,DNID)),nth1(PosNr,DelayVsInOrder,DNID),I1),
2716 (SortedVs = []
2717 -> NewInfos = [prob_annotation('DO_NOT_ENUMERATE'('$$NONE$$'))|I1] % dummy marking to avoid running analysis again
2718 ; findall(prob_annotation('DO_NOT_ENUMERATE'(DNID)),member(DNID,SortedVs),NewInfos,I1)
2719 ),
2720 (debug_mode(off) -> true
2721 ; I1=[], SortedVs=[] -> true
2722 ; ajoin(['Annotating ',KIND,' identifiers with DO_NOT_ENUMERATE: '],Msg),
2723 %write(SortedVs),nl,
2724 add_message(detect_lambda_result_auto,Msg,SortedVs:DelayVsInOrder,Span)
2725 ),
2726 add_texpr_infos(Body,NewInfos,NewBody).
2727 perform_do_not_enumerate_analysis(_,Body,_,_,Body).
2728
2729 :- public check_do_not_enum_result/2.
2730 % check if there is a difference with stored result in info field if it exists
2731 check_do_not_enum_result(NewInfos,BInfo) :- member(prob_annotation('DO_NOT_ENUMERATE'(_)),BInfo),!,
2732 findall(DNID,
2733 (member(prob_annotation('DO_NOT_ENUMERATE'(DNID)),BInfo), DNID \= '$$NONE$$'), OldIds),
2734 findall(DNID,
2735 (member(prob_annotation('DO_NOT_ENUMERATE'(DNID)),NewInfos), DNID \= '$$NONE$$'), NewIds),
2736 (OldIds = NewIds
2737 -> format('Same DO_NOT_ENUMERATE result: ~w~n',[OldIds])
2738 ; format('Difference in DO_NOT_ENUMERATE result:~nOLD: ~w~nNEW: ~w~n',[OldIds,NewIds])
2739 ).
2740 check_do_not_enum_result(_,_).
2741
2742 % --------------------
2743
2744 % we only sort at the top-level, as cleanup_post will work its way bottom-up:
2745 sort_commutative_args(Expr, I, Sorted, NI) :- nonvar(Expr),
2746 functor(Expr, Functor, 2),
2747 is_commutative(Functor),
2748 !,
2749 arg(1, Expr, Lhs),
2750 arg(2, Expr, Rhs),
2751 remove_all_infos_and_ground(Lhs,CNLhs), % remove infos for comparison
2752 remove_all_infos_and_ground(Rhs,CNRhs),
2753 get_texpr_expr(CNLhs,N1),
2754 get_texpr_expr(CNRhs,N2),
2755 ( N1 @> N2
2756 -> Sorted =.. [Functor,Rhs,Lhs],
2757 NI = [was(Expr)|I]
2758 ; Sorted =.. [Functor,Lhs,Rhs],
2759 NI = I
2760 ).
2761
2762
2763 is_commutative(conjunct).
2764 is_commutative(disjunct).
2765 is_commutative(equivalence).
2766 is_commutative(equal).
2767 is_commutative(not_equal).
2768 is_commutative(add).
2769 is_commutative(multiplication).
2770 is_commutative(union).
2771 is_commutative(intersection).
2772
2773 % --------------------
2774
2775 factor_disjunct(CEquality1,CEquality2,IOld,New,INew) :-
2776 % (x=2 & y=3) or (x=2 & y=4) -> x=2 & (y=3 or y=4) to improve constraint propagation
2777 Blacklist=[],
2778 conjunction_to_list(CEquality1,Preds1),
2779 conjunction_to_list(CEquality2,Preds2),
2780 ? select_equality(TId1,Preds1,Blacklist,TEqual,Expr1,RestPreds1,_,check_well_definedness), % also allow other preds, use safe_select(check_well_definedness,TEqual,Preds,Rest),
2781 get_texpr_id(TId1,Id),
2782 get_texpr_id(TId2,Id),
2783 ? select_equality(TId2,Preds2,Blacklist,_,Expr2,RestPreds2,_,check_well_definedness),
2784 same_texpr(Expr1,Expr2),
2785 conjunct_predicates_with_pos_info(RestPreds1,P1),
2786 conjunct_predicates_with_pos_info(RestPreds2,P2),
2787 % TO DO: do not recursively start from scratch in P1, one should start from the right of CEquality1:
2788 (fail, % disable recursive looking
2789 factor_disjunct(P1,P2,IOld,P12,INew) -> NewDisj = b(P12,pred,INew)
2790 ; disjunct_predicates_with_pos_info(P1,P2,NewDisj)),
2791 conjunct_predicates_with_pos_info(TEqual,NewDisj,NewPred),
2792 NewPred=b(New,pred,I2),
2793 include_important_info_from_removed_pred(IOld,I2,INew).
2794
2795 % ------------------------------------------
2796
2797 gen_rename(TID1,TID2,rename(ID1,ID2)) :- def_get_texpr_id(TID1,ID1), def_get_texpr_id(TID2,ID2).
2798
2799 is_not_member(not_member(LHS,RHS),LHS,RHS).
2800 is_not_member(negation(b(member(LHS,RHS),pred,_)),LHS,RHS).
2801
2802
2803 :- use_module(typing_tools,[create_maximal_type_set/2]).
2804 is_valid_id_member_check(b(member(MID,E),_,_),ID,E) :- same_id(ID,MID,SID),
2805 % + check that MID does not occur in E
2806 \+ occurs_in_expr(SID,E).
2807 is_valid_id_member_check(b(truth,_,_),ID,TypeExpr) :-
2808 get_texpr_type(ID,SType),
2809 create_maximal_type_set(SType,TypeExpr). % Note: this no longer introduces identifiers, which could clash
2810 is_valid_id_member_check(b(conjunct(A,B),_,_),ID,Res) :-
2811 ? is_valid_id_member_check(A,ID,EA),
2812 ? is_valid_id_member_check(B,ID,EB),
2813 get_texpr_type(EA,Type),
2814 safe_create_texpr(intersection(EA,EB),Type,Res).
2815
2816 contains_equality(TID1,TID2,RHS) :-
2817 ? b_interpreter:member_conjunct(b(equal(A,B),pred,_),RHS,_),
2818 (same_id(A,TID1,_),same_id(B,TID2,_) ; same_id(A,TID2,_),same_id(B,TID1,_)).
2819
2820 simplify_let_subst(Ids,Pred,Subst,NIds,RestPred,NewSubst) :-
2821 % remove let identifiers whose definitions are very simple, i.e. identifiers
2822 Eq = b(equal(TypID,TExpr),pred,_),
2823 can_be_optimized_away(TypID),
2824 get_texpr_id(TypID,ToReplace),
2825 b_interpreter:member_conjunct(Eq,Pred,RestPred),
2826 is_simple_expression(TExpr),
2827 nth0(_N,Ids,TI,NIds),get_texpr_id(TI,ToReplace),
2828 !,
2829 % Intitially there was an issue as we may also replace in the LHS of assignments
2830 % see e.g. TestLet = LET cnt BE cnt=1 IN IF cnt=0 THEN ABORT ELSE cnt :: {0,1} END END; in SubstitutionLaws
2831 % However, now the static type checker rejects those assignments
2832 replace_id_by_expr(Subst,ToReplace,TExpr,NSubst),
2833 % TO DO: it seems like cleanup rules are not applied on NSubst, e.g., function for set_extension rules
2834 debug_println(9,replaced_let_subst_id(ToReplace)),
2835 (Subst==NSubst -> NewSubst=NSubst ; clean_up(NSubst,[],NewSubst)).
2836
2837 can_be_optimized_away(b(_,_,I)) :- nonmember(do_not_optimize_away,I).
2838
2839 %replace_in_rhs(ID,E,RHS,CleanNewRHS) :- replace_id_by_expr(RHS,ID,E,NewRHS), clean_up(NewRHS,[],CleanNewRHS).
2840
2841 can_be_replaced(RHS,_,Ids) :- get_texpr_id(RHS,RHSID),!,
2842 \+ (member(TID2,Ids), get_texpr_id(TID2,RHSID)). % ID occurs in Ids, replacing it in Expr will move the scope
2843 % example: Z Test (\LET x==1 @ (\LET x==x+1; y==x @ 7*x+y)) = 15
2844 can_be_replaced(_RHS,UsedIds,Ids) :- % TO DO: compute used ids
2845 %find_identifier_uses(RHS,[],UsedIds),
2846 get_texpr_ids(Ids,AtomicIds), sort(AtomicIds,SortedIds),
2847 \+ ord_intersect(UsedIds,SortedIds).
2848
2849
2850 simplify_let(Ids,Exprs,Expr,NIds,NExprs,CleanNewExpr) :-
2851 ? nth0(N,Ids,TId,NIds),
2852 get_texpr_id(TId,Id),
2853 can_be_optimized_away(TId),
2854 nth0(N,Exprs,LetExpr,NExprs),
2855 find_identifier_uses_if_necessary(LetExpr,[],LetExprIds),
2856 \+ ord_member(Id,LetExprIds), %\+ occurs_in_expr(Id,LetExpr), % illegal let, e.g., i = i+1;
2857 can_be_replaced(LetExpr,LetExprIds,Ids), % moving LetExpr will not produce scoping issues
2858 maplist(not_occurs_in_expr(Id),NExprs), % The ID is not used for defining other RHS in the same let
2859 simplify_let_aux(TId,Id,LetExpr,Expr,CleanNewExpr).
2860
2861 simplify_let_aux(_TId,Id,LetExpr,Expr,CleanNewExpr) :-
2862 % remove let identifiers whose definitions are very simple, i.e. identifiers
2863 is_simple_expression(LetExpr),
2864 % TId = LetExpr
2865 % TO DO: do not do this to outer variables which the user cares about !!
2866 !,
2867 %maplist(replace_in_rhs(Id,LetExpr),NExprs,NewExprs),
2868 replace_id_by_expr(Expr,Id,LetExpr,NExpr),
2869 clean_up(NExpr,[],CleanNewExpr). % clean up adjust eg used_ids info; necessary for test 568 in prob_safe_mode
2870 simplify_let_aux(TId,Id,LetExpr,Expr,CleanNewExpr) :-
2871 % push the let expression down the AST. E.g. "LET a=E IN (4*(a+z*a) + z)" would
2872 % be transformed to "4*(LET a=E IN (a+z*a)) + z"
2873 % If the final form is like "LET a=E IN a" it will be simplified to E.
2874 \+ do_not_to_move_let_inside(Expr),
2875 ( identifier_sub_ast(Expr,Id,SubPosition) ->
2876 prune_sub_ast_pos_list(SubPosition,Id,LetExpr,Expr,SafeSubPosition),
2877 SafeSubPosition = [_|_], % The LET can actually be moved down
2878 % SubPosition points to the highest point in the AST coveringa all occurences
2879 exchange_ast_position(SafeSubPosition,Expr,OldInner,NewInner,NExpr),
2880 get_texpr_type(OldInner,Type),
2881 ( get_texpr_id(OldInner,Id) -> % There is only one reference to Id,
2882 debug_format(19,'Simplified LET for ~w away, single usage~n',[Id]),
2883 NewInner = LetExpr % replace it with the expression
2884 % We need to check that we are not simply just exchanging lets with each other
2885 ; cycle_detection(Id,SafeSubPosition,Expr) -> debug_println(9,cycle(Id)),fail
2886 ; Type=pred -> % print(created_let_predicate(N,Id,SafeSubPosition,NIds)),nl,
2887 extract_important_info_from_subexpressions(LetExpr,OldInner,NewLetInfo), % maybe no longer necessary because of cleanups call below
2888 create_texpr(let_predicate([TId],[LetExpr],OldInner),pred,NewLetInfo,NewInner)
2889 ; % print(create_let_expression(TId)),nl,
2890 extract_important_info_from_subexpressions(LetExpr,OldInner,NewLetInfo), % maybe no longer necessary because of cleanups call below
2891 create_texpr(let_expression([TId],[LetExpr],OldInner),Type,NewLetInfo,NewInner)),
2892 clean_up(NExpr,[],CleanNewExpr) % maybe we only need WD post rules ?
2893 ; always_well_defined(LetExpr) -> % Id does not occur in the expression -> just remove the LET
2894 CleanNewExpr = Expr),!.
2895
2896 % this has to be checked not just at the top-level but along the SubPosition path
2897 do_not_to_move_let_inside(b(E,_T,Infos)) :-
2898 (do_not_to_move_let_inside_aux(E) -> true
2899 ; E=exists(_,_), (get_preference(lift_existential_quantifiers,true) ; member(allow_to_lift_exists,Infos))
2900 ).
2901 %add_message(simplify_let,'Not moving LET inside: ',b(E,_T,Infos),Infos).
2902 % exists can be lifted which can also lead to duplication allow_to_lift_exists
2903 % for those quantifiers we may duplicate the computation of a let by moving it inside:
2904 do_not_to_move_let_inside_aux(forall(_,_,_)). % otherwise we may compute the let multiple times
2905 do_not_to_move_let_inside_aux(comprehension_set(_,_)). % ditto
2906 do_not_to_move_let_inside_aux(general_product(_,_,_)). % ditto (PI)
2907 do_not_to_move_let_inside_aux(general_sum(_,_,_)). % ditto (SIGMA)
2908 do_not_to_move_let_inside_aux(lambda(_,_,_)). % ditto
2909 do_not_to_move_let_inside_aux(quantified_intersection(_,_,_)). % ditto
2910 do_not_to_move_let_inside_aux(quantified_union(_,_,_)). % ditto
2911 %do_not_to_move_let_inside_aux(exists(_,_)). % can lead to duplication upon lifting or semi-lifting, e.g., if two exists are nested?
2912 % TODO: investigate if we should disable moving LET into exists in general
2913 do_not_to_move_let_inside_aux(convert_bool(_)). % can lead to duplication if reification fails
2914
2915
2916 not_occurs_in_expr(Id,Expr) :- \+ occurs_in_expr(Id,Expr).
2917
2918 cycle_detection(Id,SubPosition,Expr) :-
2919 ? (get_constructor(SubPosition,Expr,CC),
2920 \+ let_constructor(CC) -> fail % at least one other constructor found
2921 ; debug_println(9,cycle_let_detection(Id))
2922 ).
2923 % we have a let constructor which can be modified by simplify_let:
2924 let_constructor(let_expression).
2925 let_constructor(let_predicate).
2926 let_constructor(let_substitution).
2927
2928 % traverse a SubPositions List from identifier_sub_ast and check for potential duplication
2929 % by quantifiers, if found: prune list at that point
2930 prune_sub_ast_pos_list([],_,_,_,[]).
2931 prune_sub_ast_pos_list([Pos|T],Id,LetExpr,OldTExpr,Res) :-
2932 remove_bt(OldTExpr,OldExpr,NewExpr,_NewTExpr),
2933 (do_not_to_move_let_inside(OldTExpr)
2934 -> Res=[],
2935 (debug_mode(off) -> true ; add_message(simplify_let,'Not moving LET inside quantifier/bool: ',Id,OldTExpr))
2936 ; Res = [Pos|TR],
2937 syntaxtransformation(OldExpr,Subs,_Names,_NSubs,NewExpr),
2938 nth0(Pos,Subs, OldSelected,_Rest),
2939 prune_sub_ast_pos_list(T,Id,LetExpr,OldSelected,TR),
2940 (TR=[], avoid_top_level_let_within(OldExpr)
2941 -> Res=[] % we would create a let at the top-level of this
2942 ; Res = [Pos|TR]
2943 )
2944 ).
2945
2946 avoid_top_level_let_within(card(_)). % reification of card does not work yet with top-level let_predicate, for test 1562
2947 % Note: maybe it is best to avoid pushing into card completely, as even at the next
2948 % level the let could disturb the reification small set detection?
2949
2950 % get a SubPosition path (as produced by identifier_sub_ast) and
2951 % generate upon backtracking all constructors that are used along the Path
2952 get_constructor([Pos|T],OldTExpr,ConstructorForPos) :-
2953 remove_bt(OldTExpr,OldExpr,NewExpr,_NewTExpr),
2954 (functor(OldExpr,ConstructorForPos,_)
2955 ; syntaxtransformation(OldExpr,Subs,_Names,_NSubs,NewExpr),
2956 nth0(Pos,Subs, OldSelected,_Rest),
2957 get_constructor(T,OldSelected,ConstructorForPos)
2958 ).
2959
2960 is_simple_expression(TExpr) :-
2961 get_texpr_expr(TExpr,Expr),
2962 is_simple_expression2(Expr),!.
2963 is_simple_expression(TExpr) :-
2964 is_just_type(TExpr).
2965 is_simple_expression2(identifier(_)).
2966 is_simple_expression2(integer(_)).
2967 is_simple_expression2(real(_)).
2968 is_simple_expression2(string(_)).
2969 is_simple_expression2(boolean_true).
2970 is_simple_expression2(boolean_false).
2971 is_simple_expression2(empty_set).
2972 is_simple_expression2(empty_sequence).
2973 %is_simple_expression2(interval(Low,Up)) :- is_simple_expression(Low), is_simple_expression(Up).
2974 % TODO: simple couples? simple records?
2975
2976 % a variation of is_simple_expression, allowing some simple constructs
2977 is_simple_expression_lvl(TExpr,Lvl) :-
2978 get_texpr_expr(TExpr,Expr),
2979 is_simple_expression2_lvl(Expr,Lvl),!.
2980 is_simple_expression2_lvl(Cons,Lvl) :- simple_binary_constructor(Cons,A,B), !,
2981 Lvl>0, L1 is Lvl-1,
2982 is_simple_expression_lvl(A,L1),is_simple_expression_lvl(B,L1).
2983 is_simple_expression2_lvl(Cons,Lvl) :- simple_unary_constructor(Cons,A),!,
2984 Lvl>0, L1 is Lvl-1,
2985 is_simple_expression_lvl(A,L1).
2986 is_simple_expression2_lvl(E,_) :- is_simple_expression2(E).
2987
2988 simple_binary_constructor(function(A,B),A,B).
2989 simple_binary_constructor(couple(A,B),A,B).
2990 % TODO: simple records?
2991 simple_unary_constructor(reverse(A),A).
2992 simple_unary_constructor(set_extension([A]),A).
2993 simple_unary_constructor(sequence_extension([A]),A).
2994
2995 % check for duplication of complex LHS expressions by replacing ID with LHS NrOccurences of times for Rule
2996 is_replace_id_by_expr_ok(_LHS,_ID,NrOccurences,_Rule) :- NrOccurences < 2.
2997 is_replace_id_by_expr_ok(_LHS,_ID,_,_Rule) :-
2998 get_preference(normalize_ast,true),!. % is necessary at least for remove_member_comprehension, remove_not_member_comprehension
2999 is_replace_id_by_expr_ok(_LHS,_ID,_,_Rule) :-
3000 get_preference(use_common_subexpression_elimination,true),!.
3001 is_replace_id_by_expr_ok(LHS,_ID,NrOccurences,_Rule) :-
3002 (NrOccurences<3 -> Lvl=2 ; NrOccurences<6 -> Lvl=1 ; Lvl=0), % what heuristic should we use here; test 1750 seems to indicate that Lvl=4 would still be beneficial for NrOccurences=2 and lambda_guard1 rule
3003 is_simple_expression_lvl(LHS,Lvl).
3004 is_replace_id_by_expr_ok(LHS,ID,Count,Rule) :-
3005 debug_mode(on),
3006 format('replace ~w (~w times) not ok for ~w using: ',[ID,Count,Rule]), translate:print_bexpr(LHS),nl,fail.
3007
3008
3009 % detect either Event-B identity or id over full type
3010 is_event_b_identity(b(X,_,_)) :- is_event_b_identity_aux(X).
3011 is_event_b_identity_aux(event_b_identity).
3012 is_event_b_identity_aux(identity(T)) :- is_just_type(T).
3013
3014 :- use_module(library(avl),[avl_member/2]).
3015 % check if we have a set extension and return list of terms
3016 is_set_extension(b(S,T,I),L) :- is_set_extension_aux(S,T,I,L).
3017 is_set_extension_aux(set_extension(L),_,_,L).
3018 % TO DO: detect sequence_extension
3019 is_set_extension_aux(value(avl_set(A)),SetType,I,L) :- % computed by eval_set_extension
3020 is_set_type(SetType,Type),
3021 findall(b(value(M),Type,I),avl_member(M,A),L).
3022
3023 is_sequence_extension(b(S,T,I),L) :- is_sequence_extension_aux(S,T,I,L).
3024 is_sequence_extension_aux(sequence_extension(L),_,_,L).
3025 % TO DO: detect value/set_extensions
3026
3027 recursion_detection_enabled(A,B,I) :-
3028 ? (recursion_detection_enabled_aux(A,B,I) -> true).
3029 recursion_detection_enabled_aux(A,_B,I) :-
3030 animation_mode(b), % in B mode,
3031 memberchk(section(properties),I), % the rule should be only applied to properties
3032 % and where A is an abstract constant.
3033 get_texpr_info(A,AInfo),memberchk(loc(_,_,abstract_constants),AInfo).
3034 recursion_detection_enabled_aux(A,_B,_I) :-
3035 animation_minor_mode(eventb), % in Event-B,
3036 %TODO: Limit application to axioms
3037 get_texpr_info(A,AInfo), % A must be a constant
3038 memberchk(loc(_,constants),AInfo).
3039 recursion_detection_enabled_aux(_A,_B,_I) :-
3040 animation_minor_mode(z). % use always in Z
3041 recursion_detection_enabled_aux(_A,_B,Infos) :- % check for @desc recursive_let pragma
3042 member(description(D),Infos), rec_let_pragma(D).
3043
3044 rec_let_pragma(recursive_let).
3045 rec_let_pragma(letrec). % more compact exists in other languages
3046 rec_let_pragma(reclet). % Z syntax
3047
3048 % peel of relational compositions and replace with function application
3049 % used to translate (F;G)(X) --> G(F(X)) or (F;G;H)(X) --> H(G(F(X))) ...
3050 peel_rel_composition(b(composition(F,G),_,_),TypeGArg,Info,Arg,GFres,L1) :-
3051 get_texpr_type(G,SType),
3052 bsyntaxtree:is_set_type(SType,couple(TypeFArg,_)),
3053 !,
3054 %Note: rule is multi: we will detect compositions inside G at next iteration
3055 peel_rel_composition(F,TypeFArg,Info,Arg,FRes,Level), L1 is Level+1,
3056 safe_create_function_call(G,FRes,TypeGArg,Info,GFres).
3057 peel_rel_composition(Fun,TypeFArg,Info,Arg,FArg,0) :-
3058 safe_create_function_call(Fun,Arg,TypeFArg,Info,FArg). % TODO: apply function_call_opt
3059
3060 % create a function call and detect certain optimisations like lambda inlining
3061 safe_create_function_call(Fun,Arg,TypeFArg,Info,Res) :-
3062 safe_create_texpr(function(Fun,Arg),TypeFArg,Info,FArg),
3063 (cleanup_pre_function(Fun,Arg,TypeFArg,Info,CleanupRes,Info2,_)
3064 -> Res = b(CleanupRes,TypeFArg,Info2)
3065 ; Res=FArg
3066 ).
3067
3068
3069 construct_union_from_list([X],_,_,Res) :- !, Res=X.
3070 construct_union_from_list([X,Y|T],Type,Info,Res) :-
3071 construct_union_from_list([Y|T],Type,Info,RHS),
3072 Res = b(union(X,RHS),Type,Info).
3073 construct_inter_from_list([X],_,_,Res) :- !, Res=X.
3074 construct_inter_from_list([X,Y|T],Type,Info,Res) :-
3075 construct_inter_from_list([Y|T],Type,Info,RHS),
3076 Res = b(intersection(X,RHS),Type,Info).
3077
3078 % LEQ_SYM_BREAK / LEQ_SYM does not support all types yet:
3079 sym_break_supported_type(Var) :- var(Var),!,fail.
3080 sym_break_supported_type(integer).
3081 sym_break_supported_type(boolean).
3082 sym_break_supported_type(string).
3083 sym_break_supported_type(global(_)).
3084 sym_break_supported_type(couple(A,B)) :- sym_break_supported_type(A), sym_break_supported_type(B).
3085 sym_break_supported_type(record(F)) :- maplist(sym_break_supported_field,F).
3086 sym_break_supported_field(field(_,T)) :- sym_break_supported_type(T).
3087 % example with pairs: !(x,y).(x:s2 & y:s2 & x/=y => prj1(INTEGER,INTEGER)(x)/=prj1(INTEGER,INTEGER)(y)) (with let s2 = {x,y|x:1..10000 & y:{x+1}}); here we get a slow-down; maybe we should check if RHS complicated enough
3088 % here it is beneficial: !(x,y).(x:dom(s)&y:dom(s)&x/=y => s(x)+s(y)>0) with let s={x,y,v|x:1..10&y:1..50&v=x+y}; runtime goes down from 9.7 to 6.1 seconds
3089
3090 ?construct_sym_break(integer,TID1,TID2,Pred,Res) :- member_in_conjunction(Neq,Pred), is_id_inequality(Neq,TID1,TID2),
3091 !, get_texpr_info(TID1,Info1),
3092 Res = b(less(TID1,TID2),pred,Info1). % we don't need the external function; we can used <
3093 construct_sym_break(integer,TID1,TID2,_Pred,Res) :- !, get_texpr_info(TID1,Info1),
3094 Res = b(less_equal(TID1,TID2),pred,Info1). % we don't need the external function; we can used <= ; we could check whether < or <= already in Pred ? occurs in test 1360: #(vv,ww).(vv < ww & ww < vv)
3095 construct_sym_break(_,TID1,TID2,_,Res) :- get_texpr_info(TID1,Info1),
3096 Res = b(external_pred_call('LEQ_SYM',[TID1,TID2]),pred,Info1).
3097
3098 % construct {Expr1,Expr2}
3099 construct_set_extension(Expr1,Expr2,Res) :- same_texpr(Expr1,Expr2),!,
3100 get_texpr_type(Expr1,Type),
3101 extract_info(Expr1,Infos), % will also copy used_ids; ok as this does not change by adding set_extension
3102 Res = b(set_extension([Expr1]),set(Type),Infos).
3103 construct_set_extension(Expr1,Expr2,Res) :-
3104 get_texpr_type(Expr1,Type),
3105 extract_info(Expr1,Expr2,Infos),
3106 (Expr1 @=< Expr2 -> Lst=[Expr1,Expr2] ; Lst=[Expr2,Expr1]), % solves issue with ParserTests; {FALSE,TRUE}
3107 Res = b(set_extension(Lst),set(Type),Infos).
3108
3109 l_construct_set_extension([E1],[E2],Res) :- !, construct_set_extension(E1,E2,Res).
3110 l_construct_set_extension(L1,L2,Res) :- append(L1,L2,L12),
3111 L12=[Expr1|T],!,
3112 get_texpr_type(Expr1,Type),
3113 last(T,Expr2),
3114 extract_info(Expr1,Expr2,Infos), % TODO: improve info extraction; sort L12 values?
3115 Res = b(set_extension(L12),set(Type),Infos).
3116 l_construct_set_extension(A,B,Res) :-
3117 add_internal_error('Requires at least two els:',l_construct_set_extension(A,B,Res)),fail.
3118
3119 is_id_inequality(b(not_equal(A,B),pred,_),X,Y) :-
3120 (same_texpr(A,X) -> same_texpr(B,Y) ; same_texpr(A,Y), same_texpr(B,X)).
3121
3122
3123 %known_set(b(integer_set(_),set(integer),_)). % used for forall splitting; TODO: use is_integer_set ??
3124 %known_set(b(interval(_,_),set(integer),_)).
3125
3126 % detect if we have an if-then-else function (which is then applied to a dummy argument)
3127 is_if_then_else(b(comprehension_set([TDummyID1,ID2],CONJ),_Type,_),_,_DUMMYARG,IFPRED,THEN,ELSE) :-
3128 % we ignore the _DUMMYARG as here we do not check the value of DUMMYARG in the body
3129 % TO DO: also allow removal of equalities as in TLA case below
3130 % DETECT {Dummy,Res| Test => Res=THEN & not(Test) => Res=ELSE}
3131 get_texpr_id(ID2,LambdaID), get_texpr_id(TDummyID1,DummyID),
3132 is_ifte_case_conjunct(CONJ,IFPRED,EQ1,EQ2),
3133 is_equality_conj(EQ1,II1,THEN), get_texpr_id(II1,LambdaID),
3134 is_equality_conj(EQ2,II2,ELSE), get_texpr_id(II2,LambdaID),
3135 \+ occurs_in_expr(DummyID,IFPRED),\+ occurs_in_expr(LambdaID,IFPRED),
3136 \+ occurs_in_expr(DummyID,THEN), \+ occurs_in_expr(LambdaID,THEN),
3137 \+ occurs_in_expr(DummyID,ELSE), \+ occurs_in_expr(LambdaID,ELSE).
3138
3139 % Recognize B2TLA encodings as well: %((x).(x=0 & PRED|C1)\/%(x).(x=0 & not(PRED)|C2)) (0)
3140 %is_if_then_else(IF,_,_,_,_) :- nl,print(IF),nl,nl,fail.
3141 is_if_then_else(b(union(COMP1,COMP2),_Type,_),_,DUMMYARG,IFPRED,THEN,ELSE) :-
3142 if_then_else_lambda(COMP1,DUMMYARG,IFPRED,THEN),
3143 if_then_else_lambda(COMP2,DUMMYARG,NOT_IFPRED,ELSE),
3144 is_negation_of(IFPRED,NOT_IFPRED).
3145
3146 is_if_then_else(b(set_extension([CASE1,CASE2]),_,Info),POST,Arg,IFPRED,THEN,ELSE) :-
3147 (POST=post -> true ; data_validation_mode), % in cleanup_pre the wd info is not yet computed
3148 Arg = b(convert_bool(IFPRED),boolean,_),
3149 % {TRUE|->v1,FALSE|->v2}(bool(TEST)) --> IF TEST THEN v1 ELSE v2 END
3150 % example: {TRUE|->1,FALSE|->2}(bool(2>3)) --> IF 2>3 THEN 1 ELSE 2 END
3151 CASE1 = b(couple(b(B1,boolean,_),Val1),_,_),
3152 CASE2 = b(couple(b(B2,boolean,_),Val2),_,_),
3153 ( B1=boolean_true,B2=boolean_false -> THEN=Val1,ELSE=Val2
3154 ; B2=boolean_true,B1=boolean_false -> THEN=Val2,ELSE=Val1),
3155 (always_well_defined_or_disprover_mode(THEN),
3156 always_well_defined_or_disprover_mode(ELSE) -> true
3157 %,add_message(function_if_then_else,'Detected {TRUE|->v1,FALSE|->v2}(bool(TEST)) construct without WD condition, rewriting it to IF TEST THEN v1 ELSE v2 END','',Info)
3158 % otherwise: the transformation to IF-THEN-ELSE may remove WD problem
3159 ; silent_mode(on) -> true
3160 ; %data_validation_mode,
3161 add_message(function_if_then_else,'Detected {TRUE|->v1,FALSE|->v2}(bool(TEST)) construct with WD condition, you should probably rewrite it to IF TEST THEN v1 ELSE v2 END','',Info),
3162 true % fail
3163 ).
3164
3165 if_then_else_lambda(b(comprehension_set([TDummyID,TLAMBDAID],CONJ),_,_),DUMMYARG,IFPRED,RESULT) :-
3166 conjunction_to_nontyping_list(CONJ,CL),
3167 get_texpr_id(TDummyID,DummyID),
3168 get_texpr_id(TLAMBDAID,LambdaID),
3169 (remove_equality(DummyID,DUMMYVAL,CL,ConjList) % look if there is an equality for the DummyID
3170 -> same_texpr(DUMMYVAL,DUMMYARG), % TO DO: check that we apply the function with this value
3171 \+ occurs_in_expr(LambdaID,DUMMYVAL), % ensure this is really the same value
3172 \+ occurs_in_expr(DummyID,DUMMYVAL)
3173 ; ConjList=CL),
3174 remove_equality(LambdaID,RESULT,ConjList,RestList),
3175 \+ occurs_in_expr(LambdaID,RESULT),
3176 \+ occurs_in_expr(DummyID,RESULT), % otherwise this is not really a dummy identifier
3177 conjunct_predicates_with_pos_info(RestList,IFPRED),
3178 \+ occurs_in_expr(DummyID,IFPRED).
3179
3180 % DETECT (IFPRED => EQ1) & (not(IFPRED) => EQ2)
3181 is_ifte_case_conjunct(CONJ,IFPRED,EQ1,EQ2) :-
3182 is_a_conjunct(CONJ,IMP1,IMP2),
3183 is_an_implication_conj(IMP1,IFPRED,EQ1),
3184 is_an_implication_conj(IMP2,NOT_IFPRED,EQ2),
3185 is_negation_of(IFPRED,NOT_IFPRED).
3186 % TO DO: also deal with lazy_lets wrapped around
3187 %is_ifte_case_conjunct(lazy_let_pred(ID,IFPRED,CONJ),IFPRED,EQ1,EQ2) :-
3188 % is_a_conjunct(CONJ,IMP1,IMP2),
3189 % is_an_implication(IMP1,IFPRED,EQ1),
3190 % is_an_implication(IMP2,NOT_IFPRED,EQ2),
3191 % is_negation_of(IFPRED,NOT_IFPRED).
3192
3193 % detect explicit if-then-else for cleanup_post:
3194 explicit_if_then_else(if_then_else(IF,THEN,ELSE),IF,THEN,ELSE).
3195 explicit_if_then_else(if([b(if_elsif(IF,THEN),subst,_)|TAIL]),IF,THEN,ELSE) :-
3196 (TAIL = [b(if_elsif(b(truth,pred,_),EE),subst,_)|_] -> ELSE = EE
3197 ; TAIL = [] -> ELSE = b(skip,subst,[generated])
3198 ).
3199
3200 % just like is_an_implication but allow typing conjuncts (not yet removed in pre-phase)
3201 is_an_implication_conj(Pred,LHS,RHS) :- is_an_implication(Pred,LHS,RHS),!.
3202 is_an_implication_conj(b(conjunct(A,B),pred,_),LHS,RHS) :-
3203 (is_typing_predicate(A) -> is_an_implication_conj(B,LHS,RHS)
3204 ; is_typing_predicate(B) -> is_an_implication_conj(A,LHS,RHS)).
3205
3206 % just like is_equality but allow typing conjuncts (not yet removed in pre-phase)
3207 is_equality_conj(EQ,LHS,RHS) :- is_equality(EQ,LHS,RHS).
3208 is_equality_conj(b(conjunct(A,B),pred,_),LHS,RHS) :-
3209 (is_typing_predicate(A) -> is_equality_conj(B,LHS,RHS)
3210 ; is_typing_predicate(B) -> is_equality_conj(A,LHS,RHS)).
3211
3212 % remove a dummy equality from list
3213 remove_equality(ID,RHS,ConjList,Rest) :-
3214 DummyEQ = b(equal(DID,RHS),pred,_), % TO DO: also accept simple typing memberships ?
3215 get_texpr_id(DID,ID),
3216 select(DummyEQ,ConjList,Rest). %, print(eq(DID,RHS)),nl.
3217
3218 get_texpr_boolean(b(X,_,_),Res) :- is_boolan_expr(X,Res).
3219 is_boolan_expr(boolean_true,boolean_true).
3220 is_boolan_expr(boolean_false,boolean_false).
3221 is_boolan_expr(value(X),Res) :- nonvar(X), conv_bool_val(X,Res).
3222 conv_bool_val(pred_true,boolean_true).
3223 conv_bool_val(pred_false,boolean_false).
3224
3225 is_typing_conjunct(b(member(_,B),_,_)) :- is_just_type(B).
3226 is_typing_predicate(Typing) :- conjunction_to_list(Typing,LT), maplist(is_typing_conjunct,LT).
3227 conjunction_to_nontyping_list(Pred,List) :- conjunction_to_list(Pred,TList), exclude(is_typing_conjunct,TList,List).
3228
3229 % used e.g. for translating : ran({x1,...xn|P}) --> {xn| #(x1,...).(P)}
3230 % we annotate this exists as allow_to_lift; as the origin is a set comprehension which originally had all variables at the top-level (including the existentially quantified ones)
3231 create_outer_exists_for_dom_range(Ids,CompPred,NewCompPred) :-
3232 create_outer_exists_for_dom_range2(Ids,CompPred,NewCompPred1),
3233 compute_used_ids_info_if_necessary(NewCompPred1,NewCompPred).
3234 create_outer_exists_for_dom_range2(Ids,b(exists(InnerIds,P),pred,Infos),New) :-
3235 member(allow_to_lift_exists,Infos),
3236 append(Ids,InnerIds,NewIds),!, % simply add Ids to existing existential quantifier
3237 New = b(exists(NewIds,P),pred,NewInfos),
3238 remove_from_used_ids(Infos,Ids,NewInfos).
3239 create_outer_exists_for_dom_range2(Ids,P,New) :-
3240 % we could also use construct_optimized_exists/3 it does a full partitioning of P; see also components_partition_exists rule above
3241 create_exists_opt_liftable(Ids,P,New). % marked as liftable as origin is a set comprehension with all ids
3242 % calls create_exists_opt: detects also simple tautologies like #x.(x=E)
3243 % + predicates that do not use one of the quantified identifiers are moved outside
3244 %N=b(P2,T2,[allow_to_lift_exists|I2]). %, check_ast(N).
3245
3246 % remove newly quantified Typed IDs from used_ids info; if the info exists
3247 remove_from_used_ids(OldInfo,NewQuantifiedTIds,NewInfo) :-
3248 select(used_ids(OldUsed),OldInfo,I1),!,
3249 get_texpr_ids(NewQuantifiedTIds,NewQ),
3250 NewInfo = [used_ids(NewUsed)|I1],
3251 ord_subtract(OldUsed,NewQ,NewUsed).
3252 remove_from_used_ids(I,_,I).
3253
3254 % if _lambda_result_ occurs in list; rename it so that we do not get issues with enumeration
3255 rename_lambda_result_id(Ids,CompPred,NewIds,NewCompPred) :-
3256 ? select(ID,Ids,Rest),
3257 get_texpr_id(ID,'_lambda_result_'),
3258 !,
3259 get_unique_id_inside('__RANGE_LAMBDA__',CompPred,FRESHID), % if we don't rename then _lambda_result_ will not be enumerated ! TO DO: also check different from Ids if we want to remove __ prefix
3260 % TO DO: remove lambda_result(Info)
3261 ? rename_bt(CompPred,[rename('_lambda_result_',FRESHID)],NewCompPred),
3262 get_texpr_type(ID,IDType), get_texpr_info(ID,IDInfo),
3263 NewIds = [b(identifier(FRESHID),IDType,IDInfo)|Rest].
3264 rename_lambda_result_id(Ids,CompPred,Ids,CompPred).
3265
3266 contains_predicate(convert_bool(Pred),boolean,Pred,
3267 convert_bool(NewP),NewP).
3268 contains_predicate(comprehension_set(CompIds,Pred),_,Pred,
3269 comprehension_set(CompIds,NewP),NewP).
3270 contains_predicate(general_sum(Ids,Pred,Expression),integer,Pred,
3271 general_sum(Ids,NewP,Expression),NewP).
3272 contains_predicate(general_product(Ids,Pred,Expression),integer,Pred,
3273 general_product(Ids,NewP,Expression),NewP).
3274 contains_predicate(if_then_else(Pred,Then,Else),_,Pred,
3275 if_then_else(NewP,Then,Else),NewP).
3276 contains_predicate(assertion_expression(Pred,ErrMsg,Expr),_,Pred,
3277 assertion_expression(NewP,ErrMsg,Expr),NewP).
3278 contains_predicate(precondition(Pred,Body),subst,Pred,
3279 precondition(NewP,Body),NewP).
3280 contains_predicate(assertion(Pred,Body),subst,Pred,
3281 assertion(NewP,Body),NewP).
3282 contains_predicate(becomes_such(Vars,Pred),subst,Pred,
3283 becomes_such(Vars,NewP),NewP).
3284 contains_predicate(any(Parameters,Pred,Body),subst,Pred,
3285 any(Parameters,NewP,Body),NewP).
3286 contains_predicate(lazy_let_expr(ID,SharedExpr,MainExpr),pred, SharedExpr,
3287 lazy_let_expr(ID,NewSharedExpr,MainExpr), NewSharedExpr) :-
3288 get_texpr_type(SharedExpr,pred).
3289 contains_predicate(lazy_let_subst(ID,SharedExpr,MainExpr),pred, SharedExpr,
3290 lazy_let_subst(ID,NewSharedExpr,MainExpr), NewSharedExpr) :-
3291 get_texpr_type(SharedExpr,pred).
3292 contains_predicate(lazy_let_pred(ID,SharedExpr,MainExpr),pred, MainExpr,
3293 lazy_let_pred(ID,SharedExpr,NewMainExpr), NewMainExpr) :-
3294 \+ get_texpr_type(SharedExpr,pred).
3295 % while(COND,STMT,INV,VARIANT), select, if --> can have multiple predicates !!
3296 contains_predicates(while(Cond, Stmt,Invariant,Variant),subst, [Cond,Invariant],
3297 while(NewCond,Stmt,NewInv, Variant), [NewCond,NewInv]).
3298 contains_predicates(if(Whens),subst,Preds,
3299 if(NewWhens),NewPreds) :-
3300 get_predicates_from_list_of_cases(Whens,Preds,NewWhens,NewPreds).
3301 contains_predicates(select(Whens),subst,Preds,
3302 select(NewWhens),NewPreds) :-
3303 get_predicates_from_list_of_cases(Whens,Preds,NewWhens,NewPreds).
3304 contains_predicates(select(Whens,Else),subst,Preds,
3305 select(NewWhens,Else),NewPreds) :-
3306 get_predicates_from_list_of_cases(Whens,Preds,NewWhens,NewPreds).
3307 contains_predicates(lazy_let_pred(ID,SharedExpr,MainExpr),pred, [SharedExpr,MainExpr],
3308 lazy_let_pred(ID,NSharedExpr,NMainExpr), [NSharedExpr,NMainExpr]) :-
3309 get_texpr_type(SharedExpr,pred).
3310
3311 get_predicates_from_list_of_cases([],[],[],[]).
3312 get_predicates_from_list_of_cases([H|T],Preds,[NewH|NewT],NewPreds) :-
3313 (get_single_predicate(H,Pred,NH,NewPred)
3314 -> NewH=NH, Preds=[Pred|TP], NewPreds = [NewPred|NTP]
3315 ; NewH=H, Preds=TP, NewPreds = NTP
3316 ),
3317 get_predicates_from_list_of_cases(T,TP,NewT,NTP).
3318
3319 get_single_predicate(b(E,T,I),Preds,b(NewE,T,I),NewPreds) :-
3320 get_single_predicate_aux(E,Preds,NewE,NewPreds).
3321 get_single_predicate_aux(select_when(Pred,Body),Pred,select_when(NewPred,Body),NewPred).
3322 get_single_predicate_aux(if_elsif(Pred,Body),Pred,if_elsif(NewPred,Body),NewPred).
3323
3324
3325 % Detect useless statements in sequential compositions:
3326 % useful for LCHIP code, e.g., where dummy code is added for the code generator: i9 : (i9 : BOOL); i9 := TRUE
3327 % in test 1660 we remove an assignment that reads an unitialised variable
3328 filter_useless_subst_in_sequence([],_,R) :- !, R=[].
3329 filter_useless_subst_in_sequence([S1],_,R) :- !, R=[S1].
3330 filter_useless_subst_in_sequence([S1|S2],change,R) :- useless_subst_in_sequence(S1,S2),!,
3331 add_hint_message(filter_useless_subst_in_sequence,'Removing useless substitution in sequence','',S1),
3332 filter_useless_subst_in_sequence(S2,_,R).
3333 filter_useless_subst_in_sequence([S1|S2],Change,[S1|RS]) :- filter_useless_subst_in_sequence(S2,Change,RS).
3334
3335 useless_subst_in_sequence(b(Subst,subst,Info),Sequence2) :- % print(check(Subst,Sequence2)),nl,
3336 useless_code_before_sequence(Subst,Info,Sequence2).
3337
3338 useless_code_before_sequence(skip,_,_) :- !.
3339 useless_code_before_sequence(Subst,_,SubstList) :- is_non_failing_assignment(Subst,TID), def_get_texpr_id(TID,ID),
3340 is_dead(ID,SubstList).
3341
3342 % first naive version to compute if the variable ID is dead when followed by a list of substitutions
3343 is_dead(ID,[b(Subst,subst,Info)|_]) :- % we currently only look at first statement; TO DO: improve
3344 is_dead_aux(Subst,Info,ID).
3345 is_dead_aux(assign_single_id(TID,RHS),_Info,ID) :-
3346 get_texpr_id(TID,ID), % we assign to ID; TO DO: deal with other assignments and assignments to functions f(i) := ...
3347 find_identifier_uses_if_necessary(RHS,[],UsedIds),
3348 \+ ord_member(ID,UsedIds).
3349
3350 % non failing assignment without WD condition, note that we may still try and read identifiers that have not been initialised (having term(undefined) as value), see test 1660
3351 is_non_failing_assignment(becomes_such([TID],Pred),TID) :- is_truth(Pred).
3352 is_non_failing_assignment(becomes_element_of([TID],Set),TID) :- definitely_not_empty_set(Set).
3353 is_non_failing_assignment(assign_single_id(TID,RHS),TID) :- always_well_defined_or_disprover_mode(RHS).
3354 is_non_failing_assignment(assign([LHS],[RHS]),TID) :- always_well_defined_or_disprover_mode(RHS),
3355 get_lhs_assigned_identifier(LHS,TID).
3356
3357
3358 % ---------------------------------------------
3359
3360 :- use_module(extrasrc(b_expression_sharing),[cse_optimize_predicate/2]).
3361 % these are "global" optimizations at the predicate level
3362 % they are only called once a predicate has been completely constructed
3363 predicate_level_optimizations(Pred,NewPred) :-
3364 predicate_level_optimizations(Pred,NewPred,[]).
3365 predicate_level_optimizations(Pred,NewPred,Path) :-
3366 inner_predicate_level_optimizations(Pred,Pred1),
3367 (get_preference(use_common_subexpression_elimination,true),
3368 \+ do_not_optimise_in_context(Path)
3369 -> cse_optimize_predicate(Pred1,NewPred)
3370 ; NewPred=Pred1
3371 ). %,print_opt_debug_info(Pred,NewPred,Path).
3372 /*
3373 print_opt_debug_info(Pred,NewPred,Path) :-
3374 (Pred==NewPred -> true
3375 ; same_texpr(Pred,NewPred) -> true
3376 ; format('Optimized pred ~w: ',[Path]), print_bexpr(NewPred),nl
3377 % , (Path=[] -> trace ; true)
3378 ).
3379 */
3380
3381 do_not_optimise_in_context([path_arg(top_level(invariant),Nr)]) :-
3382 get_preference(use_po,true),
3383 debug_format(19,'% NOT applying CSE to Invariant Nr ~w (PROOF_INFO = TRUE)~n',[Nr]).
3384
3385 :- use_module(partition_detection,[detect_all_partitions_in_predicate/2]).
3386 % this predicate is also called for exists, forall, ...:
3387 inner_predicate_level_optimizations(Pred,NewPred) :-
3388 detect_all_partitions_in_predicate(Pred,NewPred1),
3389 (get_preference(remove_implied_constraints,true)
3390 -> remove_implied_constraints(NewPred1,NewPred)
3391 ; NewPred=NewPred1)
3392 . %,(Pred==NewPred -> true ; print('Optimized pred: '), print_bexpr(NewPred),nl).
3393
3394
3395
3396 % ----------------------------------
3397
3398 remove_implied_constraints(Predicate,NewPredicate) :-
3399 conjunction_to_list(Predicate,PList),
3400 remove_implied_constraints(PList,[],PNew),
3401 conjunct_predicates_with_pos_info(PNew,NewPredicate).
3402
3403 % remove constraints which are redundant for ProB
3404 % example:
3405 % n=1000 & f:1..n --> BOOL & f:1..n +-> BOOL & !x.(x:dom(f) => f(x) = bool(x>50)) & f: 1..n <-> BOOL & dom(f)=1..n
3406 % runtime goes from 500 ms down to 300 ms by remove +->, <-> and dom(f) checks
3407 % but test 1442 has issue: still unclear how useful this static detection is
3408 % it is probably most useful for proving/disproving where we have lots of redundant/derived hypotheses
3409
3410 remove_implied_constraints([],_,[]).
3411 remove_implied_constraints([Constraint|T],SoFar,Result) :-
3412 % print('Checking: '), print_bexpr(Constraint),nl,
3413 possible_implied_constraint(Constraint,C1),
3414 % print('Checking if implied constraint: '), print_bexpr(Constraint),nl,
3415 (member(TC2,T) ; member(TC2,SoFar)),
3416 get_texpr_expr(TC2,C2),
3417 implied_constraint2(C2,C1),
3418 (debug_mode(off) -> true
3419 ; print('Removing implied constraint: '), print_bexpr(Constraint),
3420 print(' <=== '), print_bexpr(TC2),nl),
3421 !,
3422 remove_implied_constraints(T,SoFar,Result).
3423 remove_implied_constraints([H|T],SoFar,[H|RT]) :- remove_implied_constraints(T,[H|SoFar],RT).
3424
3425 possible_implied_constraint(b(E,T,I),E) :-
3426 (possible_implied_constraint2(E,T,I) -> true).
3427 possible_implied_constraint2(member(_,b(FUNCTION,_,_)),_,_) :- functor(FUNCTION,F,2),
3428 (function_implication2(F,_) -> true ; F = relations).
3429 possible_implied_constraint2(equal(b(domain(_),_,_),_),_,_). % TO DO: other way around
3430
3431 % f: A --> B ==> f: A +-> B, f: A<->B, dom(f) = A
3432 % test 1442: issue with surjection
3433 implied_constraint2(member(Fun1,b(FUNCTION1,T,_)), member(Fun2,b(FUNCTION2,T,_))) :-
3434 functor(FUNCTION1,F1,2), arg(1,FUNCTION1,X1), arg(2,FUNCTION1,Y1),
3435 functor(FUNCTION2,F2,2), arg(1,FUNCTION2,X2), arg(2,FUNCTION2,Y2),
3436 function_implication(F1,F2),
3437 same_texpr(Fun1,Fun2),
3438 same_texpr(X1,X2),
3439 same_texpr(Y1,Y2).
3440 % f: A --> B ==> dom(f) = A
3441 implied_constraint2(member(Fun2,b(FUNCTION2,_,_)), equal(b(domain(Fun1),_,_),Domain)) :-
3442 functor(FUNCTION2,F2,2), arg(1,FUNCTION2,Domain2),
3443 total_function(F2),
3444 same_texpr(Fun1,Fun2),
3445 same_texpr(Domain,Domain2).
3446 % TODO: f: A -->> B ==> ran(f) = B ?
3447
3448
3449 total_function(total_bijection).
3450 total_function(total_injection).
3451 total_function(total_surjection).
3452 total_function(total_function).
3453 %total_relation(total_surjection_relation). % not sure if in this case the constraint is maybe not useful after all?
3454 %total_relation(total_relation).
3455
3456 function_implication(F1,F2) :- function_implication2(F1,F2).
3457 function_implication(F1,F2) :- function_implication2(F1,Z), function_implication(Z,F2).
3458
3459 function_implication2(total_bijection,total_injection).
3460 function_implication2(total_bijection,total_surjection).
3461 function_implication2(total_injection,total_function).
3462 function_implication2(total_surjection,total_function).
3463 function_implication2(total_function,partial_function).
3464 function_implication2(partial_function,relations).
3465 function_implication2(partial_injection,partial_function). % >+>
3466 function_implication2(partial_surjection,partial_function).
3467 %function_implication2(partial_bijection,partial_injection).
3468 %function_implication2(partial_bijection,partial_surjection).
3469 function_implication2(total_relation,relations).
3470 function_implication2(surjection_relation,relations).
3471 function_implication2(total_surjection_relation,total_relation).
3472 function_implication2(total_surjection_relation,surjection_relation).
3473
3474 % ------------------
3475
3476
3477 % divide a list of identifiers into domain and range identifiers
3478 get_domain_range_ids([D,R],[D],[R]) :- !.
3479 get_domain_range_ids([D1,D2|T],[D1|DT],R) :- get_domain_range_ids([D2|T],DT,R).
3480
3481
3482 % detect whether there is a pattern of a recursive usage of the identifier: ID(x) or ID[x] or x:ID
3483 find_recursive_usage(TExpr,ID) :-
3484 syntaxtraversion(TExpr,Expr,_,_,Subs,TNames), % print(try_id(ID,Expr,Subs,TNames)),nl,
3485 ( Expr = function(Fun,_), get_texpr_id(Fun,ID) -> true
3486 ; Expr = image(Rel,_), get_texpr_id(Rel,ID) -> true
3487 ; Expr = member(_,Set), get_texpr_id(Set,ID) -> true
3488 ? ; \+ (member(ID1,TNames),get_texpr_id(ID1,ID)), % new local variable with same name
3489 ? member(Sub,Subs), find_recursive_usage(Sub,ID)
3490 ).
3491
3492 :- use_module(bsyntaxtree,[transform_bexpr/3]).
3493 % find comprehension sets and mark them as recursive if they use the recursive ID
3494 mark_recursion(TExpr,RecID,NewTExpr) :-
3495 (transform_bexpr(b_ast_cleanup:mark_comprehension_set(RecID),TExpr,NewTExpr)
3496 -> true
3497 ; add_internal_error('Call failed: ',transform_bexpr(b_ast_cleanup:mark_comprehension_set(RecID),TExpr,NewTExpr)),
3498 NewTExpr=TExpr).
3499
3500 :- public mark_comprehension_set/3.
3501 mark_comprehension_set(RecID,b(lambda(Ids,P,Expr),Type,Info),
3502 b(lambda(Ids,P,Expr),Type,NInfo)) :-
3503 (find_recursive_usage(P,RecID) -> true ; find_recursive_usage(Expr,RecID)),
3504 get_texpr_ids(Ids,AtomicIds),
3505 (silent_mode(on) -> true
3506 ; format('Recursive lambda using ~w detected (name: ~w)~n',[AtomicIds,RecID]),
3507 error_manager:print_message_span(Info),nl
3508 ),
3509 add_texpr_infos(Info,[prob_annotation('SYMBOLIC'),prob_annotation('RECURSIVE')],NInfo).
3510 mark_comprehension_set(RecID,b(comprehension_set(Ids,P),Type,Info),
3511 b(comprehension_set(Ids,P),Type,NInfo)) :-
3512 % DO NOT MARK IT IF IT IS IN RESULT POSITION of recursive function ?
3513 find_recursive_usage(P,RecID),
3514 get_texpr_ids(Ids,AtomicIds),
3515 (silent_mode(on) -> true
3516 ; format('Recursive comprehension set using ~w detected (name: ~w)~n',[AtomicIds,RecID]),
3517 error_manager:print_message_span(Info),nl
3518 ),
3519 NInfo = [prob_annotation('SYMBOLIC'),prob_annotation('RECURSIVE')|Info]. % TO DO: only add if not already there
3520
3521
3522 % pred(h) --> h-1, succ(h) --> h+1
3523 precompute_pred_succ_function_call(Fun,Arg,ArithOp) :-
3524 get_texpr_expr(Fun,PS),
3525 ( PS=predecessor -> Op=minus
3526 ; PS=successor -> Op=add), % we could use add_one predicate
3527 ArithOp =.. [Op,Arg,Integer],
3528 create_texpr(integer(1),integer,[],Integer).
3529
3530 %
3531 one(b(integer(1),integer,[])).
3532 create_interval_member(X,LowBound,UpBound,Member) :-
3533 safe_create_texpr(interval(LowBound,UpBound),set(integer),Interval),
3534 safe_create_texpr(member(X,Interval),pred,Member).
3535
3536 get_leq_comparison(less(A,B),A,B1) :- minus_one(B,BM1),
3537 safe_create_texpr(BM1,integer,B1).
3538 get_leq_comparison(greater(B,A),A,B1) :- get_leq_comparison(less(A,B),A,B1).
3539 get_leq_comparison(less_equal(A,B),A,B).
3540 get_leq_comparison(greater_equal(B,A),A,B).
3541
3542 minus_one(b(integer(I),integer,_),Res) :- !, I1 is I-1, Res=integer(I1).
3543 minus_one(B,minus(B,One)) :- one(One).
3544 add_one(b(integer(I),integer,_),Res) :- !, I1 is I+1, Res=integer(I1).
3545 add_one(B,add(B,One)) :- one(One).
3546
3547 % get_geq_comparison(Expr,LHS,RHS) ; RHS can be shifted by 1
3548 get_geq_comparison(less(B,A),A,B1) :- get_geq_comparison(greater(A,B),A,B1).
3549 get_geq_comparison(greater(A,B),A,B1) :- add_one(B,BP1),
3550 safe_create_texpr(BP1,integer,B1).
3551 get_geq_comparison(less_equal(B,A),A,B).
3552 get_geq_comparison(greater_equal(A,B),A,B).
3553 get_geq_comparison(member(A,SET),A,b(integer(Bound),integer,[])) :-
3554 is_inf_integer_set_with_lower_bound(SET,Bound).
3555 % comparison operators:
3556 comparison(equal(A,B),A,B,equal(SA,SB),SA,SB).
3557 comparison(not_equal(A,B),A,B,not_equal(SA,SB),SA,SB).
3558 comparison(greater(A,B),A,B,greater(SA,SB),SA,SB).
3559 comparison(less(A,B),A,B,less(SA,SB),SA,SB).
3560 comparison(greater_equal(A,B),A,B,greater_equal(SA,SB),SA,SB).
3561 comparison(less_equal(A,B),A,B,less_equal(SA,SB),SA,SB).
3562 % rules to simplify binary comparison arguments
3563 simplify_comparison_terms(b(A,T,_IA),b(B,T,_IB),RA,RB) :-
3564 simplify_comparison_terms2(A,B,RA,RB).
3565 % TO DO: expand into much better simplifier !
3566 simplify_comparison_terms2(minus(A1,A2),minus(B1,B2),ResA,ResB) :-
3567 ( same_texpr(A1,B1) -> ResA=B2, ResB=A2 % X-A2 < X-B2 <=> B2 < A2
3568 ; same_texpr(A2,B2) -> ResA=A1, ResB=B1). % A1-X < B1-X <=> A1 < B1
3569 simplify_comparison_terms2(add(A1,A2),add(B1,B2),ResA,ResB) :-
3570 ( same_texpr(A1,B1) -> ResA=A2, ResB=B2 % X+A2 < X+B2 <=> A2 < B2
3571 ; same_texpr(A2,B2) -> ResA=A1, ResB=B1 % A1+X < B1+X <=> A1 < B1
3572 ; same_texpr(A1,B2) -> ResA=A2, ResB=B1 % X+A2 < B1+X <=> A2 < B1
3573 ; same_texpr(A2,B1) -> ResA=A1, ResB=B2). % A1+X < X+B2 <=> A1 < B2
3574 % multiplication: beware of sign, same with division
3575
3576 /* not used at the moment:
3577 clpfd_arith_integer_expression(b(E,integer,_)) :- clpfd_arith_integer_expression_aux(E).
3578 % check if we have an expression that can be dealt with by b_compute_arith_expression
3579 clpfd_arith_integer_expression_aux(unary_minus(X)) :-
3580 X \= b(integer(_),integer,_). % if it is an explicit integer we can compute it normally
3581 clpfd_arith_integer_expression_aux(add(_,_)).
3582 clpfd_arith_integer_expression_aux(minus(_,_)).
3583 clpfd_arith_integer_expression_aux(multiplication(_,_)).
3584 */
3585
3586 % simplify equality/inequality Unifications:
3587 simplify_equality(b(A,T,_),b(B,T,_),A2,B2) :-
3588 simplify_equality_aux(A,B,T,A2,B2).
3589 simplify_equality_aux(set_extension([A1]),set_extension([B1]),_,A2,B2) :- !,
3590 opt_simplify_equality(A1,B1,A2,B2).
3591 simplify_equality_aux(CoupleA,Type,CoupleB,A3,B3) :-
3592 get_couple(CoupleA,Type,A1,A2),
3593 get_couple(CoupleB,Type,B1,B2),
3594 (same_texpr(A1,B1), % (1,x)=(1,3) -> x=3
3595 always_well_defined_or_disprover_mode(A1)
3596 -> opt_simplify_equality(A2,B2,A3,B3)
3597 ; same_texpr(A2,B2),always_well_defined_or_disprover_mode(A2)
3598 -> opt_simplify_equality(A1,B1,A3,B3)
3599 ; different_texpr_values(A1,B1), % (1,x)=(2,3) -> 1=2
3600 always_well_defined_or_wd_improvements_allowed(A2),
3601 always_well_defined_or_wd_improvements_allowed(B2)
3602 -> (A3,B3) = (A1,B1) % no need to compare A2,B2
3603 ; different_texpr_values(A2,B2), always_well_defined_or_wd_improvements_allowed(A1),
3604 always_well_defined_or_wd_improvements_allowed(B1)
3605 -> (A3,B3) = (A2,B2) % no need to compare A1,B1
3606 ).
3607
3608 % flexibly get a couple from either AST or value:
3609 get_couple(couple(A1,A2),_,A1,A2).
3610 get_couple(value(CVal),couple(T1,T2),A1,A2) :- nonvar(CVal), CVal=(V1,V2),
3611 A1=b(value(V1),T1,[]), A2=b(value(V2),T2,[]).
3612
3613 opt_simplify_equality(A1,B1,A2,B2) :-
3614 (simplify_equality(A1,B1,A2,B2) -> true ; A2=A1, B2=B1).
3615
3616 % record field set extraction:
3617 construct_field_sets(FieldsSetsOut, field(Name,Type), field(Name,NewSet)) :-
3618 (member(field_set(Name,NewSet),FieldsSetsOut)
3619 -> true
3620 ; create_maximal_type_set(Type,NewSet)
3621 ).
3622
3623 % traverse a list of conjuncts and check that they all restrict fields of a record ID
3624 % all sets are combined via intersection
3625 l_update_record_field_membership([],_) --> [].
3626 l_update_record_field_membership([H|T],ID) -->
3627 update_record_field_membership(H,ID), l_update_record_field_membership(T,ID).
3628 update_record_field_membership(b(member(b(LHS,_,_),TRHS),pred,_),ID) --> update2(LHS,TRHS,ID).
3629 update2(record_field(RECID,FieldName),TRHS,ID) --> {get_texpr_id(RECID,ID)},add_field_restriction(FieldName,TRHS).
3630 update2(identifier(ID),b(struct(b(rec(FieldSets),_,_)),_,_),ID) -->
3631 l_add_field_restriction(FieldSets).
3632
3633 l_add_field_restriction([]) --> [].
3634 l_add_field_restriction([field(FieldName,TRHS)|T]) -->
3635 add_field_restriction(FieldName,TRHS), l_add_field_restriction(T).
3636 add_field_restriction(FieldName,TRHS,FieldsIn,FieldsOut) :-
3637 (select(field_set(FieldName,OldSet),FieldsIn,F2)
3638 -> OldSet = b(_,Type,_),
3639 safe_create_texpr(intersection(OldSet,TRHS),Type,NewSet),
3640 FieldsOut = [field_set(FieldName,NewSet)|F2]
3641 ; FieldsOut = [field_set(FieldName,TRHS)|FieldsIn]).
3642 % end record field extraction
3643
3644
3645 extract_unions(A,R) :- get_texpr_expr(A,union(A1,A2)),!,
3646 extract_unions(A1,R1), extract_unions(A2,R2),
3647 append(R1,R2,R).
3648 extract_unions(A,[A]).
3649
3650 gen_member_predicates(B,SEl,TExpr) :- safe_create_texpr(member(SEl,B),pred,TExpr).
3651
3652 % when constructing an expression/predicate: important to ripple wd information up
3653 extract_important_info_from_subexpression(b(_,_,Info),NewInfo) :-
3654 include(important_info_from_sub_expr,Info,NewInfo).
3655
3656 extract_important_info_from_subexpressions(b(_,_,Info1),b(_,_,Info2),NewInfo) :-
3657 include(important_info_from_sub_expr,Info1,II1),
3658 (memberchk(contains_wd_condition,Info2), nonmember(contains_wd_condition,II1)
3659 -> NewInfo = [contains_wd_condition|II1]
3660 ; NewInfo=II1). % TO DO: maybe also import other Infos? merge position info (nodeid(_))?
3661 % other important ones: removed_typing ??
3662
3663 % include important info from removed conjunct (note: see also extract_info in bsyntaxtree)
3664 % include_important_info(RemovedPredInfo,RemainingPredInfo,NewInfo)
3665 include_important_info_from_removed_pred([],Info2,Info2).
3666 include_important_info_from_removed_pred([H1|Info1],Info2,NewInfo2) :-
3667 (is_removed_typing_info(H1), nonmember(removed_typing,Info2)
3668 -> NewInfo2 = [removed_typing|Info2]
3669 ; include_important_info_from_removed_pred(Info1,Info2,NewInfo2)).
3670
3671 is_removed_typing_info(was(_)).
3672 is_removed_typing_info(removed_typing).
3673
3674 important_info_from_sub_expr(removed_typing).
3675 important_info_from_sub_expr(contains_wd_condition).
3676 important_info_from_sub_expr(prob_annotation(_)).
3677 important_info_from_sub_expr(nodeid(_)).
3678 important_info_from_sub_expr(was(_)).
3679 %important_info(allow_to_lift_exists). % important but only for exists; should not be copied to outer predicates
3680
3681 % add important infos in case an expression gets simplified into a sub-expression, e.g., bool(X)=TRUE -> X
3682 add_important_info_from_super_expression(Infos,SubInfos,NewSubInfos) :-
3683 include(important_info_from_super_expression,Infos,Important), % print(add_important(Important)),nl,
3684 add_infos_if_new(Important,SubInfos,NewSubInfos).
3685
3686
3687 important_info_from_super_expression(label(_)).
3688 important_info_from_super_expression(P) :- is_rodin_label_info(P). % important for Rodin proof info; if an invariant is partioned
3689 %add_important_info_to_texpr_from_super(Infos,b(Sub,T,SubInfos),b(Sub,T,NewSubInfos)) :- !,
3690 % add_important_info_from_super_expression(Infos,SubInfos,NewSubInfos).
3691
3692 important_info_for_exists(allow_to_lift_exists).
3693 important_info_for_exists(Label) :- important_info_from_super_expression(Label).
3694 % add important infos to individual conjuncts which are exists constructs; used when partitioning of exists:
3695 add_important_infos_to_exists_conjuncts(TPred,SuperInfos,SuperIds,NewTPred) :-
3696 include(important_info_for_exists,SuperInfos,Important),
3697 (Important=[]
3698 -> NewTPred=TPred
3699 ; add_to_conjuncts_aux(TPred,Important,SuperIds,NewTPred)
3700 ).
3701 add_to_conjuncts_aux(b(Pred,Type,Infos),Important,SuperIds,b(NP,Type,NewSubInfos)) :-
3702 (Pred=conjunct(A,B)
3703 -> NP=conjunct(NA,NB), NewSubInfos=Infos,
3704 add_to_conjuncts_aux(A,Important,SuperIds,NA),
3705 add_to_conjuncts_aux(B,Important,SuperIds,NB)
3706 ? ; Pred=exists(InnerIds,_), member(TID,InnerIds),
3707 def_get_texpr_id(TID,ID),
3708 ord_member(ID,SuperIds) % the exists is probably related to the outer exists
3709 % (TODO: it could be a lifted clashing one: perform this annotation directly in construct_optimized_exists !!)
3710 -> append(Important,Infos,NewSubInfos), % copy infos from original exists
3711 NP=Pred
3712 ; NP=Pred, NewSubInfos=Infos).
3713
3714 % extract all assignments from a list of statements; last arg is the number of assignments extracted
3715 extract_assignments([],[],[],[],0).
3716 extract_assignments([H|T],ResLHS,ResRHS,Rest,Nr) :-
3717 is_ordinary_assignment(H,LHS,RHS,Cnt),!,
3718 extract_assignments(T,LT,RT,Rest,N),
3719 append(LHS,LT,ResLHS), append(RHS,RT,ResRHS), Nr is N+Cnt.
3720 extract_assignments([H|T],LT,RT,[H|Rest],Nr) :-
3721 extract_assignments(T,LT,RT,Rest,Nr).
3722 % assigned_after(Primed),modifies(Var)
3723
3724 % check if we have an ordinary assignment that can be merged, optimised:
3725 is_ordinary_assignment(b(S,_,Info),LHS,RHS,Cnt) :- is_ordinary_assignment_aux(S,Info,LHS,RHS,Cnt).
3726 is_ordinary_assignment_aux(skip,_Info,[],[],0).
3727 is_ordinary_assignment_aux(assign_single_id(LHS,RHS),_Info,[LHS],[RHS],0). % count=0: used for parallel merge: assign_single_id less useful to merge with
3728 is_ordinary_assignment_aux(assign(LHS,RHS),Info,LHS,RHS,1) :-
3729 \+ member(assigned_after(_),Info), % these assignments are treated in a special way
3730 \+ member(modifies(_),Info).
3731
3732 % merge assignments in a list of statements to be executed by sequential composition:
3733 merge_assignments([S1,S2|T],merged,Res) :- merge_two_assignments(S1,S2,New),!,
3734 merge_assignments([New|T],_,Res).
3735 merge_assignments([],no_merge,[]).
3736 merge_assignments([H|T],Merge,[H|TR]) :- merge_assignments(T,Merge,TR).
3737
3738 :- use_module(b_read_write_info,[get_lhs_assigned_identifier/2]).
3739 get_lhs_assigned_ids(LHS,SortedIds) :-
3740 maplist(get_lhs_assigned_identifier,LHS,TLHSAssign),
3741 get_sorted_ids(TLHSAssign,SortedIds).
3742 merge_two_assignments(S1,S2,NewAssignment) :-
3743 is_ordinary_assignment(S1,LHS1,RHS1,_),
3744 is_ordinary_assignment(S2,LHS2,RHS2,_),
3745 get_lhs_assigned_ids(LHS1,SortedIDs1),
3746 get_lhs_assigned_ids(LHS2,SortedIDs2),
3747 ord_disjoint(SortedIDs1,SortedIDs2), % no race condition
3748 maplist(not_occurs_in_predicate(SortedIDs1),RHS2),
3749 maplist(not_occurs_in_predicate(SortedIDs1),LHS2), % not used in left-hand side, e.g., f(x+y) := RHS
3750 get_texpr_info(S1,I1), get_texpr_info(S2,I2),
3751 merge_info(I1,I2,Infos),
3752 append(LHS1,LHS2,NewLHS),
3753 append(RHS1,RHS2,NewRHS),
3754 NewAssignment = b(assign(NewLHS,NewRHS),subst,Infos),
3755 (debug_mode(off) -> true ; print('Merged assignments: '),translate:print_subst(NewAssignment),nl).
3756 construct_sequence([],skip).
3757 construct_sequence([TH],H) :- !, TH=b(H,_,_).
3758 construct_sequence(List,sequence(List)).
3759
3760 % check if we have a simple expression which will not be complicated to calculate
3761 ?simple_expression(b(E,_,_)) :- simple2(E).
3762 % (simple2(E) -> true ; print(not_simple(E)),nl).
3763 simple2(bool_set).
3764 simple2(boolean_false).
3765 simple2(boolean_true).
3766 simple2(empty_sequence).
3767 simple2(empty_set).
3768 simple2(identifier(_)).
3769 %simple2(integer_set(_)).
3770 simple2(integer(_)).
3771 simple2(lazy_lookup_expr(_)).
3772 simple2(lazy_let_expr(_,A,B)) :- simple2(B), simple_expr_or_pred(A).
3773 simple2(max_int).
3774 simple2(min_int).
3775 simple2(real_set).
3776 simple2(real(_)).
3777 simple2(string_set).
3778 simple2(string(_)).
3779 simple2(value(_)).
3780 simple2(first_of_pair(_)). simple2(second_of_pair(_)).
3781 simple2(couple(A,B)) :- simple_expression(A), simple_expression(B).
3782 ?simple2(interval(A,B)) :- simple_expression(A), simple_expression(B).
3783 ?simple2(add(A,B)) :- simple_expression(A), simple_expression(B).
3784 ?simple2(minus(A,B)) :- simple_expression(A), simple_expression(B).
3785 simple2(multiplication(A,B)) :- simple_expression(A), simple_expression(B).
3786 simple2(unary_minus(A)) :- simple_expression(A).
3787 ?simple2(convert_bool(A)) :- simple_predicate(A).
3788 simple2(sequence_extension(A)) :- maplist(simple_expression,A).
3789 simple2(set_extension(A)) :- maplist(simple_expression,A). % a bit more expensive than sequence_extension: elements need to be compared
3790 simple2(X) :- is_integer_set(X,_).
3791
3792 simple_expr_or_pred(b(E,T,_)) :- (T=pred -> simplep2(E) ; simple2(E)).
3793
3794 ?simple_predicate(b(E,_,_)) :- simplep2(E).
3795 ?simplep2(equal(A,B)) :- simple_expression(A), simple_expression(B). % could be slightly more expensive if set type
3796 simplep2(not_equal(A,B)) :- simple_expression(A), simple_expression(B). % ditto
3797 simplep2(lazy_let_pred(_,A,B)) :- simple_predicate(B), simple_expr_or_pred(A).
3798 simplep2(less(A,B)) :- simple_expression(A), simple_expression(B).
3799 simplep2(less_equal(A,B)) :- simple_expression(A), simple_expression(B).
3800 simplep2(greater(A,B)) :- simple_expression(A), simple_expression(B).
3801 simplep2(greater_equal(A,B)) :- simple_expression(A), simple_expression(B).
3802
3803 % detect ID = Expr or Expr = ID
3804 identifier_equality(TExpr,ID,TID,Expr) :- is_equality(TExpr,LHS,RHS),
3805 ( get_texpr_id(LHS,ID), TID=LHS, Expr = RHS
3806 ; get_texpr_id(RHS,ID), TID=RHS, Expr = LHS).
3807
3808
3809 ?id_member_of_set_extension(TExpr,ID,TID,[Expr]) :- identifier_equality(TExpr,ID,TID,Expr).
3810 id_member_of_set_extension(b(member(TID,SEXT),pred,_),ID,TID,SList) :- get_texpr_id(TID,ID),
3811 is_set_extension(SEXT,SList).
3812
3813 % check if merging disjunctions of set_extensionts of this type is useful in CLP(FD) mode
3814 % see get_fd_type in clpfd_tables, ...
3815 type_contains_fd_index(V) :- var(V),!,fail.
3816 type_contains_fd_index(couple(A,_)) :- type_contains_fd_index(A).
3817 type_contains_fd_index(record([field(_,T1)|_])) :- type_contains_fd_index(T1).
3818 type_contains_fd_index(global(_)).
3819 type_contains_fd_index(integer).
3820 type_contains_fd_index(boolean).
3821
3822
3823 create_equalities_for_let(ORefs,Primed,Equalities) :-
3824 maplist(create_equality_for_let,ORefs,Primed,Equalities).
3825 create_equality_for_let(oref(PrimedId,OrigId,Type),TPrimed,Equality) :-
3826 create_texpr(identifier(OrigId),Type,[],TOrig),
3827 create_texpr(identifier(PrimedId),Type,[],TPrimed),
3828 safe_create_texpr(equal(TPrimed,TOrig),pred,Equality).
3829
3830 % inserts a let statement. If the original statement is a precondition or any, the let is moved
3831 % inside the original statement to prevent strange side-effects. This can be used for other,
3832 % non-value changing substitutions as well.
3833 insert_let(TExpr,Ids,P,NTExpr) :-
3834 remove_bt(TExpr,Expr,NewExpr,NTExpr),
3835 move_let_inside(Expr,Old,New,NewExpr),!,
3836 insert_let(Old,Ids,P,New).
3837 insert_let(TExpr,Ids,P,NTExpr) :-
3838 create_texpr(let(Ids,P,TExpr),subst,[],NTExpr).
3839 move_let_inside(precondition(Cond,Old),Old,New,precondition(Cond,New)).
3840 move_let_inside(any(Any,Where,Old),Old,New,any(Any,Where,New)).
3841
3842 % find_one_point_rules(+TypedIds,+Blacklist,+Predicates,
3843 % -LetIds,-LetExprs,-RemainingIds,-RemainingPredicates)
3844 % TypedIds: The ids that are quantified in the exists clause
3845 % Blacklist: All ids that must not be used in the found expression
3846 % Predicates: The predicates of the exists (without already used id=E predicates)
3847 % LetIds: The ids that can be introduced as LET
3848 % LetExprs. For each id (in LetIds) the corresponding expression
3849 % RemainingIds: The ids that are not converted into LETs
3850 % RemainingPredicates: The predicates after removing the id=E predicates
3851 % (e.g., f = {1|->2} & !e.(2:dom(f) & e=f(2) => e>100) should not generate a WD-error)
3852 find_one_point_rules(TIds,Preds,Blacklist,LetIds,Exprs,RestIds,NewPreds) :-
3853 typed_ids_to_avl(TIds,AVL),
3854 find_one_point_equalities(Preds,is_leftmost,AVL,Blacklist,LetIds,Exprs,RestIds,NewPreds).
3855
3856 :- use_module(library(avl),[avl_range/2, avl_fetch/3, avl_delete/4, empty_avl/1]).
3857 :- use_module(bsyntaxtree,[is_equality/3]).
3858 find_one_point_equalities([],_,AVL,_,[],[],RestIds,[]) :-
3859 avl_range(AVL,RestIds).
3860 find_one_point_equalities([TEqual|TPreds],WDLEFT,AVL,Blacklist,LetIds,Exprs,RestIds,NewPreds) :-
3861 split_equality(TEqual,TEq1,TEq2),
3862 %print('Splitting equality: '), translate:print_bexpr(TEqual),nl,
3863 !,
3864 find_one_point_equalities([TEq1,TEq2|TPreds],WDLEFT,AVL,Blacklist,LetIds,Exprs,RestIds,NewPreds).
3865 find_one_point_equalities([TEqual|TPreds],WDLEFT,AVL,Blacklist,[LetID|LetIds],[Expr|Exprs],RestIds,NewPreds) :-
3866 is_equality(TEqual,TA,TB),
3867 ( get_texpr_id(TA,Id),TB=Expr ; get_texpr_id(TB,Id),TA=Expr ),
3868 avl_fetch(Id,AVL,LetID), % we have an equality involving a quantified identifier
3869 %print(wdleft(WDLEFT,Id)),nl, print_bexpr(Expr),nl,
3870 (WDLEFT=is_leftmost
3871 -> true % all the expressions to the left of the equality are well-defined
3872 ; always_defined_full_check_or_disprover_mode(Expr)), % we can lift Id=Expr to an outer LET
3873 % example: UNION(x).(1:dom(f) & x=f(1)|{x}) --> do not lift x=f(1) out if f(1) is not WD, see test 2195
3874 find_identifier_uses_if_necessary(Expr,[],UsedIds),
3875 ord_disjoint(Blacklist,UsedIds),
3876 % TODO: what if we have an equality between two quantified ids in the blacklist?
3877 !,
3878 avl_delete(Id,AVL,_,AVL2),
3879 (empty_avl(AVL2) % check if we have found equalities for all ids
3880 -> NewPreds=TPreds, LetIds=[],Exprs=[],RestIds=[]
3881 ; % should we add Id to Blacklist; usually all ids are already in the blacklist
3882 % WDLEFT remains unchanged
3883 update_wd_to_left(WDLEFT,Expr,NewWDLEFT),
3884 find_one_point_equalities(TPreds,NewWDLEFT,AVL2,Blacklist,LetIds,Exprs,RestIds,NewPreds)
3885 ).
3886 find_one_point_equalities([TEqual|TPreds],_WDLEFT,AVL,Blacklist,LetIds,Exprs,RestIds,[TEqual|NewPreds]) :-
3887 %update_wd_to_left(WDLEFT,Expr,NewWDLEFT),
3888 find_one_point_equalities(TPreds,not_leftmost,AVL,Blacklist,LetIds,Exprs,RestIds,NewPreds).
3889
3890 % update information about whether the next conjunct should still be considered as leftmost concerning WD
3891 update_wd_to_left(is_leftmost,Expr,NewWD) :- always_defined_full_check_or_disprover_mode(Expr),!,
3892 NewWD = is_leftmost.
3893 update_wd_to_left(_,_,not_leftmost).
3894
3895
3896 :- use_module(library(avl),[list_to_avl/2]).
3897 get_avl_aux(TID,Id-TID) :- get_texpr_id(TID,Id).
3898
3899 % convert an unsorted typed identifier list to an AVL tree
3900 typed_ids_to_avl(TIds,AVL) :-
3901 maplist(get_avl_aux,TIds,L),
3902 list_to_avl(L,AVL).
3903
3904
3905 % select a predicate from Preds of the form id=Expr (or Expr=id) where Expr does not contain
3906 % references to identifiers in Blacklist. Rest is Preds without id=Expr
3907 select_equality(TId,Preds,Blacklist,TEqual,Expr,Rest,UsedIds,CheckWellDef) :-
3908 get_texpr_id(TId,Id),
3909 ? safe_select(CheckWellDef,TEqual,Preds,Rest),
3910 is_equality(TEqual,TA,TB), % the ast_cleanup rules have not run yet on the sub-expressions of the exists: detect more equalities
3911 ( get_texpr_id(TA,Id),TB=Expr ; get_texpr_id(TB,Id),TA=Expr ),
3912 find_identifier_uses_if_necessary(Expr,[],UsedIds),
3913 ord_disjoint(Blacklist,UsedIds).
3914
3915
3916 % safely select a predicate from List, preserving WD (well-definedness)
3917 safe_select(check_well_definedness,Element,[H|T],Rest) :- !,
3918 (Element=H,Rest=T % either first element
3919 ; % or if later element; then it must be well-defined; otherwise H could fail
3920 ? select(Element,T,TRest), Rest=[H|TRest],
3921 always_defined_full_check_or_disprover_mode(Element) % we cannot use always_well_defined(Element) in cleanup_pre; it is only computed in cleanup_post at the moment; TO DO: we now do compute in pre phase
3922 %, print(always_wd(Element)),nl
3923 ).
3924 ?safe_select(_,Element,List,Rest) :- select(Element,List,Rest).
3925
3926 % split predicate list into conjuncts using a certain list of ids and those not
3927 split_predicates(LP,Ids,UsingIds,NotUsingIds) :-
3928 get_sorted_ids(Ids,SIds),
3929 ? filter(not_occurs_in_predicate(SIds),LP,NP,UP),
3930 conjunct_predicates_with_pos_info(NP,NotUsingIds),
3931 conjunct_predicates_with_pos_info(UP,UsingIds).
3932
3933 not_occurs_in_predicate([],_Pred) :- !.
3934 not_occurs_in_predicate(SortedIDs,Pred) :- SortedIDs = [ID1|_],
3935 (ID1 = b(_,_,_) -> add_internal_error('Wrapped identifiers: ',not_occurs_in_predicate(SortedIDs,Pred)) ; true),
3936 find_identifier_uses_if_necessary(Pred,[],UsedIds),
3937 ord_disjoint(SortedIDs,UsedIds).
3938 get_sorted_ids(Ids,SIds) :-
3939 get_texpr_ids(Ids,UnsortedIds),sort(UnsortedIds,SIds).
3940
3941 pred_succ_compset(Op,comprehension_set([A,B],Pred)) :-
3942 %get_unique_id('_a_',AId),get_unique_id('_b_',BId),
3943 BId = '_lambda_result_',
3944 (Op = add -> AId = '_succ_' ; AId='_pred_'),
3945 create_texpr(identifier(AId),integer,[],A),
3946 create_texpr(identifier(BId),integer,[lambda_result(BId)],B),
3947 create_texpr(integer(1),integer,[],Integer),
3948 create_texpr(ArithOp,integer,[],TArithOp),
3949 ArithOp =.. [Op,A,Integer],
3950 safe_create_texpr(equal(B,TArithOp),pred,[prob_annotation('LAMBDA-EQUALITY')],Pred).
3951
3952 add_used_identifier_info(_Ids,_P,IOld,INew) :-
3953 ? member(used_ids(_),IOld),!,INew=IOld.
3954 add_used_identifier_info(Ids,P,IOld,[used_ids(FoundIds)|IOld]) :-
3955 % add used identifiers to information
3956 get_sorted_ids(Ids,Ignore),
3957 find_identifier_uses(P,Ignore,FoundIds).
3958
3959 add_used_ids_defined_by_equality(_Ids,P,IOld,INew) :-
3960 ? member(used_ids(UsedIds),IOld),!,
3961 findall(ID, (member_in_conjunction(Equality,P),
3962 identifier_equality(Equality,ID,_TID,Expr),
3963 ord_member(ID,UsedIds),
3964 not_occurs_in_expr(ID,Expr)), % TO DO: we could check also other ids defined by equality already found
3965 IdsDefinedByEquality),
3966 ? (select(used_ids_defined_by_equality(_),IOld,I1) -> true ; I1=IOld),
3967 (IdsDefinedByEquality=[] -> INew=I1
3968 ; %debug_println(9,used_ids_defined_by_equality(IdsDefinedByEquality)),
3969 INew = [used_ids_defined_by_equality(IdsDefinedByEquality)|I1]
3970 ).
3971 add_used_ids_defined_by_equality(Ids,P,IOld,INew) :-
3972 add_internal_error('No used_ids info:',add_used_ids_defined_by_equality(Ids,P,IOld,INew)),
3973 INew=IOld.
3974
3975
3976 % can be used to check the validity of the used_ids field, e.g., for existential quantifier
3977 check_used_ids_info(Parameters,Predicate,StoredUsedIds,PP) :-
3978 % get_global_identifiers(Ignored), and add to Parameters ??
3979 (add_used_identifier_info(Parameters,Predicate,[],[used_ids(UsedIds)])
3980 -> (StoredUsedIds=UsedIds -> true
3981 ; ord_subset(UsedIds,StoredUsedIds)
3982 -> format('Suboptimal used_ids info: ~w (actual ~w) [origin ~w with ~w]~n',[StoredUsedIds,UsedIds,PP,Parameters])
3983 %, print_bexpr(Predicate),nl
3984 ; add_internal_error('Incorrect used_ids info: ', check_used_ids_info(Parameters,Predicate,UsedIds,PP)),
3985 print_bexpr(Predicate),nl,
3986 (extract_span_description(Predicate,PosMsg) -> format('Location: ~w~n',[PosMsg]) ; true),
3987 ord_subtract(UsedIds,StoredUsedIds,Delta),
3988 format('Incorrect used_ids info: ~w (actual ~w)~nNot included: ~w~n~n',[StoredUsedIds,UsedIds,Delta])
3989 %, print_bexpr(Predicate),nl
3990 )
3991 ; add_internal_error('Could not computed used ids:',
3992 add_used_identifier_info(Parameters,Predicate,[],[used_ids(_)]))
3993 ).
3994
3995 % update used_ids_info for existential and universal quantifier (at top-level only !)
3996 recompute_used_ids_info(b(E,pred,Info0),Res) :-
3997 delete(Info0,used_ids(_),Info1),
3998 recompute_used_ids_info_aux(E,Info1,Info2),!, Res= b(E,pred,Info2).
3999 recompute_used_ids_info(TE,TE).
4000
4001 compute_used_ids_info_if_necessary(b(E,pred,Info1),Res) :-
4002 recompute_used_ids_info_aux(E,Info1,Info2),!, Res= b(E,pred,Info2).
4003 compute_used_ids_info_if_necessary(TE,TE).
4004
4005 recompute_used_ids_info_aux(exists(Parameters,Predicate),Info1,Info2) :-
4006 add_used_identifier_info(Parameters,Predicate,Info1,Info2).
4007 recompute_used_ids_info_aux(forall(Parameters,Lhs,Rhs),Info1,Info2) :-
4008 conjunct_predicates([Lhs,Rhs],Predicate),
4009 add_used_identifier_info(Parameters,Predicate,Info1,Info2).
4010 % for while loop we could recompute modifies and reads info
4011
4012 % generation of unique identifiers
4013 :- dynamic unique_id_counter/1.
4014 unique_id_counter(1).
4015
4016 get_unique_id_inside(Prefix,Pred,ResultId) :-
4017 (\+ occurs_in_expr(Prefix,Pred) % first try and see whether we need to append a number
4018 -> ResultId = Prefix
4019 ; get_unique_id(Prefix,ResultId)
4020 ).
4021 get_unique_id_inside(Prefix,Pred,Expr,ResultId) :-
4022 ( \+ occurs_in_expr(Prefix,Pred),
4023 \+ occurs_in_expr(Prefix,Expr) % first try and see whether we need to append a number
4024 -> ResultId = Prefix
4025 ; get_unique_id(Prefix,ResultId)
4026 ).
4027
4028 get_unique_id(Prefix,Id) :-
4029 retract(unique_id_counter(Old)),
4030 New is Old + 1,
4031 assertz(unique_id_counter(New)),
4032 safe_atom_chars(Prefix,CPrefix,get_unique_id1),
4033 number_chars(Old,CNumber),
4034 append(CPrefix,CNumber,CId),
4035 safe_atom_chars(Id,CId,get_unique_id2).
4036
4037 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4038 % replace all variables in types by "any"
4039
4040 ground_type_to_any(T,Exceptions) :- var(T),!,
4041 ( exact_member(T,Exceptions) -> ! % any variable exact member in list is not grounded
4042 ; T=any).
4043 ground_type_to_any(record(Fields),Exceptions) :- !,
4044 % treat records separately, we do not want the list of fields to be bound to any; see B/Tickets/RecordPartiallyTyped
4045 ground_field_types(Fields,Exceptions).
4046 ground_type_to_any(T,_) :- ground(T),!.
4047 ground_type_to_any(T,Exceptions) :-
4048 functor(T,_,Arity),
4049 ground_type_args(Arity,T,Exceptions).
4050 ground_type_args(0,_T,_Exceptions) :- !.
4051 ground_type_args(N,T,Exceptions) :-
4052 arg(N,T,Arg),
4053 ground_type_to_any(Arg,Exceptions),
4054 N2 is N-1,
4055 ground_type_args(N2,T,Exceptions).
4056
4057 ground_field_types(T,Exceptions) :- var(T),!,
4058 ( exact_member(T,Exceptions) -> ! % any variable exact member in list is not grounded
4059 ; print(grounding_open_ended_record),nl, % should we generate a warning here ?
4060 T=[]
4061 ).
4062 ground_field_types([],_) :- !.
4063 ground_field_types([field(Name,Type)|T],Exceptions) :- !,
4064 (var(Name)
4065 -> add_internal_error('Unbound record field name: ',ground_field_types([field(Name,Type)|T],Exceptions))
4066 ; true),
4067 ground_type_to_any(Type,Exceptions),
4068 ground_field_types(T,Exceptions).
4069 ground_field_types(Other,Exceptions) :-
4070 add_internal_error('Illegal record field list: ',ground_field_types(Other,Exceptions)).
4071
4072 % annote variables of becomes_such with before_substitution infos
4073 annotate_becomes_such_vars(Ids1,Pred,Ids2) :-
4074 find_used_primed_ids(Pred,Ids1,BeforeAfter),
4075 maplist(add_before_after_info(BeforeAfter),Ids1,Ids2).
4076 % put optional before/after usage into the information of the identifiers
4077 % makes only sense in the context of becomes_such substitutions
4078 add_before_after_info(BeforeAfter,TId,TId2) :-
4079 def_get_texpr_id(TId,Id),
4080 ( member(ba(Id,BeforeId),BeforeAfter) ->
4081 get_texpr_type(TId,Type), get_texpr_info(TId,Info),
4082 create_texpr(identifier(Id),Type,[before_substitution(Id,BeforeId)|Info],TId2)
4083 ; TId = TId2 ).
4084
4085 % find all used pairs of before/after variables, e.g. ba(x,'x$0')
4086 % see becomes_such substitutions
4087 find_used_primed_ids(TExpr,PossibleIds,Uses) :-
4088 prime_identifiers0(PossibleIds,TP0),
4089 get_sorted_ids(TP0,SP0), % sorted list of primed ids
4090 find_used_primed_ids2(SP0,TExpr,[],Uses).
4091 find_used_primed_ids2(SP0,TExpr,In,Out) :-
4092 syntaxtraversion(TExpr,Expr,_,_Infos,Subs,_),
4093 ( (Expr = identifier(FullId),
4094 %member(before_substitution(Id,FullId),Infos) % this info is not available in Event-B mode
4095 ord_member(FullId,SP0),
4096 prime_atom0(Id,FullId))
4097 -> ord_add_element(In,ba(Id,FullId),Uses)
4098 ; In = Uses ),
4099 foldl(find_used_primed_ids2(SP0),Subs,Uses,Out).
4100
4101 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4102 % find expressions which are possibly not well-defined
4103 is_possibly_undefined(Expr) :- always_wd(Expr),!,fail.
4104 is_possibly_undefined(Expr) :-
4105 safe_syntaxelement_det(Expr,Subs,_Names,_,_),
4106 % note: can be very long list Subs for set_extension
4107 ? member(Sub,Subs),
4108 get_texpr_info(Sub,Info),
4109 memberchk(contains_wd_condition,Info),!.
4110 is_possibly_undefined(Expr) :-
4111 ? has_top_level_wd_condition(Expr). %%,print(wd(F,Expr)),nl.
4112
4113 has_top_level_wd_condition(Expr) :- functor(Expr,F,_),
4114 ? has_wd_condition(F,Expr).
4115
4116 % a few common cases which are always defined:
4117 always_wd(bool_set).
4118 always_wd(boolean_false).
4119 always_wd(boolean_true).
4120 always_wd(empty_set).
4121 always_wd(identifier(_)).
4122 always_wd(integer(_)).
4123 always_wd(integer_set(_)).
4124 always_wd(real_set).
4125 always_wd(real(_)).
4126 always_wd(string(_)).
4127 always_wd(string_set).
4128 %always_wd(value(_)). ?
4129 always_wd(truth).
4130
4131
4132 always_defined_full_check_or_disprover_mode(_) :- preferences:get_preference(disprover_mode,true),!.
4133 always_defined_full_check_or_disprover_mode(BExpr) :- \+ full_check_is_possibly_undefined(BExpr).
4134
4135 % a version which does the full traversal; can be used before contains_wd_condition has been computed
4136 full_check_is_possibly_undefined(BExpr) :- get_texpr_expr(BExpr,Expr),
4137 full_check_is_possibly_undefined_aux(Expr).
4138 full_check_is_possibly_undefined_aux(Expr) :-
4139 functor(Expr,F,_),has_wd_condition(F,Expr),!.
4140 full_check_is_possibly_undefined_aux(Expr) :-
4141 syntaxtraversion(_,Expr,_,_,Subs,_),
4142 ? member(Sub,Subs),
4143 full_check_is_possibly_undefined(Sub),!.
4144
4145 :- use_module(external_functions,[external_fun_has_wd_condition/1]).
4146 % determine if an operator has an attached WD condition (used to compute contains_wd_condition)
4147 % division and module must not divide by zero
4148 has_wd_condition(div,Expr) :- arg(2,Expr,DIV),
4149 ? \+ definitely_not_zero(DIV).
4150 has_wd_condition(floored_div,Expr) :- arg(2,Expr,DIV),
4151 ? \+ definitely_not_zero(DIV).
4152 has_wd_condition(div_real,Expr) :- arg(2,Expr,DIV),
4153 \+ definitely_not_zero(DIV).
4154 % functions must not be applied to values outside their domain
4155 has_wd_condition(function,_Expr). % if lambda over total domain we could remove wd_condition, but ast_cleanup rule then already replaces it with assertion_expression, which gets optimised away in this case
4156 has_wd_condition(assertion_expression,_). % gets translated from function application
4157 has_wd_condition(modulo,Expr) :- arg(2,Expr,DIV),
4158 ? (\+ definitely_not_zero(DIV) ;
4159 \+ definitely_not_negative(DIV) ;
4160 arg(1,Expr,A1), \+ definitely_not_negative(A1)).
4161 % power_of must have a non-negative exponent (?)
4162 has_wd_condition(power_of,Expr) :- arg(2,Expr,EXP),
4163 \+ definitely_not_negative(EXP).
4164 has_wd_condition(power_of_real,Expr) :- arg(1,Expr,Base), arg(2,Expr,EXP),
4165 (definitely_not_negative(Base)
4166 -> (definitely_not_zero(Base) -> fail % no WD if base > 0
4167 ; definitely_not_negative(EXP) -> fail % 0.0 ^ EXP is defined if EXP >=0
4168 ; true % 0.0 ^ -1.0 is a division by zero
4169 )
4170 ; true). % things like -1.0 ^ 0.5 is not a real number; we could check if EXP is guaranteed an integ
4171 % Note: REAL ** INTEGER has no WD condition, but power_of_real has a WD condition
4172 has_wd_condition(iteration,Expr) :- arg(2,Expr,Idx),
4173 \+ definitely_not_negative(Idx).
4174 % min and max need a non-empty set
4175 % also Atelier-B manual requires the set to have an upper limit
4176 has_wd_condition(max,Expr) :- arg(1,Expr,S), \+ definitely_not_empty_and_finite(S).
4177 has_wd_condition(min,Expr) :- arg(1,Expr,S), \+ definitely_not_empty_and_finite(S).
4178 has_wd_condition(max_real,Expr) :- arg(1,Expr,S), \+ definitely_not_empty_and_finite(S).
4179 has_wd_condition(min_real,Expr) :- arg(1,Expr,S), \+ definitely_not_empty_and_finite(S).
4180 % all the sequence operations must not be applied to non-sequence
4181 % relations and some must not be applied to empty-sequences
4182 has_wd_condition(size,E) :- arg(1,E,S), \+ definitely_sequence(S).
4183 has_wd_condition(first,E) :- arg(1,E,S), \+ definitely_not_empty_sequence(S).
4184 has_wd_condition(last,E) :- arg(1,E,S), \+ definitely_not_empty_sequence(S).
4185 has_wd_condition(front,E) :- arg(1,E,S), \+ definitely_not_empty_sequence(S).
4186 has_wd_condition(tail,E) :- arg(1,E,S), \+ definitely_not_empty_sequence(S).
4187 has_wd_condition(rev,E) :- arg(1,E,S), \+ definitely_sequence(S).
4188 has_wd_condition(concat,_).
4189 has_wd_condition(insert_front,_).
4190 has_wd_condition(insert_tail,_).
4191 has_wd_condition(restrict_front,_).
4192 has_wd_condition(restrict_tail,_).
4193 has_wd_condition(general_concat,_).
4194 % the general intersection must not be applied to an empty set of sets
4195 has_wd_condition(general_intersection,Expr) :- arg(1,Expr,S),
4196 \+ definitely_not_empty(S).
4197 has_wd_condition(quantified_intersection,_). % gets translated to general_intersection
4198 % card must not be applied to infinite sets:
4199 has_wd_condition(card,Expr) :- arg(1,Expr,S), \+ definitely_finite(S).
4200 has_wd_condition(general_sum,_). % TO DO: \+ definitely_finite2(comprehension_set(Ids,P))
4201 has_wd_condition(general_product,_). % ditto; note: sets which are summed/multiplied must be finite
4202 has_wd_condition(mu,_). % Z MU Operator
4203 has_wd_condition(freetype_destructor,_).
4204 has_wd_condition(external_function_call,Expr) :- arg(1,Expr,FunName),
4205 external_fun_has_wd_condition(FunName).
4206 has_wd_condition(external_pred_call,Expr) :- arg(1,Expr,FunName),
4207 external_fun_has_wd_condition(FunName).
4208 % external_subst_call?
4209 has_wd_condition(operation_call_in_expr,_). % we now assume all operation calls may have PRE-conditions
4210 % or involve recursion, and thus may loop; TO DO: compute this information per operation by a fixpoint algorithm
4211
4212 definitely_not_zero(b(integer(X),integer,_)) :- integer(X), X \= 0.
4213 definitely_not_zero(b(real(X),real,_)) :- atom(X), construct_real(X,R), R \= 0.0.
4214 definitely_not_negative(b(integer(X),integer,_)) :- number(X), X >= 0.
4215 % to do add more ?: card(_), ...
4216
4217 definitely_not_empty(b(S,_,_)) :- def_not_empty2(S).
4218 def_not_empty2(set_extension([_|_])).
4219 def_not_empty2(sequence_extension([_|_])).
4220 def_not_empty2(union(A,B)) :- (definitely_not_empty(A) -> true ; definitely_not_empty(B)).
4221 def_not_empty2(value(S)) :- % what about closures ?
4222 definitely_not_empty_finite_value(S).
4223 % TODO: add more cases; but currently only used for general_intersection
4224
4225 definitely_not_empty_and_finite(b(S,_,_)) :- def_not_empty_fin2(S).
4226 def_not_empty_fin2(bool_set).
4227 def_not_empty_fin2(set_extension([_|_])).
4228 def_not_empty_fin2(sequence_extension([_|_])).
4229 def_not_empty_fin2(cartesian_product(A,B)) :- definitely_not_empty_and_finite(A), definitely_not_empty_and_finite(B).
4230 def_not_empty_fin2(union(A,B)) :- definitely_not_empty_and_finite(A), definitely_not_empty_and_finite(B).
4231 def_not_empty_fin2(overwrite(A,B)) :- definitely_not_empty_and_finite(A),definitely_not_empty_and_finite(B).
4232 def_not_empty_fin2(interval(A,B)) :- definitely_not_empty_set(b(interval(A,B),set(integer),[])).
4233 def_not_empty_fin2(value(S)) :- % what about closures ?
4234 definitely_not_empty_finite_value(S). %kernel_objects:not_empty_set(S).
4235
4236 definitely_not_empty_finite_value(S) :- var(S),!,fail.
4237 definitely_not_empty_finite_value([_|_]). % we assume no infinite closure at end
4238 definitely_not_empty_finite_value(avl_set(_)).
4239 %definitely_not_empty_value(closure(P,T,B)) :-
4240
4241 definitely_not_empty_sequence(b(S,_,_)) :- definitely_not_empty_sequence2(S).
4242 definitely_not_empty_sequence2(sequence_extension(_)).
4243
4244 definitely_sequence(b(S,_,_)) :- definitely_sequence2(S).
4245 definitely_sequence2(empty_sequence).
4246 definitely_sequence2(sequence_extension(_)).
4247
4248 :- use_module(typing_tools,[is_provably_finite_type/1, is_infinite_type/1]).
4249 is_infinite_ground_type(Type) :-
4250 ground(Type), is_infinite_type(Type). % non-ground types happen e.g. in test 472
4251
4252 definitely_finite(b(S,Type,_)) :-
4253 (ground(Type)
4254 -> (is_provably_finite_type(Type)
4255 -> true
4256 ; definitely_finite2(S) -> true
4257 %; \+ is_infinite_type(Type) -> print(no_longer_assuming_finite(Type)),nl,nl,fail
4258 )
4259 ; definitely_finite2(S)).
4260 definitely_finite2(bool_set).
4261 definitely_finite2(empty_set).
4262 definitely_finite2(empty_sequence).
4263 definitely_finite2(set_extension(_)).
4264 definitely_finite2(sequence_extension(_)).
4265 definitely_finite2(cartesian_product(A,B)) :- definitely_finite(A), definitely_finite(B).
4266 definitely_finite2(overwrite(A,B)) :- definitely_finite(A), definitely_finite(B).
4267 definitely_finite2(union(A,B)) :- definitely_finite(A), definitely_finite(B).
4268 definitely_finite2(intersection(A,B)) :- (definitely_finite(A) -> true ; definitely_finite(B)).
4269 definitely_finite2(set_subtraction(A,_)) :- definitely_finite(A).
4270 definitely_finite2(domain_restriction(_,B)) :- definitely_finite(B). % A finite does not guarantee finite relation
4271 definitely_finite2(domain_subtraction(_,B)) :- definitely_finite(B).
4272 definitely_finite2(range_restriction(A,_)) :- definitely_finite(A). % B finite does not guarantee finite relation
4273 definitely_finite2(range_subtraction(A,_)) :- definitely_finite(A).
4274 definitely_finite2(interval(_,_)).
4275 definitely_finite2(value(S)) :- nonvar(S),(S=[] ; S=avl_set(_)).
4276 % TO DO: add other operators : comprehension_set(Ids,P)
4277
4278
4279 ?definitely_infinite(b(S,_,_)) :- !,definitely_infinite2(S).
4280 definitely_infinite(S) :- add_internal_error('AST not wrapped:',definitely_infinite(S)),fail.
4281 definitely_infinite2(string_set).
4282 definitely_infinite2(real_set).
4283 definitely_infinite2(integer_set(X)) :-
4284 X='NATURAL' ; X='NATURAL1' ; X='INTEGER'.
4285 definitely_infinite2(seq1(S)) :- definitely_not_empty_set(S).
4286 definitely_infinite2(seq(S)) :- definitely_not_empty_set(S).
4287 definitely_infinite2(cartesian_product(A,B)) :- is_infinite_cart_prod(A,B).
4288 ?definitely_infinite2(pow_subset(S)) :- definitely_infinite(S).
4289 definitely_infinite2(pow1_subset(S)) :- definitely_infinite(S).
4290 definitely_infinite2(fin_subset(S)) :- definitely_infinite(S). % the set of finite subsets is infinite
4291 definitely_infinite2(fin1_subset(S)) :- definitely_infinite(S).
4292 definitely_infinite2(iseq(S)) :- definitely_infinite(S).
4293 definitely_infinite2(iseq1(S)) :- definitely_infinite(S).
4294 definitely_infinite2(perm(S)) :- definitely_infinite(S).
4295 ?definitely_infinite2(value(V)) :- infinite_value_set(V).
4296 definitely_infinite2(relations(A,B)) :- is_infinite_cart_prod(A,B).
4297 definitely_infinite2(partial_function(A,B)) :- is_infinite_cart_prod(A,B).
4298 definitely_infinite2(total_function(A,B)) :-
4299 (definitely_infinite(A) -> definitely_not_empty_set_card_gt1(B) % INTEGER-->{1} is finite, INTEGER-->BOOL is inf.
4300 ? ; definitely_infinite(B) -> definitely_not_empty_set(A)). % {TRUE} --> INTEGER is infinite
4301 definitely_infinite2(total_relation(A,B)) :- definitely_infinite2(total_function(A,B)).
4302 % TODO: partial_injection, total_injection, partial_surjection, total_surjection, total_bijection, partial_bijection,
4303 % surjection_relation, total_surjection_relation
4304 % cf total_surjection_card
4305
4306 % non empty sets with at least two elements:
4307 definitely_not_empty_set_card_gt1(bool_set).
4308 definitely_not_empty_set_card_gt1(A) :- definitely_infinite(A).
4309
4310 is_infinite_cart_prod(A,B) :-
4311 (definitely_infinite(A) -> definitely_not_empty_set(B) % INTEGER*{} is finite
4312 ? ; definitely_infinite(B) -> definitely_not_empty_set(A)).
4313
4314 infinite_value_set(V) :- var(V),!,fail.
4315 infinite_value_set(global_set(X)) :-
4316 X='NATURAL' ; X='NATURAL1' ; X='INTEGER'.
4317 infinite_value_set(closure(P,T,B)) :-
4318 % T \= [integer], % otherwise we could intersect with NATURAL,... ????
4319 custom_explicit_sets:is_infinite_closure(P,T,B).
4320 infinite_value_set(freetype(ID)) :- kernel_freetypes:is_infinite_freetype(ID).
4321
4322
4323
4324
4325 % check if %(Ids).(Pred|_) is infinite
4326 infinite_or_symbolic_domain_for_lambda(Ids,b(Expr,pred,_),Kind) :-
4327 ? inf_dom_aux(Expr,Ids,Kind).
4328 inf_dom_aux(member(TID2,InfSet),[TID],infinite) :- same_id(TID,TID2,_),
4329 ? definitely_infinite(InfSet).
4330 inf_dom_aux(truth,Ids,infinite) :-
4331 ? member(TID,Ids), get_texpr_type(TID,Type),
4332 is_infinite_ground_type(Type).
4333 inf_dom_aux(COMP,[TID|_],infinite) :- % A \= "" or A \= 0 or A \= B+1 or A < B*B or ...
4334 ? binary_inf_comparison(COMP,A,B),
4335 get_texpr_type(TID,Type), is_infinite_ground_type(Type),
4336 same_id(A,TID,ID),
4337 not_occurs_in_expr(ID,B). % ensure B does not depend on A; e.g. we have %x.(x/=x | E) is empty
4338 inf_dom_aux(equal(EXTFUN,BOOL),Ids,symbolic) :-
4339 % something like f = %s.(s:STRING & REGEX_MATCH(s,"[a-z]+")=TRUE | s)
4340 get_texpr_expr(EXTFUN,external_function_call(FUN,Args)),
4341 get_texpr_boolean(BOOL,_),
4342 is_symbolic_ext_pred(FUN,Args,Ids).
4343 inf_dom_aux(external_pred_call(FUN,Args),Ids,symbolic) :-
4344 is_symbolic_ext_pred(FUN,Args,Ids).
4345
4346 % a comparator which allows infinitely many values for first argument with fixed second argument
4347 binary_inf_comparison(not_equal(A,B),AA,BB) :- sym_unify(A,B,AA,BB).
4348 binary_inf_comparison(less(A,B),AA,BB) :- sym_unify(A,B,AA,BB).
4349 binary_inf_comparison(less_equal(A,B),AA,BB) :- sym_unify(A,B,AA,BB).
4350 ?binary_inf_comparison(greater(A,B),AA,BB) :- sym_unify(A,B,AA,BB).
4351 binary_inf_comparison(greater_equal(A,B),AA,BB) :- sym_unify(A,B,AA,BB).
4352
4353 sym_unify(A,B,A,B).
4354 sym_unify(A,B,B,A).
4355
4356 % not guaranteed to be infinite, but makes sense to keep symbolic
4357 is_symbolic_ext_pred(FUN,Args,[TID|_]) :-
4358 symbolic_ext_pred(FUN),
4359 def_get_texpr_id(TID,ID),
4360 (member(A,Args), occurs_in_expr(ID,A) -> true). % ensure the condition is not static and depends on an argument
4361
4362 % external predicates which indicate that the corresponding function should be kept symbolic
4363 symbolic_ext_pred('IS_REGEX').
4364 symbolic_ext_pred('GET_IS_REGEX').
4365 symbolic_ext_pred('REGEX_MATCH').
4366 symbolic_ext_pred('REGEX_IMATCH').
4367 symbolic_ext_pred('GET_IS_REGEX_MATCH').
4368 symbolic_ext_pred('GET_IS_REGEX_IMATCH').
4369 symbolic_ext_pred('STRING_EQUAL_CASE_INSENSITIVE').
4370 symbolic_ext_pred('STRING_IS_ALPHANUMERIC').
4371 symbolic_ext_pred('STRING_IS_DECIMAL').
4372 symbolic_ext_pred('STRING_IS_NUMBER').
4373 symbolic_ext_pred('GET_STRING_EQUAL_CASE_INSENSITIVE').
4374 symbolic_ext_pred('GET_STRING_IS_ALPHANUMERIC').
4375 symbolic_ext_pred('GET_STRING_IS_DECIMAL').
4376 symbolic_ext_pred('GET_STRING_IS_NUMBER').
4377 symbolic_ext_pred('GET_STRING_IS_INT').
4378 symbolic_ext_pred('FILE_EXISTS').
4379 symbolic_ext_pred('GET_FILE_EXISTS').
4380 symbolic_ext_pred('DIRECTORY_EXISTS').
4381 symbolic_ext_pred('GET_DIRECTORY_EXISTS').
4382 % TODO: add more external predicates
4383 %symbolic_ext_pred(X) :- nl,print(not_symbolic(X)),nl,fail.
4384
4385
4386 :- use_module(custom_explicit_sets,[quick_is_definitely_maximal_set/1]).
4387 % should we use is_just_type/1 instead ?? TO DO: check
4388 definitely_maximal_set(b(S,_,_)) :- definitely_maximal2(S).
4389 definitely_maximal2(integer_set('INTEGER')).
4390 definitely_maximal2(bool_set).
4391 definitely_maximal2(string_set).
4392 definitely_maximal2(typeset).
4393 definitely_maximal2(comprehension_set(_,b(truth,_,_))). % also covers is_integer_set(X,'INTEGER')
4394 definitely_maximal2(value(S)) :- nonvar(S),quick_is_definitely_maximal_set(S).
4395 % TO DO: cartesian product, records, ... if useful
4396
4397
4398 % just a sequence consisting of a single element
4399 is_singleton_sequence(b(sequence_extension([ELEMENT]),_,_),ELEMENT).
4400
4401 % check if type does not contain sets
4402 type_contains_no_sets(X) :- var(X),!,fail. % in test 472 we have a variable type
4403 type_contains_no_sets(integer).
4404 type_contains_no_sets(boolean).
4405 type_contains_no_sets(string).
4406 type_contains_no_sets(global(_)).
4407 type_contains_no_sets(couple(A,B)) :- type_contains_no_sets(A), type_contains_no_sets(B).
4408 type_contains_no_sets(record(Fields)) :- field_types_ok(Fields).
4409 field_types_ok([]).
4410 field_types_ok([field(_,Type)|T]) :- type_contains_no_sets(Type), field_types_ok(T).
4411
4412 % ----------------------------------
4413
4414
4415 select_conjunct(Predicate,Conjunction,Prefix,Suffix) :-
4416 conjunction_to_list(Conjunction,List),
4417 append(Prefix,[Predicate|Suffix],List).
4418
4419
4420 data_validation_mode :-
4421 (get_preference(data_validation_mode,true) -> true
4422 ; environ(prob_data_validation_mode,true)).
4423
4424 % optionally provide hints about rewritings or potential improvements
4425 add_hint_message(_,_Msg,_Term,_Span) :- debug_mode(off),
4426 get_preference(performance_monitoring_on,false), % should we use another preference?
4427 !.
4428 add_hint_message(Src,Msg,Term,Span) :-
4429 add_message(Src,Msg,Term,Span).
4430
4431 % ------------------------
4432
4433 % mini partial evaluation / constant expression evaluation of B expressions
4434 % TO DO: unify with b_compile and b_expression_sharing !
4435 % But this one only pre-computes top-level operators; assumes bottom-up traversal
4436
4437 :- use_module(kernel_objects,[safe_pown/3]).
4438 pre_compute_static_int_expression(add(A,B),Result) :- % plus
4439 get_integer(A,IA), get_integer(B,IB),
4440 Result is IA+IB.
4441 pre_compute_static_int_expression(minus(A,B),Result) :- % plus
4442 get_integer(A,IA), get_integer(B,IB),
4443 Result is IA-IB.
4444 pre_compute_static_int_expression(unary_minus(A),Result) :- % plus
4445 get_integer(A,IA),
4446 Result is -IA.
4447 pre_compute_static_int_expression(multiplication(A,B),Result) :-
4448 get_integer(A,IA), get_integer(B,IB),
4449 Result is IA*IB.
4450 pre_compute_static_int_expression(div(A,B),Result) :- % TO DO: also add floored_div
4451 get_integer(B,IB), IB \= 0,
4452 get_integer(A,IA),
4453 Result is IA//IB.
4454 pre_compute_static_int_expression(modulo(A,B),Result) :-
4455 get_integer(B,IB), IB > 0,
4456 get_integer(A,IA), IA >= 0,
4457 Result is IA mod IB.
4458 pre_compute_static_int_expression(power_of(A,B),Result) :-
4459 get_integer(A,IA), get_integer(B,IB), IB >= 0,
4460 safe_pown(IA,IB,Result), number(Result).
4461
4462 % ----------------------------------------
4463