GCC Code Coverage Report
Directory: . Exec Total Coverage
File: src/theory/datatypes/theory_datatypes.cpp Lines: 962 1125 85.5 %
Date: 2021-08-06 Branches: 2237 5150 43.4 %

Line Exec Source
1
/******************************************************************************
2
 * Top contributors (to current version):
3
 *   Andrew Reynolds, Morgan Deters, Mathias Preiner
4
 *
5
 * This file is part of the cvc5 project.
6
 *
7
 * Copyright (c) 2009-2021 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.
11
 * ****************************************************************************
12
 *
13
 * Implementation of the theory of datatypes.
14
 */
15
#include "theory/datatypes/theory_datatypes.h"
16
17
#include <map>
18
#include <sstream>
19
20
#include "base/check.h"
21
#include "expr/dtype.h"
22
#include "expr/dtype_cons.h"
23
#include "expr/kind.h"
24
#include "expr/skolem_manager.h"
25
#include "options/datatypes_options.h"
26
#include "options/quantifiers_options.h"
27
#include "options/smt_options.h"
28
#include "options/theory_options.h"
29
#include "proof/proof_node_manager.h"
30
#include "smt/logic_exception.h"
31
#include "theory/datatypes/datatypes_rewriter.h"
32
#include "theory/datatypes/theory_datatypes_type_rules.h"
33
#include "theory/datatypes/theory_datatypes_utils.h"
34
#include "theory/logic_info.h"
35
#include "theory/quantifiers_engine.h"
36
#include "theory/rewriter.h"
37
#include "theory/theory_model.h"
38
#include "theory/theory_state.h"
39
#include "theory/type_enumerator.h"
40
#include "theory/valuation.h"
41
42
using namespace std;
43
using namespace cvc5::kind;
44
using namespace cvc5::context;
45
46
namespace cvc5 {
47
namespace theory {
48
namespace datatypes {
49
50
9853
TheoryDatatypes::TheoryDatatypes(Context* c,
51
                                 UserContext* u,
52
                                 OutputChannel& out,
53
                                 Valuation valuation,
54
                                 const LogicInfo& logicInfo,
55
9853
                                 ProofNodeManager* pnm)
56
    : Theory(THEORY_DATATYPES, c, u, out, valuation, logicInfo, pnm),
57
      d_term_sk(u),
58
      d_labels(c),
59
      d_selector_apps(c),
60
      d_collectTermsCache(c),
61
      d_collectTermsCacheU(u),
62
      d_functionTerms(c),
63
      d_singleton_eq(u),
64
      d_lemmas_produced_c(u),
65
      d_sygusExtension(nullptr),
66
      d_state(c, u, valuation),
67
      d_im(*this, d_state, pnm),
68
9853
      d_notify(d_im, *this)
69
{
70
71
9853
  d_true = NodeManager::currentNM()->mkConst( true );
72
9853
  d_zero = NodeManager::currentNM()->mkConst( Rational(0) );
73
9853
  d_dtfCounter = 0;
74
75
  // indicate we are using the default theory state object
76
9853
  d_theoryState = &d_state;
77
9853
  d_inferManager = &d_im;
78
9853
}
79
80
29559
TheoryDatatypes::~TheoryDatatypes() {
81
35487
  for(std::map< Node, EqcInfo* >::iterator i = d_eqc_info.begin(), iend = d_eqc_info.end();
82
35487
      i != iend; ++i){
83
25634
    EqcInfo* current = (*i).second;
84
25634
    Assert(current != NULL);
85
25634
    delete current;
86
  }
87
19706
}
88
89
9853
TheoryRewriter* TheoryDatatypes::getTheoryRewriter() { return &d_rewriter; }
90
91
3768
ProofRuleChecker* TheoryDatatypes::getProofChecker() { return &d_checker; }
92
93
9853
bool TheoryDatatypes::needsEqualityEngine(EeSetupInfo& esi)
94
{
95
9853
  esi.d_notify = &d_notify;
96
9853
  esi.d_name = "theory::datatypes::ee";
97
  // need notifications on new constructors, merging datatype eqcs
98
9853
  esi.d_notifyNewClass = true;
99
9853
  esi.d_notifyMerge = true;
100
9853
  return true;
101
}
102
103
9853
void TheoryDatatypes::finishInit()
104
{
105
9853
  Assert(d_equalityEngine != nullptr);
106
  // The kinds we are treating as function application in congruence
107
9853
  d_equalityEngine->addFunctionKind(kind::APPLY_CONSTRUCTOR);
108
9853
  d_equalityEngine->addFunctionKind(kind::APPLY_SELECTOR_TOTAL);
109
9853
  d_equalityEngine->addFunctionKind(kind::APPLY_TESTER);
110
  // We could but don't do congruence for DT_SIZE and DT_HEIGHT_BOUND here.
111
  // It also could make sense in practice to do congruence for APPLY_UF, but
112
  // this is not done.
113
9853
  if (getQuantifiersEngine() && options::sygus())
114
  {
115
    quantifiers::TermDbSygus* tds =
116
1151
        getQuantifiersEngine()->getTermDatabaseSygus();
117
1151
    d_sygusExtension.reset(new SygusExtension(d_state, d_im, tds));
118
    // do congruence on evaluation functions
119
1151
    d_equalityEngine->addFunctionKind(kind::DT_SYGUS_EVAL);
120
  }
121
  // testers are not relevant for model building
122
9853
  d_valuation.setIrrelevantKind(APPLY_TESTER);
123
9853
}
124
125
2137738
TheoryDatatypes::EqcInfo* TheoryDatatypes::getOrMakeEqcInfo( TNode n, bool doMake ){
126
2137738
  if( !hasEqcInfo( n ) ){
127
455890
    if( doMake ){
128
      //add to labels
129
149463
      d_labels[ n ] = 0;
130
131
149463
      std::map< Node, EqcInfo* >::iterator eqc_i = d_eqc_info.find( n );
132
      EqcInfo* ei;
133
149463
      if( eqc_i != d_eqc_info.end() ){
134
123829
        ei = eqc_i->second;
135
      }else{
136
25634
        ei = new EqcInfo( getSatContext() );
137
25634
        d_eqc_info[n] = ei;
138
      }
139
149463
      if( n.getKind()==APPLY_CONSTRUCTOR ){
140
106887
        ei->d_constructor = n;
141
      }
142
143
      //add to selectors
144
149463
      d_selector_apps[n] = 0;
145
146
149463
      return ei;
147
    }else{
148
306427
      return NULL;
149
    }
150
  }else{
151
1681848
    std::map< Node, EqcInfo* >::iterator eqc_i = d_eqc_info.find( n );
152
1681848
    return (*eqc_i).second;
153
  }
154
}
155
156
571860
TNode TheoryDatatypes::getEqcConstructor( TNode r ) {
157
571860
  if( r.getKind()==APPLY_CONSTRUCTOR ){
158
357059
    return r;
159
  }else{
160
214801
    EqcInfo * ei = getOrMakeEqcInfo( r, false );
161
214801
    if( ei && !ei->d_constructor.get().isNull() ){
162
65046
      return ei->d_constructor.get();
163
    }else{
164
149755
      return r;
165
    }
166
  }
167
}
168
169
503222
bool TheoryDatatypes::preCheck(Effort level)
170
{
171
1006444
  Trace("datatypes-check") << "TheoryDatatypes::preCheck: " << level
172
503222
                           << std::endl;
173
503222
  d_im.process();
174
503222
  d_im.reset();
175
503222
  return false;
176
}
177
178
503222
void TheoryDatatypes::postCheck(Effort level)
179
{
180
1006444
  Trace("datatypes-check") << "TheoryDatatypes::postCheck: " << level
181
503222
                           << std::endl;
182
  // Apply any last pending inferences, which may occur if the last processed
183
  // fact was an internal one and triggered further internal inferences.
184
503222
  d_im.process();
185
503222
  if (level == EFFORT_LAST_CALL)
186
  {
187
5541
    Assert(d_sygusExtension != nullptr);
188
5541
    d_sygusExtension->check();
189
  }
190
1027436
  else if (level == EFFORT_FULL && !d_state.isInConflict()
191
529471
           && !d_im.hasSentLemma() && !d_valuation.needCheck())
192
  {
193
    //check for cycles
194
28106
    Assert(!d_im.hasPendingFact());
195
4
    do {
196
28110
      d_im.reset();
197
28110
      Trace("datatypes-proc") << "Check cycles..." << std::endl;
198
28110
      checkCycles();
199
28110
      Trace("datatypes-proc") << "...finish check cycles" << std::endl;
200
28110
      d_im.process();
201
28110
      if (d_state.isInConflict() || d_im.hasSentLemma())
202
      {
203
143
        return;
204
      }
205
27967
    } while (d_im.hasSentFact());
206
207
    //check for splits
208
27963
    Trace("datatypes-debug") << "Check for splits " << endl;
209
1484
    do {
210
29447
      d_im.reset();
211
58894
      std::map< TypeNode, Node > rec_singletons;
212
29447
      eq::EqClassesIterator eqcs_i = eq::EqClassesIterator(d_equalityEngine);
213
1018515
      while( !eqcs_i.isFinished() ){
214
990361
        Node n = (*eqcs_i);
215
        //TODO : avoid irrelevant (pre-registered but not asserted) terms here?
216
990361
        TypeNode tn = n.getType();
217
495827
        if( tn.isDatatype() ){
218
171044
          Trace("datatypes-debug") << "Process equivalence class " << n << std::endl;
219
171044
          EqcInfo* eqc = getOrMakeEqcInfo( n );
220
          //if there are more than 1 possible constructors for eqc
221
171044
          if( !hasLabel( eqc, n ) ){
222
39346
            Trace("datatypes-debug") << "No constructor..." << std::endl;
223
77399
            TypeNode tt = tn;
224
39346
            const DType& dt = tt.getDType();
225
78692
            Trace("datatypes-debug")
226
78692
                << "Datatype " << dt.getName() << " is "
227
78692
                << dt.getCardinalityClass(tt) << " "
228
39346
                << dt.isRecursiveSingleton(tt) << std::endl;
229
39346
            bool continueProc = true;
230
39346
            if( dt.isRecursiveSingleton( tt ) ){
231
8
              Trace("datatypes-debug") << "Check recursive singleton..." << std::endl;
232
              //handle recursive singleton case
233
8
              std::map< TypeNode, Node >::iterator itrs = rec_singletons.find( tn );
234
8
              if( itrs!=rec_singletons.end() ){
235
8
                Node eq = n.eqNode( itrs->second );
236
4
                if( d_singleton_eq.find( eq )==d_singleton_eq.end() ){
237
4
                  d_singleton_eq[eq] = true;
238
                  // get assumptions
239
4
                  bool success = true;
240
8
                  std::vector< Node > assumptions;
241
                  //if there is at least one uninterpreted sort occurring within the datatype and the logic is not quantified, add lemmas ensuring cardinality is more than one,
242
                  //  do not infer the equality if at least one sort was processed.
243
                  //otherwise, if the logic is quantified, under the assumption that all uninterpreted sorts have cardinality one,
244
                  //  infer the equality.
245
4
                  for( unsigned i=0; i<dt.getNumRecursiveSingletonArgTypes( tt ); i++ ){
246
                    TypeNode type = dt.getRecursiveSingletonArgType(tt, i);
247
                    if( getQuantifiersEngine() ){
248
                      // under the assumption that the cardinality of this type is one
249
                      Node a = getSingletonLemma(type, true);
250
                      assumptions.push_back( a.negate() );
251
                    }else{
252
                      success = false;
253
                      // assert that the cardinality of this type is more than one
254
                      getSingletonLemma(type, false);
255
                    }
256
                  }
257
4
                  if( success ){
258
8
                    Node assumption = n.eqNode(itrs->second);
259
4
                    assumptions.push_back(assumption);
260
8
                    Node lemma = assumptions.size()==1 ? assumptions[0] : NodeManager::currentNM()->mkNode( OR, assumptions );
261
4
                    Trace("dt-singleton") << "*************Singleton equality lemma " << lemma << std::endl;
262
4
                    d_im.lemma(lemma, InferenceId::DATATYPES_REC_SINGLETON_EQ);
263
                  }
264
                }
265
              }else{
266
4
                rec_singletons[tn] = n;
267
              }
268
              //do splitting for quantified logics (incomplete anyways)
269
8
              continueProc = ( getQuantifiersEngine()!=NULL );
270
            }
271
39346
            if( continueProc ){
272
39346
              Trace("datatypes-debug") << "Get possible cons..." << std::endl;
273
              //all other cases
274
77399
              std::vector< bool > pcons;
275
39346
              getPossibleCons( eqc, n, pcons );
276
              //check if we do not need to resolve the constructor type for this equivalence class.
277
              // this is if there are no selectors for this equivalence class, and its possible values are infinite,
278
              //  then do not split.
279
39346
              int consIndex = -1;
280
39346
              int fconsIndex = -1;
281
39346
              bool needSplit = true;
282
143262
              for (size_t j = 0, psize = pcons.size(); j < psize; j++)
283
              {
284
103916
                if( pcons[j] ) {
285
102674
                  if( consIndex==-1 ){
286
39240
                    consIndex = j;
287
                  }
288
205348
                  Trace("datatypes-debug") << j << " compute finite..."
289
102674
                                           << std::endl;
290
                  // Notice that we split here on all datatypes except the
291
                  // truly infinite ones. It is possible to also not split
292
                  // on those that are interpreted-finite when finite model
293
                  // finding is disabled, but as a heuristic we choose to split
294
                  // on those too.
295
205348
                  bool ifin = dt[j].getCardinalityClass(tt)
296
102674
                              != CardinalityClass::INFINITE;
297
205348
                  Trace("datatypes-debug") << "...returned " << ifin
298
102674
                                           << std::endl;
299
102674
                  if (!ifin)
300
                  {
301
62279
                    if( !eqc || !eqc->d_selectors ){
302
56803
                      needSplit = false;
303
                    }
304
                  }else{
305
40395
                    if( fconsIndex==-1 ){
306
30597
                      fconsIndex = j;
307
                    }
308
                  }
309
                }
310
              }
311
              //if we want to force an assignment of constructors to all ground eqc
312
              //d_dtfCounter++;
313
59542
              if( !needSplit && options::dtForceAssignment() && d_dtfCounter%2==0 ){
314
                Trace("datatypes-force-assign") << "Force assignment for " << n << std::endl;
315
                needSplit = true;
316
                consIndex = fconsIndex!=-1 ? fconsIndex : consIndex;
317
              }
318
319
39346
              if( needSplit ) {
320
19150
                if( dt.getNumConstructors()==1 ){
321
                  //this may not be necessary?
322
                  //if only one constructor, then this term must be this constructor
323
35714
                  Node t = utils::mkTester(n, 0, dt);
324
17857
                  d_im.addPendingInference(
325
                      t, InferenceId::DATATYPES_SPLIT, d_true);
326
17857
                  Trace("datatypes-infer") << "DtInfer : 1-cons (full) : " << t << std::endl;
327
                }else{
328
1293
                  Assert(consIndex != -1 || dt.isSygus());
329
2586
                  if( options::dtBinarySplit() && consIndex!=-1 ){
330
                    Node test = utils::mkTester(n, consIndex, dt);
331
                    Trace("dt-split") << "*************Split for possible constructor " << dt[consIndex] << " for " << n << endl;
332
                    test = Rewriter::rewrite( test );
333
                    NodeBuilder nb(kind::OR);
334
                    nb << test << test.notNode();
335
                    Node lemma = nb;
336
                    d_im.lemma(lemma, InferenceId::DATATYPES_BINARY_SPLIT);
337
                    d_im.requirePhase(test, true);
338
                  }else{
339
1293
                    Trace("dt-split") << "*************Split for constructors on " << n <<  endl;
340
2586
                    Node lemma = utils::mkSplit(n, dt);
341
1293
                    Trace("dt-split-debug") << "Split lemma is : " << lemma << std::endl;
342
1293
                    d_im.sendDtLemma(lemma,
343
                                     InferenceId::DATATYPES_SPLIT,
344
                                     LemmaProperty::SEND_ATOMS);
345
                  }
346
2586
                  if( !options::dtBlastSplits() ){
347
1293
                    break;
348
                  }
349
                }
350
              }else{
351
20196
                Trace("dt-split-debug") << "Do not split constructor for " << n << " : " << n.getType() << " " << dt.getNumConstructors() << std::endl;
352
              }
353
            }
354
          }else{
355
131698
            Trace("datatypes-debug") << "Has constructor " << eqc->d_constructor.get() << std::endl;
356
          }
357
        }
358
494534
        ++eqcs_i;
359
      }
360
29447
      if (d_im.hasSentLemma())
361
      {
362
        // clear pending facts: we added a lemma, so internal inferences are
363
        // no longer necessary
364
1250
        d_im.clearPendingFacts();
365
      }
366
      else
367
      {
368
        // we did not add a lemma, process internal inferences. This loop
369
        // will repeat.
370
28197
        Trace("datatypes-debug") << "Flush pending facts..." << std::endl;
371
28197
        d_im.process();
372
      }
373
57819
    } while (!d_state.isInConflict() && !d_im.hasSentLemma()
374
56275
             && d_im.hasSentFact());
375
55926
    Trace("datatypes-debug")
376
55926
        << "Finished, conflict=" << d_state.isInConflict()
377
27963
        << ", lemmas=" << d_im.hasSentLemma() << std::endl;
378
27963
    if (!d_state.isInConflict())
379
    {
380
26888
      Trace("dt-model-debug") << std::endl;
381
26888
      printModelDebug("dt-model-debug");
382
    }
383
  }
384
385
503079
  Trace("datatypes-check") << "Finished check effort " << level << std::endl;
386
503079
  if( Debug.isOn("datatypes") || Debug.isOn("datatypes-split") ) {
387
    Notice() << "TheoryDatatypes::check(): done" << endl;
388
  }
389
}
390
391
11041
bool TheoryDatatypes::needsCheckLastEffort() {
392
11041
  return d_sygusExtension != nullptr;
393
}
394
395
1760502
void TheoryDatatypes::notifyFact(TNode atom,
396
                                 bool polarity,
397
                                 TNode fact,
398
                                 bool isInternal)
399
{
400
3521004
  Trace("datatypes-debug") << "TheoryDatatypes::assertFact : " << fact
401
1760502
                           << ", isInternal = " << isInternal << std::endl;
402
  // could be sygus-specific
403
1760502
  if (d_sygusExtension)
404
  {
405
1399051
    d_sygusExtension->assertFact(atom, polarity);
406
  }
407
  //add to tester if applicable
408
3521004
  Node t_arg;
409
1760502
  int tindex = utils::isTester(atom, t_arg);
410
1760502
  if (tindex >= 0)
411
  {
412
763950
    Trace("dt-tester") << "Assert tester : " << atom << " for " << t_arg << std::endl;
413
1527900
    Node rep = getRepresentative( t_arg );
414
763950
    EqcInfo* eqc = getOrMakeEqcInfo( rep, true );
415
    Node tst =
416
1527900
        isInternal ? (polarity ? Node(atom) : atom.notNode()) : Node(fact);
417
763950
    addTester(tindex, tst, eqc, rep, t_arg);
418
763950
    Trace("dt-tester") << "Done assert tester." << std::endl;
419
763950
    Trace("dt-tester") << "Done pending merges." << std::endl;
420
763950
    if (!d_state.isInConflict() && polarity)
421
    {
422
221291
      if (d_sygusExtension)
423
      {
424
170890
        Trace("dt-tester") << "Assert tester to sygus : " << atom << std::endl;
425
170890
        d_sygusExtension->assertTester(tindex, t_arg, atom);
426
170890
        Trace("dt-tester") << "Done assert tester to sygus." << std::endl;
427
      }
428
    }
429
  }else{
430
996552
    Trace("dt-tester-debug") << "Assert (non-tester) : " << atom << std::endl;
431
  }
432
1760502
  Trace("datatypes-debug") << "TheoryDatatypes::assertFact : finished " << fact << std::endl;
433
  // now, flush pending facts if this wasn't an internal call
434
1760502
  if (!isInternal)
435
  {
436
1471099
    d_im.process();
437
  }
438
1760502
}
439
440
171169
void TheoryDatatypes::preRegisterTerm(TNode n)
441
{
442
342338
  Trace("datatypes-prereg")
443
171169
      << "TheoryDatatypes::preRegisterTerm() " << n << endl;
444
  // external selectors should be preprocessed away by now
445
171169
  Assert(n.getKind() != APPLY_SELECTOR);
446
  // must ensure the type is well founded and has no nested recursion if
447
  // the option dtNestedRec is not set to true.
448
342338
  TypeNode tn = n.getType();
449
171169
  if (tn.isDatatype())
450
  {
451
67708
    const DType& dt = tn.getDType();
452
67708
    Trace("dt-expand") << "Check properties of " << dt.getName() << std::endl;
453
67708
    if (!dt.isWellFounded())
454
    {
455
      std::stringstream ss;
456
      ss << "Cannot handle non-well-founded datatype " << dt.getName();
457
      throw LogicException(ss.str());
458
    }
459
67708
    Trace("dt-expand") << "...well-founded ok" << std::endl;
460
135416
    if (!options::dtNestedRec())
461
    {
462
67480
      if (dt.hasNestedRecursion())
463
      {
464
2
        std::stringstream ss;
465
1
        ss << "Cannot handle nested-recursive datatype " << dt.getName();
466
1
        throw LogicException(ss.str());
467
      }
468
67479
      Trace("dt-expand") << "...nested recursion ok" << std::endl;
469
    }
470
  }
471
171168
  collectTerms( n );
472
171168
  switch (n.getKind()) {
473
77634
  case kind::EQUAL:
474
  case kind::APPLY_TESTER:
475
    // add predicate trigger for testers and equalities
476
    // Get triggered for both equal and dis-equal
477
77634
    d_equalityEngine->addTriggerPredicate(n);
478
77634
    break;
479
93534
  default:
480
    // Function applications/predicates
481
93534
    d_equalityEngine->addTerm(n);
482
93534
    if (d_sygusExtension)
483
    {
484
21388
      d_sygusExtension->preRegisterTerm(n);
485
    }
486
93534
    break;
487
  }
488
171168
  d_im.process();
489
171168
}
490
491
80972
TrustNode TheoryDatatypes::ppRewrite(TNode in, std::vector<SkolemLemma>& lems)
492
{
493
80972
  Debug("tuprec") << "TheoryDatatypes::ppRewrite(" << in << ")" << endl;
494
  // first, see if we need to expand definitions
495
161944
  TrustNode texp = d_rewriter.expandDefinition(in);
496
80972
  if (!texp.isNull())
497
  {
498
4360
    return texp;
499
  }
500
76612
  if( in.getKind()==EQUAL ){
501
8282
    Node nn;
502
8282
    std::vector< Node > rew;
503
4187
    if (utils::checkClash(in[0], in[1], rew))
504
    {
505
      nn = NodeManager::currentNM()->mkConst(false);
506
    }
507
    else
508
    {
509
12489
      nn = rew.size()==0 ? d_true :
510
8302
                ( rew.size()==1 ? rew[0] : NodeManager::currentNM()->mkNode( kind::AND, rew ) );
511
    }
512
4187
    if (in != nn)
513
    {
514
92
      return TrustNode::mkTrustRewrite(in, nn, nullptr);
515
    }
516
  }
517
518
  // nothing to do
519
76520
  return TrustNode::null();
520
}
521
522
48567
TrustNode TheoryDatatypes::explain(TNode literal)
523
{
524
48567
  return d_im.explainLit(literal);
525
}
526
527
/** called when a new equivalance class is created */
528
302918
void TheoryDatatypes::eqNotifyNewClass(TNode t){
529
302918
  if( t.getKind()==APPLY_CONSTRUCTOR ){
530
106887
    getOrMakeEqcInfo( t, true );
531
  }
532
302918
}
533
534
/** called when two equivalance classes have merged */
535
1957300
void TheoryDatatypes::eqNotifyMerge(TNode t1, TNode t2)
536
{
537
1957300
  if( t1.getType().isDatatype() ){
538
912894
    Trace("datatypes-merge")
539
456447
        << "NotifyMerge : " << t1 << " " << t2 << std::endl;
540
456447
    merge(t1, t2);
541
  }
542
1957300
}
543
544
456447
void TheoryDatatypes::merge( Node t1, Node t2 ){
545
456447
  if (!d_state.isInConflict())
546
  {
547
456304
    Trace("datatypes-merge") << "Merge " << t1 << " " << t2 << std::endl;
548
456304
    Assert(areEqual(t1, t2));
549
911193
    TNode trep1 = t1;
550
911193
    TNode trep2 = t2;
551
456304
    EqcInfo* eqc2 = getOrMakeEqcInfo( t2 );
552
456304
    if( eqc2 ){
553
337295
      bool checkInst = false;
554
337295
      if( !eqc2->d_constructor.get().isNull() ){
555
107932
        trep2 = eqc2->d_constructor.get();
556
      }
557
337295
      EqcInfo* eqc1 = getOrMakeEqcInfo( t1 );
558
337295
      if( eqc1 ){
559
325872
        Trace("datatypes-debug") << "  merge eqc info " << eqc2 << " into " << eqc1 << std::endl;
560
325872
        if( !eqc1->d_constructor.get().isNull() ){
561
270141
          trep1 = eqc1->d_constructor.get();
562
        }
563
        //check for clash
564
650720
        TNode cons1 = eqc1->d_constructor.get();
565
650720
        TNode cons2 = eqc2->d_constructor.get();
566
        //if both have constructor, then either clash or unification
567
325872
        if( !cons1.isNull() && !cons2.isNull() ){
568
63652
          Trace("datatypes-debug") << "  constructors : " << cons1 << " " << cons2 << std::endl;
569
126285
          Node unifEq = cons1.eqNode( cons2 );
570
126285
          std::vector< Node > rew;
571
63652
          if (utils::checkClash(cons1, cons2, rew))
572
          {
573
2038
            std::vector<Node> conf;
574
1019
            conf.push_back(unifEq);
575
2038
            Trace("dt-conflict")
576
1019
                << "CONFLICT: Clash conflict : " << conf << std::endl;
577
1019
            d_im.sendDtConflict(conf, InferenceId::DATATYPES_CLASH_CONFLICT);
578
1019
            return;
579
          }
580
          else
581
          {
582
62633
            Assert(areEqual(cons1, cons2));
583
            //do unification
584
182801
            for( int i=0; i<(int)cons1.getNumChildren(); i++ ) {
585
120168
              if( !areEqual( cons1[i], cons2[i] ) ){
586
67336
                Node eq = cons1[i].eqNode( cons2[i] );
587
33668
                d_im.addPendingInference(
588
                    eq, InferenceId::DATATYPES_UNIF, unifEq);
589
33668
                Trace("datatypes-infer") << "DtInfer : cons-inj : " << eq << " by " << unifEq << std::endl;
590
              }
591
            }
592
          }
593
        }
594
324853
        Trace("datatypes-debug") << "  instantiated : " << eqc1->d_inst << " " << eqc2->d_inst << std::endl;
595
324853
        eqc1->d_inst = eqc1->d_inst || eqc2->d_inst;
596
324853
        if( !cons2.isNull() ){
597
100820
          if( cons1.isNull() ){
598
38187
            Trace("datatypes-debug") << "  must check if it is okay to set the constructor." << std::endl;
599
38187
            checkInst = true;
600
38187
            addConstructor( eqc2->d_constructor.get(), eqc1, t1 );
601
38187
            if (d_state.isInConflict())
602
            {
603
5
              return;
604
            }
605
          }
606
        }
607
      }else{
608
11423
        Trace("datatypes-debug") << "  no eqc info for " << t1 << ", must create" << std::endl;
609
        //just copy the equivalence class information
610
11423
        eqc1 = getOrMakeEqcInfo( t1, true );
611
11423
        eqc1->d_inst.set( eqc2->d_inst );
612
11423
        eqc1->d_constructor.set( eqc2->d_constructor );
613
11423
        eqc1->d_selectors.set( eqc2->d_selectors );
614
      }
615
616
617
      //merge labels
618
336271
      NodeUIntMap::iterator lbl_i = d_labels.find(t2);
619
336271
      if( lbl_i != d_labels.end() ){
620
336271
        Trace("datatypes-debug") << "  merge labels from " << eqc2 << " " << t2 << std::endl;
621
336271
        size_t n_label = (*lbl_i).second;
622
583824
        for (size_t i = 0; i < n_label; i++)
623
        {
624
247944
          Assert(i < d_labels_data[t2].size());
625
495497
          Node t = d_labels_data[ t2 ][i];
626
495497
          Node t_arg = d_labels_args[t2][i];
627
247944
          unsigned tindex = d_labels_tindex[t2][i];
628
247944
          addTester( tindex, t, eqc1, t1, t_arg );
629
247944
          if (d_state.isInConflict())
630
          {
631
391
            Trace("datatypes-debug") << "  conflict!" << std::endl;
632
391
            return;
633
          }
634
        }
635
636
      }
637
      //merge selectors
638
335880
      if( !eqc1->d_selectors && eqc2->d_selectors ){
639
51581
        eqc1->d_selectors = true;
640
51581
        checkInst = true;
641
      }
642
335880
      NodeUIntMap::iterator sel_i = d_selector_apps.find(t2);
643
335880
      if( sel_i != d_selector_apps.end() ){
644
335880
        Trace("datatypes-debug") << "  merge selectors from " << eqc2 << " " << t2 << std::endl;
645
335880
        size_t n_sel = (*sel_i).second;
646
759008
        for (size_t j = 0; j < n_sel; j++)
647
        {
648
423128
          addSelector( d_selector_apps_data[t2][j], eqc1, t1, eqc2->d_constructor.get().isNull() );
649
        }
650
      }
651
335880
      if( checkInst ){
652
89763
        Trace("datatypes-debug") << "  checking instantiate" << std::endl;
653
89763
        instantiate( eqc1, t1 );
654
89763
        if (d_state.isInConflict())
655
        {
656
          return;
657
        }
658
      }
659
    }
660
454889
    Trace("datatypes-debug") << "Finished Merge " << t1 << " " << t2 << std::endl;
661
  }
662
}
663
664
25634
TheoryDatatypes::EqcInfo::EqcInfo( context::Context* c )
665
    : d_inst( c, false )
666
51268
    , d_constructor( c, Node::null() )
667
76902
    , d_selectors( c, false )
668
25634
{}
669
670
171044
bool TheoryDatatypes::hasLabel( EqcInfo* eqc, Node n ){
671
171044
  return ( eqc && !eqc->d_constructor.get().isNull() ) || !getLabel( n ).isNull();
672
}
673
674
667411
Node TheoryDatatypes::getLabel( Node n ) {
675
667411
  NodeUIntMap::iterator lbl_i = d_labels.find(n);
676
667411
  if( lbl_i != d_labels.end() ){
677
605565
    size_t n_lbl = (*lbl_i).second;
678
605565
    if( n_lbl>0 && d_labels_data[n][ n_lbl-1 ].getKind()!=kind::NOT ){
679
208336
      return d_labels_data[n][ n_lbl-1 ];
680
    }
681
  }
682
459075
  return Node::null();
683
}
684
685
1282063
int TheoryDatatypes::getLabelIndex( EqcInfo* eqc, Node n ){
686
1282063
  if( eqc && !eqc->d_constructor.get().isNull() ){
687
757491
    return utils::indexOf(eqc->d_constructor.get().getOperator());
688
  }else{
689
1049144
    Node lbl = getLabel( n );
690
524572
    if( lbl.isNull() ){
691
419729
      return -1;
692
    }else{
693
104843
      int tindex = utils::isTester(lbl);
694
209686
      Trace("datatypes-debug") << "Label of " << n << " is " << lbl
695
104843
                               << " with tindex " << tindex << std::endl;
696
104843
      Assert(tindex != -1);
697
104843
      return tindex;
698
    }
699
  }
700
}
701
702
8469
bool TheoryDatatypes::hasTester( Node n ) {
703
8469
  NodeUIntMap::iterator lbl_i = d_labels.find(n);
704
8469
  if( lbl_i != d_labels.end() ){
705
    return (*lbl_i).second>0;
706
  }else{
707
8469
    return false;
708
  }
709
}
710
711
77380
void TheoryDatatypes::getPossibleCons( EqcInfo* eqc, Node n, std::vector< bool >& pcons ){
712
154760
  TypeNode tn = n.getType();
713
77380
  const DType& dt = tn.getDType();
714
77380
  int lindex = getLabelIndex( eqc, n );
715
77380
  pcons.resize( dt.getNumConstructors(), lindex==-1 );
716
77380
  if( lindex!=-1 ){
717
    pcons[ lindex ] = true;
718
  }else{
719
77380
    NodeUIntMap::iterator lbl_i = d_labels.find(n);
720
77380
    if( lbl_i != d_labels.end() ){
721
46457
      size_t n_lbl = (*lbl_i).second;
722
228821
      for (size_t i = 0; i < n_lbl; i++)
723
      {
724
182364
        Assert(d_labels_data[n][i].getKind() == NOT);
725
182364
        unsigned tindex = d_labels_tindex[n][i];
726
182364
        pcons[ tindex ] = false;
727
      }
728
    }
729
  }
730
77380
}
731
732
116954
Node TheoryDatatypes::getTermSkolemFor( Node n ) {
733
116954
  if( n.getKind()==APPLY_CONSTRUCTOR ){
734
13928
    NodeMap::const_iterator it = d_term_sk.find( n );
735
13928
    if( it==d_term_sk.end() ){
736
1319
      NodeManager* nm = NodeManager::currentNM();
737
1319
      SkolemManager* sm = nm->getSkolemManager();
738
      //add purification unit lemma ( k = n )
739
2638
      Node k = sm->mkPurifySkolem(n, "kdt");
740
1319
      d_term_sk[n] = k;
741
2638
      Node eq = k.eqNode( n );
742
1319
      Trace("datatypes-infer") << "DtInfer : ref : " << eq << std::endl;
743
1319
      d_im.addPendingLemma(eq, InferenceId::DATATYPES_PURIFY);
744
1319
      return k;
745
    }else{
746
12609
      return (*it).second;
747
    }
748
  }else{
749
103026
    return n;
750
  }
751
}
752
753
1011894
void TheoryDatatypes::addTester(
754
    unsigned ttindex, Node t, EqcInfo* eqc, Node n, Node t_arg)
755
{
756
1011894
  Trace("datatypes-debug") << "Add tester : " << t << " to eqc(" << n << ")" << std::endl;
757
1011894
  Debug("datatypes-labels") << "Add tester " << t << " " << n << " " << eqc << std::endl;
758
1011894
  bool tpolarity = t.getKind()!=NOT;
759
1011894
  Assert((tpolarity ? t : t[0]).getKind() == APPLY_TESTER);
760
1297861
  Node j, jt;
761
1011894
  bool makeConflict = false;
762
1011894
  int prevTIndex = getLabelIndex(eqc, n);
763
1011894
  if (prevTIndex >= 0)
764
  {
765
669724
    unsigned ptu = static_cast<unsigned>(prevTIndex);
766
    //if we already know the constructor type, check whether it is in conflict or redundant
767
669724
    if ((ptu == ttindex) != tpolarity)
768
    {
769
1228
      if( !eqc->d_constructor.get().isNull() ){
770
        //conflict because equivalence class contains a constructor
771
2456
        std::vector<Node> conf;
772
1228
        conf.push_back(t);
773
1228
        conf.push_back(t_arg.eqNode(eqc->d_constructor.get()));
774
2456
        Trace("dt-conflict")
775
1228
            << "CONFLICT: Tester eq conflict " << conf << std::endl;
776
1228
        d_im.sendDtConflict(conf, InferenceId::DATATYPES_TESTER_CONFLICT);
777
1228
        return;
778
      }else{
779
        makeConflict = true;
780
        //conflict because the existing label is contradictory
781
        j = getLabel( n );
782
        jt = j;
783
      }
784
    }else{
785
668496
      return;
786
    }
787
  }else{
788
    //otherwise, scan list of labels
789
342170
    NodeUIntMap::iterator lbl_i = d_labels.find(n);
790
342170
    Assert(lbl_i != d_labels.end());
791
342170
    size_t n_lbl = (*lbl_i).second;
792
628137
    std::map< int, bool > neg_testers;
793
1266892
    for (size_t i = 0; i < n_lbl; i++)
794
    {
795
942999
      Assert(d_labels_data[n][i].getKind() == NOT);
796
942999
      unsigned jtindex = d_labels_tindex[n][i];
797
942999
      if( jtindex==ttindex ){
798
18277
        if( tpolarity ){  //we are in conflict
799
108
          j = d_labels_data[n][i];
800
108
          jt = j[0];
801
108
          makeConflict = true;
802
108
          break;
803
        }else{            //it is redundant
804
18169
          return;
805
        }
806
      }else{
807
924722
        neg_testers[jtindex] = true;
808
      }
809
    }
810
324001
    if( !makeConflict ){
811
323893
      Debug("datatypes-labels") << "Add to labels " << t << std::endl;
812
323893
      d_labels[n] = n_lbl + 1;
813
323893
      if (n_lbl < d_labels_data[n].size())
814
      {
815
        // reuse spot in the vector
816
312929
        d_labels_data[n][n_lbl] = t;
817
312929
        d_labels_args[n][n_lbl] = t_arg;
818
312929
        d_labels_tindex[n][n_lbl] = ttindex;
819
      }else{
820
10964
        d_labels_data[n].push_back(t);
821
10964
        d_labels_args[n].push_back(t_arg);
822
10964
        d_labels_tindex[n].push_back(ttindex);
823
      }
824
323893
      n_lbl++;
825
826
323893
      const DType& dt = t_arg.getType().getDType();
827
323893
      Debug("datatypes-labels") << "Labels at " << n_lbl << " / " << dt.getNumConstructors() << std::endl;
828
323893
      if( tpolarity ){
829
103026
        instantiate( eqc, n );
830
        // We could propagate is-C1(x) => not is-C2(x) here for all other
831
        // constructors, but empirically this hurts performance.
832
      }else{
833
        //check if we have reached the maximum number of testers
834
        // in this case, add the positive tester
835
220867
        if (n_lbl == dt.getNumConstructors() - 1)
836
        {
837
76068
          std::vector< bool > pcons;
838
38034
          getPossibleCons( eqc, n, pcons );
839
38034
          int testerIndex = -1;
840
122213
          for( unsigned i=0; i<pcons.size(); i++ ) {
841
122213
            if( pcons[i] ){
842
38034
              testerIndex = i;
843
38034
              break;
844
            }
845
          }
846
38034
          Assert(testerIndex != -1);
847
          //we must explain why each term in the set of testers for this equivalence class is equal
848
76068
          std::vector< Node > eq_terms;
849
76068
          NodeBuilder nb(kind::AND);
850
219156
          for (unsigned i = 0; i < n_lbl; i++)
851
          {
852
362244
            Node ti = d_labels_data[n][i];
853
181122
            nb << ti;
854
181122
            Assert(ti.getKind() == NOT);
855
362244
            Node t_arg2 = d_labels_args[n][i];
856
181122
            if( std::find( eq_terms.begin(), eq_terms.end(), t_arg2 )==eq_terms.end() ){
857
43047
              eq_terms.push_back( t_arg2 );
858
43047
              if( t_arg2!=t_arg ){
859
5013
                nb << t_arg2.eqNode( t_arg );
860
              }
861
            }
862
          }
863
          Node t_concl = testerIndex == -1
864
                             ? NodeManager::currentNM()->mkConst(false)
865
76068
                             : utils::mkTester(t_arg, testerIndex, dt);
866
76068
          Node t_concl_exp = ( nb.getNumChildren() == 1 ) ? nb.getChild( 0 ) : nb;
867
38034
          d_im.addPendingInference(
868
              t_concl, InferenceId::DATATYPES_LABEL_EXH, t_concl_exp);
869
38034
          Trace("datatypes-infer") << "DtInfer : label : " << t_concl << " by " << t_concl_exp << std::endl;
870
38034
          return;
871
        }
872
      }
873
    }
874
  }
875
285967
  if( makeConflict ){
876
108
    Debug("datatypes-labels") << "Explain " << j << " " << t << std::endl;
877
216
    std::vector<Node> conf;
878
108
    conf.push_back(j);
879
108
    conf.push_back(t);
880
108
    conf.push_back(jt[0].eqNode(t_arg));
881
108
    Trace("dt-conflict") << "CONFLICT: Tester conflict : " << conf << std::endl;
882
108
    d_im.sendDtConflict(conf, InferenceId::DATATYPES_TESTER_MERGE_CONFLICT);
883
  }
884
}
885
886
446050
void TheoryDatatypes::addSelector( Node s, EqcInfo* eqc, Node n, bool assertFacts ) {
887
446050
  Trace("dt-collapse-sel") << "Add selector : " << s << " to eqc(" << n << ")" << std::endl;
888
  //check to see if it is redundant
889
446050
  NodeUIntMap::iterator sel_i = d_selector_apps.find(n);
890
446050
  Assert(sel_i != d_selector_apps.end());
891
446050
  if( sel_i != d_selector_apps.end() ){
892
446050
    size_t n_sel = (*sel_i).second;
893
807873
    for (size_t j = 0; j < n_sel; j++)
894
    {
895
1000319
      Node ss = d_selector_apps_data[n][j];
896
638496
      if( s.getOperator()==ss.getOperator() && ( s.getKind()!=DT_HEIGHT_BOUND || s[1]==ss[1] ) ){
897
276673
        Trace("dt-collapse-sel") << "...redundant." << std::endl;
898
276673
        return;
899
      }
900
    }
901
    //add it to the vector
902
    //sel->push_back( s );
903
169377
    d_selector_apps[n] = n_sel + 1;
904
169377
    if (n_sel < d_selector_apps_data[n].size())
905
    {
906
152286
      d_selector_apps_data[n][n_sel] = s;
907
    }else{
908
17091
      d_selector_apps_data[n].push_back( s );
909
    }
910
911
169377
    eqc->d_selectors = true;
912
  }
913
169377
  if( assertFacts && !eqc->d_constructor.get().isNull() ){
914
    //conclude the collapsed merge
915
127839
    collapseSelector( s, eqc->d_constructor.get() );
916
  }
917
}
918
919
38187
void TheoryDatatypes::addConstructor( Node c, EqcInfo* eqc, Node n ){
920
38187
  Trace("datatypes-debug") << "Add constructor : " << c << " to eqc(" << n << ")" << std::endl;
921
38187
  Assert(eqc->d_constructor.get().isNull());
922
  //check labels
923
38187
  NodeUIntMap::iterator lbl_i = d_labels.find(n);
924
38187
  if( lbl_i != d_labels.end() ){
925
38187
    size_t constructorIndex = utils::indexOf(c.getOperator());
926
38187
    size_t n_lbl = (*lbl_i).second;
927
169540
    for (size_t i = 0; i < n_lbl; i++)
928
    {
929
262711
      Node t = d_labels_data[n][i];
930
131358
      if (d_labels_data[n][i].getKind() == NOT)
931
      {
932
94949
        unsigned tindex = d_labels_tindex[n][i];
933
94949
        if (tindex == constructorIndex)
934
        {
935
10
          std::vector<Node> conf;
936
5
          conf.push_back(t);
937
5
          conf.push_back(t[0][0].eqNode(c));
938
10
          Trace("dt-conflict")
939
5
              << "CONFLICT: Tester merge eq conflict : " << conf << std::endl;
940
5
          d_im.sendDtConflict(conf, InferenceId::DATATYPES_TESTER_CONFLICT);
941
5
          return;
942
        }
943
      }
944
    }
945
  }
946
  //check selectors
947
38182
  NodeUIntMap::iterator sel_i = d_selector_apps.find(n);
948
38182
  if( sel_i != d_selector_apps.end() ){
949
38182
    size_t n_sel = (*sel_i).second;
950
144796
    for (size_t j = 0; j < n_sel; j++)
951
    {
952
213228
      Node s = d_selector_apps_data[n][j];
953
      //collapse the selector
954
106614
      collapseSelector( s, c );
955
    }
956
  }
957
38182
  eqc->d_constructor.set( c );
958
}
959
960
234453
void TheoryDatatypes::collapseSelector( Node s, Node c ) {
961
234453
  Assert(c.getKind() == APPLY_CONSTRUCTOR);
962
234453
  Trace("dt-collapse-sel") << "collapse selector : " << s << " " << c << std::endl;
963
468906
  Node r;
964
234453
  bool wrong = false;
965
468906
  Node eq_exp = s[0].eqNode(c);
966
234453
  if( s.getKind()==kind::APPLY_SELECTOR_TOTAL ){
967
349992
    Node selector = s.getOperator();
968
174996
    size_t constructorIndex = utils::indexOf(c.getOperator());
969
174996
    const DType& dt = utils::datatypeOf(selector);
970
174996
    const DTypeConstructor& dtc = dt[constructorIndex];
971
174996
    int selectorIndex = dtc.getSelectorIndexInternal(selector);
972
174996
    wrong = selectorIndex<0;
973
174996
    r = NodeManager::currentNM()->mkNode( kind::APPLY_SELECTOR_TOTAL, s.getOperator(), c );
974
  }
975
234453
  if( !r.isNull() ){
976
349992
    Node rrs;
977
174996
    if (wrong)
978
    {
979
      // Must use make ground term here instead of the rewriter, since we
980
      // do not want to introduce arbitrary values. This is important so that
981
      // we avoid constants for types that are not "closed enumerable", e.g.
982
      // uninterpreted sorts and arrays, where the solver does not fully
983
      // handle values of the sort. The call to mkGroundTerm does not introduce
984
      // values for these sorts.
985
81761
      rrs = r.getType().mkGroundTerm();
986
163522
      Trace("datatypes-wrong-sel")
987
81761
          << "Bad apply " << r << " term = " << rrs
988
81761
          << ", value = " << r.getType().mkGroundValue() << std::endl;
989
    }
990
    else
991
    {
992
93235
      rrs = Rewriter::rewrite(r);
993
    }
994
174996
    if (s != rrs)
995
    {
996
224050
      Node eq = s.eqNode(rrs);
997
      // Since collapsing selectors may generate new terms, we must send
998
      // this out as a lemma if it is of an external type, or otherwise we
999
      // may ask for the equality status of terms that only datatypes knows
1000
      // about, see issue #5344.
1001
112025
      bool forceLemma = !s.getType().isDatatype();
1002
112025
      Trace("datatypes-infer") << "DtInfer : collapse sel";
1003
112025
      Trace("datatypes-infer") << " : " << eq << " by " << eq_exp << std::endl;
1004
112025
      d_im.addPendingInference(
1005
          eq, InferenceId::DATATYPES_COLLAPSE_SEL, eq_exp, forceLemma);
1006
    }
1007
  }
1008
234453
}
1009
1010
114572
EqualityStatus TheoryDatatypes::getEqualityStatus(TNode a, TNode b){
1011
114572
  Assert(d_equalityEngine->hasTerm(a) && d_equalityEngine->hasTerm(b));
1012
114572
  if (d_equalityEngine->areEqual(a, b))
1013
  {
1014
    // The terms are implied to be equal
1015
4783
    return EQUALITY_TRUE;
1016
  }
1017
109789
  if (d_equalityEngine->areDisequal(a, b, false))
1018
  {
1019
    // The terms are implied to be dis-equal
1020
    return EQUALITY_FALSE;
1021
  }
1022
109789
  return EQUALITY_FALSE_IN_MODEL;
1023
}
1024
1025
88167
void TheoryDatatypes::addCarePairs(TNodeTrie* t1,
1026
                                   TNodeTrie* t2,
1027
                                   unsigned arity,
1028
                                   unsigned depth,
1029
                                   unsigned& n_pairs)
1030
{
1031
88167
  if( depth==arity ){
1032
10422
    if( t2!=NULL ){
1033
20844
      Node f1 = t1->getData();
1034
20844
      Node f2 = t2->getData();
1035
10422
      if( !areEqual( f1, f2 ) ){
1036
10422
        Trace("dt-cg") << "Check " << f1 << " and " << f2 << std::endl;
1037
20844
        vector< pair<TNode, TNode> > currentPairs;
1038
31424
        for (unsigned k = 0; k < f1.getNumChildren(); ++ k) {
1039
42004
          TNode x = f1[k];
1040
42004
          TNode y = f2[k];
1041
21002
          Assert(d_equalityEngine->hasTerm(x));
1042
21002
          Assert(d_equalityEngine->hasTerm(y));
1043
21002
          Assert(!areDisequal(x, y));
1044
21002
          Assert(!areCareDisequal(x, y));
1045
21002
          if (!d_equalityEngine->areEqual(x, y))
1046
          {
1047
11831
            Trace("dt-cg") << "Arg #" << k << " is " << x << " " << y << std::endl;
1048
35493
            if (d_equalityEngine->isTriggerTerm(x, THEORY_DATATYPES)
1049
35493
                && d_equalityEngine->isTriggerTerm(y, THEORY_DATATYPES))
1050
            {
1051
1945
              TNode x_shared = d_equalityEngine->getTriggerTermRepresentative(
1052
3890
                  x, THEORY_DATATYPES);
1053
1945
              TNode y_shared = d_equalityEngine->getTriggerTermRepresentative(
1054
3890
                  y, THEORY_DATATYPES);
1055
1945
              currentPairs.push_back(make_pair(x_shared, y_shared));
1056
            }
1057
          }
1058
        }
1059
12367
        for (unsigned c = 0; c < currentPairs.size(); ++ c) {
1060
1945
          Trace("dt-cg-pair") << "Pair : " << currentPairs[c].first << " " << currentPairs[c].second << std::endl;
1061
1945
          addCarePair(currentPairs[c].first, currentPairs[c].second);
1062
1945
          n_pairs++;
1063
        }
1064
      }
1065
    }
1066
  }else{
1067
77745
    if( t2==NULL ){
1068
69100
      if( depth<(arity-1) ){
1069
        //add care pairs internal to each child
1070
30835
        for (std::pair<const TNode, TNodeTrie>& tt : t1->d_data)
1071
        {
1072
18583
          addCarePairs(&tt.second, nullptr, arity, depth + 1, n_pairs);
1073
        }
1074
      }
1075
      //add care pairs based on each pair of non-disequal arguments
1076
185454
      for (std::map<TNode, TNodeTrie>::iterator it = t1->d_data.begin();
1077
185454
           it != t1->d_data.end();
1078
           ++it)
1079
      {
1080
116354
        std::map<TNode, TNodeTrie>::iterator it2 = it;
1081
116354
        ++it2;
1082
349034
        for( ; it2 != t1->d_data.end(); ++it2 ){
1083
116340
          if (!d_equalityEngine->areDisequal(it->first, it2->first, false))
1084
          {
1085
50138
            if( !areCareDisequal(it->first, it2->first) ){
1086
11882
              addCarePairs( &it->second, &it2->second, arity, depth+1, n_pairs );
1087
            }
1088
          }
1089
        }
1090
      }
1091
    }else{
1092
      //add care pairs based on product of indices, non-disequal arguments
1093
26731
      for (std::pair<const TNode, TNodeTrie>& tt1 : t1->d_data)
1094
      {
1095
41380
        for (std::pair<const TNode, TNodeTrie>& tt2 : t2->d_data)
1096
        {
1097
23294
          if (!d_equalityEngine->areDisequal(tt1.first, tt2.first, false))
1098
          {
1099
14839
            if (!areCareDisequal(tt1.first, tt2.first))
1100
            {
1101
7185
              addCarePairs(&tt1.second, &tt2.second, arity, depth + 1, n_pairs);
1102
            }
1103
          }
1104
        }
1105
      }
1106
    }
1107
  }
1108
88167
}
1109
1110
11787
void TheoryDatatypes::computeCareGraph(){
1111
11787
  unsigned n_pairs = 0;
1112
11787
  Trace("dt-cg-summary") << "Compute graph for dt..." << d_functionTerms.size() << " " << d_sharedTerms.size() << std::endl;
1113
11787
  Trace("dt-cg") << "Build indices..." << std::endl;
1114
23574
  std::map<TypeNode, std::map<Node, TNodeTrie> > index;
1115
23574
  std::map< Node, unsigned > arity;
1116
  //populate indices
1117
11787
  unsigned functionTerms = d_functionTerms.size();
1118
250640
  for( unsigned i=0; i<functionTerms; i++ ){
1119
477706
    TNode f1 = d_functionTerms[i];
1120
238853
    Assert(d_equalityEngine->hasTerm(f1));
1121
238853
    Trace("dt-cg-debug") << "...build for " << f1 << std::endl;
1122
    //break into index based on operator, and type of first argument (since some operators are parametric)
1123
477706
    Node op = f1.getOperator();
1124
477706
    TypeNode tn = f1[0].getType();
1125
477706
    std::vector< TNode > reps;
1126
238853
    bool has_trigger_arg = false;
1127
516035
    for( unsigned j=0; j<f1.getNumChildren(); j++ ){
1128
277182
      reps.push_back(d_equalityEngine->getRepresentative(f1[j]));
1129
277182
      if (d_equalityEngine->isTriggerTerm(f1[j], THEORY_DATATYPES))
1130
      {
1131
230197
        has_trigger_arg = true;
1132
      }
1133
    }
1134
    //only may contribute to care pairs if has at least one trigger argument
1135
238853
    if( has_trigger_arg ){
1136
201064
      index[tn][op].addTerm( f1, reps );
1137
201064
      arity[op] = reps.size();
1138
    }
1139
  }
1140
  //for each index
1141
29573
  for (std::pair<const TypeNode, std::map<Node, TNodeTrie> >& tt : index)
1142
  {
1143
68303
    for (std::pair<const Node, TNodeTrie>& t : tt.second)
1144
    {
1145
101034
      Trace("dt-cg") << "Process index " << tt.first << ", " << t.first << "..."
1146
50517
                     << std::endl;
1147
50517
      addCarePairs(&t.second, nullptr, arity[t.first], 0, n_pairs);
1148
    }
1149
  }
1150
11787
  Trace("dt-cg-summary") << "...done, # pairs = " << n_pairs << std::endl;
1151
11787
}
1152
1153
9868
bool TheoryDatatypes::collectModelValues(TheoryModel* m,
1154
                                         const std::set<Node>& termSet)
1155
{
1156
19736
  Trace("dt-cmi") << "Datatypes : Collect model values "
1157
9868
                  << d_equalityEngine->consistent() << std::endl;
1158
9868
  Trace("dt-model") << std::endl;
1159
9868
  printModelDebug( "dt-model" );
1160
9868
  Trace("dt-model") << std::endl;
1161
1162
  //get all constructors
1163
9868
  eq::EqClassesIterator eqccs_i = eq::EqClassesIterator(d_equalityEngine);
1164
19736
  std::vector< Node > cons;
1165
19736
  std::vector< Node > nodes;
1166
19736
  std::map< Node, Node > eqc_cons;
1167
529708
  while( !eqccs_i.isFinished() ){
1168
519840
    Node eqc = (*eqccs_i);
1169
    //for all equivalence classes that are datatypes
1170
    //if( termSet.find( eqc )==termSet.end() ){
1171
    //  Trace("dt-cmi-debug") << "Irrelevant eqc : " << eqc << std::endl;
1172
    //}
1173
259920
    if( eqc.getType().isDatatype() ){
1174
53112
      EqcInfo* ei = getOrMakeEqcInfo( eqc );
1175
53112
      if( ei && !ei->d_constructor.get().isNull() ){
1176
89286
        Node c = ei->d_constructor.get();
1177
44643
        cons.push_back( c );
1178
44643
        eqc_cons[ eqc ] = c;
1179
      }else{
1180
        //if eqc contains a symbol known to datatypes (a selector), then we must assign
1181
        //should assign constructors to EQC if they have a selector or a tester
1182
8469
        bool shouldConsider = ( ei && ei->d_selectors ) || hasTester( eqc );
1183
8469
        if( shouldConsider ){
1184
          nodes.push_back( eqc );
1185
        }
1186
      }
1187
    }
1188
    //}
1189
259920
    ++eqccs_i;
1190
  }
1191
1192
  //unsigned orig_size = nodes.size();
1193
19736
  std::map< TypeNode, int > typ_enum_map;
1194
19736
  std::vector< TypeEnumerator > typ_enum;
1195
9868
  unsigned index = 0;
1196
9868
  while( index<nodes.size() ){
1197
    Node eqc = nodes[index];
1198
    Node neqc;
1199
    bool addCons = false;
1200
    TypeNode tt = eqc.getType();
1201
    const DType& dt = tt.getDType();
1202
    if (!d_equalityEngine->hasTerm(eqc))
1203
    {
1204
      Assert(false);
1205
    }else{
1206
      Trace("dt-cmi") << "NOTICE : Datatypes: no constructor in equivalence class " << eqc << std::endl;
1207
      Trace("dt-cmi") << "   Type : " << eqc.getType() << std::endl;
1208
      EqcInfo* ei = getOrMakeEqcInfo( eqc );
1209
      std::vector< bool > pcons;
1210
      getPossibleCons( ei, eqc, pcons );
1211
      Trace("dt-cmi") << "Possible constructors : ";
1212
      for( unsigned i=0; i<pcons.size(); i++ ){
1213
        Trace("dt-cmi") << pcons[i] << " ";
1214
      }
1215
      Trace("dt-cmi") << std::endl;
1216
      for( unsigned r=0; r<2; r++ ){
1217
        if( neqc.isNull() ){
1218
          for( unsigned i=0; i<pcons.size(); i++ ){
1219
            // must try the infinite ones first
1220
            bool cfinite =
1221
                d_state.isFiniteType(dt[i].getSpecializedConstructorType(tt));
1222
            if( pcons[i] && (r==1)==cfinite ){
1223
              neqc = utils::getInstCons(eqc, dt, i);
1224
              break;
1225
            }
1226
          }
1227
        }
1228
      }
1229
      addCons = true;
1230
    }
1231
    if( !neqc.isNull() ){
1232
      Trace("dt-cmi") << "Assign : " << neqc << std::endl;
1233
      if (!m->assertEquality(eqc, neqc, true))
1234
      {
1235
        return false;
1236
      }
1237
      eqc_cons[ eqc ] = neqc;
1238
    }
1239
    if( addCons ){
1240
      cons.push_back( neqc );
1241
    }
1242
    ++index;
1243
  }
1244
1245
54527
  for( std::map< Node, Node >::iterator it = eqc_cons.begin(); it != eqc_cons.end(); ++it ){
1246
89318
    Node eqc = it->first;
1247
44659
    if( eqc.getType().isCodatatype() ){
1248
      //until models are implemented for codatatypes
1249
      //throw Exception("Models for codatatypes are not supported in this version.");
1250
      //must proactive expand to avoid looping behavior in model builder
1251
75
      if( !it->second.isNull() ){
1252
124
        std::map< Node, int > vmap;
1253
124
        Node v = getCodatatypesValue( it->first, eqc_cons, vmap, 0 );
1254
62
        Trace("dt-cmi") << "  EQC(" << it->first << "), constructor is " << it->second << ", value is " << v << ", const = " << v.isConst() << std::endl;
1255
62
        if (!m->assertEquality(eqc, v, true))
1256
        {
1257
          return false;
1258
        }
1259
62
        m->assertSkeleton(v);
1260
      }
1261
    }else{
1262
44584
      Trace("dt-cmi") << "Datatypes : assert representative " << it->second << " for " << it->first << std::endl;
1263
44584
      m->assertSkeleton(it->second);
1264
    }
1265
  }
1266
9868
  return true;
1267
}
1268
1269
1270
199
Node TheoryDatatypes::getCodatatypesValue( Node n, std::map< Node, Node >& eqc_cons, std::map< Node, int >& vmap, int depth ){
1271
199
  std::map< Node, int >::iterator itv = vmap.find( n );
1272
199
  if( itv!=vmap.end() ){
1273
6
    int debruijn = depth - 1 - itv->second;
1274
    return NodeManager::currentNM()->mkConst(
1275
6
        UninterpretedConstant(n.getType(), debruijn));
1276
193
  }else if( n.getType().isDatatype() ){
1277
173
    Node nc = eqc_cons[n];
1278
139
    if( !nc.isNull() ){
1279
105
      vmap[n] = depth;
1280
105
      Trace("dt-cmi-cdt-debug") << "    map " << n << " -> " << depth << std::endl;
1281
105
      Assert(nc.getKind() == APPLY_CONSTRUCTOR);
1282
210
      std::vector< Node > children;
1283
105
      children.push_back( nc.getOperator() );
1284
242
      for( unsigned i=0; i<nc.getNumChildren(); i++ ){
1285
274
        Node r = getRepresentative( nc[i] );
1286
274
        Node rv = getCodatatypesValue( r, eqc_cons, vmap, depth+1 );
1287
137
        children.push_back( rv );
1288
      }
1289
105
      vmap.erase( n );
1290
105
      return NodeManager::currentNM()->mkNode( APPLY_CONSTRUCTOR, children );
1291
    }
1292
  }
1293
88
  return n;
1294
}
1295
1296
Node TheoryDatatypes::getSingletonLemma( TypeNode tn, bool pol ) {
1297
  NodeManager* nm = NodeManager::currentNM();
1298
  SkolemManager* sm = nm->getSkolemManager();
1299
  int index = pol ? 0 : 1;
1300
  std::map< TypeNode, Node >::iterator it = d_singleton_lemma[index].find( tn );
1301
  if( it==d_singleton_lemma[index].end() ){
1302
    Node a;
1303
    if( pol ){
1304
      Node v1 = nm->mkBoundVar(tn);
1305
      Node v2 = nm->mkBoundVar(tn);
1306
      a = nm->mkNode(FORALL, nm->mkNode(BOUND_VAR_LIST, v1, v2), v1.eqNode(v2));
1307
    }else{
1308
      Node v1 = sm->mkDummySkolem("k1", tn);
1309
      Node v2 = sm->mkDummySkolem("k2", tn);
1310
      a = v1.eqNode( v2 ).negate();
1311
      //send out immediately as lemma
1312
      d_im.lemma(a, InferenceId::DATATYPES_REC_SINGLETON_FORCE_DEQ);
1313
      Trace("dt-singleton") << "******** assert " << a << " to avoid singleton cardinality for type " << tn << std::endl;
1314
    }
1315
    d_singleton_lemma[index][tn] = a;
1316
    return a;
1317
  }else{
1318
    return it->second;
1319
  }
1320
}
1321
1322
288122
void TheoryDatatypes::collectTerms( Node n ) {
1323
288122
  if (d_collectTermsCache.find(n) != d_collectTermsCache.end())
1324
  {
1325
    // already processed
1326
38864
    return;
1327
  }
1328
249258
  d_collectTermsCache[n] = true;
1329
249258
  Kind nk = n.getKind();
1330
249258
  if (nk == APPLY_CONSTRUCTOR)
1331
  {
1332
100417
    Debug("datatypes") << "  Found constructor " << n << endl;
1333
100417
    if (n.getNumChildren() > 0)
1334
    {
1335
72701
      d_functionTerms.push_back(n);
1336
    }
1337
100417
    return;
1338
  }
1339
148841
  if (nk == APPLY_SELECTOR_TOTAL || nk == DT_SIZE || nk == DT_HEIGHT_BOUND)
1340
  {
1341
22922
    d_functionTerms.push_back(n);
1342
    // we must also record which selectors exist
1343
22922
    Trace("dt-collapse-sel") << "  Found selector " << n << endl;
1344
45844
    Node rep = getRepresentative(n[0]);
1345
    // record it in the selectors
1346
22922
    EqcInfo* eqc = getOrMakeEqcInfo(rep, true);
1347
    // add it to the eqc info
1348
22922
    addSelector(n, eqc, rep);
1349
  }
1350
1351
  // now, do user-context-dependent lemmas
1352
148841
  if (nk != DT_SIZE && nk != DT_HEIGHT_BOUND)
1353
  {
1354
    // if not one of these kinds, there are no lemmas
1355
144357
    return;
1356
  }
1357
4484
  if (d_collectTermsCacheU.find(n) != d_collectTermsCacheU.end())
1358
  {
1359
2158
    return;
1360
  }
1361
2326
  d_collectTermsCacheU[n] = true;
1362
1363
2326
  NodeManager* nm = NodeManager::currentNM();
1364
1365
2326
  if (nk == DT_SIZE)
1366
  {
1367
4652
    Node lem = nm->mkNode(LEQ, d_zero, n);
1368
4652
    Trace("datatypes-infer")
1369
2326
        << "DtInfer : size geq zero : " << lem << std::endl;
1370
2326
    d_im.addPendingLemma(lem, InferenceId::DATATYPES_SIZE_POS);
1371
  }
1372
  else if (nk == DT_HEIGHT_BOUND && n[1].getConst<Rational>().isZero())
1373
  {
1374
    std::vector<Node> children;
1375
    const DType& dt = n[0].getType().getDType();
1376
    for (unsigned i = 0, ncons = dt.getNumConstructors(); i < ncons; i++)
1377
    {
1378
      if (utils::isNullaryConstructor(dt[i]))
1379
      {
1380
        Node test = utils::mkTester(n[0], i, dt);
1381
        children.push_back(test);
1382
      }
1383
    }
1384
    Node lem;
1385
    if (children.empty())
1386
    {
1387
      lem = n.negate();
1388
    }
1389
    else
1390
    {
1391
      lem = n.eqNode(children.size() == 1 ? children[0]
1392
                                          : nm->mkNode(OR, children));
1393
    }
1394
    Trace("datatypes-infer") << "DtInfer : zero height : " << lem << std::endl;
1395
    d_im.addPendingLemma(lem, InferenceId::DATATYPES_HEIGHT_ZERO);
1396
  }
1397
}
1398
1399
127477
Node TheoryDatatypes::getInstantiateCons(Node n, const DType& dt, int index)
1400
{
1401
127477
  if( n.getKind()==APPLY_CONSTRUCTOR && n.getNumChildren()==0 ){
1402
10523
    return n;
1403
  }
1404
  //add constructor to equivalence class
1405
233908
  Node k = getTermSkolemFor( n );
1406
233908
  Node n_ic = utils::getInstCons(k, dt, index);
1407
116954
  n_ic = Rewriter::rewrite( n_ic );
1408
  // it may be a new term, so we collect terms and add it to the equality engine
1409
116954
  collectTerms( n_ic );
1410
116954
  d_equalityEngine->addTerm(n_ic);
1411
116954
  Debug("dt-enum") << "Made instantiate cons " << n_ic << std::endl;
1412
116954
  return n_ic;
1413
}
1414
1415
192789
void TheoryDatatypes::instantiate( EqcInfo* eqc, Node n ){
1416
192789
  Trace("datatypes-debug") << "Instantiate: " << n << std::endl;
1417
  //add constructor to equivalence class if not done so already
1418
192789
  int index = getLabelIndex( eqc, n );
1419
192789
  if (index == -1 || eqc->d_inst)
1420
  {
1421
141147
    return;
1422
  }
1423
244431
  Node exp;
1424
244431
  Node tt;
1425
127477
  if (!eqc->d_constructor.get().isNull())
1426
  {
1427
24451
    exp = d_true;
1428
24451
    tt = eqc->d_constructor;
1429
  }
1430
  else
1431
  {
1432
103026
    exp = getLabel(n);
1433
103026
    tt = exp[0];
1434
  }
1435
244431
  TypeNode ttn = tt.getType();
1436
127477
  const DType& dt = ttn.getDType();
1437
  // instantiate this equivalence class
1438
127477
  eqc->d_inst = true;
1439
244431
  Node tt_cons = getInstantiateCons(tt, dt, index);
1440
244431
  Node eq;
1441
127477
  if (tt == tt_cons)
1442
  {
1443
10523
    return;
1444
  }
1445
116954
  eq = tt.eqNode(tt_cons);
1446
  // Determine if the equality must be sent out as a lemma. Notice that
1447
  // we  keep new equalities from the instantiate rule internal
1448
  // as long as they are for datatype constructors that have no arguments that
1449
  // have finite external type, which corresponds to:
1450
  //   forceLemma = dt[index].hasFiniteExternalArgType(ttn);
1451
  // Such equalities must be sent because they introduce selector terms that
1452
  // may contribute to conflicts due to cardinality (good examples of this are
1453
  // regress0/datatypes/dt-param-card4-bool-sat.smt2 and
1454
  // regress0/datatypes/list-bool.smt2).
1455
  bool forceLemma;
1456
233908
  if (options::dtPoliteOptimize())
1457
  {
1458
116954
    forceLemma = dt[index].hasFiniteExternalArgType(ttn);
1459
  }
1460
  else
1461
  {
1462
    forceLemma = dt.involvesExternalType();
1463
  }
1464
233908
  Trace("datatypes-infer-debug") << "DtInstantiate : " << eqc << " " << eq
1465
116954
                                 << " forceLemma = " << forceLemma << std::endl;
1466
116954
  d_im.addPendingInference(eq, InferenceId::DATATYPES_INST, exp, forceLemma);
1467
233908
  Trace("datatypes-infer") << "DtInfer : instantiate : " << eq << " by " << exp
1468
116954
                           << std::endl;
1469
}
1470
1471
28110
void TheoryDatatypes::checkCycles() {
1472
28110
  Trace("datatypes-cycle-check") << "Check acyclicity" << std::endl;
1473
56083
  std::vector< Node > cdt_eqc;
1474
28110
  eq::EqClassesIterator eqcs_i = eq::EqClassesIterator(d_equalityEngine);
1475
1016350
  while( !eqcs_i.isFinished() ){
1476
988377
    Node eqc = (*eqcs_i);
1477
988377
    TypeNode tn = eqc.getType();
1478
494257
    if( tn.isDatatype() ) {
1479
168051
      if( !tn.isCodatatype() ){
1480
333754
        if( options::dtCyclic() ){
1481
          //do cycle checks
1482
333617
          std::map< TNode, bool > visited;
1483
333617
          std::map< TNode, bool > proc;
1484
333617
          std::vector<Node> expl;
1485
166877
          Trace("datatypes-cycle-check") << "...search for cycle starting at " << eqc << std::endl;
1486
333617
          Node cn = searchForCycle( eqc, eqc, visited, proc, expl );
1487
166877
          Trace("datatypes-cycle-check") << "...finish." << std::endl;
1488
          //if we discovered a different cycle while searching this one
1489
166877
          if( !cn.isNull() && cn!=eqc ){
1490
19
            visited.clear();
1491
19
            proc.clear();
1492
19
            expl.clear();
1493
38
            Node prev = cn;
1494
19
            cn = searchForCycle( cn, cn, visited, proc, expl );
1495
19
            Assert(prev == cn);
1496
          }
1497
1498
166877
          if( !cn.isNull() ) {
1499
137
            Assert(expl.size() > 0);
1500
274
            Trace("dt-conflict")
1501
137
                << "CONFLICT: Cycle conflict : " << expl << std::endl;
1502
137
            d_im.sendDtConflict(expl, InferenceId::DATATYPES_CYCLE);
1503
137
            return;
1504
          }
1505
        }
1506
      }else{
1507
        //indexing
1508
1174
        cdt_eqc.push_back( eqc );
1509
      }
1510
    }
1511
494120
    ++eqcs_i;
1512
  }
1513
27973
  Trace("datatypes-cycle-check") << "Check uniqueness" << std::endl;
1514
  //process codatatypes
1515
28063
  if( cdt_eqc.size()>1 && options::cdtBisimilar() ){
1516
90
    printModelDebug("dt-cdt-debug");
1517
90
    Trace("dt-cdt-debug") << "Process " << cdt_eqc.size() << " co-datatypes" << std::endl;
1518
180
    std::vector< std::vector< Node > > part_out;
1519
180
    std::vector<Node> exp;
1520
180
    std::map< Node, Node > cn;
1521
180
    std::map< Node, std::map< Node, int > > dni;
1522
1260
    for( unsigned i=0; i<cdt_eqc.size(); i++ ){
1523
1170
      cn[cdt_eqc[i]] = cdt_eqc[i];
1524
    }
1525
90
    separateBisimilar( cdt_eqc, part_out, exp, cn, dni, 0, false );
1526
90
    Trace("dt-cdt-debug") << "Done separate bisimilar." << std::endl;
1527
90
    if( !part_out.empty() ){
1528
10
      Trace("dt-cdt-debug") << "Process partition size " << part_out.size() << std::endl;
1529
20
      for( unsigned i=0; i<part_out.size(); i++ ){
1530
20
        std::vector< Node > part;
1531
10
        part.push_back( part_out[i][0] );
1532
20
        for( unsigned j=1; j<part_out[i].size(); j++ ){
1533
10
          Trace("dt-cdt") << "Codatatypes : " << part_out[i][0] << " and " << part_out[i][j] << " must be equal!!" << std::endl;
1534
10
          part.push_back( part_out[i][j] );
1535
20
          std::vector< std::vector< Node > > tpart_out;
1536
10
          exp.clear();
1537
10
          cn.clear();
1538
10
          cn[part_out[i][0]] = part_out[i][0];
1539
10
          cn[part_out[i][j]] = part_out[i][j];
1540
10
          dni.clear();
1541
10
          separateBisimilar( part, tpart_out, exp, cn, dni, 0, true );
1542
10
          Assert(tpart_out.size() == 1 && tpart_out[0].size() == 2);
1543
10
          part.pop_back();
1544
          //merge based on explanation
1545
10
          Trace("dt-cdt") << "  exp is : ";
1546
38
          for( unsigned k=0; k<exp.size(); k++ ){
1547
28
            Trace("dt-cdt") << exp[k] << " ";
1548
          }
1549
10
          Trace("dt-cdt") << std::endl;
1550
20
          Node eq = part_out[i][0].eqNode( part_out[i][j] );
1551
20
          Node eqExp = NodeManager::currentNM()->mkAnd(exp);
1552
10
          d_im.addPendingInference(eq, InferenceId::DATATYPES_BISIMILAR, eqExp);
1553
10
          Trace("datatypes-infer") << "DtInfer : cdt-bisimilar : " << eq << " by " << eqExp << std::endl;
1554
        }
1555
      }
1556
    }
1557
  }
1558
}
1559
1560
//everything is in terms of representatives
1561
278
void TheoryDatatypes::separateBisimilar(
1562
    std::vector<Node>& part,
1563
    std::vector<std::vector<Node> >& part_out,
1564
    std::vector<Node>& exp,
1565
    std::map<Node, Node>& cn,
1566
    std::map<Node, std::map<Node, int> >& dni,
1567
    int dniLvl,
1568
    bool mkExp)
1569
{
1570
278
  if( !mkExp ){
1571
240
    Trace("dt-cdt-debug") << "Separate bisimilar : " << std::endl;
1572
1818
    for( unsigned i=0; i<part.size(); i++ ){
1573
1578
      Trace("dt-cdt-debug") << "   " << part[i] << ", current = " << cn[part[i]] << std::endl;
1574
    }
1575
  }
1576
278
  Assert(part.size() > 1);
1577
556
  std::map< Node, std::vector< Node > > new_part;
1578
556
  std::map< Node, std::vector< Node > > new_part_c;
1579
556
  std::map< int, std::vector< Node > > new_part_rec;
1580
1581
556
  std::map< Node, Node > cn_cons;
1582
1932
  for( unsigned j=0; j<part.size(); j++ ){
1583
3308
    Node c = cn[part[j]];
1584
1654
    std::map< Node, int >::iterator it_rec = dni[part[j]].find( c );
1585
1654
    if( it_rec!=dni[part[j]].end() ){
1586
      //looped
1587
46
      if( !mkExp ){ Trace("dt-cdt-debug") << "  - " << part[j] << " is looping at index " << it_rec->second << std::endl; }
1588
46
      new_part_rec[ it_rec->second ].push_back( part[j] );
1589
    }else{
1590
1608
      if( c.getType().isDatatype() ){
1591
2704
        Node ncons = getEqcConstructor( c );
1592
1352
        if( ncons.getKind()==APPLY_CONSTRUCTOR ) {
1593
810
          Node cc = ncons.getOperator();
1594
405
          cn_cons[part[j]] = ncons;
1595
405
          if (mkExp && c != ncons)
1596
          {
1597
20
            exp.push_back(c.eqNode(ncons));
1598
          }
1599
405
          new_part[cc].push_back( part[j] );
1600
405
          if( !mkExp ){ Trace("dt-cdt-debug") << "  - " << part[j] << " is datatype " << ncons << "." << std::endl; }
1601
        }else{
1602
947
          new_part_c[c].push_back( part[j] );
1603
947
          if( !mkExp ){ Trace("dt-cdt-debug") << "  - " << part[j] << " is unspecified datatype." << std::endl; }
1604
        }
1605
      }else{
1606
        //add equivalences
1607
256
        if( !mkExp ){ Trace("dt-cdt-debug") << "  - " << part[j] << " is term " << c << "." << std::endl; }
1608
256
        new_part_c[c].push_back( part[j] );
1609
      }
1610
    }
1611
  }
1612
  //direct add for constants
1613
1376
  for( std::map< Node, std::vector< Node > >::iterator it = new_part_c.begin(); it != new_part_c.end(); ++it ){
1614
1098
    if( it->second.size()>1 ){
1615
186
      std::vector< Node > vec;
1616
93
      vec.insert( vec.begin(), it->second.begin(), it->second.end() );
1617
93
      part_out.push_back( vec );
1618
    }
1619
  }
1620
  //direct add for recursive
1621
304
  for( std::map< int, std::vector< Node > >::iterator it = new_part_rec.begin(); it != new_part_rec.end(); ++it ){
1622
26
    if( it->second.size()>1 ){
1623
40
      std::vector< Node > vec;
1624
20
      vec.insert( vec.begin(), it->second.begin(), it->second.end() );
1625
20
      part_out.push_back( vec );
1626
    }else{
1627
      //add back : could match a datatype?
1628
    }
1629
  }
1630
  //recurse for the datatypes
1631
502
  for( std::map< Node, std::vector< Node > >::iterator it = new_part.begin(); it != new_part.end(); ++it ){
1632
224
    if( it->second.size()>1 ){
1633
      //set dni to check for loops
1634
170
      std::map< Node, Node > dni_rem;
1635
351
      for( unsigned i=0; i<it->second.size(); i++ ){
1636
532
        Node n = it->second[i];
1637
266
        dni[n][cn[n]] = dniLvl;
1638
266
        dni_rem[n] = cn[n];
1639
      }
1640
1641
      //we will split based on the arguments of the datatype
1642
170
      std::vector< std::vector< Node > > split_new_part;
1643
85
      split_new_part.push_back( it->second );
1644
1645
85
      unsigned nChildren = cn_cons[it->second[0]].getNumChildren();
1646
      //for each child of constructor
1647
85
      unsigned cindex = 0;
1648
405
      while( cindex<nChildren && !split_new_part.empty() ){
1649
160
        if( !mkExp ){ Trace("dt-cdt-debug") << "Split argument #" << cindex << " of " << it->first << "..." << std::endl; }
1650
320
        std::vector< std::vector< Node > > next_split_new_part;
1651
338
        for( unsigned j=0; j<split_new_part.size(); j++ ){
1652
          //set current node
1653
642
          for( unsigned k=0; k<split_new_part[j].size(); k++ ){
1654
928
            Node n = split_new_part[j][k];
1655
928
            Node cnc = cn_cons[n][cindex];
1656
928
            Node nr = getRepresentative(cnc);
1657
464
            cn[n] = nr;
1658
464
            if (mkExp && cnc != nr)
1659
            {
1660
8
              exp.push_back(nr.eqNode(cnc));
1661
            }
1662
          }
1663
356
          std::vector< std::vector< Node > > c_part_out;
1664
178
          separateBisimilar( split_new_part[j], c_part_out, exp, cn, dni, dniLvl+1, mkExp );
1665
178
          next_split_new_part.insert( next_split_new_part.end(), c_part_out.begin(), c_part_out.end() );
1666
        }
1667
160
        split_new_part.clear();
1668
160
        split_new_part.insert( split_new_part.end(), next_split_new_part.begin(), next_split_new_part.end() );
1669
160
        cindex++;
1670
      }
1671
85
      part_out.insert( part_out.end(), split_new_part.begin(), split_new_part.end() );
1672
1673
351
      for( std::map< Node, Node >::iterator it2 = dni_rem.begin(); it2 != dni_rem.end(); ++it2 ){
1674
266
        dni[it2->first].erase( it2->second );
1675
      }
1676
    }
1677
  }
1678
278
}
1679
1680
//postcondition: if cycle detected, explanation is why n is a subterm of on
1681
712192
Node TheoryDatatypes::searchForCycle(TNode n,
1682
                                     TNode on,
1683
                                     std::map<TNode, bool>& visited,
1684
                                     std::map<TNode, bool>& proc,
1685
                                     std::vector<Node>& explanation,
1686
                                     bool firstTime)
1687
{
1688
712192
  Trace("datatypes-cycle-check2") << "Search for cycle " << n << " " << on << endl;
1689
1424384
  TNode ncons;
1690
1424384
  TNode nn;
1691
712192
  if( !firstTime ){
1692
545296
    nn = getRepresentative( n );
1693
545296
    if( nn==on ){
1694
137
      if (n != nn)
1695
      {
1696
98
        explanation.push_back(n.eqNode(nn));
1697
      }
1698
137
      return on;
1699
    }
1700
  }else{
1701
166896
    nn = getRepresentative( n );
1702
  }
1703
712055
  if( proc.find( nn )!=proc.end() ){
1704
141528
    return Node::null();
1705
  }
1706
570527
  Trace("datatypes-cycle-check2") << "...representative : " << nn << " " << ( visited.find( nn ) == visited.end() ) << " " << visited.size() << std::endl;
1707
570527
  if( visited.find( nn ) == visited.end() ) {
1708
570508
    Trace("datatypes-cycle-check2") << "  visit : " << nn << std::endl;
1709
570508
    visited[nn] = true;
1710
1141016
    TNode nncons = getEqcConstructor(nn);
1711
570508
    if (nncons.getKind() == APPLY_CONSTRUCTOR)
1712
    {
1713
966035
      for (unsigned i = 0; i < nncons.getNumChildren(); i++)
1714
      {
1715
        TNode cn =
1716
1089631
            searchForCycle(nncons[i], on, visited, proc, explanation, false);
1717
545296
        if( cn==on ) {
1718
          //add explanation for why the constructor is connected
1719
850
          if (n != nncons)
1720
          {
1721
465
            explanation.push_back(n.eqNode(nncons));
1722
          }
1723
850
          return on;
1724
544446
        }else if( !cn.isNull() ){
1725
111
          return cn;
1726
        }
1727
      }
1728
    }
1729
569547
    Trace("datatypes-cycle-check2") << "  unvisit : " << nn << std::endl;
1730
569547
    proc[nn] = true;
1731
569547
    visited.erase( nn );
1732
569547
    return Node::null();
1733
  }else{
1734
38
    TypeNode tn = nn.getType();
1735
19
    if( tn.isDatatype() ) {
1736
19
      if( !tn.isCodatatype() ){
1737
19
        return nn;
1738
      }
1739
    }
1740
    return Node::null();
1741
  }
1742
}
1743
1744
2812759
bool TheoryDatatypes::hasTerm(TNode a) { return d_equalityEngine->hasTerm(a); }
1745
1746
649527
bool TheoryDatatypes::areEqual( TNode a, TNode b ){
1747
649527
  if( a==b ){
1748
9457
    return true;
1749
640070
  }else if( hasTerm( a ) && hasTerm( b ) ){
1750
640070
    return d_equalityEngine->areEqual(a, b);
1751
  }else{
1752
    return false;
1753
  }
1754
}
1755
1756
21002
bool TheoryDatatypes::areDisequal( TNode a, TNode b ){
1757
21002
  if( a==b ){
1758
4525
    return false;
1759
16477
  }else if( hasTerm( a ) && hasTerm( b ) ){
1760
16477
    return d_equalityEngine->areDisequal(a, b, false);
1761
  }else{
1762
    //TODO : constants here?
1763
    return false;
1764
  }
1765
}
1766
1767
85979
bool TheoryDatatypes::areCareDisequal( TNode x, TNode y ) {
1768
85979
  Trace("datatypes-cg") << "areCareDisequal: " << x << " " << y << std::endl;
1769
85979
  Assert(d_equalityEngine->hasTerm(x));
1770
85979
  Assert(d_equalityEngine->hasTerm(y));
1771
257937
  if (d_equalityEngine->isTriggerTerm(x, THEORY_DATATYPES)
1772
257937
      && d_equalityEngine->isTriggerTerm(y, THEORY_DATATYPES))
1773
  {
1774
    TNode x_shared =
1775
82634
        d_equalityEngine->getTriggerTermRepresentative(x, THEORY_DATATYPES);
1776
    TNode y_shared =
1777
82634
        d_equalityEngine->getTriggerTermRepresentative(y, THEORY_DATATYPES);
1778
64272
    EqualityStatus eqStatus = d_valuation.getEqualityStatus(x_shared, y_shared);
1779
64272
    if( eqStatus==EQUALITY_FALSE_AND_PROPAGATED || eqStatus==EQUALITY_FALSE || eqStatus==EQUALITY_FALSE_IN_MODEL ){
1780
45910
      return true;
1781
    }
1782
  }
1783
40069
  return false;
1784
}
1785
1786
1499665
TNode TheoryDatatypes::getRepresentative( TNode a ){
1787
1499665
  if( hasTerm( a ) ){
1788
1499665
    return d_equalityEngine->getRepresentative(a);
1789
  }else{
1790
    return a;
1791
  }
1792
}
1793
1794
36846
void TheoryDatatypes::printModelDebug( const char* c ){
1795
36846
  if(! (Trace.isOn(c))) {
1796
36846
    return;
1797
  }
1798
1799
  Trace( c ) << "Datatypes model : " << std::endl;
1800
  eq::EqClassesIterator eqcs_i = eq::EqClassesIterator(d_equalityEngine);
1801
  while( !eqcs_i.isFinished() ){
1802
    Node eqc = (*eqcs_i);
1803
    //if( !eqc.getType().isBoolean() ){
1804
      if( eqc.getType().isDatatype() ){
1805
        Trace( c ) << "DATATYPE : ";
1806
      }
1807
      Trace( c ) << eqc << " : " << eqc.getType() << " : " << std::endl;
1808
      Trace( c ) << "   { ";
1809
      //add terms to model
1810
      eq::EqClassIterator eqc_i = eq::EqClassIterator(eqc, d_equalityEngine);
1811
      while( !eqc_i.isFinished() ){
1812
        if( (*eqc_i)!=eqc ){
1813
          Trace( c ) << (*eqc_i) << " ";
1814
        }
1815
        ++eqc_i;
1816
      }
1817
      Trace( c ) << "}" << std::endl;
1818
      if( eqc.getType().isDatatype() ){
1819
        EqcInfo* ei = getOrMakeEqcInfo( eqc );
1820
        if( ei ){
1821
          Trace( c ) << "   Instantiated : " << ei->d_inst.get() << std::endl;
1822
          Trace( c ) << "   Constructor : ";
1823
          if( !ei->d_constructor.get().isNull() ){
1824
            Trace( c )<< ei->d_constructor.get();
1825
          }
1826
          Trace( c ) << std::endl << "   Labels : ";
1827
          if( hasLabel( ei, eqc ) ){
1828
            Trace( c ) << getLabel( eqc );
1829
          }else{
1830
            NodeUIntMap::iterator lbl_i = d_labels.find(eqc);
1831
            if( lbl_i != d_labels.end() ){
1832
              for (size_t j = 0; j < (*lbl_i).second; j++)
1833
              {
1834
                Trace( c ) << d_labels_data[eqc][j] << " ";
1835
              }
1836
            }
1837
          }
1838
          Trace( c ) << std::endl;
1839
          Trace( c ) << "   Selectors : " << ( ei->d_selectors ? "yes, " : "no " );
1840
          NodeUIntMap::iterator sel_i = d_selector_apps.find(eqc);
1841
          if( sel_i != d_selector_apps.end() ){
1842
            for (size_t j = 0; j < (*sel_i).second; j++)
1843
            {
1844
              Trace( c ) << d_selector_apps_data[eqc][j] << " ";
1845
            }
1846
          }
1847
          Trace( c ) << std::endl;
1848
        }
1849
      }
1850
    //}
1851
    ++eqcs_i;
1852
  }
1853
}
1854
1855
9868
void TheoryDatatypes::computeRelevantTerms(std::set<Node>& termSet)
1856
{
1857
19736
  Trace("dt-cmi") << "Have " << termSet.size() << " relevant terms..."
1858
9868
                  << std::endl;
1859
1860
  //also include non-singleton dt equivalence classes  TODO : revisit this
1861
9868
  eq::EqClassesIterator eqcs_i = eq::EqClassesIterator(d_equalityEngine);
1862
529708
  while( !eqcs_i.isFinished() ){
1863
519840
    TNode r = (*eqcs_i);
1864
259920
    if (r.getType().isDatatype())
1865
    {
1866
53112
      eq::EqClassIterator eqc_i = eq::EqClassIterator(r, d_equalityEngine);
1867
444368
      while (!eqc_i.isFinished())
1868
      {
1869
195628
        termSet.insert(*eqc_i);
1870
195628
        ++eqc_i;
1871
      }
1872
    }
1873
259920
    ++eqcs_i;
1874
  }
1875
9868
}
1876
1877
std::pair<bool, Node> TheoryDatatypes::entailmentCheck(TNode lit)
1878
{
1879
  Trace("dt-entail") << "Check entailed : " << lit << std::endl;
1880
  Node atom = lit.getKind()==NOT ? lit[0] : lit;
1881
  bool pol = lit.getKind()!=NOT;
1882
  if( atom.getKind()==APPLY_TESTER ){
1883
    Node n = atom[0];
1884
    if( hasTerm( n ) ){
1885
      Node r = d_equalityEngine->getRepresentative(n);
1886
      EqcInfo * ei = getOrMakeEqcInfo( r, false );
1887
      int l_index = getLabelIndex( ei, r );
1888
      int t_index = static_cast<int>(utils::indexOf(atom.getOperator()));
1889
      Trace("dt-entail") << "  Tester indices are " << t_index << " and " << l_index << std::endl;
1890
      if( l_index!=-1 && (l_index==t_index)==pol ){
1891
        std::vector< TNode > exp_c;
1892
        Node eqToExplain;
1893
        if( ei && !ei->d_constructor.get().isNull() ){
1894
          eqToExplain = n.eqNode(ei->d_constructor.get());
1895
        }else{
1896
          Node lbl = getLabel( n );
1897
          Assert(!lbl.isNull());
1898
          exp_c.push_back( lbl );
1899
          Assert(areEqual(n, lbl[0]));
1900
          eqToExplain = n.eqNode(lbl[0]);
1901
        }
1902
        d_equalityEngine->explainLit(eqToExplain, exp_c);
1903
        Node exp = NodeManager::currentNM()->mkAnd(exp_c);
1904
        Trace("dt-entail") << "  entailed, explanation is " << exp << std::endl;
1905
        return make_pair(true, exp);
1906
      }
1907
    }
1908
  }
1909
  return make_pair(false, Node::null());
1910
}
1911
1912
}  // namespace datatypes
1913
}  // namespace theory
1914
29322
}  // namespace cvc5