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