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