GCC Code Coverage Report
Directory: . Exec Total Coverage
File: src/theory/datatypes/theory_datatypes.cpp Lines: 1009 1139 88.6 %
Date: 2021-09-07 Branches: 2305 5134 44.9 %

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
9926
TheoryDatatypes::TheoryDatatypes(Env& env,
51
                                 OutputChannel& out,
52
9926
                                 Valuation valuation)
53
    : Theory(THEORY_DATATYPES, env, out, valuation),
54
9926
      d_term_sk(getUserContext()),
55
      d_labels(getSatContext()),
56
      d_selector_apps(getSatContext()),
57
      d_collectTermsCache(getSatContext()),
58
9926
      d_collectTermsCacheU(getUserContext()),
59
      d_functionTerms(getSatContext()),
60
9926
      d_singleton_eq(getUserContext()),
61
      d_sygusExtension(nullptr),
62
      d_state(env, valuation),
63
      d_im(*this, d_state, d_pnm),
64
39704
      d_notify(d_im, *this)
65
{
66
67
9926
  d_true = NodeManager::currentNM()->mkConst( true );
68
9926
  d_zero = NodeManager::currentNM()->mkConst( Rational(0) );
69
9926
  d_dtfCounter = 0;
70
71
  // indicate we are using the default theory state object
72
9926
  d_theoryState = &d_state;
73
9926
  d_inferManager = &d_im;
74
9926
}
75
76
29769
TheoryDatatypes::~TheoryDatatypes() {
77
35301
  for(std::map< Node, EqcInfo* >::iterator i = d_eqc_info.begin(), iend = d_eqc_info.end();
78
35301
      i != iend; ++i){
79
25378
    EqcInfo* current = (*i).second;
80
25378
    Assert(current != NULL);
81
25378
    delete current;
82
  }
83
19846
}
84
85
9926
TheoryRewriter* TheoryDatatypes::getTheoryRewriter() { return &d_rewriter; }
86
87
3786
ProofRuleChecker* TheoryDatatypes::getProofChecker() { return &d_checker; }
88
89
9926
bool TheoryDatatypes::needsEqualityEngine(EeSetupInfo& esi)
90
{
91
9926
  esi.d_notify = &d_notify;
92
9926
  esi.d_name = "theory::datatypes::ee";
93
  // need notifications on new constructors, merging datatype eqcs
94
9926
  esi.d_notifyNewClass = true;
95
9926
  esi.d_notifyMerge = true;
96
9926
  return true;
97
}
98
99
9926
void TheoryDatatypes::finishInit()
100
{
101
9926
  Assert(d_equalityEngine != nullptr);
102
  // The kinds we are treating as function application in congruence
103
9926
  d_equalityEngine->addFunctionKind(kind::APPLY_CONSTRUCTOR);
104
9926
  d_equalityEngine->addFunctionKind(kind::APPLY_SELECTOR_TOTAL);
105
9926
  d_equalityEngine->addFunctionKind(kind::APPLY_TESTER);
106
  // We could but don't do congruence for DT_SIZE and DT_HEIGHT_BOUND here.
107
  // It also could make sense in practice to do congruence for APPLY_UF, but
108
  // this is not done.
109
9926
  if (getQuantifiersEngine() && options::sygus())
110
  {
111
    quantifiers::TermDbSygus* tds =
112
1191
        getQuantifiersEngine()->getTermDatabaseSygus();
113
1191
    d_sygusExtension.reset(new SygusExtension(d_state, d_im, tds));
114
    // do congruence on evaluation functions
115
1191
    d_equalityEngine->addFunctionKind(kind::DT_SYGUS_EVAL);
116
  }
117
  // testers are not relevant for model building
118
9926
  d_valuation.setIrrelevantKind(APPLY_TESTER);
119
9926
}
120
121
2033309
TheoryDatatypes::EqcInfo* TheoryDatatypes::getOrMakeEqcInfo( TNode n, bool doMake ){
122
2033309
  if( !hasEqcInfo( n ) ){
123
437918
    if( doMake ){
124
      //add to labels
125
145177
      d_labels[ n ] = 0;
126
127
145177
      std::map< Node, EqcInfo* >::iterator eqc_i = d_eqc_info.find( n );
128
      EqcInfo* ei;
129
145177
      if( eqc_i != d_eqc_info.end() ){
130
119799
        ei = eqc_i->second;
131
      }else{
132
25378
        ei = new EqcInfo( getSatContext() );
133
25378
        d_eqc_info[n] = ei;
134
      }
135
145177
      if( n.getKind()==APPLY_CONSTRUCTOR ){
136
101982
        ei->d_constructor = n;
137
      }
138
139
      //add to selectors
140
145177
      d_selector_apps[n] = 0;
141
142
145177
      return ei;
143
    }else{
144
292741
      return NULL;
145
    }
146
  }else{
147
1595391
    std::map< Node, EqcInfo* >::iterator eqc_i = d_eqc_info.find( n );
148
1595391
    return (*eqc_i).second;
149
  }
150
}
151
152
532700
TNode TheoryDatatypes::getEqcConstructor( TNode r ) {
153
532700
  if( r.getKind()==APPLY_CONSTRUCTOR ){
154
346649
    return r;
155
  }else{
156
186051
    EqcInfo * ei = getOrMakeEqcInfo( r, false );
157
186051
    if( ei && !ei->d_constructor.get().isNull() ){
158
59106
      return ei->d_constructor.get();
159
    }else{
160
126945
      return r;
161
    }
162
  }
163
}
164
165
472636
bool TheoryDatatypes::preCheck(Effort level)
166
{
167
945272
  Trace("datatypes-check") << "TheoryDatatypes::preCheck: " << level
168
472636
                           << std::endl;
169
472636
  d_im.process();
170
472636
  d_im.reset();
171
472636
  return false;
172
}
173
174
472636
void TheoryDatatypes::postCheck(Effort level)
175
{
176
945272
  Trace("datatypes-check") << "TheoryDatatypes::postCheck: " << level
177
472636
                           << std::endl;
178
  // Apply any last pending inferences, which may occur if the last processed
179
  // fact was an internal one and triggered further internal inferences.
180
472636
  d_im.process();
181
472636
  if (level == EFFORT_LAST_CALL)
182
  {
183
5567
    Assert(d_sygusExtension != nullptr);
184
5567
    d_sygusExtension->check();
185
  }
186
966827
  else if (level == EFFORT_FULL && !d_state.isInConflict()
187
499483
           && !d_im.hasSentLemma() && !d_valuation.needCheck())
188
  {
189
    //check for cycles
190
28677
    Assert(!d_im.hasPendingFact());
191
4
    do {
192
28681
      d_im.reset();
193
28681
      Trace("datatypes-proc") << "Check cycles..." << std::endl;
194
28681
      checkCycles();
195
28681
      Trace("datatypes-proc") << "...finish check cycles" << std::endl;
196
28681
      d_im.process();
197
28681
      if (d_state.isInConflict() || d_im.hasSentLemma())
198
      {
199
143
        return;
200
      }
201
28538
    } while (d_im.hasSentFact());
202
203
    //check for splits
204
28534
    Trace("datatypes-debug") << "Check for splits " << endl;
205
1325
    do {
206
29859
      d_im.reset();
207
59718
      std::map< TypeNode, Node > rec_singletons;
208
29859
      eq::EqClassesIterator eqcs_i = eq::EqClassesIterator(d_equalityEngine);
209
927511
      while( !eqcs_i.isFinished() ){
210
898933
        Node n = (*eqcs_i);
211
        //TODO : avoid irrelevant (pre-registered but not asserted) terms here?
212
898933
        TypeNode tn = n.getType();
213
450107
        if( tn.isDatatype() ){
214
147319
          Trace("datatypes-debug") << "Process equivalence class " << n << std::endl;
215
147319
          EqcInfo* eqc = getOrMakeEqcInfo( n );
216
          //if there are more than 1 possible constructors for eqc
217
147319
          if( !hasLabel( eqc, n ) ){
218
34030
            Trace("datatypes-debug") << "No constructor..." << std::endl;
219
66779
            TypeNode tt = tn;
220
34030
            const DType& dt = tt.getDType();
221
68060
            Trace("datatypes-debug")
222
68060
                << "Datatype " << dt.getName() << " is "
223
68060
                << dt.getCardinalityClass(tt) << " "
224
34030
                << dt.isRecursiveSingleton(tt) << std::endl;
225
34030
            bool continueProc = true;
226
34030
            if( dt.isRecursiveSingleton( tt ) ){
227
8
              Trace("datatypes-debug") << "Check recursive singleton..." << std::endl;
228
              //handle recursive singleton case
229
8
              std::map< TypeNode, Node >::iterator itrs = rec_singletons.find( tn );
230
8
              if( itrs!=rec_singletons.end() ){
231
8
                Node eq = n.eqNode( itrs->second );
232
4
                if( d_singleton_eq.find( eq )==d_singleton_eq.end() ){
233
4
                  d_singleton_eq[eq] = true;
234
                  // get assumptions
235
4
                  bool success = true;
236
8
                  std::vector< Node > assumptions;
237
                  //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,
238
                  //  do not infer the equality if at least one sort was processed.
239
                  //otherwise, if the logic is quantified, under the assumption that all uninterpreted sorts have cardinality one,
240
                  //  infer the equality.
241
4
                  for( unsigned i=0; i<dt.getNumRecursiveSingletonArgTypes( tt ); i++ ){
242
                    TypeNode type = dt.getRecursiveSingletonArgType(tt, i);
243
                    if( getQuantifiersEngine() ){
244
                      // under the assumption that the cardinality of this type is one
245
                      Node a = getSingletonLemma(type, true);
246
                      assumptions.push_back( a.negate() );
247
                    }else{
248
                      success = false;
249
                      // assert that the cardinality of this type is more than one
250
                      getSingletonLemma(type, false);
251
                    }
252
                  }
253
4
                  if( success ){
254
8
                    Node assumption = n.eqNode(itrs->second);
255
4
                    assumptions.push_back(assumption);
256
8
                    Node lemma = assumptions.size()==1 ? assumptions[0] : NodeManager::currentNM()->mkNode( OR, assumptions );
257
4
                    Trace("dt-singleton") << "*************Singleton equality lemma " << lemma << std::endl;
258
4
                    d_im.lemma(lemma, InferenceId::DATATYPES_REC_SINGLETON_EQ);
259
                  }
260
                }
261
              }else{
262
4
                rec_singletons[tn] = n;
263
              }
264
              //do splitting for quantified logics (incomplete anyways)
265
8
              continueProc = ( getQuantifiersEngine()!=NULL );
266
            }
267
34030
            if( continueProc ){
268
34030
              Trace("datatypes-debug") << "Get possible cons..." << std::endl;
269
              //all other cases
270
66779
              std::vector< bool > pcons;
271
34030
              getPossibleCons( eqc, n, pcons );
272
              //check if we do not need to resolve the constructor type for this equivalence class.
273
              // this is if there are no selectors for this equivalence class, and its possible values are infinite,
274
              //  then do not split.
275
34030
              int consIndex = -1;
276
34030
              int fconsIndex = -1;
277
34030
              bool needSplit = true;
278
129107
              for (size_t j = 0, psize = pcons.size(); j < psize; j++)
279
              {
280
95077
                if( pcons[j] ) {
281
93855
                  if( consIndex==-1 ){
282
33924
                    consIndex = j;
283
                  }
284
187710
                  Trace("datatypes-debug") << j << " compute finite..."
285
93855
                                           << std::endl;
286
                  // Notice that we split here on all datatypes except the
287
                  // truly infinite ones. It is possible to also not split
288
                  // on those that are interpreted-finite when finite model
289
                  // finding is disabled, but as a heuristic we choose to split
290
                  // on those too.
291
187710
                  bool ifin = dt[j].getCardinalityClass(tt)
292
93855
                              != CardinalityClass::INFINITE;
293
187710
                  Trace("datatypes-debug") << "...returned " << ifin
294
93855
                                           << std::endl;
295
93855
                  if (!ifin)
296
                  {
297
55075
                    if( !eqc || !eqc->d_selectors ){
298
51385
                      needSplit = false;
299
                    }
300
                  }else{
301
38780
                    if( fconsIndex==-1 ){
302
29962
                      fconsIndex = j;
303
                    }
304
                  }
305
                }
306
              }
307
              //if we want to force an assignment of constructors to all ground eqc
308
              //d_dtfCounter++;
309
34030
              if( !needSplit && options::dtForceAssignment() && d_dtfCounter%2==0 ){
310
                Trace("datatypes-force-assign") << "Force assignment for " << n << std::endl;
311
                needSplit = true;
312
                consIndex = fconsIndex!=-1 ? fconsIndex : consIndex;
313
              }
314
315
34030
              if( needSplit ) {
316
17218
                if( dt.getNumConstructors()==1 ){
317
                  //this may not be necessary?
318
                  //if only one constructor, then this term must be this constructor
319
31874
                  Node t = utils::mkTester(n, 0, dt);
320
15937
                  d_im.addPendingInference(
321
                      t, InferenceId::DATATYPES_SPLIT, d_true);
322
15937
                  Trace("datatypes-infer") << "DtInfer : 1-cons (full) : " << t << std::endl;
323
                }else{
324
1281
                  Assert(consIndex != -1 || dt.isSygus());
325
1281
                  if( options::dtBinarySplit() && consIndex!=-1 ){
326
                    Node test = utils::mkTester(n, consIndex, dt);
327
                    Trace("dt-split") << "*************Split for possible constructor " << dt[consIndex] << " for " << n << endl;
328
                    test = Rewriter::rewrite( test );
329
                    NodeBuilder nb(kind::OR);
330
                    nb << test << test.notNode();
331
                    Node lemma = nb;
332
                    d_im.lemma(lemma, InferenceId::DATATYPES_BINARY_SPLIT);
333
                    d_im.requirePhase(test, true);
334
                  }else{
335
1281
                    Trace("dt-split") << "*************Split for constructors on " << n <<  endl;
336
2562
                    Node lemma = utils::mkSplit(n, dt);
337
1281
                    Trace("dt-split-debug") << "Split lemma is : " << lemma << std::endl;
338
1281
                    d_im.sendDtLemma(lemma,
339
                                     InferenceId::DATATYPES_SPLIT,
340
                                     LemmaProperty::SEND_ATOMS);
341
                  }
342
1281
                  if( !options::dtBlastSplits() ){
343
1281
                    break;
344
                  }
345
                }
346
              }else{
347
16812
                Trace("dt-split-debug") << "Do not split constructor for " << n << " : " << n.getType() << " " << dt.getNumConstructors() << std::endl;
348
              }
349
            }
350
          }else{
351
113289
            Trace("datatypes-debug") << "Has constructor " << eqc->d_constructor.get() << std::endl;
352
          }
353
        }
354
448826
        ++eqcs_i;
355
      }
356
29859
      if (d_im.hasSentLemma())
357
      {
358
        // clear pending facts: we added a lemma, so internal inferences are
359
        // no longer necessary
360
1240
        d_im.clearPendingFacts();
361
      }
362
      else
363
      {
364
        // we did not add a lemma, process internal inferences. This loop
365
        // will repeat.
366
28619
        Trace("datatypes-debug") << "Flush pending facts..." << std::endl;
367
28619
        d_im.process();
368
      }
369
58799
    } while (!d_state.isInConflict() && !d_im.hasSentLemma()
370
57293
             && d_im.hasSentFact());
371
57068
    Trace("datatypes-debug")
372
57068
        << "Finished, conflict=" << d_state.isInConflict()
373
28534
        << ", lemmas=" << d_im.hasSentLemma() << std::endl;
374
28534
    if (!d_state.isInConflict())
375
    {
376
27615
      Trace("dt-model-debug") << std::endl;
377
27615
      printModelDebug("dt-model-debug");
378
    }
379
  }
380
381
472493
  Trace("datatypes-check") << "Finished check effort " << level << std::endl;
382
472493
  if( Debug.isOn("datatypes") || Debug.isOn("datatypes-split") ) {
383
    Notice() << "TheoryDatatypes::check(): done" << endl;
384
  }
385
}
386
387
11180
bool TheoryDatatypes::needsCheckLastEffort() {
388
11180
  return d_sygusExtension != nullptr;
389
}
390
391
1698158
void TheoryDatatypes::notifyFact(TNode atom,
392
                                 bool polarity,
393
                                 TNode fact,
394
                                 bool isInternal)
395
{
396
3396316
  Trace("datatypes-debug") << "TheoryDatatypes::assertFact : " << fact
397
1698158
                           << ", isInternal = " << isInternal << std::endl;
398
  // could be sygus-specific
399
1698158
  if (d_sygusExtension)
400
  {
401
1332065
    d_sygusExtension->assertFact(atom, polarity);
402
  }
403
  //add to tester if applicable
404
3396316
  Node t_arg;
405
1698158
  int tindex = utils::isTester(atom, t_arg);
406
1698158
  if (tindex >= 0)
407
  {
408
742453
    Trace("dt-tester") << "Assert tester : " << atom << " for " << t_arg << std::endl;
409
1484906
    Node rep = getRepresentative( t_arg );
410
742453
    EqcInfo* eqc = getOrMakeEqcInfo( rep, true );
411
    Node tst =
412
1484906
        isInternal ? (polarity ? Node(atom) : atom.notNode()) : Node(fact);
413
742453
    addTester(tindex, tst, eqc, rep, t_arg);
414
742453
    Trace("dt-tester") << "Done assert tester." << std::endl;
415
742453
    Trace("dt-tester") << "Done pending merges." << std::endl;
416
742453
    if (!d_state.isInConflict() && polarity)
417
    {
418
214481
      if (d_sygusExtension)
419
      {
420
166351
        Trace("dt-tester") << "Assert tester to sygus : " << atom << std::endl;
421
166351
        d_sygusExtension->assertTester(tindex, t_arg, atom);
422
166351
        Trace("dt-tester") << "Done assert tester to sygus." << std::endl;
423
      }
424
    }
425
  }else{
426
955705
    Trace("dt-tester-debug") << "Assert (non-tester) : " << atom << std::endl;
427
  }
428
1698158
  Trace("datatypes-debug") << "TheoryDatatypes::assertFact : finished " << fact << std::endl;
429
  // now, flush pending facts if this wasn't an internal call
430
1698158
  if (!isInternal)
431
  {
432
1421324
    d_im.process();
433
  }
434
1698158
}
435
436
175838
void TheoryDatatypes::preRegisterTerm(TNode n)
437
{
438
351676
  Trace("datatypes-prereg")
439
175838
      << "TheoryDatatypes::preRegisterTerm() " << n << endl;
440
  // external selectors should be preprocessed away by now
441
175838
  Assert(n.getKind() != APPLY_SELECTOR);
442
  // must ensure the type is well founded and has no nested recursion if
443
  // the option dtNestedRec is not set to true.
444
351676
  TypeNode tn = n.getType();
445
175838
  if (tn.isDatatype())
446
  {
447
70253
    const DType& dt = tn.getDType();
448
70253
    Trace("dt-expand") << "Check properties of " << dt.getName() << std::endl;
449
70253
    if (!dt.isWellFounded())
450
    {
451
      std::stringstream ss;
452
      ss << "Cannot handle non-well-founded datatype " << dt.getName();
453
      throw LogicException(ss.str());
454
    }
455
70253
    Trace("dt-expand") << "...well-founded ok" << std::endl;
456
70253
    if (!options::dtNestedRec())
457
    {
458
70025
      if (dt.hasNestedRecursion())
459
      {
460
2
        std::stringstream ss;
461
1
        ss << "Cannot handle nested-recursive datatype " << dt.getName();
462
1
        throw LogicException(ss.str());
463
      }
464
70024
      Trace("dt-expand") << "...nested recursion ok" << std::endl;
465
    }
466
  }
467
175837
  collectTerms( n );
468
175837
  switch (n.getKind()) {
469
79957
  case kind::EQUAL:
470
  case kind::APPLY_TESTER:
471
    // add predicate trigger for testers and equalities
472
    // Get triggered for both equal and dis-equal
473
79957
    d_equalityEngine->addTriggerPredicate(n);
474
79957
    break;
475
95880
  default:
476
    // Function applications/predicates
477
95880
    d_equalityEngine->addTerm(n);
478
95880
    if (d_sygusExtension)
479
    {
480
21171
      d_sygusExtension->preRegisterTerm(n);
481
    }
482
95880
    break;
483
  }
484
175837
  d_im.process();
485
175837
}
486
487
80345
TrustNode TheoryDatatypes::ppRewrite(TNode in, std::vector<SkolemLemma>& lems)
488
{
489
80345
  Debug("tuprec") << "TheoryDatatypes::ppRewrite(" << in << ")" << endl;
490
  // first, see if we need to expand definitions
491
160690
  TrustNode texp = d_rewriter.expandDefinition(in);
492
80345
  if (!texp.isNull())
493
  {
494
4238
    return texp;
495
  }
496
76107
  if( in.getKind()==EQUAL ){
497
8288
    Node nn;
498
8288
    std::vector< Node > rew;
499
4190
    if (utils::checkClash(in[0], in[1], rew))
500
    {
501
      nn = NodeManager::currentNM()->mkConst(false);
502
    }
503
    else
504
    {
505
12498
      nn = rew.size()==0 ? d_true :
506
8308
                ( rew.size()==1 ? rew[0] : NodeManager::currentNM()->mkNode( kind::AND, rew ) );
507
    }
508
4190
    if (in != nn)
509
    {
510
92
      return TrustNode::mkTrustRewrite(in, nn, nullptr);
511
    }
512
  }
513
514
  // nothing to do
515
76015
  return TrustNode::null();
516
}
517
518
48411
TrustNode TheoryDatatypes::explain(TNode literal)
519
{
520
48411
  return d_im.explainLit(literal);
521
}
522
523
/** called when a new equivalance class is created */
524
296112
void TheoryDatatypes::eqNotifyNewClass(TNode t){
525
296112
  if( t.getKind()==APPLY_CONSTRUCTOR ){
526
101982
    getOrMakeEqcInfo( t, true );
527
  }
528
296112
}
529
530
/** called when two equivalance classes have merged */
531
1889088
void TheoryDatatypes::eqNotifyMerge(TNode t1, TNode t2)
532
{
533
1889088
  if( t1.getType().isDatatype() ){
534
899338
    Trace("datatypes-merge")
535
449669
        << "NotifyMerge : " << t1 << " " << t2 << std::endl;
536
449669
    merge(t1, t2);
537
  }
538
1889088
}
539
540
449669
void TheoryDatatypes::merge( Node t1, Node t2 ){
541
449669
  if (d_state.isInConflict())
542
  {
543
129862
    return;
544
  }
545
449539
  Trace("datatypes-merge") << "Merge " << t1 << " " << t2 << std::endl;
546
449539
  Assert(areEqual(t1, t2));
547
769476
  TNode trep1 = t1;
548
769476
  TNode trep2 = t2;
549
449539
  EqcInfo* eqc2 = getOrMakeEqcInfo(t2);
550
449539
  if (eqc2 == nullptr)
551
  {
552
128244
    return;
553
  }
554
321295
  bool checkInst = false;
555
321295
  if (!eqc2->d_constructor.get().isNull())
556
  {
557
102648
    trep2 = eqc2->d_constructor.get();
558
  }
559
321295
  EqcInfo* eqc1 = getOrMakeEqcInfo(t1);
560
321295
  if (eqc1)
561
  {
562
617010
    Trace("datatypes-debug")
563
308505
        << "  merge eqc info " << eqc2 << " into " << eqc1 << std::endl;
564
308505
    if (!eqc1->d_constructor.get().isNull())
565
    {
566
255276
      trep1 = eqc1->d_constructor.get();
567
    }
568
    // check for clash
569
616024
    TNode cons1 = eqc1->d_constructor.get();
570
616024
    TNode cons2 = eqc2->d_constructor.get();
571
    // if both have constructor, then either clash or unification
572
308505
    if (!cons1.isNull() && !cons2.isNull())
573
    {
574
118370
      Trace("datatypes-debug")
575
59185
          << "  constructors : " << cons1 << " " << cons2 << std::endl;
576
117389
      Node unifEq = cons1.eqNode(cons2);
577
117389
      std::vector<Node> rew;
578
59185
      if (utils::checkClash(cons1, cons2, rew))
579
      {
580
1962
        std::vector<Node> conf;
581
981
        conf.push_back(unifEq);
582
1962
        Trace("dt-conflict")
583
981
            << "CONFLICT: Clash conflict : " << conf << std::endl;
584
981
        d_im.sendDtConflict(conf, InferenceId::DATATYPES_CLASH_CONFLICT);
585
981
        return;
586
      }
587
      else
588
      {
589
58204
        Assert(areEqual(cons1, cons2));
590
        // do unification
591
171120
        for (size_t i = 0, nchild = cons1.getNumChildren(); i < nchild; i++)
592
        {
593
112916
          if (!areEqual(cons1[i], cons2[i]))
594
          {
595
59496
            Node eq = cons1[i].eqNode(cons2[i]);
596
29748
            d_im.addPendingInference(eq, InferenceId::DATATYPES_UNIF, unifEq);
597
59496
            Trace("datatypes-infer") << "DtInfer : cons-inj : " << eq << " by "
598
29748
                                     << unifEq << std::endl;
599
          }
600
        }
601
      }
602
    }
603
615048
    Trace("datatypes-debug") << "  instantiated : " << eqc1->d_inst << " "
604
307524
                             << eqc2->d_inst << std::endl;
605
307524
    eqc1->d_inst = eqc1->d_inst || eqc2->d_inst;
606
307524
    if (!cons2.isNull())
607
    {
608
94475
      if (cons1.isNull())
609
      {
610
72542
        Trace("datatypes-debug")
611
36271
            << "  must check if it is okay to set the constructor."
612
36271
            << std::endl;
613
36271
        checkInst = true;
614
36271
        addConstructor(eqc2->d_constructor.get(), eqc1, t1);
615
36271
        if (d_state.isInConflict())
616
        {
617
5
          return;
618
        }
619
      }
620
    }
621
  }
622
  else
623
  {
624
25580
    Trace("datatypes-debug")
625
12790
        << "  no eqc info for " << t1 << ", must create" << std::endl;
626
    // just copy the equivalence class information
627
12790
    eqc1 = getOrMakeEqcInfo(t1, true);
628
12790
    eqc1->d_inst.set(eqc2->d_inst);
629
12790
    eqc1->d_constructor.set(eqc2->d_constructor);
630
12790
    eqc1->d_selectors.set(eqc2->d_selectors);
631
  }
632
633
  // merge labels
634
320309
  NodeUIntMap::iterator lbl_i = d_labels.find(t2);
635
320309
  if (lbl_i != d_labels.end())
636
  {
637
640618
    Trace("datatypes-debug")
638
320309
        << "  merge labels from " << eqc2 << " " << t2 << std::endl;
639
320309
    size_t n_label = (*lbl_i).second;
640
560822
    for (size_t i = 0; i < n_label; i++)
641
    {
642
240885
      Assert(i < d_labels_data[t2].size());
643
481398
      Node t = d_labels_data[t2][i];
644
481398
      Node t_arg = d_labels_args[t2][i];
645
240885
      unsigned tindex = d_labels_tindex[t2][i];
646
240885
      addTester(tindex, t, eqc1, t1, t_arg);
647
240885
      if (d_state.isInConflict())
648
      {
649
372
        Trace("datatypes-debug") << "  conflict!" << std::endl;
650
372
        return;
651
      }
652
    }
653
  }
654
  // merge selectors
655
319937
  if (!eqc1->d_selectors && eqc2->d_selectors)
656
  {
657
49444
    eqc1->d_selectors = true;
658
49444
    checkInst = true;
659
  }
660
319937
  NodeUIntMap::iterator sel_i = d_selector_apps.find(t2);
661
319937
  if (sel_i != d_selector_apps.end())
662
  {
663
639874
    Trace("datatypes-debug")
664
319937
        << "  merge selectors from " << eqc2 << " " << t2 << std::endl;
665
319937
    size_t n_sel = (*sel_i).second;
666
722352
    for (size_t j = 0; j < n_sel; j++)
667
    {
668
402415
      addSelector(d_selector_apps_data[t2][j],
669
                  eqc1,
670
                  t1,
671
402415
                  eqc2->d_constructor.get().isNull());
672
    }
673
  }
674
319937
  if (checkInst)
675
  {
676
85710
    Trace("datatypes-debug") << "  checking instantiate" << std::endl;
677
85710
    instantiate(eqc1, t1);
678
  }
679
319937
  Trace("datatypes-debug") << "Finished Merge " << t1 << " " << t2 << std::endl;
680
}
681
682
25378
TheoryDatatypes::EqcInfo::EqcInfo(context::Context* c)
683
    : d_inst(c, false),
684
50756
      d_constructor(c, Node::null()),
685
76134
      d_selectors(c, false)
686
25378
{}
687
688
147319
bool TheoryDatatypes::hasLabel( EqcInfo* eqc, Node n ){
689
147319
  return ( eqc && !eqc->d_constructor.get().isNull() ) || !getLabel( n ).isNull();
690
}
691
692
638800
Node TheoryDatatypes::getLabel( Node n ) {
693
638800
  NodeUIntMap::iterator lbl_i = d_labels.find(n);
694
638800
  if( lbl_i != d_labels.end() ){
695
584074
    size_t n_lbl = (*lbl_i).second;
696
584074
    if( n_lbl>0 && d_labels_data[n][ n_lbl-1 ].getKind()!=kind::NOT ){
697
199521
      return d_labels_data[n][ n_lbl-1 ];
698
    }
699
  }
700
439279
  return Node::null();
701
}
702
703
1238829
int TheoryDatatypes::getLabelIndex( EqcInfo* eqc, Node n ){
704
1238829
  if( eqc && !eqc->d_constructor.get().isNull() ){
705
733124
    return utils::indexOf(eqc->d_constructor.get().getOperator());
706
  }else{
707
1011410
    Node lbl = getLabel( n );
708
505705
    if( lbl.isNull() ){
709
405249
      return -1;
710
    }else{
711
100456
      int tindex = utils::isTester(lbl);
712
200912
      Trace("datatypes-debug") << "Label of " << n << " is " << lbl
713
100456
                               << " with tindex " << tindex << std::endl;
714
100456
      Assert(tindex != -1);
715
100456
      return tindex;
716
    }
717
  }
718
}
719
720
8492
bool TheoryDatatypes::hasTester( Node n ) {
721
8492
  NodeUIntMap::iterator lbl_i = d_labels.find(n);
722
8492
  if( lbl_i != d_labels.end() ){
723
2
    return (*lbl_i).second>0;
724
  }else{
725
8490
    return false;
726
  }
727
}
728
729
71162
void TheoryDatatypes::getPossibleCons( EqcInfo* eqc, Node n, std::vector< bool >& pcons ){
730
142324
  TypeNode tn = n.getType();
731
71162
  const DType& dt = tn.getDType();
732
71162
  int lindex = getLabelIndex( eqc, n );
733
71162
  pcons.resize( dt.getNumConstructors(), lindex==-1 );
734
71162
  if( lindex!=-1 ){
735
    pcons[ lindex ] = true;
736
  }else{
737
71162
    NodeUIntMap::iterator lbl_i = d_labels.find(n);
738
71162
    if( lbl_i != d_labels.end() ){
739
43799
      size_t n_lbl = (*lbl_i).second;
740
221205
      for (size_t i = 0; i < n_lbl; i++)
741
      {
742
177406
        Assert(d_labels_data[n][i].getKind() == NOT);
743
177406
        unsigned tindex = d_labels_tindex[n][i];
744
177406
        pcons[ tindex ] = false;
745
      }
746
    }
747
  }
748
71162
}
749
750
111509
Node TheoryDatatypes::getTermSkolemFor( Node n ) {
751
111509
  if( n.getKind()==APPLY_CONSTRUCTOR ){
752
12890
    NodeMap::const_iterator it = d_term_sk.find( n );
753
12890
    if( it==d_term_sk.end() ){
754
1251
      NodeManager* nm = NodeManager::currentNM();
755
1251
      SkolemManager* sm = nm->getSkolemManager();
756
      //add purification unit lemma ( k = n )
757
2502
      Node k = sm->mkPurifySkolem(n, "kdt");
758
1251
      d_term_sk[n] = k;
759
2502
      Node eq = k.eqNode( n );
760
1251
      Trace("datatypes-infer") << "DtInfer : ref : " << eq << std::endl;
761
1251
      d_im.addPendingLemma(eq, InferenceId::DATATYPES_PURIFY);
762
1251
      return k;
763
    }else{
764
11639
      return (*it).second;
765
    }
766
  }else{
767
98619
    return n;
768
  }
769
}
770
771
983338
void TheoryDatatypes::addTester(
772
    unsigned ttindex, Node t, EqcInfo* eqc, Node n, Node t_arg)
773
{
774
983338
  Trace("datatypes-debug") << "Add tester : " << t << " to eqc(" << n << ")" << std::endl;
775
983338
  Debug("datatypes-labels") << "Add tester " << t << " " << n << " " << eqc << std::endl;
776
983338
  bool tpolarity = t.getKind()!=NOT;
777
983338
  Assert((tpolarity ? t : t[0]).getKind() == APPLY_TESTER);
778
1261981
  Node j, jt;
779
983338
  bool makeConflict = false;
780
983338
  int prevTIndex = getLabelIndex(eqc, n);
781
983338
  if (prevTIndex >= 0)
782
  {
783
649430
    unsigned ptu = static_cast<unsigned>(prevTIndex);
784
    //if we already know the constructor type, check whether it is in conflict or redundant
785
649430
    if ((ptu == ttindex) != tpolarity)
786
    {
787
1235
      if( !eqc->d_constructor.get().isNull() ){
788
        //conflict because equivalence class contains a constructor
789
2470
        std::vector<Node> conf;
790
1235
        conf.push_back(t);
791
1235
        conf.push_back(t_arg.eqNode(eqc->d_constructor.get()));
792
2470
        Trace("dt-conflict")
793
1235
            << "CONFLICT: Tester eq conflict " << conf << std::endl;
794
1235
        d_im.sendDtConflict(conf, InferenceId::DATATYPES_TESTER_CONFLICT);
795
1235
        return;
796
      }else{
797
        makeConflict = true;
798
        //conflict because the existing label is contradictory
799
        j = getLabel( n );
800
        jt = j;
801
      }
802
    }else{
803
648195
      return;
804
    }
805
  }else{
806
    //otherwise, scan list of labels
807
333908
    NodeUIntMap::iterator lbl_i = d_labels.find(n);
808
333908
    Assert(lbl_i != d_labels.end());
809
333908
    size_t n_lbl = (*lbl_i).second;
810
612551
    std::map< int, bool > neg_testers;
811
1250323
    for (size_t i = 0; i < n_lbl; i++)
812
    {
813
934658
      Assert(d_labels_data[n][i].getKind() == NOT);
814
934658
      unsigned jtindex = d_labels_tindex[n][i];
815
934658
      if( jtindex==ttindex ){
816
18243
        if( tpolarity ){  //we are in conflict
817
108
          j = d_labels_data[n][i];
818
108
          jt = j[0];
819
108
          makeConflict = true;
820
108
          break;
821
        }else{            //it is redundant
822
18135
          return;
823
        }
824
      }else{
825
916415
        neg_testers[jtindex] = true;
826
      }
827
    }
828
315773
    if( !makeConflict ){
829
315665
      Debug("datatypes-labels") << "Add to labels " << t << std::endl;
830
315665
      d_labels[n] = n_lbl + 1;
831
315665
      if (n_lbl < d_labels_data[n].size())
832
      {
833
        // reuse spot in the vector
834
304816
        d_labels_data[n][n_lbl] = t;
835
304816
        d_labels_args[n][n_lbl] = t_arg;
836
304816
        d_labels_tindex[n][n_lbl] = ttindex;
837
      }else{
838
10849
        d_labels_data[n].push_back(t);
839
10849
        d_labels_args[n].push_back(t_arg);
840
10849
        d_labels_tindex[n].push_back(ttindex);
841
      }
842
315665
      n_lbl++;
843
844
315665
      const DType& dt = t_arg.getType().getDType();
845
315665
      Debug("datatypes-labels") << "Labels at " << n_lbl << " / " << dt.getNumConstructors() << std::endl;
846
315665
      if( tpolarity ){
847
98619
        instantiate(eqc, n);
848
        // We could propagate is-C1(x) => not is-C2(x) here for all other
849
        // constructors, but empirically this hurts performance.
850
      }else{
851
        //check if we have reached the maximum number of testers
852
        // in this case, add the positive tester
853
217046
        if (n_lbl == dt.getNumConstructors() - 1)
854
        {
855
74260
          std::vector< bool > pcons;
856
37130
          getPossibleCons( eqc, n, pcons );
857
37130
          int testerIndex = -1;
858
118980
          for( unsigned i=0; i<pcons.size(); i++ ) {
859
118980
            if( pcons[i] ){
860
37130
              testerIndex = i;
861
37130
              break;
862
            }
863
          }
864
37130
          Assert(testerIndex != -1);
865
          //we must explain why each term in the set of testers for this equivalence class is equal
866
74260
          std::vector< Node > eq_terms;
867
74260
          NodeBuilder nb(kind::AND);
868
213312
          for (unsigned i = 0; i < n_lbl; i++)
869
          {
870
352364
            Node ti = d_labels_data[n][i];
871
176182
            nb << ti;
872
176182
            Assert(ti.getKind() == NOT);
873
352364
            Node t_arg2 = d_labels_args[n][i];
874
176182
            if( std::find( eq_terms.begin(), eq_terms.end(), t_arg2 )==eq_terms.end() ){
875
42115
              eq_terms.push_back( t_arg2 );
876
42115
              if( t_arg2!=t_arg ){
877
4985
                nb << t_arg2.eqNode( t_arg );
878
              }
879
            }
880
          }
881
          Node t_concl = testerIndex == -1
882
                             ? NodeManager::currentNM()->mkConst(false)
883
74260
                             : utils::mkTester(t_arg, testerIndex, dt);
884
74260
          Node t_concl_exp = ( nb.getNumChildren() == 1 ) ? nb.getChild( 0 ) : nb;
885
37130
          d_im.addPendingInference(
886
              t_concl, InferenceId::DATATYPES_LABEL_EXH, t_concl_exp);
887
37130
          Trace("datatypes-infer") << "DtInfer : label : " << t_concl << " by " << t_concl_exp << std::endl;
888
37130
          return;
889
        }
890
      }
891
    }
892
  }
893
278643
  if( makeConflict ){
894
108
    Debug("datatypes-labels") << "Explain " << j << " " << t << std::endl;
895
216
    std::vector<Node> conf;
896
108
    conf.push_back(j);
897
108
    conf.push_back(t);
898
108
    conf.push_back(jt[0].eqNode(t_arg));
899
108
    Trace("dt-conflict") << "CONFLICT: Tester conflict : " << conf << std::endl;
900
108
    d_im.sendDtConflict(conf, InferenceId::DATATYPES_TESTER_MERGE_CONFLICT);
901
  }
902
}
903
904
424746
void TheoryDatatypes::addSelector( Node s, EqcInfo* eqc, Node n, bool assertFacts ) {
905
424746
  Trace("dt-collapse-sel") << "Add selector : " << s << " to eqc(" << n << ")" << std::endl;
906
  //check to see if it is redundant
907
424746
  NodeUIntMap::iterator sel_i = d_selector_apps.find(n);
908
424746
  Assert(sel_i != d_selector_apps.end());
909
424746
  if( sel_i != d_selector_apps.end() ){
910
424746
    size_t n_sel = (*sel_i).second;
911
774309
    for (size_t j = 0; j < n_sel; j++)
912
    {
913
959956
      Node ss = d_selector_apps_data[n][j];
914
610393
      if( s.getOperator()==ss.getOperator() && ( s.getKind()!=DT_HEIGHT_BOUND || s[1]==ss[1] ) ){
915
260830
        Trace("dt-collapse-sel") << "...redundant." << std::endl;
916
260830
        return;
917
      }
918
    }
919
    //add it to the vector
920
    //sel->push_back( s );
921
163916
    d_selector_apps[n] = n_sel + 1;
922
163916
    if (n_sel < d_selector_apps_data[n].size())
923
    {
924
147151
      d_selector_apps_data[n][n_sel] = s;
925
    }else{
926
16765
      d_selector_apps_data[n].push_back( s );
927
    }
928
929
163916
    eqc->d_selectors = true;
930
  }
931
163916
  if( assertFacts && !eqc->d_constructor.get().isNull() ){
932
    //conclude the collapsed merge
933
122679
    collapseSelector( s, eqc->d_constructor.get() );
934
  }
935
}
936
937
36271
void TheoryDatatypes::addConstructor( Node c, EqcInfo* eqc, Node n ){
938
36271
  Trace("datatypes-debug") << "Add constructor : " << c << " to eqc(" << n << ")" << std::endl;
939
36271
  Assert(eqc->d_constructor.get().isNull());
940
  //check labels
941
36271
  NodeUIntMap::iterator lbl_i = d_labels.find(n);
942
36271
  if( lbl_i != d_labels.end() ){
943
36271
    size_t constructorIndex = utils::indexOf(c.getOperator());
944
36271
    size_t n_lbl = (*lbl_i).second;
945
164255
    for (size_t i = 0; i < n_lbl; i++)
946
    {
947
255973
      Node t = d_labels_data[n][i];
948
127989
      if (d_labels_data[n][i].getKind() == NOT)
949
      {
950
93833
        unsigned tindex = d_labels_tindex[n][i];
951
93833
        if (tindex == constructorIndex)
952
        {
953
10
          std::vector<Node> conf;
954
5
          conf.push_back(t);
955
5
          conf.push_back(t[0][0].eqNode(c));
956
10
          Trace("dt-conflict")
957
5
              << "CONFLICT: Tester merge eq conflict : " << conf << std::endl;
958
5
          d_im.sendDtConflict(conf, InferenceId::DATATYPES_TESTER_CONFLICT);
959
5
          return;
960
        }
961
      }
962
    }
963
  }
964
  //check selectors
965
36266
  NodeUIntMap::iterator sel_i = d_selector_apps.find(n);
966
36266
  if( sel_i != d_selector_apps.end() ){
967
36266
    size_t n_sel = (*sel_i).second;
968
141439
    for (size_t j = 0; j < n_sel; j++)
969
    {
970
210346
      Node s = d_selector_apps_data[n][j];
971
      //collapse the selector
972
105173
      collapseSelector( s, c );
973
    }
974
  }
975
36266
  eqc->d_constructor.set( c );
976
}
977
978
227852
void TheoryDatatypes::collapseSelector( Node s, Node c ) {
979
227852
  Assert(c.getKind() == APPLY_CONSTRUCTOR);
980
227852
  Trace("dt-collapse-sel") << "collapse selector : " << s << " " << c << std::endl;
981
455704
  Node r;
982
227852
  bool wrong = false;
983
455704
  Node eq_exp = s[0].eqNode(c);
984
227852
  if( s.getKind()==kind::APPLY_SELECTOR_TOTAL ){
985
338282
    Node selector = s.getOperator();
986
169141
    size_t constructorIndex = utils::indexOf(c.getOperator());
987
169141
    const DType& dt = utils::datatypeOf(selector);
988
169141
    const DTypeConstructor& dtc = dt[constructorIndex];
989
169141
    int selectorIndex = dtc.getSelectorIndexInternal(selector);
990
169141
    wrong = selectorIndex<0;
991
169141
    r = NodeManager::currentNM()->mkNode( kind::APPLY_SELECTOR_TOTAL, s.getOperator(), c );
992
  }
993
227852
  if( !r.isNull() ){
994
338282
    Node rrs;
995
169141
    if (wrong)
996
    {
997
      // Must use make ground term here instead of the rewriter, since we
998
      // do not want to introduce arbitrary values. This is important so that
999
      // we avoid constants for types that are not "closed enumerable", e.g.
1000
      // uninterpreted sorts and arrays, where the solver does not fully
1001
      // handle values of the sort. The call to mkGroundTerm does not introduce
1002
      // values for these sorts.
1003
79548
      rrs = r.getType().mkGroundTerm();
1004
159096
      Trace("datatypes-wrong-sel")
1005
79548
          << "Bad apply " << r << " term = " << rrs
1006
79548
          << ", value = " << r.getType().mkGroundValue() << std::endl;
1007
    }
1008
    else
1009
    {
1010
89593
      rrs = Rewriter::rewrite(r);
1011
    }
1012
169141
    if (s != rrs)
1013
    {
1014
216230
      Node eq = s.eqNode(rrs);
1015
      // Since collapsing selectors may generate new terms, we must send
1016
      // this out as a lemma if it is of an external type, or otherwise we
1017
      // may ask for the equality status of terms that only datatypes knows
1018
      // about, see issue #5344.
1019
108115
      bool forceLemma = !s.getType().isDatatype();
1020
108115
      Trace("datatypes-infer") << "DtInfer : collapse sel";
1021
108115
      Trace("datatypes-infer") << " : " << eq << " by " << eq_exp << std::endl;
1022
108115
      d_im.addPendingInference(
1023
          eq, InferenceId::DATATYPES_COLLAPSE_SEL, eq_exp, forceLemma);
1024
    }
1025
  }
1026
227852
}
1027
1028
131335
EqualityStatus TheoryDatatypes::getEqualityStatus(TNode a, TNode b){
1029
131335
  Assert(d_equalityEngine->hasTerm(a) && d_equalityEngine->hasTerm(b));
1030
131335
  if (d_equalityEngine->areEqual(a, b))
1031
  {
1032
    // The terms are implied to be equal
1033
4810
    return EQUALITY_TRUE;
1034
  }
1035
126525
  if (d_equalityEngine->areDisequal(a, b, false))
1036
  {
1037
    // The terms are implied to be dis-equal
1038
    return EQUALITY_FALSE;
1039
  }
1040
126525
  return EQUALITY_FALSE_IN_MODEL;
1041
}
1042
1043
82824
void TheoryDatatypes::addCarePairs(TNodeTrie* t1,
1044
                                   TNodeTrie* t2,
1045
                                   unsigned arity,
1046
                                   unsigned depth,
1047
                                   unsigned& n_pairs)
1048
{
1049
82824
  if( depth==arity ){
1050
9595
    if( t2!=NULL ){
1051
19190
      Node f1 = t1->getData();
1052
19190
      Node f2 = t2->getData();
1053
9595
      if( !areEqual( f1, f2 ) ){
1054
9595
        Trace("dt-cg") << "Check " << f1 << " and " << f2 << std::endl;
1055
19190
        vector< pair<TNode, TNode> > currentPairs;
1056
28987
        for (unsigned k = 0; k < f1.getNumChildren(); ++ k) {
1057
38784
          TNode x = f1[k];
1058
38784
          TNode y = f2[k];
1059
19392
          Assert(d_equalityEngine->hasTerm(x));
1060
19392
          Assert(d_equalityEngine->hasTerm(y));
1061
19392
          Assert(!areDisequal(x, y));
1062
19392
          Assert(!areCareDisequal(x, y));
1063
19392
          if (!d_equalityEngine->areEqual(x, y))
1064
          {
1065
10944
            Trace("dt-cg") << "Arg #" << k << " is " << x << " " << y << std::endl;
1066
32832
            if (d_equalityEngine->isTriggerTerm(x, THEORY_DATATYPES)
1067
32832
                && d_equalityEngine->isTriggerTerm(y, THEORY_DATATYPES))
1068
            {
1069
2002
              TNode x_shared = d_equalityEngine->getTriggerTermRepresentative(
1070
4004
                  x, THEORY_DATATYPES);
1071
2002
              TNode y_shared = d_equalityEngine->getTriggerTermRepresentative(
1072
4004
                  y, THEORY_DATATYPES);
1073
2002
              currentPairs.push_back(make_pair(x_shared, y_shared));
1074
            }
1075
          }
1076
        }
1077
11597
        for (unsigned c = 0; c < currentPairs.size(); ++ c) {
1078
2002
          Trace("dt-cg-pair") << "Pair : " << currentPairs[c].first << " " << currentPairs[c].second << std::endl;
1079
2002
          addCarePair(currentPairs[c].first, currentPairs[c].second);
1080
2002
          n_pairs++;
1081
        }
1082
      }
1083
    }
1084
  }else{
1085
73229
    if( t2==NULL ){
1086
65786
      if( depth<(arity-1) ){
1087
        //add care pairs internal to each child
1088
28517
        for (std::pair<const TNode, TNodeTrie>& tt : t1->d_data)
1089
        {
1090
16895
          addCarePairs(&tt.second, nullptr, arity, depth + 1, n_pairs);
1091
        }
1092
      }
1093
      //add care pairs based on each pair of non-disequal arguments
1094
172750
      for (std::map<TNode, TNodeTrie>::iterator it = t1->d_data.begin();
1095
172750
           it != t1->d_data.end();
1096
           ++it)
1097
      {
1098
106964
        std::map<TNode, TNodeTrie>::iterator it2 = it;
1099
106964
        ++it2;
1100
311758
        for( ; it2 != t1->d_data.end(); ++it2 ){
1101
102397
          if (!d_equalityEngine->areDisequal(it->first, it2->first, false))
1102
          {
1103
50940
            if( !areCareDisequal(it->first, it2->first) ){
1104
10714
              addCarePairs( &it->second, &it2->second, arity, depth+1, n_pairs );
1105
            }
1106
          }
1107
        }
1108
      }
1109
    }else{
1110
      //add care pairs based on product of indices, non-disequal arguments
1111
22328
      for (std::pair<const TNode, TNodeTrie>& tt1 : t1->d_data)
1112
      {
1113
36435
        for (std::pair<const TNode, TNodeTrie>& tt2 : t2->d_data)
1114
        {
1115
21550
          if (!d_equalityEngine->areDisequal(tt1.first, tt2.first, false))
1116
          {
1117
15883
            if (!areCareDisequal(tt1.first, tt2.first))
1118
            {
1119
6324
              addCarePairs(&tt1.second, &tt2.second, arity, depth + 1, n_pairs);
1120
            }
1121
          }
1122
        }
1123
      }
1124
    }
1125
  }
1126
82824
}
1127
1128
11908
void TheoryDatatypes::computeCareGraph(){
1129
11908
  unsigned n_pairs = 0;
1130
11908
  Trace("dt-cg-summary") << "Compute graph for dt..." << d_functionTerms.size() << " " << d_sharedTerms.size() << std::endl;
1131
11908
  Trace("dt-cg") << "Build indices..." << std::endl;
1132
23816
  std::map<TypeNode, std::map<Node, TNodeTrie> > index;
1133
23816
  std::map< Node, unsigned > arity;
1134
  //populate indices
1135
11908
  unsigned functionTerms = d_functionTerms.size();
1136
228633
  for( unsigned i=0; i<functionTerms; i++ ){
1137
433450
    TNode f1 = d_functionTerms[i];
1138
216725
    Assert(d_equalityEngine->hasTerm(f1));
1139
216725
    Trace("dt-cg-debug") << "...build for " << f1 << std::endl;
1140
    //break into index based on operator, and type of first argument (since some operators are parametric)
1141
433450
    Node op = f1.getOperator();
1142
433450
    TypeNode tn = f1[0].getType();
1143
433450
    std::vector< TNode > reps;
1144
216725
    bool has_trigger_arg = false;
1145
465979
    for( unsigned j=0; j<f1.getNumChildren(); j++ ){
1146
249254
      reps.push_back(d_equalityEngine->getRepresentative(f1[j]));
1147
249254
      if (d_equalityEngine->isTriggerTerm(f1[j], THEORY_DATATYPES))
1148
      {
1149
206873
        has_trigger_arg = true;
1150
      }
1151
    }
1152
    //only may contribute to care pairs if has at least one trigger argument
1153
216725
    if( has_trigger_arg ){
1154
182917
      index[tn][op].addTerm( f1, reps );
1155
182917
      arity[op] = reps.size();
1156
    }
1157
  }
1158
  //for each index
1159
29214
  for (std::pair<const TypeNode, std::map<Node, TNodeTrie> >& tt : index)
1160
  {
1161
66197
    for (std::pair<const Node, TNodeTrie>& t : tt.second)
1162
    {
1163
97782
      Trace("dt-cg") << "Process index " << tt.first << ", " << t.first << "..."
1164
48891
                     << std::endl;
1165
48891
      addCarePairs(&t.second, nullptr, arity[t.first], 0, n_pairs);
1166
    }
1167
  }
1168
11908
  Trace("dt-cg-summary") << "...done, # pairs = " << n_pairs << std::endl;
1169
11908
}
1170
1171
10006
bool TheoryDatatypes::collectModelValues(TheoryModel* m,
1172
                                         const std::set<Node>& termSet)
1173
{
1174
20012
  Trace("dt-cmi") << "Datatypes : Collect model values "
1175
10006
                  << d_equalityEngine->consistent() << std::endl;
1176
10006
  Trace("dt-model") << std::endl;
1177
10006
  printModelDebug( "dt-model" );
1178
10006
  Trace("dt-model") << std::endl;
1179
1180
  //get all constructors
1181
10006
  eq::EqClassesIterator eqccs_i = eq::EqClassesIterator(d_equalityEngine);
1182
20012
  std::vector< Node > cons;
1183
20012
  std::vector< Node > nodes;
1184
20012
  std::map< Node, Node > eqc_cons;
1185
517532
  while( !eqccs_i.isFinished() ){
1186
507526
    Node eqc = (*eqccs_i);
1187
    //for all equivalence classes that are datatypes
1188
    //if( termSet.find( eqc )==termSet.end() ){
1189
    //  Trace("dt-cmi-debug") << "Irrelevant eqc : " << eqc << std::endl;
1190
    //}
1191
253763
    if( eqc.getType().isDatatype() ){
1192
49547
      EqcInfo* ei = getOrMakeEqcInfo( eqc );
1193
49547
      if( ei && !ei->d_constructor.get().isNull() ){
1194
82110
        Node c = ei->d_constructor.get();
1195
41055
        cons.push_back( c );
1196
41055
        eqc_cons[ eqc ] = c;
1197
      }else{
1198
        //if eqc contains a symbol known to datatypes (a selector), then we must assign
1199
        //should assign constructors to EQC if they have a selector or a tester
1200
8492
        bool shouldConsider = ( ei && ei->d_selectors ) || hasTester( eqc );
1201
8492
        if( shouldConsider ){
1202
2
          nodes.push_back( eqc );
1203
        }
1204
      }
1205
    }
1206
    //}
1207
253763
    ++eqccs_i;
1208
  }
1209
1210
  //unsigned orig_size = nodes.size();
1211
20012
  std::map< TypeNode, int > typ_enum_map;
1212
20012
  std::vector< TypeEnumerator > typ_enum;
1213
10006
  unsigned index = 0;
1214
10010
  while( index<nodes.size() ){
1215
4
    Node eqc = nodes[index];
1216
4
    Node neqc;
1217
2
    bool addCons = false;
1218
4
    TypeNode tt = eqc.getType();
1219
2
    const DType& dt = tt.getDType();
1220
2
    if (!d_equalityEngine->hasTerm(eqc))
1221
    {
1222
      Assert(false);
1223
    }else{
1224
2
      Trace("dt-cmi") << "NOTICE : Datatypes: no constructor in equivalence class " << eqc << std::endl;
1225
2
      Trace("dt-cmi") << "   Type : " << eqc.getType() << std::endl;
1226
2
      EqcInfo* ei = getOrMakeEqcInfo( eqc );
1227
4
      std::vector< bool > pcons;
1228
2
      getPossibleCons( ei, eqc, pcons );
1229
2
      Trace("dt-cmi") << "Possible constructors : ";
1230
10
      for( unsigned i=0; i<pcons.size(); i++ ){
1231
8
        Trace("dt-cmi") << pcons[i] << " ";
1232
      }
1233
2
      Trace("dt-cmi") << std::endl;
1234
6
      for( unsigned r=0; r<2; r++ ){
1235
4
        if( neqc.isNull() ){
1236
2
          for( unsigned i=0; i<pcons.size(); i++ ){
1237
            // must try the infinite ones first
1238
            bool cfinite =
1239
2
                d_state.isFiniteType(dt[i].getSpecializedConstructorType(tt));
1240
2
            if( pcons[i] && (r==1)==cfinite ){
1241
2
              neqc = utils::getInstCons(eqc, dt, i);
1242
2
              break;
1243
            }
1244
          }
1245
        }
1246
      }
1247
2
      addCons = true;
1248
    }
1249
2
    if( !neqc.isNull() ){
1250
2
      Trace("dt-cmi") << "Assign : " << neqc << std::endl;
1251
2
      if (!m->assertEquality(eqc, neqc, true))
1252
      {
1253
        return false;
1254
      }
1255
2
      eqc_cons[ eqc ] = neqc;
1256
    }
1257
2
    if( addCons ){
1258
2
      cons.push_back( neqc );
1259
    }
1260
2
    ++index;
1261
  }
1262
1263
51079
  for( std::map< Node, Node >::iterator it = eqc_cons.begin(); it != eqc_cons.end(); ++it ){
1264
82146
    Node eqc = it->first;
1265
41073
    if( eqc.getType().isCodatatype() ){
1266
      //until models are implemented for codatatypes
1267
      //throw Exception("Models for codatatypes are not supported in this version.");
1268
      //must proactive expand to avoid looping behavior in model builder
1269
75
      if( !it->second.isNull() ){
1270
124
        std::map< Node, int > vmap;
1271
124
        Node v = getCodatatypesValue( it->first, eqc_cons, vmap, 0 );
1272
62
        Trace("dt-cmi") << "  EQC(" << it->first << "), constructor is " << it->second << ", value is " << v << ", const = " << v.isConst() << std::endl;
1273
62
        if (!m->assertEquality(eqc, v, true))
1274
        {
1275
          return false;
1276
        }
1277
62
        m->assertSkeleton(v);
1278
      }
1279
    }else{
1280
40998
      Trace("dt-cmi") << "Datatypes : assert representative " << it->second << " for " << it->first << std::endl;
1281
40998
      m->assertSkeleton(it->second);
1282
    }
1283
  }
1284
10006
  return true;
1285
}
1286
1287
1288
199
Node TheoryDatatypes::getCodatatypesValue( Node n, std::map< Node, Node >& eqc_cons, std::map< Node, int >& vmap, int depth ){
1289
199
  std::map< Node, int >::iterator itv = vmap.find( n );
1290
199
  if( itv!=vmap.end() ){
1291
6
    int debruijn = depth - 1 - itv->second;
1292
    return NodeManager::currentNM()->mkConst(
1293
6
        UninterpretedConstant(n.getType(), debruijn));
1294
193
  }else if( n.getType().isDatatype() ){
1295
173
    Node nc = eqc_cons[n];
1296
139
    if( !nc.isNull() ){
1297
105
      vmap[n] = depth;
1298
105
      Trace("dt-cmi-cdt-debug") << "    map " << n << " -> " << depth << std::endl;
1299
105
      Assert(nc.getKind() == APPLY_CONSTRUCTOR);
1300
210
      std::vector< Node > children;
1301
105
      children.push_back( nc.getOperator() );
1302
242
      for( unsigned i=0; i<nc.getNumChildren(); i++ ){
1303
274
        Node r = getRepresentative( nc[i] );
1304
274
        Node rv = getCodatatypesValue( r, eqc_cons, vmap, depth+1 );
1305
137
        children.push_back( rv );
1306
      }
1307
105
      vmap.erase( n );
1308
105
      return NodeManager::currentNM()->mkNode( APPLY_CONSTRUCTOR, children );
1309
    }
1310
  }
1311
88
  return n;
1312
}
1313
1314
Node TheoryDatatypes::getSingletonLemma( TypeNode tn, bool pol ) {
1315
  NodeManager* nm = NodeManager::currentNM();
1316
  SkolemManager* sm = nm->getSkolemManager();
1317
  int index = pol ? 0 : 1;
1318
  std::map< TypeNode, Node >::iterator it = d_singleton_lemma[index].find( tn );
1319
  if( it==d_singleton_lemma[index].end() ){
1320
    Node a;
1321
    if( pol ){
1322
      Node v1 = nm->mkBoundVar(tn);
1323
      Node v2 = nm->mkBoundVar(tn);
1324
      a = nm->mkNode(FORALL, nm->mkNode(BOUND_VAR_LIST, v1, v2), v1.eqNode(v2));
1325
    }else{
1326
      Node v1 = sm->mkDummySkolem("k1", tn);
1327
      Node v2 = sm->mkDummySkolem("k2", tn);
1328
      a = v1.eqNode( v2 ).negate();
1329
      //send out immediately as lemma
1330
      d_im.lemma(a, InferenceId::DATATYPES_REC_SINGLETON_FORCE_DEQ);
1331
      Trace("dt-singleton") << "******** assert " << a << " to avoid singleton cardinality for type " << tn << std::endl;
1332
    }
1333
    d_singleton_lemma[index][tn] = a;
1334
    return a;
1335
  }else{
1336
    return it->second;
1337
  }
1338
}
1339
1340
287346
void TheoryDatatypes::collectTerms( Node n ) {
1341
287346
  if (d_collectTermsCache.find(n) != d_collectTermsCache.end())
1342
  {
1343
    // already processed
1344
38097
    return;
1345
  }
1346
249249
  d_collectTermsCache[n] = true;
1347
249249
  Kind nk = n.getKind();
1348
249249
  if (nk == APPLY_CONSTRUCTOR)
1349
  {
1350
95747
    Debug("datatypes") << "  Found constructor " << n << endl;
1351
95747
    if (n.getNumChildren() > 0)
1352
    {
1353
68610
      d_functionTerms.push_back(n);
1354
    }
1355
95747
    return;
1356
  }
1357
153502
  if (nk == APPLY_SELECTOR_TOTAL || nk == DT_SIZE || nk == DT_HEIGHT_BOUND)
1358
  {
1359
22331
    d_functionTerms.push_back(n);
1360
    // we must also record which selectors exist
1361
22331
    Trace("dt-collapse-sel") << "  Found selector " << n << endl;
1362
44662
    Node rep = getRepresentative(n[0]);
1363
    // record it in the selectors
1364
22331
    EqcInfo* eqc = getOrMakeEqcInfo(rep, true);
1365
    // add it to the eqc info
1366
22331
    addSelector(n, eqc, rep);
1367
  }
1368
1369
  // now, do user-context-dependent lemmas
1370
153502
  if (nk != DT_SIZE && nk != DT_HEIGHT_BOUND)
1371
  {
1372
    // if not one of these kinds, there are no lemmas
1373
148965
    return;
1374
  }
1375
4537
  if (d_collectTermsCacheU.find(n) != d_collectTermsCacheU.end())
1376
  {
1377
2178
    return;
1378
  }
1379
2359
  d_collectTermsCacheU[n] = true;
1380
1381
2359
  NodeManager* nm = NodeManager::currentNM();
1382
1383
2359
  if (nk == DT_SIZE)
1384
  {
1385
4718
    Node lem = nm->mkNode(LEQ, d_zero, n);
1386
4718
    Trace("datatypes-infer")
1387
2359
        << "DtInfer : size geq zero : " << lem << std::endl;
1388
2359
    d_im.addPendingLemma(lem, InferenceId::DATATYPES_SIZE_POS);
1389
  }
1390
  else if (nk == DT_HEIGHT_BOUND && n[1].getConst<Rational>().isZero())
1391
  {
1392
    std::vector<Node> children;
1393
    const DType& dt = n[0].getType().getDType();
1394
    for (unsigned i = 0, ncons = dt.getNumConstructors(); i < ncons; i++)
1395
    {
1396
      if (utils::isNullaryConstructor(dt[i]))
1397
      {
1398
        Node test = utils::mkTester(n[0], i, dt);
1399
        children.push_back(test);
1400
      }
1401
    }
1402
    Node lem;
1403
    if (children.empty())
1404
    {
1405
      lem = n.negate();
1406
    }
1407
    else
1408
    {
1409
      lem = n.eqNode(children.size() == 1 ? children[0]
1410
                                          : nm->mkNode(OR, children));
1411
    }
1412
    Trace("datatypes-infer") << "DtInfer : zero height : " << lem << std::endl;
1413
    d_im.addPendingLemma(lem, InferenceId::DATATYPES_HEIGHT_ZERO);
1414
  }
1415
}
1416
1417
121796
Node TheoryDatatypes::getInstantiateCons(Node n, const DType& dt, int index)
1418
{
1419
121796
  if( n.getKind()==APPLY_CONSTRUCTOR && n.getNumChildren()==0 ){
1420
10287
    return n;
1421
  }
1422
  //add constructor to equivalence class
1423
223018
  Node k = getTermSkolemFor( n );
1424
223018
  Node n_ic = utils::getInstCons(k, dt, index);
1425
111509
  n_ic = Rewriter::rewrite( n_ic );
1426
  // it may be a new term, so we collect terms and add it to the equality engine
1427
111509
  collectTerms( n_ic );
1428
111509
  d_equalityEngine->addTerm(n_ic);
1429
111509
  Debug("dt-enum") << "Made instantiate cons " << n_ic << std::endl;
1430
111509
  return n_ic;
1431
}
1432
1433
184329
bool TheoryDatatypes::instantiate(EqcInfo* eqc, Node n)
1434
{
1435
184329
  Trace("datatypes-debug") << "Instantiate: " << n << std::endl;
1436
  //add constructor to equivalence class if not done so already
1437
184329
  int index = getLabelIndex( eqc, n );
1438
184329
  if (index == -1 || eqc->d_inst)
1439
  {
1440
62533
    return false;
1441
  }
1442
243592
  Node exp;
1443
243592
  Node tt;
1444
121796
  if (!eqc->d_constructor.get().isNull())
1445
  {
1446
23177
    exp = d_true;
1447
23177
    tt = eqc->d_constructor;
1448
  }
1449
  else
1450
  {
1451
98619
    exp = getLabel(n);
1452
98619
    tt = exp[0];
1453
  }
1454
243592
  TypeNode ttn = tt.getType();
1455
121796
  const DType& dt = ttn.getDType();
1456
  // instantiate this equivalence class
1457
121796
  eqc->d_inst = true;
1458
243592
  Node tt_cons = getInstantiateCons(tt, dt, index);
1459
243592
  Node eq;
1460
121796
  if (tt == tt_cons)
1461
  {
1462
    // not necessary
1463
10287
    return false;
1464
  }
1465
111509
  eq = tt.eqNode(tt_cons);
1466
  // Determine if the equality must be sent out as a lemma. Notice that
1467
  // we  keep new equalities from the instantiate rule internal
1468
  // as long as they are for datatype constructors that have no arguments that
1469
  // have finite external type, which corresponds to:
1470
  //   forceLemma = dt[index].hasFiniteExternalArgType(ttn);
1471
  // Such equalities must be sent because they introduce selector terms that
1472
  // may contribute to conflicts due to cardinality (good examples of this are
1473
  // regress0/datatypes/dt-param-card4-bool-sat.smt2 and
1474
  // regress0/datatypes/list-bool.smt2).
1475
  bool forceLemma;
1476
111509
  if (options::dtPoliteOptimize())
1477
  {
1478
111509
    forceLemma = dt[index].hasFiniteExternalArgType(ttn);
1479
  }
1480
  else
1481
  {
1482
    forceLemma = dt.involvesExternalType();
1483
  }
1484
223018
  Trace("datatypes-infer-debug") << "DtInstantiate : " << eqc << " " << eq
1485
111509
                                 << " forceLemma = " << forceLemma << std::endl;
1486
223018
  Trace("datatypes-infer") << "DtInfer : instantiate : " << eq << " by " << exp
1487
111509
                           << std::endl;
1488
111509
  d_im.addPendingInference(eq, InferenceId::DATATYPES_INST, exp, forceLemma);
1489
111509
  return true;
1490
}
1491
1492
28681
void TheoryDatatypes::checkCycles() {
1493
28681
  Trace("datatypes-cycle-check") << "Check acyclicity" << std::endl;
1494
57225
  std::vector< Node > cdt_eqc;
1495
28681
  eq::EqClassesIterator eqcs_i = eq::EqClassesIterator(d_equalityEngine);
1496
951809
  while( !eqcs_i.isFinished() ){
1497
923265
    Node eqc = (*eqcs_i);
1498
923265
    TypeNode tn = eqc.getType();
1499
461701
    if( tn.isDatatype() ) {
1500
150646
      if( !tn.isCodatatype() ){
1501
149472
        if( options::dtCyclic() ){
1502
          //do cycle checks
1503
298807
          std::map< TNode, bool > visited;
1504
298807
          std::map< TNode, bool > proc;
1505
298807
          std::vector<Node> expl;
1506
149472
          Trace("datatypes-cycle-check") << "...search for cycle starting at " << eqc << std::endl;
1507
298807
          Node cn = searchForCycle( eqc, eqc, visited, proc, expl );
1508
149472
          Trace("datatypes-cycle-check") << "...finish." << std::endl;
1509
          //if we discovered a different cycle while searching this one
1510
149472
          if( !cn.isNull() && cn!=eqc ){
1511
19
            visited.clear();
1512
19
            proc.clear();
1513
19
            expl.clear();
1514
38
            Node prev = cn;
1515
19
            cn = searchForCycle( cn, cn, visited, proc, expl );
1516
19
            Assert(prev == cn);
1517
          }
1518
1519
149472
          if( !cn.isNull() ) {
1520
137
            Assert(expl.size() > 0);
1521
274
            Trace("dt-conflict")
1522
137
                << "CONFLICT: Cycle conflict : " << expl << std::endl;
1523
137
            d_im.sendDtConflict(expl, InferenceId::DATATYPES_CYCLE);
1524
137
            return;
1525
          }
1526
        }
1527
      }else{
1528
        //indexing
1529
1174
        cdt_eqc.push_back( eqc );
1530
      }
1531
    }
1532
461564
    ++eqcs_i;
1533
  }
1534
28544
  Trace("datatypes-cycle-check") << "Check uniqueness" << std::endl;
1535
  //process codatatypes
1536
28544
  if( cdt_eqc.size()>1 && options::cdtBisimilar() ){
1537
90
    printModelDebug("dt-cdt-debug");
1538
90
    Trace("dt-cdt-debug") << "Process " << cdt_eqc.size() << " co-datatypes" << std::endl;
1539
180
    std::vector< std::vector< Node > > part_out;
1540
180
    std::vector<Node> exp;
1541
180
    std::map< Node, Node > cn;
1542
180
    std::map< Node, std::map< Node, int > > dni;
1543
1260
    for( unsigned i=0; i<cdt_eqc.size(); i++ ){
1544
1170
      cn[cdt_eqc[i]] = cdt_eqc[i];
1545
    }
1546
90
    separateBisimilar( cdt_eqc, part_out, exp, cn, dni, 0, false );
1547
90
    Trace("dt-cdt-debug") << "Done separate bisimilar." << std::endl;
1548
90
    if( !part_out.empty() ){
1549
10
      Trace("dt-cdt-debug") << "Process partition size " << part_out.size() << std::endl;
1550
20
      for( unsigned i=0; i<part_out.size(); i++ ){
1551
20
        std::vector< Node > part;
1552
10
        part.push_back( part_out[i][0] );
1553
20
        for( unsigned j=1; j<part_out[i].size(); j++ ){
1554
10
          Trace("dt-cdt") << "Codatatypes : " << part_out[i][0] << " and " << part_out[i][j] << " must be equal!!" << std::endl;
1555
10
          part.push_back( part_out[i][j] );
1556
20
          std::vector< std::vector< Node > > tpart_out;
1557
10
          exp.clear();
1558
10
          cn.clear();
1559
10
          cn[part_out[i][0]] = part_out[i][0];
1560
10
          cn[part_out[i][j]] = part_out[i][j];
1561
10
          dni.clear();
1562
10
          separateBisimilar( part, tpart_out, exp, cn, dni, 0, true );
1563
10
          Assert(tpart_out.size() == 1 && tpart_out[0].size() == 2);
1564
10
          part.pop_back();
1565
          //merge based on explanation
1566
10
          Trace("dt-cdt") << "  exp is : ";
1567
38
          for( unsigned k=0; k<exp.size(); k++ ){
1568
28
            Trace("dt-cdt") << exp[k] << " ";
1569
          }
1570
10
          Trace("dt-cdt") << std::endl;
1571
20
          Node eq = part_out[i][0].eqNode( part_out[i][j] );
1572
20
          Node eqExp = NodeManager::currentNM()->mkAnd(exp);
1573
10
          d_im.addPendingInference(eq, InferenceId::DATATYPES_BISIMILAR, eqExp);
1574
10
          Trace("datatypes-infer") << "DtInfer : cdt-bisimilar : " << eq << " by " << eqExp << std::endl;
1575
        }
1576
      }
1577
    }
1578
  }
1579
}
1580
1581
//everything is in terms of representatives
1582
278
void TheoryDatatypes::separateBisimilar(
1583
    std::vector<Node>& part,
1584
    std::vector<std::vector<Node> >& part_out,
1585
    std::vector<Node>& exp,
1586
    std::map<Node, Node>& cn,
1587
    std::map<Node, std::map<Node, int> >& dni,
1588
    int dniLvl,
1589
    bool mkExp)
1590
{
1591
278
  if( !mkExp ){
1592
240
    Trace("dt-cdt-debug") << "Separate bisimilar : " << std::endl;
1593
1818
    for( unsigned i=0; i<part.size(); i++ ){
1594
1578
      Trace("dt-cdt-debug") << "   " << part[i] << ", current = " << cn[part[i]] << std::endl;
1595
    }
1596
  }
1597
278
  Assert(part.size() > 1);
1598
556
  std::map< Node, std::vector< Node > > new_part;
1599
556
  std::map< Node, std::vector< Node > > new_part_c;
1600
556
  std::map< int, std::vector< Node > > new_part_rec;
1601
1602
556
  std::map< Node, Node > cn_cons;
1603
1932
  for( unsigned j=0; j<part.size(); j++ ){
1604
3308
    Node c = cn[part[j]];
1605
1654
    std::map< Node, int >::iterator it_rec = dni[part[j]].find( c );
1606
1654
    if( it_rec!=dni[part[j]].end() ){
1607
      //looped
1608
46
      if( !mkExp ){ Trace("dt-cdt-debug") << "  - " << part[j] << " is looping at index " << it_rec->second << std::endl; }
1609
46
      new_part_rec[ it_rec->second ].push_back( part[j] );
1610
    }else{
1611
1608
      if( c.getType().isDatatype() ){
1612
2704
        Node ncons = getEqcConstructor( c );
1613
1352
        if( ncons.getKind()==APPLY_CONSTRUCTOR ) {
1614
810
          Node cc = ncons.getOperator();
1615
405
          cn_cons[part[j]] = ncons;
1616
405
          if (mkExp && c != ncons)
1617
          {
1618
20
            exp.push_back(c.eqNode(ncons));
1619
          }
1620
405
          new_part[cc].push_back( part[j] );
1621
405
          if( !mkExp ){ Trace("dt-cdt-debug") << "  - " << part[j] << " is datatype " << ncons << "." << std::endl; }
1622
        }else{
1623
947
          new_part_c[c].push_back( part[j] );
1624
947
          if( !mkExp ){ Trace("dt-cdt-debug") << "  - " << part[j] << " is unspecified datatype." << std::endl; }
1625
        }
1626
      }else{
1627
        //add equivalences
1628
256
        if( !mkExp ){ Trace("dt-cdt-debug") << "  - " << part[j] << " is term " << c << "." << std::endl; }
1629
256
        new_part_c[c].push_back( part[j] );
1630
      }
1631
    }
1632
  }
1633
  //direct add for constants
1634
1376
  for( std::map< Node, std::vector< Node > >::iterator it = new_part_c.begin(); it != new_part_c.end(); ++it ){
1635
1098
    if( it->second.size()>1 ){
1636
186
      std::vector< Node > vec;
1637
93
      vec.insert( vec.begin(), it->second.begin(), it->second.end() );
1638
93
      part_out.push_back( vec );
1639
    }
1640
  }
1641
  //direct add for recursive
1642
304
  for( std::map< int, std::vector< Node > >::iterator it = new_part_rec.begin(); it != new_part_rec.end(); ++it ){
1643
26
    if( it->second.size()>1 ){
1644
40
      std::vector< Node > vec;
1645
20
      vec.insert( vec.begin(), it->second.begin(), it->second.end() );
1646
20
      part_out.push_back( vec );
1647
    }else{
1648
      //add back : could match a datatype?
1649
    }
1650
  }
1651
  //recurse for the datatypes
1652
502
  for( std::map< Node, std::vector< Node > >::iterator it = new_part.begin(); it != new_part.end(); ++it ){
1653
224
    if( it->second.size()>1 ){
1654
      //set dni to check for loops
1655
170
      std::map< Node, Node > dni_rem;
1656
351
      for( unsigned i=0; i<it->second.size(); i++ ){
1657
532
        Node n = it->second[i];
1658
266
        dni[n][cn[n]] = dniLvl;
1659
266
        dni_rem[n] = cn[n];
1660
      }
1661
1662
      //we will split based on the arguments of the datatype
1663
170
      std::vector< std::vector< Node > > split_new_part;
1664
85
      split_new_part.push_back( it->second );
1665
1666
85
      unsigned nChildren = cn_cons[it->second[0]].getNumChildren();
1667
      //for each child of constructor
1668
85
      unsigned cindex = 0;
1669
405
      while( cindex<nChildren && !split_new_part.empty() ){
1670
160
        if( !mkExp ){ Trace("dt-cdt-debug") << "Split argument #" << cindex << " of " << it->first << "..." << std::endl; }
1671
320
        std::vector< std::vector< Node > > next_split_new_part;
1672
338
        for( unsigned j=0; j<split_new_part.size(); j++ ){
1673
          //set current node
1674
642
          for( unsigned k=0; k<split_new_part[j].size(); k++ ){
1675
928
            Node n = split_new_part[j][k];
1676
928
            Node cnc = cn_cons[n][cindex];
1677
928
            Node nr = getRepresentative(cnc);
1678
464
            cn[n] = nr;
1679
464
            if (mkExp && cnc != nr)
1680
            {
1681
8
              exp.push_back(nr.eqNode(cnc));
1682
            }
1683
          }
1684
356
          std::vector< std::vector< Node > > c_part_out;
1685
178
          separateBisimilar( split_new_part[j], c_part_out, exp, cn, dni, dniLvl+1, mkExp );
1686
178
          next_split_new_part.insert( next_split_new_part.end(), c_part_out.begin(), c_part_out.end() );
1687
        }
1688
160
        split_new_part.clear();
1689
160
        split_new_part.insert( split_new_part.end(), next_split_new_part.begin(), next_split_new_part.end() );
1690
160
        cindex++;
1691
      }
1692
85
      part_out.insert( part_out.end(), split_new_part.begin(), split_new_part.end() );
1693
1694
351
      for( std::map< Node, Node >::iterator it2 = dni_rem.begin(); it2 != dni_rem.end(); ++it2 ){
1695
266
        dni[it2->first].erase( it2->second );
1696
      }
1697
    }
1698
  }
1699
278
}
1700
1701
//postcondition: if cycle detected, explanation is why n is a subterm of on
1702
671415
Node TheoryDatatypes::searchForCycle(TNode n,
1703
                                     TNode on,
1704
                                     std::map<TNode, bool>& visited,
1705
                                     std::map<TNode, bool>& proc,
1706
                                     std::vector<Node>& explanation,
1707
                                     bool firstTime)
1708
{
1709
671415
  Trace("datatypes-cycle-check2") << "Search for cycle " << n << " " << on << endl;
1710
1342830
  TNode ncons;
1711
1342830
  TNode nn;
1712
671415
  if( !firstTime ){
1713
521924
    nn = getRepresentative( n );
1714
521924
    if( nn==on ){
1715
137
      if (n != nn)
1716
      {
1717
98
        explanation.push_back(n.eqNode(nn));
1718
      }
1719
137
      return on;
1720
    }
1721
  }else{
1722
149491
    nn = getRepresentative( n );
1723
  }
1724
671278
  if( proc.find( nn )!=proc.end() ){
1725
139911
    return Node::null();
1726
  }
1727
531367
  Trace("datatypes-cycle-check2") << "...representative : " << nn << " " << ( visited.find( nn ) == visited.end() ) << " " << visited.size() << std::endl;
1728
531367
  if( visited.find( nn ) == visited.end() ) {
1729
531348
    Trace("datatypes-cycle-check2") << "  visit : " << nn << std::endl;
1730
531348
    visited[nn] = true;
1731
1062696
    TNode nncons = getEqcConstructor(nn);
1732
531348
    if (nncons.getKind() == APPLY_CONSTRUCTOR)
1733
    {
1734
926313
      for (unsigned i = 0; i < nncons.getNumChildren(); i++)
1735
      {
1736
        TNode cn =
1737
1042887
            searchForCycle(nncons[i], on, visited, proc, explanation, false);
1738
521924
        if( cn==on ) {
1739
          //add explanation for why the constructor is connected
1740
850
          if (n != nncons)
1741
          {
1742
465
            explanation.push_back(n.eqNode(nncons));
1743
          }
1744
850
          return on;
1745
521074
        }else if( !cn.isNull() ){
1746
111
          return cn;
1747
        }
1748
      }
1749
    }
1750
530387
    Trace("datatypes-cycle-check2") << "  unvisit : " << nn << std::endl;
1751
530387
    proc[nn] = true;
1752
530387
    visited.erase( nn );
1753
530387
    return Node::null();
1754
  }else{
1755
38
    TypeNode tn = nn.getType();
1756
19
    if( tn.isDatatype() ) {
1757
19
      if( !tn.isCodatatype() ){
1758
19
        return nn;
1759
      }
1760
    }
1761
    return Node::null();
1762
  }
1763
}
1764
1765
2708358
bool TheoryDatatypes::hasTerm(TNode a) { return d_equalityEngine->hasTerm(a); }
1766
1767
630254
bool TheoryDatatypes::areEqual( TNode a, TNode b ){
1768
630254
  if( a==b ){
1769
9280
    return true;
1770
620974
  }else if( hasTerm( a ) && hasTerm( b ) ){
1771
620974
    return d_equalityEngine->areEqual(a, b);
1772
  }else{
1773
    return false;
1774
  }
1775
}
1776
1777
19392
bool TheoryDatatypes::areDisequal( TNode a, TNode b ){
1778
19392
  if( a==b ){
1779
4587
    return false;
1780
14805
  }else if( hasTerm( a ) && hasTerm( b ) ){
1781
14805
    return d_equalityEngine->areDisequal(a, b, false);
1782
  }else{
1783
    //TODO : constants here?
1784
    return false;
1785
  }
1786
}
1787
1788
86215
bool TheoryDatatypes::areCareDisequal( TNode x, TNode y ) {
1789
86215
  Trace("datatypes-cg") << "areCareDisequal: " << x << " " << y << std::endl;
1790
86215
  Assert(d_equalityEngine->hasTerm(x));
1791
86215
  Assert(d_equalityEngine->hasTerm(y));
1792
258645
  if (d_equalityEngine->isTriggerTerm(x, THEORY_DATATYPES)
1793
258645
      && d_equalityEngine->isTriggerTerm(y, THEORY_DATATYPES))
1794
  {
1795
    TNode x_shared =
1796
83561
        d_equalityEngine->getTriggerTermRepresentative(x, THEORY_DATATYPES);
1797
    TNode y_shared =
1798
83561
        d_equalityEngine->getTriggerTermRepresentative(y, THEORY_DATATYPES);
1799
66673
    EqualityStatus eqStatus = d_valuation.getEqualityStatus(x_shared, y_shared);
1800
66673
    if( eqStatus==EQUALITY_FALSE_AND_PROPAGATED || eqStatus==EQUALITY_FALSE || eqStatus==EQUALITY_FALSE_IN_MODEL ){
1801
49785
      return true;
1802
    }
1803
  }
1804
36430
  return false;
1805
}
1806
1807
1436800
TNode TheoryDatatypes::getRepresentative( TNode a ){
1808
1436800
  if( hasTerm( a ) ){
1809
1436800
    return d_equalityEngine->getRepresentative(a);
1810
  }else{
1811
    return a;
1812
  }
1813
}
1814
1815
37711
void TheoryDatatypes::printModelDebug( const char* c ){
1816
37711
  if(! (Trace.isOn(c))) {
1817
37711
    return;
1818
  }
1819
1820
  Trace( c ) << "Datatypes model : " << std::endl;
1821
  eq::EqClassesIterator eqcs_i = eq::EqClassesIterator(d_equalityEngine);
1822
  while( !eqcs_i.isFinished() ){
1823
    Node eqc = (*eqcs_i);
1824
    //if( !eqc.getType().isBoolean() ){
1825
      if( eqc.getType().isDatatype() ){
1826
        Trace( c ) << "DATATYPE : ";
1827
      }
1828
      Trace( c ) << eqc << " : " << eqc.getType() << " : " << std::endl;
1829
      Trace( c ) << "   { ";
1830
      //add terms to model
1831
      eq::EqClassIterator eqc_i = eq::EqClassIterator(eqc, d_equalityEngine);
1832
      while( !eqc_i.isFinished() ){
1833
        if( (*eqc_i)!=eqc ){
1834
          Trace( c ) << (*eqc_i) << " ";
1835
        }
1836
        ++eqc_i;
1837
      }
1838
      Trace( c ) << "}" << std::endl;
1839
      if( eqc.getType().isDatatype() ){
1840
        EqcInfo* ei = getOrMakeEqcInfo( eqc );
1841
        if( ei ){
1842
          Trace( c ) << "   Instantiated : " << ei->d_inst.get() << std::endl;
1843
          Trace( c ) << "   Constructor : ";
1844
          if( !ei->d_constructor.get().isNull() ){
1845
            Trace( c )<< ei->d_constructor.get();
1846
          }
1847
          Trace( c ) << std::endl << "   Labels : ";
1848
          if( hasLabel( ei, eqc ) ){
1849
            Trace( c ) << getLabel( eqc );
1850
          }else{
1851
            NodeUIntMap::iterator lbl_i = d_labels.find(eqc);
1852
            if( lbl_i != d_labels.end() ){
1853
              for (size_t j = 0; j < (*lbl_i).second; j++)
1854
              {
1855
                Trace( c ) << d_labels_data[eqc][j] << " ";
1856
              }
1857
            }
1858
          }
1859
          Trace( c ) << std::endl;
1860
          Trace( c ) << "   Selectors : " << ( ei->d_selectors ? "yes, " : "no " );
1861
          NodeUIntMap::iterator sel_i = d_selector_apps.find(eqc);
1862
          if( sel_i != d_selector_apps.end() ){
1863
            for (size_t j = 0; j < (*sel_i).second; j++)
1864
            {
1865
              Trace( c ) << d_selector_apps_data[eqc][j] << " ";
1866
            }
1867
          }
1868
          Trace( c ) << std::endl;
1869
        }
1870
      }
1871
    //}
1872
    ++eqcs_i;
1873
  }
1874
}
1875
1876
10006
void TheoryDatatypes::computeRelevantTerms(std::set<Node>& termSet)
1877
{
1878
20012
  Trace("dt-cmi") << "Have " << termSet.size() << " relevant terms..."
1879
10006
                  << std::endl;
1880
1881
  //also include non-singleton dt equivalence classes  TODO : revisit this
1882
10006
  eq::EqClassesIterator eqcs_i = eq::EqClassesIterator(d_equalityEngine);
1883
517532
  while( !eqcs_i.isFinished() ){
1884
507526
    TNode r = (*eqcs_i);
1885
253763
    if (r.getType().isDatatype())
1886
    {
1887
49547
      eq::EqClassIterator eqc_i = eq::EqClassIterator(r, d_equalityEngine);
1888
413721
      while (!eqc_i.isFinished())
1889
      {
1890
182087
        termSet.insert(*eqc_i);
1891
182087
        ++eqc_i;
1892
      }
1893
    }
1894
253763
    ++eqcs_i;
1895
  }
1896
10006
}
1897
1898
std::pair<bool, Node> TheoryDatatypes::entailmentCheck(TNode lit)
1899
{
1900
  Trace("dt-entail") << "Check entailed : " << lit << std::endl;
1901
  Node atom = lit.getKind()==NOT ? lit[0] : lit;
1902
  bool pol = lit.getKind()!=NOT;
1903
  if( atom.getKind()==APPLY_TESTER ){
1904
    Node n = atom[0];
1905
    if( hasTerm( n ) ){
1906
      Node r = d_equalityEngine->getRepresentative(n);
1907
      EqcInfo * ei = getOrMakeEqcInfo( r, false );
1908
      int l_index = getLabelIndex( ei, r );
1909
      int t_index = static_cast<int>(utils::indexOf(atom.getOperator()));
1910
      Trace("dt-entail") << "  Tester indices are " << t_index << " and " << l_index << std::endl;
1911
      if( l_index!=-1 && (l_index==t_index)==pol ){
1912
        std::vector< TNode > exp_c;
1913
        Node eqToExplain;
1914
        if( ei && !ei->d_constructor.get().isNull() ){
1915
          eqToExplain = n.eqNode(ei->d_constructor.get());
1916
        }else{
1917
          Node lbl = getLabel( n );
1918
          Assert(!lbl.isNull());
1919
          exp_c.push_back( lbl );
1920
          Assert(areEqual(n, lbl[0]));
1921
          eqToExplain = n.eqNode(lbl[0]);
1922
        }
1923
        d_equalityEngine->explainLit(eqToExplain, exp_c);
1924
        Node exp = NodeManager::currentNM()->mkAnd(exp_c);
1925
        Trace("dt-entail") << "  entailed, explanation is " << exp << std::endl;
1926
        return make_pair(true, exp);
1927
      }
1928
    }
1929
  }
1930
  return make_pair(false, Node::null());
1931
}
1932
1933
}  // namespace datatypes
1934
}  // namespace theory
1935
29502
}  // namespace cvc5