Removing comments related to issues (#3232)
[cvc5.git] / src / theory / theory_model_builder.cpp
1 /********************* */
2 /*! \file theory_model_builder.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Andrew Reynolds, Clark Barrett, Andres Noetzli
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 Implementation of theory model buidler class
13 **/
14 #include "theory/theory_model_builder.h"
15
16 #include "options/quantifiers_options.h"
17 #include "options/smt_options.h"
18 #include "options/uf_options.h"
19 #include "theory/theory_engine.h"
20 #include "theory/uf/theory_uf_model.h"
21
22 using namespace std;
23 using namespace CVC4::kind;
24 using namespace CVC4::context;
25
26 namespace CVC4 {
27 namespace theory {
28
29 TheoryEngineModelBuilder::TheoryEngineModelBuilder(TheoryEngine* te) : d_te(te)
30 {
31 }
32
33 bool TheoryEngineModelBuilder::isAssignable(TNode n)
34 {
35 if (n.getKind() == kind::SELECT || n.getKind() == kind::APPLY_SELECTOR_TOTAL)
36 {
37 // selectors are always assignable (where we guarantee that they are not
38 // evaluatable here)
39 if (!options::ufHo())
40 {
41 Assert(!n.getType().isFunction());
42 return true;
43 }
44 else
45 {
46 // might be a function field
47 return !n.getType().isFunction();
48 }
49 }
50 else if (n.getKind() == kind::FLOATINGPOINT_COMPONENT_SIGN)
51 {
52 // Extracting the sign of a floating-point number acts similar to a
53 // selector on a datatype, i.e. if `(sign x)` wasn't assigned a value, we
54 // can pick an arbitrary one. Note that the other components of a
55 // floating-point number should always be assigned a value.
56 return true;
57 }
58 else
59 {
60 // non-function variables, and fully applied functions
61 if (!options::ufHo())
62 {
63 // no functions exist, all functions are fully applied
64 Assert(n.getKind() != kind::HO_APPLY);
65 Assert(!n.getType().isFunction());
66 return n.isVar() || n.getKind() == kind::APPLY_UF;
67 }
68 else
69 {
70 // Assert( n.getKind() != kind::APPLY_UF );
71 return (n.isVar() && !n.getType().isFunction())
72 || n.getKind() == kind::APPLY_UF
73 || (n.getKind() == kind::HO_APPLY
74 && n[0].getType().getNumChildren() == 2);
75 }
76 }
77 }
78
79 void TheoryEngineModelBuilder::addAssignableSubterms(TNode n,
80 TheoryModel* tm,
81 NodeSet& cache)
82 {
83 if (n.isClosure())
84 {
85 return;
86 }
87 if (cache.find(n) != cache.end())
88 {
89 return;
90 }
91 if (isAssignable(n))
92 {
93 tm->d_equalityEngine->addTerm(n);
94 }
95 for (TNode::iterator child_it = n.begin(); child_it != n.end(); ++child_it)
96 {
97 addAssignableSubterms(*child_it, tm, cache);
98 }
99 cache.insert(n);
100 }
101
102 void TheoryEngineModelBuilder::assignConstantRep(TheoryModel* tm,
103 Node eqc,
104 Node const_rep)
105 {
106 d_constantReps[eqc] = const_rep;
107 Trace("model-builder") << " Assign: Setting constant rep of " << eqc
108 << " to " << const_rep << endl;
109 tm->d_rep_set.setTermForRepresentative(const_rep, eqc);
110 }
111
112 bool TheoryEngineModelBuilder::isExcludedCdtValue(
113 Node val,
114 std::set<Node>* repSet,
115 std::map<Node, Node>& assertedReps,
116 Node eqc)
117 {
118 Trace("model-builder-debug")
119 << "Is " << val << " and excluded codatatype value for " << eqc << "? "
120 << std::endl;
121 for (set<Node>::iterator i = repSet->begin(); i != repSet->end(); ++i)
122 {
123 Assert(assertedReps.find(*i) != assertedReps.end());
124 Node rep = assertedReps[*i];
125 Trace("model-builder-debug") << " Rep : " << rep << std::endl;
126 // check matching val to rep with eqc as a free variable
127 Node eqc_m;
128 if (isCdtValueMatch(val, rep, eqc, eqc_m))
129 {
130 Trace("model-builder-debug") << " ...matches with " << eqc << " -> "
131 << eqc_m << std::endl;
132 if (eqc_m.getKind() == kind::UNINTERPRETED_CONSTANT)
133 {
134 Trace("model-builder-debug") << "*** " << val
135 << " is excluded datatype for " << eqc
136 << std::endl;
137 return true;
138 }
139 }
140 }
141 return false;
142 }
143
144 bool TheoryEngineModelBuilder::isCdtValueMatch(Node v,
145 Node r,
146 Node eqc,
147 Node& eqc_m)
148 {
149 if (r == v)
150 {
151 return true;
152 }
153 else if (r == eqc)
154 {
155 if (eqc_m.isNull())
156 {
157 // only if an uninterpreted constant?
158 eqc_m = v;
159 return true;
160 }
161 else
162 {
163 return v == eqc_m;
164 }
165 }
166 else if (v.getKind() == kind::APPLY_CONSTRUCTOR
167 && r.getKind() == kind::APPLY_CONSTRUCTOR)
168 {
169 if (v.getOperator() == r.getOperator())
170 {
171 for (unsigned i = 0; i < v.getNumChildren(); i++)
172 {
173 if (!isCdtValueMatch(v[i], r[i], eqc, eqc_m))
174 {
175 return false;
176 }
177 }
178 return true;
179 }
180 }
181 return false;
182 }
183
184 bool TheoryEngineModelBuilder::involvesUSort(TypeNode tn)
185 {
186 if (tn.isSort())
187 {
188 return true;
189 }
190 else if (tn.isArray())
191 {
192 return involvesUSort(tn.getArrayIndexType())
193 || involvesUSort(tn.getArrayConstituentType());
194 }
195 else if (tn.isSet())
196 {
197 return involvesUSort(tn.getSetElementType());
198 }
199 else if (tn.isDatatype())
200 {
201 const Datatype& dt = ((DatatypeType)(tn).toType()).getDatatype();
202 return dt.involvesUninterpretedType();
203 }
204 else
205 {
206 return false;
207 }
208 }
209
210 bool TheoryEngineModelBuilder::isExcludedUSortValue(
211 std::map<TypeNode, unsigned>& eqc_usort_count,
212 Node v,
213 std::map<Node, bool>& visited)
214 {
215 Assert(v.isConst());
216 if (visited.find(v) == visited.end())
217 {
218 visited[v] = true;
219 TypeNode tn = v.getType();
220 if (tn.isSort())
221 {
222 Trace("model-builder-debug") << "Is excluded usort value : " << v << " "
223 << tn << std::endl;
224 unsigned card = eqc_usort_count[tn];
225 Trace("model-builder-debug") << " Cardinality is " << card << std::endl;
226 unsigned index =
227 v.getConst<UninterpretedConstant>().getIndex().toUnsignedInt();
228 Trace("model-builder-debug") << " Index is " << index << std::endl;
229 return index > 0 && index >= card;
230 }
231 for (unsigned i = 0; i < v.getNumChildren(); i++)
232 {
233 if (isExcludedUSortValue(eqc_usort_count, v[i], visited))
234 {
235 return true;
236 }
237 }
238 }
239 return false;
240 }
241
242 void TheoryEngineModelBuilder::addToTypeList(
243 TypeNode tn,
244 std::vector<TypeNode>& type_list,
245 std::unordered_set<TypeNode, TypeNodeHashFunction>& visiting)
246 {
247 if (std::find(type_list.begin(), type_list.end(), tn) == type_list.end())
248 {
249 if (visiting.find(tn) == visiting.end())
250 {
251 visiting.insert(tn);
252 /* This must make a recursive call on all types that are subterms of
253 * values of the current type.
254 * Note that recursive traversal here is over enumerated expressions
255 * (very low expression depth). */
256 if (tn.isArray())
257 {
258 addToTypeList(tn.getArrayIndexType(), type_list, visiting);
259 addToTypeList(tn.getArrayConstituentType(), type_list, visiting);
260 }
261 else if (tn.isSet())
262 {
263 addToTypeList(tn.getSetElementType(), type_list, visiting);
264 }
265 else if (tn.isDatatype())
266 {
267 const Datatype& dt = ((DatatypeType)(tn).toType()).getDatatype();
268 for (unsigned i = 0; i < dt.getNumConstructors(); i++)
269 {
270 for (unsigned j = 0; j < dt[i].getNumArgs(); j++)
271 {
272 TypeNode ctn = TypeNode::fromType(dt[i][j].getRangeType());
273 addToTypeList(ctn, type_list, visiting);
274 }
275 }
276 }
277 Assert(std::find(type_list.begin(), type_list.end(), tn)
278 == type_list.end());
279 type_list.push_back(tn);
280 }
281 }
282 }
283
284 bool TheoryEngineModelBuilder::buildModel(Model* m)
285 {
286 Trace("model-builder") << "TheoryEngineModelBuilder: buildModel" << std::endl;
287 TheoryModel* tm = (TheoryModel*)m;
288
289 // buildModel should only be called once per check
290 Assert(!tm->isBuilt());
291
292 // Reset model
293 tm->reset();
294
295 // mark as built
296 tm->d_modelBuilt = true;
297 tm->d_modelBuiltSuccess = false;
298
299 // Collect model info from the theories
300 Trace("model-builder") << "TheoryEngineModelBuilder: Collect model info..."
301 << std::endl;
302 if (!d_te->collectModelInfo(tm))
303 {
304 return false;
305 }
306
307 // model-builder specific initialization
308 if (!preProcessBuildModel(tm))
309 {
310 return false;
311 }
312
313 // Loop through all terms and make sure that assignable sub-terms are in the
314 // equality engine
315 // Also, record #eqc per type (for finite model finding)
316 std::map<TypeNode, unsigned> eqc_usort_count;
317 eq::EqClassesIterator eqcs_i = eq::EqClassesIterator(tm->d_equalityEngine);
318 {
319 NodeSet cache;
320 for (; !eqcs_i.isFinished(); ++eqcs_i)
321 {
322 eq::EqClassIterator eqc_i =
323 eq::EqClassIterator((*eqcs_i), tm->d_equalityEngine);
324 for (; !eqc_i.isFinished(); ++eqc_i)
325 {
326 addAssignableSubterms(*eqc_i, tm, cache);
327 }
328 TypeNode tn = (*eqcs_i).getType();
329 if (tn.isSort())
330 {
331 if (eqc_usort_count.find(tn) == eqc_usort_count.end())
332 {
333 eqc_usort_count[tn] = 1;
334 }
335 else
336 {
337 eqc_usort_count[tn]++;
338 }
339 }
340 }
341 }
342
343 Trace("model-builder") << "Collect representatives..." << std::endl;
344
345 // Process all terms in the equality engine, store representatives for each EC
346 d_constantReps.clear();
347 std::map<Node, Node> assertedReps;
348 TypeSet typeConstSet, typeRepSet, typeNoRepSet;
349 TypeEnumeratorProperties tep;
350 if (options::finiteModelFind())
351 {
352 tep.d_fixed_usort_card = true;
353 for (std::map<TypeNode, unsigned>::iterator it = eqc_usort_count.begin();
354 it != eqc_usort_count.end();
355 ++it)
356 {
357 Trace("model-builder") << "Fixed bound (#eqc) for " << it->first << " : "
358 << it->second << std::endl;
359 tep.d_fixed_card[it->first] = Integer(it->second);
360 }
361 typeConstSet.setTypeEnumeratorProperties(&tep);
362 }
363 // AJR: build ordered list of types that ensures that base types are
364 // enumerated first.
365 // (I think) this is only strictly necessary for finite model finding +
366 // parametric types instantiated with uninterpreted sorts, but is probably
367 // a good idea to do in general since it leads to models with smaller term
368 // sizes.
369 std::vector<TypeNode> type_list;
370 eqcs_i = eq::EqClassesIterator(tm->d_equalityEngine);
371 for (; !eqcs_i.isFinished(); ++eqcs_i)
372 {
373 // eqc is the equivalence class representative
374 Node eqc = (*eqcs_i);
375 Trace("model-builder") << "Processing EC: " << eqc << endl;
376 Assert(tm->d_equalityEngine->getRepresentative(eqc) == eqc);
377 TypeNode eqct = eqc.getType();
378 Assert(assertedReps.find(eqc) == assertedReps.end());
379 Assert(d_constantReps.find(eqc) == d_constantReps.end());
380
381 // Loop through terms in this EC
382 Node rep, const_rep;
383 eq::EqClassIterator eqc_i = eq::EqClassIterator(eqc, tm->d_equalityEngine);
384 for (; !eqc_i.isFinished(); ++eqc_i)
385 {
386 Node n = *eqc_i;
387 Trace("model-builder") << " Processing Term: " << n << endl;
388 // Record as rep if this node was specified as a representative
389 if (tm->d_reps.find(n) != tm->d_reps.end())
390 {
391 // AJR: I believe this assertion is too strict,
392 // e.g. datatypes may assert representative for two constructor terms
393 // that are not in the care graph and are merged during
394 // collectModelInfo.
395 // Assert(rep.isNull());
396 rep = tm->d_reps[n];
397 Assert(!rep.isNull());
398 Trace("model-builder") << " Rep( " << eqc << " ) = " << rep
399 << std::endl;
400 }
401 // Record as const_rep if this node is constant
402 if (n.isConst())
403 {
404 Assert(const_rep.isNull());
405 const_rep = n;
406 Trace("model-builder") << " ConstRep( " << eqc << " ) = " << const_rep
407 << std::endl;
408 }
409 // model-specific processing of the term
410 tm->addTermInternal(n);
411 }
412
413 // Assign representative for this EC
414 if (!const_rep.isNull())
415 {
416 // Theories should not specify a rep if there is already a constant in the
417 // EC
418 // AJR: I believe this assertion is too strict, eqc with asserted reps may
419 // merge with constant eqc
420 // Assert(rep.isNull() || rep == const_rep);
421 assignConstantRep(tm, eqc, const_rep);
422 typeConstSet.add(eqct.getBaseType(), const_rep);
423 }
424 else if (!rep.isNull())
425 {
426 assertedReps[eqc] = rep;
427 typeRepSet.add(eqct.getBaseType(), eqc);
428 std::unordered_set<TypeNode, TypeNodeHashFunction> visiting;
429 addToTypeList(eqct.getBaseType(), type_list, visiting);
430 }
431 else
432 {
433 typeNoRepSet.add(eqct, eqc);
434 std::unordered_set<TypeNode, TypeNodeHashFunction> visiting;
435 addToTypeList(eqct, type_list, visiting);
436 }
437 }
438
439 // Need to ensure that each EC has a constant representative.
440
441 Trace("model-builder") << "Processing EC's..." << std::endl;
442
443 TypeSet::iterator it;
444 vector<TypeNode>::iterator type_it;
445 set<Node>::iterator i, i2;
446 bool changed, unassignedAssignable, assignOne = false;
447 set<TypeNode> evaluableSet;
448
449 // Double-fixed-point loop
450 // Outer loop handles a special corner case (see code at end of loop for
451 // details)
452 for (;;)
453 {
454 // Inner fixed-point loop: we are trying to learn constant values for every
455 // EC. Each time through this loop, we process all of the
456 // types by type and may learn some new EC values. EC's in one type may
457 // depend on EC's in another type, so we need a fixed-point loop
458 // to ensure that we learn as many EC values as possible
459 do
460 {
461 changed = false;
462 unassignedAssignable = false;
463 evaluableSet.clear();
464
465 // Iterate over all types we've seen
466 for (type_it = type_list.begin(); type_it != type_list.end(); ++type_it)
467 {
468 TypeNode t = *type_it;
469 TypeNode tb = t.getBaseType();
470 set<Node>* noRepSet = typeNoRepSet.getSet(t);
471
472 // 1. Try to evaluate the EC's in this type
473 if (noRepSet != NULL && !noRepSet->empty())
474 {
475 Trace("model-builder") << " Eval phase, working on type: " << t
476 << endl;
477 bool assignable, evaluable, evaluated;
478 d_normalizedCache.clear();
479 for (i = noRepSet->begin(); i != noRepSet->end();)
480 {
481 i2 = i;
482 ++i;
483 assignable = false;
484 evaluable = false;
485 evaluated = false;
486 Trace("model-builder-debug") << "Look at eqc : " << (*i2)
487 << std::endl;
488 eq::EqClassIterator eqc_i =
489 eq::EqClassIterator(*i2, tm->d_equalityEngine);
490 for (; !eqc_i.isFinished(); ++eqc_i)
491 {
492 Node n = *eqc_i;
493 Trace("model-builder-debug") << "Look at term : " << n
494 << std::endl;
495 if (isAssignable(n))
496 {
497 assignable = true;
498 Trace("model-builder-debug") << "...assignable" << std::endl;
499 }
500 else
501 {
502 evaluable = true;
503 Trace("model-builder-debug") << "...try to normalize"
504 << std::endl;
505 Node normalized = normalize(tm, n, true);
506 if (normalized.isConst())
507 {
508 typeConstSet.add(tb, normalized);
509 assignConstantRep(tm, *i2, normalized);
510 Trace("model-builder") << " Eval: Setting constant rep of "
511 << (*i2) << " to " << normalized
512 << endl;
513 changed = true;
514 evaluated = true;
515 noRepSet->erase(i2);
516 break;
517 }
518 }
519 }
520 if (!evaluated)
521 {
522 if (evaluable)
523 {
524 evaluableSet.insert(tb);
525 }
526 if (assignable)
527 {
528 unassignedAssignable = true;
529 }
530 }
531 }
532 }
533
534 // 2. Normalize any non-const representative terms for this type
535 set<Node>* repSet = typeRepSet.getSet(t);
536 if (repSet != NULL && !repSet->empty())
537 {
538 Trace("model-builder")
539 << " Normalization phase, working on type: " << t << endl;
540 d_normalizedCache.clear();
541 for (i = repSet->begin(); i != repSet->end();)
542 {
543 Assert(assertedReps.find(*i) != assertedReps.end());
544 Node rep = assertedReps[*i];
545 Node normalized = normalize(tm, rep, false);
546 Trace("model-builder") << " Normalizing rep (" << rep
547 << "), normalized to (" << normalized << ")"
548 << endl;
549 if (normalized.isConst())
550 {
551 changed = true;
552 typeConstSet.add(tb, normalized);
553 assignConstantRep(tm, *i, normalized);
554 assertedReps.erase(*i);
555 i2 = i;
556 ++i;
557 repSet->erase(i2);
558 }
559 else
560 {
561 if (normalized != rep)
562 {
563 assertedReps[*i] = normalized;
564 changed = true;
565 }
566 ++i;
567 }
568 }
569 }
570 }
571 } while (changed);
572
573 if (!unassignedAssignable)
574 {
575 break;
576 }
577
578 // 3. Assign unassigned assignable EC's using type enumeration - assign a
579 // value *different* from all other EC's if the type is infinite
580 // Assign first value from type enumerator otherwise - for finite types, we
581 // rely on polite framework to ensure that EC's that have to be
582 // different are different.
583
584 // Only make assignments on a type if:
585 // 1. there are no terms that share the same base type with un-normalized
586 // representatives
587 // 2. there are no terms that share teh same base type that are unevaluated
588 // evaluable terms
589 // Alternatively, if 2 or 3 don't hold but we are in a special
590 // deadlock-breaking mode where assignOne is true, go ahead and make one
591 // assignment
592 changed = false;
593 // must iterate over the ordered type list to ensure that we do not
594 // enumerate values with subterms
595 // having types that we are currently enumerating (when possible)
596 // for example, this ensures we enumerate uninterpreted sort U before (List
597 // of U) and (Array U U)
598 // however, it does not break cyclic type dependencies for mutually
599 // recursive datatypes, but this is handled
600 // by recording all subterms of enumerated values in TypeSet::addSubTerms.
601 for (type_it = type_list.begin(); type_it != type_list.end(); ++type_it)
602 {
603 TypeNode t = *type_it;
604 // continue if there are no more equivalence classes of this type to
605 // assign
606 std::set<Node>* noRepSetPtr = typeNoRepSet.getSet(t);
607 if (noRepSetPtr == NULL)
608 {
609 continue;
610 }
611 set<Node>& noRepSet = *noRepSetPtr;
612 if (noRepSet.empty())
613 {
614 continue;
615 }
616
617 // get properties of this type
618 bool isCorecursive = false;
619 if (t.isDatatype())
620 {
621 const Datatype& dt = ((DatatypeType)(t).toType()).getDatatype();
622 isCorecursive =
623 dt.isCodatatype() && (!dt.isFinite(t.toType())
624 || dt.isRecursiveSingleton(t.toType()));
625 }
626 #ifdef CVC4_ASSERTIONS
627 bool isUSortFiniteRestricted = false;
628 if (options::finiteModelFind())
629 {
630 isUSortFiniteRestricted = !t.isSort() && involvesUSort(t);
631 }
632 #endif
633
634 set<Node>* repSet = typeRepSet.getSet(t);
635 TypeNode tb = t.getBaseType();
636 if (!assignOne)
637 {
638 set<Node>* repSet = typeRepSet.getSet(tb);
639 if (repSet != NULL && !repSet->empty())
640 {
641 continue;
642 }
643 if (evaluableSet.find(tb) != evaluableSet.end())
644 {
645 continue;
646 }
647 }
648 Trace("model-builder") << " Assign phase, working on type: " << t
649 << endl;
650 bool assignable, evaluable CVC4_UNUSED;
651 for (i = noRepSet.begin(); i != noRepSet.end();)
652 {
653 i2 = i;
654 ++i;
655 eq::EqClassIterator eqc_i =
656 eq::EqClassIterator(*i2, tm->d_equalityEngine);
657 assignable = false;
658 evaluable = false;
659 for (; !eqc_i.isFinished(); ++eqc_i)
660 {
661 Node n = *eqc_i;
662 if (isAssignable(n))
663 {
664 assignable = true;
665 }
666 else
667 {
668 evaluable = true;
669 }
670 }
671 Trace("model-builder-debug")
672 << " eqc " << *i2 << " is assignable=" << assignable
673 << ", evaluable=" << evaluable << std::endl;
674 if (assignable)
675 {
676 Assert(!evaluable || assignOne);
677 // this assertion ensures that if we are assigning to a term of
678 // Boolean type, then the term is either a variable or an APPLY_UF.
679 // Note we only assign to terms of Boolean type if the term occurs in
680 // a singleton equivalence class; otherwise the term would have been
681 // in the equivalence class of true or false and would not need
682 // assigning.
683 Assert(!t.isBoolean() || (*i2).isVar()
684 || (*i2).getKind() == kind::APPLY_UF);
685 Node n;
686 if (t.getCardinality().isInfinite())
687 {
688 // if (!t.isInterpretedFinite()) {
689 bool success;
690 do
691 {
692 Trace("model-builder-debug") << "Enumerate term of type " << t
693 << std::endl;
694 n = typeConstSet.nextTypeEnum(t, true);
695 //--- AJR: this code checks whether n is a legal value
696 Assert(!n.isNull());
697 success = true;
698 Trace("model-builder-debug") << "Check if excluded : " << n
699 << std::endl;
700 #ifdef CVC4_ASSERTIONS
701 if (isUSortFiniteRestricted)
702 {
703 // must not involve uninterpreted constants beyond cardinality
704 // bound (which assumed to coincide with #eqc)
705 // this is just an assertion now, since TypeEnumeratorProperties
706 // should ensure that only legal values are enumerated wrt this
707 // constraint.
708 std::map<Node, bool> visited;
709 success = !isExcludedUSortValue(eqc_usort_count, n, visited);
710 if (!success)
711 {
712 Trace("model-builder")
713 << "Excluded value for " << t << " : " << n
714 << " due to out of range uninterpreted constant."
715 << std::endl;
716 }
717 Assert(success);
718 }
719 #endif
720 if (success && isCorecursive)
721 {
722 if (repSet != NULL && !repSet->empty())
723 {
724 // in the case of codatatypes, check if it is in the set of
725 // values that we cannot assign
726 success = !isExcludedCdtValue(n, repSet, assertedReps, *i2);
727 if (!success)
728 {
729 Trace("model-builder")
730 << "Excluded value : " << n
731 << " due to alpha-equivalent codatatype expression."
732 << std::endl;
733 }
734 }
735 }
736 //---
737 } while (!success);
738 }
739 else
740 {
741 TypeEnumerator te(t);
742 n = *te;
743 }
744 Assert(!n.isNull());
745 assignConstantRep(tm, *i2, n);
746 changed = true;
747 noRepSet.erase(i2);
748 if (assignOne)
749 {
750 assignOne = false;
751 break;
752 }
753 }
754 }
755 }
756
757 // Corner case - I'm not sure this can even happen - but it's theoretically
758 // possible to have a cyclical dependency
759 // in EC assignment/evaluation, e.g. EC1 = {a, b + 1}; EC2 = {b, a - 1}. In
760 // this case, neither one will get assigned because we are waiting
761 // to be able to evaluate. But we will never be able to evaluate because
762 // the variables that need to be assigned are in
763 // these same EC's. In this case, repeat the whole fixed-point computation
764 // with the difference that the first EC
765 // that has both assignable and evaluable expressions will get assigned.
766 if (!changed)
767 {
768 Assert(!assignOne); // check for infinite loop!
769 assignOne = true;
770 }
771 }
772
773 #ifdef CVC4_ASSERTIONS
774 // Assert that all representatives have been converted to constants
775 for (it = typeRepSet.begin(); it != typeRepSet.end(); ++it)
776 {
777 set<Node>& repSet = TypeSet::getSet(it);
778 if (!repSet.empty())
779 {
780 Trace("model-builder") << "***Non-empty repSet, size = " << repSet.size()
781 << ", first = " << *(repSet.begin()) << endl;
782 Assert(false);
783 }
784 }
785 #endif /* CVC4_ASSERTIONS */
786
787 Trace("model-builder") << "Copy representatives to model..." << std::endl;
788 tm->d_reps.clear();
789 std::map<Node, Node>::iterator itMap;
790 for (itMap = d_constantReps.begin(); itMap != d_constantReps.end(); ++itMap)
791 {
792 tm->d_reps[itMap->first] = itMap->second;
793 tm->d_rep_set.add(itMap->second.getType(), itMap->second);
794 }
795
796 Trace("model-builder") << "Make sure ECs have reps..." << std::endl;
797 // Make sure every EC has a rep
798 for (itMap = assertedReps.begin(); itMap != assertedReps.end(); ++itMap)
799 {
800 tm->d_reps[itMap->first] = itMap->second;
801 tm->d_rep_set.add(itMap->second.getType(), itMap->second);
802 }
803 for (it = typeNoRepSet.begin(); it != typeNoRepSet.end(); ++it)
804 {
805 set<Node>& noRepSet = TypeSet::getSet(it);
806 set<Node>::iterator i;
807 for (i = noRepSet.begin(); i != noRepSet.end(); ++i)
808 {
809 tm->d_reps[*i] = *i;
810 tm->d_rep_set.add((*i).getType(), *i);
811 }
812 }
813
814 // modelBuilder-specific initialization
815 if (!processBuildModel(tm))
816 {
817 return false;
818 }
819
820 tm->d_modelBuiltSuccess = true;
821 return true;
822 }
823
824 void TheoryEngineModelBuilder::postProcessModel(bool incomplete, Model* m)
825 {
826 // if we are incomplete, there is no guarantee on the model.
827 // thus, we do not check the model here.
828 if (incomplete)
829 {
830 return;
831 }
832 TheoryModel* tm = static_cast<TheoryModel*>(m);
833 Assert(tm != nullptr);
834 // debug-check the model if the checkModels() is enabled.
835 if (options::checkModels())
836 {
837 debugCheckModel(tm);
838 }
839 }
840
841 void TheoryEngineModelBuilder::debugCheckModel(TheoryModel* tm)
842 {
843 #ifdef CVC4_ASSERTIONS
844 Assert(tm->isBuilt());
845 eq::EqClassesIterator eqcs_i = eq::EqClassesIterator(tm->d_equalityEngine);
846 std::map<Node, Node>::iterator itMap;
847 // Check that every term evaluates to its representative in the model
848 for (eqcs_i = eq::EqClassesIterator(tm->d_equalityEngine);
849 !eqcs_i.isFinished();
850 ++eqcs_i)
851 {
852 // eqc is the equivalence class representative
853 Node eqc = (*eqcs_i);
854 // get the representative
855 Node rep = tm->getRepresentative(eqc);
856 if (!rep.isConst() && eqc.getType().isBoolean())
857 {
858 // if Boolean, it does not necessarily have a constant representative, use
859 // get value instead
860 rep = tm->getValue(eqc);
861 Assert(rep.isConst());
862 }
863 eq::EqClassIterator eqc_i = eq::EqClassIterator(eqc, tm->d_equalityEngine);
864 for (; !eqc_i.isFinished(); ++eqc_i)
865 {
866 Node n = *eqc_i;
867 static int repCheckInstance = 0;
868 ++repCheckInstance;
869
870 // non-linear mult is not necessarily accurate wrt getValue
871 if (n.getKind() != kind::NONLINEAR_MULT)
872 {
873 Debug("check-model::rep-checking") << "( " << repCheckInstance << ") "
874 << "n: " << n << endl
875 << "getValue(n): " << tm->getValue(n)
876 << endl
877 << "rep: " << rep << endl;
878 Assert(tm->getValue(*eqc_i) == rep,
879 "run with -d check-model::rep-checking for details");
880 }
881 }
882 }
883 #endif /* CVC4_ASSERTIONS */
884
885 // builder-specific debugging
886 debugModel(tm);
887 }
888
889 Node TheoryEngineModelBuilder::normalize(TheoryModel* m, TNode r, bool evalOnly)
890 {
891 std::map<Node, Node>::iterator itMap = d_constantReps.find(r);
892 if (itMap != d_constantReps.end())
893 {
894 return (*itMap).second;
895 }
896 NodeMap::iterator it = d_normalizedCache.find(r);
897 if (it != d_normalizedCache.end())
898 {
899 return (*it).second;
900 }
901 Trace("model-builder-debug") << "do normalize on " << r << std::endl;
902 Node retNode = r;
903 if (r.getNumChildren() > 0)
904 {
905 std::vector<Node> children;
906 if (r.getMetaKind() == kind::metakind::PARAMETERIZED)
907 {
908 children.push_back(r.getOperator());
909 }
910 bool childrenConst = true;
911 for (size_t i = 0; i < r.getNumChildren(); ++i)
912 {
913 Node ri = r[i];
914 bool recurse = true;
915 if (!ri.isConst())
916 {
917 if (m->d_equalityEngine->hasTerm(ri))
918 {
919 itMap =
920 d_constantReps.find(m->d_equalityEngine->getRepresentative(ri));
921 if (itMap != d_constantReps.end())
922 {
923 ri = (*itMap).second;
924 recurse = false;
925 }
926 else if (!evalOnly)
927 {
928 recurse = false;
929 }
930 }
931 if (recurse)
932 {
933 ri = normalize(m, ri, evalOnly);
934 }
935 if (!ri.isConst())
936 {
937 childrenConst = false;
938 }
939 }
940 children.push_back(ri);
941 }
942 retNode = NodeManager::currentNM()->mkNode(r.getKind(), children);
943 if (childrenConst)
944 {
945 retNode = Rewriter::rewrite(retNode);
946 Assert(retNode.getKind() == kind::APPLY_UF
947 || !retNode.getType().isFirstClass()
948 || retNode.isConst());
949 }
950 }
951 d_normalizedCache[r] = retNode;
952 return retNode;
953 }
954
955 bool TheoryEngineModelBuilder::preProcessBuildModel(TheoryModel* m)
956 {
957 return true;
958 }
959
960 bool TheoryEngineModelBuilder::processBuildModel(TheoryModel* m)
961 {
962 if (m->areFunctionValuesEnabled())
963 {
964 assignFunctions(m);
965 }
966 return true;
967 }
968
969 void TheoryEngineModelBuilder::assignFunction(TheoryModel* m, Node f)
970 {
971 Assert(!options::ufHo());
972 uf::UfModelTree ufmt(f);
973 Node default_v;
974 for (size_t i = 0; i < m->d_uf_terms[f].size(); i++)
975 {
976 Node un = m->d_uf_terms[f][i];
977 vector<TNode> children;
978 children.push_back(f);
979 Trace("model-builder-debug") << " process term : " << un << std::endl;
980 for (size_t j = 0; j < un.getNumChildren(); ++j)
981 {
982 Node rc = m->getRepresentative(un[j]);
983 Trace("model-builder-debug2") << " get rep : " << un[j] << " returned "
984 << rc << std::endl;
985 Assert(rc.isConst());
986 children.push_back(rc);
987 }
988 Node simp = NodeManager::currentNM()->mkNode(un.getKind(), children);
989 Node v = m->getRepresentative(un);
990 Trace("model-builder") << " Setting (" << simp << ") to (" << v << ")"
991 << endl;
992 ufmt.setValue(m, simp, v);
993 default_v = v;
994 }
995 if (default_v.isNull())
996 {
997 // choose default value from model if none exists
998 TypeEnumerator te(f.getType().getRangeType());
999 default_v = (*te);
1000 }
1001 ufmt.setDefaultValue(m, default_v);
1002 bool condenseFuncValues = options::condenseFunctionValues();
1003 if (condenseFuncValues)
1004 {
1005 ufmt.simplify();
1006 }
1007 std::stringstream ss;
1008 ss << "_arg_";
1009 Node val = ufmt.getFunctionValue(ss.str().c_str(), condenseFuncValues);
1010 m->assignFunctionDefinition(f, val);
1011 // ufmt.debugPrint( std::cout, m );
1012 }
1013
1014 void TheoryEngineModelBuilder::assignHoFunction(TheoryModel* m, Node f)
1015 {
1016 Assert(options::ufHo());
1017 TypeNode type = f.getType();
1018 std::vector<TypeNode> argTypes = type.getArgTypes();
1019 std::vector<Node> args;
1020 std::vector<TNode> apply_args;
1021 for (unsigned i = 0; i < argTypes.size(); i++)
1022 {
1023 Node v = NodeManager::currentNM()->mkBoundVar(argTypes[i]);
1024 args.push_back(v);
1025 if (i > 0)
1026 {
1027 apply_args.push_back(v);
1028 }
1029 }
1030 // start with the base return value (currently we use the same default value
1031 // for all functions)
1032 TypeEnumerator te(type.getRangeType());
1033 Node curr = (*te);
1034 std::map<Node, std::vector<Node> >::iterator itht = m->d_ho_uf_terms.find(f);
1035 if (itht != m->d_ho_uf_terms.end())
1036 {
1037 for (size_t i = 0; i < itht->second.size(); i++)
1038 {
1039 Node hn = itht->second[i];
1040 Trace("model-builder-debug") << " process : " << hn << std::endl;
1041 Assert(hn.getKind() == kind::HO_APPLY);
1042 Assert(m->areEqual(hn[0], f));
1043 Node hni = m->getRepresentative(hn[1]);
1044 Trace("model-builder-debug2") << " get rep : " << hn[0]
1045 << " returned " << hni << std::endl;
1046 Assert(hni.isConst());
1047 Assert(hni.getType().isSubtypeOf(args[0].getType()));
1048 hni = Rewriter::rewrite(args[0].eqNode(hni));
1049 Node hnv = m->getRepresentative(hn);
1050 Trace("model-builder-debug2") << " get rep val : " << hn
1051 << " returned " << hnv << std::endl;
1052 Assert(hnv.isConst());
1053 if (!apply_args.empty())
1054 {
1055 Assert(hnv.getKind() == kind::LAMBDA
1056 && hnv[0].getNumChildren() + 1 == args.size());
1057 std::vector<TNode> largs;
1058 for (unsigned j = 0; j < hnv[0].getNumChildren(); j++)
1059 {
1060 largs.push_back(hnv[0][j]);
1061 }
1062 Assert(largs.size() == apply_args.size());
1063 hnv = hnv[1].substitute(
1064 largs.begin(), largs.end(), apply_args.begin(), apply_args.end());
1065 hnv = Rewriter::rewrite(hnv);
1066 }
1067 Assert(!TypeNode::leastCommonTypeNode(hnv.getType(), curr.getType())
1068 .isNull());
1069 curr = NodeManager::currentNM()->mkNode(kind::ITE, hni, hnv, curr);
1070 }
1071 }
1072 Node val = NodeManager::currentNM()->mkNode(
1073 kind::LAMBDA,
1074 NodeManager::currentNM()->mkNode(kind::BOUND_VAR_LIST, args),
1075 curr);
1076 m->assignFunctionDefinition(f, val);
1077 }
1078
1079 // This struct is used to sort terms by the "size" of their type
1080 // The size of the type is the number of nodes in the type, for example
1081 // size of Int is 1
1082 // size of Function( Int, Int ) is 3
1083 // size of Function( Function( Bool, Int ), Int ) is 5
1084 struct sortTypeSize
1085 {
1086 // stores the size of the type
1087 std::map<TypeNode, unsigned> d_type_size;
1088 // get the size of type tn
1089 unsigned getTypeSize(TypeNode tn)
1090 {
1091 std::map<TypeNode, unsigned>::iterator it = d_type_size.find(tn);
1092 if (it != d_type_size.end())
1093 {
1094 return it->second;
1095 }
1096 else
1097 {
1098 unsigned sum = 1;
1099 for (unsigned i = 0; i < tn.getNumChildren(); i++)
1100 {
1101 sum += getTypeSize(tn[i]);
1102 }
1103 d_type_size[tn] = sum;
1104 return sum;
1105 }
1106 }
1107
1108 public:
1109 // compares the type size of i and j
1110 // returns true iff the size of i is less than that of j
1111 // tiebreaks are determined by node value
1112 bool operator()(Node i, Node j)
1113 {
1114 int si = getTypeSize(i.getType());
1115 int sj = getTypeSize(j.getType());
1116 if (si < sj)
1117 {
1118 return true;
1119 }
1120 else if (si == sj)
1121 {
1122 return i < j;
1123 }
1124 else
1125 {
1126 return false;
1127 }
1128 }
1129 };
1130
1131 void TheoryEngineModelBuilder::assignFunctions(TheoryModel* m)
1132 {
1133 if (!options::assignFunctionValues())
1134 {
1135 return;
1136 }
1137 Trace("model-builder") << "Assigning function values..." << std::endl;
1138 std::vector<Node> funcs_to_assign = m->getFunctionsToAssign();
1139
1140 if (options::ufHo())
1141 {
1142 // sort based on type size if higher-order
1143 Trace("model-builder") << "Sort functions by type..." << std::endl;
1144 sortTypeSize sts;
1145 std::sort(funcs_to_assign.begin(), funcs_to_assign.end(), sts);
1146 }
1147
1148 if (Trace.isOn("model-builder"))
1149 {
1150 Trace("model-builder") << "...have " << funcs_to_assign.size()
1151 << " functions to assign:" << std::endl;
1152 for (unsigned k = 0; k < funcs_to_assign.size(); k++)
1153 {
1154 Node f = funcs_to_assign[k];
1155 Trace("model-builder") << " [" << k << "] : " << f << " : "
1156 << f.getType() << std::endl;
1157 }
1158 }
1159
1160 // construct function values
1161 for (unsigned k = 0; k < funcs_to_assign.size(); k++)
1162 {
1163 Node f = funcs_to_assign[k];
1164 Trace("model-builder") << " Function #" << k << " is " << f << std::endl;
1165 // std::map< Node, std::vector< Node > >::iterator itht =
1166 // m->d_ho_uf_terms.find( f );
1167 if (!options::ufHo())
1168 {
1169 Trace("model-builder") << " Assign function value for " << f
1170 << " based on APPLY_UF" << std::endl;
1171 assignFunction(m, f);
1172 }
1173 else
1174 {
1175 Trace("model-builder") << " Assign function value for " << f
1176 << " based on curried HO_APPLY" << std::endl;
1177 assignHoFunction(m, f);
1178 }
1179 }
1180 Trace("model-builder") << "Finished assigning function values." << std::endl;
1181 }
1182
1183 } /* namespace CVC4::theory */
1184 } /* namespace CVC4 */