Interface for example evaluation cache utilities (#3726)
[cvc5.git] / src / theory / quantifiers / sygus / synth_conjecture.h
1 /********************* */
2 /*! \file synth_conjecture.h
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Andrew Reynolds, Haniel Barbosa, Tim King
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2019 by the authors listed in the file AUTHORS
8 ** in the top-level source directory) and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing information.\endverbatim
11 **
12 ** \brief Class that encapsulates techniques for a single (SyGuS) synthesis
13 ** conjecture.
14 **/
15
16 #include "cvc4_private.h"
17
18 #ifndef CVC4__THEORY__QUANTIFIERS__SYNTH_CONJECTURE_H
19 #define CVC4__THEORY__QUANTIFIERS__SYNTH_CONJECTURE_H
20
21 #include <memory>
22
23 #include "theory/decision_manager.h"
24 #include "theory/quantifiers/expr_miner_manager.h"
25 #include "theory/quantifiers/sygus/ce_guided_single_inv.h"
26 #include "theory/quantifiers/sygus/cegis.h"
27 #include "theory/quantifiers/sygus/cegis_core_connective.h"
28 #include "theory/quantifiers/sygus/cegis_unif.h"
29 #include "theory/quantifiers/sygus/example_eval_cache.h"
30 #include "theory/quantifiers/sygus/example_infer.h"
31 #include "theory/quantifiers/sygus/sygus_grammar_cons.h"
32 #include "theory/quantifiers/sygus/sygus_pbe.h"
33 #include "theory/quantifiers/sygus/sygus_process_conj.h"
34 #include "theory/quantifiers/sygus/sygus_repair_const.h"
35 #include "theory/quantifiers/sygus/sygus_stats.h"
36
37 namespace CVC4 {
38 namespace theory {
39 namespace quantifiers {
40
41 class SynthEngine;
42 class SygusStatistics;
43
44 /**
45 * A base class for generating values for actively-generated enumerators.
46 * At a high level, the job of this class is to accept a stream of "abstract
47 * values" a1, ..., an, ..., and generate a (possibly larger) stream of
48 * "concrete values" c11, ..., c1{m_1}, ..., cn1, ... cn{m_n}, ....
49 */
50 class EnumValGenerator
51 {
52 public:
53 virtual ~EnumValGenerator() {}
54 /** initialize this class with enumerator e */
55 virtual void initialize(Node e) = 0;
56 /** Inform this generator that abstract value v was enumerated. */
57 virtual void addValue(Node v) = 0;
58 /**
59 * Increment this value generator. If this returns false, then we are out of
60 * values. If this returns true, getCurrent(), if non-null, returns the
61 * current term.
62 */
63 virtual bool increment() = 0;
64 /** Get the current concrete value generated by this class. */
65 virtual Node getCurrent() = 0;
66 };
67
68 /** a synthesis conjecture
69 * This class implements approaches for a synthesis conecjture, given by data
70 * member d_quant.
71 * This includes both approaches for synthesis in Reynolds et al CAV 2015. It
72 * determines which approach and optimizations are applicable to the
73 * conjecture, and has interfaces for implementing them.
74 */
75 class SynthConjecture
76 {
77 public:
78 SynthConjecture(QuantifiersEngine* qe, SynthEngine* p, SygusStatistics& s);
79 ~SynthConjecture();
80 /** presolve */
81 void presolve();
82 /** get original version of conjecture */
83 Node getConjecture() { return d_quant; }
84 /** get deep embedding version of conjecture */
85 Node getEmbeddedConjecture() { return d_embed_quant; }
86 //-------------------------------for counterexample-guided check/refine
87 /** increment the number of times we have successfully done candidate
88 * refinement */
89 void incrementRefineCount() { d_refine_count++; }
90 /** whether the conjecture is waiting for a call to doCheck below */
91 bool needsCheck();
92 /** whether the conjecture is waiting for a call to doRefine below */
93 bool needsRefinement() const;
94 /** do syntax-guided enumerative check
95 *
96 * This is step 2(a) of Figure 3 of Reynolds et al CAV 2015.
97 *
98 * The method returns true if this conjecture is finished trying solutions
99 * for the given call to SynthEngine::check.
100 *
101 * Notice that we make multiple calls to doCheck on one call to
102 * SynthEngine::check. For example, if we are using an actively-generated
103 * enumerator, one enumerated (abstract) term may correspond to multiple
104 * concrete terms t1, ..., tn to check, where we make up to n calls to doCheck
105 * when each of t1, ..., tn fails to satisfy the current refinement lemmas.
106 */
107 bool doCheck(std::vector<Node>& lems);
108 /** do refinement
109 * This is step 2(b) of Figure 3 of Reynolds et al CAV 2015.
110 */
111 void doRefine(std::vector<Node>& lems);
112 //-------------------------------end for counterexample-guided check/refine
113 /**
114 * Prints the synthesis solution to output stream out. This invokes solution
115 * reconstruction if the conjecture is single invocation. Otherwise, it
116 * returns the solution found by sygus enumeration.
117 */
118 void printSynthSolution(std::ostream& out);
119 /** get synth solutions
120 *
121 * This method returns true if this class has a solution available to the
122 * conjecture that it was assigned.
123 *
124 * Let q be the synthesis conjecture assigned to this class.
125 * This method adds entries to sol_map[q] that map functions-to-synthesize to
126 * their builtin solution, which has the same type. For example, for synthesis
127 * conjecture exists f. forall x. f( x )>x, this function will update
128 * sol_map[q] to contain the entry:
129 * f -> (lambda x. x+1)
130 */
131 bool getSynthSolutions(std::map<Node, std::map<Node, Node> >& sol_map);
132 /**
133 * The feasible guard whose semantics are "this conjecture is feasiable".
134 * This is "G" in Figure 3 of Reynolds et al CAV 2015.
135 */
136 Node getGuard() const;
137 /** is ground */
138 bool isGround() { return d_inner_vars.empty(); }
139 /** are we using single invocation techniques */
140 bool isSingleInvocation() const;
141 /** preregister conjecture
142 * This is used as a heuristic for solution reconstruction, so that we
143 * remember expressions in the conjecture before preprocessing, since they
144 * may be helpful during solution reconstruction (Figure 5 of Reynolds et al
145 * CAV 2015)
146 */
147 void preregisterConjecture(Node q);
148 /** assign conjecture q to this class */
149 void assign(Node q);
150 /** has a conjecture been assigned to this class */
151 bool isAssigned() { return !d_embed_quant.isNull(); }
152 /**
153 * Get model value for term n.
154 */
155 Node getModelValue(Node n);
156
157 /** get utility for static preprocessing and analysis of conjectures */
158 SynthConjectureProcess* getProcess() { return d_ceg_proc.get(); }
159 /** get constant repair utility */
160 SygusRepairConst* getRepairConst() { return d_sygus_rconst.get(); }
161 /** get example inference utility */
162 ExampleInfer* getExampleInfer() { return d_exampleInfer.get(); }
163 /** get the example evaluation cache utility for enumerator e */
164 ExampleEvalCache* getExampleEvalCache(Node e);
165 /** get program by examples module */
166 SygusPbe* getPbe() { return d_ceg_pbe.get(); }
167 /** get the symmetry breaking predicate for type */
168 Node getSymmetryBreakingPredicate(
169 Node x, Node e, TypeNode tn, unsigned tindex, unsigned depth);
170 /** print out debug information about this conjecture */
171 void debugPrint(const char* c);
172 /** check side condition
173 *
174 * This returns false if the solution { d_candidates -> cvals } does not
175 * satisfy the side condition of the conjecture maintained by this class,
176 * if it exists, and true otherwise.
177 */
178 bool checkSideCondition(const std::vector<Node>& cvals) const;
179
180 private:
181 /** reference to quantifier engine */
182 QuantifiersEngine* d_qe;
183 /** pointer to the synth engine that owns this */
184 SynthEngine* d_parent;
185 /** reference to the statistics of parent */
186 SygusStatistics& d_stats;
187 /** term database sygus of d_qe */
188 TermDbSygus* d_tds;
189 /** The feasible guard. */
190 Node d_feasible_guard;
191 /**
192 * Do we have a solution in this solve context? This flag is reset to false
193 * on every call to presolve.
194 */
195 bool d_hasSolution;
196 /** the decision strategy for the feasible guard */
197 std::unique_ptr<DecisionStrategy> d_feasible_strategy;
198 /** single invocation utility */
199 std::unique_ptr<CegSingleInv> d_ceg_si;
200 /** utility for static preprocessing and analysis of conjectures */
201 std::unique_ptr<SynthConjectureProcess> d_ceg_proc;
202 /** grammar utility */
203 std::unique_ptr<CegGrammarConstructor> d_ceg_gc;
204 /** repair constant utility */
205 std::unique_ptr<SygusRepairConst> d_sygus_rconst;
206 /** example inference utility */
207 std::unique_ptr<ExampleInfer> d_exampleInfer;
208 /** example evaluation cache utility for each enumerator */
209 std::map<Node, std::unique_ptr<ExampleEvalCache> > d_exampleEvalCache;
210
211 //------------------------modules
212 /** program by examples module */
213 std::unique_ptr<SygusPbe> d_ceg_pbe;
214 /** CEGIS module */
215 std::unique_ptr<Cegis> d_ceg_cegis;
216 /** CEGIS UNIF module */
217 std::unique_ptr<CegisUnif> d_ceg_cegisUnif;
218 /** connective core utility */
219 std::unique_ptr<CegisCoreConnective> d_sygus_ccore;
220 /** the set of active modules (subset of the above list) */
221 std::vector<SygusModule*> d_modules;
222 /** master module
223 *
224 * This is the module (one of those above) that takes sole responsibility
225 * for this conjecture, determined during assign(...).
226 */
227 SygusModule* d_master;
228 //------------------------end modules
229
230 //------------------------enumerators
231 /**
232 * Get model values for terms n, store in vector v. This method returns true
233 * if and only if all values added to v are non-null.
234 *
235 * The argument activeIncomplete indicates whether n contains an active
236 * enumerator that is currently not finished enumerating values, but returned
237 * null on a call to getEnumeratedValue. This value is used for determining
238 * whether we should call getEnumeratedValues again within a call to
239 * SynthConjecture::check.
240 *
241 * It removes terms from n that correspond to "inactive" enumerators, that
242 * is, enumerators whose values have been exhausted.
243 */
244 bool getEnumeratedValues(std::vector<Node>& n,
245 std::vector<Node>& v,
246 bool& activeIncomplete);
247 /**
248 * Get model value for term n. If n has a value that was excluded by
249 * datatypes sygus symmetry breaking, this method returns null. It sets
250 * activeIncomplete to true if there is an actively-generated enumerator whose
251 * current value is null but it has not finished generating values.
252 */
253 Node getEnumeratedValue(Node n, bool& activeIncomplete);
254 /** enumerator generators for each actively-generated enumerator */
255 std::map<Node, std::unique_ptr<EnumValGenerator> > d_evg;
256 /**
257 * Map from enumerators to whether they are currently being
258 * "actively-generated". That is, we are in a state where we have called
259 * d_evg[e].addValue(v) for some v, and d_evg[e].getNext() has not yet
260 * returned null. The range of this map stores the abstract value that
261 * we are currently generating values from.
262 */
263 std::map<Node, Node> d_ev_curr_active_gen;
264 /** the current waiting value of each actively-generated enumerator, if any
265 *
266 * This caches values that are actively generated and that we have not yet
267 * passed to a call to SygusModule::constructCandidates. An example of when
268 * this may occur is when there are two actively-generated enumerators e1 and
269 * e2. Say on some iteration we actively-generate v1 for e1, the value
270 * of e2 was excluded by symmetry breaking, and say the current master sygus
271 * module does not handle partial models. Hence, we abort the current check.
272 * We remember that the value of e1 was v1 by storing it here, so that on
273 * a future check when v2 has a proper value, it is returned.
274 */
275 std::map<Node, Node> d_ev_active_gen_waiting;
276 /** the first value enumerated for each actively-generated enumerator
277 *
278 * This is to implement an optimization that only guards the blocking lemma
279 * for the first value of an actively-generated enumerator.
280 */
281 std::map<Node, Node> d_ev_active_gen_first_val;
282 //------------------------end enumerators
283
284 /** list of constants for quantified formula
285 * The outer Skolems for the negation of d_embed_quant.
286 */
287 std::vector<Node> d_candidates;
288 /** base instantiation
289 * If d_embed_quant is forall d. exists y. P( d, y ), then
290 * this is the formula exists y. P( d_candidates, y ). Notice that
291 * (exists y. F) is shorthand above for ~( forall y. ~F ).
292 */
293 Node d_base_inst;
294 /** list of variables on inner quantification */
295 std::vector<Node> d_inner_vars;
296 /**
297 * The set of skolems for the current "verification" lemma, if one exists.
298 * This may be added to during calls to doCheck(). The model values for these
299 * skolems are analyzed during doRefine().
300 */
301 std::vector<Node> d_ce_sk_vars;
302 /**
303 * If we have already tested the satisfiability of the current verification
304 * lemma, this stores the model values of d_ce_sk_vars in the current
305 * (satisfiable, failed) verification lemma.
306 */
307 std::vector<Node> d_ce_sk_var_mvs;
308 /**
309 * Whether the above vector has been set. We have this flag since the above
310 * vector may be set to empty (e.g. for ground synthesis conjectures).
311 */
312 bool d_set_ce_sk_vars;
313
314 /** the asserted (negated) conjecture */
315 Node d_quant;
316 /**
317 * The side condition for solving the conjecture, after conversion to deep
318 * embedding.
319 */
320 Node d_embedSideCondition;
321 /** (negated) conjecture after simplification */
322 Node d_simp_quant;
323 /** (negated) conjecture after simplification, conversion to deep embedding */
324 Node d_embed_quant;
325 /** candidate information */
326 class CandidateInfo
327 {
328 public:
329 CandidateInfo() {}
330 /** list of terms we have instantiated candidates with */
331 std::vector<Node> d_inst;
332 };
333 std::map<Node, CandidateInfo> d_cinfo;
334 /**
335 * The first index of an instantiation in CandidateInfo::d_inst that we have
336 * not yet tried to repair.
337 */
338 unsigned d_repair_index;
339 /** number of times we have called doRefine */
340 unsigned d_refine_count;
341 /** get candidadate */
342 Node getCandidate(unsigned int i) { return d_candidates[i]; }
343 /** record instantiation (this is used to construct solutions later) */
344 void recordInstantiation(std::vector<Node>& vs)
345 {
346 Assert(vs.size() == d_candidates.size());
347 for (unsigned i = 0; i < vs.size(); i++)
348 {
349 d_cinfo[d_candidates[i]].d_inst.push_back(vs[i]);
350 }
351 }
352 /** get synth solutions internal
353 *
354 * This function constructs the body of solutions for all
355 * functions-to-synthesize in this conjecture and stores them in sols, in
356 * order. For each solution added to sols, we add an integer indicating what
357 * kind of solution n is, where if sols[i] = n, then
358 * if status[i] = 0: n is the (builtin term) corresponding to the solution,
359 * if status[i] = 1: n is the sygus representation of the solution.
360 * We store builtin versions under some conditions (such as when the sygus
361 * grammar is being ignored).
362 *
363 * This consults the single invocation module to get synthesis solutions if
364 * isSingleInvocation() returns true.
365 *
366 * For example, for conjecture exists fg. forall x. f(x)>g(x), this function
367 * may set ( sols, status ) to ( { x+1, d_x() }, { 1, 0 } ), where d_x() is
368 * the sygus datatype constructor corresponding to variable x.
369 */
370 bool getSynthSolutionsInternal(std::vector<Node>& sols,
371 std::vector<int>& status);
372 //-------------------------------- sygus stream
373 /** current stream guard */
374 Node d_current_stream_guard;
375 /** the decision strategy for streaming solutions */
376 class SygusStreamDecisionStrategy : public DecisionStrategyFmf
377 {
378 public:
379 SygusStreamDecisionStrategy(context::Context* satContext,
380 Valuation valuation);
381 /** make literal */
382 Node mkLiteral(unsigned i) override;
383 /** identify */
384 std::string identify() const override
385 {
386 return std::string("sygus_stream");
387 }
388 };
389 std::unique_ptr<SygusStreamDecisionStrategy> d_stream_strategy;
390 /** get current stream guard */
391 Node getCurrentStreamGuard() const;
392 /** get stream guarded lemma
393 *
394 * If sygusStream is enabled, this returns ( G V n ) where G is the guard
395 * returned by getCurrentStreamGuard, otherwise this returns n.
396 */
397 Node getStreamGuardedLemma(Node n) const;
398 /**
399 * Prints the current synthesis solution to the output stream indicated by
400 * the Options object, send a lemma blocking the current solution to the
401 * output channel, which we refer to as a "stream exclusion lemma".
402 *
403 * The argument enums is the set of enumerators that comprise the current
404 * solution, and values is their current values.
405 */
406 void printAndContinueStream(const std::vector<Node>& enums,
407 const std::vector<Node>& values);
408 /** exclude the current solution { enums -> values } */
409 void excludeCurrentSolution(const std::vector<Node>& enums,
410 const std::vector<Node>& values);
411 /**
412 * Whether we have guarded a stream exclusion lemma when using sygusStream.
413 * This is an optimization that allows us to guard only the first stream
414 * exclusion lemma.
415 */
416 bool d_guarded_stream_exc;
417 //-------------------------------- end sygus stream
418 /** expression miner managers for each function-to-synthesize
419 *
420 * Notice that for each function-to-synthesize, we enumerate a stream of
421 * candidate solutions, where each of these streams is independent. Thus,
422 * we maintain separate expression miner managers for each of them.
423 *
424 * This is used for the sygusRewSynth() option to synthesize new candidate
425 * rewrite rules.
426 */
427 std::map<Node, ExpressionMinerManager> d_exprm;
428 };
429
430 } // namespace quantifiers
431 } // namespace theory
432 } /* namespace CVC4 */
433
434 #endif