summaryrefslogtreecommitdiff
path: root/src/theory/theory_engine.cpp
blob: 3e1dc6fe4f08e402694b173253180cf23915d613 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
/*********************                                                        */
/*! \file theory_engine.cpp
 ** \verbatim
 ** Original author: mdeters
 ** Major contributors: barrett, dejan
 ** Minor contributors (to current version): cconway, taking
 ** This file is part of the CVC4 prototype.
 ** Copyright (c) 2009, 2010, 2011  The Analysis of Computer Systems Group (ACSys)
 ** Courant Institute of Mathematical Sciences
 ** New York University
 ** See the file COPYING in the top-level source directory for licensing
 ** information.\endverbatim
 **
 ** \brief The theory engine.
 **
 ** The theory engine.
 **/

#include <vector>
#include <list>

#include "expr/attribute.h"
#include "expr/node.h"
#include "expr/node_builder.h"
#include "util/options.h"

#include "theory/theory.h"
#include "theory/theory_engine.h"
#include "theory/rewriter.h"
#include "theory/theory_traits.h"

#include "util/node_visitor.h"
#include "util/ite_removal.h"

using namespace std;

using namespace CVC4;
using namespace CVC4::theory;

TheoryEngine::TheoryEngine(context::Context* context,
                           context::UserContext* userContext,
                           const LogicInfo& logicInfo)
: d_propEngine(NULL),
  d_decisionEngine(NULL),
  d_context(context),
  d_userContext(userContext),
  d_logicInfo(logicInfo),
  d_notify(*this),
  d_sharedTerms(d_notify, context),
  d_ppCache(),
  d_possiblePropagations(context),
  d_hasPropagated(context),
  d_inConflict(context, false),
  d_hasShutDown(false),
  d_incomplete(context, false),
  d_sharedLiteralsIn(context),
  d_assertedLiteralsOut(context),
  d_propagatedLiterals(context),
  d_propagatedLiteralsIndex(context, 0),
  d_decisionRequests(context),
  d_decisionRequestsIndex(context, 0),
  d_combineTheoriesTime("TheoryEngine::combineTheoriesTime"),
  d_inPreregister(false),
  d_preRegistrationVisitor(this, context),
  d_sharedTermsVisitor(d_sharedTerms),
  d_unconstrainedSimp(context, logicInfo)
{
  for(TheoryId theoryId = theory::THEORY_FIRST; theoryId != theory::THEORY_LAST; ++ theoryId) {
    d_theoryTable[theoryId] = NULL;
    d_theoryOut[theoryId] = NULL;
  }
  Rewriter::init();
  StatisticsRegistry::registerStat(&d_combineTheoriesTime);
  d_true = NodeManager::currentNM()->mkConst<bool>(true);
  d_false = NodeManager::currentNM()->mkConst<bool>(false);
}

TheoryEngine::~TheoryEngine() {
  Assert(d_hasShutDown);

  for(TheoryId theoryId = theory::THEORY_FIRST; theoryId != theory::THEORY_LAST; ++ theoryId) {
    if(d_theoryTable[theoryId] != NULL) {
      delete d_theoryTable[theoryId];
      delete d_theoryOut[theoryId];
    }
  }

  StatisticsRegistry::unregisterStat(&d_combineTheoriesTime);
}

void TheoryEngine::preRegister(TNode preprocessed) {

  if(Dump.isOn("missed-t-propagations")) {
    d_possiblePropagations.push_back(preprocessed);
  }
  d_preregisterQueue.push(preprocessed);

  if (!d_inPreregister) {
    // We're in pre-register
    d_inPreregister = true;

    // Process the pre-registration queue
    while (!d_preregisterQueue.empty()) {
      // Get the next atom to pre-register
      preprocessed = d_preregisterQueue.front();
      d_preregisterQueue.pop();

      // Pre-register the terms in the atom
      bool multipleTheories = NodeVisitor<PreRegisterVisitor>::run(d_preRegistrationVisitor, preprocessed);
      if (multipleTheories) {
        // Collect the shared terms if there are multipe theories
        NodeVisitor<SharedTermsVisitor>::run(d_sharedTermsVisitor, preprocessed);
      }
    }

    // Leaving pre-register
    d_inPreregister = false;
  }
}

void TheoryEngine::printAssertions(const char* tag) {
  if (Debug.isOn(tag)) {
    for (TheoryId theoryId = THEORY_FIRST; theoryId < THEORY_LAST; ++theoryId) {
      Theory* theory = d_theoryTable[theoryId];
      if (theory && d_logicInfo.isTheoryEnabled(theoryId)) {
        Debug(tag) << "--------------------------------------------" << std::endl;
        Debug(tag) << "Assertions of " << theory->getId() << ": " << std::endl;
        context::CDList<Assertion>::const_iterator it = theory->facts_begin(), it_end = theory->facts_end();
        for (unsigned i = 0; it != it_end; ++ it, ++i) {
            if ((*it).isPreregistered) {
              Debug(tag) << "[" << i << "]: ";
            } else {
              Debug(tag) << "(" << i << "): ";
            }
            Debug(tag) << (*it).assertion << endl;
        }

        if (d_logicInfo.isSharingEnabled()) {
          Debug(tag) << "Shared terms of " << theory->getId() << ": " << std::endl;
          context::CDList<TNode>::const_iterator it = theory->shared_terms_begin(), it_end = theory->shared_terms_end();
          for (unsigned i = 0; it != it_end; ++ it, ++i) {
              Debug(tag) << "[" << i << "]: " << (*it) << endl;
          }
        }
      }
    }

  }
}

template<typename T, bool doAssert>
class scoped_vector_clear {
  vector<T>& d_v;
public:
  scoped_vector_clear(vector<T>& v)
  : d_v(v) {
    Assert(!doAssert || d_v.empty());
  }
  ~scoped_vector_clear() {
    d_v.clear();
  }

};

/**
 * Check all (currently-active) theories for conflicts.
 * @param effort the effort level to use
 */
void TheoryEngine::check(Theory::Effort effort) {

  d_propEngine->checkTime();

#ifdef CVC4_FOR_EACH_THEORY_STATEMENT
#undef CVC4_FOR_EACH_THEORY_STATEMENT
#endif
#define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
    if (theory::TheoryTraits<THEORY>::hasCheck && d_logicInfo.isTheoryEnabled(THEORY)) { \
       reinterpret_cast<theory::TheoryTraits<THEORY>::theory_class*>(theoryOf(THEORY))->check(effort); \
       if (d_inConflict) { \
         break; \
       } \
    }

  // make sure d_propagatedSharedLiterals is cleared on exit
  scoped_vector_clear<SharedLiteral, true> clear_shared_literals(d_propagatedSharedLiterals);

  // Do the checking
  try {

    // Mark the output channel unused (if this is FULL_EFFORT, and nothing
    // is done by the theories, no additional check will be needed)
    d_outputChannelUsed = false;

    // Mark the lemmas flag (no lemmas added)
    d_lemmasAdded = false;

    while (true) {

      Debug("theory") << "TheoryEngine::check(" << effort << "): running check" << std::endl;
      Assert(d_propagatedSharedLiterals.empty());

      if (Debug.isOn("theory::assertions")) {
        printAssertions("theory::assertions");
      }

      // Do the checking
      CVC4_FOR_EACH_THEORY;

      if(Dump.isOn("missed-t-conflicts")) {
        Dump("missed-t-conflicts")
            << CommentCommand("Completeness check for T-conflicts; expect sat")
            << CheckSatCommand();
      }

      Debug("theory") << "TheoryEngine::check(" << effort << "): running propagation after the initial check" << std::endl;

      // We are still satisfiable, propagate as much as possible
      propagate(effort);

      // If we have any propagated shared literals, we enqueue them to the theories and re-check
      if (d_propagatedSharedLiterals.size() > 0) {
        Debug("theory") << "TheoryEngine::check(" << effort << "): distributing shared literals" << std::endl;
        outputSharedLiterals();
        continue;
      }

      // If we added any lemmas, we're done
      if (d_lemmasAdded) {
        Debug("theory") << "TheoryEngine::check(" << effort << "): lemmas added, done" << std::endl;
        break;
      }

      // If in full check and no lemmas added, run the combination
      if (Theory::fullEffort(effort) && d_logicInfo.isSharingEnabled()) {
        // Do the combination
        Debug("theory") << "TheoryEngine::check(" << effort << "): running combination" << std::endl;
        combineTheories();
        // If we have any propagated shared literals, we enqueue them to the theories and re-check
        if (d_propagatedSharedLiterals.size() > 0) {
          Debug("theory") << "TheoryEngine::check(" << effort << "): distributing shared literals" << std::endl;
          outputSharedLiterals();
        } else {
          // No propagated shared literals, we're either sat, or there are lemmas added
          break;
        }
      } else {
        break;
      }
    }

    Debug("theory") << "TheoryEngine::check(" << effort << "): done, we are " << (d_inConflict ? "unsat" : "sat") << (d_lemmasAdded ? " with new lemmas" : " with no new lemmas") << std::endl;

  } catch(const theory::Interrupted&) {
    Trace("theory") << "TheoryEngine::check() => conflict" << endl;
  }
}

void TheoryEngine::outputSharedLiterals() {

  scoped_vector_clear<SharedLiteral, false> clear_shared_literals(d_propagatedSharedLiterals);

  // Assert all the shared literals
  for (unsigned i = 0; i < d_propagatedSharedLiterals.size(); ++ i) {
    const SharedLiteral& eq = d_propagatedSharedLiterals[i];
    // Check if the theory already got this one
    if (d_assertedLiteralsOut.find(eq.toAssert) == d_assertedLiteralsOut.end()) {
      Debug("sharing") << "TheoryEngine::outputSharedLiterals(): asserting " << eq.toAssert.node << " to " << eq.toAssert.theory << std::endl;
      Debug("sharing") << "TheoryEngine::outputSharedLiterals(): orignal " << eq.toExplain << std::endl;
      d_assertedLiteralsOut[eq.toAssert] = eq.toExplain;
      if (eq.toAssert.theory == theory::THEORY_LAST) {
        d_propagatedLiterals.push_back(eq.toAssert.node);
      } else {
        theoryOf(eq.toAssert.theory)->assertFact(eq.toAssert.node, false);
      }
    }
  }
}


void TheoryEngine::combineTheories() {

  Debug("sharing") << "TheoryEngine::combineTheories()" << std::endl;

  TimerStat::CodeTimer combineTheoriesTimer(d_combineTheoriesTime);

  // Care graph we'll be building
  CareGraph careGraph;

#ifdef CVC4_FOR_EACH_THEORY_STATEMENT
#undef CVC4_FOR_EACH_THEORY_STATEMENT
#endif
#define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
  if (theory::TheoryTraits<THEORY>::isParametric && d_logicInfo.isTheoryEnabled(THEORY)) { \
     reinterpret_cast<theory::TheoryTraits<THEORY>::theory_class*>(theoryOf(THEORY))->getCareGraph(careGraph); \
  }

  // Call on each parametric theory to give us its care graph
  CVC4_FOR_EACH_THEORY;

  // Now add splitters for the ones we are interested in
  CareGraph::const_iterator care_it = careGraph.begin();
  CareGraph::const_iterator care_it_end = careGraph.end();
  for (; care_it != care_it_end; ++ care_it) {
    const CarePair& carePair = *care_it;

    Debug("sharing") << "TheoryEngine::combineTheories(): checking " << carePair.a << " = " << carePair.b << " from " << carePair.theory << std::endl;

    if (d_sharedTerms.areEqual(carePair.a, carePair.b) ||
        d_sharedTerms.areDisequal(carePair.a, carePair.b)) {
      continue;
    }

    if (carePair.a.isConst() && carePair.b.isConst()) {
      // TODO: equality engine should auto-detect these as disequal
      d_sharedTerms.processSharedLiteral(carePair.a.eqNode(carePair.b).notNode(), d_true);
      continue;
    }

    Node equality = carePair.a.eqNode(carePair.b);
    Node normalizedEquality = Rewriter::rewrite(equality);
    bool isTrivial = normalizedEquality.getKind() == kind::CONST_BOOLEAN;
    bool value;
    if (isTrivial || (d_propEngine->isSatLiteral(normalizedEquality) && d_propEngine->hasValue(normalizedEquality, value))) {
      // Missed propagation!
      Debug("sharing") << "TheoryEngine::combineTheories(): has a literal or is trivial" << std::endl;
      
      if (isTrivial) {
        value = normalizedEquality.getConst<bool>();
        normalizedEquality = d_true;
      }
      else {
        d_sharedLiteralsIn[normalizedEquality] = theory::THEORY_LAST;
        if (!value) normalizedEquality = normalizedEquality.notNode();
      }
      if (!value) {
        equality = equality.notNode();
      }
      d_sharedTerms.processSharedLiteral(equality, normalizedEquality);
      continue;
    }

    // There is no value, so we need to split on it
    Debug("sharing") << "TheoryEngine::combineTheories(): requesting a split " << std::endl;
    lemma(equality.orNode(equality.notNode()), false, false);

  }
}

void TheoryEngine::propagate(Theory::Effort effort) {
  // Definition of the statement that is to be run by every theory
#ifdef CVC4_FOR_EACH_THEORY_STATEMENT
#undef CVC4_FOR_EACH_THEORY_STATEMENT
#endif
#define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
  if (theory::TheoryTraits<THEORY>::hasPropagate && d_logicInfo.isTheoryEnabled(THEORY)) { \
    reinterpret_cast<theory::TheoryTraits<THEORY>::theory_class*>(theoryOf(THEORY))->propagate(effort); \
  }

  // Propagate for each theory using the statement above
  CVC4_FOR_EACH_THEORY;

  if(Dump.isOn("missed-t-propagations")) {
    for(unsigned i = 0; i < d_possiblePropagations.size(); ++ i) {
      Node atom = d_possiblePropagations[i];
      bool value;
      if (d_propEngine->hasValue(atom, value)) continue;
      // Doesn't have a value, check it (and the negation)
      if(d_hasPropagated.find(atom) == d_hasPropagated.end()) {
        Dump("missed-t-propagations")
          << CommentCommand("Completeness check for T-propagations; expect invalid")
          << QueryCommand(atom.toExpr())
          << QueryCommand(atom.notNode().toExpr());
      }
    }
  }
}

bool TheoryEngine::properConflict(TNode conflict) const {
  bool value;
  if (conflict.getKind() == kind::AND) {
    for (unsigned i = 0; i < conflict.getNumChildren(); ++ i) {
      if (! getPropEngine()->hasValue(conflict[i], value)) {
        Debug("properConflict") << "Bad conflict is due to unassigned atom: "
                                << conflict[i] << endl;
        return false;
      }
      if (! value) {
        Debug("properConflict") << "Bad conflict is due to false atom: "
                                << conflict[i] << endl;
        return false;
      }
    }
  } else {
    if (! getPropEngine()->hasValue(conflict, value)) {
      Debug("properConflict") << "Bad conflict is due to unassigned atom: "
                              << conflict << endl;
      return false;
    }
    if(! value) {
      Debug("properConflict") << "Bad conflict is due to false atom: "
                              << conflict << endl;
      return false;
    }
  }
  return true;
}

bool TheoryEngine::properPropagation(TNode lit) const {
  if(!getPropEngine()->isTranslatedSatLiteral(lit)) {
    return false;
  }
  bool b;
  return !getPropEngine()->hasValue(lit, b);
}

bool TheoryEngine::properExplanation(TNode node, TNode expl) const {
  // Explanation must be either a conjunction of true literals that have true SAT values already
  // or a singled literal that has a true SAT value already.
  if (expl.getKind() == kind::AND) {
    for (unsigned i = 0; i < expl.getNumChildren(); ++ i) {
      bool value;
      if (!d_propEngine->hasValue(expl[i], value) || !value) {
        return false;
      }
    }
  } else {
    bool value;
    return d_propEngine->hasValue(expl, value) && value;
  }
  return true;
}

Node TheoryEngine::getValue(TNode node) {
  kind::MetaKind metakind = node.getMetaKind();

  // special case: prop engine handles boolean vars
  if(metakind == kind::metakind::VARIABLE && node.getType().isBoolean()) {
    return d_propEngine->getValue(node);
  }

  // special case: value of a constant == itself
  if(metakind == kind::metakind::CONSTANT) {
    return node;
  }

  // otherwise ask the theory-in-charge
  return theoryOf(node)->getValue(node);

}/* TheoryEngine::getValue(TNode node) */

bool TheoryEngine::presolve() {

  try {
    // Definition of the statement that is to be run by every theory
#ifdef CVC4_FOR_EACH_THEORY_STATEMENT
#undef CVC4_FOR_EACH_THEORY_STATEMENT
#endif
#define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
    if (theory::TheoryTraits<THEORY>::hasPresolve) { \
      reinterpret_cast<theory::TheoryTraits<THEORY>::theory_class*>(theoryOf(THEORY))->presolve(); \
      if(d_inConflict) { \
        return true; \
      } \
    }

    // Presolve for each theory using the statement above
    CVC4_FOR_EACH_THEORY;
  } catch(const theory::Interrupted&) {
    Trace("theory") << "TheoryEngine::presolve() => interrupted" << endl;
  }
  // return whether we have a conflict
  return false;
}/* TheoryEngine::presolve() */

void TheoryEngine::postsolve() {

  try {
    // Definition of the statement that is to be run by every theory
#ifdef CVC4_FOR_EACH_THEORY_STATEMENT
#undef CVC4_FOR_EACH_THEORY_STATEMENT
#endif
#define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
    if (theory::TheoryTraits<THEORY>::hasPostsolve) { \
      reinterpret_cast<theory::TheoryTraits<THEORY>::theory_class*>(theoryOf(THEORY))->postsolve(); \
      Assert(! d_inConflict, "conflict raised during postsolve()"); \
    }

    // Postsolve for each theory using the statement above
    CVC4_FOR_EACH_THEORY;
  } catch(const theory::Interrupted&) {
    Trace("theory") << "TheoryEngine::postsolve() => interrupted" << endl;
  }
}/* TheoryEngine::postsolve() */


void TheoryEngine::notifyRestart() {
  // Definition of the statement that is to be run by every theory
#ifdef CVC4_FOR_EACH_THEORY_STATEMENT
#undef CVC4_FOR_EACH_THEORY_STATEMENT
#endif
#define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
  if (theory::TheoryTraits<THEORY>::hasNotifyRestart && d_logicInfo.isTheoryEnabled(THEORY)) { \
    reinterpret_cast<theory::TheoryTraits<THEORY>::theory_class*>(theoryOf(THEORY))->notifyRestart(); \
  }

  // notify each theory using the statement above
  CVC4_FOR_EACH_THEORY;
}

void TheoryEngine::ppStaticLearn(TNode in, NodeBuilder<>& learned) {

  // Definition of the statement that is to be run by every theory
#ifdef CVC4_FOR_EACH_THEORY_STATEMENT
#undef CVC4_FOR_EACH_THEORY_STATEMENT
#endif
#define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
  if (theory::TheoryTraits<THEORY>::hasStaticLearning) { \
    reinterpret_cast<theory::TheoryTraits<THEORY>::theory_class*>(theoryOf(THEORY))->ppStaticLearn(in, learned); \
  }

  // static learning for each theory using the statement above
  CVC4_FOR_EACH_THEORY;
}

void TheoryEngine::shutdown() {
  // Set this first; if a Theory shutdown() throws an exception,
  // at least the destruction of the TheoryEngine won't confound
  // matters.
  d_hasShutDown = true;

  // Shutdown all the theories
  for(TheoryId theoryId = theory::THEORY_FIRST; theoryId < theory::THEORY_LAST; ++theoryId) {
    if(d_theoryTable[theoryId]) {
      theoryOf(static_cast<TheoryId>(theoryId))->shutdown();
    }
  }

  theory::Rewriter::shutdown();
  d_ppCache.clear();
}

theory::Theory::PPAssertStatus TheoryEngine::solve(TNode literal, SubstitutionMap& substitutionOut) {
  TNode atom = literal.getKind() == kind::NOT ? literal[0] : literal;
  Trace("theory::solve") << "TheoryEngine::solve(" << literal << "): solving with " << theoryOf(atom)->getId() << endl;
  Theory::PPAssertStatus solveStatus = theoryOf(atom)->ppAssert(literal, substitutionOut);
  Trace("theory::solve") << "TheoryEngine::solve(" << literal << ") => " << solveStatus << endl;
  return solveStatus;
}

// Recursively traverse a term and call the theory rewriter on its sub-terms
Node TheoryEngine::ppTheoryRewrite(TNode term)
{
  NodeMap::iterator find = d_ppCache.find(term);
  if (find != d_ppCache.end()) {
    return (*find).second;
  }
  unsigned nc = term.getNumChildren();
  if (nc == 0) {
    return theoryOf(term)->ppRewrite(term);
  }
  Trace("theory-pp") << "ppTheoryRewrite { " << term << endl;
  NodeBuilder<> newNode(term.getKind());
  if (term.getMetaKind() == kind::metakind::PARAMETERIZED) {
    newNode << term.getOperator();
  }
  unsigned i;
  for (i = 0; i < nc; ++i) {
    newNode << ppTheoryRewrite(term[i]);
  }
  Node newTerm = Rewriter::rewrite(Node(newNode));
  Node newTerm2 = theoryOf(newTerm)->ppRewrite(newTerm);
  if (newTerm != newTerm2) {
    newTerm = ppTheoryRewrite(Rewriter::rewrite(newTerm2));
  }
  d_ppCache[term] = newTerm;
  Trace("theory-pp")<< "ppTheoryRewrite returning " << newTerm << "}" << endl;
  return newTerm;
}


void TheoryEngine::preprocessStart()
{
  d_ppCache.clear();
}


struct preprocess_stack_element {
  TNode node;
  bool children_added;
  preprocess_stack_element(TNode node)
  : node(node), children_added(false) {}
};/* struct preprocess_stack_element */


Node TheoryEngine::preprocess(TNode assertion) {

  Trace("theory::preprocess") << "TheoryEngine::preprocess(" << assertion << ")" << endl;

  // Do a topological sort of the subexpressions and substitute them
  vector<preprocess_stack_element> toVisit;
  toVisit.push_back(assertion);

  while (!toVisit.empty())
  {
    // The current node we are processing
    preprocess_stack_element& stackHead = toVisit.back();
    TNode current = stackHead.node;

    Debug("theory::internal") << "TheoryEngine::preprocess(" << assertion << "): processing " << current << endl;

    // If node already in the cache we're done, pop from the stack
    NodeMap::iterator find = d_ppCache.find(current);
    if (find != d_ppCache.end()) {
      toVisit.pop_back();
      continue;
    }

    // If this is an atom, we preprocess its terms with the theory ppRewriter
    if (Theory::theoryOf(current) != THEORY_BOOL) {
      d_ppCache[current] = ppTheoryRewrite(current);
      continue;
    }

    // Not yet substituted, so process
    if (stackHead.children_added) {
      // Children have been processed, so substitute
      NodeBuilder<> builder(current.getKind());
      if (current.getMetaKind() == kind::metakind::PARAMETERIZED) {
        builder << current.getOperator();
      }
      for (unsigned i = 0; i < current.getNumChildren(); ++ i) {
        Assert(d_ppCache.find(current[i]) != d_ppCache.end());
        builder << d_ppCache[current[i]];
      }
      // Mark the substitution and continue
      Node result = builder;
      Debug("theory::internal") << "TheoryEngine::preprocess(" << assertion << "): setting " << current << " -> " << result << endl;
      d_ppCache[current] = result;
      toVisit.pop_back();
    } else {
      // Mark that we have added the children if any
      if (current.getNumChildren() > 0) {
        stackHead.children_added = true;
        // We need to add the children
        for(TNode::iterator child_it = current.begin(); child_it != current.end(); ++ child_it) {
          TNode childNode = *child_it;
          NodeMap::iterator childFind = d_ppCache.find(childNode);
          if (childFind == d_ppCache.end()) {
            toVisit.push_back(childNode);
          }
        }
      } else {
        // No children, so we're done
        Debug("substitution::internal") << "SubstitutionMap::internalSubstitute(" << assertion << "): setting " << current << " -> " << current << endl;
        d_ppCache[current] = current;
        toVisit.pop_back();
      }
    }
  }

  // Return the substituted version
  return d_ppCache[assertion];
}

void TheoryEngine::assertFact(TNode node)
{
  Trace("theory") << "TheoryEngine::assertFact(" << node << ")" << std::endl;
  // Trace("theory::assertions") << "TheoryEngine::assertFact(" << node << "): d_sharedTermsExist = " << (d_sharedTermsExist ? "true" : "false") << std::endl;

  d_propEngine->checkTime();

  // Get the atom
  bool negated = node.getKind() == kind::NOT;
  TNode atom = negated ? node[0] : node;
  Theory* theory = theoryOf(atom);

  if (d_logicInfo.isSharingEnabled()) {

    Trace("theory::assertions") << "TheoryEngine::assertFact(" << node << "): hasShared terms = " << (d_sharedTerms.hasSharedTerms(atom) ? "true" : "false") << std::endl;

    // If any shared terms, notify the theories
    if (d_sharedTerms.hasSharedTerms(atom)) {
      SharedTermsDatabase::shared_terms_iterator it = d_sharedTerms.begin(atom);
      SharedTermsDatabase::shared_terms_iterator it_end = d_sharedTerms.end(atom);
      for (; it != it_end; ++ it) {
        TNode term = *it;
        Theory::Set theories = d_sharedTerms.getTheoriesToNotify(atom, term);
        for (TheoryId id = THEORY_FIRST; id != THEORY_LAST; ++ id) {
          if (Theory::setContains(id, theories)) {
            theoryOf(id)->addSharedTermInternal(term);
          }
        }
        d_sharedTerms.markNotified(term, theories);
      }
      if (d_propagatedSharedLiterals.size() > 0) {
        Debug("theory") << "TheoryEngine::assertFact: distributing shared literals from new shared terms" << std::endl;
        outputSharedLiterals();
      }
    }

    if (atom.getKind() == kind::EQUAL &&
        d_sharedTerms.isShared(atom[0]) &&
        d_sharedTerms.isShared(atom[1])) {
      Debug("sharing") << "TheoryEngine::assertFact: asserting shared node: " << node << std::endl;
      // Important: don't let facts through that are already known by the shared terms database or we can get into a loop in explain
      if ((negated && d_sharedTerms.areDisequal(atom[0], atom[1])) ||
          ((!negated) && d_sharedTerms.areEqual(atom[0], atom[1]))) {
        Debug("sharing") << "TheoryEngine::assertFact: sharedLiteral already known(" << node << ")" << std::endl;
        return;
      }
      d_sharedLiteralsIn[node] = THEORY_LAST;
      d_sharedTerms.processSharedLiteral(node, node);
      if (d_propagatedSharedLiterals.size() > 0) {
        Debug("theory") << "TheoryEngine::assertFact: distributing shared literals from new assertion" << std::endl;
        outputSharedLiterals();
      }
      // TODO: have processSharedLiteral propagate disequalities?
      if (node.getKind() == kind::EQUAL) {
        // Don't have to assert it - this will be taken care of by processSharedLiteral
        Assert(d_logicInfo.isTheoryEnabled(theory->getId()));
        return;
      }
    }
    // If theory didn't already get this literal, add to the map
    NodeTheoryPair ntp(node, theory->getId());
    if (d_assertedLiteralsOut.find(ntp) == d_assertedLiteralsOut.end()) {
      d_assertedLiteralsOut[ntp] = Node();
    }
  }

  // Assert the fact to the appropriate theory and mark it active
  theory->assertFact(node, true);
  Assert(d_logicInfo.isTheoryEnabled(theory->getId()));
}

void TheoryEngine::propagate(TNode literal, theory::TheoryId theory) {

  Debug("theory") << "TheoryEngine::propagate(" << literal << ", " << theory << ")" << std::endl;

  d_propEngine->checkTime();

  if(Dump.isOn("t-propagations")) {
    Dump("t-propagations") << CommentCommand("negation of theory propagation: expect valid")
                           << QueryCommand(literal.toExpr());
  }
  if(Dump.isOn("missed-t-propagations")) {
    d_hasPropagated.insert(literal);
  }

  bool negated = (literal.getKind() == kind::NOT);
  TNode atom = negated ? literal[0] : literal;
  bool value;

  if (!d_logicInfo.isSharingEnabled() || atom.getKind() != kind::EQUAL ||
      !d_sharedTerms.isShared(atom[0]) || !d_sharedTerms.isShared(atom[1])) {
    // If not an equality or if an equality between terms that are not both shared,
    // it must be a SAT literal so we enqueue it
    Assert(d_propEngine->isSatLiteral(literal));
    if (d_propEngine->hasValue(literal, value)) {
      // if we are propagting something that already has a sat value we better be the same
      Debug("theory") << "literal " << literal << ") propagated by " << theory << " but already has a sat value " << (value ? "true" : "false") << std::endl;
      Assert(value);
    } else {
      d_propagatedLiterals.push_back(literal);
    }
  } else {
    // Important: don't let facts through that are already known by the shared terms database or we can get into a loop in explain
    if ((negated && d_sharedTerms.areDisequal(atom[0], atom[1])) ||
        ((!negated) && d_sharedTerms.areEqual(atom[0], atom[1]))) {
      Debug("sharing") << "TheoryEngine::propagate: sharedLiteral already known(" << literal << ")" << std::endl;
      return;
    }

    // Otherwise it is a shared-term (dis-)equality
    Node normalizedLiteral = Rewriter::rewrite(literal);
    if (d_propEngine->isSatLiteral(normalizedLiteral)) {
      // If there is a literal, propagate it to SAT
      SharedLiteral sharedLiteral(normalizedLiteral, literal, theory::THEORY_LAST);
      d_propagatedSharedLiterals.push_back(sharedLiteral);
    }
    // Assert to interested theories
    Debug("shared-in") << "TheoryEngine::propagate: asserting shared node: " << literal << std::endl;
    d_sharedLiteralsIn[literal] = theory;
    d_sharedTerms.processSharedLiteral(literal, literal);
  }
}


void TheoryEngine::propagateAsDecision(TNode literal, theory::TheoryId theory) {
  Debug("theory") << "EngineOutputChannel::propagateAsDecision(" << literal << ", " << theory << ")" << std::endl;

  d_propEngine->checkTime();

  Assert(d_propEngine->isSatLiteral(literal.getKind() == kind::NOT ? literal[0] : literal), "OutputChannel::propagateAsDecision() requires a SAT literal (or negation of one)");

  d_decisionRequests.push_back(literal);
}

theory::EqualityStatus TheoryEngine::getEqualityStatus(TNode a, TNode b) {
  Assert(a.getType() == b.getType());
  if (d_sharedTerms.isShared(a) && d_sharedTerms.isShared(b)) {
    if (d_sharedTerms.areEqual(a,b)) {
      return EQUALITY_TRUE_AND_PROPAGATED;
    }
    else if (d_sharedTerms.areDisequal(a,b)) {
      return EQUALITY_FALSE_AND_PROPAGATED;
    }
  }
  return theoryOf(Theory::theoryOf(a.getType()))->getEqualityStatus(a, b);
}

Node TheoryEngine::getExplanation(TNode node) {
  Debug("theory") << "TheoryEngine::getExplanation(" << node << ")" << std::endl;

  TNode atom = node.getKind() == kind::NOT ? node[0] : node;

  Node explanation;

  // The theory that has explaining to do
  Theory* theory;

  //This is true if atom is a shared assertion
  bool sharedLiteral = false;

  AssertedLiteralsOutMap::iterator find;
  // "find" will have a value when sharedAssertion is true
  if (d_logicInfo.isSharingEnabled() && atom.getKind() == kind::EQUAL) {
    find = d_assertedLiteralsOut.find(NodeTheoryPair(node, theory::THEORY_LAST));
    sharedLiteral = (find != d_assertedLiteralsOut.end());
  }

  // Get the explanation
  if(sharedLiteral) {
    explanation = explain(ExplainTask((*find).second, SHARED_LITERAL_OUT));
  } else {
    theory = theoryOf(atom);
    explanation = theory->explain(node);

    // Explain any shared equalities that might be in the explanation
    if (d_logicInfo.isSharingEnabled()) {
      explanation = explain(ExplainTask(explanation, THEORY_EXPLANATION, theory->getId()));
    }
  }

  Assert(!explanation.isNull());
  if(Dump.isOn("t-explanations")) {
    Dump("t-explanations") << CommentCommand(std::string("theory explanation from ") + theoryOf(atom)->identify() + ": expect valid")
      << QueryCommand(explanation.impNode(node).toExpr());
  }
  Assert(properExplanation(node, explanation));

  Debug("theory::explain") << "TheoryEngine::getExplanation(" << node << ") => " << explanation << std::endl;

  return explanation;
}

Node TheoryEngine::explain(ExplainTask toExplain)
{
  Debug("theory") << "TheoryEngine::explain(" << toExplain.node << ", " << toExplain.kind << ", " << toExplain.theory << ")" << std::endl;

  std::set<TNode> satAssertions;
  std::deque<ExplainTask> explainQueue;
  // TODO: benchmark whether this helps
  std::hash_set<ExplainTask, ExplainTaskHashFunction> explained;

#ifdef CVC4_ASSERTIONS
  bool value;
#endif

  // No need to explain "true"
  explained.insert(ExplainTask(d_true, SHARED_DATABASE_EXPLANATION));

  while (true) {

    Debug("theory-explain") << "TheoryEngine::explain(" << toExplain.node << ", " << toExplain.kind << ", " << toExplain.theory << ")" << std::endl;

    if (explained.find(toExplain) == explained.end()) {

      explained.insert(toExplain);

      if (toExplain.node.getKind() == kind::AND) {
        for (unsigned i = 0, i_end = toExplain.node.getNumChildren(); i != i_end; ++ i) {
          explainQueue.push_back(ExplainTask(toExplain.node[i], toExplain.kind, toExplain.theory));
        }
      }
      else {

        switch (toExplain.kind) {

          // toExplain.node contains a shared literal sent out from theory engine (before being rewritten)
          case SHARED_LITERAL_OUT: {
            // Shortcut - see if this came directly from a theory
            SharedLiteralsInMap::iterator it = d_sharedLiteralsIn.find(toExplain.node);
            if (it != d_sharedLiteralsIn.end()) {
              TheoryId id = (*it).second;
              if (id == theory::THEORY_LAST) {
                Assert(d_propEngine->isSatLiteral(toExplain.node));
                Assert(d_propEngine->hasValue(toExplain.node, value) && value);
                satAssertions.insert(toExplain.node);
                break;
              }
              explainQueue.push_back(ExplainTask(theoryOf((*it).second)->explain(toExplain.node), THEORY_EXPLANATION, (*it).second));
            }
            // Otherwise, get explanation from shared terms database
            else {
              explainQueue.push_back(ExplainTask(d_sharedTerms.explain(toExplain.node), SHARED_DATABASE_EXPLANATION));
            }
            break;
          }

            // toExplain.node contains explanation from theory, toExplain.theory contains theory that produced explanation
          case THEORY_EXPLANATION: {
            AssertedLiteralsOutMap::iterator find = d_assertedLiteralsOut.find(NodeTheoryPair(toExplain.node, toExplain.theory));
            if (find == d_assertedLiteralsOut.end() || (*find).second.isNull()) {
              Assert(d_propEngine->isSatLiteral(toExplain.node));
              Assert(d_propEngine->hasValue(toExplain.node, value) && value);
              satAssertions.insert(toExplain.node);
            }
            else {
              explainQueue.push_back(ExplainTask((*find).second, SHARED_LITERAL_OUT));
            }
            break;
          }

            // toExplain.node contains an explanation from the shared terms database
            // Each literal in the explanation should be in the d_sharedLiteralsIn map
          case SHARED_DATABASE_EXPLANATION: {
            Assert(d_sharedLiteralsIn.find(toExplain.node) != d_sharedLiteralsIn.end());
            TheoryId id = d_sharedLiteralsIn[toExplain.node];
            if (id == theory::THEORY_LAST) {
              Assert(d_propEngine->isSatLiteral(toExplain.node));
              Assert(d_propEngine->hasValue(toExplain.node, value) && value);
              satAssertions.insert(toExplain.node);
            }
            else {
              explainQueue.push_back(ExplainTask(theoryOf(id)->explain(toExplain.node), THEORY_EXPLANATION, id));
            }
            break;
          }        
          default:
            Unreachable();
        }
      }
    }

    if (explainQueue.empty()) break;

    toExplain = explainQueue.front();
    explainQueue.pop_front();
  }

  Assert(satAssertions.size() > 0);
  if (satAssertions.size() == 1) {
    return *(satAssertions.begin());
  }

  // Now build the explanation
  NodeBuilder<> conjunction(kind::AND);
  std::set<TNode>::const_iterator it = satAssertions.begin();
  std::set<TNode>::const_iterator it_end = satAssertions.end();
  while (it != it_end) {
    conjunction << *it;
    ++ it;
  }
  return conjunction;
}

void TheoryEngine::conflict(TNode conflict, TheoryId theoryId) {

  // Mark that we are in conflict
  d_inConflict = true;

  if(Dump.isOn("t-conflicts")) {
    Dump("t-conflicts") << CommentCommand("theory conflict: expect unsat")
                        << CheckSatCommand(conflict.toExpr());
  }

  if (d_logicInfo.isSharingEnabled()) {
    // In the multiple-theories case, we need to reconstruct the conflict
    Node fullConflict = explain(ExplainTask(conflict, THEORY_EXPLANATION, theoryId));
    Assert(properConflict(fullConflict));
    Debug("theory") << "TheoryEngine::conflict(" << conflict << ", " << theoryId << "): " << fullConflict << std::endl;
    lemma(fullConflict, true, false);
  } else {
    // When only one theory, the conflict should need no processing
    Assert(properConflict(conflict));
    lemma(conflict, true, false);
  }
}


//Conflict from shared terms database
void TheoryEngine::sharedConflict(TNode conflict) {
  // Mark that we are in conflict
  d_inConflict = true;

  if(Dump.isOn("t-conflicts")) {
    Dump("t-conflicts") << CommentCommand("theory conflict: expect unsat")
                        << CheckSatCommand(conflict.toExpr());
  }

  Node fullConflict = explain(ExplainTask(d_sharedTerms.explain(conflict), SHARED_DATABASE_EXPLANATION));
  Assert(properConflict(fullConflict));
  Debug("theory") << "TheoryEngine::sharedConflict(" << conflict << "): " << fullConflict << std::endl;
  lemma(fullConflict, true, false);
}


Node TheoryEngine::ppSimpITE(TNode assertion)
{
  Node result = d_iteSimplifier.simpITE(assertion);
  result = d_iteSimplifier.simplifyWithCare(result);
  result = Rewriter::rewrite(result);
  return result;
}


void TheoryEngine::ppUnconstrainedSimp(vector<Node>& assertions)
{
  d_unconstrainedSimp.processAssertions(assertions);
}
generated by cgit on debian on lair
contact matthew@masot.net with questions or feedback