| 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(b_interpreter_components,[ | |
| 6 | reset_component_info/1, | |
| 7 | b_trace_test_components/3, b_trace_test_components/4, | |
| 8 | b_trace_test_components_wf/4, b_trace_test_components_wf/7, | |
| 9 | unsat_component/2, unsat_component_enumeration_warning/1, | |
| 10 | unsat_or_unknown_component_exists/0, | |
| 11 | unsat_component_abort_error/1, | |
| 12 | unsat_conjunct_inside_component/4, | |
| 13 | det_solution_for_constant/2, get_det_solution_for_constant_value_kind/2, | |
| 14 | det_solution_for_constant_was_stored/0, det_solution_for_constant_was_stored/1, | |
| 15 | b_tracetest_boolean_expression/5, | |
| 16 | ||
| 17 | construct_optimized_exists/3, construct_optimized_exists/4, | |
| 18 | construct_optimized_exists/5, | |
| 19 | extract_equalities_in_quantifier/4 | |
| 20 | ]). | |
| 21 | ||
| 22 | :- use_module(b_interpreter,[b_test_boolean_expression/6]). | |
| 23 | :- use_module(preferences). | |
| 24 | :- use_module(kernel_waitflags). | |
| 25 | :- use_module(tools). | |
| 26 | :- use_module(translate). | |
| 27 | :- use_module(error_manager). | |
| 28 | :- use_module(library(lists)). | |
| 29 | :- use_module(b_enumerate, [b_tighter_enumerate_all_values/2, b_tighter_enumerate_values/3]). | |
| 30 | ||
| 31 | :- use_module(debug,[debug_println/2, debug_mode/1, debug_level_active_for/1]). | |
| 32 | :- use_module(tools,[start_ms_timer/1, stop_ms_timer_with_msg/2, stop_ms_timer_with_debug_msg/2]). | |
| 33 | ||
| 34 | :- use_module(chrsrc(chr_integer_inequality),[attach_chr_integer_inequality_to_wf_store/1]). | |
| 35 | ||
| 36 | ||
| 37 | :- use_module(module_information,[module_info/2]). | |
| 38 | :- module_info(group,interpreter). | |
| 39 | :- module_info(description,'This module can be used to split a predicate into components and solving each component individually (with tracing feedback).'). | |
| 40 | ||
| 41 | :- set_prolog_flag(double_quotes, codes). | |
| 42 | ||
| 43 | /* -------------- */ | |
| 44 | /* dynamic bits */ | |
| 45 | /* -------------- */ | |
| 46 | ||
| 47 | :- dynamic skipped_unsat_conjunct/1, unsat_conjunct_inside_component/4. | |
| 48 | reset_unsat_conjunct_inside_component_info :- | |
| 49 | retractall(skipped_unsat_conjunct(_)), | |
| 50 | retractall(unsat_conjunct_inside_component(_,_,_,_)). | |
| 51 | reset_tracetest_for_component :- retractall(skipped_unsat_conjunct(_)). % to be called before trace checking a component | |
| 52 | ||
| 53 | % individual components which are directly unsatisfiable in phase 0 (WF0) | |
| 54 | assert_skipped_failed_conjunct(ComponentNr,BE) :- assert_skipped_unsat_conjunct, | |
| 55 | assertz(unsat_conjunct_inside_component(ComponentNr,BE,false,'')), | |
| 56 | (preferences:get_preference(provide_trace_information,false) -> true | |
| 57 | ; add_message(b_interpreter_components,' *** INCONSISTENCY DETECTED, SKIPPING COMPONENT NR: ', | |
| 58 | ComponentNr, BE), | |
| 59 | (debug_mode(on) -> LIM=500 ; LIM=150), print_bexpr_with_limit(BE,LIM),nl | |
| 60 | ). | |
| 61 | % individual components which create enumeration warnings in phase 0: | |
| 62 | assert_skipped_unknown_conjunct(ComponentNr,BE,Reason) :- assert_skipped_unknown_conjunct, | |
| 63 | assertz(unsat_conjunct_inside_component(ComponentNr,BE,unknown,Reason)), | |
| 64 | ((Reason=abort_error; Reason=well_definedness_error) | |
| 65 | -> assert_unsat_component_abort_error(ComponentNr) | |
| 66 | ; true), | |
| 67 | (preferences:get_preference(provide_trace_information,false) -> true | |
| 68 | ; get_reason_msg(Reason,MSG),format(' *** Skipping predicate due to ~w:',[MSG]), | |
| 69 | write(' '),print_bexpr_with_limit(BE,150),nl, | |
| 70 | format('~n *** Predicate is unknown~n *** COMPONENT NUMBER: ~w~n',[ComponentNr]) | |
| 71 | ). | |
| 72 | assert_skipped_unsat_conjunct :- | |
| 73 | (skipped_unsat_conjunct(false) -> true | |
| 74 | ; retractall(skipped_unsat_conjunct(_)), assertz(skipped_unsat_conjunct(false))). | |
| 75 | assert_skipped_unknown_conjunct :- | |
| 76 | (skipped_unsat_conjunct(_) -> true ; assertz(skipped_unsat_conjunct(unknown))). | |
| 77 | ||
| 78 | get_reason_msg(enumeration_warning,R) :- !, R='ENUMERATION WARNING'. | |
| 79 | get_reason_msg(M,M). | |
| 80 | ||
| 81 | ||
| 82 | :- dynamic unsat_component/2, unsat_component_enumeration_warning/1, unsat_component_abort_error/1. | |
| 83 | reset_unsat_component_info :- | |
| 84 | retractall(unsat_component(_,_)), | |
| 85 | retractall(unsat_component_enumeration_warning(_)), | |
| 86 | retractall(unsat_component_abort_error(_)). | |
| 87 | ||
| 88 | reset_all_component_infos :- | |
| 89 | reset_unsat_component_info, | |
| 90 | reset_unsat_conjunct_inside_component_info, | |
| 91 | reset_observe_state. | |
| 92 | ||
| 93 | :- use_module(eventhandling,[register_event_listener/3]). | |
| 94 | :- register_event_listener(clear_specification,reset_all_component_infos, | |
| 95 | 'Reset b_interpreter_components unsat component info.'). | |
| 96 | ||
| 97 | ||
| 98 | store_unsat_component_nr(X) :- % use if you do not know if it is unknown or unsat | |
| 99 | %error_manager:print_error_scopes, | |
| 100 | (critical_enumeration_warning_occured_in_error_scope | |
| 101 | -> Res = unknown | |
| 102 | % should we also detect abort_error_occured_in_error_scope ? | |
| 103 | ; Res=false), | |
| 104 | store_unsat_component_nr(X,Res). | |
| 105 | ||
| 106 | store_unsat_component_nr(X,FalseOrUnknown) :- | |
| 107 | debug_println(9,store_unsat_component_nr(X,FalseOrUnknown)), | |
| 108 | (unsat_component(X,false) -> true | |
| 109 | ; retractall(unsat_component(X,_)),assertz(unsat_component(X,FalseOrUnknown)) | |
| 110 | ), | |
| 111 | (critical_enumeration_warning_occured_in_error_scope, | |
| 112 | \+ unsat_component_enumeration_warning(X) | |
| 113 | -> assertz(unsat_component_enumeration_warning(X)), | |
| 114 | debug_println(19,enumeration_warning_in_component(X)) | |
| 115 | ; true), | |
| 116 | (abort_error_occured_in_error_scope | |
| 117 | -> assert_unsat_component_abort_error(X) | |
| 118 | ; true). | |
| 119 | %portray_unsat_components. | |
| 120 | unsat_component_exists :- unsat_component(_,false),!. | |
| 121 | unsat_or_unknown_component_exists :- unsat_component(_,_),!. | |
| 122 | ||
| 123 | % store the fact that an abort or wd error occurred for component | |
| 124 | assert_unsat_component_abort_error(X) :- \+ unsat_component_abort_error(X), | |
| 125 | assertz(unsat_component_abort_error(X)), | |
| 126 | debug_println(19,unsat_component_abort_error(X)). | |
| 127 | ||
| 128 | % small utility to display status of components | |
| 129 | :- public portray_unsat_components/0. | |
| 130 | portray_unsat_components :- format('Unsat components~n',[]), | |
| 131 | unsat_component(Comp,Status), | |
| 132 | (unsat_component_abort_error(Comp) -> Abort='abort/well_definedness error' ; Abort=''), | |
| 133 | (unsat_component_enumeration_warning(Comp) -> EW='enumeration_warning' ; EW=''), | |
| 134 | format('* component: ~w -> ~w ~w ~w~n',[Comp,Status,Abort,EW]), | |
| 135 | unsat_conjunct_inside_component(Comp,BE,S,Reason), | |
| 136 | format(' -> reason for ~w: ~w : ',[S,Reason]), translate:print_bexpr_with_limit(BE,100),nl, | |
| 137 | fail. | |
| 138 | portray_unsat_components. | |
| 139 | ||
| 140 | ||
| 141 | :- dynamic allow_skipping_over_components/0. | |
| 142 | reset_component_info(AllowSkip) :- retractall(allow_skipping_over_components), | |
| 143 | (AllowSkip==true -> assertz(allow_skipping_over_components) ; true), | |
| 144 | reset_unsat_component_info, | |
| 145 | reset_unsat_conjunct_inside_component_info. | |
| 146 | ||
| 147 | % in Disprover mode we can stop straightaway; we are not interested in finding values for identifiers in other components; unless we have an enumeration warning !! | |
| 148 | % TO DO: keep track of enumeration warnings per component | |
| 149 | ||
| 150 | /* -------------- */ | |
| 151 | ||
| 152 | ||
| 153 | :- use_module(library(avl)). | |
| 154 | % You can use the term one as ComponentNr if you don't know the number or it is not relevant | |
| 155 | b_tracetest_boolean_expression(BE,LS,S,WF,ComponentNr) :- %print(catch(ComponentNr)),nl, | |
| 156 | empty_avl(Ai), | |
| 157 | bb_put(b_interpreter_components_conjunct_nr,0), | |
| 158 | ? | catch_enumeration_warning_exceptions_and_wd_failures( |
| 159 | b_tracetest_boolean_expression1(BE,LS,S,WF,ComponentNr,Ai,_Ao,0,_), | |
| 160 | % this should not backtrack (without WF0 set); otherwise we may get problems with error blocks nesting | |
| 161 | assert_skipped_unknown_conjunct_nr(ComponentNr,BE,enumeration_warning), | |
| 162 | true, % true: add exceptions as event errors | |
| 163 | assert_skipped_unknown_conjunct(ComponentNr,BE,well_definedness_error), % for WD error | |
| 164 | component(ComponentNr)). % Source argument for debugging | |
| 165 | ||
| 166 | % the outer handler above catches enumeration warnings for all conjuncts (safe_b_test_boolean_expression | |
| 167 | % avoids setting up an error scope per conjunct); try and find the conjunct which was being checked | |
| 168 | assert_skipped_unknown_conjunct_nr(ComponentNr,BE,Reason) :- | |
| 169 | (bb_get(b_interpreter_components_conjunct_nr,CNr), CNr>0, | |
| 170 | get_nth_tracetest_conjunct(BE,CNr,Conjunct) | |
| 171 | -> assert_skipped_unknown_conjunct(ComponentNr,Conjunct,Reason) | |
| 172 | ; assert_skipped_unknown_conjunct(ComponentNr,BE,Reason)). | |
| 173 | ||
| 174 | :- use_module(self_check). | |
| 175 | :- assert_must_succeed((bsyntaxtree:parse_pred("f = /*@symbolic*/ {x|x:INTEGER & x mod 7 = 2} & card(f) = 3",P), | |
| 176 | reset_component_info(false), init_wait_flags(WF,[test]), | |
| 177 | b_tracetest_boolean_expression(P,[],[bind(f,_)],WF,77), | |
| 178 | findall(TC,(unsat_conjunct_inside_component(77,C,unknown,enumeration_warning),translate_bexpression(C,TC)),L), | |
| 179 | reset_component_info(false), error_manager:reset_errors, | |
| 180 | L == ['card(f) = 3'])). % only the conjunct raising the enumeration warning is recorded | |
| 181 | :- assert_must_succeed((bsyntaxtree:parse_pred("x>1 & (y>2 & z>3) & not(x>4 or y>5)",P), | |
| 182 | findall(N-TC,(member(N,[1,2,3,4,5,6]),get_nth_tracetest_conjunct(P,N,C),translate_bexpression(C,TC)),L), | |
| 183 | L == [1-'x > 1',2-'y > 2',3-'z > 3',4-'not(x > 4)',5-'not(y > 5)'])). | |
| 184 | ||
| 185 | % get the Nr-th conjunct as processed by b_tracetest_boolean_expression1 | |
| 186 | get_nth_tracetest_conjunct(BE,Nr,Conjunct) :- get_nth_tracetest_conj(BE,Nr,0,_,Conjunct). | |
| 187 | get_nth_tracetest_conj(BE,Nr,C0,C,Conjunct) :- | |
| 188 | is_a_conjunct_or_neg_disj(BE,LHS,RHS),!, | |
| 189 | (get_nth_tracetest_conj(LHS,Nr,C0,C1,Conjunct) -> C=C1 | |
| 190 | ; get_nth_tracetest_conj_count(LHS,C0,C1), % LHS did not contain the conjunct, count its conjuncts | |
| 191 | get_nth_tracetest_conj(RHS,Nr,C1,C,Conjunct)). | |
| 192 | get_nth_tracetest_conj(BE,Nr,C0,C,BE) :- C is C0+1, C=Nr. | |
| 193 | get_nth_tracetest_conj_count(BE,C0,C) :- | |
| 194 | (is_a_conjunct_or_neg_disj(BE,LHS,RHS) | |
| 195 | -> get_nth_tracetest_conj_count(LHS,C0,C1), get_nth_tracetest_conj_count(RHS,C1,C) | |
| 196 | ; C is C0+1). | |
| 197 | ||
| 198 | b_tracetest_boolean_expression1(b(Expr,_,Infos),LS,S,WF,ComponentNr,Ai,Ao,C0,C) :- | |
| 199 | ? | b_tracetest_boolean_expression2(Expr,Infos,LS,S,WF,ComponentNr,Ai,Ao,C0,C). |
| 200 | ||
| 201 | :- use_module(bsyntaxtree,[is_a_conjunct_or_neg_disj/3]). | |
| 202 | b_tracetest_boolean_expression2(Conjunct,Info,LocalState,State,WF,ComponentNr,Ai,Ao,C0,C) :- | |
| 203 | is_a_conjunct_or_neg_disj(b(Conjunct,pred,Info),LHS,RHS), | |
| 204 | % also detects: not(A or B) <=> not(A) & not(B) and not(A=>B) <=> A & not(B) | |
| 205 | % \+(Info = [try_smt|_]), | |
| 206 | !, | |
| 207 | %% print('check lhs of conjunct: '), translate:print_bexpr(LHS),nl, | |
| 208 | b_tracetest_boolean_expression1(LHS,LocalState,State,WF,ComponentNr,Ai,Aii,C0,C1), | |
| 209 | %% print('check rhs of conjunct: '), translate:print_bexpr(RHS),nl, | |
| 210 | ? | b_tracetest_boolean_expression1(RHS,LocalState,State,WF,ComponentNr,Aii,Ao,C1,C). |
| 211 | b_tracetest_boolean_expression2(BE,Infos,LS,S,WF,ComponentNr,Ai,Ao,C0,C) :- | |
| 212 | C is C0+1, | |
| 213 | bb_put(b_interpreter_components_conjunct_nr,C), % used by assert_skipped_unknown_conjunct_nr | |
| 214 | (get_preference(provide_trace_information,true) | |
| 215 | -> format('~n====> (~w) ',[ComponentNr]), | |
| 216 | print_bexpr_with_limit(b(BE,pred,Infos),250),nl | |
| 217 | ; true), | |
| 218 | ? | if(safe_b_test_boolean_expression(ComponentNr,b(BE,pred,Infos),LS,S,WF,Ai,Ao), |
| 219 | true, | |
| 220 | (assert_skipped_failed_conjunct(ComponentNr,b(BE,pred,Infos)), | |
| 221 | Ai=Ao)). | |
| 222 | ||
| 223 | ||
| 224 | safe_b_test_boolean_expression(ComponentNr,BE,LS,S,WF,Ai,Ao) :- | |
| 225 | preferences:get_preference(provide_trace_information,false), | |
| 226 | \+ abort_error_occured_in_error_scope, | |
| 227 | % avoid setting up new error scope for every conjunct with catch_enumeration_warning | |
| 228 | % BE is only displayed in TRACE_INFO mode anyway | |
| 229 | % can be a bottleneck, e.g., for :prob-file ../prob_examples/public_examples/Eval/Sudoku_SAT.eval | |
| 230 | !, | |
| 231 | ? | if(b_test_boolean_expression(BE,LS,S,WF,Ai,Ao),true, |
| 232 | (abort_error_occured_in_error_scope | |
| 233 | -> assert_unknown(ComponentNr,BE,abort_error,Ai,Ao) | |
| 234 | ; fail) | |
| 235 | ). | |
| 236 | safe_b_test_boolean_expression(ComponentNr,BE,LS,S,WF,Ai,Ao) :- | |
| 237 | catch_enumeration_warning_exceptions_and_wd_failures( | |
| 238 | b_test_boolean_expression(BE,LS,S,WF,Ai,Ao), % this should not backtrack (without WF0 set); | |
| 239 | % otherwise we may get problems with error blocks nesting | |
| 240 | assert_unknown(ComponentNr,BE,enumeration_warning,Ai,Ao), % call when exception caught | |
| 241 | true, % true: add exceptions as event errors | |
| 242 | assert_unknown(ComponentNr,BE,well_definedness_error,Ai,Ao), % call when wd_error caught | |
| 243 | component(ComponentNr)). % Source argument for debugging | |
| 244 | ||
| 245 | % Note: this will only detect enumeration warnings and WD errors in WF0 phase | |
| 246 | ||
| 247 | assert_unknown(ComponentNr,BE,Reason,Ai,Ao) :- % print(assert_unknown(ComponentNr,Reason)),nl, | |
| 248 | assert_skipped_unknown_conjunct(ComponentNr,BE,Reason),Ai=Ao. | |
| 249 | ||
| 250 | :- use_module(bsyntaxtree,[predicate_components_in_scope/3, | |
| 251 | predicate_identifiers_in_scope/3]). | |
| 252 | :- use_module(b_enumerate,[extract_do_not_enum_ids_from_predicate/2]). | |
| 253 | ||
| 254 | get_typedval_id(typedval(_Val,_Type,ID,_),ID). | |
| 255 | ground_typeval(typedval(Val,_Type,_ID,_)) :- ground_value(Val). | |
| 256 | :- use_module(probsrc(translate), [pretty_type/2, translate_bvalue_with_limit/3]). | |
| 257 | get_typedval_info(typedval(Val,Type,ID,_),Info) :- | |
| 258 | pretty_type(Type,TS), translate_bvalue_with_limit(Val,100,VS), | |
| 259 | ajoin([ID, ' : ', TS, ' : ', VS],Info). | |
| 260 | b_trace_test_components(Properties,ConstantsState,TypedVals) :- | |
| 261 | %format('b_trace_test_components(~w,~w,~w)',[Properties,ConstantsState,TypedVals]), | |
| 262 | b_trace_test_components(Properties,ConstantsState,TypedVals,all). | |
| 263 | b_trace_test_components_wf(Properties,ConstantsState,TypedVals,WF) :- | |
| 264 | ? | b_trace_test_components_wf(Properties,ConstantsState,TypedVals,all,satisfiable,complete,WF). |
| 265 | b_trace_test_components(Properties,ConstantsState,TypedVals,RelevantVars) :- | |
| 266 | b_trace_test_components_wf(Properties,ConstantsState,TypedVals,RelevantVars, | |
| 267 | satisfiable,complete,no_wf_available). | |
| 268 | % in contrast to /3 and /4 b_trace_test_components_wf/7 does not fail if the predicate is unsatisfiable | |
| 269 | % (provided skipping over unsat components is allowed, see reset_component_info/1); | |
| 270 | % instead it returns unsatisfiable for SatResult | |
| 271 | % if SatResult is not instantiated before the call, below we will try and solve predicates first which | |
| 272 | % provide solutions for the ConstantsState | |
| 273 | ||
| 274 | :- dynamic comp_without_ids_cached_result/1. | |
| 275 | ||
| 276 | :- use_module(probsrc(tools),[split_list/4]). | |
| 277 | b_trace_test_components_wf(Properties,ConstantsState,TypedVals,RelevantVars,SatResult,Complete,OuterWF) :- | |
| 278 | % we now treat all TypedVals as local variables: | |
| 279 | % ensure that we count them in predicate_components/predicate_identifiers | |
| 280 | % (in case they clash with global identifiers)! | |
| 281 | %start_ms_timer(T0), | |
| 282 | maplist(get_typedval_id,TypedVals,LocalVars), | |
| 283 | extract_do_not_enum_ids_from_predicate(Properties,DoNotEnumVars), | |
| 284 | (preferences:get_preference(partition_predicates,true) | |
| 285 | -> predicate_components_in_scope(Properties,LocalVars,Components), | |
| 286 | length(Components,Len), print_trace_message(nr_of_components(Len)), | |
| 287 | (SatResult == satisfiable | |
| 288 | -> CompWithIds = Components, CompNoIds=[], Len1=Len | |
| 289 | ; % we are interested in finding a solution for constants, even if the predicate is unsatisfiable | |
| 290 | % split components in those relevant for finding values for constants and those not | |
| 291 | % the latter are processed at the end, to find a solution for all constants if they are inconsistent | |
| 292 | split_list(has_identifier,Components,CompWithIds,CompNoIds), | |
| 293 | length(CompWithIds,Len1), print_trace_message(nr_of_components_with_ids(Len1)) | |
| 294 | ) | |
| 295 | ; predicate_identifiers_in_scope(Properties,LocalVars,PropVars), | |
| 296 | CompWithIds = [component(Properties,PropVars)],Len1=1, | |
| 297 | CompNoIds = [] | |
| 298 | ), | |
| 299 | reset_observe_state, retractall(comp_without_ids_cached_result(_)), | |
| 300 | %stop_ms_timer_with_debug_msg(T0,b_trace_test_components_preprocessing), | |
| 301 | ? | b_trace_test_components2(CompWithIds,ConstantsState,TypedVals,RelevantVars,DoNotEnumVars,1,NextNr,WFList1,OuterWF), |
| 302 | ? | ground_and_get_sat_result(WFList1,NextNr,Sat1), % ground components up until (not including) NextNr |
| 303 | (Sat1=satisfiable % we have found a solution for the constants | |
| 304 | -> Complete=complete, | |
| 305 | (CompNoIds=[] -> SatResult=satisfiable | |
| 306 | ; comp_without_ids_cached_result(CachedRes) | |
| 307 | -> SatResult=CachedRes % we can re-use cached result; these properties depend on nothing else | |
| 308 | ; length(CompNoIds,LenNoIds), NF is NextNr+LenNoIds-1, | |
| 309 | debug_format(19,'-->> Checking ~w components ~w..~w without identifiers~n',[LenNoIds,NextNr,NF]), | |
| 310 | ? | b_trace_test_components2(CompNoIds,ConstantsState,[],RelevantVars, |
| 311 | DoNotEnumVars,NextNr,FinalNr,WFList,OuterWF), | |
| 312 | % the remaining components instantiate no identifiers; we just need to check them once; no need to backtrack | |
| 313 | % Note: if ground_and_get_sat_result returns unsatisfiable we may have pending co-routines | |
| 314 | % we use once and check the result afterwards: once a component is marked unsat | |
| 315 | % other solutions cannot change the result and backtracking would just waste time | |
| 316 | ? | once(ground_and_get_sat_result(WFList,FinalNr,NoIdsRes)), |
| 317 | NoIdsRes==satisfiable -> | |
| 318 | assert(comp_without_ids_cached_result(satisfiable)), | |
| 319 | SatResult=satisfiable | |
| 320 | ; assert(comp_without_ids_cached_result(unsatisfiable)), | |
| 321 | SatResult=unsatisfiable | |
| 322 | ) | |
| 323 | ; Complete=incomplete, SatResult=Sat1). | |
| 324 | ||
| 325 | has_identifier(component(_Properties,[_|_])). | |
| 326 | ||
| 327 | % UptoCompNr is the next component number | |
| 328 | ground_and_get_sat_result(_,UpToCompNr,SatResult) :- | |
| 329 | unsat_component(UnsatComponentNr,false), | |
| 330 | UnsatComponentNr < UpToCompNr, | |
| 331 | debug_println(9,unsatisfiable_predicate(UnsatComponentNr,UpToCompNr)), | |
| 332 | !, | |
| 333 | SatResult=unsatisfiable. | |
| 334 | ground_and_get_sat_result(WFList,UpToCompNr,SatResult) :- | |
| 335 | ? | get_unsat_component_aux(WFList,UpToCompNr,SatResult). |
| 336 | ||
| 337 | get_unsat_component_aux(WFList,UpToCompNr,SatResult) :- | |
| 338 | print_trace_message(grounding_wait_flags), % Note: for unknown components we continue grounding | |
| 339 | ? | l_ground_wait_flags(WFList), |
| 340 | (unsat_component(UnsatComponentNr,Status), UnsatComponentNr < UpToCompNr | |
| 341 | -> debug_println(19,unsat_component(UnsatComponentNr,Status)), | |
| 342 | SatResult = unsatisfiable | |
| 343 | ; SatResult = satisfiable). | |
| 344 | get_unsat_component_aux(_,UpToCompNr,SatResult) :- | |
| 345 | unsat_component(UnsatComponentNr,_), UnsatComponentNr < UpToCompNr, | |
| 346 | !, | |
| 347 | SatResult = unsatisfiable. | |
| 348 | ||
| 349 | ||
| 350 | :- use_module(b_ast_cleanup,[predicate_level_optimizations/2]). | |
| 351 | :- use_module(debug,[printsilent_message/1]). | |
| 352 | print_trace_message(Msg) :- | |
| 353 | (preference(provide_trace_information,false) -> true | |
| 354 | ; printsilent_message(Msg)). | |
| 355 | :- use_module(probsrc(value_persistance),[cache_is_activated/0]). | |
| 356 | print_trace_message_with_typed_vals(Msg,TypedVals) :- | |
| 357 | (preference(provide_trace_information,false) -> true | |
| 358 | ; (cache_is_activated -> exclude(ground_typeval,TypedVals,NGTypedVals) ; NGTypedVals=TypedVals), | |
| 359 | (NGTypedVals=[] -> true | |
| 360 | ; printsilent_message(Msg), | |
| 361 | maplist(get_typedval_info,NGTypedVals,IDs), | |
| 362 | printsilent_message(IDs) | |
| 363 | ) | |
| 364 | ). | |
| 365 | ||
| 366 | b_trace_test_components2([],_ConstantsState,TypedVals,_,_,Nr,NextNr,ResWF,OuterWF) :- | |
| 367 | (TypedVals=[] | |
| 368 | -> print_trace_message(finished_processing_component_predicates), | |
| 369 | ResWF=[], NextNr = Nr | |
| 370 | ; print_trace_message_with_typed_vals('Enumerating Identifiers without constraints: ',TypedVals), | |
| 371 | init_wait_flags(WF0,[b_tighter_enumerate_values]), | |
| 372 | copy_wait_flag_call_stack_info(OuterWF,WF0,WF), | |
| 373 | b_tighter_enumerate_all_values(TypedVals,WF), | |
| 374 | ResWF=[wf_comp(WF,Nr)], NextNr is Nr+1 | |
| 375 | ). | |
| 376 | b_trace_test_components2([component(Pred,ComponentVars)|T],ConstantsState,TypedVals,RelevantVars,DoNotEnumVars, | |
| 377 | Nr,NextNr,ResWF,OuterWF) :- | |
| 378 | N1 is Nr+1, | |
| 379 | ( RelevantVars\=all, ComponentVars\= all, | |
| 380 | ComponentVars \= [], % a component without identifiers (e.g., 1=0 after propagating x=1) is always relevant | |
| 381 | lists_are_disjoint(RelevantVars,ComponentVars) | |
| 382 | -> print_trace_message(skipping_irrelevant_component(Nr,ComponentVars)), | |
| 383 | b_trace_test_components2(T,ConstantsState,TypedVals,RelevantVars,DoNotEnumVars,N1,NextNr,ResWF,OuterWF) | |
| 384 | ; %% print(checking_component_properties(Nr,ComponentVars)),nl, %% | |
| 385 | %% print(component(Nr)),nl, translate:nested_print_bexpr_as_classicalb(Pred),debug:nl_time, | |
| 386 | ResWF = [wf_comp(WF,Nr)|TWF], | |
| 387 | init_wait_flags(WF0,[wf_comp(Nr)]), | |
| 388 | copy_wait_flag_call_stack_info(OuterWF,WF0,WF), | |
| 389 | (preferences:preference(use_chr_solver,true) -> attach_chr_integer_inequality_to_wf_store(WF) ; true), | |
| 390 | (ComponentVars=all | |
| 391 | -> InTypedVals=TypedVals, OutTypedVals=[], ProjectedState=ConstantsState | |
| 392 | ; project_typed_vals(TypedVals,ComponentVars,InTypedVals,OutTypedVals), | |
| 393 | project_state(ConstantsState,ComponentVars,ProjectedState) | |
| 394 | % relevant, e.g., for exists which may wait on state becoming ground | |
| 395 | ), | |
| 396 | observe_state(InTypedVals,WF,Nr), %% | |
| 397 | reset_tracetest_for_component, | |
| 398 | predicate_level_optimizations(Pred,OPred), | |
| 399 | ? | b_tracetest_boolean_expression(OPred,[],ProjectedState,WF,Nr), |
| 400 | observe_state_finished(InTypedVals,WF,Nr), | |
| 401 | % Skipping can only occur in this call above, not in enumeration phase | |
| 402 | (skipped_unsat_conjunct(FalseOrUnknown) | |
| 403 | -> store_unsat_component_nr(Nr,FalseOrUnknown), % can be unknown due to an enumeration warning, cf. test 1390 | |
| 404 | % print('UNSAT: '),translate:nested_print_bexpr(Pred),nl,nl, | |
| 405 | allow_skipping_over_components % check if we allow skipping over unsat components to | |
| 406 | % maybe find as many values for constants as possible (partial setup_constants),... | |
| 407 | % Note: in Disprover mode or solve_predicate (REPL) we can stop and fail straightaway | |
| 408 | ; %print_bt_message(setup_enumerating_constants(Nr)), %%(TypedVals)), %% | |
| 409 | b_tighter_enumerate_values(InTypedVals,DoNotEnumVars,WF), | |
| 410 | (preferences:get_preference(disprover_mode,false) -> true | |
| 411 | ? | ; ground_wait_flag0(WF) % ensure that we give each component the chance to run WF0 inconsistency checks |
| 412 | %, print(finished_wf0_grounding_in_disprover_mode(Nr)),nl | |
| 413 | ) | |
| 414 | ), | |
| 415 | % we could ground waitflag 1 (deterministic computations) ? | |
| 416 | ? | b_trace_test_components2(T,ConstantsState,OutTypedVals,RelevantVars,DoNotEnumVars,N1,NextNr,TWF,OuterWF) |
| 417 | ). | |
| 418 | ||
| 419 | ||
| 420 | l_ground_wait_flags(WF) :- | |
| 421 | ? | l_ground_wait_flags(WF,WFE,Result), |
| 422 | (Result=false | |
| 423 | -> (!,fail) % Cut: to prevent backtracking to find other solutions for earlier components ! | |
| 424 | % Assumption: each component is independent and finding other solution for earlier component would again lead to failure in last component checked by l_ground_wait_flags/2 | |
| 425 | ; grd_ef(WFE)). | |
| 426 | ||
| 427 | l_ground_wait_flags([],_,true). | |
| 428 | l_ground_wait_flags([wf_comp(_,ComponentNr)|TWF],WFE,SatResult) :- | |
| 429 | unsat_component(ComponentNr,_),!, % We no longer try and ground unknown components | |
| 430 | l_ground_wait_flags(TWF,WFE,SatResult). | |
| 431 | l_ground_wait_flags([wf_comp(WF,ComponentNr)|TWF],WFE,SatResult) :- | |
| 432 | (debug_mode(off) -> true ; write(grounding_component(ComponentNr)),nl, start_ms_timer(Timer)), | |
| 433 | % print_bt_message(grounding_component(ComponentNr)), portray_waitflags(WF),nl, %% | |
| 434 | % maybe we should set up new error scope ? <--- TO DO | |
| 435 | ? | if(ground_constraintprop_wait_flags(WF), |
| 436 | ((pending_abort_error(WF) -> assert_unsat_component_abort_error(ComponentNr) ; true), | |
| 437 | (debug_mode(on) -> (pending_abort_error(WF) -> Msg='PENDING WD/ABORT ERROR'; Msg='true'), | |
| 438 | stop_ms_timer_with_msg(Timer,component(ComponentNr,Msg)) | |
| 439 | ; true), | |
| 440 | get_enumeration_finished_wait_flag(WF,WFE), % bind enumeration finished to the global outer WFE flag | |
| 441 | ? | l_ground_wait_flags(TWF,WFE,SatResult) % continue with other components |
| 442 | ), | |
| 443 | ((debug_mode(on) -> stop_ms_timer_with_msg(Timer,component(ComponentNr,'false_or_unknown')) ; true), | |
| 444 | store_unsat_component_nr(ComponentNr), | |
| 445 | SatResult=false)). | |
| 446 | ||
| 447 | project_typed_vals([],_,[],[]). | |
| 448 | project_typed_vals([typedval(Val,Type,VarID,EnumWarningInfos)|Rest],ComponentVars,In,Out) :- | |
| 449 | ? | (member(VarID,ComponentVars) |
| 450 | -> In = [typedval(Val,Type,VarID,EnumWarningInfos)|In2], Out2=Out | |
| 451 | ; Out = [typedval(Val,Type,VarID,EnumWarningInfos)|Out2], In2=In | |
| 452 | ), project_typed_vals(Rest,ComponentVars,In2,Out2). | |
| 453 | project_state([],_,[]). | |
| 454 | project_state([bind(VarID,Value)|Rest],ComponentVars,Out) :- | |
| 455 | ? | (member(VarID,ComponentVars) |
| 456 | -> Out=[bind(VarID,Value)|Out2] | |
| 457 | ; Out=Out2 | |
| 458 | ), project_state(Rest,ComponentVars,Out2). | |
| 459 | ||
| 460 | ||
| 461 | :- use_module(specfile,[get_specification_description/2]). | |
| 462 | :- use_module(state_packing,[pack_value/2,unpack_value/2]). | |
| 463 | :- volatile det_solution_for_constant_packed/2. | |
| 464 | :- dynamic det_solution_for_constant_packed/2. | |
| 465 | assert_det_solution_for_constant(Var,Val) :- | |
| 466 | (do_not_store_large_value(Val) -> PVal = '$TOO_LARGE' ,debug_println(4,not_storing_large_det_value(Var)) | |
| 467 | ; pack_value(Val,PVal) | |
| 468 | %,translate:translate_bvalue_with_limit(Val,200,VS),format(' STORING ---> ~w = ~w~n',[Var,VS]) | |
| 469 | ), | |
| 470 | assertz(det_solution_for_constant_packed(Var,PVal)). | |
| 471 | ||
| 472 | det_solution_for_constant(Var,Val) :- | |
| 473 | if(det_solution_for_constant_packed(Var,PVal), | |
| 474 | unpack_det_sol(Var,PVal,Val), | |
| 475 | (get_specification_description(properties,PROPS), | |
| 476 | ajoin([PROPS, ' are *not* true and no value was found (deterministically) for the following CONSTANT: '], Msg), | |
| 477 | add_message(det_value_not_found_for_constant,Msg,Var), | |
| 478 | fail) | |
| 479 | ). | |
| 480 | unpack_det_sol(Var,PVal,Val) :- | |
| 481 | (PVal = '$TOO_LARGE' | |
| 482 | -> ajoin(['The following CONSTANT was not stored due to its size (set preference ALLOW_INCOMPLETE_SETUP_CONSTANTS to TRUE to store all constants found): '], Msg), | |
| 483 | add_message(det_value_not_stored_for_constant,Msg,Var), | |
| 484 | fail | |
| 485 | ; unpack_value(PVal,Val) | |
| 486 | ). | |
| 487 | ||
| 488 | :- use_module(probsrc(translate), [translate_bvalue_kind/2]). | |
| 489 | get_det_solution_for_constant_value_kind(Var,ValKind) :- | |
| 490 | det_solution_for_constant_packed(Var,PVal), | |
| 491 | (PVal = '$TOO_LARGE' -> ValKind='LARGE-VALUE' | |
| 492 | ; unpack_value(PVal,Val), | |
| 493 | (translate_bvalue_kind(Val,K) -> ValKind=K ; ValKind='UNKNOWN-VALUE') | |
| 494 | ). | |
| 495 | ||
| 496 | det_solution_for_constant_was_stored :- (det_solution_for_constant_was_stored(_) -> true). | |
| 497 | det_solution_for_constant_was_stored(Var) :- det_solution_for_constant_packed(Var,_). | |
| 498 | ||
| 499 | :- use_module(probsrc(bsyntaxtree),[map_over_bexpr/2]). | |
| 500 | :- use_module(avl_tools,[avl_height_less_than/2, avl_fetch_root/2]). | |
| 501 | :- use_module(tools_lists,[length_greater/2]). | |
| 502 | :- assert_must_succeed((findall(int(X),between:between(1,2000,X),IL),custom_explicit_sets:convert_to_avl(IL,A), | |
| 503 | b_interpreter_components:value_too_large(freeval(t,c,A)))). | |
| 504 | :- assert_must_fail((custom_explicit_sets:convert_to_avl([int(1)],A), | |
| 505 | b_interpreter_components:value_too_large(freeval(t,c,A)))). | |
| 506 | :- assert_must_succeed((findall(int(X),between:between(1,600,X),L), % long list (also in TRACE_INFO mode) | |
| 507 | b_interpreter_components:value_too_large(L))). | |
| 508 | :- assert_must_fail(b_interpreter_components:value_too_large([int(1),int(2)])). | |
| 509 | :- assert_must_succeed((findall(int(X),between:between(1,2000,X),IL),custom_explicit_sets:convert_to_avl(IL,A), | |
| 510 | b_interpreter_components:value_too_large([A,int(1)]))). % short list with large first element | |
| 511 | :- assert_must_succeed((findall(int(X),between:between(1,2000,X),IL),custom_explicit_sets:convert_to_avl(IL,A), | |
| 512 | custom_explicit_sets:convert_to_avl([A],S), | |
| 513 | b_interpreter_components:value_too_large(S))). % small set with large root element | |
| 514 | :- assert_must_fail((findall(int(X),between:between(1,2000,X),IL),custom_explicit_sets:convert_to_avl(IL,A), | |
| 515 | preferences:call_with_preference(b_interpreter_components:do_not_store_large_value(A), | |
| 516 | allow_incomplete_partial_setup_constants,true))). | |
| 517 | ||
| 518 | do_not_store_large_value(X) :- | |
| 519 | preference(allow_incomplete_partial_setup_constants,false), %if true we always store the value | |
| 520 | value_too_large(X). | |
| 521 | ||
| 522 | value_too_large(V) :- var(V),!,fail. % should not happen | |
| 523 | value_too_large(avl_set(A)) :- | |
| 524 | (preference(provide_trace_information,false) -> MaxH=7 ; MaxH=9), | |
| 525 | (avl_height_less_than(A,MaxH) | |
| 526 | -> avl_fetch_root(A,RootElement), | |
| 527 | value_too_large(RootElement) % Just check size of root element; but there could be other bigger ones | |
| 528 | ; true). % set large | |
| 529 | ||
| 530 | value_too_large([H|T]) :- | |
| 531 | ((preference(provide_trace_information,false) -> length_greater(T,127) ; length_greater(T,511)) | |
| 532 | -> true ; value_too_large(H)). % just check if first element is too large; but there could be other large ones | |
| 533 | value_too_large((A,B)) :- (value_too_large(A) -> true ; value_too_large(B)). | |
| 534 | value_too_large(rec(F)) :- member(field(_,FVal),F), value_too_large(FVal). | |
| 535 | value_too_large(freeval(_ID,_Case,Value)) :- value_too_large(Value). | |
| 536 | value_too_large(closure(P,T,B)) :- | |
| 537 | \+ custom_explicit_sets:is_interval_closure(P,T,B,_,_), | |
| 538 | uses_large_value(B). | |
| 539 | % we can have large symbolic closures; cf PlanProGross.mch; see also test 1637 | |
| 540 | ||
| 541 | % assumes values are all ground: | |
| 542 | uses_large_value_aux(value(V)) :- value_too_large(V). | |
| 543 | ||
| 544 | uses_large_value(BExpr) :- | |
| 545 | map_over_bexpr(uses_large_value_aux,BExpr). | |
| 546 | ||
| 547 | ||
| 548 | :- use_module(tools_printing,[print_value_summary/1]). | |
| 549 | :- use_module(probsrc(translate), [translate_bvalue_to_codes_with_limit/3]). | |
| 550 | print_found_value(Val) :- debug_level_active_for(19),!,print_value_summary(Val). | |
| 551 | print_found_value(Val) :- translate_bvalue_to_codes_with_limit(Val,100,C), format(user_output,'~s',[C]). | |
| 552 | ||
| 553 | reset_observe_state :- retractall(det_solution_for_constant_packed(_,_)). | |
| 554 | ||
| 555 | observe_state(Env,WF,ComponentNr) :- | |
| 556 | (debug_mode(off) -> true | |
| 557 | ; length(Env,NrVal), | |
| 558 | format('-->> start processing component (~w) with ~w identifier(s)~n',[ComponentNr,NrVal])), | |
| 559 | get_wait_flag0(WF,WF0), get_wait_flag1(observe_state,WF,WF1), | |
| 560 | observe_state2(Env,WF0,WF1). | |
| 561 | ||
| 562 | observe_state_finished(Env,WF,ComponentNr) :- | |
| 563 | (preferences:get_preference(provide_trace_information,true) | |
| 564 | -> get_wait_flag0(WF,WF0), | |
| 565 | when((ground(Env);nonvar(WF0)),print_success(WF0,ComponentNr,Env,WF)) | |
| 566 | %% ,when(nonvar(WF1),(nl, print('Starting Phase 1'),nl, portray_waitflags(WF))) | |
| 567 | ; true). | |
| 568 | ||
| 569 | :- use_module(debug,[debug_format/3]). | |
| 570 | print_success(WF0,ComponentNr,_,_WF) :- nonvar(WF0),!, | |
| 571 | debug_format(19,'~n-->> WF0 for component (~w) grounded.~n',[ComponentNr]). | |
| 572 | print_success(_,ComponentNr,Env,_WF) :- | |
| 573 | (Env=[] | |
| 574 | -> | |
| 575 | format('~n-->> SUCCESS; processed component w/o identifiers (~w)~n',[ComponentNr]) | |
| 576 | ; Env = [typedval(_,_,Var,_)] -> | |
| 577 | format('~n-->> SUCCESS; only identifier ~w valued in component (~w)~n',[Var,ComponentNr]) | |
| 578 | ; length(Env,NrVal), | |
| 579 | format('~n-->> SUCCESS; all ~w identifier(s) valued in component (~w)~n',[NrVal,ComponentNr]) | |
| 580 | ), | |
| 581 | (debug_mode(on) | |
| 582 | -> findall(V,member(typedval(_,_,V,_),Env),Vars), | |
| 583 | statistics(walltime,[W,_]), format('-->> (walltime: ~w ms) : identifiers = ~w~n',[W,Vars]) | |
| 584 | ; true), | |
| 585 | %%,check_for_multiple_solutions(WF,ComponentNr) %% comment in to check for multiple solutions | |
| 586 | nl. | |
| 587 | ||
| 588 | observe_state2([],_,_). | |
| 589 | observe_state2([Binding|T],WF0,WF1) :- get_binding_value(Binding,VarID,Val), | |
| 590 | observe_variable(VarID,Val,WF0,WF1),observe_state2(T,WF0,WF1). | |
| 591 | ||
| 592 | get_binding_value(bind(Id,Value),Id,Value). | |
| 593 | get_binding_value(typedval(Value,_Type,Id,_Trigger),Id,Value). | |
| 594 | ||
| 595 | % print a warning message if we find multiple solutions *after* all constants have been valued | |
| 596 | %:- public check_for_multiple_solutions/2. | |
| 597 | %check_for_multiple_solutions(WF,ComponentNr) :- get_enumeration_finished_wait_flag(WF,EWF), | |
| 598 | % retractall(solution_found(ComponentNr,_)), | |
| 599 | % add_solution(EWF,ComponentNr). | |
| 600 | %:- volatile solution_found/2. | |
| 601 | %:- dynamic solution_found/2. | |
| 602 | %:- block add_solution(-,?). | |
| 603 | %add_solution(_,ComponentNr) :- retract(solution_found(ComponentNr,Nr)),!, | |
| 604 | % print('*** Multiple solutions found *after valuation* for component '), print(ComponentNr),nl, | |
| 605 | % N1 is Nr+1, | |
| 606 | % print('*** Solution: '),print(N1),nl, | |
| 607 | % assertz(solution_found(ComponentNr,N1)). | |
| 608 | %add_solution(_,ComponentNr) :- | |
| 609 | % assertz(solution_found(ComponentNr,1)). | |
| 610 | ||
| 611 | observe_variable(Var,Val,WF0,_WF1) :- preferences:get_preference(provide_trace_information,false),!, | |
| 612 | observe_variable_no_trace(Var,Val,WF0). | |
| 613 | observe_variable(Var,Val,WF0,WF1) :- | |
| 614 | ground_value_check(Val,GrVal), | |
| 615 | observe_variable0_block(Var,Val,GrVal,WF0,WF1). | |
| 616 | :- block observe_variable0_block(?,?,-,-,?). | |
| 617 | observe_variable0_block(Var,Val,GrVal,WF0,WF1) :- | |
| 618 | (var(GrVal) -> write(' :?: '), write(Var), write(' '), print_found_value(Val), | |
| 619 | observe_variable1(Var,Val,WF1) | |
| 620 | ; (var(WF0) -> write('-->> ') | |
| 621 | ; write('--0-->> ')), % WF0/GrVal grounded at same time probably does not happen (often) | |
| 622 | write(Var),nl, write(' '),print_found_value(Val),print_walltime,nl, | |
| 623 | assert_det_solution_for_constant(Var,Val) | |
| 624 | ). | |
| 625 | :- use_module(kernel_tools,[ground_value/1,ground_value_check/2]). | |
| 626 | :- block observe_variable_no_trace(?,-,-). | |
| 627 | observe_variable_no_trace(Var,Val,WF0) :- nonvar(WF0),!, % important e.g. for test 1368 | |
| 628 | (ground_value(Val) -> assert_det_solution_for_constant(Var,Val) ; true). | |
| 629 | observe_variable_no_trace(Var,Val,WF0) :- ground_value_check(Val,GV), | |
| 630 | %tools_printing:print_term_summary(gr_val_check(Var,Val,GV)),nl, | |
| 631 | observe_variable_no_trace4(Var,GV,Val,WF0). | |
| 632 | :- block observe_variable_no_trace4(?,-,?,-). | |
| 633 | observe_variable_no_trace4(_,GV,_,_) :- var(GV),!. | |
| 634 | observe_variable_no_trace4(Var,_,Val,_) :- assert_det_solution_for_constant(Var,Val). % this could be expensive !? | |
| 635 | ||
| 636 | print_walltime :- statistics(walltime,[Tot,Delta]), | |
| 637 | (debug_mode(on) -> print(' '),tools:print_memory_used_wo_gc ; true), | |
| 638 | format(' ~w ms (Delta ~w ms) ',[Tot,Delta]). | |
| 639 | ||
| 640 | observe_variable1(Var,Val,WF1) :- ground_value_check(Val,GV), | |
| 641 | observe_variable1_block(Var,Val,WF1,GV). | |
| 642 | :- block observe_variable1_block(?,?,-,-). | |
| 643 | observe_variable1_block(Var,Val,_WF1,GV):- | |
| 644 | (nonvar(GV) | |
| 645 | -> write('--1-->> '), write(Var),nl, write(' '),print_found_value(Val), | |
| 646 | assert_det_solution_for_constant(Var,Val) | |
| 647 | ; write(' :?1?: '), write(Var), write(' '), print_found_value(Val) | |
| 648 | %% , when(ground(Val), (print('--ground-->> '),print(Var),print(' '), print_found_value(Val))) % comment in to see grounding | |
| 649 | %% , external_functions:observe_state([bind(Var,Val)]) % comment in to observe values | |
| 650 | %% , translate:print_bstate([bind(Var,Val)]),nl % comment in to print full value with CLP(FD) info | |
| 651 | ). | |
| 652 | ||
| 653 | ||
| 654 | % -------------------- | |
| 655 | ||
| 656 | construct_optimized_exists(Parameters,Body,Pred) :- | |
| 657 | construct_optimized_exists(Parameters,Body,Pred,true,_). | |
| 658 | construct_optimized_exists(Parameters,Body,Pred,Simplify) :- | |
| 659 | construct_optimized_exists(Parameters,Body,Pred,Simplify,_). | |
| 660 | ||
| 661 | % we could also partition inside b_interpreter ? | |
| 662 | construct_optimized_exists(Parameters,Body,Pred,Simplify,NrComponents) :- | |
| 663 | % we can actually do more: first project out all conjuncts which do not have any variables in common with Parameters | |
| 664 | % #x.(P(x) & Q) <=> #x.(P(x)) & Q | |
| 665 | % we can also use a stronger version of predicate components #(x,y).( P(x,v) & Q(v,y)) <=> #(x).P(x,v) & #(y).Q(v,y) | |
| 666 | get_texpr_ids(Parameters,PIDs), | |
| 667 | %print(constructing_optimized_exists(PIDs)),nl, | |
| 668 | LocalVars = PIDs, | |
| 669 | predicate_components_with_restriction(Body,LocalVars,PIDs,Components0), % we focus partition decision on PIDs, not on all identifiers | |
| 670 | %length(Components,Len), print(nr_of_components_for_exists(Len,Components)),nl, | |
| 671 | (wd_safe_component_order(Body,Components0) -> Components=Components0 | |
| 672 | ; Components=[component(Body,PIDs)]), % do not split: splitting would evaluate a conjunct before its WD guard | |
| 673 | conjunct_components(Components,Parameters,Pred,Simplify,NrComponents). | |
| 674 | ||
| 675 | % check that conjoining the components in order does not move a conjunct with a WD condition | |
| 676 | % in front of a conjunct that preceded it in the original body, | |
| 677 | % e.g., #x.(x:1..2 & s:seq(INTEGER) & first(s)=x) must not become #x.(x:1..2 & first(s)=x) & s:seq(INTEGER) | |
| 678 | % we do not use always_well_defined_or_wd_reorderings_allowed: allow_improving_wd_mode permits reorderings | |
| 679 | % that improve well-definedness, but moving a conjunct before its guard would worsen it | |
| 680 | wd_safe_component_order(Body,Components) :- | |
| 681 | conjunction_to_list(Body,Conjuncts), | |
| 682 | (maplist(always_well_defined_or_disprover_mode,Conjuncts) -> true | |
| 683 | ; findall(P,(member(component(CP,_),Components), conjunction_to_list(CP,CL), member(P,CL)),NewOrder), | |
| 684 | positions_in_list(NewOrder,Conjuncts,Positions), | |
| 685 | wd_safe_positions(NewOrder,Positions,[]) | |
| 686 | ). | |
| 687 | ||
| 688 | % get the position of each new conjunct in the original list of conjuncts; fails if a conjunct is not found | |
| 689 | positions_in_list([],_,[]). | |
| 690 | positions_in_list([P|T],Conjuncts,[Pos|PT]) :- | |
| 691 | ? | nth1(Pos,Conjuncts,C), C==P, !, |
| 692 | positions_in_list(T,Conjuncts,PT). | |
| 693 | ||
| 694 | % a conjunct with a WD condition at original position Pos must come after all conjuncts at positions < Pos | |
| 695 | wd_safe_positions([],[],_). | |
| 696 | wd_safe_positions([P|T],[Pos|PT],Seen) :- | |
| 697 | (always_well_defined_or_disprover_mode(P) -> true | |
| 698 | ; include(lt(Pos),Seen,SeenBefore), % positions are distinct: all of 1..Pos-1 seen iff Pos-1 of them seen | |
| 699 | length(SeenBefore,Len), Len is Pos-1), | |
| 700 | wd_safe_positions(T,PT,[Pos|Seen]). | |
| 701 | lt(Pos,X) :- X < Pos. | |
| 702 | % print('* EXISTS: '),translate:print_bexpr(Pred),nl. | |
| 703 | ||
| 704 | :- use_module(bsyntaxtree). | |
| 705 | conjunct_components(C,Parameters,Res,Simplify,NrComponents) :- | |
| 706 | conjunct_components2(C,Parameters,List,Simplify,0,NrComponents), | |
| 707 | conjunct_predicates_with_pos_info(List,Res). | |
| 708 | ||
| 709 | conjunct_components2([],_Parameters,[],_,Nr,Nr). % :- (Parameters=[] -> true ; print(unused_existential_var(Parameters)),nl). | |
| 710 | conjunct_components2([component(Pred,ComponentVars)|T],Parameters,Res,Simplify,InNr,OutNr) :- | |
| 711 | augment_ids(ComponentVars,CV), % translate atomic id names into b(identifier(... | |
| 712 | tools:list_intersection(CV,Parameters,ExistParas), % TO DO: use ordsets | |
| 713 | (Simplify=true | |
| 714 | -> create_and_simplify_exists(ExistParas,Pred,EP) % no use in recursively calling construct_optimized_exists | |
| 715 | ; Simplify= no_cleanup_and_simplify | |
| 716 | -> create_exists(ExistParas,Pred,EP0), % avoid loops when called from ast_cleanup | |
| 717 | get_texpr_info(EP0,AllInfos0), | |
| 718 | (nonmember(nodeid(_),AllInfos0),ExistParas=[Par1|_] | |
| 719 | -> get_texpr_info(Par1,AllInfos1),extract_pos_infos(AllInfos1,PIs) % try and get position from ids | |
| 720 | ; PIs=[]), % we already have a position info | |
| 721 | add_texpr_infos(EP0,[partitioned_exists|PIs],EP) % add ,removed_typing ?? | |
| 722 | ; create_unsimplified_exists(ExistParas,Pred,EP) | |
| 723 | ), | |
| 724 | (EP=b(truth,pred,[]) % or should we allow _ for Info field ?? | |
| 725 | -> Res=TRes | |
| 726 | ; Res=[EP|TRes]), | |
| 727 | In1 is InNr+1, | |
| 728 | conjunct_components2(T,Parameters,TRes,Simplify,In1,OutNr). | |
| 729 | ||
| 730 | ||
| 731 | % translate a list of atomic ides into ids with the b/3 wrapper | |
| 732 | augment_ids([],[]). | |
| 733 | augment_ids([ID|T],[b(identifier(ID),_,_)|TT]) :- augment_ids(T,TT). | |
| 734 | ||
| 735 | % extract and inline simple equalities to remove quantified variables; useful for exists and forall | |
| 736 | % TO DO: move to b_quantifier_optimizations.pl or similar | |
| 737 | extract_equalities_in_quantifier(Parameters,Pred, ReducedParas,OutPred) :- | |
| 738 | extract_equalities2(Pred,Parameters,ReducedParas,NewPred,[],Subst), | |
| 739 | %sort(Subst,SortedSubst), | |
| 740 | %print(extracted(Subst)),nl, | |
| 741 | apply_subst(Subst,NewPred,OutPred). | |
| 742 | % apply equality inside expressions: note: this may duplicate expressions ! | |
| 743 | % However, it also works if the equalities contain parameters | |
| 744 | ||
| 745 | :- use_module(bsyntaxtree,[is_equality/3]). | |
| 746 | ||
| 747 | extract_equalities2(b(conjunct(A,B),pred,Info),Ids,RemIds,Res) --> !, | |
| 748 | {Res=b(conjunct(PA,PB),pred,Info)}, | |
| 749 | extract_equalities2(A, Ids,RemIds1,PA), | |
| 750 | extract_equalities2(B,RemIds1,RemIds,PB). | |
| 751 | extract_equalities2(TEqual,Ids,RemIds,NewPred,InSubst,OutSubst) :- | |
| 752 | is_equality(TEqual,ID,E), | |
| 753 | % TODO: we could try and split equalities if possible; usually this is done by ast_cleanup though? | |
| 754 | %(bsyntaxtree:split_equality(TEqual,A,B) -> nl,print('COULD BE SPLIT: '),translate:print_bexpr(TEqual),nl ; true), | |
| 755 | same_id_is_member(ID,Ids,SID,RemIds), | |
| 756 | %\+ occurs_in_expr(SID,E), % not cyclic; we check it again after applyng InSubst to E below | |
| 757 | \+ in_subst_dom(SID,InSubst), % ensure we don't already have an equation for the same ID | |
| 758 | compose_with_subst(InSubst,SID,E,OutSubst), % we can compose with existing substitution without occurs-check problem | |
| 759 | always_well_defined_or_disprover_mode(E), % otherwise we may move evaluation of E forward ! | |
| 760 | !, | |
| 761 | NewPred=b(truth,pred,[]). | |
| 762 | extract_equalities2(X,Ids,Ids,X) --> []. | |
| 763 | ||
| 764 | ||
| 765 | ||
| 766 | % compose a new binding Var/Expr with existing substitution Subst; where Subst was not yet applied to Expr | |
| 767 | compose_with_subst(Subst,Var,Expr,[Var/NewExpr|ModSubst]) :- | |
| 768 | apply_subst(Subst,Expr,NewExpr), | |
| 769 | \+ occurs_in_expr(Var,NewExpr), % otherwise cyclic | |
| 770 | apply_binding_to_substitution(Subst,Var,NewExpr,ModSubst). | |
| 771 | apply_binding_to_substitution([],_,_,[]). | |
| 772 | apply_binding_to_substitution([TV/TE|T],Var,Expr,[TV/TE2|NT]) :- | |
| 773 | \+ occurs_in_expr(TV,Expr), % otherwise we get a cyclic substitution --> fail | |
| 774 | replace_id_by_expr(TE,Var,Expr,TE2), | |
| 775 | apply_binding_to_substitution(T,Var,Expr,NT). | |
| 776 | ||
| 777 | apply_subst([],X,X). | |
| 778 | apply_subst([Var/Expr|T],E,NewE) :- | |
| 779 | (replace_id_by_expr(E,Var,Expr,E2) % replace identifier Var by expression Expr | |
| 780 | -> %apply_to_tail(T,Var,Expr,NT), % apply binding to tail of substitution | |
| 781 | apply_subst(T,E2,NewE) | |
| 782 | ; add_internal_error('Call failed: ',apply_subst([Var/Expr|T],E,NewE)),NewE=E). | |
| 783 | ||
| 784 | ||
| 785 | in_subst_dom(X,[I/_|T]) :- (X=I -> true ; in_subst_dom(X,T)). | |
| 786 | ||
| 787 | same_id_is_member(X,[H|T],SID,Rest) :- | |
| 788 | (same_id(X,H,SID) -> Rest=T ; Rest=[H|TR],same_id_is_member(X,T,SID,TR)). | |
| 789 | ||
| 790 | % TO DO: investigate what is the exact difference with create_exists_opt; partition into components is only done by construct_optimized_exists/3 | |
| 791 | create_and_simplify_exists(Paras,Pred,ResultingPred) :- | |
| 792 | extract_equalities_in_quantifier(Paras,Pred,NewParas,NewPred), | |
| 793 | create_and_simplify_exists2(NewParas,NewPred,ResultingPred). | |
| 794 | ||
| 795 | %:- use_module(b_interpreter_check,[arithmetic_op/4]). % TODO REFACTOR and move this and code below to separate module | |
| 796 | create_and_simplify_exists2([],Pred,R) :- !,R=Pred. | |
| 797 | % simplify #ID.(ID:E1 & ID:E2) <=> E1 /\ E2 /= {} , etc... now done in ast_cleanup | |
| 798 | % simplify #ID.(ID/:E) <=> E /= FullType also done in ast_cleanup | |
| 799 | % simplify #SID.(SID > Expr) <=> truth now done in ast_cleanup | |
| 800 | create_and_simplify_exists2(Parameters,Body,Res) :- create_unsimplified_exists(Parameters,Body,Res). | |
| 801 | % TO DO: treat nested exists | |
| 802 | ||
| 803 | ||
| 804 | ||
| 805 | :- use_module(b_ast_cleanup,[clean_up_pred/3]). | |
| 806 | :- use_module(bsyntaxtree,[add_texpr_info_if_new/3]). | |
| 807 | create_unsimplified_exists(Parameters,Body,Res) :- | |
| 808 | maplist(mark_generated_exists,Parameters,Para2), % mark that this is an artificially constructed; we now mark the exists | |
| 809 | create_exists(Para2,Body,Res1), | |
| 810 | add_texpr_info_if_new(Res1,removed_typing,Res2), % unconditionally add this info, avoid generating warnings in exists_body_warning, see test 625 | |
| 811 | % and avoid useless_let_message | |
| 812 | % previously removed_typing was only added for disjuncts or implications | |
| 813 | clean_up_pred(Res2,[],Res). % also computes used_ids, | |
| 814 | % and performs some existential quantifier optimisations like replace_exists_by_not_empty | |
| 815 | ||
| 816 | mark_generated_exists(TID1,TID2) :- add_texpr_info_if_new(TID1,generated_exists_parameter,TID2). |