diff --git a/.clang-tidy b/.clang-tidy index 568eae5eb..19f2849a7 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -421,4 +421,3 @@ CheckOptions: - key: llvm-else-after-return.WarnOnUnfixable value: 'false' ... - diff --git a/CHANGES.md b/CHANGES.md index 915ed6910..00eea2b0b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -346,7 +346,7 @@ ## gringo/clingo 4.2 - * added clingo + * added clingo * supports very flexible scripting support * can cover iclingo and oclingo functionality now * added stack traces to lua error messages diff --git a/CMakeLists.txt b/CMakeLists.txt index 82b72b6f3..3733bea95 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -324,4 +324,3 @@ if (NOT CLINGO_BUILD_STATIC AND (CLINGO_BUILD_SHARED OR Python_Development_FOUND set_target_properties(${target} PROPERTIES POSITION_INDEPENDENT_CODE ON) endforeach() endif() - diff --git a/app/clingo/main.cc b/app/clingo/main.cc index c7455c147..d08159d86 100644 --- a/app/clingo/main.cc +++ b/app/clingo/main.cc @@ -23,10 +23,10 @@ // }}} #ifdef CLINGO_WITH_PYTHON -# include +#include #endif #ifdef CLINGO_WITH_LUA -# include +#include #endif #include @@ -34,19 +34,18 @@ extern "C" CLINGO_VISIBILITY_DEFAULT int clingo_main_(int argc, char *argv[]); -int main(int argc, char** argv) { -# ifdef CLINGO_WITH_PYTHON +int main(int argc, char **argv) { +#ifdef CLINGO_WITH_PYTHON if (!clingo_register_python_()) { std::cerr << clingo_error_message() << std::endl; return 1; } -# endif -# ifdef CLINGO_WITH_LUA +#endif +#ifdef CLINGO_WITH_LUA if (!clingo_register_lua_(nullptr)) { std::cerr << clingo_error_message() << std::endl; return 1; } -# endif +#endif return clingo_main_(argc, argv); } - diff --git a/app/clingo/tests/lp/aggregates.lp b/app/clingo/tests/lp/aggregates.lp index 40d674880..92307cab6 100644 --- a/app/clingo/tests/lp/aggregates.lp +++ b/app/clingo/tests/lp/aggregates.lp @@ -31,8 +31,8 @@ asstwo(S,u):-arg(S),ass(S,u),saturate. sattwo(S):-arg(S),ass(S,u),saturate. :-not saturate. #show ass/2. - + :-ass(s1, 0),ass(s2, 0),ass(s3, 0). :-ass(s1, 1),ass(s2, 0),ass(s3, 1). - -%unfounded: saturate, asstwo(s1,0), asstwo(s1,0) \ No newline at end of file + +%unfounded: saturate, asstwo(s1,0), asstwo(s1,0) diff --git a/app/clingo/tests/lp/elevator.lp b/app/clingo/tests/lp/elevator.lp index b56bd775d..9389307a3 100644 --- a/app/clingo/tests/lp/elevator.lp +++ b/app/clingo/tests/lp/elevator.lp @@ -80,6 +80,3 @@ x(A,D,t) :- h(a(A,F),t-1), o(A,G+D,D), p(A,D), i(a(A,G)), D*F < D*G, #show. #show h/2. - - - diff --git a/app/clingo/tests/lp/project.lp b/app/clingo/tests/lp/project.lp index 09284d2c1..8d9d8cd19 100644 --- a/app/clingo/tests/lp/project.lp +++ b/app/clingo/tests/lp/project.lp @@ -3,5 +3,3 @@ 1 { p(1..2) } 1. 1 { q(1..2) } 1. - - diff --git a/app/clingo/tests/lp/show.lp b/app/clingo/tests/lp/show.lp index 804cdda78..6d9c797ad 100644 --- a/app/clingo/tests/lp/show.lp +++ b/app/clingo/tests/lp/show.lp @@ -13,4 +13,3 @@ q(k+1), k < 3. {show} :- k == 3. #show p(1..4) : show, k == 3. - diff --git a/app/clingo/tests/lua/add_minimize.lp b/app/clingo/tests/lua/add_minimize.lp index 8f1bd0383..e7b2bf4d1 100644 --- a/app/clingo/tests/lua/add_minimize.lp +++ b/app/clingo/tests/lua/add_minimize.lp @@ -31,4 +31,3 @@ end 2 { a; b; c }. 2 { b; c; d }. - diff --git a/app/clingo/tests/lua/add_weight.lp b/app/clingo/tests/lua/add_weight.lp index fbe59fbe2..1bbcc71fc 100644 --- a/app/clingo/tests/lua/add_weight.lp +++ b/app/clingo/tests/lua/add_weight.lp @@ -28,4 +28,3 @@ end #end. { a; b; c }. - diff --git a/app/clingo/tests/lua/conformant1.lp b/app/clingo/tests/lua/conformant1.lp index 9d35ae40d..9ea467740 100644 --- a/app/clingo/tests/lua/conformant1.lp +++ b/app/clingo/tests/lua/conformant1.lp @@ -1,4 +1,4 @@ -#script (lua) +#script (lua) function main(prg) local step = 0 local check = false @@ -29,7 +29,7 @@ function main(prg) if ret.satisfiable then break end - else + else break end end @@ -60,7 +60,7 @@ contradict(F) :- complement(F,L,M), effect(A,L,N1), effect(A,M,N2), { holds(F,0) } :- complement(F,L,M), not initially(L), not initially(M). holds(F,0) :- initially(L), complement(F,L,M). -holds_oneof(N,B) :- +holds_oneof(N,B) :- initially_oneof(N,_,B); not holds(F,0) : initially_oneof(N,M,B), complement(F,L,M); holds(F,0) : initially_oneof(N,L,B), complement(F,L,M). @@ -80,7 +80,7 @@ holds(L,t) :- occurs(A,t), effect(A,L,N), holds(C,t-1) : condition(A,C,N). holds(L,t) :- holds(L,t-1), complement(L,M), not holds(M,t). :- contradict(F), complement(F,L,M), holds((L),t), holds((M),t). -caused(L,t) :- occurs(A,t), effect(A,L,N), +caused(L,t) :- occurs(A,t), effect(A,L,N), not holds(F',t-1) : condition(A,M',N), complement(F',L',M'); holds(F',t-1) : condition(A,L',N), complement(F',L',M'). holds(F,t) :- caused(L,t), complement(F,L,M). @@ -126,9 +126,9 @@ pos_executable(T,t) :- occurs(A,T), alt_holds(C,T-1,t) : executable(A,C), C != pos_goal_or(N,t) :- goal_or(N,L,B), alt_holds(L,t,t), vol(t). pos_goal_or(N,t) :- goal_or(N,L,B), goal(L), vol(t). -bottom(t) :- pos_goal_or(N,t) : goal_or(N,_,_); +bottom(t) :- pos_goal_or(N,t) : goal_or(N,_,_); alt_holds(L,t,t) : goal(L); - pos_executable(R,t) : R = 1..t; + pos_executable(R,t) : R = 1..t; not_contradict(F,S,t) : contradict(F), S = 1..t; vol(t). @@ -159,7 +159,7 @@ fluent(cpa_coin_at(cpa_c0, cpa_f1, cpa_p1)). fluent(cpa_coin_at(cpa_c1, cpa_f1, cpa_p0)). fluent(cpa_coin_at(cpa_c1, cpa_f1, cpa_p1)). -%% actions ------ +%% actions ------ action(cpa_collect(cpa_c0, cpa_f0, cpa_p0)). action(cpa_collect(cpa_c0, cpa_f0, cpa_p1)). @@ -186,7 +186,7 @@ action(cpa_step_out(cpa_e0, cpa_f1, cpa_p0)). action(cpa_step_out(cpa_e1, cpa_f0, cpa_p1)). action(cpa_step_out(cpa_e1, cpa_f1, cpa_p1)). -%% executable ------ +%% executable ------ executable(cpa_collect(cpa_c0, cpa_f0, cpa_p0),cpa_at(cpa_f0, cpa_p0)). executable(cpa_collect(cpa_c0, cpa_f0, cpa_p1),cpa_at(cpa_f0, cpa_p1)). @@ -209,7 +209,7 @@ executable(cpa_step_out(cpa_e0, cpa_f1, cpa_p0),cpa_inside(cpa_e0)). executable(cpa_step_out(cpa_e1, cpa_f0, cpa_p1),cpa_inside(cpa_e1)). executable(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),cpa_inside(cpa_e1)). -%% effects ------ +%% effects ------ effect(cpa_collect(cpa_c0, cpa_f1, cpa_p0),cpa_have(cpa_c0),1). effect(cpa_collect(cpa_c0, cpa_f1, cpa_p0),neg(cpa_coin_at(cpa_c0, cpa_f1, cpa_p0)),1). @@ -268,7 +268,7 @@ effect(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),cpa_at(cpa_f1, cpa_p1),1). effect(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),neg(cpa_inside(cpa_e1)),1). condition(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),cpa_in(cpa_e1, cpa_f1),1). -%% initial state ------ +%% initial state ------ initially(cpa_at(cpa_f0, cpa_p0)). initially(neg(cpa_at(cpa_f0, cpa_p1))). @@ -287,8 +287,7 @@ initially_oneof(3,cpa_coin_at(cpa_c1, cpa_f1, cpa_p0),1). initially_oneof(3,cpa_coin_at(cpa_c0, cpa_f1, cpa_p1),2). initially_oneof(3,cpa_coin_at(cpa_c1, cpa_f1, cpa_p1),2). -%% goal state ---------- +%% goal state ---------- goal(cpa_have(cpa_c0)). goal(cpa_have(cpa_c1)). - diff --git a/app/clingo/tests/lua/conformant2.lp b/app/clingo/tests/lua/conformant2.lp index d59fb2b57..1e65a2dd0 100644 --- a/app/clingo/tests/lua/conformant2.lp +++ b/app/clingo/tests/lua/conformant2.lp @@ -1,4 +1,4 @@ -#script (lua) +#script (lua) function main(prg) local step = 0 local check = false @@ -29,7 +29,7 @@ function main(prg) if ret.satisfiable then break end - else + else break end end @@ -60,7 +60,7 @@ contradict(F) :- complement(F,L,M), effect(A,L,N1), effect(A,M,N2), { holds(F,0) } :- complement(F,L,M), not initially(L), not initially(M). holds(F,0) :- initially(L), complement(F,L,M). -holds_oneof(N,B) :- +holds_oneof(N,B) :- initially_oneof(N,_,B); not holds(F,0) : initially_oneof(N,M,B), complement(F,L,M); holds(F,0) : initially_oneof(N,L,B), complement(F,L,M). @@ -80,7 +80,7 @@ holds(L,t) :- occurs(A,t), effect(A,L,N), holds(C,t-1) : condition(A,C,N). holds(L,t) :- holds(L,t-1), complement(L,M), not holds(M,t). :- contradict(F), complement(F,L,M), holds((L),t), holds((M),t). -caused(L,t) :- occurs(A,t), effect(A,L,N), +caused(L,t) :- occurs(A,t), effect(A,L,N), not holds(F',t-1) : condition(A,M',N), complement(F',L',M'); holds(F',t-1) : condition(A,L',N), complement(F',L',M'). holds(F,t) :- caused(L,t), complement(F,L,M). @@ -126,9 +126,9 @@ pos_executable(T,t) :- occurs(A,T), alt_holds(C,T-1,t) : executable(A,C), C != pos_goal_or(N,t) :- goal_or(N,L,B), alt_holds(L,t,t), vol(t). pos_goal_or(N,t) :- goal_or(N,L,B), goal(L), vol(t). -bottom(t) :- pos_goal_or(N,t) : goal_or(N,_,_); +bottom(t) :- pos_goal_or(N,t) : goal_or(N,_,_); alt_holds(L,t,t) : goal(L); - pos_executable(R,t) : R = 1..t; + pos_executable(R,t) : R = 1..t; not_contradict(F,S,t) : contradict(F), S = 1..t; vol(t). @@ -148,7 +148,7 @@ fluent(cpa_visited(cpa_n2)). fluent(cpa_at(cpa_n1)). fluent(cpa_at(cpa_n2)). -%% actions ------ +%% actions ------ action(cpa_start(cpa_n1)). action(cpa_start(cpa_n2)). @@ -157,7 +157,7 @@ action(cpa_travel(cpa_n1, cpa_n2)). action(cpa_travel(cpa_n2, cpa_n1)). action(cpa_travel(cpa_n2, cpa_n2)). -%% executable ------ +%% executable ------ executable(cpa_start(cpa_n1),true). executable(cpa_start(cpa_n2),true). @@ -166,7 +166,7 @@ executable(cpa_travel(cpa_n1, cpa_n2),cpa_started). executable(cpa_travel(cpa_n2, cpa_n1),cpa_started). executable(cpa_travel(cpa_n2, cpa_n2),cpa_started). -%% effects ------ +%% effects ------ effect(cpa_start(cpa_n1),cpa_started,1). effect(cpa_start(cpa_n1),cpa_visited(cpa_n1),1). @@ -183,7 +183,7 @@ effect(cpa_travel(cpa_n2, cpa_n1),cpa_at(cpa_n1),1). effect(cpa_travel(cpa_n2, cpa_n1),neg(cpa_at(cpa_n2)),1). condition(cpa_travel(cpa_n2, cpa_n1),cpa_at(cpa_n2),1). -%% initial state ------ +%% initial state ------ initially(neg(cpa_visited(cpa_n1))). initially(neg(cpa_visited(cpa_n2))). @@ -191,8 +191,7 @@ initially(neg(cpa_started)). initially_oneof(1,cpa_at(cpa_n1),1). initially_oneof(1,cpa_at(cpa_n2),2). -%% goal state ---------- +%% goal state ---------- goal(cpa_visited(cpa_n1)). goal(cpa_visited(cpa_n2)). - diff --git a/app/clingo/tests/lua/conformant3.lp b/app/clingo/tests/lua/conformant3.lp index 7f966543f..380b31af9 100644 --- a/app/clingo/tests/lua/conformant3.lp +++ b/app/clingo/tests/lua/conformant3.lp @@ -1,4 +1,4 @@ -#script (lua) +#script (lua) function main(prg) local step = 0 local check = false @@ -29,7 +29,7 @@ function main(prg) if ret.satisfiable then break end - else + else break end end @@ -60,7 +60,7 @@ contradict(F) :- complement(F,L,M), effect(A,L,N1), effect(A,M,N2), { holds(F,0) } :- complement(F,L,M), not initially(L), not initially(M). holds(F,0) :- initially(L), complement(F,L,M). -holds_oneof(N,B) :- +holds_oneof(N,B) :- initially_oneof(N,_,B); not holds(F,0) : initially_oneof(N,M,B), complement(F,L,M); holds(F,0) : initially_oneof(N,L,B), complement(F,L,M). @@ -80,7 +80,7 @@ holds(L,t) :- occurs(A,t), effect(A,L,N), holds(C,t-1) : condition(A,C,N). holds(L,t) :- holds(L,t-1), complement(L,M), not holds(M,t). :- contradict(F), complement(F,L,M), holds((L),t), holds((M),t). -caused(L,t) :- occurs(A,t), effect(A,L,N), +caused(L,t) :- occurs(A,t), effect(A,L,N), not holds(F',t-1) : condition(A,M',N), complement(F',L',M'); holds(F',t-1) : condition(A,L',N), complement(F',L',M'). holds(F,t) :- caused(L,t), complement(F,L,M). @@ -126,9 +126,9 @@ pos_executable(T,t) :- occurs(A,T), alt_holds(C,T-1,t) : executable(A,C), C != pos_goal_or(N,t) :- goal_or(N,L,B), alt_holds(L,t,t), vol(t). pos_goal_or(N,t) :- goal_or(N,L,B), goal(L), vol(t). -bottom(t) :- pos_goal_or(N,t) : goal_or(N,_,_); +bottom(t) :- pos_goal_or(N,t) : goal_or(N,_,_); alt_holds(L,t,t) : goal(L); - pos_executable(R,t) : R = 1..t; + pos_executable(R,t) : R = 1..t; not_contradict(F,S,t) : contradict(F), S = 1..t; vol(t). @@ -164,7 +164,7 @@ fluent(cpa_noisy(cpa_p0)). fluent(cpa_noisy(cpa_p1)). fluent(cpa_noisy(cpa_p2)). -%% actions ------ +%% actions ------ action(cpa_certify(cpa_p0)). action(cpa_certify(cpa_p1)). @@ -201,7 +201,7 @@ action(cpa_request_copy(cpa_p2, cpa_s3)). action(cpa_request_copy(cpa_p2, cpa_s4)). action(cpa_request_copy(cpa_p2, cpa_s5)). -%% executable ------ +%% executable ------ executable(cpa_certify(cpa_p0),cpa_read(cpa_p0)). executable(cpa_certify(cpa_p1),cpa_read(cpa_p1)). @@ -238,7 +238,7 @@ executable(cpa_request_copy(cpa_p2, cpa_s3),cpa_current_stage(cpa_s3)). executable(cpa_request_copy(cpa_p2, cpa_s4),cpa_current_stage(cpa_s4)). executable(cpa_request_copy(cpa_p2, cpa_s5),cpa_current_stage(cpa_s5)). -%% effects ------ +%% effects ------ effect(cpa_certify(cpa_p0),cpa_bad(cpa_p0),1). condition(cpa_certify(cpa_p0),cpa_noisy(cpa_p0),1). @@ -297,7 +297,7 @@ effect(cpa_request_copy(cpa_p2, cpa_s2),neg(cpa_noisy(cpa_p2)),1). effect(cpa_request_copy(cpa_p2, cpa_s2),neg(cpa_bad(cpa_p2)),1). condition(cpa_request_copy(cpa_p2, cpa_s2),cpa_bad(cpa_p2),1). -%% initial state ------ +%% initial state ------ initially(cpa_current_stage(cpa_s0)). initially(cpa_in_channel(cpa_p0)). @@ -324,9 +324,8 @@ initially_oneof(1,neg(cpa_noisy(cpa_p0)),2). initially_oneof(1,neg(cpa_noisy(cpa_p2)),2). initially_oneof(1,neg(cpa_noisy(cpa_p1)),2). -%% goal state ---------- +%% goal state ---------- goal(cpa_ok(cpa_p0)). goal(cpa_ok(cpa_p1)). goal(cpa_ok(cpa_p2)). - diff --git a/app/clingo/tests/lua/cover-lua.lp b/app/clingo/tests/lua/cover-lua.lp index 1e9f090d1..edd17874d 100644 --- a/app/clingo/tests/lua/cover-lua.lp +++ b/app/clingo/tests/lua/cover-lua.lp @@ -6,7 +6,7 @@ State = { } State.__index = State function State.new() - local x = { + local x = { leaves = {}, last = nil } diff --git a/app/clingo/tests/lua/domain.lp b/app/clingo/tests/lua/domain.lp index 020363b70..d283f8082 100644 --- a/app/clingo/tests/lua/domain.lp +++ b/app/clingo/tests/lua/domain.lp @@ -1,5 +1,5 @@ p(1). -{ p(3) }. +{ p(3) }. #external p(1..3). q(X) :- p(X). @@ -30,4 +30,4 @@ function main(prg) io.flush() end -#end. +#end. diff --git a/app/clingo/tests/lua/mutex-bug.lp b/app/clingo/tests/lua/mutex-bug.lp index be5834337..602d8876a 100644 --- a/app/clingo/tests/lua/mutex-bug.lp +++ b/app/clingo/tests/lua/mutex-bug.lp @@ -1,4 +1,4 @@ -#script (lua) +#script (lua) function main(prg) prg:ground({{"base", {}}, {"plan_graph_base", {}}}) @@ -121,4 +121,3 @@ init(at_ferry(a)). init(empty_ferry). goal(at(c1, b)). goal(at(c2, b)). - diff --git a/app/clingo/tests/lua/observer.lp b/app/clingo/tests/lua/observer.lp index c544a60cf..5f7b600f4 100644 --- a/app/clingo/tests/lua/observer.lp +++ b/app/clingo/tests/lua/observer.lp @@ -200,10 +200,10 @@ function Observer:theory_term_compound(term_id, name_id_or_type, arguments) end function Observer:theory_element(element_id, terms, condition) - self.__elems[element_id] = function () + self.__elems[element_id] = function () condition = table.sort_unique(self:__map_lits(condition)) return Function("elem", {Tuple(table.map(terms, function (i) - return self.__terms[i]() + return self.__terms[i]() end)), Tuple(condition)}) end end diff --git a/app/clingo/tests/lua/propagator.lp b/app/clingo/tests/lua/propagator.lp index 33644ae2f..c23330402 100644 --- a/app/clingo/tests/lua/propagator.lp +++ b/app/clingo/tests/lua/propagator.lp @@ -4,7 +4,7 @@ require("clingo") -- {{{1 Aux -function max(a, b) +function max(a, b) if a < b then return b else diff --git a/app/clingo/tests/lua/robots.lp b/app/clingo/tests/lua/robots.lp index 523fa86d0..9aa181aa9 100644 --- a/app/clingo/tests/lua/robots.lp +++ b/app/clingo/tests/lua/robots.lp @@ -94,10 +94,10 @@ go(R, D, t) :- selectRobot(R, t), selectDir(D,t). #external volatile(t). % --- Uncomment an integrity constraint to pose a query -% - numbers indicated minimum number of moves +% - numbers indicated minimum number of moves % - sometimes a heuristics was better than another -:- instance(1), not position(red, 5,2,t), volatile(t). % red moon: 9, vmtf +:- instance(1), not position(red, 5,2,t), volatile(t). % red moon: 9, vmtf :- instance(2), not position(red, 15,2,t), volatile(t). % red triangle: 10, ? :- instance(3), not position(green, 2,3,t), volatile(t). % green triangle: 9, berkmin :- instance(4), not position(blue, 12,3,t), volatile(t). % blue star: 8, ? @@ -209,4 +209,3 @@ barrier( 7,13,south). barrier(15,13,south). barrier(10,14,south). barrier( 3,15,south). - diff --git a/app/clingo/tests/lua/setconfig.lp b/app/clingo/tests/lua/setconfig.lp index 48cc50401..a46e3ac26 100644 --- a/app/clingo/tests/lua/setconfig.lp +++ b/app/clingo/tests/lua/setconfig.lp @@ -25,4 +25,3 @@ end #show a : a. #show b : b. #show c : c. - diff --git a/app/clingo/tests/lua/show.lp b/app/clingo/tests/lua/show.lp index 21065b0ce..795315865 100644 --- a/app/clingo/tests/lua/show.lp +++ b/app/clingo/tests/lua/show.lp @@ -41,5 +41,5 @@ c. #show a : b. #program result. -res(X) :- X = @getModels(). +res(X) :- X = @getModels(). #show res/1. diff --git a/app/clingo/tests/lua/sokoban_back.lp b/app/clingo/tests/lua/sokoban_back.lp index 46659f1f7..bd6b0e346 100644 --- a/app/clingo/tests/lua/sokoban_back.lp +++ b/app/clingo/tests/lua/sokoban_back.lp @@ -134,4 +134,3 @@ square(7, 4). square(3, 5). square(4, 5). square(5, 5). - diff --git a/app/clingo/tests/lua/solitaire_para.lp b/app/clingo/tests/lua/solitaire_para.lp index dcd8e1d5f..3bf5afced 100644 --- a/app/clingo/tests/lua/solitaire_para.lp +++ b/app/clingo/tests/lua/solitaire_para.lp @@ -137,4 +137,3 @@ stone(X, Y, t) :- field(X, Y), stone(X, Y, t - 1), not jumped(X, Y, t), not remo :- { not stone(X, Y, t) : field(X, Y) } n, volatile(t). % the last stone shall be in the center :- not stone(0, 0, t), volatile(t). - diff --git a/app/clingo/tests/lua/test-numeric.lp b/app/clingo/tests/lua/test-numeric.lp index 89199f3b0..235ef501b 100644 --- a/app/clingo/tests/lua/test-numeric.lp +++ b/app/clingo/tests/lua/test-numeric.lp @@ -8,7 +8,7 @@ end function main(prg) local bot = 100 - local lit = function (sym) + local lit = function (sym) return prg.symbolic_atoms:lookup(sym).literal end prg:ground({{"base", {}}}) diff --git a/app/clingo/tests/lua/test.lp b/app/clingo/tests/lua/test.lp index b1678b05c..61ba63153 100644 --- a/app/clingo/tests/lua/test.lp +++ b/app/clingo/tests/lua/test.lp @@ -58,4 +58,3 @@ r(k,X) :- test(X). #external volatile(k). :- not c(5), not volatile(k). volatile(k-1). - diff --git a/app/clingo/tests/lua/theory-term-types.lp b/app/clingo/tests/lua/theory-term-types.lp index d99482f52..f502e1249 100644 --- a/app/clingo/tests/lua/theory-term-types.lp +++ b/app/clingo/tests/lua/theory-term-types.lp @@ -1,7 +1,7 @@ #script (lua) clingo = require("clingo") -function types() +function types() return { tostring(clingo.TheoryTermType.Tuple), tostring(clingo.TheoryTermType.List), @@ -15,4 +15,3 @@ end #end. p(@types()). - diff --git a/app/clingo/tests/python/add_minimize.lp b/app/clingo/tests/python/add_minimize.lp index 432718370..8e981568e 100644 --- a/app/clingo/tests/python/add_minimize.lp +++ b/app/clingo/tests/python/add_minimize.lp @@ -22,4 +22,3 @@ def main(prg): 2 { a; b; c }. 2 { b; c; d }. - diff --git a/app/clingo/tests/python/add_weight.lp b/app/clingo/tests/python/add_weight.lp index 616ba256c..c8fcdd000 100644 --- a/app/clingo/tests/python/add_weight.lp +++ b/app/clingo/tests/python/add_weight.lp @@ -19,4 +19,3 @@ def main(prg): #end. { a; b; c }. - diff --git a/app/clingo/tests/python/assumptions3.lp b/app/clingo/tests/python/assumptions3.lp index 9f8668e7b..cff25ac69 100644 --- a/app/clingo/tests/python/assumptions3.lp +++ b/app/clingo/tests/python/assumptions3.lp @@ -8,7 +8,7 @@ def main(prg): prg.solve(assumptions=[(Function("a"), True), (Function("b"), False), (Function("d"), True)]) prg.solve(assumptions=[(Function("a"), False), (Function("c"), True)]) -#end. +#end. #external d. { a; b; c }. diff --git a/app/clingo/tests/python/cancel.lp b/app/clingo/tests/python/cancel.lp index 7ef4491de..177e103ba 100644 --- a/app/clingo/tests/python/cancel.lp +++ b/app/clingo/tests/python/cancel.lp @@ -1,4 +1,4 @@ -#script (python) +#script (python) import clingo diff --git a/app/clingo/tests/python/domain.lp b/app/clingo/tests/python/domain.lp index ff4705095..ba502cb0f 100644 --- a/app/clingo/tests/python/domain.lp +++ b/app/clingo/tests/python/domain.lp @@ -1,5 +1,5 @@ p(1). -{ p(3) }. +{ p(3) }. #external p(1..3). q(X) :- p(X). @@ -25,4 +25,4 @@ def main(prg): print (out) sys.stdout.flush() -#end. +#end. diff --git a/app/clingo/tests/python/interrupt.lp b/app/clingo/tests/python/interrupt.lp index 993ffe8cb..fd4dd84b1 100644 --- a/app/clingo/tests/python/interrupt.lp +++ b/app/clingo/tests/python/interrupt.lp @@ -1,4 +1,4 @@ -#script (python) +#script (python) import clingo diff --git a/app/clingo/tests/python/multi.lp b/app/clingo/tests/python/multi.lp index 80bb1fe1d..ca44890be 100644 --- a/app/clingo/tests/python/multi.lp +++ b/app/clingo/tests/python/multi.lp @@ -15,4 +15,3 @@ def main(prg): #program b. :- p(X). - diff --git a/app/clingo/tests/python/project.lp b/app/clingo/tests/python/project.lp index 2f50c9fc8..965dbcd1b 100644 --- a/app/clingo/tests/python/project.lp +++ b/app/clingo/tests/python/project.lp @@ -118,6 +118,3 @@ def main(prg): idocc(I,n) :- occ(I,n,Q). :- { idocc(I,n) } th-1. - - - diff --git a/app/clingo/tests/python/setconfig.lp b/app/clingo/tests/python/setconfig.lp index 2fc3100a1..28931c550 100644 --- a/app/clingo/tests/python/setconfig.lp +++ b/app/clingo/tests/python/setconfig.lp @@ -26,4 +26,3 @@ def main(prg): #show a : a. #show b : b. #show c : c. - diff --git a/app/clingo/tests/python/show.lp b/app/clingo/tests/python/show.lp index 2aab69ae0..dde898aca 100644 --- a/app/clingo/tests/python/show.lp +++ b/app/clingo/tests/python/show.lp @@ -35,6 +35,5 @@ c. #show a : b. #program result. -res(X) :- X = @getModels(). +res(X) :- X = @getModels(). #show res/1. - diff --git a/app/clingo/tests/python/test-numeric.lp b/app/clingo/tests/python/test-numeric.lp index cef0d1477..aca23252b 100644 --- a/app/clingo/tests/python/test-numeric.lp +++ b/app/clingo/tests/python/test-numeric.lp @@ -11,7 +11,7 @@ def main(prg): prg.ground([("base", [])]) prg.solve(assumptions=[(p(3), False), lit(p(4))]) prg.solve(assumptions=[(p(3), True), -lit(p(4))]) - + prg.assign_external(p(1), True) prg.solve(assumptions=[-lit(p(3)), -lit(p(4))]) prg.assign_external(-lit(p(1)), True) @@ -21,7 +21,7 @@ def main(prg): prg.solve(assumptions=[-lit(p(3)), -lit(p(4)), bot]) prg.solve(assumptions=[-lit(p(3)), -lit(p(4)), -bot]) - + # note: this actually creates the external # hence, the subsequent call with the assumption is unsatisfiable prg.assign_external(bot, True) diff --git a/app/clingo/tests/python/test.lp b/app/clingo/tests/python/test.lp index d1d2b37bf..4cef3c203 100644 --- a/app/clingo/tests/python/test.lp +++ b/app/clingo/tests/python/test.lp @@ -59,4 +59,3 @@ r(k,X) :- test(X). #external volatile(k). :- not c(5), not volatile(k). volatile(k-1). - diff --git a/app/clingo/tests/run.py b/app/clingo/tests/run.py index 8e673b087..04234be8d 100755 --- a/app/clingo/tests/run.py +++ b/app/clingo/tests/run.py @@ -1,39 +1,44 @@ #!/usr/bin/python -import re +import argparse +import difflib as dl import os import os.path -import sys +import re import subprocess as sp -import difflib as dl -import argparse +import sys -parser = argparse.ArgumentParser(description=""" +parser = argparse.ArgumentParser( + description=""" Can be used to run and normalize tests. Additional options can be passed to clingo by adding them at the end of the command line preceded by '--'. -""") -parser.add_argument('-c', '--clingo', default=None, help="path to clingo executable") +""" +) +parser.add_argument("-c", "--clingo", default=None, help="path to clingo executable") subparsers = parser.add_subparsers(dest="action", help="sub-command --help") subparsers.required = True -parser_run = subparsers.add_parser('run', help='run all tests') -parser_normalize = subparsers.add_parser('normalize', help='normalize the output of clingo') +parser_run = subparsers.add_parser("run", help="run all tests") +parser_normalize = subparsers.add_parser( + "normalize", help="normalize the output of clingo" +) parser_normalize.add_argument("file") argv = sys.argv[1:] extra_argv = [] if "--" in argv: - extra_argv = argv[argv.index("--")+1:] - argv = argv[:argv.index("--")] + extra_argv = argv[argv.index("--") + 1 :] + argv = argv[: argv.index("--")] parse_ret = parser.parse_args(argv) if parse_ret.action is None: - print (parser.usage) + print(parser.usage) exit(0) clingo = parse_ret.clingo + def find_clingo(): clingos = [ "build/debug/bin/clingo", @@ -42,27 +47,29 @@ def find_clingo(): "build/cmake/bin/clingo", "build/bin/Debug/clingo.exe", "build/bin/Release/clingo.exe", - ] + ] for x in clingos: x = os.path.normpath("{}/../../../{}".format(wd, x)) if os.path.exists(x): return x return None + wd = os.path.normpath(os.path.dirname(__file__)) if clingo is None: clingo = find_clingo() if clingo is None: - print ("no usable clingo version found") + print("no usable clingo version found") exit(1) + def normalize(out): - state=0 - current=[] - step=0 - result="ERROR" - norm=[] + state = 0 + current = [] + step = 0 + result = "ERROR" + norm = [] for line in out.split("\n"): if state == 1: if step > 0: @@ -77,104 +84,113 @@ def normalize(out): current = [] if state == 2: current.append(line.strip().split(" ")) - state=0 + state = 0 elif line.startswith("Solving..."): state = 1 elif line.startswith("Answer: "): state = 2 elif line.startswith("SATISFIABLE"): - result="SAT" - state=1 + result = "SAT" + state = 1 elif line.startswith("UNSATISFIABLE"): - result="UNSAT" - state=1 + result = "UNSAT" + state = 1 elif line.startswith("UNKNOWN"): - result="UNKNOWN" - state=1 + result = "UNKNOWN" + state = 1 elif line.startswith("OPTIMUM FOUND"): - result="OPTIMUM FOUND" - state=1 + result = "OPTIMUM FOUND" + state = 1 norm.append(result) norm.append("") return "\n".join(norm) + if parse_ret.action == "normalize": args = [clingo, "0", parse_ret.file, "-Wnone"] b = os.path.splitext(parse_ret.file)[0] if os.path.exists(b + ".cmd"): - with open(b + ".cmd", 'r') as cmd_file: + with open(b + ".cmd", "r") as cmd_file: for x in cmd_file: args.extend(x.strip().split()) args.extend(extra_argv) - out, err = sp.Popen(args, stderr=sp.PIPE, stdout=sp.PIPE, universal_newlines=True).communicate() + out, err = sp.Popen( + args, stderr=sp.PIPE, stdout=sp.PIPE, universal_newlines=True + ).communicate() sys.stdout.write(normalize(out)) exit(0) if parse_ret.action == "run": - total = 0 + total = 0 failed = 0 - out, err = sp.Popen([clingo, "--version"], stderr=sp.PIPE, stdout=sp.PIPE, universal_newlines=True).communicate() - with_python = out.find("with Python") > 0 - with_lua = out.find("with Lua") > 0 + out, err = sp.Popen( + [clingo, "--version"], stderr=sp.PIPE, stdout=sp.PIPE, universal_newlines=True + ).communicate() + with_python = out.find("with Python") > 0 + with_lua = out.find("with Lua") > 0 with_threads = out.find("WITH_THREADS=1") > 0 for root, dirs, files in os.walk(wd): for f in sorted(files): if f.endswith(".lp"): b = os.path.join(root, f[:-3]) - with open(b + ".lp", 'r') as inst_file: + with open(b + ".lp", "r") as inst_file: inst = inst_file.read() - if (not with_python and re.search(r"#script[ ]*\(python\)", inst)) or \ - (not with_lua and re.search(r"#script[ ]*\(lua\)", inst)) or \ - (not with_threads and re.search("async_=", inst)) or \ - (not with_threads and re.search("solve_async", inst)): + if ( + (not with_python and re.search(r"#script[ ]*\(python\)", inst)) + or (not with_lua and re.search(r"#script[ ]*\(lua\)", inst)) + or (not with_threads and re.search("async_=", inst)) + or (not with_threads and re.search("solve_async", inst)) + ): continue - total+= 1 + total += 1 sys.stdout.flush() args = [clingo, "0", b + ".lp", "-Wnone"] if os.path.exists(b + ".cmd"): - with open(b + ".cmd", 'r') as cmd_file: + with open(b + ".cmd", "r") as cmd_file: for x in cmd_file: args.extend(x.strip().split()) args.extend(extra_argv) - out, err = sp.Popen(args, stderr=sp.PIPE, stdout=sp.PIPE, universal_newlines=True).communicate() + out, err = sp.Popen( + args, stderr=sp.PIPE, stdout=sp.PIPE, universal_newlines=True + ).communicate() norm = normalize(out) - with open(b + ".sol", 'r') as sol_file: - sol = sol_file.read() + with open(b + ".sol", "r") as sol_file: + sol = sol_file.read() if norm != sol: - failed+= 1 + failed += 1 print - print ("-" * 79) - print (" ".join(args)) - print ("." * 79) + print("-" * 79) + print(" ".join(args)) + print("." * 79) print - print ("FAILED:") + print("FAILED:") d = dl.Differ() for line in list(d.compare(sol.splitlines(), norm.splitlines())): if not line.startswith(" "): - print (line) + print(line) print - print ("." * 79) + print("." * 79) print - print ("STDOUT:") + print("STDOUT:") print - print (out) + print(out) print - print ("." * 79) + print("." * 79) print - print ("STDERR:") + print("STDERR:") print - print (err) + print(err) print sys.stdout.flush() - print ("=" * 79) + print("=" * 79) if failed > 0: - print ("Some tests failed ({} of {} test cases)".format(failed, total)) + print("Some tests failed ({} of {} test cases)".format(failed, total)) print exit(1) else: - print ("All tests passed ({} test cases)".format(total)) + print("All tests passed ({} test cases)".format(total)) print exit(0) diff --git a/app/gringo/main.cc b/app/gringo/main.cc index 89fa10cb2..2390a88f0 100644 --- a/app/gringo/main.cc +++ b/app/gringo/main.cc @@ -23,10 +23,10 @@ // }}} #ifdef CLINGO_WITH_PYTHON -# include +#include #endif #ifdef CLINGO_WITH_LUA -# include +#include #endif #include @@ -35,17 +35,17 @@ extern "C" CLINGO_VISIBILITY_DEFAULT int gringo_main_(int argc, char *argv[]); int main(int argc, char *argv[]) { -# ifdef CLINGO_WITH_PYTHON +#ifdef CLINGO_WITH_PYTHON if (!clingo_register_python_()) { std::cerr << clingo_error_message() << std::endl; return 1; } -# endif -# ifdef CLINGO_WITH_LUA +#endif +#ifdef CLINGO_WITH_LUA if (!clingo_register_lua_(nullptr)) { std::cerr << clingo_error_message() << std::endl; return 1; } -# endif +#endif return gringo_main_(argc, argv); } diff --git a/app/luaclingo/main.cc b/app/luaclingo/main.cc index 664de849b..e6b0b5686 100644 --- a/app/luaclingo/main.cc +++ b/app/luaclingo/main.cc @@ -24,18 +24,17 @@ #include -#if defined _WIN32 || defined __CYGWIN__ -# define VISIBILITY_DEFAULT __declspec (dllexport) +#if defined _WIN32 || defined __CYGWIN__ +#define VISIBILITY_DEFAULT __declspec(dllexport) #else -# if __GNUC__ >= 4 -# define VISIBILITY_DEFAULT __attribute__ ((visibility ("default"))) -# else -# define VISIBILITY_DEFAULT -# endif +#if __GNUC__ >= 4 +#define VISIBILITY_DEFAULT __attribute__((visibility("default"))) +#else +#define VISIBILITY_DEFAULT +#endif #endif extern "C" VISIBILITY_DEFAULT int luaopen_clingo(lua_State *L) { clingo_register_lua_(L); return clingo_init_lua_(L); } - diff --git a/app/reify/main.cc b/app/reify/main.cc index 27315c373..999a82379 100644 --- a/app/reify/main.cc +++ b/app/reify/main.cc @@ -22,58 +22,57 @@ // }}} +#include "clingo.h" +#include "reify/program.hh" #include #include #include -#include "reify/program.hh" -#include "clingo.h" #define CLINGO_QUOTE_(name) #name #define CLINGO_QUOTE(name) CLINGO_QUOTE_(name) #ifdef CLINGO_BUILD_REVISION -# define CLINGO_VERSION_STRING CLINGO_VERSION " (" CLINGO_QUOTE(CLINGO_BUILD_REVISION) ")" +#define CLINGO_VERSION_STRING CLINGO_VERSION " (" CLINGO_QUOTE(CLINGO_BUILD_REVISION) ")" #else -# define CLINGO_VERSION_STRING CLINGO_VERSION +#define CLINGO_VERSION_STRING CLINGO_VERSION #endif struct ReifyOptions { bool calculateSCCs = false; - bool reifyStep = false; + bool reifyStep = false; }; class ReifyApp : public Potassco::Application { -public: - virtual const char* getName() const { return "reify"; } + public: + virtual const char *getName() const { return "reify"; } - virtual const char* getVersion() const { return CLINGO_VERSION_STRING; } + virtual const char *getVersion() const { return CLINGO_VERSION_STRING; } -protected: - virtual void initOptions(Potassco::ProgramOptions::OptionContext& root) { + protected: + virtual void initOptions(Potassco::ProgramOptions::OptionContext &root) { using namespace Potassco::ProgramOptions; OptionGroup reify("Reify Options"); - reify.addOptions() - ("sccs,c", flag(opts_.calculateSCCs), "calculate strongly connected components\n") - ("steps,s", flag(opts_.reifyStep), "add step numbers to generated facts\n"); + reify.addOptions()("sccs,c", flag(opts_.calculateSCCs), "calculate strongly connected components\n")( + "steps,s", flag(opts_.reifyStep), "add step numbers to generated facts\n"); root.add(reify); OptionGroup basic("Basic Options"); - basic.addOptions() - ("file,f,@2", storeTo(input_), "Input files") - ; + basic.addOptions()("file,f,@2", storeTo(input_), "Input files"); root.add(basic); } - virtual void validateOptions(const Potassco::ProgramOptions::OptionContext&, const Potassco::ProgramOptions::ParsedOptions&, const Potassco::ProgramOptions::ParsedValues&) { } + virtual void validateOptions(const Potassco::ProgramOptions::OptionContext &, + const Potassco::ProgramOptions::ParsedOptions &, + const Potassco::ProgramOptions::ParsedValues &) {} - virtual void setup() { } + virtual void setup() {} - static bool parsePositional(std::string const &, std::string& out) { + static bool parsePositional(std::string const &, std::string &out) { out = "file"; return true; } virtual Potassco::ProgramOptions::PosOption getPositional() const { return parsePositional; } - virtual void printHelp(const Potassco::ProgramOptions::OptionContext& root) { + virtual void printHelp(const Potassco::ProgramOptions::OptionContext &root) { printf("%s version %s\n", getName(), getVersion()); printUsage(); Potassco::ProgramOptions::FileOut out(stdout); @@ -92,13 +91,13 @@ class ReifyApp : public Potassco::Application { Reify::Reifier reify(std::cout, opts_.calculateSCCs, opts_.reifyStep); if (input_.empty() || input_ == "-") { reify.parse(std::cin); - } - else { + } else { std::ifstream ifs(input_); reify.parse(ifs); } } -private: + + private: std::string input_; ReifyOptions opts_; }; @@ -107,4 +106,3 @@ int main(int argc, char **argv) { ReifyApp app; return app.main(argc, argv); } - diff --git a/app/web/main.cc b/app/web/main.cc index 2d6297c70..1370a79bc 100644 --- a/app/web/main.cc +++ b/app/web/main.cc @@ -23,14 +23,14 @@ // }}} #ifdef CLINGO_WITH_LUA -# include +#include #endif #include "clingo/clingo_app.hh" #include "clingo/scripts.hh" #include class ExitException : public std::exception { -public: + public: ExitException(int status) : status_(status) { std::ostringstream oss; oss << "exited with status: " << status_; @@ -39,15 +39,14 @@ class ExitException : public std::exception { int status() const { return status_; } char const *what() const noexcept { return msg_.c_str(); } ~ExitException() = default; -private: + + private: std::string msg_; int status_; }; struct WebApp : Gringo::ClingoApp { - void exit(int status) const { - throw ExitException(status); - } + void exit(int status) const { throw ExitException(status); } }; extern "C" int run(char const *program, char const *options) { @@ -56,26 +55,24 @@ extern "C" int run(char const *program, char const *options) { Gringo::g_scripts() = Gringo::Scripts(); clingo_register_lua_(nullptr); #endif - std::streambuf* orig = std::cin.rdbuf(); - auto exit(Gringo::onExit([orig]{ std::cin.rdbuf(orig); })); + std::streambuf *orig = std::cin.rdbuf(); + auto exit(Gringo::onExit([orig] { std::cin.rdbuf(orig); })); std::istringstream input(program); std::cin.rdbuf(input.rdbuf()); std::vector> opts; - opts.emplace_back(std::initializer_list{'c','l','i','n','g','o','\0'}); + opts.emplace_back(std::initializer_list{'c', 'l', 'i', 'n', 'g', 'o', '\0'}); std::istringstream iss(options); for (std::istream_iterator it(iss), ie; it != ie; ++it) { opts.emplace_back(it->c_str(), it->c_str() + it->size() + 1); } - std::vector args; + std::vector args; for (auto &opt : opts) { args.emplace_back(opt.data()); } WebApp app; args.emplace_back(nullptr); - return app.main(args.size()-2, args.data()); - } - catch (ExitException const &e) { + return app.main(args.size() - 2, args.data()); + } catch (ExitException const &e) { return e.status(); } } - diff --git a/cmake/glob-paths.py b/cmake/glob-paths.py index 2857944a7..0b3e30a5d 100755 --- a/cmake/glob-paths.py +++ b/cmake/glob-paths.py @@ -5,11 +5,14 @@ import re import sys + def split_path(path): components = os.path.normpath(path).split(os.sep) - if len(components) > 0 and components[0] == ".": del components[0] + if len(components) > 0 and components[0] == ".": + del components[0] return components + def find(path, target): header = {} output = "" @@ -23,67 +26,91 @@ def find(path, target): components.append(filename) if re.match(r"^.*\.(h|hh|hpp|c|cc|cpp)$", filename): header.setdefault(root, "") - header[root] += " \"${{CMAKE_CURRENT_SOURCE_DIR}}/{src}\"\n".format(src="/".join(components)) + header[root] += ' "${{CMAKE_CURRENT_SOURCE_DIR}}/{src}"\n'.format( + src="/".join(components) + ) elif re.match(r"^.*\.(yy)$", filename): name, ext = os.path.splitext(filename) - path = ''.join([d + "/" for d in components[:-1]]) - header[os.path.join(root, name)] = '''\ + path = "".join([d + "/" for d in components[:-1]]) + header[os.path.join(root, name)] = ( + """\ "${{CMAKE_CURRENT_SOURCE_DIR}}/{path}{name}{ext}" ${{BISON_{name}_OUTPUTS}} -'''.format(name=name,ext=ext,path=path) - output += '''\ +""".format( + name=name, ext=ext, path=path + ) + ) + output += """\ bison_target_or_gen("{path}{name}{ext}") -'''.format(name=name, path=path, ext=ext) +""".format( + name=name, path=path, ext=ext + ) elif re.match(r"^.*\.(xh|xch)$", filename): header.setdefault(root, "") name, ext = os.path.splitext(filename) - path = ''.join(["/" + d for d in components[:-1]]) + path = "".join(["/" + d for d in components[:-1]]) options = "" if ext == ".xch": options = " OPTIONS -c" - header[root]+= '''\ + header[ + root + ] += """\ "${{CMAKE_CURRENT_SOURCE_DIR}}{path}/{name}{ext}" ${{RE2C_{name}_OUTPUT}} -'''.format(name=name,ext=ext,path=path) - output += '''\ +""".format( + name=name, ext=ext, path=path + ) + output += """\ re2c_target_or_gen("{path}/{name}{ext}") -'''.format(name=name, path=path, ext=ext, options=options) +""".format( + name=name, path=path, ext=ext, options=options + ) - output+= 'set(ide_{}_group "{} Files")\n'.format(target, target.title()) + output += 'set(ide_{}_group "{} Files")\n'.format(target, target.title()) groups = [] for root in sorted(header): components = split_path(root) - if len(components) > 0 and components[0] == "src": del components[0] - groups.append('-'.join(["{}-group".format(target)] + components)) + if len(components) > 0 and components[0] == "src": + del components[0] + groups.append("-".join(["{}-group".format(target)] + components)) output += "set({0}\n".format(groups[-1]) for value in header[root]: output += value output = output[:-1] + ")\n" - output+= """source_group("{}" FILES ${{{}}})\n""".format(r"\\".join(["${{ide_{}_group}}".format(target)] + components), groups[-1]) + output += """source_group("{}" FILES ${{{}}})\n""".format( + r"\\".join(["${{ide_{}_group}}".format(target)] + components), groups[-1] + ) - output+= 'set({}\n'.format(target) + output += "set({}\n".format(target) for group in groups: - output+= """ ${{{}}}\n""".format(group) + output += """ ${{{}}}\n""".format(group) output = output[:-1] + ")\n" return output + def rep(m): path = m.group("path") target = m.group("target") content = find(path, target) return "# [[[{}: {}\n{}# ]]]".format(target, path, content) + files = [os.path.abspath(f) for f in sys.argv[1:]] for f in files: os.chdir(os.path.dirname(f)) - content = open(f, "r").read(); - replace = re.sub(r"#[ ]*\[\[\[(?P[^:]*): (?P[^\n\]]*)(.|\n)*?\]\]\]", rep, content, 0, re.MULTILINE) + content = open(f, "r").read() + replace = re.sub( + r"#[ ]*\[\[\[(?P[^:]*): (?P[^\n\]]*)(.|\n)*?\]\]\]", + rep, + content, + 0, + re.MULTILINE, + ) if content != replace: sys.stderr.write("File {} changed!\n".format(f)) sys.stderr.flush() open(f, "w").write(replace) - diff --git a/cmake/python-site.py b/cmake/python-site.py index 9bdcb5c97..b26b6f428 100644 --- a/cmake/python-site.py +++ b/cmake/python-site.py @@ -3,11 +3,16 @@ if sys.version_info >= (3, 11): NEW_STYLE = True - from sysconfig import get_config_var, get_config_vars, get_preferred_scheme, get_path + from sysconfig import ( + get_config_var, + get_config_vars, + get_path, + get_preferred_scheme, + ) else: NEW_STYLE = False + from distutils.sysconfig import get_config_vars, get_python_lib from site import USER_SITE - from distutils.sysconfig import get_python_lib, get_config_vars parser = ArgumentParser() if sys.version_info >= (3, 7): @@ -17,8 +22,8 @@ prefix_parser = subparser.add_parser("target") prefix_group = prefix_parser.add_mutually_exclusive_group() -prefix_group.add_argument("--user", action='store_true', help='get user prefix') -prefix_group.add_argument("--prefix", type=str, help='prepend prefix') +prefix_group.add_argument("--user", action="store_true", help="get user prefix") +prefix_group.add_argument("--prefix", type=str, help="prepend prefix") prefix_parser = subparser.add_parser("suffix") @@ -39,7 +44,7 @@ platlib = get_path("platlib", scheme) print(platlib) elif result.action == "suffix": - print(get_config_var('EXT_SUFFIX')) + print(get_config_var("EXT_SUFFIX")) else: # TODO: remove once python 3.10 is eol if result.action == "target": @@ -52,7 +57,7 @@ if EXT_SUFFIX is not None: ext = EXT_SUFFIX elif SOABI is not None: - ext = ''.join('.', SOABI, SO) + ext = "".join(".", SOABI, SO) else: ext = SO print(ext) diff --git a/doc/api/DoxygenLayout.xml b/doc/api/DoxygenLayout.xml index a4d4df78d..c7adac90a 100644 --- a/doc/api/DoxygenLayout.xml +++ b/doc/api/DoxygenLayout.xml @@ -11,7 +11,7 @@ - + @@ -19,7 +19,7 @@ - + diff --git a/doc/py/Gemfile b/doc/py/Gemfile index 47b8011ff..c1d0453fa 100644 --- a/doc/py/Gemfile +++ b/doc/py/Gemfile @@ -28,4 +28,3 @@ gem "tzinfo-data", platforms: [:mingw, :mswin, :x64_mingw, :jruby] # Performance-booster for watching directories on Windows gem "wdm", "~> 0.1.0" if Gem.win_platform? - diff --git a/doc/py/_gen/gen.py b/doc/py/_gen/gen.py index ed1fdac2f..566a63cc3 100755 --- a/doc/py/_gen/gen.py +++ b/doc/py/_gen/gen.py @@ -1,16 +1,18 @@ #!/usr/bin/env python3 +import importlib.machinery import os import re -import importlib.machinery import pdoc + import clingo SUB = [ ("clingo_main", "Application", clingo.clingo_main), ("Control.register_observer", "Observer", clingo.Control.register_observer), - ("Control.register_propagator", "Propagator", clingo.Control.register_propagator)] + ("Control.register_propagator", "Propagator", clingo.Control.register_propagator), +] def parse_class(aux, name, doc): @@ -32,6 +34,7 @@ def parse_aux(): for _, name, obj in SUB: parse_class(aux, name, obj.__doc__) import aux + return aux @@ -39,9 +42,14 @@ def parse_aux(): clingo.__pdoc__ = {} for key, name, obj in SUB: - clingo.__pdoc__[key] = re.sub(r"```python.*?class ({}(\([^)]*\))?):.*?```".format(name), "", obj.__doc__, flags=re.MULTILINE|re.DOTALL) - -pdoc.tpl_lookup.directories.insert(0, './templates') + clingo.__pdoc__[key] = re.sub( + r"```python.*?class ({}(\([^)]*\))?):.*?```".format(name), + "", + obj.__doc__, + flags=re.MULTILINE | re.DOTALL, + ) + +pdoc.tpl_lookup.directories.insert(0, "./templates") ctx = pdoc.Context() cmod = pdoc.Module(clingo, context=ctx) @@ -52,9 +60,23 @@ def parse_aux(): cmod.doc["Observer"] = pdoc.Class("Observer", cmod, xmod.Observer) cmod.doc["Propagator"] = pdoc.Class("Propagator", cmod, xmod.Propagator) cmod.doc["ast"] = amod -cmod.doc["__version__"] = pdoc.Variable("__version__", cmod, "__version__: str\n\nVersion of the clingo module (`'{}'`).".format(clingo.__version__)) -cmod.doc["Infimum"] = pdoc.Variable("Infimum", cmod, '''Infimum: Symbol\n\nRepresents a symbol of type `clingo.SymbolType.Infimum`.''') -cmod.doc["Supremum"] = pdoc.Variable("Supremum", cmod, '''Supremum: Symbol\n\nRepresents a symbol of type `clingo.SymbolType.Supremum`.''') +cmod.doc["__version__"] = pdoc.Variable( + "__version__", + cmod, + "__version__: str\n\nVersion of the clingo module (`'{}'`).".format( + clingo.__version__ + ), +) +cmod.doc["Infimum"] = pdoc.Variable( + "Infimum", + cmod, + """Infimum: Symbol\n\nRepresents a symbol of type `clingo.SymbolType.Infimum`.""", +) +cmod.doc["Supremum"] = pdoc.Variable( + "Supremum", + cmod, + """Supremum: Symbol\n\nRepresents a symbol of type `clingo.SymbolType.Supremum`.""", +) pdoc.link_inheritance(ctx) prefix = "../clingo/python-api/{}".format(".".join(clingo.__version__.split(".")[:2])) @@ -69,5 +91,9 @@ def parse_aux(): open("{}/index.html".format(prefix), "w").write(cmod_html) open("{}/ast/index.html".format(prefix), "w").write(amod_html) -open("{}/index.html".format(cprefix), "w").write(cmod_html.replace("clingo/python-api/5.4", "clingo/python-api/current")) -open("{}/ast/index.html".format(cprefix), "w").write(amod_html.replace("clingo/python-api/5.4", "clingo/python-api/current")) +open("{}/index.html".format(cprefix), "w").write( + cmod_html.replace("clingo/python-api/5.4", "clingo/python-api/current") +) +open("{}/ast/index.html".format(cprefix), "w").write( + amod_html.replace("clingo/python-api/5.4", "clingo/python-api/current") +) diff --git a/doc/py/_gen/templates/html.mako b/doc/py/_gen/templates/html.mako index d09da49eb..266f67fa4 100644 --- a/doc/py/_gen/templates/html.mako +++ b/doc/py/_gen/templates/html.mako @@ -104,7 +104,7 @@ text = text.replace('Answer:', 'AnswerDUMMY') text = _re_returns.sub(_sub_returns, text) - # TODO: this kills links in the type lists + # TODO: this kills links in the type lists #md = to_markdown(text, module=module, link=link, _code_refs=re.compile(r'(?/g,">")}function r(e){return e.nodeName.toLowerCase()}function a(e,t){var r=e&&e.exec(t);return r&&0===r.index}function n(e){return E.test(e)}function i(e){var t,r,a,i,s=e.className+" ";if(s+=e.parentNode?e.parentNode.className:"",r=M.exec(s))return w(r[1])?r[1]:"no-highlight";for(s=s.split(/\s+/),t=0,a=s.length;a>t;t++)if(i=s[t],n(i)||w(i))return i}function s(e){var t,r={},a=Array.prototype.slice.call(arguments,1);for(t in e)r[t]=e[t];return a.forEach(function(e){for(t in e)r[t]=e[t]}),r}function c(e){var t=[];return function a(e,n){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?n+=i.nodeValue.length:1===i.nodeType&&(t.push({event:"start",offset:n,node:i}),n=a(i,n),r(i).match(/br|hr|img|input/)||t.push({event:"stop",offset:n,node:i}));return n}(e,0),t}function o(e,a,n){function i(){return e.length&&a.length?e[0].offset!==a[0].offset?e[0].offset"}function c(e){u+=""}function o(e){("start"===e.event?s:c)(e.node)}for(var l=0,u="",d=[];e.length||a.length;){var b=i();if(u+=t(n.substring(l,b[0].offset)),l=b[0].offset,b===e){d.reverse().forEach(c);do o(b.splice(0,1)[0]),b=i();while(b===e&&b.length&&b[0].offset===l);d.reverse().forEach(s)}else"start"===b[0].event?d.push(b[0].node):d.pop(),o(b.splice(0,1)[0])}return u+t(n.substr(l))}function l(e){return e.v&&!e.cached_variants&&(e.cached_variants=e.v.map(function(t){return s(e,{v:null},t)})),e.cached_variants||e.eW&&[s(e)]||[e]}function u(e){function t(e){return e&&e.source||e}function r(r,a){return new RegExp(t(r),"m"+(e.cI?"i":"")+(a?"g":""))}function a(n,i){if(!n.compiled){if(n.compiled=!0,n.k=n.k||n.bK,n.k){var s={},c=function(t,r){e.cI&&(r=r.toLowerCase()),r.split(" ").forEach(function(e){var r=e.split("|");s[r[0]]=[t,r[1]?Number(r[1]):1]})};"string"==typeof n.k?c("keyword",n.k):k(n.k).forEach(function(e){c(e,n.k[e])}),n.k=s}n.lR=r(n.l||/\w+/,!0),i&&(n.bK&&(n.b="\\b("+n.bK.split(" ").join("|")+")\\b"),n.b||(n.b=/\B|\b/),n.bR=r(n.b),n.e||n.eW||(n.e=/\B|\b/),n.e&&(n.eR=r(n.e)),n.tE=t(n.e)||"",n.eW&&i.tE&&(n.tE+=(n.e?"|":"")+i.tE)),n.i&&(n.iR=r(n.i)),null==n.r&&(n.r=1),n.c||(n.c=[]),n.c=Array.prototype.concat.apply([],n.c.map(function(e){return l("self"===e?n:e)})),n.c.forEach(function(e){a(e,n)}),n.starts&&a(n.starts,i);var o=n.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([n.tE,n.i]).map(t).filter(Boolean);n.t=o.length?r(o.join("|"),!0):{exec:function(){return null}}}}a(e)}function d(e,r,n,i){function s(e,t){var r,n;for(r=0,n=t.c.length;n>r;r++)if(a(t.c[r].bR,e))return t.c[r]}function c(e,t){if(a(e.eR,t)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?c(e.parent,t):void 0}function o(e,t){return!n&&a(t.iR,e)}function l(e,t){var r=v.cI?t[0].toLowerCase():t[0];return e.k.hasOwnProperty(r)&&e.k[r]}function p(e,t,r,a){var n=a?"":L.classPrefix,i='',i+t+s}function m(){var e,r,a,n;if(!N.k)return t(E);for(n="",r=0,N.lR.lastIndex=0,a=N.lR.exec(E);a;)n+=t(E.substring(r,a.index)),e=l(N,a),e?(M+=e[1],n+=p(e[0],t(a[0]))):n+=t(a[0]),r=N.lR.lastIndex,a=N.lR.exec(E);return n+t(E.substr(r))}function f(){var e="string"==typeof N.sL;if(e&&!x[N.sL])return t(E);var r=e?d(N.sL,E,!0,k[N.sL]):b(E,N.sL.length?N.sL:void 0);return N.r>0&&(M+=r.r),e&&(k[N.sL]=r.top),p(r.language,r.value,!1,!0)}function g(){C+=null!=N.sL?f():m(),E=""}function _(e){C+=e.cN?p(e.cN,"",!0):"",N=Object.create(e,{parent:{value:N}})}function h(e,t){if(E+=e,null==t)return g(),0;var r=s(t,N);if(r)return r.skip?E+=t:(r.eB&&(E+=t),g(),r.rB||r.eB||(E=t)),_(r,t),r.rB?0:t.length;var a=c(N,t);if(a){var n=N;n.skip?E+=t:(n.rE||n.eE||(E+=t),g(),n.eE&&(E=t));do N.cN&&(C+=R),N.skip||(M+=N.r),N=N.parent;while(N!==a.parent);return a.starts&&_(a.starts,""),n.rE?0:t.length}if(o(t,N))throw new Error('Illegal lexeme "'+t+'" for mode "'+(N.cN||"")+'"');return E+=t,t.length||1}var v=w(e);if(!v)throw new Error('Unknown language: "'+e+'"');u(v);var y,N=i||v,k={},C="";for(y=N;y!==v;y=y.parent)y.cN&&(C=p(y.cN,"",!0)+C);var E="",M=0;try{for(var B,S,$=0;;){if(N.t.lastIndex=$,B=N.t.exec(r),!B)break;S=h(r.substring($,B.index),B[0]),$=B.index+S}for(h(r.substr($)),y=N;y.parent;y=y.parent)y.cN&&(C+=R);return{r:M,value:C,language:e,top:N}}catch(A){if(A.message&&-1!==A.message.indexOf("Illegal"))return{r:0,value:t(r)};throw A}}function b(e,r){r=r||L.languages||k(x);var a={r:0,value:t(e)},n=a;return r.filter(w).forEach(function(t){var r=d(t,e,!1);r.language=t,r.r>n.r&&(n=r),r.r>a.r&&(n=a,a=r)}),n.language&&(a.second_best=n),a}function p(e){return L.tabReplace||L.useBR?e.replace(B,function(e,t){return L.useBR&&"\n"===e?"
":L.tabReplace?t.replace(/\t/g,L.tabReplace):""}):e}function m(e,t,r){var a=t?C[t]:r,n=[e.trim()];return e.match(/\bhljs\b/)||n.push("hljs"),-1===e.indexOf(a)&&n.push(a),n.join(" ").trim()}function f(e){var t,r,a,s,l,u=i(e);n(u)||(L.useBR?(t=document.createElementNS("http://www.w3.org/1999/xhtml","div"),t.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):t=e,l=t.textContent,a=u?d(u,l,!0):b(l),r=c(t),r.length&&(s=document.createElementNS("http://www.w3.org/1999/xhtml","div"),s.innerHTML=a.value,a.value=o(r,c(s),l)),a.value=p(a.value),e.innerHTML=a.value,e.className=m(e.className,u,a.language),e.result={language:a.language,re:a.r},a.second_best&&(e.second_best={language:a.second_best.language,re:a.second_best.r}))}function g(e){L=s(L,e)}function _(){if(!_.called){_.called=!0;var e=document.querySelectorAll("pre code");N.forEach.call(e,f)}}function h(){addEventListener("DOMContentLoaded",_,!1),addEventListener("load",_,!1)}function v(t,r){var a=x[t]=r(e);a.aliases&&a.aliases.forEach(function(e){C[e]=t})}function y(){return k(x)}function w(e){return e=(e||"").toLowerCase(),x[e]||x[C[e]]}var N=[],k=Object.keys,x={},C={},E=/^(no-?highlight|plain|text)$/i,M=/\blang(?:uage)?-([\w-]+)\b/i,B=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,R="
",L={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0};return e.highlight=d,e.highlightAuto=b,e.fixMarkup=p,e.highlightBlock=f,e.configure=g,e.initHighlighting=_,e.initHighlightingOnLoad=h,e.registerLanguage=v,e.listLanguages=y,e.getLanguage=w,e.inherit=s,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},e.C=function(t,r,a){var n=e.inherit({cN:"comment",b:t,e:r,c:[]},a||{});return n.c.push(e.PWM),n.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),n},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e.registerLanguage("apache",function(e){var t={cN:"number",b:"[\\$%]\\d+"};return{aliases:["apacheconf"],cI:!0,c:[e.HCM,{cN:"section",b:""},{cN:"attribute",b:/\w+/,r:0,k:{nomarkup:"order deny allow setenv rewriterule rewriteengine rewritecond documentroot sethandler errordocument loadmodule options header listen serverroot servername"},starts:{e:/$/,r:0,k:{literal:"on off all"},c:[{cN:"meta",b:"\\s\\[",e:"\\]$"},{cN:"variable",b:"[\\$%]\\{",e:"\\}",c:["self",t]},t,e.QSM]}}],i:/\S/}}),e.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},r={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/\b-?[a-z\._]+\b/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,r,a,t]}}),e.registerLanguage("coffeescript",function(e){var t={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super yield import export from as default await then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},r="[A-Za-z$_][0-9A-Za-z$_]*",a={cN:"subst",b:/#\{/,e:/}/,k:t},n=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,a]},{b:/"/,e:/"/,c:[e.BE,a]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[a,e.HCM]},{b:"//[gim]*",r:0},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/}]},{b:"@"+r},{sL:"javascript",eB:!0,eE:!0,v:[{b:"```",e:"```"},{b:"`",e:"`"}]}];a.c=n;var i=e.inherit(e.TM,{b:r}),s="(\\(.*\\))?\\s*\\B[-=]>",c={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:t,c:["self"].concat(n)}]};return{aliases:["coffee","cson","iced"],k:t,i:/\/\*/,c:n.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+r+"\\s*=\\s*"+s,e:"[-=]>",rB:!0,c:[i,c]},{b:/[:\(,=]\s*/,r:0,c:[{cN:"function",b:s,e:"[-=]>",rB:!0,c:[c]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[i]},i]},{b:r+":",e:":",rB:!0,rE:!0,r:0}])}}),e.registerLanguage("cpp",function(e){var t={cN:"keyword",b:"\\b[a-z\\d_]*_t\\b"},r={cN:"string",v:[{b:'(u8?|U)?L?"',e:'"',i:"\\n",c:[e.BE]},{b:'(u8?|U)?R"',e:'"',c:[e.BE]},{b:"'\\\\?.",e:"'",i:"."}]},a={cN:"number",v:[{b:"\\b(0b[01']+)"},{b:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],r:0},n={cN:"meta",b:/#\s*[a-z]+\b/,e:/$/,k:{"meta-keyword":"if else elif endif define undef warning error line pragma ifdef ifndef include"},c:[{b:/\\\n/,r:0},e.inherit(r,{cN:"meta-string"}),{cN:"meta-string",b:/<[^\n>]*>/,e:/$/,i:"\\n"},e.CLCM,e.CBCM]},i=e.IR+"\\s*\\(",s={keyword:"int float while private char catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignof constexpr decltype noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and or not",built_in:"std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr",literal:"true false nullptr NULL"},c=[t,e.CLCM,e.CBCM,a,r];return{aliases:["c","cc","h","c++","h++","hpp"],k:s,i:"",k:s,c:["self",t]},{b:e.IR+"::",k:s},{v:[{b:/=/,e:/;/},{b:/\(/,e:/\)/},{bK:"new throw return else",e:/;/}],k:s,c:c.concat([{b:/\(/,e:/\)/,k:s,c:c.concat(["self"]),r:0}]),r:0},{cN:"function",b:"("+e.IR+"[\\*&\\s]+)+"+i,rB:!0,e:/[{;=]/,eE:!0,k:s,i:/[^\w\s\*&]/,c:[{b:i,rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,k:s,r:0,c:[e.CLCM,e.CBCM,r,a,t]},e.CLCM,e.CBCM,n]},{cN:"class",bK:"class struct",e:/[{;:]/,c:[{b://,c:["self"]},e.TM]}]),exports:{preprocessor:n,strings:r,k:s}}}),e.registerLanguage("cs",function(e){var t={keyword:"abstract as base bool break byte case catch char checked const continue decimal default delegate do double enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long nameof object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual void volatile while add alias ascending async await by descending dynamic equals from get global group into join let on orderby partial remove select set value var where yield",literal:"null false true"},r={cN:"string",b:'@"',e:'"',c:[{b:'""'}]},a=e.inherit(r,{i:/\n/}),n={cN:"subst",b:"{",e:"}",k:t},i=e.inherit(n,{i:/\n/}),s={cN:"string",b:/\$"/,e:'"',i:/\n/,c:[{b:"{{"},{b:"}}"},e.BE,i]},c={cN:"string",b:/\$@"/,e:'"',c:[{b:"{{"},{b:"}}"},{b:'""'},n]},o=e.inherit(c,{i:/\n/,c:[{b:"{{"},{b:"}}"},{b:'""'},i]});n.c=[c,s,r,e.ASM,e.QSM,e.CNM,e.CBCM],i.c=[o,s,a,e.ASM,e.QSM,e.CNM,e.inherit(e.CBCM,{i:/\n/})];var l={v:[c,s,r,e.ASM,e.QSM]},u=e.IR+"(<"+e.IR+"(\\s*,\\s*"+e.IR+")*>)?(\\[\\])?";return{aliases:["csharp"],k:t,i:/::/,c:[e.C("///","$",{rB:!0,c:[{cN:"doctag",v:[{b:"///",r:0},{b:""},{b:""}]}]}),e.CLCM,e.CBCM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line region endregion pragma checksum"}},l,e.CNM,{bK:"class interface",e:/[{;=]/,i:/[^\s:]/,c:[e.TM,e.CLCM,e.CBCM]},{bK:"namespace",e:/[{;=]/,i:/[^\s:]/,c:[e.inherit(e.TM,{b:"[a-zA-Z](\\.?\\w)*"}),e.CLCM,e.CBCM]},{cN:"meta",b:"^\\s*\\[",eB:!0,e:"\\]",eE:!0,c:[{cN:"meta-string",b:/"/,e:/"/}]},{bK:"new return throw await else",r:0},{cN:"function",b:"("+u+"\\s+)+"+e.IR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:t,c:[{b:e.IR+"\\s*\\(",rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:t,r:0,c:[l,e.CNM,e.CBCM]},e.CLCM,e.CBCM]}]}}),e.registerLanguage("css",function(e){var t="[a-zA-Z-][a-zA-Z0-9_-]*",r={b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{eW:!0,eE:!0,c:[{b:/[\w-]+\(/,rB:!0,c:[{cN:"built_in",b:/[\w-]+/},{b:/\(/,e:/\)/,c:[e.ASM,e.QSM]}]},e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"number",b:"#[0-9A-Fa-f]+"},{cN:"meta",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,{cN:"selector-id",b:/#[A-Za-z0-9_-]+/},{cN:"selector-class",b:/\.[A-Za-z0-9_-]+/},{cN:"selector-attr",b:/\[/,e:/\]/,i:"$"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{b:"@",e:"[{;]",i:/:/,c:[{cN:"keyword",b:/\w+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[e.ASM,e.QSM,e.CSSNM]}]},{cN:"selector-tag",b:t,r:0},{b:"{",e:"}",i:/\S/,c:[e.CBCM,r]}]}}),e.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}}),e.registerLanguage("http",function(e){var t="HTTP/[0-9\\.]+";return{aliases:["https"],i:"\\S",c:[{b:"^"+t,e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{b:"^[A-Z]+ (.*?) "+t+"$",rB:!0,e:"$",c:[{cN:"string",b:" ",e:" ",eB:!0,eE:!0},{b:t},{cN:"keyword",b:"[A-Z]+"}]},{cN:"attribute",b:"^\\w",e:": ",eE:!0,i:"\\n|\\s|=",starts:{e:"$",r:0}},{b:"\\n\\n",starts:{sL:[],eW:!0}}]}}),e.registerLanguage("ini",function(e){var t={cN:"string",c:[e.BE],v:[{b:"'''",e:"'''",r:10},{b:'"""',e:'"""',r:10},{b:'"',e:'"'},{b:"'",e:"'"}]};return{aliases:["toml"],cI:!0,i:/\S/,c:[e.C(";","$"),e.HCM,{cN:"section",b:/^\s*\[+/,e:/\]+/},{b:/^[a-z0-9\[\]_-]+\s*=\s*/,e:"$",rB:!0,c:[{cN:"attr",b:/[a-z0-9\[\]_-]+/},{b:/=/,eW:!0,r:0,c:[{cN:"literal",b:/\bon|off|true|false|yes|no\b/},{cN:"variable",v:[{b:/\$[\w\d"][\w\d_]*/},{b:/\$\{(.*?)}/}]},t,{cN:"number",b:/([\+\-]+)?[\d]+_[\d_]+/},e.NM]}]}]}}),e.registerLanguage("java",function(e){var t="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=t+"(<"+t+"(\\s*,\\s*"+t+")*>)?",a="false synchronized int abstract float private char boolean static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do",n="\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",i={cN:"number",b:n,r:0};return{aliases:["jsp"],k:a,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",r:0},{cN:"function",b:"("+r+"\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:a,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:a,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},i,{cN:"meta",b:"@[A-Za-z]+"}]}}),e.registerLanguage("javascript",function(e){var t="[A-Za-z$_][0-9A-Za-z$_]*",r={keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},a={cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},n={cN:"subst",b:"\\$\\{",e:"\\}",k:r,c:[]},i={cN:"string",b:"`",e:"`",c:[e.BE,n]};n.c=[e.ASM,e.QSM,i,a,e.RM];var s=n.c.concat([e.CBCM,e.CLCM]);return{aliases:["js","jsx"],k:r,c:[{cN:"meta",r:10,b:/^\s*['"]use (strict|asm)['"]/},{cN:"meta",b:/^#!/,e:/$/},e.ASM,e.QSM,i,e.CLCM,e.CBCM,a,{b:/[{,]\s*/,r:0,c:[{b:t+"\\s*:",rB:!0,r:0,c:[{cN:"attr",b:t,r:0}]}]},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{cN:"function",b:"(\\(.*?\\)|"+t+")\\s*=>",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:t},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:r,c:s}]}]},{b://,sL:"xml",c:[{b:/<\w+\s*\/>/,skip:!0},{b:/<\w+/,e:/(\/\w+|\w+\/)>/,skip:!0,c:[{b:/<\w+\s*\/>/,skip:!0},"self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:t}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:s}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#(?!!)/}}),e.registerLanguage("json",function(e){var t={literal:"true false null"},r=[e.QSM,e.CNM],a={e:",",eW:!0,eE:!0,c:r,k:t},n={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(a,{b:/:/})],i:"\\S"},i={b:"\\[",e:"\\]",c:[e.inherit(a)],i:"\\S"};return r.splice(r.length,0,n,i),{c:r,k:t,i:"\\S"}}),e.registerLanguage("makefile",function(e){var t={cN:"variable",v:[{b:"\\$\\("+e.UIR+"\\)",c:[e.BE]},{b:/\$[@%`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist"],cI:!0,c:[{cN:"meta",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},e.C("",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0}]},{cN:"tag",b:"|$)",e:">",k:{name:"style"},c:[r],starts:{e:"",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"|$)",e:">",k:{name:"script"},c:[r],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"meta",v:[{b:/<\?xml/,e:/\?>/,r:10},{b:/<\?\w+/,e:/\?>/}]},{cN:"tag",b:"",c:[{cN:"name",b:/[^\/><\s]+/,r:0},r]}]}}),e.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"section",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"quote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"^```w*s*$",e:"^```s*$"},{b:"`.+?`"},{b:"^( {4}| )",e:"$",r:0}]},{b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"string",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"symbol",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:/^\[[^\n]+\]:/,rB:!0,c:[{cN:"symbol",b:/\[/,e:/\]/,eB:!0,eE:!0},{cN:"link",b:/:\s*/,e:/$/,eB:!0}]}]}}),e.registerLanguage("nginx",function(e){var t={cN:"variable",v:[{b:/\$\d+/},{b:/\$\{/,e:/}/},{b:"[\\$\\@]"+e.UIR}]},r={eW:!0,l:"[a-z/_]+",k:{literal:"on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"},r:0,i:"=>",c:[e.HCM,{cN:"string",c:[e.BE,t],v:[{b:/"/,e:/"/},{b:/'/,e:/'/}]},{b:"([a-z]+):/",e:"\\s",eW:!0,eE:!0,c:[t]},{cN:"regexp",c:[e.BE,t],v:[{b:"\\s\\^",e:"\\s|{|;",rE:!0},{b:"~\\*?\\s+",e:"\\s|{|;",rE:!0},{b:"\\*(\\.[a-z\\-]+)+"},{b:"([a-z\\-]+\\.)+\\*"}]},{cN:"number",b:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{cN:"number",b:"\\b\\d+[kKmMgGdshdwy]*\\b",r:0},t]};return{aliases:["nginxconf"],c:[e.HCM,{b:e.UIR+"\\s+{",rB:!0,e:"{",c:[{cN:"section",b:e.UIR}],r:0},{b:e.UIR+"\\s",e:";|{",rB:!0,c:[{cN:"attribute",b:e.UIR,starts:r}],r:0}],i:"[^\\s\\}]"}}),e.registerLanguage("objectivec",function(e){var t={cN:"built_in",b:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},r={keyword:"int float while char export sizeof typedef const struct for union unsigned long volatile static bool mutable if do return goto void enum else break extern asm case short default double register explicit signed typename this switch continue wchar_t inline readonly assign readwrite self @synchronized id typeof nonatomic super unichar IBOutlet IBAction strong weak copy in out inout bycopy byref oneway __strong __weak __block __autoreleasing @private @protected @public @try @property @end @throw @catch @finally @autoreleasepool @synthesize @dynamic @selector @optional @required @encode @package @import @defs @compatibility_alias __bridge __bridge_transfer __bridge_retained __bridge_retain __covariant __contravariant __kindof _Nonnull _Nullable _Null_unspecified __FUNCTION__ __PRETTY_FUNCTION__ __attribute__ getter setter retain unsafe_unretained nonnull nullable null_unspecified null_resettable class instancetype NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN",literal:"false true FALSE TRUE nil YES NO NULL",built_in:"BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once"},a=/[a-zA-Z@][a-zA-Z0-9_]*/,n="@interface @class @protocol @implementation";return{aliases:["mm","objc","obj-c"],k:r,l:a,i:""}]}]},{cN:"class",b:"("+n.split(" ").join("|")+")\\b",e:"({|$)",eE:!0,k:n,l:a,c:[e.UTM]},{b:"\\."+e.UIR,r:0}]}}),e.registerLanguage("perl",function(e){var t="getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qqfileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmgetsub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedirioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when",r={cN:"subst",b:"[$@]\\{",e:"\\}",k:t},a={b:"->{",e:"}"},n={v:[{b:/\$\d/},{b:/[\$%@](\^\w\b|#\w+(::\w+)*|{\w+}|\w+(::\w*)*)/},{b:/[\$%@][^\s\w{]/,r:0}]},i=[e.BE,r,n],s=[n,e.HCM,e.C("^\\=\\w","\\=cut",{eW:!0}),a,{cN:"string",c:i,v:[{b:"q[qwxr]?\\s*\\(",e:"\\)",r:5},{b:"q[qwxr]?\\s*\\[",e:"\\]",r:5},{b:"q[qwxr]?\\s*\\{",e:"\\}",r:5},{b:"q[qwxr]?\\s*\\|",e:"\\|",r:5},{b:"q[qwxr]?\\s*\\<",e:"\\>",r:5},{b:"qw\\s+q",e:"q",r:5},{b:"'",e:"'",c:[e.BE]},{b:'"',e:'"'},{b:"`",e:"`",c:[e.BE]},{b:"{\\w+}",c:[],r:0},{b:"-?\\w+\\s*\\=\\>",c:[],r:0}]},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\/\\/|"+e.RSR+"|\\b(split|return|print|reverse|grep)\\b)\\s*",k:"split return print reverse grep",r:0,c:[e.HCM,{cN:"regexp",b:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",r:10},{cN:"regexp",b:"(m|qr)?/",e:"/[a-z]*",c:[e.BE],r:0}]},{cN:"function",bK:"sub",e:"(\\s*\\(.*?\\))?[;{]",eE:!0,r:5,c:[e.TM]},{b:"-\\w\\b",r:0},{b:"^__DATA__$",e:"^__END__$",sL:"mojolicious",c:[{b:"^@@.*",e:"$",cN:"comment"}]}];return r.c=s,a.c=s,{aliases:["pl","pm"],l:/[\w\.]+/,k:t,c:s}}),e.registerLanguage("php",function(e){var t={b:"\\$+[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]*"},r={cN:"meta",b:/<\?(php)?|\?>/},a={cN:"string",c:[e.BE,r],v:[{b:'b"',e:'"'},{b:"b'",e:"'"},e.inherit(e.ASM,{i:null}),e.inherit(e.QSM,{i:null})]},n={v:[e.BNM,e.CNM]};return{aliases:["php3","php4","php5","php6"],cI:!0,k:"and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception default die require __FUNCTION__ enddeclare final try switch continue endfor endif declare unset true false trait goto instanceof insteadof __DIR__ __NAMESPACE__ yield finally",c:[e.HCM,e.C("//","$",{c:[r]}),e.C("/\\*","\\*/",{c:[{cN:"doctag",b:"@[A-Za-z]+"}]}),e.C("__halt_compiler.+?;",!1,{eW:!0,k:"__halt_compiler",l:e.UIR}),{cN:"string",b:/<<<['"]?\w+['"]?$/,e:/^\w+;?$/,c:[e.BE,{cN:"subst",v:[{b:/\$\w+/},{b:/\{\$/,e:/\}/}]}]},r,{cN:"keyword",b:/\$this\b/},t,{b:/(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/},{cN:"function",bK:"function",e:/[;{]/,eE:!0,i:"\\$|\\[|%",c:[e.UTM,{cN:"params",b:"\\(",e:"\\)",c:["self",t,e.CBCM,a,n]}]},{cN:"class",bK:"class interface",e:"{",eE:!0,i:/[:\(\$"]/,c:[{bK:"extends implements"},e.UTM]},{bK:"namespace",e:";",i:/[\.']/,c:[e.UTM]},{bK:"use",e:";",c:[e.UTM]},{b:"=>"},a,n]}}),e.registerLanguage("python",function(e){var t={keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10 None True False",built_in:"Ellipsis NotImplemented"},r={cN:"meta",b:/^(>>>|\.\.\.) /},a={cN:"subst",b:/\{/,e:/\}/,k:t,i:/#/},n={cN:"string",c:[e.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[r],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[r],r:10},{b:/(fr|rf|f)'''/,e:/'''/,c:[r,a]},{b:/(fr|rf|f)"""/,e:/"""/,c:[r,a]},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},{b:/(fr|rf|f)'/,e:/'/,c:[a]},{b:/(fr|rf|f)"/,e:/"/,c:[a]},e.ASM,e.QSM]},i={cN:"number",r:0,v:[{b:e.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:e.CNR+"[lLjJ]?"}]},s={cN:"params",b:/\(/,e:/\)/,c:["self",r,i,n]};return a.c=[n,i,r],{aliases:["py","gyp"],k:t,i:/(<\/|->|\?)|=>/,c:[r,i,n,e.HCM,{v:[{cN:"function",bK:"def"},{cN:"class",bK:"class"}],e:/:/,i:/[${=;\n,]/,c:[e.UTM,s,{b:/->/,eW:!0,k:"None"}]},{cN:"meta",b:/^[\t ]*@/,e:/$/},{b:/\b(print|exec)\(/}]}}),e.registerLanguage("ruby",function(e){ -var t="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",r={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},a={cN:"doctag",b:"@[A-Za-z]+"},n={b:"#<",e:">"},i=[e.C("#","$",{c:[a]}),e.C("^\\=begin","^\\=end",{c:[a],r:10}),e.C("^__END__","\\n$")],s={cN:"subst",b:"#\\{",e:"}",k:r},c={cN:"string",c:[e.BE,s],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{b:/<<(-?)\w+$/,e:/^\s*\w+$/}]},o={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:r},l=[c,n,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(i)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:t}),o].concat(i)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[c,{b:t}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:r},{b:"("+e.RSR+"|unless)\\s*",k:"unless",c:[n,{cN:"regexp",c:[e.BE,s],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(i),r:0}].concat(i);s.c=l,o.c=l;var u="[>?]>",d="[\\w#]+\\(\\w+\\):\\d+:\\d+>",b="(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>",p=[{b:/^\s*=>/,starts:{e:"$",c:l}},{cN:"meta",b:"^("+u+"|"+d+"|"+b+")",starts:{e:"$",c:l}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:r,i:/\/\*/,c:i.concat(p).concat(l)}}),e.registerLanguage("shell",function(e){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}}),e.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*#]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}}),e}); \ No newline at end of file +var t="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",r={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},a={cN:"doctag",b:"@[A-Za-z]+"},n={b:"#<",e:">"},i=[e.C("#","$",{c:[a]}),e.C("^\\=begin","^\\=end",{c:[a],r:10}),e.C("^__END__","\\n$")],s={cN:"subst",b:"#\\{",e:"}",k:r},c={cN:"string",c:[e.BE,s],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{b:/<<(-?)\w+$/,e:/^\s*\w+$/}]},o={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:r},l=[c,n,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(i)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:t}),o].concat(i)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[c,{b:t}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:r},{b:"("+e.RSR+"|unless)\\s*",k:"unless",c:[n,{cN:"regexp",c:[e.BE,s],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(i),r:0}].concat(i);s.c=l,o.c=l;var u="[>?]>",d="[\\w#]+\\(\\w+\\):\\d+:\\d+>",b="(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>",p=[{b:/^\s*=>/,starts:{e:"$",c:l}},{cN:"meta",b:"^("+u+"|"+d+"|"+b+")",starts:{e:"$",c:l}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:r,i:/\/\*/,c:i.concat(p).concat(l)}}),e.registerLanguage("shell",function(e){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}}),e.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*#]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}}),e}); diff --git a/examples/c/application.c b/examples/c/application.c index 36fdd6aac..fabae5996 100644 --- a/examples/c/application.c +++ b/examples/c/application.c @@ -1,103 +1,122 @@ #include -#include #include +#include #include // struct to store parsed command line arguments typedef struct options { - char const *program; + char const *program; } options_t; char const *name(void *data) { - (void)data; - // the name of the program printed in its help output - return "example"; + (void)data; + // the name of the program printed in its help output + return "example"; } char const *version(void *data) { - (void)data; - // the version of the program printed in its help output - return "1.0.0"; + (void)data; + // the version of the program printed in its help output + return "1.0.0"; } bool solve(clingo_control_t *ctl) { - bool ret = true; - clingo_solve_handle_t *handle; - clingo_model_t const *model; - clingo_solve_result_bitset_t result; - - // get a solve handle - if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { goto error; } - // loop over all models - while (true) { - if (!clingo_solve_handle_resume(handle)) { goto error; } - if (!clingo_solve_handle_model(handle, &model)) { goto error; } - - if (!model) { break; } - } - // close the solve handle - if (!clingo_solve_handle_get(handle, &result)) { goto error; } - - goto out; + bool ret = true; + clingo_solve_handle_t *handle; + clingo_model_t const *model; + clingo_solve_result_bitset_t result; + + // get a solve handle + if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { + goto error; + } + // loop over all models + while (true) { + if (!clingo_solve_handle_resume(handle)) { + goto error; + } + if (!clingo_solve_handle_model(handle, &model)) { + goto error; + } + + if (!model) { + break; + } + } + // close the solve handle + if (!clingo_solve_handle_get(handle, &result)) { + goto error; + } + + goto out; error: - ret = false; + ret = false; out: - // free the solve handle - return clingo_solve_handle_close(handle) && ret; + // free the solve handle + return clingo_solve_handle_close(handle) && ret; } bool parse_option(char const *value, void *data) { - char **program = (char **)data; - // allocate memory for program name - // note that we forgo freeing memory for the example - // (it could be done early in the main loop or after clingo_main finished) - if (!(*program = (char *)malloc(strlen(value) + 1))) { - return false; - } - strcpy(*program, value); - return true; + char **program = (char **)data; + // allocate memory for program name + // note that we forgo freeing memory for the example + // (it could be done early in the main loop or after clingo_main finished) + if (!(*program = (char *)malloc(strlen(value) + 1))) { + return false; + } + strcpy(*program, value); + return true; } bool register_options(clingo_options_t *options, void *data) { - options_t *options_ = (options_t*)data; - // register an option to overwrite which program part to ground - return clingo_options_add(options, "Example", "program", "Override the default program part to ground", parse_option, &options_->program, false, ""); + options_t *options_ = (options_t *)data; + // register an option to overwrite which program part to ground + return clingo_options_add(options, "Example", "program", "Override the default program part to ground", + parse_option, &options_->program, false, ""); } bool main_loop(clingo_control_t *ctl, char const *const *files, size_t size, void *data) { - options_t *options = (options_t*)data; - bool ret = true; - clingo_part_t parts[] = {{ options->program ? options->program : "base", NULL, 0 }}; - char const *const *file; - - // load files into the control object - for (file = files; file != files + size; ++file) { - if (!clingo_control_load(ctl, *file)) { goto error; } - } - // if no files are given read from stdin - if (size == 0) { - if (!clingo_control_load(ctl, "-")) { goto error; } - } - - // ground - if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { goto error; } - - // solve - if (!solve(ctl)) { goto error; } - - goto out; + options_t *options = (options_t *)data; + bool ret = true; + clingo_part_t parts[] = {{options->program ? options->program : "base", NULL, 0}}; + char const *const *file; + + // load files into the control object + for (file = files; file != files + size; ++file) { + if (!clingo_control_load(ctl, *file)) { + goto error; + } + } + // if no files are given read from stdin + if (size == 0) { + if (!clingo_control_load(ctl, "-")) { + goto error; + } + } + + // ground + if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { + goto error; + } + + // solve + if (!solve(ctl)) { + goto error; + } + + goto out; error: - ret = false; + ret = false; out: - return ret; + return ret; } int main(int argc, char const **argv) { - options_t options = { NULL }; - clingo_application_t app = { name, version, NULL, main_loop, NULL, NULL, register_options, NULL }; - return clingo_main(&app, argv+1, argc-1, &options); + options_t options = {NULL}; + clingo_application_t app = {name, version, NULL, main_loop, NULL, NULL, register_options, NULL}; + return clingo_main(&app, argv + 1, argc - 1, &options); } diff --git a/examples/c/ast.c b/examples/c/ast.c index 96409e926..e6863f6b9 100644 --- a/examples/c/ast.c +++ b/examples/c/ast.c @@ -1,229 +1,300 @@ #include -#include #include +#include bool print_model(clingo_model_t const *model) { - bool ret = true; - clingo_symbol_t *atoms = NULL; - size_t atoms_n; - clingo_symbol_t const *it, *ie; - char *str = NULL; - size_t str_n = 0; - - // determine the number of (shown) symbols in the model - if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; } + bool ret = true; + clingo_symbol_t *atoms = NULL; + size_t atoms_n; + clingo_symbol_t const *it, *ie; + char *str = NULL; + size_t str_n = 0; + + // determine the number of (shown) symbols in the model + if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { + goto error; + } - // allocate required memory to hold all the symbols - if (!(atoms = (clingo_symbol_t*)malloc(sizeof(*atoms) * atoms_n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); - goto error; - } + // allocate required memory to hold all the symbols + if (!(atoms = (clingo_symbol_t *)malloc(sizeof(*atoms) * atoms_n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); + goto error; + } - // retrieve the symbols in the model - if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { goto error; } + // retrieve the symbols in the model + if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { + goto error; + } - printf("Model:"); + printf("Model:"); - for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { - size_t n; - char *str_new; + for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { + size_t n; + char *str_new; - // determine size of the string representation of the next symbol in the model - if (!clingo_symbol_to_string_size(*it, &n)) { goto error; } + // determine size of the string representation of the next symbol in the model + if (!clingo_symbol_to_string_size(*it, &n)) { + goto error; + } - if (str_n < n) { - // allocate required memory to hold the symbol's string - if (!(str_new = (char*)realloc(str, sizeof(*str) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); - goto error; - } + if (str_n < n) { + // allocate required memory to hold the symbol's string + if (!(str_new = (char *)realloc(str, sizeof(*str) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + goto error; + } - str = str_new; - str_n = n; - } + str = str_new; + str_n = n; + } - // retrieve the symbol's string - if (!clingo_symbol_to_string(*it, str, n)) { goto error; } + // retrieve the symbol's string + if (!clingo_symbol_to_string(*it, str, n)) { + goto error; + } - printf(" %s", str); - } + printf(" %s", str); + } - printf("\n"); - goto out; + printf("\n"); + goto out; error: - ret = false; + ret = false; out: - if (atoms) { free(atoms); } - if (str) { free(str); } + if (atoms) { + free(atoms); + } + if (str) { + free(str); + } - return ret; + return ret; } typedef struct { - clingo_location_t *loc; - clingo_ast_t *atom; - clingo_program_builder_t *builder; + clingo_location_t *loc; + clingo_ast_t *atom; + clingo_program_builder_t *builder; } on_statement_data; // adds atom enable to all rule bodies -bool on_statement (clingo_ast_t *stm, on_statement_data *data) { - bool ret = true; - clingo_ast_t *lit = NULL; - clingo_ast_type_t type; - size_t size; +bool on_statement(clingo_ast_t *stm, on_statement_data *data) { + bool ret = true; + clingo_ast_t *lit = NULL; + clingo_ast_type_t type; + size_t size; - if (!clingo_ast_get_type(stm, &type)) { goto error; } + if (!clingo_ast_get_type(stm, &type)) { + goto error; + } - // pass through all statements that are not rules - if (type != clingo_ast_type_rule) { - if (!clingo_program_builder_add(data->builder, stm)) { goto error; } - goto out; - } + // pass through all statements that are not rules + if (type != clingo_ast_type_rule) { + if (!clingo_program_builder_add(data->builder, stm)) { + goto error; + } + goto out; + } - // create literal "enable" - if (!clingo_ast_build(clingo_ast_type_literal, &lit, data->loc, clingo_ast_sign_no_sign, data->atom)) { - goto error; - } + // create literal "enable" + if (!clingo_ast_build(clingo_ast_type_literal, &lit, data->loc, clingo_ast_sign_no_sign, data->atom)) { + goto error; + } - if (!clingo_ast_attribute_size_ast_array(stm, clingo_ast_attribute_body, &size)) { - goto error; - } + if (!clingo_ast_attribute_size_ast_array(stm, clingo_ast_attribute_body, &size)) { + goto error; + } - // append the literal to the rule body - if (!clingo_ast_attribute_insert_ast_at(stm, clingo_ast_attribute_body, size, lit)) { - goto error; - } + // append the literal to the rule body + if (!clingo_ast_attribute_insert_ast_at(stm, clingo_ast_attribute_body, size, lit)) { + goto error; + } - // add the rewritten statement to the program - if (!clingo_program_builder_add(data->builder, stm)) { goto error; } + // add the rewritten statement to the program + if (!clingo_program_builder_add(data->builder, stm)) { + goto error; + } - goto out; + goto out; error: - ret = false; + ret = false; out: - if (lit != NULL) { - clingo_ast_release(lit); - } - return ret; + if (lit != NULL) { + clingo_ast_release(lit); + } + return ret; } bool solve(clingo_control_t *ctl, clingo_solve_result_bitset_t *result) { - bool ret = true; - clingo_solve_handle_t *handle; - clingo_model_t const *model; - - // get a solve handle - if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { goto error; } - // loop over all models - while (true) { - if (!clingo_solve_handle_resume(handle)) { goto error; } - if (!clingo_solve_handle_model(handle, &model)) { goto error; } - // print the model - if (model) { print_model(model); } - // stop if there are no more models - else { break; } - } - // close the solve handle - if (!clingo_solve_handle_get(handle, result)) { goto error; } - - goto out; + bool ret = true; + clingo_solve_handle_t *handle; + clingo_model_t const *model; + + // get a solve handle + if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { + goto error; + } + // loop over all models + while (true) { + if (!clingo_solve_handle_resume(handle)) { + goto error; + } + if (!clingo_solve_handle_model(handle, &model)) { + goto error; + } + // print the model + if (model) { + print_model(model); + } + // stop if there are no more models + else { + break; + } + } + // close the solve handle + if (!clingo_solve_handle_get(handle, result)) { + goto error; + } + + goto out; error: - ret = false; + ret = false; out: - // free the solve handle - return clingo_solve_handle_close(handle) && ret; + // free the solve handle + return clingo_solve_handle_close(handle) && ret; } int main(int argc, char const **argv) { - char const *error_message; - int ret = 0; - clingo_solve_result_bitset_t solve_ret; - clingo_control_t *ctl = NULL; - clingo_symbolic_atoms_t const *atoms = NULL; - clingo_solve_handle_t *handle = NULL; - clingo_symbol_t sym; - clingo_symbolic_atom_iterator_t atm_it; - clingo_literal_t atm; - clingo_location_t location; - clingo_ast_t *term = NULL; - on_statement_data data = {NULL, NULL, NULL}; - clingo_part_t parts[] = {{ "base", NULL, 0 }}; - - // create a control object and pass command line arguments - if (!clingo_control_new(argv+1, argc-1, NULL, NULL, 20, &ctl) != 0) { goto error; } - - // get the program builder - if (!clingo_program_builder_init(ctl, &data.builder)) { goto error; } - - // initialize the location - location.begin_line = location.end_line = 0; - location.begin_column = location.end_column = 0; - location.begin_file = location.end_file = ""; - data.loc = &location; - - // initilize atom to add - if (!clingo_symbol_create_id("enable", true, &sym)) { goto error; } - - if (!clingo_ast_build(clingo_ast_type_symbolic_term, &term, data.loc, sym)) { - goto error; - } - if (!clingo_ast_build(clingo_ast_type_symbolic_atom, &data.atom, term)) { - goto error; - } - - // begin building a program - if (!clingo_program_builder_begin(data.builder)) { goto error; } - - // get the AST of the program - if (!clingo_ast_parse_string("a :- not b. b :- not a.", (clingo_ast_callback_t)on_statement, &data, NULL, NULL, NULL, 20)) { goto error; } - - // finish building a program - if (!clingo_program_builder_end(data.builder)) { goto error; } - - // add the external statement: #external enable. - if (!clingo_control_add(ctl, "base", NULL, 0, "#external enable.")) { - goto error; - } - - // ground the base part - if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { goto error; } - - // get the program literal coresponding to the external atom - if (!clingo_control_symbolic_atoms(ctl, &atoms)) { goto error; } - if (!clingo_symbolic_atoms_find(atoms, sym, &atm_it)) { goto error; } - if (!clingo_symbolic_atoms_literal(atoms, atm_it, &atm)) { goto error; } - - // solve with external enable = false - printf("Solving with enable = false...\n"); - if (!solve(ctl, &solve_ret)) { goto error; } - // solve with external enable = true - printf("Solving with enable = true...\n"); - if (!clingo_control_assign_external(ctl, atm, clingo_truth_value_true)) { goto error; } - if (!solve(ctl, &solve_ret)) { goto error; } - // solve with external enable = false - printf("Solving with enable = false...\n"); - if (!clingo_control_assign_external(ctl, atm, clingo_truth_value_false)) { goto error; } - if (!solve(ctl, &solve_ret)) { goto error; } - - goto out; + char const *error_message; + int ret = 0; + clingo_solve_result_bitset_t solve_ret; + clingo_control_t *ctl = NULL; + clingo_symbolic_atoms_t const *atoms = NULL; + clingo_solve_handle_t *handle = NULL; + clingo_symbol_t sym; + clingo_symbolic_atom_iterator_t atm_it; + clingo_literal_t atm; + clingo_location_t location; + clingo_ast_t *term = NULL; + on_statement_data data = {NULL, NULL, NULL}; + clingo_part_t parts[] = {{"base", NULL, 0}}; + + // create a control object and pass command line arguments + if (!clingo_control_new(argv + 1, argc - 1, NULL, NULL, 20, &ctl) != 0) { + goto error; + } + + // get the program builder + if (!clingo_program_builder_init(ctl, &data.builder)) { + goto error; + } + + // initialize the location + location.begin_line = location.end_line = 0; + location.begin_column = location.end_column = 0; + location.begin_file = location.end_file = ""; + data.loc = &location; + + // initilize atom to add + if (!clingo_symbol_create_id("enable", true, &sym)) { + goto error; + } + + if (!clingo_ast_build(clingo_ast_type_symbolic_term, &term, data.loc, sym)) { + goto error; + } + if (!clingo_ast_build(clingo_ast_type_symbolic_atom, &data.atom, term)) { + goto error; + } + + // begin building a program + if (!clingo_program_builder_begin(data.builder)) { + goto error; + } + + // get the AST of the program + if (!clingo_ast_parse_string("a :- not b. b :- not a.", (clingo_ast_callback_t)on_statement, &data, NULL, NULL, + NULL, 20)) { + goto error; + } + + // finish building a program + if (!clingo_program_builder_end(data.builder)) { + goto error; + } + + // add the external statement: #external enable. + if (!clingo_control_add(ctl, "base", NULL, 0, "#external enable.")) { + goto error; + } + + // ground the base part + if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { + goto error; + } + + // get the program literal coresponding to the external atom + if (!clingo_control_symbolic_atoms(ctl, &atoms)) { + goto error; + } + if (!clingo_symbolic_atoms_find(atoms, sym, &atm_it)) { + goto error; + } + if (!clingo_symbolic_atoms_literal(atoms, atm_it, &atm)) { + goto error; + } + + // solve with external enable = false + printf("Solving with enable = false...\n"); + if (!solve(ctl, &solve_ret)) { + goto error; + } + // solve with external enable = true + printf("Solving with enable = true...\n"); + if (!clingo_control_assign_external(ctl, atm, clingo_truth_value_true)) { + goto error; + } + if (!solve(ctl, &solve_ret)) { + goto error; + } + // solve with external enable = false + printf("Solving with enable = false...\n"); + if (!clingo_control_assign_external(ctl, atm, clingo_truth_value_false)) { + goto error; + } + if (!solve(ctl, &solve_ret)) { + goto error; + } + + goto out; error: - if (!(error_message = clingo_error_message())) { error_message = "error"; } + if (!(error_message = clingo_error_message())) { + error_message = "error"; + } - printf("%s\n", error_message); - ret = clingo_error_code(); + printf("%s\n", error_message); + ret = clingo_error_code(); out: - if (term) { clingo_ast_release(term); } - if (data.atom) { clingo_ast_release(data.atom); } - if (handle) { clingo_solve_handle_close(handle); } - if (ctl) { clingo_control_free(ctl); } + if (term) { + clingo_ast_release(term); + } + if (data.atom) { + clingo_ast_release(data.atom); + } + if (handle) { + clingo_solve_handle_close(handle); + } + if (ctl) { + clingo_control_free(ctl); + } - return ret; + return ret; } diff --git a/examples/c/backend.c b/examples/c/backend.c index ec3cc5c72..b4ae87a96 100644 --- a/examples/c/backend.c +++ b/examples/c/backend.c @@ -1,176 +1,236 @@ +#include #include -#include #include -#include +#include bool print_model(clingo_model_t const *model) { - bool ret = true; - clingo_symbol_t *atoms = NULL; - size_t atoms_n; - clingo_symbol_t const *it, *ie; - char *str = NULL; - size_t str_n = 0; - - // determine the number of (shown) symbols in the model - if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; } + bool ret = true; + clingo_symbol_t *atoms = NULL; + size_t atoms_n; + clingo_symbol_t const *it, *ie; + char *str = NULL; + size_t str_n = 0; + + // determine the number of (shown) symbols in the model + if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { + goto error; + } - // allocate required memory to hold all the symbols - if (!(atoms = (clingo_symbol_t*)malloc(sizeof(*atoms) * atoms_n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); - goto error; - } + // allocate required memory to hold all the symbols + if (!(atoms = (clingo_symbol_t *)malloc(sizeof(*atoms) * atoms_n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); + goto error; + } - // retrieve the symbols in the model - if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { goto error; } + // retrieve the symbols in the model + if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { + goto error; + } - printf("Model:"); + printf("Model:"); - for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { - size_t n; - char *str_new; + for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { + size_t n; + char *str_new; - // determine size of the string representation of the next symbol in the model - if (!clingo_symbol_to_string_size(*it, &n)) { goto error; } + // determine size of the string representation of the next symbol in the model + if (!clingo_symbol_to_string_size(*it, &n)) { + goto error; + } - if (str_n < n) { - // allocate required memory to hold the symbol's string - if (!(str_new = (char*)realloc(str, sizeof(*str) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); - goto error; - } + if (str_n < n) { + // allocate required memory to hold the symbol's string + if (!(str_new = (char *)realloc(str, sizeof(*str) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + goto error; + } - str = str_new; - str_n = n; - } + str = str_new; + str_n = n; + } - // retrieve the symbol's string - if (!clingo_symbol_to_string(*it, str, n)) { goto error; } + // retrieve the symbol's string + if (!clingo_symbol_to_string(*it, str, n)) { + goto error; + } - printf(" %s", str); - } + printf(" %s", str); + } - printf("\n"); - goto out; + printf("\n"); + goto out; error: - ret = false; + ret = false; out: - if (atoms) { free(atoms); } - if (str) { free(str); } + if (atoms) { + free(atoms); + } + if (str) { + free(str); + } - return ret; + return ret; } bool solve(clingo_control_t *ctl, clingo_solve_result_bitset_t *result) { - bool ret = true; - clingo_solve_handle_t *handle; - clingo_model_t const *model; - - // get a solve handle - if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { goto error; } - // loop over all models - while (true) { - if (!clingo_solve_handle_resume(handle)) { goto error; } - if (!clingo_solve_handle_model(handle, &model)) { goto error; } - // print the model - if (model) { print_model(model); } - // stop if there are no more models - else { break; } - } - // close the solve handle - if (!clingo_solve_handle_get(handle, result)) { goto error; } - - goto out; + bool ret = true; + clingo_solve_handle_t *handle; + clingo_model_t const *model; + + // get a solve handle + if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { + goto error; + } + // loop over all models + while (true) { + if (!clingo_solve_handle_resume(handle)) { + goto error; + } + if (!clingo_solve_handle_model(handle, &model)) { + goto error; + } + // print the model + if (model) { + print_model(model); + } + // stop if there are no more models + else { + break; + } + } + // close the solve handle + if (!clingo_solve_handle_get(handle, result)) { + goto error; + } + + goto out; error: - ret = false; + ret = false; out: - // free the solve handle - return clingo_solve_handle_close(handle) && ret; + // free the solve handle + return clingo_solve_handle_close(handle) && ret; } int main(int argc, char const **argv) { - char const *error_message; - int ret = 0; - size_t offset; - clingo_solve_result_bitset_t solve_ret; - clingo_control_t *ctl; - clingo_symbolic_atoms_t const *atoms; - clingo_backend_t *backend; - clingo_atom_t atom_ids[4]; - char const *atom_strings[] = {"a", "b", "c"}; - clingo_literal_t body[2]; - clingo_part_t parts[] = {{ "base", NULL, 0 }}; - - // create a control object and pass command line arguments - if (!clingo_control_new(argv+1, argc-1, NULL, NULL, 20, &ctl) != 0) { goto error; } - - // add a logic program to the base part - if (!clingo_control_add(ctl, "base", NULL, 0, "{a; b; c}.")) { goto error; } - - // ground the base part - if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { goto error; } - - // get the container for symbolic atoms - if (!clingo_control_symbolic_atoms(ctl, &atoms)) { goto error; } - // get the ids of atoms a, b, and c - offset = 0; - for (char const **it = atom_strings, **ie = it + sizeof(atom_strings) / sizeof(*atom_strings); it != ie; ++it) { - clingo_symbol_t sym; - clingo_symbolic_atom_iterator_t atom_it, atom_ie; - clingo_literal_t lit; - bool equal; - - // lookup the atom - if (!clingo_symbol_create_id(*it, true, &sym)) { goto error; } - if (!clingo_symbolic_atoms_find(atoms, sym, &atom_it)) { goto error; } - if (!clingo_symbolic_atoms_end(atoms, &atom_ie)) { goto error; } - if (!clingo_symbolic_atoms_iterator_is_equal_to(atoms, atom_it, atom_ie, &equal)) { goto error; } - assert(!equal); (void)equal; - - // get the atom's id - if (!clingo_symbolic_atoms_literal(atoms, atom_it, &lit)) { goto error; } - atom_ids[offset++] = lit; - } - - // get the backend - if (!clingo_control_backend(ctl, &backend)) { goto error; } - - // prepare the backend for adding rules - if (!clingo_backend_begin(backend)) { goto error; } - - // add an additional atom (called d below) - if (!clingo_backend_add_atom(backend, NULL, &atom_ids[3])) { goto error; } - - // add rule: d :- a, b. - body[0] = atom_ids[0]; - body[1] = atom_ids[1]; - if (!clingo_backend_rule(backend, false, &atom_ids[3], 1, body, sizeof(body)/sizeof(*body))) { goto error; } - - // add rule: :- not d, c. - body[0] = -(clingo_literal_t)atom_ids[3]; - body[1] = atom_ids[2]; - if (!clingo_backend_rule(backend, false, NULL, 0, body, sizeof(body)/sizeof(*body))) { goto error; } - - // finalize the backend - if (!clingo_backend_end(backend)) { goto error; } - - // solve - if (!solve(ctl, &solve_ret)) { goto error; } - - goto out; + char const *error_message; + int ret = 0; + size_t offset; + clingo_solve_result_bitset_t solve_ret; + clingo_control_t *ctl; + clingo_symbolic_atoms_t const *atoms; + clingo_backend_t *backend; + clingo_atom_t atom_ids[4]; + char const *atom_strings[] = {"a", "b", "c"}; + clingo_literal_t body[2]; + clingo_part_t parts[] = {{"base", NULL, 0}}; + + // create a control object and pass command line arguments + if (!clingo_control_new(argv + 1, argc - 1, NULL, NULL, 20, &ctl) != 0) { + goto error; + } + + // add a logic program to the base part + if (!clingo_control_add(ctl, "base", NULL, 0, "{a; b; c}.")) { + goto error; + } + + // ground the base part + if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { + goto error; + } + + // get the container for symbolic atoms + if (!clingo_control_symbolic_atoms(ctl, &atoms)) { + goto error; + } + // get the ids of atoms a, b, and c + offset = 0; + for (char const **it = atom_strings, **ie = it + sizeof(atom_strings) / sizeof(*atom_strings); it != ie; ++it) { + clingo_symbol_t sym; + clingo_symbolic_atom_iterator_t atom_it, atom_ie; + clingo_literal_t lit; + bool equal; + + // lookup the atom + if (!clingo_symbol_create_id(*it, true, &sym)) { + goto error; + } + if (!clingo_symbolic_atoms_find(atoms, sym, &atom_it)) { + goto error; + } + if (!clingo_symbolic_atoms_end(atoms, &atom_ie)) { + goto error; + } + if (!clingo_symbolic_atoms_iterator_is_equal_to(atoms, atom_it, atom_ie, &equal)) { + goto error; + } + assert(!equal); + (void)equal; + + // get the atom's id + if (!clingo_symbolic_atoms_literal(atoms, atom_it, &lit)) { + goto error; + } + atom_ids[offset++] = lit; + } + + // get the backend + if (!clingo_control_backend(ctl, &backend)) { + goto error; + } + + // prepare the backend for adding rules + if (!clingo_backend_begin(backend)) { + goto error; + } + + // add an additional atom (called d below) + if (!clingo_backend_add_atom(backend, NULL, &atom_ids[3])) { + goto error; + } + + // add rule: d :- a, b. + body[0] = atom_ids[0]; + body[1] = atom_ids[1]; + if (!clingo_backend_rule(backend, false, &atom_ids[3], 1, body, sizeof(body) / sizeof(*body))) { + goto error; + } + + // add rule: :- not d, c. + body[0] = -(clingo_literal_t)atom_ids[3]; + body[1] = atom_ids[2]; + if (!clingo_backend_rule(backend, false, NULL, 0, body, sizeof(body) / sizeof(*body))) { + goto error; + } + + // finalize the backend + if (!clingo_backend_end(backend)) { + goto error; + } + + // solve + if (!solve(ctl, &solve_ret)) { + goto error; + } + + goto out; error: - if (!(error_message = clingo_error_message())) { error_message = "error"; } + if (!(error_message = clingo_error_message())) { + error_message = "error"; + } - printf("%s\n", error_message); - ret = clingo_error_code(); + printf("%s\n", error_message); + ret = clingo_error_code(); out: - if (ctl) { clingo_control_free(ctl); } + if (ctl) { + clingo_control_free(ctl); + } - return ret; + return ret; } - diff --git a/examples/c/configuration.c b/examples/c/configuration.c index 4e155ecc1..6745b9172 100644 --- a/examples/c/configuration.c +++ b/examples/c/configuration.c @@ -1,144 +1,195 @@ #include -#include #include +#include bool print_model(clingo_model_t const *model) { - bool ret = true; - clingo_symbol_t *atoms = NULL; - size_t atoms_n; - clingo_symbol_t const *it, *ie; - char *str = NULL; - size_t str_n = 0; - - // determine the number of (shown) symbols in the model - if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; } + bool ret = true; + clingo_symbol_t *atoms = NULL; + size_t atoms_n; + clingo_symbol_t const *it, *ie; + char *str = NULL; + size_t str_n = 0; + + // determine the number of (shown) symbols in the model + if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { + goto error; + } - // allocate required memory to hold all the symbols - if (!(atoms = (clingo_symbol_t*)malloc(sizeof(*atoms) * atoms_n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); - goto error; - } + // allocate required memory to hold all the symbols + if (!(atoms = (clingo_symbol_t *)malloc(sizeof(*atoms) * atoms_n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); + goto error; + } - // retrieve the symbols in the model - if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { goto error; } + // retrieve the symbols in the model + if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { + goto error; + } - printf("Model:"); + printf("Model:"); - for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { - size_t n; - char *str_new; + for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { + size_t n; + char *str_new; - // determine size of the string representation of the next symbol in the model - if (!clingo_symbol_to_string_size(*it, &n)) { goto error; } + // determine size of the string representation of the next symbol in the model + if (!clingo_symbol_to_string_size(*it, &n)) { + goto error; + } - if (str_n < n) { - // allocate required memory to hold the symbol's string - if (!(str_new = (char*)realloc(str, sizeof(*str) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); - goto error; - } + if (str_n < n) { + // allocate required memory to hold the symbol's string + if (!(str_new = (char *)realloc(str, sizeof(*str) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + goto error; + } - str = str_new; - str_n = n; - } + str = str_new; + str_n = n; + } - // retrieve the symbol's string - if (!clingo_symbol_to_string(*it, str, n)) { goto error; } + // retrieve the symbol's string + if (!clingo_symbol_to_string(*it, str, n)) { + goto error; + } - printf(" %s", str); - } + printf(" %s", str); + } - printf("\n"); - goto out; + printf("\n"); + goto out; error: - ret = false; + ret = false; out: - if (atoms) { free(atoms); } - if (str) { free(str); } + if (atoms) { + free(atoms); + } + if (str) { + free(str); + } - return ret; + return ret; } bool solve(clingo_control_t *ctl, clingo_solve_result_bitset_t *result) { - bool ret = true; - clingo_solve_handle_t *handle; - clingo_model_t const *model; - - // get a solve handle - if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { goto error; } - // loop over all models - while (true) { - if (!clingo_solve_handle_resume(handle)) { goto error; } - if (!clingo_solve_handle_model(handle, &model)) { goto error; } - // print the model - if (model) { print_model(model); } - // stop if there are no more models - else { break; } - } - // close the solve handle - if (!clingo_solve_handle_get(handle, result)) { goto error; } - - goto out; + bool ret = true; + clingo_solve_handle_t *handle; + clingo_model_t const *model; + + // get a solve handle + if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { + goto error; + } + // loop over all models + while (true) { + if (!clingo_solve_handle_resume(handle)) { + goto error; + } + if (!clingo_solve_handle_model(handle, &model)) { + goto error; + } + // print the model + if (model) { + print_model(model); + } + // stop if there are no more models + else { + break; + } + } + // close the solve handle + if (!clingo_solve_handle_get(handle, result)) { + goto error; + } + + goto out; error: - ret = false; + ret = false; out: - // free the solve handle - return clingo_solve_handle_close(handle) && ret; + // free the solve handle + return clingo_solve_handle_close(handle) && ret; } int main(int argc, char const **argv) { - char const *error_message; - int ret = 0; - clingo_solve_result_bitset_t solve_ret; - clingo_control_t *ctl = NULL; - clingo_part_t parts[] = {{ "base", NULL, 0 }}; - clingo_configuration_t *conf; - clingo_id_t root_key, sub_key; - - // create a control object and pass command line arguments - if (!clingo_control_new(argv+1, argc-1, NULL, NULL, 20, &ctl) != 0) { goto error; } + char const *error_message; + int ret = 0; + clingo_solve_result_bitset_t solve_ret; + clingo_control_t *ctl = NULL; + clingo_part_t parts[] = {{"base", NULL, 0}}; + clingo_configuration_t *conf; + clingo_id_t root_key, sub_key; + + // create a control object and pass command line arguments + if (!clingo_control_new(argv + 1, argc - 1, NULL, NULL, 20, &ctl) != 0) { + goto error; + } - // get the configuration object and its root key - if (!clingo_control_configuration(ctl, &conf)) { goto error; } - if (!clingo_configuration_root(conf, &root_key)) { goto error; } + // get the configuration object and its root key + if (!clingo_control_configuration(ctl, &conf)) { + goto error; + } + if (!clingo_configuration_root(conf, &root_key)) { + goto error; + } - // configure to enumerate all models - if (!clingo_configuration_map_at(conf, root_key, "solve.models", &sub_key)) { goto error; } - if (!clingo_configuration_value_set(conf, sub_key, "0")) { goto error; } + // configure to enumerate all models + if (!clingo_configuration_map_at(conf, root_key, "solve.models", &sub_key)) { + goto error; + } + if (!clingo_configuration_value_set(conf, sub_key, "0")) { + goto error; + } - // configure the first solver to use the berkmin heuristic - if (!clingo_configuration_map_at(conf, root_key, "solver", &sub_key)) { goto error; } - if (!clingo_configuration_array_at(conf, sub_key, 0, &sub_key)) { goto error; } - if (!clingo_configuration_map_at(conf, sub_key, "heuristic", &sub_key)) { goto error; } - if (!clingo_configuration_value_set(conf, sub_key, "berkmin")) { goto error; } - // note that the solver entry can be used both as an array and a map - // if used as a map, this simply sets the configuration of the first solver and - // is equivalent to the code above + // configure the first solver to use the berkmin heuristic + if (!clingo_configuration_map_at(conf, root_key, "solver", &sub_key)) { + goto error; + } + if (!clingo_configuration_array_at(conf, sub_key, 0, &sub_key)) { + goto error; + } + if (!clingo_configuration_map_at(conf, sub_key, "heuristic", &sub_key)) { + goto error; + } + if (!clingo_configuration_value_set(conf, sub_key, "berkmin")) { + goto error; + } + // note that the solver entry can be used both as an array and a map + // if used as a map, this simply sets the configuration of the first solver and + // is equivalent to the code above - // add a logic program to the base part - if (!clingo_control_add(ctl, "base", NULL, 0, "a :- not b. b :- not a.")) { goto error; } + // add a logic program to the base part + if (!clingo_control_add(ctl, "base", NULL, 0, "a :- not b. b :- not a.")) { + goto error; + } - // ground the base part - if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { goto error; } + // ground the base part + if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { + goto error; + } - // solve - if (!solve(ctl, &solve_ret)) { goto error; } + // solve + if (!solve(ctl, &solve_ret)) { + goto error; + } - goto out; + goto out; error: - if (!(error_message = clingo_error_message())) { error_message = "error"; } + if (!(error_message = clingo_error_message())) { + error_message = "error"; + } - printf("%s\n", error_message); - ret = clingo_error_code(); + printf("%s\n", error_message); + ret = clingo_error_code(); out: - if (ctl) { clingo_control_free(ctl); } + if (ctl) { + clingo_control_free(ctl); + } - return ret; + return ret; } - diff --git a/examples/c/control.c b/examples/c/control.c index f634b569d..e34873d91 100644 --- a/examples/c/control.c +++ b/examples/c/control.c @@ -1,125 +1,160 @@ #include -#include #include +#include bool print_model(clingo_model_t const *model) { - bool ret = true; - clingo_symbol_t *atoms = NULL; - size_t atoms_n; - clingo_symbol_t const *it, *ie; - char *str = NULL; - size_t str_n = 0; - - // determine the number of (shown) symbols in the model - if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; } - - // allocate required memory to hold all the symbols - if (!(atoms = (clingo_symbol_t*)malloc(sizeof(*atoms) * atoms_n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); - goto error; - } - - // retrieve the symbols in the model - if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { goto error; } - - printf("Model:"); - - for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { - size_t n; - char *str_new; - - // determine size of the string representation of the next symbol in the model - if (!clingo_symbol_to_string_size(*it, &n)) { goto error; } - - if (str_n < n) { - // allocate required memory to hold the symbol's string - if (!(str_new = (char*)realloc(str, sizeof(*str) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + bool ret = true; + clingo_symbol_t *atoms = NULL; + size_t atoms_n; + clingo_symbol_t const *it, *ie; + char *str = NULL; + size_t str_n = 0; + + // determine the number of (shown) symbols in the model + if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; - } + } - str = str_new; - str_n = n; + // allocate required memory to hold all the symbols + if (!(atoms = (clingo_symbol_t *)malloc(sizeof(*atoms) * atoms_n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); + goto error; } - // retrieve the symbol's string - if (!clingo_symbol_to_string(*it, str, n)) { goto error; } + // retrieve the symbols in the model + if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { + goto error; + } + + printf("Model:"); + + for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { + size_t n; + char *str_new; + + // determine size of the string representation of the next symbol in the model + if (!clingo_symbol_to_string_size(*it, &n)) { + goto error; + } - printf(" %s", str); - } + if (str_n < n) { + // allocate required memory to hold the symbol's string + if (!(str_new = (char *)realloc(str, sizeof(*str) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + goto error; + } - printf("\n"); - goto out; + str = str_new; + str_n = n; + } + + // retrieve the symbol's string + if (!clingo_symbol_to_string(*it, str, n)) { + goto error; + } + + printf(" %s", str); + } + + printf("\n"); + goto out; error: - ret = false; + ret = false; out: - if (atoms) { free(atoms); } - if (str) { free(str); } + if (atoms) { + free(atoms); + } + if (str) { + free(str); + } - return ret; + return ret; } bool solve(clingo_control_t *ctl, clingo_solve_result_bitset_t *result) { - bool ret = true; - clingo_solve_handle_t *handle; - clingo_model_t const *model; - - // get a solve handle - if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { goto error; } - // loop over all models - while (true) { - if (!clingo_solve_handle_resume(handle)) { goto error; } - if (!clingo_solve_handle_model(handle, &model)) { goto error; } - // print the model - if (model) { print_model(model); } - // stop if there are no more models - else { break; } - } - // close the solve handle - if (!clingo_solve_handle_get(handle, result)) { goto error; } - - goto out; + bool ret = true; + clingo_solve_handle_t *handle; + clingo_model_t const *model; + + // get a solve handle + if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { + goto error; + } + // loop over all models + while (true) { + if (!clingo_solve_handle_resume(handle)) { + goto error; + } + if (!clingo_solve_handle_model(handle, &model)) { + goto error; + } + // print the model + if (model) { + print_model(model); + } + // stop if there are no more models + else { + break; + } + } + // close the solve handle + if (!clingo_solve_handle_get(handle, result)) { + goto error; + } + + goto out; error: - ret = false; + ret = false; out: - // free the solve handle - return clingo_solve_handle_close(handle) && ret; + // free the solve handle + return clingo_solve_handle_close(handle) && ret; } int main(int argc, char const **argv) { - char const *error_message; - int ret = 0; - clingo_solve_result_bitset_t solve_ret; - clingo_control_t *ctl = NULL; - clingo_part_t parts[] = {{ "base", NULL, 0 }}; - - // create a control object and pass command line arguments - if (!clingo_control_new(argv+1, argc-1, NULL, NULL, 20, &ctl) != 0) { goto error; } + char const *error_message; + int ret = 0; + clingo_solve_result_bitset_t solve_ret; + clingo_control_t *ctl = NULL; + clingo_part_t parts[] = {{"base", NULL, 0}}; + + // create a control object and pass command line arguments + if (!clingo_control_new(argv + 1, argc - 1, NULL, NULL, 20, &ctl) != 0) { + goto error; + } - // add a logic program to the base part - if (!clingo_control_add(ctl, "base", NULL, 0, "a :- not b. b :- not a.")) { goto error; } + // add a logic program to the base part + if (!clingo_control_add(ctl, "base", NULL, 0, "a :- not b. b :- not a.")) { + goto error; + } - // ground the base part - if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { goto error; } + // ground the base part + if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { + goto error; + } - // solve - if (!solve(ctl, &solve_ret)) { goto error; } + // solve + if (!solve(ctl, &solve_ret)) { + goto error; + } - goto out; + goto out; error: - if (!(error_message = clingo_error_message())) { error_message = "error"; } + if (!(error_message = clingo_error_message())) { + error_message = "error"; + } - printf("%s\n", error_message); - ret = clingo_error_code(); + printf("%s\n", error_message); + ret = clingo_error_code(); out: - if (ctl) { clingo_control_free(ctl); } + if (ctl) { + clingo_control_free(ctl); + } - return ret; + return ret; } - diff --git a/examples/c/model.c b/examples/c/model.c index 3bd0ac0cf..291b70017 100644 --- a/examples/c/model.c +++ b/examples/c/model.c @@ -1,197 +1,250 @@ #define __STDC_FORMAT_MACROS -#include #include -#include +#include #include +#include typedef struct model_buffer { - clingo_symbol_t *symbols; - size_t symbols_n; - char *string; - size_t string_n; + clingo_symbol_t *symbols; + size_t symbols_n; + char *string; + size_t string_n; } model_buffer_t; void free_model_buffer(model_buffer_t *buf) { - if (buf->symbols) { - free(buf->symbols); - buf->symbols = NULL; - buf->symbols_n = 0; - } - - if (buf->string) { - free(buf->string); - buf->string = NULL; - buf->string_n = 0; - } + if (buf->symbols) { + free(buf->symbols); + buf->symbols = NULL; + buf->symbols_n = 0; + } + + if (buf->string) { + free(buf->string); + buf->string = NULL; + buf->string_n = 0; + } } bool print_symbol(clingo_symbol_t symbol, model_buffer_t *buf) { - bool ret = true; - char *string; - size_t n; + bool ret = true; + char *string; + size_t n; - // determine size of the string representation of the next symbol in the model - if (!clingo_symbol_to_string_size(symbol, &n)) { goto error; } - - if (buf->string_n < n) { - // allocate required memory to hold the symbol's string - if (!(string = (char*)realloc(buf->string, sizeof(*buf->string) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); - goto error; + // determine size of the string representation of the next symbol in the model + if (!clingo_symbol_to_string_size(symbol, &n)) { + goto error; } - buf->string = string; - buf->string_n = n; - } + if (buf->string_n < n) { + // allocate required memory to hold the symbol's string + if (!(string = (char *)realloc(buf->string, sizeof(*buf->string) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + goto error; + } + + buf->string = string; + buf->string_n = n; + } - // retrieve the symbol's string - if (!clingo_symbol_to_string(symbol, buf->string, n)) { goto error; } - printf("%s", buf->string); - goto out; + // retrieve the symbol's string + if (!clingo_symbol_to_string(symbol, buf->string, n)) { + goto error; + } + printf("%s", buf->string); + goto out; error: - ret = false; + ret = false; out: - return ret; + return ret; } bool print_model(clingo_model_t const *model, model_buffer_t *buf, char const *label, clingo_show_type_bitset_t show) { - bool ret = true; - clingo_symbol_t *symbols; - size_t n; - clingo_symbol_t const *it, *ie; + bool ret = true; + clingo_symbol_t *symbols; + size_t n; + clingo_symbol_t const *it, *ie; + + // determine the number of (shown) symbols in the model + if (!clingo_model_symbols_size(model, show, &n)) { + goto error; + } - // determine the number of (shown) symbols in the model - if (!clingo_model_symbols_size(model, show, &n)) { goto error; } + // allocate required memory to hold all the symbols + if (buf->symbols_n < n) { + if (!(symbols = (clingo_symbol_t *)malloc(sizeof(*buf->symbols) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); + goto error; + } - // allocate required memory to hold all the symbols - if (buf->symbols_n < n) { - if (!(symbols = (clingo_symbol_t*)malloc(sizeof(*buf->symbols) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); - goto error; + buf->symbols = symbols; + buf->symbols_n = n; } - buf->symbols = symbols; - buf->symbols_n = n; - } - - // retrieve the symbols in the model - if (!clingo_model_symbols(model, show, buf->symbols, n)) { goto error; } + // retrieve the symbols in the model + if (!clingo_model_symbols(model, show, buf->symbols, n)) { + goto error; + } - printf("%s:", label); + printf("%s:", label); - for (it = buf->symbols, ie = buf->symbols + n; it != ie; ++it) { - printf(" "); - if (!print_symbol(*it, buf)) { goto error; } - } + for (it = buf->symbols, ie = buf->symbols + n; it != ie; ++it) { + printf(" "); + if (!print_symbol(*it, buf)) { + goto error; + } + } - printf("\n"); - goto out; + printf("\n"); + goto out; error: - ret = false; + ret = false; out: - return ret; + return ret; } bool print_solution(clingo_model_t const *model, model_buffer_t *data) { - bool ret = true; - uint64_t number; - clingo_model_type_t type; - char const *type_string = ""; - - // get model type - if (!clingo_model_type(model, &type)) { goto error; } + bool ret = true; + uint64_t number; + clingo_model_type_t type; + char const *type_string = ""; + + // get model type + if (!clingo_model_type(model, &type)) { + goto error; + } - switch ((enum clingo_model_type_e)type) { - case clingo_model_type_stable_model: { type_string = "Stable model"; break; } - case clingo_model_type_brave_consequences: { type_string = "Brave consequences"; break; } - case clingo_model_type_cautious_consequences: { type_string = "Cautious consequences"; break; } - } + switch ((enum clingo_model_type_e)type) { + case clingo_model_type_stable_model: { + type_string = "Stable model"; + break; + } + case clingo_model_type_brave_consequences: { + type_string = "Brave consequences"; + break; + } + case clingo_model_type_cautious_consequences: { + type_string = "Cautious consequences"; + break; + } + } - // get running number of model - if (!clingo_model_number(model, &number)) { goto error; } + // get running number of model + if (!clingo_model_number(model, &number)) { + goto error; + } - printf("%s %" PRIu64 ":\n", type_string, number); + printf("%s %" PRIu64 ":\n", type_string, number); - if (!print_model(model, data, " shown", clingo_show_type_shown)) { goto error; } - if (!print_model(model, data, " atoms", clingo_show_type_atoms)) { goto error; } - if (!print_model(model, data, " terms", clingo_show_type_terms)) { goto error; } - if (!print_model(model, data, " ~atoms", clingo_show_type_complement - | clingo_show_type_atoms)) { goto error; } + if (!print_model(model, data, " shown", clingo_show_type_shown)) { + goto error; + } + if (!print_model(model, data, " atoms", clingo_show_type_atoms)) { + goto error; + } + if (!print_model(model, data, " terms", clingo_show_type_terms)) { + goto error; + } + if (!print_model(model, data, " ~atoms", clingo_show_type_complement | clingo_show_type_atoms)) { + goto error; + } - goto out; + goto out; error: - ret = false; + ret = false; out: - return ret; + return ret; } bool solve(clingo_control_t *ctl, model_buffer_t *data, clingo_solve_result_bitset_t *result) { - bool ret = true; - clingo_solve_handle_t *handle; - clingo_model_t const *model; - - // get a solve handle - if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { goto error; } - // loop over all models - while (true) { - if (!clingo_solve_handle_resume(handle)) { goto error; } - if (!clingo_solve_handle_model(handle, &model)) { goto error; } - // print the model - if (model) { print_solution(model, data); } - // stop if there are no more models - else { break; } - } - // close the solve handle - if (!clingo_solve_handle_get(handle, result)) { goto error; } - - goto out; + bool ret = true; + clingo_solve_handle_t *handle; + clingo_model_t const *model; + + // get a solve handle + if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { + goto error; + } + // loop over all models + while (true) { + if (!clingo_solve_handle_resume(handle)) { + goto error; + } + if (!clingo_solve_handle_model(handle, &model)) { + goto error; + } + // print the model + if (model) { + print_solution(model, data); + } + // stop if there are no more models + else { + break; + } + } + // close the solve handle + if (!clingo_solve_handle_get(handle, result)) { + goto error; + } + + goto out; error: - ret = false; + ret = false; out: - // free the solve handle - return clingo_solve_handle_close(handle) && ret; + // free the solve handle + return clingo_solve_handle_close(handle) && ret; } int main(int argc, char const **argv) { - char const *error_message; - int ret = 0; - clingo_solve_result_bitset_t solve_ret; - clingo_control_t *ctl = NULL; - clingo_part_t parts[] = {{ "base", NULL, 0 }}; - model_buffer_t buf = {NULL, 0, NULL, 0}; - - // create a control object and pass command line arguments - if (!clingo_control_new(argv+1, argc-1, NULL, NULL, 20, &ctl) != 0) { goto error; } + char const *error_message; + int ret = 0; + clingo_solve_result_bitset_t solve_ret; + clingo_control_t *ctl = NULL; + clingo_part_t parts[] = {{"base", NULL, 0}}; + model_buffer_t buf = {NULL, 0, NULL, 0}; + + // create a control object and pass command line arguments + if (!clingo_control_new(argv + 1, argc - 1, NULL, NULL, 20, &ctl) != 0) { + goto error; + } - // add a logic program to the base part - if (!clingo_control_add(ctl, "base", NULL, 0, "1 {a; b} 1. #show c : b. #show a/0.")) { goto error; } + // add a logic program to the base part + if (!clingo_control_add(ctl, "base", NULL, 0, "1 {a; b} 1. #show c : b. #show a/0.")) { + goto error; + } - // ground the base part - if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { goto error; } + // ground the base part + if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { + goto error; + } - // solve - if (!solve(ctl, &buf, &solve_ret)) { goto error; } + // solve + if (!solve(ctl, &buf, &solve_ret)) { + goto error; + } - goto out; + goto out; error: - if (!(error_message = clingo_error_message())) { error_message = "error"; } + if (!(error_message = clingo_error_message())) { + error_message = "error"; + } - printf("%s\n", error_message); - ret = clingo_error_code(); + printf("%s\n", error_message); + ret = clingo_error_code(); out: - free_model_buffer(&buf); - if (ctl) { clingo_control_free(ctl); } + free_model_buffer(&buf); + if (ctl) { + clingo_control_free(ctl); + } - return ret; + return ret; } - diff --git a/examples/c/propagator.c b/examples/c/propagator.c index 1aea4e40d..1548fb13a 100644 --- a/examples/c/propagator.c +++ b/examples/c/propagator.c @@ -1,355 +1,436 @@ +#include #include -#include #include +#include #include -#include // state information for individual solving threads typedef struct { - // assignment of pigeons to holes - // (hole number -> pigeon placement literal or zero) - clingo_literal_t *holes; - size_t size; + // assignment of pigeons to holes + // (hole number -> pigeon placement literal or zero) + clingo_literal_t *holes; + size_t size; } state_t; // state information for the propagator typedef struct { - // mapping from solver literals capturing pigeon placements to hole numbers - // (solver literal -> hole number or zero) - int *pigeons; - size_t pigeons_size; - // array of states - state_t *states; - size_t states_size; + // mapping from solver literals capturing pigeon placements to hole numbers + // (solver literal -> hole number or zero) + int *pigeons; + size_t pigeons_size; + // array of states + state_t *states; + size_t states_size; } propagator_t; // returns the offset'th numeric argument of the function symbol sym bool get_arg(clingo_symbol_t sym, int offset, int *num) { - clingo_symbol_t const *args; - size_t args_size; + clingo_symbol_t const *args; + size_t args_size; - // get the arguments of the function symbol - if (!clingo_symbol_arguments(sym, &args, &args_size)) { return false; } - // get the requested numeric argument - if (!clingo_symbol_number(args[offset], num)) { return false; } + // get the arguments of the function symbol + if (!clingo_symbol_arguments(sym, &args, &args_size)) { + return false; + } + // get the requested numeric argument + if (!clingo_symbol_number(args[offset], num)) { + return false; + } - return true; + return true; } bool init(clingo_propagate_init_t *init, propagator_t *data) { - // the total number of holes pigeons can be assigned too - int holes = 0; - size_t threads = clingo_propagate_init_number_of_threads(init); - // stores the (numeric) maximum of the solver literals capturing pigeon placements - // note that the code below assumes that this literal is not negative - // which holds for the pigeon problem but not in general - clingo_literal_t max = 0; - clingo_symbolic_atoms_t const *atoms; - clingo_signature_t sig; - clingo_symbolic_atom_iterator_t atoms_it, atoms_ie; - // ensure that solve can be called multiple times - // for simplicity, the case that additional holes or pigeons to assign are grounded is not handled here - if (data->states != NULL) { - // in principle the number of threads can increase between solve calls by changing the configuration - // this case is not handled (elegantly) here - if (threads > data->states_size) { - clingo_set_error(clingo_error_runtime, "more threads than states"); + // the total number of holes pigeons can be assigned too + int holes = 0; + size_t threads = clingo_propagate_init_number_of_threads(init); + // stores the (numeric) maximum of the solver literals capturing pigeon placements + // note that the code below assumes that this literal is not negative + // which holds for the pigeon problem but not in general + clingo_literal_t max = 0; + clingo_symbolic_atoms_t const *atoms; + clingo_signature_t sig; + clingo_symbolic_atom_iterator_t atoms_it, atoms_ie; + // ensure that solve can be called multiple times + // for simplicity, the case that additional holes or pigeons to assign are grounded is not handled here + if (data->states != NULL) { + // in principle the number of threads can increase between solve calls by changing the configuration + // this case is not handled (elegantly) here + if (threads > data->states_size) { + clingo_set_error(clingo_error_runtime, "more threads than states"); + } + return true; } - return true; - } - // allocate memory for exactly one state per thread - if (!(data->states = (state_t*)malloc(sizeof(*data->states) * threads))) { - clingo_set_error(clingo_error_bad_alloc, "allocation failed"); - return false; - } - memset(data->states, 0, sizeof(*data->states) * threads); - data->states_size = threads; - - // the propagator monitors place/2 atoms and dectects conflicting assignments - // first get the symbolic atoms handle - if (!clingo_propagate_init_symbolic_atoms(init, &atoms)) { return false; } - // create place/2 signature to filter symbolic atoms with - if (!clingo_signature_create("place", 2, true, &sig)) { return false; } - // get an iterator after the last place/2 atom - // (atom order corresponds to grounding order (and is unpredictable)) - if (!clingo_symbolic_atoms_end(atoms, &atoms_ie)) { return false; } - - // loop over the place/2 atoms in two passes - // the first pass determines the maximum placement literal - // the second pass allocates memory for data structures based on the first pass - for (int pass = 0; pass < 2; ++pass) { - // get an iterator to the first place/2 atom - if (!clingo_symbolic_atoms_begin(atoms, &sig, &atoms_it)) { return false; } - if (pass == 1) { - // allocate memory for the assignemnt literal -> hole mapping - if (!(data->pigeons = (int*)malloc(sizeof(*data->pigeons) * (max + 1)))) { + // allocate memory for exactly one state per thread + if (!(data->states = (state_t *)malloc(sizeof(*data->states) * threads))) { clingo_set_error(clingo_error_bad_alloc, "allocation failed"); return false; - } - data->pigeons_size = max + 1; } - while (true) { - int h; - bool equal; - clingo_literal_t lit; - clingo_symbol_t sym; - - // stop iteration if the end is reached - if (!clingo_symbolic_atoms_iterator_is_equal_to(atoms, atoms_it, atoms_ie, &equal)) { return false; } - if (equal) { break; } - - // get the solver literal for the placement atom - if (!clingo_symbolic_atoms_literal(atoms, atoms_it, &lit)) { return false; } - if (!clingo_propagate_init_solver_literal(init, lit, &lit)) { return false; } - - if (pass == 0) { - // determine the maximum literal - assert(lit > 0); - if (lit > max) { max = lit; } - } - else { - // extract the hole number from the atom - if (!clingo_symbolic_atoms_symbol(atoms, atoms_it, &sym)) { return false; } - if (!get_arg(sym, 1, &h)) { return false; } - - // initialize the assignemnt literal -> hole mapping - data->pigeons[lit] = h; - - // watch the assignment literal - if (!clingo_propagate_init_add_watch(init, lit)) { return false; } - - // update the total number of holes - if (h + 1 > holes) { holes = h + 1; } - } - - // advance to the next placement atom - if (!clingo_symbolic_atoms_next(atoms, atoms_it, &atoms_it)) { return false; } + memset(data->states, 0, sizeof(*data->states) * threads); + data->states_size = threads; + + // the propagator monitors place/2 atoms and dectects conflicting assignments + // first get the symbolic atoms handle + if (!clingo_propagate_init_symbolic_atoms(init, &atoms)) { + return false; + } + // create place/2 signature to filter symbolic atoms with + if (!clingo_signature_create("place", 2, true, &sig)) { + return false; + } + // get an iterator after the last place/2 atom + // (atom order corresponds to grounding order (and is unpredictable)) + if (!clingo_symbolic_atoms_end(atoms, &atoms_ie)) { + return false; + } + + // loop over the place/2 atoms in two passes + // the first pass determines the maximum placement literal + // the second pass allocates memory for data structures based on the first pass + for (int pass = 0; pass < 2; ++pass) { + // get an iterator to the first place/2 atom + if (!clingo_symbolic_atoms_begin(atoms, &sig, &atoms_it)) { + return false; + } + if (pass == 1) { + // allocate memory for the assignemnt literal -> hole mapping + if (!(data->pigeons = (int *)malloc(sizeof(*data->pigeons) * (max + 1)))) { + clingo_set_error(clingo_error_bad_alloc, "allocation failed"); + return false; + } + data->pigeons_size = max + 1; + } + while (true) { + int h; + bool equal; + clingo_literal_t lit; + clingo_symbol_t sym; + + // stop iteration if the end is reached + if (!clingo_symbolic_atoms_iterator_is_equal_to(atoms, atoms_it, atoms_ie, &equal)) { + return false; + } + if (equal) { + break; + } + + // get the solver literal for the placement atom + if (!clingo_symbolic_atoms_literal(atoms, atoms_it, &lit)) { + return false; + } + if (!clingo_propagate_init_solver_literal(init, lit, &lit)) { + return false; + } + + if (pass == 0) { + // determine the maximum literal + assert(lit > 0); + if (lit > max) { + max = lit; + } + } else { + // extract the hole number from the atom + if (!clingo_symbolic_atoms_symbol(atoms, atoms_it, &sym)) { + return false; + } + if (!get_arg(sym, 1, &h)) { + return false; + } + + // initialize the assignemnt literal -> hole mapping + data->pigeons[lit] = h; + + // watch the assignment literal + if (!clingo_propagate_init_add_watch(init, lit)) { + return false; + } + + // update the total number of holes + if (h + 1 > holes) { + holes = h + 1; + } + } + + // advance to the next placement atom + if (!clingo_symbolic_atoms_next(atoms, atoms_it, &atoms_it)) { + return false; + } + } } - } - // initialize the per solver thread state information - for (size_t i = 0; i < threads; ++i) { - if (!(data->states[i].holes = (clingo_literal_t*)malloc(sizeof(*data->states[i].holes) * holes))) { - clingo_set_error(clingo_error_bad_alloc, "allocation failed"); - return false; + // initialize the per solver thread state information + for (size_t i = 0; i < threads; ++i) { + if (!(data->states[i].holes = (clingo_literal_t *)malloc(sizeof(*data->states[i].holes) * holes))) { + clingo_set_error(clingo_error_bad_alloc, "allocation failed"); + return false; + } + // initially no pigeons are assigned to any holes + // so the hole -> literal mapping is initialized with zero + // which is not a valid literal + memset(data->states[i].holes, 0, sizeof(*data->states[i].holes) * holes); + data->states[i].size = holes; } - // initially no pigeons are assigned to any holes - // so the hole -> literal mapping is initialized with zero - // which is not a valid literal - memset(data->states[i].holes, 0, sizeof(*data->states[i].holes) * holes); - data->states[i].size = holes; - } - - return true; + + return true; } bool propagate(clingo_propagate_control_t *control, const clingo_literal_t *changes, size_t size, propagator_t *data) { - // get the thread specific state - state_t state = data->states[clingo_propagate_control_thread_id(control)]; - - // apply and check the pigeon assignments done by the solver - for (size_t i = 0; i < size; ++i) { - // the freshly assigned literal - clingo_literal_t lit = changes[i]; - // a pointer to the previously assigned literal - clingo_literal_t *prev = state.holes + data->pigeons[lit]; - - // update the placement if no literal was assigned previously - if (*prev == 0) { *prev = lit; } - // create a conflicting clause and propagate it - else { - // current and previous literal must not hold together - clingo_literal_t clause[] = { -lit, -*prev }; - // stores the result when adding a clause or propagationg - // if result is false propagation must stop for the solver to backtrack - bool result; - - // add the clause - if (!clingo_propagate_control_add_clause(control, clause, sizeof(clause)/sizeof(*clause), clingo_clause_type_learnt, &result)) { return false; } - if (!result) { return true; } - - // propagate it - if (!clingo_propagate_control_propagate(control, &result)) { return false; } - if (!result) { return true; } - - // must not happen because the clause above is conflicting by construction - assert(false); + // get the thread specific state + state_t state = data->states[clingo_propagate_control_thread_id(control)]; + + // apply and check the pigeon assignments done by the solver + for (size_t i = 0; i < size; ++i) { + // the freshly assigned literal + clingo_literal_t lit = changes[i]; + // a pointer to the previously assigned literal + clingo_literal_t *prev = state.holes + data->pigeons[lit]; + + // update the placement if no literal was assigned previously + if (*prev == 0) { + *prev = lit; + } + // create a conflicting clause and propagate it + else { + // current and previous literal must not hold together + clingo_literal_t clause[] = {-lit, -*prev}; + // stores the result when adding a clause or propagationg + // if result is false propagation must stop for the solver to backtrack + bool result; + + // add the clause + if (!clingo_propagate_control_add_clause(control, clause, sizeof(clause) / sizeof(*clause), + clingo_clause_type_learnt, &result)) { + return false; + } + if (!result) { + return true; + } + + // propagate it + if (!clingo_propagate_control_propagate(control, &result)) { + return false; + } + if (!result) { + return true; + } + + // must not happen because the clause above is conflicting by construction + assert(false); + } } - } - return true; + return true; } void undo(clingo_propagate_control_t *control, const clingo_literal_t *changes, size_t size, propagator_t *data) { - // get the thread specific state - state_t state = data->states[clingo_propagate_control_thread_id(control)]; - - // undo the assignments made in propagate - for (size_t i = 0; i < size; ++i) { - clingo_literal_t lit = changes[i]; - int hole = data->pigeons[lit]; - - if (state.holes[hole] == lit) { - // undo the assignment - state.holes[hole] = 0; + // get the thread specific state + state_t state = data->states[clingo_propagate_control_thread_id(control)]; + + // undo the assignments made in propagate + for (size_t i = 0; i < size; ++i) { + clingo_literal_t lit = changes[i]; + int hole = data->pigeons[lit]; + + if (state.holes[hole] == lit) { + // undo the assignment + state.holes[hole] = 0; + } } - } } bool print_model(clingo_model_t const *model) { - bool ret = true; - clingo_symbol_t *atoms = NULL; - size_t atoms_n; - clingo_symbol_t const *it, *ie; - char *str = NULL; - size_t str_n = 0; - - // determine the number of (shown) symbols in the model - if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; } - - // allocate required memory to hold all the symbols - if (!(atoms = (clingo_symbol_t*)malloc(sizeof(*atoms) * atoms_n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); - goto error; - } - - // retrieve the symbols in the model - if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { goto error; } - - printf("Model:"); - - for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { - size_t n; - char *str_new; - - // determine size of the string representation of the next symbol in the model - if (!clingo_symbol_to_string_size(*it, &n)) { goto error; } - - if (str_n < n) { - // allocate required memory to hold the symbol's string - if (!(str_new = (char*)realloc(str, sizeof(*str) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + bool ret = true; + clingo_symbol_t *atoms = NULL; + size_t atoms_n; + clingo_symbol_t const *it, *ie; + char *str = NULL; + size_t str_n = 0; + + // determine the number of (shown) symbols in the model + if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; - } + } + + // allocate required memory to hold all the symbols + if (!(atoms = (clingo_symbol_t *)malloc(sizeof(*atoms) * atoms_n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); + goto error; + } - str = str_new; - str_n = n; + // retrieve the symbols in the model + if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { + goto error; } - // retrieve the symbol's string - if (!clingo_symbol_to_string(*it, str, n)) { goto error; } + printf("Model:"); + + for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { + size_t n; + char *str_new; + + // determine size of the string representation of the next symbol in the model + if (!clingo_symbol_to_string_size(*it, &n)) { + goto error; + } + + if (str_n < n) { + // allocate required memory to hold the symbol's string + if (!(str_new = (char *)realloc(str, sizeof(*str) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + goto error; + } - printf(" %s", str); - } + str = str_new; + str_n = n; + } - printf("\n"); - goto out; + // retrieve the symbol's string + if (!clingo_symbol_to_string(*it, str, n)) { + goto error; + } + + printf(" %s", str); + } + + printf("\n"); + goto out; error: - ret = false; + ret = false; out: - if (atoms) { free(atoms); } - if (str) { free(str); } + if (atoms) { + free(atoms); + } + if (str) { + free(str); + } - return ret; + return ret; } bool solve(clingo_control_t *ctl, clingo_solve_result_bitset_t *result) { - bool ret = true; - clingo_solve_handle_t *handle; - clingo_model_t const *model; - - // get a solve handle - if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { goto error; } - // loop over all models - while (true) { - if (!clingo_solve_handle_resume(handle)) { goto error; } - if (!clingo_solve_handle_model(handle, &model)) { goto error; } - // print the model - if (model) { print_model(model); } - // stop if there are no more models - else { break; } - } - // close the solve handle - if (!clingo_solve_handle_get(handle, result)) { goto error; } - - goto out; + bool ret = true; + clingo_solve_handle_t *handle; + clingo_model_t const *model; + + // get a solve handle + if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, NULL, NULL, &handle)) { + goto error; + } + // loop over all models + while (true) { + if (!clingo_solve_handle_resume(handle)) { + goto error; + } + if (!clingo_solve_handle_model(handle, &model)) { + goto error; + } + // print the model + if (model) { + print_model(model); + } + // stop if there are no more models + else { + break; + } + } + // close the solve handle + if (!clingo_solve_handle_get(handle, result)) { + goto error; + } + + goto out; error: - ret = false; + ret = false; out: - // free the solve handle - return clingo_solve_handle_close(handle) && ret; + // free the solve handle + return clingo_solve_handle_close(handle) && ret; } int main(int argc, char const **argv) { - char const *error_message; - int ret = 0; - clingo_solve_result_bitset_t solve_ret; - clingo_control_t *ctl = NULL; - // arguments to the pigeon program part - clingo_symbol_t args[2]; - // the pigeon program part having the number of holes and pigeons as parameters - clingo_part_t parts[] = {{ "pigeon", args, sizeof(args)/sizeof(*args) }}; - // parameters for the pigeon part - char const *params[] = {"h", "p"}; - // create a propagator with the functions above - // using the default implementation for the model check - clingo_propagator_t prop = { - (clingo_propagator_init_callback_t)init, - (clingo_propagator_propagate_callback_t)propagate, - (clingo_propagator_undo_callback_t)undo, - NULL, - NULL, - }; - // user data for the propagator - propagator_t prop_data = { NULL, 0, NULL, 0 }; - - // set the number of holes - clingo_symbol_create_number(8, &args[0]); - // set the number of pigeons - clingo_symbol_create_number(9, &args[1]); - - // create a control object and pass command line arguments - if (!clingo_control_new(argv+1, argc-1, NULL, NULL, 20, &ctl) != 0) { goto error; } - - // register the propagator - if (!clingo_control_register_propagator(ctl, &prop, &prop_data, false)) { goto error; } - - // add a logic program to the pigeon part - if (!clingo_control_add(ctl, "pigeon", params, sizeof(params)/sizeof(*params), - "1 { place(P,H) : H = 1..h } 1 :- P = 1..p.")) { goto error; } - - // ground the pigeon part - if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { goto error; } - - // solve using a model callback - if (!solve(ctl, &solve_ret)) { goto error; } - - goto out; + char const *error_message; + int ret = 0; + clingo_solve_result_bitset_t solve_ret; + clingo_control_t *ctl = NULL; + // arguments to the pigeon program part + clingo_symbol_t args[2]; + // the pigeon program part having the number of holes and pigeons as parameters + clingo_part_t parts[] = {{"pigeon", args, sizeof(args) / sizeof(*args)}}; + // parameters for the pigeon part + char const *params[] = {"h", "p"}; + // create a propagator with the functions above + // using the default implementation for the model check + clingo_propagator_t prop = { + (clingo_propagator_init_callback_t)init, + (clingo_propagator_propagate_callback_t)propagate, + (clingo_propagator_undo_callback_t)undo, + NULL, + NULL, + }; + // user data for the propagator + propagator_t prop_data = {NULL, 0, NULL, 0}; + + // set the number of holes + clingo_symbol_create_number(8, &args[0]); + // set the number of pigeons + clingo_symbol_create_number(9, &args[1]); + + // create a control object and pass command line arguments + if (!clingo_control_new(argv + 1, argc - 1, NULL, NULL, 20, &ctl) != 0) { + goto error; + } + + // register the propagator + if (!clingo_control_register_propagator(ctl, &prop, &prop_data, false)) { + goto error; + } + + // add a logic program to the pigeon part + if (!clingo_control_add(ctl, "pigeon", params, sizeof(params) / sizeof(*params), + "1 { place(P,H) : H = 1..h } 1 :- P = 1..p.")) { + goto error; + } + + // ground the pigeon part + if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { + goto error; + } + + // solve using a model callback + if (!solve(ctl, &solve_ret)) { + goto error; + } + + goto out; error: - if (!(error_message = clingo_error_message())) { error_message = "error"; } + if (!(error_message = clingo_error_message())) { + error_message = "error"; + } - printf("%s\n", error_message); - ret = clingo_error_code(); + printf("%s\n", error_message); + ret = clingo_error_code(); out: - // free the propagator state - if (prop_data.pigeons) { free(prop_data.pigeons); } - if (prop_data.states_size > 0) { - for (size_t i = 0; i < prop_data.states_size; ++i) { - if (prop_data.states[i].holes) { - free(prop_data.states[i].holes); - } + // free the propagator state + if (prop_data.pigeons) { + free(prop_data.pigeons); + } + if (prop_data.states_size > 0) { + for (size_t i = 0; i < prop_data.states_size; ++i) { + if (prop_data.states[i].holes) { + free(prop_data.states[i].holes); + } + } + free(prop_data.states); } - free(prop_data.states); - } - if (ctl) { clingo_control_free(ctl); } + if (ctl) { + clingo_control_free(ctl); + } - return ret; + return ret; } - diff --git a/examples/c/solve-async.c b/examples/c/solve-async.c index 61c8a6c77..5ad0e1e0f 100644 --- a/examples/c/solve-async.c +++ b/examples/c/solve-async.c @@ -1,135 +1,166 @@ #ifndef WIN32 +#include #include -#include -#include #include -#include +#include +#include bool print_model(clingo_model_t *model) { - bool ret = true; - clingo_symbol_t *atoms = NULL; - size_t atoms_n; - clingo_symbol_t const *it, *ie; - char *str = NULL; - size_t str_n = 0; - - // determine the number of (shown) symbols in the model - if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; } - - // allocate required memory to hold all the symbols - if (!(atoms = (clingo_symbol_t*)malloc(sizeof(*atoms) * atoms_n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); - goto error; - } - - // retrieve the symbols in the model - if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { goto error; } - - printf("Model:"); - - for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { - size_t n; - char *str_new; - - // determine size of the string representation of the next symbol in the model - if (!clingo_symbol_to_string_size(*it, &n)) { goto error; } - - if (str_n < n) { - // allocate required memory to hold the symbol's string - if (!(str_new = (char*)realloc(str, sizeof(*str) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + bool ret = true; + clingo_symbol_t *atoms = NULL; + size_t atoms_n; + clingo_symbol_t const *it, *ie; + char *str = NULL; + size_t str_n = 0; + + // determine the number of (shown) symbols in the model + if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; - } + } - str = str_new; - str_n = n; + // allocate required memory to hold all the symbols + if (!(atoms = (clingo_symbol_t *)malloc(sizeof(*atoms) * atoms_n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); + goto error; } - // retrieve the symbol's string - if (!clingo_symbol_to_string(*it, str, n)) { goto error; } + // retrieve the symbols in the model + if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { + goto error; + } - printf(" %s", str); - } + printf("Model:"); - printf("\n"); - goto out; + for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { + size_t n; + char *str_new; + + // determine size of the string representation of the next symbol in the model + if (!clingo_symbol_to_string_size(*it, &n)) { + goto error; + } + + if (str_n < n) { + // allocate required memory to hold the symbol's string + if (!(str_new = (char *)realloc(str, sizeof(*str) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + goto error; + } + + str = str_new; + str_n = n; + } + + // retrieve the symbol's string + if (!clingo_symbol_to_string(*it, str, n)) { + goto error; + } + + printf(" %s", str); + } + + printf("\n"); + goto out; error: - ret = false; + ret = false; out: - if (atoms) { free(atoms); } - if (str) { free(str); } + if (atoms) { + free(atoms); + } + if (str) { + free(str); + } - return ret; + return ret; } bool on_event(clingo_solve_event_type_t type, void *event, void *data, bool *goon) { - (void)type; - (void)event; - (void)goon; // this is true by default - if (type == clingo_solve_event_type_finish) { - atomic_flag *running = (atomic_flag*)data; - atomic_flag_clear(running); - } - return true; + (void)type; + (void)event; + (void)goon; // this is true by default + if (type == clingo_solve_event_type_finish) { + atomic_flag *running = (atomic_flag *)data; + atomic_flag_clear(running); + } + return true; } int main(int argc, char const **argv) { - char const *error_message; - int ret = 0; - atomic_flag running = ATOMIC_FLAG_INIT; - uint64_t samples = 0; - uint64_t incircle = 0; - uint64_t x, y; - clingo_solve_result_bitset_t solve_ret; - clingo_control_t *ctl = NULL; - clingo_solve_handle_t *handle = NULL; - clingo_part_t parts[] = {{ "base", NULL, 0 }}; - - // create a control object and pass command line arguments - if (!clingo_control_new(argv+1, argc-1, NULL, NULL, 20, &ctl) != 0) { goto error; } - - // add a logic program to the base part - if (!clingo_control_add(ctl, "base", NULL, 0, "#const n = 17." - "1 { p(X); q(X) } 1 :- X = 1..n." - ":- not n+1 { p(1..n); q(1..n) }.")) { goto error; } - - // ground the base part - if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { goto error; } - - atomic_flag_test_and_set(&running); - // create a solve handle with an attached vent handler - if (!clingo_control_solve(ctl, clingo_solve_mode_async | clingo_solve_mode_yield, NULL, 0, on_event, &running, &handle)) { goto error; } - - // let's approximate pi - do { - ++samples; - x = rand(); - y = rand(); - if (x * x + y * y <= (uint64_t)RAND_MAX * RAND_MAX) { incircle+= 1; } - } - while (atomic_flag_test_and_set(&running)); - printf("pi = %g\n", 4.0*incircle/samples); - - // get the solve result - if (!clingo_solve_handle_get(handle, &solve_ret)) { goto error; } - - goto out; + char const *error_message; + int ret = 0; + atomic_flag running = ATOMIC_FLAG_INIT; + uint64_t samples = 0; + uint64_t incircle = 0; + uint64_t x, y; + clingo_solve_result_bitset_t solve_ret; + clingo_control_t *ctl = NULL; + clingo_solve_handle_t *handle = NULL; + clingo_part_t parts[] = {{"base", NULL, 0}}; + + // create a control object and pass command line arguments + if (!clingo_control_new(argv + 1, argc - 1, NULL, NULL, 20, &ctl) != 0) { + goto error; + } + + // add a logic program to the base part + if (!clingo_control_add(ctl, "base", NULL, 0, + "#const n = 17." + "1 { p(X); q(X) } 1 :- X = 1..n." + ":- not n+1 { p(1..n); q(1..n) }.")) { + goto error; + } + + // ground the base part + if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { + goto error; + } + + atomic_flag_test_and_set(&running); + // create a solve handle with an attached vent handler + if (!clingo_control_solve(ctl, clingo_solve_mode_async | clingo_solve_mode_yield, NULL, 0, on_event, &running, + &handle)) { + goto error; + } + + // let's approximate pi + do { + ++samples; + x = rand(); + y = rand(); + if (x * x + y * y <= (uint64_t)RAND_MAX * RAND_MAX) { + incircle += 1; + } + } while (atomic_flag_test_and_set(&running)); + printf("pi = %g\n", 4.0 * incircle / samples); + + // get the solve result + if (!clingo_solve_handle_get(handle, &solve_ret)) { + goto error; + } + + goto out; error: - if (!(error_message = clingo_error_message())) { error_message = "error"; } + if (!(error_message = clingo_error_message())) { + error_message = "error"; + } - printf("%s\n", error_message); - ret = clingo_error_code(); + printf("%s\n", error_message); + ret = clingo_error_code(); out: - // close the handle - if (handle) { clingo_solve_handle_close(handle); } - if (ctl) { clingo_control_free(ctl); } + // close the handle + if (handle) { + clingo_solve_handle_close(handle); + } + if (ctl) { + clingo_control_free(ctl); + } - return ret; + return ret; } #else diff --git a/examples/c/statistics.c b/examples/c/statistics.c index 8839a81bc..4cdae53ca 100644 --- a/examples/c/statistics.c +++ b/examples/c/statistics.c @@ -1,257 +1,344 @@ #include -#include #include +#include bool print_model(clingo_model_t const *model) { - bool ret = true; - clingo_symbol_t *atoms = NULL; - size_t atoms_n; - clingo_symbol_t const *it, *ie; - char *str = NULL; - size_t str_n = 0; - - // determine the number of (shown) symbols in the model - if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; } - - // allocate required memory to hold all the symbols - if (!(atoms = (clingo_symbol_t*)malloc(sizeof(*atoms) * atoms_n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); - goto error; - } - - // retrieve the symbols in the model - if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { goto error; } - - printf("Model:"); - - for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { - size_t n; - char *str_new; - - // determine size of the string representation of the next symbol in the model - if (!clingo_symbol_to_string_size(*it, &n)) { goto error; } - - if (str_n < n) { - // allocate required memory to hold the symbol's string - if (!(str_new = (char*)realloc(str, sizeof(*str) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + bool ret = true; + clingo_symbol_t *atoms = NULL; + size_t atoms_n; + clingo_symbol_t const *it, *ie; + char *str = NULL; + size_t str_n = 0; + + // determine the number of (shown) symbols in the model + if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { + goto error; + } + + // allocate required memory to hold all the symbols + if (!(atoms = (clingo_symbol_t *)malloc(sizeof(*atoms) * atoms_n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); goto error; - } + } - str = str_new; - str_n = n; + // retrieve the symbols in the model + if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { + goto error; } - // retrieve the symbol's string - if (!clingo_symbol_to_string(*it, str, n)) { goto error; } + printf("Model:"); + + for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { + size_t n; + char *str_new; - printf(" %s", str); - } + // determine size of the string representation of the next symbol in the model + if (!clingo_symbol_to_string_size(*it, &n)) { + goto error; + } - printf("\n"); - goto out; + if (str_n < n) { + // allocate required memory to hold the symbol's string + if (!(str_new = (char *)realloc(str, sizeof(*str) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + goto error; + } + + str = str_new; + str_n = n; + } + + // retrieve the symbol's string + if (!clingo_symbol_to_string(*it, str, n)) { + goto error; + } + + printf(" %s", str); + } + + printf("\n"); + goto out; error: - ret = false; + ret = false; out: - if (atoms) { free(atoms); } - if (str) { free(str); } + if (atoms) { + free(atoms); + } + if (str) { + free(str); + } - return ret; + return ret; } bool event_handler(clingo_solve_event_type_t type, void *event, void *data, bool *goon) { - (void)data; - (void)goon; - switch (type) { - case clingo_solve_event_type_statistics: { - clingo_statistics_t *stats; - uint64_t root, values, summary, value; - uint16_t n = 10, random = 1; - double sum = 0; - - // obtain a pointer to the accumulated statistics - stats = ((clingo_statistics_t **)event)[1]; - - // get the root key which refering to a special modifiable entry - if (!clingo_statistics_root(stats, &root)) { return false; } - - // set some pseudo-random values in an array - if (!clingo_statistics_map_add_subkey(stats, root, "values", clingo_statistics_type_array, &values)) { return false; } - for (uint16_t i = 0; i < n; ++i) { - random = (random << 3) ^ (random ^ ((random & 0xf800) >> 13)) ^ i; - if (!clingo_statistics_array_push(stats, values, clingo_statistics_type_value, &value)) { return false; } - if (!clingo_statistics_value_set(stats, value, random)) { return false; } - sum += random; - } - - // add the sum and average of the values in a map under key summary - if (!clingo_statistics_map_add_subkey(stats, root, "summary", clingo_statistics_type_map, &summary)) { return false; } - if (!clingo_statistics_map_add_subkey(stats, summary, "sum", clingo_statistics_type_value, &value)) { return false; } - if (!clingo_statistics_value_set(stats, value, sum)) { return false; } - if (!clingo_statistics_map_add_subkey(stats, summary, "avg", clingo_statistics_type_value, &value)) { return false; } - if (!clingo_statistics_value_set(stats, value, (double)sum/n)) { return false; } - break; + (void)data; + (void)goon; + switch (type) { + case clingo_solve_event_type_statistics: { + clingo_statistics_t *stats; + uint64_t root, values, summary, value; + uint16_t n = 10, random = 1; + double sum = 0; + + // obtain a pointer to the accumulated statistics + stats = ((clingo_statistics_t **)event)[1]; + + // get the root key which refering to a special modifiable entry + if (!clingo_statistics_root(stats, &root)) { + return false; + } + + // set some pseudo-random values in an array + if (!clingo_statistics_map_add_subkey(stats, root, "values", clingo_statistics_type_array, &values)) { + return false; + } + for (uint16_t i = 0; i < n; ++i) { + random = (random << 3) ^ (random ^ ((random & 0xf800) >> 13)) ^ i; + if (!clingo_statistics_array_push(stats, values, clingo_statistics_type_value, &value)) { + return false; + } + if (!clingo_statistics_value_set(stats, value, random)) { + return false; + } + sum += random; + } + + // add the sum and average of the values in a map under key summary + if (!clingo_statistics_map_add_subkey(stats, root, "summary", clingo_statistics_type_map, &summary)) { + return false; + } + if (!clingo_statistics_map_add_subkey(stats, summary, "sum", clingo_statistics_type_value, &value)) { + return false; + } + if (!clingo_statistics_value_set(stats, value, sum)) { + return false; + } + if (!clingo_statistics_map_add_subkey(stats, summary, "avg", clingo_statistics_type_value, &value)) { + return false; + } + if (!clingo_statistics_value_set(stats, value, (double)sum / n)) { + return false; + } + break; + } } - } - return true; + return true; } bool solve(clingo_control_t *ctl, clingo_solve_result_bitset_t *result) { - bool ret = true; - clingo_solve_handle_t *handle; - clingo_model_t const *model; - - // get a solve handle - if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, event_handler, NULL, &handle)) { goto error; } - // loop over all models - while (true) { - if (!clingo_solve_handle_resume(handle)) { goto error; } - if (!clingo_solve_handle_model(handle, &model)) { goto error; } - // print the model - if (model) { print_model(model); } - // stop if there are no more models - else { break; } - } - // get the solve results - if (!clingo_solve_handle_get(handle, result)) { goto error; } - - goto out; + bool ret = true; + clingo_solve_handle_t *handle; + clingo_model_t const *model; + + // get a solve handle + if (!clingo_control_solve(ctl, clingo_solve_mode_yield, NULL, 0, event_handler, NULL, &handle)) { + goto error; + } + // loop over all models + while (true) { + if (!clingo_solve_handle_resume(handle)) { + goto error; + } + if (!clingo_solve_handle_model(handle, &model)) { + goto error; + } + // print the model + if (model) { + print_model(model); + } + // stop if there are no more models + else { + break; + } + } + // get the solve results + if (!clingo_solve_handle_get(handle, result)) { + goto error; + } + + goto out; error: - ret = false; + ret = false; out: - // free the solve handle - return clingo_solve_handle_close(handle) && ret; + // free the solve handle + return clingo_solve_handle_close(handle) && ret; } void print_prefix(int depth) { - for (int i = 0; i < depth; ++i) { - printf(" "); - } + for (int i = 0; i < depth; ++i) { + printf(" "); + } } // recursively print the statistics object bool print_statistics(const clingo_statistics_t *stats, uint64_t key, int depth) { - bool ret = true; - clingo_statistics_type_t type; - - // get the type of an entry and switch over its various values - if (!clingo_statistics_type(stats, key, &type)) { goto error; } - switch ((enum clingo_statistics_type_e)type) { - // print values - case clingo_statistics_type_value: { - double value; - - // print value (with prefix for readability) - print_prefix(depth); - if (!clingo_statistics_value_get(stats, key, &value)) { goto error; } - printf("%g\n", value); - - break; + bool ret = true; + clingo_statistics_type_t type; + + // get the type of an entry and switch over its various values + if (!clingo_statistics_type(stats, key, &type)) { + goto error; + } + switch ((enum clingo_statistics_type_e)type) { + // print values + case clingo_statistics_type_value: { + double value; + + // print value (with prefix for readability) + print_prefix(depth); + if (!clingo_statistics_value_get(stats, key, &value)) { + goto error; + } + printf("%g\n", value); + + break; + } + + // print arrays + case clingo_statistics_type_array: { + size_t size; + + // loop over array elements + if (!clingo_statistics_array_size(stats, key, &size)) { + goto error; + } + for (size_t i = 0; i < size; ++i) { + uint64_t subkey; + + // print array offset (with prefix for readability) + if (!clingo_statistics_array_at(stats, key, i, &subkey)) { + goto error; + } + print_prefix(depth); + printf("%zu:\n", i); + + // recursively print subentry + if (!print_statistics(stats, subkey, depth + 1)) { + goto error; + } + } + break; + } + + // print maps + case clingo_statistics_type_map: { + size_t size; + + // loop over map elements + if (!clingo_statistics_map_size(stats, key, &size)) { + goto error; + } + for (size_t i = 0; i < size; ++i) { + char const *name; + uint64_t subkey; + + // get and print map name (with prefix for readability) + if (!clingo_statistics_map_subkey_name(stats, key, i, &name)) { + goto error; + } + if (!clingo_statistics_map_at(stats, key, name, &subkey)) { + goto error; + } + print_prefix(depth); + printf("%s:\n", name); + + // recursively print subentry + if (!print_statistics(stats, subkey, depth + 1)) { + goto error; + } + } + } + + // this case won't occur if the statistics are traversed like this + case clingo_statistics_type_empty: { + goto out; + } } - // print arrays - case clingo_statistics_type_array: { - size_t size; + goto out; +error: + ret = false; +out: + return ret; +} - // loop over array elements - if (!clingo_statistics_array_size(stats, key, &size)) { goto error; } - for (size_t i = 0; i < size; ++i) { - uint64_t subkey; +int main(int argc, char const **argv) { + char const *error_message; + int ret = 0; + clingo_solve_result_bitset_t solve_ret; + clingo_control_t *ctl = NULL; + clingo_part_t parts[] = {{"base", NULL, 0}}; + clingo_configuration_t *conf; + clingo_id_t conf_root, conf_sub; + const clingo_statistics_t *stats; + uint64_t stats_key; + + // create a control object and pass command line arguments + if (!clingo_control_new(argv + 1, argc - 1, NULL, NULL, 20, &ctl)) { + goto error; + } - // print array offset (with prefix for readability) - if (!clingo_statistics_array_at(stats, key, i, &subkey)) { goto error; } - print_prefix(depth); - printf("%zu:\n", i); + // get the configuration object and its root key + if (!clingo_control_configuration(ctl, &conf)) { + goto error; + } + if (!clingo_configuration_root(conf, &conf_root)) { + goto error; + } + // and set the statistics level to one to get more statistics + if (!clingo_configuration_map_at(conf, conf_root, "stats", &conf_sub)) { + goto error; + } + if (!clingo_configuration_value_set(conf, conf_sub, "1")) { + goto error; + } - // recursively print subentry - if (!print_statistics(stats, subkey, depth+1)) { goto error; } - } - break; + // add a logic program to the base part + if (!clingo_control_add(ctl, "base", NULL, 0, "a :- not b. b :- not a.")) { + goto error; } - // print maps - case clingo_statistics_type_map: { - size_t size; - - // loop over map elements - if (!clingo_statistics_map_size(stats, key, &size)) { goto error; } - for (size_t i = 0; i < size; ++i) { - char const *name; - uint64_t subkey; - - // get and print map name (with prefix for readability) - if (!clingo_statistics_map_subkey_name(stats, key, i, &name)) { goto error; } - if (!clingo_statistics_map_at(stats, key, name, &subkey)) { goto error; } - print_prefix(depth); - printf("%s:\n", name); - - // recursively print subentry - if (!print_statistics(stats, subkey, depth+1)) { goto error; } - } + // ground the base part + if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { + goto error; } - // this case won't occur if the statistics are traversed like this - case clingo_statistics_type_empty: { goto out; } - } + // solve + if (!solve(ctl, &solve_ret)) { + goto error; + } - goto out; -error: - ret = false; -out: - return ret; -} + // get the statistics object, get the root key, then print the statistics recursively + if (!clingo_control_statistics(ctl, &stats)) { + goto error; + } + if (!clingo_statistics_root(stats, &stats_key)) { + goto error; + } + if (!print_statistics(stats, stats_key, 0)) { + goto error; + } -int main(int argc, char const **argv) { - char const *error_message; - int ret = 0; - clingo_solve_result_bitset_t solve_ret; - clingo_control_t *ctl = NULL; - clingo_part_t parts[] = {{ "base", NULL, 0 }}; - clingo_configuration_t *conf; - clingo_id_t conf_root, conf_sub; - const clingo_statistics_t *stats; - uint64_t stats_key; - - // create a control object and pass command line arguments - if (!clingo_control_new(argv+1, argc-1, NULL, NULL, 20, &ctl)) { goto error; } - - // get the configuration object and its root key - if (!clingo_control_configuration(ctl, &conf)) { goto error; } - if (!clingo_configuration_root(conf, &conf_root)) { goto error; } - // and set the statistics level to one to get more statistics - if (!clingo_configuration_map_at(conf, conf_root, "stats", &conf_sub)) { goto error; } - if (!clingo_configuration_value_set(conf, conf_sub, "1")) { goto error; } - - // add a logic program to the base part - if (!clingo_control_add(ctl, "base", NULL, 0, "a :- not b. b :- not a.")) { goto error; } - - // ground the base part - if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { goto error; } - - // solve - if (!solve(ctl, &solve_ret)) { goto error; } - - // get the statistics object, get the root key, then print the statistics recursively - if (!clingo_control_statistics(ctl, &stats)) { goto error; } - if (!clingo_statistics_root(stats, &stats_key)) { goto error; } - if (!print_statistics(stats, stats_key, 0)) { goto error; } - - goto out; + goto out; error: - if (!(error_message = clingo_error_message())) { error_message = "error"; } + if (!(error_message = clingo_error_message())) { + error_message = "error"; + } - printf("%s\n", error_message); - ret = clingo_error_code(); + printf("%s\n", error_message); + ret = clingo_error_code(); out: - if (ctl) { clingo_control_free(ctl); } + if (ctl) { + clingo_control_free(ctl); + } - return ret; + return ret; } - diff --git a/examples/c/symbol.c b/examples/c/symbol.c index f61b407e6..664cb54d5 100644 --- a/examples/c/symbol.c +++ b/examples/c/symbol.c @@ -1,101 +1,122 @@ #define __STDC_FORMAT_MACROS -#include +#include #include -#include +#include #include -#include +#include typedef struct { - char *string; - size_t string_n; + char *string; + size_t string_n; } string_buffer_t; void free_string_buffer(string_buffer_t *buf) { - if (buf->string) { - free(buf->string); - buf->string = NULL; - buf->string_n = 0; - } + if (buf->string) { + free(buf->string); + buf->string = NULL; + buf->string_n = 0; + } } bool print_symbol(clingo_symbol_t symbol, string_buffer_t *buf) { - bool ret = true; - char *string; - size_t n; - - // determine size of the string representation of the next symbol in the model - if (!clingo_symbol_to_string_size(symbol, &n)) { goto error; } - - if (buf->string_n < n) { - // allocate required memory to hold the symbol's string - if (!(string = (char*)realloc(buf->string, sizeof(*buf->string) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); - goto error; + bool ret = true; + char *string; + size_t n; + + // determine size of the string representation of the next symbol in the model + if (!clingo_symbol_to_string_size(symbol, &n)) { + goto error; } - buf->string = string; - buf->string_n = n; - } + if (buf->string_n < n) { + // allocate required memory to hold the symbol's string + if (!(string = (char *)realloc(buf->string, sizeof(*buf->string) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + goto error; + } - // retrieve the symbol's string - if (!clingo_symbol_to_string(symbol, buf->string, n)) { goto error; } - printf("%s", buf->string); - goto out; + buf->string = string; + buf->string_n = n; + } + + // retrieve the symbol's string + if (!clingo_symbol_to_string(symbol, buf->string, n)) { + goto error; + } + printf("%s", buf->string); + goto out; error: - ret = false; + ret = false; out: - return ret; + return ret; } int main() { - char const *error_message; - int ret = 0; - clingo_symbol_t symbols[3]; - string_buffer_t buf = { NULL, 0 }; - clingo_symbol_t const *args; - size_t size; - - // create a number, identifier (function without arguments), and a function symbol - clingo_symbol_create_number(42, &symbols[0]); - if (!clingo_symbol_create_id("x", true, &symbols[1])) { goto error; } - if (!clingo_symbol_create_function("x", symbols, 2, true, &symbols[2])) { goto error; } - - // print the symbols along with their hash values - for (size_t i = 0; i < sizeof(symbols) / sizeof(*symbols); ++i) { - printf("the hash of "); - if (!print_symbol(symbols[i], &buf)) { goto error; } - printf(" is %zu\n", clingo_symbol_hash(symbols[i])); - } - - // compare symbols - if (!clingo_symbol_arguments(symbols[2], &args, &size)) { goto error; } - assert(size == 2); - // equal to comparison - for (size_t i = 0; i < size; ++i) { - if (!print_symbol(symbols[0], &buf)) { goto error; } - printf(" %s ", clingo_symbol_is_equal_to(symbols[0], args[i]) ? "is equal to" : "is not equal to"); - if (!print_symbol(args[i], &buf)) { goto error; } + char const *error_message; + int ret = 0; + clingo_symbol_t symbols[3]; + string_buffer_t buf = {NULL, 0}; + clingo_symbol_t const *args; + size_t size; + + // create a number, identifier (function without arguments), and a function symbol + clingo_symbol_create_number(42, &symbols[0]); + if (!clingo_symbol_create_id("x", true, &symbols[1])) { + goto error; + } + if (!clingo_symbol_create_function("x", symbols, 2, true, &symbols[2])) { + goto error; + } + + // print the symbols along with their hash values + for (size_t i = 0; i < sizeof(symbols) / sizeof(*symbols); ++i) { + printf("the hash of "); + if (!print_symbol(symbols[i], &buf)) { + goto error; + } + printf(" is %zu\n", clingo_symbol_hash(symbols[i])); + } + + // compare symbols + if (!clingo_symbol_arguments(symbols[2], &args, &size)) { + goto error; + } + assert(size == 2); + // equal to comparison + for (size_t i = 0; i < size; ++i) { + if (!print_symbol(symbols[0], &buf)) { + goto error; + } + printf(" %s ", clingo_symbol_is_equal_to(symbols[0], args[i]) ? "is equal to" : "is not equal to"); + if (!print_symbol(args[i], &buf)) { + goto error; + } + printf("\n"); + } + // less than comparison + if (!print_symbol(symbols[0], &buf)) { + goto error; + } + printf(" %s ", clingo_symbol_is_less_than(symbols[0], symbols[1]) ? "is less than" : "is not less than"); + if (!print_symbol(symbols[1], &buf)) { + goto error; + } printf("\n"); - } - // less than comparison - if (!print_symbol(symbols[0], &buf)) { goto error; } - printf(" %s ", clingo_symbol_is_less_than(symbols[0], symbols[1]) ? "is less than" : "is not less than"); - if (!print_symbol(symbols[1], &buf)) { goto error; } - printf("\n"); - goto out; + goto out; error: - if (!(error_message = clingo_error_message())) { error_message = "error"; } + if (!(error_message = clingo_error_message())) { + error_message = "error"; + } - printf("%s\n", error_message); - ret = clingo_error_code(); + printf("%s\n", error_message); + ret = clingo_error_code(); out: - free_string_buffer(&buf); + free_string_buffer(&buf); - return ret; + return ret; } - diff --git a/examples/c/symbolic-atoms.c b/examples/c/symbolic-atoms.c index eb0d5d442..7d969bb14 100644 --- a/examples/c/symbolic-atoms.c +++ b/examples/c/symbolic-atoms.c @@ -1,120 +1,157 @@ #include -#include #include +#include typedef struct string_buffer { - char *string; - size_t string_n; + char *string; + size_t string_n; } string_buffer_t; void free_string_buffer(string_buffer_t *buf) { - if (buf->string) { - free(buf->string); - buf->string = NULL; - buf->string_n = 0; - } + if (buf->string) { + free(buf->string); + buf->string = NULL; + buf->string_n = 0; + } } bool print_symbol(clingo_symbol_t symbol, string_buffer_t *buf) { - bool ret = true; - char *string; - size_t n; - - // determine size of the string representation of the next symbol in the model - if (!clingo_symbol_to_string_size(symbol, &n)) { goto error; } - - if (buf->string_n < n) { - // allocate required memory to hold the symbol's string - if (!(string = (char*)realloc(buf->string, sizeof(*buf->string) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); - goto error; + bool ret = true; + char *string; + size_t n; + + // determine size of the string representation of the next symbol in the model + if (!clingo_symbol_to_string_size(symbol, &n)) { + goto error; } - buf->string = string; - buf->string_n = n; - } + if (buf->string_n < n) { + // allocate required memory to hold the symbol's string + if (!(string = (char *)realloc(buf->string, sizeof(*buf->string) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + goto error; + } - // retrieve the symbol's string - if (!clingo_symbol_to_string(symbol, buf->string, n)) { goto error; } + buf->string = string; + buf->string_n = n; + } + + // retrieve the symbol's string + if (!clingo_symbol_to_string(symbol, buf->string, n)) { + goto error; + } - printf("%s", buf->string); - goto out; + printf("%s", buf->string); + goto out; error: - ret = false; + ret = false; out: - return ret; + return ret; } int main(int argc, char const **argv) { - char const *error_message; - string_buffer_t buf = {NULL, 0}; - int ret = 0; - clingo_control_t *ctl = NULL; - clingo_part_t parts[] = {{ "base", NULL, 0 }}; - clingo_symbolic_atoms_t const *atoms; - clingo_symbolic_atom_iterator_t it_atoms, ie_atoms; - - // create a control object and pass command line arguments - if (!clingo_control_new(argv+1, argc-1, NULL, NULL, 20, &ctl) != 0) { goto error; } - - // add a logic program to the base part - if (!clingo_control_add(ctl, "base", NULL, 0, "a. {b}. #external c.")) { goto error; } - - // ground the base part - if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { goto error; } - - // get symbolic atoms - if (!clingo_control_symbolic_atoms(ctl, &atoms)) { goto error; } - - // get begin and end iterator - if (!clingo_symbolic_atoms_begin(atoms, NULL, &it_atoms)) { goto error; } - - if (!clingo_symbolic_atoms_end(atoms, &ie_atoms)) { goto error; } - - printf("Symbolic atoms:\n"); - - for (;;) { - bool equal, fact, external; - clingo_symbol_t symbol; - - // check if we are at the end of the sequence - if (!clingo_symbolic_atoms_iterator_is_equal_to(atoms, it_atoms, ie_atoms, &equal)) { goto error; } - - if (equal) { break; } + char const *error_message; + string_buffer_t buf = {NULL, 0}; + int ret = 0; + clingo_control_t *ctl = NULL; + clingo_part_t parts[] = {{"base", NULL, 0}}; + clingo_symbolic_atoms_t const *atoms; + clingo_symbolic_atom_iterator_t it_atoms, ie_atoms; + + // create a control object and pass command line arguments + if (!clingo_control_new(argv + 1, argc - 1, NULL, NULL, 20, &ctl) != 0) { + goto error; + } - // get the associated symbol - if (!clingo_symbolic_atoms_symbol(atoms, it_atoms, &symbol)) { goto error; } + // add a logic program to the base part + if (!clingo_control_add(ctl, "base", NULL, 0, "a. {b}. #external c.")) { + goto error; + } - // determine if the atom is fact or external - if (!clingo_symbolic_atoms_is_fact(atoms, it_atoms, &fact)) { goto error; } - if (!clingo_symbolic_atoms_is_external(atoms, it_atoms, &external)) { goto error; } + // ground the base part + if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { + goto error; + } - printf(" "); + // get symbolic atoms + if (!clingo_control_symbolic_atoms(ctl, &atoms)) { + goto error; + } - if (!print_symbol(symbol, &buf)) { goto error; } - if (fact) { printf(", fact"); } - if (external) { printf(", external"); } + // get begin and end iterator + if (!clingo_symbolic_atoms_begin(atoms, NULL, &it_atoms)) { + goto error; + } - printf("\n"); + if (!clingo_symbolic_atoms_end(atoms, &ie_atoms)) { + goto error; + } - // advance the next element in the sequence - if (!clingo_symbolic_atoms_next(atoms, it_atoms, &it_atoms)) { goto error; } - } + printf("Symbolic atoms:\n"); + + for (;;) { + bool equal, fact, external; + clingo_symbol_t symbol; + + // check if we are at the end of the sequence + if (!clingo_symbolic_atoms_iterator_is_equal_to(atoms, it_atoms, ie_atoms, &equal)) { + goto error; + } + + if (equal) { + break; + } + + // get the associated symbol + if (!clingo_symbolic_atoms_symbol(atoms, it_atoms, &symbol)) { + goto error; + } + + // determine if the atom is fact or external + if (!clingo_symbolic_atoms_is_fact(atoms, it_atoms, &fact)) { + goto error; + } + if (!clingo_symbolic_atoms_is_external(atoms, it_atoms, &external)) { + goto error; + } + + printf(" "); + + if (!print_symbol(symbol, &buf)) { + goto error; + } + if (fact) { + printf(", fact"); + } + if (external) { + printf(", external"); + } + + printf("\n"); + + // advance the next element in the sequence + if (!clingo_symbolic_atoms_next(atoms, it_atoms, &it_atoms)) { + goto error; + } + } - goto out; + goto out; error: - if (!(error_message = clingo_error_message())) { error_message = "error"; } + if (!(error_message = clingo_error_message())) { + error_message = "error"; + } - printf("%s\n", error_message); - ret = clingo_error_code(); + printf("%s\n", error_message); + ret = clingo_error_code(); out: - free_string_buffer(&buf); - if (ctl) { clingo_control_free(ctl); } + free_string_buffer(&buf); + if (ctl) { + clingo_control_free(ctl); + } - return ret; + return ret; } - diff --git a/examples/c/theory-atoms.c b/examples/c/theory-atoms.c index 3de67a53e..61383a20f 100644 --- a/examples/c/theory-atoms.c +++ b/examples/c/theory-atoms.c @@ -1,164 +1,211 @@ #include -#include #include +#include #include bool print_model(clingo_model_t const *model) { - bool ret = true; - clingo_symbol_t *atoms = NULL; - size_t atoms_n; - clingo_symbol_t const *it, *ie; - char *str = NULL; - size_t str_n = 0; - - // determine the number of (shown) symbols in the model - if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; } - - // allocate required memory to hold all the symbols - if (!(atoms = (clingo_symbol_t*)malloc(sizeof(*atoms) * atoms_n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); - goto error; - } - - // retrieve the symbols in the model - if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { goto error; } - - printf("Model:"); - - for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { - size_t n; - char *str_new; - - // determine size of the string representation of the next symbol in the model - if (!clingo_symbol_to_string_size(*it, &n)) { goto error; } - - if (str_n < n) { - // allocate required memory to hold the symbol's string - if (!(str_new = (char*)realloc(str, sizeof(*str) * n))) { - clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + bool ret = true; + clingo_symbol_t *atoms = NULL; + size_t atoms_n; + clingo_symbol_t const *it, *ie; + char *str = NULL; + size_t str_n = 0; + + // determine the number of (shown) symbols in the model + if (!clingo_model_symbols_size(model, clingo_show_type_shown, &atoms_n)) { goto error; - } + } - str = str_new; - str_n = n; + // allocate required memory to hold all the symbols + if (!(atoms = (clingo_symbol_t *)malloc(sizeof(*atoms) * atoms_n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for atoms"); + goto error; } - // retrieve the symbol's string - if (!clingo_symbol_to_string(*it, str, n)) { goto error; } + // retrieve the symbols in the model + if (!clingo_model_symbols(model, clingo_show_type_shown, atoms, atoms_n)) { + goto error; + } + + printf("Model:"); + + for (it = atoms, ie = atoms + atoms_n; it != ie; ++it) { + size_t n; + char *str_new; + + // determine size of the string representation of the next symbol in the model + if (!clingo_symbol_to_string_size(*it, &n)) { + goto error; + } + + if (str_n < n) { + // allocate required memory to hold the symbol's string + if (!(str_new = (char *)realloc(str, sizeof(*str) * n))) { + clingo_set_error(clingo_error_bad_alloc, "could not allocate memory for symbol's string"); + goto error; + } + + str = str_new; + str_n = n; + } - printf(" %s", str); - } + // retrieve the symbol's string + if (!clingo_symbol_to_string(*it, str, n)) { + goto error; + } - printf("\n"); - goto out; + printf(" %s", str); + } + + printf("\n"); + goto out; error: - ret = false; + ret = false; out: - if (atoms) { free(atoms); } - if (str) { free(str); } + if (atoms) { + free(atoms); + } + if (str) { + free(str); + } - return ret; + return ret; } bool solve(clingo_control_t *ctl, clingo_solve_result_bitset_t *result, clingo_literal_t assumption) { - bool ret = true; - clingo_solve_handle_t *handle; - clingo_model_t const *model; - - // get a solve handle - if (!clingo_control_solve(ctl, clingo_solve_mode_yield, &assumption, assumption != 0 ? 1 : 0, NULL, NULL, &handle)) { goto error; } - // loop over all models - while (true) { - if (!clingo_solve_handle_resume(handle)) { goto error; } - if (!clingo_solve_handle_model(handle, &model)) { goto error; } - // print the model - if (model) { print_model(model); } - // stop if there are no more models - else { break; } - } - // close the solve handle - if (!clingo_solve_handle_get(handle, result)) { goto error; } - - goto out; + bool ret = true; + clingo_solve_handle_t *handle; + clingo_model_t const *model; + + // get a solve handle + if (!clingo_control_solve(ctl, clingo_solve_mode_yield, &assumption, assumption != 0 ? 1 : 0, NULL, NULL, + &handle)) { + goto error; + } + // loop over all models + while (true) { + if (!clingo_solve_handle_resume(handle)) { + goto error; + } + if (!clingo_solve_handle_model(handle, &model)) { + goto error; + } + // print the model + if (model) { + print_model(model); + } + // stop if there are no more models + else { + break; + } + } + // close the solve handle + if (!clingo_solve_handle_get(handle, result)) { + goto error; + } + + goto out; error: - ret = false; + ret = false; out: - // free the solve handle - return clingo_solve_handle_close(handle) && ret; + // free the solve handle + return clingo_solve_handle_close(handle) && ret; } int main(int argc, char const **argv) { - char const *error_message; - int ret = 0; - size_t size; - clingo_solve_result_bitset_t solve_ret; - clingo_control_t *ctl = NULL; - clingo_part_t parts[] = {{ "base", NULL, 0 }}; - clingo_theory_atoms_t const *atoms; - clingo_literal_t lit = 0; - - // create a control object and pass command line arguments - if (!clingo_control_new(argv+1, argc-1, NULL, NULL, 20, &ctl) != 0) { goto error; } - - // add a logic program to the base part - if (!clingo_control_add(ctl, "base", NULL, 0, - "#theory t {" - " term { + : 1, binary, left };" - " &a/0 : term, any;" - " &b/1 : term, {=}, term, any" - "}." - "x :- &a { 1+2 }." - "y :- &b(3) { } = 17." - )) { goto error; } - - // ground the base part - if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { goto error; } - - // get the theory atoms container - if (!clingo_control_theory_atoms(ctl, &atoms)) { goto error; } - - // print the number of grounded theory atoms - if (!clingo_theory_atoms_size(atoms, &size)) { goto error; } - printf("number of grounded theory atoms: %zu\n", size); - - // verify that theory atom b has a guard - for (clingo_id_t atom = 0; atom < size; ++atom) { - clingo_id_t term; - char const *name; - - // get the term associated with the theory atom - if (!clingo_theory_atoms_atom_term(atoms, atom, &term)) { goto error; } - // get the name associated with the theory atom - if (!clingo_theory_atoms_term_name(atoms, term, &name)) { goto error; } - // we got theory atom b/1 here - if (strcmp(name, "b") == 0) { - bool guard; - if (!clingo_theory_atoms_atom_has_guard(atoms, atom, &guard)) { goto error; } - printf("theory atom b/1 has a guard: %s\n", guard ? "true" : "false"); - // get the literal associated with the theory atom - if (!clingo_theory_atoms_atom_literal(atoms, atom, &lit)) { goto error; } - break; - } - } - - // solve using a model callback - if (!solve(ctl, &solve_ret, lit)) { goto error; } - - goto out; + char const *error_message; + int ret = 0; + size_t size; + clingo_solve_result_bitset_t solve_ret; + clingo_control_t *ctl = NULL; + clingo_part_t parts[] = {{"base", NULL, 0}}; + clingo_theory_atoms_t const *atoms; + clingo_literal_t lit = 0; + + // create a control object and pass command line arguments + if (!clingo_control_new(argv + 1, argc - 1, NULL, NULL, 20, &ctl) != 0) { + goto error; + } + + // add a logic program to the base part + if (!clingo_control_add(ctl, "base", NULL, 0, + "#theory t {" + " term { + : 1, binary, left };" + " &a/0 : term, any;" + " &b/1 : term, {=}, term, any" + "}." + "x :- &a { 1+2 }." + "y :- &b(3) { } = 17.")) { + goto error; + } + + // ground the base part + if (!clingo_control_ground(ctl, parts, 1, NULL, NULL)) { + goto error; + } + + // get the theory atoms container + if (!clingo_control_theory_atoms(ctl, &atoms)) { + goto error; + } + + // print the number of grounded theory atoms + if (!clingo_theory_atoms_size(atoms, &size)) { + goto error; + } + printf("number of grounded theory atoms: %zu\n", size); + + // verify that theory atom b has a guard + for (clingo_id_t atom = 0; atom < size; ++atom) { + clingo_id_t term; + char const *name; + + // get the term associated with the theory atom + if (!clingo_theory_atoms_atom_term(atoms, atom, &term)) { + goto error; + } + // get the name associated with the theory atom + if (!clingo_theory_atoms_term_name(atoms, term, &name)) { + goto error; + } + // we got theory atom b/1 here + if (strcmp(name, "b") == 0) { + bool guard; + if (!clingo_theory_atoms_atom_has_guard(atoms, atom, &guard)) { + goto error; + } + printf("theory atom b/1 has a guard: %s\n", guard ? "true" : "false"); + // get the literal associated with the theory atom + if (!clingo_theory_atoms_atom_literal(atoms, atom, &lit)) { + goto error; + } + break; + } + } + + // solve using a model callback + if (!solve(ctl, &solve_ret, lit)) { + goto error; + } + + goto out; error: - if (!(error_message = clingo_error_message())) { error_message = "error"; } + if (!(error_message = clingo_error_message())) { + error_message = "error"; + } - printf("%s\n", error_message); - ret = clingo_error_code(); + printf("%s\n", error_message); + ret = clingo_error_code(); out: - if (ctl) { clingo_control_free(ctl); } + if (ctl) { + clingo_control_free(ctl); + } - return ret; + return ret; } - diff --git a/examples/c/version.c b/examples/c/version.c index 2676c8a04..9af89c25d 100644 --- a/examples/c/version.c +++ b/examples/c/version.c @@ -1,14 +1,13 @@ #include -#include #include +#include int main() { - int major, minor, revision; + int major, minor, revision; - clingo_version(&major, &minor, &revision); + clingo_version(&major, &minor, &revision); - printf("Hello, this is clingo version %d.%d.%d.\n", major, minor, revision); + printf("Hello, this is clingo version %d.%d.%d.\n", major, minor, revision); - return 0; + return 0; } - diff --git a/examples/cc/heuristic.cc b/examples/cc/heuristic.cc index 2f88d7905..e4fca29d7 100644 --- a/examples/cc/heuristic.cc +++ b/examples/cc/heuristic.cc @@ -2,65 +2,65 @@ // run this example, use the instances provided with the other example. #include -#include #include +#include namespace Detail { - template - void heap_rise_(H &h, I x) { - if (x > 0) { - auto y = (x - 1) / 2; - if (h.priority(y) < h.priority(x)) { - h.swap(x, y); - heap_rise_(h, y); - } +template void heap_rise_(H &h, I x) { + if (x > 0) { + auto y = (x - 1) / 2; + if (h.priority(y) < h.priority(x)) { + h.swap(x, y); + heap_rise_(h, y); } } - template - void heap_sink_(H &h, I i) { - auto j = i, l = 2 * j + 1, r = l + 1, s = h.size(); - if (l < s && h.priority(j) < h.priority(l)) { - j = l; - } - if (r < s && h.priority(j) < h.priority(r)) { - j = r; - } - if (i != j) { - h.swap(i, j); - heap_sink_(h, j); - } +} +template void heap_sink_(H &h, I i) { + auto j = i, l = 2 * j + 1, r = l + 1, s = h.size(); + if (l < s && h.priority(j) < h.priority(l)) { + j = l; + } + if (r < s && h.priority(j) < h.priority(r)) { + j = r; + } + if (i != j) { + h.swap(i, j); + heap_sink_(h, j); } } +} // namespace Detail -template -void heap_init(H &h) { +template void heap_init(H &h) { for (auto s = h.size(), i = s / 2; i > 0; --i) { Detail::heap_sink_(h, i - 1); } } -template -void heap_remove(H &h, I x) { +template void heap_remove(H &h, I x) { auto y = h.size() - 1; if (x != y) { auto px = h.priority(x), py = h.priority(y); h.swap(x, y); h.pop(); - if (px < py) { Detail::heap_rise_(h, x); } - else if (py < px) { Detail::heap_sink_(h, x); } + if (px < py) { + Detail::heap_rise_(h, x); + } else if (py < px) { + Detail::heap_sink_(h, x); + } } } -template -void heap_update(H &h, I x, P p) { +template void heap_update(H &h, I x, P p) { auto o = h.priority(x); h.priority(x) = p; - if (o < p) { Detail::heap_rise_(h, x); } - else if (p < o) { Detail::heap_sink_(h, x); } + if (o < p) { + Detail::heap_rise_(h, x); + } else if (p < o) { + Detail::heap_sink_(h, x); + } } -template -void heap_insert(H &h, V &&...x) { +template void heap_insert(H &h, V &&...x) { h.push(std::forward(x)...); Detail::heap_rise_(h, h.size() - 1); } @@ -72,14 +72,12 @@ struct Entry { using EntryMap = std::unordered_map; class Heap { -public: + public: int &priority(unsigned x) { assert(data[x]->second.position == x); return data[x]->second.degree; } - unsigned size() const { - return data.size(); - } + unsigned size() const { return data.size(); } void swap(unsigned x, unsigned y) { using std::swap; swap(data[x], data[y]); @@ -95,56 +93,55 @@ class Heap { data.back()->second.position = data.size() - 1; } - EntryMap::iterator front() const { - return data.front(); - } + EntryMap::iterator front() const { return data.front(); } -private: + private: std::vector data; }; class State { -public: + public: void add(Clingo::Symbol sym, int x) { auto ret = entries_.emplace(sym, Entry{0, 0}); - if (ret.second) { heap_.push(ret.first); } + if (ret.second) { + heap_.push(ret.first); + } ret.first->second.degree += x; } - void init() { - heap_init(heap_); - } + void init() { heap_init(heap_); } void update(Clingo::Symbol sym, int x) { auto &e = entries_.at(sym); - if (member(e)) { heap_update(heap_, e.position, e.degree + x); } - else { e.degree += x; } + if (member(e)) { + heap_update(heap_, e.position, e.degree + x); + } else { + e.degree += x; + } } void remove(Clingo::Symbol sym) { auto e = entries_.at(sym); - if (member(e)) { heap_remove(heap_, e.position); } + if (member(e)) { + heap_remove(heap_, e.position); + } } void insert(Clingo::Symbol sym) { auto e = entries_.find(sym); - if (!member(e->second)) { heap_insert(heap_, e); } - } - bool empty() const { - return heap_.size() == 0; - } - Clingo::Symbol peak() const { - return heap_.front()->first; + if (!member(e->second)) { + heap_insert(heap_, e); + } } + bool empty() const { return heap_.size() == 0; } + Clingo::Symbol peak() const { return heap_.front()->first; } -private: - bool member(Entry &e) { - return e.position < std::numeric_limits::max(); - } + private: + bool member(Entry &e) { return e.position < std::numeric_limits::max(); } -private: + private: EntryMap entries_; Heap heap_; }; class ColoringHeuristic : public Clingo::Heuristic { -public: + public: void init(Clingo::PropagateInit &init) override { states_.resize(init.number_of_threads()); for (auto &&a : init.symbolic_atoms()) { @@ -157,8 +154,7 @@ class ColoringHeuristic : public Clingo::Heuristic { state.add(u, 1); state.add(v, 1); } - } - else if (a.match("assign", 2)) { + } else if (a.match("assign", 2)) { auto u = a.symbol().arguments()[0]; auto l = init.solver_literal(a.literal()); init.add_watch(l); @@ -211,31 +207,32 @@ class ColoringHeuristic : public Clingo::Heuristic { return 0; } -private: + private: std::unordered_map, Clingo::SymbolVector>> graph_; std::unordered_map assign_; std::vector states_; }; class GraphColorizer : Clingo::Application { -public: + public: static int run(int argc, char const **argv) { GraphColorizer gc; - return Clingo::clingo_main(gc, {argv+1, argv+argc}); + return Clingo::clingo_main(gc, {argv + 1, argv + argc}); } -private: - char const *program_name() const noexcept override { - return "colorizer"; - }; + + private: + char const *program_name() const noexcept override { return "colorizer"; }; char const *version() const noexcept override { return "1.0"; } void main(Clingo::Control &ctl, Clingo::StringSpan files) override { for (auto &&file : files) { ctl.load(file); } - if (files.empty()) { ctl.load("-"); } + if (files.empty()) { + ctl.load("-"); + } ctl.add("base", {}, - "1 { assign(U,C) : color(C) } 1 :- vertex(U).\n" - " :- edge(U,V), assign(U,C), assign(V,C).\n"); + "1 { assign(U,C) : color(C) } 1 :- vertex(U).\n" + " :- edge(U,V), assign(U,C), assign(V,C).\n"); ColoringHeuristic heu; ctl.register_propagator(heu); ctl.ground({{"base", {}}}); @@ -243,6 +240,4 @@ class GraphColorizer : Clingo::Application { } }; -int main(int argc, char const **argv) { - return GraphColorizer::run(argc, argv); -} +int main(int argc, char const **argv) { return GraphColorizer::run(argc, argv); } diff --git a/examples/cc/inject-terms.cc b/examples/cc/inject-terms.cc index 69ac56f55..a37df761d 100644 --- a/examples/cc/inject-terms.cc +++ b/examples/cc/inject-terms.cc @@ -13,10 +13,8 @@ void ground_callback(Location, char const *name, SymbolSpan args, SymbolSpanCall int main(int argc, char const **argv) { try { - Logger logger = [](Clingo::WarningCode, char const *message) { - std::cerr << message << std::endl; - }; - Control ctl{{argv+1, size_t(argc-1)}, logger, 20}; + Logger logger = [](Clingo::WarningCode, char const *message) { std::cerr << message << std::endl; }; + Control ctl{{argv + 1, size_t(argc - 1)}, logger, 20}; // define a constant in string form std::ostringstream out; @@ -26,7 +24,8 @@ int main(int argc, char const **argv) { // define a constant via the AST AST::with_builder(ctl, [](AST::ProgramBuilder &b) { Location loc{"", "", 1, 1, 1, 1}; - b.add(AST::Node(AST::Type::Definition, loc, "e", AST::Node(AST::Type::SymbolicTerm, loc, Number(24)), false)); + b.add( + AST::Node(AST::Type::Definition, loc, "e", AST::Node(AST::Type::SymbolicTerm, loc, Number(24)), false)); }); ctl.add("base", {}, "p(@c()). p(d). p(e)."); @@ -38,9 +37,7 @@ int main(int argc, char const **argv) { } std::cout << "\n"; } - } - catch (std::exception const &e) { + } catch (std::exception const &e) { std::cerr << "example failed with: " << e.what() << std::endl; } } - diff --git a/examples/cc/solve-iteratively.cc b/examples/cc/solve-iteratively.cc index 3ecb19cb4..5556cf193 100644 --- a/examples/cc/solve-iteratively.cc +++ b/examples/cc/solve-iteratively.cc @@ -5,10 +5,8 @@ using namespace Clingo; int main(int argc, char const **argv) { try { - Logger logger = [](Clingo::WarningCode, char const *message) { - std::cerr << message << std::endl; - }; - Control ctl{{argv+1, size_t(argc-1)}, logger, 20}; + Logger logger = [](Clingo::WarningCode, char const *message) { std::cerr << message << std::endl; }; + Control ctl{{argv + 1, size_t(argc - 1)}, logger, 20}; ctl.add("base", {}, "a :- not b. b :- not a."); ctl.ground({{"base", {}}}); for (auto &m : ctl.solve()) { @@ -18,9 +16,7 @@ int main(int argc, char const **argv) { } std::cout << "\n"; } - } - catch (std::exception const &e) { + } catch (std::exception const &e) { std::cerr << "example failed with: " << e.what() << std::endl; } } - diff --git a/examples/clingo/chemistry/README.md b/examples/clingo/chemistry/README.md index 0eee4098a..97b3d235d 100644 --- a/examples/clingo/chemistry/README.md +++ b/examples/clingo/chemistry/README.md @@ -11,7 +11,7 @@ Examples - base solutions: - a(1) a(2) - + Exmaple 2: loading files: - chemistry.lp @@ -19,7 +19,7 @@ Examples - acid(42) solutions: - b(42) - + Exmaple 3: loading files: - chemistry.lp diff --git a/examples/clingo/chemistry/app.py b/examples/clingo/chemistry/app.py index 80817d26f..12334d267 100644 --- a/examples/clingo/chemistry/app.py +++ b/examples/clingo/chemistry/app.py @@ -1,8 +1,8 @@ -''' +""" Example exploring program parts and externals. -''' +""" -from typing import List, Sequence, Tuple, Optional +from typing import List, Optional, Sequence, Tuple from clingo.control import Control from clingo.symbol import Function, Number, Symbol @@ -12,48 +12,50 @@ def part_str(part: Tuple[str, List[Symbol]]): - ''' + """ Return a nice string representation of the given program part to ground. - ''' + """ if part[1]: return f'{part[0]}({", ".join(map(str, part[1]))})' - return f'{part[0]}' + return f"{part[0]}" def run(files: Sequence[str], parts: Parts, assign: Externals = ()): - ''' + """ Loads the given files into a control object, grounds the given program parts, and assign the given externals to the given truth values. - ''' + """ ctl = Control() - print(' loading files:') + print(" loading files:") for file_ in files: - print(f' - {file_}') + print(f" - {file_}") ctl.load(file_) - print(' grounding:') + print(" grounding:") for part in parts: - print(f' - {part_str(part)}') + print(f" - {part_str(part)}") ctl.ground([part]) if assign: - print(' assigning externals:') + print(" assigning externals:") for sym, truth in assign: - print(f' - {sym}={truth}') + print(f" - {sym}={truth}") ctl.assign_external(sym, truth) - print(' solutions:') - ctl.solve(on_model=lambda m: print(f' - {m}')) + print(" solutions:") + ctl.solve(on_model=lambda m: print(f" - {m}")) -print('Exmaple 1:') -run(['chemistry.lp'], [("base", [])]) +print("Exmaple 1:") +run(["chemistry.lp"], [("base", [])]) -print('\nExmaple 2:') -run(['chemistry.lp'], [("acid", [Number(42)])]) +print("\nExmaple 2:") +run(["chemistry.lp"], [("acid", [Number(42)])]) -print('\nExmaple 3:') -run(['chemistry.lp', 'external.lp'], +print("\nExmaple 3:") +run( + ["chemistry.lp", "external.lp"], [("base", []), ("acid", [Number(42)])], - [(Function("d", [Number(1), Number(42)]), True)]) + [(Function("d", [Number(1), Number(42)]), True)], +) diff --git a/examples/clingo/chemistry/chemistry.lp b/examples/clingo/chemistry/chemistry.lp index 3aec65ea1..7c656dd73 100644 --- a/examples/clingo/chemistry/chemistry.lp +++ b/examples/clingo/chemistry/chemistry.lp @@ -10,4 +10,3 @@ c(X,k) :- a(X). #program base. a(2). - diff --git a/examples/clingo/chemistry/external.lp b/examples/clingo/chemistry/external.lp index af80760f4..09a178bb7 100644 --- a/examples/clingo/chemistry/external.lp +++ b/examples/clingo/chemistry/external.lp @@ -3,4 +3,3 @@ #external d(X,k) : c(X,k). e(X,k) :- d(X,k). - diff --git a/examples/clingo/consequences/brave-lua.lp b/examples/clingo/consequences/brave-lua.lp index 0b03aa49f..0d2f31e0f 100644 --- a/examples/clingo/consequences/brave-lua.lp +++ b/examples/clingo/consequences/brave-lua.lp @@ -41,4 +41,3 @@ end #program brave. :- not holds(X) : atom(X), @is_brave(X) == 0. - diff --git a/examples/clingo/consequences/brave-py.lp b/examples/clingo/consequences/brave-py.lp index 9df8560b0..47d94ad8c 100644 --- a/examples/clingo/consequences/brave-py.lp +++ b/examples/clingo/consequences/brave-py.lp @@ -22,4 +22,3 @@ def main(prg): #program brave. :- not holds(X) : atom(X), @is_brave(X) == 0. - diff --git a/examples/clingo/context/context-lua.lp b/examples/clingo/context/context-lua.lp index 80d1b00c3..2dfd0e5cd 100644 --- a/examples/clingo/context/context-lua.lp +++ b/examples/clingo/context/context-lua.lp @@ -1,4 +1,4 @@ -#script (lua) +#script (lua) State = { } State.__index = State @@ -22,7 +22,7 @@ function State:run(prg) prg:solve{on_model=function (...) self:on_model(...) end} end -function main(prg) +function main(prg) x = State.new(21) x:run(prg) end diff --git a/examples/clingo/context/context-py.lp b/examples/clingo/context/context-py.lp index bfac4f17f..204457990 100644 --- a/examples/clingo/context/context-py.lp +++ b/examples/clingo/context/context-py.lp @@ -1,4 +1,4 @@ -#script (python) +#script (python) from clingo import Number @@ -8,14 +8,14 @@ class State: def test(self, value): return Number(self.value + value.number) - + def __on_model(self, m): print (m) def run(self, prg): prg.ground([("base", [])], self) prg.solve(on_model=self.__on_model) - + def main(prg): x = State(21) x.run(prg) diff --git a/examples/clingo/controller-async/client.lp b/examples/clingo/controller-async/client.lp index a0a42d707..f39daeb85 100644 --- a/examples/clingo/controller-async/client.lp +++ b/examples/clingo/controller-async/client.lp @@ -12,4 +12,3 @@ 1 { p(k,X); q(k,X) } 1 :- X = 1..m, sleep(k), not p. :- not m+1 { p(k,1..m); q(k,1..m) }, sleep(k), not p. - diff --git a/examples/clingo/controller-async/controller.py b/examples/clingo/controller-async/controller.py index 239ed94b1..240f7ca1f 100755 --- a/examples/clingo/controller-async/controller.py +++ b/examples/clingo/controller-async/controller.py @@ -1,23 +1,36 @@ #!/usr/bin/env python +import atexit import os import readline -import atexit import signal from threading import Condition -from clingo import Control, Number, Function + +from clingo import Control, Function, Number + class Controller: def __init__(self): histfile = os.path.join(os.path.expanduser("~"), ".controller") - try: readline.read_history_file(histfile) - except IOError: pass - readline.parse_and_bind('tab: complete') + try: + readline.read_history_file(histfile) + except IOError: + pass + readline.parse_and_bind("tab: complete") + def complete(commands, text, state): matches = [] - if state == 0: matches = [ c for c in commands if c.startswith(text) ] + if state == 0: + matches = [c for c in commands if c.startswith(text)] return matches[state] if state < len(matches) else None - readline.set_completer(lambda text, state: complete(['more_pigeon_please', 'less_pigeon_please', 'solve', 'exit'], text, state)) + + readline.set_completer( + lambda text, state: complete( + ["more_pigeon_please", "less_pigeon_please", "solve", "exit"], + text, + state, + ) + ) atexit.register(readline.write_history_file, histfile) self.solving = False self.condition = Condition() @@ -30,7 +43,9 @@ def interrupt(self, a, b): self.solver.stop() def on_finish(self, ret): - self.message = "finish: " + str(ret) + (" (INTERRUPTED)" if ret.interrupted else "") + self.message = ( + "finish: " + str(ret) + (" (INTERRUPTED)" if ret.interrupted else "") + ) self.condition.acquire() self.solving = False self.condition.notify() @@ -50,9 +65,11 @@ def run(self): while True: signal.signal(signal.SIGINT, pyInt) try: - try: input_ = raw_input - except NameError: input_ = input - line = input_('> ') + try: + input_ = raw_input + except NameError: + input_ = input + line = input_("> ") signal.signal(signal.SIGINT, signal.SIG_IGN) except EOFError: signal.signal(signal.SIGINT, signal.SIG_IGN) @@ -85,12 +102,13 @@ def run(self): else: print("unknown command: " + line) + class Solver: def __init__(self): - self.k = 0 + self.k = 0 self.prg = Control() self.prg.load("client.lp") - self.prg.ground([("pigeon", []), ("sleep", [Number(self.k)])]) + self.prg.ground([("pigeon", []), ("sleep", [Number(self.k)])]) self.prg.assign_external(Function("sleep", [Number(self.k)]), True) self.ret = None self.models = [] @@ -102,9 +120,11 @@ def start(self, on_finish): if self.ret is not None and not self.ret.unknown(): self.k = self.k + 1 self.prg.ground([("sleep", [self.k])]) - self.prg.release_external(Function("sleep", [Number(self.k-1)])) + self.prg.release_external(Function("sleep", [Number(self.k - 1)])) self.prg.assign_external(Function("sleep", [Number(self.k)]), True) - self.future = self.prg.solve(on_model=self.on_model, on_finish=on_finish, async_=True) + self.future = self.prg.solve( + on_model=self.on_model, on_finish=on_finish, async_=True + ) def stop(self): self.future.cancel() @@ -116,8 +136,8 @@ def finish(self): def set_more_pigeon(self, more): self.prg.assign_external(Function("p"), more) + st = Solver() ct = Controller() ct.register_solver(st) ct.run() - diff --git a/examples/clingo/controller-processes/README b/examples/clingo/controller-processes/README index 04b467b37..4e12daec7 100644 --- a/examples/clingo/controller-processes/README +++ b/examples/clingo/controller-processes/README @@ -1,7 +1,7 @@ This example shows how clingo's asynchronous solving capabilities can be used in a client server scenario. -To start the server, execute: +To start the server, execute: python server.py Afterwards, start the client: diff --git a/examples/clingo/controller-processes/client.lp b/examples/clingo/controller-processes/client.lp index a0a42d707..f39daeb85 100644 --- a/examples/clingo/controller-processes/client.lp +++ b/examples/clingo/controller-processes/client.lp @@ -12,4 +12,3 @@ 1 { p(k,X); q(k,X) } 1 :- X = 1..m, sleep(k), not p. :- not m+1 { p(k,1..m); q(k,1..m) }, sleep(k), not p. - diff --git a/examples/clingo/controller-processes/client.py b/examples/clingo/controller-processes/client.py index 2fc722c10..9c58b7e37 100644 --- a/examples/clingo/controller-processes/client.py +++ b/examples/clingo/controller-processes/client.py @@ -1,31 +1,40 @@ -import socket -import os import errno +import os +import socket + from clingo import Control, Function, Number + class Receiver: def __init__(self, conn): self.conn = conn self.data = bytearray() + def readline(self): pos = self.data.find(b"\n") while pos < 0: while True: - try: self.data.extend(self.conn.recv(4096)) + try: + self.data.extend(self.conn.recv(4096)) except OSError as e: - if e.errno != errno.EINTR: raise + if e.errno != errno.EINTR: + raise except socket.error as e: code, msg = e - if code != errno.EINTR: raise - else: break - pos = self. data.find(b"\n") + if code != errno.EINTR: + raise + else: + break + pos = self.data.find(b"\n") msg = self.data[:pos] - self.data = self.data[pos+1:] + self.data = self.data[pos + 1 :] return msg + class States: SOLVE = 1 - IDLE = 2 + IDLE = 2 + def main(prg): with open(".controller.PORT", "r") as f: @@ -33,16 +42,25 @@ def main(prg): os.remove(".controller.PORT") conn = socket.create_connection(("127.0.0.1", p)) try: - recv = Receiver(conn) + recv = Receiver(conn) state = States.IDLE - k = 0 - prg.ground([("pigeon", []), ("sleep", [Number(k)])]) + k = 0 + prg.ground([("pigeon", []), ("sleep", [Number(k)])]) prg.assign_external(Function("sleep", [Number(k)]), True) while True: if state == States.SOLVE: f = prg.solve( - on_model = lambda model: conn.sendall(b"Answer: " + str(model).encode() + b"\n"), - on_finish = lambda ret: conn.sendall(b"finish:" + str(ret).encode() + (b":INTERRUPTED" if ret.interrupted else b"") + b"\n"), async_=True) + on_model=lambda model: conn.sendall( + b"Answer: " + str(model).encode() + b"\n" + ), + on_finish=lambda ret: conn.sendall( + b"finish:" + + str(ret).encode() + + (b":INTERRUPTED" if ret.interrupted else b"") + + b"\n" + ), + async_=True, + ) msg = recv.readline().decode() if state == States.SOLVE: f.cancel() @@ -61,16 +79,17 @@ def main(prg): state = States.IDLE elif msg == "solve": state = States.SOLVE - else: raise(RuntimeError("unexpected message: " + msg)) + else: + raise (RuntimeError("unexpected message: " + msg)) if ret is not None and not ret.unknown: k = k + 1 prg.ground([("sleep", [Number(k)])]) - prg.release_external(Function("sleep", [Number(k-1)])) + prg.release_external(Function("sleep", [Number(k - 1)])) prg.assign_external(Function("sleep", [Number(k)]), True) finally: conn.close() + prg = Control() prg.load("client.lp") main(prg) - diff --git a/examples/clingo/controller-processes/server.py b/examples/clingo/controller-processes/server.py index 5c918cb72..ffcfd9f3e 100644 --- a/examples/clingo/controller-processes/server.py +++ b/examples/clingo/controller-processes/server.py @@ -1,39 +1,56 @@ #!/usr/bin/env python -import socket -import os -import readline import atexit +import errno +import os import random +import readline import signal -import errno +import socket histfile = os.path.join(os.path.expanduser("~"), ".controller") -try: readline.read_history_file(histfile) -except IOError: pass -readline.parse_and_bind('tab: complete') +try: + readline.read_history_file(histfile) +except IOError: + pass +readline.parse_and_bind("tab: complete") + + def complete(commands, text, state): matches = [] - if state == 0: matches = [ c for c in commands if c.startswith(text) ] + if state == 0: + matches = [c for c in commands if c.startswith(text)] return matches[state] if state < len(matches) else None -readline.set_completer(lambda text, state: complete(['more_pigeon_please', 'less_pigeon_please', 'solve', 'exit'], text, state)) + + +readline.set_completer( + lambda text, state: complete( + ["more_pigeon_please", "less_pigeon_please", "solve", "exit"], text, state + ) +) atexit.register(readline.write_history_file, histfile) + def handleMessages(conn): def interrupt(conn): signal.signal(signal.SIGINT, signal.SIG_IGN) conn.sendall(b"interrupt\n") + signal.signal(signal.SIGINT, lambda a, b: interrupt(conn)) data = bytearray() while True: while True: - try: data.extend(conn.recv(4096)) + try: + data.extend(conn.recv(4096)) except OSError as e: - if e.errno != errno.EINTR: raise + if e.errno != errno.EINTR: + raise except socket.error as e: code, msg = e - if code != errno.EINTR: raise - else: break + if code != errno.EINTR: + raise + else: + break pos = data.find(b"\n") while pos >= 0: (msg, data) = data.split(b"\n", 1) @@ -47,20 +64,24 @@ def interrupt(conn): pos = data.find(b"\n") signal.signal(signal.SIGINT, signal.SIG_IGN) + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: - for i in range(0,10): + for i in range(0, 10): try: p = random.randrange(1000, 60000) s.bind(("", p)) except OSError as e: - if e.errno != errno.EINTR: raise + if e.errno != errno.EINTR: + raise except socket.error as e: code, msg = e - if code != errno.EADDRINUSE: raise + if code != errno.EADDRINUSE: + raise continue else: - with open(".controller.PORT", "w") as f: f.write(str(p)) + with open(".controller.PORT", "w") as f: + f.write(str(p)) print("waiting for connections...") break raise "no port found" @@ -79,9 +100,11 @@ def interrupt(conn): while True: signal.signal(signal.SIGINT, pyInt) try: - try: input_ = raw_input - except NameError: input_ = input - line = input_('> ') + try: + input_ = raw_input + except NameError: + input_ = input + line = input_("> ") signal.signal(signal.SIGINT, signal.SIG_IGN) except EOFError: signal.signal(signal.SIGINT, signal.SIG_IGN) @@ -105,4 +128,3 @@ def interrupt(conn): raise finally: s.close() - diff --git a/examples/clingo/controller-threads/client.lp b/examples/clingo/controller-threads/client.lp index a0a42d707..f39daeb85 100644 --- a/examples/clingo/controller-threads/client.lp +++ b/examples/clingo/controller-threads/client.lp @@ -12,4 +12,3 @@ 1 { p(k,X); q(k,X) } 1 :- X = 1..m, sleep(k), not p. :- not m+1 { p(k,1..m); q(k,1..m) }, sleep(k), not p. - diff --git a/examples/clingo/controller-threads/controller.py b/examples/clingo/controller-threads/controller.py index 60370ff86..26a56df97 100755 --- a/examples/clingo/controller-threads/controller.py +++ b/examples/clingo/controller-threads/controller.py @@ -1,11 +1,13 @@ #!/usr/bin/env python +import atexit import os import readline -import atexit import signal +from threading import Condition, Thread + from clingo import Control, Function, Number -from threading import Thread, Condition + class Connection: def __init__(self): @@ -26,19 +28,31 @@ def send(self, message): self.condition.notify() self.condition.release() + class Controller: def __init__(self): histfile = os.path.join(os.path.expanduser("~"), ".controller") - try: readline.read_history_file(histfile) - except IOError: pass - readline.parse_and_bind('tab: complete') + try: + readline.read_history_file(histfile) + except IOError: + pass + readline.parse_and_bind("tab: complete") + def complete(commands, text, state): matches = [] - if state == 0: matches = [ c for c in commands if c.startswith(text) ] + if state == 0: + matches = [c for c in commands if c.startswith(text)] return matches[state] if state < len(matches) else None - readline.set_completer(lambda text, state: complete(['more_pigeon_please', 'less_pigeon_please', 'solve', 'exit'], text, state)) + + readline.set_completer( + lambda text, state: complete( + ["more_pigeon_please", "less_pigeon_please", "solve", "exit"], + text, + state, + ) + ) atexit.register(readline.write_history_file, histfile) - self.input = Connection() + self.input = Connection() self.output = None def register_connection(self, connection): @@ -62,9 +76,11 @@ def run(self): while True: signal.signal(signal.SIGINT, pyInt) try: - try: input_ = raw_input - except NameError: input_ = input - line = input_('> ') + try: + input_ = raw_input + except NameError: + input_ = input + line = input_("> ") signal.signal(signal.SIGINT, signal.SIG_IGN) except EOFError: signal.signal(signal.SIGINT, signal.SIG_IGN) @@ -89,17 +105,18 @@ def run(self): else: print("unknown command: " + line) + class SolveThread(Thread): STATE_SOLVE = 1 - STATE_IDLE = 2 - STATE_EXIT = 3 + STATE_IDLE = 2 + STATE_EXIT = 3 def __init__(self, connection): Thread.__init__(self) - self.k = 0 + self.k = 0 self.prg = Control() self.prg.load("client.lp") - self.prg.ground([("pigeon", []), ("sleep", [Number(self.k)])]) + self.prg.ground([("pigeon", []), ("sleep", [Number(self.k)])]) self.prg.assign_external(Function("sleep", [Number(self.k)]), True) self.state = SolveThread.STATE_IDLE self.input = Connection() @@ -109,7 +126,9 @@ def on_model(self, model): self.output.send("answer: " + str(model)), def on_finish(self, ret): - self.output.send("finish: " + str(ret) + (" (INTERRUPTED)" if ret.interrupted else "")) + self.output.send( + "finish: " + str(ret) + (" (INTERRUPTED)" if ret.interrupted else "") + ) def handle_message(self, msg): if msg == "interrupt": @@ -124,12 +143,15 @@ def handle_message(self, msg): self.state = SolveThread.STATE_IDLE elif msg == "solve": self.state = SolveThread.STATE_SOLVE - else: raise(RuntimeError("unexpected message: " + msg)) + else: + raise (RuntimeError("unexpected message: " + msg)) def run(self): while True: if self.state == SolveThread.STATE_SOLVE: - f = self.prg.solve(on_model=self.on_model, on_finish=self.on_finish, async_=True) + f = self.prg.solve( + on_model=self.on_model, on_finish=self.on_finish, async_=True + ) msg = self.input.receive() if self.state == SolveThread.STATE_SOLVE: f.cancel() @@ -142,9 +164,10 @@ def run(self): elif ret is not None and not ret.unknown: self.k = self.k + 1 self.prg.ground([("sleep", [Number(self.k)])]) - self.prg.release_external(Function("sleep", [Number(self.k-1)])) + self.prg.release_external(Function("sleep", [Number(self.k - 1)])) self.prg.assign_external(Function("sleep", [Number(self.k)]), True) + ct = Controller() st = SolveThread(ct.input) ct.register_connection(st.input) @@ -152,4 +175,3 @@ def run(self): st.start() ct.run() st.join() - diff --git a/examples/clingo/cover/control-lua.lp b/examples/clingo/cover/control-lua.lp index 5b7a6fca6..5d4a2ac0c 100644 --- a/examples/clingo/cover/control-lua.lp +++ b/examples/clingo/cover/control-lua.lp @@ -6,7 +6,7 @@ State = { } State.__index = State function State.new() - local x = { + local x = { leaves = {}, last = nil } diff --git a/examples/clingo/dl/README.md b/examples/clingo/dl/README.md index 4e4ea732a..f59fca226 100644 --- a/examples/clingo/dl/README.md +++ b/examples/clingo/dl/README.md @@ -25,7 +25,7 @@ Enumerating all solutions of a flowshop problem. Answer: 6 dl((a,1),5) dl(bound,20) dl((a,2),10) dl((b,1),8) dl((b,2),14) dl((c,1),0) dl((c,2),5) permutation(c,a) permutation(a,b) SATISFIABLE - + Models : 6 Calls : 1 Time : 0.006s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s) @@ -43,7 +43,7 @@ Finding the optimal solution of a flowshop problem. Solving... Optimum found UNSATISFIABLE - + Models : 1 Calls : 2 Time : 0.006s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s) diff --git a/examples/clingo/dl/app.py b/examples/clingo/dl/app.py index 121bdf9bb..80bea7f57 100644 --- a/examples/clingo/dl/app.py +++ b/examples/clingo/dl/app.py @@ -1,24 +1,22 @@ -''' +""" This is a scaled down version of clingo-dl show casing how to implement a propagator for difference logic. -''' +""" -from typing import List, Sequence, Optional, MutableMapping, Tuple, Set, cast import heapq import sys +from typing import List, MutableMapping, Optional, Sequence, Set, Tuple, cast -from clingo import ast +from clingo import SolveResult, ast, parse_term +from clingo.application import Application, ApplicationOptions, clingo_main +from clingo.ast import AST, ProgramBuilder, Transformer, parse_files +from clingo.control import Control +from clingo.propagator import Assignment, PropagateControl, PropagateInit, Propagator +from clingo.solving import Model from clingo.symbol import Function, Number, Symbol, SymbolType, Tuple_ from clingo.theory_atoms import TheoryTerm, TheoryTermType -from clingo.solving import Model -from clingo.propagator import Assignment, PropagateControl, PropagateInit, Propagator -from clingo.application import clingo_main, Application, ApplicationOptions -from clingo.control import Control -from clingo import SolveResult, parse_term -from clingo.ast import parse_files, AST, ProgramBuilder, Transformer - -Node = Symbol # pylint: disable=invalid-name +Node = Symbol # pylint: disable=invalid-name Weight = int Level = int Edge = Tuple[Node, Node] @@ -40,19 +38,21 @@ }. """ -_BOP = {"+": lambda a, b: a + b, - "-": lambda a, b: a - b, - "*": lambda a, b: a * b, - "**": lambda a, b: a ** b, - "\\": lambda a, b: a % b, - "/": lambda a, b: a // b} +_BOP = { + "+": lambda a, b: a + b, + "-": lambda a, b: a - b, + "*": lambda a, b: a * b, + "**": lambda a, b: a**b, + "\\": lambda a, b: a % b, + "/": lambda a, b: a // b, +} def _evaluate(term: TheoryTerm) -> Symbol: - ''' + """ Evaluates the operators in a theory term in the same fashion as clingo evaluates its arithmetic functions. - ''' + """ # tuples if term.type == TheoryTermType.Tuple: return Tuple_([_evaluate(x) for x in term.arguments]) @@ -99,19 +99,20 @@ def _evaluate(term: TheoryTerm) -> Symbol: class HeadBodyTransformer(Transformer): - ''' + """ Transformer to tag head and body occurrences of `&diff` atoms. - ''' + """ + def visit_Literal(self, lit: AST, in_lit: bool = False) -> AST: - ''' + """ Visit literal; any theory atom in a literal is a body literal. - ''' + """ return lit.update(**self.visit_children(lit, True)) def visit_TheoryAtom(self, atom: AST, in_lit: bool = False) -> AST: - ''' + """ Visit theory atom and tag as given by in_lit. - ''' + """ # pylint: disable=invalid-name,no-self-use term = atom.term if term.name == "diff" and not term.arguments: @@ -119,17 +120,20 @@ def visit_TheoryAtom(self, atom: AST, in_lit: bool = False) -> AST: atom.term = ast.Function( term.location, term.name, - [ast.Function(term.location, loc, [], False)], False) + [ast.Function(term.location, loc, [], False)], + False, + ) return atom class Graph: - ''' + """ This class captures a graph with weighted edges that can be extended incrementally. Adding an edge triggers a cycle check that will report negative cycles. - ''' + """ + _potential: MapNodeWeight _graph: MutableMapping[Node, MapNodeWeight] _gamma: MapNodeWeight @@ -138,12 +142,12 @@ class Graph: _previous_potential: MutableMapping[Level, MapNodeWeight] def __init__(self): - self._potential = {} # {node: potential} - self._graph = {} # {node: {node : weight}} - self._gamma = {} # {node: gamma} - self._last_edges = {} # {node: edge} - self._previous_edge = {} # {level: {(node, node): weight}} - self._previous_potential = {} # {level: {node: potential}} + self._potential = {} # {node: potential} + self._graph = {} # {node: {node : weight}} + self._gamma = {} # {node: gamma} + self._last_edges = {} # {node: edge} + self._previous_edge = {} # {level: {(node, node): weight}} + self._previous_potential = {} # {level: {node: potential}} @staticmethod def _set(level, key, val, previous, get_current): @@ -165,21 +169,37 @@ def _reset(level, previous, get_current): del previous[level] def _reset_edge(self, level: Level): - self._reset(level, self._previous_edge, lambda key: (self._graph[key[0]], key[1])) + self._reset( + level, self._previous_edge, lambda key: (self._graph[key[0]], key[1]) + ) def _reset_potential(self, level: Level): self._reset(level, self._previous_potential, lambda key: (self._potential, key)) def _set_edge(self, level: Level, key: Edge, val: Weight): - self._set(level, key, val, self._previous_edge, lambda key: (self._graph[key[0]], key[1])) + self._set( + level, + key, + val, + self._previous_edge, + lambda key: (self._graph[key[0]], key[1]), + ) def _set_potential(self, level: Level, key: Node, val: Weight): - self._set(level, key, val, self._previous_potential, lambda key: (self._potential, key)) - - def add_edge(self, level: Level, edge: WeightedEdge) -> Optional[List[WeightedEdge]]: - ''' + self._set( + level, + key, + val, + self._previous_potential, + lambda key: (self._potential, key), + ) + + def add_edge( + self, level: Level, edge: WeightedEdge + ) -> Optional[List[WeightedEdge]]: + """ Add an edge to the graph and return a negative cycle (if there is one). - ''' + """ u, v, d = edge # If edge already exists from u to v with lower weight, new edge is redundant if u in self._graph and v in self._graph[u] and self._graph[u][v] <= d: @@ -193,7 +213,7 @@ def add_edge(self, level: Level, edge: WeightedEdge) -> Optional[List[WeightedEd self._graph.setdefault(u, {}) self._graph.setdefault(v, {}) - changed: Set[Node] = set() # Set of nodes for which potential has been changed + changed: Set[Node] = set() # Set of nodes for which potential has been changed min_gamma: List[Tuple[Weight, Node]] = [] # Update potential change induced by new edge, 0 for other nodes @@ -213,7 +233,9 @@ def add_edge(self, level: Level, edge: WeightedEdge) -> Optional[List[WeightedEd changed.add(s) for t in self._graph[s]: if t not in changed: - gamma_t = self._potential[s] + self._graph[s][t] - self._potential[t] + gamma_t = ( + self._potential[s] + self._graph[s][t] - self._potential[t] + ) if gamma_t < self._gamma[t]: self._gamma[t] = gamma_t heapq.heappush(min_gamma, (gamma_t, t)) @@ -240,33 +262,38 @@ def add_edge(self, level: Level, edge: WeightedEdge) -> Optional[List[WeightedEd return cycle def get_assignment(self) -> List[Tuple[Node, Weight]]: - ''' + """ Get the current assignment to integer variables. - ''' + """ zero = Number(0) adjust = self._potential[zero] if zero in self._potential else 0 - return [(node, adjust - self._potential[node]) for node in self._potential if node != zero] + return [ + (node, adjust - self._potential[node]) + for node in self._potential + if node != zero + ] def backtrack(self, level): - ''' + """ Backtrack the given level. - ''' + """ self._reset_edge(level) self._reset_potential(level) class DLPropagator(Propagator): - ''' + """ A propagator for difference constraints. - ''' + """ + _l2e: MutableMapping[int, List[WeightedEdge]] _e2l: MutableMapping[WeightedEdge, List[int]] _states: List[Graph] def __init__(self): - self._l2e = {} # {literal: [(node, node, weight)]} - self._e2l = {} # {(node, node, weight): [literal]} - self._states = [] # [Graph] + self._l2e = {} # {literal: [(node, node, weight)]} + self._e2l = {} # {(node, node, weight): [literal]} + self._states = [] # [Graph] def _add_edge(self, init: PropagateInit, lit: int, u: Node, v: Node, w: Weight): edge = (u, v, w) @@ -275,10 +302,10 @@ def _add_edge(self, init: PropagateInit, lit: int, u: Node, v: Node, w: Weight): init.add_watch(lit) def init(self, init: PropagateInit): - ''' + """ Initialize the propagator extracting difference constraints from the theory data. - ''' + """ for atom in init.theory_atoms: term = atom.term if term.name == "diff" and len(term.arguments) == 1: @@ -292,9 +319,9 @@ def init(self, init: PropagateInit): self._add_edge(init, -lit, v, u, -w - 1) def propagate(self, control: PropagateControl, changes: Sequence[int]): - ''' + """ Add edges that became true to the graph to check for negative cycles. - ''' + """ state = self._state(control.thread_id) level = control.assignment.decision_level for lit in changes: @@ -307,19 +334,21 @@ def propagate(self, control: PropagateControl, changes: Sequence[int]): return def undo(self, thread_id: int, assign: Assignment, changes: Sequence[int]): - ''' + """ Backtrack the last decision level propagated. - ''' + """ # pylint: disable=unused-argument self._state(thread_id).backtrack(assign.decision_level) def on_model(self, model: Model): - ''' + """ This function should be called when a model has been found to extend it with the integer variable assignments. - ''' + """ assignment = self._state(model.thread_id).get_assignment() - model.extend([Function("dl", [var, Number(value)]) for var, value in assignment]) + model.extend( + [Function("dl", [var, Number(value)]) for var, value in assignment] + ) def _state(self, thread_id: int) -> Graph: while len(self._states) <= thread_id: @@ -330,13 +359,14 @@ def _literal(self, control, edge): for lit in self._e2l[edge]: if control.assignment.is_true(lit): return lit - raise RuntimeError('must not happen') + raise RuntimeError("must not happen") class DLApp(Application): - ''' + """ Application extending clingo with difference constraints. - ''' + """ + program_name: str = "clingo-dl" version: str = "1.0" @@ -359,11 +389,17 @@ def _parse_minimize(self, val): return True def register_options(self, options: ApplicationOptions): - ''' + """ Register application options. - ''' - group = 'Clingo.DL Options' - options.add(group, 'minimize-variable', 'Minimize the given variable', self._parse_minimize, argument="") + """ + group = "Clingo.DL Options" + options.add( + group, + "minimize-variable", + "Minimize the given variable", + self._parse_minimize, + argument="", + ) def _read(self, path: str): if path == "-": @@ -374,9 +410,7 @@ def _read(self, path: str): def _rewrite(self, ctl: Control, files: Sequence[str]): with ProgramBuilder(ctl) as bld: hbt = HeadBodyTransformer() - parse_files( - files, - lambda stm: bld.add(cast(AST, hbt.visit(stm)))) + parse_files(files, lambda stm: bld.add(cast(AST, hbt.visit(stm)))) def _on_model(self, model: Model): self._propagator.on_model(model) @@ -388,10 +422,10 @@ def _on_model(self, model: Model): break def main(self, ctl: Control, files: Sequence[str]): - ''' + """ Register the difference constraint propagator, and then ground and solve. - ''' + """ ctl.register_propagator(self._propagator) ctl.add("base", [], THEORY) @@ -409,7 +443,9 @@ def main(self, ctl: Control, files: Sequence[str]): print("Found new bound: {}".format(self._bound)) if self._bound is None: break - ctl.ground([("bound", [Number(cast(int, self._bound) - 1), self._minimize])]) + ctl.ground( + [("bound", [Number(cast(int, self._bound) - 1), self._minimize])] + ) if self._bound is not None: print("Optimum found") diff --git a/examples/clingo/domains/domains-lua.lp b/examples/clingo/domains/domains-lua.lp index 4f3f8de86..4c778c252 100644 --- a/examples/clingo/domains/domains-lua.lp +++ b/examples/clingo/domains/domains-lua.lp @@ -21,4 +21,4 @@ function main(prg) end end -#end. +#end. diff --git a/examples/clingo/domains/domains-py.lp b/examples/clingo/domains/domains-py.lp index c71e6a3f2..ddaa45364 100644 --- a/examples/clingo/domains/domains-py.lp +++ b/examples/clingo/domains/domains-py.lp @@ -16,4 +16,4 @@ def main(prg): for x in prg.symbolic_atoms.signatures: print (("~" if not x[2] else "") + x[0] + "/" + str(x[1])) -#end. +#end. diff --git a/examples/clingo/domains/instance.lp b/examples/clingo/domains/instance.lp index e100d7b19..22ff45a86 100644 --- a/examples/clingo/domains/instance.lp +++ b/examples/clingo/domains/instance.lp @@ -1,5 +1,5 @@ p(1). -{ p(3) }. +{ p(3) }. #external p(1..3). q(X) :- p(X). diff --git a/examples/clingo/expansion/GraphColouring/instances/0004-graph_colouring-125-0.lp b/examples/clingo/expansion/GraphColouring/instances/0004-graph_colouring-125-0.lp index ad8e4a5b5..b2901d890 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0004-graph_colouring-125-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0004-graph_colouring-125-0.lp @@ -1684,4 +1684,3 @@ edge(119,124). edge(124,119). edge(122,123). edge(123,122). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0005-graph_colouring-125-0.lp b/examples/clingo/expansion/GraphColouring/instances/0005-graph_colouring-125-0.lp index b7372a7f3..efb746aae 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0005-graph_colouring-125-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0005-graph_colouring-125-0.lp @@ -1646,4 +1646,3 @@ edge(117,121). edge(121,117). edge(118,124). edge(124,118). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0007-graph_colouring-125-0.lp b/examples/clingo/expansion/GraphColouring/instances/0007-graph_colouring-125-0.lp index 7324cc7c2..3b2ccb6a8 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0007-graph_colouring-125-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0007-graph_colouring-125-0.lp @@ -1606,4 +1606,3 @@ edge(119,123). edge(123,119). edge(122,124). edge(124,122). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0008-graph_colouring-125-0.lp b/examples/clingo/expansion/GraphColouring/instances/0008-graph_colouring-125-0.lp index 1c80e1f35..ab639a8a1 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0008-graph_colouring-125-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0008-graph_colouring-125-0.lp @@ -1674,4 +1674,3 @@ edge(120,125). edge(125,120). edge(121,125). edge(125,121). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0013-graph_colouring-130-0.lp b/examples/clingo/expansion/GraphColouring/instances/0013-graph_colouring-130-0.lp index 224a0f300..ebb9c13ac 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0013-graph_colouring-130-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0013-graph_colouring-130-0.lp @@ -1711,4 +1711,3 @@ edge(122,123). edge(123,122). edge(127,130). edge(130,127). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0021-graph_colouring-135-0.lp b/examples/clingo/expansion/GraphColouring/instances/0021-graph_colouring-135-0.lp index 1eaf8b863..fed225c56 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0021-graph_colouring-135-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0021-graph_colouring-135-0.lp @@ -1978,4 +1978,3 @@ edge(127,131). edge(131,127). edge(128,132). edge(132,128). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0022-graph_colouring-135-0.lp b/examples/clingo/expansion/GraphColouring/instances/0022-graph_colouring-135-0.lp index 59f3020f4..41aadb0a0 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0022-graph_colouring-135-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0022-graph_colouring-135-0.lp @@ -2040,4 +2040,3 @@ edge(129,130). edge(130,129). edge(131,133). edge(133,131). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0023-graph_colouring-135-0.lp b/examples/clingo/expansion/GraphColouring/instances/0023-graph_colouring-135-0.lp index 4f822e51b..a009a7074 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0023-graph_colouring-135-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0023-graph_colouring-135-0.lp @@ -1866,4 +1866,3 @@ edge(128,135). edge(135,128). edge(129,134). edge(134,129). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0025-graph_colouring-135-0.lp b/examples/clingo/expansion/GraphColouring/instances/0025-graph_colouring-135-0.lp index 77061f359..1e9d508f0 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0025-graph_colouring-135-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0025-graph_colouring-135-0.lp @@ -1992,4 +1992,3 @@ edge(131,132). edge(132,131). edge(134,135). edge(135,134). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0032-graph_colouring-140-0.lp b/examples/clingo/expansion/GraphColouring/instances/0032-graph_colouring-140-0.lp index 0e3e46595..edb8d654b 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0032-graph_colouring-140-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0032-graph_colouring-140-0.lp @@ -2223,4 +2223,3 @@ edge(138,139). edge(139,138). edge(139,140). edge(140,139). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0036-graph_colouring-140-0.lp b/examples/clingo/expansion/GraphColouring/instances/0036-graph_colouring-140-0.lp index 56021abb6..53d95211e 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0036-graph_colouring-140-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0036-graph_colouring-140-0.lp @@ -2123,4 +2123,3 @@ edge(133,136). edge(136,133). edge(134,136). edge(136,134). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0039-graph_colouring-140-0.lp b/examples/clingo/expansion/GraphColouring/instances/0039-graph_colouring-140-0.lp index a5baafc00..48065232e 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0039-graph_colouring-140-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0039-graph_colouring-140-0.lp @@ -2171,4 +2171,3 @@ edge(135,140). edge(140,135). edge(136,139). edge(139,136). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0040-graph_colouring-140-0.lp b/examples/clingo/expansion/GraphColouring/instances/0040-graph_colouring-140-0.lp index 16663b35a..552dd8c0f 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0040-graph_colouring-140-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0040-graph_colouring-140-0.lp @@ -2211,4 +2211,3 @@ edge(135,140). edge(140,135). edge(137,140). edge(140,137). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0046-graph_colouring-145-0.lp b/examples/clingo/expansion/GraphColouring/instances/0046-graph_colouring-145-0.lp index f1cc3c8e2..4f7d60bde 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0046-graph_colouring-145-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0046-graph_colouring-145-0.lp @@ -2342,4 +2342,3 @@ edge(140,141). edge(141,140). edge(140,142). edge(142,140). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0047-graph_colouring-145-0.lp b/examples/clingo/expansion/GraphColouring/instances/0047-graph_colouring-145-0.lp index 94df63eb2..c3d2b9dce 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0047-graph_colouring-145-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0047-graph_colouring-145-0.lp @@ -2174,4 +2174,3 @@ edge(137,141). edge(141,137). edge(138,143). edge(143,138). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0048-graph_colouring-145-0.lp b/examples/clingo/expansion/GraphColouring/instances/0048-graph_colouring-145-0.lp index 94478b6b5..13b687f73 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0048-graph_colouring-145-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0048-graph_colouring-145-0.lp @@ -2230,4 +2230,3 @@ edge(139,143). edge(143,139). edge(140,144). edge(144,140). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0050-graph_colouring-145-0.lp b/examples/clingo/expansion/GraphColouring/instances/0050-graph_colouring-145-0.lp index ef4867e3c..fdb27d3fd 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0050-graph_colouring-145-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0050-graph_colouring-145-0.lp @@ -2216,4 +2216,3 @@ edge(139,144). edge(144,139). edge(139,145). edge(145,139). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0056-graph_colouring-150-0.lp b/examples/clingo/expansion/GraphColouring/instances/0056-graph_colouring-150-0.lp index 680b5f7eb..0f6727b27 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0056-graph_colouring-150-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0056-graph_colouring-150-0.lp @@ -2249,4 +2249,3 @@ edge(145,148). edge(148,145). edge(148,149). edge(149,148). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0059-graph_colouring-150-0.lp b/examples/clingo/expansion/GraphColouring/instances/0059-graph_colouring-150-0.lp index 770c1b05e..fa73f8819 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0059-graph_colouring-150-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0059-graph_colouring-150-0.lp @@ -2371,4 +2371,3 @@ edge(143,147). edge(147,143). edge(146,148). edge(148,146). - diff --git a/examples/clingo/expansion/GraphColouring/instances/0060-graph_colouring-150-0.lp b/examples/clingo/expansion/GraphColouring/instances/0060-graph_colouring-150-0.lp index 70f220601..71767ad09 100644 --- a/examples/clingo/expansion/GraphColouring/instances/0060-graph_colouring-150-0.lp +++ b/examples/clingo/expansion/GraphColouring/instances/0060-graph_colouring-150-0.lp @@ -2469,4 +2469,3 @@ edge(144,147). edge(147,144). edge(147,148). edge(148,147). - diff --git a/examples/clingo/expansion/README b/examples/clingo/expansion/README index 2a3cf5949..5994cb24a 100644 --- a/examples/clingo/expansion/README +++ b/examples/clingo/expansion/README @@ -30,4 +30,3 @@ $ ./main.py --verbose --option solver.forget_on_step 1 \ $ ./main.py --verbose --option solver.forget_on_step 1 --maxobj 40 \ PartnerUnits/encodings/encoding.lp \ PartnerUnits/instances/180-partner_units_polynomial-47-0.lp - diff --git a/examples/clingo/expansion/main.py b/examples/clingo/expansion/main.py index 91f093682..56694f853 100755 --- a/examples/clingo/expansion/main.py +++ b/examples/clingo/expansion/main.py @@ -1,18 +1,19 @@ #!/usr/bin/env python +import argparse import json import sys -import argparse from clingo import Control, Number + class App: def __init__(self, args): self.control = Control() self.args = args self.horizon = 0 self.objects = 0 - self.end = None + self.end = None def show(self, model): if not self.args.quiet: @@ -24,9 +25,12 @@ def ground(self, kind): if self.args.scratch and count > 1: self.control = Control() - for source in self.args.file: self.control.load(source) - for i in range(0, self.objects): parts.append(("object", [Number(i + 1, count)])) - for i in range(0, self.horizon): parts.append(("horizon", [Number(i + 1, count)])) + for source in self.args.file: + self.control.load(source) + for i in range(0, self.objects): + parts.append(("object", [Number(i + 1, count)])) + for i in range(0, self.horizon): + parts.append(("horizon", [Number(i + 1, count)])) if self.args.scratch or count == 1: for option in self.args.option: @@ -41,14 +45,14 @@ def ground(self, kind): parts.append(("horizon", [Number(self.horizon), Number(count)])) if self.args.verbose: - print("") - print("Objects: {}".format(Number(self.objects))) - print("Horizon: {}".format(Number(self.horizon))) + print("") + print("Objects: {}".format(Number(self.objects))) + print("Horizon: {}".format(Number(self.horizon))) self.control.ground(parts) if self.args.verbose: - print("Solving: {}".format(count)) + print("Solving: {}".format(count)) def run(self): for source in self.args.file: @@ -63,9 +67,17 @@ def run(self): while True: ret = self.control.solve(on_model=self.show) if self.args.stats: - args = {"sort_keys": True, "indent": 0, "separators": (',', ': ')} + args = {"sort_keys": True, "indent": 0, "separators": (",", ": ")} stats = {} - for x in ["step", "enumerated", "time_cpu", "time_solve", "time_sat", "time_unsat", "time_total"]: + for x in [ + "step", + "enumerated", + "time_cpu", + "time_solve", + "time_sat", + "time_unsat", + "time_total", + ]: stats[x] = self.control.statistics[x] for x in ["lp", "ctx", "solvers"]: for y in self.control.statistics[x]: @@ -75,14 +87,42 @@ def run(self): break self.ground(False) -parser = argparse.ArgumentParser(description="Gradually expand logic programs.", epilog="""Example: main.py -x -q -s -v -m 42 -o solve.models 0 encoding.lp instance.lp""") -parser.add_argument("-x", "--scratch", action='store_true', help="start each step from scratch (single-shot solving)") -parser.add_argument("-q", "--quiet", action='store_true', help="do not print models") -parser.add_argument("-s", "--stats", action='store_true', help="print solver statistics") -parser.add_argument("-v", "--verbose", action='store_true', help="print progress information") -parser.add_argument("-m", "--maxobj", type=int, metavar="NUM", default=None, help="maximum number of introduced objects") -parser.add_argument("-o", "--option", nargs=2, metavar=("OPT", "VAL"), action="append", default=[], help="set sover options") +parser = argparse.ArgumentParser( + description="Gradually expand logic programs.", + epilog="""Example: main.py -x -q -s -v -m 42 -o solve.models 0 encoding.lp instance.lp""", +) + +parser.add_argument( + "-x", + "--scratch", + action="store_true", + help="start each step from scratch (single-shot solving)", +) +parser.add_argument("-q", "--quiet", action="store_true", help="do not print models") +parser.add_argument( + "-s", "--stats", action="store_true", help="print solver statistics" +) +parser.add_argument( + "-v", "--verbose", action="store_true", help="print progress information" +) +parser.add_argument( + "-m", + "--maxobj", + type=int, + metavar="NUM", + default=None, + help="maximum number of introduced objects", +) +parser.add_argument( + "-o", + "--option", + nargs=2, + metavar=("OPT", "VAL"), + action="append", + default=[], + help="set sover options", +) parser.add_argument("file", nargs="*", default=[], help="gringo source files") args = parser.parse_args() @@ -90,4 +130,3 @@ def run(self): parser.error("maximum number of objects must be positive") App(args).run() - diff --git a/examples/clingo/extending/README.md b/examples/clingo/extending/README.md index 4056fea03..edcf453c9 100644 --- a/examples/clingo/extending/README.md +++ b/examples/clingo/extending/README.md @@ -5,7 +5,7 @@ Examples Embedding python code to implement a function evaluated during grounding: - $ clingo embedded.lp example.lp + $ clingo embedded.lp example.lp clingo version 5.5.0 Reading from embedded.lp ... Solving... diff --git a/examples/clingo/extending/app.py b/examples/clingo/extending/app.py index cad7826cd..1a176b731 100644 --- a/examples/clingo/extending/app.py +++ b/examples/clingo/extending/app.py @@ -1,36 +1,37 @@ -''' +""" Example showing basic usage of clingo's application class. -''' +""" import sys -from typing import Sequence, Iterator +from typing import Iterator, Sequence -from clingo.symbol import Number, Symbol +from clingo.application import Application, clingo_main from clingo.control import Control -from clingo.application import clingo_main, Application +from clingo.symbol import Number, Symbol class ExampleApp(Application): - ''' + """ Example application class. - ''' + """ + program_name: str = "example" version: str = "1.0" @staticmethod def divisors(sym: Symbol) -> Iterator[Symbol]: - ''' + """ Return all divisors of the given number. - ''' + """ num = sym.number for i in range(1, num + 1): if num % i == 0: yield Number(i) def main(self, ctl: Control, files: Sequence[str]): - ''' + """ Main function of the application. - ''' + """ for path in files: ctl.load(path) if not files: diff --git a/examples/clingo/extending/module.py b/examples/clingo/extending/module.py index 1f3ec4aa8..28dd123a4 100644 --- a/examples/clingo/extending/module.py +++ b/examples/clingo/extending/module.py @@ -1,6 +1,6 @@ -''' +""" Example showing basic clingo usage of the clingo module. -''' +""" from typing import Iterator @@ -9,24 +9,24 @@ class ExampleApp: - ''' + """ Example application class. - ''' + """ @staticmethod def divisors(sym: Symbol) -> Iterator[Symbol]: - ''' + """ Return all divisors of the given number. - ''' + """ num = sym.number for i in range(1, num + 1): if num % i == 0: yield Number(i) def run(self): - ''' + """ Runs the example. - ''' + """ ctl = Control() ctl.load("example.lp") ctl.ground([("base", [])], context=self) diff --git a/examples/clingo/external/external-lua.lp b/examples/clingo/external/external-lua.lp index 2c73dc731..dc1233c29 100644 --- a/examples/clingo/external/external-lua.lp +++ b/examples/clingo/external/external-lua.lp @@ -11,4 +11,3 @@ function main(prg) prg:solve() end #end. - diff --git a/examples/clingo/external/external-py.lp b/examples/clingo/external/external-py.lp index 69ebad71e..1e3a9caf5 100644 --- a/examples/clingo/external/external-py.lp +++ b/examples/clingo/external/external-py.lp @@ -13,4 +13,3 @@ def main(prg): prg.ground([("succ", [Number(3)])]) prg.solve() #end. - diff --git a/examples/clingo/gac/README.md b/examples/clingo/gac/README.md index 6c5cfbd27..1f5fc4e55 100644 --- a/examples/clingo/gac/README.md +++ b/examples/clingo/gac/README.md @@ -10,7 +10,7 @@ Examples Answer: 1 a(2) SATISFIABLE - + Models : 1+ Calls : 1 Time : 0.001s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s) diff --git a/examples/clingo/gac/app.py b/examples/clingo/gac/app.py index 48b8df6cd..9f6c52f2e 100644 --- a/examples/clingo/gac/app.py +++ b/examples/clingo/gac/app.py @@ -3,22 +3,22 @@ """ import sys -from typing import Sequence, Tuple, List, cast +from typing import List, Sequence, Tuple, cast from clingo import ast -from clingo.solving import SolveResult -from clingo.ast import ProgramBuilder +from clingo.application import Application, clingo_main +from clingo.ast import AST, ASTType, ProgramBuilder, parse_files +from clingo.backend import Backend from clingo.control import Control -from clingo.application import clingo_main, Application from clingo.propagator import PropagateControl, PropagateInit, Propagator -from clingo.backend import Backend -from clingo.ast import parse_files, AST, ASTType +from clingo.solving import SolveResult class Transformer: """ Transformer for the guess and check solver. """ + _builder: ProgramBuilder _state: str _check: List[AST] @@ -51,6 +51,7 @@ class Checker: """ Class wrapping a solver to perform the second level check. """ + _ctl: Control _map: List[Tuple[int, int]] @@ -108,6 +109,7 @@ class CheckPropagator(Propagator): Simple propagator verifying that a check program holds on total assignments. """ + _check: List[ast.AST] _checkers: List[Checker] @@ -147,7 +149,6 @@ def init(self, init: PropagateInit): checker.ground(self._check) - def check(self, control: PropagateControl): """ Check total assignments. @@ -157,7 +158,7 @@ def check(self, control: PropagateControl): if not checker.check(control): conflict = [] - for level in range(1, assignment.decision_level+1): + for level in range(1, assignment.decision_level + 1): conflict.append(-assignment.decision(level)) control.add_clause(conflict) @@ -167,6 +168,7 @@ class GACApp(Application): """ Application class implementing a custom solver. """ + program_name: str version: str diff --git a/examples/clingo/heuristic/encoding-lua.lp b/examples/clingo/heuristic/encoding-lua.lp index 4f58364d9..c188ea668 100644 --- a/examples/clingo/heuristic/encoding-lua.lp +++ b/examples/clingo/heuristic/encoding-lua.lp @@ -99,4 +99,3 @@ end 1 { assign(U,C) : color(C) } 1 :- vertex(U). :- edge(U,V), assign(U,C), assign(V,C). - diff --git a/examples/clingo/heuristic/encoding-py.lp b/examples/clingo/heuristic/encoding-py.lp index 8e786cf67..34e52bd99 100644 --- a/examples/clingo/heuristic/encoding-py.lp +++ b/examples/clingo/heuristic/encoding-py.lp @@ -65,4 +65,3 @@ def main(prg): 1 { assign(U,C) : color(C) } 1 :- vertex(U). :- edge(U,V), assign(U,C), assign(V,C). - diff --git a/examples/clingo/hit/clingo-hit.py b/examples/clingo/hit/clingo-hit.py index 02fdde849..5caf7228a 100644 --- a/examples/clingo/hit/clingo-hit.py +++ b/examples/clingo/hit/clingo-hit.py @@ -4,30 +4,31 @@ """ import sys +from collections.abc import Callable, KeysView, Sequence from typing import cast -from collections.abc import Callable, Sequence, KeysView -from clingo.application import clingo_main, Application, ApplicationOptions, Flag +from clingo.application import Application, ApplicationOptions, Flag, clingo_main from clingo.backend import Observer +from clingo.configuration import Configuration from clingo.control import Control from clingo.solving import Model -from clingo.configuration import Configuration WeightedLit = tuple[int, int] Minimize = dict[int, list[WeightedLit]] + class HSSolver: - ''' + """ An incremental hitting set solver. - ''' + """ _map: dict[int, int] _ctl: Control def __init__(self, mini: Minimize): - ''' + """ Initialize the solver. - ''' + """ self._ctl = Control(["0", "-t4"]) self._map = {} with self._ctl.backend() as bck: @@ -42,52 +43,55 @@ def __init__(self, mini: Minimize): bck.add_minimize(prio, hs_wlits) def solve(self) -> list[int]: - ''' + """ Compute a hitting set. - ''' + """ hs: list[int] = [] + def extract(model: Model): hs.clear() for lit, hs_lit in self._map.items(): if model.is_true(hs_lit): hs.append(lit) + self._ctl.solve(on_model=extract) return hs def lits(self) -> KeysView[int]: - ''' + """ Get the literals subject to minimization. - ''' + """ return self._map.keys() def add(self, core: Sequence[int]) -> None: - ''' + """ Add a core. - ''' + """ with self._ctl.backend() as bck: bck.add_rule([], [-self._map[lit] for lit in core]) class Obs(Observer): - ''' + """ Observer to extract a minimize constraint. - ''' + """ + _mini: Minimize def __init__(self, mini: Minimize): self._mini = mini def minimize(self, priority: int, literals: Sequence[WeightedLit]) -> None: - ''' + """ Gather minimize constraints in the program. - ''' + """ self._mini.setdefault(priority, []).extend(literals) class OptApt(Application): - ''' + """ Application class implementing hitting set based minimization. - ''' + """ _trace: Flag @@ -100,23 +104,25 @@ def register_options(self, options: ApplicationOptions) -> None: """ Register clingo-hit options. """ - options.add_flag("Clingo.Hit", "--trace", "trace minimization progress", self._trace) + options.add_flag( + "Clingo.Hit", "--trace", "trace minimization progress", self._trace + ) def main(self, control: Control, files: Sequence[str]) -> None: - ''' + """ Runs the minimization algorithm. - ''' + """ cast(Configuration, control.configuration.solve).opt_mode = "ignore" for file_ in files: control.load(file_) if not files: - control.load('-') + control.load("-") mini: Minimize = {} obs = Obs(mini) control.register_observer(obs, False) - control.ground([('base', [])]) + control.ground([("base", [])]) cores: list[list[int]] = [] hss = HSSolver(mini) @@ -129,7 +135,10 @@ def main(self, control: Control, files: Sequence[str]) -> None: print("cores:", cores) print("hitting set:", hs) print("assumptions:", assume) - res = control.solve(assumptions=assume, on_core=cast(Callable[[Sequence[int]], None], cores.append)) + res = control.solve( + assumptions=assume, + on_core=cast(Callable[[Sequence[int]], None], cores.append), + ) if res.satisfiable: break if not cores[-1]: diff --git a/examples/clingo/iclingo/incmode-lua.lp b/examples/clingo/iclingo/incmode-lua.lp index 451c4c125..67051d8a9 100644 --- a/examples/clingo/iclingo/incmode-lua.lp +++ b/examples/clingo/iclingo/incmode-lua.lp @@ -1,10 +1,10 @@ -#script (lua) +#script (lua) function get(val, default) - if val ~= nil then - return val - else - return default + if val ~= nil then + return val + else + return default end end @@ -17,7 +17,7 @@ function main(prg) while (imax == nil or step < imax.number) and (step == 0 or step < imin.number or ( (istop.string == "SAT" and not ret.satisfiable) or - (istop.string == "UNSAT" and not ret.unsatisfiable) or + (istop.string == "UNSAT" and not ret.unsatisfiable) or (istop.string == "UNKNOWN" and not ret.unknown))) do local parts = {} table.insert(parts, {"check", {step}}) diff --git a/examples/clingo/iclingo/incmode-py.lp b/examples/clingo/iclingo/incmode-py.lp index 68e7bab9d..e66780c98 100644 --- a/examples/clingo/iclingo/incmode-py.lp +++ b/examples/clingo/iclingo/incmode-py.lp @@ -1,4 +1,4 @@ -#script (python) +#script (python) from clingo import Number, String, Function @@ -14,7 +14,7 @@ def main(prg): while ((imax is None or step < imax.number) and (step == 0 or step < imin.number or ( (istop.string == "SAT" and not ret.satisfiable) or - (istop.string == "UNSAT" and not ret.unsatisfiable) or + (istop.string == "UNSAT" and not ret.unsatisfiable) or (istop.string == "UNKNOWN" and not ret.unknown)))): parts = [] parts.append(("check", [Number(step)])) diff --git a/examples/clingo/incqueens/README.md b/examples/clingo/incqueens/README.md index ff3883367..d7b32c765 100644 --- a/examples/clingo/incqueens/README.md +++ b/examples/clingo/incqueens/README.md @@ -7,4 +7,3 @@ board sizes, which can be given as a list of intervals on the command line. clingo incqueens.lp incqueens-py.lp -c calls="list((1,1),(3,5),(8,9))" clingo incqueens.lp incqueens-lua.lp -c calls="list((1,1),(3,5),(8,9))" - diff --git a/examples/clingo/multishot/README.md b/examples/clingo/multishot/README.md index aaadfa9d9..dd09546d1 100644 --- a/examples/clingo/multishot/README.md +++ b/examples/clingo/multishot/README.md @@ -26,7 +26,7 @@ The branch-and-bound example: Solving... Optimum found UNSATISFIABLE - + Models : 5 Calls : 6 Time : 0.015s (Solving: 0.01s 1st Model: 0.01s Unsat: 0.00s) @@ -45,7 +45,7 @@ The incremental solving example: move(1,c,8) move(4,c,9) move(3,a,10) move(4,a,11) move(2,c,12) move(4,b,13) move(3,c,14) move(4,c,15) SATISFIABLE - + Models : 1+ Calls : 16 Time : 0.020s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s) diff --git a/examples/clingo/multishot/inc.py b/examples/clingo/multishot/inc.py index 757c31243..fbe94b628 100644 --- a/examples/clingo/multishot/inc.py +++ b/examples/clingo/multishot/inc.py @@ -1,20 +1,21 @@ -''' +""" Example implementing an iclingo-like application. -''' +""" import sys -from typing import cast, Any, Callable, Optional, Sequence +from typing import Any, Callable, Optional, Sequence, cast -from clingo.application import clingo_main, Application, ApplicationOptions +from clingo.application import Application, ApplicationOptions, clingo_main from clingo.control import Control from clingo.solving import SolveResult from clingo.symbol import Function, Number class IncConfig: - ''' + """ Configuration object for incremental solving. - ''' + """ + imin: int imax: Optional[int] istop: str @@ -25,17 +26,17 @@ def __init__(self): self.istop = "SAT" -def parse_int(conf: Any, - attr: str, - min_value: Optional[int] = None, - optional: bool = False) -> Callable[[str], bool]: - ''' +def parse_int( + conf: Any, attr: str, min_value: Optional[int] = None, optional: bool = False +) -> Callable[[str], bool]: + """ Returns a parser for integers. The parser stores its result in the `attr` attribute (given as string) of the `conf` object. The parser can be configured to only accept integers having a minimum value and also to treat value `"none"` as `None`. - ''' + """ + def parse(sval: str) -> bool: if optional and sval == "none": value = None @@ -45,25 +46,29 @@ def parse(sval: str) -> bool: raise RuntimeError("value too small") setattr(conf, attr, value) return True + return parse def parse_stop(conf: Any, attr: str) -> Callable[[str], bool]: - ''' + """ Returns a parser for `istop` values. - ''' + """ + def parse(sval: str) -> bool: if sval not in ("SAT", "UNSAT", "UNKNOWN"): raise RuntimeError("invalid value") setattr(conf, attr, sval) return True + return parse class IncApp(Application): - ''' + """ The example application implemeting incremental solving. - ''' + """ + program_name: str = "inc-example" version: str = "1.0" _conf: IncConfig @@ -72,32 +77,38 @@ def __init__(self): self._conf = IncConfig() def register_options(self, options: ApplicationOptions): - ''' + """ Register program options. - ''' + """ group = "Inc-Example Options" options.add( - group, "imin", + group, + "imin", "Minimum number of steps [{}]".format(self._conf.imin), parse_int(self._conf, "imin", min_value=0), - argument="") + argument="", + ) options.add( - group, "imax", + group, + "imax", "Maximum number of steps [{}]".format(self._conf.imax), parse_int(self._conf, "imax", min_value=0, optional=True), - argument="") + argument="", + ) options.add( - group, "istop", + group, + "istop", "Stop criterion [{}]".format(self._conf.istop), - parse_stop(self._conf, "istop")) + parse_stop(self._conf, "istop"), + ) def main(self, ctl: Control, files: Sequence[str]): - ''' + """ The main function implementing incremental solving. - ''' + """ if not files: files = ["-"] for file_ in files: @@ -108,11 +119,15 @@ def main(self, ctl: Control, files: Sequence[str]): step = 0 ret: Optional[SolveResult] = None - while ((conf.imax is None or step < conf.imax) and - (ret is None or step < conf.imin or ( - (conf.istop == "SAT" and not ret.satisfiable) or - (conf.istop == "UNSAT" and not ret.unsatisfiable) or - (conf.istop == "UNKNOWN" and not ret.unknown)))): + while (conf.imax is None or step < conf.imax) and ( + ret is None + or step < conf.imin + or ( + (conf.istop == "SAT" and not ret.satisfiable) + or (conf.istop == "UNSAT" and not ret.unsatisfiable) + or (conf.istop == "UNKNOWN" and not ret.unknown) + ) + ): parts = [] parts.append(("check", [Number(step)])) if step > 0: diff --git a/examples/clingo/multishot/opt.py b/examples/clingo/multishot/opt.py index 2fe9b63c9..ba91ec565 100644 --- a/examples/clingo/multishot/opt.py +++ b/examples/clingo/multishot/opt.py @@ -1,20 +1,21 @@ -''' +""" Exmaple to show branch and bound based optimization using multi-shot solving. -''' +""" import sys from typing import Optional, Sequence, cast -from clingo.symbol import Number, SymbolType -from clingo.solving import Model, SolveResult +from clingo.application import Application, clingo_main from clingo.control import Control -from clingo.application import clingo_main, Application +from clingo.solving import Model, SolveResult +from clingo.symbol import Number, SymbolType class OptApp(Application): - ''' + """ Example application. - ''' + """ + program_name: str = "opt-example" version: str = "1.0" _bound: Optional[int] @@ -25,20 +26,21 @@ def __init__(self): def _on_model(self, model: Model): self._bound = 0 for atom in model.symbols(atoms=True): - if (atom.match("_minimize", 2) and - atom.arguments[0].type is SymbolType.Number): + if ( + atom.match("_minimize", 2) + and atom.arguments[0].type is SymbolType.Number + ): self._bound += atom.arguments[0].number def main(self, ctl: Control, files: Sequence[str]): - ''' + """ Main function implementing branch and bound optimization. - ''' + """ if not files: files = ["-"] for file_ in files: ctl.load(file_) - ctl.add("bound", ["b"], - ":- #sum { V,I: _minimize(V,I) } >= b.") + ctl.add("bound", ["b"], ":- #sum { V,I: _minimize(V,I) } >= b.") ctl.ground([("base", [])]) while cast(SolveResult, ctl.solve(on_model=self._on_model)).satisfiable: diff --git a/examples/clingo/onmodel/onmodel-lua.lp b/examples/clingo/onmodel/onmodel-lua.lp index 7f26e0c0b..88c04f7c8 100644 --- a/examples/clingo/onmodel/onmodel-lua.lp +++ b/examples/clingo/onmodel/onmodel-lua.lp @@ -1,11 +1,11 @@ #script (lua) -function tostringTable(t) +function tostringTable(t) ret = "" comma = False for _, elem in pairs(t) do if comma then ret = ret .. ", " - else comma = true + else comma = true end ret = ret .. tostring(elem) end diff --git a/examples/clingo/opt-enum/opt.py b/examples/clingo/opt-enum/opt.py index 48bb8b106..7986e2906 100644 --- a/examples/clingo/opt-enum/opt.py +++ b/examples/clingo/opt-enum/opt.py @@ -6,37 +6,41 @@ solutions, after all optimal solutions have been enumerated, are enumerated. This process is repeated until the program becomes unsatisfiable. """ + import sys -from typing import cast, Dict, List, Optional, Sequence, Tuple +from typing import Dict, List, Optional, Sequence, Tuple, cast -from clingo.application import clingo_main, Application, ApplicationOptions, Flag +from clingo.application import Application, ApplicationOptions, Flag, clingo_main from clingo.backend import Backend, Observer from clingo.configuration import Configuration from clingo.control import Control -from clingo.propagator import Propagator, Assignment, PropagateControl -from clingo.solving import SolveResult, Model +from clingo.propagator import Assignment, PropagateControl, Propagator +from clingo.solving import Model, SolveResult from clingo.statistics import StatisticsMap class MinObs(Observer): - ''' + """ Observer to extract ground minimize constraint. - ''' + """ + literals: Dict[int, List[Tuple[int, int]]] def __init__(self): self.literals = {} - def minimize(self, priority: int, literals: Sequence[Tuple[int,int]]): - ''' + def minimize(self, priority: int, literals: Sequence[Tuple[int, int]]): + """ Intercept minimize constraint and add it to member `literals`. - ''' + """ self.literals.setdefault(priority, []).extend(literals) + class RestoreHeu(Propagator): - ''' + """ Heuristic to restore solutions when resuming optimal model enumeration. - ''' + """ + costs: Dict[Tuple[int], Sequence[int]] models: Dict[int, Sequence[int]] restore: Optional[Sequence[int]] @@ -47,10 +51,10 @@ def __init__(self): self.restore = None def set_restore(self, bound: Tuple[int]): - ''' + """ Set the best previously found solution with a cost worse than bound to restore. - ''' + """ min_costs = bound for costs, model in self.costs.items(): if bound < costs < min_costs: @@ -58,24 +62,24 @@ def set_restore(self, bound: Tuple[int]): self.restore = model def on_model(self, model: Model): - ''' + """ If a model has been found store the corresponding bound/solution. - ''' + """ idx = cast(Tuple[int], tuple(model.cost)) self.costs[idx] = self.models[model.thread_id] def check(self, control: PropagateControl): - ''' + """ Store the last solution found by a thread. - ''' + """ self.models[control.thread_id] = list(control.assignment.trail) self.restore = None def decide(self, thread_id: int, assignment: Assignment, fallback: int) -> int: - ''' + """ Either restores the last solution or falls back to the solvers heuristic. - ''' + """ if self.restore: for lit in self.restore: if assignment.is_free(lit): @@ -84,9 +88,10 @@ def decide(self, thread_id: int, assignment: Assignment, fallback: int) -> int: class OptApt(Application): - ''' + """ Application class implementing optimal model enumeration. - ''' + """ + _restore: Flag _aux_level: Dict[Tuple[int, int], int] _heu: Optional[RestoreHeu] @@ -101,22 +106,31 @@ def __init__(self): self._heu = None def register_options(self, options: ApplicationOptions): - ''' + """ Register enumeration specific heuristics. - ''' - options.add_flag("Enumerate", "restore", + """ + options.add_flag( + "Enumerate", + "restore", "heuristically restore last solution when resuming optimization", - self._restore) - - def _add_upper_bound(self, backend: Backend, wlits: Sequence[Tuple[int, int]], bound: int, level: Optional[int]): - ''' + self._restore, + ) + + def _add_upper_bound( + self, + backend: Backend, + wlits: Sequence[Tuple[int, int]], + bound: int, + level: Optional[int], + ): + """ Adds the constraint `a <> { wlits } < bound` and returns literal `a`. If level is None, then an integrity constraint is added and no auxiliary literal is introduced. This function reuses literals introduced in earlier iterations. - ''' + """ hd = [] if level is not None: if (level, bound) in self._aux_level: @@ -137,14 +151,19 @@ def _add_upper_bound(self, backend: Backend, wlits: Sequence[Tuple[int, int]], b backend.add_weight_rule(hd, lower, wlits_lower) return hd[0] if hd else None - def _set_upper_bound(self, backend: Backend, minimize: Sequence[Sequence[Tuple[int, int]]], bound: Sequence[int]): - ''' + def _set_upper_bound( + self, + backend: Backend, + minimize: Sequence[Sequence[Tuple[int, int]]], + bound: Sequence[int], + ): + """ Adds constraints discarding solutions lexicographically smaller or equal than the bound. The weighted literals in the minimize variable directly correspond to how the solver represents minimize constraints. - ''' + """ assert minimize and len(minimize) == len(bound) if len(minimize) == 1: self._add_upper_bound(backend, minimize[0], bound[0], None) @@ -167,12 +186,12 @@ def _set_upper_bound(self, backend: Backend, minimize: Sequence[Sequence[Tuple[i prefix[-1] = self._add_upper_bound(backend, wlits, value, i) def _on_model(self, model: Model) -> bool: - ''' + """ Intercept models. This function counts optimal and intermediate models as well as passes model to the restore heuristic. - ''' + """ if self._heu: self._heu.on_model(model) if model.optimality_proven: @@ -182,18 +201,23 @@ def _on_model(self, model: Model) -> bool: return True def _on_statistics(self, step: StatisticsMap, accu: StatisticsMap): - ''' + """ Sets optimization specific statistics. - ''' - #pylint: disable=unused-argument - accu.update({'Enumerate': { - 'Enumerated': self._proven, - 'Intermediate': self._intermediate}}) + """ + # pylint: disable=unused-argument + accu.update( + { + "Enumerate": { + "Enumerated": self._proven, + "Intermediate": self._intermediate, + } + } + ) def _optimize(self, control: Control): - ''' + """ Run optimal solution enumeration algorithm. - ''' + """ obs = MinObs() control.register_observer(obs) @@ -201,48 +225,63 @@ def _optimize(self, control: Control): self._heu = RestoreHeu() control.register_propagator(self._heu) - control.ground([('base', [])]) - res = cast(SolveResult, control.solve(on_model=self._on_model, on_statistics=self._on_statistics)) + control.ground([("base", [])]) + res = cast( + SolveResult, + control.solve(on_model=self._on_model, on_statistics=self._on_statistics), + ) solve_config = cast(Configuration, control.configuration.solve) num_models = int(cast(str, solve_config.models)) - minimize = [ x[1] for x in sorted(obs.literals.items(), key=lambda x: -x[0]) ] + minimize = [x[1] for x in sorted(obs.literals.items(), key=lambda x: -x[0])] - while (res.satisfiable and not res.interrupted and - minimize and 'costs' in control.statistics['summary']): - summary = control.statistics['summary'] + while ( + res.satisfiable + and not res.interrupted + and minimize + and "costs" in control.statistics["summary"] + ): + summary = control.statistics["summary"] if num_models > 0: - num_models -= int(summary['models']['optimal']) + num_models -= int(summary["models"]["optimal"]) if num_models <= 0: break solve_config.models = num_models - costs = cast(Tuple[int], tuple(int(x) for x in control.statistics['summary']['costs'])) + costs = cast( + Tuple[int], + tuple(int(x) for x in control.statistics["summary"]["costs"]), + ) with control.backend() as backend: self._set_upper_bound(backend, minimize, costs) if self._heu is not None: self._heu.set_restore(costs) - res = cast(SolveResult, control.solve(on_model=self._on_model, on_statistics=self._on_statistics)) + res = cast( + SolveResult, + control.solve( + on_model=self._on_model, on_statistics=self._on_statistics + ), + ) def main(self, control: Control, files: Sequence[str]): - ''' + """ Runs the main ground/solve algorithm. - ''' + """ for file_ in files: control.load(file_) if not files: - control.load('-') + control.load("-") solve_config = cast(Configuration, control.configuration.solve) - if solve_config.opt_mode == 'optN': + if solve_config.opt_mode == "optN": self._optimize(control) else: - control.ground([('base', [])]) + control.ground([("base", [])]) control.solve() diff --git a/examples/clingo/planning/convert.lp b/examples/clingo/planning/convert.lp index edd658baa..0cbca84b5 100644 --- a/examples/clingo/planning/convert.lp +++ b/examples/clingo/planning/convert.lp @@ -16,7 +16,7 @@ complement(F,lit(F,1),lit(F,-1)) :- fluent(F). { _holds_initially(F) } :- complement(F,L,M), not _initially(L;M). _holds_initially(F) :- _initially(L), complement(F,L,M). -holds_oneof(N,B) :- +holds_oneof(N,B) :- _initially_oneof(N,_,B); not _holds_initially(F) : _initially_oneof(N,M,B), complement(F,L,M); _holds_initially(F) : _initially_oneof(N,L,B), complement(F,L,M). @@ -25,4 +25,3 @@ holds_oneof(N,B) :- % just bizarre! :- not _holds_initially(F), _initially_oneof(N,M,B), not holds_oneof(N,B), complement(F,L,M). :- _holds_initially(F), _initially_oneof(N,L,B), not holds_oneof(N,B), complement(F,L,M). - diff --git a/examples/clingo/planning/encoding.lp b/examples/clingo/planning/encoding.lp index 3855a1f62..84280a327 100644 --- a/examples/clingo/planning/encoding.lp +++ b/examples/clingo/planning/encoding.lp @@ -27,7 +27,7 @@ holds(L,t) :- occurs(A,t), effect(A,L,N), holds(C,t-1) : condition(A,C,N). holds(L,t) :- holds(L,t-1), complement(L,M), not holds(M,t). :- contradict(F), complement(F,L,M), holds((L;M),t). -caused(L,t) :- occurs(A,t), effect(A,L,N), +caused(L,t) :- occurs(A,t), effect(A,L,N), not holds(F',t-1) : condition(A,M',N), complement(F',L',M'); holds(F',t-1) : condition(A,L',N), complement(F',L',M'). holds(F,t) :- caused(L,t), complement(F,L,M). @@ -73,9 +73,9 @@ pos_executable(T,t) :- occurs(A,T), alt_holds(C,T-1,t) : executable(A,C), C != pos_goal_or(N,t) :- goal_or(N,L), alt_holds(L,t,t), vol(t). pos_goal_or(N,t) :- goal_or(N,L), goal(L), vol(t). -bottom(t) :- pos_goal_or(N,t) : goal_or(N,_); +bottom(t) :- pos_goal_or(N,t) : goal_or(N,_); alt_holds(L,t,t) : goal(L); - pos_executable(R,t) : R = 1..t; + pos_executable(R,t) : R = 1..t; not_contradict(F,S,t) : contradict(F), S = 1..t; vol(t). diff --git a/examples/clingo/planning/planning-lua.lp b/examples/clingo/planning/planning-lua.lp index f954f283b..22685c87f 100644 --- a/examples/clingo/planning/planning-lua.lp +++ b/examples/clingo/planning/planning-lua.lp @@ -1,4 +1,4 @@ -#script (lua) +#script (lua) function main(prg) local step = 0 local check = false @@ -27,7 +27,7 @@ function main(prg) if ret.satisfiable then break end - else + else break end end diff --git a/examples/clingo/pydoc/pydoc-lib.py b/examples/clingo/pydoc/pydoc-lib.py index e2cef07ca..757b4c3af 100755 --- a/examples/clingo/pydoc/pydoc-lib.py +++ b/examples/clingo/pydoc/pydoc-lib.py @@ -1,13 +1,27 @@ #!/usr/bin/env python -import clingo, clingo.ast, subprocess, pydoc +import pydoc +import subprocess + +import clingo +import clingo.ast print("Generating documentation for clingo version {}.".format(clingo.__version__)) for m in [clingo, clingo.ast]: pydoc.writedoc(m) - subprocess.call(["sed", "-i", - "-e", r"s/\/88ff99/g", - "-e", r"s/\/22bb33/g", - "-e", r's/index<\/a>.*<\/font>/\«Potassco<\/a><\/font>/', - "-e", r's/[^<]*object<\/a>/object/g', - "-e", r's/{0}.html#/#/g', - "{0}.html".format(m.__name__)]) + subprocess.call( + [ + "sed", + "-i", + "-e", + r"s/\/88ff99/g", + "-e", + r"s/\/22bb33/g", + "-e", + r's/index<\/a>.*<\/font>/\«Potassco<\/a><\/font>/', + "-e", + r's/[^<]*object<\/a>/object/g', + "-e", + r"s/{0}.html#/#/g", + "{0}.html".format(m.__name__), + ] + ) diff --git a/examples/clingo/pydoc/pydoc.lp b/examples/clingo/pydoc/pydoc.lp index bf9972d1a..4bc3b8e47 100644 --- a/examples/clingo/pydoc/pydoc.lp +++ b/examples/clingo/pydoc/pydoc.lp @@ -5,8 +5,8 @@ import clingo, clingo.ast, pydoc, subprocess print("Generating documentation for clingo version {}.".format(clingo.__version__)) for m in [clingo, clingo.ast]: pydoc.writedoc(m) - subprocess.call(["sed", "-i", - "-e", r"s/\/88ff99/g", + subprocess.call(["sed", "-i", + "-e", r"s/\/88ff99/g", "-e", r"s/\/22bb33/g", "-e", r's/index<\/a>.*<\/font>/\«Potassco<\/a><\/font>/', "-e", r's/[^<]*object<\/a>/object/g', diff --git a/examples/clingo/robots/README.md b/examples/clingo/robots/README.md index b14806f42..5d1653ef5 100644 --- a/examples/clingo/robots/README.md +++ b/examples/clingo/robots/README.md @@ -10,4 +10,3 @@ robots. If you run out of ideas, you can click on solve! to get a little help from ASP. To start, call python visualize.py - diff --git a/examples/clingo/robots/board.lp b/examples/clingo/robots/board.lp index af51495c1..ba2c9cf96 100644 --- a/examples/clingo/robots/board.lp +++ b/examples/clingo/robots/board.lp @@ -16,7 +16,7 @@ barrier( 7, 9, 1,0). barrier( 7, 4,0, 1). barrier( 7,13,0, 1). barrier(10, 9,-1,0). barrier(16, 4,0, 1). barrier(15,13,0, 1). barrier( 4,10, 1,0). barrier( 1, 6,0, 1). barrier(10,14,0, 1). barrier( 2,11, 1,0). barrier( 4, 7,0, 1). barrier( 3,15,0, 1). -barrier( 8,11, 1,0). barrier( 8, 7,0, 1). +barrier( 8,11, 1,0). barrier( 8, 7,0, 1). available_target(red , moon , 5 , 2). available_target(red , sun , 15, 2). diff --git a/examples/clingo/robots/visualize.py b/examples/clingo/robots/visualize.py index ae5085529..deb34dae1 100755 --- a/examples/clingo/robots/visualize.py +++ b/examples/clingo/robots/visualize.py @@ -1,5 +1,6 @@ #!/usr/bin/env python -from clingo import SymbolType, Number, Function, Control +from clingo import Control, Function, Number, SymbolType + try: import Tkinter except ImportError: @@ -7,17 +8,18 @@ # {{{1 class Board + class Board: def __init__(self): - self.size = 1 - self.blocked = set() - self.barriers = set() - self.targets = set() - self.pos = dict() - self.robots = [{}] - self.moves = [] + self.size = 1 + self.blocked = set() + self.barriers = set() + self.targets = set() + self.pos = dict() + self.robots = [{}] + self.moves = [] self.current_target = None - self.solution = None + self.solution = None ctl = Control() ctl.load("board.lp") @@ -28,40 +30,50 @@ def __on_model(self, m): for atom in m.symbols(atoms=True): if atom.name == "barrier" and len(atom.arguments) == 4: x, y, dx, dy = [n.number for n in atom.arguments] - self.blocked.add((x - 1 , y - 1 , dx, dy)) - self.blocked.add((x - 1 + dx, y - 1 , -dx, dy)) - self.blocked.add((x - 1 , y - 1 + dy, dx, -dy)) + self.blocked.add((x - 1, y - 1, dx, dy)) + self.blocked.add((x - 1 + dx, y - 1, -dx, dy)) + self.blocked.add((x - 1, y - 1 + dy, dx, -dy)) self.blocked.add((x - 1 + dx, y - 1 + dy, -dx, -dy)) if dy == 0: - self.barriers.add(('west', x if dx == 1 else x - 1, y - 1)) + self.barriers.add(("west", x if dx == 1 else x - 1, y - 1)) else: - self.barriers.add(('north', x - 1, y if dy == 1 else y - 1)) + self.barriers.add(("north", x - 1, y if dy == 1 else y - 1)) elif atom.name == "dim" and len(atom.arguments) == 1: self.size = max(self.size, atom.arguments[0].number) elif atom.name == "available_target" and len(atom.arguments) == 4: - c, s, x, y = [(n.number if n.type == SymbolType.Number else str(n)) for n in atom.arguments] + c, s, x, y = [ + (n.number if n.type == SymbolType.Number else str(n)) + for n in atom.arguments + ] self.targets.add((c, s, x - 1, y - 1)) elif atom.name == "initial_pos" and len(atom.arguments) == 3: - c, x, y = [(n.number if n.type == SymbolType.Number else str(n)) for n in atom.arguments] + c, x, y = [ + (n.number if n.type == SymbolType.Number else str(n)) + for n in atom.arguments + ] self.pos[c] = (x - 1, y - 1) for d in range(0, self.size): - self.blocked.add((d , 0, 0, -1)) - self.blocked.add((d , self.size - 1, 0, 1)) - self.blocked.add((0 , d, -1, 0)) - self.blocked.add((self.size - 1, d, 1, 0)) + self.blocked.add((d, 0, 0, -1)) + self.blocked.add((d, self.size - 1, 0, 1)) + self.blocked.add((0, d, -1, 0)) + self.blocked.add((self.size - 1, d, 1, 0)) def move(self, robot, dx, dy): x, y = self.pos[robot] - while (not (x, y, dx, dy) in self.blocked and - not (x + dx, y + dy) in self.pos.values()): + while ( + not (x, y, dx, dy) in self.blocked + and not (x + dx, y + dy) in self.pos.values() + ): x += dx y += dy self.pos[robot] = (x, y) - if (self.solution is not None and - len(self.solution) > 0 and - self.solution[0][0] == robot and - self.solution[0][1] == dx and - self.solution[0][2] == dy): + if ( + self.solution is not None + and len(self.solution) > 0 + and self.solution[0][0] == robot + and self.solution[0][1] == dx + and self.solution[0][2] == dy + ): self.solution.pop(0) if len(self.solution) == 0: self.solution = None @@ -72,50 +84,60 @@ def won(self): r, _, x, y = self.current_target return self.pos[r] == (x, y) + # {{{1 class Solver # NOTE: it would be a nice gimmick to make the search interruptible + class Solver: def __init__(self, horizon=0): self.__horizon = horizon - self.__prg = Control(['-t4']) + self.__prg = Control(["-t4"]) self.__future = None self.__solution = None self.__assign = [] self.__prg.load("board.lp") self.__prg.load("robots.lp") - parts = [ ("base", []) - , ("check", [Number(0)]) - , ("state", [Number(0)]) - ] - for t in range(1, self.__horizon+1): - parts.extend([ ("trans", [Number(t)]) - , ("check", [Number(t)]) - , ("state", [Number(t)]) - ]) + parts = [("base", []), ("check", [Number(0)]), ("state", [Number(0)])] + for t in range(1, self.__horizon + 1): + parts.extend( + [("trans", [Number(t)]), ("check", [Number(t)]), ("state", [Number(t)])] + ) self.__prg.ground(parts) self.__prg.assign_external(Function("horizon", [Number(self.__horizon)]), True) def __next(self): - assert(self.__horizon < 30) + assert self.__horizon < 30 self.__prg.assign_external(Function("horizon", [Number(self.__horizon)]), False) self.__horizon += 1 - self.__prg.ground([ ("trans", [Number(self.__horizon)]) - , ("check", [Number(self.__horizon)]) - , ("state", [Number(self.__horizon)]) - ]) + self.__prg.ground( + [ + ("trans", [Number(self.__horizon)]), + ("check", [Number(self.__horizon)]), + ("state", [Number(self.__horizon)]), + ] + ) self.__prg.assign_external(Function("horizon", [Number(self.__horizon)]), True) def start(self, board): self.__assign = [] for robot, (x, y) in board.pos.items(): - self.__assign.append(Function("pos", [Function(robot), Number(x+1), Number(y+1), Number(0)])) - self.__assign.append(Function("target", - [ Function(board.current_target[0]) - , Number(board.current_target[2] + 1) - , Number(board.current_target[3] + 1) - ])) + self.__assign.append( + Function( + "pos", [Function(robot), Number(x + 1), Number(y + 1), Number(0)] + ) + ) + self.__assign.append( + Function( + "target", + [ + Function(board.current_target[0]), + Number(board.current_target[2] + 1), + Number(board.current_target[3] + 1), + ], + ) + ) for x in self.__assign: self.__prg.assign_external(x, True) self.__solution = None @@ -153,68 +175,81 @@ def __on_model(self, m): self.__solution = [] for atom in m.symbols(atoms=True): if atom.name == "move" and len(atom.arguments) == 4: - c, x, y, t = [(n.number if n.type == SymbolType.Number else str(n)) for n in atom.arguments] + c, x, y, t = [ + (n.number if n.type == SymbolType.Number else str(n)) + for n in atom.arguments + ] self.__solution.append((c, x, y, t)) self.__solution.sort(key=lambda x: x[3]) p = None i = 0 for x in self.__solution: - if p is not None and \ - p[0] == x[0] and \ - p[1] == x[1] and \ - p[2] == x[2]: + if p is not None and p[0] == x[0] and p[1] == x[1] and p[2] == x[2]: break p = x i += 1 del self.__solution[i:] + # {{{1 class Visualization + class Visualization: def __init__(self, master, board): - self.__margin = 20 - self.__tile_size = 40 - self.__canvas_width = None - self.__canvas_height = None - self.__robot_images = {} - self.__target_images = {} - self.__solution_images = [] + self.__margin = 20 + self.__tile_size = 40 + self.__canvas_width = None + self.__canvas_height = None + self.__robot_images = {} + self.__target_images = {} + self.__solution_images = [] self.__direction_images = [] - self.__entered = set() - self.__slots = {} - self.__highlights = {} - self.__targets = {} - self.__moves = {} - self.__moves_short = {} - self.__robots = {} - self.__barriers = {} - self.__tiles = [] - - self.__canvas_width = board.size * self.__tile_size + 2 * self.__margin + self.__entered = set() + self.__slots = {} + self.__highlights = {} + self.__targets = {} + self.__moves = {} + self.__moves_short = {} + self.__robots = {} + self.__barriers = {} + self.__tiles = [] + + self.__canvas_width = board.size * self.__tile_size + 2 * self.__margin self.__canvas_height = (1 + board.size) * self.__tile_size + 3 * self.__margin - self.__canvas = Tkinter.Canvas(master, width=self.__canvas_width, height=self.__canvas_height) + self.__canvas = Tkinter.Canvas( + master, width=self.__canvas_width, height=self.__canvas_height + ) self.__canvas.pack() - colors = ['green', 'red', 'blue', 'yellow'] - shapes = ['moon', 'sun', 'star', 'saturn'] - directions = [('north', 0, -1), ("east", 1, 0), ('south', 0, 1), ('west', -1, 0)] - for orientation in ['left', 'right']: - path = 'img/tile_{orientation}.gif'.format(orientation=orientation) + colors = ["green", "red", "blue", "yellow"] + shapes = ["moon", "sun", "star", "saturn"] + directions = [ + ("north", 0, -1), + ("east", 1, 0), + ("south", 0, 1), + ("west", -1, 0), + ] + for orientation in ["left", "right"]: + path = "img/tile_{orientation}.gif".format(orientation=orientation) self.__tiles.append(Tkinter.PhotoImage(file=path)) - for direction in ['north', 'west']: - path = 'img/wall_{direction}.gif'.format(direction=direction) + for direction in ["north", "west"]: + path = "img/wall_{direction}.gif".format(direction=direction) self.__barriers[direction] = (Tkinter.PhotoImage(file=path), -6, -6) for color in colors: - path = 'img/robot_{color}.gif'.format(color=color) + path = "img/robot_{color}.gif".format(color=color) self.__robots[color] = Tkinter.PhotoImage(file=path) for shape in shapes: path = "img/{shape}_{color}.gif".format(shape=shape, color=color) self.__targets[(color, shape)] = Tkinter.PhotoImage(file=path) - for (direction, dx, dy) in directions: - path = "img/arrow_{color}_{direction}.gif".format(color=color, direction=direction) + for direction, dx, dy in directions: + path = "img/arrow_{color}_{direction}.gif".format( + color=color, direction=direction + ) self.__moves[(color, dx, dy)] = Tkinter.PhotoImage(file=path) - path = "img/move_{color}_{direction}.gif".format(color=color, direction=direction) + path = "img/move_{color}_{direction}.gif".format( + color=color, direction=direction + ) self.__moves_short[(color, dx, dy)] = Tkinter.PhotoImage(file=path) for x in range(0, board.size): for y in range(0, board.size): @@ -222,49 +257,52 @@ def __init__(self, master, board): self.__margin + self.__tile_size * x, self.__margin + self.__tile_size * y, anchor=Tkinter.NW, - image=self.__tiles[(x + y) % len(self.__tiles)]) - for (t, m, x, y) in board.targets: + image=self.__tiles[(x + y) % len(self.__tiles)], + ) + for t, m, x, y in board.targets: self.__target_images[(x, y)] = self.__canvas.create_image( self.__margin + self.__tile_size * x, self.__margin + self.__tile_size * y, anchor=Tkinter.NW, - image=self.__targets[(t,m)]) - self.__canvas.itemconfig( - self.__target_images[(x, y)], - state=Tkinter.HIDDEN) - for (r, (x, y)) in board.pos.items(): + image=self.__targets[(t, m)], + ) + self.__canvas.itemconfig(self.__target_images[(x, y)], state=Tkinter.HIDDEN) + for r, (x, y) in board.pos.items(): self.__robot_images[r] = self.__canvas.create_image( self.__margin + self.__tile_size * x, self.__margin + self.__tile_size * y, anchor=Tkinter.NW, - image=self.__robots[r]) - for (d, x, y) in board.barriers: + image=self.__robots[r], + ) + for d, x, y in board.barriers: (img, dx, dy) = self.__barriers[d] self.__canvas.create_image( self.__margin + self.__tile_size * x + dx, self.__margin + self.__tile_size * y + dy, anchor=Tkinter.NW, - image=img) + image=img, + ) self.__solve_button = self.__canvas.create_text( board.size * self.__tile_size / 2 + self.__margin, (0.5 + board.size) * self.__tile_size + 2 * self.__margin, text="Solve!", activefill="blue", - state=Tkinter.HIDDEN) + state=Tkinter.HIDDEN, + ) self.__solving_text = self.__canvas.create_text( board.size * self.__tile_size / 2 + self.__margin, (0.5 + board.size) * self.__tile_size + 2 * self.__margin, text="Solving...", - state=Tkinter.HIDDEN) - self.__canvas.bind('', self.__mouse_move_event) - self.__canvas.bind('', self.__mouse_click_event) + state=Tkinter.HIDDEN, + ) + self.__canvas.bind("", self.__mouse_move_event) + self.__canvas.bind("", self.__mouse_click_event) def __mouse_over(self, tag, mx, my): if self.__canvas.itemcget(tag, "state") == Tkinter.HIDDEN: return False x, y, xx, yy = self.__canvas.bbox(tag) - return mx >= x and mx < xx and \ - my >= y and my < yy + return mx >= x and mx < xx and my >= y and my < yy def __mouse_over_triangle(self, tag, mx, my, dx, dy): if self.__mouse_over(tag, mx, my): @@ -282,7 +320,7 @@ def __mouse_click_event(self, e): for (x, y), t in self.__target_images.items(): if self.__mouse_over(t, e.x, e.y): clicked.add(("target", (x, y))) - for (t, val) in self.__direction_images: + for t, val in self.__direction_images: r, x, y, dx, dy = val if self.__mouse_over_triangle(t, e.x, e.y, dx, dy): clicked.add(("robot", val)) @@ -295,52 +333,55 @@ def __mouse_click_event(self, e): def __mouse_move_event(self, e): entered = set() - for ((x, y), t) in self.__target_images.items(): + for (x, y), t in self.__target_images.items(): if self.__mouse_over(t, e.x, e.y): entered.add(("target", (x, y))) - for (t, val) in self.__direction_images: + for t, val in self.__direction_images: r, x, y, dx, dy = val if self.__mouse_over_triangle(t, e.x, e.y, dx, dy): entered.add(("robot", val)) - for (tag, val) in self.__entered - entered: + for tag, val in self.__entered - entered: for slot in self.__slots.get(tag, []): slot("leave", val) - for (tag, val) in entered - self.__entered: + for tag, val in entered - self.__entered: for slot in self.__slots.get(tag, []): slot("enter", val) self.__entered = entered def highlight(self, x, y, active): if active and not (x, y) in self.__highlights: - m = 8 + m = 8 xx = self.__margin + x * self.__tile_size + m yy = self.__margin + y * self.__tile_size + m self.__highlights[(x, y)] = self.__canvas.create_rectangle( (xx, yy, xx + self.__tile_size - 2 * m, yy + self.__tile_size - 2 * m), width=3, - outline="blue") + outline="blue", + ) elif not active and (x, y) in self.__highlights: self.__canvas.delete(self.__highlights[(x, y)]) del self.__highlights[(x, y)] def highlight_direction(self, x, y, dx, dy, active): if active and not (x, y, dx, dy) in self.__highlights: - m = 8 + m = 8 xx = self.__margin + x * self.__tile_size + m yy = self.__margin + y * self.__tile_size + m xxx = xx + self.__tile_size - 2 * m yyy = yy + self.__tile_size - 2 * m cx = xx + (xxx - xx) / 2 cy = yy + (yyy - yy) / 2 - if dx == -1: xx, xxx = xxx, xx - if dy == -1: yy, yyy = yyy, yy - if dy == 0: xxx = xx - if dx == 0: yyy = yy + if dx == -1: + xx, xxx = xxx, xx + if dy == -1: + yy, yyy = yyy, yy + if dy == 0: + xxx = xx + if dx == 0: + yyy = yy self.__highlights[(x, y, dx, dy)] = self.__canvas.create_polygon( - (xx, yy, xxx, yyy, cx, cy), - width=3, - outline="blue", - fill="") + (xx, yy, xxx, yyy, cx, cy), width=3, outline="blue", fill="" + ) elif not active and (x, y, dx, dy) in self.__highlights: self.__canvas.delete(self.__highlights[(x, y, dx, dy)]) del self.__highlights[(x, y, dx, dy)] @@ -361,63 +402,90 @@ def connect_solve_event(self, slot): def update_board(self, board): self.clear_directions() - for (r, (x, y)) in board.pos.items(): + for r, (x, y) in board.pos.items(): ox, oy = self.__canvas.coords(self.__robot_images[r]) self.__canvas.move( self.__robot_images[r], self.__margin + self.__tile_size * x - ox, - self.__margin + self.__tile_size * y - oy) - for dx, dy in [(1,0), (0,1), (-1,0), (0,-1)]: + self.__margin + self.__tile_size * y - oy, + ) + for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]: xx = x + dx yy = y + dy - if not (x, y, dx, dy) in board.blocked and not (xx, yy) in board.pos.values(): - self.__direction_images.append(( - self.__canvas.create_image( - self.__margin + self.__tile_size * xx, - self.__margin + self.__tile_size * yy, - anchor=Tkinter.NW, - image=self.__moves_short[r, dx, dy]), - (r, x, y, dx, dy))) + if ( + not (x, y, dx, dy) in board.blocked + and not (xx, yy) in board.pos.values() + ): + self.__direction_images.append( + ( + self.__canvas.create_image( + self.__margin + self.__tile_size * xx, + self.__margin + self.__tile_size * yy, + anchor=Tkinter.NW, + image=self.__moves_short[r, dx, dy], + ), + (r, x, y, dx, dy), + ) + ) for tag in self.__solution_images: self.__canvas.delete(tag) self.__solution_images = [] if board.solution is not None: i = 0 - for (r, x, y, _) in board.solution: + for r, x, y, _ in board.solution: self.__solution_images.append( self.__canvas.create_image( self.__margin + i * self.__tile_size, 2 * self.__margin + self.__tile_size * board.size, anchor=Tkinter.NW, - image=self.__moves[(r, x, y)])) + image=self.__moves[(r, x, y)], + ) + ) i += 1 + def enable_solve(self, board, state): - self.__canvas.itemconfigure(self.__solve_button, state=Tkinter.NORMAL if state == "enabled" else Tkinter.HIDDEN) - self.__canvas.itemconfigure(self.__solving_text, state=Tkinter.NORMAL if state == "busy" else Tkinter.HIDDEN) + self.__canvas.itemconfigure( + self.__solve_button, + state=Tkinter.NORMAL if state == "enabled" else Tkinter.HIDDEN, + ) + self.__canvas.itemconfigure( + self.__solving_text, + state=Tkinter.NORMAL if state == "busy" else Tkinter.HIDDEN, + ) def update_target(self, board): - for (t, m, x, y) in board.targets: - self.__canvas.itemconfig(self.__target_images[(x, y)], state=Tkinter.NORMAL if board.current_target is None else Tkinter.HIDDEN) + for t, m, x, y in board.targets: + self.__canvas.itemconfig( + self.__target_images[(x, y)], + state=( + Tkinter.NORMAL if board.current_target is None else Tkinter.HIDDEN + ), + ) if board.current_target is not None: - self.__canvas.itemconfig(self.__target_images[board.current_target[2], board.current_target[3]], state=Tkinter.NORMAL) + self.__canvas.itemconfig( + self.__target_images[board.current_target[2], board.current_target[3]], + state=Tkinter.NORMAL, + ) def clear_directions(self): - for (tag, _) in self.__direction_images: + for tag, _ in self.__direction_images: self.__canvas.delete(tag) self.__direction_images = [] + # {{{1 Application + class Main: def __init__(self): self.__master = Tkinter.Tk() - self.__board = Board() + self.__board = Board() self.__solver = Solver() self.__canvas = Visualization(self.__master, self.__board) - #self.__master.bind("", self.__canvas.on_previous) # would be nice to have these two bindings as an undo/redo stack - #self.__master.bind("", self.__canvas.on_next) + # self.__master.bind("", self.__canvas.on_previous) # would be nice to have these two bindings as an undo/redo stack + # self.__master.bind("", self.__canvas.on_next) self.__master.bind("", lambda x: self.__master.quit()) self.__canvas.update_target(self.__board) self.__canvas.connect_target_event(self.target_event) @@ -446,14 +514,17 @@ def __update_board(self): self.__board.current_target = None self.__canvas.clear_directions() self.__canvas.update_target(self.__board) - self.__canvas.enable_solve(self.__board, "enabled" if not won and self.__board.solution is None else "disabled") + self.__canvas.enable_solve( + self.__board, + "enabled" if not won and self.__board.solution is None else "disabled", + ) def robot_event(self, event, pos): r, x, y, dx, dy = pos if event == "enter": - self.__canvas.highlight_direction(x+dx, y+dy, dx, dy, True) + self.__canvas.highlight_direction(x + dx, y + dy, dx, dy, True) elif event == "leave": - self.__canvas.highlight_direction(x+dx, y+dy, dx, dy, False) + self.__canvas.highlight_direction(x + dx, y + dy, dx, dy, False) else: self.__solver.stop() self.__board.move(r, dx, dy) @@ -474,6 +545,7 @@ def timer_event(self): def run(self): Tkinter.mainloop() + # {{{1 main app = Main() diff --git a/examples/clingo/setconf/setconf-lua.lp b/examples/clingo/setconf/setconf-lua.lp index 9dd4a3d5e..433634092 100644 --- a/examples/clingo/setconf/setconf-lua.lp +++ b/examples/clingo/setconf/setconf-lua.lp @@ -18,7 +18,7 @@ end function main(prg) prg:ground({{"base", {}}}) - + print_conf(prg.configuration, "") print ("The heuristics of the solvers in the 'many' portfolio:") diff --git a/examples/clingo/solitaire/solitaire.lp b/examples/clingo/solitaire/solitaire.lp index 1ee6a0ded..bb763a537 100644 --- a/examples/clingo/solitaire/solitaire.lp +++ b/examples/clingo/solitaire/solitaire.lp @@ -30,4 +30,3 @@ stone(X,Y,t) :- stone(X,Y,t-1), not jump(X,Y,_,t), not remove(X,Y,t). :- query(t), goal(X,Y), not stone(X,Y,t). :- query(t), not goal(X,Y), stone(X,Y,t). - diff --git a/examples/clingo/solitaire/visualize.py b/examples/clingo/solitaire/visualize.py index 96a944a31..06df390e0 100755 --- a/examples/clingo/solitaire/visualize.py +++ b/examples/clingo/solitaire/visualize.py @@ -1,14 +1,17 @@ #!/usr/bin/python -import urwid import sys -from clingo import SymbolType, Number, Function, clingo_main + +import urwid + +from clingo import Function, Number, SymbolType, clingo_main + class Board: def __init__(self, plan): - self.display = urwid.Text("", align='center') - self.plan = plan + self.display = urwid.Text("", align="center") + self.plan = plan self.current = plan.first() self.update() @@ -21,13 +24,16 @@ def prev(self, button): self.update() def update(self): - brd = [[" "] * (self.plan.width * 2 + 1) for _ in range(0, (self.plan.height * 2 + 1))] + brd = [ + [" "] * (self.plan.width * 2 + 1) + for _ in range(0, (self.plan.height * 2 + 1)) + ] - for (x, y) in self.plan.field: + for x, y in self.plan.field: brd[2 * y + 1][2 * x + 0] = "|" brd[2 * y + 1][2 * x + 2] = "|" - for (x, y) in self.plan.field: + for x, y in self.plan.field: brd[2 * y + 0][2 * x + 0] = "-" brd[2 * y + 0][2 * x + 1] = "-" brd[2 * y + 0][2 * x + 2] = "-" @@ -35,19 +41,18 @@ def update(self): brd[2 * y + 2][2 * x + 1] = "-" brd[2 * y + 2][2 * x + 2] = "-" - for (x, y) in self.plan.steps(self.current): + for x, y in self.plan.steps(self.current): brd[2 * y + 1][2 * x + 1] = "o" j = self.plan.jumped(self.current) if j != None: (x, y) = j - brd[2 * y + 1][2 * x + 1] = ("blue", "o") - + brd[2 * y + 1][2 * x + 1] = ("blue", "o") j = self.plan.jump(self.current) if j != None: (x, y, xx, yy) = j - brd[2 * y + 1][2 * x + 1] = ("red", "o") + brd[2 * y + 1][2 * x + 1] = ("red", "o") brd[2 * yy + 1][2 * xx + 1] = ("green", " ") markup = [] @@ -57,9 +62,10 @@ def update(self): self.display.set_text(markup) + class MainWindow: def __init__(self): - self.loop = None + self.loop = None def exit(self, button): raise urwid.ExitMainLoop() @@ -76,40 +82,53 @@ def run(self, plan): bc = urwid.Button("next") bd = urwid.Button("quit") - urwid.connect_signal(bb, 'click', self.exit) - urwid.connect_signal(bd, 'click', self.quit) - urwid.connect_signal(bc, 'click', c.next) - urwid.connect_signal(ba, 'click', c.prev) + urwid.connect_signal(bb, "click", self.exit) + urwid.connect_signal(bd, "click", self.quit) + urwid.connect_signal(bc, "click", c.next) + urwid.connect_signal(ba, "click", c.prev) sf = urwid.Text("") - b = urwid.Columns([sf, ('fixed', len(bc.label) + 4, bc), ('fixed', len(ba.label) + 4, ba), ('fixed', len(bb.label) + 4, bb), ('fixed', len(bd.label) + 4, bd), sf], 1) - f = urwid.Frame(urwid.Filler(c.display), None, b, 'footer') + b = urwid.Columns( + [ + sf, + ("fixed", len(bc.label) + 4, bc), + ("fixed", len(ba.label) + 4, ba), + ("fixed", len(bb.label) + 4, bb), + ("fixed", len(bd.label) + 4, bd), + sf, + ], + 1, + ) + f = urwid.Frame(urwid.Filler(c.display), None, b, "footer") palette = [ - ('red', 'black', 'light red'), - ('green', 'black', 'light green'), - ('blue', 'black', 'light blue'), ] + ("red", "black", "light red"), + ("green", "black", "light green"), + ("blue", "black", "light blue"), + ] self.loop = urwid.MainLoop(f, palette) self.loop.run() + class Plan: def __init__(self, field, init, jumps): - mx = min(x for (x, y) in field) - my = min(y for (x, y) in field) - self.width = max(x for (x, y) in field) - mx + 1 + mx = min(x for (x, y) in field) + my = min(y for (x, y) in field) + self.width = max(x for (x, y) in field) - mx + 1 self.height = max(y for (x, y) in field) - my + 1 - self.field = [ (x - mx, y - my) for (x, y) in field ] + self.field = [(x - mx, y - my) for (x, y) in field] pjumps = {} - for (t, k) in jumps.items(): pjumps[t] = [ (x - mx, y - my, xx - mx, yy - my) for (x, y, xx, yy) in k ] + for t, k in jumps.items(): + pjumps[t] = [(x - mx, y - my, xx - mx, yy - my) for (x, y, xx, yy) in k] self._jumps = [] self._steps = [] - self._steps.append([ (x - mx, y - my) for (x, y) in init ]) + self._steps.append([(x - mx, y - my) for (x, y) in init]) for t in sorted(pjumps.keys()): - for (x, y, xx, yy) in pjumps[t]: + for x, y, xx, yy in pjumps[t]: self._jumps.append((x, y, xx, yy)) self._steps.append(self._steps[-1][:]) self._steps[-1].append((xx, yy)) @@ -134,14 +153,15 @@ def prev(self, i): def first(self): return 0 + class Application: def __init__(self, name): self.program_name = name self.version = "1.0" def __on_model(self, model): - sx = { "east": 2, "west": -2, "north": 0, "south": 0 } - sy = { "east": 0, "west": 0, "north": -2, "south": 2 } + sx = {"east": 2, "west": -2, "north": 0, "south": 0} + sy = {"east": 0, "west": 0, "north": -2, "south": 2} field, init, jumps = [], [], {} @@ -153,7 +173,10 @@ def __on_model(self, model): x, y = (n.number for n in atom.arguments) init.append((x, y)) elif atom.name == "jump" and len(atom.arguments) == 4: - ox, oy, d, t = ((n.number if n.type == SymbolType.Number else str(n)) for n in atom.arguments) + ox, oy, d, t = ( + (n.number if n.type == SymbolType.Number else str(n)) + for n in atom.arguments + ) jumps.setdefault(t, []).append((ox, oy, ox + sx[d], oy + sy[d])) try: @@ -174,8 +197,9 @@ def main(self, prg, files): t += 1 prg.ground([("step", [Number(t)])]) prg.ground([("check", [Number(t)])]) - prg.release_external(Function("query", [Number(t-1)])) + prg.release_external(Function("query", [Number(t - 1)])) prg.assign_external(Function("query", [Number(t)]), True) sat = prg.solve(on_model=self.__on_model).satisfiable + sys.exit(int(clingo_main(Application("visualize"), sys.argv[1:]))) diff --git a/examples/clingo/solve-async/program.lp b/examples/clingo/solve-async/program.lp index f0b6fab3e..b83c9bc03 100644 --- a/examples/clingo/solve-async/program.lp +++ b/examples/clingo/solve-async/program.lp @@ -2,4 +2,3 @@ 1 { p(X); q(X) } 1 :- X = 1..n. :- not n+1 { p(1..n); q(1..n) }. - diff --git a/examples/clingo/stats/stats-py.lp b/examples/clingo/stats/stats-py.lp index c0f0bfc2d..4e9d3b980 100644 --- a/examples/clingo/stats/stats-py.lp +++ b/examples/clingo/stats/stats-py.lp @@ -10,5 +10,3 @@ def main(prg): print ("optimization", prg.statistics["summary"]["costs"]) #end. - - diff --git a/examples/clingo/tmode/tmode.py b/examples/clingo/tmode/tmode.py index 869efa402..60e28a18c 100644 --- a/examples/clingo/tmode/tmode.py +++ b/examples/clingo/tmode/tmode.py @@ -1,20 +1,26 @@ -from sys import stdout, exit -from textwrap import dedent from copy import copy +from sys import exit, stdout +from textwrap import dedent +from clingo import Function, Number, SymbolType, ast, clingo_main from clingo.application import Application -from clingo import SymbolType, Number, Function, ast, clingo_main + class TermTransformer(ast.Transformer): def __init__(self, parameter): self.parameter = parameter def __get_param(self, name, location): - n = name.replace('\'', '') + n = name.replace("'", "") primes = len(name) - len(n) param = ast.SymbolicTerm(location, self.parameter) if primes > 0: - param = ast.BinaryOperation(location, ast.BinaryOperator.Minus, param, ast.SymbolicTerm(location, Number(primes))) + param = ast.BinaryOperation( + location, + ast.BinaryOperator.Minus, + param, + ast.SymbolicTerm(location, Number(primes)), + ) return n, param def visit_Function(self, term): @@ -28,6 +34,7 @@ def visit_SymbolicTerm(self, term): # but this case could occur in a valid AST raise RuntimeError("not implemented") + class ProgramTransformer(ast.Transformer): def __init__(self, parameter): self.final = False @@ -40,7 +47,9 @@ def visit(self, x, *args, **kwargs): if x is ret: ret = copy(x) loc = ret.location - fun = ast.Function(loc, "finally", [ast.SymbolicTerm(loc, self.parameter)], False) + fun = ast.Function( + loc, "finally", [ast.SymbolicTerm(loc, self.parameter)], False + ) atm = ast.SymbolicAtom(fun) lit = ast.Literal(loc, ast.Sign.NoSign, atm) ret.body.append(lit) @@ -63,6 +72,7 @@ def visit_ShowSignature(self, sig): def visit_ProjectSignature(self, sig): return sig.update(arity=sig.arity + 1) + class TModeApp(Application): def __init__(self): self._imin = 0 @@ -93,19 +103,38 @@ def _parse_istop(self, value): def register_options(self, options): group = "Incremental Options" - options.add(group, "imin", "Minimum number of solving steps [0]", - self._parse_imin, argument="") - options.add(group, "imax", "Maximum number of solving steps [infinity]", - self._parse_imax, argument="") - options.add(group, "istop", dedent("""\ + options.add( + group, + "imin", + "Minimum number of solving steps [0]", + self._parse_imin, + argument="", + ) + options.add( + group, + "imax", + "Maximum number of solving steps [infinity]", + self._parse_imax, + argument="", + ) + options.add( + group, + "istop", + dedent( + """\ Stop criterion [sat] - : {sat|unsat|unknown}"""), self._parse_istop) + : {sat|unsat|unknown}""" + ), + self._parse_istop, + ) def print_model(self, model, printer): table = {} for sym in model.symbols(shown=True): if sym.type == SymbolType.Function and len(sym.arguments) > 0: - table.setdefault(sym.arguments[-1], []).append(Function(sym.name, sym.arguments[:-1])) + table.setdefault(sym.arguments[-1], []).append( + Function(sym.name, sym.arguments[:-1]) + ) for step, symbols in sorted(table.items()): stdout.write(" State {}:".format(step)) sig = None @@ -118,22 +147,26 @@ def print_model(self, model, printer): def _main(self, ctl): step, ret = 0, None - while ((self._imax is None or step < self._imax) and - (step == 0 or step < self._imin or ( - (self._istop == "SAT" and not ret.satisfiable) or - (self._istop == "UNSAT" and not ret.unsatisfiable) or - (self._istop == "UNKNOWN" and not ret.unknown)))): + while (self._imax is None or step < self._imax) and ( + step == 0 + or step < self._imin + or ( + (self._istop == "SAT" and not ret.satisfiable) + or (self._istop == "UNSAT" and not ret.unsatisfiable) + or (self._istop == "UNKNOWN" and not ret.unknown) + ) + ): parts = [] parts.append(("base", [Number(step)])) parts.append(("static", [Number(step)])) if step > 0: - ctl.release_external(Function("finally", [Number(step-1)])) + ctl.release_external(Function("finally", [Number(step - 1)])) parts.append(("dynamic", [Number(step)])) else: parts.append(("initial", [Number(0)])) ctl.ground(parts) ctl.assign_external(Function("finally", [Number(step)]), True) - ret, step = ctl.solve(), step+1 + ret, step = ctl.solve(), step + 1 def main(self, ctl, files): with ast.ProgramBuilder(ctl) as bld: @@ -143,4 +176,5 @@ def main(self, ctl, files): ctl.add("static", ["t"], "#external finally(t).") self._main(ctl) + exit(clingo_main(TModeApp())) diff --git a/examples/clingo/unblock/inst5.lp b/examples/clingo/unblock/inst5.lp index 096433a4e..e5ce7904a 100644 --- a/examples/clingo/unblock/inst5.lp +++ b/examples/clingo/unblock/inst5.lp @@ -39,4 +39,3 @@ stone(I,y,X,Y,L) :- not brick(I,X,Y-1), brick(I,X,Y), brick(I,X,Y+1), count(I,L) target(r,5,4). field(1..6,1..6). - diff --git a/examples/clingo/unblock/unblock.lp b/examples/clingo/unblock/unblock.lp index 0dadefa40..f2864fff8 100644 --- a/examples/clingo/unblock/unblock.lp +++ b/examples/clingo/unblock/unblock.lp @@ -21,7 +21,7 @@ blocked(t,X+(0..L-1),Y) :- stone(t-1,S,x,X,Y,L). blocked(t,X,Y+(0..L-1)) :- stone(t-1,S,y,X,Y,L). %:- 2 { move(t,_,_,_) }. -% allow for parallel moves +% allow for parallel moves :- 2 { move(t,S,x,X) }, field(X,_). :- 2 { move(t,S,y,Y) }, field(_,Y). :- move(t,_,x,_), move(t,_,y,_). diff --git a/examples/clingo/unblock/visualize.py b/examples/clingo/unblock/visualize.py index 94dd9feba..06d3b19da 100755 --- a/examples/clingo/unblock/visualize.py +++ b/examples/clingo/unblock/visualize.py @@ -1,31 +1,35 @@ #!/usr/bin/python -import urwid import sys -from clingo import SymbolType, Number, Function, Control +import urwid + +from clingo import Control, Function, Number, SymbolType + class Plan: def __init__(self, field, stone, target, move): - mx = min([x for (x, y) in field]) - my = min([y for (x, y) in field]) - self.width = max([x for (x, y) in field]) - mx + 1 - self.height = max([y for (x, y) in field]) - my + 1 - self.field = [ (x - mx, y - my) for (x, y) in field ] - self.target = [ (s, x - mx, y - my) for (s, x, y) in target ] - self._stones = [ [ (s, d, x - mx, y - my, l) for (s, d, x, y, l) in stone ] ] - self._moves = [ ] - self._locs = [ ] + mx = min([x for (x, y) in field]) + my = min([y for (x, y) in field]) + self.width = max([x for (x, y) in field]) - mx + 1 + self.height = max([y for (x, y) in field]) - my + 1 + self.field = [(x - mx, y - my) for (x, y) in field] + self.target = [(s, x - mx, y - my) for (s, x, y) in target] + self._stones = [[(s, d, x - mx, y - my, l) for (s, d, x, y, l) in stone]] + self._moves = [] + self._locs = [] for t in sorted(move.keys()): - for (s, d, xy) in move[t]: - xy -= (mx if d == "x" else my) + for s, d, xy in move[t]: + xy -= mx if d == "x" else my self._moves.append((s, d, xy)) self._stones.append([]) - for (ss, sd, sx, sy, sl) in self._stones[-2]: + for ss, sd, sx, sy, sl in self._stones[-2]: if ss == s: - if d == "x": sx = xy - else : sy = xy + if d == "x": + sx = xy + else: + sy = xy self._locs.append((sd, sx, sy, sl)) self._stones[-1].append((ss, sd, sx, sy, sl)) self._moves.append(None) @@ -49,11 +53,12 @@ def prev(self, i): def first(self): return 0 + class Board: def __init__(self, plan): - self.display = urwid.Text("", align='center') - self.plan = plan + self.display = urwid.Text("", align="center") + self.plan = plan self.current = plan.first() self.update() @@ -66,13 +71,16 @@ def prev(self, button): self.update() def update(self): - brd = [[" "] * (self.plan.width * 2 + 1) for _ in range(0, (self.plan.height * 2 + 1))] + brd = [ + [" "] * (self.plan.width * 2 + 1) + for _ in range(0, (self.plan.height * 2 + 1)) + ] - for (x, y) in self.plan.field: + for x, y in self.plan.field: brd[2 * y + 1][2 * x + 0] = "|" brd[2 * y + 1][2 * x + 2] = "|" - for (x, y) in self.plan.field: + for x, y in self.plan.field: brd[2 * y + 0][2 * x + 0] = "-" brd[2 * y + 0][2 * x + 1] = "-" brd[2 * y + 0][2 * x + 2] = "-" @@ -80,14 +88,17 @@ def update(self): brd[2 * y + 2][2 * x + 1] = "-" brd[2 * y + 2][2 * x + 2] = "-" - for (s, d, x, y, l) in self.plan.stones(self.current): + for s, d, x, y, l in self.plan.stones(self.current): sx = 2 * x + 1 sy = 2 * y + 1 - m = self.plan.move(self.current) - if m != None: m = m[0] + m = self.plan.move(self.current) + if m != None: + m = m[0] for sd in range(0, 2 * l - 1): - brd[sy + (sd if d == "y" else 0)][sx + (sd if d == "x" else 0)] = ('red', d) if s == m else d + brd[sy + (sd if d == "y" else 0)][sx + (sd if d == "x" else 0)] = ( + ("red", d) if s == m else d + ) loc = self.plan.loc(self.current) if loc != None: @@ -97,11 +108,13 @@ def update(self): for sd in range(0, 2 * l - 1): sx = x + (sd if d == "x" else 0) sy = y + (sd if d == "y" else 0) - if brd[sy][sx] in [" ", "|", "-"]: brd[sy][sx] = ('blue', brd[sy][sx]) + if brd[sy][sx] in [" ", "|", "-"]: + brd[sy][sx] = ("blue", brd[sy][sx]) - for (s, x, y) in self.plan.target: + for s, x, y in self.plan.target: s = brd[2 * y + 1][2 * x + 1] - if isinstance(s, tuple): s = s[1] + if isinstance(s, tuple): + s = s[1] brd[2 * y + 1][2 * x + 1] = ("green", s) markup = [] @@ -111,9 +124,10 @@ def update(self): self.display.set_text(markup) + class MainWindow: def __init__(self): - self.loop = None + self.loop = None def exit(self, button): raise urwid.ExitMainLoop() @@ -126,26 +140,40 @@ def run(self, plan): bb = urwid.Button("quit") bc = urwid.Button("next") - urwid.connect_signal(bb, 'click', self.exit) - urwid.connect_signal(bc, 'click', c.next) - urwid.connect_signal(ba, 'click', c.prev) + urwid.connect_signal(bb, "click", self.exit) + urwid.connect_signal(bc, "click", c.next) + urwid.connect_signal(ba, "click", c.prev) sf = urwid.Text("") - b = urwid.Columns([sf, ('fixed', len(bc.label) + 4, bc), ('fixed', len(ba.label) + 4, ba), ('fixed', len(bb.label) + 4, bb), sf], 1) - f = urwid.Frame(urwid.Filler(c.display), None, b, 'footer') + b = urwid.Columns( + [ + sf, + ("fixed", len(bc.label) + 4, bc), + ("fixed", len(ba.label) + 4, ba), + ("fixed", len(bb.label) + 4, bb), + sf, + ], + 1, + ) + f = urwid.Frame(urwid.Filler(c.display), None, b, "footer") palette = [ - ('red', 'black', 'light red'), - ('green', 'black', 'light green'), - ('blue', 'black', 'light blue'), ] + ("red", "black", "light red"), + ("green", "black", "light green"), + ("blue", "black", "light blue"), + ] self.loop = urwid.MainLoop(f, palette) self.loop.run() + c = Control() c.add("check", ["k"], "#external query(k).") -for f in sys.argv[1:]: c.load(f) +for f in sys.argv[1:]: + c.load(f) + + def make_on_model(field, stone, move, target): def on_model(m): for atom in m.symbols(atoms=True): @@ -153,17 +181,28 @@ def on_model(m): x, y = [n.number for n in atom.arguments] field.append((x, y)) elif atom.name == "stone" and len(atom.arguments) == 5: - s, d, x, y, l = [(n.number if n.type == SymbolType.Number else str(n)) for n in atom.arguments] + s, d, x, y, l = [ + (n.number if n.type == SymbolType.Number else str(n)) + for n in atom.arguments + ] stone.append((s, d, x, y, l)) elif atom.name == "move" and len(atom.arguments) == 4: - t, s, d, xy = [(n.number if n.type == SymbolType.Number else str(n)) for n in atom.arguments] + t, s, d, xy = [ + (n.number if n.type == SymbolType.Number else str(n)) + for n in atom.arguments + ] move.setdefault(t, []).append((s, d, xy)) elif atom.name == "target" and len(atom.arguments) == 3: - s, x, y = [(n.number if n.type == SymbolType.Number else str(n)) for n in atom.arguments] + s, x, y = [ + (n.number if n.type == SymbolType.Number else str(n)) + for n in atom.arguments + ] target.append((s, x, y)) return False + return on_model + t, field, stone, move, target = 0, [], [], {}, [] on_model = make_on_model(field, stone, move, target) c.ground([("base", [])]) @@ -171,10 +210,9 @@ def on_model(m): t += 1 c.ground([("step", [Number(t)])]) c.ground([("check", [Number(t)])]) - c.release_external(Function("query", [Number(t-1)])) + c.release_external(Function("query", [Number(t - 1)])) c.assign_external(Function("query", [Number(t)]), True) if c.solve(on_model=on_model).satisfiable: break MainWindow().run(Plan(field, stone, target, move)) - diff --git a/examples/clingo/well-founded/well-founded.py b/examples/clingo/well-founded/well-founded.py index 1adcc864c..54f38ca35 100644 --- a/examples/clingo/well-founded/well-founded.py +++ b/examples/clingo/well-founded/well-founded.py @@ -1,15 +1,15 @@ import sys -from typing import Deque, Dict, Set, List, Tuple from collections import deque +from typing import Deque, Dict, List, Set, Tuple -from networkx import DiGraph # type: ignore -from networkx.algorithms.components import strongly_connected_components # type: ignore -from networkx.algorithms.dag import topological_sort # type: ignore +from clingox.program import Program, ProgramObserver, Rule +from networkx import DiGraph # type: ignore +from networkx.algorithms.components import strongly_connected_components # type: ignore +from networkx.algorithms.dag import topological_sort # type: ignore +from clingo.application import Application, clingo_main from clingo.control import Control from clingo.symbol import Symbol -from clingo.application import Application, clingo_main -from clingox.program import Program, ProgramObserver, Rule Atom = int Literal = int @@ -26,7 +26,7 @@ def _analyze(rules: List[Rule]) -> List[List[Rule]]: occ.setdefault(abs(lit), set()).add(u) for u, rule in enumerate(rules): - atm, = rule.head + (atm,) = rule.head for v in occ.get(atm, []): dep_graph.add_edge(u, v) @@ -75,7 +75,7 @@ def is_supported(lit): return not is_false(lit) and (lit < 0 or is_true(lit) or lit in has_source) def enqueue_source(idx: RuleIndex): - atm, = scc[idx].head + (atm,) = scc[idx].head if counters_source[idx] == 0 and atm not in has_source: has_source.add(atm) is_source.add(idx) @@ -88,7 +88,7 @@ def enqueue_lit(lit: Literal): # initialize the above data structures for i, rule in enumerate(scc): - atm, = rule.head + (atm,) = rule.head if is_false(*rule.body) or is_true(atm): continue @@ -138,7 +138,7 @@ def enqueue_lit(lit: Literal): for i in watches.get(-lit, []): counters_source[i] += 1 if i in is_source: - atm, = scc[i].head + (atm,) = scc[i].head is_source.remove(i) has_source.remove(atm) if -atm not in interpretation: @@ -167,17 +167,17 @@ def enqueue_lit(lit: Literal): def well_founded(prg: Program) -> Tuple[List[Symbol], List[Symbol]]: - ''' + """ Computes the well-founded model of the given program returning a pair of facts and unknown atoms. This function assumes that the program contains only normal rules. - ''' + """ for rule in prg.rules: if len(rule.head) != 1 or rule.choice: - raise RuntimeError('only normal rules are supported') + raise RuntimeError("only normal rules are supported") if prg.weight_rules: - raise RuntimeError('only normal rules are supported') + raise RuntimeError("only normal rules are supported") # analyze program and compute well-founded model interpretation: Set[Literal] = set() @@ -186,11 +186,15 @@ def well_founded(prg: Program) -> Tuple[List[Symbol], List[Symbol]]: # compute facts fct = [atm.symbol for atm in prg.facts] - fct.extend(prg.output_atoms[lit] for lit in interpretation if lit > 0 and lit in prg.output_atoms) + fct.extend( + prg.output_atoms[lit] + for lit in interpretation + if lit > 0 and lit in prg.output_atoms + ) # compute unknowns ukn = set() for rule in prg.rules: - atm, = rule.head + (atm,) = rule.head not_false = any(-lit in interpretation for lit in rule.body) if atm not in interpretation and not not_false and atm in prg.output_atoms: ukn.add(prg.output_atoms[atm]) @@ -209,14 +213,14 @@ def main(self, ctl: Control, files): for f in files: ctl.load(f) if not files: - ctl.load('-') + ctl.load("-") ctl.ground([("base", [])]) fct, ukn = well_founded(prg) - print('Facts:') + print("Facts:") print(f'{" ".join(map(str, fct))}') - print('Unknown:') + print("Unknown:") print(f'{" ".join(map(str, ukn))}') ctl.solve() diff --git a/examples/gringo/acyc/README b/examples/gringo/acyc/README index e515aa665..a2e83dc11 100644 --- a/examples/gringo/acyc/README +++ b/examples/gringo/acyc/README @@ -2,4 +2,3 @@ Example showcasing the #edge directive. Example calls: clingo encoding.lp instance.lp - diff --git a/examples/gringo/acyc/encoding.lp b/examples/gringo/acyc/encoding.lp index a5fd665c7..fd12e8e34 100644 --- a/examples/gringo/acyc/encoding.lp +++ b/examples/gringo/acyc/encoding.lp @@ -4,4 +4,3 @@ start(X) :- X = #min { Y : node(Y) }. #edge (X,Y) : path(X,Y), not start(Y). #show path/2. - diff --git a/examples/gringo/acyc/instance.lp b/examples/gringo/acyc/instance.lp index 5aadd404c..923785553 100644 --- a/examples/gringo/acyc/instance.lp +++ b/examples/gringo/acyc/instance.lp @@ -1,3 +1,2 @@ node(a;b;c;d). edge(a,b;b,(a;c;d);c,(a;d);d,(a;c)). - diff --git a/examples/gringo/ast/README b/examples/gringo/ast/README index 50bcdbaeb..2a79fe581 100644 --- a/examples/gringo/ast/README +++ b/examples/gringo/ast/README @@ -3,4 +3,3 @@ additional parameter to all symbolic atoms occurring in a program. Example calls: gringo --text visitor.lp - diff --git a/examples/gringo/project/README b/examples/gringo/project/README index 9c0210dcf..8a2b982b9 100644 --- a/examples/gringo/project/README +++ b/examples/gringo/project/README @@ -2,4 +2,3 @@ Example showcasing the #project directive. Example calls: clingo --project 0 example.lp - diff --git a/examples/gringo/project/example.lp b/examples/gringo/project/example.lp index 848d77288..0c510ed31 100644 --- a/examples/gringo/project/example.lp +++ b/examples/gringo/project/example.lp @@ -2,4 +2,3 @@ 1 { p(1..2) } 1. 1 { q(1..2) } 1. - diff --git a/examples/gringo/queens/README b/examples/gringo/queens/README index 7a9c36a2e..51c64644b 100644 --- a/examples/gringo/queens/README +++ b/examples/gringo/queens/README @@ -3,4 +3,3 @@ Two examples that encode the n-queens problem. Example calls: clingo queens1.lp clingo queens2.lp - diff --git a/examples/gringo/subset/README b/examples/gringo/subset/README index ee5844beb..a2def1d72 100644 --- a/examples/gringo/subset/README +++ b/examples/gringo/subset/README @@ -3,4 +3,3 @@ subset minimal models. Example calls: clingo --heuristic=domain --enum-mode=domRec 0 example.lp - diff --git a/examples/gringo/toh/tohI.lp b/examples/gringo/toh/tohI.lp index 83837d5e1..7dcf14efd 100644 --- a/examples/gringo/toh/tohI.lp +++ b/examples/gringo/toh/tohI.lp @@ -3,4 +3,3 @@ peg(a;b;c). disk(1..4). init_on(1..4,a). goal_on(1..4,c). - diff --git a/examples/reify/classical/README.md b/examples/reify/classical/README.md index 8396b25dc..e6edd3e6d 100644 --- a/examples/reify/classical/README.md +++ b/examples/reify/classical/README.md @@ -21,4 +21,3 @@ call to see that ground logic program: The grounding process applies simplifications that may eliminate some atoms of the input program. To avoid this, in `example1.lp` we have added an external declaration. You can comment it and run the call again to see what happens. - diff --git a/examples/reify/common/metaD.lp b/examples/reify/common/metaD.lp index cc40d705e..17d038d14 100644 --- a/examples/reify/common/metaD.lp +++ b/examples/reify/common/metaD.lp @@ -64,4 +64,3 @@ bot :- scc(C,A), true(atom(A)), wait(C,atom(A),Z), steps(C,Z). true(atom(A)) :- supp(A), not fact(A), bot. fail(atom(A)) :- supp(A), not fact(A), bot. - diff --git a/examples/reify/gac/examples/conformant/base.lp b/examples/reify/gac/examples/conformant/base.lp index 3d464a4c2..3b6a0feef 100644 --- a/examples/reify/gac/examples/conformant/base.lp +++ b/examples/reify/gac/examples/conformant/base.lp @@ -21,7 +21,7 @@ contradict(F) :- complement(F,L,M), effect(A,L,N1), effect(A,M,N2), { holds(F,0) } :- complement(F,L,M), not initially(L), not initially(M). holds(F,0) :- initially(L), complement(F,L,M). -holds_oneof(N,B) :- +holds_oneof(N,B) :- initially_oneof(N,_,B); not holds(F,0) : initially_oneof(N,M,B), complement(F,L,M); holds(F,0) : initially_oneof(N,L,B), complement(F,L,M). @@ -39,8 +39,8 @@ holds(L,T) :- occurs(A,T), effect(A,L,N), holds(C,T-1) : condition(A,C,N). holds(L,T) :- time(T), holds(L,T-1), complement(L,M), not holds(M,T). fail :- contradict(F), complement(F,L,M), holds(L,T), holds(M,T). -caused(L,T) :- - occurs(A,T), effect(A,L,N), +caused(L,T) :- + occurs(A,T), effect(A,L,N), not holds(F',T-1) : condition(A,M',N), complement(F',L',M'); holds(F',T-1) : condition(A,L',N), complement(F',L',M'). holds(F,T) :- caused(L,T), complement(F,L,M). diff --git a/examples/reify/gac/examples/conformant/instance.lp b/examples/reify/gac/examples/conformant/instance.lp index 70f5aeed8..a8e3c31cf 100644 --- a/examples/reify/gac/examples/conformant/instance.lp +++ b/examples/reify/gac/examples/conformant/instance.lp @@ -15,7 +15,7 @@ fluent(cpa_coin_at(cpa_c0, cpa_f1, cpa_p1)). fluent(cpa_coin_at(cpa_c1, cpa_f1, cpa_p0)). fluent(cpa_coin_at(cpa_c1, cpa_f1, cpa_p1)). -%% actions ------ +%% actions ------ action(cpa_collect(cpa_c0, cpa_f0, cpa_p0)). action(cpa_collect(cpa_c0, cpa_f0, cpa_p1)). @@ -42,7 +42,7 @@ action(cpa_step_out(cpa_e0, cpa_f1, cpa_p0)). action(cpa_step_out(cpa_e1, cpa_f0, cpa_p1)). action(cpa_step_out(cpa_e1, cpa_f1, cpa_p1)). -%% executable ------ +%% executable ------ executable(cpa_collect(cpa_c0, cpa_f0, cpa_p0),cpa_at(cpa_f0, cpa_p0)). executable(cpa_collect(cpa_c0, cpa_f0, cpa_p1),cpa_at(cpa_f0, cpa_p1)). @@ -65,7 +65,7 @@ executable(cpa_step_out(cpa_e0, cpa_f1, cpa_p0),cpa_inside(cpa_e0)). executable(cpa_step_out(cpa_e1, cpa_f0, cpa_p1),cpa_inside(cpa_e1)). executable(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),cpa_inside(cpa_e1)). -%% effects ------ +%% effects ------ effect(cpa_collect(cpa_c0, cpa_f1, cpa_p0),cpa_have(cpa_c0),1). effect(cpa_collect(cpa_c0, cpa_f1, cpa_p0),neg(cpa_coin_at(cpa_c0, cpa_f1, cpa_p0)),1). @@ -124,7 +124,7 @@ effect(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),cpa_at(cpa_f1, cpa_p1),1). effect(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),neg(cpa_inside(cpa_e1)),1). condition(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),cpa_in(cpa_e1, cpa_f1),1). -%% initial state ------ +%% initial state ------ initially(cpa_at(cpa_f0, cpa_p0)). initially(neg(cpa_at(cpa_f0, cpa_p1))). @@ -143,7 +143,7 @@ initially_oneof(3,cpa_coin_at(cpa_c1, cpa_f1, cpa_p0),1). initially_oneof(3,cpa_coin_at(cpa_c0, cpa_f1, cpa_p1),2). initially_oneof(3,cpa_coin_at(cpa_c1, cpa_f1, cpa_p1),2). -%% goal state ---------- +%% goal state ---------- goal(cpa_have(cpa_c0)). goal(cpa_have(cpa_c1)). diff --git a/examples/reify/gac/examples/preferences/README.md b/examples/reify/gac/examples/preferences/README.md index 510b4b6ee..36cb04a8a 100644 --- a/examples/reify/gac/examples/preferences/README.md +++ b/examples/reify/gac/examples/preferences/README.md @@ -1,4 +1,4 @@ -# Preferences +# Preferences Call to compute all superset maximal stable models of `guess.lp`: diff --git a/examples/reify/gac/examples/tictactoe/README.md b/examples/reify/gac/examples/tictactoe/README.md index 87dd563d6..001f6c5cd 100644 --- a/examples/reify/gac/examples/tictactoe/README.md +++ b/examples/reify/gac/examples/tictactoe/README.md @@ -18,4 +18,3 @@ player cannot place her tokens in a winning position: Calls : 1 Time : 0.013s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s) CPU Time : 0.012s - diff --git a/examples/reify/many/README.md b/examples/reify/many/README.md index 0e6d453f2..eef435900 100644 --- a/examples/reify/many/README.md +++ b/examples/reify/many/README.md @@ -16,4 +16,3 @@ Finding 3 6-diverse stable models of `example.lp`: Finding 3 most diverse stable models of `example.lp`: $ clingo --output=reify example.lp | clingo -Wno-atom-undefined - encoding.lp -c m=3 -c option=2 --quiet=1,2,2 - diff --git a/examples/reify/optimization/example2.lp b/examples/reify/optimization/example2.lp index 5ed505666..61e60461b 100644 --- a/examples/reify/optimization/example2.lp +++ b/examples/reify/optimization/example2.lp @@ -21,7 +21,7 @@ contradict(F) :- complement(F,L,M), effect(A,L,N1), effect(A,M,N2), { holds(F,0) } :- complement(F,L,M), not initially(L), not initially(M). holds(F,0) :- initially(L), complement(F,L,M). -holds_oneof(N,B) :- +holds_oneof(N,B) :- initially_oneof(N,_,B); not holds(F,0) : initially_oneof(N,M,B), complement(F,L,M); holds(F,0) : initially_oneof(N,L,B), complement(F,L,M). @@ -39,8 +39,8 @@ holds(L,T) :- occurs(A,T), effect(A,L,N), holds(C,T-1) : condition(A,C,N). holds(L,T) :- time(T), holds(L,T-1), complement(L,M), not holds(M,T). fail :- contradict(F), complement(F,L,M), holds(L,T), holds(M,T). -caused(L,T) :- - occurs(A,T), effect(A,L,N), +caused(L,T) :- + occurs(A,T), effect(A,L,N), not holds(F',T-1) : condition(A,M',N), complement(F',L',M'); holds(F',T-1) : condition(A,L',N), complement(F',L',M'). holds(F,T) :- caused(L,T), complement(F,L,M). @@ -85,7 +85,7 @@ fluent(cpa_coin_at(cpa_c0, cpa_f1, cpa_p1)). fluent(cpa_coin_at(cpa_c1, cpa_f1, cpa_p0)). fluent(cpa_coin_at(cpa_c1, cpa_f1, cpa_p1)). -%% actions ------ +%% actions ------ action(cpa_collect(cpa_c0, cpa_f0, cpa_p0)). action(cpa_collect(cpa_c0, cpa_f0, cpa_p1)). @@ -112,7 +112,7 @@ action(cpa_step_out(cpa_e0, cpa_f1, cpa_p0)). action(cpa_step_out(cpa_e1, cpa_f0, cpa_p1)). action(cpa_step_out(cpa_e1, cpa_f1, cpa_p1)). -%% executable ------ +%% executable ------ executable(cpa_collect(cpa_c0, cpa_f0, cpa_p0),cpa_at(cpa_f0, cpa_p0)). executable(cpa_collect(cpa_c0, cpa_f0, cpa_p1),cpa_at(cpa_f0, cpa_p1)). @@ -135,7 +135,7 @@ executable(cpa_step_out(cpa_e0, cpa_f1, cpa_p0),cpa_inside(cpa_e0)). executable(cpa_step_out(cpa_e1, cpa_f0, cpa_p1),cpa_inside(cpa_e1)). executable(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),cpa_inside(cpa_e1)). -%% effects ------ +%% effects ------ effect(cpa_collect(cpa_c0, cpa_f1, cpa_p0),cpa_have(cpa_c0),1). effect(cpa_collect(cpa_c0, cpa_f1, cpa_p0),neg(cpa_coin_at(cpa_c0, cpa_f1, cpa_p0)),1). @@ -194,7 +194,7 @@ effect(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),cpa_at(cpa_f1, cpa_p1),1). effect(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),neg(cpa_inside(cpa_e1)),1). condition(cpa_step_out(cpa_e1, cpa_f1, cpa_p1),cpa_in(cpa_e1, cpa_f1),1). -%% initial state ------ +%% initial state ------ initially(cpa_at(cpa_f0, cpa_p0)). initially(neg(cpa_at(cpa_f0, cpa_p1))). @@ -213,8 +213,7 @@ initially_oneof(3,cpa_coin_at(cpa_c1, cpa_f1, cpa_p0),1). initially_oneof(3,cpa_coin_at(cpa_c0, cpa_f1, cpa_p1),2). initially_oneof(3,cpa_coin_at(cpa_c1, cpa_f1, cpa_p1),2). -%% goal state ---------- +%% goal state ---------- goal(cpa_have(cpa_c0)). goal(cpa_have(cpa_c1)). - diff --git a/libclingo/clingo.h b/libclingo/clingo.h index 9412c817b..e76088934 100644 --- a/libclingo/clingo.h +++ b/libclingo/clingo.h @@ -49,33 +49,33 @@ extern "C" { #endif +#include #include #include -#include #if defined _WIN32 || defined __CYGWIN__ -# define CLINGO_WIN +#define CLINGO_WIN #endif #ifdef CLINGO_NO_VISIBILITY -# define CLINGO_VISIBILITY_DEFAULT -# define CLINGO_VISIBILITY_PRIVATE +#define CLINGO_VISIBILITY_DEFAULT +#define CLINGO_VISIBILITY_PRIVATE +#else +#ifdef CLINGO_WIN +#ifdef CLINGO_BUILD_LIBRARY +#define CLINGO_VISIBILITY_DEFAULT __declspec(dllexport) +#else +#define CLINGO_VISIBILITY_DEFAULT __declspec(dllimport) +#endif +#define CLINGO_VISIBILITY_PRIVATE +#else +#if __GNUC__ >= 4 +#define CLINGO_VISIBILITY_DEFAULT __attribute__((visibility("default"))) +#define CLINGO_VISIBILITY_PRIVATE __attribute__((visibility("hidden"))) #else -# ifdef CLINGO_WIN -# ifdef CLINGO_BUILD_LIBRARY -# define CLINGO_VISIBILITY_DEFAULT __declspec (dllexport) -# else -# define CLINGO_VISIBILITY_DEFAULT __declspec (dllimport) -# endif -# define CLINGO_VISIBILITY_PRIVATE -# else -# if __GNUC__ >= 4 -# define CLINGO_VISIBILITY_DEFAULT __attribute__ ((visibility ("default"))) -# define CLINGO_VISIBILITY_PRIVATE __attribute__ ((visibility ("hidden"))) -# else -# define CLINGO_VISIBILITY_DEFAULT -# define CLINGO_VISIBILITY_PRIVATE -# endif -# endif +#define CLINGO_VISIBILITY_DEFAULT +#define CLINGO_VISIBILITY_PRIVATE +#endif +#endif #endif #if defined __GNUC__ @@ -131,7 +131,6 @@ typedef struct clingo_weighted_literal { clingo_weight_t weight; } clingo_weighted_literal_t; - //! Enumeration of error codes. //! //! @note Errors can only be recovered from if explicitly mentioned; most @@ -139,11 +138,11 @@ typedef struct clingo_weighted_literal { //! case of errors associated objects cannot be used further. If such an //! object has a free function, this function can and should still be called. enum clingo_error_e { - clingo_error_success = 0, //!< successful API calls - clingo_error_runtime = 1, //!< errors only detectable at runtime like invalid input - clingo_error_logic = 2, //!< wrong usage of the clingo API + clingo_error_success = 0, //!< successful API calls + clingo_error_runtime = 1, //!< errors only detectable at runtime like invalid input + clingo_error_logic = 2, //!< wrong usage of the clingo API clingo_error_bad_alloc = 3, //!< memory could not be allocated - clingo_error_unknown = 4 //!< errors unrelated to clingo + clingo_error_unknown = 4 //!< errors unrelated to clingo }; //! Corresponding type to ::clingo_error_e. typedef int clingo_error_t; @@ -165,12 +164,12 @@ CLINGO_VISIBILITY_DEFAULT void clingo_set_error(clingo_error_t code, char const //! Enumeration of warning codes. enum clingo_warning_e { clingo_warning_operation_undefined = 0, //!< undefined arithmetic operation or weight of aggregate - clingo_warning_runtime_error = 1, //!< to report multiple errors; a corresponding runtime error is raised later - clingo_warning_atom_undefined = 2, //!< undefined atom in program - clingo_warning_file_included = 3, //!< same file included multiple times - clingo_warning_variable_unbounded = 4, //!< CSP variable with unbounded domain - clingo_warning_global_variable = 5, //!< global variable in tuple of aggregate element - clingo_warning_other = 6, //!< other kinds of warnings + clingo_warning_runtime_error = 1, //!< to report multiple errors; a corresponding runtime error is raised later + clingo_warning_atom_undefined = 2, //!< undefined atom in program + clingo_warning_file_included = 3, //!< same file included multiple times + clingo_warning_variable_unbounded = 4, //!< CSP variable with unbounded domain + clingo_warning_global_variable = 5, //!< global variable in tuple of aggregate element + clingo_warning_other = 6, //!< other kinds of warnings }; //! Corresponding type to ::clingo_warning_e. typedef int clingo_warning_t; @@ -196,9 +195,9 @@ CLINGO_VISIBILITY_DEFAULT void clingo_version(int *major, int *minor, int *revis //! Represents three-valued truth values. enum clingo_truth_value_e { - clingo_truth_value_free = 0, //!< no truth value - clingo_truth_value_true = 1, //!< true - clingo_truth_value_false = 2 //!< false + clingo_truth_value_free = 0, //!< no truth value + clingo_truth_value_true = 1, //!< true + clingo_truth_value_false = 2 //!< false }; //! Corresponding type to ::clingo_truth_value_e. typedef int clingo_truth_value_t; @@ -265,7 +264,8 @@ typedef uint64_t clingo_signature_t; //! @param[out] signature the resulting signature //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_signature_create(char const *name, uint32_t arity, bool positive, clingo_signature_t *signature); +CLINGO_VISIBILITY_DEFAULT bool clingo_signature_create(char const *name, uint32_t arity, bool positive, + clingo_signature_t *signature); //! Get the name of a signature. //! //! @note @@ -314,9 +314,9 @@ CLINGO_VISIBILITY_DEFAULT size_t clingo_signature_hash(clingo_signature_t signat //! Enumeration of available symbol types. enum clingo_symbol_type_e { - clingo_symbol_type_infimum = 0, //!< the \#inf symbol - clingo_symbol_type_number = 1, //!< a numeric symbol, e.g., `1` - clingo_symbol_type_string = 4, //!< a string symbol, e.g., `"a"` + clingo_symbol_type_infimum = 0, //!< the \#inf symbol + clingo_symbol_type_number = 1, //!< a numeric symbol, e.g., `1` + clingo_symbol_type_string = 4, //!< a string symbol, e.g., `"a"` clingo_symbol_type_function = 5, //!< a numeric symbol, e.g., `c`, `(1, "a")`, or `f(1,"a")` clingo_symbol_type_supremum = 7 //!< the \#sup symbol }; @@ -374,7 +374,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_symbol_create_id(char const *name, bool po //! @param[out] symbol the resulting symbol //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_symbol_create_function(char const *name, clingo_symbol_t const *arguments, size_t arguments_size, bool positive, clingo_symbol_t *symbol); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbol_create_function(char const *name, clingo_symbol_t const *arguments, + size_t arguments_size, bool positive, + clingo_symbol_t *symbol); //! @} @@ -429,7 +431,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_symbol_is_negative(clingo_symbol_t symbol, //! @param[out] arguments_size the number of arguments //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime if symbol is not of type ::clingo_symbol_type_function -CLINGO_VISIBILITY_DEFAULT bool clingo_symbol_arguments(clingo_symbol_t symbol, clingo_symbol_t const **arguments, size_t *arguments_size); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbol_arguments(clingo_symbol_t symbol, clingo_symbol_t const **arguments, + size_t *arguments_size); //! Get the type of a symbol. //! //! @param[in] symbol the target symbol @@ -505,7 +508,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_add_string(char const *string, char const //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc //! - ::clingo_error_runtime if parsing fails -CLINGO_VISIBILITY_DEFAULT bool clingo_parse_term(char const *string, clingo_logger_t logger, void *logger_data, unsigned message_limit, clingo_symbol_t *symbol); +CLINGO_VISIBILITY_DEFAULT bool clingo_parse_term(char const *string, clingo_logger_t logger, void *logger_data, + unsigned message_limit, clingo_symbol_t *symbol); //! @} @@ -563,13 +567,16 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_size(clingo_symbolic_atoms_ //! @param[in] signature optional signature //! @param[out] iterator the resulting iterator //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_begin(clingo_symbolic_atoms_t const *atoms, clingo_signature_t const *signature, clingo_symbolic_atom_iterator_t *iterator); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_begin(clingo_symbolic_atoms_t const *atoms, + clingo_signature_t const *signature, + clingo_symbolic_atom_iterator_t *iterator); //! Iterator pointing to the end of the sequence of symbolic atoms. //! //! @param[in] atoms the target //! @param[out] iterator the resulting iterator //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_end(clingo_symbolic_atoms_t const *atoms, clingo_symbolic_atom_iterator_t *iterator); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_end(clingo_symbolic_atoms_t const *atoms, + clingo_symbolic_atom_iterator_t *iterator); //! Find a symbolic atom given its symbolic representation. //! //! @param[in] atoms the target @@ -577,7 +584,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_end(clingo_symbolic_atoms_t //! @param[out] iterator iterator pointing to the symbolic atom or to the end //! of the sequence if no corresponding atom is found //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_find(clingo_symbolic_atoms_t const *atoms, clingo_symbol_t symbol, clingo_symbolic_atom_iterator_t *iterator); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_find(clingo_symbolic_atoms_t const *atoms, clingo_symbol_t symbol, + clingo_symbolic_atom_iterator_t *iterator); //! Check if two iterators point to the same element (or end of the sequence). //! //! @param[in] atoms the target @@ -585,14 +593,19 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_find(clingo_symbolic_atoms_ //! @param[in] b the second iterator //! @param[out] equal whether the two iterators are equal //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_iterator_is_equal_to(clingo_symbolic_atoms_t const *atoms, clingo_symbolic_atom_iterator_t a, clingo_symbolic_atom_iterator_t b, bool *equal); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_iterator_is_equal_to(clingo_symbolic_atoms_t const *atoms, + clingo_symbolic_atom_iterator_t a, + clingo_symbolic_atom_iterator_t b, + bool *equal); //! Get the symbolic representation of an atom. //! //! @param[in] atoms the target //! @param[in] iterator iterator to the atom //! @param[out] symbol the resulting symbol //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_symbol(clingo_symbolic_atoms_t const *atoms, clingo_symbolic_atom_iterator_t iterator, clingo_symbol_t *symbol); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_symbol(clingo_symbolic_atoms_t const *atoms, + clingo_symbolic_atom_iterator_t iterator, + clingo_symbol_t *symbol); //! Check whether an atom is a fact. //! //! @note This does not determine if an atom is a cautious consequence. The @@ -603,7 +616,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_symbol(clingo_symbolic_atom //! @param[in] iterator iterator to the atom //! @param[out] fact whether the atom is a fact //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_is_fact(clingo_symbolic_atoms_t const *atoms, clingo_symbolic_atom_iterator_t iterator, bool *fact); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_is_fact(clingo_symbolic_atoms_t const *atoms, + clingo_symbolic_atom_iterator_t iterator, bool *fact); //! Check whether an atom is external. //! //! An atom is external if it has been defined using an external directive and @@ -613,7 +627,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_is_fact(clingo_symbolic_ato //! @param[in] iterator iterator to the atom //! @param[out] external whether the atom is an external //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_is_external(clingo_symbolic_atoms_t const *atoms, clingo_symbolic_atom_iterator_t iterator, bool *external); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_is_external(clingo_symbolic_atoms_t const *atoms, + clingo_symbolic_atom_iterator_t iterator, + bool *external); //! Returns the (numeric) aspif literal corresponding to the given symbolic atom. //! //! Such a literal can be mapped to a solver literal (see the \ref Propagator @@ -624,13 +640,16 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_is_external(clingo_symbolic //! @param[in] iterator iterator to the atom //! @param[out] literal the associated literal //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_literal(clingo_symbolic_atoms_t const *atoms, clingo_symbolic_atom_iterator_t iterator, clingo_literal_t *literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_literal(clingo_symbolic_atoms_t const *atoms, + clingo_symbolic_atom_iterator_t iterator, + clingo_literal_t *literal); //! Get the number of different predicate signatures used in the program. //! //! @param[in] atoms the target //! @param[out] size the number of signatures //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_signatures_size(clingo_symbolic_atoms_t const *atoms, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_signatures_size(clingo_symbolic_atoms_t const *atoms, + size_t *size); //! Get the predicate signatures occurring in a logic program. //! //! @param[in] atoms the target @@ -641,14 +660,17 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_signatures_size(clingo_symb //! - ::clingo_error_runtime if the size is too small //! //! @see clingo_symbolic_atoms_signatures_size() -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_signatures(clingo_symbolic_atoms_t const *atoms, clingo_signature_t *signatures, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_signatures(clingo_symbolic_atoms_t const *atoms, + clingo_signature_t *signatures, size_t size); //! Get an iterator to the next element in the sequence of symbolic atoms. //! //! @param[in] atoms the target //! @param[in] iterator the current iterator //! @param[out] next the succeeding iterator //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_next(clingo_symbolic_atoms_t const *atoms, clingo_symbolic_atom_iterator_t iterator, clingo_symbolic_atom_iterator_t *next); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_next(clingo_symbolic_atoms_t const *atoms, + clingo_symbolic_atom_iterator_t iterator, + clingo_symbolic_atom_iterator_t *next); //! Check whether the given iterator points to some element with the sequence //! of symbolic atoms or to the end of the sequence. //! @@ -657,7 +679,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_next(clingo_symbolic_atoms_ //! @param[out] valid whether the iterator points to some element within the //! sequence //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_is_valid(clingo_symbolic_atoms_t const *atoms, clingo_symbolic_atom_iterator_t iterator, bool *valid); +CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_is_valid(clingo_symbolic_atoms_t const *atoms, + clingo_symbolic_atom_iterator_t iterator, bool *valid); //! Callback function to inject symbols. //! @@ -667,7 +690,7 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_symbolic_atoms_is_valid(clingo_symbolic_at //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc //! @see ::clingo_ground_callback_t -typedef bool (*clingo_symbol_callback_t) (clingo_symbol_t const *symbols, size_t symbols_size, void *data); +typedef bool (*clingo_symbol_callback_t)(clingo_symbol_t const *symbols, size_t symbols_size, void *data); //! @} // {{{1 theory atoms @@ -677,10 +700,10 @@ typedef bool (*clingo_symbol_callback_t) (clingo_symbol_t const *symbols, size_t //! //! @verbatim@endverbatim //! -//! This is a very simple example that uses the @link ProgramBuilder backend@endlink to let theory atoms affect answer sets. -//! In general, the backend can be used to implement a custom theory by translating it to a logic program. -//! On the other hand, a @link Propagator propagator@endlink can be used to implement a custom theory without adding any constraints in advance. -//! Or both approaches can be combined. +//! This is a very simple example that uses the @link ProgramBuilder backend@endlink to let theory atoms affect answer +//! sets. In general, the backend can be used to implement a custom theory by translating it to a logic program. On the +//! other hand, a @link Propagator propagator@endlink can be used to implement a custom theory without adding any +//! constraints in advance. Or both approaches can be combined. //! //! ## Output ## //! @@ -702,8 +725,9 @@ typedef bool (*clingo_symbol_callback_t) (clingo_symbol_t const *symbols, size_t //! The total number of theory atoms can be obtained using clingo_theory_atoms_size(). //! //! @attention -//! All structural information about theory atoms, elements, and terms is reset after @link clingo_control_solve() solving@endlink. -//! If afterward fresh theory atoms are @link clingo_control_ground() grounded@endlink, previously used ids are reused. +//! All structural information about theory atoms, elements, and terms is reset after @link clingo_control_solve() +//! solving@endlink. If afterward fresh theory atoms are @link clingo_control_ground() grounded@endlink, previously used +//! ids are reused. //! //! For an example, see @ref theory-atoms.c. @@ -712,12 +736,12 @@ typedef bool (*clingo_symbol_callback_t) (clingo_symbol_t const *symbols, size_t //! Enumeration of theory term types. enum clingo_theory_term_type_e { - clingo_theory_term_type_tuple = 0, //!< a tuple term, e.g., `(1,2,3)` - clingo_theory_term_type_list = 1, //!< a list term, e.g., `[1,2,3]` - clingo_theory_term_type_set = 2, //!< a set term, e.g., `{1,2,3}` + clingo_theory_term_type_tuple = 0, //!< a tuple term, e.g., `(1,2,3)` + clingo_theory_term_type_list = 1, //!< a list term, e.g., `[1,2,3]` + clingo_theory_term_type_set = 2, //!< a set term, e.g., `{1,2,3}` clingo_theory_term_type_function = 3, //!< a function term, e.g., `f(1,2,3)` - clingo_theory_term_type_number = 4, //!< a number term, e.g., `42` - clingo_theory_term_type_symbol = 5 //!< a symbol term, e.g., `c` + clingo_theory_term_type_number = 4, //!< a number term, e.g., `42` + clingo_theory_term_type_symbol = 5 //!< a symbol term, e.g., `c` }; //! Corresponding type to ::clingo_theory_term_type_e. typedef int clingo_theory_term_type_t; @@ -734,7 +758,8 @@ typedef struct clingo_theory_atoms clingo_theory_atoms_t; //! @param[in] term id of the term //! @param[out] type the resulting type //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_type(clingo_theory_atoms_t const *atoms, clingo_id_t term, clingo_theory_term_type_t *type); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_type(clingo_theory_atoms_t const *atoms, clingo_id_t term, + clingo_theory_term_type_t *type); //! Get the number of the given numeric theory term. //! //! @pre The term must be of type ::clingo_theory_term_type_number. @@ -742,7 +767,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_type(clingo_theory_atoms //! @param[in] term id of the term //! @param[out] number the resulting number //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_number(clingo_theory_atoms_t const *atoms, clingo_id_t term, int *number); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_number(clingo_theory_atoms_t const *atoms, clingo_id_t term, + int *number); //! Get the name of the given constant or function theory term. //! //! @note @@ -753,7 +779,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_number(clingo_theory_ato //! @param[in] term id of the term //! @param[out] name the resulting name //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_name(clingo_theory_atoms_t const *atoms, clingo_id_t term, char const **name); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_name(clingo_theory_atoms_t const *atoms, clingo_id_t term, + char const **name); //! Get the arguments of the given function theory term. //! //! @pre The term must be of type ::clingo_theory_term_type_function. @@ -762,7 +789,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_name(clingo_theory_atoms //! @param[out] arguments the resulting arguments in form of an array of term ids //! @param[out] size the number of arguments //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_arguments(clingo_theory_atoms_t const *atoms, clingo_id_t term, clingo_id_t const **arguments, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_arguments(clingo_theory_atoms_t const *atoms, clingo_id_t term, + clingo_id_t const **arguments, size_t *size); //! Get the size of the string representation of the given theory term (including the terminating 0). //! //! @param[in] atoms container where the term is stored @@ -770,7 +798,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_arguments(clingo_theory_ //! @param[out] size the resulting size //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_to_string_size(clingo_theory_atoms_t const *atoms, clingo_id_t term, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_to_string_size(clingo_theory_atoms_t const *atoms, + clingo_id_t term, size_t *size); //! Get the string representation of the given theory term. //! //! @param[in] atoms container where the term is stored @@ -782,7 +811,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_to_string_size(clingo_th //! - ::clingo_error_bad_alloc //! //! @see clingo_theory_atoms_term_to_string_size() -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_to_string(clingo_theory_atoms_t const *atoms, clingo_id_t term, char *string, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_to_string(clingo_theory_atoms_t const *atoms, clingo_id_t term, + char *string, size_t size); //! @} //! @name Theory Element Inspection @@ -795,7 +825,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_term_to_string(clingo_theory_ //! @param[out] tuple the resulting array of term ids //! @param[out] size the number of term ids //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_tuple(clingo_theory_atoms_t const *atoms, clingo_id_t element, clingo_id_t const **tuple, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_tuple(clingo_theory_atoms_t const *atoms, + clingo_id_t element, clingo_id_t const **tuple, + size_t *size); //! Get the condition (array of aspif literals) of the given theory element. //! //! @param[in] atoms container where the element is stored @@ -803,7 +835,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_tuple(clingo_theory_a //! @param[out] condition the resulting array of aspif literals //! @param[out] size the number of term literals //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_condition(clingo_theory_atoms_t const *atoms, clingo_id_t element, clingo_literal_t const **condition, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_condition(clingo_theory_atoms_t const *atoms, + clingo_id_t element, + clingo_literal_t const **condition, size_t *size); //! Get the id of the condition of the given theory element. //! //! @note @@ -815,7 +849,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_condition(clingo_theo //! @param[in] element id of the element //! @param[out] condition the resulting condition id //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_condition_id(clingo_theory_atoms_t const *atoms, clingo_id_t element, clingo_literal_t *condition); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_condition_id(clingo_theory_atoms_t const *atoms, + clingo_id_t element, + clingo_literal_t *condition); //! Get the size of the string representation of the given theory element (including the terminating 0). //! //! @param[in] atoms container where the element is stored @@ -823,7 +859,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_condition_id(clingo_t //! @param[out] size the resulting size //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_to_string_size(clingo_theory_atoms_t const *atoms, clingo_id_t element, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_to_string_size(clingo_theory_atoms_t const *atoms, + clingo_id_t element, size_t *size); //! Get the string representation of the given theory element. //! //! @param[in] atoms container where the element is stored @@ -833,7 +870,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_to_string_size(clingo //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime if the size is too small //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_to_string(clingo_theory_atoms_t const *atoms, clingo_id_t element, char *string, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_element_to_string(clingo_theory_atoms_t const *atoms, + clingo_id_t element, char *string, size_t size); //! @} //! @name Theory Atom Inspection @@ -851,7 +889,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_size(clingo_theory_atoms_t co //! @param[in] atom id of the atom //! @param[out] term the resulting term id //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_term(clingo_theory_atoms_t const *atoms, clingo_id_t atom, clingo_id_t *term); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_term(clingo_theory_atoms_t const *atoms, clingo_id_t atom, + clingo_id_t *term); //! Get the theory elements associated with the theory atom. //! //! @param[in] atoms container where the atom is stored @@ -859,14 +898,16 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_term(clingo_theory_atoms //! @param[out] elements the resulting array of elements //! @param[out] size the number of elements //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_elements(clingo_theory_atoms_t const *atoms, clingo_id_t atom, clingo_id_t const **elements, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_elements(clingo_theory_atoms_t const *atoms, clingo_id_t atom, + clingo_id_t const **elements, size_t *size); //! Whether the theory atom has a guard. //! //! @param[in] atoms container where the atom is stored //! @param[in] atom id of the atom //! @param[out] has_guard whether the theory atom has a guard //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_has_guard(clingo_theory_atoms_t const *atoms, clingo_id_t atom, bool *has_guard); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_has_guard(clingo_theory_atoms_t const *atoms, clingo_id_t atom, + bool *has_guard); //! Get the guard consisting of a theory operator and a theory term of the given theory atom. //! //! @note @@ -877,14 +918,16 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_has_guard(clingo_theory_ //! @param[out] connective the resulting theory operator //! @param[out] term the resulting term //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_guard(clingo_theory_atoms_t const *atoms, clingo_id_t atom, char const **connective, clingo_id_t *term); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_guard(clingo_theory_atoms_t const *atoms, clingo_id_t atom, + char const **connective, clingo_id_t *term); //! Get the aspif literal associated with the given theory atom. //! //! @param[in] atoms container where the atom is stored //! @param[in] atom id of the atom //! @param[out] literal the resulting literal //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_literal(clingo_theory_atoms_t const *atoms, clingo_id_t atom, clingo_literal_t *literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_literal(clingo_theory_atoms_t const *atoms, clingo_id_t atom, + clingo_literal_t *literal); //! Get the size of the string representation of the given theory atom (including the terminating 0). //! //! @param[in] atoms container where the atom is stored @@ -892,7 +935,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_literal(clingo_theory_at //! @param[out] size the resulting size //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_to_string_size(clingo_theory_atoms_t const *atoms, clingo_id_t atom, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_to_string_size(clingo_theory_atoms_t const *atoms, + clingo_id_t atom, size_t *size); //! Get the string representation of the given theory atom. //! //! @param[in] atoms container where the atom is stored @@ -902,7 +946,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_to_string_size(clingo_th //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime if the size is too small //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_to_string(clingo_theory_atoms_t const *atoms, clingo_id_t atom, char *string, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_to_string(clingo_theory_atoms_t const *atoms, clingo_id_t atom, + char *string, size_t size); //! @} //! @} @@ -935,10 +980,11 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_theory_atoms_atom_to_string(clingo_theory_ //! An assignment assigns truth values to a set of literals. //! A literal is assigned to either @link clingo_assignment_truth_value() true or false, or is unassigned@endlink. //! Furthermore, each assigned literal is associated with a @link clingo_assignment_level() decision level@endlink. -//! There is exactly one @link clingo_assignment_decision() decision literal@endlink for each decision level greater than zero. -//! Assignments to all other literals on the same level are consequences implied by the current and possibly previous decisions. -//! Assignments on level zero are immediate consequences of the current program. -//! Decision levels are consecutive numbers starting with zero up to and including the @link clingo_assignment_decision_level() current decision level@endlink. +//! There is exactly one @link clingo_assignment_decision() decision literal@endlink for each decision level greater +//! than zero. Assignments to all other literals on the same level are consequences implied by the current and possibly +//! previous decisions. Assignments on level zero are immediate consequences of the current program. Decision levels are +//! consecutive numbers starting with zero up to and including the @link clingo_assignment_decision_level() current +//! decision level@endlink. typedef struct clingo_assignment clingo_assignment_t; //! @name Assignment Functions @@ -966,28 +1012,32 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_has_conflict(clingo_assignment_ //! @param[in] assignment the target assignment //! @param[in] literal the literal //! @return whether the literal is valid -CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_has_literal(clingo_assignment_t const *assignment, clingo_literal_t literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_has_literal(clingo_assignment_t const *assignment, + clingo_literal_t literal); //! Determine the decision level of a given literal. //! //! @param[in] assignment the target assignment //! @param[in] literal the literal //! @param[out] level the resulting level //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_level(clingo_assignment_t const *assignment, clingo_literal_t literal, uint32_t *level); +CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_level(clingo_assignment_t const *assignment, clingo_literal_t literal, + uint32_t *level); //! Determine the decision literal given a decision level. //! //! @param[in] assignment the target assignment //! @param[in] level the level //! @param[out] literal the resulting literal //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_decision(clingo_assignment_t const *assignment, uint32_t level, clingo_literal_t *literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_decision(clingo_assignment_t const *assignment, uint32_t level, + clingo_literal_t *literal); //! Check if a literal has a fixed truth value. //! //! @param[in] assignment the target assignment //! @param[in] literal the literal //! @param[out] is_fixed whether the literal is fixed //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_is_fixed(clingo_assignment_t const *assignment, clingo_literal_t literal, bool *is_fixed); +CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_is_fixed(clingo_assignment_t const *assignment, + clingo_literal_t literal, bool *is_fixed); //! Check if a literal is true. //! //! @param[in] assignment the target assignment @@ -995,7 +1045,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_is_fixed(clingo_assignment_t co //! @param[out] is_true whether the literal is true //! @return whether the call was successful //! @see clingo_assignment_truth_value() -CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_is_true(clingo_assignment_t const *assignment, clingo_literal_t literal, bool *is_true); +CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_is_true(clingo_assignment_t const *assignment, + clingo_literal_t literal, bool *is_true); //! Check if a literal has a fixed truth value. //! //! @param[in] assignment the target assignment @@ -1003,14 +1054,16 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_is_true(clingo_assignment_t con //! @param[out] is_false whether the literal is false //! @return whether the call was successful //! @see clingo_assignment_truth_value() -CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_is_false(clingo_assignment_t const *assignment, clingo_literal_t literal, bool *is_false); +CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_is_false(clingo_assignment_t const *assignment, + clingo_literal_t literal, bool *is_false); //! Determine the truth value of a given literal. //! //! @param[in] assignment the target assignment //! @param[in] literal the literal //! @param[out] value the resulting truth value //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_truth_value(clingo_assignment_t const *assignment, clingo_literal_t literal, clingo_truth_value_t *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_truth_value(clingo_assignment_t const *assignment, + clingo_literal_t literal, clingo_truth_value_t *value); //! The number of (positive) literals in the assignment. //! //! @param[in] assignment the target @@ -1022,7 +1075,8 @@ CLINGO_VISIBILITY_DEFAULT size_t clingo_assignment_size(clingo_assignment_t cons //! @param[in] offset the offset of the literal //! @param[out] literal the literal //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_at(clingo_assignment_t const *assignment, size_t offset, clingo_literal_t *literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_at(clingo_assignment_t const *assignment, size_t offset, + clingo_literal_t *literal); //! Check if the assignment is total, i.e. there are no free literal. //! //! @param[in] assignment the target @@ -1047,7 +1101,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_trail_size(clingo_assignment_t //! @param[in] level the decision level //! @param[out] offset the offset of the decision literal //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_trail_begin(clingo_assignment_t const *assignment, uint32_t level, uint32_t *offset); +CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_trail_begin(clingo_assignment_t const *assignment, uint32_t level, + uint32_t *offset); //! Returns the offset following the last literal with the given decision level. //! //! @note This function is the counterpart to clingo_assignment_trail_begin(). @@ -1056,14 +1111,16 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_trail_begin(clingo_assignment_t //! @param[in] level the decision level //! @param[out] offset the offset //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_trail_end(clingo_assignment_t const *assignment, uint32_t level, uint32_t *offset); +CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_trail_end(clingo_assignment_t const *assignment, uint32_t level, + uint32_t *offset); //! Returns the literal at the given position in the trail. //! //! @param[in] assignment the target //! @param[in] offset the offset of the literal //! @param[out] literal the literal //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_trail_at(clingo_assignment_t const *assignment, uint32_t offset, clingo_literal_t *literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_trail_at(clingo_assignment_t const *assignment, uint32_t offset, + clingo_literal_t *literal); //! @} @@ -1072,41 +1129,43 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_assignment_trail_at(clingo_assignment_t co //! Note that total checks are subject to the lock when a model is found. //! This means that information from previously found models can be used to discard assignments in check calls. enum clingo_propagator_check_mode_e { - clingo_propagator_check_mode_none = 0, //!< do not call @ref ::clingo_propagator::check() at all - clingo_propagator_check_mode_total = 1, //!< call @ref ::clingo_propagator::check() on total assignments + clingo_propagator_check_mode_none = 0, //!< do not call @ref ::clingo_propagator::check() at all + clingo_propagator_check_mode_total = 1, //!< call @ref ::clingo_propagator::check() on total assignments clingo_propagator_check_mode_fixpoint = 2, //!< call @ref ::clingo_propagator::check() on propagation fixpoints - clingo_propagator_check_mode_both = 3, //!< call @ref ::clingo_propagator::check() on propagation fixpoints and total assignments + clingo_propagator_check_mode_both = + 3, //!< call @ref ::clingo_propagator::check() on propagation fixpoints and total assignments }; //! Corresponding type to ::clingo_propagator_check_mode_e. typedef int clingo_propagator_check_mode_t; //! Undo modes for propagators. enum clingo_propagator_undo_mode_e { - clingo_propagator_undo_mode_default = 0, //!< call @ref ::clingo_propagator::undo() for non-empty change lists - clingo_propagator_undo_mode_always = 1, //!< also call @ref ::clingo_propagator::check() when check has been called + clingo_propagator_undo_mode_default = 0, //!< call @ref ::clingo_propagator::undo() for non-empty change lists + clingo_propagator_undo_mode_always = 1, //!< also call @ref ::clingo_propagator::check() when check has been called }; //! Corresponding type to ::clingo_propagator_undo_mode_e. typedef int clingo_propagator_undo_mode_t; - //! Enumeration of weight_constraint_types. enum clingo_weight_constraint_type_e { - clingo_weight_constraint_type_implication_left = -1, //!< the weight constraint implies the literal - clingo_weight_constraint_type_implication_right = 1, //!< the literal implies the weight constraint - clingo_weight_constraint_type_equivalence = 0, //!< the weight constraint is equivalent to the literal + clingo_weight_constraint_type_implication_left = -1, //!< the weight constraint implies the literal + clingo_weight_constraint_type_implication_right = 1, //!< the literal implies the weight constraint + clingo_weight_constraint_type_equivalence = 0, //!< the weight constraint is equivalent to the literal }; //! Corresponding type to ::clingo_weight_constraint_type_e. typedef int clingo_weight_constraint_type_t; //! Object to initialize a user-defined propagator before each solving step. //! -//! Each @link SymbolicAtoms symbolic@endlink or @link TheoryAtoms theory atom@endlink is uniquely associated with an aspif atom in form of a positive integer (@ref ::clingo_literal_t). -//! Aspif literals additionally are signed to represent default negation. -//! Furthermore, there are non-zero integer solver literals (also represented using @ref ::clingo_literal_t). -//! There is a surjective mapping from program atoms to solver literals. +//! Each @link SymbolicAtoms symbolic@endlink or @link TheoryAtoms theory atom@endlink is uniquely associated with an +//! aspif atom in form of a positive integer (@ref ::clingo_literal_t). Aspif literals additionally are signed to +//! represent default negation. Furthermore, there are non-zero integer solver literals (also represented using @ref +//! ::clingo_literal_t). There is a surjective mapping from program atoms to solver literals. //! -//! All methods called during propagation use solver literals whereas clingo_symbolic_atoms_literal() and clingo_theory_atoms_atom_literal() return program literals. -//! The function clingo_propagate_init_solver_literal() can be used to map program literals or @link clingo_theory_atoms_element_condition_id() condition ids@endlink to solver literals. +//! All methods called during propagation use solver literals whereas clingo_symbolic_atoms_literal() and +//! clingo_theory_atoms_atom_literal() return program literals. The function clingo_propagate_init_solver_literal() can +//! be used to map program literals or @link clingo_theory_atoms_element_condition_id() condition ids@endlink to solver +//! literals. typedef struct clingo_propagate_init clingo_propagate_init_t; //! @name Initialization Functions @@ -1118,55 +1177,67 @@ typedef struct clingo_propagate_init clingo_propagate_init_t; //! @param[in] aspif_literal the aspif literal to map //! @param[out] solver_literal the resulting solver literal //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_solver_literal(clingo_propagate_init_t const *init, clingo_literal_t aspif_literal, clingo_literal_t *solver_literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_solver_literal(clingo_propagate_init_t const *init, + clingo_literal_t aspif_literal, + clingo_literal_t *solver_literal); //! Add a watch for the solver literal in the given phase. //! //! @param[in] init the target //! @param[in] solver_literal the solver literal //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_watch(clingo_propagate_init_t *init, clingo_literal_t solver_literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_watch(clingo_propagate_init_t *init, + clingo_literal_t solver_literal); //! Add a watch for the solver literal in the given phase to the given solver thread. //! //! @param[in] init the target //! @param[in] solver_literal the solver literal //! @param[in] thread_id the id of the solver thread //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_watch_to_thread(clingo_propagate_init_t *init, clingo_literal_t solver_literal, clingo_id_t thread_id); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_watch_to_thread(clingo_propagate_init_t *init, + clingo_literal_t solver_literal, + clingo_id_t thread_id); //! Remove the watch for the solver literal in the given phase. //! //! @param[in] init the target //! @param[in] solver_literal the solver literal //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_remove_watch(clingo_propagate_init_t *init, clingo_literal_t solver_literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_remove_watch(clingo_propagate_init_t *init, + clingo_literal_t solver_literal); //! Remove the watch for the solver literal in the given phase from the given solver thread. //! //! @param[in] init the target //! @param[in] solver_literal the solver literal //! @param[in] thread_id the id of the solver thread //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_remove_watch_from_thread(clingo_propagate_init_t *init, clingo_literal_t solver_literal, uint32_t thread_id); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_remove_watch_from_thread(clingo_propagate_init_t *init, + clingo_literal_t solver_literal, + uint32_t thread_id); //! Freeze the given solver literal. //! -//! Any solver literal that is not frozen is subject to simplification and might be removed in a preprocessing step after propagator initialization. -//! A propagator should freeze all literals over which it might add clauses during propagation. -//! Note that any watched literal is automatically frozen and that it does not matter which phase of the literal is frozen. +//! Any solver literal that is not frozen is subject to simplification and might be removed in a preprocessing step +//! after propagator initialization. A propagator should freeze all literals over which it might add clauses during +//! propagation. Note that any watched literal is automatically frozen and that it does not matter which phase of the +//! literal is frozen. //! //! @param[in] init the target //! @param[in] solver_literal the solver literal //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_freeze_literal(clingo_propagate_init_t *init, clingo_literal_t solver_literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_freeze_literal(clingo_propagate_init_t *init, + clingo_literal_t solver_literal); //! Get an object to inspect the symbolic atoms. //! //! @param[in] init the target //! @param[out] atoms the resulting object //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_symbolic_atoms(clingo_propagate_init_t const *init, clingo_symbolic_atoms_t const **atoms); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_symbolic_atoms(clingo_propagate_init_t const *init, + clingo_symbolic_atoms_t const **atoms); //! Get an object to inspect the theory atoms. //! //! @param[in] init the target //! @param[out] atoms the resulting object //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_theory_atoms(clingo_propagate_init_t const *init, clingo_theory_atoms_t const **atoms); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_theory_atoms(clingo_propagate_init_t const *init, + clingo_theory_atoms_t const **atoms); //! Get the number of threads used in subsequent solving. //! //! @param[in] init the target @@ -1178,45 +1249,52 @@ CLINGO_VISIBILITY_DEFAULT int clingo_propagate_init_number_of_threads(clingo_pro //! @param[in] init the target //! @param[in] mode bitmask when to call the propagator //! @see @ref ::clingo_propagator::check() -CLINGO_VISIBILITY_DEFAULT void clingo_propagate_init_set_check_mode(clingo_propagate_init_t *init, clingo_propagator_check_mode_t mode); +CLINGO_VISIBILITY_DEFAULT void clingo_propagate_init_set_check_mode(clingo_propagate_init_t *init, + clingo_propagator_check_mode_t mode); //! Get the current check mode of the propagator. //! //! @param[in] init the target //! @see clingo_propagate_init_set_check_mode() -CLINGO_VISIBILITY_DEFAULT clingo_propagator_check_mode_t clingo_propagate_init_get_check_mode(clingo_propagate_init_t const *init); +CLINGO_VISIBILITY_DEFAULT clingo_propagator_check_mode_t +clingo_propagate_init_get_check_mode(clingo_propagate_init_t const *init); //! Configure when to call the undo method of the propagator. //! //! @param[in] init the target //! @param[in] mode when to call the propagator //! @see @ref ::clingo_propagator::check() -CLINGO_VISIBILITY_DEFAULT void clingo_propagate_init_set_undo_mode(clingo_propagate_init_t *init, clingo_propagator_undo_mode_t mode); +CLINGO_VISIBILITY_DEFAULT void clingo_propagate_init_set_undo_mode(clingo_propagate_init_t *init, + clingo_propagator_undo_mode_t mode); //! Get the current undo mode of the propagator. //! //! @param[in] init the target //! @see clingo_propagate_init_set_undo_mode() -CLINGO_VISIBILITY_DEFAULT clingo_propagator_undo_mode_t clingo_propagate_init_get_undo_mode(clingo_propagate_init_t const *init); +CLINGO_VISIBILITY_DEFAULT clingo_propagator_undo_mode_t +clingo_propagate_init_get_undo_mode(clingo_propagate_init_t const *init); //! Get the top level assignment solver. //! //! @param[in] init the target //! @return the assignment -CLINGO_VISIBILITY_DEFAULT clingo_assignment_t const *clingo_propagate_init_assignment(clingo_propagate_init_t const *init); +CLINGO_VISIBILITY_DEFAULT clingo_assignment_t const * +clingo_propagate_init_assignment(clingo_propagate_init_t const *init); //! Add a literal to the solver. //! //! To be able to use the variable in clauses during propagation or add watches to it, it has to be frozen. //! Otherwise, it might be removed during preprocessing. //! -//! @attention If variables were added, subsequent calls to functions adding constraints or ::clingo_propagate_init_propagate() are expensive. -//! It is best to add variables in batches. +//! @attention If variables were added, subsequent calls to functions adding constraints or +//! ::clingo_propagate_init_propagate() are expensive. It is best to add variables in batches. //! //! @param[in] init the target //! @param[in] freeze whether to freeze the literal //! @param[out] result the added literal //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_literal(clingo_propagate_init_t *init, bool freeze, clingo_literal_t *result); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_literal(clingo_propagate_init_t *init, bool freeze, + clingo_literal_t *result); //! Add the given clause to the solver. //! -//! @attention No further calls on the init object or functions on the assignment should be called when the result of this method is false. +//! @attention No further calls on the init object or functions on the assignment should be called when the result of +//! this method is false. //! //! @param[in] init the target //! @param[in] clause the clause to add @@ -1224,13 +1302,17 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_literal(clingo_propagat //! @param[out] result result indicating whether the problem became unsatisfiable //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_clause(clingo_propagate_init_t *init, clingo_literal_t const *clause, size_t size, bool *result); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_clause(clingo_propagate_init_t *init, + clingo_literal_t const *clause, size_t size, + bool *result); //! Add the given weight constraint to the solver. //! -//! This function adds a constraint of form `literal <=> { lit=weight | (lit, weight) in literals } >= bound` to the solver. -//! Depending on the type the `<=>` connective can be either a left implication, right implication, or equivalence. +//! This function adds a constraint of form `literal <=> { lit=weight | (lit, weight) in literals } >= bound` to the +//! solver. Depending on the type the `<=>` connective can be either a left implication, right implication, or +//! equivalence. //! -//! @attention No further calls on the init object or functions on the assignment should be called when the result of this method is false. +//! @attention No further calls on the init object or functions on the assignment should be called when the result of +//! this method is false. //! //! @param[in] init the target //! @param[in] literal the literal of the constraint @@ -1242,7 +1324,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_clause(clingo_propagate //! @param[out] result result indicating whether the problem became unsatisfiable //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_weight_constraint(clingo_propagate_init_t *init, clingo_literal_t literal, clingo_weighted_literal_t const *literals, size_t size, clingo_weight_t bound, clingo_weight_constraint_type_t type, bool compare_equal, bool *result); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_weight_constraint( + clingo_propagate_init_t *init, clingo_literal_t literal, clingo_weighted_literal_t const *literals, size_t size, + clingo_weight_t bound, clingo_weight_constraint_type_t type, bool compare_equal, bool *result); //! Add the given literal to minimize to the solver. //! //! This corresponds to a weak constraint of form `:~ literal. [weight@priority]`. @@ -1253,11 +1337,14 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_weight_constraint(cling //! @param[in] priority the priority of the literal //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_minimize(clingo_propagate_init_t *init, clingo_literal_t literal, clingo_weight_t weight, clingo_weight_t priority); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_add_minimize(clingo_propagate_init_t *init, + clingo_literal_t literal, clingo_weight_t weight, + clingo_weight_t priority); //! Propagates consequences of the underlying problem excluding registered propagators. //! //! @note The function has no effect if SAT-preprocessing is enabled. -//! @attention No further calls on the init object or functions on the assignment should be called when the result of this method is false. +//! @attention No further calls on the init object or functions on the assignment should be called when the result of +//! this method is false. //! //! @param[in] init the target //! @param[out] result result indicating whether the problem became unsatisfiable @@ -1272,10 +1359,12 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_init_propagate(clingo_propagate_ //! Clauses in the solver are either cleaned up based on a configurable deletion policy or at the end of a solving step. //! The values of this enumeration determine if a clause is subject to one of the above deletion strategies. enum clingo_clause_type_e { - clingo_clause_type_learnt = 0, //!< clause is subject to the solvers deletion policy - clingo_clause_type_static = 1, //!< clause is not subject to the solvers deletion policy - clingo_clause_type_volatile = 2, //!< like ::clingo_clause_type_learnt but the clause is deleted after a solving step - clingo_clause_type_volatile_static = 3 //!< like ::clingo_clause_type_static but the clause is deleted after a solving step + clingo_clause_type_learnt = 0, //!< clause is subject to the solvers deletion policy + clingo_clause_type_static = 1, //!< clause is not subject to the solvers deletion policy + clingo_clause_type_volatile = + 2, //!< like ::clingo_clause_type_learnt but the clause is deleted after a solving step + clingo_clause_type_volatile_static = + 3 //!< like ::clingo_clause_type_static but the clause is deleted after a solving step }; //! Corresponding type to ::clingo_clause_type_e. typedef int clingo_clause_type_t; @@ -1297,7 +1386,8 @@ CLINGO_VISIBILITY_DEFAULT clingo_id_t clingo_propagate_control_thread_id(clingo_ //! //! @param[in] control the target //! @return the assignment -CLINGO_VISIBILITY_DEFAULT clingo_assignment_t const *clingo_propagate_control_assignment(clingo_propagate_control_t const *control); +CLINGO_VISIBILITY_DEFAULT clingo_assignment_t const * +clingo_propagate_control_assignment(clingo_propagate_control_t const *control); //! Adds a new volatile literal to the underlying solver thread. //! //! @attention The literal is only valid within the current solving step and solver thread. @@ -1308,10 +1398,12 @@ CLINGO_VISIBILITY_DEFAULT clingo_assignment_t const *clingo_propagate_control_as //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc //! - ::clingo_error_logic if the assignment is conflicting -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_control_add_literal(clingo_propagate_control_t *control, clingo_literal_t *result); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_control_add_literal(clingo_propagate_control_t *control, + clingo_literal_t *result); //! Add a watch for the solver literal in the given phase. //! -//! @note Unlike @ref clingo_propagate_init_add_watch() this does not add a watch to all solver threads but just the current one. +//! @note Unlike @ref clingo_propagate_init_add_watch() this does not add a watch to all solver threads but just the +//! current one. //! //! @param[in] control the target //! @param[in] literal the literal to watch @@ -1319,26 +1411,30 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_control_add_literal(clingo_propa //! - ::clingo_error_bad_alloc //! - ::clingo_error_logic if the literal is invalid //! @see clingo_propagate_control_remove_watch() -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_control_add_watch(clingo_propagate_control_t *control, clingo_literal_t literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_control_add_watch(clingo_propagate_control_t *control, + clingo_literal_t literal); //! Check whether a literal is watched in the current solver thread. //! //! @param[in] control the target //! @param[in] literal the literal to check //! //! @return whether the literal is watched -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_control_has_watch(clingo_propagate_control_t const *control, clingo_literal_t literal); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_control_has_watch(clingo_propagate_control_t const *control, + clingo_literal_t literal); //! Removes the watch (if any) for the given solver literal. //! //! @note Similar to @ref clingo_propagate_init_add_watch() this just removes the watch in the current solver thread. //! //! @param[in] control the target //! @param[in] literal the literal to remove -CLINGO_VISIBILITY_DEFAULT void clingo_propagate_control_remove_watch(clingo_propagate_control_t *control, clingo_literal_t literal); +CLINGO_VISIBILITY_DEFAULT void clingo_propagate_control_remove_watch(clingo_propagate_control_t *control, + clingo_literal_t literal); //! Add the given clause to the solver. //! //! This method sets its result to false if the current propagation must be stopped for the solver to backtrack. //! -//! @attention No further calls on the control object or functions on the assignment should be called when the result of this method is false. +//! @attention No further calls on the control object or functions on the assignment should be called when the result of +//! this method is false. //! //! @param[in] control the target //! @param[in] clause the clause to add @@ -1347,12 +1443,15 @@ CLINGO_VISIBILITY_DEFAULT void clingo_propagate_control_remove_watch(clingo_prop //! @param[out] result result indicating whether propagation has to be stopped //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_control_add_clause(clingo_propagate_control_t *control, clingo_literal_t const *clause, size_t size, clingo_clause_type_t type, bool *result); +CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_control_add_clause(clingo_propagate_control_t *control, + clingo_literal_t const *clause, size_t size, + clingo_clause_type_t type, bool *result); //! Propagate implied literals (resulting from added clauses). //! //! This method sets its result to false if the current propagation must be stopped for the solver to backtrack. //! -//! @attention No further calls on the control object or functions on the assignment should be called when the result of this method is false. +//! @attention No further calls on the control object or functions on the assignment should be called when the result of +//! this method is false. //! //! @param[in] control the target //! @param[out] result result indicating whether propagation has to be stopped @@ -1363,16 +1462,18 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_propagate_control_propagate(clingo_propaga //! @} //! Typedef for @ref ::clingo_propagator::init(). -typedef bool (*clingo_propagator_init_callback_t) (clingo_propagate_init_t *, void *); +typedef bool (*clingo_propagator_init_callback_t)(clingo_propagate_init_t *, void *); //! Typedef for @ref ::clingo_propagator::propagate(). -typedef bool (*clingo_propagator_propagate_callback_t) (clingo_propagate_control_t *, clingo_literal_t const *, size_t, void *); +typedef bool (*clingo_propagator_propagate_callback_t)(clingo_propagate_control_t *, clingo_literal_t const *, size_t, + void *); //! Typedef for @ref ::clingo_propagator::undo(). -typedef void (*clingo_propagator_undo_callback_t) (clingo_propagate_control_t const *, clingo_literal_t const *, size_t, void *); +typedef void (*clingo_propagator_undo_callback_t)(clingo_propagate_control_t const *, clingo_literal_t const *, size_t, + void *); //! Typedef for @ref ::clingo_propagator::check(). -typedef bool (*clingo_propagator_check_callback_t) (clingo_propagate_control_t *, void *); +typedef bool (*clingo_propagator_check_callback_t)(clingo_propagate_control_t *, void *); //! An instance of this struct has to be registered with a solver to implement a custom propagator. //! @@ -1380,7 +1481,8 @@ typedef bool (*clingo_propagator_check_callback_t) (clingo_propagate_control_t * //! @see Propagator typedef struct clingo_propagator { //! This function is called once before each solving step. - //! It is used to map relevant program literals to solver literals, add watches for solver literals, and initialize the data structures used during propagation. + //! It is used to map relevant program literals to solver literals, add watches for solver literals, and initialize + //! the data structures used during propagation. //! //! @note This is the last point to access symbolic and theory atoms. //! Once the search has started, they are no longer accessible. @@ -1389,19 +1491,20 @@ typedef struct clingo_propagator { //! @param[in] data user data for the callback //! @return whether the call was successful //! @see ::clingo_propagator_init_callback_t - bool (*init) (clingo_propagate_init_t *init, void *data); + bool (*init)(clingo_propagate_init_t *init, void *data); //! Can be used to propagate solver literals given a @link clingo_assignment_t partial assignment@endlink. //! - //! Called during propagation with a non-empty array of @link clingo_propagate_init_add_watch() watched solver literals@endlink - //! that have been assigned to true since the last call to either propagate, undo, (or the start of the search) - the change set. - //! Only watched solver literals are contained in the change set. - //! Each literal in the change set is true w.r.t. the current @link clingo_assignment_t assignment@endlink. + //! Called during propagation with a non-empty array of @link clingo_propagate_init_add_watch() watched solver + //! literals@endlink that have been assigned to true since the last call to either propagate, undo, (or the start of + //! the search) - the change set. Only watched solver literals are contained in the change set. Each literal in the + //! change set is true w.r.t. the current @link clingo_assignment_t assignment@endlink. //! @ref clingo_propagate_control_add_clause() can be used to add clauses. //! If a clause is unit resulting, it can be propagated using @ref clingo_propagate_control_propagate(). //! If the result of either of the two methods is false, the propagate function must return immediately. //! - //! The following snippet shows how to use the methods to add clauses and propagate consequences within the callback. - //! The important point is to return true (true to indicate there was no error) if the result of either of the methods is false. + //! The following snippet shows how to use the methods to add clauses and propagate consequences within the + //! callback. The important point is to return true (true to indicate there was no error) if the result of either of + //! the methods is false. //! ~~~~~~~~~~~~~~~{.c} //! bool result; //! clingo_literal_t clause[] = { ... }; @@ -1421,7 +1524,8 @@ typedef struct clingo_propagator { //! //! @note //! This function can be called from different solving threads. - //! Each thread has its own assignment and id, which can be obtained using @ref clingo_propagate_control_thread_id(). + //! Each thread has its own assignment and id, which can be obtained using @ref + //! clingo_propagate_control_thread_id(). //! //! @param[in] control control object for the target solver //! @param[in] changes the change set @@ -1429,7 +1533,7 @@ typedef struct clingo_propagator { //! @param[in] data user data for the callback //! @return whether the call was successful //! @see ::clingo_propagator_propagate_callback_t - bool (*propagate) (clingo_propagate_control_t *control, clingo_literal_t const *changes, size_t size, void *data); + bool (*propagate)(clingo_propagate_control_t *control, clingo_literal_t const *changes, size_t size, void *data); //! Called whenever a solver undoes assignments to watched solver literals. //! //! This callback is meant to update assignment dependent state in the propagator. @@ -1442,10 +1546,12 @@ typedef struct clingo_propagator { //! @param[in] data user data for the callback //! @return whether the call was successful //! @see ::clingo_propagator_undo_callback_t - void (*undo) (clingo_propagate_control_t const *control, clingo_literal_t const *changes, size_t size, void *data); - //! This function is similar to @ref clingo_propagate_control_propagate() but is called without a change set on propagation fixpoints. + void (*undo)(clingo_propagate_control_t const *control, clingo_literal_t const *changes, size_t size, void *data); + //! This function is similar to @ref clingo_propagate_control_propagate() but is called without a change set on + //! propagation fixpoints. //! - //! When exactly this function is called, can be configured using the @ref clingo_propagate_init_set_check_mode() function. + //! When exactly this function is called, can be configured using the @ref clingo_propagate_init_set_check_mode() + //! function. //! //! @note This function is called even if no watches have been added. //! @@ -1453,7 +1559,7 @@ typedef struct clingo_propagator { //! @param[in] data user data for the callback //! @return whether the call was successful //! @see ::clingo_propagator_check_callback_t - bool (*check) (clingo_propagate_control_t *control, void *data); + bool (*check)(clingo_propagate_control_t *control, void *data); //! This function allows a propagator to implement domain-specific heuristics. //! //! It is called whenever propagation reaches a fixed point and @@ -1467,7 +1573,8 @@ typedef struct clingo_propagator { //! @param[in] fallback the literal chosen by the solver's heuristic //! @param[out] decision the literal to make true //! @return whether the call was successful - bool (*decide) (clingo_id_t thread_id, clingo_assignment_t const *assignment, clingo_literal_t fallback, void *data, clingo_literal_t *decision); + bool (*decide)(clingo_id_t thread_id, clingo_assignment_t const *assignment, clingo_literal_t fallback, void *data, + clingo_literal_t *decision); } clingo_propagator_t; //! @} @@ -1511,8 +1618,8 @@ typedef int clingo_comment_type_t; //! Enumeration of theory sequence types. enum clingo_theory_sequence_type_e { clingo_theory_sequence_type_tuple = 0, //!< Theory tuples "(t1,...,tn)". - clingo_theory_sequence_type_set = 1, //!< Theory sets "{t1,...,tn}". - clingo_theory_sequence_type_list = 2 //!< Theory lists "[t1,...,tn]". + clingo_theory_sequence_type_set = 1, //!< Theory sets "{t1,...,tn}". + clingo_theory_sequence_type_list = 2 //!< Theory lists "[t1,...,tn]". }; //! Corresponding type to ::clingo_theory_sequence_type_e. typedef int clingo_theory_sequence_type_t; @@ -1520,12 +1627,12 @@ typedef int clingo_theory_sequence_type_t; //! Enumeration of different heuristic modifiers. //! @ingroup ProgramInspection enum clingo_heuristic_type_e { - clingo_heuristic_type_level = 0, //!< set the level of an atom - clingo_heuristic_type_sign = 1, //!< configure which sign to chose for an atom + clingo_heuristic_type_level = 0, //!< set the level of an atom + clingo_heuristic_type_sign = 1, //!< configure which sign to chose for an atom clingo_heuristic_type_factor = 2, //!< modify VSIDS factor of an atom - clingo_heuristic_type_init = 3, //!< modify the initial VSIDS score of an atom - clingo_heuristic_type_true = 4, //!< set the level of an atom and choose a positive sign - clingo_heuristic_type_false = 5 //!< set the level of an atom and choose a negative sign + clingo_heuristic_type_init = 3, //!< modify the initial VSIDS score of an atom + clingo_heuristic_type_true = 4, //!< set the level of an atom and choose a positive sign + clingo_heuristic_type_false = 5 //!< set the level of an atom and choose a negative sign }; //! Corresponding type to ::clingo_heuristic_type_e. //! @ingroup ProgramInspection @@ -1534,9 +1641,9 @@ typedef int clingo_heuristic_type_t; //! Enumeration of different external statements. //! @ingroup ProgramInspection enum clingo_external_type_e { - clingo_external_type_free = 0, //!< allow an external to be assigned freely - clingo_external_type_true = 1, //!< assign an external to true - clingo_external_type_false = 2, //!< assign an external to false + clingo_external_type_free = 0, //!< allow an external to be assigned freely + clingo_external_type_true = 1, //!< assign an external to true + clingo_external_type_false = 2, //!< assign an external to false clingo_external_type_release = 3, //!< no longer treat an atom as external }; //! Corresponding type to ::clingo_external_type_e. @@ -1570,7 +1677,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_end(clingo_backend_t *backend); //! @param[in] body_size the number of literals in the body //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_rule(clingo_backend_t *backend, bool choice, clingo_atom_t const *head, size_t head_size, clingo_literal_t const *body, size_t body_size); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_rule(clingo_backend_t *backend, bool choice, clingo_atom_t const *head, + size_t head_size, clingo_literal_t const *body, size_t body_size); //! Add a weight rule to the program. //! //! @attention All weights and the lower bound must be positive. @@ -1583,7 +1691,10 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_rule(clingo_backend_t *backend, bo //! @param[in] body_size the number of weighted literals in the body //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_weight_rule(clingo_backend_t *backend, bool choice, clingo_atom_t const *head, size_t head_size, clingo_weight_t lower_bound, clingo_weighted_literal_t const *body, size_t body_size); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_weight_rule(clingo_backend_t *backend, bool choice, + clingo_atom_t const *head, size_t head_size, + clingo_weight_t lower_bound, + clingo_weighted_literal_t const *body, size_t body_size); //! Add a minimize constraint (or weak constraint) to the program. //! //! @param[in] backend the target backend @@ -1592,7 +1703,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_weight_rule(clingo_backend_t *back //! @param[in] size the number of weighted literals //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_minimize(clingo_backend_t *backend, clingo_weight_t priority, clingo_weighted_literal_t const* literals, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_minimize(clingo_backend_t *backend, clingo_weight_t priority, + clingo_weighted_literal_t const *literals, size_t size); //! Add a projection directive. //! //! @param[in] backend the target backend @@ -1600,7 +1712,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_minimize(clingo_backend_t *backend //! @param[in] size the number of atoms //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_project(clingo_backend_t *backend, clingo_atom_t const *atoms, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_project(clingo_backend_t *backend, clingo_atom_t const *atoms, + size_t size); //! Add an external statement. //! //! @param[in] backend the target backend @@ -1608,15 +1721,18 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_project(clingo_backend_t *backend, //! @param[in] type the type of the external statement //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_external(clingo_backend_t *backend, clingo_atom_t atom, clingo_external_type_t type); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_external(clingo_backend_t *backend, clingo_atom_t atom, + clingo_external_type_t type); //! Add an assumption directive. //! //! @param[in] backend the target backend -//! @param[in] literals the literals to assume (positive literals are true and negative literals false for the next solve call) +//! @param[in] literals the literals to assume (positive literals are true and negative literals false for the next +//! solve call) //! @param[in] size the number of atoms //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_assume(clingo_backend_t *backend, clingo_literal_t const *literals, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_assume(clingo_backend_t *backend, clingo_literal_t const *literals, + size_t size); //! Add a heuristic directive. //! //! @param[in] backend the target backend @@ -1628,7 +1744,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_assume(clingo_backend_t *backend, //! @param[in] size the number of atoms in the condition //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_heuristic(clingo_backend_t *backend, clingo_atom_t atom, clingo_heuristic_type_t type, int bias, unsigned priority, clingo_literal_t const *condition, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_heuristic(clingo_backend_t *backend, clingo_atom_t atom, + clingo_heuristic_type_t type, int bias, unsigned priority, + clingo_literal_t const *condition, size_t size); //! Add an edge directive. //! //! @param[in] backend the target backend @@ -1638,14 +1756,16 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_heuristic(clingo_backend_t *backen //! @param[in] size the number of atoms in the condition //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_acyc_edge(clingo_backend_t *backend, int node_u, int node_v, clingo_literal_t const *condition, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_acyc_edge(clingo_backend_t *backend, int node_u, int node_v, + clingo_literal_t const *condition, size_t size); //! Get a fresh atom to be used in aspif directives. //! //! @param[in] backend the target backend //! @param[in] symbol optional symbol to associate the atom with //! @param[out] atom the resulting atom //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_add_atom(clingo_backend_t *backend, clingo_symbol_t *symbol, clingo_atom_t *atom); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_add_atom(clingo_backend_t *backend, clingo_symbol_t *symbol, + clingo_atom_t *atom); //! Add a numeric theory term. //! //! @param[in] backend the target backend @@ -1653,7 +1773,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_add_atom(clingo_backend_t *backend //! @param[out] term_id the resulting term id //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_number(clingo_backend_t *backend, int number, clingo_id_t *term_id); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_number(clingo_backend_t *backend, int number, + clingo_id_t *term_id); //! Add a theory term representing a string. //! //! @param[in] backend the target backend @@ -1661,7 +1782,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_number(clingo_backend_ //! @param[out] term_id the resulting term id //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_string(clingo_backend_t *backend, char const *string, clingo_id_t *term_id); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_string(clingo_backend_t *backend, char const *string, + clingo_id_t *term_id); //! Add a theory term representing a sequence of theory terms. //! //! @param[in] backend the target backend @@ -1671,7 +1793,10 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_string(clingo_backend_ //! @param[out] term_id the resulting term id //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_sequence(clingo_backend_t *backend, clingo_theory_sequence_type_t type, clingo_id_t const *arguments, size_t size, clingo_id_t *term_id); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_sequence(clingo_backend_t *backend, + clingo_theory_sequence_type_t type, + clingo_id_t const *arguments, size_t size, + clingo_id_t *term_id); //! Add a theory term representing a function. //! //! @param[in] backend the target backend @@ -1681,7 +1806,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_sequence(clingo_backen //! @param[out] term_id the resulting term id //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_function(clingo_backend_t *backend, char const *name, clingo_id_t const *arguments, size_t size, clingo_id_t *term_id); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_function(clingo_backend_t *backend, char const *name, + clingo_id_t const *arguments, size_t size, + clingo_id_t *term_id); //! Convert the given symbol into a theory term. //! //! @param[in] backend the target backend @@ -1689,7 +1816,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_function(clingo_backen //! @param[out] term_id the resulting term id //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_symbol(clingo_backend_t *backend, clingo_symbol_t symbol, clingo_id_t *term_id); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_symbol(clingo_backend_t *backend, clingo_symbol_t symbol, + clingo_id_t *term_id); //! Add a theory atom element. //! //! @param[in] backend the target backend @@ -1700,7 +1828,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_term_symbol(clingo_backend_ //! @param[out] element_id the resulting element id //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_element(clingo_backend_t *backend, clingo_id_t const *tuple, size_t tuple_size, clingo_literal_t const *condition, size_t condition_size, clingo_id_t *element_id); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_element(clingo_backend_t *backend, clingo_id_t const *tuple, + size_t tuple_size, clingo_literal_t const *condition, + size_t condition_size, clingo_id_t *element_id); //! Add a theory atom without a guard. //! //! If atom is set to zero, the theory atom is a directive, @@ -1715,7 +1845,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_element(clingo_backend_t *b //! @param[out] atom_id the final program atom of the theory atom //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_atom(clingo_backend_t *backend, clingo_atom_t atom, clingo_id_t term_id, clingo_id_t const *elements, size_t size, clingo_atom_t *atom_id); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_atom(clingo_backend_t *backend, clingo_atom_t atom, + clingo_id_t term_id, clingo_id_t const *elements, size_t size, + clingo_atom_t *atom_id); //! Add a theory atom with a guard. //! //! See the note regarding atom at clingo_backend_theory_atom(). @@ -1730,7 +1862,11 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_atom(clingo_backend_t *back //! @param[out] atom_id the final program atom of the theory atom //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_atom_with_guard(clingo_backend_t *backend, clingo_atom_t atom, clingo_id_t term_id, clingo_id_t const *elements, size_t size, char const *operator_name, clingo_id_t right_hand_side_id, clingo_atom_t *atom_id); +CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_atom_with_guard(clingo_backend_t *backend, clingo_atom_t atom, + clingo_id_t term_id, clingo_id_t const *elements, + size_t size, char const *operator_name, + clingo_id_t right_hand_side_id, + clingo_atom_t *atom_id); //! @} @@ -1770,7 +1906,7 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_backend_theory_atom_with_guard(clingo_back enum clingo_configuration_type_e { clingo_configuration_type_value = 1, //!< the entry is a (string) value clingo_configuration_type_array = 2, //!< the entry is an array - clingo_configuration_type_map = 4 //!< the entry is a map + clingo_configuration_type_map = 4 //!< the entry is a map }; //! Bitset for values of type ::clingo_configuration_type_e. typedef unsigned clingo_configuration_type_bitset_t; @@ -1792,14 +1928,16 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_root(clingo_configuration_t //! @param[in] key the key //! @param[out] type the resulting type //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_type(clingo_configuration_t const *configuration, clingo_id_t key, clingo_configuration_type_bitset_t *type); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_type(clingo_configuration_t const *configuration, clingo_id_t key, + clingo_configuration_type_bitset_t *type); //! Get the description of an entry. //! //! @param[in] configuration the target configuration //! @param[in] key the key //! @param[out] description the description //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_description(clingo_configuration_t const *configuration, clingo_id_t key, char const **description); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_description(clingo_configuration_t const *configuration, + clingo_id_t key, char const **description); //! @name Functions to access arrays //! @{ @@ -1811,17 +1949,20 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_description(clingo_configura //! @param[in] key the key //! @param[out] size the resulting size //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_array_size(clingo_configuration_t const *configuration, clingo_id_t key, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_array_size(clingo_configuration_t const *configuration, + clingo_id_t key, size_t *size); //! Get the subkey at the given offset of an array entry. //! -//! @note Some array entries, like fore example the solver configuration, can be accessed past there actual size to add subentries. +//! @note Some array entries, like fore example the solver configuration, can be accessed past there actual size to add +//! subentries. //! @pre The @link clingo_configuration_type() type@endlink of the entry must be @ref ::clingo_configuration_type_array. //! @param[in] configuration the target configuration //! @param[in] key the key //! @param[in] offset the offset in the array //! @param[out] subkey the resulting subkey //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_array_at(clingo_configuration_t const *configuration, clingo_id_t key, size_t offset, clingo_id_t *subkey); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_array_at(clingo_configuration_t const *configuration, + clingo_id_t key, size_t offset, clingo_id_t *subkey); //! @} //! @name Functions to access maps @@ -1834,7 +1975,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_array_at(clingo_configuratio //! @param[in] key the key //! @param[out] size the resulting number //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_size(clingo_configuration_t const *configuration, clingo_id_t key, size_t* size); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_size(clingo_configuration_t const *configuration, + clingo_id_t key, size_t *size); //! Query whether the map has a key. //! //! @pre The @link clingo_configuration_type() type@endlink of the entry must be @ref ::clingo_configuration_type_map. @@ -1844,7 +1986,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_size(clingo_configuratio //! @param[in] name the name to look up the subkey //! @param[out] result whether the key is in the map //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_has_subkey(clingo_configuration_t const *configuration, clingo_id_t key, char const *name, bool *result); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_has_subkey(clingo_configuration_t const *configuration, + clingo_id_t key, char const *name, bool *result); //! Get the name associated with the offset-th subkey. //! //! @pre The @link clingo_configuration_type() type@endlink of the entry must be @ref ::clingo_configuration_type_map. @@ -1853,7 +1996,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_has_subkey(clingo_config //! @param[in] offset the offset of the name //! @param[out] name the resulting name //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_subkey_name(clingo_configuration_t const *configuration, clingo_id_t key, size_t offset, char const **name); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_subkey_name(clingo_configuration_t const *configuration, + clingo_id_t key, size_t offset, char const **name); //! Lookup a subkey under the given name. //! //! @pre The @link clingo_configuration_type() type@endlink of the entry must be @ref ::clingo_configuration_type_map. @@ -1863,7 +2007,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_subkey_name(clingo_confi //! @param[in] name the name to look up the subkey //! @param[out] subkey the resulting subkey //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_at(clingo_configuration_t const *configuration, clingo_id_t key, char const *name, clingo_id_t* subkey); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_at(clingo_configuration_t const *configuration, clingo_id_t key, + char const *name, clingo_id_t *subkey); //! @} //! @name Functions to access values @@ -1876,7 +2021,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_map_at(clingo_configuration_ //! @param[in] key the key //! @param[out] assigned whether the entry has a value //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_value_is_assigned(clingo_configuration_t const *configuration, clingo_id_t key, bool *assigned); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_value_is_assigned(clingo_configuration_t const *configuration, + clingo_id_t key, bool *assigned); //! Get the size of the string value of the given entry. //! //! @pre The @link clingo_configuration_type() type@endlink of the entry must be @ref ::clingo_configuration_type_value. @@ -1884,7 +2030,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_value_is_assigned(clingo_con //! @param[in] key the key //! @param[out] size the resulting size //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_value_get_size(clingo_configuration_t const *configuration, clingo_id_t key, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_value_get_size(clingo_configuration_t const *configuration, + clingo_id_t key, size_t *size); //! Get the string value of the given entry. //! //! @pre The @link clingo_configuration_type() type@endlink of the entry must be @ref ::clingo_configuration_type_value. @@ -1894,7 +2041,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_value_get_size(clingo_config //! @param[out] value the resulting string value //! @param[in] size the size of the given char array //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_value_get(clingo_configuration_t const *configuration, clingo_id_t key, char *value, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_value_get(clingo_configuration_t const *configuration, + clingo_id_t key, char *value, size_t size); //! Set the value of an entry. //! //! @pre The @link clingo_configuration_type() type@endlink of the entry must be @ref ::clingo_configuration_type_value. @@ -1902,7 +2050,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_value_get(clingo_configurati //! @param[in] key the key //! @param[in] value the value to set //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_value_set(clingo_configuration_t *configuration, clingo_id_t key, char const *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_configuration_value_set(clingo_configuration_t *configuration, clingo_id_t key, + char const *value); //! @} //! @} @@ -1954,7 +2103,7 @@ enum clingo_statistics_type_e { clingo_statistics_type_empty = 0, //!< the entry is invalid (has neither of the types below) clingo_statistics_type_value = 1, //!< the entry is a (double) value clingo_statistics_type_array = 2, //!< the entry is an array - clingo_statistics_type_map = 3 //!< the entry is a map + clingo_statistics_type_map = 3 //!< the entry is a map }; //! Corresponding type to ::clingo_statistics_type. typedef int clingo_statistics_type_t; @@ -1974,7 +2123,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_root(clingo_statistics_t const //! @param[in] key the key //! @param[out] type the resulting type //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_type(clingo_statistics_t const *statistics, uint64_t key, clingo_statistics_type_t *type); +CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_type(clingo_statistics_t const *statistics, uint64_t key, + clingo_statistics_type_t *type); //! @name Functions to access arrays //! @{ @@ -1986,7 +2136,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_type(clingo_statistics_t const //! @param[in] key the key //! @param[out] size the resulting size //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_array_size(clingo_statistics_t const *statistics, uint64_t key, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_array_size(clingo_statistics_t const *statistics, uint64_t key, + size_t *size); //! Get the subkey at the given offset of an array entry. //! //! @pre The @link clingo_statistics_type() type@endlink of the entry must be @ref ::clingo_statistics_type_array. @@ -1995,7 +2146,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_array_size(clingo_statistics_t //! @param[in] offset the offset in the array //! @param[out] subkey the resulting subkey //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_array_at(clingo_statistics_t const *statistics, uint64_t key, size_t offset, uint64_t *subkey); +CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_array_at(clingo_statistics_t const *statistics, uint64_t key, + size_t offset, uint64_t *subkey); //! Create the subkey at the end of an array entry. //! //! @pre The @link clingo_statistics_type() type@endlink of the entry must be @ref ::clingo_statistics_type_array. @@ -2004,7 +2156,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_array_at(clingo_statistics_t co //! @param[in] type the type of the new subkey //! @param[out] subkey the resulting subkey //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_array_push(clingo_statistics_t *statistics, uint64_t key, clingo_statistics_type_t type, uint64_t *subkey); +CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_array_push(clingo_statistics_t *statistics, uint64_t key, + clingo_statistics_type_t type, uint64_t *subkey); //! @} //! @name Functions to access maps @@ -2017,7 +2170,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_array_push(clingo_statistics_t //! @param[in] key the key //! @param[out] size the resulting number //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_size(clingo_statistics_t const *statistics, uint64_t key, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_size(clingo_statistics_t const *statistics, uint64_t key, + size_t *size); //! Test if the given map contains a specific subkey. //! //! @pre The @link clingo_statistics_type() type@endlink of the entry must be @ref ::clingo_statistics_type_map. @@ -2026,7 +2180,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_size(clingo_statistics_t co //! @param[in] name name of the subkey //! @param[out] result true if the map has a subkey with the given name //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_has_subkey(clingo_statistics_t const *statistics, uint64_t key, char const *name, bool* result); +CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_has_subkey(clingo_statistics_t const *statistics, uint64_t key, + char const *name, bool *result); //! Get the name associated with the offset-th subkey. //! //! @pre The @link clingo_statistics_type() type@endlink of the entry must be @ref ::clingo_statistics_type_map. @@ -2035,7 +2190,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_has_subkey(clingo_statistic //! @param[in] offset the offset of the name //! @param[out] name the resulting name //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_subkey_name(clingo_statistics_t const *statistics, uint64_t key, size_t offset, char const **name); +CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_subkey_name(clingo_statistics_t const *statistics, uint64_t key, + size_t offset, char const **name); //! Lookup a subkey under the given name. //! //! @pre The @link clingo_statistics_type() type@endlink of the entry must be @ref ::clingo_statistics_type_map. @@ -2045,7 +2201,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_subkey_name(clingo_statisti //! @param[in] name the name to look up the subkey //! @param[out] subkey the resulting subkey //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_at(clingo_statistics_t const *statistics, uint64_t key, char const *name, uint64_t *subkey); +CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_at(clingo_statistics_t const *statistics, uint64_t key, + char const *name, uint64_t *subkey); //! Add a subkey with the given name. //! //! @pre The @link clingo_statistics_type() type@endlink of the entry must be @ref ::clingo_statistics_type_map. @@ -2055,7 +2212,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_at(clingo_statistics_t cons //! @param[in] type the type of the new subkey //! @param[out] subkey the index of the resulting subkey //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_add_subkey(clingo_statistics_t *statistics, uint64_t key, char const *name, clingo_statistics_type_t type, uint64_t *subkey); +CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_add_subkey(clingo_statistics_t *statistics, uint64_t key, + char const *name, clingo_statistics_type_t type, + uint64_t *subkey); //! @} //! @name Functions to inspect and change values @@ -2068,7 +2227,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_map_add_subkey(clingo_statistic //! @param[in] key the key //! @param[out] value the resulting value //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_value_get(clingo_statistics_t const *statistics, uint64_t key, double *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_statistics_value_get(clingo_statistics_t const *statistics, uint64_t key, + double *value); //! Set the value of the given entry. //! //! @pre The @link clingo_statistics_type() type@endlink of the entry must be @ref ::clingo_statistics_type_value. @@ -2121,29 +2281,30 @@ typedef struct clingo_model clingo_model_t; //! Enumeration for the different model types. enum clingo_model_type_e { - clingo_model_type_stable_model = 0, //!< The model represents a stable model. - clingo_model_type_brave_consequences = 1, //!< The model represents a set of brave consequences. - clingo_model_type_cautious_consequences = 2 //!< The model represents a set of cautious consequences. + clingo_model_type_stable_model = 0, //!< The model represents a stable model. + clingo_model_type_brave_consequences = 1, //!< The model represents a set of brave consequences. + clingo_model_type_cautious_consequences = 2 //!< The model represents a set of cautious consequences. }; //! Corresponding type to ::clingo_model_type_e. typedef int clingo_model_type_t; //! Enumeration of bit flags to select symbols in models. enum clingo_show_type_e { - clingo_show_type_shown = 2, //!< Select shown atoms and terms. - clingo_show_type_atoms = 4, //!< Select all atoms. - clingo_show_type_terms = 8, //!< Select all terms. - clingo_show_type_theory = 16, //!< Select symbols added by theory. - clingo_show_type_all = 31, //!< Select everything. - clingo_show_type_complement = 32 //!< Select false instead of true atoms (::clingo_show_type_atoms) or terms (::clingo_show_type_terms). + clingo_show_type_shown = 2, //!< Select shown atoms and terms. + clingo_show_type_atoms = 4, //!< Select all atoms. + clingo_show_type_terms = 8, //!< Select all terms. + clingo_show_type_theory = 16, //!< Select symbols added by theory. + clingo_show_type_all = 31, //!< Select everything. + clingo_show_type_complement = + 32 //!< Select false instead of true atoms (::clingo_show_type_atoms) or terms (::clingo_show_type_terms). }; //! Corresponding type to ::clingo_show_type_e. typedef unsigned clingo_show_type_bitset_t; //! Enumeration for the different consequence types. enum clingo_consequence_e { - clingo_consequence_false = 0, //!< The literal is not a consequence. - clingo_consequence_true = 1, //!< The literal is a consequence. + clingo_consequence_false = 0, //!< The literal is not a consequence. + clingo_consequence_true = 1, //!< The literal is a consequence. clingo_consequence_unknown = 2, //!< The literal might or might not be a consequence. }; typedef int clingo_consequence_t; @@ -2172,7 +2333,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_model_number(clingo_model_t const *model, //! @param[out] size the number symbols //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_model_symbols_size(clingo_model_t const *model, clingo_show_type_bitset_t show, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_model_symbols_size(clingo_model_t const *model, clingo_show_type_bitset_t show, + size_t *size); //! Get the symbols of the selected types in the model. //! //! @note CSP assignments are represented using functions with name "$" @@ -2188,21 +2350,24 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_model_symbols_size(clingo_model_t const *m //! - ::clingo_error_runtime if the size is too small //! //! @see clingo_model_symbols_size() -CLINGO_VISIBILITY_DEFAULT bool clingo_model_symbols(clingo_model_t const *model, clingo_show_type_bitset_t show, clingo_symbol_t *symbols, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_model_symbols(clingo_model_t const *model, clingo_show_type_bitset_t show, + clingo_symbol_t *symbols, size_t size); //! Constant time lookup to test whether an atom is in a model. //! //! @param[in] model the target //! @param[in] atom the atom to lookup //! @param[out] contained whether the atom is contained //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_model_contains(clingo_model_t const *model, clingo_symbol_t atom, bool *contained); +CLINGO_VISIBILITY_DEFAULT bool clingo_model_contains(clingo_model_t const *model, clingo_symbol_t atom, + bool *contained); //! Check if a program literal is true in a model. //! //! @param[in] model the target //! @param[in] literal the literal to lookup //! @param[out] result whether the literal is true //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_model_is_true(clingo_model_t const *model, clingo_literal_t literal, bool *result); +CLINGO_VISIBILITY_DEFAULT bool clingo_model_is_true(clingo_model_t const *model, clingo_literal_t literal, + bool *result); //! Check if the given literal is a consequence. //! //! While enumerating cautious or brave consequences, there is partial @@ -2215,7 +2380,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_model_is_true(clingo_model_t const *model, //! @param[in] literal the literal to lookup //! @param[out] result whether the literal is a consequence //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_model_is_consequence(clingo_model_t const *model, clingo_literal_t literal, clingo_consequence_t *result); +CLINGO_VISIBILITY_DEFAULT bool clingo_model_is_consequence(clingo_model_t const *model, clingo_literal_t literal, + clingo_consequence_t *result); //! Get the number of cost values of a model. //! //! @param[in] model the target @@ -2246,7 +2412,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_model_cost(clingo_model_t const *model, in //! - ::clingo_error_runtime if the size is too small //! //! @see clingo_model_cost_size() -CLINGO_VISIBILITY_DEFAULT bool clingo_model_priority(clingo_model_t const *model, clingo_weight_t *priorities, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_model_priority(clingo_model_t const *model, clingo_weight_t *priorities, + size_t size); //! Whether the optimality of a model has been proven. //! //! @param[in] model the target @@ -2289,7 +2456,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_model_context(clingo_model_t const *model, //! @param[in] control the target //! @param[out] atoms the resulting object //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_solve_control_symbolic_atoms(clingo_solve_control_t const *control, clingo_symbolic_atoms_t const **atoms); +CLINGO_VISIBILITY_DEFAULT bool clingo_solve_control_symbolic_atoms(clingo_solve_control_t const *control, + clingo_symbolic_atoms_t const **atoms); //! Add a clause that applies to the current solving step during model //! enumeration. //! @@ -2302,7 +2470,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_solve_control_symbolic_atoms(clingo_solve_ //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc //! - ::clingo_error_runtime if adding the clause fails -CLINGO_VISIBILITY_DEFAULT bool clingo_solve_control_add_clause(clingo_solve_control_t *control, clingo_literal_t const *clause, size_t size); +CLINGO_VISIBILITY_DEFAULT bool clingo_solve_control_add_clause(clingo_solve_control_t *control, + clingo_literal_t const *clause, size_t size); //! @} //! @} @@ -2311,10 +2480,10 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_solve_control_add_clause(clingo_solve_cont // NOTE: documented in Control Module enum clingo_solve_result_e { - clingo_solve_result_satisfiable = 1, + clingo_solve_result_satisfiable = 1, clingo_solve_result_unsatisfiable = 2, - clingo_solve_result_exhausted = 4, - clingo_solve_result_interrupted = 8 + clingo_solve_result_exhausted = 4, + clingo_solve_result_interrupted = 8 }; typedef unsigned clingo_solve_result_bitset_t; @@ -2363,10 +2532,10 @@ typedef unsigned clingo_solve_mode_bitset_t; //! Enumeration of solve events. enum clingo_solve_event_type_e { - clingo_solve_event_type_model = 0, //!< Issued if a model is found. - clingo_solve_event_type_unsat = 1, //!< Issued if an optimization problem is found unsatisfiable. + clingo_solve_event_type_model = 0, //!< Issued if a model is found. + clingo_solve_event_type_unsat = 1, //!< Issued if an optimization problem is found unsatisfiable. clingo_solve_event_type_statistics = 2, //!< Issued when the statistics can be updated. - clingo_solve_event_type_finish = 3, //!< Issued if the search has completed. + clingo_solve_event_type_finish = 3, //!< Issued if the search has completed. }; //! Corresponding type to ::clingo_solve_event_type_e. typedef unsigned clingo_solve_event_type_t; @@ -2374,9 +2543,11 @@ typedef unsigned clingo_solve_event_type_t; //! Callback function called during search to notify when the search is finished or a model is ready. //! //! If a (non-recoverable) clingo API function fails in this callback, it must return false. -//! In case of errors not related to clingo, set error code ::clingo_error_unknown and return false to stop solving with an error. +//! In case of errors not related to clingo, set error code ::clingo_error_unknown and return false to stop solving with +//! an error. //! -//! The event is either a pointer to a model, a pointer to an int64_t* and a size_t, a pointer to two statistics objects (per step and accumulated statistics), or a solve result. +//! The event is either a pointer to a model, a pointer to an int64_t* and a size_t, a pointer to two statistics objects +//! (per step and accumulated statistics), or a solve result. //! @attention If the search is finished, the model is NULL. //! //! @param[in] event the current event. @@ -2385,7 +2556,7 @@ typedef unsigned clingo_solve_event_type_t; //! @return whether the call was successful //! //! @see clingo_control_solve() -typedef bool (*clingo_solve_event_callback_t) (clingo_solve_event_type_t type, void *event, void *data, bool *goon); +typedef bool (*clingo_solve_event_callback_t)(clingo_solve_event_type_t type, void *event, void *data, bool *goon); //! Search handle to a solve call. //! @@ -2403,7 +2574,8 @@ typedef struct clingo_solve_handle clingo_solve_handle_t; //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc //! - ::clingo_error_runtime if solving fails -CLINGO_VISIBILITY_DEFAULT bool clingo_solve_handle_get(clingo_solve_handle_t *handle, clingo_solve_result_bitset_t *result); +CLINGO_VISIBILITY_DEFAULT bool clingo_solve_handle_get(clingo_solve_handle_t *handle, + clingo_solve_result_bitset_t *result); //! Wait for the specified amount of time to check if the next result is ready. //! //! If the time is set to zero, this function can be used to poll if the search is still active. @@ -2430,7 +2602,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_solve_handle_model(clingo_solve_handle_t * //! @param[out] size size of the given array //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_solve_handle_core(clingo_solve_handle_t *handle, clingo_literal_t const **core, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_solve_handle_core(clingo_solve_handle_t *handle, clingo_literal_t const **core, + size_t *size); //! When a problem is satisfiable and the search is finished, get the last computed model. //! //! If the program is unsatisfiable or the search is not finished, model is set to NULL. @@ -2479,7 +2652,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_solve_handle_close(clingo_solve_handle_t * //! @addtogroup ProgramInspection //! @{ -//! An instance of this struct has to be registered with a solver to observe ground directives as they are passed to the solver. +//! An instance of this struct has to be registered with a solver to observe ground directives as they are passed to the +//! solver. //! //! @note This interface is closely modeled after the aspif format. //! For more information please refer to the specification of the aspif format. @@ -2525,7 +2699,8 @@ typedef struct clingo_ground_program_observer { //! @param[in] body_size the number of literals in the body //! @param[in] data user data for the callback //! @return whether the call was successful - bool (*rule)(bool choice, clingo_atom_t const *head, size_t head_size, clingo_literal_t const *body, size_t body_size, void *data); + bool (*rule)(bool choice, clingo_atom_t const *head, size_t head_size, clingo_literal_t const *body, + size_t body_size, void *data); //! Observe weight rules passed to the solver. //! //! @param[in] choice determines if the head is a choice or a disjunction @@ -2536,7 +2711,8 @@ typedef struct clingo_ground_program_observer { //! @param[in] body_size the number of weighted literals in the body //! @param[in] data user data for the callback //! @return whether the call was successful - bool (*weight_rule)(bool choice, clingo_atom_t const *head, size_t head_size, clingo_weight_t lower_bound, clingo_weighted_literal_t const *body, size_t body_size, void *data); + bool (*weight_rule)(bool choice, clingo_atom_t const *head, size_t head_size, clingo_weight_t lower_bound, + clingo_weighted_literal_t const *body, size_t body_size, void *data); //! Observe minimize constraints (or weak constraints) passed to the solver. //! //! @param[in] priority the priority of the constraint @@ -2544,7 +2720,7 @@ typedef struct clingo_ground_program_observer { //! @param[in] size the number of weighted literals //! @param[in] data user data for the callback //! @return whether the call was successful - bool (*minimize)(clingo_weight_t priority, clingo_weighted_literal_t const* literals, size_t size, void *data); + bool (*minimize)(clingo_weight_t priority, clingo_weighted_literal_t const *literals, size_t size, void *data); //! Observe projection directives passed to the solver. //! //! @param[in] atoms the atoms to project on @@ -2578,7 +2754,8 @@ typedef struct clingo_ground_program_observer { bool (*external)(clingo_atom_t atom, clingo_external_type_t type, void *data); //! Observe assumption directives passed to the solver. //! - //! @param[in] literals the literals to assume (positive literals are true and negative literals false for the next solve call) + //! @param[in] literals the literals to assume (positive literals are true and negative literals false for the next + //! solve call) //! @param[in] size the number of atoms //! @param[in] data user data for the callback //! @return whether the call was successful @@ -2593,7 +2770,8 @@ typedef struct clingo_ground_program_observer { //! @param[in] size the number of atoms in the condition //! @param[in] data user data for the callback //! @return whether the call was successful - bool (*heuristic)(clingo_atom_t atom, clingo_heuristic_type_t type, int bias, unsigned priority, clingo_literal_t const *condition, size_t size, void *data); + bool (*heuristic)(clingo_atom_t atom, clingo_heuristic_type_t type, int bias, unsigned priority, + clingo_literal_t const *condition, size_t size, void *data); //! Observe edge directives passed to the solver. //! //! @param[in] node_u the start vertex of the edge @@ -2632,7 +2810,8 @@ typedef struct clingo_ground_program_observer { //! @param[in] size the number of arguments //! @param[in] data user data for the callback //! @return whether the call was successful - bool (*theory_term_compound)(clingo_id_t term_id, int name_id_or_type, clingo_id_t const *arguments, size_t size, void *data); + bool (*theory_term_compound)(clingo_id_t term_id, int name_id_or_type, clingo_id_t const *arguments, size_t size, + void *data); //! Observe theory elements. //! //! @param element_id the id of the element @@ -2642,7 +2821,8 @@ typedef struct clingo_ground_program_observer { //! @param condition_size the number of literals in the condition //! @param[in] data user data for the callback //! @return whether the call was successful - bool (*theory_element)(clingo_id_t element_id, clingo_id_t const *terms, size_t terms_size, clingo_literal_t const *condition, size_t condition_size, void *data); + bool (*theory_element)(clingo_id_t element_id, clingo_id_t const *terms, size_t terms_size, + clingo_literal_t const *condition, size_t condition_size, void *data); //! Observe theory atoms without guard. //! //! @param[in] atom_id_or_zero the id of the atom or zero for directives @@ -2651,7 +2831,8 @@ typedef struct clingo_ground_program_observer { //! @param[in] size the number of elements //! @param[in] data user data for the callback //! @return whether the call was successful - bool (*theory_atom)(clingo_id_t atom_id_or_zero, clingo_id_t term_id, clingo_id_t const *elements, size_t size, void *data); + bool (*theory_atom)(clingo_id_t atom_id_or_zero, clingo_id_t term_id, clingo_id_t const *elements, size_t size, + void *data); //! Observe theory atoms with guard. //! //! @param[in] atom_id_or_zero the id of the atom or zero for directives @@ -2662,7 +2843,8 @@ typedef struct clingo_ground_program_observer { //! @param[in] right_hand_side_id the id of the term on the right hand side of the atom //! @param[in] data user data for the callback //! @return whether the call was successful - bool (*theory_atom_with_guard)(clingo_id_t atom_id_or_zero, clingo_id_t term_id, clingo_id_t const *elements, size_t size, clingo_id_t operator_id, clingo_id_t right_hand_side_id, void *data); + bool (*theory_atom_with_guard)(clingo_id_t atom_id_or_zero, clingo_id_t term_id, clingo_id_t const *elements, + size_t size, clingo_id_t operator_id, clingo_id_t right_hand_side_id, void *data); } clingo_ground_program_observer_t; //! @} @@ -2735,8 +2917,9 @@ typedef struct clingo_part { //! then this function is called with its location, name, parameters, and a callback to inject symbols as arguments. //! The callback can be called multiple times; all symbols passed are injected. //! -//! If a (non-recoverable) clingo API function fails in this callback, for example, the symbol callback, the callback must return false. -//! In case of errors not related to clingo, this function can set error ::clingo_error_unknown and return false to stop grounding with an error. +//! If a (non-recoverable) clingo API function fails in this callback, for example, the symbol callback, the callback +//! must return false. In case of errors not related to clingo, this function can set error ::clingo_error_unknown and +//! return false to stop grounding with an error. //! //! @param[in] location location from which the external function was called //! @param[in] name name of the called external function @@ -2768,7 +2951,9 @@ typedef struct clingo_part { //! return false; //! } //! ~~~~~~~~~~~~~~~ -typedef bool (*clingo_ground_callback_t) (clingo_location_t const *location, char const *name, clingo_symbol_t const *arguments, size_t arguments_size, void *data, clingo_symbol_callback_t symbol_callback, void *symbol_callback_data); +typedef bool (*clingo_ground_callback_t)(clingo_location_t const *location, char const *name, + clingo_symbol_t const *arguments, size_t arguments_size, void *data, + clingo_symbol_callback_t symbol_callback, void *symbol_callback_data); //! The available backends. //! @@ -2784,7 +2969,6 @@ enum clingo_backend_type_e { //! Corresponding type to clingo_backend_type_e. typedef unsigned clingo_backend_type_t; - //! Control object holding grounding and solving state. typedef struct clingo_control clingo_control_t; @@ -2808,7 +2992,9 @@ typedef struct clingo_control clingo_control_t; //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc //! - ::clingo_error_runtime if argument parsing fails -CLINGO_VISIBILITY_DEFAULT bool clingo_control_new(char const *const * arguments, size_t arguments_size, clingo_logger_t logger, void *logger_data, unsigned message_limit, clingo_control_t **control); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_new(char const *const *arguments, size_t arguments_size, + clingo_logger_t logger, void *logger_data, unsigned message_limit, + clingo_control_t **control); //! Free a control object created with clingo_control_new(). //! @param[in] control the target @@ -2844,7 +3030,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_load_aspif(clingo_control_t *contr //! //! This function puts the given program into a block of form: \#program name(parameters). //! -//! After extending the logic program, the corresponding program parts are typically grounded with ::clingo_control_ground. +//! After extending the logic program, the corresponding program parts are typically grounded with +//! ::clingo_control_ground. //! //! @param[in] control the target //! @param[in] name name of the program block @@ -2854,7 +3041,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_load_aspif(clingo_control_t *contr //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc //! - ::clingo_error_runtime if parsing fails -CLINGO_VISIBILITY_DEFAULT bool clingo_control_add(clingo_control_t *control, char const *name, char const * const * parameters, size_t parameters_size, char const *program); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_add(clingo_control_t *control, char const *name, + char const *const *parameters, size_t parameters_size, + char const *program); //! Ground the selected @link ::clingo_part parts @endlink of the current (non-ground) logic program. //! @@ -2874,7 +3063,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_add(clingo_control_t *control, cha //! - error code of ground callback //! //! @see clingo_part -CLINGO_VISIBILITY_DEFAULT bool clingo_control_ground(clingo_control_t *control, clingo_part_t const *parts, size_t parts_size, clingo_ground_callback_t ground_callback, void *ground_callback_data); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_ground(clingo_control_t *control, clingo_part_t const *parts, + size_t parts_size, clingo_ground_callback_t ground_callback, + void *ground_callback_data); //! @} @@ -2895,7 +3086,10 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_ground(clingo_control_t *control, //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc //! - ::clingo_error_runtime if solving could not be started -CLINGO_VISIBILITY_DEFAULT bool clingo_control_solve(clingo_control_t *control, clingo_solve_mode_bitset_t mode, clingo_literal_t const *assumptions, size_t assumptions_size, clingo_solve_event_callback_t notify, void *data, clingo_solve_handle_t **handle); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_solve(clingo_control_t *control, clingo_solve_mode_bitset_t mode, + clingo_literal_t const *assumptions, size_t assumptions_size, + clingo_solve_event_callback_t notify, void *data, + clingo_solve_handle_t **handle); //! Clean up the domains of the grounding component using the solving //! component's top level assignment. //! @@ -2926,7 +3120,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_cleanup(clingo_control_t *control) //! @param[in] value the truth value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_control_assign_external(clingo_control_t *control, clingo_literal_t literal, clingo_truth_value_t value); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_assign_external(clingo_control_t *control, clingo_literal_t literal, + clingo_truth_value_t value); //! Release an external atom. //! //! If a negative literal is passed, the corresponding atom is released. @@ -2959,7 +3154,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_remove_minimize(clingo_control_t * //! @param[in] append whether to append to (true) or replace (false) any previously added projection variables //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_control_update_project(clingo_control_t *control, clingo_atom_t const* atoms, size_t size, bool append); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_update_project(clingo_control_t *control, clingo_atom_t const *atoms, + size_t size, bool append); //! Register a custom propagator with the control object. //! @@ -2974,7 +3170,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_update_project(clingo_control_t *c //! @param[in] sequential whether the propagator should be called sequentially //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_control_register_propagator(clingo_control_t *control, clingo_propagator_t const *propagator, void *data, bool sequential); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_register_propagator(clingo_control_t *control, + clingo_propagator_t const *propagator, void *data, + bool sequential); //! Check if the solver has determined that the internal program representation is conflicting. //! //! If this function returns true, solve calls will return immediately with an unsatisfiable solve result. @@ -2995,18 +3193,17 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_is_conflicting(clingo_control_t co //! //! @attention //! The level of detail of the statistics depends on the stats option -//! (which can be set using @ref Configuration module or passed as an option when @link clingo_control_new creating the control object@endlink). -//! The default level zero only provides basic statistics, -//! level one provides extended and accumulated statistics, -//! and level two provides per-thread statistics. -//! Furthermore, the statistics object is best accessed right after solving. -//! Otherwise, not all of its entries have valid values. +//! (which can be set using @ref Configuration module or passed as an option when @link clingo_control_new creating the +//! control object@endlink). The default level zero only provides basic statistics, level one provides extended and +//! accumulated statistics, and level two provides per-thread statistics. Furthermore, the statistics object is best +//! accessed right after solving. Otherwise, not all of its entries have valid values. //! //! @param[in] control the target //! @param[out] statistics the statistics object //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_control_statistics(clingo_control_t const *control, clingo_statistics_t const **statistics); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_statistics(clingo_control_t const *control, + clingo_statistics_t const **statistics); //! Interrupt the active solve call (or the following solve call right at the beginning). //! //! @param[in] control the target @@ -3036,7 +3233,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_clasp_facade(clingo_control_t *con //! @param[in] control the target //! @param[out] configuration the configuration object //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_control_configuration(clingo_control_t *control, clingo_configuration_t **configuration); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_configuration(clingo_control_t *control, + clingo_configuration_t **configuration); //! Configure how learnt constraints are handled during enumeration. //! @@ -3093,7 +3291,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_get_enable_cleanup(clingo_control_ //! @param[in] name the name of the constant //! @param[out] symbol the resulting symbol //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_control_get_const(clingo_control_t const *control, char const *name, clingo_symbol_t *symbol); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_get_const(clingo_control_t const *control, char const *name, + clingo_symbol_t *symbol); //! Check if there is a constant definition for the given constant. //! //! @param[in] control the target @@ -3103,7 +3302,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_get_const(clingo_control_t const * //! - ::clingo_error_runtime if constant definition does not exist //! //! @see clingo_control_get_const() -CLINGO_VISIBILITY_DEFAULT bool clingo_control_has_const(clingo_control_t const *control, char const *name, bool *exists); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_has_const(clingo_control_t const *control, char const *name, + bool *exists); //! Get an object to inspect symbolic atoms (the relevant Herbrand base) used //! for grounding. //! @@ -3112,7 +3312,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_has_const(clingo_control_t const * //! @param[in] control the target //! @param[out] atoms the symbolic atoms object //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_control_symbolic_atoms(clingo_control_t const *control, clingo_symbolic_atoms_t const **atoms); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_symbolic_atoms(clingo_control_t const *control, + clingo_symbolic_atoms_t const **atoms); //! Get an object to inspect theory atoms that occur in the grounding. //! //! See the @ref TheoryAtoms module for more information. @@ -3120,7 +3321,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_symbolic_atoms(clingo_control_t co //! @param[in] control the target //! @param[out] atoms the theory atoms object //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_control_theory_atoms(clingo_control_t const *control, clingo_theory_atoms_t const **atoms); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_theory_atoms(clingo_control_t const *control, + clingo_theory_atoms_t const **atoms); //! Register a program observer with the control object. //! //! @param[in] control the target @@ -3128,7 +3330,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_theory_atoms(clingo_control_t cons //! @param[in] replace just pass the grounding to the observer but not the solver //! @param[in] data user data passed to the observer functions //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_control_register_observer(clingo_control_t *control, clingo_ground_program_observer_t const *observer, bool replace, void *data); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_register_observer(clingo_control_t *control, + clingo_ground_program_observer_t const *observer, + bool replace, void *data); //! Register a backend with the control object. //! //! This function is similar to clingo_control_register_observer except that @@ -3141,7 +3345,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_control_register_observer(clingo_control_t //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc //! - ::clingo_error_runtime (for example if the file could not be opened) -CLINGO_VISIBILITY_DEFAULT bool clingo_control_register_backend(clingo_control_t *control, clingo_backend_type_t type, char const *file, bool replace); +CLINGO_VISIBILITY_DEFAULT bool clingo_control_register_backend(clingo_control_t *control, clingo_backend_type_t type, + char const *file, bool replace); //! @} //! @name Program Modification Functions @@ -3199,28 +3404,28 @@ typedef int clingo_ast_theory_sequence_type_t; //! Enumeration of comparison relations. enum clingo_ast_comparison_operator_e { - clingo_ast_comparison_operator_greater_than = 0, //!< Operator ">". - clingo_ast_comparison_operator_less_than = 1, //!< Operator "<". - clingo_ast_comparison_operator_less_equal = 2, //!< Operator "<=". + clingo_ast_comparison_operator_greater_than = 0, //!< Operator ">". + clingo_ast_comparison_operator_less_than = 1, //!< Operator "<". + clingo_ast_comparison_operator_less_equal = 2, //!< Operator "<=". clingo_ast_comparison_operator_greater_equal = 3, //!< Operator ">=". - clingo_ast_comparison_operator_not_equal = 4, //!< Operator "!=". - clingo_ast_comparison_operator_equal = 5 //!< Operator "==". + clingo_ast_comparison_operator_not_equal = 4, //!< Operator "!=". + clingo_ast_comparison_operator_equal = 5 //!< Operator "==". }; //! Corresponding type to ::clingo_ast_comparison_operator_e. typedef int clingo_ast_comparison_operator_t; //! Enumeration of signs. enum clingo_ast_sign_e { - clingo_ast_sign_no_sign = 0, //!< For positive literals. - clingo_ast_sign_negation = 1, //!< For negative literals (prefix "not"). - clingo_ast_sign_double_negation = 2 //!< For double negated literals (prefix "not not"). + clingo_ast_sign_no_sign = 0, //!< For positive literals. + clingo_ast_sign_negation = 1, //!< For negative literals (prefix "not"). + clingo_ast_sign_double_negation = 2 //!< For double negated literals (prefix "not not"). }; //! Corresponding type to ::clingo_ast_sign_t. typedef int clingo_ast_sign_t; //! Enumeration of unary operators. enum clingo_ast_unary_operator_e { - clingo_ast_unary_operator_minus = 0, //!< Operator "-". + clingo_ast_unary_operator_minus = 0, //!< Operator "-". clingo_ast_unary_operator_negation = 1, //!< Operator "~". clingo_ast_unary_operator_absolute = 2 //!< Operator "|.|". }; @@ -3229,15 +3434,15 @@ typedef int clingo_ast_unary_operator_t; //! Enumeration of binary operators. enum clingo_ast_binary_operator_e { - clingo_ast_binary_operator_xor = 0, //!< Operator "^". - clingo_ast_binary_operator_or = 1, //!< Operator "?". - clingo_ast_binary_operator_and = 2, //!< Operator "&". - clingo_ast_binary_operator_plus = 3, //!< Operator "+". - clingo_ast_binary_operator_minus = 4, //!< Operator "-". + clingo_ast_binary_operator_xor = 0, //!< Operator "^". + clingo_ast_binary_operator_or = 1, //!< Operator "?". + clingo_ast_binary_operator_and = 2, //!< Operator "&". + clingo_ast_binary_operator_plus = 3, //!< Operator "+". + clingo_ast_binary_operator_minus = 4, //!< Operator "-". clingo_ast_binary_operator_multiplication = 5, //!< Operator "*". - clingo_ast_binary_operator_division = 6, //!< Operator "/". - clingo_ast_binary_operator_modulo = 7, //!< Operator "\". - clingo_ast_binary_operator_power = 8 //!< Operator "**". + clingo_ast_binary_operator_division = 6, //!< Operator "/". + clingo_ast_binary_operator_modulo = 7, //!< Operator "\". + clingo_ast_binary_operator_power = 8 //!< Operator "**". }; //! Corresponding type to ::clingo_ast_binary_operator_e. typedef int clingo_ast_binary_operator_t; @@ -3245,29 +3450,29 @@ typedef int clingo_ast_binary_operator_t; //! Enumeration of aggregate functions. enum clingo_ast_aggregate_function_e { clingo_ast_aggregate_function_count = 0, //!< Operator "^". - clingo_ast_aggregate_function_sum = 1, //!< Operator "?". - clingo_ast_aggregate_function_sump = 2, //!< Operator "&". - clingo_ast_aggregate_function_min = 3, //!< Operator "+". - clingo_ast_aggregate_function_max = 4 //!< Operator "-". + clingo_ast_aggregate_function_sum = 1, //!< Operator "?". + clingo_ast_aggregate_function_sump = 2, //!< Operator "&". + clingo_ast_aggregate_function_min = 3, //!< Operator "+". + clingo_ast_aggregate_function_max = 4 //!< Operator "-". }; //! Corresponding type to ::clingo_ast_aggregate_function_e. typedef int clingo_ast_aggregate_function_t; //! Enumeration of theory operators. enum clingo_ast_theory_operator_type_e { - clingo_ast_theory_operator_type_unary = 0, //!< An unary theory operator. - clingo_ast_theory_operator_type_binary_left = 1, //!< A left associative binary operator. - clingo_ast_theory_operator_type_binary_right = 2 //!< A right associative binary operator. + clingo_ast_theory_operator_type_unary = 0, //!< An unary theory operator. + clingo_ast_theory_operator_type_binary_left = 1, //!< A left associative binary operator. + clingo_ast_theory_operator_type_binary_right = 2 //!< A right associative binary operator. }; //! Corresponding type to ::clingo_ast_theory_operator_type_e. typedef int clingo_ast_theory_operator_type_t; //! Enumeration of the theory atom types. enum clingo_ast_theory_atom_definition_type_e { - clingo_ast_theory_atom_definition_type_head = 0, //!< For theory atoms that can appear in the head. - clingo_ast_theory_atom_definition_type_body = 1, //!< For theory atoms that can appear in the body. - clingo_ast_theory_atom_definition_type_any = 2, //!< For theory atoms that can appear in both head and body. - clingo_ast_theory_atom_definition_type_directive = 3 //!< For theory atoms that must not have a body. + clingo_ast_theory_atom_definition_type_head = 0, //!< For theory atoms that can appear in the head. + clingo_ast_theory_atom_definition_type_body = 1, //!< For theory atoms that can appear in the body. + clingo_ast_theory_atom_definition_type_any = 2, //!< For theory atoms that can appear in both head and body. + clingo_ast_theory_atom_definition_type_directive = 3 //!< For theory atoms that must not have a body. }; //! Corresponding type to ::clingo_ast_theory_atom_definition_type_e. typedef int clingo_ast_theory_atom_definition_type_t; @@ -3333,14 +3538,14 @@ typedef int clingo_ast_type_t; //! Enumeration of attributes types used by the AST. enum clingo_ast_attribute_type_e { - clingo_ast_attribute_type_number = 0, //!< For an attribute of type "int". - clingo_ast_attribute_type_symbol = 1, //!< For an attribute of type "clingo_ast_symbol_t". - clingo_ast_attribute_type_location = 2, //!< For an attribute of type "clingo_location_t". - clingo_ast_attribute_type_string = 3, //!< For an attribute of type "char const *". - clingo_ast_attribute_type_ast = 4, //!< For an attribute of type "clingo_ast_t *". + clingo_ast_attribute_type_number = 0, //!< For an attribute of type "int". + clingo_ast_attribute_type_symbol = 1, //!< For an attribute of type "clingo_ast_symbol_t". + clingo_ast_attribute_type_location = 2, //!< For an attribute of type "clingo_location_t". + clingo_ast_attribute_type_string = 3, //!< For an attribute of type "char const *". + clingo_ast_attribute_type_ast = 4, //!< For an attribute of type "clingo_ast_t *". clingo_ast_attribute_type_optional_ast = 5, //!< For an attribute of type "clingo_ast_t *" that can be NULL. clingo_ast_attribute_type_string_array = 6, //!< For an attribute of type "char const **". - clingo_ast_attribute_type_ast_array = 7, //!< For an attribute of type "clingo_ast_t **". + clingo_ast_attribute_type_ast_array = 7, //!< For an attribute of type "clingo_ast_t **". }; //! Corresponding type to ::clingo_ast_attribute_type. typedef int clingo_ast_attribute_type_t; @@ -3398,7 +3603,7 @@ typedef int clingo_ast_attribute_t; //! Struct to map attributes to their string representation. typedef struct clingo_ast_attribute_names { - char const * const * names; + char const *const *names; size_t size; } clingo_ast_attribute_names_t; @@ -3437,7 +3642,8 @@ typedef struct clingo_ast clingo_ast_t; //! Construct an AST of the given type. //! -//! @note The arguments corresponding to the given type can be inspected using "g_clingo_ast_constructors.constructors[type]". +//! @note The arguments corresponding to the given type can be inspected using +//! "g_clingo_ast_constructors.constructors[type]". //! //! @param[in] type the type of AST to construct //! @param[out] ast the resulting AST @@ -3548,7 +3754,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_get_type(clingo_ast_t *ast, clingo_ast //! @param[out] has_attribute the result //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_has_attribute(clingo_ast_t *ast, clingo_ast_attribute_t attribute, bool *has_attribute); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_has_attribute(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + bool *has_attribute); //! Get the type of the given AST. //! //! @param[in] ast the target AST @@ -3556,7 +3763,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_has_attribute(clingo_ast_t *ast, cling //! @param[out] type the resulting type //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_type(clingo_ast_t *ast, clingo_ast_attribute_t attribute, clingo_ast_attribute_type_t *type); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_type(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + clingo_ast_attribute_type_t *type); //! @} @@ -3570,7 +3778,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_type(clingo_ast_t *ast, clin //! @param[out] value the resulting value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_number(clingo_ast_t *ast, clingo_ast_attribute_t attribute, int *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_number(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + int *value); //! Set the value of an attribute of type "clingo_ast_attribute_type_number". //! //! @param[in] ast the target AST @@ -3578,7 +3787,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_number(clingo_ast_t *ast //! @param[in] value the value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_number(clingo_ast_t *ast, clingo_ast_attribute_t attribute, int value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_number(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + int value); //! @} @@ -3592,7 +3802,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_number(clingo_ast_t *ast //! @param[out] value the resulting value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_symbol(clingo_ast_t *ast, clingo_ast_attribute_t attribute, clingo_symbol_t *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_symbol(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + clingo_symbol_t *value); //! Set the value of an attribute of type "clingo_ast_attribute_type_symbol". //! //! @param[in] ast the target AST @@ -3600,7 +3811,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_symbol(clingo_ast_t *ast //! @param[in] value the value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_symbol(clingo_ast_t *ast, clingo_ast_attribute_t attribute, clingo_symbol_t value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_symbol(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + clingo_symbol_t value); //! @} @@ -3614,7 +3826,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_symbol(clingo_ast_t *ast //! @param[out] value the resulting value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_location(clingo_ast_t *ast, clingo_ast_attribute_t attribute, clingo_location_t *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_location(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + clingo_location_t *value); //! Set the value of an attribute of type "clingo_ast_attribute_type_location". //! //! @param[in] ast the target AST @@ -3622,7 +3835,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_location(clingo_ast_t *a //! @param[in] value the value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_location(clingo_ast_t *ast, clingo_ast_attribute_t attribute, clingo_location_t const *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_location(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + clingo_location_t const *value); //! @} @@ -3636,7 +3850,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_location(clingo_ast_t *a //! @param[out] value the resulting value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_string(clingo_ast_t *ast, clingo_ast_attribute_t attribute, char const **value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_string(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + char const **value); //! Set the value of an attribute of type "clingo_ast_attribute_type_string". //! //! @param[in] ast the target AST @@ -3644,7 +3859,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_string(clingo_ast_t *ast //! @param[in] value the value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_string(clingo_ast_t *ast, clingo_ast_attribute_t attribute, char const *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_string(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + char const *value); //! @} @@ -3658,7 +3874,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_string(clingo_ast_t *ast //! @param[out] value the resulting value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_ast(clingo_ast_t *ast, clingo_ast_attribute_t attribute, clingo_ast_t **value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_ast(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + clingo_ast_t **value); //! Set the value of an attribute of type "clingo_ast_attribute_type_ast". //! //! @param[in] ast the target AST @@ -3666,7 +3883,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_ast(clingo_ast_t *ast, c //! @param[in] value the value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_ast(clingo_ast_t *ast, clingo_ast_attribute_t attribute, clingo_ast_t *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_ast(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + clingo_ast_t *value); //! @} @@ -3682,7 +3900,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_ast(clingo_ast_t *ast, c //! @param[out] value the resulting value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_optional_ast(clingo_ast_t *ast, clingo_ast_attribute_t attribute, clingo_ast_t **value); +CLINGO_VISIBILITY_DEFAULT bool +clingo_ast_attribute_get_optional_ast(clingo_ast_t *ast, clingo_ast_attribute_t attribute, clingo_ast_t **value); //! Set the value of an attribute of type "clingo_ast_attribute_type_optional_ast". //! //! @note The value might be "NULL". @@ -3692,7 +3911,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_optional_ast(clingo_ast_ //! @param[in] value the value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_optional_ast(clingo_ast_t *ast, clingo_ast_attribute_t attribute, clingo_ast_t *value); +CLINGO_VISIBILITY_DEFAULT bool +clingo_ast_attribute_set_optional_ast(clingo_ast_t *ast, clingo_ast_attribute_t attribute, clingo_ast_t *value); //! @} @@ -3707,7 +3927,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_optional_ast(clingo_ast_ //! @param[out] value the resulting value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_string_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, size_t index, char const **value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_string_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + size_t index, char const **value); //! Set the value of an attribute of type "clingo_ast_attribute_type_string_array" at the given index. //! //! @param[in] ast the target AST @@ -3717,7 +3938,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_string_at(clingo_ast_t * //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_string_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, size_t index, char const *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_string_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + size_t index, char const *value); //! Remove an element from an attribute of type "clingo_ast_attribute_type_string_array" at the given index. //! //! @param[in] ast the target AST @@ -3725,7 +3947,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_string_at(clingo_ast_t * //! @param[in] index the target index //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_delete_string_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, size_t index); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_delete_string_at(clingo_ast_t *ast, + clingo_ast_attribute_t attribute, size_t index); //! Get the size of an attribute of type "clingo_ast_attribute_type_string_array". //! //! @param[in] ast the target AST @@ -3733,7 +3956,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_delete_string_at(clingo_ast_ //! @param[out] size the resulting size //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_size_string_array(clingo_ast_t *ast, clingo_ast_attribute_t attribute, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_size_string_array(clingo_ast_t *ast, + clingo_ast_attribute_t attribute, size_t *size); //! Insert a value into an attribute of type "clingo_ast_attribute_type_string_array" at the given index. //! //! @param[in] ast the target AST @@ -3743,7 +3967,9 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_size_string_array(clingo_ast //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_insert_string_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, size_t index, char const *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_insert_string_at(clingo_ast_t *ast, + clingo_ast_attribute_t attribute, size_t index, + char const *value); //! @} @@ -3758,7 +3984,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_insert_string_at(clingo_ast_ //! @param[out] value the resulting value //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_ast_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, size_t index, clingo_ast_t **value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_ast_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + size_t index, clingo_ast_t **value); //! Set the value of an attribute of type "clingo_ast_attribute_type_ast_array" at the given index. //! //! @param[in] ast the target AST @@ -3768,7 +3995,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_get_ast_at(clingo_ast_t *ast //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_ast_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, size_t index, clingo_ast_t *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_ast_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + size_t index, clingo_ast_t *value); //! Remove an element from an attribute of type "clingo_ast_attribute_type_ast_array" at the given index. //! //! @param[in] ast the target AST @@ -3776,7 +4004,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_set_ast_at(clingo_ast_t *ast //! @param[in] index the target index //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_delete_ast_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, size_t index); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_delete_ast_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + size_t index); //! Get the size of an attribute of type "clingo_ast_attribute_type_ast_array". //! //! @param[in] ast the target AST @@ -3784,7 +4013,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_delete_ast_at(clingo_ast_t * //! @param[out] size the resulting size //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_size_ast_array(clingo_ast_t *ast, clingo_ast_attribute_t attribute, size_t *size); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_size_ast_array(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + size_t *size); //! Insert a value into an attribute of type "clingo_ast_attribute_type_ast_array" at the given index. //! //! @param[in] ast the target AST @@ -3794,7 +4024,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_size_ast_array(clingo_ast_t //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_insert_ast_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, size_t index, clingo_ast_t *value); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_insert_ast_at(clingo_ast_t *ast, clingo_ast_attribute_t attribute, + size_t index, clingo_ast_t *value); //! @} @@ -3806,7 +4037,7 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_attribute_insert_ast_at(clingo_ast_t * //! @param[in] ast the AST //! @param[in] data a user data pointer //! @return whether the call was successful -typedef bool (*clingo_ast_callback_t) (clingo_ast_t *ast, void *data); +typedef bool (*clingo_ast_callback_t)(clingo_ast_t *ast, void *data); //! Parse the given program and return an abstract syntax tree for each statement via a callback. //! //! @note The control object can be set to a NULL to disable reading input in aspif format. @@ -3821,7 +4052,10 @@ typedef bool (*clingo_ast_callback_t) (clingo_ast_t *ast, void *data); //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime if parsing fails //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_parse_string(char const *program, clingo_ast_callback_t callback, void *callback_data, clingo_control_t *control, clingo_logger_t logger, void *logger_data, unsigned message_limit); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_parse_string(char const *program, clingo_ast_callback_t callback, + void *callback_data, clingo_control_t *control, + clingo_logger_t logger, void *logger_data, + unsigned message_limit); //! Parse the programs in the given list of files and return an abstract syntax tree for each statement via a callback. //! //! The function follows clingo's handling of files on the command line. @@ -3840,7 +4074,10 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_ast_parse_string(char const *program, clin //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_runtime if parsing fails //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_parse_files(char const * const *files, size_t size, clingo_ast_callback_t callback, void *callback_data, clingo_control_t *control, clingo_logger_t logger, void *logger_data, unsigned message_limit); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_parse_files(char const *const *files, size_t size, + clingo_ast_callback_t callback, void *callback_data, + clingo_control_t *control, clingo_logger_t logger, + void *logger_data, unsigned message_limit); //! @} @@ -3857,7 +4094,8 @@ typedef struct clingo_program_builder clingo_program_builder_t; //! @param[in] control the target //! @param[out] builder the program builder object //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_program_builder_init(clingo_control_t *control, clingo_program_builder_t **builder); +CLINGO_VISIBILITY_DEFAULT bool clingo_program_builder_init(clingo_control_t *control, + clingo_program_builder_t **builder); //! Begin building a program. //! //! @param[in] builder the target program builder @@ -3870,7 +4108,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_program_builder_begin(clingo_program_build CLINGO_VISIBILITY_DEFAULT bool clingo_program_builder_end(clingo_program_builder_t *builder); //! Adds a statement to the program. //! -//! @attention @ref clingo_program_builder_begin() must be called before adding statements and @ref clingo_program_builder_end() must be called after all statements have been added. +//! @attention @ref clingo_program_builder_begin() must be called before adding statements and @ref +//! clingo_program_builder_end() must be called after all statements have been added. //! @param[in] builder the target program builder //! @param[in] ast the AST node to add //! @return whether the call was successful; might set one of the following error codes: @@ -3900,7 +4139,8 @@ typedef int clingo_ast_unpool_type_bitset_t; //! @param[in] callback_data user data for the callback //! @return whether the call was successful; might set one of the following error codes: //! - ::clingo_error_bad_alloc -CLINGO_VISIBILITY_DEFAULT bool clingo_ast_unpool(clingo_ast_t *ast, clingo_ast_unpool_type_bitset_t unpool_type, clingo_ast_callback_t callback, void *callback_data); +CLINGO_VISIBILITY_DEFAULT bool clingo_ast_unpool(clingo_ast_t *ast, clingo_ast_unpool_type_bitset_t unpool_type, + clingo_ast_callback_t callback, void *callback_data); //! @} @@ -3958,14 +4198,14 @@ typedef struct clingo_options clingo_options_t; //! @param[in] data user data for the callback //! //! @return whether the call was successful -typedef bool (*clingo_main_function_t) (clingo_control_t *control, char const *const * files, size_t size, void *data); +typedef bool (*clingo_main_function_t)(clingo_control_t *control, char const *const *files, size_t size, void *data); //! Callback to print a model in default format. //! //! @param[in] data user data for the callback //! //! @return whether the call was successful -typedef bool (*clingo_default_model_printer_t) (void *data); +typedef bool (*clingo_default_model_printer_t)(void *data); //! Callback to customize model printing. //! @@ -3975,13 +4215,14 @@ typedef bool (*clingo_default_model_printer_t) (void *data); //! @param[in] data user data for the callback //! //! @return whether the call was successful -typedef bool (*clingo_model_printer_t) (clingo_model_t const *model, clingo_default_model_printer_t printer, void *printer_data, void *data); +typedef bool (*clingo_model_printer_t)(clingo_model_t const *model, clingo_default_model_printer_t printer, + void *printer_data, void *data); //! This struct contains a set of functions to customize the clingo application. typedef struct clingo_application { - char const *(*program_name) (void *data); //!< callback to obtain program name - char const *(*version) (void *data); //!< callback to obtain version information - unsigned (*message_limit) (void *data); //!< callback to obtain message limit + char const *(*program_name)(void *data); //!< callback to obtain program name + char const *(*version)(void *data); //!< callback to obtain version information + unsigned (*message_limit)(void *data); //!< callback to obtain message limit clingo_main_function_t main; //!< callback to override clingo's main function clingo_logger_t logger; //!< callback to override default logger clingo_model_printer_t printer; //!< callback to override default model printing @@ -4008,11 +4249,13 @@ typedef struct clingo_application { //! @param[in] multi whether the option can appear multiple times on the command-line //! @param[in] argument optional string to change the value name in the generated help output //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_options_add(clingo_options_t *options, char const *group, char const *option, char const *description, bool (*parse) (char const *value, void *data), void *data, bool multi, char const *argument); +CLINGO_VISIBILITY_DEFAULT bool clingo_options_add(clingo_options_t *options, char const *group, char const *option, + char const *description, bool (*parse)(char const *value, void *data), + void *data, bool multi, char const *argument); //! Add an option that is a simple flag. //! -//! This function is similar to @ref clingo_options_add() but simpler because it only supports flags, which do not have values. -//! If a flag is passed via the command-line the parameter target is set to true. +//! This function is similar to @ref clingo_options_add() but simpler because it only supports flags, which do not have +//! values. If a flag is passed via the command-line the parameter target is set to true. //! //! @param[in] options object to register the option with //! @param[in] group options are grouped into sections as given by this string @@ -4020,7 +4263,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_options_add(clingo_options_t *options, cha //! @param[in] description the description of the option //! @param[in] target boolean set to true if the flag is given on the command-line //! @return whether the call was successful -CLINGO_VISIBILITY_DEFAULT bool clingo_options_add_flag(clingo_options_t *options, char const *group, char const *option, char const *description, bool *target); +CLINGO_VISIBILITY_DEFAULT bool clingo_options_add_flag(clingo_options_t *options, char const *group, char const *option, + char const *description, bool *target); //! Run clingo with a customized main function (similar to python and lua embedding). //! @@ -4029,7 +4273,8 @@ CLINGO_VISIBILITY_DEFAULT bool clingo_options_add_flag(clingo_options_t *options //! @param[in] size number of arguments //! @param[in] data user data to pass to callbacks in application //! @return exit code to return from main function -CLINGO_VISIBILITY_DEFAULT int clingo_main(clingo_application_t *application, char const *const * arguments, size_t size, void *data); +CLINGO_VISIBILITY_DEFAULT int clingo_main(clingo_application_t *application, char const *const *arguments, size_t size, + void *data); //! Custom scripting language to run functions during grounding. typedef struct clingo_script { @@ -4038,7 +4283,7 @@ typedef struct clingo_script { //! @param[in] code the code to evaluate //! @param[in] data user data as given when registering the script //! @return whether the function call was successful - bool (*execute) (clingo_location_t const *location, char const *code, void *data); + bool (*execute)(clingo_location_t const *location, char const *code, void *data); //! Call the function with the given name and arguments. //! @param[in] location the location in the logic program of the function call //! @param[in] name the name of the function @@ -4048,21 +4293,23 @@ typedef struct clingo_script { //! @param[in] symbol_callback_data user data for the symbol callback //! @param[in] data user data as given when registering the script //! @return whether the function call was successful - bool (*call) (clingo_location_t const *location, char const *name, clingo_symbol_t const *arguments, size_t arguments_size, clingo_symbol_callback_t symbol_callback, void *symbol_callback_data, void *data); + bool (*call)(clingo_location_t const *location, char const *name, clingo_symbol_t const *arguments, + size_t arguments_size, clingo_symbol_callback_t symbol_callback, void *symbol_callback_data, + void *data); //! Check if the given function is callable. //! @param[in] name the name of the function //! @param[out] result whether the function is callable //! @param[in] data user data as given when registering the script //! @return whether the function call was successful - bool (*callable) (char const * name, bool *result, void *data); + bool (*callable)(char const *name, bool *result, void *data); //! Run the main function. //! @param[in] control the control object to pass to the main function //! @param[in] data user data as given when registering the script //! @return whether the function call was successful - bool (*main) (clingo_control_t *control, void *data); + bool (*main)(clingo_control_t *control, void *data); //! This function is called once when the script is deleted. //! @param[in] data user data as given when registering the script - void (*free) (void *data); + void (*free)(void *data); char const *version; } clingo_script_t; diff --git a/libclingo/clingo.hh b/libclingo/clingo.hh index 73b6314b8..1dd6e70de 100644 --- a/libclingo/clingo.hh +++ b/libclingo/clingo.hh @@ -25,20 +25,20 @@ #ifndef CLINGO_HH #define CLINGO_HH +#include +#include +#include #include -#include #include +#include #include -#include -#include -#include -#include -#include +#include #include +#include +#include #include -#include -#include -#include +#include +#include #include @@ -50,38 +50,28 @@ constexpr unsigned g_message_limit = 20; namespace Detail { -template -T cast(U u) { +template T cast(U u) { return reinterpret_cast(u); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) } -template -struct TypeInList : std::false_type { }; +template struct TypeInList : std::false_type {}; -template -struct TypeInList : std::true_type { }; +template struct TypeInList : std::true_type {}; -template -struct TypeInList : TypeInList { }; +template struct TypeInList : TypeInList {}; -template -struct VariantHolder; +template struct VariantHolder; -template -struct VariantHolder { +template struct VariantHolder { bool check_type() const { return type_ == 0; } - void emplace() { } - void emplace2() { } - void copy(VariantHolder const &h) { - static_cast(h); - } + void emplace() {} + void emplace2() {} + void copy(VariantHolder const &h) { static_cast(h); } void destroy() { type_ = 0; data_ = nullptr; } - void print(std::ostream &out) const { - static_cast(out); - } + void print(std::ostream &out) const { static_cast(out); } void swap(VariantHolder &other) noexcept { std::swap(type_, other.type_); std::swap(data_, other.data_); @@ -90,104 +80,97 @@ struct VariantHolder { void *data_ = nullptr; }; -template -struct VariantHolder : VariantHolder{ - using Helper = VariantHolder; +template struct VariantHolder : VariantHolder { + using Helper = VariantHolder; using Helper::check_type; + using Helper::data_; using Helper::emplace; using Helper::emplace2; - using Helper::data_; using Helper::type_; bool check_type(T *v) const { static_cast(v); return type_ == n; } - template - void emplace(T *v, Args&& ...x) { + template void emplace(T *v, Args &&...x) { static_cast(v); data_ = new T{std::forward(x)...}; // NOLINT type_ = n; } // NOTE: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1467 - template - void emplace2(T *v, Args&& ...x) { + template void emplace2(T *v, Args &&...x) { static_cast(v); data_ = new T(std::forward(x)...); // NOLINT type_ = n; } void copy(VariantHolder const &src) { if (src.type_ == n) { - data_ = new T(*static_cast(src.data_)); // NOLINT + data_ = new T(*static_cast(src.data_)); // NOLINT type_ = src.type_; } Helper::copy(src); } // NOTE: workaround for visual studio (C++14 can also simply use auto) -# define CLINGO_VARIANT_RETURN(Type) decltype(std::declval().visit(std::declval(), std::declval()...)) // NOLINT - template - using Ret_ = CLINGO_VARIANT_RETURN(T); - template - using ConstRet_ = CLINGO_VARIANT_RETURN(T const); +#define CLINGO_VARIANT_RETURN(Type) \ + decltype(std::declval().visit(std::declval(), std::declval()...)) // NOLINT + template using Ret_ = CLINGO_VARIANT_RETURN(T); + template using ConstRet_ = CLINGO_VARIANT_RETURN(T const); // non-const template - auto accept_(V &&visitor, Args &&... args) -> CLINGO_VARIANT_RETURN(T) { + auto accept_(V &&visitor, Args &&...args) -> CLINGO_VARIANT_RETURN(T) { static_assert(std::is_same, typename Helper::template Ret_>::value, ""); - return n == type_ - ? visitor.visit(*static_cast(data_), std::forward(args)...) - : Helper::template accept(std::forward(visitor), std::forward(args)...); + return n == type_ ? visitor.visit(*static_cast(data_), std::forward(args)...) + : Helper::template accept(std::forward(visitor), std::forward(args)...); } - template - auto accept_(V &&visitor, Args &&... args) -> CLINGO_VARIANT_RETURN(T) { + template auto accept_(V &&visitor, Args &&...args) -> CLINGO_VARIANT_RETURN(T) { assert(n == type_); - return std::forward(visitor).visit(*static_cast(data_), std::forward(args)...); + return std::forward(visitor).visit(*static_cast(data_), std::forward(args)...); } - template - auto accept(V &&visitor, Args &&... args) -> CLINGO_VARIANT_RETURN(T) { + template auto accept(V &&visitor, Args &&...args) -> CLINGO_VARIANT_RETURN(T) { return accept_(std::forward(visitor), std::forward(args)...); } // const template - auto accept_(V &&visitor, Args &&... args) const -> CLINGO_VARIANT_RETURN(T const) { + auto accept_(V &&visitor, Args &&...args) const -> CLINGO_VARIANT_RETURN(T const) { static_assert(std::is_same, typename Helper::template ConstRet_>::value, ""); - return n == type_ - ? visitor.visit(*static_cast(data_), std::forward(args)...) - : Helper::template accept(std::forward(visitor), std::forward(args)...); + return n == type_ ? visitor.visit(*static_cast(data_), std::forward(args)...) + : Helper::template accept(std::forward(visitor), std::forward(args)...); } template - auto accept_(V &&visitor, Args &&... args) const -> CLINGO_VARIANT_RETURN(T const) { + auto accept_(V &&visitor, Args &&...args) const -> CLINGO_VARIANT_RETURN(T const) { assert(n == type_); return std::forward(visitor).visit(*static_cast(data_), std::forward(args)...); } - template - auto accept(V &&visitor, Args &&... args) const -> CLINGO_VARIANT_RETURN(T const) { + template auto accept(V &&visitor, Args &&...args) const -> CLINGO_VARIANT_RETURN(T const) { return accept_(std::forward(visitor), std::forward(args)...); } -# undef CLINGO_VARIANT_RETURN +#undef CLINGO_VARIANT_RETURN void destroy() { - if (n == type_) { delete static_cast(data_); } + if (n == type_) { + delete static_cast(data_); + } Helper::destroy(); } void print(std::ostream &out) const { - if (n == type_) { out << *static_cast(data_); } + if (n == type_) { + out << *static_cast(data_); + } Helper::print(out); } }; -} // Detail +} // namespace Detail -template -class Optional { -public: +template class Optional { + public: Optional() = default; ~Optional() = default; - Optional(T const &x) : data_(new T(x)) { } - Optional(T &x) : data_(new T(x)) { } - Optional(T &&x) noexcept : data_(std::make_unique(std::move(x))) { } - template - Optional(Args&&... x) : data_(new T{std::forward(x)...}) { } - Optional(Optional &&opt) noexcept : data_(opt.data_.release()) { } - Optional(Optional &opt) : data_(opt ? new T(*opt) : nullptr) { } - Optional(Optional const &opt) : data_(opt ? new T(*opt) : nullptr) { } + Optional(T const &x) : data_(new T(x)) {} + Optional(T &x) : data_(new T(x)) {} + Optional(T &&x) noexcept : data_(std::make_unique(std::move(x))) {} + template Optional(Args &&...x) : data_(new T{std::forward(x)...}) {} + Optional(Optional &&opt) noexcept : data_(opt.data_.release()) {} + Optional(Optional &opt) : data_(opt ? new T(*opt) : nullptr) {} + Optional(Optional const &opt) : data_(opt ? new T(*opt) : nullptr) {} Optional &operator=(T const &x) { clear(); data_.reset(new T(x)); @@ -220,39 +203,37 @@ public: T const &operator*() const & { return *get(); } T &&operator*() && { return std::move(*get()); } T const &&operator*() const && { return std::move(*get()); } - template - void emplace(Args&&... x) { + template void emplace(Args &&...x) { clear(); data_(new T{std::forward(x)...}); } void clear() { data_.reset(nullptr); } explicit operator bool() const { return data_ != nullptr; } -private: + + private: std::unique_ptr data_; }; -template -class Variant { +template class Variant { using Holder = Detail::VariantHolder<1, T...>; -public: - Variant(Variant const &other) : Variant(other.data_) { } + + public: + Variant(Variant const &other) : Variant(other.data_) {} Variant(Variant &&other) noexcept { data_.swap(other.data_); } - template - Variant(U &&u, std::enable_if_t::value> *t = nullptr) { + template Variant(U &&u, std::enable_if_t::value> *t = nullptr) { static_cast(t); emplace2(std::forward(u)); } - template - Variant(U &u, std::enable_if_t::value> *t = nullptr) { + template Variant(U &u, std::enable_if_t::value> *t = nullptr) { static_cast(t); emplace2(u); } - template - Variant(U const &u, typename std::enable_if_t::value> *t = nullptr) { emplace2(u); } - template - static Variant make(Args&& ...args) { + template Variant(U const &u, typename std::enable_if_t::value> *t = nullptr) { + emplace2(u); + } + template static Variant make(Args &&...args) { Variant x; - x.data_.emplace(static_cast(nullptr), std::forward(args)...); + x.data_.emplace(static_cast(nullptr), std::forward(args)...); return x; } ~Variant() { data_.destroy(); } @@ -279,31 +260,30 @@ public: emplace2(u); return *this; } - template - U &get() { - if (!data_.check_type(static_cast(nullptr))) { throw std::bad_cast(); } - return *static_cast(data_.data_); + template U &get() { + if (!data_.check_type(static_cast(nullptr))) { + throw std::bad_cast(); + } + return *static_cast(data_.data_); } - template - U const &get() const { - if (!data_.check_type(static_cast(nullptr))) { throw std::bad_cast(); } - return *static_cast(data_.data_); + template U const &get() const { + if (!data_.check_type(static_cast(nullptr))) { + throw std::bad_cast(); + } + return *static_cast(data_.data_); } - template - void emplace(Args&& ...args) { + template void emplace(Args &&...args) { Variant x; - x.data_.emplace(static_cast(nullptr), std::forward(args)...); + x.data_.emplace(static_cast(nullptr), std::forward(args)...); data_.swap(x.data_); } - template - bool is() const { return data_.check_type(static_cast(nullptr)); } + template bool is() const { return data_.check_type(static_cast(nullptr)); } void swap(Variant &other) noexcept { data_.swap(other.data_); } - template - typename Holder::template Ret_ accept(V &&visitor, Args &&... args) { + template typename Holder::template Ret_ accept(V &&visitor, Args &&...args) { return data_.accept(std::forward(visitor), std::forward(args)...); } template - typename Holder::template ConstRet_ accept(V &&visitor, Args &&... args) const { + typename Holder::template ConstRet_ accept(V &&visitor, Args &&...args) const { return data_.accept(std::forward(visitor), std::forward(args)...); } friend std::ostream &operator<<(std::ostream &out, Variant const &x) { @@ -311,11 +291,9 @@ public: return out; } -private: + private: Variant() = default; - Variant(Holder const &data) { - data_.copy(data); - } + Variant(Holder const &data) { data_.copy(data); } Variant &operator=(Holder const &data) { Variant x(data); data_.swap(x.data_); @@ -330,10 +308,9 @@ private: x.swap(data_); return *this; } - template - void emplace2(Args&& ...args) { + template void emplace2(Args &&...args) { Variant x; - x.data_.emplace2(static_cast(nullptr), std::forward(args)...); + x.data_.emplace2(static_cast(nullptr), std::forward(args)...); data_.swap(x.data_); } @@ -342,14 +319,11 @@ private: // {{{1 span -template -class IteratorRange { -public: +template class IteratorRange { + public: using reference = typename Iterator::reference; using difference_type = typename Iterator::difference_type; - IteratorRange(Iterator begin, Iterator end) - : begin_(begin) - , end_(end) { } + IteratorRange(Iterator begin, Iterator end) : begin_(begin), end_(end) {} reference operator[](difference_type n) { auto it = begin_; std::advance(it, n); @@ -359,147 +333,145 @@ public: bool empty() { return begin_ == end_; } Iterator begin() { return begin_; } Iterator end() { return end_; } -private: + + private: Iterator begin_; Iterator end_; }; -template -IteratorRange make_range(Iterator ib, Iterator ie) { - return {ib, ie}; -} +template IteratorRange make_range(Iterator ib, Iterator ie) { return {ib, ie}; } -template -class ValuePointer { -public: - ValuePointer(T value) : value_(std::move(value)) { } +template class ValuePointer { + public: + ValuePointer(T value) : value_(std::move(value)) {} T &operator*() { return value_; } T *operator->() { return &value_; } -private: + + private: T value_; }; -template > -class ArrayIterator { -public: +template > class ArrayIterator { + public: using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = ptrdiff_t; using pointer = P; using reference = T; - explicit ArrayIterator(A arr, size_t index = 0) - : arr_(std::move(arr)) - , index_(index) { } - ArrayIterator& operator++() { ++index_; return *this; } + explicit ArrayIterator(A arr, size_t index = 0) : arr_(std::move(arr)), index_(index) {} + ArrayIterator &operator++() { + ++index_; + return *this; + } ArrayIterator operator++(int) { ArrayIterator t(*this); ++*this; return t; } - ArrayIterator& operator--() { --index_; return *this; } + ArrayIterator &operator--() { + --index_; + return *this; + } ArrayIterator operator--(int) { ArrayIterator t(*this); --*this; return t; } - ArrayIterator& operator+=(difference_type n) { index_ += n; return *this; } - ArrayIterator& operator-=(difference_type n) { index_ -= n; return *this; } - friend ArrayIterator operator+(ArrayIterator it, difference_type n) { return ArrayIterator{it.arr_, it.index_ + n}; } - friend ArrayIterator operator+(difference_type n, ArrayIterator it) { return ArrayIterator{it.arr_, it.index_ + n}; } - friend ArrayIterator operator-(ArrayIterator it, difference_type n) { return ArrayIterator{it.arr_, it.index_ - n}; } - friend difference_type operator-(ArrayIterator a, ArrayIterator b) { return a.index_ - b.index_; } + ArrayIterator &operator+=(difference_type n) { + index_ += n; + return *this; + } + ArrayIterator &operator-=(difference_type n) { + index_ -= n; + return *this; + } + friend ArrayIterator operator+(ArrayIterator it, difference_type n) { + return ArrayIterator{it.arr_, it.index_ + n}; + } + friend ArrayIterator operator+(difference_type n, ArrayIterator it) { + return ArrayIterator{it.arr_, it.index_ + n}; + } + friend ArrayIterator operator-(ArrayIterator it, difference_type n) { + return ArrayIterator{it.arr_, it.index_ - n}; + } + friend difference_type operator-(ArrayIterator a, ArrayIterator b) { return a.index_ - b.index_; } reference operator*() { return arr_->operator[](index_); } pointer operator->() { return arr_->at(index_); } - friend void swap(ArrayIterator& lhs, ArrayIterator& rhs) noexcept { + friend void swap(ArrayIterator &lhs, ArrayIterator &rhs) noexcept { std::swap(lhs.arr_, rhs.arr_); std::swap(lhs.index_, rhs.index_); } friend bool operator==(ArrayIterator lhs, ArrayIterator rhs) { return lhs.index_ == rhs.index_; } friend bool operator!=(ArrayIterator lhs, ArrayIterator rhs) { return !(lhs == rhs); } - friend bool operator< (ArrayIterator lhs, ArrayIterator rhs) { return (lhs.index_ + 1) < (rhs.index_ + 1); } - friend bool operator> (ArrayIterator lhs, ArrayIterator rhs) { return rhs < lhs; } + friend bool operator<(ArrayIterator lhs, ArrayIterator rhs) { return (lhs.index_ + 1) < (rhs.index_ + 1); } + friend bool operator>(ArrayIterator lhs, ArrayIterator rhs) { return rhs < lhs; } friend bool operator<=(ArrayIterator lhs, ArrayIterator rhs) { return !(lhs > rhs); } friend bool operator>=(ArrayIterator lhs, ArrayIterator rhs) { return !(lhs < rhs); } -private: + + private: A arr_; size_t index_; }; -template -struct ToIterator { +template struct ToIterator { T const *operator()(T const *x) const { return x; } }; -template > -class Span : private I { -public: +template > class Span : private I { + public: #if __cplusplus >= 201703L using IteratorType = typename std::invoke_result_t; #else using IteratorType = std::result_of_t; #endif using ReferenceType = decltype(*std::declval()); - Span(I to_it = I()) - : Span(nullptr, size_t(0), to_it) { } - template - Span(U const *begin, size_t size) - : Span(static_cast(begin), size) { } - Span(T const *begin, size_t size, I to_it = I()) - : Span(begin, begin + size, to_it) { } // NOLINT - Span(std::initializer_list c, I to_it = I()) - : Span(c.size() > 0 ? &*c.begin() : nullptr, c.size(), to_it) { } - template - Span(U const &c, I to_it = I()) - : Span(!c.empty() ? &*c.begin() : nullptr, c.size(), to_it) { } - Span(T const *begin, T const *end, I to_it = I()) - : I(to_it) - , begin_(begin) - , end_(end) { } + Span(I to_it = I()) : Span(nullptr, size_t(0), to_it) {} + template Span(U const *begin, size_t size) : Span(static_cast(begin), size) {} + Span(T const *begin, size_t size, I to_it = I()) : Span(begin, begin + size, to_it) {} // NOLINT + Span(std::initializer_list c, I to_it = I()) : Span(c.size() > 0 ? &*c.begin() : nullptr, c.size(), to_it) {} + template Span(U const &c, I to_it = I()) : Span(!c.empty() ? &*c.begin() : nullptr, c.size(), to_it) {} + Span(T const *begin, T const *end, I to_it = I()) : I(to_it), begin_(begin), end_(end) {} IteratorType begin() const { return I::operator()(begin_); } IteratorType end() const { return I::operator()(end_); } ReferenceType operator[](size_t offset) const { return *(begin() + offset); } ReferenceType front() const { return *begin(); } - ReferenceType back() const { return *I::operator()(end_-1); } + ReferenceType back() const { return *I::operator()(end_ - 1); } T const *data() const { return begin_; } size_t size() const { return end_ - begin_; } bool empty() const { return begin_ == end_; } -private: + + private: T const *begin_; T const *end_; }; -template -inline typename Span::IteratorType begin(Span const &span) { +template inline typename Span::IteratorType begin(Span const &span) { return span.begin(); } -template -inline typename Span::IteratorType end(Span const& span) { - return span.end(); -} +template inline typename Span::IteratorType end(Span const &span) { return span.end(); } -template > -inline Span make_span(T const *begin, size_t size, I to_it = I()) { +template > inline Span make_span(T const *begin, size_t size, I to_it = I()) { return {begin, size, std::move(to_it)}; } -template -bool equal_range(T const &a, U const &b) { +template bool equal_range(T const &a, U const &b) { using namespace std; return a.size() == b.size() && std::equal(begin(a), end(a), begin(b)); } -template -bool operator==(Span const &a, Span const &b) { return equal_range(a, b); } +template bool operator==(Span const &a, Span const &b) { return equal_range(a, b); } -template -std::ostream &operator<<(std::ostream &out, Span const &span) { +template std::ostream &operator<<(std::ostream &out, Span const &span) { out << "{"; bool comma = false; for (auto &x : span) { - if (comma) { out << ", "; } - else { out << " "; } + if (comma) { + out << ", "; + } else { + out << " "; + } out << x; comma = true; } @@ -516,31 +488,39 @@ using weight_t = clingo_weight_t; using atom_t = clingo_atom_t; class WeightedLiteral { -public: - WeightedLiteral(clingo_literal_t lit, clingo_weight_t weight) - : wlit_{lit, weight} { } - explicit WeightedLiteral(clingo_weighted_literal_t wlit) - : wlit_(wlit) { } + public: + WeightedLiteral(clingo_literal_t lit, clingo_weight_t weight) : wlit_{lit, weight} {} + explicit WeightedLiteral(clingo_weighted_literal_t wlit) : wlit_(wlit) {} literal_t literal() const { return wlit_.literal; } weight_t weight() const { return wlit_.weight; } clingo_weighted_literal_t const &to_c() const { return wlit_; } clingo_weighted_literal_t &to_c() { return wlit_; } -private: + + private: clingo_weighted_literal_t wlit_; }; using WeightedLiteralSpan = Span; enum class TruthValue { - Free = clingo_truth_value_free, - True = clingo_truth_value_true, + Free = clingo_truth_value_free, + True = clingo_truth_value_true, False = clingo_truth_value_false }; inline std::ostream &operator<<(std::ostream &out, TruthValue tv) { switch (tv) { - case TruthValue::Free: { out << "Free"; break; } - case TruthValue::True: { out << "True"; break; } - case TruthValue::False: { out << "False"; break; } + case TruthValue::Free: { + out << "Free"; + break; + } + case TruthValue::True: { + out << "True"; + break; + } + case TruthValue::False: { + out << "False"; + break; + } } return out; } @@ -548,9 +528,8 @@ inline std::ostream &operator<<(std::ostream &out, TruthValue tv) { // {{{1 signature class Signature { -public: - explicit Signature(clingo_signature_t sig) - : sig_(sig) { } + public: + explicit Signature(clingo_signature_t sig) : sig_(sig) {} Signature(char const *name, uint32_t arity, bool positive = true); char const *name() const; uint32_t arity() const; @@ -560,7 +539,8 @@ public: clingo_signature_t const &to_c() const { return sig_; } clingo_signature_t &to_c() { return sig_; } -private: + + private: clingo_signature_t sig_; }; @@ -570,26 +550,27 @@ inline std::ostream &operator<<(std::ostream &out, Signature sig) { } bool operator==(Signature a, Signature b); bool operator!=(Signature a, Signature b); -bool operator< (Signature a, Signature b); +bool operator<(Signature a, Signature b); bool operator<=(Signature a, Signature b); -bool operator> (Signature a, Signature b); +bool operator>(Signature a, Signature b); bool operator>=(Signature a, Signature b); -} namespace std { +} // namespace Clingo +namespace std { -template<> -struct hash { +template <> struct hash { size_t operator()(Clingo::Signature sig) const { return sig.hash(); } }; -} namespace Clingo { +} // namespace std +namespace Clingo { // {{{1 symbol enum class SymbolType : clingo_symbol_type_t { - Infimum = clingo_symbol_type_infimum, - Number = clingo_symbol_type_number, - String = clingo_symbol_type_string, + Infimum = clingo_symbol_type_infimum, + Number = clingo_symbol_type_number, + String = clingo_symbol_type_string, Function = clingo_symbol_type_function, Supremum = clingo_symbol_type_supremum }; @@ -597,10 +578,10 @@ enum class SymbolType : clingo_symbol_type_t { class Symbol; using SymbolSpan = Span; using SymbolVector = std::vector; -using SymbolSpanCallback = std::function; +using SymbolSpanCallback = std::function; class Symbol { -public: + public: Symbol(); explicit Symbol(clingo_symbol_t c_sym); int number() const; @@ -615,7 +596,8 @@ public: size_t hash() const; clingo_symbol_t &to_c() { return sym_; } clingo_symbol_t const &to_c() const { return sym_; } -private: + + private: clingo_symbol_t sym_ = 0; }; @@ -629,53 +611,55 @@ Symbol Function(char const *name, SymbolSpan args, bool positive = true); std::ostream &operator<<(std::ostream &out, Symbol sym); bool operator==(Symbol a, Symbol b); bool operator!=(Symbol a, Symbol b); -bool operator< (Symbol a, Symbol b); +bool operator<(Symbol a, Symbol b); bool operator<=(Symbol a, Symbol b); -bool operator> (Symbol a, Symbol b); +bool operator>(Symbol a, Symbol b); bool operator>=(Symbol a, Symbol b); -} namespace std { +} // namespace Clingo +namespace std { -template<> -struct hash { +template <> struct hash { size_t operator()(Clingo::Symbol sym) const { return sym.hash(); } }; -} namespace Clingo { +} // namespace std +namespace Clingo { // {{{1 symbolic atoms class SymbolicAtom { friend class SymbolicAtomIterator; -public: + + public: explicit SymbolicAtom(clingo_symbolic_atoms_t const *atoms, clingo_symbolic_atom_iterator_t range) - : atoms_(atoms) - , range_(range) { } + : atoms_(atoms), range_(range) {} Symbol symbol() const; literal_t literal() const; bool is_fact() const; bool is_external() const; bool match(char const *name, unsigned arity) const; clingo_symbolic_atom_iterator_t to_c() const { return range_; } -private: + + private: clingo_symbolic_atoms_t const *atoms_; clingo_symbolic_atom_iterator_t range_; }; class SymbolicAtomIterator : private SymbolicAtom { -public: + public: using iterator_category = std::input_iterator_tag; using value_type = SymbolicAtom; using difference_type = ptrdiff_t; - using pointer = SymbolicAtom*; - using reference = SymbolicAtom&; + using pointer = SymbolicAtom *; + using reference = SymbolicAtom &; explicit SymbolicAtomIterator(clingo_symbolic_atoms_t const *atoms, clingo_symbolic_atom_iterator_t range) - : SymbolicAtom{atoms, range} { } + : SymbolicAtom{atoms, range} {} SymbolicAtom &operator*() { return *this; } SymbolicAtom *operator->() { return this; } SymbolicAtomIterator &operator++(); - SymbolicAtomIterator operator++ (int) { + SymbolicAtomIterator operator++(int) { auto range = range_; ++(*this); return SymbolicAtomIterator{atoms_, range}; @@ -687,9 +671,8 @@ public: }; class SymbolicAtoms { -public: - explicit SymbolicAtoms(clingo_symbolic_atoms_t const *atoms) - : atoms_(atoms) { } + public: + explicit SymbolicAtoms(clingo_symbolic_atoms_t const *atoms) : atoms_(atoms) {} SymbolicAtomIterator begin() const; SymbolicAtomIterator begin(Signature sig) const; SymbolicAtomIterator end() const; @@ -698,7 +681,8 @@ public: size_t length() const; clingo_symbolic_atoms_t const *to_c() const { return atoms_; } SymbolicAtom operator[](Symbol atom) const { return *find(atom); } -private: + + private: clingo_symbolic_atoms_t const *atoms_; }; @@ -713,65 +697,77 @@ enum class TheoryTermType : clingo_theory_term_type_t { Symbol = clingo_theory_term_type_symbol }; -template -class TheoryIterator { -public: +template class TheoryIterator { + public: using iterator_category = std::random_access_iterator_tag; using value_type = T const; using difference_type = ptrdiff_t; - using pointer = T*; + using pointer = T *; using reference = T; - explicit TheoryIterator(clingo_theory_atoms_t const *atoms, clingo_id_t const* id) - : elem_(atoms) - , id_(id) { } - TheoryIterator& operator++() { ++id_; return *this; } // NOLINT + explicit TheoryIterator(clingo_theory_atoms_t const *atoms, clingo_id_t const *id) : elem_(atoms), id_(id) {} + TheoryIterator &operator++() { + ++id_; + return *this; + } // NOLINT TheoryIterator operator++(int) { TheoryIterator t(*this); ++*this; return t; } - TheoryIterator& operator--() { --id_; return *this; } // NOLINT + TheoryIterator &operator--() { + --id_; + return *this; + } // NOLINT TheoryIterator operator--(int) { TheoryIterator t(*this); --*this; return t; } - TheoryIterator& operator+=(difference_type n) { id_ += n; return *this; } // NOLINT - TheoryIterator& operator-=(difference_type n) { id_ -= n; return *this; } // NOLINT - friend TheoryIterator operator+(TheoryIterator it, difference_type n) { return TheoryIterator{it.atoms(), it.id_ + n}; } - friend TheoryIterator operator+(difference_type n, TheoryIterator it) { return TheoryIterator{it.atoms(), it.id_ + n}; } - friend TheoryIterator operator-(TheoryIterator it, difference_type n) { return TheoryIterator{it.atoms(), it.id_ - n}; } - friend difference_type operator-(TheoryIterator a, TheoryIterator b) { return a.id_ - b.id_; } + TheoryIterator &operator+=(difference_type n) { + id_ += n; + return *this; + } // NOLINT + TheoryIterator &operator-=(difference_type n) { + id_ -= n; + return *this; + } // NOLINT + friend TheoryIterator operator+(TheoryIterator it, difference_type n) { + return TheoryIterator{it.atoms(), it.id_ + n}; + } + friend TheoryIterator operator+(difference_type n, TheoryIterator it) { + return TheoryIterator{it.atoms(), it.id_ + n}; + } + friend TheoryIterator operator-(TheoryIterator it, difference_type n) { + return TheoryIterator{it.atoms(), it.id_ - n}; + } + friend difference_type operator-(TheoryIterator a, TheoryIterator b) { return a.id_ - b.id_; } T operator*() { return elem_ = *id_; } T *operator->() { return &(elem_ = *id_); } - friend void swap(TheoryIterator& lhs, TheoryIterator& rhs) noexcept { + friend void swap(TheoryIterator &lhs, TheoryIterator &rhs) noexcept { std::swap(lhs.id_, rhs.id_); std::swap(lhs.elem_, rhs.elem_); } friend bool operator==(TheoryIterator lhs, TheoryIterator rhs) { return lhs.id_ == rhs.id_; } friend bool operator!=(TheoryIterator lhs, TheoryIterator rhs) { return !(lhs == rhs); } - friend bool operator< (TheoryIterator lhs, TheoryIterator rhs) { return lhs.id_ < rhs.id_; } - friend bool operator> (TheoryIterator lhs, TheoryIterator rhs) { return rhs < lhs; } + friend bool operator<(TheoryIterator lhs, TheoryIterator rhs) { return lhs.id_ < rhs.id_; } + friend bool operator>(TheoryIterator lhs, TheoryIterator rhs) { return rhs < lhs; } friend bool operator<=(TheoryIterator lhs, TheoryIterator rhs) { return !(lhs > rhs); } friend bool operator>=(TheoryIterator lhs, TheoryIterator rhs) { return !(lhs < rhs); } -private: + private: clingo_theory_atoms_t const *&atoms() { return elem_.atoms_; } - T elem_; + T elem_; clingo_id_t const *id_; }; -template -class ToTheoryIterator { -public: - explicit ToTheoryIterator(clingo_theory_atoms_t const *atoms) - : atoms_(atoms) { } - T operator ()(clingo_id_t const *id) const { - return T{atoms_, id}; - } -private: +template class ToTheoryIterator { + public: + explicit ToTheoryIterator(clingo_theory_atoms_t const *atoms) : atoms_(atoms) {} + T operator()(clingo_id_t const *id) const { return T{atoms_, id}; } + + private: clingo_theory_atoms_t const *atoms_; }; @@ -781,19 +777,18 @@ using TheoryTermSpan = Span>; class TheoryTerm { friend class TheoryIterator; -public: - explicit TheoryTerm(clingo_theory_atoms_t const *atoms, clingo_id_t id) - : atoms_(atoms) - , id_(id) { } + + public: + explicit TheoryTerm(clingo_theory_atoms_t const *atoms, clingo_id_t id) : atoms_(atoms), id_(id) {} TheoryTermType type() const; int number() const; char const *name() const; TheoryTermSpan arguments() const; clingo_id_t to_c() const { return id_; } std::string to_string() const; -private: - TheoryTerm(clingo_theory_atoms_t const *atoms) - : TheoryTerm(atoms, 0) { } + + private: + TheoryTerm(clingo_theory_atoms_t const *atoms) : TheoryTerm(atoms, 0) {} TheoryTerm &operator=(clingo_id_t id) { id_ = id; return *this; @@ -811,18 +806,17 @@ using LiteralSpan = Span; class TheoryElement { friend class TheoryIterator; -public: - explicit TheoryElement(clingo_theory_atoms_t const *atoms, clingo_id_t id) - : atoms_(atoms) - , id_(id) { } + + public: + explicit TheoryElement(clingo_theory_atoms_t const *atoms, clingo_id_t id) : atoms_(atoms), id_(id) {} TheoryTermSpan tuple() const; LiteralSpan condition() const; literal_t condition_id() const; std::string to_string() const; clingo_id_t to_c() const { return id_; } -private: - TheoryElement(clingo_theory_atoms_t const *atoms) - : TheoryElement(atoms, 0) { } + + private: + TheoryElement(clingo_theory_atoms_t const *atoms) : TheoryElement(atoms, 0) {} TheoryElement &operator=(clingo_id_t id) { id_ = id; return *this; @@ -835,10 +829,9 @@ std::ostream &operator<<(std::ostream &out, TheoryElement term); class TheoryAtom { friend class TheoryAtomIterator; -public: - explicit TheoryAtom(clingo_theory_atoms_t const *atoms, clingo_id_t id) - : atoms_(atoms) - , id_(id) { } + + public: + explicit TheoryAtom(clingo_theory_atoms_t const *atoms, clingo_id_t id) : atoms_(atoms), id_(id) {} TheoryElementSpan elements() const; TheoryTerm term() const; bool has_guard() const; @@ -846,9 +839,9 @@ public: std::pair guard() const; std::string to_string() const; clingo_id_t to_c() const { return id_; } -private: - TheoryAtom(clingo_theory_atoms_t const *atoms) - : TheoryAtom(atoms, 0) { } + + private: + TheoryAtom(clingo_theory_atoms_t const *atoms) : TheoryAtom(atoms, 0) {} TheoryAtom &operator=(clingo_id_t id) { id_ = id; return *this; @@ -860,115 +853,154 @@ private: std::ostream &operator<<(std::ostream &out, TheoryAtom term); class TheoryAtomIterator : private TheoryAtom { -public: + public: using iterator_category = std::random_access_iterator_tag; using value_type = TheoryAtom; using difference_type = ptrdiff_t; - using pointer = TheoryAtom*; + using pointer = TheoryAtom *; using reference = TheoryAtom; - explicit TheoryAtomIterator(clingo_theory_atoms_t const *atoms, clingo_id_t id) - : TheoryAtom{atoms, id} { } - TheoryAtomIterator& operator++() { ++id_; return *this; } + explicit TheoryAtomIterator(clingo_theory_atoms_t const *atoms, clingo_id_t id) : TheoryAtom{atoms, id} {} + TheoryAtomIterator &operator++() { + ++id_; + return *this; + } TheoryAtomIterator operator++(int) { auto t = *this; ++*this; return t; } - TheoryAtomIterator& operator--() { --id_; return *this; } + TheoryAtomIterator &operator--() { + --id_; + return *this; + } TheoryAtomIterator operator--(int) { auto t = *this; --*this; return t; } - TheoryAtomIterator& operator+=(difference_type n) { id_ += static_cast(n); return *this; } - TheoryAtomIterator& operator-=(difference_type n) { id_ -= static_cast(n); return *this; } - friend TheoryAtomIterator operator+(TheoryAtomIterator it, difference_type n) { return TheoryAtomIterator{it.atoms(), clingo_id_t(it.id() + n)}; } - friend TheoryAtomIterator operator+(difference_type n, TheoryAtomIterator it) { return TheoryAtomIterator{it.atoms(), clingo_id_t(it.id() + n)}; } - friend TheoryAtomIterator operator-(TheoryAtomIterator it, difference_type n) { return TheoryAtomIterator{it.atoms(), clingo_id_t(it.id() - n)}; } - friend difference_type operator-(TheoryAtomIterator a, TheoryAtomIterator b) { return a.id() - b.id(); } + TheoryAtomIterator &operator+=(difference_type n) { + id_ += static_cast(n); + return *this; + } + TheoryAtomIterator &operator-=(difference_type n) { + id_ -= static_cast(n); + return *this; + } + friend TheoryAtomIterator operator+(TheoryAtomIterator it, difference_type n) { + return TheoryAtomIterator{it.atoms(), clingo_id_t(it.id() + n)}; + } + friend TheoryAtomIterator operator+(difference_type n, TheoryAtomIterator it) { + return TheoryAtomIterator{it.atoms(), clingo_id_t(it.id() + n)}; + } + friend TheoryAtomIterator operator-(TheoryAtomIterator it, difference_type n) { + return TheoryAtomIterator{it.atoms(), clingo_id_t(it.id() - n)}; + } + friend difference_type operator-(TheoryAtomIterator a, TheoryAtomIterator b) { return a.id() - b.id(); } TheoryAtom operator*() { return *this; } TheoryAtom *operator->() { return this; } - friend void swap(TheoryAtomIterator& lhs, TheoryAtomIterator& rhs) noexcept { + friend void swap(TheoryAtomIterator &lhs, TheoryAtomIterator &rhs) noexcept { std::swap(lhs.atoms(), rhs.atoms()); std::swap(lhs.id(), rhs.id()); } - friend bool operator==(TheoryAtomIterator lhs, TheoryAtomIterator rhs) { return lhs.atoms() == rhs.atoms() && lhs.id() == rhs.id(); } + friend bool operator==(TheoryAtomIterator lhs, TheoryAtomIterator rhs) { + return lhs.atoms() == rhs.atoms() && lhs.id() == rhs.id(); + } friend bool operator!=(TheoryAtomIterator lhs, TheoryAtomIterator rhs) { return !(lhs == rhs); } - friend bool operator< (TheoryAtomIterator lhs, TheoryAtomIterator rhs) { assert(lhs.atoms() == rhs.atoms()); return (lhs.id() + 1) < (rhs.id() + 1); } - friend bool operator> (TheoryAtomIterator lhs, TheoryAtomIterator rhs) { return rhs < lhs; } + friend bool operator<(TheoryAtomIterator lhs, TheoryAtomIterator rhs) { + assert(lhs.atoms() == rhs.atoms()); + return (lhs.id() + 1) < (rhs.id() + 1); + } + friend bool operator>(TheoryAtomIterator lhs, TheoryAtomIterator rhs) { return rhs < lhs; } friend bool operator<=(TheoryAtomIterator lhs, TheoryAtomIterator rhs) { return !(lhs > rhs); } friend bool operator>=(TheoryAtomIterator lhs, TheoryAtomIterator rhs) { return !(lhs < rhs); } -private: + + private: clingo_theory_atoms_t const *&atoms() { return atoms_; } clingo_id_t &id() { return id_; } }; class TheoryAtoms { -public: - explicit TheoryAtoms(clingo_theory_atoms_t const *atoms) - : atoms_(atoms) { } + public: + explicit TheoryAtoms(clingo_theory_atoms_t const *atoms) : atoms_(atoms) {} TheoryAtomIterator begin() const; TheoryAtomIterator end() const; size_t size() const; clingo_theory_atoms_t const *to_c() const { return atoms_; } -private: + + private: clingo_theory_atoms_t const *atoms_; }; // {{{1 trail -template -class IndexIterator { -public: +template class IndexIterator { + public: using iterator_category = std::random_access_iterator_tag; using value_type = typename T::value_type; using difference_type = I; - using pointer = value_type*; + using pointer = value_type *; using reference = value_type; - explicit IndexIterator(T *con = nullptr, U index = 0) - : con_(con) - , index_(index) { } - IndexIterator& operator++() { ++index_; return *this; } + explicit IndexIterator(T *con = nullptr, U index = 0) : con_(con), index_(index) {} + IndexIterator &operator++() { + ++index_; + return *this; + } IndexIterator operator++(int) { IndexIterator t(*this); ++*this; return t; } - IndexIterator& operator--() { --index_; return *this; } + IndexIterator &operator--() { + --index_; + return *this; + } IndexIterator operator--(int) { IndexIterator t(*this); --*this; return t; } - IndexIterator& operator+=(difference_type n) { index_ += n; return *this; } - IndexIterator& operator-=(difference_type n) { index_ -= n; return *this; } - friend IndexIterator operator+(IndexIterator it, difference_type n) { return IndexIterator{it.con_, it.index_ + n}; } - friend IndexIterator operator+(difference_type n, IndexIterator it) { return IndexIterator{it.con_, it.index_ + n}; } - friend IndexIterator operator-(IndexIterator it, difference_type n) { return IndexIterator{it.con_, it.index_ - n}; } - friend difference_type operator-(IndexIterator a, IndexIterator b) { return a.index_ - b.index_; } + IndexIterator &operator+=(difference_type n) { + index_ += n; + return *this; + } + IndexIterator &operator-=(difference_type n) { + index_ -= n; + return *this; + } + friend IndexIterator operator+(IndexIterator it, difference_type n) { + return IndexIterator{it.con_, it.index_ + n}; + } + friend IndexIterator operator+(difference_type n, IndexIterator it) { + return IndexIterator{it.con_, it.index_ + n}; + } + friend IndexIterator operator-(IndexIterator it, difference_type n) { + return IndexIterator{it.con_, it.index_ - n}; + } + friend difference_type operator-(IndexIterator a, IndexIterator b) { return a.index_ - b.index_; } value_type operator*() { return con_->at(index_); } - friend void swap(IndexIterator& lhs, IndexIterator& rhs) noexcept { + friend void swap(IndexIterator &lhs, IndexIterator &rhs) noexcept { std::swap(lhs.con_, rhs.con_); std::swap(lhs.index_, rhs.index_); } friend bool operator==(IndexIterator lhs, IndexIterator rhs) { return lhs.index_ == rhs.index_; } friend bool operator!=(IndexIterator lhs, IndexIterator rhs) { return !(lhs == rhs); } - friend bool operator< (IndexIterator lhs, IndexIterator rhs) { return lhs.index_ + 1 < rhs.index_ + 1; } - friend bool operator> (IndexIterator lhs, IndexIterator rhs) { return rhs < lhs; } + friend bool operator<(IndexIterator lhs, IndexIterator rhs) { return lhs.index_ + 1 < rhs.index_ + 1; } + friend bool operator>(IndexIterator lhs, IndexIterator rhs) { return rhs < lhs; } friend bool operator<=(IndexIterator lhs, IndexIterator rhs) { return !(lhs > rhs); } friend bool operator>=(IndexIterator lhs, IndexIterator rhs) { return !(lhs < rhs); } -private: + + private: T *con_; U index_; }; class Trail { -public: + public: using iterator = IndexIterator; using value_type = literal_t; - explicit Trail(clingo_assignment_t const *ass) : ass_{ass} { } + explicit Trail(clingo_assignment_t const *ass) : ass_{ass} {} uint32_t size() const; uint32_t begin_offset(uint32_t level) const; uint32_t end_offset(uint32_t level) const; @@ -979,18 +1011,18 @@ public: literal_t at(uint32_t offset) const; literal_t operator[](uint32_t offset) const { return at(offset); } clingo_assignment_t const *to_c() const { return ass_; } -private: + + private: clingo_assignment_t const *ass_; }; // {{{1 assignment class Assignment { -public: + public: using iterator = IndexIterator>; using value_type = literal_t; - explicit Assignment(clingo_assignment_t const *ass) - : ass_(ass) { } + explicit Assignment(clingo_assignment_t const *ass) : ass_(ass) {} bool has_conflict() const; uint32_t decision_level() const; uint32_t root_level() const; @@ -1009,34 +1041,34 @@ public: iterator end() const { return iterator{this, size()}; } Trail trail() const { return Trail{ass_}; } clingo_assignment_t const *to_c() const { return ass_; } -private: + + private: clingo_assignment_t const *ass_; }; // {{{1 propagate init enum PropagatorCheckMode : clingo_propagator_check_mode_t { - None = clingo_propagator_check_mode_none, - Total = clingo_propagator_check_mode_total, + None = clingo_propagator_check_mode_none, + Total = clingo_propagator_check_mode_total, Partial = clingo_propagator_check_mode_fixpoint, - Both = clingo_propagator_check_mode_both, + Both = clingo_propagator_check_mode_both, }; enum class PropagatorUndoMode : clingo_propagator_undo_mode_t { Default = clingo_propagator_undo_mode_default, - Always = clingo_propagator_undo_mode_always, + Always = clingo_propagator_undo_mode_always, }; enum WeightConstraintType : clingo_weight_constraint_type_t { - LeftImplication = clingo_weight_constraint_type_implication_left, + LeftImplication = clingo_weight_constraint_type_implication_left, RightImplication = clingo_weight_constraint_type_implication_right, - Equivalence = clingo_weight_constraint_type_equivalence, + Equivalence = clingo_weight_constraint_type_equivalence, }; class PropagateInit { -public: - explicit PropagateInit(clingo_propagate_init_t *init) - : init_(init) { } + public: + explicit PropagateInit(clingo_propagate_init_t *init) : init_(init) {} literal_t solver_literal(literal_t lit) const; void add_watch(literal_t lit); void add_watch(literal_t literal, id_t thread_id); @@ -1053,11 +1085,13 @@ public: void set_undo_mode(PropagatorUndoMode mode); literal_t add_literal(bool freeze = true); bool add_clause(LiteralSpan clause); - bool add_weight_constraint(literal_t literal, WeightedLiteralSpan literals, weight_t bound, WeightConstraintType type, bool compare_equal = false); + bool add_weight_constraint(literal_t literal, WeightedLiteralSpan literals, weight_t bound, + WeightConstraintType type, bool compare_equal = false); void add_minimize(literal_t literal, weight_t weight, weight_t priority = 0); bool propagate(); clingo_propagate_init_t *to_c() const { return init_; } -private: + + private: clingo_propagate_init_t *init_; }; @@ -1072,18 +1106,29 @@ enum class ClauseType : clingo_clause_type_t { inline std::ostream &operator<<(std::ostream &out, ClauseType t) { switch (t) { - case ClauseType::Learnt: { out << "Learnt"; break; } - case ClauseType::Static: { out << "Static"; break; } - case ClauseType::Volatile: { out << "Volatile"; break; } - case ClauseType::VolatileStatic: { out << "VolatileStatic"; break; } + case ClauseType::Learnt: { + out << "Learnt"; + break; + } + case ClauseType::Static: { + out << "Static"; + break; + } + case ClauseType::Volatile: { + out << "Volatile"; + break; + } + case ClauseType::VolatileStatic: { + out << "VolatileStatic"; + break; + } } return out; } class PropagateControl { -public: - explicit PropagateControl(clingo_propagate_control_t *ctl) - : ctl_(ctl) { } + public: + explicit PropagateControl(clingo_propagate_control_t *ctl) : ctl_(ctl) {} id_t thread_id() const; Assignment assignment() const; literal_t add_literal(); @@ -1093,14 +1138,15 @@ public: bool add_clause(LiteralSpan clause, ClauseType type = ClauseType::Learnt); bool propagate(); clingo_propagate_control_t *to_c() const { return ctl_; } -private: + + private: clingo_propagate_control_t *ctl_; }; // {{{1 propagator class Propagator { -public: + public: Propagator() = default; Propagator(Propagator const &) = default; Propagator(Propagator &&) noexcept = default; @@ -1114,7 +1160,7 @@ public: }; class Heuristic : public Propagator { -public: + public: Heuristic() = default; Heuristic(Heuristic const &) = default; Heuristic(Heuristic &&) noexcept = default; @@ -1130,45 +1176,75 @@ using IdSpan = Span; using AtomSpan = Span; enum class HeuristicType : clingo_heuristic_type_t { - Level = clingo_heuristic_type_level, - Sign = clingo_heuristic_type_sign, + Level = clingo_heuristic_type_level, + Sign = clingo_heuristic_type_sign, Factor = clingo_heuristic_type_factor, - Init = clingo_heuristic_type_init, - True = clingo_heuristic_type_true, - False = clingo_heuristic_type_false + Init = clingo_heuristic_type_init, + True = clingo_heuristic_type_true, + False = clingo_heuristic_type_false }; inline std::ostream &operator<<(std::ostream &out, HeuristicType t) { switch (t) { - case HeuristicType::Level: { out << "Level"; break; } - case HeuristicType::Sign: { out << "Sign"; break; } - case HeuristicType::Factor: { out << "Factor"; break; } - case HeuristicType::Init: { out << "Init"; break; } - case HeuristicType::True: { out << "True"; break; } - case HeuristicType::False: { out << "False"; break; } + case HeuristicType::Level: { + out << "Level"; + break; + } + case HeuristicType::Sign: { + out << "Sign"; + break; + } + case HeuristicType::Factor: { + out << "Factor"; + break; + } + case HeuristicType::Init: { + out << "Init"; + break; + } + case HeuristicType::True: { + out << "True"; + break; + } + case HeuristicType::False: { + out << "False"; + break; + } } return out; } enum class ExternalType { - Free = clingo_external_type_free, - True = clingo_external_type_true, - False = clingo_external_type_false, + Free = clingo_external_type_free, + True = clingo_external_type_true, + False = clingo_external_type_false, Release = clingo_external_type_release }; inline std::ostream &operator<<(std::ostream &out, ExternalType t) { switch (t) { - case ExternalType::Free: { out << "Free"; break; } - case ExternalType::True: { out << "True"; break; } - case ExternalType::False: { out << "False"; break; } - case ExternalType::Release: { out << "Release"; break; } + case ExternalType::Free: { + out << "Free"; + break; + } + case ExternalType::True: { + out << "True"; + break; + } + case ExternalType::False: { + out << "False"; + break; + } + case ExternalType::Release: { + out << "Release"; + break; + } } return out; } class GroundProgramObserver { -public: + public: GroundProgramObserver() = default; GroundProgramObserver(GroundProgramObserver const &) = default; GroundProgramObserver(GroundProgramObserver &&) noexcept = default; @@ -1195,15 +1271,14 @@ public: virtual void theory_term_compound(id_t term_id, int name_id_or_type, IdSpan arguments); virtual void theory_element(id_t element_id, IdSpan terms, LiteralSpan condition); virtual void theory_atom(id_t atom_id_or_zero, id_t term_id, IdSpan elements); - virtual void theory_atom_with_guard(id_t atom_id_or_zero, id_t term_id, IdSpan elements, id_t operator_id, id_t right_hand_side_id); + virtual void theory_atom_with_guard(id_t atom_id_or_zero, id_t term_id, IdSpan elements, id_t operator_id, + id_t right_hand_side_id); virtual ~GroundProgramObserver() = default; }; -inline void GroundProgramObserver::init_program(bool incremental) { - static_cast(incremental); -} -inline void GroundProgramObserver::begin_step() { } -inline void GroundProgramObserver::end_step() { } +inline void GroundProgramObserver::init_program(bool incremental) { static_cast(incremental); } +inline void GroundProgramObserver::begin_step() {} +inline void GroundProgramObserver::end_step() {} inline void GroundProgramObserver::rule(bool choice, AtomSpan head, LiteralSpan body) { static_cast(choice); @@ -1211,7 +1286,8 @@ inline void GroundProgramObserver::rule(bool choice, AtomSpan head, LiteralSpan static_cast(body); } -inline void GroundProgramObserver::weight_rule(bool choice, AtomSpan head, weight_t lower_bound, WeightedLiteralSpan body) { +inline void GroundProgramObserver::weight_rule(bool choice, AtomSpan head, weight_t lower_bound, + WeightedLiteralSpan body) { static_cast(choice); static_cast(head); static_cast(lower_bound); @@ -1223,9 +1299,7 @@ inline void GroundProgramObserver::minimize(weight_t priority, WeightedLiteralSp static_cast(literals); } -inline void GroundProgramObserver::project(AtomSpan atoms) { - static_cast(atoms); -} +inline void GroundProgramObserver::project(AtomSpan atoms) { static_cast(atoms); } inline void GroundProgramObserver::output_atom(Symbol symbol, atom_t atom) { static_cast(symbol); @@ -1242,11 +1316,10 @@ inline void GroundProgramObserver::external(atom_t atom, ExternalType type) { static_cast(type); } -inline void GroundProgramObserver::assume(LiteralSpan literals) { - static_cast(literals); -} +inline void GroundProgramObserver::assume(LiteralSpan literals) { static_cast(literals); } -inline void GroundProgramObserver::heuristic(atom_t atom, HeuristicType type, int bias, unsigned priority, LiteralSpan condition) { +inline void GroundProgramObserver::heuristic(atom_t atom, HeuristicType type, int bias, unsigned priority, + LiteralSpan condition) { static_cast(atom); static_cast(type); static_cast(bias); @@ -1260,7 +1333,6 @@ inline void GroundProgramObserver::acyc_edge(int node_u, int node_v, LiteralSpan static_cast(condition); } - inline void GroundProgramObserver::theory_term_number(id_t term_id, int number) { static_cast(term_id); static_cast(number); @@ -1289,7 +1361,8 @@ inline void GroundProgramObserver::theory_atom(id_t atom_id_or_zero, id_t term_i static_cast(elements); } -inline void GroundProgramObserver::theory_atom_with_guard(id_t atom_id_or_zero, id_t term_id, IdSpan elements, id_t operator_id, id_t right_hand_side_id) { +inline void GroundProgramObserver::theory_atom_with_guard(id_t atom_id_or_zero, id_t term_id, IdSpan elements, + id_t operator_id, id_t right_hand_side_id) { static_cast(atom_id_or_zero); static_cast(term_id); static_cast(elements); @@ -1297,18 +1370,16 @@ inline void GroundProgramObserver::theory_atom_with_guard(id_t atom_id_or_zero, static_cast(right_hand_side_id); } - // {{{1 symbolic literal class SymbolicLiteral { -public: - SymbolicLiteral(Symbol sym, bool positive) - : symbol_{sym.to_c()} - , positive_{positive} { } + public: + SymbolicLiteral(Symbol sym, bool positive) : symbol_{sym.to_c()}, positive_{positive} {} Symbol symbol() const { return Symbol{symbol_}; } bool is_positive() const { return positive_; } bool is_negative() const { return !positive_; } -private: + + private: clingo_symbol_t symbol_; bool positive_; }; @@ -1316,31 +1387,37 @@ private: using SymbolicLiteralSpan = Span; inline std::ostream &operator<<(std::ostream &out, SymbolicLiteral sym) { - if (sym.is_negative()) { out << "~"; } + if (sym.is_negative()) { + out << "~"; + } out << sym.symbol(); return out; } -inline bool operator==(SymbolicLiteral a, SymbolicLiteral b) { return a.is_negative() == b.is_negative() && a.symbol() == b.symbol(); } +inline bool operator==(SymbolicLiteral a, SymbolicLiteral b) { + return a.is_negative() == b.is_negative() && a.symbol() == b.symbol(); +} inline bool operator!=(SymbolicLiteral a, SymbolicLiteral b) { return !(a == b); } -inline bool operator< (SymbolicLiteral a, SymbolicLiteral b) { - if (a.is_negative() != b.is_negative()) { return !a.is_negative() && b.is_negative(); } +inline bool operator<(SymbolicLiteral a, SymbolicLiteral b) { + if (a.is_negative() != b.is_negative()) { + return !a.is_negative() && b.is_negative(); + } return a.symbol() < b.symbol(); } inline bool operator<=(SymbolicLiteral a, SymbolicLiteral b) { return !(b < a); } -inline bool operator> (SymbolicLiteral a, SymbolicLiteral b) { return (b < a); } +inline bool operator>(SymbolicLiteral a, SymbolicLiteral b) { return (b < a); } inline bool operator>=(SymbolicLiteral a, SymbolicLiteral b) { return !(a < b); } // {{{1 solve control class SolveControl { -public: - explicit SolveControl(clingo_solve_control_t *ctl) - : ctl_(ctl) { } + public: + explicit SolveControl(clingo_solve_control_t *ctl) : ctl_(ctl) {} void add_clause(SymbolicLiteralSpan clause); void add_clause(LiteralSpan clause); SymbolicAtoms symbolic_atoms() const; clingo_solve_control_t *to_c() const { return ctl_; } -private: + + private: clingo_solve_control_t *ctl_; }; @@ -1353,18 +1430,19 @@ enum class ModelType : clingo_model_type_t { }; class ShowType { -public: + public: enum Type : clingo_show_type_bitset_t { - Shown = clingo_show_type_shown, - Atoms = clingo_show_type_atoms, - Terms = clingo_show_type_terms, - Theory = clingo_show_type_theory, - All = clingo_show_type_all, + Shown = clingo_show_type_shown, + Atoms = clingo_show_type_atoms, + Terms = clingo_show_type_terms, + Theory = clingo_show_type_theory, + All = clingo_show_type_all, Complement = clingo_show_type_complement }; - ShowType(clingo_show_type_bitset_t type) : type_(type) { } + ShowType(clingo_show_type_bitset_t type) : type_(type) {} operator clingo_show_type_bitset_t() const { return type_; } -private: + + private: clingo_show_type_bitset_t type_; }; @@ -1378,7 +1456,7 @@ using CostVector = std::vector; using PriorityVector = std::vector; class Model { -public: + public: explicit Model(clingo_model_t *model); Model(Model const &) = delete; Model(Model &&) noexcept = delete; @@ -1399,7 +1477,8 @@ public: uint64_t number() const; explicit operator bool() const { return model_ != nullptr; } clingo_model_t *to_c() const { return model_; } -private: + + private: clingo_model_t *model_; }; @@ -1411,10 +1490,9 @@ inline std::ostream &operator<<(std::ostream &out, Model const &m) { // {{{1 solve result class SolveResult { -public: + public: SolveResult() = default; - explicit SolveResult(clingo_solve_result_bitset_t res) - : res_(res) { } + explicit SolveResult(clingo_solve_result_bitset_t res) : res_(res) {} bool is_satisfiable() const { return (res_ & clingo_solve_result_satisfiable) != 0; } bool is_unsatisfiable() const { return (res_ & clingo_solve_result_unsatisfiable) != 0; } bool is_unknown() const { return (res_ & 3) == 0; } @@ -1424,28 +1502,36 @@ public: clingo_solve_result_bitset_t const &to_c() const { return res_; } friend bool operator==(SolveResult a, SolveResult b) { return a.res_ == b.res_; } friend bool operator!=(SolveResult a, SolveResult b) { return a.res_ != b.res_; } -private: + + private: clingo_solve_result_bitset_t res_{0}; }; inline std::ostream &operator<<(std::ostream &out, SolveResult res) { - if (res.is_satisfiable()) { + if (res.is_satisfiable()) { out << "SATISFIABLE"; - if (!res.is_exhausted()) { out << "+"; } + if (!res.is_exhausted()) { + out << "+"; + } + } else if (res.is_unsatisfiable()) { + out << "UNSATISFIABLE"; + } else { + out << "UNKNOWN"; + } + if (res.is_interrupted()) { + out << "/INTERRUPTED"; } - else if (res.is_unsatisfiable()) { out << "UNSATISFIABLE"; } - else { out << "UNKNOWN"; } - if (res.is_interrupted()) { out << "/INTERRUPTED"; } return out; } // {{{1 location class Location : public clingo_location_t { -public: - explicit Location(clingo_location_t loc) : clingo_location_t(loc) { } - Location(char const *begin_file, char const *end_file, size_t begin_line, size_t end_line, size_t begin_column, size_t end_column) - : clingo_location_t{begin_file, end_file, begin_line, end_line, begin_column, end_column} { } + public: + explicit Location(clingo_location_t loc) : clingo_location_t(loc) {} + Location(char const *begin_file, char const *end_file, size_t begin_line, size_t end_line, size_t begin_column, + size_t end_column) + : clingo_location_t{begin_file, end_file, begin_line, end_line, begin_column, end_column} {} char const *begin_file() const { return clingo_location_t::begin_file; } char const *end_file() const { return clingo_location_t::end_file; } size_t begin_line() const { return clingo_location_t::begin_line; } @@ -1458,11 +1544,19 @@ inline std::ostream &operator<<(std::ostream &out, Location loc) { out << loc.begin_file() << ":" << loc.begin_line() << ":" << loc.begin_column(); bool dash = true; bool eq = std::strcmp(loc.begin_file(), loc.end_file()) == 0; - if (!eq) { out << (dash ? "-" : ":") << loc.end_file(); dash = false; } + if (!eq) { + out << (dash ? "-" : ":") << loc.end_file(); + dash = false; + } eq = eq && (loc.begin_line() == loc.end_line()); - if (!eq) { out << (dash ? "-" : ":") << loc.end_line(); dash = false; } + if (!eq) { + out << (dash ? "-" : ":") << loc.end_line(); + dash = false; + } eq = eq && (loc.begin_column() == loc.end_column()); - if (!eq) { out << (dash ? "-" : ":") << loc.end_column(); } + if (!eq) { + out << (dash ? "-" : ":") << loc.end_column(); + } return out; } @@ -1475,7 +1569,7 @@ enum class TheorySequenceType { }; class Backend { -public: + public: explicit Backend(clingo_backend_t *backend); Backend(Backend const &backend) = delete; Backend(Backend &&backend) noexcept; @@ -1503,57 +1597,69 @@ public: atom_t theory_atom(id_t term_id, IdSpan elements); atom_t theory_atom(id_t term_id, IdSpan elements, char const *operator_name, id_t right_hand_side_id); atom_t theory_atom(id_t atom_id_or_zero, id_t term_id, IdSpan elements); - atom_t theory_atom(id_t atom_id_or_zero, id_t term_id, IdSpan elements, char const *operator_name, id_t right_hand_side_id); + atom_t theory_atom(id_t atom_id_or_zero, id_t term_id, IdSpan elements, char const *operator_name, + id_t right_hand_side_id); clingo_backend_t *to_c() const { return backend_; } -private: + + private: clingo_backend_t *backend_ = nullptr; }; // {{{1 statistics -template -class KeyIterator { -public: +template class KeyIterator { + public: using iterator_category = std::random_access_iterator_tag; using value_type = char const *; using difference_type = ptrdiff_t; using pointer = ValuePointer; using reference = char const *; - explicit KeyIterator(T const *map, size_t index = 0) - : map_(map) - , index_(index) { } - KeyIterator& operator++() { ++index_; return *this; } + explicit KeyIterator(T const *map, size_t index = 0) : map_(map), index_(index) {} + KeyIterator &operator++() { + ++index_; + return *this; + } KeyIterator operator++(int) { KeyIterator t(*this); ++*this; return t; } - KeyIterator& operator--() { --index_; return *this; } + KeyIterator &operator--() { + --index_; + return *this; + } KeyIterator operator--(int) { KeyIterator t(*this); --*this; return t; } - KeyIterator& operator+=(difference_type n) { index_ += n; return *this; } - KeyIterator& operator-=(difference_type n) { index_ -= n; return *this; } + KeyIterator &operator+=(difference_type n) { + index_ += n; + return *this; + } + KeyIterator &operator-=(difference_type n) { + index_ -= n; + return *this; + } friend KeyIterator operator+(KeyIterator it, difference_type n) { return KeyIterator{it.map_, it.index_ + n}; } friend KeyIterator operator+(difference_type n, KeyIterator it) { return KeyIterator{it.map_, it.index_ + n}; } friend KeyIterator operator-(KeyIterator it, difference_type n) { return KeyIterator{it.map_, it.index_ - n}; } - friend difference_type operator-(KeyIterator a, KeyIterator b) { return a.index_ - b.index_; } + friend difference_type operator-(KeyIterator a, KeyIterator b) { return a.index_ - b.index_; } reference operator*() { return map_->key_name(index_); } pointer operator->() { return pointer(**this); } - friend void swap(KeyIterator& lhs, KeyIterator& rhs) noexcept { + friend void swap(KeyIterator &lhs, KeyIterator &rhs) noexcept { std::swap(lhs.map_, rhs.map_); std::swap(lhs.index_, rhs.index_); } friend bool operator==(KeyIterator lhs, KeyIterator rhs) { return lhs.index_ == rhs.index_; } friend bool operator!=(KeyIterator lhs, KeyIterator rhs) { return !(lhs == rhs); } - friend bool operator< (KeyIterator lhs, KeyIterator rhs) { return (lhs.index_ + 1) < (rhs.index_ + 1); } - friend bool operator> (KeyIterator lhs, KeyIterator rhs) { return rhs < lhs; } + friend bool operator<(KeyIterator lhs, KeyIterator rhs) { return (lhs.index_ + 1) < (rhs.index_ + 1); } + friend bool operator>(KeyIterator lhs, KeyIterator rhs) { return rhs < lhs; } friend bool operator<=(KeyIterator lhs, KeyIterator rhs) { return !(lhs > rhs); } friend bool operator>=(KeyIterator lhs, KeyIterator rhs) { return !(lhs < rhs); } -private: + + private: T const *map_; size_t index_; }; @@ -1564,17 +1670,15 @@ enum class StatisticsType : clingo_statistics_type_t { Map = clingo_statistics_type_map }; -template -class StatisticsBase { +template class StatisticsBase { friend class KeyIterator; -public: - using statistics_t = std::conditional_t; + + public: + using statistics_t = std::conditional_t; using KeyIteratorT = KeyIterator; using ArrayIteratorT = ArrayIterator; using KeyRangeT = IteratorRange; - explicit StatisticsBase(statistics_t stats, uint64_t key) - : stats_(stats) - , key_(key) { } + explicit StatisticsBase(statistics_t stats, uint64_t key) : stats_(stats), key_(key) {} // generic StatisticsType type() const; // arrays @@ -1596,7 +1700,8 @@ public: double value() const; void set_value(double d); statistics_t to_c() const { return stats_; } -private: + + private: char const *key_name(size_t index) const; statistics_t stats_; uint64_t key_; @@ -1604,12 +1709,12 @@ private: using Statistics = StatisticsBase; using UserStatistics = StatisticsBase; -using UserStatisticCallback = std::function; +using UserStatisticCallback = std::function; // {{{1 solve handle class SolveEventHandler { -public: + public: SolveEventHandler() = default; SolveEventHandler(SolveEventHandler const &) = default; SolveEventHandler(SolveEventHandler &&) noexcept = default; @@ -1627,18 +1732,14 @@ inline bool SolveEventHandler::on_model(Model &model) { return true; } -inline void SolveEventHandler::on_unsat(Span lower_bound) { - static_cast(lower_bound); -} +inline void SolveEventHandler::on_unsat(Span lower_bound) { static_cast(lower_bound); } inline void SolveEventHandler::on_statistics(UserStatistics step, UserStatistics accu) { static_cast(step); static_cast(accu); } -inline void SolveEventHandler::on_finish(SolveResult result) { - static_cast(result); -} +inline void SolveEventHandler::on_finish(SolveResult result) { static_cast(result); } namespace Detail { @@ -1647,7 +1748,7 @@ class AssignOnce; } // namespace Detail class SolveHandle { -public: + public: SolveHandle() = default; explicit SolveHandle(clingo_solve_handle_t *it, Detail::AssignOnce &ptr); SolveHandle(SolveHandle &&it) noexcept; @@ -1667,22 +1768,22 @@ public: Model const *last(); void cancel(); clingo_solve_handle_t *to_c() const { return iter_; } -private: + + private: Model model_{nullptr}; clingo_solve_handle_t *iter_{nullptr}; Detail::AssignOnce *exception_{nullptr}; }; class ModelIterator { -public: + public: using iterator_category = std::input_iterator_tag; using value_type = Model; using difference_type = ptrdiff_t; using pointer = Model const *; using reference = Model const &; - explicit ModelIterator(SolveHandle &iter) - : iter_(&iter) { } + explicit ModelIterator(SolveHandle &iter) : iter_(&iter) {} ModelIterator() = default; ModelIterator &operator++() { iter_->next(); @@ -1703,7 +1804,8 @@ public: return ap == bp; } friend bool operator!=(ModelIterator a, ModelIterator b) { return !(a == b); } -private: + + private: SolveHandle *iter_{nullptr}; }; @@ -1722,10 +1824,9 @@ using ConfigurationKeyRange = IteratorRange; class Configuration { friend class KeyIterator; -public: - explicit Configuration(clingo_configuration_t *conf, clingo_id_t key) - : conf_(conf) - , key_(key) { } + + public: + explicit Configuration(clingo_configuration_t *conf, clingo_id_t key) : conf_(conf), key_(key) {} // arrays bool is_array() const; Configuration operator[](size_t index); @@ -1748,7 +1849,8 @@ public: // generic char const *decription() const; clingo_configuration_t *to_c() const { return conf_; } -private: + + private: char const *key_name(size_t index) const; clingo_configuration_t *conf_; unsigned key_; @@ -1757,20 +1859,20 @@ private: // {{{1 control class Part { -public: + public: Part(char const *name, SymbolSpan params) - : part_{name, Detail::cast(params.begin()), params.size()} { } - explicit Part(clingo_part_t part) - : part_(part) { } + : part_{name, Detail::cast(params.begin()), params.size()} {} + explicit Part(clingo_part_t part) : part_(part) {} char const *name() const { return part_.name; } - SymbolSpan params() const { return {Detail::cast(part_.params), part_.size}; } + SymbolSpan params() const { return {Detail::cast(part_.params), part_.size}; } clingo_part_t const &to_c() const { return part_; } clingo_part_t &to_c() { return part_; } -private: + + private: clingo_part_t part_; }; using PartSpan = Span; -using GroundCallback = std::function; +using GroundCallback = std::function; using StringSpan = Span; enum class ErrorCode : clingo_error_t { @@ -1795,7 +1897,7 @@ enum class WarningCode : clingo_warning_t { Other = clingo_warning_other, }; -using Logger = std::function; +using Logger = std::function; inline std::ostream &operator<<(std::ostream &out, WarningCode code) { out << clingo_warning_string(static_cast(code)); @@ -1804,7 +1906,8 @@ inline std::ostream &operator<<(std::ostream &out, WarningCode code) { class Control { struct Impl; -public: + + public: Control(StringSpan args = {}, Logger logger = nullptr, unsigned message_limit = g_message_limit); explicit Control(clingo_control_t *ctl, bool owns = true); Control(Control &&c) noexcept; @@ -1814,8 +1917,10 @@ public: ~Control() noexcept; void add(char const *name, StringSpan params, char const *part); void ground(PartSpan parts, GroundCallback cb = nullptr); - SolveHandle solve(LiteralSpan assumptions, SolveEventHandler *handler = nullptr, bool asynchronous = false, bool yield = true); - SolveHandle solve(SymbolicLiteralSpan assumptions = {}, SolveEventHandler *handler = nullptr, bool asynchronous = false, bool yield = true); + SolveHandle solve(LiteralSpan assumptions, SolveEventHandler *handler = nullptr, bool asynchronous = false, + bool yield = true); + SolveHandle solve(SymbolicLiteralSpan assumptions = {}, SolveEventHandler *handler = nullptr, + bool asynchronous = false, bool yield = true); void assign_external(literal_t literal, TruthValue value); void assign_external(Symbol atom, TruthValue value); void release_external(literal_t literal); @@ -1837,15 +1942,15 @@ public: void enable_cleanup(bool value); bool enable_cleanup() const; Backend backend(); - template - void with_backend(F f) { + template void with_backend(F f) { auto b = backend(); f(b); } Configuration configuration(); Statistics statistics() const; clingo_control_t *to_c() const; -private: + + private: Impl *impl_; }; @@ -1902,9 +2007,9 @@ enum class AggregateFunction { }; enum class TheoryOperatorType { - Unary = clingo_ast_theory_operator_type_unary, - BinaryLeft = clingo_ast_theory_operator_type_binary_left, - BinaryRight = clingo_ast_theory_operator_type_binary_right, + Unary = clingo_ast_theory_operator_type_unary, + BinaryLeft = clingo_ast_theory_operator_type_binary_left, + BinaryRight = clingo_ast_theory_operator_type_binary_right, }; enum class TheoryAtomDefinitionType { @@ -2025,10 +2130,9 @@ class StringVector; using NodeValue = Variant, StringVector, NodeVector>; class Node { -public: + public: explicit Node(clingo_ast_t *ast); - template - Node(Type type, Args&& ...args); + template Node(Type type, Args &&...args); Node(Node const &ast); Node(Node &&ast) noexcept; Node &operator=(Node const &ast); @@ -2038,17 +2142,13 @@ public: Node deep_copy() const; Type type() const; NodeValue get(Attribute attribute) const; - template - T get(Attribute attribute) const; + template T get(Attribute attribute) const; void set(Attribute attribute, NodeValue value); - template - void visit_attribute(Visitor &&visitor) const; - template - void visit_ast(Visitor &&visitor) const; - template - Node transform_ast(Visitor &&visitor) const; + template void visit_attribute(Visitor &&visitor) const; + template void visit_ast(Visitor &&visitor) const; + template Node transform_ast(Visitor &&visitor) const; std::string to_string() const; - std::vector unpool(bool other=true, bool condition=true) const; + std::vector unpool(bool other = true, bool condition = true) const; clingo_ast_t *to_c() const { return ast_; } friend std::ostream &operator<<(std::ostream &out, Node const &ast); friend bool operator<(Node const &a, Node const &b); @@ -2058,25 +2158,27 @@ public: friend bool operator==(Node const &a, Node const &b); friend bool operator!=(Node const &a, Node const &b); size_t hash() const; -private: + + private: clingo_ast_t *ast_; }; class NodeRef { -public: + public: NodeRef(NodeVector *vec, size_t index); NodeRef &operator=(Node const &ast); Node get() const; - operator Node () const; -private: + operator Node() const; + + private: NodeVector *vec_; size_t index_; }; class NodeVector { -public: + public: using value_type = Node; - using iterator = ArrayIterator; + using iterator = ArrayIterator; using const_iterator = ArrayIterator; NodeVector(Node ast, clingo_ast_attribute_t attr); @@ -2098,7 +2200,8 @@ public: void clear(); Node &ast(); Node const &ast() const; -private: + + private: Node ast_; clingo_ast_attribute_t attr_; }; @@ -2106,20 +2209,21 @@ private: class StringVector; class StringRef { -public: + public: StringRef(StringVector *vec, size_t index); StringRef &operator=(char const *str); char const *get() const; operator char const *() const; -private: + + private: StringVector *vec_; size_t index_; }; class StringVector { -public: + public: using value_type = char const *; - using iterator = ArrayIterator; + using iterator = ArrayIterator; using const_iterator = ArrayIterator; StringVector(Node ast, clingo_ast_attribute_t attr); @@ -2141,13 +2245,14 @@ public: void clear(); Node &ast(); Node const &ast() const; -private: + + private: Node ast_; clingo_ast_attribute_t attr_; }; class ProgramBuilder { -public: + public: explicit ProgramBuilder(Control &ctl); explicit ProgramBuilder(clingo_program_builder_t *builder); ProgramBuilder() = delete; @@ -2161,54 +2266,58 @@ public: void add(Node const &ast); clingo_program_builder_t *to_c() const { return builder_; } -private: + private: clingo_program_builder_t *builder_; }; template -void parse_string(char const *program, Callback &&cb, Logger logger = nullptr, unsigned message_limit = g_message_limit); +void parse_string(char const *program, Callback &&cb, Logger logger = nullptr, + unsigned message_limit = g_message_limit); template -void parse_string(char const *program, Callback &&cb, Control &control, Logger logger = nullptr, unsigned message_limit = g_message_limit); +void parse_string(char const *program, Callback &&cb, Control &control, Logger logger = nullptr, + unsigned message_limit = g_message_limit); template void parse_files(StringSpan files, Callback &&cb, Logger logger = nullptr, unsigned message_limit = g_message_limit); template -void parse_files(StringSpan files, Callback &&cb, Control &control, Logger logger = nullptr, unsigned message_limit = g_message_limit); +void parse_files(StringSpan files, Callback &&cb, Control &control, Logger logger = nullptr, + unsigned message_limit = g_message_limit); -template -inline void with_builder(Control &ctl, F f) { +template inline void with_builder(Control &ctl, F f) { auto b = ProgramBuilder{ctl}; f(b); } } // namespace AST -} namespace std { +} // namespace Clingo +namespace std { -template<> -struct hash { +template <> struct hash { size_t operator()(Clingo::AST::Node const &ast) const { return ast.hash(); } }; -} namespace Clingo { +} // namespace std +namespace Clingo { // {{{1 clingo application namespace Detail { - using ParserList = std::forward_list>; +using ParserList = std::forward_list>; } class ClingoOptions { -public: + public: explicit ClingoOptions(clingo_options_t *options, Detail::ParserList &parsers) - : options_{options} - , parsers_{&parsers} { } + : options_{options}, parsers_{&parsers} {} clingo_options_t *to_c() const { return options_; } - void add(char const *group, char const *option, char const *description, std::function parser, bool multi = false, char const *argument = nullptr); + void add(char const *group, char const *option, char const *description, + std::function parser, bool multi = false, char const *argument = nullptr); void add_flag(char const *group, char const *option, char const *description, bool &target); -private: + + private: clingo_options_t *options_; Detail::ParserList *parsers_; }; @@ -2245,10 +2354,20 @@ inline int clingo_main(Application &application, StringSpan arguments); //{{{1 implementation #define CLINGO_CALLBACK_TRY try // NOLINT -#define CLINGO_CALLBACK_CATCH(ref) catch (...){ (ref) = std::current_exception(); return false; } return true // NOLINT +#define CLINGO_CALLBACK_CATCH(ref) \ + catch (...) { \ + (ref) = std::current_exception(); \ + return false; \ + } \ + return true // NOLINT #define CLINGO_TRY try // NOLINT -#define CLINGO_CATCH catch (...){ Detail::handle_cxx_error(); return false; } return true // NOLINT +#define CLINGO_CATCH \ + catch (...) { \ + Detail::handle_cxx_error(); \ + return false; \ + } \ + return true // NOLINT namespace Clingo { @@ -2259,13 +2378,23 @@ namespace Detail { inline void handle_error(bool ret) { if (!ret) { char const *msg = clingo_error_message(); - if (msg == nullptr) { msg = "no message"; } + if (msg == nullptr) { + msg = "no message"; + } switch (static_cast(clingo_error_code())) { - case clingo_error_runtime: { throw std::runtime_error(msg); } - case clingo_error_logic: { throw std::logic_error(msg); } - case clingo_error_bad_alloc: { throw std::bad_alloc(); } + case clingo_error_runtime: { + throw std::runtime_error(msg); + } + case clingo_error_logic: { + throw std::logic_error(msg); + } + case clingo_error_bad_alloc: { + throw std::bad_alloc(); + } case clingo_error_unknown: - case clingo_error_success: { throw std::runtime_error(msg); } + case clingo_error_success: { + throw std::runtime_error(msg); + } } } } @@ -2281,10 +2410,10 @@ inline void handle_error(bool ret, std::exception_ptr &exc) { } } -enum class AssignState { Unassigned=0, Writing=1, Assigned=2 }; +enum class AssignState { Unassigned = 0, Writing = 1, Assigned = 2 }; class AssignOnce { -public: + public: AssignOnce &operator=(std::exception_ptr x) { auto ua = AssignState::Unassigned; if (state_.compare_exchange_strong(ua, AssignState::Writing)) { @@ -2303,78 +2432,74 @@ public: state_ = AssignState::Unassigned; val_ = nullptr; } -private: + + private: std::atomic state_{AssignState::Unassigned}; std::exception_ptr val_ = nullptr; // NOLINT }; inline void handle_error(bool ret, AssignOnce &exc) { - if (!ret) { handle_error(ret, *exc); } + if (!ret) { + handle_error(ret, *exc); + } } inline void handle_cxx_error() { - try { throw; } - catch (std::bad_alloc const &e) { clingo_set_error(clingo_error_bad_alloc, e.what()); return; } - catch (std::runtime_error const &e) { clingo_set_error(clingo_error_runtime, e.what()); return; } - catch (std::logic_error const &e) { clingo_set_error(clingo_error_logic, e.what()); return; } - catch (...) { } // NOLINT(bugprone-empty-catch) + try { + throw; + } catch (std::bad_alloc const &e) { + clingo_set_error(clingo_error_bad_alloc, e.what()); + return; + } catch (std::runtime_error const &e) { + clingo_set_error(clingo_error_runtime, e.what()); + return; + } catch (std::logic_error const &e) { + clingo_set_error(clingo_error_logic, e.what()); + return; + } catch (...) { + } // NOLINT(bugprone-empty-catch) clingo_set_error(clingo_error_unknown, "unknown error"); } -template -std::string to_string(S size, P print, Args ...args) { +template std::string to_string(S size, P print, Args... args) { std::vector ret; size_t n = 0; Detail::handle_error(size(std::forward(args)..., &n)); ret.resize(n); Detail::handle_error(print(std::forward(args)..., ret.data(), n)); - return {ret.begin(), ret.end()-1}; + return {ret.begin(), ret.end() - 1}; } } // namespace Detail // {{{2 signature -inline Signature::Signature(char const *name, uint32_t arity, bool positive) -: sig_{0} { +inline Signature::Signature(char const *name, uint32_t arity, bool positive) : sig_{0} { Detail::handle_error(clingo_signature_create(name, arity, positive, &sig_)); } -inline char const *Signature::name() const { - return clingo_signature_name(sig_); -} +inline char const *Signature::name() const { return clingo_signature_name(sig_); } -inline uint32_t Signature::arity() const { - return clingo_signature_arity(sig_); -} +inline uint32_t Signature::arity() const { return clingo_signature_arity(sig_); } -inline bool Signature::positive() const { - return clingo_signature_is_positive(sig_); -} +inline bool Signature::positive() const { return clingo_signature_is_positive(sig_); } -inline bool Signature::negative() const { - return clingo_signature_is_negative(sig_); -} +inline bool Signature::negative() const { return clingo_signature_is_negative(sig_); } -inline size_t Signature::hash() const { - return clingo_signature_hash(sig_); -} +inline size_t Signature::hash() const { return clingo_signature_hash(sig_); } -inline bool operator==(Signature a, Signature b) { return clingo_signature_is_equal_to(a.to_c(), b.to_c()); } +inline bool operator==(Signature a, Signature b) { return clingo_signature_is_equal_to(a.to_c(), b.to_c()); } inline bool operator!=(Signature a, Signature b) { return !clingo_signature_is_equal_to(a.to_c(), b.to_c()); } -inline bool operator< (Signature a, Signature b) { return clingo_signature_is_less_than(a.to_c(), b.to_c()); } +inline bool operator<(Signature a, Signature b) { return clingo_signature_is_less_than(a.to_c(), b.to_c()); } inline bool operator<=(Signature a, Signature b) { return !clingo_signature_is_less_than(b.to_c(), a.to_c()); } -inline bool operator> (Signature a, Signature b) { return clingo_signature_is_less_than(b.to_c(), a.to_c()); } +inline bool operator>(Signature a, Signature b) { return clingo_signature_is_less_than(b.to_c(), a.to_c()); } inline bool operator>=(Signature a, Signature b) { return !clingo_signature_is_less_than(a.to_c(), b.to_c()); } // {{{2 symbol -inline Symbol::Symbol() { - clingo_symbol_create_number(0, &sym_); -} +inline Symbol::Symbol() { clingo_symbol_create_number(0, &sym_); } -inline Symbol::Symbol(clingo_symbol_t sym) -: sym_(sym) { } +inline Symbol::Symbol(clingo_symbol_t sym) : sym_(sym) {} inline Symbol Number(int num) { clingo_symbol_t sym = 0; @@ -2408,7 +2533,8 @@ inline Symbol Id(char const *id, bool positive) { inline Symbol Function(char const *name, SymbolSpan args, bool positive) { clingo_symbol_t sym = 0; - Detail::handle_error(clingo_symbol_create_function(name, Detail::cast(args.begin()), args.size(), positive, &sym)); + Detail::handle_error(clingo_symbol_create_function(name, Detail::cast(args.begin()), + args.size(), positive, &sym)); return Symbol(sym); } @@ -2449,9 +2575,7 @@ inline SymbolSpan Symbol::arguments() const { return {Detail::cast(ret), n}; } -inline SymbolType Symbol::type() const { - return static_cast(clingo_symbol_type(sym_)); -} +inline SymbolType Symbol::type() const { return static_cast(clingo_symbol_type(sym_)); } inline bool Symbol::match(char const *name, unsigned arity) const { return type() == SymbolType::Function && strcmp(this->name(), name) == 0 && this->arguments().size() == arity; @@ -2461,20 +2585,18 @@ inline std::string Symbol::to_string() const { return Detail::to_string(clingo_symbol_to_string_size, clingo_symbol_to_string, sym_); } -inline size_t Symbol::hash() const { - return clingo_symbol_hash(sym_); -} +inline size_t Symbol::hash() const { return clingo_symbol_hash(sym_); } inline std::ostream &operator<<(std::ostream &out, Symbol sym) { out << sym.to_string(); return out; } -inline bool operator==(Symbol a, Symbol b) { return clingo_symbol_is_equal_to(a.to_c(), b.to_c()); } +inline bool operator==(Symbol a, Symbol b) { return clingo_symbol_is_equal_to(a.to_c(), b.to_c()); } inline bool operator!=(Symbol a, Symbol b) { return !clingo_symbol_is_equal_to(a.to_c(), b.to_c()); } -inline bool operator< (Symbol a, Symbol b) { return clingo_symbol_is_less_than(a.to_c(), b.to_c()); } +inline bool operator<(Symbol a, Symbol b) { return clingo_symbol_is_less_than(a.to_c(), b.to_c()); } inline bool operator<=(Symbol a, Symbol b) { return !clingo_symbol_is_less_than(b.to_c(), a.to_c()); } -inline bool operator> (Symbol a, Symbol b) { return clingo_symbol_is_less_than(b.to_c(), a.to_c()); } +inline bool operator>(Symbol a, Symbol b) { return clingo_symbol_is_less_than(b.to_c(), a.to_c()); } inline bool operator>=(Symbol a, Symbol b) { return !clingo_symbol_is_less_than(a.to_c(), b.to_c()); } // {{{2 symbolic atoms @@ -2503,9 +2625,7 @@ inline bool SymbolicAtom::is_external() const { return ret; } -inline bool SymbolicAtom::match(char const *name, unsigned arity) const { - return symbol().match(name, arity); -} +inline bool SymbolicAtom::match(char const *name, unsigned arity) const { return symbol().match(name, arity); } inline SymbolicAtomIterator &SymbolicAtomIterator::operator++() { clingo_symbolic_atom_iterator_t range = 0; @@ -2522,14 +2642,16 @@ inline SymbolicAtomIterator::operator bool() const { inline bool SymbolicAtomIterator::operator==(SymbolicAtomIterator it) const { bool ret = atoms_ == it.atoms_; - if (ret) { Detail::handle_error(clingo_symbolic_atoms_iterator_is_equal_to(atoms_, range_, it.range_, &ret)); } + if (ret) { + Detail::handle_error(clingo_symbolic_atoms_iterator_is_equal_to(atoms_, range_, it.range_, &ret)); + } return ret; } inline SymbolicAtomIterator SymbolicAtoms::begin() const { clingo_symbolic_atom_iterator_t it = 0; Detail::handle_error(clingo_symbolic_atoms_begin(atoms_, nullptr, &it)); - return SymbolicAtomIterator{atoms_, it}; + return SymbolicAtomIterator{atoms_, it}; } inline SymbolicAtomIterator SymbolicAtoms::begin(Signature sig) const { @@ -2602,7 +2724,6 @@ inline std::string TheoryTerm::to_string() const { return Detail::to_string(clingo_theory_atoms_term_to_string_size, clingo_theory_atoms_term_to_string, atoms_, id_); } - inline TheoryTermSpan TheoryElement::tuple() const { clingo_id_t const *ret = nullptr; size_t n = 0; @@ -2624,7 +2745,8 @@ inline literal_t TheoryElement::condition_id() const { } inline std::string TheoryElement::to_string() const { - return Detail::to_string(clingo_theory_atoms_element_to_string_size, clingo_theory_atoms_element_to_string, atoms_, id_); + return Detail::to_string(clingo_theory_atoms_element_to_string_size, clingo_theory_atoms_element_to_string, atoms_, + id_); } inline std::ostream &operator<<(std::ostream &out, TheoryElement term) { @@ -2673,13 +2795,9 @@ inline std::ostream &operator<<(std::ostream &out, TheoryAtom term) { return out; } -inline TheoryAtomIterator TheoryAtoms::begin() const { - return TheoryAtomIterator{atoms_, 0}; -} +inline TheoryAtomIterator TheoryAtoms::begin() const { return TheoryAtomIterator{atoms_, 0}; } -inline TheoryAtomIterator TheoryAtoms::end() const { - return TheoryAtomIterator{atoms_, clingo_id_t(size())}; -} +inline TheoryAtomIterator TheoryAtoms::end() const { return TheoryAtomIterator{atoms_, clingo_id_t(size())}; } inline size_t TheoryAtoms::size() const { size_t ret = 0; @@ -2715,21 +2833,13 @@ inline literal_t Trail::at(uint32_t offset) const { // {{{2 assignment -inline bool Assignment::has_conflict() const { - return clingo_assignment_has_conflict(ass_); -} +inline bool Assignment::has_conflict() const { return clingo_assignment_has_conflict(ass_); } -inline uint32_t Assignment::decision_level() const { - return clingo_assignment_decision_level(ass_); -} +inline uint32_t Assignment::decision_level() const { return clingo_assignment_decision_level(ass_); } -inline uint32_t Assignment::root_level() const { - return clingo_assignment_root_level(ass_); -} +inline uint32_t Assignment::root_level() const { return clingo_assignment_root_level(ass_); } -inline bool Assignment::has_literal(literal_t lit) const { - return clingo_assignment_has_literal(ass_, lit); -} +inline bool Assignment::has_literal(literal_t lit) const { return clingo_assignment_has_literal(ass_, lit); } inline TruthValue Assignment::truth_value(literal_t lit) const { clingo_truth_value_t ret = 0; @@ -2767,13 +2877,9 @@ inline bool Assignment::is_false(literal_t lit) const { return ret; } -inline size_t Assignment::size() const { - return clingo_assignment_size(ass_); -} +inline size_t Assignment::size() const { return clingo_assignment_size(ass_); } -inline bool Assignment::is_total() const { - return clingo_assignment_is_total(ass_); -} +inline bool Assignment::is_total() const { return clingo_assignment_is_total(ass_); } inline literal_t Assignment::at(size_t offset) const { clingo_literal_t ret = 0; @@ -2809,13 +2915,9 @@ inline void PropagateInit::freeze_literal(literal_t lit) { Detail::handle_error(clingo_propagate_init_freeze_literal(init_, lit)); } -inline int PropagateInit::number_of_threads() const { - return clingo_propagate_init_number_of_threads(init_); -} +inline int PropagateInit::number_of_threads() const { return clingo_propagate_init_number_of_threads(init_); } -inline Assignment PropagateInit::assignment() const { - return Assignment{clingo_propagate_init_assignment(init_)}; -} +inline Assignment PropagateInit::assignment() const { return Assignment{clingo_propagate_init_assignment(init_)}; } inline SymbolicAtoms PropagateInit::symbolic_atoms() const { clingo_symbolic_atoms_t const *ret = nullptr; @@ -2857,9 +2959,12 @@ inline bool PropagateInit::add_clause(LiteralSpan clause) { return ret; } -inline bool PropagateInit::add_weight_constraint(literal_t literal, WeightedLiteralSpan literals, weight_t bound, WeightConstraintType type, bool compare_equal) { +inline bool PropagateInit::add_weight_constraint(literal_t literal, WeightedLiteralSpan literals, weight_t bound, + WeightConstraintType type, bool compare_equal) { bool ret = false; - Detail::handle_error(clingo_propagate_init_add_weight_constraint(init_, literal, Detail::cast(literals.begin()), literals.size(), bound, type, compare_equal, &ret)); + Detail::handle_error(clingo_propagate_init_add_weight_constraint( + init_, literal, Detail::cast(literals.begin()), literals.size(), bound, type, + compare_equal, &ret)); return ret; } @@ -2875,13 +2980,9 @@ inline bool PropagateInit::propagate() { // {{{2 propagate control -inline id_t PropagateControl::thread_id() const { - return clingo_propagate_control_thread_id(ctl_); -} +inline id_t PropagateControl::thread_id() const { return clingo_propagate_control_thread_id(ctl_); } -inline Assignment PropagateControl::assignment() const { - return Assignment{clingo_propagate_control_assignment(ctl_)}; -} +inline Assignment PropagateControl::assignment() const { return Assignment{clingo_propagate_control_assignment(ctl_)}; } inline literal_t PropagateControl::add_literal() { clingo_literal_t ret = 0; @@ -2897,13 +2998,12 @@ inline bool PropagateControl::has_watch(literal_t literal) const { return clingo_propagate_control_has_watch(ctl_, literal); } -inline void PropagateControl::remove_watch(literal_t literal) { - clingo_propagate_control_remove_watch(ctl_, literal); -} +inline void PropagateControl::remove_watch(literal_t literal) { clingo_propagate_control_remove_watch(ctl_, literal); } inline bool PropagateControl::add_clause(LiteralSpan clause, ClauseType type) { bool ret = false; - Detail::handle_error(clingo_propagate_control_add_clause(ctl_, clause.begin(), clause.size(), static_cast(type), &ret)); + Detail::handle_error(clingo_propagate_control_add_clause(ctl_, clause.begin(), clause.size(), + static_cast(type), &ret)); return ret; } @@ -2915,9 +3015,7 @@ inline bool PropagateControl::propagate() { // {{{2 propagator -inline void Propagator::init(PropagateInit &init) { - static_cast(init); -} +inline void Propagator::init(PropagateInit &init) { static_cast(init); } inline void Propagator::propagate(PropagateControl &ctl, LiteralSpan changes) { static_cast(ctl); @@ -2929,9 +3027,7 @@ inline void Propagator::undo(PropagateControl const &ctl, LiteralSpan changes) n static_cast(changes); } -inline void Propagator::check(PropagateControl &ctl) { - static_cast(ctl); -} +inline void Propagator::check(PropagateControl &ctl) { static_cast(ctl); } inline literal_t Heuristic::decide(id_t thread_id, Assignment const &assign, literal_t fallback) { static_cast(thread_id); @@ -2956,20 +3052,21 @@ inline void SolveControl::add_clause(SymbolicLiteralSpan clause) { if (it != atoms.end()) { auto lit = it->literal(); lits.emplace_back(x.is_positive() ? lit : -lit); + } else if (x.is_negative()) { + return; } - else if (x.is_negative()) { return; } } add_clause(LiteralSpan{lits}); } inline void SolveControl::add_clause(LiteralSpan clause) { - Detail::handle_error(clingo_solve_control_add_clause(ctl_, Detail::cast(clause.begin()), clause.size())); + Detail::handle_error( + clingo_solve_control_add_clause(ctl_, Detail::cast(clause.begin()), clause.size())); } // {{{2 model -inline Model::Model(clingo_model_t *model) -: model_(model) { } +inline Model::Model(clingo_model_t *model) : model_(model) {} inline bool Model::contains(Symbol atom) const { bool ret = false; @@ -3008,7 +3105,8 @@ inline PriorityVector Model::priorities() const { } inline void Model::extend(SymbolSpan symbols) { - Detail::handle_error(clingo_model_extend(model_, Detail::cast(symbols.begin()), symbols.size())); + Detail::handle_error( + clingo_model_extend(model_, Detail::cast(symbols.begin()), symbols.size())); } inline SymbolVector Model::symbols(ShowType show) const { @@ -3052,16 +3150,11 @@ inline id_t Model::thread_id() const { // {{{2 solve handle -namespace Detail { - -} // namespace Detail +namespace Detail {} // namespace Detail -inline SolveHandle::SolveHandle(clingo_solve_handle_t *it, Detail::AssignOnce &ptr) -: iter_(it) -, exception_(&ptr) { } +inline SolveHandle::SolveHandle(clingo_solve_handle_t *it, Detail::AssignOnce &ptr) : iter_(it), exception_(&ptr) {} -inline SolveHandle::SolveHandle(SolveHandle &&it) noexcept -: SolveHandle() { *this = std::move(it); } +inline SolveHandle::SolveHandle(SolveHandle &&it) noexcept : SolveHandle() { *this = std::move(it); } inline SolveHandle &SolveHandle::operator=(SolveHandle &&it) noexcept { std::swap(iter_, it.iter_); @@ -3069,13 +3162,9 @@ inline SolveHandle &SolveHandle::operator=(SolveHandle &&it) noexcept { return *this; } -inline void SolveHandle::resume() { - Detail::handle_error(clingo_solve_handle_resume(iter_), *exception_); -} +inline void SolveHandle::resume() { Detail::handle_error(clingo_solve_handle_resume(iter_), *exception_); } -inline void SolveHandle::wait() { - (void)wait(-1); -} +inline void SolveHandle::wait() { (void)wait(-1); } inline bool SolveHandle::wait(double timeout) { bool res = true; @@ -3086,13 +3175,13 @@ inline bool SolveHandle::wait(double timeout) { inline Model const &SolveHandle::model() { clingo_model_t const *m = nullptr; Detail::handle_error(clingo_solve_handle_model(iter_, &m), *exception_); - new (&model_) Model{const_cast(m)}; // NOLINT + new (&model_) Model{const_cast(m)}; // NOLINT return model_; } - inline Model const *SolveHandle::last() { +inline Model const *SolveHandle::last() { clingo_model_t const *m = nullptr; Detail::handle_error(clingo_solve_handle_last(iter_, &m), *exception_); - new (&model_) Model{const_cast(m)}; // NOLINT + new (&model_) Model{const_cast(m)}; // NOLINT return m ? &model_ : nullptr; } @@ -3114,13 +3203,9 @@ inline SolveResult SolveHandle::get() { return SolveResult{ret}; } -inline void SolveHandle::cancel() { - Detail::handle_error(clingo_solve_handle_cancel(iter_), *exception_); -} +inline void SolveHandle::cancel() { Detail::handle_error(clingo_solve_handle_cancel(iter_), *exception_); } -inline SolveHandle::~SolveHandle() noexcept(false) { - close(); -} +inline SolveHandle::~SolveHandle() noexcept(false) { close(); } inline void SolveHandle::close() { if (iter_ != nullptr) { @@ -3131,23 +3216,18 @@ inline void SolveHandle::close() { // {{{2 backend -inline Backend::Backend(Backend &&backend) noexcept { - *this = std::move(backend); -} +inline Backend::Backend(Backend &&backend) noexcept { *this = std::move(backend); } inline Backend &Backend::operator=(Backend &&backend) noexcept { std::swap(backend_, backend.backend_); return *this; } -inline Backend::Backend(clingo_backend_t *backend) -: backend_{backend} { +inline Backend::Backend(clingo_backend_t *backend) : backend_{backend} { Detail::handle_error(clingo_backend_begin(backend_)); } -inline Backend::~Backend() noexcept(false) { - close(); -} +inline Backend::~Backend() noexcept(false) { close(); } inline void Backend::close() { if (backend_ != nullptr) { @@ -3161,11 +3241,14 @@ inline void Backend::rule(bool choice, AtomSpan head, LiteralSpan body) { } inline void Backend::weight_rule(bool choice, AtomSpan head, weight_t lower, WeightedLiteralSpan body) { - Detail::handle_error(clingo_backend_weight_rule(backend_, choice, head.begin(), head.size(), lower, Detail::cast(body.begin()), body.size())); + Detail::handle_error(clingo_backend_weight_rule(backend_, choice, head.begin(), head.size(), lower, + Detail::cast(body.begin()), + body.size())); } inline void Backend::minimize(weight_t prio, WeightedLiteralSpan body) { - Detail::handle_error(clingo_backend_minimize(backend_, prio, Detail::cast(body.begin()), body.size())); + Detail::handle_error(clingo_backend_minimize( + backend_, prio, Detail::cast(body.begin()), body.size())); } inline void Backend::project(AtomSpan atoms) { @@ -3181,7 +3264,8 @@ inline void Backend::assume(LiteralSpan lits) { } inline void Backend::heuristic(atom_t atom, HeuristicType type, int bias, unsigned priority, LiteralSpan condition) { - Detail::handle_error(clingo_backend_heuristic(backend_, atom, static_cast(type), bias, priority, condition.begin(), condition.size())); + Detail::handle_error(clingo_backend_heuristic(backend_, atom, static_cast(type), bias, + priority, condition.begin(), condition.size())); } inline void Backend::acyc_edge(int node_u, int node_v, LiteralSpan condition) { @@ -3215,7 +3299,8 @@ inline id_t Backend::add_theory_term_string(char const *string) { inline id_t Backend::add_theory_term_sequence(TheorySequenceType type, IdSpan elements) { clingo_id_t ret = 0; - Detail::handle_error(clingo_backend_theory_term_sequence(backend_, static_cast(type), elements.data(), elements.size(), &ret)); + Detail::handle_error(clingo_backend_theory_term_sequence(backend_, static_cast(type), + elements.data(), elements.size(), &ret)); return ret; } @@ -3233,70 +3318,74 @@ inline id_t Backend::add_theory_term_symbol(Symbol symbol) { inline id_t Backend::add_theory_element(IdSpan tuple, LiteralSpan condition) { clingo_id_t ret = 0; - Detail::handle_error(clingo_backend_theory_element(backend_, tuple.data(), tuple.size(), condition.begin(), condition.size(), &ret)); + Detail::handle_error( + clingo_backend_theory_element(backend_, tuple.data(), tuple.size(), condition.begin(), condition.size(), &ret)); return ret; } inline atom_t Backend::theory_atom(id_t term_id, IdSpan elements) { atom_t ret = 0; - Detail::handle_error(clingo_backend_theory_atom(backend_, std::numeric_limits::max(), term_id, elements.begin(), elements.size(), &ret)); + Detail::handle_error(clingo_backend_theory_atom(backend_, std::numeric_limits::max(), term_id, + elements.begin(), elements.size(), &ret)); return ret; } inline atom_t Backend::theory_atom(id_t term_id, IdSpan elements, char const *operator_name, id_t right_hand_side_id) { atom_t ret = 0; - Detail::handle_error(clingo_backend_theory_atom_with_guard(backend_, std::numeric_limits::max(), term_id, elements.begin(), elements.size(), operator_name, right_hand_side_id, &ret)); + Detail::handle_error(clingo_backend_theory_atom_with_guard(backend_, std::numeric_limits::max(), term_id, + elements.begin(), elements.size(), operator_name, + right_hand_side_id, &ret)); return ret; } inline atom_t Backend::theory_atom(id_t atom_id_or_zero, id_t term_id, IdSpan elements) { atom_t ret = 0; - Detail::handle_error(clingo_backend_theory_atom(backend_, atom_id_or_zero, term_id, elements.begin(), elements.size(), &ret)); + Detail::handle_error( + clingo_backend_theory_atom(backend_, atom_id_or_zero, term_id, elements.begin(), elements.size(), &ret)); return ret; } -inline atom_t Backend::theory_atom(id_t atom_id_or_zero, id_t term_id, IdSpan elements, char const *operator_name, id_t right_hand_side_id) { +inline atom_t Backend::theory_atom(id_t atom_id_or_zero, id_t term_id, IdSpan elements, char const *operator_name, + id_t right_hand_side_id) { atom_t ret = 0; - Detail::handle_error(clingo_backend_theory_atom_with_guard(backend_, atom_id_or_zero, term_id, elements.begin(), elements.size(), operator_name, right_hand_side_id, &ret)); + Detail::handle_error(clingo_backend_theory_atom_with_guard(backend_, atom_id_or_zero, term_id, elements.begin(), + elements.size(), operator_name, right_hand_side_id, + &ret)); return ret; } // {{{2 statistics -template -inline StatisticsType StatisticsBase::type() const { +template inline StatisticsType StatisticsBase::type() const { clingo_statistics_type_t ret = 0; Detail::handle_error(clingo_statistics_type(stats_, key_, &ret)); return StatisticsType(ret); } -template -inline size_t StatisticsBase::size() const { +template inline size_t StatisticsBase::size() const { size_t ret = 0; Detail::handle_error(clingo_statistics_array_size(stats_, key_, &ret)); return ret; } -template -void StatisticsBase::ensure_size(size_t size, StatisticsType type) { - for (auto s = this->size(); s < size; ++s) { push(type); } +template void StatisticsBase::ensure_size(size_t size, StatisticsType type) { + for (auto s = this->size(); s < size; ++s) { + push(type); + } } -template -inline StatisticsBase StatisticsBase::operator[](size_t index) const { +template inline StatisticsBase StatisticsBase::operator[](size_t index) const { uint64_t ret = 0; Detail::handle_error(clingo_statistics_array_at(stats_, key_, index, &ret)); return StatisticsBase{stats_, ret}; } -template -inline StatisticsBase StatisticsBase::push(StatisticsType type) { +template inline StatisticsBase StatisticsBase::push(StatisticsType type) { uint64_t ret = 0; Detail::handle_error(clingo_statistics_array_push(stats_, key_, static_cast(type), &ret)); return StatisticsBase{stats_, ret}; } - template inline typename StatisticsBase::ArrayIteratorT StatisticsBase::begin() const { return ArrayIteratorT{this, 0}; @@ -3307,15 +3396,13 @@ inline typename StatisticsBase::ArrayIteratorT StatisticsBase -inline StatisticsBase StatisticsBase::operator[](char const *name) const { +template inline StatisticsBase StatisticsBase::operator[](char const *name) const { uint64_t ret = 0; Detail::handle_error(clingo_statistics_map_at(stats_, key_, name, &ret)); return StatisticsBase{stats_, ret}; } -template -inline bool StatisticsBase::has_subkey(char const *name) const { +template inline bool StatisticsBase::has_subkey(char const *name) const { bool ret = false; Detail::handle_error(clingo_statistics_map_has_subkey(stats_, key_, name, &ret)); return ret; @@ -3324,31 +3411,28 @@ inline bool StatisticsBase::has_subkey(char const *name) const { template inline StatisticsBase StatisticsBase::add_subkey(char const *name, StatisticsType type) { uint64_t ret = 0; - Detail::handle_error(clingo_statistics_map_add_subkey(stats_, key_, name, static_cast(type), &ret)); + Detail::handle_error( + clingo_statistics_map_add_subkey(stats_, key_, name, static_cast(type), &ret)); return StatisticsBase{stats_, ret}; } -template -inline typename StatisticsBase::KeyRangeT StatisticsBase::keys() const { +template inline typename StatisticsBase::KeyRangeT StatisticsBase::keys() const { size_t ret = 0; Detail::handle_error(clingo_statistics_map_size(stats_, key_, &ret)); - return KeyRangeT{ KeyIteratorT{this, 0}, KeyIteratorT{this, ret} }; + return KeyRangeT{KeyIteratorT{this, 0}, KeyIteratorT{this, ret}}; } -template -inline double StatisticsBase::value() const { +template inline double StatisticsBase::value() const { double ret = 0; Detail::handle_error(clingo_statistics_value_get(stats_, key_, &ret)); return ret; } -template -inline void StatisticsBase::set_value(double d) { +template inline void StatisticsBase::set_value(double d) { Detail::handle_error(clingo_statistics_value_set(stats_, key_, d)); } -template -inline char const *StatisticsBase::key_name(size_t index) const { +template inline char const *StatisticsBase::key_name(size_t index) const { char const *ret = nullptr; Detail::handle_error(clingo_statistics_map_subkey_name(stats_, key_, index, &ret)); return ret; @@ -3362,13 +3446,9 @@ inline Configuration Configuration::operator[](size_t index) { return Configuration{conf_, ret}; } -inline ConfigurationArrayIterator Configuration::begin() { - return ConfigurationArrayIterator{this, 0}; -} +inline ConfigurationArrayIterator Configuration::begin() { return ConfigurationArrayIterator{this, 0}; } -inline ConfigurationArrayIterator Configuration::end() { - return ConfigurationArrayIterator{this, size()}; -} +inline ConfigurationArrayIterator Configuration::end() { return ConfigurationArrayIterator{this, size()}; } inline size_t Configuration::size() const { size_t n = 0; @@ -3376,9 +3456,7 @@ inline size_t Configuration::size() const { return n; } -inline bool Configuration::empty() const { - return size() == 0; -} +inline bool Configuration::empty() const { return size() == 0; } inline Configuration Configuration::operator[](char const *name) { clingo_id_t ret = 0; @@ -3389,7 +3467,7 @@ inline Configuration Configuration::operator[](char const *name) { inline ConfigurationKeyRange Configuration::keys() const { size_t n = 0; Detail::handle_error(clingo_configuration_map_size(conf_, key_, &n)); - return ConfigurationKeyRange{ ConfigurationKeyIterator{this, size_t(0)}, ConfigurationKeyIterator{this, size_t(n)} }; + return ConfigurationKeyRange{ConfigurationKeyIterator{this, size_t(0)}, ConfigurationKeyIterator{this, size_t(n)}}; } inline bool Configuration::is_value() const { @@ -3441,77 +3519,84 @@ inline char const *Configuration::key_name(size_t index) const { return ret; } - // {{{2 ast namespace AST { namespace ASTDetail { -template -struct construct_ast { +template struct construct_ast { template - static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, int arg, Args&& ...args) { + static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, int arg, + Args &&...args) { if (cons.size <= i || cons.arguments[i].type != clingo_ast_attribute_type_number) { // NOLINT throw std::runtime_error("invalid argument"); } return construct_ast::template construct(type, cons, std::forward(args)..., arg); } template - static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, char const *arg, Args&& ...args) { + static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, char const *arg, + Args &&...args) { if (cons.size <= i || cons.arguments[i].type != clingo_ast_attribute_type_string) { // NOLINT throw std::runtime_error("invalid argument"); } return construct_ast::template construct(type, cons, std::forward(args)..., arg); } template - static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, Symbol const &arg, Args&& ...args) { + static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, Symbol const &arg, + Args &&...args) { if (cons.size <= i || cons.arguments[i].type != clingo_ast_attribute_type_symbol) { // NOLINT throw std::runtime_error("invalid argument"); } return construct_ast::template construct(type, cons, std::forward(args)..., arg.to_c()); } template - static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, Location const &arg, Args&& ...args) { + static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, Location const &arg, + Args &&...args) { if (cons.size <= i || cons.arguments[i].type != clingo_ast_attribute_type_location) { // NOLINT throw std::runtime_error("invalid argument"); } return construct_ast::template construct(type, cons, std::forward(args)..., &arg); } template - static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, Node const &arg, Args&& ...args) { + static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, Node const &arg, + Args &&...args) { if (cons.size <= i || cons.arguments[i].type != clingo_ast_attribute_type_ast) { // NOLINT throw std::runtime_error("invalid argument"); } return construct_ast::template construct(type, cons, std::forward(args)..., arg.to_c()); } template - static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, Optional const &arg, Args&& ...args) { + static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, + Optional const &arg, Args &&...args) { if (cons.size <= i || cons.arguments[i].type != clingo_ast_attribute_type_optional_ast) { // NOLINT throw std::runtime_error("invalid argument"); } return construct_ast::template construct(type, cons, std::forward(args)..., arg.get()); } template - static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, std::vector const &arg, Args&& ...args) { + static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, + std::vector const &arg, Args &&...args) { if (cons.size <= i || cons.arguments[i].type != clingo_ast_attribute_type_ast_array) { // NOLINT throw std::runtime_error("invalid argument"); } - return construct_ast::template construct(type, cons, std::forward(args)..., arg.data(), arg.size()); + return construct_ast::template construct(type, cons, std::forward(args)..., arg.data(), + arg.size()); } template - static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, std::vector const &arg, Args&& ...args) { + static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, + std::vector const &arg, Args &&...args) { if (cons.size <= i || cons.arguments[i].type != clingo_ast_attribute_type_string_array) { // NOLINT throw std::runtime_error("invalid argument"); } - return construct_ast::template construct(type, cons, std::forward(args)..., arg.data(), arg.size()); + return construct_ast::template construct(type, cons, std::forward(args)..., arg.data(), + arg.size()); } }; -template <> -struct construct_ast<0> { +template <> struct construct_ast<0> { template - static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, Args&& ...args) { + static clingo_ast_t *construct(clingo_ast_type_t type, clingo_ast_constructor_t const &cons, Args &&...args) { if (cons.size != i) { throw std::runtime_error("invalid argument"); } @@ -3521,24 +3606,21 @@ struct construct_ast<0> { } }; -template -struct ASTVisitor { +template struct ASTVisitor { void operator()(Attribute attr, NodeValue value) { if (value.is()) { auto &ast = value.get(); if (v(ast)) { ast.visit_attribute(*this); } - } - else if (value.is>()) { + } else if (value.is>()) { auto *ast = value.get>().get(); if (ast != nullptr) { if (v(*ast)) { ast->visit_attribute(*this); } } - } - else if (value.is()) { + } else if (value.is()) { for (Node ast : value.get()) { if (v(ast)) { ast.visit_attribute(*this); @@ -3553,26 +3635,18 @@ struct ASTVisitor { // Node -inline Node::Node(clingo_ast_t *ast) -: ast_{ast} { } +inline Node::Node(clingo_ast_t *ast) : ast_{ast} {} template -Node::Node(Type type, Args&& ...args) -: ast_{ASTDetail::construct_ast::template construct<0>( - static_cast(type), - g_clingo_ast_constructors.constructors[static_cast(type)], // NOLINT - std::forward(args)...)} { -} +Node::Node(Type type, Args &&...args) + : ast_{ASTDetail::construct_ast::template construct<0>( + static_cast(type), + g_clingo_ast_constructors.constructors[static_cast(type)], // NOLINT + std::forward(args)...)} {} -inline Node::Node(Node const &ast) -: ast_{ast.ast_} { - clingo_ast_acquire(ast_); -} +inline Node::Node(Node const &ast) : ast_{ast.ast_} { clingo_ast_acquire(ast_); } -inline Node::Node(Node &&ast) noexcept -: ast_{ast.ast_} { - ast.ast_ = nullptr; -} +inline Node::Node(Node &&ast) noexcept : ast_{ast.ast_} { ast.ast_ = nullptr; } inline Node &Node::operator=(Node const &ast) { // NOLINT if (ast_ != ast.ast_) { @@ -3672,10 +3746,7 @@ inline NodeValue Node::get(Attribute attribute) const { return {NodeVector{*this, attr}}; } -template -T Node::get(Attribute attribute) const { - return get(attribute).get(); -} +template T Node::get(Attribute attribute) const { return get(attribute).get(); } inline void Node::set(Attribute attribute, NodeValue value) { bool has_attribute = false; @@ -3697,14 +3768,15 @@ inline void Node::set(Attribute attribute, NodeValue value) { return Detail::handle_error(clingo_ast_attribute_set_location(ast_, attr, &value.get())); } case clingo_ast_attribute_type_string: { - return Detail::handle_error(clingo_ast_attribute_set_string(ast_, attr, value.get())); + return Detail::handle_error(clingo_ast_attribute_set_string(ast_, attr, value.get())); } case clingo_ast_attribute_type_ast: { return Detail::handle_error(clingo_ast_attribute_set_ast(ast_, attr, value.get().ast_)); } case clingo_ast_attribute_type_optional_ast: { auto *ast = value.get>().get(); - return Detail::handle_error(clingo_ast_attribute_set_optional_ast(ast_, attr, ast != nullptr ? ast->ast_ : nullptr)); + return Detail::handle_error( + clingo_ast_attribute_set_optional_ast(ast_, attr, ast != nullptr ? ast->ast_ : nullptr)); } case clingo_ast_attribute_type_string_array: { auto val = get(attribute); @@ -3733,8 +3805,7 @@ inline void Node::set(Attribute attribute, NodeValue value) { } } -template -inline void Node::visit_attribute(Visitor &&visitor) const { +template inline void Node::visit_attribute(Visitor &&visitor) const { auto visit = std::forward(visitor); auto const &cons = g_clingo_ast_constructors.constructors[static_cast(type())]; // NOLINT for (auto const &x : make_span(cons.arguments, cons.size)) { @@ -3743,16 +3814,14 @@ inline void Node::visit_attribute(Visitor &&visitor) const { } } -template -inline void Node::visit_ast(Visitor &&visitor) const { +template inline void Node::visit_ast(Visitor &&visitor) const { ASTDetail::ASTVisitor v{visitor}; if (std::forward(visitor)(*this)) { visit_attribute(v); } } -template -Node Node::transform_ast(Transformer &&visitor) const { +template Node Node::transform_ast(Transformer &&visitor) const { auto visit = std::forward(visitor); std::vector, std::vector>>> result; visit_attribute([&](Attribute attr, NodeValue value) { @@ -3763,8 +3832,7 @@ Node Node::transform_ast(Transformer &&visitor) const { if (tra.to_c() != ptr) { result.emplace_back(attr, std::move(tra)); } - } - else if (value.is>()) { + } else if (value.is>()) { auto *ast = value.get>().get(); if (ast != nullptr) { auto *ptr = ast->to_c(); @@ -3773,8 +3841,7 @@ Node Node::transform_ast(Transformer &&visitor) const { result.emplace_back(attr, Optional{std::move(tra)}); } } - } - else if (value.is()) { + } else if (value.is()) { auto &ast_vec = value.get(); bool changed = false; std::vector vec; @@ -3807,11 +3874,9 @@ Node Node::transform_ast(Transformer &&visitor) const { for (auto &x : result) { if (x.second.is()) { ret.set(x.first, x.second.get()); - } - else if (x.second.is>()) { + } else if (x.second.is>()) { ret.set(x.first, x.second.get>()); - } - else { + } else { auto val = ret.get(x.first); auto &vec = x.second.get>(); val.clear(); @@ -3835,12 +3900,15 @@ inline std::vector Node::unpool(bool other, bool condition) const { } using Data = std::pair, std::exception_ptr>; Data data({}, nullptr); - Detail::handle_error(clingo_ast_unpool(ast_, type, [](clingo_ast_t *ast, void *data) -> bool { - auto &d = *static_cast(data); - clingo_ast_acquire(ast); - CLINGO_CALLBACK_TRY { d.first.emplace_back(ast); } - CLINGO_CALLBACK_CATCH(d.second); - }, &data)); + Detail::handle_error(clingo_ast_unpool( + ast_, type, + [](clingo_ast_t *ast, void *data) -> bool { + auto &d = *static_cast(data); + clingo_ast_acquire(ast); + CLINGO_CALLBACK_TRY { d.first.emplace_back(ast); } + CLINGO_CALLBACK_CATCH(d.second); + }, + &data)); return std::move(data.first); } @@ -3856,17 +3924,11 @@ inline bool operator<(Node const &a, Node const &b) { return clingo_ast_less_than(a.ast_, b.ast_); } -inline bool operator>(Node const &a, Node const &b) { - return b < a; -} +inline bool operator>(Node const &a, Node const &b) { return b < a; } -inline bool operator<=(Node const &a, Node const &b) { - return !(b < a); -} +inline bool operator<=(Node const &a, Node const &b) { return !(b < a); } -inline bool operator>=(Node const &a, Node const &b) { - return !(a < b); -} +inline bool operator>=(Node const &a, Node const &b) { return !(a < b); } inline bool operator==(Node const &a, Node const &b) { if (a.ast_ == nullptr || b.ast_ == nullptr) { @@ -3875,52 +3937,32 @@ inline bool operator==(Node const &a, Node const &b) { return clingo_ast_equal(a.ast_, b.ast_); } -inline bool operator!=(Node const &a, Node const &b) { - return !(a == b); -} +inline bool operator!=(Node const &a, Node const &b) { return !(a == b); } -inline size_t Node::hash() const { - return clingo_ast_hash(ast_); -} +inline size_t Node::hash() const { return clingo_ast_hash(ast_); } // NodeVector -inline NodeRef::NodeRef(NodeVector *vec, size_t index) -: vec_{vec} -, index_{index} { } +inline NodeRef::NodeRef(NodeVector *vec, size_t index) : vec_{vec}, index_{index} {} inline NodeRef &NodeRef::operator=(Node const &ast) { vec_->set(vec_->begin() + static_cast(index_), ast); return *this; } -inline Node NodeRef::get() const { - return static_cast(vec_)->operator[](index_); -} +inline Node NodeRef::get() const { return static_cast(vec_)->operator[](index_); } -inline NodeRef::operator Node () const { - return get(); -} +inline NodeRef::operator Node() const { return get(); } -inline NodeVector::NodeVector(Node ast, clingo_ast_attribute_t attr) -: ast_{std::move(ast)} -, attr_{attr} { } +inline NodeVector::NodeVector(Node ast, clingo_ast_attribute_t attr) : ast_{std::move(ast)}, attr_{attr} {} -inline NodeVector::iterator NodeVector::begin() { - return iterator{this, 0}; -} +inline NodeVector::iterator NodeVector::begin() { return iterator{this, 0}; } -inline NodeVector::iterator NodeVector::end() { - return iterator{this, size()}; -} +inline NodeVector::iterator NodeVector::end() { return iterator{this, size()}; } -inline NodeVector::const_iterator NodeVector::begin() const { - return const_iterator{this, 0}; -} +inline NodeVector::const_iterator NodeVector::begin() const { return const_iterator{this, 0}; } -inline NodeVector::const_iterator NodeVector::end() const { - return const_iterator{this, size()}; -} +inline NodeVector::const_iterator NodeVector::end() const { return const_iterator{this, size()}; } inline size_t NodeVector::size() const { size_t ret = 0; @@ -3928,9 +3970,7 @@ inline size_t NodeVector::size() const { return ret; } -inline bool NodeVector::empty() const { - return size() == 0; -} +inline bool NodeVector::empty() const { return size() == 0; } inline NodeVector::iterator NodeVector::insert(iterator it, Node const &ast) { Detail::handle_error(clingo_ast_attribute_insert_ast_at(ast_.to_c(), attr_, it - begin(), ast.to_c())); @@ -3946,13 +3986,9 @@ inline void NodeVector::set(iterator it, Node const &ast) { Detail::handle_error(clingo_ast_attribute_set_ast_at(ast_.to_c(), attr_, it - begin(), ast.to_c())); } -inline NodeRef NodeVector::operator[](size_t idx) { - return NodeRef{this, idx}; -} +inline NodeRef NodeVector::operator[](size_t idx) { return NodeRef{this, idx}; } -inline ValuePointer NodeVector::at(size_t idx) { - return operator[](idx); -} +inline ValuePointer NodeVector::at(size_t idx) { return operator[](idx); } inline Node NodeVector::operator[](size_t idx) const { clingo_ast_t *ret = nullptr; @@ -3960,17 +3996,11 @@ inline Node NodeVector::operator[](size_t idx) const { return Node{ret}; } -inline ValuePointer NodeVector::at(size_t idx) const { - return operator[](idx); -} +inline ValuePointer NodeVector::at(size_t idx) const { return operator[](idx); } -inline void NodeVector::push_back(Node const &ast) { - insert(end(), ast); -} +inline void NodeVector::push_back(Node const &ast) { insert(end(), ast); } -inline void NodeVector::pop_back() { - erase(end() - 1); -} +inline void NodeVector::pop_back() { erase(end() - 1); } inline void NodeVector::clear() { for (size_t n = size(); n > 0; --n) { @@ -3978,54 +4008,34 @@ inline void NodeVector::clear() { } } -inline Node &NodeVector::ast() { - return ast_; -} +inline Node &NodeVector::ast() { return ast_; } -inline Node const &NodeVector::ast() const { - return ast_; -} +inline Node const &NodeVector::ast() const { return ast_; } // StringRef -inline StringRef::StringRef(StringVector *vec, size_t index) -: vec_{vec} -, index_{index} { } +inline StringRef::StringRef(StringVector *vec, size_t index) : vec_{vec}, index_{index} {} inline StringRef &StringRef::operator=(char const *str) { vec_->set(vec_->begin() + static_cast(index_), str); return *this; } -inline char const *StringRef::get() const { - return static_cast(vec_)->operator[](index_); -} +inline char const *StringRef::get() const { return static_cast(vec_)->operator[](index_); } -inline StringRef::operator char const *() const { - return get(); -} +inline StringRef::operator char const *() const { return get(); } // StringVector -inline StringVector::StringVector(Node ast, clingo_ast_attribute_t attr) -: ast_{std::move(ast)} -, attr_{attr} { } +inline StringVector::StringVector(Node ast, clingo_ast_attribute_t attr) : ast_{std::move(ast)}, attr_{attr} {} -inline StringVector::iterator StringVector::begin() { - return iterator{this, 0}; -} +inline StringVector::iterator StringVector::begin() { return iterator{this, 0}; } -inline StringVector::iterator StringVector::end() { - return iterator{this, size()}; -} +inline StringVector::iterator StringVector::end() { return iterator{this, size()}; } -inline StringVector::const_iterator StringVector::begin() const { - return const_iterator{this, 0}; -} +inline StringVector::const_iterator StringVector::begin() const { return const_iterator{this, 0}; } -inline StringVector::const_iterator StringVector::end() const { - return const_iterator{this, size()}; -} +inline StringVector::const_iterator StringVector::end() const { return const_iterator{this, size()}; } inline size_t StringVector::size() const { size_t ret = 0; @@ -4033,9 +4043,7 @@ inline size_t StringVector::size() const { return ret; } -inline bool StringVector::empty() const { - return size() == 0; -} +inline bool StringVector::empty() const { return size() == 0; } inline StringVector::iterator StringVector::insert(iterator it, char const *str) { Detail::handle_error(clingo_ast_attribute_insert_string_at(ast_.to_c(), attr_, it - begin(), str)); @@ -4047,13 +4055,9 @@ inline StringVector::iterator StringVector::erase(iterator it) { return it; } -inline StringRef StringVector::operator[](size_t idx) { - return {this, idx}; -} +inline StringRef StringVector::operator[](size_t idx) { return {this, idx}; } -inline ValuePointer StringVector::at(size_t idx) { - return operator[](idx); -} +inline ValuePointer StringVector::at(size_t idx) { return operator[](idx); } inline char const *StringVector::operator[](size_t idx) const { char const *ret = nullptr; @@ -4061,17 +4065,11 @@ inline char const *StringVector::operator[](size_t idx) const { return ret; } -inline ValuePointer StringVector::at(size_t idx) const { - return operator[](idx); -} +inline ValuePointer StringVector::at(size_t idx) const { return operator[](idx); } -inline void StringVector::push_back(char const *str) { - insert(end(), str); -} +inline void StringVector::push_back(char const *str) { insert(end(), str); } -inline void StringVector::pop_back() { - erase(end() - 1); -} +inline void StringVector::pop_back() { erase(end() - 1); } inline void StringVector::clear() { for (size_t n = size(); n > 0; --n) { @@ -4079,29 +4077,22 @@ inline void StringVector::clear() { } } -inline Node &StringVector::ast() { - return ast_; -} +inline Node &StringVector::ast() { return ast_; } -inline Node const &StringVector::ast() const { - return ast_; -} +inline Node const &StringVector::ast() const { return ast_; } // ProgramBuilder -inline ProgramBuilder::ProgramBuilder(Control &ctl) -: builder_{nullptr} { +inline ProgramBuilder::ProgramBuilder(Control &ctl) : builder_{nullptr} { Detail::handle_error(clingo_program_builder_init(ctl.to_c(), &builder_)); Detail::handle_error(clingo_program_builder_begin(builder_)); } -inline ProgramBuilder::ProgramBuilder(clingo_program_builder_t *builder) -: builder_{builder} { +inline ProgramBuilder::ProgramBuilder(clingo_program_builder_t *builder) : builder_{builder} { Detail::handle_error(clingo_program_builder_begin(builder_)); } -inline ProgramBuilder::ProgramBuilder(ProgramBuilder &&builder) noexcept -: builder_{nullptr} { +inline ProgramBuilder::ProgramBuilder(ProgramBuilder &&builder) noexcept : builder_{nullptr} { std::swap(builder_, builder.builder_); } @@ -4112,9 +4103,7 @@ inline void ProgramBuilder::close() { } } -inline ProgramBuilder::~ProgramBuilder() noexcept(false) { - close(); -} +inline ProgramBuilder::~ProgramBuilder() noexcept(false) { close(); } inline void ProgramBuilder::add(Node const &ast) { Detail::handle_error(clingo_program_builder_add(builder_, ast.to_c())); @@ -4125,36 +4114,54 @@ inline void ProgramBuilder::add(Node const &ast) { namespace ASTDetail { template -inline void parse_string(char const *program, Callback &&cb, clingo_control_t *control, Logger logger, unsigned message_limit) { +inline void parse_string(char const *program, Callback &&cb, clingo_control_t *control, Logger logger, + unsigned message_limit) { using Data = std::pair; auto data = Data(std::forward(cb), nullptr); - Detail::handle_error(clingo_ast_parse_string(program, [](clingo_ast_t *ast, void *data) -> bool { - auto &d = *static_cast(data); - clingo_ast_acquire(ast); - CLINGO_CALLBACK_TRY { d.first(Node{ast}); } - CLINGO_CALLBACK_CATCH(d.second); - }, &data, nullptr, [](clingo_warning_t code, char const *msg, void *data) { - try { (*static_cast(data))(static_cast(code), msg); } - catch (...) { } // NOLINT - }, &logger, message_limit), data.second); + Detail::handle_error(clingo_ast_parse_string( + program, + [](clingo_ast_t *ast, void *data) -> bool { + auto &d = *static_cast(data); + clingo_ast_acquire(ast); + CLINGO_CALLBACK_TRY { d.first(Node{ast}); } + CLINGO_CALLBACK_CATCH(d.second); + }, + &data, nullptr, + [](clingo_warning_t code, char const *msg, void *data) { + try { + (*static_cast(data))(static_cast(code), msg); + } catch (...) { + } // NOLINT + }, + &logger, message_limit), + data.second); } template -inline void parse_files(StringSpan files, Callback &&cb, clingo_control_t *control, Logger logger, unsigned message_limit) { +inline void parse_files(StringSpan files, Callback &&cb, clingo_control_t *control, Logger logger, + unsigned message_limit) { using Data = std::pair; auto data = Data(std::forward(cb), nullptr); - Detail::handle_error(clingo_ast_parse_files(files.begin(), files.size(), [](clingo_ast_t *ast, void *data) -> bool { - auto &d = *static_cast(data); - clingo_ast_acquire(ast); - CLINGO_CALLBACK_TRY { d.first(Node{ast}); } - CLINGO_CALLBACK_CATCH(d.second); - }, &data, nullptr, [](clingo_warning_t code, char const *msg, void *data) { - try { (*static_cast(data))(static_cast(code), msg); } - catch (...) { } // NOLINT - }, &logger, message_limit), data.second); + Detail::handle_error(clingo_ast_parse_files( + files.begin(), files.size(), + [](clingo_ast_t *ast, void *data) -> bool { + auto &d = *static_cast(data); + clingo_ast_acquire(ast); + CLINGO_CALLBACK_TRY { d.first(Node{ast}); } + CLINGO_CALLBACK_CATCH(d.second); + }, + &data, nullptr, + [](clingo_warning_t code, char const *msg, void *data) { + try { + (*static_cast(data))(static_cast(code), msg); + } catch (...) { + } // NOLINT + }, + &logger, message_limit), + data.second); } -} // namespace +} // namespace ASTDetail template inline void parse_string(char const *program, Callback &&cb, Logger logger, unsigned message_limit) { @@ -4186,84 +4193,83 @@ struct Control::Impl { Impl(Impl &&) noexcept = delete; Impl &operator=(Impl const &) = delete; Impl &operator=(Impl &&) noexcept = delete; - Impl(Logger logger) - : ctl(nullptr) - , handler(nullptr) - , logger(std::move(logger)) - , owns(true) { } - Impl(clingo_control_t *ctl, bool owns) - : ctl(ctl) - , handler(nullptr) - , owns(owns) { } + Impl(Logger logger) : ctl(nullptr), handler(nullptr), logger(std::move(logger)), owns(true) {} + Impl(clingo_control_t *ctl, bool owns) : ctl(ctl), handler(nullptr), owns(owns) {} ~Impl() { - if (ctl != nullptr && owns) { clingo_control_free(ctl); } + if (ctl != nullptr && owns) { + clingo_control_free(ctl); + } } operator clingo_control_t *() const { return ctl; } clingo_control_t *ctl; SolveEventHandler *handler; Detail::AssignOnce ptr; Logger logger; - std::forward_list> propagators_; - std::forward_list> observers_; + std::forward_list> propagators_; + std::forward_list> observers_; bool owns; }; inline Clingo::Control::Control(StringSpan args, Logger logger, unsigned message_limit) -: impl_(new Clingo::Control::Impl(std::move(logger))) -{ + : impl_(new Clingo::Control::Impl(std::move(logger))) { clingo_logger_t f = [](clingo_warning_t code, char const *msg, void *data) { - try { (*static_cast(data))(static_cast(code), msg); } - catch (...) { } // NOLINT(bugprone-empty-catch) + try { + (*static_cast(data))(static_cast(code), msg); + } catch (...) { + } // NOLINT(bugprone-empty-catch) }; - Detail::handle_error(clingo_control_new(args.begin(), args.size(), impl_->logger ? f : nullptr, impl_->logger ? &impl_->logger : nullptr, message_limit, &impl_->ctl)); + Detail::handle_error(clingo_control_new(args.begin(), args.size(), impl_->logger ? f : nullptr, + impl_->logger ? &impl_->logger : nullptr, message_limit, &impl_->ctl)); } -inline Control::Control(clingo_control_t *ctl, bool owns) - : impl_(new Impl(ctl, owns)) { } +inline Control::Control(clingo_control_t *ctl, bool owns) : impl_(new Impl(ctl, owns)) {} -inline Control::Control(Control &&c) noexcept -: impl_(nullptr) { - *this = std::move(c); -} +inline Control::Control(Control &&c) noexcept : impl_(nullptr) { *this = std::move(c); } inline Control &Control::operator=(Control &&c) noexcept { std::swap(impl_, c.impl_); return *this; } -inline Control::~Control() noexcept { - delete impl_; -} +inline Control::~Control() noexcept { delete impl_; } inline void Control::add(char const *name, StringSpan params, char const *part) { Detail::handle_error(clingo_control_add(*impl_, name, params.begin(), params.size(), part)); } inline void Control::ground(PartSpan parts, GroundCallback cb) { - using Data = std::pair; + using Data = std::pair; Data data(cb, impl_->ptr); impl_->ptr.reset(); - clingo_ground_callback_t ccb = [](clingo_location_t const *loc, char const *name, clingo_symbol_t const *args, size_t n, void *data, clingo_symbol_callback_t cb, void *cbdata) -> bool { - auto &d = *static_cast(data); + clingo_ground_callback_t ccb = [](clingo_location_t const *loc, char const *name, clingo_symbol_t const *args, + size_t n, void *data, clingo_symbol_callback_t cb, void *cbdata) -> bool { + auto &d = *static_cast(data); CLINGO_CALLBACK_TRY { if (d.first) { - struct Ret : std::exception { }; + struct Ret : std::exception {}; try { - d.first(Location(*loc), name, {Detail::cast(args), n}, [cb, cbdata](SymbolSpan symret) { - if (!cb(Detail::cast(symret.begin()), symret.size(), cbdata)) { throw Ret(); } - }); + d.first(Location(*loc), name, {Detail::cast(args), n}, + [cb, cbdata](SymbolSpan symret) { + if (!cb(Detail::cast(symret.begin()), symret.size(), cbdata)) { + throw Ret(); + } + }); + } catch (Ret const &e) { + return false; } - catch (Ret const &e) { return false; } } } CLINGO_CALLBACK_CATCH(d.second); }; - Detail::handle_error(clingo_control_ground(*impl_, Detail::cast(parts.begin()), parts.size(), cb ? ccb : nullptr, &data), data.second); + Detail::handle_error(clingo_control_ground(*impl_, Detail::cast(parts.begin()), parts.size(), + cb ? ccb : nullptr, &data), + data.second); } inline clingo_control_t *Control::to_c() const { return *impl_; } -inline SolveHandle Control::solve(SymbolicLiteralSpan assumptions, SolveEventHandler *handler, bool asynchronous, bool yield) { +inline SolveHandle Control::solve(SymbolicLiteralSpan assumptions, SolveEventHandler *handler, bool asynchronous, + bool yield) { std::vector lits; auto atoms = symbolic_atoms(); for (auto const &x : assumptions) { @@ -4271,8 +4277,7 @@ inline SolveHandle Control::solve(SymbolicLiteralSpan assumptions, SolveEventHan if (it != atoms.end()) { auto lit = it->literal(); lits.emplace_back(x.is_positive() ? lit : -lit); - } - else if (x.is_positive()) { + } else if (x.is_positive()) { lits.emplace_back(1); lits.emplace_back(-1); } @@ -4283,23 +4288,27 @@ inline SolveHandle Control::solve(SymbolicLiteralSpan assumptions, SolveEventHan inline SolveHandle Control::solve(LiteralSpan assumptions, SolveEventHandler *handler, bool asynchronous, bool yield) { clingo_solve_handle_t *it = nullptr; clingo_solve_mode_bitset_t mode = 0; - if (asynchronous) { mode |= clingo_solve_mode_async; } - if (yield) { mode |= clingo_solve_mode_yield; } + if (asynchronous) { + mode |= clingo_solve_mode_async; + } + if (yield) { + mode |= clingo_solve_mode_yield; + } impl_->handler = handler; impl_->ptr.reset(); clingo_solve_event_callback_t on_event = [](clingo_solve_event_type_t type, void *event, void *pdata, bool *goon) { - Impl &data = *static_cast(pdata); + Impl &data = *static_cast(pdata); switch (static_cast(type)) { case clingo_solve_event_type_model: { CLINGO_CALLBACK_TRY { - Model m{static_cast(event)}; + Model m{static_cast(event)}; *goon = data.handler->on_model(m); } CLINGO_CALLBACK_CATCH(data.ptr); } case clingo_solve_event_type_unsat: { CLINGO_CALLBACK_TRY { - auto *span = static_cast*>(event); + auto *span = static_cast *>(event); data.handler->on_unsat(make_span(span->first, span->second)); *goon = true; } @@ -4307,12 +4316,13 @@ inline SolveHandle Control::solve(LiteralSpan assumptions, SolveEventHandler *ha } case clingo_solve_event_type_statistics: { CLINGO_CALLBACK_TRY { - auto **stats = static_cast(event); + auto **stats = static_cast(event); uint64_t step_root = 0; uint64_t accu_root = 0; Detail::handle_error(clingo_statistics_root(stats[0], &step_root)); // NOLINT Detail::handle_error(clingo_statistics_root(stats[1], &accu_root)); // NOLINT - data.handler->on_statistics(UserStatistics{stats[0], step_root}, UserStatistics{stats[1], accu_root}); // NOLINT + data.handler->on_statistics(UserStatistics{stats[0], step_root}, + UserStatistics{stats[1], accu_root}); // NOLINT *goon = true; return true; } @@ -4320,7 +4330,7 @@ inline SolveHandle Control::solve(LiteralSpan assumptions, SolveEventHandler *ha } case clingo_solve_event_type_finish: { CLINGO_CALLBACK_TRY { - data.handler->on_finish(SolveResult{*static_cast(event)}); + data.handler->on_finish(SolveResult{*static_cast(event)}); *goon = true; return true; } @@ -4329,7 +4339,9 @@ inline SolveHandle Control::solve(LiteralSpan assumptions, SolveEventHandler *ha } return false; }; - Detail::handle_error(clingo_control_solve(*impl_, mode, assumptions.begin(), assumptions.size(), handler != nullptr ? on_event : nullptr, impl_, &it), impl_->ptr); + Detail::handle_error(clingo_control_solve(*impl_, mode, assumptions.begin(), assumptions.size(), + handler != nullptr ? on_event : nullptr, impl_, &it), + impl_->ptr); return SolveHandle{it, impl_->ptr}; } @@ -4340,7 +4352,9 @@ inline void Control::assign_external(literal_t literal, TruthValue value) { inline void Control::assign_external(Symbol atom, TruthValue value) { auto atoms = symbolic_atoms(); auto it = atoms.find(atom); - if (it != atoms.end()) { assign_external(it->literal(), value); } + if (it != atoms.end()) { + assign_external(it->literal(), value); + } } inline void Control::release_external(literal_t literal) { @@ -4350,7 +4364,9 @@ inline void Control::release_external(literal_t literal) { inline void Control::release_external(Symbol atom) { auto atoms = symbolic_atoms(); auto it = atoms.find(atom); - if (it != atoms.end()) { release_external(it->literal()); } + if (it != atoms.end()) { + release_external(it->literal()); + } } inline SymbolicAtoms Control::symbolic_atoms() const { @@ -4367,10 +4383,10 @@ inline TheoryAtoms Control::theory_atoms() const { namespace Detail { -using PropagatorData = std::pair; +using PropagatorData = std::pair; inline static bool g_init(clingo_propagate_init_t *ctl, void *pdata) { - PropagatorData &data = *static_cast(pdata); + PropagatorData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { PropagateInit pi(ctl); data.first.init(pi); @@ -4378,8 +4394,9 @@ inline static bool g_init(clingo_propagate_init_t *ctl, void *pdata) { CLINGO_CALLBACK_CATCH(data.second); } -inline static bool g_propagate(clingo_propagate_control_t *ctl, clingo_literal_t const *changes, size_t n, void *pdata) { - PropagatorData &data = *static_cast(pdata); +inline static bool g_propagate(clingo_propagate_control_t *ctl, clingo_literal_t const *changes, size_t n, + void *pdata) { + PropagatorData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { PropagateControl pc(ctl); data.first.propagate(pc, {changes, n}); @@ -4387,14 +4404,15 @@ inline static bool g_propagate(clingo_propagate_control_t *ctl, clingo_literal_t CLINGO_CALLBACK_CATCH(data.second); } -inline static void g_undo(clingo_propagate_control_t const *ctl, clingo_literal_t const *changes, size_t n, void *pdata) { - PropagatorData &data = *static_cast(pdata); - PropagateControl pc(const_cast(ctl)); // NOLINT +inline static void g_undo(clingo_propagate_control_t const *ctl, clingo_literal_t const *changes, size_t n, + void *pdata) { + PropagatorData &data = *static_cast(pdata); + PropagateControl pc(const_cast(ctl)); // NOLINT data.first.undo(pc, {changes, n}); } inline static bool g_check(clingo_propagate_control_t *ctl, void *pdata) { - PropagatorData &data = *static_cast(pdata); + PropagatorData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { PropagateControl pc(ctl); data.first.check(pc); @@ -4402,11 +4420,12 @@ inline static bool g_check(clingo_propagate_control_t *ctl, void *pdata) { CLINGO_CALLBACK_CATCH(data.second); } -inline static bool g_decide(clingo_id_t ti, clingo_assignment_t const *a, clingo_literal_t f, void *pdata, clingo_literal_t *l) { - PropagatorData &data = *static_cast(pdata); +inline static bool g_decide(clingo_id_t ti, clingo_assignment_t const *a, clingo_literal_t f, void *pdata, + clingo_literal_t *l) { + PropagatorData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { Assignment ass{a}; - *l = static_cast(data.first).decide(ti, ass, f); // NOLINT + *l = static_cast(data.first).decide(ti, ass, f); // NOLINT } CLINGO_CALLBACK_CATCH(data.second); } @@ -4416,140 +4435,154 @@ inline static bool g_decide(clingo_id_t ti, clingo_assignment_t const *a, cling inline void Control::register_propagator(Propagator &propagator, bool sequential) { impl_->propagators_.emplace_front(propagator, impl_->ptr); static clingo_propagator_t g_propagator = { - Detail::g_init, - Detail::g_propagate, - Detail::g_undo, - Detail::g_check, - nullptr, + Detail::g_init, Detail::g_propagate, Detail::g_undo, Detail::g_check, nullptr, }; - Detail::handle_error(clingo_control_register_propagator(*impl_, &g_propagator, &impl_->propagators_.front(), sequential)); + Detail::handle_error( + clingo_control_register_propagator(*impl_, &g_propagator, &impl_->propagators_.front(), sequential)); } inline void Control::register_propagator(Heuristic &propagator, bool sequential) { impl_->propagators_.emplace_front(propagator, impl_->ptr); static clingo_propagator_t g_propagator = { - Detail::g_init, - Detail::g_propagate, - Detail::g_undo, - Detail::g_check, - Detail::g_decide, + Detail::g_init, Detail::g_propagate, Detail::g_undo, Detail::g_check, Detail::g_decide, }; - Detail::handle_error(clingo_control_register_propagator(*impl_, &g_propagator, &impl_->propagators_.front(), sequential)); + Detail::handle_error( + clingo_control_register_propagator(*impl_, &g_propagator, &impl_->propagators_.front(), sequential)); } namespace Detail { -using ObserverData = std::pair; +using ObserverData = std::pair; inline bool g_init_program(bool incremental, void *pdata) { - ObserverData &data = *static_cast(pdata); + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.init_program(incremental); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_begin_step(void *pdata) { - ObserverData &data = *static_cast(pdata); + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.begin_step(); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_end_step(void *pdata) { - ObserverData &data = *static_cast(pdata); + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.end_step(); } CLINGO_CALLBACK_CATCH(data.second); } -inline bool g_rule(bool choice, clingo_atom_t const *head, size_t head_size, clingo_literal_t const *body, size_t body_size, void *pdata) { - ObserverData &data = *static_cast(pdata); +inline bool g_rule(bool choice, clingo_atom_t const *head, size_t head_size, clingo_literal_t const *body, + size_t body_size, void *pdata) { + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.rule(choice, AtomSpan(head, head_size), LiteralSpan(body, body_size)); } CLINGO_CALLBACK_CATCH(data.second); } -inline bool g_weight_rule(bool choice, clingo_atom_t const *head, size_t head_size, clingo_weight_t lower_bound, clingo_weighted_literal_t const *body, size_t body_size, void *pdata) { - ObserverData &data = *static_cast(pdata); - CLINGO_CALLBACK_TRY { data.first.weight_rule(choice, AtomSpan(head, head_size), lower_bound, WeightedLiteralSpan(Detail::cast(body), body_size)); } +inline bool g_weight_rule(bool choice, clingo_atom_t const *head, size_t head_size, clingo_weight_t lower_bound, + clingo_weighted_literal_t const *body, size_t body_size, void *pdata) { + ObserverData &data = *static_cast(pdata); + CLINGO_CALLBACK_TRY { + data.first.weight_rule(choice, AtomSpan(head, head_size), lower_bound, + WeightedLiteralSpan(Detail::cast(body), body_size)); + } CLINGO_CALLBACK_CATCH(data.second); } -inline bool g_minimize(clingo_weight_t priority, clingo_weighted_literal_t const* literals, size_t size, void *pdata) { - ObserverData &data = *static_cast(pdata); - CLINGO_CALLBACK_TRY { data.first.minimize(priority, WeightedLiteralSpan(Detail::cast(literals), size)); } +inline bool g_minimize(clingo_weight_t priority, clingo_weighted_literal_t const *literals, size_t size, void *pdata) { + ObserverData &data = *static_cast(pdata); + CLINGO_CALLBACK_TRY { + data.first.minimize(priority, WeightedLiteralSpan(Detail::cast(literals), size)); + } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_project(clingo_atom_t const *atoms, size_t size, void *pdata) { - ObserverData &data = *static_cast(pdata); + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.project(AtomSpan(atoms, size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_output_atom(clingo_symbol_t symbol, clingo_atom_t atom, void *pdata) { - ObserverData &data = *static_cast(pdata); + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.output_atom(Symbol{symbol}, atom); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_output_term(clingo_symbol_t symbol, clingo_literal_t const *condition, size_t size, void *pdata) { - ObserverData &data = *static_cast(pdata); + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.output_term(Symbol{symbol}, LiteralSpan{condition, size}); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_external(clingo_atom_t atom, clingo_external_type_t type, void *pdata) { - ObserverData &data = *static_cast(pdata); + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.external(atom, static_cast(type)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_assume(clingo_literal_t const *literals, size_t size, void *pdata) { - ObserverData &data = *static_cast(pdata); + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.assume(LiteralSpan(literals, size)); } CLINGO_CALLBACK_CATCH(data.second); } -inline bool g_heuristic(clingo_atom_t atom, clingo_heuristic_type_t type, int bias, unsigned priority, clingo_literal_t const *condition, size_t size, void *pdata) { - ObserverData &data = *static_cast(pdata); - CLINGO_CALLBACK_TRY { data.first.heuristic(atom, static_cast(type), bias, priority, LiteralSpan(condition, size)); } +inline bool g_heuristic(clingo_atom_t atom, clingo_heuristic_type_t type, int bias, unsigned priority, + clingo_literal_t const *condition, size_t size, void *pdata) { + ObserverData &data = *static_cast(pdata); + CLINGO_CALLBACK_TRY { + data.first.heuristic(atom, static_cast(type), bias, priority, LiteralSpan(condition, size)); + } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_acyc_edge(int node_u, int node_v, clingo_literal_t const *condition, size_t size, void *pdata) { - ObserverData &data = *static_cast(pdata); + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.acyc_edge(node_u, node_v, LiteralSpan(condition, size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_theory_term_number(clingo_id_t term_id, int number, void *pdata) { - ObserverData &data = *static_cast(pdata); + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.theory_term_number(term_id, number); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_theory_term_string(clingo_id_t term_id, char const *name, void *pdata) { - ObserverData &data = *static_cast(pdata); + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.theory_term_string(term_id, name); } CLINGO_CALLBACK_CATCH(data.second); } -inline bool g_theory_term_compound(clingo_id_t term_id, int name_id_or_type, clingo_id_t const *arguments, size_t size, void *pdata) { - ObserverData &data = *static_cast(pdata); +inline bool g_theory_term_compound(clingo_id_t term_id, int name_id_or_type, clingo_id_t const *arguments, size_t size, + void *pdata) { + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.theory_term_compound(term_id, name_id_or_type, IdSpan(arguments, size)); } CLINGO_CALLBACK_CATCH(data.second); } -inline bool g_theory_element(clingo_id_t element_id, clingo_id_t const *terms, size_t terms_size, clingo_literal_t const *condition, size_t condition_size, void *pdata) { - ObserverData &data = *static_cast(pdata); - CLINGO_CALLBACK_TRY { data.first.theory_element(element_id, IdSpan(terms, terms_size), LiteralSpan(condition, condition_size)); } +inline bool g_theory_element(clingo_id_t element_id, clingo_id_t const *terms, size_t terms_size, + clingo_literal_t const *condition, size_t condition_size, void *pdata) { + ObserverData &data = *static_cast(pdata); + CLINGO_CALLBACK_TRY { + data.first.theory_element(element_id, IdSpan(terms, terms_size), LiteralSpan(condition, condition_size)); + } CLINGO_CALLBACK_CATCH(data.second); } -inline bool g_theory_atom(clingo_id_t atom_id_or_zero, clingo_id_t term_id, clingo_id_t const *elements, size_t size, void *pdata) { - ObserverData &data = *static_cast(pdata); +inline bool g_theory_atom(clingo_id_t atom_id_or_zero, clingo_id_t term_id, clingo_id_t const *elements, size_t size, + void *pdata) { + ObserverData &data = *static_cast(pdata); CLINGO_CALLBACK_TRY { data.first.theory_atom(atom_id_or_zero, term_id, IdSpan(elements, size)); } CLINGO_CALLBACK_CATCH(data.second); } -inline bool g_theory_atom_with_guard(clingo_id_t atom_id_or_zero, clingo_id_t term_id, clingo_id_t const *elements, size_t size, clingo_id_t operator_id, clingo_id_t right_hand_side_id, void *pdata) { - ObserverData &data = *static_cast(pdata); - CLINGO_CALLBACK_TRY { data.first.theory_atom_with_guard(atom_id_or_zero, term_id, IdSpan(elements, size), operator_id, right_hand_side_id); } +inline bool g_theory_atom_with_guard(clingo_id_t atom_id_or_zero, clingo_id_t term_id, clingo_id_t const *elements, + size_t size, clingo_id_t operator_id, clingo_id_t right_hand_side_id, + void *pdata) { + ObserverData &data = *static_cast(pdata); + CLINGO_CALLBACK_TRY { + data.first.theory_atom_with_guard(atom_id_or_zero, term_id, IdSpan(elements, size), operator_id, + right_hand_side_id); + } CLINGO_CALLBACK_CATCH(data.second); } @@ -4557,33 +4590,29 @@ inline bool g_theory_atom_with_guard(clingo_id_t atom_id_or_zero, clingo_id_t te inline void Control::register_observer(GroundProgramObserver &observer, bool replace) { impl_->observers_.emplace_front(observer, impl_->ptr); - static clingo_ground_program_observer_t g_observer = { - Detail::g_init_program, - Detail::g_begin_step, - Detail::g_end_step, - Detail::g_rule, - Detail::g_weight_rule, - Detail::g_minimize, - Detail::g_project, - Detail::g_output_atom, - Detail::g_output_term, - Detail::g_external, - Detail::g_assume, - Detail::g_heuristic, - Detail::g_acyc_edge, - Detail::g_theory_term_number, - Detail::g_theory_term_string, - Detail::g_theory_term_compound, - Detail::g_theory_element, - Detail::g_theory_atom, - Detail::g_theory_atom_with_guard - }; + static clingo_ground_program_observer_t g_observer = {Detail::g_init_program, + Detail::g_begin_step, + Detail::g_end_step, + Detail::g_rule, + Detail::g_weight_rule, + Detail::g_minimize, + Detail::g_project, + Detail::g_output_atom, + Detail::g_output_term, + Detail::g_external, + Detail::g_assume, + Detail::g_heuristic, + Detail::g_acyc_edge, + Detail::g_theory_term_number, + Detail::g_theory_term_string, + Detail::g_theory_term_compound, + Detail::g_theory_element, + Detail::g_theory_atom, + Detail::g_theory_atom_with_guard}; Detail::handle_error(clingo_control_register_observer(*impl_, &g_observer, replace, &impl_->observers_.front())); } -inline bool Control::is_conflicting() const noexcept { - return clingo_control_is_conflicting(*impl_); -} +inline bool Control::is_conflicting() const noexcept { return clingo_control_is_conflicting(*impl_); } inline bool Control::has_const(char const *name) const { bool ret = false; @@ -4597,9 +4626,7 @@ inline Symbol Control::get_const(char const *name) const { return Symbol(ret); } -inline void Control::interrupt() noexcept { - clingo_control_interrupt(*impl_); -} +inline void Control::interrupt() noexcept { clingo_control_interrupt(*impl_); } inline void *Control::claspFacade() { void *ret = nullptr; @@ -4607,9 +4634,7 @@ inline void *Control::claspFacade() { return ret; } -inline void Control::load(char const *file) { - Detail::handle_error(clingo_control_load(*impl_, file)); -} +inline void Control::load(char const *file) { Detail::handle_error(clingo_control_load(*impl_, file)); } inline void Control::enable_enumeration_assumption(bool value) { Detail::handle_error(clingo_control_set_enable_enumeration_assumption(*impl_, value)); @@ -4619,17 +4644,13 @@ inline bool Control::enable_enumeration_assumption() const { return clingo_control_get_enable_enumeration_assumption(*impl_); } -inline void Control::cleanup() { - Detail::handle_error(clingo_control_cleanup(*impl_)); -} +inline void Control::cleanup() { Detail::handle_error(clingo_control_cleanup(*impl_)); } inline void Control::enable_cleanup(bool value) { Detail::handle_error(clingo_control_set_enable_cleanup(*impl_, value)); } -inline bool Control::enable_cleanup() const { - return clingo_control_get_enable_cleanup(*impl_); -} +inline bool Control::enable_cleanup() const { return clingo_control_get_enable_cleanup(*impl_); } inline Backend Control::backend() { clingo_backend_t *ret = nullptr; @@ -4655,28 +4676,30 @@ inline Statistics Control::statistics() const { // {{{2 clingo application -inline void ClingoOptions::add(char const *group, char const *option, char const *description, std::function parse, bool multi, char const *argument) { +inline void ClingoOptions::add(char const *group, char const *option, char const *description, + std::function parse, bool multi, char const *argument) { parsers_->emplace_front(std::move(parse)); - Detail::handle_error(clingo_options_add(to_c(), group, option, description, [](char const *value, void *data) { - auto& p = *static_cast(data); - try { return p(value); } - catch (...) { return false; } - }, &parsers_->front(), multi, argument)); + Detail::handle_error(clingo_options_add( + to_c(), group, option, description, + [](char const *value, void *data) { + auto &p = *static_cast(data); + try { + return p(value); + } catch (...) { + return false; + } + }, + &parsers_->front(), multi, argument)); } -inline void ClingoOptions::add_flag(char const *group, char const *option, char const *description, bool &target) { // NOLINT +inline void ClingoOptions::add_flag(char const *group, char const *option, char const *description, + bool &target) { // NOLINT Detail::handle_error(clingo_options_add_flag(to_c(), group, option, description, &target)); } -inline unsigned Application::message_limit() const noexcept { - return g_message_limit; -} -inline char const *Application::program_name() const noexcept { - return "clingo"; -} -inline char const *Application::version() const noexcept { - return CLINGO_VERSION; -} +inline unsigned Application::message_limit() const noexcept { return g_message_limit; } +inline char const *Application::program_name() const noexcept { return "clingo"; } +inline char const *Application::version() const noexcept { return CLINGO_VERSION; } inline void Application::print_model(Model const &model, std::function default_printer) noexcept { // NOLINT static_cast(model); default_printer(); @@ -4686,11 +4709,8 @@ inline void Application::log(WarningCode code, char const *message) noexcept { fprintf(stderr, "%s\n", message); // NOLINT fflush(stderr); } -inline void Application::register_options(ClingoOptions &options) { - static_cast(options); -} -inline void Application::validate_options() { -} +inline void Application::register_options(ClingoOptions &options) { static_cast(options); } +inline void Application::validate_options() {} namespace Detail { @@ -4700,22 +4720,22 @@ struct ApplicationData { }; inline static unsigned g_message_limit(void *adata) { - ApplicationData &data = *static_cast(adata); + ApplicationData &data = *static_cast(adata); return data.app->message_limit(); } inline static char const *g_program_name(void *adata) { - ApplicationData &data = *static_cast(adata); + ApplicationData &data = *static_cast(adata); return data.app->program_name(); } inline static char const *g_version(void *adata) { - ApplicationData &data = *static_cast(adata); + ApplicationData &data = *static_cast(adata); return data.app->version(); } -inline static bool g_main(clingo_control_t *control, char const *const * files, size_t size, void *adata) { - ApplicationData &data = *static_cast(adata); +inline static bool g_main(clingo_control_t *control, char const *const *files, size_t size, void *adata) { + ApplicationData &data = *static_cast(adata); CLINGO_TRY { Control ctl{control, false}; data.app->main(ctl, {files, size}); @@ -4724,14 +4744,15 @@ inline static bool g_main(clingo_control_t *control, char const *const * files, } inline static void g_logger(clingo_warning_t code, char const *message, void *adata) { - ApplicationData &data = *static_cast(adata); + ApplicationData &data = *static_cast(adata); return data.app->log(static_cast(code), message); } -inline static bool g_model_printer(clingo_model_t const *model, clingo_default_model_printer_t printer, void *printer_data, void *data) { - ApplicationData &app_data = *static_cast(data); +inline static bool g_model_printer(clingo_model_t const *model, clingo_default_model_printer_t printer, + void *printer_data, void *data) { + ApplicationData &app_data = *static_cast(data); CLINGO_TRY { - app_data.app->print_model(Model(const_cast(model)), [&]() { // NOLINT + app_data.app->print_model(Model(const_cast(model)), [&]() { // NOLINT Detail::handle_error(printer(printer_data)); }); } @@ -4739,7 +4760,7 @@ inline static bool g_model_printer(clingo_model_t const *model, clingo_default_m } inline static bool g_register_options(clingo_options_t *options, void *adata) { - ApplicationData &data = *static_cast(adata); + ApplicationData &data = *static_cast(adata); CLINGO_TRY { ClingoOptions opts{options, data.parsers}; data.app->register_options(opts); @@ -4748,21 +4769,26 @@ inline static bool g_register_options(clingo_options_t *options, void *adata) { } inline static bool g_validate_options(void *adata) { - ApplicationData &data = *static_cast(adata); + ApplicationData &data = *static_cast(adata); CLINGO_TRY { data.app->validate_options(); } CLINGO_CATCH; } -} // namespace +} // namespace Detail // {{{2 global functions inline Symbol parse_term(char const *str, Logger logger, unsigned message_limit) { clingo_symbol_t ret = 0; - Detail::handle_error(clingo_parse_term(str, [](clingo_warning_t code, char const *msg, void *data) { - try { (*static_cast(data))(static_cast(code), msg); } - catch (...) { } // NOLINT(bugprone-empty-catch) - }, &logger, message_limit, &ret)); + Detail::handle_error(clingo_parse_term( + str, + [](clingo_warning_t code, char const *msg, void *data) { + try { + (*static_cast(data))(static_cast(code), msg); + } catch (...) { + } // NOLINT(bugprone-empty-catch) + }, + &logger, message_limit, &ret)); return Symbol(ret); } @@ -4781,15 +4807,8 @@ inline std::tuple version() { inline int clingo_main(Application &application, StringSpan arguments) { Detail::ApplicationData data{&application, Detail::ParserList{}}; static clingo_application_t g_app = { - Detail::g_program_name, - Detail::g_version, - Detail::g_message_limit, - Detail::g_main, - Detail::g_logger, - Detail::g_model_printer, - Detail::g_register_options, - Detail::g_validate_options - }; + Detail::g_program_name, Detail::g_version, Detail::g_message_limit, Detail::g_main, + Detail::g_logger, Detail::g_model_printer, Detail::g_register_options, Detail::g_validate_options}; return ::clingo_main(&g_app, arguments.begin(), arguments.size(), &data); } diff --git a/libclingo/clingo/astv2.hh b/libclingo/clingo/astv2.hh index 219d8026e..8ccf2d46d 100644 --- a/libclingo/clingo/astv2.hh +++ b/libclingo/clingo/astv2.hh @@ -25,8 +25,8 @@ #ifndef CLINGO_AST_HH #define CLINGO_AST_HH -#include #include +#include #include #include @@ -34,14 +34,15 @@ // TODO: // - the way OAST and SAST are handled is really realy ugly -namespace Gringo { namespace Input { +namespace Gringo { +namespace Input { class AST; // Note: we do not need all the shared pointer functionality and also want to // have control about the refcount for the C binding. class SAST { -public: + public: SAST(); SAST(SAST const &ast); SAST(SAST &&ast) noexcept; @@ -57,18 +58,19 @@ public: unsigned use_count() const; void clear(); ~SAST(); -private: + + private: AST *ast_; }; -using SASTCallback = std::function; +using SASTCallback = std::function; struct OAST { SAST ast; }; class AST { -public: + public: using StrVec = std::vector; using ASTVec = std::vector; using Value = mpark::variant; @@ -88,8 +90,7 @@ public: void value(clingo_ast_attribute_e name, Value value); clingo_ast_type_e type() const; SAST copy(); - template - SAST update(Args&&... args) { + template SAST update(Args &&...args) { auto ast = SAST{type_}; for (auto &val : values_) { ast->values_.emplace_back(update_(val, std::forward(args)...)); @@ -106,14 +107,14 @@ public: void decRef(); unsigned refCount() const; bool unique() const; -private: + + private: AttributeVector::iterator find_(clingo_ast_attribute_e name); AttributeVector::const_iterator find_(clingo_ast_attribute_e name) const; - AttributeVector::value_type update_(AttributeVector::value_type const &x) { - return x; - } + AttributeVector::value_type update_(AttributeVector::value_type const &x) { return x; } template - AttributeVector::value_type update_(AttributeVector::value_type const &x, clingo_ast_attribute_e name, V &&value, Args&&... args) { + AttributeVector::value_type update_(AttributeVector::value_type const &x, clingo_ast_attribute_e name, V &&value, + Args &&...args) { if (x.first == name) { return {name, std::forward(value)}; } @@ -130,9 +131,10 @@ std::ostream &operator<<(std::ostream &out, AST const &ast); std::unique_ptr build(SASTCallback cb); void parse(INongroundProgramBuilder &prg, Logger &log, AST const &ast); -tl::optional unpool(SAST &ast, clingo_ast_unpool_type_bitset_t type=clingo_ast_unpool_type_all); +tl::optional unpool(SAST &ast, clingo_ast_unpool_type_bitset_t type = clingo_ast_unpool_type_all); -} } // namespace Input Gringo +} // namespace Input +} // namespace Gringo struct clingo_ast { Gringo::Input::AST ast; diff --git a/libclingo/clingo/clingo_app.hh b/libclingo/clingo/clingo_app.hh index 7613489fa..abe455dfc 100644 --- a/libclingo/clingo/clingo_app.hh +++ b/libclingo/clingo/clingo_app.hh @@ -25,8 +25,8 @@ #ifndef CLINGO_CLINGOAPP_HH #define CLINGO_CLINGOAPP_HH -#include #include "clingo/clingocontrol.hh" +#include namespace Gringo { @@ -34,38 +34,44 @@ namespace Gringo { class ClingoApp : public Clasp::Cli::ClaspAppBase { using ClaspOutput = Clasp::Cli::Output; using ProblemType = Clasp::ProblemType; - using BaseType = Clasp::Cli::ClaspAppBase; - using OptionParser = std::function; + using BaseType = Clasp::Cli::ClaspAppBase; + using OptionParser = std::function; enum class ConfigUpdate { KEEP, REPLACE }; -public: + + public: ClingoApp(UIClingoApp app = gringo_make_unique()); - const char* getName() const override { return app_->program_name(); } - const char* getVersion() const override { return app_->version(); } - const char* getUsage() const override { return "[number] [options] [files]"; } + const char *getName() const override { return app_->program_name(); } + const char *getVersion() const override { return app_->version(); } + const char *getUsage() const override { return "[number] [options] [files]"; } - void addOption(char const *group, char const *option, char const *description, OptionParser parse, char const *argument = nullptr, bool multi = false); + void addOption(char const *group, char const *option, char const *description, OptionParser parse, + char const *argument = nullptr, bool multi = false); void addFlag(char const *group, char const *option, char const *description, bool &target); -protected: + + protected: enum Mode { mode_clingo = 0, mode_clasp = 1, mode_gringo = 2 }; - void initOptions(Potassco::ProgramOptions::OptionContext& root) override; - void validateOptions(const Potassco::ProgramOptions::OptionContext& root, const Potassco::ProgramOptions::ParsedOptions& parsed, const Potassco::ProgramOptions::ParsedValues& vals) override; + void initOptions(Potassco::ProgramOptions::OptionContext &root) override; + void validateOptions(const Potassco::ProgramOptions::OptionContext &root, + const Potassco::ProgramOptions::ParsedOptions &parsed, + const Potassco::ProgramOptions::ParsedValues &vals) override; ProblemType getProblemType() override; - void run(Clasp::ClaspFacade& clasp) override; - ClaspOutput* createTextOutput(const Clasp::Cli::ClaspAppBase::TextOptions& options) override; - void printHelp(const Potassco::ProgramOptions::OptionContext& root) override; - void printVersion() override; + void run(Clasp::ClaspFacade &clasp) override; + ClaspOutput *createTextOutput(const Clasp::Cli::ClaspAppBase::TextOptions &options) override; + void printHelp(const Potassco::ProgramOptions::OptionContext &root) override; + void printVersion() override; // ------------------------------------------------------------------------------------------- // Event handler - void onEvent(const Clasp::Event& ev) override; - bool onModel(const Clasp::Solver& s, const Clasp::Model& m) override; + void onEvent(const Clasp::Event &ev) override; + bool onModel(const Clasp::Solver &s, const Clasp::Model &m) override; // ------------------------------------------------------------------------------------------- -private: + private: Potassco::ProgramOptions::OptionGroup &addGroup_(char const *group_name); -private: - ClingoApp(const ClingoApp&); - ClingoApp& operator=(const ClingoApp&); + + private: + ClingoApp(const ClingoApp &); + ClingoApp &operator=(const ClingoApp &); ClingoOptions grOpts_; Mode mode_; std::unique_ptr grd; diff --git a/libclingo/clingo/clingocontrol.hh b/libclingo/clingo/clingocontrol.hh index c96000d12..8f93bb0f5 100644 --- a/libclingo/clingo/clingocontrol.hh +++ b/libclingo/clingo/clingocontrol.hh @@ -26,25 +26,25 @@ #define CLINGO_CLINGOCONTROL_HH #include "clingo.h" -#include +#include +#include +#include +#include +#include +#include #include #include #include -#include -#include +#include +#include +#include #include #include -#include -#include #include -#include -#include -#include -#include -#include -#include +#include #include -#include +#include +#include namespace Gringo { @@ -52,34 +52,38 @@ namespace Gringo { class ClingoControl; class ClaspAPIBackend : public Backend { -public: - ClaspAPIBackend(ClingoControl& ctl) : ctl_(ctl) { } - ClaspAPIBackend(const ClaspAPIBackend&) = delete; - ClaspAPIBackend& operator=(const ClaspAPIBackend&) = delete; + public: + ClaspAPIBackend(ClingoControl &ctl) : ctl_(ctl) {} + ClaspAPIBackend(const ClaspAPIBackend &) = delete; + ClaspAPIBackend &operator=(const ClaspAPIBackend &) = delete; void initProgram(bool incremental) override; void beginStep() override; - void rule(Potassco::Head_t ht, const Potassco::AtomSpan& head, const Potassco::LitSpan& body) override; - void rule(Potassco::Head_t ht, const Potassco::AtomSpan& head, Potassco::Weight_t bound, const Potassco::WeightLitSpan& body) override; - void minimize(Potassco::Weight_t prio, const Potassco::WeightLitSpan& lits) override; - void project(const Potassco::AtomSpan& atoms) override; + void rule(Potassco::Head_t ht, const Potassco::AtomSpan &head, const Potassco::LitSpan &body) override; + void rule(Potassco::Head_t ht, const Potassco::AtomSpan &head, Potassco::Weight_t bound, + const Potassco::WeightLitSpan &body) override; + void minimize(Potassco::Weight_t prio, const Potassco::WeightLitSpan &lits) override; + void project(const Potassco::AtomSpan &atoms) override; void output(Symbol sym, Potassco::Atom_t atom) override; - void output(Symbol sym, Potassco::LitSpan const& condition) override; + void output(Symbol sym, Potassco::LitSpan const &condition) override; void external(Potassco::Atom_t a, Potassco::Value_t v) override; - void assume(const Potassco::LitSpan& lits) override; - void heuristic(Potassco::Atom_t a, Potassco::Heuristic_t t, int bias, unsigned prio, const Potassco::LitSpan& condition) override; - void acycEdge(int s, int t, const Potassco::LitSpan& condition) override; + void assume(const Potassco::LitSpan &lits) override; + void heuristic(Potassco::Atom_t a, Potassco::Heuristic_t t, int bias, unsigned prio, + const Potassco::LitSpan &condition) override; + void acycEdge(int s, int t, const Potassco::LitSpan &condition) override; void theoryTerm(Potassco::Id_t termId, int number) override; - void theoryTerm(Potassco::Id_t termId, const Potassco::StringSpan& name) override; - void theoryTerm(Potassco::Id_t termId, int cId, const Potassco::IdSpan& args) override; - void theoryElement(Potassco::Id_t elementId, const Potassco::IdSpan& terms, const Potassco::LitSpan& cond) override; - void theoryAtom(Potassco::Id_t atomOrZero, Potassco::Id_t termId, const Potassco::IdSpan& elements) override; - void theoryAtom(Potassco::Id_t atomOrZero, Potassco::Id_t termId, const Potassco::IdSpan& elements, Potassco::Id_t op, Potassco::Id_t rhs) override; + void theoryTerm(Potassco::Id_t termId, const Potassco::StringSpan &name) override; + void theoryTerm(Potassco::Id_t termId, int cId, const Potassco::IdSpan &args) override; + void theoryElement(Potassco::Id_t elementId, const Potassco::IdSpan &terms, const Potassco::LitSpan &cond) override; + void theoryAtom(Potassco::Id_t atomOrZero, Potassco::Id_t termId, const Potassco::IdSpan &elements) override; + void theoryAtom(Potassco::Id_t atomOrZero, Potassco::Id_t termId, const Potassco::IdSpan &elements, + Potassco::Id_t op, Potassco::Id_t rhs) override; void endStep() override; ~ClaspAPIBackend() noexcept override; -private: + + private: std::string str_(Symbol sym); Clasp::Asp::LogicProgram *prg(); - ClingoControl& ctl_; + ClingoControl &ctl_; std::ostringstream out_; }; @@ -88,27 +92,40 @@ using ClingoOptions = GringoOptions; // {{{1 declaration of ClingoControl class ClingoPropagatorLock : public Clasp::ClingoPropagatorLock { -public: + public: ClingoPropagatorLock() : seq_(0) {} - void lock() override { if (mut_) mut_->lock(); } - void unlock() override { if (mut_) mut_->unlock(); } - ClingoPropagatorLock* add(bool seq) { - if (seq) { ++seq_; return this; } + void lock() override { + if (mut_) + mut_->lock(); + } + void unlock() override { + if (mut_) + mut_->unlock(); + } + ClingoPropagatorLock *add(bool seq) { + if (seq) { + ++seq_; + return this; + } return 0; } void init(unsigned nThreads) { - if (nThreads < 2 || !seq_) { mut_ = nullptr; } - else if (!mut_.get()) { mut_ = gringo_make_unique(); } + if (nThreads < 2 || !seq_) { + mut_ = nullptr; + } else if (!mut_.get()) { + mut_ = gringo_make_unique(); + } } -private: + + private: using OptLock = std::unique_ptr; - OptLock mut_; + OptLock mut_; unsigned seq_; }; class ClingoApp; class IClingoApp { -public: + public: virtual unsigned message_limit() const { return 20; } virtual char const *program_name() const { return "clingo"; } virtual char const *version() const { return clingo_version_string(); } @@ -130,37 +147,31 @@ public: printer(); } virtual void register_options(ClingoApp &app) { static_cast(app); } - virtual void validate_options() { } + virtual void validate_options() {} virtual ~IClingoApp() = default; }; using UIClingoApp = std::unique_ptr; class TheoryOutput : public Clasp::OutputTable::Theory { -public: - char const * first(const Clasp::Model&) override; - char const * next() override; - void add(Potassco::Span symbols) { - symbols_.insert(symbols_.end(), begin(symbols), end(symbols)); - } - void copy_symbols(std::vector &symbols) { - symbols.insert(symbols.end(), symbols_.begin(), symbols_.end()); - } + public: + char const *first(const Clasp::Model &) override; + char const *next() override; + void add(Potassco::Span symbols) { symbols_.insert(symbols_.end(), begin(symbols), end(symbols)); } + void copy_symbols(std::vector &symbols) { symbols.insert(symbols.end(), symbols_.begin(), symbols_.end()); } void reset() { symbols_.clear(); index_ = 0; } -private: + private: std::vector symbols_; - std::string current_; - size_t index_; + std::string current_; + size_t index_; }; class UserStatistics : public Potassco::AbstractStatistics { -public: - explicit UserStatistics() - : stats_{nullptr} - , root_{0} { } + public: + explicit UserStatistics() : stats_{nullptr}, root_{0} {} void init(Potassco::AbstractStatistics *stats, char const *root) { stats_ = stats; root_ = stats_->add(stats_->root(), root, Potassco::Statistics_t::Map); @@ -174,50 +185,64 @@ public: Key_t at(Key_t arr, size_t index) const override { return stats_->at(arr, index); } Key_t push(Key_t arr, Potassco::Statistics_t type) override { return stats_->push(arr, type); } - const char* key(Key_t mapK, size_t i) const override { return stats_->key(mapK, i); } - Key_t get(Key_t mapK, const char* at) const override { return stats_->get(mapK, at); } - bool find(Key_t mapK, const char* element, Key_t* outKey) const override { return stats_->find(mapK, element, outKey); } + const char *key(Key_t mapK, size_t i) const override { return stats_->key(mapK, i); } + Key_t get(Key_t mapK, const char *at) const override { return stats_->get(mapK, at); } + bool find(Key_t mapK, const char *element, Key_t *outKey) const override { + return stats_->find(mapK, element, outKey); + } - Key_t add(Key_t mapK, const char* name, Potassco::Statistics_t type) override { return stats_->add(mapK, name, type); } + Key_t add(Key_t mapK, const char *name, Potassco::Statistics_t type) override { + return stats_->add(mapK, name, type); + } double value(Key_t key) const override { return stats_->value(key); } void set(Key_t key, double value) override { return stats_->set(key, value); } -private: + + private: Potassco::AbstractStatistics *stats_; Key_t root_; }; class ClingoSolveFuture; -class ClingoControl : public clingo_control, private ConfigProxy, private SymbolicAtoms, private Potassco::AbstractHeuristic { +class ClingoControl : public clingo_control, + private ConfigProxy, + private SymbolicAtoms, + private Potassco::AbstractHeuristic { class ControlBackend; -public: - using StringVec = std::vector; - using ExternalVec = std::vector>; - using PostGroundFunc = std::function; - using PreSolveFunc = std::function; + + public: + using StringVec = std::vector; + using ExternalVec = std::vector>; + using PostGroundFunc = std::function; + using PreSolveFunc = std::function; enum class ConfigUpdate { KEEP, REPLACE }; - ClingoControl(Scripts &scripts, bool clingoMode, Clasp::ClaspFacade *clasp, Clasp::Cli::ClaspCliConfig &claspConfig, PostGroundFunc pgf, PreSolveFunc psf, Logger::Printer printer, unsigned messageLimit); + ClingoControl(Scripts &scripts, bool clingoMode, Clasp::ClaspFacade *clasp, Clasp::Cli::ClaspCliConfig &claspConfig, + PostGroundFunc pgf, PreSolveFunc psf, Logger::Printer printer, unsigned messageLimit); ~ClingoControl() noexcept override; void prepare(Assumptions ass); void parse(); - void parse(const StringVec& files, const ClingoOptions& opts, Clasp::Asp::LogicProgram* out, bool addStdIn = true); - void main(IClingoApp &app, StringVec const &files, const ClingoOptions& opts, Clasp::Asp::LogicProgram* out); + void parse(const StringVec &files, const ClingoOptions &opts, Clasp::Asp::LogicProgram *out, bool addStdIn = true); + void main(IClingoApp &app, StringVec const &files, const ClingoOptions &opts, Clasp::Asp::LogicProgram *out); bool onModel(Clasp::Model const &m); bool onUnsat(Potassco::Span optimization); void onFinish(Clasp::ClaspFacade::Result ret); bool update(); - Clasp::Asp::LogicProgram* claspProgram() const; + Clasp::Asp::LogicProgram *claspProgram() const; - virtual void postGround(Clasp::ProgramBuilder& prg) { + virtual void postGround(Clasp::ProgramBuilder &prg) { if (pgf_ && !pgf_(prg)) { fflush(stderr); fflush(stdout); std::_Exit(0); } } - virtual void prePrepare(Clasp::ClaspFacade& ) { } - virtual void preSolve(Clasp::ClaspFacade& clasp) { if (psf_) { psf_(clasp);} } - virtual void postSolve(Clasp::ClaspFacade& ) { } + virtual void prePrepare(Clasp::ClaspFacade &) {} + virtual void preSolve(Clasp::ClaspFacade &clasp) { + if (psf_) { + psf_(clasp); + } + } + virtual void postSolve(Clasp::ClaspFacade &) {} // {{{2 SymbolicAtoms interface @@ -240,8 +265,9 @@ public: bool hasSubKey(unsigned key, char const *name) const override; unsigned getSubKey(unsigned key, char const *name) const override; unsigned getArrKey(unsigned key, unsigned idx) const override; - void getKeyInfo(unsigned key, int* nSubkeys = 0, int* arrLen = 0, const char** help = 0, int* nValues = 0) const override; - const char* getSubKeyName(unsigned key, unsigned idx) const override; + void getKeyInfo(unsigned key, int *nSubkeys = 0, int *arrLen = 0, const char **help = 0, + int *nValues = 0) const override; + const char *getSubKeyName(unsigned key, unsigned idx) const override; bool getKeyValue(unsigned key, std::string &value) const override; void setKeyValue(unsigned key, const char *val) override; unsigned getRootKey() const override; @@ -280,18 +306,16 @@ public: void interrupt() override; void *claspFacade() override; bool beginAddBackend() override; - Gringo::Output::TheoryData &theoryData() override { - return out_->data.theory(); - } + Gringo::Output::TheoryData &theoryData() override { return out_->data.theory(); } Id_t addAtom(Symbol sym) override; void addFact(Potassco::Atom_t uid) override; Backend *getBackend() override { - if (!backend_) { throw std::runtime_error("backend not available"); } + if (!backend_) { + throw std::runtime_error("backend not available"); + } return backend_; }; - Backend &getASPIFBackend() override { - return *aspif_bck_; - }; + Backend &getASPIFBackend() override { return *aspif_bck_; }; void endAddBackend() override; Potassco::Atom_t addProgramAtom() override; Logger &logger() override { return logger_; } @@ -303,57 +327,58 @@ public: parsed_ = true; } void registerObserver(UBackend obs, bool replace) override { - if (replace) { clingoMode_ = false; } + if (replace) { + clingoMode_ = false; + } out_->registerObserver(std::move(obs), replace); } // }}}2 Lit decide(Id_t solverId, Potassco::AbstractAssignment const &assignment, Lit fallback) override; - std::unique_ptr out_; - Scripts &scripts_; - Input::Program prg_; - Defines defs_; - std::unique_ptr aspif_bck_; - std::unique_ptr pb_; - std::unique_ptr parser_; - USolveEventHandler eventHandler_; - Clasp::ClaspFacade *clasp_ = nullptr; - Clasp::Cli::ClaspCliConfig &claspConfig_; - PostGroundFunc pgf_; - PreSolveFunc psf_; - std::unique_ptr data_; - std::vector props_; - std::vector heus_; - std::vector> propagators_; - std::vector added_atoms_; - std::unordered_set added_facts_; - ClingoPropagatorLock propLock_; - Logger logger_; - TheoryOutput theory_; - Backend *backend_ = nullptr; - std::unique_ptr backend_prg_; - UserStatistics step_stats_; - UserStatistics accu_stats_; - bool enableEnumAssupmption_ = true; - bool enableCleanup_ = true; - bool clingoMode_; - bool verbose_ = false; - bool parsed_ = false; - bool configUpdate_ = false; - bool grounded_ = false; - bool initialized_ = false; - bool incmode_ = false; - bool canClean_ = false; - bool preserveFacts_ = false; + std::unique_ptr out_; + Scripts &scripts_; + Input::Program prg_; + Defines defs_; + std::unique_ptr aspif_bck_; + std::unique_ptr pb_; + std::unique_ptr parser_; + USolveEventHandler eventHandler_; + Clasp::ClaspFacade *clasp_ = nullptr; + Clasp::Cli::ClaspCliConfig &claspConfig_; + PostGroundFunc pgf_; + PreSolveFunc psf_; + std::unique_ptr data_; + std::vector props_; + std::vector heus_; + std::vector> propagators_; + std::vector added_atoms_; + std::unordered_set added_facts_; + ClingoPropagatorLock propLock_; + Logger logger_; + TheoryOutput theory_; + Backend *backend_ = nullptr; + std::unique_ptr backend_prg_; + UserStatistics step_stats_; + UserStatistics accu_stats_; + bool enableEnumAssupmption_ = true; + bool enableCleanup_ = true; + bool clingoMode_; + bool verbose_ = false; + bool parsed_ = false; + bool configUpdate_ = false; + bool grounded_ = false; + bool initialized_ = false; + bool incmode_ = false; + bool canClean_ = false; + bool preserveFacts_ = false; }; // {{{1 declaration of ClingoModel class ClingoModel : public Model { -public: - ClingoModel(ClingoControl &ctl, Clasp::Model const *model = nullptr) - : ctl_(ctl), model_(model) { } + public: + ClingoModel(ClingoControl &ctl, Clasp::Model const *model = nullptr) : ctl_(ctl), model_(model) {} void reset(Clasp::Model const &m) { model_ = &m; } bool contains(Symbol atom) const override { auto atm = out().find(atom); @@ -383,32 +408,28 @@ public: auto lit = lp().getLiteral(x); if (lit != Clasp::lit_true()) { claspLits.push_back(lit); + } else { + return; } - else { return; } } claspLits.push_back(~ctx().stepLiteral()); std::sort(claspLits.begin(), claspLits.end()); claspLits.erase(std::unique(claspLits.begin(), claspLits.end()), claspLits.end()); - auto it = std::adjacent_find(claspLits.begin(), claspLits.end(), [](Clasp::Literal const &a, Clasp::Literal const &b) { - return a.var() == b.var(); - }); + auto it = + std::adjacent_find(claspLits.begin(), claspLits.end(), + [](Clasp::Literal const &a, Clasp::Literal const &b) { return a.var() == b.var(); }); if (it == claspLits.end()) { model_->ctx->commitClause(claspLits); } } - Gringo::SymbolicAtoms const &getDomain() const override { - return ctl_.getDomain(); - } - bool isTrue(Potassco::Lit_t lit) const override { - return model_->isTrue(lp().getLiteral(lit)); - } + Gringo::SymbolicAtoms const &getDomain() const override { return ctl_.getDomain(); } + bool isTrue(Potassco::Lit_t lit) const override { return model_->isTrue(lp().getLiteral(lit)); } ConsequenceType isConsequence(Potassco::Lit_t literal) const override { auto lit = lp().getLiteral(literal); auto res = ConsequenceType::False; if (model_->isDef(lit)) { res = ConsequenceType::True; - } - else if (model_->isEst(lit)) { + } else if (model_->isEst(lit)) { res = ConsequenceType::Unknown; } if (res != ConsequenceType::False && !isProjected(literal)) { @@ -417,8 +438,12 @@ public: return res; } ModelType type() const override { - if (model_->type & Clasp::Model::Brave) { return ModelType::BraveConsequences; } - if (model_->type & Clasp::Model::Cautious) { return ModelType::CautiousConsequences; } + if (model_->type & Clasp::Model::Brave) { + return ModelType::BraveConsequences; + } + if (model_->type & Clasp::Model::Cautious) { + return ModelType::CautiousConsequences; + } return ModelType::StableModel; } void add(Potassco::Span symbols) override { ctl_.theory_.add(symbols); } @@ -426,8 +451,11 @@ public: Potassco::Id_t threadId() const override { return model_->sId; } bool optimality_proven() const override { return model_->opt; } ClingoControl &context() { return ctl_; } -private: - Clasp::Asp::LogicProgram const &lp() const { return *static_cast(ctl_.clasp_->program()); }; + + private: + Clasp::Asp::LogicProgram const &lp() const { + return *static_cast(ctl_.clasp_->program()); + }; Output::OutputBase const &out() const { return *ctl_.out_; }; Clasp::SharedContext const &ctx() const { return ctl_.clasp_->ctx; }; bool isProjected(Potassco::Lit_t literal) const { @@ -436,51 +464,54 @@ private: } return lp().isShown(literal); } - ClingoControl &ctl_; - Clasp::Model const *model_; - mutable SymVec atms_; + ClingoControl &ctl_; + Clasp::Model const *model_; + mutable SymVec atms_; }; // {{{1 declaration of ClingoSolveFuture SolveResult convert(Clasp::ClaspFacade::Result res); class ClingoSolveFuture : public Gringo::SolveFuture { -public: + public: ClingoSolveFuture(ClingoControl &ctl, Clasp::SolveMode_t mode); - SolveResult get() override; + SolveResult get() override; Model const *model() override; Potassco::LitSpan unsatCore() override; Model const *lastModel() override; bool wait(double timeout) override; void resume() override; void cancel() override; -private: - Potassco::LitVec core_; - ClingoModel model_; + + private: + Potassco::LitVec core_; + ClingoModel model_; Clasp::ClaspFacade::SolveHandle handle_; }; // {{{1 declaration of ClingoLib class ClingoLib : public Clasp::EventHandler, public ClingoControl { -public: - ClingoLib(Scripts &scripts, int argc, char const * const *argv, Logger::Printer printer, unsigned messageLimit); + public: + ClingoLib(Scripts &scripts, int argc, char const *const *argv, Logger::Printer printer, unsigned messageLimit); ~ClingoLib() override; -protected: - void initOptions(Potassco::ProgramOptions::OptionContext& root); - static bool parsePositional(const std::string& s, std::string& out); + + protected: + void initOptions(Potassco::ProgramOptions::OptionContext &root); + static bool parsePositional(const std::string &s, std::string &out); // ------------------------------------------------------------------------------------------- // Event handler - void onEvent(const Clasp::Event& ev) override; - bool onModel(const Clasp::Solver& s, const Clasp::Model& m) override; - bool onUnsat(const Clasp::Solver&, const Clasp::Model&) override; -private: - ClingoLib(const ClingoLib&); - ClingoLib& operator=(const ClingoLib&); - ClingoOptions grOpts_; - Clasp::Cli::ClaspCliConfig claspConfig_; - Clasp::ClaspFacade clasp_; + void onEvent(const Clasp::Event &ev) override; + bool onModel(const Clasp::Solver &s, const Clasp::Model &m) override; + bool onUnsat(const Clasp::Solver &, const Clasp::Model &) override; + + private: + ClingoLib(const ClingoLib &); + ClingoLib &operator=(const ClingoLib &); + ClingoOptions grOpts_; + Clasp::Cli::ClaspCliConfig claspConfig_; + Clasp::ClaspFacade clasp_; }; // }}}1 diff --git a/libclingo/clingo/control.hh b/libclingo/clingo/control.hh index 2c465bcb7..0e33a2f27 100644 --- a/libclingo/clingo/control.hh +++ b/libclingo/clingo/control.hh @@ -25,14 +25,14 @@ #ifndef CLINGO_CONTROL_HH #define CLINGO_CONTROL_HH -#include -#include -#include +#include #include +#include #include #include +#include +#include #include -#include namespace Gringo { @@ -67,17 +67,17 @@ namespace Gringo { // {{{1 declaration of SolveResult class SolveResult { -public: - enum Satisfiabily : unsigned { Unknown=0, Satisfiable=1, Unsatisfiable=2 }; + public: + enum Satisfiabily : unsigned { Unknown = 0, Satisfiable = 1, Unsatisfiable = 2 }; SolveResult(Satisfiabily status, bool exhausted, bool interrupted) - : repr_(static_cast(status) | (exhausted << 2) | (interrupted << 3)) { } - SolveResult(unsigned repr) - : repr_(repr) { } + : repr_(static_cast(status) | (exhausted << 2) | (interrupted << 3)) {} + SolveResult(unsigned repr) : repr_(repr) {} Satisfiabily satisfiable() const { return static_cast(repr_ & 3); } bool exhausted() const { return (repr_ >> 2) & 1; } bool interrupted() const { return (repr_ >> 3) & 1; } operator unsigned() const { return repr_; } -private: + + private: unsigned repr_; }; @@ -115,7 +115,7 @@ struct clingo_model { virtual ConsequenceType isConsequence(Potassco::Lit_t literal) const = 0; virtual Gringo::SymbolicAtoms const &getDomain() const = 0; virtual void add(Potassco::Span symbols) = 0; - virtual ~clingo_model() { } + virtual ~clingo_model() {} }; namespace Gringo { @@ -131,7 +131,7 @@ struct SolveEventHandler { using USolveEventHandler = std::unique_ptr; inline bool SolveEventHandler::on_model(Model &) { return true; } inline bool SolveEventHandler::on_unsat(Potassco::Span optimization) { return true; } -inline void SolveEventHandler::on_finish(SolveResult, Potassco::AbstractStatistics *, Potassco::AbstractStatistics *) { } +inline void SolveEventHandler::on_finish(SolveResult, Potassco::AbstractStatistics *, Potassco::AbstractStatistics *) {} struct SolveFuture { virtual SolveResult get() = 0; @@ -141,31 +141,39 @@ struct SolveFuture { virtual bool wait(double timeout) = 0; virtual void cancel() = 0; virtual void resume() = 0; - virtual ~SolveFuture() { } + virtual ~SolveFuture() {} }; using USolveFuture = std::unique_ptr; struct DefaultSolveFuture : SolveFuture { - DefaultSolveFuture(USolveEventHandler cb) : cb_(std::move(cb)) { } - SolveResult get() override { resume(); return {SolveResult::Unknown, false, false}; } - Model const *model() override { resume(); return nullptr; } - Potassco::LitSpan unsatCore() override { - throw std::runtime_error("no core available"); + DefaultSolveFuture(USolveEventHandler cb) : cb_(std::move(cb)) {} + SolveResult get() override { + resume(); + return {SolveResult::Unknown, false, false}; } - Model const *lastModel() override { - throw std::runtime_error("no model available"); + Model const *model() override { + resume(); + return nullptr; + } + Potassco::LitSpan unsatCore() override { throw std::runtime_error("no core available"); } + Model const *lastModel() override { throw std::runtime_error("no model available"); } + bool wait(double) override { + resume(); + return true; } - bool wait(double) override { resume(); return true; } void cancel() override { resume(); } void resume() override { if (!done_) { done_ = true; - if (cb_) { cb_->on_finish({SolveResult::Unknown, false, false}, nullptr, nullptr); } + if (cb_) { + cb_->on_finish({SolveResult::Unknown, false, false}, nullptr, nullptr); + } } } ~DefaultSolveFuture() override { resume(); } -private: + + private: USolveEventHandler cb_; bool done_ = false; }; @@ -176,12 +184,13 @@ struct ConfigProxy { virtual bool hasSubKey(unsigned key, char const *name) const = 0; virtual unsigned getSubKey(unsigned key, char const *name) const = 0; virtual unsigned getArrKey(unsigned key, unsigned idx) const = 0; - virtual void getKeyInfo(unsigned key, int* nSubkeys = 0, int* arrLen = 0, const char** help = 0, int* nValues = 0) const = 0; - virtual const char* getSubKeyName(unsigned key, unsigned idx) const = 0; + virtual void getKeyInfo(unsigned key, int *nSubkeys = 0, int *arrLen = 0, const char **help = 0, + int *nValues = 0) const = 0; + virtual const char *getSubKeyName(unsigned key, unsigned idx) const = 0; virtual bool getKeyValue(unsigned key, std::string &value) const = 0; virtual void setKeyValue(unsigned key, const char *val) = 0; virtual unsigned getRootKey() const = 0; - virtual ~ConfigProxy() { } + virtual ~ConfigProxy() {} }; // {{{1 declaration of Propagator @@ -194,7 +203,8 @@ using PropagateInit = clingo_propagate_init; struct clingo_propagate_init { virtual Potassco::Lit_t addLiteral(bool freeze) = 0; virtual bool addClause(Potassco::LitSpan lits) = 0; - virtual bool addWeightConstraint(Potassco::Lit_t lit, Potassco::WeightLitSpan lits, Potassco::Weight_t bound, int type, bool eq) = 0; + virtual bool addWeightConstraint(Potassco::Lit_t lit, Potassco::WeightLitSpan lits, Potassco::Weight_t bound, + int type, bool eq) = 0; virtual void addMinimize(Potassco::Lit_t literal, Potassco::Weight_t weight, Potassco::Weight_t priority) = 0; virtual bool propagate() = 0; virtual Gringo::Output::DomainData const &theory() const = 0; @@ -234,14 +244,15 @@ using Control = clingo_control; struct clingo_control { using Assumptions = Potassco::LitSpan; using GroundVec = std::vector>; - using NewControlFunc = Gringo::Control* (*)(int, char const **); + using NewControlFunc = Gringo::Control *(*)(int, char const **); using FreeControlFunc = void (*)(Gringo::Control *); virtual Gringo::ConfigProxy &getConf() = 0; virtual Gringo::SymbolicAtoms const &getDomain() const = 0; virtual void ground(GroundVec const &vec, Gringo::Context *context) = 0; - virtual Gringo::USolveFuture solve(Assumptions assumptions, clingo_solve_mode_bitset_t mode, Gringo::USolveEventHandler cb = nullptr) = 0; + virtual Gringo::USolveFuture solve(Assumptions assumptions, clingo_solve_mode_bitset_t mode, + Gringo::USolveEventHandler cb = nullptr) = 0; virtual void interrupt() = 0; virtual void *claspFacade() = 0; virtual void add(std::string const &name, Gringo::StringVec const ¶ms, std::string const &part) = 0; diff --git a/libclingo/clingo/gringo_options.hh b/libclingo/clingo/gringo_options.hh index 24a20fc99..cd8f26968 100644 --- a/libclingo/clingo/gringo_options.hh +++ b/libclingo/clingo/gringo_options.hh @@ -32,24 +32,24 @@ namespace Gringo { struct GringoOptions { - enum class AppType {Gringo, Clingo, Lib}; + enum class AppType { Gringo, Clingo, Lib }; using SigVec = std::vector; std::vector defines; - Output::OutputOptions outputOptions; - Output::OutputFormat outputFormat = Output::OutputFormat::INTERMEDIATE; - bool verbose = false; - bool wNoOperationUndefined = false; - bool wNoAtomUndef = false; - bool wNoFileIncluded = false; - bool wNoGlobalVariable = false; - bool wNoOther = false; - bool rewriteMinimize = false; - bool keepFacts = false; - bool singleShot = false; - SigVec sigvec; + Output::OutputOptions outputOptions; + Output::OutputFormat outputFormat = Output::OutputFormat::INTERMEDIATE; + bool verbose = false; + bool wNoOperationUndefined = false; + bool wNoAtomUndef = false; + bool wNoFileIncluded = false; + bool wNoGlobalVariable = false; + bool wNoOther = false; + bool rewriteMinimize = false; + bool keepFacts = false; + bool singleShot = false; + SigVec sigvec; }; -void registerOptions(Potassco::ProgramOptions::OptionGroup& group, GringoOptions& opts, GringoOptions::AppType type); +void registerOptions(Potassco::ProgramOptions::OptionGroup &group, GringoOptions &opts, GringoOptions::AppType type); } // namespace Gringo diff --git a/libclingo/clingo/scripts.hh b/libclingo/clingo/scripts.hh index 5642a3a7b..0e253b41c 100644 --- a/libclingo/clingo/scripts.hh +++ b/libclingo/clingo/scripts.hh @@ -31,7 +31,7 @@ namespace Gringo { class Script : public Context { -public: + public: virtual void main(Control &ctl) = 0; virtual char const *version() = 0; ~Script() override = default; @@ -40,7 +40,7 @@ using UScript = std::shared_ptr