Clingo
Loading...
Searching...
No Matches
context.hh
1#pragma once
2
3#include <clingo/control/term.hh>
4
5#include <clingo/input/literal.hh>
6#include <clingo/input/program.hh>
7#include <clingo/input/term.hh>
8
9#include <clingo/ground/base.hh>
10#include <clingo/ground/program.hh>
11#include <clingo/ground/script.hh>
12
13#include <clingo/input/rewrite/analyze.hh>
14
15#include <clingo/util/small_vector.hh>
16#include <clingo/util/type_traits.hh>
17
18#include <ostream>
19
20namespace CppClingo::Control {
21
24
29
32
35
38
41 public:
48 void print(std::ostream &out, Ground::ProfileType type, Ground::ProfileDetail detail) const;
52 void begin_step();
56 void end_step();
58 void accept(Ground::ProfileNode::Visitor const &visit) const {
59 for (auto const &[_, node] : nodes_) {
60 node->accept(visit, 0);
61 }
62 }
63
64 private:
67 std::hash<Input::Stm const *>, std::equal_to<void>>;
68
70 NodeMap nodes_;
71};
72
76 public:
78 BuildContext(std::pmr::monotonic_buffer_resource &mbr, Logger &log, SymbolStore &store,
79 TheorySigVec const &theory_directives, Ground::Bases &base, Input::Component const &comp,
82 : mbr_{&mbr}, log_{&log}, store_{&store}, theory_directives_{&theory_directives}, base_{&base}, comp_{&comp},
83 def_map_{&def_map}, gcomp_{&gcomp}, var_map_{&var_map}, body_{&body}, states_{&states}, context_{context},
84 profile_{&profile} {}
85
87 [[nodiscard]] auto index(Input::LitSymbolic const &lit) const -> size_t {
88 auto it = comp_->incomplete.find(&lit.term());
89 if (it != comp_->incomplete.end()) {
90 return static_cast<size_t>(it - comp_->incomplete.begin());
91 }
93 }
95 [[nodiscard]] auto single_pass(Input::Lit const &lit) const -> bool {
96 if (intersects(comp_->type, Input::ComponentType::single_pass)) {
97 return true;
98 }
99 if (auto const *slit = std::get_if<Input::LitSymbolic>(&lit); slit != nullptr) {
100 return slit->sign() != Sign::none || index(*slit) == Ground::stratified_index;
101 }
102 return true;
103 }
104
106 [[nodiscard]] auto single_pass_body() const -> bool {
107 return intersects(comp_->type, Input::ComponentType::single_pass) ||
108 std::ranges::all_of(*body_, [](auto const &lit) { return lit->single_pass(); });
109 }
110
112 [[nodiscard]] auto next_index() -> size_t { return comp_->incomplete.size() + index_++; }
113
115 [[nodiscard]] auto logger() const -> Logger & { return *log_; }
116
118 [[nodiscard]] auto store() const -> SymbolStore & { return *store_; }
119
121 [[nodiscard]] auto context() const -> Ground::ScriptCallback * { return context_; }
122
124 [[nodiscard]] auto profile() const -> ProfileProgram & { return *profile_; }
125
128 -> std::pair<Ground::UTerm, Ground::ProjectState *> {
129 return base_->add_project(*store_, term, base);
130 }
131
133 [[nodiscard]] auto type() const -> Input::ComponentType { return comp_->type; };
134
136 auto add_base(std::tuple<String, size_t, bool> sig) -> Ground::AtomBase & { return base_->add_base(sig); }
137
139 [[nodiscard]] auto mbr() const -> std::pmr::monotonic_buffer_resource & { return *mbr_; }
140
142 [[nodiscard]] auto def_map() const -> DefMap & { return *def_map_; }
144 [[nodiscard]] auto var_map() const -> VarMap & { return *var_map_; }
145
147 [[nodiscard]] auto gcomp() const -> Ground::Component & { return *gcomp_; }
149 [[nodiscard]] auto body() const -> Ground::ULitVec & { return *body_; }
150
152 template <class T, class... Args> [[nodiscard]] auto state(Args &&...args) -> T & {
153 states_->emplace_back(std::make_unique<T>(std::forward<Args>(args)...));
154 return static_cast<T &>(*states_->back());
155 }
156
158 auto inc_priority() -> size_t { return priority++; }
159
161 [[nodiscard]] auto simple_lit(Input::Lit const &lit) -> Ground::AtomSimple {
162 auto res = Ground::AtomSimple{};
163 with_simple_lit(lit, [&res]([[maybe_unused]] auto sig, auto term, auto &base, auto provides) {
164 res.emplace(std::make_tuple(std::move(term), std::ref(base), std::move(provides)));
165 });
166 return res;
167 }
168
170 [[nodiscard]] auto simple_lit(Input::Term const &term) -> Ground::AtomSimple::value_type {
171 auto res = Ground::AtomSimple{};
172 with_simple_lit(term, [&res]([[maybe_unused]] auto sig, auto term, auto &base, auto provides) {
173 res.emplace(std::make_tuple(std::move(term), std::ref(base), std::move(provides)));
174 });
175 assert(res);
176 return *std::move(res);
177 }
178
180 template <class F> void with_simple_lit(Input::Term const &term, F &&fun) {
181 auto provides = std::vector<size_t>{};
182 auto sig = signature(term);
183 assert(sig);
184 auto &base = add_base(*sig);
185 if (auto it = def_map_->find(&term); it != def_map_->end()) {
186 provides = it->second;
187 }
188 std::invoke(std::forward<F>(fun), *sig, build_term(*var_map_, term), base, std::move(provides));
189 }
190
192 template <class F> void with_simple_lit(Input::Lit const &lit, F &&fun, bool expect_truth = false) {
193 std::visit(
194 [&]<class T>(T const &lit) {
195 if constexpr (Util::matches<T, Input::LitSymbolic>) {
196 assert(lit.sign() == Sign::none);
197 with_simple_lit(lit.term(), std::forward<F>(fun));
198 return;
199 } else if constexpr (Util::matches<T, Input::LitBool>) {
200 if (lit.value() == expect_truth) {
201 return;
202 }
203 }
204 throw std::runtime_error("unexpected literal in rule head");
205 },
206 lit);
207 }
208
210 [[nodiscard]] auto is_theory_directive(TheorySig sig) const -> bool {
211 return std::ranges::binary_search(*theory_directives_, sig);
212 }
213
214 private:
215 std::pmr::monotonic_buffer_resource *mbr_;
216 Logger *log_;
217 SymbolStore *store_;
218 TheorySigVec const *theory_directives_;
219 Ground::Bases *base_;
220 Input::Component const *comp_;
221 DefMap *def_map_;
222 Ground::Component *gcomp_;
224 Ground::ULitVec *body_;
225 Ground::UStateVec *states_;
226 Ground::ScriptCallback *context_;
227 ProfileProgram *profile_;
228 size_t priority = 0;
229 size_t index_ = 0;
230};
231
233
234} // namespace CppClingo::Control
Context object holding necessary data for translating from input to ground representation.
Definition context.hh:75
auto inc_priority() -> size_t
Increment the priority and return its previous value.
Definition context.hh:158
auto simple_lit(Input::Lit const &lit) -> Ground::AtomSimple
Translate the given simple input literal into a simple ground atom.
Definition context.hh:161
auto state(Args &&...args) -> T &
Add a new state object for a body aggregate literal.
Definition context.hh:152
auto next_index() -> size_t
Return a fresh atom index.
Definition context.hh:112
auto def_map() const -> DefMap &
Get the definition map.
Definition context.hh:142
auto single_pass(Input::Lit const &lit) const -> bool
Check if the given input literal is single pass.
Definition context.hh:95
auto store() const -> SymbolStore &
Get the symbol store.
Definition context.hh:118
auto var_map() const -> VarMap &
Get the variable map.
Definition context.hh:144
auto index(Input::LitSymbolic const &lit) const -> size_t
Get the index of the given symbolic literal.
Definition context.hh:87
auto context() const -> Ground::ScriptCallback *
Get the associated context to call scripts.
Definition context.hh:121
auto add_base(std::tuple< String, size_t, bool > sig) -> Ground::AtomBase &
Add an atom base for the given signature.
Definition context.hh:136
auto is_theory_directive(TheorySig sig) const -> bool
Check whether the given signature corresponds to a directive.
Definition context.hh:210
auto add_project(Ground::UTerm const &term, Ground::AtomBase &base) -> std::pair< Ground::UTerm, Ground::ProjectState * >
Add a base for a projection.
Definition context.hh:127
void with_simple_lit(Input::Term const &term, F &&fun)
Translate the given input term (for an atom) with a callback.
Definition context.hh:180
auto gcomp() const -> Ground::Component &
Get the current component.
Definition context.hh:147
auto logger() const -> Logger &
Get the logger.
Definition context.hh:115
auto single_pass_body() const -> bool
Check if the (current) body can be grounded in a single pass.
Definition context.hh:106
auto mbr() const -> std::pmr::monotonic_buffer_resource &
Get the monotonic allocator for the component.
Definition context.hh:139
void with_simple_lit(Input::Lit const &lit, F &&fun, bool expect_truth=false)
Translate the given simple input literal with a callback.
Definition context.hh:192
auto type() const -> Input::ComponentType
Get the component type.
Definition context.hh:133
BuildContext(std::pmr::monotonic_buffer_resource &mbr, Logger &log, SymbolStore &store, TheorySigVec const &theory_directives, Ground::Bases &base, Input::Component const &comp, DefMap &def_map, Ground::Component &gcomp, VarMap &var_map, Ground::ULitVec &body, Ground::UStateVec &states, Ground::ScriptCallback *context, ProfileProgram &profile)
Construct the build context.
Definition context.hh:78
auto profile() const -> ProfileProgram &
Get the symbol store.
Definition context.hh:124
auto body() const -> Ground::ULitVec &
Get the current statement body.
Definition context.hh:149
auto simple_lit(Input::Term const &term) -> Ground::AtomSimple::value_type
Translate the given input term (for an atom) into a simple ground atom.
Definition context.hh:170
Class storing profiling data for a program.
Definition context.hh:40
void begin_step()
Begin a new grounding step.
void end_step()
End the current grounding step.
void print(std::ostream &out, Ground::ProfileType type, Ground::ProfileDetail detail) const
Print the profiling data to the given output stream.
auto add(Input::Stm const &stm) -> Ground::ProfileNodeInternal &
Add a profiling node for a statement.
void accept(Ground::ProfileNode::Visitor const &visit) const
Visit all profiling nodes with the given visitor function.
Definition context.hh:58
An atom base used to store derivable atoms and associated state.
Definition base.hh:212
The base for all atoms and terms.
Definition base.hh:407
auto add_base(std::tuple< String, size_t, bool > sig) -> Ground::AtomBase &
Add an atom base.
auto add_project(SymbolStore &store, Ground::UTerm const &term, Ground::AtomBase &base) -> std::pair< Ground::UTerm, ProjectState * >
Add a base for a projected atom.
Captures statements depending cyclically on each other.
Definition program.hh:13
Profile node that can hold children.
Definition profile.hh:155
std::function< void(std::variant< std::pair< std::string_view, bool >, std::pair< ProfileStats const *, ProfileType > >, size_t)> Visitor
The type of visitor function to use for visiting profile nodes.
Definition profile.hh:106
Interface to call functions during parsing/grounding.
Definition script.hh:28
Literal representing a symbolic literal.
Definition literal.hh:104
Simple logger to report message to stderr or via a callback.
Definition logger.hh:63
A store for symbols.
Definition symbol.hh:454
auto build_term(Util::unordered_map< String, size_t > const &var_map, Input::Term const &term, bool &has_projection) -> Ground::UTerm
Translates input theory terms to their ground representation.
Util::unordered_map< String, size_t > VarMap
A map from variable names (input) to their indices (ground).
Definition context.hh:34
CppClingo::Ground::BaseMap BaseMap
A map from signatures to atom bases.
Definition context.hh:31
Util::unordered_map< Input::Term const *, std::vector< size_t > > DefMap
A map from terms to the indices defining them.
Definition context.hh:37
CppClingo::Ground::ProjectMap ProjectMap
A map from a terms with projections associated state used during grounding.
Definition context.hh:28
std::tuple< String, size_t > TheorySig
A signature of a theory atom.
Definition core.hh:182
std::vector< TheorySig > TheorySigVec
A vector of theory atom signatures.
Definition core.hh:184
@ none
No sign.
Util::ordered_map< std::tuple< String, size_t, bool >, UAtomBase > BaseMap
A map from signatures to atom bases.
Definition base.hh:404
Util::ordered_map< Ground::UTerm, UProjectState > ProjectMap
A map from a terms with projections associated state used during grounding.
Definition base.hh:401
std::vector< UState > UStateVec
A vector of states.
Definition base.hh:448
ProfileType
Whether to process per step or accumulated profiling data.
Definition profile.hh:19
ProfileDetail
Whether to print profile data into a compact or detailed form.
Definition profile.hh:25
std::optional< std::tuple< Ground::UTerm, AtomBase &, std::vector< size_t > > > AtomSimple
Represents a simple head literal which is either represented by a symbol term or #false captured by s...
Definition literal.hh:231
std::vector< ULit > ULitVec
A vector of literals.
Definition literal.hh:31
constexpr auto stratified_index
Marker for stratified literals.
Definition literal.hh:189
std::unique_ptr< Term > UTerm
A unique pointer holding a term.
Definition term.hh:34
std::variant< LitBool, LitComparison, LitSymbolic > Lit
Variant holding the different literal types.
Definition literal.hh:129
@ single_pass
The component can be grounded in one pass.
std::variant< StmRule, StmTheory, StmOptimize, StmWeakConstraint, StmShow, StmShowNothing, StmShowSig, StmProject, StmProjectSig, StmDefined, StmExternal, StmEdge, StmHeuristic, StmScript, StmInclude, StmProgram, StmConst, StmParts, StmComment > Stm
Variant of available statements.
Definition statement.hh:828
std::variant< TermVariable, TermSymbol, TermTuple, TermFunction, TermAbs, TermUnary, TermBinary, TermFormatString > Term
Variant holding the different term types.
Definition term.hh:48
tsl::ordered_map< Key, T, Hash, KeyEqual, Allocator, ValueTypeContainer, IndexType > ordered_map
Alias for ordered maps.
Definition ordered_map.hh:16
tsl::hopscotch_map< Key, T, Hash, KeyEqual, Allocator, NeighborhoodSize, StoreHash, GrowthPolicy > unordered_map
Alias for unordered maps.
Definition unordered_map.hh:17
A refined component.
Definition program.hh:116
Util::ordered_map< Term const *, Util::ordered_set< Term const * > > incomplete
This vector captures literals that are not yet complete.
Definition program.hh:125
ComponentType type
The type of the component.
Definition program.hh:127