ce01006863a933d42742b8a23b7e9933a1830d8c
[cvc5.git] / src / theory / strings / theory_strings.cpp
1 /********************* */
2 /*! \file theory_strings.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Andrew Reynolds, Tianyi Liang, Morgan Deters
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2018 by the authors listed in the file AUTHORS
8 ** in the top-level source directory) and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing information.\endverbatim
11 **
12 ** \brief Implementation of the theory of strings.
13 **
14 ** Implementation of the theory of strings.
15 **/
16
17 #include "theory/strings/theory_strings.h"
18
19 #include <cmath>
20
21 #include "expr/kind.h"
22 #include "options/strings_options.h"
23 #include "smt/command.h"
24 #include "smt/logic_exception.h"
25 #include "smt/smt_statistics_registry.h"
26 #include "theory/ext_theory.h"
27 #include "theory/quantifiers/term_database.h"
28 #include "theory/rewriter.h"
29 #include "theory/strings/theory_strings_rewriter.h"
30 #include "theory/strings/type_enumerator.h"
31 #include "theory/theory_model.h"
32 #include "theory/valuation.h"
33
34 using namespace std;
35 using namespace CVC4::context;
36 using namespace CVC4::kind;
37
38 namespace CVC4 {
39 namespace theory {
40 namespace strings {
41
42 std::ostream& operator<<(std::ostream& out, Inference i)
43 {
44 switch (i)
45 {
46 case INFER_SSPLIT_CST_PROP: out << "S-Split(CST-P)-prop"; break;
47 case INFER_SSPLIT_VAR_PROP: out << "S-Split(VAR)-prop"; break;
48 case INFER_LEN_SPLIT: out << "Len-Split(Len)"; break;
49 case INFER_LEN_SPLIT_EMP: out << "Len-Split(Emp)"; break;
50 case INFER_SSPLIT_CST_BINARY: out << "S-Split(CST-P)-binary"; break;
51 case INFER_SSPLIT_CST: out << "S-Split(CST-P)"; break;
52 case INFER_SSPLIT_VAR: out << "S-Split(VAR)"; break;
53 case INFER_FLOOP: out << "F-Loop"; break;
54 default: out << "?"; break;
55 }
56 return out;
57 }
58
59 std::ostream& operator<<(std::ostream& out, InferStep s)
60 {
61 switch (s)
62 {
63 case BREAK: out << "break"; break;
64 case CHECK_INIT: out << "check_init"; break;
65 case CHECK_CONST_EQC: out << "check_const_eqc"; break;
66 case CHECK_EXTF_EVAL: out << "check_extf_eval"; break;
67 case CHECK_CYCLES: out << "check_cycles"; break;
68 case CHECK_FLAT_FORMS: out << "check_flat_forms"; break;
69 case CHECK_NORMAL_FORMS_EQ: out << "check_normal_forms_eq"; break;
70 case CHECK_NORMAL_FORMS_DEQ: out << "check_normal_forms_deq"; break;
71 case CHECK_CODES: out << "check_codes"; break;
72 case CHECK_LENGTH_EQC: out << "check_length_eqc"; break;
73 case CHECK_EXTF_REDUCTION: out << "check_extf_reduction"; break;
74 case CHECK_MEMBERSHIP: out << "check_membership"; break;
75 case CHECK_CARDINALITY: out << "check_cardinality"; break;
76 default: out << "?"; break;
77 }
78 return out;
79 }
80
81 Node TheoryStrings::TermIndex::add( TNode n, unsigned index, TheoryStrings* t, Node er, std::vector< Node >& c ) {
82 if( index==n.getNumChildren() ){
83 if( d_data.isNull() ){
84 d_data = n;
85 }
86 return d_data;
87 }else{
88 Assert( index<n.getNumChildren() );
89 TNode nir = t->getRepresentative( n[index] );
90 //if it is empty, and doing CONCAT, ignore
91 if( nir==er && n.getKind()==kind::STRING_CONCAT ){
92 return add( n, index+1, t, er, c );
93 }else{
94 c.push_back( nir );
95 return d_children[nir].add( n, index+1, t, er, c );
96 }
97 }
98 }
99
100 TheoryStrings::TheoryStrings(context::Context* c,
101 context::UserContext* u,
102 OutputChannel& out,
103 Valuation valuation,
104 const LogicInfo& logicInfo)
105 : Theory(THEORY_STRINGS, c, u, out, valuation, logicInfo),
106 RMAXINT(LONG_MAX),
107 d_notify(*this),
108 d_equalityEngine(d_notify, c, "theory::strings", true),
109 d_conflict(c, false),
110 d_infer(c),
111 d_infer_exp(c),
112 d_nf_pairs(c),
113 d_pregistered_terms_cache(u),
114 d_registered_terms_cache(u),
115 d_length_lemma_terms_cache(u),
116 d_skolem_ne_reg_cache(u),
117 d_preproc(u),
118 d_preproc_cache(u),
119 d_extf_infer_cache(c),
120 d_extf_infer_cache_u(u),
121 d_ee_disequalities(c),
122 d_congruent(c),
123 d_proxy_var(u),
124 d_proxy_var_to_length(u),
125 d_functionsTerms(c),
126 d_has_extf(c, false),
127 d_has_str_code(false),
128 d_regexp_memberships(c),
129 d_regexp_ucached(u),
130 d_regexp_ccached(c),
131 d_pos_memberships(c),
132 d_neg_memberships(c),
133 d_inter_cache(c),
134 d_inter_index(c),
135 d_processed_memberships(c),
136 d_regexp_ant(c),
137 d_input_vars(u),
138 d_input_var_lsum(u),
139 d_cardinality_lits(u),
140 d_curr_cardinality(c, 0),
141 d_strategy_init(false)
142 {
143 setupExtTheory();
144 getExtTheory()->addFunctionKind(kind::STRING_SUBSTR);
145 getExtTheory()->addFunctionKind(kind::STRING_STRIDOF);
146 getExtTheory()->addFunctionKind(kind::STRING_ITOS);
147 getExtTheory()->addFunctionKind(kind::STRING_STOI);
148 getExtTheory()->addFunctionKind(kind::STRING_STRREPL);
149 getExtTheory()->addFunctionKind(kind::STRING_STRCTN);
150 getExtTheory()->addFunctionKind(kind::STRING_IN_REGEXP);
151 getExtTheory()->addFunctionKind(kind::STRING_LEQ);
152 getExtTheory()->addFunctionKind(kind::STRING_CODE);
153
154 // The kinds we are treating as function application in congruence
155 d_equalityEngine.addFunctionKind(kind::STRING_LENGTH);
156 d_equalityEngine.addFunctionKind(kind::STRING_CONCAT);
157 d_equalityEngine.addFunctionKind(kind::STRING_IN_REGEXP);
158 d_equalityEngine.addFunctionKind(kind::STRING_CODE);
159 if( options::stringLazyPreproc() ){
160 d_equalityEngine.addFunctionKind(kind::STRING_STRCTN);
161 d_equalityEngine.addFunctionKind(kind::STRING_LEQ);
162 d_equalityEngine.addFunctionKind(kind::STRING_SUBSTR);
163 d_equalityEngine.addFunctionKind(kind::STRING_ITOS);
164 d_equalityEngine.addFunctionKind(kind::STRING_STOI);
165 d_equalityEngine.addFunctionKind(kind::STRING_STRIDOF);
166 d_equalityEngine.addFunctionKind(kind::STRING_STRREPL);
167 }
168
169 d_zero = NodeManager::currentNM()->mkConst( Rational( 0 ) );
170 d_one = NodeManager::currentNM()->mkConst( Rational( 1 ) );
171 d_neg_one = NodeManager::currentNM()->mkConst(Rational(-1));
172 d_emptyString = NodeManager::currentNM()->mkConst( ::CVC4::String("") );
173 std::vector< Node > nvec;
174 d_emptyRegexp = NodeManager::currentNM()->mkNode( kind::REGEXP_EMPTY, nvec );
175 d_true = NodeManager::currentNM()->mkConst( true );
176 d_false = NodeManager::currentNM()->mkConst( false );
177
178 d_card_size = TheoryStringsRewriter::getAlphabetCardinality();
179 }
180
181 TheoryStrings::~TheoryStrings() {
182 for( std::map< Node, EqcInfo* >::iterator it = d_eqc_info.begin(); it != d_eqc_info.end(); ++it ){
183 delete it->second;
184 }
185 }
186
187 Node TheoryStrings::getRepresentative( Node t ) {
188 if( d_equalityEngine.hasTerm( t ) ){
189 return d_equalityEngine.getRepresentative( t );
190 }else{
191 return t;
192 }
193 }
194
195 bool TheoryStrings::hasTerm( Node a ){
196 return d_equalityEngine.hasTerm( a );
197 }
198
199 bool TheoryStrings::areEqual( Node a, Node b ){
200 if( a==b ){
201 return true;
202 }else if( hasTerm( a ) && hasTerm( b ) ){
203 return d_equalityEngine.areEqual( a, b );
204 }else{
205 return false;
206 }
207 }
208
209 bool TheoryStrings::areDisequal( Node a, Node b ){
210 if( a==b ){
211 return false;
212 }else{
213 if( hasTerm( a ) && hasTerm( b ) ) {
214 Node ar = d_equalityEngine.getRepresentative( a );
215 Node br = d_equalityEngine.getRepresentative( b );
216 return ( ar!=br && ar.isConst() && br.isConst() ) || d_equalityEngine.areDisequal( ar, br, false );
217 }else{
218 Node ar = getRepresentative( a );
219 Node br = getRepresentative( b );
220 return ar!=br && ar.isConst() && br.isConst();
221 }
222 }
223 }
224
225 bool TheoryStrings::areCareDisequal( TNode x, TNode y ) {
226 Assert( d_equalityEngine.hasTerm(x) );
227 Assert( d_equalityEngine.hasTerm(y) );
228 if( d_equalityEngine.isTriggerTerm(x, THEORY_STRINGS) && d_equalityEngine.isTriggerTerm(y, THEORY_STRINGS) ){
229 TNode x_shared = d_equalityEngine.getTriggerTermRepresentative(x, THEORY_STRINGS);
230 TNode y_shared = d_equalityEngine.getTriggerTermRepresentative(y, THEORY_STRINGS);
231 EqualityStatus eqStatus = d_valuation.getEqualityStatus(x_shared, y_shared);
232 if( eqStatus==EQUALITY_FALSE_AND_PROPAGATED || eqStatus==EQUALITY_FALSE || eqStatus==EQUALITY_FALSE_IN_MODEL ){
233 return true;
234 }
235 }
236 return false;
237 }
238
239 Node TheoryStrings::getLengthExp( Node t, std::vector< Node >& exp, Node te ){
240 Assert( areEqual( t, te ) );
241 Node lt = mkLength( te );
242 if( hasTerm( lt ) ){
243 // use own length if it exists, leads to shorter explanation
244 return lt;
245 }else{
246 EqcInfo * ei = getOrMakeEqcInfo( t, false );
247 Node length_term = ei ? ei->d_length_term : Node::null();
248 if( length_term.isNull() ){
249 //typically shouldnt be necessary
250 length_term = t;
251 }
252 Debug("strings") << "TheoryStrings::getLengthTerm " << t << " is " << length_term << std::endl;
253 addToExplanation( length_term, te, exp );
254 return Rewriter::rewrite( NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, length_term ) );
255 }
256 }
257
258 Node TheoryStrings::getLength( Node t, std::vector< Node >& exp ) {
259 return getLengthExp( t, exp, t );
260 }
261
262 void TheoryStrings::setMasterEqualityEngine(eq::EqualityEngine* eq) {
263 d_equalityEngine.setMasterEqualityEngine(eq);
264 }
265
266 void TheoryStrings::addSharedTerm(TNode t) {
267 Debug("strings") << "TheoryStrings::addSharedTerm(): "
268 << t << " " << t.getType().isBoolean() << endl;
269 d_equalityEngine.addTriggerTerm(t, THEORY_STRINGS);
270 Debug("strings") << "TheoryStrings::addSharedTerm() finished" << std::endl;
271 }
272
273 EqualityStatus TheoryStrings::getEqualityStatus(TNode a, TNode b) {
274 if( d_equalityEngine.hasTerm(a) && d_equalityEngine.hasTerm(b) ){
275 if (d_equalityEngine.areEqual(a, b)) {
276 // The terms are implied to be equal
277 return EQUALITY_TRUE;
278 }
279 if (d_equalityEngine.areDisequal(a, b, false)) {
280 // The terms are implied to be dis-equal
281 return EQUALITY_FALSE;
282 }
283 }
284 return EQUALITY_UNKNOWN;
285 }
286
287 void TheoryStrings::propagate(Effort e) {
288 // direct propagation now
289 }
290
291 bool TheoryStrings::propagate(TNode literal) {
292 Debug("strings-propagate") << "TheoryStrings::propagate(" << literal << ")" << std::endl;
293 // If already in conflict, no more propagation
294 if (d_conflict) {
295 Debug("strings-propagate") << "TheoryStrings::propagate(" << literal << "): already in conflict" << std::endl;
296 return false;
297 }
298 // Propagate out
299 bool ok = d_out->propagate(literal);
300 if (!ok) {
301 d_conflict = true;
302 }
303 return ok;
304 }
305
306 /** explain */
307 void TheoryStrings::explain(TNode literal, std::vector<TNode>& assumptions) {
308 Debug("strings-explain") << "Explain " << literal << " " << d_conflict << std::endl;
309 bool polarity = literal.getKind() != kind::NOT;
310 TNode atom = polarity ? literal : literal[0];
311 unsigned ps = assumptions.size();
312 std::vector< TNode > tassumptions;
313 if (atom.getKind() == kind::EQUAL) {
314 if( atom[0]!=atom[1] ){
315 Assert( hasTerm( atom[0] ) );
316 Assert( hasTerm( atom[1] ) );
317 d_equalityEngine.explainEquality(atom[0], atom[1], polarity, tassumptions);
318 }
319 } else {
320 d_equalityEngine.explainPredicate(atom, polarity, tassumptions);
321 }
322 for( unsigned i=0; i<tassumptions.size(); i++ ){
323 if( std::find( assumptions.begin(), assumptions.end(), tassumptions[i] )==assumptions.end() ){
324 assumptions.push_back( tassumptions[i] );
325 }
326 }
327 if (Debug.isOn("strings-explain-debug"))
328 {
329 Debug("strings-explain-debug") << "Explanation for " << literal << " was "
330 << std::endl;
331 for (unsigned i = ps; i < assumptions.size(); i++)
332 {
333 Debug("strings-explain-debug") << " " << assumptions[i] << std::endl;
334 }
335 }
336 }
337
338 Node TheoryStrings::explain( TNode literal ){
339 Debug("strings-explain") << "explain called on " << literal << std::endl;
340 std::vector< TNode > assumptions;
341 explain( literal, assumptions );
342 if( assumptions.empty() ){
343 return d_true;
344 }else if( assumptions.size()==1 ){
345 return assumptions[0];
346 }else{
347 return NodeManager::currentNM()->mkNode( kind::AND, assumptions );
348 }
349 }
350
351 bool TheoryStrings::getCurrentSubstitution( int effort, std::vector< Node >& vars,
352 std::vector< Node >& subs, std::map< Node, std::vector< Node > >& exp ) {
353 Trace("strings-subs") << "getCurrentSubstitution, effort = " << effort << std::endl;
354 for( unsigned i=0; i<vars.size(); i++ ){
355 Node n = vars[i];
356 Trace("strings-subs") << " get subs for " << n << "..." << std::endl;
357 if( effort>=3 ){
358 //model values
359 Node mv = d_valuation.getModel()->getRepresentative( n );
360 Trace("strings-subs") << " model val : " << mv << std::endl;
361 subs.push_back( mv );
362 }else{
363 Node nr = getRepresentative( n );
364 std::map< Node, Node >::iterator itc = d_eqc_to_const.find( nr );
365 if( itc!=d_eqc_to_const.end() ){
366 //constant equivalence classes
367 Trace("strings-subs") << " constant eqc : " << d_eqc_to_const_exp[nr] << " " << d_eqc_to_const_base[nr] << " " << nr << std::endl;
368 subs.push_back( itc->second );
369 if( !d_eqc_to_const_exp[nr].isNull() ){
370 exp[n].push_back( d_eqc_to_const_exp[nr] );
371 }
372 if( !d_eqc_to_const_base[nr].isNull() ){
373 addToExplanation( n, d_eqc_to_const_base[nr], exp[n] );
374 }
375 }else if( effort>=1 && effort<3 && n.getType().isString() ){
376 //normal forms
377 Node ns = getNormalString( d_normal_forms_base[nr], exp[n] );
378 subs.push_back( ns );
379 Trace("strings-subs") << " normal eqc : " << ns << " " << d_normal_forms_base[nr] << " " << nr << std::endl;
380 if( !d_normal_forms_base[nr].isNull() ) {
381 addToExplanation( n, d_normal_forms_base[nr], exp[n] );
382 }
383 }else{
384 //representative?
385 //Trace("strings-subs") << " representative : " << nr << std::endl;
386 //addToExplanation( n, nr, exp[n] );
387 //subs.push_back( nr );
388 subs.push_back( n );
389 }
390 }
391 }
392 return true;
393 }
394
395 int TheoryStrings::getReduction( int effort, Node n, Node& nr ) {
396 //determine the effort level to process the extf at
397 // 0 - at assertion time, 1+ - after no other reduction is applicable
398 Assert( d_extf_info_tmp.find( n )!=d_extf_info_tmp.end() );
399 if( d_extf_info_tmp[n].d_model_active ){
400 int r_effort = -1;
401 int pol = d_extf_info_tmp[n].d_pol;
402 if( n.getKind()==kind::STRING_STRCTN ){
403 if( pol==1 ){
404 r_effort = 1;
405 }else if( pol==-1 ){
406 if( effort==2 ){
407 Node x = n[0];
408 Node s = n[1];
409 std::vector< Node > lexp;
410 Node lenx = getLength( x, lexp );
411 Node lens = getLength( s, lexp );
412 if( areEqual( lenx, lens ) ){
413 Trace("strings-extf-debug") << " resolve extf : " << n << " based on equal lengths disequality." << std::endl;
414 //we can reduce to disequality when lengths are equal
415 if( !areDisequal( x, s ) ){
416 lexp.push_back( lenx.eqNode(lens) );
417 lexp.push_back( n.negate() );
418 Node xneqs = x.eqNode(s).negate();
419 sendInference( lexp, xneqs, "NEG-CTN-EQL", true );
420 }
421 return 1;
422 }else{
423 r_effort = 2;
424 }
425 }
426 }
427 }else{
428 if( options::stringLazyPreproc() ){
429 if( n.getKind()==kind::STRING_SUBSTR ){
430 r_effort = 1;
431 }else if( n.getKind()!=kind::STRING_IN_REGEXP ){
432 r_effort = 2;
433 }
434 }
435 }
436 if( effort==r_effort ){
437 Node c_n = pol==-1 ? n.negate() : n;
438 if( d_preproc_cache.find( c_n )==d_preproc_cache.end() ){
439 d_preproc_cache[ c_n ] = true;
440 Trace("strings-process-debug") << "Process reduction for " << n << ", pol = " << pol << std::endl;
441 Kind k = n.getKind();
442 if (k == kind::STRING_STRCTN && pol == 1)
443 {
444 Node x = n[0];
445 Node s = n[1];
446 //positive contains reduces to a equality
447 Node sk1 = mkSkolemCached( x, s, sk_id_ctn_pre, "sc1" );
448 Node sk2 = mkSkolemCached( x, s, sk_id_ctn_post, "sc2" );
449 Node eq = Rewriter::rewrite( x.eqNode( mkConcat( sk1, s, sk2 ) ) );
450 std::vector< Node > exp_vec;
451 exp_vec.push_back( n );
452 sendInference( d_empty_vec, exp_vec, eq, "POS-CTN", true );
453 //we've reduced this n
454 Trace("strings-extf-debug") << " resolve extf : " << n << " based on positive contain reduction." << std::endl;
455 return 1;
456 }
457 else if (k != kind::STRING_CODE)
458 {
459 Assert(k == STRING_SUBSTR || k == STRING_STRCTN || k == STRING_STRIDOF
460 || k == STRING_ITOS
461 || k == STRING_STOI
462 || k == STRING_STRREPL
463 || k == STRING_LEQ);
464 std::vector< Node > new_nodes;
465 Node res = d_preproc.simplify( n, new_nodes );
466 Assert( res!=n );
467 new_nodes.push_back( NodeManager::currentNM()->mkNode( kind::EQUAL, res, n ) );
468 Node nnlem = new_nodes.size()==1 ? new_nodes[0] : NodeManager::currentNM()->mkNode( kind::AND, new_nodes );
469 nnlem = Rewriter::rewrite( nnlem );
470 Trace("strings-red-lemma") << "Reduction_" << effort << " lemma : " << nnlem << std::endl;
471 Trace("strings-red-lemma") << "...from " << n << std::endl;
472 sendInference( d_empty_vec, nnlem, "Reduction", true );
473 //we've reduced this n
474 Trace("strings-extf-debug") << " resolve extf : " << n << " based on reduction." << std::endl;
475 return 1;
476 }
477 }else{
478 return 1;
479 }
480 }
481 }
482 return 0;
483 }
484
485 /////////////////////////////////////////////////////////////////////////////
486 // NOTIFICATIONS
487 /////////////////////////////////////////////////////////////////////////////
488
489
490 void TheoryStrings::presolve() {
491 Debug("strings-presolve") << "TheoryStrings::Presolving : get fmf options " << (options::stringFMF() ? "true" : "false") << std::endl;
492 initializeStrategy();
493 }
494
495
496 /////////////////////////////////////////////////////////////////////////////
497 // MODEL GENERATION
498 /////////////////////////////////////////////////////////////////////////////
499
500 bool TheoryStrings::collectModelInfo(TheoryModel* m)
501 {
502 Trace("strings-model") << "TheoryStrings : Collect model info" << std::endl;
503 Trace("strings-model") << "TheoryStrings : assertEqualityEngine." << std::endl;
504
505 //AJR : no use doing this since we cannot preregister terms with finite types that don't belong to strings.
506 // change this if we generalize to sequences.
507 //set<Node> termSet;
508 // Compute terms appearing in assertions and shared terms
509 //computeRelevantTerms(termSet);
510 //m->assertEqualityEngine( &d_equalityEngine, &termSet );
511
512 if (!m->assertEqualityEngine(&d_equalityEngine))
513 {
514 return false;
515 }
516
517 NodeManager* nm = NodeManager::currentNM();
518 // Generate model
519 std::vector< Node > nodes;
520 getEquivalenceClasses( nodes );
521 std::map< Node, Node > processed;
522 std::vector< std::vector< Node > > col;
523 std::vector< Node > lts;
524 separateByLength( nodes, col, lts );
525 //step 1 : get all values for known lengths
526 std::vector< Node > lts_values;
527 std::map< unsigned, bool > values_used;
528 for( unsigned i=0; i<col.size(); i++ ) {
529 Trace("strings-model") << "Checking length for {";
530 for( unsigned j=0; j<col[i].size(); j++ ) {
531 if( j>0 ) {
532 Trace("strings-model") << ", ";
533 }
534 Trace("strings-model") << col[i][j];
535 }
536 Trace("strings-model") << " } (length is " << lts[i] << ")" << std::endl;
537 if( lts[i].isConst() ) {
538 lts_values.push_back( lts[i] );
539 Assert(lts[i].getConst<Rational>() <= RMAXINT, "Exceeded LONG_MAX in string model");
540 unsigned lvalue = lts[i].getConst<Rational>().getNumerator().toUnsignedInt();
541 values_used[ lvalue ] = true;
542 }else{
543 //get value for lts[i];
544 if( !lts[i].isNull() ){
545 Node v = d_valuation.getModelValue(lts[i]);
546 Trace("strings-model") << "Model value for " << lts[i] << " is " << v << std::endl;
547 lts_values.push_back( v );
548 Assert(v.getConst<Rational>() <= RMAXINT, "Exceeded LONG_MAX in string model");
549 unsigned lvalue = v.getConst<Rational>().getNumerator().toUnsignedInt();
550 values_used[ lvalue ] = true;
551 }else{
552 //Trace("strings-model-warn") << "No length for eqc " << col[i][0] << std::endl;
553 //Assert( false );
554 lts_values.push_back( Node::null() );
555 }
556 }
557 }
558 ////step 2 : assign arbitrary values for unknown lengths?
559 // confirmed by calculus invariant, see paper
560 Trace("strings-model") << "Assign to equivalence classes..." << std::endl;
561 std::map<Node, Node> pure_eq_assign;
562 //step 3 : assign values to equivalence classes that are pure variables
563 for( unsigned i=0; i<col.size(); i++ ){
564 std::vector< Node > pure_eq;
565 Trace("strings-model") << "The equivalence classes ";
566 for (const Node& eqc : col[i])
567 {
568 Trace("strings-model") << eqc << " ";
569 //check if col[i][j] has only variables
570 if (!eqc.isConst())
571 {
572 Assert(d_normal_forms.find(eqc) != d_normal_forms.end());
573 if (d_normal_forms[eqc].size() == 1)
574 {
575 // does it have a code and the length of these equivalence classes are
576 // one?
577 if (d_has_str_code && lts_values[i] == d_one)
578 {
579 EqcInfo* eip = getOrMakeEqcInfo(eqc, false);
580 if (eip && !eip->d_code_term.get().isNull())
581 {
582 // its value must be equal to its code
583 Node ct = nm->mkNode(kind::STRING_CODE, eip->d_code_term.get());
584 Node ctv = d_valuation.getModelValue(ct);
585 unsigned cvalue =
586 ctv.getConst<Rational>().getNumerator().toUnsignedInt();
587 Trace("strings-model") << "(code: " << cvalue << ") ";
588 std::vector<unsigned> vec;
589 vec.push_back(String::convertCodeToUnsignedInt(cvalue));
590 Node mv = nm->mkConst(String(vec));
591 pure_eq_assign[eqc] = mv;
592 m->getEqualityEngine()->addTerm(mv);
593 }
594 }
595 pure_eq.push_back(eqc);
596 }
597 }
598 else
599 {
600 processed[eqc] = eqc;
601 }
602 }
603 Trace("strings-model") << "have length " << lts_values[i] << std::endl;
604
605 //assign a new length if necessary
606 if( !pure_eq.empty() ){
607 if( lts_values[i].isNull() ){
608 // start with length two (other lengths have special precendence)
609 unsigned lvalue = 2;
610 while( values_used.find( lvalue )!=values_used.end() ){
611 lvalue++;
612 }
613 Trace("strings-model") << "*** Decide to make length of " << lvalue << std::endl;
614 lts_values[i] = nm->mkConst(Rational(lvalue));
615 values_used[ lvalue ] = true;
616 }
617 Trace("strings-model") << "Need to assign values of length " << lts_values[i] << " to equivalence classes ";
618 for( unsigned j=0; j<pure_eq.size(); j++ ){
619 Trace("strings-model") << pure_eq[j] << " ";
620 }
621 Trace("strings-model") << std::endl;
622
623 //use type enumerator
624 Assert(lts_values[i].getConst<Rational>() <= RMAXINT, "Exceeded LONG_MAX in string model");
625 StringEnumeratorLength sel(lts_values[i].getConst<Rational>().getNumerator().toUnsignedInt());
626 for (const Node& eqc : pure_eq)
627 {
628 Node c;
629 std::map<Node, Node>::iterator itp = pure_eq_assign.find(eqc);
630 if (itp == pure_eq_assign.end())
631 {
632 Assert( !sel.isFinished() );
633 c = *sel;
634 while (m->hasTerm(c))
635 {
636 ++sel;
637 Assert(!sel.isFinished());
638 c = *sel;
639 }
640 ++sel;
641 }
642 else
643 {
644 c = itp->second;
645 }
646 Trace("strings-model") << "*** Assigned constant " << c << " for "
647 << eqc << std::endl;
648 processed[eqc] = c;
649 if (!m->assertEquality(eqc, c, true))
650 {
651 return false;
652 }
653 }
654 }
655 }
656 Trace("strings-model") << "String Model : Pure Assigned." << std::endl;
657 //step 4 : assign constants to all other equivalence classes
658 for( unsigned i=0; i<nodes.size(); i++ ){
659 if( processed.find( nodes[i] )==processed.end() ){
660 Assert( d_normal_forms.find( nodes[i] )!=d_normal_forms.end() );
661 Trace("strings-model") << "Construct model for " << nodes[i] << " based on normal form ";
662 for( unsigned j=0; j<d_normal_forms[nodes[i]].size(); j++ ) {
663 if( j>0 ) Trace("strings-model") << " ++ ";
664 Trace("strings-model") << d_normal_forms[nodes[i]][j];
665 Node r = getRepresentative( d_normal_forms[nodes[i]][j] );
666 if( !r.isConst() && processed.find( r )==processed.end() ){
667 Trace("strings-model") << "(UNPROCESSED)";
668 }
669 }
670 Trace("strings-model") << std::endl;
671 std::vector< Node > nc;
672 for( unsigned j=0; j<d_normal_forms[nodes[i]].size(); j++ ) {
673 Node r = getRepresentative( d_normal_forms[nodes[i]][j] );
674 Assert( r.isConst() || processed.find( r )!=processed.end() );
675 nc.push_back(r.isConst() ? r : processed[r]);
676 }
677 Node cc = mkConcat( nc );
678 Assert( cc.getKind()==kind::CONST_STRING );
679 Trace("strings-model") << "*** Determined constant " << cc << " for " << nodes[i] << std::endl;
680 processed[nodes[i]] = cc;
681 if (!m->assertEquality(nodes[i], cc, true))
682 {
683 return false;
684 }
685 }
686 }
687 //Trace("strings-model") << "String Model : Assigned." << std::endl;
688 Trace("strings-model") << "String Model : Finished." << std::endl;
689 return true;
690 }
691
692 /////////////////////////////////////////////////////////////////////////////
693 // MAIN SOLVER
694 /////////////////////////////////////////////////////////////////////////////
695
696
697 void TheoryStrings::preRegisterTerm(TNode n) {
698 if( d_pregistered_terms_cache.find(n) == d_pregistered_terms_cache.end() ) {
699 d_pregistered_terms_cache.insert(n);
700 Trace("strings-preregister")
701 << "TheoryString::preregister : " << n << std::endl;
702 //check for logic exceptions
703 Kind k = n.getKind();
704 if( !options::stringExp() ){
705 if (k == kind::STRING_STRIDOF || k == kind::STRING_ITOS
706 || k == kind::STRING_STOI
707 || k == kind::STRING_STRREPL
708 || k == kind::STRING_STRCTN
709 || k == STRING_LEQ)
710 {
711 std::stringstream ss;
712 ss << "Term of kind " << k
713 << " not supported in default mode, try --strings-exp";
714 throw LogicException(ss.str());
715 }
716 }
717 switch (k)
718 {
719 case kind::EQUAL: {
720 d_equalityEngine.addTriggerEquality(n);
721 break;
722 }
723 case kind::STRING_IN_REGEXP: {
724 d_out->requirePhase(n, true);
725 d_equalityEngine.addTriggerPredicate(n);
726 d_equalityEngine.addTerm(n[0]);
727 d_equalityEngine.addTerm(n[1]);
728 break;
729 }
730 default: {
731 registerTerm(n, 0);
732 TypeNode tn = n.getType();
733 if (tn.isRegExp() && n.isVar())
734 {
735 std::stringstream ss;
736 ss << "Regular expression variables are not supported.";
737 throw LogicException(ss.str());
738 }
739 if( tn.isString() ) {
740 // all characters of constants should fall in the alphabet
741 if (n.isConst())
742 {
743 std::vector<unsigned> vec = n.getConst<String>().getVec();
744 for (unsigned u : vec)
745 {
746 if (u >= d_card_size)
747 {
748 std::stringstream ss;
749 ss << "Characters in string \"" << n
750 << "\" are outside of the given alphabet.";
751 throw LogicException(ss.str());
752 }
753 }
754 }
755 // if finite model finding is enabled,
756 // then we minimize the length of this term if it is a variable
757 // but not an internally generated Skolem, or a term that does
758 // not belong to this theory.
759 if (options::stringFMF()
760 && (n.isVar() ? d_all_skolems.find(n) == d_all_skolems.end()
761 : kindToTheoryId(k) != THEORY_STRINGS))
762 {
763 d_input_vars.insert(n);
764 }
765 d_equalityEngine.addTerm(n);
766 } else if (tn.isBoolean()) {
767 // Get triggered for both equal and dis-equal
768 d_equalityEngine.addTriggerPredicate(n);
769 } else {
770 // Function applications/predicates
771 d_equalityEngine.addTerm(n);
772 if( options::stringExp() ){
773 //collect extended functions here: some may not be asserted to strings (such as those with return type Int),
774 // but we need to record them so they are treated properly
775 getExtTheory()->registerTermRec( n );
776 }
777 }
778 //concat terms do not contribute to theory combination? TODO: verify
779 if (n.hasOperator() && kindToTheoryId(k) == THEORY_STRINGS
780 && k != kind::STRING_CONCAT)
781 {
782 d_functionsTerms.push_back( n );
783 }
784 }
785 }
786 }
787 }
788
789 Node TheoryStrings::expandDefinition(LogicRequest &logicRequest, Node node) {
790 Trace("strings-exp-def") << "TheoryStrings::expandDefinition : " << node << std::endl;
791 return node;
792 }
793
794
795 void TheoryStrings::check(Effort e) {
796 if (done() && e<EFFORT_FULL) {
797 return;
798 }
799
800 TimerStat::CodeTimer checkTimer(d_checkTime);
801
802 bool polarity;
803 TNode atom;
804
805 if( !done() && !hasTerm( d_emptyString ) ) {
806 preRegisterTerm( d_emptyString );
807 }
808
809 // Trace("strings-process") << "Theory of strings, check : " << e << std::endl;
810 Trace("strings-check") << "Theory of strings, check : " << e << std::endl;
811 while ( !done() && !d_conflict ) {
812 // Get all the assertions
813 Assertion assertion = get();
814 TNode fact = assertion.assertion;
815
816 Trace("strings-assertion") << "get assertion: " << fact << endl;
817 polarity = fact.getKind() != kind::NOT;
818 atom = polarity ? fact : fact[0];
819
820 //assert pending fact
821 assertPendingFact( atom, polarity, fact );
822 }
823 doPendingFacts();
824
825 Assert(d_strategy_init);
826 std::map<Effort, std::pair<unsigned, unsigned> >::iterator itsr =
827 d_strat_steps.find(e);
828 if (!d_conflict && !d_valuation.needCheck() && itsr != d_strat_steps.end())
829 {
830 Trace("strings-check") << "Theory of strings " << e << " effort check "
831 << std::endl;
832 if(Trace.isOn("strings-eqc")) {
833 for( unsigned t=0; t<2; t++ ) {
834 eq::EqClassesIterator eqcs2_i = eq::EqClassesIterator( &d_equalityEngine );
835 Trace("strings-eqc") << (t==0 ? "STRINGS:" : "OTHER:") << std::endl;
836 while( !eqcs2_i.isFinished() ){
837 Node eqc = (*eqcs2_i);
838 bool print = (t==0 && eqc.getType().isString() ) || (t==1 && !eqc.getType().isString() );
839 if (print) {
840 eq::EqClassIterator eqc2_i = eq::EqClassIterator( eqc, &d_equalityEngine );
841 Trace("strings-eqc") << "Eqc( " << eqc << " ) : { ";
842 while( !eqc2_i.isFinished() ) {
843 if( (*eqc2_i)!=eqc && (*eqc2_i).getKind()!=kind::EQUAL ){
844 Trace("strings-eqc") << (*eqc2_i) << " ";
845 }
846 ++eqc2_i;
847 }
848 Trace("strings-eqc") << " } " << std::endl;
849 EqcInfo * ei = getOrMakeEqcInfo( eqc, false );
850 if( ei ){
851 Trace("strings-eqc-debug") << "* Length term : " << ei->d_length_term.get() << std::endl;
852 Trace("strings-eqc-debug") << "* Cardinality lemma k : " << ei->d_cardinality_lem_k.get() << std::endl;
853 Trace("strings-eqc-debug") << "* Normalization length lemma : " << ei->d_normalized_length.get() << std::endl;
854 }
855 }
856 ++eqcs2_i;
857 }
858 Trace("strings-eqc") << std::endl;
859 }
860 Trace("strings-eqc") << std::endl;
861 }
862 unsigned sbegin = itsr->second.first;
863 unsigned send = itsr->second.second;
864 bool addedLemma = false;
865 bool addedFact;
866 do{
867 runStrategy(sbegin, send);
868 // flush the facts
869 addedFact = !d_pending.empty();
870 addedLemma = !d_lemma_cache.empty();
871 doPendingFacts();
872 doPendingLemmas();
873 // repeat if we did not add a lemma or conflict
874 }while( !d_conflict && !addedLemma && addedFact );
875
876 Trace("strings-check") << "Theory of strings done full effort check " << addedLemma << " " << d_conflict << std::endl;
877 }
878 Trace("strings-check") << "Theory of strings, done check : " << e << std::endl;
879 Assert( d_pending.empty() );
880 Assert( d_lemma_cache.empty() );
881 }
882
883 bool TheoryStrings::needsCheckLastEffort() {
884 if( options::stringGuessModel() ){
885 return d_has_extf.get();
886 }else{
887 return false;
888 }
889 }
890
891 void TheoryStrings::checkExtfReductions( int effort ) {
892 //standardize this?
893 //std::vector< Node > nred;
894 //getExtTheory()->doReductions( effort, nred, false );
895
896 std::vector< Node > extf = getExtTheory()->getActive();
897 Trace("strings-process") << " checking " << extf.size() << " active extf"
898 << std::endl;
899 for( unsigned i=0; i<extf.size(); i++ ){
900 Node n = extf[i];
901 Trace("strings-process") << " check " << n << ", active in model="
902 << d_extf_info_tmp[n].d_model_active << std::endl;
903 Node nr;
904 int ret = getReduction( effort, n, nr );
905 Assert( nr.isNull() );
906 if( ret!=0 ){
907 getExtTheory()->markReduced( extf[i] );
908 if (hasProcessed())
909 {
910 return;
911 }
912 }
913 }
914 }
915
916 TheoryStrings::EqcInfo::EqcInfo(context::Context* c)
917 : d_length_term(c),
918 d_code_term(c),
919 d_cardinality_lem_k(c),
920 d_normalized_length(c)
921 {
922 }
923
924 TheoryStrings::EqcInfo * TheoryStrings::getOrMakeEqcInfo( Node eqc, bool doMake ) {
925 std::map< Node, EqcInfo* >::iterator eqc_i = d_eqc_info.find( eqc );
926 if( eqc_i==d_eqc_info.end() ){
927 if( doMake ){
928 EqcInfo* ei = new EqcInfo( getSatContext() );
929 d_eqc_info[eqc] = ei;
930 return ei;
931 }else{
932 return NULL;
933 }
934 }else{
935 return (*eqc_i).second;
936 }
937 }
938
939
940 /** Conflict when merging two constants */
941 void TheoryStrings::conflict(TNode a, TNode b){
942 if( !d_conflict ){
943 Debug("strings-conflict") << "Making conflict..." << std::endl;
944 d_conflict = true;
945 Node conflictNode;
946 conflictNode = explain( a.eqNode(b) );
947 Trace("strings-conflict") << "CONFLICT: Eq engine conflict : " << conflictNode << std::endl;
948 d_out->conflict( conflictNode );
949 }
950 }
951
952 /** called when a new equivalance class is created */
953 void TheoryStrings::eqNotifyNewClass(TNode t){
954 Kind k = t.getKind();
955 if (k == kind::STRING_LENGTH || k == kind::STRING_CODE)
956 {
957 Trace("strings-debug") << "New length eqc : " << t << std::endl;
958 Node r = d_equalityEngine.getRepresentative(t[0]);
959 EqcInfo * ei = getOrMakeEqcInfo( r, true );
960 if (k == kind::STRING_LENGTH)
961 {
962 ei->d_length_term = t[0];
963 }
964 else
965 {
966 ei->d_code_term = t[0];
967 }
968 //we care about the length of this string
969 registerTerm( t[0], 1 );
970 }else{
971 //getExtTheory()->registerTerm( t );
972 }
973 }
974
975 /** called when two equivalance classes will merge */
976 void TheoryStrings::eqNotifyPreMerge(TNode t1, TNode t2){
977 EqcInfo * e2 = getOrMakeEqcInfo(t2, false);
978 if( e2 ){
979 EqcInfo * e1 = getOrMakeEqcInfo( t1 );
980 //add information from e2 to e1
981 if( !e2->d_length_term.get().isNull() ){
982 e1->d_length_term.set( e2->d_length_term );
983 }
984 if (!e2->d_code_term.get().isNull())
985 {
986 e1->d_code_term.set(e2->d_code_term);
987 }
988 if( e2->d_cardinality_lem_k.get()>e1->d_cardinality_lem_k.get() ) {
989 e1->d_cardinality_lem_k.set( e2->d_cardinality_lem_k );
990 }
991 if( !e2->d_normalized_length.get().isNull() ){
992 e1->d_normalized_length.set( e2->d_normalized_length );
993 }
994 }
995 }
996
997 /** called when two equivalance classes have merged */
998 void TheoryStrings::eqNotifyPostMerge(TNode t1, TNode t2) {
999
1000 }
1001
1002 /** called when two equivalance classes are disequal */
1003 void TheoryStrings::eqNotifyDisequal(TNode t1, TNode t2, TNode reason) {
1004 if( t1.getType().isString() ){
1005 //store disequalities between strings, may need to check if their lengths are equal/disequal
1006 d_ee_disequalities.push_back( t1.eqNode( t2 ) );
1007 }
1008 }
1009
1010 void TheoryStrings::addCarePairs( quantifiers::TermArgTrie * t1, quantifiers::TermArgTrie * t2, unsigned arity, unsigned depth ) {
1011 if( depth==arity ){
1012 if( t2!=NULL ){
1013 Node f1 = t1->getNodeData();
1014 Node f2 = t2->getNodeData();
1015 if( !d_equalityEngine.areEqual( f1, f2 ) ){
1016 Trace("strings-cg-debug") << "TheoryStrings::computeCareGraph(): checking function " << f1 << " and " << f2 << std::endl;
1017 vector< pair<TNode, TNode> > currentPairs;
1018 for (unsigned k = 0; k < f1.getNumChildren(); ++ k) {
1019 TNode x = f1[k];
1020 TNode y = f2[k];
1021 Assert( d_equalityEngine.hasTerm(x) );
1022 Assert( d_equalityEngine.hasTerm(y) );
1023 Assert( !d_equalityEngine.areDisequal( x, y, false ) );
1024 Assert( !areCareDisequal( x, y ) );
1025 if( !d_equalityEngine.areEqual( x, y ) ){
1026 if( d_equalityEngine.isTriggerTerm(x, THEORY_STRINGS) && d_equalityEngine.isTriggerTerm(y, THEORY_STRINGS) ){
1027 TNode x_shared = d_equalityEngine.getTriggerTermRepresentative(x, THEORY_STRINGS);
1028 TNode y_shared = d_equalityEngine.getTriggerTermRepresentative(y, THEORY_STRINGS);
1029 currentPairs.push_back(make_pair(x_shared, y_shared));
1030 }
1031 }
1032 }
1033 for (unsigned c = 0; c < currentPairs.size(); ++ c) {
1034 Trace("strings-cg-pair") << "TheoryStrings::computeCareGraph(): pair : " << currentPairs[c].first << " " << currentPairs[c].second << std::endl;
1035 addCarePair(currentPairs[c].first, currentPairs[c].second);
1036 }
1037 }
1038 }
1039 }else{
1040 if( t2==NULL ){
1041 if( depth<(arity-1) ){
1042 //add care pairs internal to each child
1043 for( std::map< TNode, quantifiers::TermArgTrie >::iterator it = t1->d_data.begin(); it != t1->d_data.end(); ++it ){
1044 addCarePairs( &it->second, NULL, arity, depth+1 );
1045 }
1046 }
1047 //add care pairs based on each pair of non-disequal arguments
1048 for( std::map< TNode, quantifiers::TermArgTrie >::iterator it = t1->d_data.begin(); it != t1->d_data.end(); ++it ){
1049 std::map< TNode, quantifiers::TermArgTrie >::iterator it2 = it;
1050 ++it2;
1051 for( ; it2 != t1->d_data.end(); ++it2 ){
1052 if( !d_equalityEngine.areDisequal(it->first, it2->first, false) ){
1053 if( !areCareDisequal(it->first, it2->first) ){
1054 addCarePairs( &it->second, &it2->second, arity, depth+1 );
1055 }
1056 }
1057 }
1058 }
1059 }else{
1060 //add care pairs based on product of indices, non-disequal arguments
1061 for( std::map< TNode, quantifiers::TermArgTrie >::iterator it = t1->d_data.begin(); it != t1->d_data.end(); ++it ){
1062 for( std::map< TNode, quantifiers::TermArgTrie >::iterator it2 = t2->d_data.begin(); it2 != t2->d_data.end(); ++it2 ){
1063 if( !d_equalityEngine.areDisequal(it->first, it2->first, false) ){
1064 if( !areCareDisequal(it->first, it2->first) ){
1065 addCarePairs( &it->second, &it2->second, arity, depth+1 );
1066 }
1067 }
1068 }
1069 }
1070 }
1071 }
1072 }
1073
1074 void TheoryStrings::computeCareGraph(){
1075 //computing the care graph here is probably still necessary, due to operators that take non-string arguments TODO: verify
1076 Trace("strings-cg") << "TheoryStrings::computeCareGraph(): Build term indices..." << std::endl;
1077 std::map< Node, quantifiers::TermArgTrie > index;
1078 std::map< Node, unsigned > arity;
1079 unsigned functionTerms = d_functionsTerms.size();
1080 for (unsigned i = 0; i < functionTerms; ++ i) {
1081 TNode f1 = d_functionsTerms[i];
1082 Trace("strings-cg") << "...build for " << f1 << std::endl;
1083 Node op = f1.getOperator();
1084 std::vector< TNode > reps;
1085 bool has_trigger_arg = false;
1086 for( unsigned j=0; j<f1.getNumChildren(); j++ ){
1087 reps.push_back( d_equalityEngine.getRepresentative( f1[j] ) );
1088 if( d_equalityEngine.isTriggerTerm( f1[j], THEORY_STRINGS ) ){
1089 has_trigger_arg = true;
1090 }
1091 }
1092 if( has_trigger_arg ){
1093 index[op].addTerm( f1, reps );
1094 arity[op] = reps.size();
1095 }
1096 }
1097 //for each index
1098 for( std::map< Node, quantifiers::TermArgTrie >::iterator itii = index.begin(); itii != index.end(); ++itii ){
1099 Trace("strings-cg") << "TheoryStrings::computeCareGraph(): Process index " << itii->first << "..." << std::endl;
1100 addCarePairs( &itii->second, NULL, arity[ itii->first ], 0 );
1101 }
1102 }
1103
1104 void TheoryStrings::assertPendingFact(Node atom, bool polarity, Node exp) {
1105 Trace("strings-pending") << "Assert pending fact : " << atom << " " << polarity << " from " << exp << std::endl;
1106 Assert(atom.getKind() != kind::OR, "Infer error: a split.");
1107 if( atom.getKind()==kind::EQUAL ){
1108 Trace("strings-pending-debug") << " Register term" << std::endl;
1109 for( unsigned j=0; j<2; j++ ) {
1110 if( !d_equalityEngine.hasTerm( atom[j] ) && atom[j].getType().isString() ) {
1111 registerTerm( atom[j], 0 );
1112 }
1113 }
1114 Trace("strings-pending-debug") << " Now assert equality" << std::endl;
1115 d_equalityEngine.assertEquality( atom, polarity, exp );
1116 Trace("strings-pending-debug") << " Finished assert equality" << std::endl;
1117 } else {
1118 d_equalityEngine.assertPredicate( atom, polarity, exp );
1119 //process extf
1120 if( atom.getKind()==kind::STRING_IN_REGEXP ){
1121 if( polarity && atom[1].getKind()==kind::REGEXP_RANGE ){
1122 if( d_extf_infer_cache_u.find( atom )==d_extf_infer_cache_u.end() ){
1123 d_extf_infer_cache_u.insert( atom );
1124 //length of first argument is one
1125 Node conc = d_one.eqNode( NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, atom[0] ) );
1126 Node lem = NodeManager::currentNM()->mkNode( kind::OR, atom.negate(), conc );
1127 Trace("strings-lemma") << "Strings::Lemma RE-Range-Len : " << lem << std::endl;
1128 d_out->lemma( lem );
1129 }
1130 }
1131 }
1132 //register the atom here, since it may not create a new equivalence class
1133 //getExtTheory()->registerTerm( atom );
1134 }
1135 Trace("strings-pending-debug") << " Now collect terms" << std::endl;
1136 //collect extended function terms in the atom
1137 getExtTheory()->registerTermRec( atom );
1138 Trace("strings-pending-debug") << " Finished collect terms" << std::endl;
1139 }
1140
1141 void TheoryStrings::doPendingFacts() {
1142 size_t i=0;
1143 while( !d_conflict && i<d_pending.size() ) {
1144 Node fact = d_pending[i];
1145 Node exp = d_pending_exp[ fact ];
1146 if(fact.getKind() == kind::AND) {
1147 for(size_t j=0; j<fact.getNumChildren(); j++) {
1148 bool polarity = fact[j].getKind() != kind::NOT;
1149 TNode atom = polarity ? fact[j] : fact[j][0];
1150 assertPendingFact(atom, polarity, exp);
1151 }
1152 } else {
1153 bool polarity = fact.getKind() != kind::NOT;
1154 TNode atom = polarity ? fact : fact[0];
1155 assertPendingFact(atom, polarity, exp);
1156 }
1157 i++;
1158 }
1159 d_pending.clear();
1160 d_pending_exp.clear();
1161 }
1162
1163 void TheoryStrings::doPendingLemmas() {
1164 if( !d_conflict && !d_lemma_cache.empty() ){
1165 for( unsigned i=0; i<d_lemma_cache.size(); i++ ){
1166 Trace("strings-pending") << "Process pending lemma : " << d_lemma_cache[i] << std::endl;
1167 d_out->lemma( d_lemma_cache[i] );
1168 }
1169 for( std::map< Node, bool >::iterator it = d_pending_req_phase.begin(); it != d_pending_req_phase.end(); ++it ){
1170 Trace("strings-pending") << "Require phase : " << it->first << ", polarity = " << it->second << std::endl;
1171 d_out->requirePhase( it->first, it->second );
1172 }
1173 }
1174 d_lemma_cache.clear();
1175 d_pending_req_phase.clear();
1176 }
1177
1178 bool TheoryStrings::hasProcessed() {
1179 return d_conflict || !d_lemma_cache.empty() || !d_pending.empty();
1180 }
1181
1182 void TheoryStrings::addToExplanation( Node a, Node b, std::vector< Node >& exp ) {
1183 if( a!=b ){
1184 Debug("strings-explain") << "Add to explanation : " << a << " == " << b << std::endl;
1185 Assert( areEqual( a, b ) );
1186 exp.push_back( a.eqNode( b ) );
1187 }
1188 }
1189
1190 void TheoryStrings::addToExplanation( Node lit, std::vector< Node >& exp ) {
1191 if( !lit.isNull() ){
1192 exp.push_back( lit );
1193 }
1194 }
1195
1196 void TheoryStrings::checkInit() {
1197 //build term index
1198 d_eqc_to_const.clear();
1199 d_eqc_to_const_base.clear();
1200 d_eqc_to_const_exp.clear();
1201 d_eqc_to_len_term.clear();
1202 d_term_index.clear();
1203 d_strings_eqc.clear();
1204
1205 std::map< Kind, unsigned > ncongruent;
1206 std::map< Kind, unsigned > congruent;
1207 d_emptyString_r = getRepresentative( d_emptyString );
1208 eq::EqClassesIterator eqcs_i = eq::EqClassesIterator( &d_equalityEngine );
1209 while( !eqcs_i.isFinished() ){
1210 Node eqc = (*eqcs_i);
1211 TypeNode tn = eqc.getType();
1212 if( !tn.isRegExp() ){
1213 if( tn.isString() ){
1214 d_strings_eqc.push_back( eqc );
1215 }
1216 Node var;
1217 eq::EqClassIterator eqc_i = eq::EqClassIterator( eqc, &d_equalityEngine );
1218 while( !eqc_i.isFinished() ) {
1219 Node n = *eqc_i;
1220 if( n.isConst() ){
1221 d_eqc_to_const[eqc] = n;
1222 d_eqc_to_const_base[eqc] = n;
1223 d_eqc_to_const_exp[eqc] = Node::null();
1224 }else if( tn.isInteger() ){
1225 if( n.getKind()==kind::STRING_LENGTH ){
1226 Node nr = getRepresentative( n[0] );
1227 d_eqc_to_len_term[nr] = n[0];
1228 }
1229 }else if( n.getNumChildren()>0 ){
1230 Kind k = n.getKind();
1231 if( k!=kind::EQUAL ){
1232 if( d_congruent.find( n )==d_congruent.end() ){
1233 std::vector< Node > c;
1234 Node nc = d_term_index[k].add( n, 0, this, d_emptyString_r, c );
1235 if( nc!=n ){
1236 //check if we have inferred a new equality by removal of empty components
1237 if( n.getKind()==kind::STRING_CONCAT && !areEqual( nc, n ) ){
1238 std::vector< Node > exp;
1239 unsigned count[2] = { 0, 0 };
1240 while( count[0]<nc.getNumChildren() || count[1]<n.getNumChildren() ){
1241 //explain empty prefixes
1242 for( unsigned t=0; t<2; t++ ){
1243 Node nn = t==0 ? nc : n;
1244 while( count[t]<nn.getNumChildren() &&
1245 ( nn[count[t]]==d_emptyString || areEqual( nn[count[t]], d_emptyString ) ) ){
1246 if( nn[count[t]]!=d_emptyString ){
1247 exp.push_back( nn[count[t]].eqNode( d_emptyString ) );
1248 }
1249 count[t]++;
1250 }
1251 }
1252 //explain equal components
1253 if( count[0]<nc.getNumChildren() ){
1254 Assert( count[1]<n.getNumChildren() );
1255 if( nc[count[0]]!=n[count[1]] ){
1256 exp.push_back( nc[count[0]].eqNode( n[count[1]] ) );
1257 }
1258 count[0]++;
1259 count[1]++;
1260 }
1261 }
1262 //infer the equality
1263 sendInference( exp, n.eqNode( nc ), "I_Norm" );
1264 }else if( getExtTheory()->hasFunctionKind( n.getKind() ) ){
1265 //mark as congruent : only process if neither has been reduced
1266 getExtTheory()->markCongruent( nc, n );
1267 }
1268 //this node is congruent to another one, we can ignore it
1269 Trace("strings-process-debug") << " congruent term : " << n << std::endl;
1270 d_congruent.insert( n );
1271 congruent[k]++;
1272 }else if( k==kind::STRING_CONCAT && c.size()==1 ){
1273 Trace("strings-process-debug") << " congruent term by singular : " << n << " " << c[0] << std::endl;
1274 //singular case
1275 if( !areEqual( c[0], n ) ){
1276 std::vector< Node > exp;
1277 //explain empty components
1278 bool foundNEmpty = false;
1279 for( unsigned i=0; i<n.getNumChildren(); i++ ){
1280 if( areEqual( n[i], d_emptyString ) ){
1281 if( n[i]!=d_emptyString ){
1282 exp.push_back( n[i].eqNode( d_emptyString ) );
1283 }
1284 }else{
1285 Assert( !foundNEmpty );
1286 if( n[i]!=c[0] ){
1287 exp.push_back( n[i].eqNode( c[0] ) );
1288 }
1289 foundNEmpty = true;
1290 }
1291 }
1292 AlwaysAssert( foundNEmpty );
1293 //infer the equality
1294 sendInference( exp, n.eqNode( c[0] ), "I_Norm_S" );
1295 }
1296 d_congruent.insert( n );
1297 congruent[k]++;
1298 }else{
1299 ncongruent[k]++;
1300 }
1301 }else{
1302 congruent[k]++;
1303 }
1304 }
1305 }else{
1306 if( d_congruent.find( n )==d_congruent.end() ){
1307 if( var.isNull() ){
1308 var = n;
1309 }else{
1310 Trace("strings-process-debug") << " congruent variable : " << n << std::endl;
1311 d_congruent.insert( n );
1312 }
1313 }
1314 }
1315 ++eqc_i;
1316 }
1317 }
1318 ++eqcs_i;
1319 }
1320 if( Trace.isOn("strings-process") ){
1321 for( std::map< Kind, TermIndex >::iterator it = d_term_index.begin(); it != d_term_index.end(); ++it ){
1322 Trace("strings-process") << " Terms[" << it->first << "] = " << ncongruent[it->first] << "/" << (congruent[it->first]+ncongruent[it->first]) << std::endl;
1323 }
1324 }
1325 }
1326
1327 void TheoryStrings::checkConstantEquivalenceClasses()
1328 {
1329 // do fixed point
1330 unsigned prevSize;
1331 std::vector<Node> vecc;
1332 do
1333 {
1334 vecc.clear();
1335 Trace("strings-process-debug") << "Check constant equivalence classes..."
1336 << std::endl;
1337 prevSize = d_eqc_to_const.size();
1338 checkConstantEquivalenceClasses(&d_term_index[kind::STRING_CONCAT], vecc);
1339 } while (!hasProcessed() && d_eqc_to_const.size() > prevSize);
1340 }
1341
1342 void TheoryStrings::checkConstantEquivalenceClasses( TermIndex* ti, std::vector< Node >& vecc ) {
1343 Node n = ti->d_data;
1344 if( !n.isNull() ){
1345 //construct the constant
1346 Node c = mkConcat( vecc );
1347 if( !areEqual( n, c ) ){
1348 Trace("strings-debug") << "Constant eqc : " << c << " for " << n << std::endl;
1349 Trace("strings-debug") << " ";
1350 for( unsigned i=0; i<vecc.size(); i++ ){
1351 Trace("strings-debug") << vecc[i] << " ";
1352 }
1353 Trace("strings-debug") << std::endl;
1354 unsigned count = 0;
1355 unsigned countc = 0;
1356 std::vector< Node > exp;
1357 while( count<n.getNumChildren() ){
1358 while( count<n.getNumChildren() && areEqual( n[count], d_emptyString ) ){
1359 addToExplanation( n[count], d_emptyString, exp );
1360 count++;
1361 }
1362 if( count<n.getNumChildren() ){
1363 Trace("strings-debug") << "...explain " << n[count] << " " << vecc[countc] << std::endl;
1364 if( !areEqual( n[count], vecc[countc] ) ){
1365 Node nrr = getRepresentative( n[count] );
1366 Assert( !d_eqc_to_const_exp[nrr].isNull() );
1367 addToExplanation( n[count], d_eqc_to_const_base[nrr], exp );
1368 exp.push_back( d_eqc_to_const_exp[nrr] );
1369 }else{
1370 addToExplanation( n[count], vecc[countc], exp );
1371 }
1372 countc++;
1373 count++;
1374 }
1375 }
1376 //exp contains an explanation of n==c
1377 Assert( countc==vecc.size() );
1378 if( hasTerm( c ) ){
1379 sendInference( exp, n.eqNode( c ), "I_CONST_MERGE" );
1380 return;
1381 }else if( !hasProcessed() ){
1382 Node nr = getRepresentative( n );
1383 std::map< Node, Node >::iterator it = d_eqc_to_const.find( nr );
1384 if( it==d_eqc_to_const.end() ){
1385 Trace("strings-debug") << "Set eqc const " << n << " to " << c << std::endl;
1386 d_eqc_to_const[nr] = c;
1387 d_eqc_to_const_base[nr] = n;
1388 d_eqc_to_const_exp[nr] = mkAnd( exp );
1389 }else if( c!=it->second ){
1390 //conflict
1391 Trace("strings-debug") << "Conflict, other constant was " << it->second << ", this constant was " << c << std::endl;
1392 if( d_eqc_to_const_exp[nr].isNull() ){
1393 // n==c ^ n == c' => false
1394 addToExplanation( n, it->second, exp );
1395 }else{
1396 // n==c ^ n == d_eqc_to_const_base[nr] == c' => false
1397 exp.push_back( d_eqc_to_const_exp[nr] );
1398 addToExplanation( n, d_eqc_to_const_base[nr], exp );
1399 }
1400 sendInference( exp, d_false, "I_CONST_CONFLICT" );
1401 return;
1402 }else{
1403 Trace("strings-debug") << "Duplicate constant." << std::endl;
1404 }
1405 }
1406 }
1407 }
1408 for( std::map< TNode, TermIndex >::iterator it = ti->d_children.begin(); it != ti->d_children.end(); ++it ){
1409 std::map< Node, Node >::iterator itc = d_eqc_to_const.find( it->first );
1410 if( itc!=d_eqc_to_const.end() ){
1411 vecc.push_back( itc->second );
1412 checkConstantEquivalenceClasses( &it->second, vecc );
1413 vecc.pop_back();
1414 if( hasProcessed() ){
1415 break;
1416 }
1417 }
1418 }
1419 }
1420
1421 void TheoryStrings::checkExtfEval( int effort ) {
1422 Trace("strings-extf-list") << "Active extended functions, effort=" << effort << " : " << std::endl;
1423 d_extf_info_tmp.clear();
1424 bool has_nreduce = false;
1425 std::vector< Node > terms = getExtTheory()->getActive();
1426 std::vector< Node > sterms;
1427 std::vector< std::vector< Node > > exp;
1428 getExtTheory()->getSubstitutedTerms( effort, terms, sterms, exp );
1429 for( unsigned i=0; i<terms.size(); i++ ){
1430 Node n = terms[i];
1431 Node sn = sterms[i];
1432 //setup information about extf
1433 d_extf_info_tmp[n].init();
1434 std::map< Node, ExtfInfoTmp >::iterator itit = d_extf_info_tmp.find( n );
1435 if( n.getType().isBoolean() ){
1436 if( areEqual( n, d_true ) ){
1437 itit->second.d_pol = 1;
1438 }else if( areEqual( n, d_false ) ){
1439 itit->second.d_pol = -1;
1440 }
1441 }
1442 Trace("strings-extf-debug") << "Check extf " << n << " == " << sn << ", pol = " << itit->second.d_pol << ", effort=" << effort << "..." << std::endl;
1443 //do the inference
1444 Node to_reduce;
1445 if( n!=sn ){
1446 itit->second.d_exp.insert( itit->second.d_exp.end(), exp[i].begin(), exp[i].end() );
1447 // inference is rewriting the substituted node
1448 Node nrc = Rewriter::rewrite( sn );
1449 //if rewrites to a constant, then do the inference and mark as reduced
1450 if( nrc.isConst() ){
1451 if( effort<3 ){
1452 getExtTheory()->markReduced( n );
1453 Trace("strings-extf-debug") << " resolvable by evaluation..." << std::endl;
1454 std::vector< Node > exps;
1455 // The following optimization gets the "symbolic definition" of
1456 // an extended term. The symbolic definition of a term t is a term
1457 // t' where constants are replaced by their corresponding proxy
1458 // variables.
1459 // For example, if lsym is a proxy variable for "", then
1460 // str.replace( lsym, lsym, lsym ) is the symbolic definition for
1461 // str.replace( "", "", "" ). It is generally better to use symbolic
1462 // definitions when doing cd-rewriting for the purpose of minimizing
1463 // clauses, e.g. we infer the unit equality:
1464 // str.replace( lsym, lsym, lsym ) == ""
1465 // instead of making this inference multiple times:
1466 // x = "" => str.replace( x, x, x ) == ""
1467 // y = "" => str.replace( y, y, y ) == ""
1468 Trace("strings-extf-debug") << " get symbolic definition..." << std::endl;
1469 Node nrs = getSymbolicDefinition( sn, exps );
1470 if( !nrs.isNull() ){
1471 Trace("strings-extf-debug") << " rewrite " << nrs << "..." << std::endl;
1472 Node nrsr = Rewriter::rewrite(nrs);
1473 // ensure the symbolic form is not rewritable
1474 if (nrsr != nrs)
1475 {
1476 // we cannot use the symbolic definition if it rewrites
1477 Trace("strings-extf-debug") << " symbolic definition is trivial..." << std::endl;
1478 nrs = Node::null();
1479 }
1480 }else{
1481 Trace("strings-extf-debug") << " could not infer symbolic definition." << std::endl;
1482 }
1483 Node conc;
1484 if( !nrs.isNull() ){
1485 Trace("strings-extf-debug") << " symbolic def : " << nrs << std::endl;
1486 if( !areEqual( nrs, nrc ) ){
1487 //infer symbolic unit
1488 if( n.getType().isBoolean() ){
1489 conc = nrc==d_true ? nrs : nrs.negate();
1490 }else{
1491 conc = nrs.eqNode( nrc );
1492 }
1493 itit->second.d_exp.clear();
1494 }
1495 }else{
1496 if( !areEqual( n, nrc ) ){
1497 if( n.getType().isBoolean() ){
1498 if( areEqual( n, nrc==d_true ? d_false : d_true ) ){
1499 itit->second.d_exp.push_back( nrc==d_true ? n.negate() : n );
1500 conc = d_false;
1501 }else{
1502 conc = nrc==d_true ? n : n.negate();
1503 }
1504 }else{
1505 conc = n.eqNode( nrc );
1506 }
1507 }
1508 }
1509 if( !conc.isNull() ){
1510 Trace("strings-extf") << " resolve extf : " << sn << " -> " << nrc << std::endl;
1511 sendInference( itit->second.d_exp, conc, effort==0 ? "EXTF" : "EXTF-N", true );
1512 if( d_conflict ){
1513 Trace("strings-extf-debug") << " conflict, return." << std::endl;
1514 return;
1515 }
1516 }
1517 }else{
1518 //check if it is already equal, if so, mark as reduced. Otherwise, do nothing.
1519 if( areEqual( n, nrc ) ){
1520 Trace("strings-extf") << " resolved extf, since satisfied by model: " << n << std::endl;
1521 itit->second.d_model_active = false;
1522 }
1523 }
1524 //if it reduces to a conjunction, infer each and reduce
1525 }else if( ( nrc.getKind()==kind::OR && itit->second.d_pol==-1 ) || ( nrc.getKind()==kind::AND && itit->second.d_pol==1 ) ){
1526 Assert( effort<3 );
1527 getExtTheory()->markReduced( n );
1528 itit->second.d_exp.push_back( itit->second.d_pol==-1 ? n.negate() : n );
1529 Trace("strings-extf-debug") << " decomposable..." << std::endl;
1530 Trace("strings-extf") << " resolve extf : " << sn << " -> " << nrc << ", pol = " << itit->second.d_pol << std::endl;
1531 for( unsigned i=0; i<nrc.getNumChildren(); i++ ){
1532 sendInference( itit->second.d_exp, itit->second.d_pol==-1 ? nrc[i].negate() : nrc[i], effort==0 ? "EXTF_d" : "EXTF_d-N" );
1533 }
1534 }else{
1535 to_reduce = nrc;
1536 }
1537 }else{
1538 to_reduce = sterms[i];
1539 }
1540 //if not reduced
1541 if( !to_reduce.isNull() ){
1542 Assert( effort<3 );
1543 if( effort==1 ){
1544 Trace("strings-extf") << " cannot rewrite extf : " << to_reduce << std::endl;
1545 }
1546 checkExtfInference( n, to_reduce, itit->second, effort );
1547 if( Trace.isOn("strings-extf-list") ){
1548 Trace("strings-extf-list") << " * " << to_reduce;
1549 if( itit->second.d_pol!=0 ){
1550 Trace("strings-extf-list") << ", pol = " << itit->second.d_pol;
1551 }
1552 if( n!=to_reduce ){
1553 Trace("strings-extf-list") << ", from " << n;
1554 }
1555 Trace("strings-extf-list") << std::endl;
1556 }
1557 if( getExtTheory()->isActive( n ) && itit->second.d_model_active ){
1558 has_nreduce = true;
1559 }
1560 }
1561 }
1562 d_has_extf = has_nreduce;
1563 }
1564
1565 void TheoryStrings::checkExtfInference( Node n, Node nr, ExtfInfoTmp& in, int effort ){
1566 //make additional inferences that do not contribute to the reduction of n, but may help show a refutation
1567 if( in.d_pol!=0 ){
1568 //add original to explanation
1569 in.d_exp.push_back( in.d_pol==1 ? n : n.negate() );
1570
1571 //d_extf_infer_cache stores whether we have made the inferences associated with a node n,
1572 // this may need to be generalized if multiple inferences apply
1573
1574 if( nr.getKind()==kind::STRING_STRCTN ){
1575 if( ( in.d_pol==1 && nr[1].getKind()==kind::STRING_CONCAT ) || ( in.d_pol==-1 && nr[0].getKind()==kind::STRING_CONCAT ) ){
1576 if( d_extf_infer_cache.find( nr )==d_extf_infer_cache.end() ){
1577 d_extf_infer_cache.insert( nr );
1578
1579 //one argument does (not) contain each of the components of the other argument
1580 int index = in.d_pol==1 ? 1 : 0;
1581 std::vector< Node > children;
1582 children.push_back( nr[0] );
1583 children.push_back( nr[1] );
1584 //Node exp_n = mkAnd( exp );
1585 for( unsigned i=0; i<nr[index].getNumChildren(); i++ ){
1586 children[index] = nr[index][i];
1587 Node conc = NodeManager::currentNM()->mkNode( kind::STRING_STRCTN, children );
1588 conc = Rewriter::rewrite(in.d_pol == 1 ? conc : conc.negate());
1589 // check if it already (does not) hold
1590 if (hasTerm(conc))
1591 {
1592 if (areEqual(conc, d_false))
1593 {
1594 // should be a conflict
1595 sendInference(in.d_exp, conc, "CTN_Decompose");
1596 }
1597 else if (getExtTheory()->hasFunctionKind(conc.getKind()))
1598 {
1599 // can mark as reduced, since model for n => model for conc
1600 getExtTheory()->markReduced(conc);
1601 }
1602 }
1603 }
1604
1605 }
1606 }else{
1607 //store this (reduced) assertion
1608 //Assert( effort==0 || nr[0]==getRepresentative( nr[0] ) );
1609 bool pol = in.d_pol==1;
1610 if( std::find( d_extf_info_tmp[nr[0]].d_ctn[pol].begin(), d_extf_info_tmp[nr[0]].d_ctn[pol].end(), nr[1] )==d_extf_info_tmp[nr[0]].d_ctn[pol].end() ){
1611 Trace("strings-extf-debug") << " store contains info : " << nr[0] << " " << pol << " " << nr[1] << std::endl;
1612 d_extf_info_tmp[nr[0]].d_ctn[pol].push_back( nr[1] );
1613 d_extf_info_tmp[nr[0]].d_ctn_from[pol].push_back( n );
1614 //transitive closure for contains
1615 bool opol = !pol;
1616 for( unsigned i=0; i<d_extf_info_tmp[nr[0]].d_ctn[opol].size(); i++ ){
1617 Node onr = d_extf_info_tmp[nr[0]].d_ctn[opol][i];
1618 Node conc = NodeManager::currentNM()->mkNode( kind::STRING_STRCTN, pol ? nr[1] : onr, pol ? onr : nr[1] );
1619 conc = Rewriter::rewrite( conc );
1620 bool do_infer = false;
1621 if( conc.getKind()==kind::EQUAL ){
1622 do_infer = !areDisequal( conc[0], conc[1] );
1623 }else{
1624 do_infer = !areEqual( conc, d_false );
1625 }
1626 if( do_infer ){
1627 conc = conc.negate();
1628 std::vector< Node > exp_c;
1629 exp_c.insert( exp_c.end(), in.d_exp.begin(), in.d_exp.end() );
1630 Node ofrom = d_extf_info_tmp[nr[0]].d_ctn_from[opol][i];
1631 Assert( d_extf_info_tmp.find( ofrom )!=d_extf_info_tmp.end() );
1632 exp_c.insert( exp_c.end(), d_extf_info_tmp[ofrom].d_exp.begin(), d_extf_info_tmp[ofrom].d_exp.end() );
1633 sendInference( exp_c, conc, "CTN_Trans" );
1634 }
1635 }
1636 }else{
1637 Trace("strings-extf-debug") << " redundant." << std::endl;
1638 getExtTheory()->markReduced( n );
1639 }
1640 }
1641 }
1642 }
1643 }
1644
1645 Node TheoryStrings::getSymbolicDefinition( Node n, std::vector< Node >& exp ) {
1646 if( n.getNumChildren()==0 ){
1647 NodeNodeMap::const_iterator it = d_proxy_var.find( n );
1648 if( it==d_proxy_var.end() ){
1649 return Node::null();
1650 }else{
1651 Node eq = n.eqNode( (*it).second );
1652 eq = Rewriter::rewrite( eq );
1653 if( std::find( exp.begin(), exp.end(), eq )==exp.end() ){
1654 exp.push_back( eq );
1655 }
1656 return (*it).second;
1657 }
1658 }else{
1659 std::vector< Node > children;
1660 if (n.getMetaKind() == kind::metakind::PARAMETERIZED) {
1661 children.push_back( n.getOperator() );
1662 }
1663 for( unsigned i=0; i<n.getNumChildren(); i++ ){
1664 if( n.getKind()==kind::STRING_IN_REGEXP && i==1 ){
1665 children.push_back( n[i] );
1666 }else{
1667 Node ns = getSymbolicDefinition( n[i], exp );
1668 if( ns.isNull() ){
1669 return Node::null();
1670 }else{
1671 children.push_back( ns );
1672 }
1673 }
1674 }
1675 return NodeManager::currentNM()->mkNode( n.getKind(), children );
1676 }
1677 }
1678
1679 Node TheoryStrings::getConstantEqc( Node eqc ) {
1680 std::map< Node, Node >::iterator it = d_eqc_to_const.find( eqc );
1681 if( it!=d_eqc_to_const.end() ){
1682 return it->second;
1683 }else{
1684 return Node::null();
1685 }
1686 }
1687
1688 void TheoryStrings::debugPrintFlatForms( const char * tc ){
1689 for( unsigned k=0; k<d_strings_eqc.size(); k++ ){
1690 Node eqc = d_strings_eqc[k];
1691 if( d_eqc[eqc].size()>1 ){
1692 Trace( tc ) << "EQC [" << eqc << "]" << std::endl;
1693 }else{
1694 Trace( tc ) << "eqc [" << eqc << "]";
1695 }
1696 std::map< Node, Node >::iterator itc = d_eqc_to_const.find( eqc );
1697 if( itc!=d_eqc_to_const.end() ){
1698 Trace( tc ) << " C: " << itc->second;
1699 if( d_eqc[eqc].size()>1 ){
1700 Trace( tc ) << std::endl;
1701 }
1702 }
1703 if( d_eqc[eqc].size()>1 ){
1704 for( unsigned i=0; i<d_eqc[eqc].size(); i++ ){
1705 Node n = d_eqc[eqc][i];
1706 Trace( tc ) << " ";
1707 for( unsigned j=0; j<d_flat_form[n].size(); j++ ){
1708 Node fc = d_flat_form[n][j];
1709 itc = d_eqc_to_const.find( fc );
1710 Trace( tc ) << " ";
1711 if( itc!=d_eqc_to_const.end() ){
1712 Trace( tc ) << itc->second;
1713 }else{
1714 Trace( tc ) << fc;
1715 }
1716 }
1717 if( n!=eqc ){
1718 Trace( tc ) << ", from " << n;
1719 }
1720 Trace( tc ) << std::endl;
1721 }
1722 }else{
1723 Trace( tc ) << std::endl;
1724 }
1725 }
1726 Trace( tc ) << std::endl;
1727 }
1728
1729 void TheoryStrings::debugPrintNormalForms( const char * tc ) {
1730 }
1731
1732 struct sortConstLength {
1733 std::map< Node, unsigned > d_const_length;
1734 bool operator() (Node i, Node j) {
1735 std::map< Node, unsigned >::iterator it_i = d_const_length.find( i );
1736 std::map< Node, unsigned >::iterator it_j = d_const_length.find( j );
1737 if( it_i==d_const_length.end() ){
1738 if( it_j==d_const_length.end() ){
1739 return i<j;
1740 }else{
1741 return false;
1742 }
1743 }else{
1744 if( it_j==d_const_length.end() ){
1745 return true;
1746 }else{
1747 return it_i->second<it_j->second;
1748 }
1749 }
1750 }
1751 };
1752
1753 void TheoryStrings::checkCycles()
1754 {
1755 // first check for cycles, while building ordering of equivalence classes
1756 d_flat_form.clear();
1757 d_flat_form_index.clear();
1758 d_eqc.clear();
1759 //rebuild strings eqc based on acyclic ordering
1760 std::vector< Node > eqc;
1761 eqc.insert( eqc.end(), d_strings_eqc.begin(), d_strings_eqc.end() );
1762 d_strings_eqc.clear();
1763 if( options::stringBinaryCsp() ){
1764 //sort: process smallest constants first (necessary if doing binary splits)
1765 sortConstLength scl;
1766 for( unsigned i=0; i<eqc.size(); i++ ){
1767 std::map< Node, Node >::iterator itc = d_eqc_to_const.find( eqc[i] );
1768 if( itc!=d_eqc_to_const.end() ){
1769 scl.d_const_length[eqc[i]] = itc->second.getConst<String>().size();
1770 }
1771 }
1772 std::sort( eqc.begin(), eqc.end(), scl );
1773 }
1774 for( unsigned i=0; i<eqc.size(); i++ ){
1775 std::vector< Node > curr;
1776 std::vector< Node > exp;
1777 checkCycles( eqc[i], curr, exp );
1778 if( hasProcessed() ){
1779 return;
1780 }
1781 }
1782 }
1783
1784 void TheoryStrings::checkFlatForms()
1785 {
1786 // debug print flat forms
1787 if (Trace.isOn("strings-ff"))
1788 {
1789 Trace("strings-ff") << "Flat forms : " << std::endl;
1790 debugPrintFlatForms("strings-ff");
1791 }
1792
1793 // inferences without recursively expanding flat forms
1794
1795 //(1) approximate equality by containment, infer conflicts
1796 for (const Node& eqc : d_strings_eqc)
1797 {
1798 Node c = getConstantEqc(eqc);
1799 if (!c.isNull())
1800 {
1801 // if equivalence class is constant, all component constants in flat forms
1802 // must be contained in it, in order
1803 std::map<Node, std::vector<Node> >::iterator it = d_eqc.find(eqc);
1804 if (it != d_eqc.end())
1805 {
1806 for (const Node& n : it->second)
1807 {
1808 int firstc, lastc;
1809 if (!TheoryStringsRewriter::canConstantContainList(
1810 c, d_flat_form[n], firstc, lastc))
1811 {
1812 Trace("strings-ff-debug") << "Flat form for " << n
1813 << " cannot be contained in constant "
1814 << c << std::endl;
1815 Trace("strings-ff-debug") << " indices = " << firstc << "/"
1816 << lastc << std::endl;
1817 // conflict, explanation is n = base ^ base = c ^ relevant portion
1818 // of ( n = f[n] )
1819 std::vector<Node> exp;
1820 Assert(d_eqc_to_const_base.find(eqc) != d_eqc_to_const_base.end());
1821 addToExplanation(n, d_eqc_to_const_base[eqc], exp);
1822 Assert(d_eqc_to_const_exp.find(eqc) != d_eqc_to_const_exp.end());
1823 if (!d_eqc_to_const_exp[eqc].isNull())
1824 {
1825 exp.push_back(d_eqc_to_const_exp[eqc]);
1826 }
1827 for (int e = firstc; e <= lastc; e++)
1828 {
1829 if (d_flat_form[n][e].isConst())
1830 {
1831 Assert(e >= 0 && e < (int)d_flat_form_index[n].size());
1832 Assert(d_flat_form_index[n][e] >= 0
1833 && d_flat_form_index[n][e] < (int)n.getNumChildren());
1834 addToExplanation(
1835 d_flat_form[n][e], n[d_flat_form_index[n][e]], exp);
1836 }
1837 }
1838 Node conc = d_false;
1839 sendInference(exp, conc, "F_NCTN");
1840 return;
1841 }
1842 }
1843 }
1844 }
1845 }
1846
1847 //(2) scan lists, unification to infer conflicts and equalities
1848 for (const Node& eqc : d_strings_eqc)
1849 {
1850 std::map<Node, std::vector<Node> >::iterator it = d_eqc.find(eqc);
1851 if (it == d_eqc.end() || it->second.size() <= 1)
1852 {
1853 continue;
1854 }
1855 // iterate over start index
1856 for (unsigned start = 0; start < it->second.size() - 1; start++)
1857 {
1858 for (unsigned r = 0; r < 2; r++)
1859 {
1860 bool isRev = r == 1;
1861 checkFlatForm(it->second, start, isRev);
1862 if (d_conflict)
1863 {
1864 return;
1865 }
1866 }
1867 }
1868 }
1869 }
1870
1871 void TheoryStrings::checkFlatForm(std::vector<Node>& eqc,
1872 unsigned start,
1873 bool isRev)
1874 {
1875 unsigned count = 0;
1876 std::vector<Node> inelig;
1877 for (unsigned i = 0; i <= start; i++)
1878 {
1879 inelig.push_back(eqc[start]);
1880 }
1881 Node a = eqc[start];
1882 Node b;
1883 do
1884 {
1885 std::vector<Node> exp;
1886 Node conc;
1887 int inf_type = -1;
1888 unsigned eqc_size = eqc.size();
1889 unsigned asize = d_flat_form[a].size();
1890 if (count == asize)
1891 {
1892 for (unsigned i = start + 1; i < eqc_size; i++)
1893 {
1894 b = eqc[i];
1895 if (std::find(inelig.begin(), inelig.end(), b) == inelig.end())
1896 {
1897 unsigned bsize = d_flat_form[b].size();
1898 if (count < bsize)
1899 {
1900 // endpoint
1901 std::vector<Node> conc_c;
1902 for (unsigned j = count; j < bsize; j++)
1903 {
1904 conc_c.push_back(
1905 b[d_flat_form_index[b][j]].eqNode(d_emptyString));
1906 }
1907 Assert(!conc_c.empty());
1908 conc = mkAnd(conc_c);
1909 inf_type = 2;
1910 Assert(count > 0);
1911 // swap, will enforce is empty past current
1912 a = eqc[i];
1913 b = eqc[start];
1914 count--;
1915 break;
1916 }
1917 inelig.push_back(eqc[i]);
1918 }
1919 }
1920 }
1921 else
1922 {
1923 Node curr = d_flat_form[a][count];
1924 Node curr_c = getConstantEqc(curr);
1925 Node ac = a[d_flat_form_index[a][count]];
1926 std::vector<Node> lexp;
1927 Node lcurr = getLength(ac, lexp);
1928 for (unsigned i = 1; i < eqc_size; i++)
1929 {
1930 b = eqc[i];
1931 if (std::find(inelig.begin(), inelig.end(), b) == inelig.end())
1932 {
1933 if (count == d_flat_form[b].size())
1934 {
1935 inelig.push_back(b);
1936 // endpoint
1937 std::vector<Node> conc_c;
1938 for (unsigned j = count; j < asize; j++)
1939 {
1940 conc_c.push_back(
1941 a[d_flat_form_index[a][j]].eqNode(d_emptyString));
1942 }
1943 Assert(!conc_c.empty());
1944 conc = mkAnd(conc_c);
1945 inf_type = 2;
1946 Assert(count > 0);
1947 count--;
1948 break;
1949 }
1950 else
1951 {
1952 Node cc = d_flat_form[b][count];
1953 if (cc != curr)
1954 {
1955 Node bc = b[d_flat_form_index[b][count]];
1956 inelig.push_back(b);
1957 Assert(!areEqual(curr, cc));
1958 Node cc_c = getConstantEqc(cc);
1959 if (!curr_c.isNull() && !cc_c.isNull())
1960 {
1961 // check for constant conflict
1962 int index;
1963 Node s = TheoryStringsRewriter::splitConstant(
1964 cc_c, curr_c, index, isRev);
1965 if (s.isNull())
1966 {
1967 addToExplanation(ac, d_eqc_to_const_base[curr], exp);
1968 addToExplanation(d_eqc_to_const_exp[curr], exp);
1969 addToExplanation(bc, d_eqc_to_const_base[cc], exp);
1970 addToExplanation(d_eqc_to_const_exp[cc], exp);
1971 conc = d_false;
1972 inf_type = 0;
1973 break;
1974 }
1975 }
1976 else if ((d_flat_form[a].size() - 1) == count
1977 && (d_flat_form[b].size() - 1) == count)
1978 {
1979 conc = ac.eqNode(bc);
1980 inf_type = 3;
1981 break;
1982 }
1983 else
1984 {
1985 // if lengths are the same, apply LengthEq
1986 std::vector<Node> lexp2;
1987 Node lcc = getLength(bc, lexp2);
1988 if (areEqual(lcurr, lcc))
1989 {
1990 Trace("strings-ff-debug") << "Infer " << ac << " == " << bc
1991 << " since " << lcurr
1992 << " == " << lcc << std::endl;
1993 // exp_n.push_back( getLength( curr, true ).eqNode(
1994 // getLength( cc, true ) ) );
1995 Trace("strings-ff-debug") << "Explanation for " << lcurr
1996 << " is ";
1997 for (unsigned j = 0; j < lexp.size(); j++)
1998 {
1999 Trace("strings-ff-debug") << lexp[j] << std::endl;
2000 }
2001 Trace("strings-ff-debug") << "Explanation for " << lcc
2002 << " is ";
2003 for (unsigned j = 0; j < lexp2.size(); j++)
2004 {
2005 Trace("strings-ff-debug") << lexp2[j] << std::endl;
2006 }
2007 exp.insert(exp.end(), lexp.begin(), lexp.end());
2008 exp.insert(exp.end(), lexp2.begin(), lexp2.end());
2009 addToExplanation(lcurr, lcc, exp);
2010 conc = ac.eqNode(bc);
2011 inf_type = 1;
2012 break;
2013 }
2014 }
2015 }
2016 }
2017 }
2018 }
2019 }
2020 if (!conc.isNull())
2021 {
2022 Trace("strings-ff-debug")
2023 << "Found inference : " << conc << " based on equality " << a
2024 << " == " << b << ", " << isRev << " " << inf_type << std::endl;
2025 addToExplanation(a, b, exp);
2026 // explain why prefixes up to now were the same
2027 for (unsigned j = 0; j < count; j++)
2028 {
2029 Trace("strings-ff-debug") << "Add at " << d_flat_form_index[a][j] << " "
2030 << d_flat_form_index[b][j] << std::endl;
2031 addToExplanation(
2032 a[d_flat_form_index[a][j]], b[d_flat_form_index[b][j]], exp);
2033 }
2034 // explain why other components up to now are empty
2035 for (unsigned t = 0; t < 2; t++)
2036 {
2037 Node c = t == 0 ? a : b;
2038 int jj;
2039 if (inf_type == 3 || (t == 1 && inf_type == 2))
2040 {
2041 // explain all the empty components for F_EndpointEq, all for
2042 // the short end for F_EndpointEmp
2043 jj = isRev ? -1 : c.getNumChildren();
2044 }
2045 else
2046 {
2047 jj = t == 0 ? d_flat_form_index[a][count]
2048 : d_flat_form_index[b][count];
2049 }
2050 int startj = isRev ? jj + 1 : 0;
2051 int endj = isRev ? c.getNumChildren() : jj;
2052 for (int j = startj; j < endj; j++)
2053 {
2054 if (areEqual(c[j], d_emptyString))
2055 {
2056 addToExplanation(c[j], d_emptyString, exp);
2057 }
2058 }
2059 }
2060 // notice that F_EndpointEmp is not typically applied, since
2061 // strict prefix equality ( a.b = a ) where a,b non-empty
2062 // is conflicting by arithmetic len(a.b)=len(a)+len(b)!=len(a)
2063 // when len(b)!=0.
2064 sendInference(
2065 exp,
2066 conc,
2067 inf_type == 0
2068 ? "F_Const"
2069 : (inf_type == 1 ? "F_Unify" : (inf_type == 2 ? "F_EndpointEmp"
2070 : "F_EndpointEq")));
2071 if (d_conflict)
2072 {
2073 return;
2074 }
2075 break;
2076 }
2077 count++;
2078 } while (inelig.size() < eqc.size());
2079
2080 for (const Node& n : eqc)
2081 {
2082 std::reverse(d_flat_form[n].begin(), d_flat_form[n].end());
2083 std::reverse(d_flat_form_index[n].begin(), d_flat_form_index[n].end());
2084 }
2085 }
2086
2087 Node TheoryStrings::checkCycles( Node eqc, std::vector< Node >& curr, std::vector< Node >& exp ){
2088 if( std::find( curr.begin(), curr.end(), eqc )!=curr.end() ){
2089 // a loop
2090 return eqc;
2091 }else if( std::find( d_strings_eqc.begin(), d_strings_eqc.end(), eqc )==d_strings_eqc.end() ){
2092 curr.push_back( eqc );
2093 //look at all terms in this equivalence class
2094 eq::EqClassIterator eqc_i = eq::EqClassIterator( eqc, &d_equalityEngine );
2095 while( !eqc_i.isFinished() ) {
2096 Node n = (*eqc_i);
2097 if( d_congruent.find( n )==d_congruent.end() ){
2098 if( n.getKind() == kind::STRING_CONCAT ){
2099 Trace("strings-cycle") << eqc << " check term : " << n << " in " << eqc << std::endl;
2100 if( eqc!=d_emptyString_r ){
2101 d_eqc[eqc].push_back( n );
2102 }
2103 for( unsigned i=0; i<n.getNumChildren(); i++ ){
2104 Node nr = getRepresentative( n[i] );
2105 if( eqc==d_emptyString_r ){
2106 //for empty eqc, ensure all components are empty
2107 if( nr!=d_emptyString_r ){
2108 std::vector< Node > exp;
2109 exp.push_back( n.eqNode( d_emptyString ) );
2110 sendInference( exp, n[i].eqNode( d_emptyString ), "I_CYCLE_E" );
2111 return Node::null();
2112 }
2113 }else{
2114 if( nr!=d_emptyString_r ){
2115 d_flat_form[n].push_back( nr );
2116 d_flat_form_index[n].push_back( i );
2117 }
2118 //for non-empty eqc, recurse and see if we find a loop
2119 Node ncy = checkCycles( nr, curr, exp );
2120 if( !ncy.isNull() ){
2121 Trace("strings-cycle") << eqc << " cycle: " << ncy << " at " << n << "[" << i << "] : " << n[i] << std::endl;
2122 addToExplanation( n, eqc, exp );
2123 addToExplanation( nr, n[i], exp );
2124 if( ncy==eqc ){
2125 //can infer all other components must be empty
2126 for( unsigned j=0; j<n.getNumChildren(); j++ ){
2127 //take first non-empty
2128 if( j!=i && !areEqual( n[j], d_emptyString ) ){
2129 sendInference( exp, n[j].eqNode( d_emptyString ), "I_CYCLE" );
2130 return Node::null();
2131 }
2132 }
2133 Trace("strings-error") << "Looping term should be congruent : " << n << " " << eqc << " " << ncy << std::endl;
2134 //should find a non-empty component, otherwise would have been singular congruent (I_Norm_S)
2135 Assert( false );
2136 }else{
2137 return ncy;
2138 }
2139 }else{
2140 if( hasProcessed() ){
2141 return Node::null();
2142 }
2143 }
2144 }
2145 }
2146 }
2147 }
2148 ++eqc_i;
2149 }
2150 curr.pop_back();
2151 //now we can add it to the list of equivalence classes
2152 d_strings_eqc.push_back( eqc );
2153 }else{
2154 //already processed
2155 }
2156 return Node::null();
2157 }
2158
2159 void TheoryStrings::checkNormalFormsEq()
2160 {
2161 if( !options::stringEagerLen() ){
2162 for( unsigned i=0; i<d_strings_eqc.size(); i++ ) {
2163 Node eqc = d_strings_eqc[i];
2164 eq::EqClassIterator eqc_i = eq::EqClassIterator( eqc, &d_equalityEngine );
2165 while( !eqc_i.isFinished() ) {
2166 Node n = (*eqc_i);
2167 if( d_congruent.find( n )==d_congruent.end() ){
2168 registerTerm( n, 2 );
2169 }
2170 ++eqc_i;
2171 }
2172 }
2173 }
2174
2175 if (hasProcessed())
2176 {
2177 return;
2178 }
2179 // calculate normal forms for each equivalence class, possibly adding
2180 // splitting lemmas
2181 d_normal_forms.clear();
2182 d_normal_forms_exp.clear();
2183 std::map<Node, Node> nf_to_eqc;
2184 std::map<Node, Node> eqc_to_nf;
2185 std::map<Node, Node> eqc_to_exp;
2186 for (const Node& eqc : d_strings_eqc)
2187 {
2188 Trace("strings-process-debug") << "- Verify normal forms are the same for "
2189 << eqc << std::endl;
2190 normalizeEquivalenceClass(eqc);
2191 Trace("strings-debug") << "Finished normalizing eqc..." << std::endl;
2192 if (hasProcessed())
2193 {
2194 return;
2195 }
2196 Node nf_term = mkConcat(d_normal_forms[eqc]);
2197 std::map<Node, Node>::iterator itn = nf_to_eqc.find(nf_term);
2198 if (itn != nf_to_eqc.end())
2199 {
2200 // two equivalence classes have same normal form, merge
2201 std::vector<Node> nf_exp;
2202 nf_exp.push_back(mkAnd(d_normal_forms_exp[eqc]));
2203 nf_exp.push_back(eqc_to_exp[itn->second]);
2204 Node eq =
2205 d_normal_forms_base[eqc].eqNode(d_normal_forms_base[itn->second]);
2206 sendInference(nf_exp, eq, "Normal_Form");
2207 if( hasProcessed() ){
2208 return;
2209 }
2210 }
2211 else
2212 {
2213 nf_to_eqc[nf_term] = eqc;
2214 eqc_to_nf[eqc] = nf_term;
2215 eqc_to_exp[eqc] = mkAnd(d_normal_forms_exp[eqc]);
2216 }
2217 Trace("strings-process-debug")
2218 << "Done verifying normal forms are the same for " << eqc << std::endl;
2219 }
2220 if (Trace.isOn("strings-nf"))
2221 {
2222 Trace("strings-nf") << "**** Normal forms are : " << std::endl;
2223 for (std::map<Node, Node>::iterator it = eqc_to_exp.begin();
2224 it != eqc_to_exp.end();
2225 ++it)
2226 {
2227 Trace("strings-nf") << " N[" << it->first << "] (base "
2228 << d_normal_forms_base[it->first]
2229 << ") = " << eqc_to_nf[it->first] << std::endl;
2230 Trace("strings-nf") << " exp: " << it->second << std::endl;
2231 }
2232 Trace("strings-nf") << std::endl;
2233 }
2234 }
2235
2236 void TheoryStrings::checkCodes()
2237 {
2238 // ensure that lemmas regarding str.code been added for each constant string
2239 // of length one
2240 if (d_has_str_code)
2241 {
2242 NodeManager* nm = NodeManager::currentNM();
2243 // str.code applied to the code term for each equivalence class that has a
2244 // code term but is not a constant
2245 std::vector<Node> nconst_codes;
2246 // str.code applied to the proxy variables for each equivalence classes that
2247 // are constants of size one
2248 std::vector<Node> const_codes;
2249 for (const Node& eqc : d_strings_eqc)
2250 {
2251 if (d_normal_forms[eqc].size() == 1 && d_normal_forms[eqc][0].isConst())
2252 {
2253 Node c = d_normal_forms[eqc][0];
2254 Trace("strings-code-debug") << "Get proxy variable for " << c
2255 << std::endl;
2256 Node cc = nm->mkNode(kind::STRING_CODE, c);
2257 cc = Rewriter::rewrite(cc);
2258 Assert(cc.isConst());
2259 NodeNodeMap::const_iterator it = d_proxy_var.find(c);
2260 AlwaysAssert(it != d_proxy_var.end());
2261 Node vc = nm->mkNode(kind::STRING_CODE, (*it).second);
2262 if (!areEqual(cc, vc))
2263 {
2264 sendInference(d_empty_vec, cc.eqNode(vc), "Code_Proxy");
2265 }
2266 const_codes.push_back(vc);
2267 }
2268 else
2269 {
2270 EqcInfo* ei = getOrMakeEqcInfo(eqc, false);
2271 if (ei && !ei->d_code_term.get().isNull())
2272 {
2273 Node vc = nm->mkNode(kind::STRING_CODE, ei->d_code_term.get());
2274 nconst_codes.push_back(vc);
2275 }
2276 }
2277 }
2278 if (hasProcessed())
2279 {
2280 return;
2281 }
2282 // now, ensure that str.code is injective
2283 std::vector<Node> cmps;
2284 cmps.insert(cmps.end(), const_codes.rbegin(), const_codes.rend());
2285 cmps.insert(cmps.end(), nconst_codes.rbegin(), nconst_codes.rend());
2286 for (unsigned i = 0, num_ncc = nconst_codes.size(); i < num_ncc; i++)
2287 {
2288 Node c1 = nconst_codes[i];
2289 cmps.pop_back();
2290 for (const Node& c2 : cmps)
2291 {
2292 Trace("strings-code-debug")
2293 << "Compare codes : " << c1 << " " << c2 << std::endl;
2294 if (!areDisequal(c1, c2) && !areEqual(c1, d_neg_one))
2295 {
2296 Node eq_no = c1.eqNode(d_neg_one);
2297 Node deq = c1.eqNode(c2).negate();
2298 Node eqn = c1[0].eqNode(c2[0]);
2299 // str.code(x)==-1 V str.code(x)!=str.code(y) V x==y
2300 Node inj_lem = nm->mkNode(kind::OR, eq_no, deq, eqn);
2301 sendInference(d_empty_vec, inj_lem, "Code_Inj");
2302 }
2303 }
2304 }
2305 }
2306 }
2307
2308 //compute d_normal_forms_(base,exp,exp_depend)[eqc]
2309 void TheoryStrings::normalizeEquivalenceClass( Node eqc ) {
2310 Trace("strings-process-debug") << "Process equivalence class " << eqc << std::endl;
2311 if( areEqual( eqc, d_emptyString ) ) {
2312 #ifdef CVC4_ASSERTIONS
2313 for( unsigned j=0; j<d_eqc[eqc].size(); j++ ){
2314 Node n = d_eqc[eqc][j];
2315 for( unsigned i=0; i<n.getNumChildren(); i++ ){
2316 Assert( areEqual( n[i], d_emptyString ) );
2317 }
2318 }
2319 #endif
2320 //do nothing
2321 Trace("strings-process-debug") << "Return process equivalence class " << eqc << " : empty." << std::endl;
2322 d_normal_forms_base[eqc] = d_emptyString;
2323 d_normal_forms[eqc].clear();
2324 d_normal_forms_exp[eqc].clear();
2325 } else {
2326 Assert( d_normal_forms.find(eqc)==d_normal_forms.end() );
2327 //phi => t = s1 * ... * sn
2328 // normal form for each non-variable term in this eqc (s1...sn)
2329 std::vector< std::vector< Node > > normal_forms;
2330 // explanation for each normal form (phi)
2331 std::vector< std::vector< Node > > normal_forms_exp;
2332 // dependency information
2333 std::vector< std::map< Node, std::map< bool, int > > > normal_forms_exp_depend;
2334 // record terms for each normal form (t)
2335 std::vector< Node > normal_form_src;
2336 // get normal forms
2337 getNormalForms(eqc, normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend);
2338 if( hasProcessed() ){
2339 return;
2340 }
2341 // process the normal forms
2342 processNEqc( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend );
2343 if( hasProcessed() ){
2344 return;
2345 }
2346 //debugPrintNormalForms( "strings-solve", eqc, normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend );
2347
2348 //construct the normal form
2349 Assert( !normal_forms.empty() );
2350
2351 int nf_index = 0;
2352 std::vector< Node >::iterator itn = std::find( normal_form_src.begin(), normal_form_src.end(), eqc );
2353 if( itn!=normal_form_src.end() ){
2354 nf_index = itn - normal_form_src.begin();
2355 Trace("strings-solve-debug2") << "take normal form " << nf_index << std::endl;
2356 Assert( normal_form_src[nf_index]==eqc );
2357 }else{
2358 //just take the first normal form
2359 Trace("strings-solve-debug2") << "take the first normal form" << std::endl;
2360 }
2361 d_normal_forms[eqc].insert( d_normal_forms[eqc].end(), normal_forms[nf_index].begin(), normal_forms[nf_index].end() );
2362 d_normal_forms_exp[eqc].insert( d_normal_forms_exp[eqc].end(), normal_forms_exp[nf_index].begin(), normal_forms_exp[nf_index].end() );
2363 Trace("strings-solve-debug2") << "take normal form ... done" << std::endl;
2364 d_normal_forms_base[eqc] = normal_form_src[nf_index];
2365 //track dependencies
2366 for( unsigned i=0; i<normal_forms_exp[nf_index].size(); i++ ){
2367 Node exp = normal_forms_exp[nf_index][i];
2368 for( unsigned r=0; r<2; r++ ){
2369 d_normal_forms_exp_depend[eqc][exp][r==0] = normal_forms_exp_depend[nf_index][exp][r==0];
2370 }
2371 }
2372 Trace("strings-process-debug") << "Return process equivalence class " << eqc << " : returned, size = " << d_normal_forms[eqc].size() << std::endl;
2373 }
2374 }
2375
2376 void trackNfExpDependency( std::vector< Node >& nf_exp_n, std::map< Node, std::map< bool, int > >& nf_exp_depend_n, Node exp, int new_val, int new_rev_val ){
2377 if( std::find( nf_exp_n.begin(), nf_exp_n.end(), exp )==nf_exp_n.end() ){
2378 nf_exp_n.push_back( exp );
2379 }
2380 for( unsigned k=0; k<2; k++ ){
2381 int val = k==0 ? new_val : new_rev_val;
2382 std::map< bool, int >::iterator itned = nf_exp_depend_n[exp].find( k==1 );
2383 if( itned==nf_exp_depend_n[exp].end() ){
2384 Trace("strings-process-debug") << "Deps : set dependency on " << exp << " to " << val << " isRev=" << (k==0) << std::endl;
2385 nf_exp_depend_n[exp][k==1] = val;
2386 }else{
2387 Trace("strings-process-debug") << "Deps : Multiple dependencies on " << exp << " : " << itned->second << " " << val << " isRev=" << (k==0) << std::endl;
2388 //if we already have a dependency (in the case of non-linear string equalities), it is min/max
2389 bool cmp = val > itned->second;
2390 if( cmp==(k==1) ){
2391 nf_exp_depend_n[exp][k==1] = val;
2392 }
2393 }
2394 }
2395 }
2396
2397 void TheoryStrings::getNormalForms( Node &eqc, std::vector< std::vector< Node > > &normal_forms, std::vector< Node > &normal_form_src,
2398 std::vector< std::vector< Node > > &normal_forms_exp, std::vector< std::map< Node, std::map< bool, int > > >& normal_forms_exp_depend ) {
2399 //constant for equivalence class
2400 Node eqc_non_c = eqc;
2401 Trace("strings-process-debug") << "Get normal forms " << eqc << std::endl;
2402 eq::EqClassIterator eqc_i = eq::EqClassIterator( eqc, &d_equalityEngine );
2403 while( !eqc_i.isFinished() ){
2404 Node n = (*eqc_i);
2405 if( d_congruent.find( n )==d_congruent.end() ){
2406 if( n.getKind() == kind::CONST_STRING || n.getKind() == kind::STRING_CONCAT ){
2407 Trace("strings-process-debug") << "Get Normal Form : Process term " << n << " in eqc " << eqc << std::endl;
2408 std::vector< Node > nf_n;
2409 std::vector< Node > nf_exp_n;
2410 std::map< Node, std::map< bool, int > > nf_exp_depend_n;
2411 if( n.getKind()==kind::CONST_STRING ){
2412 if( n!=d_emptyString ) {
2413 nf_n.push_back( n );
2414 }
2415 }else if( n.getKind()==kind::STRING_CONCAT ){
2416 for( unsigned i=0; i<n.getNumChildren(); i++ ) {
2417 Node nr = d_equalityEngine.getRepresentative( n[i] );
2418 Trace("strings-process-debug") << "Normalizing subterm " << n[i] << " = " << nr << std::endl;
2419 Assert( d_normal_forms.find( nr )!=d_normal_forms.end() );
2420 unsigned orig_size = nf_n.size();
2421 unsigned add_size = d_normal_forms[nr].size();
2422 //if not the empty string, add to current normal form
2423 if( !d_normal_forms[nr].empty() ){
2424 for( unsigned r=0; r<d_normal_forms[nr].size(); r++ ) {
2425 if( Trace.isOn("strings-error") ) {
2426 if( d_normal_forms[nr][r].getKind()==kind::STRING_CONCAT ){
2427 Trace("strings-error") << "Strings::Error: From eqc = " << eqc << ", " << n << " index " << i << ", bad normal form : ";
2428 for( unsigned rr=0; rr<d_normal_forms[nr].size(); rr++ ) {
2429 Trace("strings-error") << d_normal_forms[nr][rr] << " ";
2430 }
2431 Trace("strings-error") << std::endl;
2432 }
2433 }
2434 Assert( d_normal_forms[nr][r].getKind()!=kind::STRING_CONCAT );
2435 }
2436 nf_n.insert( nf_n.end(), d_normal_forms[nr].begin(), d_normal_forms[nr].end() );
2437 }
2438
2439 for( unsigned j=0; j<d_normal_forms_exp[nr].size(); j++ ){
2440 Node exp = d_normal_forms_exp[nr][j];
2441 //track depends
2442 trackNfExpDependency( nf_exp_n, nf_exp_depend_n, exp,
2443 orig_size + d_normal_forms_exp_depend[nr][exp][false],
2444 orig_size + ( add_size - d_normal_forms_exp_depend[nr][exp][true] ) );
2445 }
2446 if( d_normal_forms_base[nr]!=n[i] ){
2447 Assert( d_normal_forms_base.find( nr )!=d_normal_forms_base.end() );
2448 Node eq = n[i].eqNode( d_normal_forms_base[nr] );
2449 //track depends : entire current segment is dependent upon base equality
2450 trackNfExpDependency( nf_exp_n, nf_exp_depend_n, eq, orig_size, orig_size + add_size );
2451 }
2452 }
2453 //convert forward indices to reverse indices
2454 int total_size = nf_n.size();
2455 for( std::map< Node, std::map< bool, int > >::iterator it = nf_exp_depend_n.begin(); it != nf_exp_depend_n.end(); ++it ){
2456 it->second[true] = total_size - it->second[true];
2457 Assert( it->second[true]>=0 );
2458 }
2459 }
2460 //if not equal to self
2461 if( nf_n.size()>1 || ( nf_n.size()==1 && nf_n[0].getKind()==kind::CONST_STRING ) ){
2462 if( nf_n.size()>1 ) {
2463 for( unsigned i=0; i<nf_n.size(); i++ ){
2464 if( Trace.isOn("strings-error") ){
2465 Trace("strings-error") << "Cycle for normal form ";
2466 printConcat(nf_n,"strings-error");
2467 Trace("strings-error") << "..." << nf_n[i] << std::endl;
2468 }
2469 Assert( !areEqual( nf_n[i], n ) );
2470 }
2471 }
2472 normal_forms.push_back(nf_n);
2473 normal_form_src.push_back(n);
2474 normal_forms_exp.push_back(nf_exp_n);
2475 normal_forms_exp_depend.push_back(nf_exp_depend_n);
2476 }else{
2477 //this was redundant: combination of self + empty string(s)
2478 Node nn = nf_n.size()==0 ? d_emptyString : nf_n[0];
2479 Assert( areEqual( nn, eqc ) );
2480 }
2481 }else{
2482 eqc_non_c = n;
2483 }
2484 }
2485 ++eqc_i;
2486 }
2487
2488 if( normal_forms.empty() ) {
2489 Trace("strings-solve-debug2") << "construct the normal form" << std::endl;
2490 //do not choose a concat here use "eqc_non_c" (in this case they have non-trivial explanation why they normalize to self)
2491 std::vector< Node > eqc_non_c_nf;
2492 getConcatVec( eqc_non_c, eqc_non_c_nf );
2493 normal_forms.push_back( eqc_non_c_nf );
2494 normal_form_src.push_back( eqc_non_c );
2495 normal_forms_exp.push_back( std::vector< Node >() );
2496 normal_forms_exp_depend.push_back( std::map< Node, std::map< bool, int > >() );
2497 }else{
2498 if(Trace.isOn("strings-solve")) {
2499 Trace("strings-solve") << "--- Normal forms for equivalance class " << eqc << " : " << std::endl;
2500 for( unsigned i=0; i<normal_forms.size(); i++ ) {
2501 Trace("strings-solve") << "#" << i << " (from " << normal_form_src[i] << ") : ";
2502 for( unsigned j=0; j<normal_forms[i].size(); j++ ) {
2503 if(j>0) {
2504 Trace("strings-solve") << ", ";
2505 }
2506 Trace("strings-solve") << normal_forms[i][j];
2507 }
2508 Trace("strings-solve") << std::endl;
2509 Trace("strings-solve") << " Explanation is : ";
2510 if(normal_forms_exp[i].size() == 0) {
2511 Trace("strings-solve") << "NONE";
2512 } else {
2513 for( unsigned j=0; j<normal_forms_exp[i].size(); j++ ) {
2514 if(j>0) {
2515 Trace("strings-solve") << " AND ";
2516 }
2517 Trace("strings-solve") << normal_forms_exp[i][j];
2518 }
2519 Trace("strings-solve") << std::endl;
2520 Trace("strings-solve") << "WITH DEPENDENCIES : " << std::endl;
2521 for( unsigned j=0; j<normal_forms_exp[i].size(); j++ ) {
2522 Trace("strings-solve") << " " << normal_forms_exp[i][j] << " -> ";
2523 Trace("strings-solve") << normal_forms_exp_depend[i][normal_forms_exp[i][j]][false] << ",";
2524 Trace("strings-solve") << normal_forms_exp_depend[i][normal_forms_exp[i][j]][true] << std::endl;
2525 }
2526 }
2527 Trace("strings-solve") << std::endl;
2528
2529 }
2530 } else {
2531 Trace("strings-solve") << "--- Single normal form for equivalence class " << eqc << std::endl;
2532 }
2533
2534 //if equivalence class is constant, approximate as containment, infer conflicts
2535 Node c = getConstantEqc( eqc );
2536 if( !c.isNull() ){
2537 Trace("strings-solve") << "Eqc is constant " << c << std::endl;
2538 for( unsigned i=0; i<normal_forms.size(); i++ ) {
2539 int firstc, lastc;
2540 if( !TheoryStringsRewriter::canConstantContainList( c, normal_forms[i], firstc, lastc ) ){
2541 Node n = normal_form_src[i];
2542 //conflict
2543 Trace("strings-solve") << "Normal form for " << n << " cannot be contained in constant " << c << std::endl;
2544 //conflict, explanation is n = base ^ base = c ^ relevant porition of ( n = N[n] )
2545 std::vector< Node > exp;
2546 Assert( d_eqc_to_const_base.find( eqc )!=d_eqc_to_const_base.end() );
2547 addToExplanation( n, d_eqc_to_const_base[eqc], exp );
2548 Assert( d_eqc_to_const_exp.find( eqc )!=d_eqc_to_const_exp.end() );
2549 if( !d_eqc_to_const_exp[eqc].isNull() ){
2550 exp.push_back( d_eqc_to_const_exp[eqc] );
2551 }
2552 //TODO: this can be minimized based on firstc/lastc, normal_forms_exp_depend
2553 exp.insert( exp.end(), normal_forms_exp[i].begin(), normal_forms_exp[i].end() );
2554 Node conc = d_false;
2555 sendInference( exp, conc, "N_NCTN" );
2556 }
2557 }
2558 }
2559 }
2560 }
2561
2562 void TheoryStrings::getExplanationVectorForPrefix( std::vector< std::vector< Node > > &normal_forms_exp, std::vector< std::map< Node, std::map< bool, int > > >& normal_forms_exp_depend,
2563 unsigned i, int index, bool isRev, std::vector< Node >& curr_exp ) {
2564 if( index==-1 || !options::stringMinPrefixExplain() ){
2565 curr_exp.insert(curr_exp.end(), normal_forms_exp[i].begin(), normal_forms_exp[i].end() );
2566 }else{
2567 for( unsigned k=0; k<normal_forms_exp[i].size(); k++ ){
2568 Node exp = normal_forms_exp[i][k];
2569 int dep = normal_forms_exp_depend[i][exp][isRev];
2570 if( dep<=index ){
2571 curr_exp.push_back( exp );
2572 Trace("strings-explain-prefix-debug") << " include : " << exp << std::endl;
2573 }else{
2574 Trace("strings-explain-prefix-debug") << " exclude : " << exp << std::endl;
2575 }
2576 }
2577 }
2578 }
2579
2580 void TheoryStrings::getExplanationVectorForPrefixEq( std::vector< std::vector< Node > > &normal_forms, std::vector< Node > &normal_form_src,
2581 std::vector< std::vector< Node > > &normal_forms_exp, std::vector< std::map< Node, std::map< bool, int > > >& normal_forms_exp_depend,
2582 unsigned i, unsigned j, int index_i, int index_j, bool isRev, std::vector< Node >& curr_exp ) {
2583 Trace("strings-explain-prefix") << "Get explanation for prefix " << index_i << ", " << index_j << " of normal forms " << i << " and " << j << ", reverse = " << isRev << std::endl;
2584 for( unsigned r=0; r<2; r++ ){
2585 getExplanationVectorForPrefix( normal_forms_exp, normal_forms_exp_depend, r==0 ? i : j, r==0 ? index_i : index_j, isRev, curr_exp );
2586 }
2587 Trace("strings-explain-prefix") << "Included " << curr_exp.size() << " / " << ( normal_forms_exp[i].size() + normal_forms_exp[j].size() ) << std::endl;
2588 addToExplanation( normal_form_src[i], normal_form_src[j], curr_exp );
2589 }
2590
2591
2592 void TheoryStrings::processNEqc( std::vector< std::vector< Node > > &normal_forms, std::vector< Node > &normal_form_src,
2593 std::vector< std::vector< Node > > &normal_forms_exp, std::vector< std::map< Node, std::map< bool, int > > >& normal_forms_exp_depend ){
2594 //the possible inferences
2595 std::vector< InferInfo > pinfer;
2596 // loop over all pairs
2597 for(unsigned i=0; i<normal_forms.size()-1; i++) {
2598 //unify each normalform[j] with normal_forms[i]
2599 for(unsigned j=i+1; j<normal_forms.size(); j++ ) {
2600 //ensure that normal_forms[i] and normal_forms[j] are the same modulo equality, add to pinfer if not
2601 Trace("strings-solve") << "Strings: Process normal form #" << i << " against #" << j << "..." << std::endl;
2602 if( isNormalFormPair( normal_form_src[i], normal_form_src[j] ) ) {
2603 Trace("strings-solve") << "Strings: Already cached." << std::endl;
2604 }else{
2605 //process the reverse direction first (check for easy conflicts and inferences)
2606 unsigned rindex = 0;
2607 processReverseNEq( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend, i, j, rindex, 0, pinfer );
2608 if( hasProcessed() ){
2609 return;
2610 }else if( !pinfer.empty() && pinfer.back().d_id==1 ){
2611 break;
2612 }
2613 //AJR: for less aggressive endpoint inference
2614 //rindex = 0;
2615
2616 unsigned index = 0;
2617 processSimpleNEq( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend, i, j, index, false, rindex, pinfer );
2618 if( hasProcessed() ){
2619 return;
2620 }else if( !pinfer.empty() && pinfer.back().d_id==1 ){
2621 break;
2622 }
2623 }
2624 }
2625 }
2626 if( !pinfer.empty() ){
2627 //now, determine which of the possible inferences we want to add
2628 unsigned use_index = 0;
2629 bool set_use_index = false;
2630 Trace("strings-solve") << "Possible inferences (" << pinfer.size() << ") : " << std::endl;
2631 unsigned min_id = 9;
2632 unsigned max_index = 0;
2633 for (unsigned i = 0, size = pinfer.size(); i < size; i++)
2634 {
2635 Trace("strings-solve") << "From " << pinfer[i].d_i << " / " << pinfer[i].d_j << " (rev=" << pinfer[i].d_rev << ") : ";
2636 Trace("strings-solve")
2637 << pinfer[i].d_conc << " by " << pinfer[i].d_id << std::endl;
2638 if (!set_use_index || pinfer[i].d_id < min_id
2639 || (pinfer[i].d_id == min_id && pinfer[i].d_index > max_index))
2640 {
2641 min_id = pinfer[i].d_id;
2642 max_index = pinfer[i].d_index;
2643 use_index = i;
2644 set_use_index = true;
2645 }
2646 }
2647 //send the inference
2648 if( !pinfer[use_index].d_nf_pair[0].isNull() ){
2649 Assert( !pinfer[use_index].d_nf_pair[1].isNull() );
2650 addNormalFormPair( pinfer[use_index].d_nf_pair[0], pinfer[use_index].d_nf_pair[1] );
2651 }
2652 std::stringstream ssi;
2653 ssi << pinfer[use_index].d_id;
2654 sendInference(pinfer[use_index].d_ant,
2655 pinfer[use_index].d_antn,
2656 pinfer[use_index].d_conc,
2657 ssi.str().c_str(),
2658 pinfer[use_index].sendAsLemma());
2659 for( std::map< int, std::vector< Node > >::iterator it = pinfer[use_index].d_new_skolem.begin(); it != pinfer[use_index].d_new_skolem.end(); ++it ){
2660 for( unsigned i=0; i<it->second.size(); i++ ){
2661 if( it->first==0 ){
2662 sendLengthLemma( it->second[i] );
2663 }else if( it->first==1 ){
2664 registerNonEmptySkolem( it->second[i] );
2665 }
2666 }
2667 }
2668 }
2669 }
2670
2671 bool TheoryStrings::InferInfo::sendAsLemma() {
2672 return true;
2673 }
2674
2675 void TheoryStrings::processReverseNEq( std::vector< std::vector< Node > > &normal_forms, std::vector< Node > &normal_form_src,
2676 std::vector< std::vector< Node > > &normal_forms_exp, std::vector< std::map< Node, std::map< bool, int > > >& normal_forms_exp_depend,
2677 unsigned i, unsigned j, unsigned& index, unsigned rproc, std::vector< InferInfo >& pinfer ) {
2678 //reverse normal form of i, j
2679 std::reverse( normal_forms[i].begin(), normal_forms[i].end() );
2680 std::reverse( normal_forms[j].begin(), normal_forms[j].end() );
2681
2682 processSimpleNEq( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend, i, j, index, true, rproc, pinfer );
2683
2684 //reverse normal form of i, j
2685 std::reverse( normal_forms[i].begin(), normal_forms[i].end() );
2686 std::reverse( normal_forms[j].begin(), normal_forms[j].end() );
2687 }
2688
2689 //rproc is the # is the size of suffix that is identical
2690 void TheoryStrings::processSimpleNEq( std::vector< std::vector< Node > > &normal_forms, std::vector< Node > &normal_form_src,
2691 std::vector< std::vector< Node > > &normal_forms_exp, std::vector< std::map< Node, std::map< bool, int > > >& normal_forms_exp_depend,
2692 unsigned i, unsigned j, unsigned& index, bool isRev, unsigned rproc, std::vector< InferInfo >& pinfer ) {
2693 Assert( rproc<=normal_forms[i].size() && rproc<=normal_forms[j].size() );
2694 bool success;
2695 do {
2696 success = false;
2697 //if we are at the end
2698 if( index==(normal_forms[i].size()-rproc) || index==(normal_forms[j].size()-rproc) ){
2699 if( index==(normal_forms[i].size()-rproc) && index==(normal_forms[j].size()-rproc) ){
2700 //we're done
2701 }else{
2702 //the remainder must be empty
2703 unsigned k = index==(normal_forms[i].size()-rproc) ? j : i;
2704 unsigned index_k = index;
2705 //Node eq_exp = mkAnd( curr_exp );
2706 std::vector< Node > curr_exp;
2707 getExplanationVectorForPrefixEq( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend, i, j, -1, -1, isRev, curr_exp );
2708 while( !d_conflict && index_k<(normal_forms[k].size()-rproc) ){
2709 //can infer that this string must be empty
2710 Node eq = normal_forms[k][index_k].eqNode( d_emptyString );
2711 //Trace("strings-lemma") << "Strings: Infer " << eq << " from " << eq_exp << std::endl;
2712 Assert( !areEqual( d_emptyString, normal_forms[k][index_k] ) );
2713 sendInference( curr_exp, eq, "N_EndpointEmp" );
2714 index_k++;
2715 }
2716 }
2717 }else{
2718 Trace("strings-solve-debug") << "Process " << normal_forms[i][index] << " ... " << normal_forms[j][index] << std::endl;
2719 if( normal_forms[i][index]==normal_forms[j][index] ){
2720 Trace("strings-solve-debug") << "Simple Case 1 : strings are equal" << std::endl;
2721 index++;
2722 success = true;
2723 }else{
2724 Assert( !areEqual(normal_forms[i][index], normal_forms[j][index]) );
2725 std::vector< Node > temp_exp;
2726 Node length_term_i = getLength( normal_forms[i][index], temp_exp );
2727 Node length_term_j = getLength( normal_forms[j][index], temp_exp );
2728 //check length(normal_forms[i][index]) == length(normal_forms[j][index])
2729 if( areEqual( length_term_i, length_term_j ) ){
2730 Trace("strings-solve-debug") << "Simple Case 2 : string lengths are equal" << std::endl;
2731 Node eq = normal_forms[i][index].eqNode( normal_forms[j][index] );
2732 //eq = Rewriter::rewrite( eq );
2733 Node length_eq = length_term_i.eqNode( length_term_j );
2734 //temp_exp.insert(temp_exp.end(), curr_exp.begin(), curr_exp.end() );
2735 getExplanationVectorForPrefixEq( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend, i, j, index, index, isRev, temp_exp );
2736 temp_exp.push_back(length_eq);
2737 sendInference( temp_exp, eq, "N_Unify" );
2738 return;
2739 }else if( ( normal_forms[i][index].getKind()!=kind::CONST_STRING && index==normal_forms[i].size()-rproc-1 ) ||
2740 ( normal_forms[j][index].getKind()!=kind::CONST_STRING && index==normal_forms[j].size()-rproc-1 ) ){
2741 Trace("strings-solve-debug") << "Simple Case 3 : at endpoint" << std::endl;
2742 std::vector< Node > antec;
2743 //antec.insert(antec.end(), curr_exp.begin(), curr_exp.end() );
2744 getExplanationVectorForPrefixEq( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend, i, j, -1, -1, isRev, antec );
2745 std::vector< Node > eqn;
2746 for( unsigned r=0; r<2; r++ ) {
2747 int index_k = index;
2748 int k = r==0 ? i : j;
2749 std::vector< Node > eqnc;
2750 for( unsigned index_l=index_k; index_l<(normal_forms[k].size()-rproc); index_l++ ) {
2751 if(isRev) {
2752 eqnc.insert(eqnc.begin(), normal_forms[k][index_l] );
2753 } else {
2754 eqnc.push_back( normal_forms[k][index_l] );
2755 }
2756 }
2757 eqn.push_back( mkConcat( eqnc ) );
2758 }
2759 if( !areEqual( eqn[0], eqn[1] ) ){
2760 sendInference( antec, eqn[0].eqNode( eqn[1] ), "N_EndpointEq", true );
2761 return;
2762 }else{
2763 Assert( normal_forms[i].size()==normal_forms[j].size() );
2764 index = normal_forms[i].size()-rproc;
2765 }
2766 }else if( normal_forms[i][index].isConst() && normal_forms[j][index].isConst() ){
2767 Node const_str = normal_forms[i][index];
2768 Node other_str = normal_forms[j][index];
2769 Trace("strings-solve-debug") << "Simple Case 3 : Const Split : " << const_str << " vs " << other_str << " at index " << index << ", isRev = " << isRev << std::endl;
2770 unsigned len_short = const_str.getConst<String>().size() <= other_str.getConst<String>().size() ? const_str.getConst<String>().size() : other_str.getConst<String>().size();
2771 bool isSameFix = isRev ? const_str.getConst<String>().rstrncmp(other_str.getConst<String>(), len_short): const_str.getConst<String>().strncmp(other_str.getConst<String>(), len_short);
2772 if( isSameFix ) {
2773 //same prefix/suffix
2774 //k is the index of the string that is shorter
2775 int k = const_str.getConst<String>().size()<other_str.getConst<String>().size() ? i : j;
2776 int l = const_str.getConst<String>().size()<other_str.getConst<String>().size() ? j : i;
2777 //update the nf exp dependencies
2778 //notice this is not critical for soundness: not doing the below incrementing will only lead to overapproximating when antecedants are required in explanations
2779 for( std::map< Node, std::map< bool, int > >::iterator itnd = normal_forms_exp_depend[l].begin(); itnd != normal_forms_exp_depend[l].end(); ++itnd ){
2780 for( std::map< bool, int >::iterator itnd2 = itnd->second.begin(); itnd2 != itnd->second.end(); ++itnd2 ){
2781 //see if this can be incremented: it can if it is not relevant to the current index
2782 Assert( itnd2->second>=0 && itnd2->second<=(int)normal_forms[l].size() );
2783 bool increment = (itnd2->first==isRev) ? itnd2->second>(int)index : ( (int)normal_forms[l].size()-1-itnd2->second )<(int)index;
2784 if( increment ){
2785 normal_forms_exp_depend[l][itnd->first][itnd2->first] = itnd2->second + 1;
2786 }
2787 }
2788 }
2789 if( isRev ){
2790 int new_len = normal_forms[l][index].getConst<String>().size() - len_short;
2791 Node remainderStr = NodeManager::currentNM()->mkConst( normal_forms[l][index].getConst<String>().substr(0, new_len) );
2792 Trace("strings-solve-debug-test") << "Break normal form of " << normal_forms[l][index] << " into " << normal_forms[k][index] << ", " << remainderStr << std::endl;
2793 normal_forms[l].insert( normal_forms[l].begin()+index + 1, remainderStr );
2794 }else{
2795 Node remainderStr = NodeManager::currentNM()->mkConst(normal_forms[l][index].getConst<String>().substr(len_short));
2796 Trace("strings-solve-debug-test") << "Break normal form of " << normal_forms[l][index] << " into " << normal_forms[k][index] << ", " << remainderStr << std::endl;
2797 normal_forms[l].insert( normal_forms[l].begin()+index + 1, remainderStr );
2798 }
2799 normal_forms[l][index] = normal_forms[k][index];
2800 index++;
2801 success = true;
2802 }else{
2803 //conflict
2804 std::vector< Node > antec;
2805 getExplanationVectorForPrefixEq( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend, i, j, index, index, isRev, antec );
2806 sendInference( antec, d_false, "N_Const", true );
2807 return;
2808 }
2809 }else{
2810 //construct the candidate inference "info"
2811 InferInfo info;
2812 info.d_index = index;
2813 //for debugging
2814 info.d_i = i;
2815 info.d_j = j;
2816 info.d_rev = isRev;
2817 bool info_valid = false;
2818 Assert( index<normal_forms[i].size()-rproc && index<normal_forms[j].size()-rproc );
2819 std::vector< Node > lexp;
2820 Node length_term_i = getLength( normal_forms[i][index], lexp );
2821 Node length_term_j = getLength( normal_forms[j][index], lexp );
2822 //split on equality between string lengths (note that splitting on equality between strings is worse since it is harder to process)
2823 if( !areDisequal( length_term_i, length_term_j ) && !areEqual( length_term_i, length_term_j ) &&
2824 normal_forms[i][index].getKind()!=kind::CONST_STRING && normal_forms[j][index].getKind()!=kind::CONST_STRING ){ //AJR: remove the latter 2 conditions?
2825 Trace("strings-solve-debug") << "Non-simple Case 1 : string lengths neither equal nor disequal" << std::endl;
2826 //try to make the lengths equal via splitting on demand
2827 Node length_eq = NodeManager::currentNM()->mkNode( kind::EQUAL, length_term_i, length_term_j );
2828 length_eq = Rewriter::rewrite( length_eq );
2829 //set info
2830 info.d_conc = NodeManager::currentNM()->mkNode( kind::OR, length_eq, length_eq.negate() );
2831 info.d_pending_phase[ length_eq ] = true;
2832 info.d_id = INFER_LEN_SPLIT;
2833 info_valid = true;
2834 }else{
2835 Trace("strings-solve-debug") << "Non-simple Case 2 : must compare strings" << std::endl;
2836 int loop_in_i = -1;
2837 int loop_in_j = -1;
2838 if( detectLoop( normal_forms, i, j, index, loop_in_i, loop_in_j, rproc ) ){
2839 if( !isRev ){ //FIXME
2840 getExplanationVectorForPrefixEq( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend, i, j, -1, -1, isRev, info.d_ant );
2841 //set info
2842 if( processLoop( normal_forms, normal_form_src, i, j, loop_in_i!=-1 ? i : j, loop_in_i!=-1 ? j : i, loop_in_i!=-1 ? loop_in_i : loop_in_j, index, info ) ){
2843 info_valid = true;
2844 }
2845 }
2846 }else{
2847 //AJR: length entailment here?
2848 if( normal_forms[i][index].getKind() == kind::CONST_STRING || normal_forms[j][index].getKind() == kind::CONST_STRING ){
2849 unsigned const_k = normal_forms[i][index].getKind() == kind::CONST_STRING ? i : j;
2850 unsigned nconst_k = normal_forms[i][index].getKind() == kind::CONST_STRING ? j : i;
2851 Node other_str = normal_forms[nconst_k][index];
2852 Assert( other_str.getKind()!=kind::CONST_STRING, "Other string is not constant." );
2853 Assert( other_str.getKind()!=kind::STRING_CONCAT, "Other string is not CONCAT." );
2854 if( !d_equalityEngine.areDisequal( other_str, d_emptyString, true ) ){
2855 Node eq = other_str.eqNode( d_emptyString );
2856 //set info
2857 info.d_conc = NodeManager::currentNM()->mkNode( kind::OR, eq, eq.negate() );
2858 info.d_id = INFER_LEN_SPLIT_EMP;
2859 info_valid = true;
2860 }else{
2861 if( !isRev ){ //FIXME
2862 Node xnz = other_str.eqNode( d_emptyString ).negate();
2863 unsigned index_nc_k = index+1;
2864 //Node next_const_str = TheoryStringsRewriter::collectConstantStringAt( normal_forms[nconst_k], index_nc_k, false );
2865 unsigned start_index_nc_k = index+1;
2866 Node next_const_str = TheoryStringsRewriter::getNextConstantAt( normal_forms[nconst_k], start_index_nc_k, index_nc_k, false );
2867 if( !next_const_str.isNull() ) {
2868 unsigned index_c_k = index;
2869 Node const_str = TheoryStringsRewriter::collectConstantStringAt( normal_forms[const_k], index_c_k, false );
2870 Assert( !const_str.isNull() );
2871 CVC4::String stra = const_str.getConst<String>();
2872 CVC4::String strb = next_const_str.getConst<String>();
2873 //since non-empty, we start with charecter #1
2874 size_t p;
2875 if( isRev ){
2876 CVC4::String stra1 = stra.prefix( stra.size()-1 );
2877 p = stra.size() - stra1.roverlap(strb);
2878 Trace("strings-csp-debug") << "Compute roverlap : " << const_str << " " << next_const_str << std::endl;
2879 size_t p2 = stra1.rfind(strb);
2880 p = p2==std::string::npos ? p : ( p>p2+1? p2+1 : p );
2881 Trace("strings-csp-debug") << "overlap : " << stra1 << " " << strb << " returned " << p << " " << p2 << " " << (p2==std::string::npos) << std::endl;
2882 }else{
2883 CVC4::String stra1 = stra.substr( 1 );
2884 p = stra.size() - stra1.overlap(strb);
2885 Trace("strings-csp-debug") << "Compute overlap : " << const_str << " " << next_const_str << std::endl;
2886 size_t p2 = stra1.find(strb);
2887 p = p2==std::string::npos ? p : ( p>p2+1? p2+1 : p );
2888 Trace("strings-csp-debug") << "overlap : " << stra1 << " " << strb << " returned " << p << " " << p2 << " " << (p2==std::string::npos) << std::endl;
2889 }
2890 if( p>1 ){
2891 if( start_index_nc_k==index+1 ){
2892 info.d_ant.push_back( xnz );
2893 getExplanationVectorForPrefixEq( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend,
2894 const_k, nconst_k, index_c_k, index_nc_k, isRev, info.d_ant );
2895 Node prea = p==stra.size() ? const_str : NodeManager::currentNM()->mkConst( isRev ? stra.suffix( p ) : stra.prefix( p ) );
2896 Node sk = mkSkolemCached( other_str, prea, isRev ? sk_id_c_spt_rev : sk_id_c_spt, "c_spt", -1 );
2897 Trace("strings-csp") << "Const Split: " << prea << " is removed from " << stra << " due to " << strb << ", p=" << p << std::endl;
2898 //set info
2899 info.d_conc = other_str.eqNode( isRev ? mkConcat( sk, prea ) : mkConcat(prea, sk) );
2900 info.d_new_skolem[0].push_back( sk );
2901 info.d_id = INFER_SSPLIT_CST_PROP;
2902 info_valid = true;
2903 }
2904 /* FIXME for isRev, speculative
2905 else if( options::stringLenPropCsp() ){
2906 //propagate length constraint
2907 std::vector< Node > cc;
2908 for( unsigned i=index; i<start_index_nc_k; i++ ){
2909 cc.push_back( normal_forms[nconst_k][i] );
2910 }
2911 Node lt = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, mkConcat( cc ) );
2912 conc = NodeManager::currentNM()->mkNode( kind::GEQ, lt, NodeManager::currentNM()->mkConst( Rational(p) ) );
2913 sendInference( ant, conc, "S-Split(CSP-P)-lprop", true );
2914 }
2915 */
2916 }
2917 }
2918 if( !info_valid ){
2919 info.d_ant.push_back( xnz );
2920 Node const_str = normal_forms[const_k][index];
2921 getExplanationVectorForPrefixEq( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend, i, j, index, index, isRev, info.d_ant );
2922 CVC4::String stra = const_str.getConst<String>();
2923 if( options::stringBinaryCsp() && stra.size()>3 ){
2924 //split string in half
2925 Node c_firstHalf = NodeManager::currentNM()->mkConst( isRev ? stra.substr( stra.size()/2 ) : stra.substr(0, stra.size()/2 ) );
2926 Node sk = mkSkolemCached( other_str, c_firstHalf , isRev ? sk_id_vc_bin_spt_rev : sk_id_vc_bin_spt, "cb_spt", -1 );
2927 Trace("strings-csp") << "Const Split: " << c_firstHalf << " is removed from " << const_str << " (binary) " << std::endl;
2928 info.d_conc = NodeManager::currentNM()->mkNode( kind::OR, other_str.eqNode( isRev ? mkConcat( sk, c_firstHalf ) : mkConcat( c_firstHalf, sk ) ),
2929 NodeManager::currentNM()->mkNode( kind::AND,
2930 sk.eqNode( d_emptyString ).negate(),
2931 c_firstHalf.eqNode( isRev ? mkConcat( sk, other_str ) : mkConcat( other_str, sk ) ) ) );
2932 info.d_new_skolem[0].push_back( sk );
2933 info.d_id = INFER_SSPLIT_CST_BINARY;
2934 info_valid = true;
2935 }else{
2936 // normal v/c split
2937 Node firstChar = stra.size() == 1 ? const_str : NodeManager::currentNM()->mkConst( isRev ? stra.suffix( 1 ) : stra.prefix( 1 ) );
2938 Node sk = mkSkolemCached( other_str, firstChar, isRev ? sk_id_vc_spt_rev : sk_id_vc_spt, "c_spt", -1 );
2939 Trace("strings-csp") << "Const Split: " << firstChar << " is removed from " << const_str << " (serial) " << std::endl;
2940 info.d_conc = other_str.eqNode( isRev ? mkConcat( sk, firstChar ) : mkConcat(firstChar, sk) );
2941 info.d_new_skolem[0].push_back( sk );
2942 info.d_id = INFER_SSPLIT_CST;
2943 info_valid = true;
2944 }
2945 }
2946 }
2947 }
2948 }else{
2949 int lentTestSuccess = -1;
2950 Node lentTestExp;
2951 if( options::stringCheckEntailLen() ){
2952 //check entailment
2953 for( unsigned e=0; e<2; e++ ){
2954 Node t = e==0 ? normal_forms[i][index] : normal_forms[j][index];
2955 //do not infer constants are larger than variables
2956 if( t.getKind()!=kind::CONST_STRING ){
2957 Node lt1 = e==0 ? length_term_i : length_term_j;
2958 Node lt2 = e==0 ? length_term_j : length_term_i;
2959 Node ent_lit = Rewriter::rewrite( NodeManager::currentNM()->mkNode( kind::GT, lt1, lt2 ) );
2960 std::pair<bool, Node> et = d_valuation.entailmentCheck( THEORY_OF_TYPE_BASED, ent_lit );
2961 if( et.first ){
2962 Trace("strings-entail") << "Strings entailment : " << ent_lit << " is entailed in the current context." << std::endl;
2963 Trace("strings-entail") << " explanation was : " << et.second << std::endl;
2964 lentTestSuccess = e;
2965 lentTestExp = et.second;
2966 break;
2967 }
2968 }
2969 }
2970 }
2971
2972 getExplanationVectorForPrefixEq( normal_forms, normal_form_src, normal_forms_exp, normal_forms_exp_depend, i, j, index, index, isRev, info.d_ant );
2973 //x!=e /\ y!=e
2974 for(unsigned xory=0; xory<2; xory++) {
2975 Node x = xory==0 ? normal_forms[i][index] : normal_forms[j][index];
2976 Node xgtz = x.eqNode( d_emptyString ).negate();
2977 if( d_equalityEngine.areDisequal( x, d_emptyString, true ) ) {
2978 info.d_ant.push_back( xgtz );
2979 } else {
2980 info.d_antn.push_back( xgtz );
2981 }
2982 }
2983 Node sk = mkSkolemCached( normal_forms[i][index], normal_forms[j][index], isRev ? sk_id_v_spt_rev : sk_id_v_spt, "v_spt", -1 );
2984 //must add length requirement
2985 info.d_new_skolem[1].push_back( sk );
2986 Node eq1 = normal_forms[i][index].eqNode( isRev ? mkConcat(sk, normal_forms[j][index]) : mkConcat(normal_forms[j][index], sk) );
2987 Node eq2 = normal_forms[j][index].eqNode( isRev ? mkConcat(sk, normal_forms[i][index]) : mkConcat(normal_forms[i][index], sk) );
2988
2989 if( lentTestSuccess!=-1 ){
2990 info.d_antn.push_back( lentTestExp );
2991 info.d_conc = lentTestSuccess==0 ? eq1 : eq2;
2992 info.d_id = INFER_SSPLIT_VAR_PROP;
2993 info_valid = true;
2994 }else{
2995 Node ldeq = NodeManager::currentNM()->mkNode( kind::EQUAL, length_term_i, length_term_j ).negate();
2996 if( d_equalityEngine.areDisequal( length_term_i, length_term_j, true ) ){
2997 info.d_ant.push_back( ldeq );
2998 }else{
2999 info.d_antn.push_back(ldeq);
3000 }
3001 //set info
3002 info.d_conc = NodeManager::currentNM()->mkNode( kind::OR, eq1, eq2 );
3003 info.d_id = INFER_SSPLIT_VAR;
3004 info_valid = true;
3005 }
3006 }
3007 }
3008 }
3009 if( info_valid ){
3010 pinfer.push_back( info );
3011 Assert( !success );
3012 }
3013 }
3014 }
3015 }
3016 }while( success );
3017 }
3018
3019 bool TheoryStrings::detectLoop( std::vector< std::vector< Node > > &normal_forms, int i, int j, int index, int &loop_in_i, int &loop_in_j, unsigned rproc ){
3020 int has_loop[2] = { -1, -1 };
3021 if( options::stringLB() != 2 ) {
3022 for( unsigned r=0; r<2; r++ ) {
3023 int n_index = (r==0 ? i : j);
3024 int other_n_index = (r==0 ? j : i);
3025 if( normal_forms[other_n_index][index].getKind() != kind::CONST_STRING ) {
3026 for( unsigned lp = index+1; lp<normal_forms[n_index].size()-rproc; lp++ ){
3027 if( normal_forms[n_index][lp]==normal_forms[other_n_index][index] ){
3028 has_loop[r] = lp;
3029 break;
3030 }
3031 }
3032 }
3033 }
3034 }
3035 if( has_loop[0]!=-1 || has_loop[1]!=-1 ) {
3036 loop_in_i = has_loop[0];
3037 loop_in_j = has_loop[1];
3038 return true;
3039 } else {
3040 Trace("strings-solve-debug") << "No loops detected." << std::endl;
3041 return false;
3042 }
3043 }
3044
3045 //xs(zy)=t(yz)xr
3046 bool TheoryStrings::processLoop( std::vector< std::vector< Node > > &normal_forms, std::vector< Node > &normal_form_src,
3047 int i, int j, int loop_n_index, int other_n_index, int loop_index, int index, InferInfo& info ){
3048 if( options::stringAbortLoop() ){
3049 std::stringstream ss;
3050 ss << "Looping word equation encountered." << std::endl;
3051 throw LogicException(ss.str());
3052 }
3053 NodeManager* nm = NodeManager::currentNM();
3054 Node conc;
3055 Trace("strings-loop") << "Detected possible loop for "
3056 << normal_forms[loop_n_index][loop_index] << std::endl;
3057 Trace("strings-loop") << " ... (X)= " << normal_forms[other_n_index][index]
3058 << std::endl;
3059
3060 Trace("strings-loop") << " ... T(Y.Z)= ";
3061 std::vector<Node>& veci = normal_forms[loop_n_index];
3062 std::vector<Node> vec_t(veci.begin() + index, veci.begin() + loop_index);
3063 Node t_yz = mkConcat(vec_t);
3064 Trace("strings-loop") << " (" << t_yz << ")" << std::endl;
3065 Trace("strings-loop") << " ... S(Z.Y)= ";
3066 std::vector<Node>& vecoi = normal_forms[other_n_index];
3067 std::vector<Node> vec_s(vecoi.begin() + index + 1, vecoi.end());
3068 Node s_zy = mkConcat(vec_s);
3069 Trace("strings-loop") << s_zy << std::endl;
3070 Trace("strings-loop") << " ... R= ";
3071 std::vector<Node> vec_r(veci.begin() + loop_index + 1, veci.end());
3072 Node r = mkConcat(vec_r);
3073 Trace("strings-loop") << r << std::endl;
3074
3075 if (s_zy.isConst() && r.isConst() && r != d_emptyString)
3076 {
3077 int c;
3078 bool flag = true;
3079 if (s_zy.getConst<String>().tailcmp(r.getConst<String>(), c))
3080 {
3081 if (c >= 0)
3082 {
3083 s_zy = nm->mkConst(s_zy.getConst<String>().substr(0, c));
3084 r = d_emptyString;
3085 vec_r.clear();
3086 Trace("strings-loop") << "Strings::Loop: Refactor S(Z.Y)= " << s_zy
3087 << ", c=" << c << std::endl;
3088 flag = false;
3089 }
3090 }
3091 if (flag)
3092 {
3093 Trace("strings-loop") << "Strings::Loop: tails are different."
3094 << std::endl;
3095 sendInference(info.d_ant, conc, "Loop Conflict", true);
3096 return false;
3097 }
3098 }
3099
3100 Node split_eq;
3101 for (unsigned r = 0; r < 2; r++)
3102 {
3103 Node t = r == 0 ? normal_forms[loop_n_index][loop_index] : t_yz;
3104 split_eq = t.eqNode(d_emptyString);
3105 Node split_eqr = Rewriter::rewrite(split_eq);
3106 // the equality could rewrite to false
3107 if (!split_eqr.isConst())
3108 {
3109 if (!areDisequal(t, d_emptyString))
3110 {
3111 // try to make t equal to empty to avoid loop
3112 info.d_conc = nm->mkNode(kind::OR, split_eq, split_eq.negate());
3113 info.d_id = INFER_LEN_SPLIT_EMP;
3114 return true;
3115 }
3116 else
3117 {
3118 info.d_ant.push_back(split_eq.negate());
3119 }
3120 }
3121 else
3122 {
3123 Assert(!split_eqr.getConst<bool>());
3124 }
3125 }
3126
3127 Node ant = mkExplain(info.d_ant);
3128 info.d_ant.clear();
3129 info.d_antn.push_back(ant);
3130
3131 Node str_in_re;
3132 if (s_zy == t_yz && r == d_emptyString && s_zy.isConst()
3133 && s_zy.getConst<String>().isRepeated())
3134 {
3135 Node rep_c = nm->mkConst(s_zy.getConst<String>().substr(0, 1));
3136 Trace("strings-loop") << "Special case (X)="
3137 << normal_forms[other_n_index][index] << " "
3138 << std::endl;
3139 Trace("strings-loop") << "... (C)=" << rep_c << " " << std::endl;
3140 // special case
3141 str_in_re =
3142 nm->mkNode(kind::STRING_IN_REGEXP,
3143 normal_forms[other_n_index][index],
3144 nm->mkNode(kind::REGEXP_STAR,
3145 nm->mkNode(kind::STRING_TO_REGEXP, rep_c)));
3146 conc = str_in_re;
3147 }
3148 else if (t_yz.isConst())
3149 {
3150 Trace("strings-loop") << "Strings::Loop: Const Normal Breaking."
3151 << std::endl;
3152 CVC4::String s = t_yz.getConst<CVC4::String>();
3153 unsigned size = s.size();
3154 std::vector<Node> vconc;
3155 for (unsigned len = 1; len <= size; len++)
3156 {
3157 Node y = nm->mkConst(s.substr(0, len));
3158 Node z = nm->mkConst(s.substr(len, size - len));
3159 Node restr = s_zy;
3160 Node cc;
3161 if (r != d_emptyString)
3162 {
3163 std::vector<Node> v2(vec_r);
3164 v2.insert(v2.begin(), y);
3165 v2.insert(v2.begin(), z);
3166 restr = mkConcat(z, y);
3167 cc = Rewriter::rewrite(s_zy.eqNode(mkConcat(v2)));
3168 }
3169 else
3170 {
3171 cc = Rewriter::rewrite(s_zy.eqNode(mkConcat(z, y)));
3172 }
3173 if (cc == d_false)
3174 {
3175 continue;
3176 }
3177 Node conc2 = nm->mkNode(
3178 kind::STRING_IN_REGEXP,
3179 normal_forms[other_n_index][index],
3180 nm->mkNode(kind::REGEXP_CONCAT,
3181 nm->mkNode(kind::STRING_TO_REGEXP, y),
3182 nm->mkNode(kind::REGEXP_STAR,
3183 nm->mkNode(kind::STRING_TO_REGEXP, restr))));
3184 cc = cc == d_true ? conc2 : nm->mkNode(kind::AND, cc, conc2);
3185 d_regexp_ant[conc2] = ant;
3186 vconc.push_back(cc);
3187 }
3188 conc = vconc.size() == 0 ? Node::null() : vconc.size() == 1
3189 ? vconc[0]
3190 : nm->mkNode(kind::OR, vconc);
3191 }
3192 else
3193 {
3194 Trace("strings-loop") << "Strings::Loop: Normal Loop Breaking."
3195 << std::endl;
3196 // right
3197 Node sk_w = mkSkolemS("w_loop");
3198 Node sk_y = mkSkolemS("y_loop", 1);
3199 Node sk_z = mkSkolemS("z_loop");
3200 // t1 * ... * tn = y * z
3201 Node conc1 = t_yz.eqNode(mkConcat(sk_y, sk_z));
3202 // s1 * ... * sk = z * y * r
3203 vec_r.insert(vec_r.begin(), sk_y);
3204 vec_r.insert(vec_r.begin(), sk_z);
3205 Node conc2 = s_zy.eqNode(mkConcat(vec_r));
3206 Node conc3 =
3207 normal_forms[other_n_index][index].eqNode(mkConcat(sk_y, sk_w));
3208 Node restr = r == d_emptyString ? s_zy : mkConcat(sk_z, sk_y);
3209 str_in_re =
3210 nm->mkNode(kind::STRING_IN_REGEXP,
3211 sk_w,
3212 nm->mkNode(kind::REGEXP_STAR,
3213 nm->mkNode(kind::STRING_TO_REGEXP, restr)));
3214
3215 std::vector<Node> vec_conc;
3216 vec_conc.push_back(conc1);
3217 vec_conc.push_back(conc2);
3218 vec_conc.push_back(conc3);
3219 vec_conc.push_back(str_in_re);
3220 // vec_conc.push_back(sk_y.eqNode(d_emptyString).negate());//by mkskolems
3221 conc = nm->mkNode(kind::AND, vec_conc);
3222 } // normal case
3223
3224 // set its antecedant to ant, to say when it is relevant
3225 if (!str_in_re.isNull())
3226 {
3227 d_regexp_ant[str_in_re] = ant;
3228 }
3229 // we will be done
3230 if (options::stringProcessLoop())
3231 {
3232 info.d_conc = conc;
3233 info.d_id = INFER_FLOOP;
3234 info.d_nf_pair[0] = normal_form_src[i];
3235 info.d_nf_pair[1] = normal_form_src[j];
3236 return true;
3237 }
3238 d_out->setIncomplete();
3239 return false;
3240 }
3241
3242 //return true for lemma, false if we succeed
3243 void TheoryStrings::processDeq( Node ni, Node nj ) {
3244 //Assert( areDisequal( ni, nj ) );
3245 if( d_normal_forms[ni].size()>1 || d_normal_forms[nj].size()>1 ){
3246 std::vector< Node > nfi;
3247 nfi.insert( nfi.end(), d_normal_forms[ni].begin(), d_normal_forms[ni].end() );
3248 std::vector< Node > nfj;
3249 nfj.insert( nfj.end(), d_normal_forms[nj].begin(), d_normal_forms[nj].end() );
3250
3251 int revRet = processReverseDeq( nfi, nfj, ni, nj );
3252 if( revRet!=0 ){
3253 return;
3254 }
3255
3256 nfi.clear();
3257 nfi.insert( nfi.end(), d_normal_forms[ni].begin(), d_normal_forms[ni].end() );
3258 nfj.clear();
3259 nfj.insert( nfj.end(), d_normal_forms[nj].begin(), d_normal_forms[nj].end() );
3260
3261 unsigned index = 0;
3262 while( index<nfi.size() || index<nfj.size() ){
3263 int ret = processSimpleDeq( nfi, nfj, ni, nj, index, false );
3264 if( ret!=0 ) {
3265 return;
3266 }else{
3267 Assert( index<nfi.size() && index<nfj.size() );
3268 Node i = nfi[index];
3269 Node j = nfj[index];
3270 Trace("strings-solve-debug") << "...Processing(DEQ) " << i << " " << j << std::endl;
3271 if( !areEqual( i, j ) ){
3272 Assert( i.getKind()!=kind::CONST_STRING || j.getKind()!=kind::CONST_STRING );
3273 std::vector< Node > lexp;
3274 Node li = getLength( i, lexp );
3275 Node lj = getLength( j, lexp );
3276 if( areDisequal( li, lj ) ){
3277 if( i.getKind()==kind::CONST_STRING || j.getKind()==kind::CONST_STRING ){
3278 //check if empty
3279 Node const_k = i.getKind() == kind::CONST_STRING ? i : j;
3280 Node nconst_k = i.getKind() == kind::CONST_STRING ? j : i;
3281 Node lnck = i.getKind() == kind::CONST_STRING ? lj : li;
3282 if( !d_equalityEngine.areDisequal( nconst_k, d_emptyString, true ) ){
3283 Node eq = nconst_k.eqNode( d_emptyString );
3284 Node conc = NodeManager::currentNM()->mkNode( kind::OR, eq, eq.negate() );
3285 sendInference( d_empty_vec, conc, "D-DISL-Emp-Split" );
3286 return;
3287 }else{
3288 //split on first character
3289 CVC4::String str = const_k.getConst<String>();
3290 Node firstChar = str.size() == 1 ? const_k : NodeManager::currentNM()->mkConst( str.prefix( 1 ) );
3291 if( areEqual( lnck, d_one ) ){
3292 if( areDisequal( firstChar, nconst_k ) ){
3293 return;
3294 }else if( !areEqual( firstChar, nconst_k ) ){
3295 //splitting on demand : try to make them disequal
3296 if (sendSplit(
3297 firstChar, nconst_k, "S-Split(DEQL-Const)", false))
3298 {
3299 return;
3300 }
3301 }
3302 }else{
3303 Node sk = mkSkolemCached( nconst_k, firstChar, sk_id_dc_spt, "dc_spt", 2 );
3304 Node skr = mkSkolemCached( nconst_k, firstChar, sk_id_dc_spt_rem, "dc_spt_rem" );
3305 Node eq1 = nconst_k.eqNode( NodeManager::currentNM()->mkNode( kind::STRING_CONCAT, sk, skr ) );
3306 eq1 = Rewriter::rewrite( eq1 );
3307 Node eq2 = nconst_k.eqNode( NodeManager::currentNM()->mkNode( kind::STRING_CONCAT, firstChar, skr ) );
3308 std::vector< Node > antec;
3309 antec.insert( antec.end(), d_normal_forms_exp[ni].begin(), d_normal_forms_exp[ni].end() );
3310 antec.insert( antec.end(), d_normal_forms_exp[nj].begin(), d_normal_forms_exp[nj].end() );
3311 antec.push_back( nconst_k.eqNode( d_emptyString ).negate() );
3312 sendInference( antec, NodeManager::currentNM()->mkNode( kind::OR,
3313 NodeManager::currentNM()->mkNode( kind::AND, eq1, sk.eqNode( firstChar ).negate() ), eq2 ), "D-DISL-CSplit" );
3314 d_pending_req_phase[ eq1 ] = true;
3315 return;
3316 }
3317 }
3318 }else{
3319 Trace("strings-solve") << "Non-Simple Case 1 : add lemma " << std::endl;
3320 //must add lemma
3321 std::vector< Node > antec;
3322 std::vector< Node > antec_new_lits;
3323 antec.insert( antec.end(), d_normal_forms_exp[ni].begin(), d_normal_forms_exp[ni].end() );
3324 antec.insert( antec.end(), d_normal_forms_exp[nj].begin(), d_normal_forms_exp[nj].end() );
3325 //check disequal
3326 if( areDisequal( ni, nj ) ){
3327 antec.push_back( ni.eqNode( nj ).negate() );
3328 }else{
3329 antec_new_lits.push_back( ni.eqNode( nj ).negate() );
3330 }
3331 antec_new_lits.push_back( li.eqNode( lj ).negate() );
3332 std::vector< Node > conc;
3333 Node sk1 = mkSkolemCached( i, j, sk_id_deq_x, "x_dsplit" );
3334 Node sk2 = mkSkolemCached( i, j, sk_id_deq_y, "y_dsplit" );
3335 Node sk3 = mkSkolemCached( i, j, sk_id_deq_z, "z_dsplit", 1 );
3336 //Node nemp = sk3.eqNode(d_emptyString).negate();
3337 //conc.push_back(nemp);
3338 Node lsk1 = mkLength( sk1 );
3339 conc.push_back( lsk1.eqNode( li ) );
3340 Node lsk2 = mkLength( sk2 );
3341 conc.push_back( lsk2.eqNode( lj ) );
3342 conc.push_back( NodeManager::currentNM()->mkNode( kind::OR, j.eqNode( mkConcat( sk1, sk3 ) ), i.eqNode( mkConcat( sk2, sk3 ) ) ) );
3343 sendInference( antec, antec_new_lits, NodeManager::currentNM()->mkNode( kind::AND, conc ), "D-DISL-Split" );
3344 ++(d_statistics.d_deq_splits);
3345 return;
3346 }
3347 }else if( areEqual( li, lj ) ){
3348 Assert( !areDisequal( i, j ) );
3349 //splitting on demand : try to make them disequal
3350 if (sendSplit(i, j, "S-Split(DEQL)", false))
3351 {
3352 return;
3353 }
3354 }else{
3355 //splitting on demand : try to make lengths equal
3356 if (sendSplit(li, lj, "D-Split"))
3357 {
3358 return;
3359 }
3360 }
3361 }
3362 index++;
3363 }
3364 }
3365 Assert( false );
3366 }
3367 }
3368
3369 int TheoryStrings::processReverseDeq( std::vector< Node >& nfi, std::vector< Node >& nfj, Node ni, Node nj ) {
3370 //reverse normal form of i, j
3371 std::reverse( nfi.begin(), nfi.end() );
3372 std::reverse( nfj.begin(), nfj.end() );
3373
3374 unsigned index = 0;
3375 int ret = processSimpleDeq( nfi, nfj, ni, nj, index, true );
3376
3377 //reverse normal form of i, j
3378 std::reverse( nfi.begin(), nfi.end() );
3379 std::reverse( nfj.begin(), nfj.end() );
3380
3381 return ret;
3382 }
3383
3384 int TheoryStrings::processSimpleDeq( std::vector< Node >& nfi, std::vector< Node >& nfj, Node ni, Node nj, unsigned& index, bool isRev ){
3385 // See if one side is constant, if so, the disequality ni != nj is satisfied
3386 // since ni does not contain nj or vice versa.
3387 // This is only valid when isRev is false, since when isRev=true, the contents
3388 // of normal form vectors nfi and nfj are reversed.
3389 if (!isRev)
3390 {
3391 for (unsigned i = 0; i < 2; i++)
3392 {
3393 Node c = getConstantEqc(i == 0 ? ni : nj);
3394 if (!c.isNull())
3395 {
3396 int findex, lindex;
3397 if (!TheoryStringsRewriter::canConstantContainList(
3398 c, i == 0 ? nfj : nfi, findex, lindex))
3399 {
3400 Trace("strings-solve-debug")
3401 << "Disequality: constant cannot contain list" << std::endl;
3402 return 1;
3403 }
3404 }
3405 }
3406 }
3407 while( index<nfi.size() || index<nfj.size() ) {
3408 if( index>=nfi.size() || index>=nfj.size() ){
3409 Trace("strings-solve-debug") << "Disequality normalize empty" << std::endl;
3410 std::vector< Node > ant;
3411 //we have a conflict : because the lengths are equal, the remainder needs to be empty, which will lead to a conflict
3412 Node lni = getLengthExp( ni, ant, d_normal_forms_base[ni] );
3413 Node lnj = getLengthExp( nj, ant, d_normal_forms_base[nj] );
3414 ant.push_back( lni.eqNode( lnj ) );
3415 ant.insert( ant.end(), d_normal_forms_exp[ni].begin(), d_normal_forms_exp[ni].end() );
3416 ant.insert( ant.end(), d_normal_forms_exp[nj].begin(), d_normal_forms_exp[nj].end() );
3417 std::vector< Node > cc;
3418 std::vector< Node >& nfk = index>=nfi.size() ? nfj : nfi;
3419 for( unsigned index_k=index; index_k<nfk.size(); index_k++ ){
3420 cc.push_back( nfk[index_k].eqNode( d_emptyString ) );
3421 }
3422 Node conc = cc.size()==1 ? cc[0] : NodeManager::currentNM()->mkNode( kind::AND, cc );
3423 conc = Rewriter::rewrite( conc );
3424 sendInference( ant, conc, "Disequality Normalize Empty", true);
3425 return -1;
3426 }else{
3427 Node i = nfi[index];
3428 Node j = nfj[index];
3429 Trace("strings-solve-debug") << "...Processing(QED) " << i << " " << j << std::endl;
3430 if( !areEqual( i, j ) ) {
3431 if( i.getKind()==kind::CONST_STRING && j.getKind()==kind::CONST_STRING ) {
3432 unsigned int len_short = i.getConst<String>().size() < j.getConst<String>().size() ? i.getConst<String>().size() : j.getConst<String>().size();
3433 bool isSameFix = isRev ? i.getConst<String>().rstrncmp(j.getConst<String>(), len_short): i.getConst<String>().strncmp(j.getConst<String>(), len_short);
3434 if( isSameFix ) {
3435 //same prefix/suffix
3436 //k is the index of the string that is shorter
3437 Node nk = i.getConst<String>().size() < j.getConst<String>().size() ? i : j;
3438 Node nl = i.getConst<String>().size() < j.getConst<String>().size() ? j : i;
3439 Node remainderStr;
3440 if( isRev ){
3441 int new_len = nl.getConst<String>().size() - len_short;
3442 remainderStr = NodeManager::currentNM()->mkConst( nl.getConst<String>().substr(0, new_len) );
3443 Trace("strings-solve-debug-test") << "Rev. Break normal form of " << nl << " into " << nk << ", " << remainderStr << std::endl;
3444 } else {
3445 remainderStr = NodeManager::currentNM()->mkConst( nl.getConst<String>().substr( len_short ) );
3446 Trace("strings-solve-debug-test") << "Break normal form of " << nl << " into " << nk << ", " << remainderStr << std::endl;
3447 }
3448 if( i.getConst<String>().size() < j.getConst<String>().size() ) {
3449 nfj.insert( nfj.begin() + index + 1, remainderStr );
3450 nfj[index] = nfi[index];
3451 } else {
3452 nfi.insert( nfi.begin() + index + 1, remainderStr );
3453 nfi[index] = nfj[index];
3454 }
3455 }else{
3456 return 1;
3457 }
3458 }else{
3459 std::vector< Node > lexp;
3460 Node li = getLength( i, lexp );
3461 Node lj = getLength( j, lexp );
3462 if( areEqual( li, lj ) && areDisequal( i, j ) ){
3463 Trace("strings-solve") << "Simple Case 2 : found equal length disequal sub strings " << i << " " << j << std::endl;
3464 //we are done: D-Remove
3465 return 1;
3466 }else{
3467 return 0;
3468 }
3469 }
3470 }
3471 index++;
3472 }
3473 }
3474 return 0;
3475 }
3476
3477 void TheoryStrings::addNormalFormPair( Node n1, Node n2 ){
3478 if( !isNormalFormPair( n1, n2 ) ){
3479 int index = 0;
3480 NodeIntMap::const_iterator it = d_nf_pairs.find( n1 );
3481 if( it!=d_nf_pairs.end() ){
3482 index = (*it).second;
3483 }
3484 d_nf_pairs[n1] = index + 1;
3485 if( index<(int)d_nf_pairs_data[n1].size() ){
3486 d_nf_pairs_data[n1][index] = n2;
3487 }else{
3488 d_nf_pairs_data[n1].push_back( n2 );
3489 }
3490 Assert( isNormalFormPair( n1, n2 ) );
3491 } else {
3492 Trace("strings-nf-debug") << "Already a normal form pair " << n1 << " " << n2 << std::endl;
3493 }
3494 }
3495
3496 bool TheoryStrings::isNormalFormPair( Node n1, Node n2 ) {
3497 //TODO: modulo equality?
3498 return isNormalFormPair2( n1, n2 ) || isNormalFormPair2( n2, n1 );
3499 }
3500
3501 bool TheoryStrings::isNormalFormPair2( Node n1, Node n2 ) {
3502 //Trace("strings-debug") << "is normal form pair. " << n1 << " " << n2 << std::endl;
3503 NodeIntMap::const_iterator it = d_nf_pairs.find( n1 );
3504 if( it!=d_nf_pairs.end() ){
3505 Assert( d_nf_pairs_data.find( n1 )!=d_nf_pairs_data.end() );
3506 for( int i=0; i<(*it).second; i++ ){
3507 Assert( i<(int)d_nf_pairs_data[n1].size() );
3508 if( d_nf_pairs_data[n1][i]==n2 ){
3509 return true;
3510 }
3511 }
3512 }
3513 return false;
3514 }
3515
3516 void TheoryStrings::registerTerm( Node n, int effort ) {
3517 TypeNode tn = n.getType();
3518 bool do_register = true;
3519 if (!tn.isString())
3520 {
3521 if (options::stringEagerLen())
3522 {
3523 do_register = effort == 0;
3524 }
3525 else
3526 {
3527 do_register = effort > 0 || n.getKind() != kind::STRING_CONCAT;
3528 }
3529 }
3530 if( do_register ){
3531 if(d_registered_terms_cache.find(n) == d_registered_terms_cache.end()) {
3532 d_registered_terms_cache.insert(n);
3533 Debug("strings-register") << "TheoryStrings::registerTerm() " << n << ", effort = " << effort << std::endl;
3534 if (tn.isString())
3535 {
3536 //register length information:
3537 // for variables, split on empty vs positive length
3538 // for concat/const/replace, introduce proxy var and state length relation
3539 Node lsum;
3540 bool processed = false;
3541 if( n.getKind()!=kind::STRING_CONCAT && n.getKind()!=kind::CONST_STRING ) {
3542 if( d_length_lemma_terms_cache.find( n )==d_length_lemma_terms_cache.end() ){
3543 Node lsumb = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, n );
3544 lsum = Rewriter::rewrite( lsumb );
3545 // can register length term if it does not rewrite
3546 if( lsum==lsumb ){
3547 sendLengthLemma( n );
3548 processed = true;
3549 }
3550 }else{
3551 processed = true;
3552 }
3553 }
3554 if( !processed ){
3555 Node sk = mkSkolemS( "lsym", -1 );
3556 StringsProxyVarAttribute spva;
3557 sk.setAttribute(spva,true);
3558 Node eq = Rewriter::rewrite( sk.eqNode(n) );
3559 Trace("strings-lemma") << "Strings::Lemma LENGTH Term : " << eq << std::endl;
3560 d_proxy_var[n] = sk;
3561 Trace("strings-assert") << "(assert " << eq << ")" << std::endl;
3562 d_out->lemma(eq);
3563 Node skl = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, sk );
3564 if( n.getKind()==kind::STRING_CONCAT ){
3565 std::vector<Node> node_vec;
3566 for( unsigned i=0; i<n.getNumChildren(); i++ ) {
3567 if( n[i].getAttribute(StringsProxyVarAttribute()) ){
3568 Assert( d_proxy_var_to_length.find( n[i] )!=d_proxy_var_to_length.end() );
3569 node_vec.push_back( d_proxy_var_to_length[n[i]] );
3570 }else{
3571 Node lni = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, n[i] );
3572 node_vec.push_back(lni);
3573 }
3574 }
3575 lsum = NodeManager::currentNM()->mkNode( kind::PLUS, node_vec );
3576 lsum = Rewriter::rewrite( lsum );
3577 }else if( n.getKind()==kind::CONST_STRING ){
3578 lsum = NodeManager::currentNM()->mkConst( ::CVC4::Rational( n.getConst<String>().size() ) );
3579 }
3580 Assert( !lsum.isNull() );
3581 d_proxy_var_to_length[sk] = lsum;
3582 Node ceq = Rewriter::rewrite( skl.eqNode( lsum ) );
3583 Trace("strings-lemma") << "Strings::Lemma LENGTH : " << ceq << std::endl;
3584 Trace("strings-lemma-debug") << " prerewrite : " << skl.eqNode( lsum ) << std::endl;
3585 Trace("strings-assert") << "(assert " << ceq << ")" << std::endl;
3586 d_out->lemma(ceq);
3587 }
3588 }
3589 else if (n.getKind() == kind::STRING_CODE)
3590 {
3591 d_has_str_code = true;
3592 NodeManager* nm = NodeManager::currentNM();
3593 // ite( str.len(s)==1, 0 <= str.code(s) < num_codes, str.code(s)=-1 )
3594 Node code_len = mkLength(n[0]).eqNode(d_one);
3595 Node code_eq_neg1 = n.eqNode(d_neg_one);
3596 Node code_range = nm->mkNode(
3597 kind::AND,
3598 nm->mkNode(kind::GEQ, n, d_zero),
3599 nm->mkNode(
3600 kind::LT, n, nm->mkConst(Rational(CVC4::String::num_codes()))));
3601 Node lem = nm->mkNode(kind::ITE, code_len, code_range, code_eq_neg1);
3602 Trace("strings-lemma") << "Strings::Lemma CODE : " << lem << std::endl;
3603 Trace("strings-assert") << "(assert " << lem << ")" << std::endl;
3604 d_out->lemma(lem);
3605 }
3606 }
3607 }
3608 }
3609
3610 void TheoryStrings::sendInference( std::vector< Node >& exp, std::vector< Node >& exp_n, Node eq, const char * c, bool asLemma ) {
3611 eq = eq.isNull() ? d_false : Rewriter::rewrite( eq );
3612 if( eq!=d_true ){
3613 if( Trace.isOn("strings-infer-debug") ){
3614 Trace("strings-infer-debug") << "By " << c << ", infer : " << eq << " from: " << std::endl;
3615 for( unsigned i=0; i<exp.size(); i++ ){
3616 Trace("strings-infer-debug") << " " << exp[i] << std::endl;
3617 }
3618 for( unsigned i=0; i<exp_n.size(); i++ ){
3619 Trace("strings-infer-debug") << " N:" << exp_n[i] << std::endl;
3620 }
3621 //Trace("strings-infer-debug") << "as lemma : " << asLemma << std::endl;
3622 }
3623 //check if we should send a lemma or an inference
3624 if( asLemma || eq==d_false || eq.getKind()==kind::OR || !exp_n.empty() || options::stringInferAsLemmas() ){
3625 Node eq_exp;
3626 if( options::stringRExplainLemmas() ){
3627 eq_exp = mkExplain( exp, exp_n );
3628 }else{
3629 if( exp.empty() ){
3630 eq_exp = mkAnd( exp_n );
3631 }else if( exp_n.empty() ){
3632 eq_exp = mkAnd( exp );
3633 }else{
3634 std::vector< Node > ev;
3635 ev.insert( ev.end(), exp.begin(), exp.end() );
3636 ev.insert( ev.end(), exp_n.begin(), exp_n.end() );
3637 eq_exp = NodeManager::currentNM()->mkNode( kind::AND, ev );
3638 }
3639 }
3640 // if we have unexplained literals, this lemma is not a conflict
3641 if (eq == d_false && !exp_n.empty())
3642 {
3643 eq = eq_exp.negate();
3644 eq_exp = d_true;
3645 }
3646 sendLemma( eq_exp, eq, c );
3647 }else{
3648 sendInfer( mkAnd( exp ), eq, c );
3649 }
3650 }
3651 }
3652
3653 void TheoryStrings::sendInference( std::vector< Node >& exp, Node eq, const char * c, bool asLemma ) {
3654 std::vector< Node > exp_n;
3655 sendInference( exp, exp_n, eq, c, asLemma );
3656 }
3657
3658 void TheoryStrings::sendLemma( Node ant, Node conc, const char * c ) {
3659 if( conc.isNull() || conc == d_false ) {
3660 Trace("strings-conflict") << "Strings::Conflict : " << c << " : " << ant << std::endl;
3661 Trace("strings-lemma") << "Strings::Conflict : " << c << " : " << ant << std::endl;
3662 Trace("strings-assert") << "(assert (not " << ant << ")) ; conflict " << c << std::endl;
3663 d_out->conflict(ant);
3664 d_conflict = true;
3665 } else {
3666 Node lem;
3667 if( ant == d_true ) {
3668 lem = conc;
3669 }else{
3670 lem = NodeManager::currentNM()->mkNode( kind::IMPLIES, ant, conc );
3671 }
3672 Trace("strings-lemma") << "Strings::Lemma " << c << " : " << lem << std::endl;
3673 Trace("strings-assert") << "(assert " << lem << ") ; lemma " << c << std::endl;
3674 d_lemma_cache.push_back( lem );
3675 }
3676 }
3677
3678 void TheoryStrings::sendInfer( Node eq_exp, Node eq, const char * c ) {
3679 if( options::stringInferSym() ){
3680 std::vector< Node > vars;
3681 std::vector< Node > subs;
3682 std::vector< Node > unproc;
3683 inferSubstitutionProxyVars( eq_exp, vars, subs, unproc );
3684 if( unproc.empty() ){
3685 Trace("strings-lemma-debug") << "Strings::Infer " << eq << " from " << eq_exp << " by " << c << std::endl;
3686 Node eqs = eq.substitute( vars.begin(), vars.end(), subs.begin(), subs.end() );
3687 Trace("strings-lemma-debug") << "Strings::Infer Alternate : " << eqs << std::endl;
3688 for( unsigned i=0; i<vars.size(); i++ ){
3689 Trace("strings-lemma-debug") << " " << vars[i] << " -> " << subs[i] << std::endl;
3690 }
3691 sendLemma( d_true, eqs, c );
3692 return;
3693 }else{
3694 for( unsigned i=0; i<unproc.size(); i++ ){
3695 Trace("strings-lemma-debug") << " non-trivial exp : " << unproc[i] << std::endl;
3696 }
3697 }
3698 }
3699 Trace("strings-lemma") << "Strings::Infer " << eq << " from " << eq_exp << " by " << c << std::endl;
3700 Trace("strings-assert") << "(assert (=> " << eq_exp << " " << eq << ")) ; infer " << c << std::endl;
3701 d_pending.push_back( eq );
3702 d_pending_exp[eq] = eq_exp;
3703 d_infer.push_back( eq );
3704 d_infer_exp.push_back( eq_exp );
3705 }
3706
3707 bool TheoryStrings::sendSplit(Node a, Node b, const char* c, bool preq)
3708 {
3709 Node eq = a.eqNode( b );
3710 eq = Rewriter::rewrite( eq );
3711 if (!eq.isConst())
3712 {
3713 Node neq = NodeManager::currentNM()->mkNode(kind::NOT, eq);
3714 Node lemma_or = NodeManager::currentNM()->mkNode(kind::OR, eq, neq);
3715 Trace("strings-lemma") << "Strings::Lemma " << c << " SPLIT : " << lemma_or
3716 << std::endl;
3717 d_lemma_cache.push_back(lemma_or);
3718 d_pending_req_phase[eq] = preq;
3719 ++(d_statistics.d_splits);
3720 return true;
3721 }
3722 return false;
3723 }
3724
3725
3726 void TheoryStrings::sendLengthLemma( Node n ){
3727 Node n_len = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, n);
3728 if( options::stringSplitEmp() || !options::stringLenGeqZ() ){
3729 NodeManager* nm = NodeManager::currentNM();
3730 Node n_len_eq_z = n_len.eqNode( d_zero );
3731 Node n_len_eq_z_2 = n.eqNode( d_emptyString );
3732 Node case_empty = nm->mkNode(AND, n_len_eq_z, n_len_eq_z_2);
3733 case_empty = Rewriter::rewrite(case_empty);
3734 Node case_nempty = nm->mkNode(GT, n_len, d_zero);
3735 if (!case_empty.isConst())
3736 {
3737 Node lem = nm->mkNode(OR, case_empty, case_nempty);
3738 d_out->lemma(lem);
3739 Trace("strings-lemma") << "Strings::Lemma LENGTH >= 0 : " << lem
3740 << std::endl;
3741 // prefer trying the empty case first
3742 // notice that requirePhase must only be called on rewritten literals that
3743 // occur in the CNF stream.
3744 n_len_eq_z = Rewriter::rewrite(n_len_eq_z);
3745 Assert(!n_len_eq_z.isConst());
3746 d_out->requirePhase(n_len_eq_z, true);
3747 n_len_eq_z_2 = Rewriter::rewrite(n_len_eq_z_2);
3748 Assert(!n_len_eq_z_2.isConst());
3749 d_out->requirePhase(n_len_eq_z_2, true);
3750 }
3751 else if (!case_empty.getConst<bool>())
3752 {
3753 // the rewriter knows that n is non-empty
3754 Trace("strings-lemma")
3755 << "Strings::Lemma LENGTH > 0 (non-empty): " << case_nempty
3756 << std::endl;
3757 d_out->lemma(case_nempty);
3758 }
3759 else
3760 {
3761 // If n = "" ---> true or len( n ) = 0 ----> true, then we expect that
3762 // n ---> "". Since this method is only called on non-constants n, it must
3763 // be that n = "" ^ len( n ) = 0 does not rewrite to true.
3764 Assert(false);
3765 }
3766 }
3767 //AJR: probably a good idea
3768 if( options::stringLenGeqZ() ){
3769 Node n_len_geq = NodeManager::currentNM()->mkNode( kind::GEQ, n_len, d_zero);
3770 n_len_geq = Rewriter::rewrite( n_len_geq );
3771 d_out->lemma( n_len_geq );
3772 }
3773 }
3774
3775 void TheoryStrings::inferSubstitutionProxyVars( Node n, std::vector< Node >& vars, std::vector< Node >& subs, std::vector< Node >& unproc ) {
3776 if( n.getKind()==kind::AND ){
3777 for( unsigned i=0; i<n.getNumChildren(); i++ ){
3778 inferSubstitutionProxyVars( n[i], vars, subs, unproc );
3779 }
3780 return;
3781 }else if( n.getKind()==kind::EQUAL ){
3782 Node ns = n.substitute( vars.begin(), vars.end(), subs.begin(), subs.end() );
3783 ns = Rewriter::rewrite( ns );
3784 if( ns.getKind()==kind::EQUAL ){
3785 Node s;
3786 Node v;
3787 for( unsigned i=0; i<2; i++ ){
3788 Node ss;
3789 if( ns[i].getAttribute(StringsProxyVarAttribute()) ){
3790 ss = ns[i];
3791 }else if( ns[i].isConst() ){
3792 NodeNodeMap::const_iterator it = d_proxy_var.find( ns[i] );
3793 if( it!=d_proxy_var.end() ){
3794 ss = (*it).second;
3795 }
3796 }
3797 if( !ss.isNull() ){
3798 v = ns[1-i];
3799 if( v.getNumChildren()==0 ){
3800 if( s.isNull() ){
3801 s = ss;
3802 }else{
3803 //both sides involved in proxy var
3804 if( ss==s ){
3805 return;
3806 }else{
3807 s = Node::null();
3808 }
3809 }
3810 }
3811 }
3812 }
3813 if( !s.isNull() ){
3814 subs.push_back( s );
3815 vars.push_back( v );
3816 return;
3817 }
3818 }else{
3819 n = ns;
3820 }
3821 }
3822 if( n!=d_true ){
3823 unproc.push_back( n );
3824 }
3825 }
3826
3827
3828 Node TheoryStrings::mkConcat( Node n1, Node n2 ) {
3829 return Rewriter::rewrite( NodeManager::currentNM()->mkNode( kind::STRING_CONCAT, n1, n2 ) );
3830 }
3831
3832 Node TheoryStrings::mkConcat( Node n1, Node n2, Node n3 ) {
3833 return Rewriter::rewrite( NodeManager::currentNM()->mkNode( kind::STRING_CONCAT, n1, n2, n3 ) );
3834 }
3835
3836 Node TheoryStrings::mkConcat( const std::vector< Node >& c ) {
3837 return Rewriter::rewrite( c.size()>1 ? NodeManager::currentNM()->mkNode( kind::STRING_CONCAT, c ) : ( c.size()==1 ? c[0] : d_emptyString ) );
3838 }
3839
3840 Node TheoryStrings::mkLength( Node t ) {
3841 return Rewriter::rewrite( NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, t ) );
3842 }
3843
3844 Node TheoryStrings::mkSkolemCached( Node a, Node b, int id, const char * c, int isLenSplit ){
3845 //return mkSkolemS( c, isLenSplit );
3846 std::map< int, Node >::iterator it = d_skolem_cache[a][b].find( id );
3847 if( it==d_skolem_cache[a][b].end() ){
3848 Node sk = mkSkolemS( c, isLenSplit );
3849 d_skolem_cache[a][b][id] = sk;
3850 return sk;
3851 }else{
3852 return it->second;
3853 }
3854 }
3855
3856 //isLenSplit: -1-ignore, 0-no restriction, 1-greater than one, 2-one
3857 Node TheoryStrings::mkSkolemS( const char *c, int isLenSplit ) {
3858 Node n = NodeManager::currentNM()->mkSkolem( c, NodeManager::currentNM()->stringType(), "string sko" );
3859 d_all_skolems.insert(n);
3860 d_length_lemma_terms_cache.insert( n );
3861 ++(d_statistics.d_new_skolems);
3862 if( isLenSplit==0 ){
3863 sendLengthLemma( n );
3864 } else if( isLenSplit == 1 ){
3865 registerNonEmptySkolem( n );
3866 }else if( isLenSplit==2 ){
3867 Node len_one = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, n ).eqNode( d_one );
3868 Trace("strings-lemma") << "Strings::Lemma SK-ONE : " << len_one << std::endl;
3869 Trace("strings-assert") << "(assert " << len_one << ")" << std::endl;
3870 d_out->lemma( len_one );
3871 }
3872 return n;
3873 }
3874
3875 void TheoryStrings::registerNonEmptySkolem( Node n ) {
3876 if( d_skolem_ne_reg_cache.find( n )==d_skolem_ne_reg_cache.end() ){
3877 d_skolem_ne_reg_cache.insert( n );
3878 d_equalityEngine.assertEquality(n.eqNode(d_emptyString), false, d_true);
3879 Node len_n_gt_z = NodeManager::currentNM()->mkNode(kind::GT,
3880 NodeManager::currentNM()->mkNode(kind::STRING_LENGTH, n), d_zero);
3881 Trace("strings-lemma") << "Strings::Lemma SK-NON-ZERO : " << len_n_gt_z << std::endl;
3882 Trace("strings-assert") << "(assert " << len_n_gt_z << ")" << std::endl;
3883 d_out->lemma(len_n_gt_z);
3884 }
3885 }
3886
3887 Node TheoryStrings::mkExplain( std::vector< Node >& a ) {
3888 std::vector< Node > an;
3889 return mkExplain( a, an );
3890 }
3891
3892 Node TheoryStrings::mkExplain( std::vector< Node >& a, std::vector< Node >& an ) {
3893 std::vector< TNode > antec_exp;
3894 for( unsigned i=0; i<a.size(); i++ ) {
3895 if( std::find( a.begin(), a.begin() + i, a[i] )==a.begin() + i ) {
3896 bool exp = true;
3897 Debug("strings-explain") << "Ask for explanation of " << a[i] << std::endl;
3898 //assert
3899 if(a[i].getKind() == kind::EQUAL) {
3900 //Assert( hasTerm(a[i][0]) );
3901 //Assert( hasTerm(a[i][1]) );
3902 Assert( areEqual(a[i][0], a[i][1]) );
3903 if( a[i][0]==a[i][1] ){
3904 exp = false;
3905 }
3906 } else if( a[i].getKind()==kind::NOT && a[i][0].getKind()==kind::EQUAL ) {
3907 Assert( hasTerm(a[i][0][0]) );
3908 Assert( hasTerm(a[i][0][1]) );
3909 AlwaysAssert( d_equalityEngine.areDisequal(a[i][0][0], a[i][0][1], true) );
3910 }else if( a[i].getKind() == kind::AND ){
3911 for( unsigned j=0; j<a[i].getNumChildren(); j++ ){
3912 a.push_back( a[i][j] );
3913 }
3914 exp = false;
3915 }
3916 if( exp ) {
3917 unsigned ps = antec_exp.size();
3918 explain(a[i], antec_exp);
3919 Debug("strings-explain") << "Done, explanation was : " << std::endl;
3920 for( unsigned j=ps; j<antec_exp.size(); j++ ) {
3921 Debug("strings-explain") << " " << antec_exp[j] << std::endl;
3922 }
3923 Debug("strings-explain") << std::endl;
3924 }
3925 }
3926 }
3927 for( unsigned i=0; i<an.size(); i++ ) {
3928 if( std::find( an.begin(), an.begin() + i, an[i] )==an.begin() + i ){
3929 Debug("strings-explain") << "Add to explanation (new literal) " << an[i] << std::endl;
3930 antec_exp.push_back(an[i]);
3931 }
3932 }
3933 Node ant;
3934 if( antec_exp.empty() ) {
3935 ant = d_true;
3936 } else if( antec_exp.size()==1 ) {
3937 ant = antec_exp[0];
3938 } else {
3939 ant = NodeManager::currentNM()->mkNode( kind::AND, antec_exp );
3940 }
3941 //ant = Rewriter::rewrite( ant );
3942 return ant;
3943 }
3944
3945 Node TheoryStrings::mkAnd( std::vector< Node >& a ) {
3946 std::vector< Node > au;
3947 for( unsigned i=0; i<a.size(); i++ ){
3948 if( std::find( au.begin(), au.end(), a[i] )==au.end() ){
3949 au.push_back( a[i] );
3950 }
3951 }
3952 if( au.empty() ) {
3953 return d_true;
3954 } else if( au.size() == 1 ) {
3955 return au[0];
3956 } else {
3957 return NodeManager::currentNM()->mkNode( kind::AND, au );
3958 }
3959 }
3960
3961 void TheoryStrings::getConcatVec( Node n, std::vector< Node >& c ) {
3962 if( n.getKind()==kind::STRING_CONCAT ) {
3963 for( unsigned i=0; i<n.getNumChildren(); i++ ) {
3964 if( !areEqual( n[i], d_emptyString ) ) {
3965 c.push_back( n[i] );
3966 }
3967 }
3968 }else{
3969 c.push_back( n );
3970 }
3971 }
3972
3973 void TheoryStrings::checkNormalFormsDeq()
3974 {
3975 std::vector< std::vector< Node > > cols;
3976 std::vector< Node > lts;
3977 std::map< Node, std::map< Node, bool > > processed;
3978
3979 //for each pair of disequal strings, must determine whether their lengths are equal or disequal
3980 for( NodeList::const_iterator id = d_ee_disequalities.begin(); id != d_ee_disequalities.end(); ++id ) {
3981 Node eq = *id;
3982 Node n[2];
3983 for( unsigned i=0; i<2; i++ ){
3984 n[i] = d_equalityEngine.getRepresentative( eq[i] );
3985 }
3986 if( processed[n[0]].find( n[1] )==processed[n[0]].end() ){
3987 processed[n[0]][n[1]] = true;
3988 Node lt[2];
3989 for( unsigned i=0; i<2; i++ ){
3990 EqcInfo* ei = getOrMakeEqcInfo( n[i], false );
3991 lt[i] = ei ? ei->d_length_term : Node::null();
3992 if( lt[i].isNull() ){
3993 lt[i] = eq[i];
3994 }
3995 lt[i] = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, lt[i] );
3996 }
3997 if( !areEqual( lt[0], lt[1] ) && !areDisequal( lt[0], lt[1] ) ){
3998 sendSplit( lt[0], lt[1], "DEQ-LENGTH-SP" );
3999 }
4000 }
4001 }
4002
4003 if( !hasProcessed() ){
4004 separateByLength( d_strings_eqc, cols, lts );
4005 for( unsigned i=0; i<cols.size(); i++ ){
4006 if( cols[i].size()>1 && d_lemma_cache.empty() ){
4007 Trace("strings-solve") << "- Verify disequalities are processed for " << cols[i][0] << ", normal form : ";
4008 printConcat( d_normal_forms[cols[i][0]], "strings-solve" );
4009 Trace("strings-solve") << "... #eql = " << cols[i].size() << std::endl;
4010 //must ensure that normal forms are disequal
4011 for( unsigned j=0; j<cols[i].size(); j++ ){
4012 for( unsigned k=(j+1); k<cols[i].size(); k++ ){
4013 //for strings that are disequal, but have the same length
4014 if( areDisequal( cols[i][j], cols[i][k] ) ){
4015 Assert( !d_conflict );
4016 Trace("strings-solve") << "- Compare " << cols[i][j] << " ";
4017 printConcat( d_normal_forms[cols[i][j]], "strings-solve" );
4018 Trace("strings-solve") << " against " << cols[i][k] << " ";
4019 printConcat( d_normal_forms[cols[i][k]], "strings-solve" );
4020 Trace("strings-solve") << "..." << std::endl;
4021 processDeq( cols[i][j], cols[i][k] );
4022 if( hasProcessed() ){
4023 return;
4024 }
4025 }
4026 }
4027 }
4028 }
4029 }
4030 }
4031 }
4032
4033 void TheoryStrings::checkLengthsEqc() {
4034 if( options::stringLenNorm() ){
4035 for( unsigned i=0; i<d_strings_eqc.size(); i++ ){
4036 //if( d_normal_forms[nodes[i]].size()>1 ) {
4037 Trace("strings-process-debug") << "Process length constraints for " << d_strings_eqc[i] << std::endl;
4038 //check if there is a length term for this equivalence class
4039 EqcInfo* ei = getOrMakeEqcInfo( d_strings_eqc[i], false );
4040 Node lt = ei ? ei->d_length_term : Node::null();
4041 if( !lt.isNull() ) {
4042 Node llt = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, lt );
4043 //now, check if length normalization has occurred
4044 if( ei->d_normalized_length.get().isNull() ) {
4045 Node nf = mkConcat( d_normal_forms[d_strings_eqc[i]] );
4046 if( Trace.isOn("strings-process-debug") ){
4047 Trace("strings-process-debug") << " normal form is " << nf << " from base " << d_normal_forms_base[d_strings_eqc[i]] << std::endl;
4048 Trace("strings-process-debug") << " normal form exp is: " << std::endl;
4049 for( unsigned j=0; j<d_normal_forms_exp[d_strings_eqc[i]].size(); j++ ){
4050 Trace("strings-process-debug") << " " << d_normal_forms_exp[d_strings_eqc[i]][j] << std::endl;
4051 }
4052 }
4053
4054 //if not, add the lemma
4055 std::vector< Node > ant;
4056 ant.insert( ant.end(), d_normal_forms_exp[d_strings_eqc[i]].begin(), d_normal_forms_exp[d_strings_eqc[i]].end() );
4057 ant.push_back( d_normal_forms_base[d_strings_eqc[i]].eqNode( lt ) );
4058 Node lc = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, nf );
4059 Node lcr = Rewriter::rewrite( lc );
4060 Trace("strings-process-debug") << "Rewrote length " << lc << " to " << lcr << std::endl;
4061 Node eq = llt.eqNode( lcr );
4062 if( llt!=lcr ){
4063 ei->d_normalized_length.set( eq );
4064 sendInference( ant, eq, "LEN-NORM", true );
4065 }
4066 }
4067 }else{
4068 Trace("strings-process-debug") << "No length term for eqc " << d_strings_eqc[i] << " " << d_eqc_to_len_term[d_strings_eqc[i]] << std::endl;
4069 if( !options::stringEagerLen() ){
4070 Node c = mkConcat( d_normal_forms[d_strings_eqc[i]] );
4071 registerTerm( c, 3 );
4072 /*
4073 if( !c.isConst() ){
4074 NodeNodeMap::const_iterator it = d_proxy_var.find( c );
4075 if( it!=d_proxy_var.end() ){
4076 Node pv = (*it).second;
4077 Assert( d_proxy_var_to_length.find( pv )!=d_proxy_var_to_length.end() );
4078 Node pvl = d_proxy_var_to_length[pv];
4079 Node ceq = Rewriter::rewrite( mkLength( pv ).eqNode( pvl ) );
4080 sendInference( d_empty_vec, ceq, "LEN-NORM-I", true );
4081 }
4082 }
4083 */
4084 }
4085 }
4086 //} else {
4087 // Trace("strings-process-debug") << "Do not process length constraints for " << nodes[i] << " " << d_normal_forms[nodes[i]].size() << std::endl;
4088 //}
4089 }
4090 }
4091 }
4092
4093 void TheoryStrings::checkCardinality() {
4094 //int cardinality = options::stringCharCardinality();
4095 //Trace("strings-solve-debug2") << "get cardinality: " << cardinality << endl;
4096
4097 //AJR: this will create a partition of eqc, where each collection has length that are pairwise propagated to be equal.
4098 // we do not require disequalities between the lengths of each collection, since we split on disequalities between lengths of string terms that are disequal (DEQ-LENGTH-SP).
4099 // TODO: revisit this?
4100 std::vector< std::vector< Node > > cols;
4101 std::vector< Node > lts;
4102 separateByLength( d_strings_eqc, cols, lts );
4103
4104 for( unsigned i = 0; i<cols.size(); ++i ) {
4105 Node lr = lts[i];
4106 Trace("strings-card") << "Number of strings with length equal to " << lr << " is " << cols[i].size() << std::endl;
4107 if( cols[i].size() > 1 ) {
4108 // size > c^k
4109 unsigned card_need = 1;
4110 double curr = (double)cols[i].size();
4111 while( curr>d_card_size ){
4112 curr = curr/(double)d_card_size;
4113 card_need++;
4114 }
4115 Trace("strings-card") << "Need length " << card_need << " for this number of strings (where alphabet size is " << d_card_size << ")." << std::endl;
4116 //check if we need to split
4117 bool needsSplit = true;
4118 if( lr.isConst() ){
4119 // if constant, compare
4120 Node cmp = NodeManager::currentNM()->mkNode( kind::GEQ, lr, NodeManager::currentNM()->mkConst( Rational( card_need ) ) );
4121 cmp = Rewriter::rewrite( cmp );
4122 needsSplit = cmp!=d_true;
4123 }else{
4124 // find the minimimum constant that we are unknown to be disequal from, or otherwise stop if we increment such that cardinality does not apply
4125 unsigned r=0;
4126 bool success = true;
4127 while( r<card_need && success ){
4128 Node rr = NodeManager::currentNM()->mkConst<Rational>( Rational(r) );
4129 if( areDisequal( rr, lr ) ){
4130 r++;
4131 }else{
4132 success = false;
4133 }
4134 }
4135 if( r>0 ){
4136 Trace("strings-card") << "Symbolic length " << lr << " must be at least " << r << " due to constant disequalities." << std::endl;
4137 }
4138 needsSplit = r<card_need;
4139 }
4140
4141 if( needsSplit ){
4142 unsigned int int_k = (unsigned int)card_need;
4143 for( std::vector< Node >::iterator itr1 = cols[i].begin();
4144 itr1 != cols[i].end(); ++itr1) {
4145 for( std::vector< Node >::iterator itr2 = itr1 + 1;
4146 itr2 != cols[i].end(); ++itr2) {
4147 if(!areDisequal( *itr1, *itr2 )) {
4148 // add split lemma
4149 if (sendSplit(*itr1, *itr2, "CARD-SP"))
4150 {
4151 return;
4152 }
4153 }
4154 }
4155 }
4156 EqcInfo* ei = getOrMakeEqcInfo( lr, true );
4157 Trace("strings-card") << "Previous cardinality used for " << lr << " is " << ((int)ei->d_cardinality_lem_k.get()-1) << std::endl;
4158 if( int_k+1 > ei->d_cardinality_lem_k.get() ){
4159 Node k_node = NodeManager::currentNM()->mkConst( ::CVC4::Rational( int_k ) );
4160 //add cardinality lemma
4161 Node dist = NodeManager::currentNM()->mkNode( kind::DISTINCT, cols[i] );
4162 std::vector< Node > vec_node;
4163 vec_node.push_back( dist );
4164 for( std::vector< Node >::iterator itr1 = cols[i].begin();
4165 itr1 != cols[i].end(); ++itr1) {
4166 Node len = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, *itr1 );
4167 if( len!=lr ) {
4168 Node len_eq_lr = len.eqNode(lr);
4169 vec_node.push_back( len_eq_lr );
4170 }
4171 }
4172 Node len = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, cols[i][0] );
4173 Node cons = NodeManager::currentNM()->mkNode( kind::GEQ, len, k_node );
4174 cons = Rewriter::rewrite( cons );
4175 ei->d_cardinality_lem_k.set( int_k+1 );
4176 if( cons!=d_true ){
4177 sendInference( d_empty_vec, vec_node, cons, "CARDINALITY", true );
4178 return;
4179 }
4180 }
4181 }
4182 }
4183 }
4184 }
4185
4186 void TheoryStrings::getEquivalenceClasses( std::vector< Node >& eqcs ) {
4187 eq::EqClassesIterator eqcs_i = eq::EqClassesIterator( &d_equalityEngine );
4188 while( !eqcs_i.isFinished() ) {
4189 Node eqc = (*eqcs_i);
4190 //if eqc.getType is string
4191 if (eqc.getType().isString()) {
4192 eqcs.push_back( eqc );
4193 }
4194 ++eqcs_i;
4195 }
4196 }
4197
4198 void TheoryStrings::separateByLength(std::vector< Node >& n,
4199 std::vector< std::vector< Node > >& cols,
4200 std::vector< Node >& lts ) {
4201 unsigned leqc_counter = 0;
4202 std::map< Node, unsigned > eqc_to_leqc;
4203 std::map< unsigned, Node > leqc_to_eqc;
4204 std::map< unsigned, std::vector< Node > > eqc_to_strings;
4205 for( unsigned i=0; i<n.size(); i++ ) {
4206 Node eqc = n[i];
4207 Assert( d_equalityEngine.getRepresentative(eqc)==eqc );
4208 EqcInfo* ei = getOrMakeEqcInfo( eqc, false );
4209 Node lt = ei ? ei->d_length_term : Node::null();
4210 if( !lt.isNull() ){
4211 lt = NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, lt );
4212 Node r = d_equalityEngine.getRepresentative( lt );
4213 if( eqc_to_leqc.find( r )==eqc_to_leqc.end() ){
4214 eqc_to_leqc[r] = leqc_counter;
4215 leqc_to_eqc[leqc_counter] = r;
4216 leqc_counter++;
4217 }
4218 eqc_to_strings[ eqc_to_leqc[r] ].push_back( eqc );
4219 }else{
4220 eqc_to_strings[leqc_counter].push_back( eqc );
4221 leqc_counter++;
4222 }
4223 }
4224 for( std::map< unsigned, std::vector< Node > >::iterator it = eqc_to_strings.begin(); it != eqc_to_strings.end(); ++it ){
4225 cols.push_back( std::vector< Node >() );
4226 cols.back().insert( cols.back().end(), it->second.begin(), it->second.end() );
4227 lts.push_back( leqc_to_eqc[it->first] );
4228 }
4229 }
4230
4231 void TheoryStrings::printConcat( std::vector< Node >& n, const char * c ) {
4232 for( unsigned i=0; i<n.size(); i++ ){
4233 if( i>0 ) Trace(c) << " ++ ";
4234 Trace(c) << n[i];
4235 }
4236 }
4237
4238
4239
4240 //// Finite Model Finding
4241
4242 Node TheoryStrings::getNextDecisionRequest( unsigned& priority ) {
4243 if( options::stringFMF() && !d_conflict ){
4244 Node in_var_lsum = d_input_var_lsum.get();
4245 //Trace("strings-fmf-debug") << "Strings::FMF: Assertion Level = " << d_valuation.getAssertionLevel() << std::endl;
4246 //initialize the term we will minimize
4247 if( in_var_lsum.isNull() && !d_input_vars.empty() ){
4248 Trace("strings-fmf-debug") << "Input variables: ";
4249 std::vector< Node > ll;
4250 for(NodeSet::key_iterator itr = d_input_vars.key_begin();
4251 itr != d_input_vars.key_end(); ++itr) {
4252 Trace("strings-fmf-debug") << " " << (*itr) ;
4253 ll.push_back( NodeManager::currentNM()->mkNode( kind::STRING_LENGTH, *itr ) );
4254 }
4255 Trace("strings-fmf-debug") << std::endl;
4256 in_var_lsum = ll.size()==1 ? ll[0] : NodeManager::currentNM()->mkNode( kind::PLUS, ll );
4257 in_var_lsum = Rewriter::rewrite( in_var_lsum );
4258 d_input_var_lsum.set( in_var_lsum );
4259 }
4260 if( !in_var_lsum.isNull() ){
4261 //Trace("strings-fmf") << "Get next decision request." << std::endl;
4262 //check if we need to decide on something
4263 int decideCard = d_curr_cardinality.get();
4264 if( d_cardinality_lits.find( decideCard )!=d_cardinality_lits.end() ){
4265 bool value;
4266 Node cnode = d_cardinality_lits[ d_curr_cardinality.get() ];
4267 if( d_valuation.hasSatValue( cnode, value ) ) {
4268 if( !value ){
4269 d_curr_cardinality.set( d_curr_cardinality.get() + 1 );
4270 decideCard = d_curr_cardinality.get();
4271 Trace("strings-fmf-debug") << "Has false SAT value, increment and decide." << std::endl;
4272 }else{
4273 decideCard = -1;
4274 Trace("strings-fmf-debug") << "Has true SAT value, do not decide." << std::endl;
4275 }
4276 }else{
4277 Trace("strings-fmf-debug") << "No SAT value, decide." << std::endl;
4278 }
4279 }
4280 if( decideCard!=-1 ){
4281 if( d_cardinality_lits.find( decideCard )==d_cardinality_lits.end() ){
4282 Node lit = NodeManager::currentNM()->mkNode( kind::LEQ, in_var_lsum, NodeManager::currentNM()->mkConst( Rational( decideCard ) ) );
4283 lit = Rewriter::rewrite( lit );
4284 d_cardinality_lits[decideCard] = lit;
4285 Node lem = NodeManager::currentNM()->mkNode( kind::OR, lit, lit.negate() );
4286 Trace("strings-fmf") << "Strings::FMF: Add decision lemma " << lem << ", decideCard = " << decideCard << std::endl;
4287 d_out->lemma( lem );
4288 d_out->requirePhase( lit, true );
4289 }
4290 Node lit = d_cardinality_lits[ decideCard ];
4291 Trace("strings-fmf") << "Strings::FMF: Decide positive on " << lit << std::endl;
4292 priority = 1;
4293 return lit;
4294 }
4295 }
4296 }
4297 return Node::null();
4298 }
4299
4300 Node TheoryStrings::ppRewrite(TNode atom) {
4301 Trace("strings-ppr") << "TheoryStrings::ppRewrite " << atom << std::endl;
4302 if( !options::stringLazyPreproc() ){
4303 //eager preprocess here
4304 std::vector< Node > new_nodes;
4305 Node ret = d_preproc.processAssertion( atom, new_nodes );
4306 if( ret!=atom ){
4307 Trace("strings-ppr") << " rewrote " << atom << " -> " << ret << ", with " << new_nodes.size() << " lemmas." << std::endl;
4308 for( unsigned i=0; i<new_nodes.size(); i++ ){
4309 Trace("strings-ppr") << " lemma : " << new_nodes[i] << std::endl;
4310 d_out->lemma( new_nodes[i] );
4311 }
4312 return ret;
4313 }else{
4314 Assert( new_nodes.empty() );
4315 }
4316 }
4317 return atom;
4318 }
4319
4320 // Stats
4321 TheoryStrings::Statistics::Statistics():
4322 d_splits("theory::strings::NumOfSplitOnDemands", 0),
4323 d_eq_splits("theory::strings::NumOfEqSplits", 0),
4324 d_deq_splits("theory::strings::NumOfDiseqSplits", 0),
4325 d_loop_lemmas("theory::strings::NumOfLoops", 0),
4326 d_new_skolems("theory::strings::NumOfNewSkolems", 0)
4327 {
4328 smtStatisticsRegistry()->registerStat(&d_splits);
4329 smtStatisticsRegistry()->registerStat(&d_eq_splits);
4330 smtStatisticsRegistry()->registerStat(&d_deq_splits);
4331 smtStatisticsRegistry()->registerStat(&d_loop_lemmas);
4332 smtStatisticsRegistry()->registerStat(&d_new_skolems);
4333 }
4334
4335 TheoryStrings::Statistics::~Statistics(){
4336 smtStatisticsRegistry()->unregisterStat(&d_splits);
4337 smtStatisticsRegistry()->unregisterStat(&d_eq_splits);
4338 smtStatisticsRegistry()->unregisterStat(&d_deq_splits);
4339 smtStatisticsRegistry()->unregisterStat(&d_loop_lemmas);
4340 smtStatisticsRegistry()->unregisterStat(&d_new_skolems);
4341 }
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362 //// Regular Expressions
4363
4364
4365 unsigned TheoryStrings::getNumMemberships( Node n, bool isPos ) {
4366 if( isPos ){
4367 NodeIntMap::const_iterator it = d_pos_memberships.find( n );
4368 if( it!=d_pos_memberships.end() ){
4369 return (*it).second;
4370 }
4371 }else{
4372 NodeIntMap::const_iterator it = d_neg_memberships.find( n );
4373 if( it!=d_neg_memberships.end() ){
4374 return (*it).second;
4375 }
4376 }
4377 return 0;
4378 }
4379
4380 Node TheoryStrings::getMembership( Node n, bool isPos, unsigned i ) {
4381 return isPos ? d_pos_memberships_data[n][i] : d_neg_memberships_data[n][i];
4382 }
4383
4384 Node TheoryStrings::mkRegExpAntec(Node atom, Node ant) {
4385 if(d_regexp_ant.find(atom) == d_regexp_ant.end()) {
4386 return NodeManager::currentNM()->mkNode(kind::AND, ant, atom);
4387 } else {
4388 Node n = d_regexp_ant[atom];
4389 return NodeManager::currentNM()->mkNode(kind::AND, ant, n);
4390 }
4391 }
4392
4393 void TheoryStrings::checkMemberships() {
4394 //add the memberships
4395 std::vector<Node> mems = getExtTheory()->getActive(kind::STRING_IN_REGEXP);
4396 for (unsigned i = 0; i < mems.size(); i++) {
4397 Node n = mems[i];
4398 Assert( d_extf_info_tmp.find( n )!=d_extf_info_tmp.end() );
4399 if( d_extf_info_tmp[n].d_pol==1 || d_extf_info_tmp[n].d_pol==-1 ){
4400 bool pol = d_extf_info_tmp[n].d_pol==1;
4401 Trace("strings-process-debug") << " add membership : " << n << ", pol = " << pol << std::endl;
4402 addMembership( pol ? n : n.negate() );
4403 }else{
4404 Trace("strings-process-debug") << " irrelevant (non-asserted) membership : " << n << std::endl;
4405 }
4406 }
4407
4408 bool addedLemma = false;
4409 bool changed = false;
4410 std::vector< Node > processed;
4411 std::vector< Node > cprocessed;
4412
4413 Trace("regexp-debug") << "Checking Memberships ... " << std::endl;
4414 //if(options::stringEIT()) {
4415 //TODO: Opt for normal forms
4416 for( NodeIntMap::const_iterator itr_xr = d_pos_memberships.begin(); itr_xr != d_pos_memberships.end(); ++itr_xr ){
4417 bool spflag = false;
4418 Node x = (*itr_xr).first;
4419 Trace("regexp-debug") << "Checking Memberships for " << x << std::endl;
4420 if(d_inter_index.find(x) == d_inter_index.end()) {
4421 d_inter_index[x] = 0;
4422 }
4423 int cur_inter_idx = d_inter_index[x];
4424 unsigned n_pmem = (*itr_xr).second;
4425 Assert( getNumMemberships( x, true )==n_pmem );
4426 if( cur_inter_idx != (int)n_pmem ) {
4427 if( n_pmem == 1) {
4428 d_inter_cache[x] = getMembership( x, true, 0 );
4429 d_inter_index[x] = 1;
4430 Trace("regexp-debug") << "... only one choice " << std::endl;
4431 } else if(n_pmem > 1) {
4432 Node r;
4433 if(d_inter_cache.find(x) != d_inter_cache.end()) {
4434 r = d_inter_cache[x];
4435 }
4436 if(r.isNull()) {
4437 r = getMembership( x, true, 0 );
4438 cur_inter_idx = 1;
4439 }
4440
4441 unsigned k_start = cur_inter_idx;
4442 Trace("regexp-debug") << "... staring from : " << cur_inter_idx << ", we have " << n_pmem << std::endl;
4443 for(unsigned k = k_start; k<n_pmem; k++) {
4444 Node r2 = getMembership( x, true, k );
4445 r = d_regexp_opr.intersect(r, r2, spflag);
4446 if(spflag) {
4447 break;
4448 } else if(r == d_emptyRegexp) {
4449 std::vector< Node > vec_nodes;
4450 for( unsigned kk=0; kk<=k; kk++ ){
4451 Node rr = getMembership( x, true, kk );
4452 Node n = NodeManager::currentNM()->mkNode(kind::STRING_IN_REGEXP, x, rr);
4453 vec_nodes.push_back( n );
4454 }
4455 Node conc;
4456 sendInference(vec_nodes, conc, "INTERSECT CONFLICT", true);
4457 addedLemma = true;
4458 break;
4459 }
4460 if(d_conflict) {
4461 break;
4462 }
4463 }
4464 //updates
4465 if(!d_conflict && !spflag) {
4466 d_inter_cache[x] = r;
4467 d_inter_index[x] = (int)n_pmem;
4468 }
4469 }
4470 }
4471 }
4472 //}
4473
4474 Trace("regexp-debug") << "... No Intersect Conflict in Memberships, addedLemma: " << addedLemma << std::endl;
4475 if(!addedLemma) {
4476 NodeManager* nm = NodeManager::currentNM();
4477 for( unsigned i=0; i<d_regexp_memberships.size(); i++ ) {
4478 //check regular expression membership
4479 Node assertion = d_regexp_memberships[i];
4480 Trace("regexp-debug") << "Check : " << assertion << " " << (d_regexp_ucached.find(assertion) == d_regexp_ucached.end()) << " " << (d_regexp_ccached.find(assertion) == d_regexp_ccached.end()) << std::endl;
4481 if( d_regexp_ucached.find(assertion) == d_regexp_ucached.end()
4482 && d_regexp_ccached.find(assertion) == d_regexp_ccached.end() ) {
4483 Trace("strings-regexp") << "We have regular expression assertion : " << assertion << std::endl;
4484 Node atom = assertion.getKind()==kind::NOT ? assertion[0] : assertion;
4485 bool polarity = assertion.getKind()!=kind::NOT;
4486 bool flag = true;
4487 Node x = atom[0];
4488 Node r = atom[1];
4489 std::vector< Node > rnfexp;
4490
4491 if (!x.isConst())
4492 {
4493 x = getNormalString(x, rnfexp);
4494 changed = true;
4495 }
4496 if (!d_regexp_opr.checkConstRegExp(r))
4497 {
4498 r = getNormalSymRegExp(r, rnfexp);
4499 changed = true;
4500 }
4501 Trace("strings-regexp-nf") << "Term " << atom << " is normalized to "
4502 << x << " IN " << r << std::endl;
4503 if (changed)
4504 {
4505 Node tmp =
4506 Rewriter::rewrite(nm->mkNode(kind::STRING_IN_REGEXP, x, r));
4507 if (!polarity)
4508 {
4509 tmp = tmp.negate();
4510 }
4511 if (tmp == d_true)
4512 {
4513 d_regexp_ccached.insert(assertion);
4514 continue;
4515 }
4516 else if (tmp == d_false)
4517 {
4518 Node antec = mkRegExpAntec(assertion, mkExplain(rnfexp));
4519 Node conc = Node::null();
4520 sendLemma(antec, conc, "REGEXP NF Conflict");
4521 addedLemma = true;
4522 break;
4523 }
4524 }
4525
4526 if( polarity ) {
4527 flag = checkPDerivative(x, r, atom, addedLemma, rnfexp);
4528 } else {
4529 if(! options::stringExp()) {
4530 throw LogicException("Strings Incomplete (due to Negative Membership) by default, try --strings-exp option.");
4531 }
4532 }
4533 if(flag) {
4534 //check if the term is atomic
4535 Node xr = getRepresentative( x );
4536 //Trace("strings-regexp") << xr << " is rep of " << x << std::endl;
4537 //Assert( d_normal_forms.find( xr )!=d_normal_forms.end() );
4538 Trace("strings-regexp")
4539 << "Unroll/simplify membership of atomic term " << xr
4540 << std::endl;
4541 // if so, do simple unrolling
4542 std::vector<Node> nvec;
4543
4544 if (nvec.empty())
4545 {
4546 d_regexp_opr.simplify(atom, nvec, polarity);
4547 }
4548 Node antec = assertion;
4549 if (d_regexp_ant.find(assertion) != d_regexp_ant.end())
4550 {
4551 antec = d_regexp_ant[assertion];
4552 for (std::vector<Node>::const_iterator itr = nvec.begin();
4553 itr < nvec.end();
4554 itr++)
4555 {
4556 if (itr->getKind() == kind::STRING_IN_REGEXP)
4557 {
4558 if (d_regexp_ant.find(*itr) == d_regexp_ant.end())
4559 {
4560 d_regexp_ant[*itr] = antec;
4561 }
4562 }
4563 }
4564 }
4565 antec = NodeManager::currentNM()->mkNode(
4566 kind::AND, antec, mkExplain(rnfexp));
4567 Node conc = nvec.size() == 1
4568 ? nvec[0]
4569 : NodeManager::currentNM()->mkNode(kind::AND, nvec);
4570 conc = Rewriter::rewrite(conc);
4571 sendLemma(antec, conc, "REGEXP_Unfold");
4572 addedLemma = true;
4573 if (changed)
4574 {
4575 cprocessed.push_back(assertion);
4576 }
4577 else
4578 {
4579 processed.push_back(assertion);
4580 }
4581 // d_regexp_ucached[assertion] = true;
4582 }
4583 }
4584 if(d_conflict) {
4585 break;
4586 }
4587 }
4588 }
4589 if( addedLemma ) {
4590 if( !d_conflict ){
4591 for( unsigned i=0; i<processed.size(); i++ ) {
4592 Trace("strings-regexp") << "...add " << processed[i] << " to u-cache." << std::endl;
4593 d_regexp_ucached.insert(processed[i]);
4594 }
4595 for( unsigned i=0; i<cprocessed.size(); i++ ) {
4596 Trace("strings-regexp") << "...add " << cprocessed[i] << " to c-cache." << std::endl;
4597 d_regexp_ccached.insert(cprocessed[i]);
4598 }
4599 }
4600 }
4601 }
4602
4603 bool TheoryStrings::checkPDerivative( Node x, Node r, Node atom, bool &addedLemma, std::vector< Node > &nf_exp ) {
4604
4605 Node antnf = mkExplain(nf_exp);
4606
4607 if(areEqual(x, d_emptyString)) {
4608 Node exp;
4609 switch(d_regexp_opr.delta(r, exp)) {
4610 case 0: {
4611 Node antec = mkRegExpAntec(atom, x.eqNode(d_emptyString));
4612 antec = NodeManager::currentNM()->mkNode(kind::AND, antec, antnf);
4613 sendLemma(antec, exp, "RegExp Delta");
4614 addedLemma = true;
4615 d_regexp_ccached.insert(atom);
4616 return false;
4617 }
4618 case 1: {
4619 d_regexp_ccached.insert(atom);
4620 break;
4621 }
4622 case 2: {
4623 Node antec = mkRegExpAntec(atom, x.eqNode(d_emptyString));
4624 antec = NodeManager::currentNM()->mkNode(kind::AND, antec, antnf);
4625 Node conc = Node::null();
4626 sendLemma(antec, conc, "RegExp Delta CONFLICT");
4627 addedLemma = true;
4628 d_regexp_ccached.insert(atom);
4629 return false;
4630 }
4631 default:
4632 //Impossible
4633 break;
4634 }
4635 } else {
4636 /*Node xr = getRepresentative( x );
4637 if(x != xr) {
4638 Node n = NodeManager::currentNM()->mkNode(kind::STRING_IN_REGEXP, xr, r);
4639 Node nn = Rewriter::rewrite( n );
4640 if(nn == d_true) {
4641 d_regexp_ccached.insert(atom);
4642 return false;
4643 } else if(nn == d_false) {
4644 Node antec = mkRegExpAntec(atom, x.eqNode(xr));
4645 Node conc = Node::null();
4646 sendLemma(antec, conc, "RegExp Delta CONFLICT");
4647 addedLemma = true;
4648 d_regexp_ccached.insert(atom);
4649 return false;
4650 }
4651 }*/
4652 Node sREant = mkRegExpAntec(atom, d_true);
4653 sREant = NodeManager::currentNM()->mkNode(kind::AND, sREant, antnf);
4654 if(deriveRegExp( x, r, sREant )) {
4655 addedLemma = true;
4656 d_regexp_ccached.insert(atom);
4657 return false;
4658 }
4659 }
4660 return true;
4661 }
4662
4663 CVC4::String TheoryStrings::getHeadConst( Node x ) {
4664 if( x.isConst() ) {
4665 return x.getConst< String >();
4666 } else if( x.getKind() == kind::STRING_CONCAT ) {
4667 if( x[0].isConst() ) {
4668 return x[0].getConst< String >();
4669 } else {
4670 return d_emptyString.getConst< String >();
4671 }
4672 } else {
4673 return d_emptyString.getConst< String >();
4674 }
4675 }
4676
4677 bool TheoryStrings::deriveRegExp( Node x, Node r, Node ant ) {
4678 // TODO cstr in vre
4679 Assert(x != d_emptyString);
4680 Trace("regexp-derive") << "TheoryStrings::deriveRegExp: x=" << x << ", r= " << r << std::endl;
4681 //if(x.isConst()) {
4682 // Node n = NodeManager::currentNM()->mkNode( kind::STRING_IN_REGEXP, x, r );
4683 // Node r = Rewriter::rewrite( n );
4684 // if(n != r) {
4685 // sendLemma(ant, r, "REGEXP REWRITE");
4686 // return true;
4687 // }
4688 //}
4689 CVC4::String s = getHeadConst( x );
4690 if( !s.isEmptyString() && d_regexp_opr.checkConstRegExp( r ) ) {
4691 Node conc = Node::null();
4692 Node dc = r;
4693 bool flag = true;
4694 for(unsigned i=0; i<s.size(); ++i) {
4695 CVC4::String c = s.substr(i, 1);
4696 Node dc2;
4697 int rt = d_regexp_opr.derivativeS(dc, c, dc2);
4698 dc = dc2;
4699 if(rt == 0) {
4700 //TODO
4701 } else if(rt == 2) {
4702 // CONFLICT
4703 flag = false;
4704 break;
4705 }
4706 }
4707 // send lemma
4708 if(flag) {
4709 if(x.isConst()) {
4710 Assert(false, "Impossible: TheoryStrings::deriveRegExp: const string in const regular expression.");
4711 return false;
4712 } else {
4713 Assert( x.getKind() == kind::STRING_CONCAT );
4714 std::vector< Node > vec_nodes;
4715 for(unsigned int i=1; i<x.getNumChildren(); ++i ) {
4716 vec_nodes.push_back( x[i] );
4717 }
4718 Node left = mkConcat( vec_nodes );
4719 left = Rewriter::rewrite( left );
4720 conc = NodeManager::currentNM()->mkNode( kind::STRING_IN_REGEXP, left, dc );
4721
4722 /*std::vector< Node > sdc;
4723 d_regexp_opr.simplify(conc, sdc, true);
4724 if(sdc.size() == 1) {
4725 conc = sdc[0];
4726 } else {
4727 conc = Rewriter::rewrite(NodeManager::currentNM()->mkNode(kind::AND, conc));
4728 }*/
4729 }
4730 }
4731 sendLemma(ant, conc, "RegExp-Derive");
4732 return true;
4733 } else {
4734 return false;
4735 }
4736 }
4737
4738 void TheoryStrings::addMembership(Node assertion) {
4739 bool polarity = assertion.getKind() != kind::NOT;
4740 TNode atom = polarity ? assertion : assertion[0];
4741 Node x = atom[0];
4742 Node r = atom[1];
4743 if(polarity) {
4744 int index = 0;
4745 NodeIntMap::const_iterator it = d_pos_memberships.find( x );
4746 if( it!=d_nf_pairs.end() ){
4747 index = (*it).second;
4748 for( int k=0; k<index; k++ ){
4749 if( k<(int)d_pos_memberships_data[x].size() ){
4750 if( d_pos_memberships_data[x][k]==r ){
4751 return;
4752 }
4753 }else{
4754 break;
4755 }
4756 }
4757 }
4758 d_pos_memberships[x] = index + 1;
4759 if( index<(int)d_pos_memberships_data[x].size() ){
4760 d_pos_memberships_data[x][index] = r;
4761 }else{
4762 d_pos_memberships_data[x].push_back( r );
4763 }
4764 } else if(!options::stringIgnNegMembership()) {
4765 /*if(options::stringEIT() && d_regexp_opr.checkConstRegExp(r)) {
4766 int rt;
4767 Node r2 = d_regexp_opr.complement(r, rt);
4768 Node a = NodeManager::currentNM()->mkNode(kind::STRING_IN_REGEXP, x, r2);
4769 }*/
4770 int index = 0;
4771 NodeIntMap::const_iterator it = d_neg_memberships.find( x );
4772 if( it!=d_nf_pairs.end() ){
4773 index = (*it).second;
4774 for( int k=0; k<index; k++ ){
4775 if( k<(int)d_neg_memberships_data[x].size() ){
4776 if( d_neg_memberships_data[x][k]==r ){
4777 return;
4778 }
4779 }else{
4780 break;
4781 }
4782 }
4783 }
4784 d_neg_memberships[x] = index + 1;
4785 if( index<(int)d_neg_memberships_data[x].size() ){
4786 d_neg_memberships_data[x][index] = r;
4787 }else{
4788 d_neg_memberships_data[x].push_back( r );
4789 }
4790 }
4791 // old
4792 if(polarity || !options::stringIgnNegMembership()) {
4793 d_regexp_memberships.push_back( assertion );
4794 }
4795 }
4796
4797 Node TheoryStrings::getNormalString( Node x, std::vector< Node >& nf_exp ){
4798 if( !x.isConst() ){
4799 Node xr = getRepresentative( x );
4800 if( d_normal_forms.find( xr ) != d_normal_forms.end() ){
4801 Node ret = mkConcat( d_normal_forms[xr] );
4802 nf_exp.insert( nf_exp.end(), d_normal_forms_exp[xr].begin(), d_normal_forms_exp[xr].end() );
4803 addToExplanation( x, d_normal_forms_base[xr], nf_exp );
4804 Trace("strings-debug") << "Term: " << x << " has a normal form " << ret << std::endl;
4805 return ret;
4806 } else {
4807 if(x.getKind() == kind::STRING_CONCAT) {
4808 std::vector< Node > vec_nodes;
4809 for(unsigned i=0; i<x.getNumChildren(); i++) {
4810 Node nc = getNormalString( x[i], nf_exp );
4811 vec_nodes.push_back( nc );
4812 }
4813 return mkConcat( vec_nodes );
4814 }
4815 }
4816 }
4817 return x;
4818 }
4819
4820 Node TheoryStrings::getNormalSymRegExp(Node r, std::vector<Node> &nf_exp) {
4821 Node ret = r;
4822 switch( r.getKind() ) {
4823 case kind::REGEXP_EMPTY:
4824 case kind::REGEXP_SIGMA:
4825 break;
4826 case kind::STRING_TO_REGEXP: {
4827 if(!r[0].isConst()) {
4828 Node tmp = getNormalString( r[0], nf_exp );
4829 if(tmp != r[0]) {
4830 ret = NodeManager::currentNM()->mkNode(kind::STRING_TO_REGEXP, tmp);
4831 }
4832 }
4833 break;
4834 }
4835 case kind::REGEXP_CONCAT:
4836 case kind::REGEXP_UNION:
4837 case kind::REGEXP_INTER:
4838 case kind::REGEXP_STAR:
4839 {
4840 std::vector< Node > vec_nodes;
4841 for (const Node& cr : r)
4842 {
4843 vec_nodes.push_back(getNormalSymRegExp(cr, nf_exp));
4844 }
4845 ret = Rewriter::rewrite(
4846 NodeManager::currentNM()->mkNode(r.getKind(), vec_nodes));
4847 break;
4848 }
4849 //case kind::REGEXP_PLUS:
4850 //case kind::REGEXP_OPT:
4851 //case kind::REGEXP_RANGE:
4852 default: {
4853 Trace("strings-error") << "Unsupported term: " << r << " in normalization SymRegExp." << std::endl;
4854 Assert( false );
4855 //return Node::null();
4856 }
4857 }
4858 return ret;
4859 }
4860
4861 /** run the given inference step */
4862 void TheoryStrings::runInferStep(InferStep s, int effort)
4863 {
4864 Trace("strings-process") << "Run " << s;
4865 if (effort > 0)
4866 {
4867 Trace("strings-process") << ", effort = " << effort;
4868 }
4869 Trace("strings-process") << "..." << std::endl;
4870 switch (s)
4871 {
4872 case CHECK_INIT: checkInit(); break;
4873 case CHECK_CONST_EQC: checkConstantEquivalenceClasses(); break;
4874 case CHECK_EXTF_EVAL: checkExtfEval(effort); break;
4875 case CHECK_CYCLES: checkCycles(); break;
4876 case CHECK_FLAT_FORMS: checkFlatForms(); break;
4877 case CHECK_NORMAL_FORMS_EQ: checkNormalFormsEq(); break;
4878 case CHECK_NORMAL_FORMS_DEQ: checkNormalFormsDeq(); break;
4879 case CHECK_CODES: checkCodes(); break;
4880 case CHECK_LENGTH_EQC: checkLengthsEqc(); break;
4881 case CHECK_EXTF_REDUCTION: checkExtfReductions(effort); break;
4882 case CHECK_MEMBERSHIP: checkMemberships(); break;
4883 case CHECK_CARDINALITY: checkCardinality(); break;
4884 default: Unreachable(); break;
4885 }
4886 Trace("strings-process") << "Done " << s
4887 << ", addedFact = " << !d_pending.empty() << " "
4888 << !d_lemma_cache.empty()
4889 << ", d_conflict = " << d_conflict << std::endl;
4890 }
4891
4892 bool TheoryStrings::hasStrategyEffort(Effort e) const
4893 {
4894 return d_strat_steps.find(e) != d_strat_steps.end();
4895 }
4896
4897 void TheoryStrings::addStrategyStep(InferStep s, int effort, bool addBreak)
4898 {
4899 // must run check init first
4900 Assert((s == CHECK_INIT)==d_infer_steps.empty());
4901 // must use check cycles when using flat forms
4902 Assert(s != CHECK_FLAT_FORMS
4903 || std::find(d_infer_steps.begin(), d_infer_steps.end(), CHECK_CYCLES)
4904 != d_infer_steps.end());
4905 d_infer_steps.push_back(s);
4906 d_infer_step_effort.push_back(effort);
4907 if (addBreak)
4908 {
4909 d_infer_steps.push_back(BREAK);
4910 d_infer_step_effort.push_back(0);
4911 }
4912 }
4913
4914 void TheoryStrings::initializeStrategy()
4915 {
4916 // initialize the strategy if not already done so
4917 if (!d_strategy_init)
4918 {
4919 std::map<Effort, unsigned> step_begin;
4920 std::map<Effort, unsigned> step_end;
4921 d_strategy_init = true;
4922 // beginning indices
4923 step_begin[EFFORT_FULL] = 0;
4924 if (options::stringEager())
4925 {
4926 step_begin[EFFORT_STANDARD] = 0;
4927 }
4928 // add the inference steps
4929 addStrategyStep(CHECK_INIT);
4930 addStrategyStep(CHECK_CONST_EQC);
4931 addStrategyStep(CHECK_EXTF_EVAL, 0);
4932 addStrategyStep(CHECK_CYCLES);
4933 if (options::stringFlatForms())
4934 {
4935 addStrategyStep(CHECK_FLAT_FORMS);
4936 }
4937 addStrategyStep(CHECK_EXTF_REDUCTION, 1);
4938 if (options::stringEager())
4939 {
4940 // do only the above inferences at standard effort, if applicable
4941 step_end[EFFORT_STANDARD] = d_infer_steps.size() - 1;
4942 }
4943 addStrategyStep(CHECK_NORMAL_FORMS_EQ);
4944 addStrategyStep(CHECK_EXTF_EVAL, 1);
4945 if (!options::stringEagerLen())
4946 {
4947 addStrategyStep(CHECK_LENGTH_EQC);
4948 }
4949 addStrategyStep(CHECK_NORMAL_FORMS_DEQ);
4950 addStrategyStep(CHECK_CODES);
4951 if (options::stringEagerLen())
4952 {
4953 addStrategyStep(CHECK_LENGTH_EQC);
4954 }
4955 if (options::stringExp() && !options::stringGuessModel())
4956 {
4957 addStrategyStep(CHECK_EXTF_REDUCTION, 2);
4958 }
4959 addStrategyStep(CHECK_MEMBERSHIP);
4960 addStrategyStep(CHECK_CARDINALITY);
4961 step_end[EFFORT_FULL] = d_infer_steps.size() - 1;
4962 if (options::stringExp() && options::stringGuessModel())
4963 {
4964 step_begin[EFFORT_LAST_CALL] = d_infer_steps.size();
4965 // these two steps are run in parallel
4966 addStrategyStep(CHECK_EXTF_REDUCTION, 2, false);
4967 addStrategyStep(CHECK_EXTF_EVAL, 3);
4968 step_end[EFFORT_LAST_CALL] = d_infer_steps.size() - 1;
4969 }
4970 // set the beginning/ending ranges
4971 for (const std::pair<const Effort, unsigned>& it_begin : step_begin)
4972 {
4973 Effort e = it_begin.first;
4974 std::map<Effort, unsigned>::iterator it_end = step_end.find(e);
4975 Assert(it_end != step_end.end());
4976 d_strat_steps[e] =
4977 std::pair<unsigned, unsigned>(it_begin.second, it_end->second);
4978 }
4979 }
4980 }
4981
4982 void TheoryStrings::runStrategy(unsigned sbegin, unsigned send)
4983 {
4984 Trace("strings-process") << "----check, next round---" << std::endl;
4985 for (unsigned i = sbegin; i <= send; i++)
4986 {
4987 InferStep curr = d_infer_steps[i];
4988 if (curr == BREAK)
4989 {
4990 if (hasProcessed())
4991 {
4992 break;
4993 }
4994 }
4995 else
4996 {
4997 runInferStep(curr, d_infer_step_effort[i]);
4998 if (d_conflict)
4999 {
5000 break;
5001 }
5002 }
5003 }
5004 Trace("strings-process") << "----finished round---" << std::endl;
5005 }
5006
5007 }/* CVC4::theory::strings namespace */
5008 }/* CVC4::theory namespace */
5009 }/* CVC4 namespace */