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(bsyntaxtree,
6 [is_texpr/1, % checks if the given argument is a typed expression
7
8 get_texpr_expr/2, % get the expression part of a typed expression
9 get_texpr_type/2, % get the type of a typed expression
10 get_texpr_info/2, % get the list of information of a typed expression
11 get_texpr_id/2, % get the id of a typed identifier, fails if it's not an identifier
12 def_get_texpr_id/2, % same as above, but raises error if arg1 is not an identifier
13 def_get_texpr_ids/2, % maplist of the above, i.e., translate a typed id list into a plain list of id names
14 create_typed_id/3, % create a typed identifier
15 same_id/3, % true if two typed identifiers have the same id
16 same_ids/2, % true if two lists of typed identifiers have the same ids
17 same_ids_and_types/2, % also check types
18 split_names_and_types/3, % split list of typed ids into ids and types
19 get_texpr_exprs/2, % list variant of the above
20 get_texpr_types/2, % list variant of the above
21 get_texpr_infos/2, % list variant of the above
22 get_texpr_ids/2, % list variant of the above
23 get_texpr_pos/2, % get the position of a typed expression
24 extract_pos_infos/2, % get the position info sub list of an info list
25 copy_pos_infos/3, % copy position infos from one typed expression to another
26 delete_pos_info/2, % delete position info from an info list
27 merge_info/3, % merge two information lists as well as possible
28 update_infos/3, % provide updates to an existing info list
29 get_info_pos/2, % get the position directly from info field
30 contains_info_pos/1, % true if info field contains position infos
31
32 same_texpr/2, % check if two typed expressions are equal modulo Info fields
33 different_texpr_values/2, % check if two type expressions are WD and definitely denote different values
34
35 create_texpr/4, % creates a typed expression by giving expression, type and infos
36 add_texpr_infos/3, % adds some more information to a typed expression at front
37 add_texpr_info_if_new/3, % adds one info field to typed B expression info list at front if it is new
38 add_texpr_infos_if_new/3, % ditto but list of infos can be added
39 add_info_if_new/3, % adds to info list
40 add_infos_if_new/3, % same for list of info items
41 safe_create_texpr/3, % a version of create_texpr which extracts wd-info from sub-expressionssafe_create_texpr
42 safe_create_texpr/4,
43 texpr_contains_wd_condition/1,
44 sub_expression_contains_wd_condition/1, % utility to check if sub-expression contains wd condition
45
46 get_rodin_name/2, get_rodin_model_name/2,
47 is_rodin_label_info/1,
48 get_texpr_label/2, get_texpr_labels/2,
49 get_info_labels/2, select_info_labels/3,
50 add_labels_to_texpr/3,
51 get_texpr_description/2, % get @desc pragma for typed expression
52 add_texpr_description/3, % add an additional description by hand
53 info_has_ignore_pragma/1, % check if an info list has an ignore pragma
54 predicate_has_ignore_pragma/1, % ditto for the info list of a predicate
55 always_well_defined/1, always_well_defined_or_disprover_mode/1,
56 always_well_defined_or_wd_reorderings_allowed/1,
57 always_well_defined_or_wd_improvements_allowed/1,
58 finite_wd_set_value/1, finite_set_or_disprover_mode/1,
59 is_truth/1, is_falsity/1,
60 conjunct_predicates/2,
61 conjunct_predicates_with_pos_info/3, conjunct_predicates_with_pos_info/2,
62 is_a_conjunct/3, is_a_conjunct_without_label/3, decompose_conjunct/3,
63 is_a_disjunct/3, is_an_implication/3, is_an_equivalence/3, is_a_negation/2,
64 conjunction_to_list/2,
65 conjunction_to_list_with_rodin_labels/2, % a variation which propagates labels down to conjuncts
66 member_in_conjunction/2, select_member_in_conjunction/3,
67 flatten_conjunctions/2,
68 size_of_conjunction/2,
69 member_in_conjunction_cse/3,
70 disjunct_predicates/2,
71 disjunct_predicates_with_pos_info/3,
72 disjunction_to_list/2,
73 is_a_disjunct_or_implication/4,
74 is_a_conjunct_or_neg_disj/3,
75
76 predicate_components/2, % split a predicate into components which use distinct identifiers
77 predicate_components_in_scope/3, % ditto with an optional list of local variables
78 predicate_components_with_restriction/4,
79 predicate_identifiers/2, predicate_identifiers_in_scope/3,
80
81 project_predicate_on_identifiers/5,
82
83 find_identifier_uses_top_level/2, % not including global sets and constants
84 find_identifier_uses/3, find_identifier_uses_if_necessary/3,
85 find_identifier_uses_l/3,
86 find_typed_identifier_uses/3,
87 find_typed_identifier_uses/2, % not including global sets and constants
88 find_typed_identifier_uses_l/3,
89 get_global_identifiers/1, get_global_identifiers/2,
90 occurs_in_expr/2, some_id_occurs_in_expr/2,
91 single_usage_identifier/3,
92 update_used_ids/3,
93 check_computed_used_ids/2,
94
95 create_exists/3, create_or_merge_exists/3,
96 create_exists_or_let_predicate/3,
97 create_exists_opt_liftable/3,
98 create_exists_opt/3, create_exists_opt/4, create_exists_opt/5,
99 create_forall/3,
100 create_negation/2, is_negation_of/2, get_negated_operator_expr/2,
101 create_implication/3,
102 create_equivalence/3,
103 is_equality/3,
104 create_equality/3, split_equality/3, get_texpr_couple/3,
105 create_couple/3, create_couple/2, nested_couple_to_list/2,
106 create_comprehension_set/4,
107 is_eventb_comprehension_set/4, is_eventb_comprehension_set/6,
108 singleton_set_extension/2,
109 is_membership/3, is_membership_or_equality/3,
110 is_pow_subset/2, is_pow1_subset/2,
111
112 detect_global_predicates/4,
113
114 definitely_not_empty_set/1, definitely_empty_set/1,
115 get_integer/2,
116 get_interval/3,
117
118 replace_id_by_expr/4,
119 replace_id_by_expr_with_count/5, % also count number of replacements
120 replace_ids_by_exprs/4,
121 remove_used_id_from_info/3, % remove an id from used_id info field if it exists
122 remove_used_ids_from_info/3, % remove list of ids (order of args different !)
123
124 rename_bt/3, % a simplified version of replace_ids_by_exprs, which assumes target of renamings are variables
125 rename_bt_l/3,
126 remove_bt/4,
127 syntaxtransformation/5,
128 syntaxtransformation_det/5, % faster, non-backtracking version
129
130 map_over_bexpr/2, map_over_typed_bexpr/2, map_over_typed_bexpr/3,
131 map_over_typed_bexpr_with_names/2,
132 map_over_bexpr_top_down_acc/3, map_over_typed_bexpr_top_down_acc/3,
133 reduce_over_bexpr/4,
134 transform_bexpr/3, % transform a typed B expression bottom-up
135 transform_bexpr_with_scoping/3, % ditto, but we also provide info about local ids
136 transform_bexpr_with_bup_accs/5, transform_bexpr_with_acc/5,
137 non_det_transform_bexpr_with_acc/5, % can be used to generate several transformed expressions
138 uses_implementable_integers/1,
139 min_max_integer_value_used/3, min_max_integer_value_used/5,
140 syntaxtraversion/6,
141 safe_syntaxelement/5,
142 safe_syntaxelement_det/5, % a deterministic, non-backtracking version
143 is_subst_syntaxelement/1,
144 is_syntax_constant/1,
145
146 remove_all_infos/2, extract_info/2, extract_info/3, extract_info_wo_used_ids/2,
147 bsyntax_pattern/2,
148
149 remove_all_infos_and_ground/2,
150
151 check_if_typed_predicate/1,
152 check_if_typed_expression/1,
153 check_if_typed_substitution/1,
154
155 strip_and_norm_ast/2,
156 same_norm_texpr/2,
157 get_texpr_functor/3,
158
159 is_set_type/2, get_set_type/2, get_texpr_set_type/2,
160 is_just_type/1, is_just_type/2,
161
162 create_recursive_compset/6,
163 unique_typed_id/3,
164 mark_bexpr_as_symbolic/2,
165
166 identifier_sub_ast/3, exchange_ast_position/5,
167
168 has_declared_identifier/2, add_declaration_for_identifier/3,
169 check_ast/1, check_ast/2,
170 repair_used_ids/3,
171 print_ast/1,
172 rewrite_if_then_else_expr_to_b/2
173 ]).
174
175 % meta_predicate annotations should appear before loading any code:
176
177 :- meta_predicate map_over_full_bexpr_no_fail(1,?).
178
179 :- meta_predicate map_over_bexpr(1,?).
180 :- meta_predicate map_over_typed_bexpr(1,?).
181 :- meta_predicate map_over_typed_bexpr(2,?,?).
182 :- meta_predicate map_over_bexpr_top_down_acc(3,?,?).
183 :- meta_predicate map_over_typed_bexpr_top_down_acc(3,?,?).
184
185 :- meta_predicate reduce_over_bexpr(3,?,?,?).
186 :- meta_predicate transform_bexpr(2,?,?).
187 :- meta_predicate l_transform_bexpr(?,2,?).
188 :- meta_predicate transform_bexpr_with_scoping(3,?,?).
189 :- meta_predicate transform_bexpr_with_scoping2(3,?,?,?).
190 :- meta_predicate l_transform_bexpr_with_scoping(?,3,?,?).
191 :- meta_predicate transform_bexpr_with_bup_accs(4,?,?,?,?).
192 :- meta_predicate l_transform_bexpr_with_bup_accs(?,4,?,?,?).
193 :- meta_predicate transform_bexpr_with_acc(4,?,?,?,?).
194 :- meta_predicate l_transform_bexpr_with_acc(?,4,?,?,?).
195 :- meta_predicate non_det_transform_bexpr_with_acc(4,?,?,?,?).
196 :- meta_predicate l_nd_transform_bexpr_with_acc(?,4,?,?,?).
197
198 % -----------
199
200
201 :- use_module(tools).
202
203 :- use_module(module_information,[module_info/2]).
204 :- module_info(group,typechecker).
205 :- module_info(description,'This module provides operations on the type-checked AST.').
206
207 :- use_module(library(lists)).
208 :- use_module(library(ordsets)).
209 :- use_module(library(avl)).
210 :- use_module(library(terms)).
211
212 :- use_module(self_check).
213 :- use_module(error_manager).
214 :- use_module(translate,[print_bexpr/1,translate_bexpression/2]).
215 :- use_module(gensym,[gensym/2]).
216 :- use_module(preferences,[get_preference/2,preference/2]).
217 :- use_module(debug,[debug_mode/1,debug_format/3]).
218
219 :- use_module(typing_tools,[is_finite_type_in_context/2,normalize_type/2]).
220 :- use_module(tools_lists,[convlist_max/4]).
221
222 :- set_prolog_flag(double_quotes, codes).
223
224 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
225 % basic access to enriched syntax tree
226
227 is_texpr(b(_,_,_)).
228
229 get_texpr_expr(b(Name,_,_),R) :- !,R=Name.
230 get_texpr_expr(E,_) :- add_error_fail(get_texpr_expr,'B Expression not properly wrapped: ',E).
231
232 get_texpr_type(b(_,Type,_),R) :- !, R=Type.
233 get_texpr_type(E,_) :- add_error_fail(get_texpr_type,'B Expression not properly wrapped: ',E).
234 get_texpr_info(b(_,_,Info),R) :- !, R=Info.
235 get_texpr_info(E,_) :- add_error_fail(get_texpr_info,'B Expression not properly wrapped: ',E).
236
237 %! get_texpr_id(+Texpr,-Id)
238 get_texpr_id(b(N,_,_),Id) :- !, N=identifier(Id).
239 get_texpr_id(E,_) :- add_error_fail(get_texpr_id,'B Expression not properly wrapped: ',E).
240 /* same as above: but must succeed */
241 def_get_texpr_id(b(identifier(Id),_,_),R) :- !,R=Id.
242 def_get_texpr_id(b(E,_,_),_) :- !,
243 add_error_fail(def_get_texpr_id,'Could not extract identifier from typed expression: ',E).
244 def_get_texpr_id(ID,_) :- add_error_fail(def_get_texpr_id,'Could not extract identifier, not properly wrapped: ',ID).
245
246 % translate a list of ids with the b/3 wrapper into a plain id list; throw error if not an identifier
247 % used to also be called get_texpr_id_names
248 def_get_texpr_ids(L,Ids) :- maplist(def_get_texpr_id,L,Ids).
249
250 create_typed_id(IDName,Type,b(identifier(IDName),Type,[])).
251
252 same_id(X,Y,ID) :- get_texpr_id(X,ID), get_texpr_id(Y,ID).
253
254 same_ids([],[]).
255 same_ids([X|Xs],[Y|Ys]) :- same_id(X,Y,_), same_ids(Xs,Ys).
256
257 % check if two lists of identifiers have the same name and types
258 same_ids_and_types([],[]).
259 same_ids_and_types([b(identifier(Id),T1,_)|Xs],[b(identifier(Id),T2,_)|Ys]) :- unify_types_strict(T1,T2),
260 same_ids_and_types(Xs,Ys).
261
262 % split a list of typed identifiers into atomic ids and types
263 split_names_and_types([],N,T) :- !, N=[], T=[].
264 split_names_and_types([Identifier|IdRest],[Name|NRest],[Type|TRest]) :- !,
265 def_get_texpr_id(Identifier,Name),
266 get_texpr_type(Identifier,Type),
267 split_names_and_types(IdRest,NRest,TRest).
268 split_names_and_types(TIDS,N,R) :-
269 add_internal_error('Illegal call to:',split_names_and_types(TIDS,N,R)),fail.
270
271
272
273 % check if two wrapped expressions are equal (modulo associated Info, e.g. source loc info)
274 same_texpr(b(E1,Type,_),b(E2,Type,_)) :- % should we do a == check first ?? probably not as it may traverse the entire structure (see email exchange with SICStus 28.1.2015)
275 same_functor(E1,E2),
276 safe_syntaxelement_det(E1,Subs1,_Names1,_List1,Constant),
277 safe_syntaxelement_det(E2,Subs2,_Names2,_List2,Constant2),
278 Constant==Constant2, % in case we have values with variables inside !
279 same_sub_expressions(Subs1,Subs2).
280
281 same_sub_expressions([],[]).
282 same_sub_expressions([H1|T1],[H2|T2]) :- same_texpr(H1,H2), same_sub_expressions(T1,T2).
283
284 % check if two wrapped expressions definitely denote a different value (and are well-defined)
285 % only detects certain cases !
286 different_texpr_values(b(E1,Type,I1),b(E2,Type,I2)) :-
287 different_value(E1,E2,CheckWD),
288 (CheckWD=false -> true
289 ; always_well_defined_or_wd_improvements_allowed(b(E1,Type,I1)),
290 always_well_defined_or_wd_improvements_allowed(b(E2,Type,I2))).
291 different_value(boolean_false,boolean_true,false) :- !.
292 different_value(boolean_true,boolean_false,false) :- !.
293 different_value(integer(X),IY,false) :- get_integer_aux(IY,Y),!, X\=Y.
294 different_value(string(X),string(Y),false) :- !, X\=Y.
295 different_value(value(VX),Y,false) :- !, different_val_from(VX,Y).
296 different_value(empty_set,S,check_wd) :- !, non_empty_set(S).
297 different_value(S,empty_set,check_wd) :- !, non_empty_set(S).
298 % should we compare two set_extensions ? couples ? records ? reals?
299
300 different_val_from(Var,_) :- var(Var),!,fail.
301 different_val_from(int(X),IY) :- integer(X), get_integer_aux(IY,Y), X\=Y.
302 different_val_from(fd(X,Gs),value(FY)) :- nonvar(X), nonvar(FY), FY=fd(Y,Gs), nonvar(Y), X\=Y.
303 different_val_from(pred_false,boolean_true).
304 different_val_from(pred_false,value(BY)) :- BY==pred_true.
305 different_val_from(pred_true,boolean_false).
306 different_val_from(pred_true,value(BY)) :- BY==pred_false.
307 different_val_from(string(X),string(Y)) :- !, X\=Y.
308 different_val_from(string(X),value(VY)) :- nonvar(VY), VY=string(Y), nonvar(Y), !, X\=Y.
309 different_val_from(avl_set(node(_,_,_,_,_)),empty_set).
310
311 non_empty_set(set_extension([_|_])).
312 non_empty_set(sequence_extension([_|_])).
313
314
315 get_texpr_exprs([],[]).
316 get_texpr_exprs([E|Rest],[N|NRest]) :- get_texpr_expr(E,N),get_texpr_exprs(Rest,NRest).
317 get_texpr_exprs(b(E,_,_),Res) :- add_internal_error('Illegal call:',get_texpr_infos(b(E,_,_),Res)), Res=[E].
318 get_texpr_types([],[]).
319 get_texpr_types([E|Rest],[T|TRest]) :- get_texpr_type(E,T),get_texpr_types(Rest,TRest).
320 get_texpr_types(b(_,T,_),Res) :- add_internal_error('Illegal call:',get_texpr_infos(b(_,T,_),Res)), Res=[T].
321 get_texpr_infos([],[]).
322 get_texpr_infos([E|Rest],[I|IRest]) :- get_texpr_info(E,I),get_texpr_infos(Rest,IRest).
323 get_texpr_infos(b(_,_,I),Res) :- add_internal_error('Illegal call:',get_texpr_infos(b(_,_,I),Res)), Res=[I].
324 get_texpr_ids([],[]).
325 get_texpr_ids([E|Rest],[I|IRest]) :- get_texpr_id(E,I),get_texpr_ids(Rest,IRest).
326
327 get_texpr_pos(TExpr,Pos) :-
328 get_texpr_info(TExpr,Infos),
329 ? ( member(nodeid(Pos1),Infos) -> !,Pos=Pos1
330 ; Pos = none).
331
332 % similar to get_texpr_pos, but returns sub-list of infos relating to position
333 extract_pos_infos(Infos,InfoRes) :-
334 ? ( member(nodeid(Pos1),Infos) -> !,InfoRes=[nodeid(Pos1)]
335 ; InfoRes = []).
336
337 % copy position info from first arg to second argument
338 copy_pos_infos(b(_,_,Infos1),Arg2,Res) :-
339 member(nodeid(Pos1),Infos1),!,
340 Arg2 = b(E,T,Infos2), Res = b(E,T,Infos3),
341 delete_pos_info(Infos2,Infos2d),
342 Infos3 = [nodeid(Pos1)|Infos2d].
343 copy_pos_infos(_,TE,TE).
344
345 delete_pos_info(Infos1,Infos2) :-
346 select(nodeid(_),Infos1,D),!, Infos2=D.
347 %delete(Infos1,nodeid(_),Infos2).
348 delete_pos_info(I,I).
349
350
351
352 get_info_pos(Infos,Pos) :- (member(nodeid(Pos1),Infos) -> Pos=Pos1 ; Pos=none).
353 contains_info_pos(Infos) :- (member(nodeid(NI),Infos) -> NI \= none).
354
355 create_texpr(Expr,Type,Info,b(Expr,Type,Info)).
356
357 add_texpr_infos(b(Expr,Type,Old),Infos,b(Expr,Type,New)) :- !,
358 append(Infos,Old,New).
359 add_texpr_infos(Other,Infos,Res) :-
360 add_internal_error('Illegal call, not BExpr:',add_texpr_infos(Other,Infos,Res)),fail.
361
362 add_texpr_info_if_new(b(Expr,Type,Old),Info,b(Expr,Type,New)) :- !,
363 add_info_if_new(Old,Info,New).
364 add_texpr_info_if_new(Other,Infos,Res) :-
365 add_internal_error('Illegal call, not BExpr:',add_texpr_info_if_new(Other,Infos,Res)),fail.
366 % add multiple infos:
367 add_texpr_infos_if_new(b(Expr,Type,Old),Infos,b(Expr,Type,New)) :-
368 add_infos_if_new(Infos,Old,New).
369
370 % add to info list:
371 add_info_if_new(Old,Info,New) :-
372 (member(Info,Old) -> New=Old ; New = [Info|Old]).
373
374 add_infos_if_new([]) --> [].
375 add_infos_if_new([Info|T]) --> add_info(Info), add_infos_if_new(T).
376 add_info(Info,Old,New) :-
377 (member(Info,Old) -> New=Old ; New = [Info|Old]).
378
379
380 % try and extract the Rodin name of a predicate or expression
381 get_rodin_name(Expression,Name) :- get_texpr_pos(Expression,rodinpos(Name,_)), Name \= [].
382 get_rodin_name(Expression,Name) :- get_texpr_pos(Expression,rodinpos(_Model,Name,_)), Name \= []. % new rodinpos
383
384 get_rodin_model_name(Expression,Model) :-
385 get_texpr_pos(Expression,rodinpos(Model,Name,_)), Name \= []. % new rodinpos
386
387 % try and extract the Rodin name or label pragma of a predicate or expression
388 get_texpr_labels(TExpr,Label) :-
389 get_texpr_info(TExpr,Infos),
390 member(I,Infos), info_label(I,Label).
391 get_info_labels(Infos,LabelList) :-
392 ? member(I,Infos), info_label(I,LabelList).
393 select_info_labels(LabelList,Infos,Rest) :-
394 select(I,Infos,Rest), info_label(I,LabelList).
395 info_label(nodeid(NodeID),[Name]) :- nodeid_info_label(NodeID,Name).
396 info_label(label(LabelList),LabelList).
397
398 nodeid_info_label(rodinpos(Name,_),Name) :- Name \= [].
399 nodeid_info_label(rodinpos(Model,Name,_),FullName) :- Name \= [], % new rodinpos
400 ajoin([Model,':',Name], FullName). % TO DO: if only one level; don't do this
401 % TODO: provide separate way to access this derived information:
402 %nodeid_info_label(rodin_derived_context_pos(Model,Context,Label),FullName) :-
403 % ajoin([Model,'.',Context,':',Label], FullName).
404
405
406 add_labels_to_texpr(E,[],R) :- !, R=E. % no labels to add
407 add_labels_to_texpr(b(E,T,I),Labels,b(E,T,NewI)) :-
408 (select(label(OldList),I,Rest)
409 -> append(Labels,OldList,NewList), NewI=[label(NewList)|Rest]
410 % TO DO: what if we have Rodin labels
411 ; NewI = [label(Labels)|I]
412 ).
413
414 get_texpr_label(TExpr,Label) :- get_texpr_labels(TExpr,Labels), member(Label,Labels).
415
416 get_texpr_description(TExpr,Description) :-
417 get_texpr_info(TExpr,Infos),
418 memberchk(description(Description),Infos).
419
420 add_texpr_description(b(E,T,I),Description,b(E,T,[description(Description)|I])).
421
422 % check if an info list has an ignore pragma
423 info_has_ignore_pragma(Infos) :-
424 member(description('prob-ignore'),Infos).
425 % detect_prob_ignore ast_cleanup rule also generates this description annotation
426
427 predicate_has_ignore_pragma(b(_E,pred,I)) :-
428 %add_message(check_prob_ignore,'Pred: ',b(_E,pred,I),I),
429 info_has_ignore_pragma(I).
430
431 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
432
433 :- assert_must_succeed( (E = "1/2",
434 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
435 Type==integer, Err==none, always_well_defined(ET) ) ).
436 :- assert_must_succeed( (E = "3 mod 2",
437 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
438 Type==integer, Err==none, always_well_defined(ET) ) ).
439 :- assert_must_succeed( (E = "1/0",
440 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
441 Type==integer, Err==none, \+ always_well_defined(ET) ) ).
442 :- assert_must_succeed( (E = "2*(3 mod card({}))",
443 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
444 Type==integer, Err==none, \+ always_well_defined(ET) ) ).
445 :- assert_must_succeed( (E = "1/(2+1-3)",
446 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
447 Type==integer, Err==none, \+ always_well_defined(ET) ) ).
448 :- assert_must_succeed( (E = "max({1,2,3,0})",
449 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
450 Type==integer, Err==none, always_well_defined(ET) ) ).
451 :- assert_must_succeed( (E = "min({1,2,3,0})",
452 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
453 Type==integer, Err==none, always_well_defined(ET) ) ).
454 :- assert_must_succeed( (E = "min({1,2,3,0}-(0..4))",
455 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
456 Type==integer, Err==none, \+ always_well_defined(ET) ) ).
457 :- assert_must_succeed( (E = "2+max({1,2,3, 1/0})",
458 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
459 Type==integer, Err==none,\+ always_well_defined(ET) ) ).
460 :- assert_must_succeed( (E = "2-card({1,2,3})",
461 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
462 Type==integer, Err==none, always_well_defined(ET) ) ).
463 :- assert_must_succeed( (E = "2-card({1,2,3, 1/0})",
464 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
465 Type==integer, Err==none,\+ always_well_defined(ET) ) ).
466 :- assert_must_succeed( (E = "bool(2-size([1,2,3, 1/0])=3)",
467 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
468 Type==boolean, Err==none, \+ always_well_defined(ET) ) ).
469 :- assert_must_succeed( (E = "bool(2-size([1,2,3, 1/2, 3 mod 2, 3**2])=size([]))",
470 bmachine:b_parse_machine_expression_from_codes(E,ET,Type,false,Err),
471 Type==boolean, Err==none, always_well_defined(ET) ) ).
472
473 always_well_defined_or_wd_reorderings_allowed(BE) :- % allow re-ordering to improve Left-to-right WD
474 (preferences:preference(disprover_mode,true) -> true % we can assume all calls are well-defined
475 ; preferences:preference(allow_improving_wd_mode,true) -> true
476 ; preferences:preference(data_validation_mode,true) -> true
477 ; always_well_defined_or_discharged(BE)).
478 always_well_defined_or_wd_improvements_allowed(BE) :- % allow to remove useless calls which could be non-WD
479 % example #x(x = f(...)) -> btrue or f[{}] --> {}
480 always_well_defined_or_wd_reorderings_allowed(BE). % we currently use the same definition
481 always_well_defined_or_disprover_mode(BE) :-
482 (preferences:preference(disprover_mode,true) -> true % we can assume all calls are well-defined
483 ; always_well_defined_or_discharged(BE)).
484
485 always_well_defined_or_discharged(b(E,_,Infos)) :- !,
486 (nonmember(contains_wd_condition,Infos) -> true
487 ; always_wd(E) -> true % some special rules
488 ; member(discharged_wd_po,Infos) -> true
489 %; nl, functor(E,F,N), F \= function, print(non_wd(F,N)),nl,nl,fail
490 ).
491 always_well_defined_or_discharged(E) :-
492 add_error_fail(always_well_defined,'Illegal call: ',always_well_defined_or_discharged(E)).
493
494 % should ensure that there is no failure and no error raised
495 always_well_defined(b(E,_,Infos)) :- !,
496 (nonmember(contains_wd_condition,Infos) -> true
497 ; always_wd(E) -> true % some special rules
498 %; nl, functor(E,F,N), F \= function, print(non_wd(F,N)),nl,nl,fail
499 ).
500 always_well_defined(E) :- add_error_fail(always_well_defined,'Illegal call: ',always_well_defined(E)).
501
502
503 :- assert_must_succeed( always_wd(div( b(integer(2),integer,[]), b(integer(2),integer,[]) )) ).
504 :- assert_must_fail( always_wd(div( b(integer(2),integer,[]), b(integer(0),integer,[]) )) ).
505 :- assert_must_succeed( always_wd(modulo( b(integer(2),integer,[]), b(integer(2),integer,[]) )) ).
506 :- assert_must_fail( always_wd(modulo( b(integer(2),integer,[]), b(integer(0),integer,[]) )) ).
507 :- assert_must_fail( always_wd(modulo( b(integer(2),integer,[]), b(integer(-2),integer,[]) )) ).
508 :- assert_must_fail( always_wd(modulo( b(integer(-1),integer,[]), b(integer(2),integer,[]) )) ).
509 :- assert_must_succeed( always_wd(power_of( b(integer(2),integer,[]), b(integer(3),integer,[]) )) ).
510 :- assert_must_succeed( always_wd(power_of( b(integer(2),integer,[]), b(integer(0),integer,[]) )) ).
511 :- assert_must_fail( always_wd(power_of( b(integer(2),integer,[]), b(integer(-1),integer,[]) )) ).
512
513 % catch cases where the construct is currently so instantiated that we can determine that it is well-defined
514 % can happen e.g. during closure compilation
515 :- use_module(custom_explicit_sets,[check_unique_in_domain_of_avlset/2]).
516 :- use_module(kernel_tools,[ground_value/1]).
517 always_wd(power_of(X,Y)) :- get_integer(Y,Val), Val>=0,
518 (eventb_mode -> get_integer(X,ValX), ValX >=0
519 ; always_well_defined(X)).
520 always_wd(div(X,Y)) :- get_integer(Y,Val), Val\=0, always_well_defined(X).
521 always_wd(modulo(X,Y)) :- get_integer(Y,Val), Val>0, % Z Live allows negative numbers here it seems, cf modulo2
522 (z_or_tla_minor_mode -> true % in Z, TLA we can have negative numbers here
523 ; get_integer(X,ValX), ValX>=0).
524 always_wd(function(X,Y)) :- nonvar(X),
525 X= b(value(AVLSET),_,_), nonvar(AVLSET), AVLSET=avl_set(AVL),
526 always_wd_avl_function(AVL,Y).
527 always_wd(min(X)) :- non_empty_finite_wd_set_value(X).
528 always_wd(max(X)) :- non_empty_finite_wd_set_value(X).
529 always_wd(card(X)) :- finite_wd_set_value(X).
530 always_wd(size(X)) :- finite_wd_seq_value(X).
531 always_wd(first(X)) :- non_empty_wd_seq_value(X).
532 always_wd(front(X)) :- non_empty_wd_seq_value(X).
533 always_wd(last(X)) :- non_empty_wd_seq_value(X).
534 always_wd(tail(X)) :- non_empty_wd_seq_value(X). % TO DO: add restrict_front, restrict_tail ?
535 always_wd(general_intersection(X)) :- non_empty_finite_wd_set_value(X).
536 always_wd(value(_)). % we have already computed the value and will raise WD error; to be 100 % safe we could restrict this to ground values
537 % other candidates: size(_), first(_) last(_) tail(_) front(_) restrict_front(_,_) restrict_tail(_,_) rel_iterate(_,_)
538 always_wd(typeset).
539 % operators that are always wd on their own:
540 always_wd(record_field(RecEx,FieldName)) :- ground(FieldName),
541 always_well_defined(RecEx).
542 always_wd(unary_minus(A)) :- always_well_defined(A).
543 always_wd(unary_minus_real(A)) :- always_well_defined(A).
544 always_wd(first_of_pair(A)) :- always_well_defined(A).
545 always_wd(add(A,B)) :- always_well_defined(A),always_well_defined(B).
546 always_wd(add_real(A,B)) :- always_well_defined(A),always_well_defined(B).
547 always_wd(minus(A,B)) :- always_well_defined(A),always_well_defined(B).
548 always_wd(minus_real(A,B)) :- always_well_defined(A),always_well_defined(B).
549 always_wd(multiplication(A,B)) :- always_well_defined(A),always_well_defined(B).
550 always_wd(multiplication_real(A,B)) :- always_well_defined(A),always_well_defined(B).
551 always_wd(equal(A,B)) :- always_well_defined(A),always_well_defined(B).
552 always_wd(not_equal(A,B)) :- always_well_defined(A),always_well_defined(B).
553 always_wd(less_equal(A,B)) :- always_well_defined(A),always_well_defined(B).
554 always_wd(less_equal_real(A,B)) :- always_well_defined(A),always_well_defined(B).
555 always_wd(greater_equal(A,B)) :- always_well_defined(A),always_well_defined(B).
556 always_wd(less(A,B)) :- always_well_defined(A),always_well_defined(B).
557 always_wd(less_real(A,B)) :- always_well_defined(A),always_well_defined(B).
558 always_wd(greater(A,B)) :- always_well_defined(A),always_well_defined(B).
559 always_wd(couple(A,B)) :- always_well_defined(A),always_well_defined(B).
560 % TO DO: add more/all other operators ?
561
562 always_wd_avl_function(AVL,Y) :- nonvar(Y), Y= b(value(Val),_,_),
563 ground_value(Val), !,
564 % Warning: this does not check that the whole AVL is a function; just this particular lookup is ok
565 check_unique_in_domain_of_avlset(Val,AVL). % ,print(ok),nl.
566 always_wd_avl_function(AVL,Y) :- always_well_defined(Y),
567 custom_explicit_sets:quick_definitely_maximal_total_function_avl(AVL).
568
569 % non empty set with WD elements
570 non_empty_finite_wd_set_value(b(E,_,_)) :- non_empty_fin_wd_set2(E).
571 non_empty_fin_wd_set2(bool_set).
572 non_empty_fin_wd_set2(value(X)) :- definitely_not_empty_finite_value(X).
573 non_empty_fin_wd_set2(set_extension(S)) :- l_always_well_defined(S). % the set_extension could contain wd_errors !!
574 non_empty_fin_wd_set2(sequence_extension(S)) :- l_always_well_defined(S). % ditto
575 non_empty_fin_wd_set2(interval(A,B)) :- get_integer(A,IA), get_integer(B,IB), IA =< IB.
576 % see not_empty_set_aux
577 definitely_not_empty_finite_value(X) :- var(X),!,fail.
578 definitely_not_empty_finite_value(avl_set(_)).
579 definitely_not_empty_finite_value([_|_]).
580 definitely_not_empty_finite_value(closure(P,T,B)) :-
581 custom_explicit_sets:is_interval_closure(P,T,B,LOW,UP), integer(LOW),integer(UP), LOW =< UP.
582
583
584 non_empty_wd_seq_value(b(E,_,_)) :- non_empty_seq2(E).
585 non_empty_seq2(value(X)) :- definitely_not_empty_seq(X).
586 non_empty_seq2(sequence_extension(S)) :- l_always_well_defined(S), S=[_|_].
587
588 definitely_not_empty_seq(X) :- var(X),!,fail.
589 definitely_not_empty_seq(avl_set(A)) :- custom_explicit_sets:is_avl_sequence(A).
590 definitely_not_empty_seq([El1|T]) :- T==[],nonvar(El1), El1=(IDX,_), IDX==int(1). % TO DO: add more cases ?
591
592
593 finite_set_or_disprover_mode(Set) :-
594 (preferences:preference(disprover_mode,true) -> true % we can assume all calls are well-defined
595 ; finite_wd_set_value(Set)).
596
597 :- use_module(typing_tools,[is_provably_finite_type/1]).
598 % we could also use is_finite_type_in_context to allow deferred sets to be counted as finite
599 finite_wd_set_value(b(E,T,_)) :- !, (finite_set2(E) -> true ; is_provably_finite_type(T)).
600 finite_wd_set_value(E) :- add_internal_error('Not a BExpr: ',E),fail.
601 finite_set2(empty_set).
602 finite_set2(empty_sequence).
603 finite_set2(value(X)) :- X==[] -> true ; definitely_not_empty_finite_value(X).
604 finite_set2(set_extension(S)) :- l_always_well_defined(S). % the set_extension could contain wd_errors !!
605 finite_set2(sequence_extension(S)) :- l_always_well_defined(S). % ditto
606
607 finite_wd_seq_value(b(E,_,_)) :- finite_seq2(E).
608 finite_seq2(empty_set).
609 finite_seq2(empty_sequence).
610 finite_seq2(value(X)) :- finite_seq_value(X).
611 finite_seq2(sequence_extension(S)) :- l_always_well_defined(S).
612
613 finite_seq_value(X) :- var(X),!,fail.
614 finite_seq_value([]).
615 finite_seq_value(avl_set(A)) :- custom_explicit_sets:is_avl_sequence(A).
616 % it could be expensive to check if non empty list is a B sequence ??
617
618 l_always_well_defined([]).
619 l_always_well_defined([H|T]) :- always_well_defined(H), l_always_well_defined(T).
620
621 is_truth(b(F,pred,_)) :- is_truth_aux(F).
622 is_truth_aux(truth).
623 is_truth_aux(value(V)) :- V==pred_true. % can occur in CSE mode
624
625 is_falsity(b(F,pred,_)) :- is_falsity_aux(F).
626 is_falsity_aux(falsity).
627 is_falsity_aux(value(V)) :- V==pred_false. % can occur in CSE mode
628
629 % conjunction of a list of predicates
630 % NOTE: bsyntaxtree:conjunct_predicates([P1,P2,P3],R). --> generates R = b(conjunct(b(conjunct(P1,P2),pred,[]),P3),pred,[])
631 conjunct_predicates(V,R) :- var(V),!, add_internal_error('Variable conjunction list: ',conjunct_predicates(V,R)),fail.
632 conjunct_predicates([],b(truth,pred,[])).
633 conjunct_predicates([P|Rest],Result) :- conjunct2(Rest,P,Result).
634 conjunct2([],P,P).
635 conjunct2([Q|Rest],P,Result) :- conjunct3(P,Q,R), conjunct2(Rest,R,Result).
636 conjunct3(b(truth,_,_),P,P) :- !.
637 conjunct3(P,b(truth,_,_),P) :- !.
638 conjunct3(A,B,b(conjunct(A,B),pred,NewInfo)) :- extract_info(A,B,NewInfo).
639
640 % disjunction of a list of predicates
641 disjunct_predicates([],b(falsity,pred,[])).
642 disjunct_predicates([P|Rest],Result) :- disjunct2(Rest,P,Result).
643 disjunct2([],P,P).
644 disjunct2([Q|Rest],P,Result) :- disjunct3(P,Q,R), disjunct2(Rest,R,Result).
645 disjunct3(b(falsity,_,_),P,R) :- !, R=P.
646 disjunct3(b(truth,T,I),_,R) :- !, R=b(truth,T,I).
647 disjunct3(P,b(falsity,_,_),R) :- !, R=P.
648 disjunct3(_,b(truth,T,I),R) :- !, R=b(truth,T,I).
649 disjunct3(A,B,b(disjunct(A,B),pred,NewInfo)) :- extract_info(A,B,NewInfo).
650
651 % conjunct two predicates and try and construct position information
652 conjunct_predicates_with_pos_info(A,B,AB) :- is_truth(B),!, AB=A.
653 conjunct_predicates_with_pos_info(A,B,AB) :- is_truth(A),!, AB=B.
654 conjunct_predicates_with_pos_info(A,B,AB) :-
655 conjunct_predicates([A,B],AB0), % this may contain position info if B is truth; hence we do check above
656 (try_get_merged_position_info(A,B,ABI)
657 -> add_texpr_infos(AB0,[ABI],AB) %,print(abi(ABI)),nl
658 ; AB=AB0).
659
660 % disjunct two predicates and try and construct position information
661 disjunct_predicates_with_pos_info(A,B,AB) :-
662 disjunct_predicates([A,B],AB0),
663 (try_get_merged_position_info(A,B,ABI)
664 -> add_texpr_infos(AB0,[ABI],AB) %,print(abi(ABI)),nl
665 ; AB=AB0).
666
667 try_get_merged_position_info(b(_,_,I1),b(_,_,I2),PosInfo) :-
668 (try_get_merged_position_info_aux(I1,I2,MergedInfo) -> PosInfo = MergedInfo
669 ; get_non_label_posinfo(Pos1,I1) -> PosInfo=nodeid(Pos1)
670 ; get_non_label_posinfo(Pos2,I2) -> PosInfo=nodeid(Pos2)
671 ).
672 try_get_merged_position_info_aux(I1,I2,nodeid(pos(C,Filenumber,Srow,Scol,Erow,Ecol))) :-
673 member(nodeid(pos(C1,Filenumber,Srow1,Scol1,Erow1,Ecol1)),I1),
674 (number(C1),number(Srow1),number(Scol1),number(Erow1),number(Ecol1)
675 -> true ; add_internal_error('Info field 1 not yet instantiated: ',try_get_merged_position_info(I1)),fail),
676 !,
677 member(nodeid(pos(C2,Filenumber,Srow2,Scol2,Erow2,Ecol2)),I2),
678 (number(C2),number(Srow2),number(Scol2),number(Erow2),number(Ecol2)
679 -> true ; add_internal_error('Info field 2 not yet instantiated: ',try_get_merged_position_info(I2)),fail),
680 !,
681 % merge position info if in same file
682 (C1 =< C2 -> C=C1, Srow=Srow1,Scol=Scol1 ; C=C2, Srow=Srow2,Scol=Scol2),
683 ((Erow1 > Erow2 ; Erow1=Erow2, Ecol1 >= Ecol2)
684 -> Erow =Erow1, Ecol=Ecol1
685 ; Erow =Erow2, Ecol=Ecol2).
686
687 % get position info which is not a label; label info should not be propagated to outer conjuncts/disjuncts/...
688 get_non_label_posinfo(Pos,Infos) :- member(nodeid(Pos),Infos),
689 \+ functor(Pos,rodinpos,_).
690
691 get_texpr_non_label_posinfo(b(_,_,Infos),nodeid(Pos)) :- get_non_label_posinfo(Pos,Infos).
692
693 % conjunct list of predicates and try and construct position information
694 conjunct_predicates_with_pos_info([H|T],Res) :- is_truth(H),!,
695 (T=[] -> Res = H ; conjunct_predicates_with_pos_info(T,Res)).
696 conjunct_predicates_with_pos_info([H|T],Res) :-
697 last_non_truth(T,none,Last), % the truth elements will be removed and are not relevant; get last relevant predicate
698 Last \= none,
699 try_get_merged_position_info(H,Last,MergedPosInfo), % try and merge position of first and last element
700 !,
701 conjunct_predicates([H|T],Res0),
702 add_texpr_infos(Res0,[MergedPosInfo],Res). % Res0 should have no nodeid field
703 conjunct_predicates_with_pos_info(L,Res) :- conjunct_predicates(L,Res).
704
705 :- assert_must_succeed((bsyntaxtree:last_non_truth([a,b,c],none,L),L==c)).
706 :- assert_must_succeed((bsyntaxtree:last_non_truth([a,b,c,b(truth,pred,[])],none,L),L==c)).
707
708 % get last non-truth element and filter out all truth elements
709 last_non_truth([],Acc,Acc).
710 last_non_truth([H|T],NonTruth,Last) :- is_truth(H),!, last_non_truth(T,NonTruth,Last).
711 last_non_truth([H|T],_,Last) :- last_non_truth(T,H,Last).
712
713
714 texpr_contains_wd_condition(b(_,_,Info)) :- !, memberchk(contains_wd_condition,Info).
715 texpr_contains_wd_condition(E) :- add_internal_error('Not a texpr: ',texpr_contains_wd_condition(E)).
716
717 % a version of create_texpr which collects automatically important infos from sub-expressions
718 safe_create_texpr(Expr,Type,b(Expr,Type,Info)) :- %
719 ? (sub_expression_contains_wd_condition(Expr) -> Info = [contains_wd_condition] ; Info=[]).
720
721 safe_create_texpr(Expr,Type,Info,b(Expr,Type,FullInfo)) :- %
722 ((sub_expression_contains_wd_condition(Expr), nonmember(contains_wd_condition, Info)) -> FullInfo = [contains_wd_condition|Info] ; FullInfo=Info).
723
724 ?sub_expression_contains_wd_condition(Expr) :- sub_expression_contains_wd_condition(Expr,_).
725 sub_expression_contains_wd_condition(Expr,Sub) :-
726 safe_syntaxelement_det(Expr,Subs,_Names,_L,_C),
727 ? member(b(Sub,_,Infos),Subs),
728 (var(Infos)
729 -> add_internal_error('Typed expression not sufficiently instantiated (variable Infos): ',sub_expression_contains_wd_condition(Expr)),
730 fail
731 ; memberchk(contains_wd_condition,Infos)).
732
733 % provide updated infos (e.g., reads(...)) and remove any old info fields with same functor
734 update_infos([],Infos,Infos).
735 update_infos([Update|T],OldInfos,NewInfos) :-
736 functor(Update,F,N),
737 functor(Old,F,N),
738 delete(OldInfos,Old,OldInfos1),
739 update_infos(T,[Update|OldInfos1],NewInfos).
740
741 % merge two info lists and try to reconcile position information:
742 merge_info(Info1,Info2,Res) :-
743 merge_imp_info2(Info2,Info1,NewInfo),
744 (try_get_merged_position_info_aux(Info1,Info2,NewPos)
745 -> delete_pos_info(NewInfo,NI2),
746 Res = [NewPos|NI2]
747 ; Res = NewInfo).
748
749 % extract important info but without used_ids:
750 extract_info_wo_used_ids(b(_,_,Info1),Info) :-
751 extract_pos_infos(Info1,PosInfos),
752 extract_just_important_info_aux(Info1,[],I1),
753 append(PosInfos,I1,Info).
754 extract_info_wo_used_ids_and_pos(b(_,_,Info1),b(_,_,Info2),Info) :-
755 extract_just_important_info_aux(Info1,[],I1),
756 extract_just_important_info_aux(Info2,I1,Info).
757
758 % extract important info from one sub-expression:
759 extract_info(b(_,_,Info1),NewInfo) :-
760 extract_imp_info1(Info1,I1),!, NewInfo = I1.
761 extract_info(A,R) :-
762 add_internal_error('Could not extract info: ',extract_info(A,R)),
763 R=[].
764 % extract imortant info fields from two (sub-)expressions
765 extract_info(b(_,_,Info1),b(_,_,Info2),NewInfo) :-
766 merge_imp_info2(Info1,Info2,II),!, NewInfo = II.
767 %:- use_module(library(ordsets),[ord_intersection/3]).
768 % ord_intersection(Info1,Info2,NewInfo),!.
769 % TO DO: should we merge nodeid position information !?
770 extract_info(A,B,R) :- add_internal_error('Could not extract info: ',extract_info(A,B,R)),
771 R=[].
772
773 % extract important info and used_ids
774 extract_imp_info1([],[]).
775 extract_imp_info1([H|T],Res) :-
776 ((important_info(H); H=used_ids(_)) -> Res=[H|ET], extract_imp_info1(T,ET)
777 ; extract_imp_info1(T,Res)
778 ).
779
780 % extract and merge important info and try to merge used_ids from two info lists
781 merge_imp_info2(Info1,Info2,ResInfos) :-
782 extract_imp_info1(Info1,I1),
783 extract_imp_info1(Info2,I2),
784 merge_aux(I1,I2,ResInfos).
785
786 merge_aux([],I2,Res) :- !, delete(I2,used_ids(_),Res). % used_ids not valid for new construct
787 merge_aux(I1,[],Res) :- !, delete(I1,used_ids(_),Res). % ditto
788 merge_aux(I1,I2,ResInfos) :-
789 ? (select(used_ids(Ids1),I1,II1)
790 ? -> (select(used_ids(Ids2),I2,II2)
791 -> ord_union(Ids1,Ids2,Ids3),
792 append(II1,[used_ids(Ids3)|II2],II)
793 ; append(II1,I2,II)
794 )
795 ; delete(I2,used_ids(_),II2),
796 append(I1,II2,II)
797 ),
798 sort(II,ResInfos). % TO DO: sort sublists ? and use ord_union?
799
800 important_info(contains_wd_condition).
801 important_info(prob_annotation(_)).
802 important_info(allow_to_lift_exists).
803 important_info(removed_typing).
804 %important_info(lambda_result(_)). % should probably not be copied
805
806 % variation of above which does not extract and merge used_ids:
807 extract_just_important_info_aux([],Acc,Acc).
808 extract_just_important_info_aux([H|T],Acc,Res) :-
809 (important_info(H), \+ member(H,Acc) -> extract_just_important_info_aux(T,[H|Acc],Res)
810 ; extract_just_important_info_aux(T,Acc,Res)).
811
812
813 is_a_conjunct(b(conjunct(A,B),pred,_),A,B).
814 % use is_a_conjunct_without_label if you want to avoid decomposing conjunction associated with a single label
815 is_a_conjunct_without_label(b(conjunct(A,B),pred,I),A,B) :- \+ get_info_labels(I,_).
816 % use decompose conjunct if you want to propagate labels down to the conjuncts
817 decompose_conjunct(b(conjunct(A,B),pred,I),ResA,ResB) :-
818 (get_info_labels(I,Labels)
819 -> add_labels_to_texpr(A,Labels,ResA), add_labels_to_texpr(B,Labels,ResB)
820 ; ResA=A, ResB=B).
821
822 size_of_conjunction(C,Size) :- size_of_conjunction(C,0,Size).
823 size_of_conjunction(C,Acc,Res) :- is_a_conjunct(C,A,B),!,
824 size_of_conjunction(B,Acc,A1),
825 size_of_conjunction(A,A1,Res).
826 size_of_conjunction(_,Acc,Size) :- Size is Acc+1.
827
828 conjunction_to_list(C,L) :- var(C),!,
829 add_error_fail(conjunction_to_list,'Internal error: var :',conjunction_to_list(C,L)).
830 conjunction_to_list(C,List) :-
831 conjunction_to_list2(C,List,[]).
832 conjunction_to_list2(X,I,O) :- X=b(E,_,_),
833 (E=conjunct(LHS,RHS) -> conjunction_to_list2(LHS,I,Inter),
834 conjunction_to_list2(RHS,Inter,O)
835 ; E = truth -> I=O
836 ; I = [X|O]).
837
838 % a variation of conjunction_to_list which propagates Rodin and pragma label infos down
839 % important for proof info; maybe we should only propagate Rodin labels ?
840 conjunction_to_list_with_rodin_labels(C,L) :- var(C),!,
841 add_error_fail(conjunction_to_list,'Internal error: var :',conjunction_to_list_with_rodin_labels(C,L)).
842 conjunction_to_list_with_rodin_labels(C,List) :-
843 conjunction_to_list_with_labels2(C,List,[]).
844 conjunction_to_list_with_labels2(b(conjunct(A,B),pred,Infos),I,O) :- !,
845 copy_rodin_label(Infos,A,B,LHS,RHS),
846 conjunction_to_list_with_labels2(LHS,I,Inter),
847 conjunction_to_list_with_labels2(RHS,Inter,O).
848 conjunction_to_list_with_labels2(X,I,O) :- X=b(E,_,_),
849 ( E = truth -> I=O
850 ; I = [X|O]).
851
852
853 copy_rodin_label(Infos,A,B,NewA,NewB) :- member(Pos,Infos), is_rodin_label_info(Pos),!,
854 add_rodin_label_info(A,Pos,NewA),
855 add_rodin_label_info(B,Pos,NewB).
856 copy_rodin_label(_,A,B,A,B).
857
858 add_rodin_label_info(b(E,T,I),Pos,b(E,T,I2)) :-
859 (member(Pos,I), is_rodin_label_info(Pos) -> I2=I
860 ; I2 = [Pos|I]).
861
862 is_rodin_label_info(nodeid(Pos)) :- functor(Pos,rodinpos,_).
863
864
865 flatten_conjunctions(List,FlattenedList) :- flatten_conj_aux(List,FlattenedList,[]).
866 flatten_conj_aux([]) --> !, [].
867 flatten_conj_aux([H|T]) --> !, flatten_conj_aux(H),flatten_conj_aux(T).
868 flatten_conj_aux(C) --> {is_a_conjunct(C,LHS,RHS)},
869 !,
870 flatten_conj_aux(LHS), flatten_conj_aux(RHS).
871 flatten_conj_aux(Truth) --> {is_truth(Truth)},!,[].
872 flatten_conj_aux(C) --> [C].
873
874 member_in_conjunction(M,Conj) :- is_a_conjunct(Conj,LHS,RHS),!,
875 ? (member_in_conjunction(M,LHS) ; member_in_conjunction(M,RHS)).
876 member_in_conjunction(M,M).
877
878 % a version of member_in_conjunction which can deal with lazy_let_pred :
879 % member_in_conjunction_cse(FullConjunctWithLets,InnerConjunctNotALet, Conjunction)
880 member_in_conjunction_cse(M,InnerConj,Conj) :- is_a_conjunct(Conj,LHS,RHS),!,
881 (member_in_conjunction_cse(M,InnerConj,LHS) ; member_in_conjunction_cse(M,InnerConj,RHS)).
882 member_in_conjunction_cse(Conj,InnerConj,b(lazy_let_pred(ID,Share,Body),pred,Info)) :-
883 Conj = b(lazy_let_pred(ID,Share,BConj),pred,Info),!,
884 member_in_conjunction_cse(BConj,InnerConj,Body).
885 member_in_conjunction_cse(M,M,M).
886
887 % not terribly efficient way to select and remove a conjunct from a predicate
888 select_member_in_conjunction(M,Conj,Rest) :- is_a_conjunct(Conj,LHS,RHS),!,
889 (select_member_in_conjunction(M,LHS,RL), conjunct_predicates([RL,RHS],Rest)
890 ; select_member_in_conjunction(M,RHS,RR), conjunct_predicates([LHS,RR],Rest)).
891 select_member_in_conjunction(M,M,b(truth,pred,[])).
892
893 is_a_disjunct(b(disjunct(A,B),pred,_),A,B).
894 is_a_negation(b(negation(A),pred,_),A).
895
896 disjunction_to_list(C,L) :- var(C),!,
897 add_error_fail(disjunction_to_list,'Internal error: var :',disjunction_to_list(C,L)).
898 disjunction_to_list(C,List) :-
899 disjunction_to_list2(C,List,[]).
900 disjunction_to_list2(C,I,O) :- is_a_disjunct(C,LHS,RHS),!,
901 disjunction_to_list2(LHS,I,Inter),
902 disjunction_to_list2(RHS,Inter,O).
903 disjunction_to_list2(X,[X|R],R).
904
905 is_an_implication(b(implication(A,B),pred,_),A,B).
906
907 is_an_equivalence(b(equivalence(A,B),pred,_),A,B).
908
909
910 is_a_disjunct_or_implication(b(DI,pred,_),Type,A,B) :- is_a_disj_or_impl_aux(DI,Type,A,B).
911 is_a_disj_or_impl_aux(disjunct(A,B),'disjunction',A,B).
912 is_a_disj_or_impl_aux(implication(A,B),'implication',NA,B) :-
913 create_negation(A,NA).
914 is_a_disj_or_impl_aux(negation(b(conjunct(A,B),pred,_)),'negated conjunction',NA,NB) :-
915 create_negation(A,NA),create_negation(B,NB).
916
917 % a more liberal version of is_a_conjunct/2 which also detects negated disjunctions/implications
918 is_a_conjunct_or_neg_disj(b(DI,pred,I),A,B) :- is_conjunct_aux(DI,I,A,B).
919
920 is_conjunct_aux(conjunct(LHS,RHS),_,LHS,RHS).
921 is_conjunct_aux(negation(DISJ),_,NegLHS,NegRHS) :-
922 is_a_disjunct_or_implication(DISJ,_Type,LHS,RHS),
923 create_negation(LHS,NegLHS),
924 create_negation(RHS,NegRHS).
925 is_conjunct_aux(equal(TA,TB),I,b(equal(TA1,TB1),pred,I),b(equal(TA2,TB2),pred,I)) :-
926 % split TA1|->TA2 = TB1|->TB2, cf, split_equality/3; useful for enumeration order analysis
927 get_texpr_couple(TA,TA1,TA2),
928 get_texpr_couple(TB,TB1,TB2).
929 % print('Splitting equality in is_a_conjunct_or_neg_disj: '), translate:print_bexpr(b(equal(TA,TB),pred,I)),nl.
930
931 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
932 % remove all info fields by fresh variables
933 % typically the result will be unified with AST terms which contain full info fields
934 remove_all_infos(TExpr,TNExpr) :-
935 var(TExpr),!,TExpr=TNExpr.
936 % in contrast to remove_all_infos_and_ground we provide no special treatment of values with closures here;
937 % there could be a problem if we unify with a free variable as value
938 remove_all_infos(TExpr,TNExpr) :-
939 get_texpr_expr(TExpr,Expr),
940 get_texpr_type(TExpr,Type),
941 syntaxtransformation(Expr,Subs,_,NSubs,NExpr),
942 create_texpr(NExpr,Type,_,TNExpr),
943 maplist(remove_all_infos,Subs,NSubs).
944
945 % replace all info fields
946 remove_all_infos_and_ground(TExpr,TNExpr) :-
947 var(TExpr),!,TExpr=TNExpr.
948 remove_all_infos_and_ground(b(value(Value),Type,_),TNExpr) :-
949 % special case for closure(_,_,_) since it is not covered by syntraxtransformation/5
950 % most useful for intervals
951 !,
952 remove_all_infos_from_bvalue(Value,NValue),
953 TNExpr = b(value(NValue),Type,[]).
954 remove_all_infos_and_ground(TExpr,TNExpr) :-
955 get_texpr_expr(TExpr,Expr),
956 get_texpr_type(TExpr,Type),
957 syntaxtransformation(Expr,Subs,_,NSubs,NExpr),
958 create_texpr(NExpr,Type,[],TNExpr),
959 maplist(remove_all_infos_and_ground,Subs,NSubs).
960
961 remove_all_infos_from_bvalue(Var,Res) :- var(Var),!, Res=Var.
962 remove_all_infos_from_bvalue((A,B),(RA,RB)) :- !,
963 remove_all_infos_from_bvalue(A,RA),
964 remove_all_infos_from_bvalue(B,RB).
965 remove_all_infos_from_bvalue(closure(P,T,Body),Res) :- !,
966 remove_all_infos_and_ground(Body,RBody),
967 Res = closure(P,T,RBody).
968 % TODO: we could provide more cases like records, sets as lists, freetype values
969 remove_all_infos_from_bvalue(Val,Val).
970
971 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
972
973 % a version of create_exists_opt which also detects top-level disjunctions
974 % and marks the exists as generated and as allow_to_lift_exists
975 create_exists_opt_liftable(Ids,b(disjunct(A,B),pred,Info1),NewPred) :- !,
976 create_exists_opt_liftable(Ids,A,PA),
977 create_exists_opt_liftable(Ids,B,PB),
978 disjunct_predicates_with_pos_info(PA,PB,b(NP,pred,Info2)),
979 NewPred=b(NP,pred,NewInfo),
980 extract_just_important_info_aux(Info1,Info2,NewInfo). % copy symbolic or other relevant info
981 create_exists_opt_liftable(Ids,Pred,NewPred) :- conjunction_to_list(Pred,L),
982 create_exists_opt(Ids,L,[allow_to_lift_exists],NewPred,_Modified).
983
984 % create_exists_opt(TIds,Preds,NewPred)
985 % creating an existential quantification with some optimisations.
986 % TIds: The typed identifiers that are quantified
987 % Preds: A list of predicates
988 % NewPred: The (optimised) quantified expression
989 % Basically two optimisations are performed:
990 % - identifiers that are not used at all are removed from the quantifier
991 % - predicates that do not use one of the quantified identifiers are moved
992 % outside the quantification, resulting in a predicate of the form "P & #x.Q(x)"
993
994 create_exists_opt(TIds,Preds,NewPred) :-
995 create_exists_opt(TIds,Preds,[],NewPred,_).
996
997 create_exists_opt(TIds,Preds,NewPred,Modified) :-
998 create_exists_opt(TIds,Preds,[],NewPred,Modified).
999
1000 create_exists_opt([],Preds,_,NewPred,Modified) :- !, Modified = false,
1001 conjunct_predicates(Preds,NewPred).
1002 create_exists_opt(TIds,Preds,AdditionalInfos,Res,Mod) :-
1003 get_texpr_ids(TIds,UnsortedIds), sort(UnsortedIds,Ids),
1004 (create_exists_opt1(TIds,Ids,Preds,AdditionalInfos,NewPred2,Modified) -> Res = NewPred2, Mod=Modified
1005 ; add_internal_error('Call failed:',create_exists_opt(TIds,Preds,AdditionalInfos,_,_)),fail).
1006 %create_exists_opt1(TIds,_,Preds,AdditionalInfos,NewPred,Modified) :- preference(data_validation_mode,true),
1007 % % do not lift predicates outside of existential quantifiers and change order; see rule_avec_DV.mch ClearSy example (N_ITERa_avec_DV_sans_DV) and test 1945
1008 create_exists_opt1(TIds,Ids,Preds,AdditionalInfos,NewPred2,Modified) :-
1009 create_exists_opt2(Preds,first,Ids,[],Inner,Outer,UsedIds),
1010 % Inner: quantified part, Outer: part which does not have to be quantified
1011 ( Inner = [] -> AllPreds=Outer % no exists needed
1012 ; % Inner = [_|_] ->
1013 create_filtered_exists(TIds,UsedIds,Inner,AdditionalInfos,Exists,IModified),
1014 append(Outer,[Exists],AllPreds)
1015 ),
1016 (Outer=[_|_] -> Modified=true % TO DO: check if TIds=UsedTIds
1017 ; IModified==true -> Modified=true
1018 ; UsedIds == Ids -> Modified= false
1019 ; Modified=true),
1020 conjunct_predicates(AllPreds,NewPred2).
1021
1022 % create an exists for the used Ids only
1023 create_filtered_exists(TIds,UsedIds,Inner,AdditionalInfos,Exists,_) :-
1024 ceo_filter_used_ids(TIds,UsedIds,UsedTIds), % filter out unused variables
1025 conjunct_predicates_with_pos_info(Inner,I), % we could store used_ids info
1026 create_exists_detect_tautology_aux(UsedTIds,I,AdditionalInfos,Exists).
1027 % remove_typing also added in create_exists_detect_tautology_aux
1028
1029
1030 % return Inner: predicates inside quantifier and Outer: predicates that can be moved out of the quantifier
1031 create_exists_opt2([],_,_Ids,UsedIds,[],[],UsedIds) :- !.
1032 create_exists_opt2([Pred|Prest],First,Ids,UsedIdsIn,Inner,Outer,UsedIdsOut) :- !,
1033 find_identifier_uses_if_necessary(Pred, [], LocalUses), % TODO: add used_ids(LocalUses) to Pred
1034 ord_intersection(Ids,LocalUses,ExistsIdsUsed),
1035 ( ExistsIdsUsed = [], % Pred uses none of the quantified ids: we can move it out
1036 (First==first -> true
1037 ; preference(data_validation_mode,false), % see test 1945; step 39 in trace replay
1038 always_well_defined_or_disprover_mode(Pred) % TODO: we should probably also check this !
1039 )
1040 ->
1041 Inner = Irest,
1042 Outer = [Pred|Orest], % move Pred out of existential quantifier as it does not depend on quantified variables
1043 % format('MOVED out of #(~w): ',[Ids]),translate:print_bexpr(Pred), format(' Uses ~w [~w]~n',[LocalUses,ExistsIdsUsed]),
1044 create_exists_opt2(Prest,first,Ids,UsedIdsIn,Irest,Orest,UsedIdsOut)
1045 ;
1046 update_used_ids(Pred,LocalUses,Pred2),
1047 Inner = [Pred2|Irest],
1048 Outer = Orest,
1049 ord_union(UsedIdsIn,ExistsIdsUsed,Urest),
1050 create_exists_opt2(Prest,not_first_anymore,Ids,Urest,Irest,Orest,UsedIdsOut)
1051 ).
1052 create_exists_opt2(Pred,First,Ids,UsedIdsIn,Inner,Outer,UsedIdsOut) :-
1053 add_error(create_exists_opt,'Expecting predicate list: ',Pred),
1054 create_exists_opt2([Pred],First,Ids,UsedIdsIn,Inner,Outer,UsedIdsOut).
1055
1056 % construct exists optimized: keep only used TIds
1057 ceo_filter_used_ids([],_UsedIds,[]).
1058 ceo_filter_used_ids([TId|Irest],UsedIds,Filtered) :-
1059 get_texpr_id(TId,Id),
1060 ( ord_member(Id,UsedIds) -> Filtered = [TId|Frest] % id used: keep it
1061 ; Filtered = Frest),
1062 ceo_filter_used_ids(Irest,UsedIds,Frest).
1063
1064 % a version of create_exists which also detects x=E and x:E, x>E, not(x>E) tautologies
1065 % we could replace this by a more generic prover
1066 create_exists_detect_tautology_aux([TID],b(member(LHS,RHS),pred,_),_,Truth) :-
1067 get_texpr_id(LHS,ID), get_texpr_id(TID,ID),
1068 definitely_not_empty_set(RHS),
1069 always_well_defined_or_disprover_mode(RHS),
1070 !, % replace #x.(x:RHS) by TRUTH
1071 debug_format(19,'Detected tautology exists membership over ~w~n',[ID]),
1072 Truth=b(truth,pred,[]).
1073 create_exists_detect_tautology_aux([TID],b(Pred,_,_),_,Truth) :-
1074 is_comparison(Pred,pos_neg(pos,TID),L,R), get_texpr_id(TID,ID),
1075 ((LHS,RHS)=(L,R) ; (LHS,RHS)=(R,L)),
1076 get_texpr_id(LHS,ID),
1077 \+ occurs_in_expr(ID,RHS),
1078 always_well_defined_or_disprover_mode(RHS),
1079 !, % replace #x.(x COMP E) by TRUTH
1080 debug_format(19,'Detected tautology comparison over ~w~n',[ID]),
1081 Truth=b(truth,pred,[]).
1082 %create_exists_detect_tautology_aux(Ids,b(disjunct(A,B),pred,Info1),AdditionalInfos,NewPred) :- !,
1083 % create_exists(Ids,A,PA), create_exists(Ids,B,PB),
1084 % disjunct_predicates_with_pos_info(PA,PB,b(NP,pred,Info2)),
1085 % NewPred=b(NP,pred,NewInfo),
1086 % extract_just_important_info_aux(Info1,Info2,NewInfo). % copy symbolic or other relevant info
1087 create_exists_detect_tautology_aux(Ids,Pred,AdditionalInfos,NewPred2) :-
1088 create_exists_or_let_predicate(Ids,Pred,NewPred),
1089 add_texpr_infos_if_new(NewPred,[removed_typing|AdditionalInfos],NewPred2).
1090 % removed_typing to avoid spurious exists_body_warning, see test 1681, 625
1091
1092
1093 is_eventb_comprehension_set(b(comprehension_set(TopIds,Body),_,Info),Ids,PRED,EXPR) :-
1094 is_eventb_comprehension_set(TopIds,Body,Info,Ids,PRED,EXPR).
1095 is_eventb_comprehension_set([TID1],Body,Info,Ids,PRED,EXPR) :-
1096 Body = b(exists(Ids,InnerBody),pred,_),
1097 member(was(event_b_comprehension_set),Info),
1098 conjunction_to_list(InnerBody,Inner),
1099 append(Inner1,[b(equal(TID2,EXPR),pred,_)],Inner),
1100 same_id(TID1,TID2,_),
1101 conjunct_predicates(Inner1,PRED),
1102 % we check that TID1 is not being used in P1 and not just rely on was(event_b_comprehension_set)
1103 not_occurs_in_expr(PRED,TID1).
1104
1105 % -------------------
1106
1107 is_equal(b(equal(LHS,RHS),pred,_),A,B) :-
1108 ((A,B)=(LHS,RHS) ; (A,B)=(RHS,LHS)).
1109
1110 :- use_module(typing_tools,[type_has_at_least_two_elements/1]).
1111 is_comparison(greater(A,B),_,A,B).
1112 is_comparison(less(A,B),_,A,B).
1113 is_comparison(greater_equal(A,B),_,A,B).
1114 is_comparison(less_equal(A,B),_,A,B).
1115 is_comparison(equal(A,B),pos_neg(P,TID),A,B) :-
1116 % for neg: we need to make sure there is more than one value in the type (otherwise we cannot make equal false)
1117 % for pos: assuming the RHS expression above is well-defined there must be at least one element; no need to check non_empty_type(Type)
1118 (P=pos -> true ; get_texpr_type(TID,Type),type_has_at_least_two_elements(Type)).
1119 is_comparison(not_equal(A,B),pos_neg(P,TID),A,B) :- % ditto but with pos and neg reversed
1120 (P=neg -> true ; get_texpr_type(TID,Type),type_has_at_least_two_elements(Type)).
1121 is_comparison(negation(b(Comp,pred,_)),PosNeg,A,B) :- negate(PosNeg,P2),
1122 is_comparison(Comp,P2,A,B).
1123 negate(pos_neg(pos,T),pos_neg(neg,T)).
1124 negate(pos_neg(neg,T),pos_neg(pos,T)).
1125
1126
1127
1128 % is true if a predicate Pred can be split into two parts:
1129 % Outer which does not depend on LocalIds (can be lifted out) and Inner which does
1130 detect_global_predicates(LocalIds,Pred,Outer,Inner) :-
1131 get_texpr_ids(LocalIds,UnsortedIds), sort(UnsortedIds,Ids),
1132 conjunction_to_list(Pred,Preds),
1133 split_predicate_local_global(Preds,Ids,OuterL,InnerL),
1134 OuterL \= [],
1135 conjunct_predicates(OuterL,Outer),
1136 conjunct_predicates(InnerL,Inner).
1137 split_predicate_local_global([],_Ids,[],[]).
1138 split_predicate_local_global([P|Ps],Ids,Outer,Inner) :-
1139 (is_local_predicate(Ids,P)
1140 -> Inner = [P|Is], split_predicate_local_global(Ps,Ids,Outer,Is)
1141 ; Outer = [P|Os], split_predicate_local_global(Ps,Ids,Os,Inner)).
1142 is_local_predicate(Ids,Pred) :-
1143 find_identifier_uses_if_necessary(Pred, [], LocalUses),
1144 ord_intersect(Ids,LocalUses).
1145
1146 %:- use_module(b_global_sets,[b_global_set/1]).
1147 definitely_not_empty_set(b(SET,T,_)) :- not_empty_set_aux(SET,T).
1148 not_empty_set_aux(bool_set,_).
1149 not_empty_set_aux(integer_set(_),_).
1150 not_empty_set_aux(float_set,_).
1151 not_empty_set_aux(real_set,_).
1152 not_empty_set_aux(string_set,_).
1153 not_empty_set_aux(set_extension(X),_) :- dif(X,[]).
1154 not_empty_set_aux(sequence_extension(X),_) :- dif(X,[]).
1155 not_empty_set_aux(pow_subset(_),_). % always contains at least the empty set
1156 not_empty_set_aux(fin_subset(_),_). % ditto
1157 not_empty_set_aux(seq(_),_). % ditto
1158 not_empty_set_aux(seq1(_),_). % ditto
1159 not_empty_set_aux(pow1_subset(A),_) :- definitely_not_empty_set(A).
1160 not_empty_set_aux(fin1_subset(A),_) :- definitely_not_empty_set(A).
1161 not_empty_set_aux(seq1(A),_) :- definitely_not_empty_set(A).
1162 not_empty_set_aux(iseq1(A),_) :- definitely_not_empty_set(A).
1163 not_empty_set_aux(cartesian_product(A,B),_) :- definitely_not_empty_set(A), definitely_not_empty_set(B).
1164 not_empty_set_aux(partial_function(_A,_B),_). % always contains at least the empty set
1165 not_empty_set_aux(partial_injection(_A,_B),_). % ditto
1166 not_empty_set_aux(relations(_A,_B),_). % ditto
1167 not_empty_set_aux(total_function(A,B),_) :-
1168 (definitely_not_empty_set(B) -> true
1169 ; definitely_empty_set(A)). % if A is empty, then the set of total functions is {{}}
1170 % TODO: add a few more function rules
1171 not_empty_set_aux(value(S),_) :- not_empty_value(S).
1172
1173 %not_empty_set_aux(identifier(X),set(global(X))) :- bmachine:b_get_machine_set(X). % what if we have a local variable ? ENSURE THAT WE DO NOT ALLOW identifier X to stand for global set X; see ExistentialGlobalSetIDTest in Tester % also: b_global_set not yet computed when ast_cleanup runs on startup !
1174 % TO DO: determine which identifier(X) refer to global set names
1175 not_empty_set_aux(interval(A,B),_) :- get_integer(A,IA), get_integer(B,IB), IA =< IB.
1176
1177 :- use_module(b_global_sets,[b_non_empty_global_set/1]).
1178 not_empty_value(S) :- var(S),!,fail.
1179 not_empty_value(avl_set(_)).
1180 not_empty_value([_|_]).
1181 not_empty_value(global_set(G)) :- b_non_empty_global_set(G). % always true
1182 %TODO: closure?
1183
1184 definitely_empty_set(b(ES,_,_)) :- is_empty_set_aux(ES).
1185 is_empty_set_aux(empty_set).
1186 is_empty_set_aux(empty_sequence).
1187 is_empty_set_aux(domain(D)) :- definitely_empty_set(D).
1188 is_empty_set_aux(range(D)) :- definitely_empty_set(D).
1189 is_empty_set_aux(domain_subtraction(_,Rel)) :- definitely_empty_set(Rel).
1190 is_empty_set_aux(domain_restriction(Dom,Rel)) :- (definitely_empty_set(Dom) -> true ; definitely_empty_set(Rel)).
1191 is_empty_set_aux(range_restriction(Rel,Ran)) :- (definitely_empty_set(Ran) -> true ; definitely_empty_set(Rel)).
1192 is_empty_set_aux(range_subtraction(Rel,_)) :- definitely_empty_set(Rel).
1193 is_empty_set_aux(interval(A,B)) :- get_integer(A,IA), get_integer(B,IB), IA > IB.
1194 is_empty_set_aux(intersection(A,B)) :- (definitely_empty_set(A) -> true ; definitely_empty_set(B)).
1195 is_empty_set_aux(value(V)) :- V==[].
1196
1197
1198 get_integer(b(B,_,_),I) :- get_integer_aux(B,I).
1199 get_integer_aux(integer(I),I).
1200 get_integer_aux(value(V),I) :- get_integer_value(V,I).
1201 get_integer_value(V,I) :- nonvar(V),V=int(I), integer(I).
1202
1203
1204
1205 :- use_module(probsrc(custom_explicit_sets),[avl_is_interval/3]).
1206 get_interval(b(I,set(integer),_),Low,Up) :-
1207 is_interval_aux(I,Low,Up).
1208 is_interval_aux(interval(Low,Up),Low,Up).
1209 is_interval_aux(value(CS),Low,Up) :- nonvar(CS), CS=avl_set(AVL), % occurs in Leftpad_i.imp
1210 Low = b(integer(LI),integer,[]), Up = b(integer(UI),integer,[]),
1211 avl_is_interval(AVL,LI,UI).
1212 is_interval_aux(set_extension(List),Low,Up) :- print(l(List)),nl,
1213 sort(List,SList),
1214 SList = [Low|Rest], get_integer(Low,LI),
1215 last(SList,Up), get_integer(Up,UI),
1216 length(List,Len),
1217 Len is UI-LI+1,
1218 maplist(get_integer,Rest,_).
1219
1220 % a simple let-detection
1221 create_exists_or_let_predicate([H|T],b(conjunct(LHS,RHS),pred,I),NewPred) :- get_texpr_id(H,ID),
1222 ? is_equal(LHS,TID,IDEXPR), % TO DO: should we do a more complicated check here ? exist technique useful for SLOT-24 codespeed test
1223 get_texpr_id(TID,ID), \+ occurs_in_expr(ID,IDEXPR),
1224 maplist(not_occurs_in_expr(IDEXPR),T),
1225 !,
1226 NewPred = b(let_predicate([TID],[IDEXPR],Body),pred,I),
1227 %print('LET: '),translate:print_bexpr(NewPred),nl,
1228 create_exists_or_let_predicate(T,RHS,Body).
1229 create_exists_or_let_predicate(Ids,Pred,NewPred) :- create_exists(Ids,Pred,NewPred).
1230
1231 not_occurs_in_expr(IDEXPR,TID) :- get_texpr_id(TID,ID), \+ occurs_in_expr(ID,IDEXPR).
1232
1233 create_exists([],Pred,NewPred) :- !,Pred=NewPred.
1234 create_exists(Ids,Pred,NewPred) :-
1235 find_identifier_uses_for_quantifier_body(Ids,Pred, Used),
1236 extract_info_wo_used_ids(Pred,NewImportantInfo),
1237 create_texpr(exists(Ids,Pred),pred,[used_ids(Used)|NewImportantInfo],NewPred).
1238
1239 % a version of create_exists which can merge with an already present exists if possible
1240 % possibly more expensive as identfiers used are recomputed for the moment (TODO: reuse used_ids and subtract)
1241 create_or_merge_exists(IDs, Condition, Exists):-
1242 get_texpr_expr(Condition,exists(InnerVars,InnerCond)),!,
1243 % fuse two exists together
1244 append(IDs,InnerVars,Vars),
1245 create_or_merge_exists(Vars,InnerCond,Exists).
1246 create_or_merge_exists(IDs, Condition, Exists):-
1247 create_exists(IDs,Condition,Exists).
1248
1249
1250 create_forall([],Pred,NewPred) :- !,Pred=NewPred.
1251 create_forall(Ids,Pred,NewPred) :-
1252 find_identifier_uses_for_quantifier_body(Ids,Pred, Used),
1253 split_forall_body(Pred,LHS,RHS),
1254 extract_info_wo_used_ids_and_pos(LHS,RHS,NewImportantInfo),
1255 create_texpr(forall(Ids,LHS,RHS),pred,[used_ids(Used)|NewImportantInfo],NewPred).
1256 split_forall_body(b(implication(LHS,RHS),_,_),LHS,RHS) :- !.
1257 split_forall_body(RHS,b(truth,pred,[]),RHS).
1258
1259 create_implication(b(truth,pred,_),P,Res) :- !, Res=P.
1260 create_implication(b(falsity,pred,_),P,Res) :- !, create_negation(P,Res).
1261 create_implication(Lhs,Rhs,b(implication(Lhs,Rhs),pred,NewInfo)) :-
1262 extract_info(Lhs,Rhs,NewInfo).
1263
1264 create_equivalence(Lhs,Rhs, b(equivalence(Lhs,Rhs),pred,NewInfo)) :-
1265 extract_info(Lhs,Rhs,NewInfo).
1266
1267 create_negation(b(P,pred,I),Res) :- create_negation_aux(P,I,R),!,Res=R.
1268 create_negation(Pred,b(negation(Pred),pred,NewInfo)) :-
1269 extract_info(Pred,Infos),
1270 (get_texpr_non_label_posinfo(Pred,Pos) -> NewInfo = [Pos|Infos] ; NewInfo=Infos).
1271
1272 create_negation_aux(truth,I,R) :- !, R=b(falsity,pred,I).
1273 create_negation_aux(falsity,I,R) :- !, R=b(truth,pred,I).
1274 create_negation_aux(negation(Pred),_,R) :- R=Pred. % not(not(P)) = P
1275 %create_negation_aux(equal(A,B),I,R) :- !, R=b(not_equal(A,B),pred,I).
1276 %create_negation_aux(not_equal(A,B),I,R) :- !, R=b(equal(A,B),pred,I).
1277 % we could add some rules about negating member <-> not_member, ... but be careful with effects on is_negation_of
1278
1279 % check if something is the negation of something else (quite stupid at the moment)
1280 % used, e.g., to detect IF-THEN-ELSE constructs in b_ast_cleanup
1281 is_negation_of(P,NP) :-
1282 create_negation(P,NotP), % works both with not(A),A or A,not(A)
1283 same_texpr(NotP,NP).
1284 is_negation_of(b(P,pred,_),b(NP,pred,_)) :- is_negation_aux(P,NP).
1285
1286 is_negation_aux(equal(A,B),NP) :- is_negation_of_equality(NP,A,B).
1287 is_negation_aux(not_equal(A,B),NP) :- is_negation_of_disequality(NP,A,B).
1288 is_negation_aux(subset(XA,SA),not_subset(XB,SB)) :- same_texpr(XA,XB), same_texpr(SA,SB).
1289 is_negation_aux(not_subset(XA,SA),subset(XB,SB)) :- same_texpr(XA,XB), same_texpr(SA,SB).
1290 is_negation_aux(subset_strict(XA,SA),not_subset_strict(XB,SB)) :- same_texpr(XA,XB), same_texpr(SA,SB).
1291 is_negation_aux(not_subset_strict(XA,SA),subset_strict(XB,SB)) :- same_texpr(XA,XB), same_texpr(SA,SB).
1292 is_negation_aux(member(XA,SA),not_member(XB,SB)) :- same_texpr(XA,XB), same_texpr(SA,SB).
1293 is_negation_aux(not_member(XA,SA),member(XB,SB)) :- same_texpr(XA,XB), same_texpr(SA,SB).
1294 is_negation_aux(less(A,B),greater_equal(AA,BB)) :- same_texpr(A,AA), same_texpr(B,BB).
1295 is_negation_aux(less(A,B),less_equal(BB,AA)) :- same_texpr(A,AA), same_texpr(B,BB).
1296 is_negation_aux(less_equal(B,A),less(AA,BB)) :- same_texpr(A,AA), same_texpr(B,BB).
1297 is_negation_aux(less_equal(A,B),greater(AA,BB)) :- same_texpr(A,AA), same_texpr(B,BB).
1298 is_negation_aux(greater_equal(A,B),NP) :- is_negation_aux(less_equal(B,A),NP).
1299 is_negation_aux(greater(A,B),NP) :- is_negation_aux(less(B,A),NP).
1300 is_negation_aux(less_equal_real(B,A),less_real(AA,BB)) :- same_texpr(A,AA), same_texpr(B,BB).
1301 is_negation_aux(less_real(B,A),less_equal_real(AA,BB)) :- same_texpr(A,AA), same_texpr(B,BB).
1302 is_negation_aux(negation(A),negation(B)) :- is_negation_of(A,B).
1303 is_negation_aux(truth,falsity).
1304 is_negation_aux(falsity,truth).
1305 % TO DO: detect more ?? x < y <=> not ( x > y-1 )
1306
1307 is_negation_of_equality(not_equal(AA,BB),A,B) :- same_texpr(A,AA), same_texpr(B,BB).
1308 is_negation_of_equality(equal(AA,BB),A,B) :- same_texpr(A,AA), neg_value(BB,B).
1309
1310 neg_value(b(boolean_true,_,_),b(boolean_false,_,_)).
1311 neg_value(b(boolean_false,_,_),b(boolean_true,_,_)).
1312
1313 is_negation_of_disequality(equal(AA,BB),A,B) :- same_texpr(A,AA), same_texpr(B,BB).
1314 is_negation_of_disequality(not_equal(AA,BB),A,B) :- same_texpr(A,AA), neg_value(BB,B).
1315
1316
1317 % another version which is simpler can can be used to get the negation of some operators
1318
1319 get_negated_operator_expr(b(E,pred,_),Res) :- negate_expr_aux(E,Res).
1320 negate_expr_aux(falsity,truth).
1321 negate_expr_aux(truth,falsity).
1322 negate_expr_aux(member(X,S),not_member(X,S)).
1323 negate_expr_aux(not_member(X,S),member(X,S)).
1324 negate_expr_aux(subset(X,S),not_subset(X,S)).
1325 negate_expr_aux(not_subset(X,S),subset(X,S)).
1326 negate_expr_aux(subset_strict(X,S),not_subset_strict(X,S)).
1327 negate_expr_aux(not_subset_strict(X,S),subset_strict(X,S)).
1328 negate_expr_aux(equal(X,S),not_equal(X,S)).
1329 negate_expr_aux(not_equal(X,S),equal(X,S)).
1330 negate_expr_aux(less(X,S),greater_equal(X,S)).
1331 negate_expr_aux(greater_equal(X,S),less(X,S)).
1332 negate_expr_aux(less_equal(X,S),greater(X,S)).
1333 negate_expr_aux(greater(X,S),less_equal(X,S)).
1334 negate_expr_aux(less_equal_real(X,S),less_real(S,X)).
1335 negate_expr_aux(less_real(X,S),less_equal_real(S,X)).
1336 % TO DO: negation()
1337
1338
1339 % a liberal version for finding equalities
1340 is_equality(TP,TA,TB) :- get_texpr_expr(TP,P), is_equality_aux(P,TA,TB).
1341
1342 is_equality_aux(Var,TA,TB) :- var(Var),!, add_internal_error('Illegal call: ', is_equality_aux(Var,TA,TB)),fail.
1343 is_equality_aux(equal(TA,TB),TA,TB).
1344 is_equality_aux(not_equal(TA,TB),NTA,NTB) :-
1345 (negate_boolean_value(TB,NTB) -> NTA=TA
1346 ; NTB=TB, negate_boolean_value(TA,NTA)). % TA /= TRUE ---> TA = FALSE
1347 is_equality_aux(partition(TA,[TB]),TA,TB).
1348 is_equality_aux(member(TA,TSet),TA,TB) :- singleton_set_extension(TSet,TB). % TA:{TB}
1349 is_equality_aux(negation(TExpr),TA,TB) :- get_negated_operator_expr(TExpr,NT), is_equality_aux(NT,TA,TB).
1350
1351 negate_boolean_value(b(B,T,I),b(NB,T,I)) :- neg_bool_aux(B,NB).
1352 neg_bool_aux(boolean_true,boolean_false).
1353 neg_bool_aux(boolean_false,boolean_true).
1354 % TODO: should we also detect value(pred_true), ....
1355
1356 singleton_set_extension(b(SONE,Type,_),El) :- singleton_set_extension_aux(SONE,Type,El).
1357 singleton_set_extension_aux(set_extension([El]),_,El).
1358 singleton_set_extension_aux(value(Set),set(Type),b(value(El),Type,[])) :- custom_explicit_sets:singleton_set(Set,El).
1359 singleton_set_extension_aux(sequence_extension([El]),_,Couple) :-
1360 ONE = b(integer(1),integer,[]),
1361 create_couple(ONE,El,Couple).
1362
1363
1364 % detect various forms of membership:
1365 is_membership(b(Expr,pred,_),TID,Set) :- is_membership_aux(Expr,TID,Set).
1366 is_membership_aux(member(TID,Set),TID,Set).
1367 is_membership_aux(subset(SONE,Set),TID,Set) :- singleton_set_extension(SONE,TID). % {TID} <: Set
1368
1369 % detect even more forms of membership:
1370 is_membership_or_equality(b(Expr,pred,_),TID,Set) :-
1371 (is_membership_aux(Expr,TID,Set) -> true ; is_mem_eq_aux(Expr,TID,Set)).
1372
1373 is_mem_eq_aux(equal(TID,VAL),TID,Set) :- % x=VAL <==> x:{VAL}
1374 get_texpr_type(VAL,Type),
1375 safe_create_texpr(set_extension([VAL]),set(Type),Set).
1376
1377 % ---------------------------------
1378
1379 is_pow_subset(B,Set) :-
1380 ( B = b(pow_subset(Set),_,_)
1381 ; B = b(fin_subset(Set),_,_),
1382 finite_wd_set_value(Set)
1383 ).
1384 is_pow1_subset(B,Set) :-
1385 ( B = b(pow1_subset(Set),_,_)
1386 ; B = b(fin1_subset(Set),_,_),
1387 finite_wd_set_value(Set)
1388 ).
1389
1390 % ---------------------------------
1391
1392 get_texpr_couple(b(couple(TA1,TA2),_,_),TA1,TA2).
1393
1394 % detect TA1|->TA2 = TB1|->TB2 and split into two
1395 split_equality(b(equal(TA,TB),pred,I),b(equal(TA1,TB1),pred,I),b(equal(TA2,TB2),pred,I)) :-
1396 get_texpr_couple(TA,TA1,TA2),
1397 get_texpr_couple(TB,TB1,TB2).
1398
1399 create_equality(b(_,TA,_),b(_,TB,_),_) :- TA \= TB, \+ unify_types_strict(TA,TB),!,
1400 add_internal_error('Creating equality with incompatible types:',equal(TA,TB)),fail.
1401 create_equality(A,B,Equality) :-
1402 safe_create_texpr(equal(A,B),pred,Equality).
1403
1404 create_couple(A,B,b(couple(A,B),couple(TA,TB),Infos)) :-
1405 get_texpr_type(A,TA), get_texpr_type(B,TB),
1406 extract_info(A,B,Infos).
1407
1408 % couplise_list for typed expression list
1409 create_couple([A],Couple) :- !,A=Couple.
1410 create_couple([A,B|Rest],Couple) :-
1411 create_couple(A,B,Couple1),
1412 create_couple([Couple1|Rest],Couple).
1413
1414 % derive typing from Ids
1415 create_comprehension_set(Ids,Pred,Info,CompSet) :-
1416 get_texpr_types(Ids,Types),
1417 couplise_list(Types,ElementType),
1418 create_texpr(comprehension_set(Ids,Pred),set(ElementType),Info,CompSet).
1419
1420
1421 :- assert_must_succeed(bsyntaxtree:nested_couple_to_list(b(couple(b(couple(a,b),x,[]),c),xx,[]),[a,b,c])).
1422 :- assert_must_succeed(bsyntaxtree:nested_couple_to_list(b(couple(a,c),x,[]),[a,c])).
1423 :- assert_must_succeed(bsyntaxtree:nested_couple_to_list(b(couple(a,b(couple(b,c),x,[])),xx,[]),[a,b(couple(b,c),x,[])])).
1424 nested_couple_to_list(NC,L) :- nested_couple_to_list_dcg(NC,L,[]).
1425 nested_couple_to_list_dcg(b(couple(A,B),_,_)) --> !,
1426 nested_couple_to_list_dcg(A), [B].
1427 nested_couple_to_list_dcg(E) --> [E].
1428
1429 % --------------------------------------
1430
1431
1432 % check if identifier(s) occur in typed expressions
1433
1434 occurs_in_expr(ID,TExpr) :- var(ID),!,
1435 add_internal_error('Variable id: ',occurs_in_expr(ID,TExpr)),fail.
1436 occurs_in_expr(ID,TExpr) :- ID=b(_,_,_),!, add_internal_error('Non-atomic identifier: ',occurs_in_expr(ID,TExpr)),fail.
1437 occurs_in_expr(ID,TExpr) :- ID=[_|_],!,
1438 add_internal_error('List instead of identifier: ',occurs_in_expr(ID,TExpr)),fail.
1439 occurs_in_expr(ID,TExpr) :- occurs_in_expr1(TExpr,ID).
1440
1441 % treat a few common operators here; possibly avoid traversing whole term if we find ID in a sub-tree
1442 occurs_in_expr1(TExpr,ID) :- TExpr = b(Expr,_,_),!,
1443 occurs_in_expr2(Expr,TExpr,ID).
1444 occurs_in_expr1(TExpr,ID) :- add_internal_error('Illegal typed expression:',occurs_in_expr1(TExpr,ID)).
1445
1446 occurs_in_expr2(add(A,B),_,ID) :- !,
1447 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID)).
1448 occurs_in_expr2(conjunct(A,B),_,ID) :- !,
1449 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID)).
1450 occurs_in_expr2(couple(A,B),_,ID) :- !,
1451 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID)).
1452 occurs_in_expr2(member(A,B),_,ID) :- !,
1453 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID)).
1454 occurs_in_expr2(equal(A,B),_,ID) :- !,
1455 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID)).
1456 occurs_in_expr2(function(A,B),_,ID) :- !,
1457 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID)).
1458 occurs_in_expr2(image(A,B),_,ID) :- !,
1459 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID)).
1460 occurs_in_expr2(intersection(A,B),_,ID) :- !,
1461 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID)).
1462 occurs_in_expr2(interval(A,B),_,ID) :- !,
1463 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID)).
1464 occurs_in_expr2(not_equal(A,B),_,ID) :- !,
1465 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID)).
1466 occurs_in_expr2(assertion_expression(A,_Msg,B),_,ID) :- !,
1467 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID)).
1468 occurs_in_expr2(domain(A),_,ID) :- !, occurs_in_expr1(A,ID).
1469 occurs_in_expr2(range(A),_,ID) :- !, occurs_in_expr1(A,ID).
1470 occurs_in_expr2(record_field(A,_FieldName),_,ID) :- !, occurs_in_expr1(A,ID).
1471 occurs_in_expr2(identifier(ID1),_,ID) :- !,
1472 ID1 = ID.
1473 occurs_in_expr2(integer(_),_,_ID) :- !,fail.
1474 occurs_in_expr2(string(_),_,_ID) :- !,fail.
1475 occurs_in_expr2(value(_),_,_ID) :- !,fail.
1476 occurs_in_expr2(truth,_,_ID) :- !,fail.
1477 occurs_in_expr2(if_then_else(A,B,C),_,ID) :- !,
1478 (occurs_in_expr1(A,ID) -> true ; occurs_in_expr1(B,ID) -> true ; occurs_in_expr1(C,ID)).
1479 occurs_in_expr2(rec(Fields),_,ID) :- !,
1480 l_field_occurs_in_expr1(Fields,ID).
1481 occurs_in_expr2(set_extension(Elements),_,ID) :- !,
1482 l_occurs_in_expr1(Elements,ID).
1483 occurs_in_expr2(sequence_extension(Elements),_,ID) :- !,
1484 l_occurs_in_expr1(Elements,ID).
1485 occurs_in_expr2(Expr,_,ID) :-
1486 syntaxelement(Expr,List,[], [], [], _), % no bound quantifiers; TO DO: treat bound quantifiers
1487 !,
1488 l_occurs_in_expr1(List,ID).
1489 occurs_in_expr2(_E,TExpr,ID) :-
1490 %functor(_E,F,N), print(occurs_in_expr2(F,N,ID)),nl,
1491 (find_identifier_uses_if_necessary(TExpr,[],Used)
1492 -> %check_sorted(Used),
1493 %add_message(bsyntaxtree,'Occurs check: ',ID:Used,TExpr), translate:nested_print_bexpr(TExpr),nl,
1494 ord_member(ID,Used)
1495 ; add_failed_call_error(find_identifier_uses(TExpr,[],_)),fail).
1496 % TO DO: optimize so that we only look for ID; we don't have to keep track of other IDs
1497
1498 l_occurs_in_expr1([H|T],ID) :- !,
1499 (occurs_in_expr1(H,ID) -> true ; l_occurs_in_expr1(T,ID)).
1500 l_occurs_in_expr1(L,ID) :- L \= [],
1501 add_internal_error('Illegal typed expression list:',l_occurs_in_expr1(L,ID)).
1502 l_field_occurs_in_expr1([field(_,H)|T],ID) :- !,
1503 (occurs_in_expr1(H,ID) -> true ; l_field_occurs_in_expr1(T,ID)).
1504 l_field_occurs_in_expr1(L,ID) :- L \= [],
1505 add_internal_error('Illegal record field list:',l_field_occurs_in_expr1(L,ID)).
1506
1507 %check_sorted(List) :- sort(List,SL), (SL \= List -> add_internal_error('Not sorted:',List) ; true).
1508
1509 some_id_occurs_in_expr([H|T],TExpr) :- (var(H) ; \+ atomic(H) ; var(T) ; T=[H2|_], H2 @< H),
1510 add_internal_error('Must be (sorted) atomic identifiers: ',some_id_occurs_in_expr([H|T],TExpr)),
1511 fail.
1512 some_id_occurs_in_expr([Id],TExpr) :- !, % use version without complete find_identifier_uses
1513 occurs_in_expr(Id,TExpr).
1514 some_id_occurs_in_expr(SortedIDs,TExpr) :-
1515 find_identifier_uses_if_necessary(TExpr,[],Used),
1516 list_to_ord_set(Used,UsedSorted),
1517 ord_intersect(UsedSorted,SortedIDs).
1518
1519 % -----------------------------
1520
1521 % find used identifiers in typed expressions
1522
1523 % a special version for quantifier bodies, attempting to reuse used_ids info
1524 find_identifier_uses_for_quantifier_body(TIds,Body,Res) :-
1525 get_texpr_ids(TIds,Ids),
1526 list_to_ord_set(Ids,Ignore),
1527 find_identifier_uses_if_necessary(Body,Ignore,Res).
1528
1529 % only run find_identifier_uses if necessary because no used_ids Info field present
1530 % TO DO: we could consider using used_ids within find_typed_identifier_uses: drawback: we would need to store types
1531 find_identifier_uses_if_necessary(Expr,Ignore,Res) :-
1532 get_texpr_info(Expr,I),
1533 ? member(used_ids(UIds),I),!, %print('+'),nl,
1534 find_with_reuse(Expr,UIds,Ignore,Res).
1535 find_identifier_uses_if_necessary(Expr,Ignore,Res) :- find_identifier_uses(Expr,Ignore,Res).
1536
1537 find_with_reuse(Expr,UIds,Ignore,Res) :- preference(prob_safe_mode,true),
1538 !,
1539 (is_ordset(Ignore) -> true ; add_internal_error('Not ordset: ',Ignore)),
1540 (is_ordset(UIds) -> true ; add_internal_error('Not ordset: ',UIds)),
1541 ord_subtract(UIds,Ignore,Res0),
1542 find_identifier_uses(Expr,Ignore,Res1),
1543 (Res1=Res0 -> true
1544 ; ord_subtract(Res1,Res0,Miss), % missing
1545 ord_subtract(Res0,Res1,Res01), % too much
1546 (Miss=[] -> add_message(find_identifier_uses_if_necessary,'Suboptimal used_ids: ',Res01,Expr)
1547 ; add_internal_error('Incorrect used_ids:',used_ids(missing(Miss),toomuch(Res01),usedids(UIds),
1548 ignore(Ignore),real(Res1))),
1549 translate:print_bexpr(Expr),nl
1550 )
1551 ),
1552 Res=Res1.
1553 find_with_reuse(_,UIds,Ignore,Res) :-
1554 %(is_ordset(Ignore) -> true ; add_internal_error('Not ordset: ',Ignore)),
1555 ord_subtract(UIds,Ignore,Res).
1556
1557
1558 find_identifier_uses_top_level(TExpr,Ids) :-
1559 get_global_identifiers(Ignored), % ignore all global sets and global constants;
1560 % hence find_identifier_uses_top_level/2 usually should only be called for top level expressions
1561 find_identifier_uses(TExpr,Ignored,Ids).
1562
1563 :- use_module(tools,[safe_sort/3]).
1564 find_identifier_uses(TExpr,Ignored,Ids) :-
1565 %tools_printing:print_term_summary(find_identifier_uses(TExpr,Ignored,Ids)),nl,
1566 check_is_texpr(TExpr,find_identifier_uses),
1567 (find_typed_identifier_uses(TExpr,Ignored,TIds)
1568 -> get_texpr_ids(TIds,RIds),
1569 % in case of type errors, or when type checking is not yet complete, we can have multiple entries of the same identifier with different types !
1570 sort(RIds,Ids) % was remove_dups, but remove_dups just calls sort; TODO: implement get_sorted_texpr_ids
1571 ; add_internal_error('Call failed:',find_typed_identifier_uses(TExpr,Ignored,_)),
1572 Ids=[]
1573 ).
1574 find_identifier_uses_l(TExprs,Ignored,Ids) :-
1575 find_typed_identifier_uses_l(TExprs,Ignored,TIds),
1576 get_texpr_ids(TIds,RIds),
1577 sort(RIds,Ids). % see above
1578
1579 check_is_texpr(X,Context) :-
1580 (get_texpr_expr(X,_) -> true ; add_internal_error('Expected TExpr: ', check_is_texpr(X,Context))).
1581
1582 find_typed_identifier_uses(TExpr,Ids) :-
1583 get_global_identifiers(Ignored), % ignore all global sets and global constants; hence find_typed_identifier_uses/2 usually should only be called for top level expressions
1584 find_typed_identifier_uses(TExpr,Ignored,Ids).
1585
1586 find_typed_identifier_uses(TExpr,Ignored,Ids) :- var(TExpr),!,
1587 add_internal_error('Variable typed expression: ', find_typed_identifier_uses(TExpr,Ignored,Ids)),
1588 Ids = [].
1589 find_typed_identifier_uses(TExpr,Ignored,Ids) :-
1590 find_typed_identifier_uses_l([TExpr],Ignored,Ids).
1591
1592 find_typed_identifier_uses2(TExpr,Ignored,Ids,Rest) :-
1593 get_texpr_expr(TExpr,Expr),
1594 safe_syntaxelement_det(Expr,Subs,TNames,_,_), % QSubs=[],
1595 ( uses_an_identifier(Expr,Id,TExpr,Ignored) ->
1596 ( ord_member(Id,Ignored) -> Ids=Rest
1597 ;
1598 get_texpr_type(TExpr,Type),
1599 normalize_type(Type,NType), % replace seq by set;
1600 % warning: when type-check not yet complete we have variables here
1601 create_texpr(identifier(Id),NType,[],TId),
1602 %print(adding(Id,NType,Ignored)),nl,
1603 Ids = [TId|Rest]
1604 )
1605 % ; (Expr = becomes_such(TIds,_)), nl,print(uses_primes(Expr)),nl,fail
1606 ; indirectly_uses_identifiers(Expr,Ignored,IndirectIds) ->
1607 add_typed_ids(IndirectIds,Ids,Rest2),
1608 find_typed_identifier_uses2_l(Subs,Ignored,Rest2,Rest)
1609 ; TNames = [] -> find_typed_identifier_uses2_l(Subs,Ignored,Ids,Rest)
1610 ;
1611 %find_typed_identifier_uses2_l(QSubs,Ignored,Ids,Ids2), % useless here as QSubs=[]
1612 get_texpr_ids(TNames,Names),
1613 list_to_ord_set(Names,SNames), ord_union(SNames,Ignored,Ignored2),
1614 find_typed_identifier_uses2_l(Subs,Ignored2,Ids,Rest)).
1615 find_typed_identifier_uses2_l([],_) --> !, [].
1616 find_typed_identifier_uses2_l([Expr|Rest],Ignored) --> !,
1617 find_typed_identifier_uses2(Expr,Ignored),
1618 find_typed_identifier_uses2_l(Rest,Ignored).
1619 find_typed_identifier_uses2_l(E,Ignored) -->
1620 {add_internal_error('Illegal arguments (not a list):',find_typed_identifier_uses2_l(E,Ignored)),fail}.
1621
1622 %Note: above we do not remap uses of Id$0 to Id in becomes_such;
1623 % this is done in find_read_vars_for_becomes_such in b_read_write_info
1624
1625
1626 uses_an_identifier(Expr,Id) :- uses_an_identifier(Expr,Id,none,[]).
1627
1628 uses_an_identifier(identifier(Id),Id,_,_).
1629 uses_an_identifier(lazy_lookup_pred(Id),Id,_,_).
1630 uses_an_identifier(lazy_lookup_expr(Id),Id,_,_).
1631 uses_an_identifier(value(_),Id,b(_,_,Info),Ignored) :- Ignored \= [],
1632 member(was_identifier(Id),Info),
1633 member('$examine_value_was_identifier_info',Ignored),!.
1634
1635 % uses multiple ids and we also need to inspect subs (operation call arguments)
1636 indirectly_uses_identifiers(operation_call_in_expr(Operation,_),Ignored,IndirectIds) :-
1637 get_texpr_info(Operation,Info),
1638 (memberchk(reads(Vars),Info)
1639 -> (var(Vars) % can happen during initial computation of read_write info for recursive operation calls in expr
1640 -> add_message(bsyntaxtree,'Operation reads info not yet computed (probably recursive call): ',Operation,Info),
1641 fail % Assume this is a direct recursive call which adds no used ids,
1642 % case happens in test 1960 for recursive call to Fact; TODO: more robust solution or disallow recursion
1643 ; true)
1644 ; add_warning(bsyntaxtree,'Operation call contains no read infos:',Operation,Info),fail),
1645 ord_subtract(Vars,Ignored,IndirectIds),
1646 IndirectIds \= [].
1647
1648 % this is to convert untyped ids in operation call reads infos to typed ids
1649 add_typed_ids([]) --> [].
1650 add_typed_ids([Id|T]) --> {var_cst_type(Id,Type)},!,
1651 {create_texpr(identifier(Id),Type,[],TId)}, [TId], add_typed_ids(T).
1652 add_typed_ids([Id|T]) --> {debug_println(19,ignoring_used_id(Id))}, add_typed_ids(T).
1653
1654 :- use_module(bmachine,[bmachine_is_precompiled/0, b_is_variable/2,b_is_constant/2]).
1655 var_cst_type(Name,Type) :- bmachine_is_precompiled,!,
1656 (b_is_variable(Name,Type) ; b_is_constant(Name,Type)),!.
1657 var_cst_type(_,any). % TODO: provide a better solution; maybe only allow untyped find_identifier_uses ??
1658
1659 % -------------
1660
1661 find_typed_identifier_uses_l(TExprs,Ignored,Ids) :-
1662 check_atomic_ids(Ignored),
1663 list_to_ord_set(Ignored,SIgnored),
1664 find_typed_identifier_uses2_l(TExprs,SIgnored,Unsorted,[]),!,
1665 safe_sort(find_typed_identifier_uses,Unsorted,Ids),
1666 (preference(prob_safe_mode,true) -> check_typed_ids(Ids) ; true).
1667 find_typed_identifier_uses_l(TExprs,Ignored,Ids) :-
1668 add_internal_error('Call failed:',find_typed_identifier_uses_l(TExprs,Ignored,Ids)),
1669 fail.
1670
1671 check_typed_ids([]) :- !.
1672 check_typed_ids([b(identifier(ID),T,_)|Tail]) :- !, check_ids3(Tail,ID,T).
1673 check_typed_ids(Other) :- add_internal_error('Unexpected typed id list:',check_typed_ids(Other)).
1674
1675
1676 check_atomic_ids([]) :- !.
1677 check_atomic_ids([Id|_]) :- atomic(Id),!.
1678 check_atomic_ids(Other) :- add_internal_error('Expected atomic id list:',check_atomic_ids(Other)).
1679
1680
1681 check_ids3([],_,_) :- !.
1682 check_ids3([b(identifier(ID),T,_)|Tail],ID1,T1) :- !,
1683 (ID=ID1 -> add_internal_error('Identifier appears multiple times with types:',id(ID,T1,T)) ; true),
1684 check_ids3(Tail,ID,T).
1685 check_ids3(Other,ID1,T1) :- add_internal_error('Unexpected typed id list:',check_ids3(Other,ID1,T1)).
1686
1687
1688 update_used_ids(b(Pred,T,OInfo),UsedIds,b(Pred,T,[used_ids(UsedIds)|NInfo])) :-
1689 delete(OInfo,used_ids(_),NInfo).
1690
1691 % check if some pre-computed used ids are valid wrt find_typed_identifier_uses
1692 check_computed_used_ids(TExpr,CompUsedIds) :-
1693 find_identifier_uses(TExpr,[],RealUsedIds),
1694 (RealUsedIds=CompUsedIds -> print(ok(CompUsedIds)),nl
1695 ; add_error(range,'Unexpected used ids:',CompUsedIds,TExpr),
1696 format('Real: ~w~nComp: ~w~n',[RealUsedIds,CompUsedIds]),trace
1697 ).
1698
1699 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1700 % break predicate into components with disjunct identifiers
1701 % Pred: a predicate
1702 % Components: a list of terms component/2 where the first argument
1703 % is a predicate, the second is the set of used identifiers
1704 predicate_components(Pred,Res) :- predicate_components_in_scope(Pred,[],Res).
1705 predicate_components_in_scope(Pred,LocalVars,Res) :-
1706 predicate_components_with_restriction(Pred,LocalVars,all,Res).
1707
1708 predicate_components_with_restriction(Pred,LocalVars,RestrictionList,Res) :-
1709 conjunction_to_list(Pred,Preds),
1710 l_predicate_identifiers(Preds,LocalVars,PredIds),
1711 (RestrictionList=all -> R=all ; list_to_ord_set(RestrictionList,R)),
1712 try_find_and_remove_equalities(PredIds,PredIds2),
1713 % print(find_components(R)),nl,nl,
1714 %%(member(pred(P,Ids,X),PredIds2), nl,print(pred(Ids,X)),nl,translate:print_bexpr(P),nl,fail ; true),
1715 find_components(PredIds2,R,Components),
1716 !,
1717 %maplist(print_component,Components),
1718 Components=Res.
1719 predicate_components_with_restriction(Pred,_,_,[component(Pred,[])]) :-
1720 add_internal_error('predicate_components failed: ',predicate_components_with_restriction(Pred,_,_,_)).
1721
1722 % print_component(component(Pred,Ids)) :- format('Component over ~w :~n',[Ids]), translate:print_bexpr(Pred),nl.
1723
1724 % get the list of used identifiers for each predicate
1725 l_predicate_identifiers([],_LocalVars,[]).
1726 l_predicate_identifiers([Pred|PRest],LocalVars,[pred(Pred,Ids,_Selected)|IRest]) :-
1727 predicate_identifiers_in_scope(Pred,LocalVars,Ids), % Do not ignore local variables; used instead of enumerate set elements
1728 l_predicate_identifiers(PRest,LocalVars,IRest).
1729
1730
1731 try_find_and_remove_equalities(PredAndIds,PredAndIds2) :-
1732 preferences:get_preference(partition_predicates_inline_equalities,true),
1733 \+ preferences:get_preference(use_solver_on_load,kodkod),
1734 ? find_and_remove_equalities(PredAndIds,RR),
1735 !, PredAndIds2=RR.
1736 try_find_and_remove_equalities(Ps,Ps).
1737
1738 :- use_module(debug,[debug_println/2]).
1739 % find and apply obvious equalities so that they do not interfere with partitioning into components
1740 % example: c = 1 & f: 1..c --> A & g: 1..c --> B
1741 % TO DO: preprocess and do one pass to detect potential equalities
1742 find_and_remove_equalities([],[]).
1743 find_and_remove_equalities(List,[pred(P,PIds,Sel)|FT]) :-
1744 ? select(pred(P,PIds,Sel),List,Rest),
1745 %PIds = [Id],
1746 identifier_equality(P,Id,Value),
1747 %(value_which_can_be_replaced(Value) -> true ; nl,print('Not replaced: '),translate:print_bexpr(Value),nl,fail),
1748 (get_texpr_id(Value,Id2)
1749 -> Id2 \= Id %,print(inline_id(Id,Id2)),nl
1750 % Note: this inlining does *not* help with partitioning; but does help ProB detect common predicates/expressions
1751 ; PIds=[Id],value_which_can_be_replaced(Value)),
1752 debug_println(9,replace_simple_equality(Id,PIds)),
1753 maplist(apply_to_pred(Id,Value),Rest,RT),
1754 !,
1755 ? find_and_remove_equalities(RT,FT).
1756 % TO DO: detect equalityes x = EXPR, where EXPR does not contain x and where x occurs in no other predicate
1757 % we can then annotate x as not to enumerate
1758 find_and_remove_equalities(R,R).
1759
1760 identifier_equality(b(equal(LHS,RHS),_,_),Id,EqTerm) :-
1761 (get_texpr_id(LHS,Id) -> EqTerm = RHS
1762 ; get_texpr_id(RHS,Id) -> EqTerm = LHS).
1763 % TO DO: should we detect other equalities?
1764
1765 value_which_can_be_replaced(b(E,T,_)) :- value_which_can_be_replaced2(E,T).
1766 %(value_which_can_be_replaced2(E,T) -> true ; print(not_val(E)),nl,fail).
1767 value_which_can_be_replaced2(value(_),_).
1768 value_which_can_be_replaced2(integer(_),_).
1769 %value_which_can_be_replaced2(identifier(I),global(G)) :- b_global_constant(G), id_not_used_anywhere(I).
1770 value_which_can_be_replaced2(integer_set(_),_).
1771 value_which_can_be_replaced2(unary_minus(A),_) :- value_which_can_be_replaced(A).
1772 value_which_can_be_replaced2(add(A,B),_) :- value_which_can_be_replaced(A), value_which_can_be_replaced(B).
1773 % we could compute the value
1774 value_which_can_be_replaced2(minus(A,B),_) :- value_which_can_be_replaced(A), value_which_can_be_replaced(B).
1775 value_which_can_be_replaced2(multiplication(A,B),_) :- value_which_can_be_replaced(A), value_which_can_be_replaced(B).
1776 value_which_can_be_replaced2(div(A,B),_) :-
1777 get_integer(B,IB), IB \= 0,
1778 value_which_can_be_replaced(A).
1779 value_which_can_be_replaced2(floored_div(A,B),T) :- value_which_can_be_replaced2(div(A,B),T).
1780 % should we add: with WD check: division, modulo, .... ? see also simple2 in b_ast_cleanup
1781 value_which_can_be_replaced2(max_int,_).
1782 value_which_can_be_replaced2(min_int,_).
1783 value_which_can_be_replaced2(float_set,_).
1784 value_which_can_be_replaced2(real(_),_).
1785 value_which_can_be_replaced2(real_set,_).
1786 value_which_can_be_replaced2(string(_),_).
1787 value_which_can_be_replaced2(string_set,_).
1788 value_which_can_be_replaced2(boolean_true,_).
1789 value_which_can_be_replaced2(boolean_false,_).
1790 value_which_can_be_replaced2(bool_set,_).
1791 value_which_can_be_replaced2(empty_set,_).
1792 value_which_can_be_replaced2(empty_sequence,_).
1793 value_which_can_be_replaced2(couple(A,B),_) :- value_which_can_be_replaced(A), value_which_can_be_replaced(B).
1794 value_which_can_be_replaced2(interval(A,B),_) :- value_which_can_be_replaced(A), value_which_can_be_replaced(B).
1795 value_which_can_be_replaced2(set_extension(L),_) :- maplist(value_which_can_be_replaced,L).
1796 value_which_can_be_replaced2(sequence_extension(L),_) :- maplist(value_which_can_be_replaced,L).
1797 value_which_can_be_replaced2(cartesian_product(A,B),_) :- % typing equations, like t_float = INTEGER*NATURAL1
1798 simple_value_set(A), simple_value_set(B).
1799 value_which_can_be_replaced2(pow_subset(A),_) :- simple_value_set(A).
1800 %value_which_can_be_replaced2(identifier(_),_). % TO DO: check that this is not the LHS identifier which we replace !!
1801 % identifiers can also be replaced: we check above that the only identifier in the predicate is the equality identifier
1802 % TO DO: enable this but then we need to fix replace_id_by_expr2 to updated the used_ids info ! + we can have scoping issues !?; see test 1358
1803
1804 % TO DO: also allow inlining of prj1/prj2 of simple_value_set:
1805 % not_val(comprehension_set([b(identifier(_zzzz_unary),integer,[generated(first)]),b(identifier(_zzzz_binary),integer,[generated(first)]),b(identifier(_lambda_result_),integer,[lambda_result])],b(equal(b(identifier(_lambda_result_),integer,[lambda_result]),b(identifier(_zzzz_unary),integer,[generated(first)])),pred,[prob_annotation(LAMBDA),lambda_result])))
1806 % not_val(comprehension_set([b(identifier(_zzzz_unary),integer,[generated(second)]),b(identifier(_zzzz_binary),integer,[generated(second)]),b(identifier(_lambda_result_),integer,[lambda_result])],b(equal(b(identifier(_lambda_result_),integer,[lambda_result]),b(identifier(_zzzz_binary),integer,[generated(second)])),pred,[prob_annotation(LAMBDA),lambda_result])))
1807
1808 % TO DO: maybe check if it is an infinite type which cannot be evaluated anyway
1809 simple_value_set(b(E,_,_)) :- simple_value_set2(E).
1810 %simple_value_set2(bool_set). % Warning: we could have a finite construct which gets evaluated multiple times
1811 simple_value_set2(string_set).
1812 simple_value_set2(integer_set(_)).
1813 simple_value_set2(float_set).
1814 simple_value_set2(real_set).
1815 simple_value_set2(cartesian_product(A,B)) :- simple_value_set(A), simple_value_set(B).
1816 simple_value_set2(pow_subset(A)) :- simple_value_set(A).
1817 % POW, records struct(_) set ?
1818
1819 % apply a substiution of ID/Expr on a pred(EXPR,VarList,X) term
1820 % Expr must either be a variable or contain no variables at all
1821 apply_to_pred(ID,Expr,pred(E1,PIds1,X),pred(E2,PIds3,X)) :-
1822 ? (select(ID,PIds1,PIds2)
1823 -> replace_id_by_expr(E1,ID,Expr,E2), %,print(applied(ID)),nl,translate:print_bexpr(E2),nl
1824 % TO DO: replace_id_by_expr does not seem to update used_ids info !! check_used_ids_info fails for test 1358 if we allow identifiers inside Expr
1825 (get_texpr_id(Expr,NewID)
1826 -> ord_add_element(PIds2,NewID,PIds3)
1827 ; PIds3 = PIds2)
1828 %, format('Apply ~w -> ~w : ',[ID,NewID]),translate:print_bexpr(E2),nl
1829 ; E1=E2,PIds1=PIds3).
1830
1831
1832 % project a predicate : keep only those Predicates that are directly or
1833 % indirectly relevant for Ids; FullIds are all identifiers used by ProjectedPredicate
1834 project_predicate_on_identifiers(Pred,Ids,ProjectedPredicate,FullIds, RestList) :-
1835 (debug_mode(on)
1836 -> print('project: '),print_bexpr(Pred),nl, print(' on : '), print(Ids),nl
1837 ; true),
1838 conjunction_to_list(Pred,Preds),
1839 l_predicate_identifiers(Preds,[],PredIds), % TO DO: allow LocalVariables to be passed
1840 % print(predids(PredIds)),nl,
1841 try_find_and_remove_equalities(PredIds,PredIds2),
1842 extract_all_predicates(Ids,all,Ids,PredIds2,ProjectedPredicates, RestList,FullIds),
1843 conjunct_predicates(ProjectedPredicates,ProjectedPredicate),
1844 (debug_mode(on)
1845 -> print('*result: '),print_bexpr(ProjectedPredicate),nl,
1846 print(' on : '), print(FullIds),nl
1847 ; true).
1848
1849 %print_preds([]).
1850 %print_preds([pred(P,_IDs,_)|T]) :- translate:print_bexpr(P), nl, print(' '), print_preds(T).
1851
1852 :- use_module(b_global_sets,[b_get_global_constants/1, b_get_enumerated_set_constants/1, b_get_global_sets/1]).
1853 predicate_identifiers(Pred,Ids) :- predicate_identifiers_in_scope(Pred,[],Ids).
1854 predicate_identifiers_in_scope(Pred,LocalVariables,Ids) :-
1855 get_global_identifiers(IS),
1856 list_to_ord_set(LocalVariables,LV),
1857 ord_subtract(IS,LV,Ignore2), % Do not ignore any local variable; it will be used instead of enumerate set element
1858 find_identifier_uses_if_necessary(Pred,Ignore2,Ids1), % Ignore enumerated set names
1859 list_to_ord_set(Ids1,Ids).
1860
1861 get_global_identifiers(IDs) :- get_global_identifiers(IDs,all).
1862 % get global set and constant identifiers which you usually want to exclude for find_identifier_uses
1863 get_global_identifiers(IDs,Option) :-
1864 (Option=ignore_promoted_constants
1865 % do not include those constants that have been automatically promoted as enumerated set elements
1866 -> b_get_enumerated_set_constants(EnumeratedSetCsts)
1867 ; b_get_global_constants(EnumeratedSetCsts)
1868 ),
1869 % b_global_sets:b_get_global_enumerated_sets(GSets), % is there a reason to exclude deferred sets ??; cardinality inference,... are all done before partitioning ?
1870 b_get_global_sets(GSets),
1871 append(GSets,EnumeratedSetCsts,GE),
1872 list_to_ord_set(GE,IDs).
1873
1874 % find_components(ListOf_pred, Restrict, Out:ListOfComponents)
1875 % role of Restrict: all if we do normal partition or List of VariableIDs on which we restrict our attention to (for Existential quantifier construction)
1876 find_components([],_,[]).
1877 find_components([pred(P,PIds,true)|PRest],Restrict,[component(Pred,Ids)|CRest]) :-
1878 % find all predicates which are using identifiers occuring in PIds
1879 % (and additionally those which use common identifiers )
1880 ord_restrict(Restrict,PIds,InterIDs),
1881 %format('Treating predicate with ids ~w; restr. intersect = ~w~n',[PIds,InterIDs]),
1882 ( InterIDs =[] ->
1883 % we simply copy this predicate into a single component; not with the scope of Restricted IDs
1884 % print(skip(PIds,P)),nl, %
1885 Pred=P, Ids=PIds, PRest=Rest
1886 ;
1887 extract_all_predicates(InterIDs,Restrict,PIds,PRest,Preds,Rest,Ids),
1888 %length([P|Preds],Len), format('Detected component with ~w conjuncts over ~w~n',[Len,Ids]),
1889 conjunct_predicates_with_pos_info([P|Preds],Pred)
1890 ),
1891 find_components(Rest,Restrict,CRest).
1892 extract_all_predicates([],_,_,Preds,Found,Rest,[]) :- !, % selecting done at end: keep same order of conjuncts
1893 select_predicates(Preds,Found,Rest).
1894 extract_all_predicates(Ids,Restrict,OldIds,Preds,Found,Rest,ResultIds) :-
1895 % search for all predicates that directly use one of the
1896 % identifiers in "Ids"
1897 select_all_using_preds(Preds,Ids,FoundIds),
1898 ord_subtract(FoundIds,OldIds,NewIds),
1899 ord_restrict(Restrict,NewIds,NewIdsToExtract),
1900 ord_union(OldIds,FoundIds,OldIds2),
1901 % now recursively do this which the new identifiers that we have found
1902 extract_all_predicates(NewIdsToExtract,Restrict,OldIds2,Preds,Found,Rest,RestIds),
1903 ord_union([Ids,NewIds,RestIds],ResultIds).
1904
1905 % mark all predicates which intersect with ComponentIds and compute new ids to be added to the component
1906 select_all_using_preds([],_,[]).
1907 select_all_using_preds([pred(_P,PIds,Selected)|PRest],ComponentIds,NewFoundIds) :-
1908 ( (Selected==true ; ord_disjoint(PIds,ComponentIds)) ->
1909 NewFoundIds1 = []
1910 ; % we select the predicate for the component
1911 ord_subtract(PIds,ComponentIds,NewFoundIds1),
1912 Selected=true
1913 ),
1914 select_all_using_preds(PRest,ComponentIds,NewFoundIds2),
1915 ord_union(NewFoundIds1,NewFoundIds2,NewFoundIds).
1916
1917 % ord_intersection with special case for all term
1918 ord_restrict(all,Ids,Res) :- !, Res=Ids.
1919 ord_restrict(Restrict,Ids,Res) :- ord_intersection(Ids,Restrict,Res).
1920
1921 select_predicates(Predicates,FoundPreds,OtherPreds) :-
1922 split_list(is_selected_predicate,Predicates,FoundPredIds,OtherPreds),
1923 maplist(extract_found_predicate,FoundPredIds,FoundPreds).
1924 is_selected_predicate(pred(_P,_PIds,Selected)) :- ground(Selected).
1925 extract_found_predicate(pred(P,_PIds,_Selected),P).
1926
1927 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1928 % replace (simultaneously) multiple identifiers by expressions
1929 % this could be used to replace the predicate replace_id_by_expr by mapping everything in a
1930 % singleton list. however, that would involve list operations instead of unifications
1931 parse_pred(Codes,TExpr) :- %format('Parsing ~s~n',[Codes]),
1932 bmachine:b_parse_machine_predicate_from_codes_open(no_quantifier,Codes,[],[],TExpr).
1933 parse_expr(Codes,TExpr) :- bmachine:b_parse_machine_expression_from_codes(Codes,[],TExpr,_Type,true,_Error).
1934 test_result(1,b(equal(b(comprehension_set([b(identifier(__FRESH____),integer,_)],
1935 b(greater(b(identifier(__FRESH____2),integer,_),b(identifier(x),integer,_)),pred,_)),set(integer),_),
1936 b(empty_set,set(integer),_)),pred,_)).
1937
1938 :- assert_must_succeed((bsyntaxtree:parse_pred("{x|x:INTEGER & x>y}={}",T1), replace_ids_by_exprs(T1,[],[],T1))).
1939 :- assert_must_succeed((bsyntaxtree:parse_pred("{x|x:INTEGER & x>y}={}",T1), bsyntaxtree:parse_expr("100",T2),
1940 replace_ids_by_exprs(T1,[y],[T2],R),bsyntaxtree:parse_pred("{x|x>100}={}",T3),same_texpr(R,T3) )).
1941 :- assert_must_succeed((bsyntaxtree:parse_pred("{x|x:INTEGER & x>y}={}",T1),
1942 replace_ids_by_exprs(T1,[y],[b(identifier(x),integer,[])],R),
1943 bsyntaxtree:test_result(1,R),bsyntaxtree:parse_pred("{x|x:INTEGER & x>x}={}",T3),\+ same_texpr(R,T3) )).
1944 :- assert_must_succeed((bsyntaxtree:parse_pred("{x,y|x:INTEGER & y:INTEGER & x>v & y>w}={}",T1),
1945 replace_ids_by_exprs(T1,[v,w],[b(identifier(w),integer,[]),b(identifier(v),integer,[])],R),
1946 bsyntaxtree:parse_pred("{x,y|x:INTEGER & y:INTEGER & x>w & y>v}={}",T3), same_texpr(R,T3) )).
1947 :- assert_must_succeed((gensym:reset_gensym, bsyntaxtree:parse_pred("{x,y|x:INTEGER & y:INTEGER & x>v & y>w}={}",T1),
1948 replace_ids_by_exprs(T1,[v,w],[b(identifier(w),integer,[]),b(identifier(x),integer,[])],R),
1949 translate:translate_bexpression(R,TR),
1950 TR = '{`__FRESH____1`,y|`__FRESH____1` > w & y > x} = {}')). %'{__FRESH____1,y|(__FRESH____1 : INTEGER & y : INTEGER) & (__FRESH____1 > w & y > x)} = {}' )).
1951
1952 replace_ids_by_exprs(TExpr,[TId],[Inserted],Replaced) :- !, % better, more robust and efficient version
1953 check_ids([TId],[Id]),
1954 replace_id_by_expr(TExpr,Id,Inserted,Replaced).
1955 replace_ids_by_exprs(TExpr,[],[],Replaced) :- !, Replaced=TExpr. % Nothing to do
1956 replace_ids_by_exprs(TExpr,Ids,Exprs,Replaced) :-
1957 check_ids(Ids,Ids2), % convert to atomic identifiers
1958 find_identifier_uses_l(Exprs,[],ExprsUsedIds),
1959 sort(ExprsUsedIds,SExprsUsedIds),
1960 generate_rename_list(Ids2,Exprs,RenameList),
1961 %print(replace(RenameList,SExprsUsedIds)),nl,
1962 replace_ids_by_exprs2(RenameList,SExprsUsedIds,TExpr,Replaced,_). %, nl,print(done),nl.
1963 % a version of replace_ids_by_exprs2 for maplist:
1964 %replace_ids_by_exprs1(RenameList,SExprsUsedIds,TExpr,Replaced) :-
1965 % replace_ids_by_exprs2(RenameList,SExprsUsedIds,TExpr,Replaced,_). %, print('Rep: '), translate:print_bexpr(Replaced),nl.
1966
1967 generate_rename_list([],[],[]).
1968 generate_rename_list([ID1|T],[Expr1|TE],[rename(ID1,Expr1)|RT]) :- generate_rename_list(T,TE,RT).
1969
1970 check_ids([],[]).
1971 check_ids([H|T],[ID|IT]) :- (atomic(H) -> ID=H ; def_get_texpr_id(H,ID)), check_ids(T,IT).
1972 replace_ids_by_exprs2(RenameList,ExprsUsedIds,TExpr,Replaced,WDC) :-
1973 remove_bt(TExpr,Expr,NewExpr,TNewExpr),
1974 ? ( Expr = identifier(Id), member(rename(Id,Inserted),RenameList) ->
1975 Replaced = Inserted,
1976 get_texpr_info(Inserted,Infos),
1977 (memberchk(contains_wd_condition,Infos)
1978 -> WDC = true ; WDC = false) % WDC = true means we have added a wd-condition where previously there was none
1979 ; contains_no_ids(Expr) -> Replaced=TExpr, WDC=false
1980 ;
1981 syntaxtransformation_det(Expr,Subs1,Names,NSubs,NewExpr),
1982 find_variable_clashes(Names,ExprsUsedIds,RenameNames), % check for variable caputure
1983 (RenameNames = []
1984 -> Subs = Subs1 % no variable capture occured
1985 ; %format('*** VARIABLE CAPTURE : ~w~n~n',[RenameNames]),
1986 rename_bt_l(Subs1,RenameNames,Subs) % replace affected names by fresh ids in sub arguments (will also change list of quantified variables itself)
1987 ),
1988 %l_replace_ids_by_exprs2(QSubs,RenameList,ExprsUsedIds,NQSubs,WDC1), % QSubs are like RHS of let expression, where Names are not in scope
1989 remove_hidden_names(Names,RenameList,UpdatedRenameList),
1990 ( UpdatedRenameList = [] -> % all Ids are now hidden for the inner expressions
1991 NSubs=Subs, WDC=false
1992 ;
1993 l_replace_ids_by_exprs2(Subs,UpdatedRenameList,ExprsUsedIds,NSubs,WDC)
1994 ),
1995 TNewExpr = b(E1,T1,Info1),
1996 rename_update_used_ids_info(RenameList,Info1,Info2),
1997 add_wd_if_needed(WDC,b(E1,T1,Info2),Replaced)
1998 ).
1999
2000 contains_no_ids(integer(_)).
2001 contains_no_ids(string(_)).
2002 contains_no_ids(value(_)).
2003
2004
2005 % check if we have to rename any quantified variable to avoid variable capture of RHS of renamings
2006 % example, suppose we rename x/y+1 and we enter {y|y>x} we have to generate {fresh|fresh>y+1} and *not* {y|y>y+1}
2007 find_variable_clashes([],_,[]).
2008 find_variable_clashes([Name|Names],ExprsUsedIds,[rename(ID,FRESHID)|Renaming] ) :-
2009 def_get_texpr_id(Name,ID),
2010 ord_member(ID,ExprsUsedIds), % the quantified name is also introduced by the renaming
2011 !,
2012 gensym('__FRESH__',FRESHID),
2013 find_variable_clashes(Names,ExprsUsedIds,Renaming).
2014 find_variable_clashes([_|Names],ExprsUsedIds,Renaming) :-
2015 find_variable_clashes(Names,ExprsUsedIds,Renaming).
2016
2017
2018 l_replace_ids_by_exprs2([],_,_,[],false).
2019 l_replace_ids_by_exprs2([H|T],UpdatedRenameList,ExprsUsedIds,[IH|IT],WDC) :-
2020 replace_ids_by_exprs2(UpdatedRenameList,ExprsUsedIds,H,IH,WDC1),
2021 l_replace_ids_by_exprs2(T,UpdatedRenameList,ExprsUsedIds,IT,WDC2),
2022 and_wdc(WDC1,WDC2,WDC).
2023
2024 % remove any identifiers that are now "invisible" because they are masked by quantified names
2025 % e.g., when we enter #x.(P) then a renaming of x will be "hidden" inside P
2026 remove_hidden_names([],RenameList,RenameList).
2027 remove_hidden_names([Name|Names],RenameList,NewRenameList) :-
2028 def_get_texpr_id(Name,ID),
2029 delete(RenameList,rename(ID,_),RenameList1),
2030 !, % only one rename should exist
2031 %print(del(ID,RenameList1)),nl,
2032 remove_hidden_names(Names,RenameList1,NewRenameList).
2033
2034 find_rhs_ids(rename(Id,TExpr),rename_ids(Id,InsUsedIds)) :- find_identifier_uses(TExpr,[],InsUsedIds).
2035
2036 % apply a rename list to the used_ids,... information fields
2037 % this is more tricky than applying a single identifier, as we first have to deleted all ids
2038 % and remember which ones were deleted, and only then insert the corresponding ids
2039 % e.g., we could have a RenameList = [rename(p,q),rename(q,p)] ; see test 1776 M1_Internal_v3.mch
2040 rename_update_used_ids_info(RenameList,IIn,IOut) :-
2041 l_find_rhs_ids(RenameList,RenameList2),
2042 %maplist(apply_rename_list(RenameList2),IIn,IOut).
2043 l_apply_rename_list(IIn,RenameList2,IOut).
2044
2045 l_find_rhs_ids([],[]).
2046 l_find_rhs_ids([R1|T],[NR1|NTR]) :-
2047 find_rhs_ids(R1,NR1),
2048 l_find_rhs_ids(T,NTR).
2049
2050 l_apply_rename_list([],_,[]).
2051 l_apply_rename_list([Info1|T],RenameList2,[NewInfo1|NTI]) :-
2052 apply_rename_list(RenameList2,Info1,NewInfo1),
2053 l_apply_rename_list(T,RenameList2,NTI).
2054
2055 apply_rename_list(RenameList,I,NI) :-
2056 apply_rename_list2(I,RenameList,NI).
2057 apply_rename_list2(used_ids(IDS),RenameList,used_ids(NewIDS)) :- !, apply_rename_list_to_ids(RenameList,IDS,[],NewIDS).
2058 apply_rename_list2(reads(IDS),RenameList,reads(NewIDS)) :- !, apply_rename_list_to_ids(RenameList,IDS,[],NewIDS).
2059 apply_rename_list2(modifies(IDS),RenameList,modifies(NewIDS)) :- !, apply_rename_list_to_ids(RenameList,IDS,[],NewIDS).
2060 apply_rename_list2(Info,_,Info).
2061
2062 % apply a rename list to a sorted list of ids
2063 apply_rename_list_to_ids([],Acc,ToInsert,Res) :- ord_union(Acc,ToInsert,Res).
2064 apply_rename_list_to_ids([rename_ids(Id,NewIds)|T],Acc,ToInsert,Res) :-
2065 (ord_delete_existing_element(Acc,Id,Acc2) % the Id occurs and is deleted
2066 -> ord_union(NewIds,ToInsert,ToInsert2),
2067 apply_rename_list_to_ids(T,Acc2,ToInsert2,Res)
2068 ; apply_rename_list_to_ids(T,Acc,ToInsert,Res)).
2069
2070 ord_delete_existing_element(List,El,ResList) :- % ord_del_element also succeeds if El is not in the list !
2071 ord_intersection([El],List,[El],ResList).
2072 % -----------------------
2073 % remove an Identifier from used_ids Info field if it exists
2074 remove_used_id_from_info(I,ID_to_remove,NI) :-
2075 update_used_ids_info(I,ID_to_remove,[],NI).
2076
2077 remove_used_ids_from_info([],I,I).
2078 remove_used_ids_from_info([ID_to_remove|T],I,NI) :- remove_used_id_from_info(I,ID_to_remove,I2),
2079 remove_used_ids_from_info(T,I2,NI).
2080
2081 % remove a single Identifier from used_ids Info field if it exists and insert sorted list of ids instead
2082 % a simpler version of rename_update_used_ids_info for a single identifier
2083 update_used_ids_info([],_,_,[]).
2084 update_used_ids_info([InfoField|T],ID_to_remove,IDsInserted,[NewInfoField|NT]) :-
2085 (update_id_from_info_field(ID_to_remove,IDsInserted,InfoField,R)
2086 -> NewInfoField=R
2087 ; NewInfoField=InfoField),
2088 update_used_ids_info(T,ID_to_remove,IDsInserted,NT).
2089
2090 update_id_from_info_field(ID_to_remove,IDsInserted,I,NI) :-
2091 update_id_from_info_field2(I,ID_to_remove,IDsInserted,NI).
2092 update_id_from_info_field2(used_ids(IDS),ID,IDsInserted,used_ids(NewIDS)) :- update_id(IDS,ID,IDsInserted,NewIDS).
2093 update_id_from_info_field2(reads(IDS),ID,IDsInserted,reads(NewIDS)) :- update_id(IDS,ID,IDsInserted,NewIDS).
2094 update_id_from_info_field2(modifies(IDS),ID,IDsInserted,modifies(NewIDS)) :- update_id(IDS,ID,IDsInserted,NewIDS).
2095
2096 update_id(IDS,ID_to_remove,IDsInserted,NewIDS) :-
2097 ord_delete_existing_element(IDS,ID_to_remove,IDS2), % the Id occurs and is deleted
2098 ord_union(IDsInserted,IDS2,NewIDS).
2099 %if ord_del_element fails we do not add IDsInserted: we assume the used_ids info is correct and ID_to_remove does not occur !
2100 % We could use this info to avoid traversing subtree !
2101 % print(projecting_away_unknown_id(ID_to_remove,IDS)),nl,
2102
2103 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2104
2105 :- assert_must_succeed((gensym:reset_gensym, bsyntaxtree:exists_ast(A), replace_id_by_expr(A,y,b(identifier(x),integer,[]),RA),translate:translate_bexpression(RA,TR),
2106 TR = 'r = {`__FRESH____1`|`__FRESH____1` : 1 .. x & `__FRESH____1` mod 2 = 1}' )).
2107 :- assert_must_succeed((bsyntaxtree:parse_pred("{x|x:INTEGER & x>y}={}",T1),
2108 replace_id_by_expr(T1,y,b(identifier(x),integer,[]),R),
2109 bsyntaxtree:test_result(1,R),bsyntaxtree:parse_pred("{x|x:INTEGER & x>x}={}",T3),
2110 \+ same_texpr(R,T3) )).
2111 :- assert_must_succeed((bsyntaxtree:parse_pred("{x|x:INTEGER & x>y}={}",T1), bsyntaxtree:parse_expr("100",T2),
2112 replace_id_by_expr(T1,y,T2,R),bsyntaxtree:parse_pred("{x|x>100}={}",T3),same_texpr(R,T3) )).
2113
2114 % replace an identifier Id by an expression Inserted
2115 replace_id_by_expr(TExpr,Id,Inserted,Replaced) :-
2116 replace_id_by_expr_with_count(TExpr,Id,Inserted,Replaced,_).
2117
2118 replace_id_by_expr_with_count(TExpr,Id,Inserted,Replaced,NrReplacements) :- \+ atomic(Id),!,
2119 add_internal_error('Id not atomic: ',replace_id_by_expr(TExpr,Id,Inserted,Replaced)),
2120 Replaced = TExpr, NrReplacements=0.
2121 replace_id_by_expr_with_count(TExpr,Id,Inserted,Replaced,NrReplacements) :-
2122 %find_all_relevant_quantified_vars(Id,TExpr,QVars),
2123 find_identifier_uses(Inserted,[],SInsUsedIds), % SInsUsedIds is sorted
2124 replace_id_by_expr2(Id,Inserted,SInsUsedIds,TExpr,Replaced,_WDC,0,NrReplacements).
2125
2126 replace_id_by_expr2(Id,Inserted,InsUsedIds,TExpr,Replaced,WDC,InR,OutR) :-
2127 remove_bt(TExpr,Expr,NewExpr,TNewExpr),
2128 ( Expr = identifier(Id) -> % TODO: count number of replacements
2129 Replaced = Inserted,
2130 OutR is InR+1,
2131 get_texpr_info(Inserted,Infos),
2132 (memberchk(contains_wd_condition,Infos)
2133 -> WDC = true ; WDC = false) % WDC = true means we have added a wd-condition where previously there was none
2134 ; contains_no_ids(Expr) -> Replaced=TExpr, WDC=false, OutR=InR
2135 ;
2136 syntaxtransformation_det(Expr,Subs,Names,NSubs,NewExpr),
2137 get_texpr_id(TId,Id),
2138 ( memberchk(TId,Names) -> % the Id is now hidden for the inner expressions
2139 NSubs=Subs, WDC=false, OutR = InR
2140 ; (InsUsedIds \= [],
2141 get_texpr_ids(Names,Ns),sort(Ns,SNs),
2142 ord_intersection(SNs,InsUsedIds,Captured),
2143 Captured \= [] %, print(inter(SNs,InsUsedIds,Captured)),nl
2144 )
2145 % The Names introduced clash with variables used in the Inserted expression
2146 -> findall(rename(X,FRESHID),(member(X,Captured),gensym:gensym('__FRESH__',FRESHID)),RenameList),
2147 %print(rename(RenameList)),nl,
2148 rename_bt_l(Subs,RenameList,RenSubs),
2149 l_replace_id_by_expr2(RenSubs,Id,Inserted,InsUsedIds,NSubs,WDC,InR,OutR)
2150 ;
2151 l_replace_id_by_expr2(Subs,Id,Inserted,InsUsedIds,NSubs,WDC,InR,OutR)
2152 ),
2153 TNewExpr = b(E1,T1,Info1),
2154 update_used_ids_info(Info1,Id,InsUsedIds,Info2),
2155 %(E1 = exists(P,_) -> print(exists(P,Id,Info1,Info2)),nl ; true),
2156 add_wd_if_needed(WDC,b(E1,T1,Info2),Replaced)
2157 ).
2158
2159 l_replace_id_by_expr2([],_,_,_,[],false,R,R).
2160 l_replace_id_by_expr2([H|T],Id,Inserted,InsUsedIds,[IH|IT],WDC,InR,OutR) :-
2161 replace_id_by_expr2(Id,Inserted,InsUsedIds,H,IH,WDC1,InR,InR2),
2162 l_replace_id_by_expr2(T,Id,Inserted,InsUsedIds,IT,WDC2,InR2,OutR),
2163 and_wdc(WDC1,WDC2,WDC).
2164
2165 % conjunct wd condition added flag
2166 and_wdc(true,_,R) :- !,R=true.
2167 and_wdc(_,true,R) :- !, R=true.
2168 and_wdc(_,_,false).
2169
2170 % add contains_wd_condition if a change occured during replacement of id by expression
2171 add_wd_if_needed(true,b(E,T,Infos),Replaced) :-
2172 nonmember(contains_wd_condition,Infos),
2173 !,
2174 Replaced = b(E,T,[contains_wd_condition|Infos]).
2175 add_wd_if_needed(_,T,T).
2176
2177
2178
2179 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2180
2181
2182 % syntaxtransformation_fixed/7 is the same as syntaxtransformation/5 with the exception
2183 % that we distinguish between subexpressions that have the newly introduced identifiers (Names)
2184 % in scope (OSubs) and those who don't (OExprs). The only expressions where the latter case is relevant
2185 % are let_expression and let_predicate.
2186 % TODO: This is a quick'n dirty fix for only some cases.
2187 % NO LONGER REQUIRED: let_expression and let_predicate now obey another semantic, not the Z semantics anymore
2188 %syntaxtransformation_fixed(OExpr,OExprs,OSubs,Names,NExprs,NSubs,NExpr) :-
2189 %syntaxtransformation_fixed(Expr,[],Subs,Names,[],NSubs,NExpr) :-
2190 % syntaxtransformation_det(Expr,Subs,Names,NSubs,NExpr).
2191
2192
2193 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2194 % rename identifier
2195
2196 % r = {x|x : 1..y & x mod 2 = 1}
2197 exists_ast(AST) :- AST =
2198 b(equal(b(identifier(r),set(integer),[nodeid(none)]),
2199 b(comprehension_set([b(identifier(x),integer,[nodeid(none)])],
2200 b(conjunct(b(member(b(identifier(x),integer,[nodeid(none)]),
2201 b(interval(b(integer(1),integer,[nodeid(none)]),b(identifier(y),integer,[nodeid(none)])),
2202 set(integer),[nodeid(none)])),pred,[nodeid(none)]),
2203 b(equal(b(modulo(b(identifier(x),integer,[nodeid(none)]),
2204 b(integer(2),integer,[nodeid(none)])),integer,[contains_wd_condition,nodeid(none)]),
2205 b(integer(1),integer,[nodeid(none)])),pred,
2206 [contains_wd_condition,nodeid(none)])),pred,[contains_wd_condition,nodeid(none)])),
2207 set(integer),[contains_wd_condition,nodeid(none)])),
2208 pred,[contains_wd_condition,nodeid(none)]).
2209
2210 :- assert_must_succeed((bsyntaxtree:exists_ast(A), rename_bt(A,[rename(x,xx)],RA), RA==A )).
2211 :- assert_must_succeed((bsyntaxtree:exists_ast(A), rename_bt(A,[rename(r,v)],RA),
2212 translate:translate_bexpression(RA,TR), TR='v = {x|x : 1 .. y & x mod 2 = 1}' )).
2213 :- assert_must_succeed((gensym:reset_gensym, bsyntaxtree:exists_ast(A), rename_bt(A,[rename(y,x)],RA), RA \= A,
2214 translate:translate_bexpression(RA,TR),
2215 TR = 'r = {`__FRESH____1`|`__FRESH____1` : 1 .. x & `__FRESH____1` mod 2 = 1}' )).
2216
2217 % a simplified version of replace_ids_by_exprs, which assumes target of renamings are variables
2218 rename_bt(Expr,[],Res) :- !,Res=Expr.
2219 rename_bt(OExpr,Renamings,NExpr) :-
2220 create_texpr(Old,Type,OInfo,OExpr),
2221 create_texpr(New,Type,NInfo,NExpr),
2222 rename_in_infos(OInfo,Renamings,NInfo),
2223 rename_bt2(Old,Renamings,New).
2224 rename_bt2(identifier(Old),Renamings,identifier(New)) :-
2225 !, rename_id(Old,Renamings,New).
2226 rename_bt2(lazy_lookup_expr(Old),Renamings,lazy_lookup_expr(New)) :-
2227 !, rename_id(Old,Renamings,New).
2228 rename_bt2(lazy_lookup_pred(Old),Renamings,lazy_lookup_pred(New)) :-
2229 !, rename_id(Old,Renamings,New).
2230 rename_bt2(OExpr,Renamings,NExpr) :-
2231 syntaxtransformation(OExpr,Subs,TNames,NSubs,NExpr),
2232 get_texpr_exprs(TNames,Names),
2233 remove_renamings(Names,Renamings,NRenamings),
2234 rename_bt_l(Subs,NRenamings,NSubs).
2235 rename_bt_l([],_,[]).
2236 rename_bt_l([Old|ORest],Renamings,[New|NRest]) :-
2237 rename_bt(Old,Renamings,New),
2238 rename_bt_l(ORest,Renamings,NRest).
2239
2240 remove_renamings([],Renamings,Renamings).
2241 remove_renamings([identifier(Name)|Rest],Old,New) :-
2242 ? ( select(rename(Name,_),Old,Inter1) -> true % Name no longer visible to renaming
2243 ; Old = Inter1),
2244 (member(rename(_OldName,Name),Inter1) ->
2245 gensym('__FRESH__',FRESHID),
2246 %print(variable_capture_in_rename(Name,from(OldName),FRESHID)),nl,
2247 Inter2 = [rename(Name,FRESHID)|Inter1]
2248 ; Inter2 = Inter1),
2249 remove_renamings(Rest,Inter2,New).
2250
2251 rename_in_infos(Old,Renamings,New) :-
2252 ( has_info_to_rename(Old) ->
2253 maplist(rename_in_infos2(Renamings),Old,New)
2254 ;
2255 Old = New).
2256 rename_in_infos2(Renamings,OInfo,NInfo) :-
2257 ( infos_to_rename(OInfo,OIds,SortedNIds,NInfo) ->
2258 rename_ids(OIds,Renamings,NIds),
2259 sort(NIds,SortedNIds)
2260 ;
2261 OInfo = NInfo).
2262
2263 rename_ids([],_,[]).
2264 rename_ids([OId|Orest],Renamings,[NId|Nrest]) :-
2265 rename_id(OId,Renamings,NId),
2266 rename_ids(Orest,Renamings,Nrest).
2267 rename_id(Old,Renamings,New) :-
2268 ( memberchk(rename(Old,New),Renamings) -> true % we could use ord_member if we sort !
2269 ; Old=New).
2270
2271 has_info_to_rename(Infos) :-
2272 ? member(I,Infos),infos_to_rename(I,_,_,_),!.
2273
2274 infos_to_rename(modifies(O),O,N,modifies(N)).
2275 infos_to_rename(reads(O),O,N,reads(N)).
2276 infos_to_rename(non_det_modifies(O),O,N,non_det_modifies(N)).
2277 infos_to_rename(modifies_locals(O),O,N,modifies_locals(N)).
2278 infos_to_rename(reads_locals(O),O,N,reads_locals(N)).
2279 infos_to_rename(used_ids(O),O,N,used_ids(N)).
2280 %infos_to_rename(lambda_result(O),[O],[N],lambda_result(N)). % whould we no longer assume that we have lambda result, as predicate has possibly changed!?
2281
2282
2283 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2284 % remove type information for transformations
2285
2286 remove_bt(b(Expr,Type,Infos),Expr,NExpr,b(NExpr,Type,Infos)).
2287
2288 remove_bt_and_used_ids(b(OldExpr,T,Infos),OldExpr,NewExpr,b(NewExpr,T,NewInfos)) :-
2289 delete(Infos,used_ids(_),NewInfos). % invalidate used_ids info
2290
2291 %remove_bt_l([],[],[],[]).
2292 %remove_bt_l([OT|OTRest],[O|ORest],[N|NRest],[NT|NTRest]) :-
2293 % remove_bt(OT,O,N,NT),
2294 % remove_bt_l(OTRest,ORest,NRest,NTRest).
2295
2296 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2297 % traversations
2298 % Takes a predicate or expression or substitution and extracts:
2299 % the expression itself Expr, its type Type, the syntaxnode information Infos
2300 % + the subexpressions as a list Subs and the local identifiers declared
2301 syntaxtraversion(b(Expr,Type,Infos),Expr,Type,Infos,Subs,Names) :- !,
2302 safe_syntaxelement(Expr,Subs,Names,_,_).
2303 syntaxtraversion(IExpr,Expr,Type,Infos,Subs,Names) :-
2304 add_internal_error('Not properly wrapped', syntaxtraversion(IExpr,Expr,Type,Infos,Subs,Names)),
2305 fail.
2306
2307
2308 map_over_full_bexpr_no_fail(P,BExpr) :-
2309 syntaxtraversion(BExpr,Expr,_,_,Subs,_TNames),
2310 call(P,Expr), % the predicate should not fail
2311 (Subs=[] -> true ; maplist(map_over_full_bexpr_no_fail(P),Subs)).
2312
2313 map_over_bexpr(P,BExpr) :-
2314 syntaxtraversion(BExpr,Expr,_,_,Subs,_TNames),
2315 (call(P,Expr) % should probably fail so that by backtrack we recurse
2316 ;
2317 member(Sub,Subs), map_over_bexpr(P,Sub)
2318 ).
2319 % same as above but gets typed expressions:
2320 map_over_typed_bexpr(P,BExpr) :-
2321 syntaxtraversion(BExpr,_Expr,_,_,Subs,_TNames),
2322 (call(P,BExpr)
2323 ;
2324 ? member(Sub,Subs), map_over_typed_bexpr(P,Sub)
2325 ).
2326 % same as above but returns value:
2327 map_over_typed_bexpr(P,BExpr,Result) :-
2328 syntaxtraversion(BExpr,_Expr,_,_,Subs,_TNames),
2329 (call(P,BExpr,Result)
2330 ;
2331 ? member(Sub,Subs), map_over_typed_bexpr(P,Sub,Result)
2332 ).
2333 % this one gets TNames (locally introduced variables as parameter)
2334 map_over_typed_bexpr_with_names(P,BExpr) :-
2335 syntaxtraversion(BExpr,_Expr,_,_,Subs,TNames),
2336 (call(P,BExpr,TNames)
2337 ;
2338 member(Sub,Subs), map_over_typed_bexpr_with_names(P,Sub)
2339 ).
2340
2341 % same as map_over_expr but provides an accumulator passed top-down to children; needs to be used by failure driven loop
2342
2343 map_over_bexpr_top_down_acc(P,BExpr,TDAcc) :-
2344 syntaxtraversion(BExpr,Expr,_,_,Subs,_TNames),
2345 (call(P,Expr,TDAcc,NewAcc)
2346 -> member(Sub,Subs), map_over_bexpr_top_down_acc(P,Sub,NewAcc)
2347 ; member(Sub,Subs), map_over_bexpr_top_down_acc(P,Sub,TDAcc)
2348 ).
2349 % now a version which gets the typed predicate as argument
2350
2351 map_over_typed_bexpr_top_down_acc(P,BExpr,TDAcc) :-
2352 syntaxtraversion(BExpr,_Expr,_,_,Subs,_TNames),
2353 (call(P,BExpr,TDAcc,NewAcc)
2354 -> member(Sub,Subs), map_over_typed_bexpr_top_down_acc(P,Sub,NewAcc)
2355 ; member(Sub,Subs), map_over_typed_bexpr_top_down_acc(P,Sub,TDAcc)
2356 ).
2357
2358
2359 reduce_over_bexpr(P,BExpr,InitialValue,ResultValue) :-
2360 syntaxtraversion(BExpr,Expr,_,_,Subs,_TNames),
2361 call(P,Expr,InitialValue,I1), % print(reduce(P,Expr,InitialValue,I1)),nl,
2362 scanlist(reduce_over_bexpr(P),Subs,I1,ResultValue).
2363
2364 % apply a predicate over a syntax tree (bottom-up)
2365
2366 transform_bexpr(Pred,b(Expr,Type,Info),NewBExpr) :- !,
2367 syntaxtransformation(Expr,Subs,_Names,NSubs,NewExpr1),
2368 l_transform_bexpr(Subs,Pred,NSubs),
2369 (call(Pred,b(NewExpr1,Type,Info),NewBExpr) -> true ; NewBExpr = b(NewExpr1,Type,Info)).
2370 transform_bexpr(Pred,Expr,NewBExpr) :-
2371 add_internal_error('Expression not properly wrapped:',transform_bexpr(Pred,Expr,NewBExpr)),
2372 fail.
2373
2374 l_transform_bexpr([],_,[]).
2375 l_transform_bexpr([SubH|T],Pred,[TSubH|TT]) :-
2376 transform_bexpr(Pred,SubH,TSubH),
2377 l_transform_bexpr(T,Pred,TT).
2378
2379 % apply a predicate over a syntax tree (bottom-up), and provide scoping info about local ids
2380
2381 transform_bexpr_with_scoping(Pred,b(Expr,Type,Info),NewBExpr) :-
2382 transform_bexpr_with_scoping2(Pred,b(Expr,Type,Info),NewBExpr,[]).
2383 transform_bexpr_with_scoping2(Pred,b(Expr,Type,Info),NewBExpr,LocalIds) :-
2384 syntaxtransformation(Expr,Subs,Names,NSubs,NewExpr1),
2385 get_texpr_ids(Names,QuantifiedNewIds), list_to_ord_set(QuantifiedNewIds,SQuantifiedNewIds),
2386 ord_union(LocalIds,SQuantifiedNewIds,NewLocalIds),
2387 l_transform_bexpr_with_scoping(Subs,Pred,NSubs,NewLocalIds),
2388 (call(Pred,b(NewExpr1,Type,Info),NewBExpr,LocalIds) -> true ; NewBExpr = b(NewExpr1,Type,Info)).
2389
2390 l_transform_bexpr_with_scoping([],_,[],_).
2391 l_transform_bexpr_with_scoping([SubH|T],Pred,[TSubH|TT],LocalIds) :-
2392 transform_bexpr_with_scoping2(Pred,SubH,TSubH,LocalIds),
2393 l_transform_bexpr_with_scoping(T,Pred,TT,LocalIds).
2394
2395
2396 % apply a predicate over a syntax tree (bottom-up) with Accumulator result
2397 % Accumulator is constructed bottom up; Pred receives *all* accumulators of sub expressions
2398
2399 transform_bexpr_with_bup_accs(Pred,b(Expr,Type,Info),NewBExpr,EmptyAcc,Acc) :-
2400 syntaxtransformation(Expr,Subs,_Names,NSubs,NewExpr1),
2401 l_transform_bexpr_with_bup_accs(Subs,Pred,NSubs,EmptyAcc,SubAccs),
2402 (call(Pred,b(NewExpr1,Type,Info),NewBExpr,SubAccs,Acc) -> true
2403 ; NewBExpr = b(NewExpr1,Type,Info), Acc = EmptyAcc).
2404
2405 l_transform_bexpr_with_bup_accs([],_,[],_,[]).
2406 l_transform_bexpr_with_bup_accs([SubH|T],Pred,[TSubH|TT],EmptyAcc,[Acc1|RestAcc]) :-
2407 transform_bexpr_with_bup_accs(Pred,SubH,TSubH,EmptyAcc,Acc1),
2408 l_transform_bexpr_with_bup_accs(T,Pred,TT,EmptyAcc,RestAcc).
2409
2410 % apply a predicate over a syntax tree (bottom-up) with Accumulator result
2411 % a single Accumulator is passed along
2412
2413 transform_bexpr_with_acc(_Pred,E,NewBExpr,InAcc,Acc) :- var(E),!,
2414 NewBExpr=E, Acc=InAcc.
2415 transform_bexpr_with_acc(Pred,b(Expr,Type,Info),NewBExpr,InAcc,Acc) :-
2416 syntaxtransformation(Expr,Subs,_Names,NSubs,NewExpr1),
2417 l_transform_bexpr_with_acc(Subs,Pred,NSubs,InAcc,SubAcc),
2418 (call(Pred,b(NewExpr1,Type,Info),NewBExpr,SubAcc,Acc) -> true
2419 ; NewBExpr = b(NewExpr1,Type,Info), Acc = SubAcc).
2420
2421 l_transform_bexpr_with_acc([],_,[],Acc,Acc).
2422 l_transform_bexpr_with_acc([SubH|T],Pred,[TSubH|TT],InAcc,ResAcc) :-
2423 transform_bexpr_with_acc(Pred,SubH,TSubH,InAcc,Acc1),
2424 l_transform_bexpr_with_acc(T,Pred,TT,Acc1,ResAcc).
2425
2426 % a non-deterministic version of this
2427 non_det_transform_bexpr_with_acc(_Pred,E,NewBExpr,InAcc,Acc) :- var(E),!,
2428 NewBExpr=E, Acc=InAcc.
2429 non_det_transform_bexpr_with_acc(Pred,b(Expr,Type,Info),NewBExpr,InAcc,Acc) :-
2430 syntaxtransformation(Expr,Subs,_Names,NSubs,NewExpr1),
2431 l_nd_transform_bexpr_with_acc(Subs,Pred,NSubs,InAcc,SubAcc),
2432 if(call(Pred,b(NewExpr1,Type,Info),NewBExpr,SubAcc,Acc),
2433 true,
2434 (NewBExpr = b(NewExpr1,Type,Info), Acc = SubAcc)).
2435
2436 l_nd_transform_bexpr_with_acc([],_,[],Acc,Acc).
2437 l_nd_transform_bexpr_with_acc([SubH|T],Pred,[TSubH|TT],InAcc,ResAcc) :-
2438 non_det_transform_bexpr_with_acc(Pred,SubH,TSubH,InAcc,Acc1),
2439 l_nd_transform_bexpr_with_acc(T,Pred,TT,Acc1,ResAcc).
2440
2441
2442 % -------------------------
2443
2444 min_max_integer_value_used(BExpr,Min,Max) :-
2445 min_max_integer_value_used(BExpr,none,none,Min,Max).
2446 min_max_integer_value_used(BExpr,IMin,IMax,Min,Max) :-
2447 reduce_over_bexpr(min_max_aux,BExpr,minmax(IMin,IMax),minmax(Min,Max)).
2448
2449 min_max_aux(sequence_extension(L),minmax(Min,Max),minmax(NMin,NMax)) :- !,
2450 length(L,Len), % we use implicitly numbers from 1..Len
2451 (number(Min),1>Min -> NMin=Min ; NMin=1),
2452 (number(Max),Len<Max -> NMax=Max ; NMax=Len).
2453 min_max_aux(integer(N),minmax(Min,Max),minmax(NMin,NMax)) :- !,
2454 (number(Min),N>Min -> NMin=Min ; NMin=N),
2455 (number(Max),N<Max -> NMax=Max ; NMax=N).
2456 min_max_aux(_,V,V).
2457
2458 % check if a B expression uses something like NAT,NAT1,INT, MAXINT or MININT.
2459 uses_implementable_integers(BExpr) :-
2460 map_over_bexpr(uses_implementable_integers_aux,BExpr).
2461
2462 uses_implementable_integers_aux(maxint).
2463 uses_implementable_integers_aux(minint).
2464 uses_implementable_integers_aux(integer_set(X)) :-
2465 (X='NAT1' ; X='NAT' ; X='INT').
2466
2467 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2468 % some checks
2469 check_if_typed_predicate(b(Pred,X,_)) :- ground(X), X=pred, % at runtime there can be value(X) with variables inside !
2470 syntaxelement(Pred,_,_,_,_,TypePred), (TypePred=pred -> true ; TypePred = pred/only_typecheck).
2471 check_if_typed_expression(b(Expr,Type,_)) :-
2472 syntaxelement(Expr,_,_,_,_,TypeExpr),
2473 (TypeExpr=expr -> true ; TypeExpr = expr/only_typecheck),
2474 Type \== pred, Type \== subst, ground(Type).
2475 check_if_typed_substitution(b(Subst,X,_)) :- ground(X), X=subst,
2476 syntaxelement(Subst,_,_,_,_,subst).
2477
2478 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2479 % transformations
2480
2481 syntaxtransformation(Expr,Subs,Names,NSubs,NExpr) :-
2482 functor(Expr,F,Arity),
2483 functor(NExpr,F,Arity),
2484 safe_syntaxelement(Expr,Subs,Names,Lists,Constant),
2485 all_same_length(Lists,NLists),
2486 syntaxelement(NExpr,NSubs,_,NLists,Constant,_).
2487 % a faster non-backtracking version:
2488 syntaxtransformation_det(Expr,Subs,Names,NSubs,NExpr) :-
2489 functor(Expr,F,Arity),
2490 functor(NExpr,F,Arity),
2491 safe_syntaxelement_det(Expr,Subs,Names,Lists,Constant),
2492 all_same_length(Lists,NLists),
2493 syntaxelement(NExpr,NSubs,_,NLists,Constant,_).
2494
2495
2496 safe_syntaxelement(Expr,Subs,Names,Lists,Constant) :-
2497 ( syntaxelement(Expr,SubsX,NamesX,Lists,ConstantX,_) ->
2498 Subs=SubsX, Names=NamesX, Constant=ConstantX
2499 %(Subs,Names,Constant)=(SubsX,NamesX,ConstantX)
2500 ;
2501 functor(Expr,F,Arity),
2502 add_error_fail(bsyntaxtree,'Uncovered syntax element: ', F/Arity)
2503 ).
2504 % a faster non-backtracking version of safe_syntaxelement, assuming Subs, Names, ... are fresh vars
2505 safe_syntaxelement_det(Expr,Subs,Names,Lists,Constant) :-
2506 (syntaxelement(Expr,Subs,Names,Lists,Constant,_) -> true
2507 ; functor(Expr,F,Arity),
2508 add_error_fail(bsyntaxtree,'Uncovered syntax element: ', F/Arity)).
2509
2510 is_subst_syntaxelement(Subst) :-
2511 syntaxelement(Subst,_,_,_,_,subst).
2512
2513 % check if we have a syntax node without parameters
2514 is_syntax_constant(Expr) :- atom(Expr), syntaxelement(Expr,_,_,_,_,_).
2515
2516 % syntaxelement(Expr,SubExprs,Identifiers,Lists,Constant,Type):
2517 % Expr: the expression itself
2518 % SubExprs: a list of sub-expressions
2519 % Identifiers: a list of identifiers that are newly introduced (e.g. by a quantifier)
2520 % Lists: A list of lists in the expression, to prevent infinite loops when having variable parts
2521 % Constant: A part of the expression that is not a sub-expression (e.g. the number in integer(...))
2522 % Type: Fundamental type of the element (predicate, expression, etc)
2523
2524 % predicates
2525 syntaxelement(truth, [], [], [], [], pred).
2526 syntaxelement(falsity, [], [], [], [], pred).
2527 syntaxelement(unknown_truth_value(Msg),[], [], [], Msg, pred). % artificial, e.g., created by well_def_analyser
2528 syntaxelement(conjunct(A,B), [A,B],[], [], [], pred).
2529 %syntaxelement(conjunct(As), As, [], [], [], pred). % TO DO: support associative version of conjunct
2530 syntaxelement(negation(A), [A], [], [], [], pred).
2531 syntaxelement(disjunct(A,B), [A,B],[], [], [], pred).
2532 syntaxelement(implication(A,B), [A,B],[], [], [], pred).
2533 syntaxelement(equivalence(A,B), [A,B],[], [], [], pred).
2534 syntaxelement(equal(A,B), [A,B],[], [], [], pred).
2535 syntaxelement(not_equal(A,B), [A,B],[], [], [], pred).
2536 syntaxelement(member(A,B), [A,B],[], [], [], pred).
2537 syntaxelement(not_member(A,B), [A,B],[], [], [], pred).
2538 syntaxelement(subset(A,B), [A,B],[], [], [], pred).
2539 syntaxelement(subset_strict(A,B), [A,B],[], [], [], pred).
2540 syntaxelement(not_subset(A,B), [A,B],[], [], [], pred).
2541 syntaxelement(not_subset_strict(A,B),[A,B],[], [], [], pred).
2542 syntaxelement(less_equal(A,B), [A,B],[], [], [], pred).
2543 syntaxelement(less(A,B), [A,B],[], [], [], pred).
2544 syntaxelement(less_equal_real(A,B), [A,B],[], [], [], pred).
2545 syntaxelement(less_real(A,B), [A,B],[], [], [], pred).
2546 syntaxelement(greater_equal(A,B), [A,B],[], [], [], pred).
2547 syntaxelement(greater(A,B), [A,B],[], [], [], pred).
2548 syntaxelement(forall(Ids,D,P), [D,P|Ids],Ids,[Ids], [], pred).
2549 syntaxelement(exists(Ids,P), [P|Ids], Ids,[Ids], [], pred).
2550 syntaxelement(finite(A), [A], [], [], [], pred/only_typecheck).
2551 syntaxelement(partition(S,Es), [S|Es],[],[Es],[],pred).
2552 syntaxelement(kodkod(PId,Ids), Ids,[],[Ids],PId, pred).
2553 syntaxelement(external_pred_call(F,Args),Args,[],[Args],F,pred).
2554
2555 % expressions
2556 syntaxelement(value(V), [], [], [], V, expr).
2557 syntaxelement(operation_call_in_expr(Id,As), As, [], [As], Id, expr). % Do not treat Id as a sub-expression for find_identifier_uses, ...
2558 %syntaxelement(operation_call_in_expr(Id,As), [Id|As], [], [As], [], expr). % was like this, but changed to avoid op(.) ids in find_identifier_uses
2559 syntaxelement(boolean_true, [], [], [], [], expr).
2560 syntaxelement(boolean_false, [], [], [], [], expr).
2561 syntaxelement(max_int, [], [], [], [], expr).
2562 syntaxelement(min_int, [], [], [], [], expr).
2563 syntaxelement(empty_set, [], [], [], [], expr).
2564 syntaxelement(bool_set, [], [], [], [], expr).
2565 syntaxelement(float_set, [], [], [], [], expr).
2566 syntaxelement(real(I), [], [], [], I, expr).
2567 syntaxelement(real_set, [], [], [], [], expr).
2568 syntaxelement(string_set, [], [], [], [], expr).
2569 syntaxelement(convert_bool(A), [A], [], [], [], expr).
2570 syntaxelement(convert_real(A), [A], [], [], [], expr).
2571 syntaxelement(convert_int_floor(A), [A], [], [], [], expr).
2572 syntaxelement(convert_int_ceiling(A), [A], [], [], [], expr).
2573 syntaxelement(add(A,B), [A,B],[], [], [], expr).
2574 syntaxelement(add_real(A,B), [A,B],[], [], [], expr).
2575 syntaxelement(minus(A,B), [A,B],[], [], [], expr).
2576 syntaxelement(minus_real(A,B), [A,B],[], [], [], expr).
2577 syntaxelement(minus_or_set_subtract(A,B),[A,B],[], [], [], expr/only_typecheck).
2578 syntaxelement(unary_minus(A), [A], [], [], [], expr).
2579 syntaxelement(unary_minus_real(A), [A], [], [], [], expr).
2580 syntaxelement(multiplication(A,B), [A,B],[], [], [], expr).
2581 syntaxelement(multiplication_real(A,B),[A,B],[], [], [], expr).
2582 syntaxelement(mult_or_cart(A,B), [A,B],[], [], [], expr/only_typecheck).
2583 syntaxelement(cartesian_product(A,B), [A,B],[], [], [], expr).
2584 syntaxelement(div(A,B), [A,B],[], [], [], expr).
2585 syntaxelement(div_real(A,B), [A,B],[], [], [], expr).
2586 syntaxelement(floored_div(A,B), [A,B],[], [], [], expr).
2587 syntaxelement(modulo(A,B), [A,B],[], [], [], expr).
2588 syntaxelement(power_of(A,B), [A,B],[], [], [], expr).
2589 syntaxelement(power_of_real(A,B), [A,B],[], [], [], expr).
2590 syntaxelement(successor, [], [], [], [], expr).
2591 syntaxelement(predecessor, [], [], [], [], expr).
2592 syntaxelement(max(A), [A], [], [], [], expr).
2593 syntaxelement(max_real(A), [A], [], [], [], expr).
2594 syntaxelement(min(A), [A], [], [], [], expr).
2595 syntaxelement(min_real(A), [A], [], [], [], expr).
2596 syntaxelement(card(A), [A], [], [], [], expr).
2597 syntaxelement(couple(A,B), [A,B],[], [], [], expr).
2598 syntaxelement(pow_subset(A), [A], [], [], [], expr).
2599 syntaxelement(pow1_subset(A), [A], [], [], [], expr).
2600 syntaxelement(fin_subset(A), [A], [], [], [], expr).
2601 syntaxelement(fin1_subset(A), [A], [], [], [], expr).
2602 syntaxelement(interval(A,B), [A,B],[], [], [], expr).
2603 syntaxelement(union(A,B), [A,B],[], [], [], expr).
2604 syntaxelement(intersection(A,B), [A,B],[], [], [], expr).
2605 syntaxelement(set_subtraction(A,B), [A,B],[], [], [], expr).
2606 syntaxelement(general_union(A), [A], [], [], [], expr).
2607 syntaxelement(general_intersection(A), [A] , [], [], [], expr).
2608 syntaxelement(relations(A,B), [A,B],[], [], [], expr).
2609 syntaxelement(identity(A), [A], [], [], [], expr).
2610 syntaxelement(event_b_identity, [], [], [], [], expr). % for Rodin 1.0, TO DO: Daniel please check
2611 syntaxelement(reverse(A), [A], [], [], [], expr).
2612 syntaxelement(first_projection(A,B), [A,B],[], [], [], expr/only_typecheck).
2613 syntaxelement(first_of_pair(A), [A], [], [], [], expr).
2614 syntaxelement(event_b_first_projection(A),[A], [], [], [], expr/only_typecheck).
2615 syntaxelement(event_b_first_projection_v2,[], [], [], [], expr/only_typecheck). % for Rodin 1.0, TO DO: Daniel please check
2616 syntaxelement(second_projection(A,B), [A,B],[], [], [], expr/only_typecheck).
2617 syntaxelement(event_b_second_projection_v2,[], [], [], [], expr/only_typecheck). % for Rodin 1.0, TO DO: Daniel please check
2618 syntaxelement(second_of_pair(A), [A], [], [], [], expr).
2619 syntaxelement(event_b_second_projection(A),[A], [], [], [], expr/only_typecheck).
2620 syntaxelement(composition(A,B), [A,B],[], [], [], expr).
2621 syntaxelement(ring(A,B), [A,B],[], [], [], expr/only_typecheck).
2622 syntaxelement(direct_product(A,B), [A,B],[], [], [], expr).
2623 syntaxelement(parallel_product(A,B), [A,B],[], [], [], expr).
2624 syntaxelement(trans_function(A), [A], [], [], [], expr).
2625 syntaxelement(trans_relation(A), [A], [], [], [], expr).
2626 syntaxelement(iteration(A,B), [A,B],[], [], [], expr).
2627 syntaxelement(reflexive_closure(A), [A], [], [], [], expr).
2628 syntaxelement(closure(A), [A], [], [], [], expr).
2629 syntaxelement(domain(A), [A], [], [], [], expr).
2630 syntaxelement(range(A), [A], [], [], [], expr).
2631 syntaxelement(image(A,B), [A,B],[], [], [], expr).
2632 syntaxelement(domain_restriction(A,B), [A,B],[], [], [], expr).
2633 syntaxelement(domain_subtraction(A,B), [A,B],[], [], [], expr).
2634 syntaxelement(range_restriction(A,B), [A,B],[], [], [], expr).
2635 syntaxelement(range_subtraction(A,B), [A,B],[], [], [], expr).
2636 syntaxelement(overwrite(A,B), [A,B],[], [], [], expr).
2637 syntaxelement(partial_function(A,B), [A,B],[], [], [], expr).
2638 syntaxelement(total_function(A,B), [A,B],[], [], [], expr).
2639 syntaxelement(partial_injection(A,B), [A,B],[], [], [], expr).
2640 syntaxelement(total_injection(A,B), [A,B],[], [], [], expr).
2641 syntaxelement(partial_surjection(A,B), [A,B],[], [], [], expr).
2642 syntaxelement(total_surjection(A,B), [A,B],[], [], [], expr).
2643 syntaxelement(total_bijection(A,B), [A,B],[], [], [], expr).
2644 syntaxelement(partial_bijection(A,B), [A,B],[], [], [], expr).
2645 syntaxelement(total_relation(A,B), [A,B],[], [], [], expr).
2646 syntaxelement(surjection_relation(A,B),[A,B],[], [], [], expr).
2647 syntaxelement(total_surjection_relation(A,B),[A,B],[], [], [], expr).
2648 syntaxelement(seq(A), [A], [], [], [], expr).
2649 syntaxelement(seq1(A), [A], [], [], [], expr).
2650 syntaxelement(iseq(A), [A], [], [], [], expr).
2651 syntaxelement(iseq1(A), [A], [], [], [], expr).
2652 syntaxelement(perm(A), [A], [], [], [], expr).
2653 syntaxelement(empty_sequence, [], [], [], [], expr).
2654 syntaxelement(size(A), [A], [], [], [], expr).
2655 syntaxelement(first(A), [A], [], [], [], expr).
2656 syntaxelement(last(A), [A], [], [], [], expr).
2657 syntaxelement(front(A), [A], [], [], [], expr).
2658 syntaxelement(tail(A), [A], [], [], [], expr).
2659 syntaxelement(rev(A), [A], [], [], [], expr).
2660 syntaxelement(concat(A,B), [A,B],[], [], [], expr).
2661 syntaxelement(insert_front(A,B), [A,B],[], [], [], expr).
2662 syntaxelement(insert_tail(A,B), [A,B],[], [], [], expr).
2663 syntaxelement(restrict_front(A,B), [A,B],[], [], [], expr).
2664 syntaxelement(restrict_tail(A,B), [A,B],[], [], [], expr).
2665 syntaxelement(general_concat(A), [A], [], [], [], expr).
2666 syntaxelement(function(A,B), [A,B],[], [], [], expr).
2667 syntaxelement(external_function_call(F,Args),Args,[],[Args],F,expr).
2668 syntaxelement(identifier(I), [], [], [], I, expr).
2669 syntaxelement(lazy_lookup_expr(I), [], [], [], I, expr).
2670 syntaxelement(lazy_lookup_pred(I), [], [], [], I, pred).
2671 syntaxelement(integer(I), [], [], [], I, expr).
2672 syntaxelement(integer_set(T), [], [], [], T, expr).
2673 syntaxelement(string(S), [], [], [], S, expr).
2674 syntaxelement(set_extension(L), L, [], [L], [], expr).
2675 syntaxelement(sequence_extension(L), L, [], [L], [], expr).
2676 syntaxelement(comprehension_set(Ids,P),[P|Ids], Ids,[Ids], [], expr).
2677 syntaxelement(event_b_comprehension_set(Ids,E,P),[E,P|Ids], Ids,[Ids], [], expr/only_typecheck).
2678 syntaxelement(lambda(Ids,P,E), [P,E|Ids],Ids,[Ids], [], expr).
2679 syntaxelement(general_sum(Ids,P,E), [P,E|Ids],Ids,[Ids], [], expr).
2680 syntaxelement(general_product(Ids,P,E), [P,E|Ids],Ids,[Ids], [], expr).
2681 syntaxelement(quantified_union(Ids,P,E), [P,E|Ids],Ids,[Ids], [], expr).
2682 syntaxelement(quantified_intersection(Ids,P,E), [P,E|Ids],Ids,[Ids], [], expr).
2683 syntaxelement(struct(Rec), [Rec], [], [], [], expr).
2684 syntaxelement(rec(Fields), FContent, [], [FContent], FNames, expr) :- syntaxfields(Fields,FContent, FNames).
2685 syntaxelement(record_field(R,I), [R], [], [], I, expr).
2686 syntaxelement(assertion_expression(Cond,ErrMsg,Expr), [Cond,Expr], [], [], ErrMsg, expr).
2687 syntaxelement(typeset, [], [], [], [], expr/only_typecheck).
2688
2689 syntaxelement(tree(A), [A], [], [], [], expr).
2690 syntaxelement(btree(A), [A], [], [], [], expr).
2691 syntaxelement(const(A,B), [A,B],[], [], [], expr).
2692 syntaxelement(top(A), [A], [], [], [], expr).
2693 syntaxelement(sons(A), [A], [], [], [], expr).
2694 syntaxelement(prefix(A), [A], [], [], [], expr).
2695 syntaxelement(postfix(A), [A], [], [], [], expr).
2696 syntaxelement(sizet(A), [A], [], [], [], expr).
2697 syntaxelement(mirror(A), [A], [], [], [], expr).
2698 syntaxelement(rank(A,B), [A,B],[], [], [], expr).
2699 syntaxelement(father(A,B), [A,B],[], [], [], expr).
2700 syntaxelement(son(A,B,C), [A,B,C],[], [], [], expr).
2701 syntaxelement(subtree(A,B), [A,B],[], [], [], expr).
2702 syntaxelement(arity(A,B), [A,B],[], [], [], expr).
2703 syntaxelement(bin(A), [A],[], [], [], expr).
2704 syntaxelement(bin(A,B,C), [A,B,C],[], [], [], expr).
2705 syntaxelement(infix(A), [A], [], [], [], expr).
2706 syntaxelement(left(A), [A], [], [], [], expr).
2707 syntaxelement(right(A), [A], [], [], [], expr).
2708
2709 % substitutions
2710 syntaxelement(skip, [], [], [], [], subst).
2711 syntaxelement(precondition(A,B), [A,B],[], [], [], subst).
2712 syntaxelement(assertion(A,B), [A,B],[], [], [], subst).
2713 syntaxelement(if_elsif(A,B), [A,B],[], [], [], subst/elsif).
2714 syntaxelement(while(A,B,C,D), [A,B,C,D],[], [], [], subst).
2715 % used only internally in the interpreter, contains last value of variant:
2716 syntaxelement(while1(A,B,C,D,E), [A,B,C,D],[], [], E, subst).
2717 syntaxelement(select_when(A,B), [A,B],[], [], [], subst/when).
2718 syntaxelement(block(S),[S],[],[],[], subst/only_typecheck).
2719 syntaxelement(assign(Lhs,Rhs),Exprs,[],[Lhs,Rhs], [], subst) :- append(Lhs,Rhs,Exprs).
2720 syntaxelement(assign_single_id(Id,Rhs),[Id,Rhs],[],[], [], subst).
2721 syntaxelement(any(Ids,P,S),[P,S|Ids],Ids,[Ids], [], subst).
2722 syntaxelement(var(Ids,S), [S|Ids], Ids,[Ids], [], subst).
2723 syntaxelement(if(Ifs), Ifs, [], [Ifs], [], subst).
2724 syntaxelement(parallel(Ss), Ss, [], [Ss], [], subst).
2725 syntaxelement(sequence(Ss), Ss, [], [Ss], [], subst).
2726 syntaxelement(becomes_element_of(Ids,E), [E|Ids], [], [Ids], [], subst).
2727 syntaxelement(becomes_such(Ids,P), [P|Ids], [], [Ids], [], subst). % Ids are new value, Ids$0 is old value
2728 syntaxelement(evb2_becomes_such(Ids,P), [P|Ids], [], [Ids], [], subst/only_typecheck).
2729 syntaxelement(let(Ids,P,S), [P,S|Ids], Ids, [Ids], [], subst).
2730 syntaxelement(operation_call(Id,Rs,As), [Id|Exprs], [], [Rs,As], [], subst) :- append(Rs,As,Exprs).
2731 syntaxelement(case(E,Eithers,Else), [E,Else|Eithers], [], [Eithers], [], subst).
2732 syntaxelement(case_or(Es,S), [S|Es], [], [Es], [], subst/caseor).
2733 syntaxelement(choice(Ss), Ss, [], [Ss], [], subst).
2734 syntaxelement(select(Whens), Whens, [], [Whens], [], subst).
2735 syntaxelement(select(Whens,Else), [Else|Whens], [], [Whens], [], subst).
2736 syntaxelement(operation(I,Rs,As,B), [I,B|Ids], Ids, [Rs,As], [], subst) :- append(Rs,As,Ids).
2737 syntaxelement(external_subst_call(F,Args),Args,[],[Args],F,subst).
2738
2739 % elements of a VALUES clause
2740 syntaxelement(values_entry(I,E),[I,E],[],[],[],values_entry).
2741
2742 % syntax for Event-B events
2743 syntaxelement(rlevent(I,Sec,St,Ps,G,Ts,As,VWs,PWs,Ums,Rs), Subs, [], [Ps,Ts,As,VWs,PWs,Ums,Rs], [I,Sec], subst) :-
2744 append([[St],Ps,[G],Ts,As,VWs,PWs,Ums,Rs],Subs).
2745 syntaxelement(witness(I,P), [I,P], [], [], [], witness).
2746
2747 % extended syntax for Z
2748 syntaxelement(let_predicate(Ids,As,Pred), Exprs, Ids, [Ids,As], [], pred) :- append([Ids,As,[Pred]],Exprs).
2749 syntaxelement(let_expression(Ids,As,Expr), Exprs, Ids, [Ids,As], [], expr) :- append([Ids,As,[Expr]],Exprs).
2750 syntaxelement(let_expression_global(Ids,As,Expr), Exprs, Ids, [Ids,As], [], expr) :- % version used by b_compiler
2751 append([Ids,As,[Expr]],Exprs).
2752 syntaxelement(lazy_let_expr(TID,A,Expr), [TID, A, Expr], [TID], [[TID],[A]], [], expr).
2753 syntaxelement(lazy_let_pred(TID,A,Expr), [TID, A, Expr], [TID], [[TID],[A]], [], pred).
2754 syntaxelement(lazy_let_subst(TID,A,Expr), [TID, A, Expr], [TID], [[TID],[A]], [], subst).
2755 syntaxelement(if_then_else(If,Then,Else),[If,Then,Else], [], [], [], expr).
2756 syntaxelement(compaction(A), [A], [], [], [], expr).
2757 syntaxelement(mu(A), [A], [], [], [], expr).
2758 syntaxelement(bag_items(A), [A], [], [], [], expr).
2759
2760 syntaxelement(freetype_set(Id), [], [], [], Id, expr).
2761 syntaxelement(freetype_case(Type,Case,Expr), [Expr], [], [], [Type,Case], pred).
2762 syntaxelement(freetype_constructor(Type,Case,Expr), [Expr], [], [], [Type,Case], expr).
2763 syntaxelement(freetype_destructor(Type,Case,Expr), [Expr], [], [], [Type,Case], expr).
2764
2765 syntaxelement(ordinary, [], [], [], [], status).
2766 syntaxelement(anticipated(Variant), [Variant], [], [], [], status).
2767 syntaxelement(convergent(Variant), [Variant], [], [], [], status).
2768
2769 % Just one ID expected
2770 syntaxelement(recursive_let(Id,C),[Id,C],[Id],[],[], expr). % Note: Id is not really introduced !
2771
2772
2773 % fields of records
2774 %syntaxfields(Fields,C,_) :- var(Fields),var(C),var(N),!, add_internal_error('Illegal call: ',syntaxfields(Fields,C,N)),fail.
2775 syntaxfields([],[],[]).
2776 syntaxfields([field(N,C)|Rest],[C|CRest],[N|NRest]) :- syntaxfields(Rest,CRest,NRest).
2777
2778 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2779 % helper for declaration of quantified identifiers
2780
2781 % has_declared_identifier/2 returns a list of identifiers which are declared in
2782 % this AST node. The main difference to the Names variable when doing a
2783 % syntaxtraversion/6 or similiar is that the identifiers are described by
2784 % predicates.
2785 has_declared_identifier(TExpr,Ids) :-
2786 get_texpr_expr(TExpr,Expr),
2787 ( default_declaration(Expr,_,Ids,_)
2788 ; non_default_declaration(Expr,Ids)).
2789
2790 add_declaration_for_identifier(b(Expr,Type,Infos),Decl,b(NExpr,Type,NewInfos)) :-
2791 %delete(Infos,used_ids(_),NewInfos), % we cannot
2792 ( default_declaration(Expr,Predicate,Ids,Constant) ->
2793 same_functor(Expr,NExpr),
2794 conjunct_predicates([Decl,Predicate],NPredicate),
2795 default_declaration(NExpr,NPredicate,Ids,Constant)
2796 ; non_default_declaration(Expr,Ids) ->
2797 add_non_default_declaration(Expr,Decl,NExpr)
2798 ),
2799 add_used_ids(Infos,Ids,Decl,NewInfos).
2800
2801 % add used ids of a predicate within quantification of Ids to current used_ids info; if it is there
2802 add_used_ids(Infos,Ids,Pred,NewInfos) :- update_used_ids(Infos,OldUsed,NewInfos,NewUsed),
2803 !, % a field needs updating
2804 find_identifier_uses(Pred,[],NewIds), get_texpr_ids(Ids,UnsortedIds),sort(UnsortedIds,SIds),
2805 ord_subtract(NewIds,SIds,NewIds2),
2806 ord_union(NewIds2,OldUsed,NewUsed).
2807 add_used_ids(I,_,_,I).
2808
2809 % just update used_ids field (e.g., when just computed to store it for later)
2810 update_used_ids(Infos,OldUsed,NewInfos,NewUsed) :- select(OldInfo,Infos,I1),
2811 used_ids_like_info(OldInfo,F,OldUsed),!,
2812 used_ids_like_info(NewInfo,F,NewUsed),NewInfos = [NewInfo|I1].
2813
2814 % info fields which contain used_ids information
2815 used_ids_like_info(used_ids(UsedIds),used_ids,UsedIds).
2816 used_ids_like_info(reads(UsedIds),reads,UsedIds).
2817
2818 :- use_module(probsrc(btypechecker), [prime_identifiers/2]).
2819
2820 % default_declaration(Expr,Predicate,Ids,Constant)
2821 default_declaration(forall(Ids,D,P),D,Ids,P).
2822 default_declaration(exists(Ids,P),P,Ids,[]).
2823 default_declaration(comprehension_set(Ids,P),P,Ids,[]).
2824 default_declaration(event_b_comprehension_set(Ids,E,P),P,Ids,E). % translated !?
2825 default_declaration(lambda(Ids,P,E),P,Ids,E).
2826 default_declaration(general_sum(Ids,P,E),P,Ids,E).
2827 default_declaration(general_product(Ids,P,E),P,Ids,E).
2828 default_declaration(quantified_union(Ids,P,E),P,Ids,E).
2829 default_declaration(quantified_intersection(Ids,P,E),P,Ids,E).
2830 default_declaration(any(Ids,P,S),P,Ids,S).
2831 default_declaration(becomes_such(Ids,P),P,Ids,[]).
2832 default_declaration(evb2_becomes_such(Ids,P),P,Primed,[]) :-
2833 nl,print(evb2(Ids,Primed)),nl,nl, % no longer used, as it is translated to becomes_such
2834 prime_identifiers(Ids,Primed).
2835 default_declaration(rlevent(I,Sec,St,Ps,G,Ts,As,VWs,PWs,Ums,Rs),G,Ps,
2836 [I,Sec,St,Ps,Ts,As,VWs,PWs,Ums,Rs]).
2837 default_declaration(let_predicate(Ids,Ps,Body),Ps,Ids,Body) :- print(let(Ids)),nl. % TODO: check format of Ps
2838 default_declaration(let_expression(Ids,Ps,Body),Ps,Ids,Body) :- print(let(Ids)),nl. % TODO: check format of Ps
2839 default_declaration(let_expression_global(Ids,Ps,Body),Ps,Ids,Body) :- print(let(Ids)),nl. % TODO: check format of Ps
2840 % TODO: lazy let ?
2841
2842 non_default_declaration(operation(_I,Rs,As,_TBody),Ids) :-
2843 append(Rs,As,Ids).
2844
2845 add_non_default_declaration(operation(I,Rs,As,TBody),Decl,operation(I,Rs,As,NTBody)) :-
2846 ( remove_bt(TBody,precondition(P,S),precondition(NP,S),NTBody) ->
2847 conjunct_predicates([Decl,P],NP)
2848 ;
2849 create_texpr(precondition(Decl,TBody),subst,[],NTBody)).
2850
2851 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2852 % pattern definitions (not yet finished)
2853
2854 bsyntax_pattern(Expr,TExpr) :-
2855 var(Expr),!,Expr=TExpr.
2856 bsyntax_pattern(-Expr,TExpr) :-
2857 !,remove_all_infos(Expr,TExpr).
2858 bsyntax_pattern(Expr,TExpr) :-
2859 functor(Expr,b,3),!,Expr=TExpr.
2860 bsyntax_pattern(Expr:Type/Info,TExpr) :-
2861 !,bsyntax_pattern2(Expr,Type,Info,TExpr).
2862 bsyntax_pattern(Expr:Type,TExpr) :-
2863 !,bsyntax_pattern2(Expr,Type,_Info,TExpr).
2864 bsyntax_pattern(Expr/Info,TExpr) :-
2865 !,bsyntax_pattern2(Expr,_Type,Info,TExpr).
2866 bsyntax_pattern(Expr,TExpr) :-
2867 !,bsyntax_pattern2(Expr,_Type,_Info,TExpr).
2868
2869 bsyntax_pattern2(Pattern,Type,Info,TExpr) :-
2870 functor(Pattern,Functor,Arity),
2871 functor(R,Functor,Arity),
2872 create_texpr(R,Type,Info,TExpr),
2873 syntaxelement(Pattern,PSubs,_,PLists,Const,EType),
2874 syntaxelement(R,RSubs,_,RLists,Const,EType),
2875 ( EType==pred -> Type=pred
2876 ; EType==subst -> Type=subst
2877 ; true),
2878 all_same_length(PLists,RLists),
2879 maplist(bsyntax_pattern,PSubs,RSubs).
2880
2881 all_same_length([],[]).
2882 all_same_length([A|Arest],[B|Brest]) :-
2883 ( var(A),var(B) ->
2884 add_error_fail(bsyntaxtree,'At least one list should contain nonvar elements for all_same_length',[A,B])
2885 ;
2886 same_length(A,B)),
2887 all_same_length(Arest,Brest).
2888
2889 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2890 % strip an AST into a more compact form (without b/3 terms)
2891
2892 strip_and_norm_ast(TExpr,SNExpr) :-
2893 get_texpr_expr(TExpr,Expr),
2894 strip_and_norm_ast_aux(Expr,SNExpr).
2895
2896 :- use_module(tools,[safe_univ_no_cutoff/2]).
2897 strip_and_norm_ast_aux(Expr,Res) :-
2898 comm_assoc_subs(Expr,Op,Subs,[]), !, % associative & commutative operator detected
2899 maplist(strip_and_norm_ast_aux,Subs,NSubs), % Subs are already unwrapped
2900 sort(NSubs,Sorted), % in case there are associative operators that are not commutative: insert is_commutative check
2901 safe_univ_no_cutoff(Res,[Op|Sorted]).
2902 strip_and_norm_ast_aux(Expr,Res) :-
2903 assoc_subs(Expr,Op,Subs,[]), !, % associative operator detected
2904 maplist(strip_and_norm_ast_aux,Subs,NSubs), % Subs are already unwrapped
2905 safe_univ_no_cutoff(Res,[Op|NSubs]).
2906 strip_and_norm_ast_aux(Expr,SNExpr) :-
2907 syntaxtransformation(Expr,Subs,_,NSubs,SExpr),
2908 strip_and_norm_ast_l(Subs,NSubs),
2909 norm_strip(SExpr,SNExpr).
2910
2911 strip_and_norm_ast_l([],[]).
2912 strip_and_norm_ast_l([TExpr|Trest],[NExpr|Nrest]) :-
2913 strip_and_norm_ast(TExpr,NExpr),
2914 strip_and_norm_ast_l(Trest,Nrest).
2915
2916 norm_strip(greater_equal(A,B),less_equal(B,A)) :- !.
2917 norm_strip(greater(A,B),less(B,A)) :- !.
2918 norm_strip(set_extension(NL),set_extension(SNL)) :- !,
2919 sort(NL,SNL).
2920 norm_strip(Old,New) :-
2921 functor(Old,Functor,2),
2922 is_commutative(Functor),!,
2923 arg(1,Old,OA),
2924 arg(2,Old,OB),
2925 ( OA @> OB -> New =.. [Functor,OB,OA]
2926 ; New=Old).
2927 norm_strip(Old,Old).
2928 % TO DO: flatten associative operators into lists !
2929
2930 comm_assoc_subs(conjunct(TA,TB),conjunct) --> !,
2931 {get_texpr_expr(TA,A), get_texpr_expr(TB,B)},
2932 comm_assoc_subs(A,conjunct), comm_assoc_subs(B,conjunct).
2933 comm_assoc_subs(disjunct(TA,TB),disjunct) --> !,
2934 {get_texpr_expr(TA,A), get_texpr_expr(TB,B)},
2935 comm_assoc_subs(A,disjunct), comm_assoc_subs(B,disjunct).
2936 comm_assoc_subs(add(TA,TB),add) --> !,
2937 {get_texpr_expr(TA,A), get_texpr_expr(TB,B)},
2938 comm_assoc_subs(A,add), comm_assoc_subs(B,add).
2939 comm_assoc_subs(multiplication(TA,TB),multiplication) --> !,
2940 {get_texpr_expr(TA,A), get_texpr_expr(TB,B)},
2941 comm_assoc_subs(A,multiplication), comm_assoc_subs(B,multiplication).
2942 comm_assoc_subs(union(TA,TB),union) --> !,
2943 {get_texpr_expr(TA,A), get_texpr_expr(TB,B)},
2944 comm_assoc_subs(A,union), comm_assoc_subs(B,union).
2945 comm_assoc_subs(intersection(TA,TB),intersection) --> !,
2946 {get_texpr_expr(TA,A), get_texpr_expr(TB,B)},
2947 comm_assoc_subs(A,intersection), comm_assoc_subs(B,intersection).
2948 comm_assoc_subs(Expr,Op) --> {nonvar(Op)},[Expr]. % base case for other operators
2949
2950 % detect just associative operators
2951 assoc_subs(concat(TA,TB),concat) --> !,
2952 {get_texpr_expr(TA,A), get_texpr_expr(TB,B)},
2953 assoc_subs(A,concat), assoc_subs(B,concat).
2954 assoc_subs(composition(TA,TB),composition) --> !,
2955 {get_texpr_expr(TA,A), get_texpr_expr(TB,B)},
2956 assoc_subs(A,composition), assoc_subs(B,composition).
2957 assoc_subs(Expr,Op) --> {nonvar(Op)},[Expr]. % base case for other operators
2958
2959 is_commutative(conjunct).
2960 is_commutative(disjunct).
2961 is_commutative(equivalence).
2962 is_commutative(equal).
2963 is_commutative(not_equal).
2964 is_commutative(add).
2965 is_commutative(multiplication).
2966 is_commutative(union).
2967 is_commutative(intersection).
2968
2969 % check if two type expressions are same modulo info fields and reordering of commutative operators
2970 % same_texpr does not reorder wrt commutativity.
2971 same_norm_texpr(TExpr1,TExpr2) :-
2972 strip_and_norm_ast(TExpr1,N1),
2973 strip_and_norm_ast(TExpr2,N1).
2974
2975
2976 % small utility to get functor of texpr:
2977 get_texpr_functor(b(E,_,_),F,N) :- !, functor(E,F,N).
2978 get_texpr_functor(E,_,+) :- add_error_fail(get_texpr_functor,'Not a typed expression: ',E).
2979
2980 % -------------------------
2981
2982 % check if a ProB type is a set type:
2983 is_set_type(set(Type),Type).
2984 is_set_type(seq(Type),couple(integer,Type)).
2985 % should we have a rule for any ?? : in all cases using is_set_type any seems not possible; better that we generate error message in get_set_type or get_texpr_set_type
2986 % is_set_type(any,any).
2987
2988 get_set_type(TypeX,Res) :-
2989 ? (is_set_type(TypeX,SetType) -> Res=SetType ; add_error_fail(get_set_type,'Not a set type: ',TypeX)).
2990
2991 get_texpr_set_type(X,Res) :- get_texpr_type(X,TypeX),
2992 get_set_type(TypeX,Res).
2993
2994
2995 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2996 % check if a set contains all elements of a type, i.e., maximal type
2997 is_just_type(Expr) :- is_just_type(Expr,[]).
2998 % is_just_type(+Expr,+RTT):
2999 % like is_just_type/1 but RTT is a list of identifiers (without type information)
3000 % of variables or constants that are known to be types, too.
3001 % E.g. is_just_type(a ** INTEGER) would fail but is_just_type(a ** INTEGER,[a]) would
3002 % succeed.
3003 is_just_type(b(E,T,I),RTT) :- is_just_type3(E,T,I,RTT).
3004
3005
3006 is_just_type3(identifier(G),set(Type),Infos,RefsToTypes) :-
3007 ( Type = global(G), memberchk(given_set,Infos)
3008 ; memberchk(G,RefsToTypes)),!.
3009 is_just_type3(freetype_set(_),_,_,_).
3010 is_just_type3(pow_subset(E),_,_,RTT) :- is_just_type(E,RTT).
3011 is_just_type3(fin_subset(E),T,_,RTT) :-
3012 is_finite_type_in_context(proving,T), % animation or proving
3013 is_just_type(E,RTT).
3014 is_just_type3(integer_set('INTEGER'),set(integer),_,_).
3015 is_just_type3(bool_set,set(boolean),_,_).
3016 is_just_type3(real_set,set(real),_,_).
3017 is_just_type3(string_set,set(string),_,_).
3018 is_just_type3(cartesian_product(A,B),_,_,RTT) :-
3019 is_just_type(A,RTT),is_just_type(B,RTT).
3020 is_just_type3(mult_or_cart(A,B),_,_,RTT) :- % is_just_type/1 could be called before the cleanup
3021 is_just_type(A,RTT),is_just_type(B,RTT). % of an expression has finished
3022 is_just_type3(relations(A,B),_,_,RTT) :-
3023 is_just_type(A,RTT),is_just_type(B,RTT).
3024 is_just_type3(struct(b(rec(Fields),_,_)),_,_,RTT) :-
3025 maplist(field_is_just_type(RTT),Fields).
3026 is_just_type3(typeset,_,_,_).
3027 is_just_type3(comprehension_set(_,b(truth,_,_)),_,_,_).
3028 is_just_type3(value(Val),ST,_,_) :- is_set_type(ST,Type), is_maximal_value(Val,Type). % also see: quick_is_definitely_maximal_set(Val).
3029
3030 field_is_just_type(RTT,field(_,Set)) :- is_just_type(Set,RTT).
3031
3032 is_maximal_value(V,_) :- var(V),!,fail.
3033 is_maximal_value(global_set(GS),Type) :- (GS=='INTEGER' -> true ; Type==global(GS)). % we could call is_maximal_global_set(GS) or b_global_set (but requires compiled)
3034
3035 % Generate a custom matching / visitor predicate
3036 % bsyntaxtree:gen_visitor(bexpr_variables_aux,bexpr_variables)
3037 /*
3038 gen_visitor(Pred, BodyPred) :- syntaxelement(Expr,SubsX,_NamesX,_Lists,_ConstantX,_),
3039 print_clause(Pred,BodyPred,Expr,SubsX),
3040 fail.
3041 gen_visitor(Pred, BodyPred) :- nl.
3042
3043 print_clause(Pred,BodyPred,Expr,SubsX) :- E=..[Op|SubsX], format('~w(~w) :- ',[Pred,Expr]).
3044 */
3045
3046 /*
3047 * create_recursive_compset(+Ids,+Cond,+Type,+Infos,-RecId,-TCompSet)
3048 * creates a recursive comprehension set:
3049 * Ids is the list of the introduced typed identifiers
3050 * Cond is the condition (a typed predicate)
3051 * Infos are additional informations for the comprehension set syntax element
3052 * RecId is the identifier (untyped, an atom) that can be used in Cond to refer to the
3053 * comprehension set recursively. Usually RecId is used in Cond as a variable
3054 * TCompSet is the generated recursive comprehension set, the recursion parameter is introduced
3055 * by a recusive(Id,CompSet) syntax element
3056 */
3057 create_recursive_compset(Ids,Cond,Type,Infos,RecId,TCompSet) :-
3058 unique_id("recursive.",RecId),
3059 add_symbolic_annotation(Infos,RInfos),
3060 create_texpr(comprehension_set(Ids,Cond),Type,RInfos,TCompSet1),
3061 create_typed_id(RecId,Type,TRecId),
3062 create_texpr(recursive_let(TRecId,TCompSet1),Type,[],TCompSet).
3063
3064 unique_typed_id(Prefix,Type,TId) :-
3065 unique_id(Prefix,Id),
3066 create_typed_id(Id,Type,TId).
3067
3068
3069 mark_bexpr_as_symbolic(b(E,T,I),b(E2,T,RI)) :-
3070 add_symbolic_annotation(I,RI),
3071 mark_aux(E,E2).
3072 mark_aux(union(A,B),R) :- !, R=union(SA,SB),
3073 mark_bexpr_as_symbolic(A,SA), mark_bexpr_as_symbolic(B,SB).
3074 % union is currently the only operator that is kept symbolically
3075 mark_aux(A,A).
3076
3077 add_symbolic_annotation([H|I],R) :- H == prob_annotation('SYMBOLIC'),!, R=[H|I].
3078 add_symbolic_annotation(I,R) :- !, R=[prob_annotation('SYMBOLIC')|I].
3079
3080 % identifier_sub_ast(+TExpr,+Identifier,-SubPosition):
3081 % Find occurences of an identifier "Identifier" in an expression "TExpr"
3082 % Returns a list of positions (beginning with 0) that describes the position of a sub-expression
3083 % that contains all occurrences of Identifier in TExpr.
3084 % E.g. [1,0,1] means "second sub-expression of TExpr, then the first sub-expression of that,
3085 % then the second sub-expression of that".
3086 % When an identifier has multiple occurences, the position of the sub-expression is returned
3087 % where all occurences of it are located.
3088 % If the identifier is not found, the call fails.
3089 % Sub-expressions are meant like the ones syntaxtraversion or syntaxtransformation return.
3090 identifier_sub_ast(TExpr,Identifier,SubPosition) :-
3091 syntaxtraversion(TExpr,Expr,_Type,_Infos,AllSubs,Names),
3092 identifier_sub_ast_aux(Expr,AllSubs,Names,Identifier,SubPosition).
3093 identifier_sub_ast_aux(identifier(Identifier),[],[],Identifier,[]) :- !.
3094 identifier_sub_ast_aux(_Expr,AllSubs,Names,Identifier,SubPosition) :-
3095 get_texpr_id(TId,Identifier),nonmember(TId,Names),
3096 % For each sub-expression E in the list AllSubs create a term Pos-E
3097 % where Pos is E's position (starting with 0) in AllSubs
3098 foldl(annotate_pos,AllSubs,AllAnnotatedSubs,0,_),
3099 % Introduced identifiers occur alsa as sub-expressions, remove those
3100 foldl(select_sub,Names,AllAnnotatedSubs,RealAnnSubs),
3101 convlist_max(identifier_sub_ast_aux2(Identifier),2,RealAnnSubs,SubPositions), % find at most 2 sols
3102 ( SubPositions = [SubPosition] -> true
3103 ; SubPositions = [_,_|_] -> % More then one occurrences - make this the found node
3104 SubPosition = []).
3105 identifier_sub_ast_aux2(Identifier,Pos-TExpr,[Pos|SubPosition]) :-
3106 identifier_sub_ast(TExpr,Identifier,SubPosition).
3107 annotate_pos(TExpr,I-TExpr,I,I2) :- I2 is I+1.
3108 select_sub(Name,AnnotatedSubs,Result) :-
3109 selectchk(_Pos-Name,AnnotatedSubs,Result).
3110
3111
3112
3113 % exchange_ast_position(+SubPosition,+OldTExpr,-OldInner,+NewInner,-NewTExpr):
3114 % exchanges a sub-expression in the expression "OldTExpr".
3115 % SubPosition is a list of positions like identifier_sub_ast/3 returns it.
3116 % OldInner is the sub-expression found in OldTExpr.
3117 % NewInner is the new sub-expression.
3118 % NewTExpr is the new expression that originates from replacing OldInner by NewInner.
3119 exchange_ast_position([],Old,Old,New,New).
3120 exchange_ast_position([Pos|RestPos],OldTExpr,OldInner,NewInner,NewTExpr) :-
3121 remove_bt_and_used_ids(OldTExpr,OldExpr,NewExpr,NewTExpr), % also invalidates used_ids info
3122 syntaxtransformation(OldExpr,Subs,_Names,NSubs,NewExpr),
3123 nth0(Pos,Subs, OldSelected,Rest),
3124 nth0(Pos,NSubs,NewSelected,Rest),
3125 exchange_ast_position(RestPos,OldSelected,OldInner,NewInner,NewSelected).
3126
3127
3128 % -----------------------
3129
3130 :- public check_used_ids/2.
3131 % a simple checker, only checks used_ids info fields for entire typed expression:
3132 check_used_ids(TExpr,PP) :- %format('CHECK AST for ~w~n',[PP]),
3133 map_over_typed_bexpr(check_used_ids_texpr_fail(PP),TExpr).
3134 check_used_ids(_,_).
3135 check_used_ids_texpr_fail(PP,E) :- check_used_ids_texpr(PP,E),!,fail.
3136 check_used_ids_texpr(PP,b(P,T,I)) :- member(used_ids(UIds1),I),!,
3137 (find_identifier_uses(b(P,T,I),[],UIds2) -> true
3138 ; add_internal_error('find_identifier_uses failed',PP),fail),
3139 (UIds1==UIds2 -> true
3140 ; format('*** Wrong used_ids Info (~w)!!~n Used_ids: ~w~n Comp_ids: ~w~n',[PP,UIds1,UIds2]),
3141 translate:print_bexpr(b(P,T,I)),nl,
3142 add_error(check_used_ids,'Wrong used_ids: ',PP,I)
3143 ).
3144 check_used_ids_texpr(_,_).
3145
3146 % repair any broken used_ids info in typed expression TExpr and re-compute used_ids if necessary
3147 % PP is a program point, will be reported in case of an error
3148 repair_used_ids(PP,TExpr,Res) :-
3149 (transform_bexpr(bsyntaxtree:repair_used_ids_info(PP),TExpr,NewTExpr) -> Res=NewTExpr
3150 ; add_internal_error('Repairing used_ids failed:',PP),
3151 Res=TExpr).
3152
3153 % we could also simply call recompute_used_ids_inf; but it would not generate any messages
3154 repair_used_ids_info(PP,b(P,T,I),b(P,T,NI)) :- %functor(P,FF,_), print(repair(FF)),nl,
3155 select(used_ids(OldUsed),I,I2),!,
3156 (find_identifier_uses(b(P,T,I),[],NewUsed)
3157 -> (NewUsed=OldUsed -> NI=I
3158 ; NI = [used_ids(NewUsed)|I2],
3159 add_message(repair_used_ids,'Updating used_ids for: ',b(P,T,I),I2)
3160 )
3161 ; add_internal_error('find_identifier_uses failed',PP),
3162 NI=I
3163 ).
3164 repair_used_ids_info(PP,b(P,T,I),b(P,T,NI)) :-
3165 requires_used_ids(P),
3166 (find_identifier_uses(b(P,T,I),[],NewUsed) -> true
3167 ; add_internal_error('find_identifier_uses failed',PP),fail
3168 ),
3169 !,
3170 NI=[used_ids(NewUsed)|I].
3171 repair_used_ids_info(_,B,B).
3172
3173 requires_used_ids(exists(_,_)).
3174 requires_used_ids(forall(_,_,_)).
3175
3176 % a simple checker to see if an AST is well-formed:
3177 % can be tested e.g. as follows: b_get_invariant_from_machine(I), check_ast(I).
3178 % called in prob_safe_mode by clean_up_section
3179
3180 check_ast(TE) :- check_ast(false,TE).
3181 check_ast(AllowVars,TExpr) :- %nl,print('CHECK AST'),nl,
3182 map_over_typed_bexpr(check_ast_texpr(AllowVars),TExpr).
3183 check_ast(_,_).
3184
3185 :- use_module(typing_tools,[valid_ground_type/1]).
3186 %check_ast_texpr(X) :- print(check(X)),nl,fail.
3187 check_ast_texpr(AllowVars,AST) :- AST = b(E,Type,Infos),
3188 (debug:debug_level_active_for(9) -> write(' check_ast: '),print_bexpr(AST), write(' :: '), write(Type), nl ; true),
3189 (check_expr(E,Type,Infos) -> true
3190 ; add_error(check_ast_texpr,'Invalid Expr: ', AST) %, trace, check_expr(E,Type,Infos)
3191 ),
3192 (check_type(Type,AllowVars) -> true
3193 ; add_error(check_ast_texpr,'Invalid Type for: ',AST,Infos)),
3194 safe_functor(E,F),
3195 check_ast_typing(E,Type,Infos),
3196 (check_infos(Infos,F) -> true ; add_error(check_ast_texpr,'Invalid Infos: ',AST)),
3197 check_special_rules(E,Type,Infos),
3198 fail. % to force backtracking in map_over_typed_bexpr
3199
3200
3201 check_special_rules(operation_call_in_expr(Operation,_),_,OInfos) :- !,
3202 get_texpr_info(Operation,Info), % reads info important for used_ids computation
3203 (memberchk(reads(_V),Info) -> true
3204 ; add_error(check_ast_texpr,'Missing reads info: ',Operation,OInfos)).
3205
3206
3207 safe_functor(V,R) :- var(V),!,R='$VAR'.
3208 safe_functor(E,F/N) :- functor(E,F,N).
3209
3210 % check whether the type term is ok
3211 check_type(X,AllowVars) :- var(X),!,
3212 (AllowVars==true -> true ; add_error(check_type,'Variable type: ',X),fail).
3213 check_type(pred,_) :- !.
3214 check_type(subst,_) :- !.
3215 check_type(op(Paras,Returns),AllowVars) :- !,
3216 maplist(check_normal_type(AllowVars),Paras),
3217 maplist(check_normal_type(AllowVars),Returns).
3218 check_type(T,AllowVars) :- check_normal_type(AllowVars,T).
3219
3220 check_normal_type(AllowVars,T) :-
3221 (AllowVars \== true -> valid_ground_type(T)
3222 ; ground(T) -> valid_ground_type(T)
3223 ; true). % TO DO: call valid_ground_type but pass AllowVars
3224
3225 :- use_module(probsrc(btypechecker), [lookup_type_for_expr/2, unify_types_werrors/4]).
3226 % check whether type is compatible with operators
3227 check_ast_typing(member(A,B),Type,Pos) :- !,
3228 get_texpr_type(B,TB), check_set_type(TB,member,Pos),
3229 check_type(Type,pred,member),
3230 get_texpr_type(A,TA),
3231 unify_types_werrors(set(TA),TB,Pos,member).
3232 check_ast_typing(not_equal(A,B),Type,Pos) :- !, check_ast_typing(equal(A,B),Type,Pos).
3233 check_ast_typing(equal(A,B),Type,Pos) :- !,
3234 get_texpr_type(B,TB),
3235 get_texpr_type(A,TA),
3236 unify_types_werrors(TA,TB,Pos,'='),
3237 (non_value_type(TA)
3238 -> add_error(check_ast_typing,'Binary predicate has to have values as arguments:',TA,Pos)
3239 ; Type=pred -> true
3240 ; add_error(check_ast_typing,'Illegal type for binary predicate:',Type,Pos)
3241 ).
3242 check_ast_typing(greater_equal(A,B),Type,_) :- !,
3243 get_texpr_type(A,TA),check_type(TA,integer,greater_equal),
3244 get_texpr_type(B,TB),check_type(TB,integer,greater_equal), check_type(Type,pred,member).
3245 check_ast_typing(Expr,Type,Pos) :-
3246 syntaxtransformation(Expr,Subs,Names,NSubs,NewExpr),
3247 check_names(Names,Pos),
3248 (lookup_type(NewExpr,T) -> true
3249 ; add_warning(check_ast_typing,'Unable to lookup type for: ',NewExpr),
3250 fail
3251 ),
3252 !,
3253 (unify_types_werrors(Type,T,Pos,'check_ast')
3254 -> maplist(check_sub_type(Expr,Pos),Subs,NSubs)
3255 ; add_error(check_ast_typing,'Type mismatch for expression:',Expr,Pos)
3256 ).
3257 check_ast_typing(_,subst,_) :- !. % ignore subst for the moment
3258 check_ast_typing(operation(_TName,_Res,_Params,_TBody),_,_) :- !. % ignore operations for the moment
3259 check_ast_typing(Expr,_,Pos) :-
3260 syntaxtransformation(Expr,_,_Names,_,_NewExpr),!,
3261 add_message(check_ast_typing,'Cannot lookup type for expression: ',Expr,Pos).
3262 check_ast_typing(Expr,_,Pos) :-
3263 add_message(check_ast_typing,'No applicable type rule for expression: ',Expr,Pos).
3264
3265 non_value_type(X) :- var(X),!,fail.
3266 non_value_type(pred).
3267 non_value_type(subst).
3268 non_value_type(op(_)).
3269
3270
3271 check_names([],_).
3272 check_names([H|T],Pos) :-
3273 (member(H,T) -> add_error(check_ast_name,'Duplicate name:',H,Pos) ; check_names(T,Pos)).
3274
3275 check_sub_type(OuterExpr,Pos,Arg,Type) :- get_texpr_type(Arg,T),!,
3276 (unify_types_werrors(Type,T,Pos,'check_sub_type') -> true
3277 ; add_error(check_ast_typing,'Type mismatch for sub-expression:',Arg,Pos),
3278 write('Outer expression: '),translate:print_bexpr(OuterExpr),nl,
3279 write('Outer type: '),write(Type),nl,
3280 write('Arg type: '),write(T),nl,print(type(T)),nl, tools_printing:print_term_summary(Arg),nl,trace
3281 ).
3282 check_sub_type(_,Pos,Arg,_) :-
3283 add_error(check_ast_typing,'Cannot extract type: ',Arg,Pos).
3284
3285 lookup_type(identifier(_),_) :- !. % ignore typing issues for identifiers
3286 lookup_type(Expr,Type) :- lookup_type_for_expr(Expr,Type).
3287
3288 check_set_type(Var,_,_) :- var(Var),!.
3289 check_set_type(set(_),_,_) :- !.
3290 check_set_type(seq(_),_,_) :- !.
3291 check_set_type(Type,Func,Pos) :- add_error(check_ast_typing,'Invalid type for operator: ',Func:Type,Pos).
3292
3293 check_type(Type,Type,_) :- !.
3294 check_type(Type,_,Func) :- add_error(check_ast_typing,'Unexpected type for operator: ',Func:Type).
3295
3296 check_infos(X,F) :- var(X),!, add_error(check_infos,'Info field list not terminated: ',F:X),fail.
3297 check_infos([],_).
3298 check_infos([H|_],F) :- \+ ground(H),!, add_error(check_infos,'Info field not ground: ',F:H),fail.
3299 check_infos([[H|T]|_],F) :- !, add_error(check_infos,'Info field contains nested list: ',F:[H|T]),fail.
3300 check_infos([cse_used_ids(H)|T],F) :- member(cse_used_ids(H2),T),!,
3301 add_error(check_infos,'Multiple cse_used_ids entries: ',F:[H,H2]),fail.
3302 check_infos([used_ids(H)|T],F) :- member(used_ids(H2),T),!,
3303 add_error(check_infos,'Multiple used_ids entries: ',F:[H,H2]),fail.
3304 check_infos([nodeid(N1)|T],F) :- member(nodeid(N2),T),!,
3305 add_error(check_infos,'Multiple nodeid entries: ',F:[N1,N2],[nodeid(N1)]),fail.
3306 check_infos([removed_typing|T],F) :- member(removed_typing,T),!,
3307 add_error(check_infos,'Multiple removed_typing entries: ',F,T),fail.
3308 check_infos([_|T],F) :- check_infos(T,F).
3309
3310 check_expr(Expr,Type,Infos) :- nonmember(contains_wd_condition,Infos),
3311 sub_expression_contains_wd_condition(Expr,Sub),
3312 TE = b(Expr,Type,Infos),
3313 (Type = subst
3314 -> fail % AST cleanup is not called for substitutions; WD-info not available for substitutions at the moment
3315 ; translate_bexpression(TE,PS)),
3316 functor(Expr,Functor,_),
3317 functor(Sub,SubFunctor,_),
3318 tools:ajoin(['Node for AST node ',Functor,' does not contain WD info from Subexpression ',SubFunctor,' :'],Msg),
3319 add_warning(check_expr,Msg,PS,TE).
3320 % well_def_analyser:nested_print_wd_bexpr(TE),nl.
3321 % TODO: check when we have an unnecessary WD condition
3322 check_expr(Expr,Type,Infos) :- nonmember(contains_wd_condition,Infos),
3323 always_not_wd_top(Expr),
3324 add_warning(check_expr,'AST is not well-defined but does not contain WD info: ',b(Expr,Type,Infos),Infos).
3325 check_expr(member(LHS,RHS),Type,Infos) :- is_just_type(RHS),
3326 get_preference(optimize_ast,true),
3327 !,
3328 TE = b(member(LHS,RHS),Type,Infos),
3329 translate:translate_bexpression(TE,PS),
3330 add_warning(check_expr,'AST contains redundant typing predicate: ',PS,TE).
3331 check_expr(identifier(ID),_,_) :- illegal_id(ID),!,
3332 add_error(check_infos,'Illegal identifier: ', identifier(ID)).
3333 check_expr(lazy_lookup_expr(ID),_,_) :- illegal_id(ID),!,
3334 add_error(check_infos,'Illegal identifier: ', lazy_lookup_expr(ID)).
3335 check_expr(lazy_lookup_pred(ID),_,_) :- illegal_id(ID),!,
3336 add_error(check_infos,'Illegal identifier: ', lazy_lookup_pred(ID)).
3337 check_expr(exists(Parameters,Condition),pred,Infos) :- !,
3338 check_used_ids(exists,Parameters,Condition,Infos,_Used).
3339 check_expr(forall(Parameters,LHS,RHS),pred,Infos) :- !,
3340 create_implication(LHS,RHS,Condition),
3341 check_used_ids(forall,Parameters,Condition,Infos,_Used). %
3342 check_expr(value(V),Type,_) :- !, check_bvalue(V,Type).
3343 check_expr(_,_,_).
3344
3345 % will check all used_ids fields (not just for exists and forall)
3346 :- public check_used_ids_in_ast/1.
3347 check_used_ids_in_ast(closure(_,_,TExpr)) :- !, (map_over_typed_bexpr(check_used_ids_aux,TExpr) ; true).
3348 check_used_ids_in_ast(TExpr) :- map_over_typed_bexpr(check_used_ids_aux,TExpr).
3349 check_used_ids_in_ast(_).
3350
3351 check_used_ids_aux(AST) :- AST = b(_,_,Infos),
3352 member(used_ids(_),Infos),!,
3353 find_identifier_uses_if_necessary(AST,[],_), % will perform check
3354 fail.
3355
3356 % --------------------
3357
3358 :- use_module(specfile,[eventb_mode/0, z_or_tla_minor_mode/0]).
3359 % check if an expression is definitely not WD; looking at the top-level operator only
3360 always_not_wd_top(function(X,_)) :- definitely_empty_set(X). % TODO: detect a few more cases, e.g., arg not in dom
3361 always_not_wd_top(power_of(X,Y)) :- (get_integer(Y,VY), VY < 0 -> true
3362 ; eventb_mode, get_integer(X,VX), VX < 0).
3363 always_not_wd_top(div(_,Val)) :- get_integer(Val,VV), VV==0.
3364 always_not_wd_top(modulo(X,Y)) :-
3365 (get_integer(Y,VY), VY=<0
3366 -> true % there seems to be a def for Z in Z Live, cf modulo2
3367 ; get_integer(X,VX), VX<0, \+ z_or_tla_minor_mode).
3368 always_not_wd_top(min(X)) :- definitely_empty_set(X).
3369 always_not_wd_top(max(X)) :- definitely_empty_set(X).
3370 always_not_wd_top(size(X)) :- definitely_not_sequence(X). % TODO: detect infinite sets; also for card(_)
3371 always_not_wd_top(first(X)) :- definitely_not_non_empty_sequence(X).
3372 always_not_wd_top(front(X)) :- definitely_not_non_empty_sequence(X).
3373 always_not_wd_top(last(X)) :- definitely_not_non_empty_sequence(X).
3374 always_not_wd_top(tail(X)) :- definitely_not_non_empty_sequence(X).
3375 always_not_wd_top(general_intersection(X)) :- definitely_empty_set(X).
3376
3377 definitely_not_non_empty_sequence(X) :-
3378 (definitely_empty_set(X) -> true ; definitely_not_sequence(X)).
3379
3380 :- use_module(avl_tools,[avl_min_pair/3]).
3381 definitely_not_sequence(b(value(A),_,_)) :- nonvar(A), A=avl_set(AVL),
3382 avl_min_pair(AVL,int(StartIndex),_), StartIndex \= 1.
3383 % TODO: treat set_extension
3384
3385 :- use_module(b_ast_cleanup,[check_used_ids_info/4]).
3386 check_used_ids(Quantifier,Parameters,Condition,Infos,Used) :-
3387 select(used_ids(Used),Infos,Rest)
3388 -> check_used_ids_info(Parameters,Condition,Used,Quantifier), %% comment in to check used_ids field
3389 (member(used_ids(_),Rest)
3390 -> add_internal_error('Multiple used_ids info fields:',Parameters:Infos) ; true)
3391 ;
3392 add_internal_error(
3393 'Expected information of used identifiers information',Quantifier:Parameters:Infos).
3394
3395 illegal_id(ID) :- var(ID),!.
3396 illegal_id(op(ID)) :- !, \+ atom(ID).
3397 illegal_id(ID) :- \+ atom(ID).
3398
3399 :- use_module(btypechecker, [unify_types_strict/2, couplise_list/2]).
3400 :- use_module(avl_tools,[check_is_non_empty_avl/1]).
3401 % TO DO: we could check type more
3402 check_bvalue(V,_) :- var(V),!.
3403 check_bvalue(avl_set(A),Type) :- !, unify_types_strict(Type,set(_)),
3404 check_is_non_empty_avl(A).
3405 check_bvalue(closure(_,T,B),Type) :- !,
3406 couplise_list(T,CT), unify_types_strict(set(CT),Type),
3407 check_ast(B).
3408 check_bvalue(_,_).
3409
3410 % -----------------------
3411
3412
3413 indent_ws(X) :- X<1,!.
3414 indent_ws(X) :- print(' '), X1 is X-1, indent_ws(X1).
3415
3416 print_ast_td(b(E,T,I),Level,L1) :-
3417 indent_ws(Level),
3418 (E=identifier(_)
3419 -> format('~w (~w) -> ~w~n',[E,T,I])
3420 ; functor(E,F,N),
3421 format('~w/~w (~w) -> ~w~n',[F,N,T,I])
3422 ),
3423 L1 is Level+1.
3424 print_ast(TExpr) :-
3425 (map_over_typed_bexpr_top_down_acc(print_ast_td,TExpr,0),fail ; true).
3426
3427 % ---------------------
3428
3429 :- dynamic count_id_usage/2.
3430 single_usage_id_count(Expr) :- uses_an_identifier(Expr,Id),
3431 retract(count_id_usage(Id,Count)),
3432 !,
3433 Count=0,
3434 C1 is Count+1,
3435 assertz(count_id_usage(Id,C1)).
3436 single_usage_id_count(_).
3437
3438 % check if an identifier is used at most once
3439 single_usage_identifier(ID,ExprOrPredicates,Count) :-
3440 retractall(count_id_usage(_,_)),
3441 assertz(count_id_usage(ID,0)),
3442 % TO DO: take care of naming; do not count occurences when we enter scope defining ID
3443 maplist(single_usage_cnt,ExprOrPredicates),
3444 retract(count_id_usage(ID,Count)).
3445
3446 single_usage_cnt(ExprOrPredicate) :- map_over_full_bexpr_no_fail(single_usage_id_count,ExprOrPredicate).
3447
3448 gen_fresh_id_if_necessary(Default,Expr,FreshID) :-
3449 occurs_in_expr(Default,Expr),!,
3450 gensym('__FRESH_ID__',FreshID). % assumes _Fresh_XXX not used
3451 gen_fresh_id_if_necessary(Default,_,Default).
3452
3453 %% rewrite_if_then_else_expr_to_b(IfThenElseExpr, NExpr).
3454 % Rewrite if-then-else expr to B as understood by Atelier-B.
3455 % {d,x| d:BOOL & If => x=Then & not(if) => x=Else}(TRUE)
3456 rewrite_if_then_else_expr_to_b(if_then_else(If,Then,Else), NExpr) :-
3457 get_texpr_type(Then,Type),
3458 ARG = b(boolean_true,boolean,[]), AT=boolean, % we could use unit type or BOOL here
3459 gen_fresh_id_if_necessary('_zzzz_unary',b(if_then_else(If,Then,Else),Type,[]),AID1),
3460 gen_fresh_id_if_necessary('_zzzz_binary',b(if_then_else(If,Then,Else),Type,[]),AID2),
3461 safe_create_texpr(identifier(AID1), AT, [], Id1), % a dummy argument
3462 safe_create_texpr(identifier(AID2), Type, [], Id2), % The result
3463 safe_create_texpr(equal(Id2,Then), pred, [], Eq1),
3464 safe_create_texpr(equal(Id2,Else), pred, [], Eq2),
3465 safe_create_texpr(implication(If,Eq1), pred, [], Pred1),
3466 safe_create_texpr(negation(If), pred, [], NIf),
3467 safe_create_texpr(implication(NIf,Eq2), pred, [], Pred2),
3468 safe_create_texpr(conjunct(Pred1,Pred2), pred, [], Pred),
3469 safe_create_texpr(comprehension_set([Id1,Id2],Pred), set(couple(AT,Type)), [], FUN),
3470 NExpr = function(FUN,ARG).