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