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