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