Introducing internal commands for SyGuS commands (#2627)
[cvc5.git] / src / parser / smt2 / smt2.cpp
1 /********************* */
2 /*! \file smt2.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Andrew Reynolds, Kshitij Bansal, 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 Definitions of SMT2 constants.
13 **
14 ** Definitions of SMT2 constants.
15 **/
16 #include "parser/smt2/smt2.h"
17
18 #include "api/cvc4cpp.h"
19 #include "expr/type.h"
20 #include "options/options.h"
21 #include "parser/antlr_input.h"
22 #include "parser/parser.h"
23 #include "parser/smt1/smt1.h"
24 #include "parser/smt2/smt2_input.h"
25 #include "printer/sygus_print_callback.h"
26 #include "smt/command.h"
27 #include "util/bitvector.h"
28
29 #include <algorithm>
30
31 // ANTLR defines these, which is really bad!
32 #undef true
33 #undef false
34
35 namespace CVC4 {
36 namespace parser {
37
38 Smt2::Smt2(api::Solver* solver, Input* input, bool strictMode, bool parseOnly)
39 : Parser(solver, input, strictMode, parseOnly), d_logicSet(false)
40 {
41 if (!strictModeEnabled())
42 {
43 addTheory(Smt2::THEORY_CORE);
44 }
45 }
46
47 void Smt2::addArithmeticOperators() {
48 Parser::addOperator(kind::PLUS);
49 Parser::addOperator(kind::MINUS);
50 Parser::addOperator(kind::UMINUS);
51 Parser::addOperator(kind::MULT);
52 Parser::addOperator(kind::LT);
53 Parser::addOperator(kind::LEQ);
54 Parser::addOperator(kind::GT);
55 Parser::addOperator(kind::GEQ);
56
57 // NOTE: this operator is non-standard
58 addOperator(kind::POW, "^");
59 }
60
61 void Smt2::addTranscendentalOperators()
62 {
63 addOperator(kind::EXPONENTIAL, "exp");
64 addOperator(kind::SINE, "sin");
65 addOperator(kind::COSINE, "cos");
66 addOperator(kind::TANGENT, "tan");
67 addOperator(kind::COSECANT, "csc");
68 addOperator(kind::SECANT, "sec");
69 addOperator(kind::COTANGENT, "cot");
70 addOperator(kind::ARCSINE, "arcsin");
71 addOperator(kind::ARCCOSINE, "arccos");
72 addOperator(kind::ARCTANGENT, "arctan");
73 addOperator(kind::ARCCOSECANT, "arccsc");
74 addOperator(kind::ARCSECANT, "arcsec");
75 addOperator(kind::ARCCOTANGENT, "arccot");
76 addOperator(kind::SQRT, "sqrt");
77 }
78
79 void Smt2::addBitvectorOperators() {
80 addOperator(kind::BITVECTOR_CONCAT, "concat");
81 addOperator(kind::BITVECTOR_NOT, "bvnot");
82 addOperator(kind::BITVECTOR_AND, "bvand");
83 addOperator(kind::BITVECTOR_OR, "bvor");
84 addOperator(kind::BITVECTOR_NEG, "bvneg");
85 addOperator(kind::BITVECTOR_PLUS, "bvadd");
86 addOperator(kind::BITVECTOR_MULT, "bvmul");
87 addOperator(kind::BITVECTOR_UDIV, "bvudiv");
88 addOperator(kind::BITVECTOR_UREM, "bvurem");
89 addOperator(kind::BITVECTOR_SHL, "bvshl");
90 addOperator(kind::BITVECTOR_LSHR, "bvlshr");
91 addOperator(kind::BITVECTOR_ULT, "bvult");
92 addOperator(kind::BITVECTOR_NAND, "bvnand");
93 addOperator(kind::BITVECTOR_NOR, "bvnor");
94 addOperator(kind::BITVECTOR_XOR, "bvxor");
95 addOperator(kind::BITVECTOR_XNOR, "bvxnor");
96 addOperator(kind::BITVECTOR_COMP, "bvcomp");
97 addOperator(kind::BITVECTOR_SUB, "bvsub");
98 addOperator(kind::BITVECTOR_SDIV, "bvsdiv");
99 addOperator(kind::BITVECTOR_SREM, "bvsrem");
100 addOperator(kind::BITVECTOR_SMOD, "bvsmod");
101 addOperator(kind::BITVECTOR_ASHR, "bvashr");
102 addOperator(kind::BITVECTOR_ULE, "bvule");
103 addOperator(kind::BITVECTOR_UGT, "bvugt");
104 addOperator(kind::BITVECTOR_UGE, "bvuge");
105 addOperator(kind::BITVECTOR_SLT, "bvslt");
106 addOperator(kind::BITVECTOR_SLE, "bvsle");
107 addOperator(kind::BITVECTOR_SGT, "bvsgt");
108 addOperator(kind::BITVECTOR_SGE, "bvsge");
109 addOperator(kind::BITVECTOR_REDOR, "bvredor");
110 addOperator(kind::BITVECTOR_REDAND, "bvredand");
111
112 Parser::addOperator(kind::BITVECTOR_BITOF);
113 Parser::addOperator(kind::BITVECTOR_EXTRACT);
114 Parser::addOperator(kind::BITVECTOR_REPEAT);
115 Parser::addOperator(kind::BITVECTOR_ZERO_EXTEND);
116 Parser::addOperator(kind::BITVECTOR_SIGN_EXTEND);
117 Parser::addOperator(kind::BITVECTOR_ROTATE_LEFT);
118 Parser::addOperator(kind::BITVECTOR_ROTATE_RIGHT);
119
120 Parser::addOperator(kind::INT_TO_BITVECTOR);
121 Parser::addOperator(kind::BITVECTOR_TO_NAT);
122 }
123
124 void Smt2::addStringOperators() {
125 addOperator(kind::STRING_CONCAT, "str.++");
126 addOperator(kind::STRING_LENGTH, "str.len");
127 addOperator(kind::STRING_SUBSTR, "str.substr" );
128 addOperator(kind::STRING_STRCTN, "str.contains" );
129 addOperator(kind::STRING_CHARAT, "str.at" );
130 addOperator(kind::STRING_STRIDOF, "str.indexof" );
131 addOperator(kind::STRING_STRREPL, "str.replace" );
132 addOperator(kind::STRING_PREFIX, "str.prefixof" );
133 addOperator(kind::STRING_SUFFIX, "str.suffixof" );
134 // at the moment, we only use this syntax for smt2.6.1
135 if (getLanguage() == language::input::LANG_SMTLIB_V2_6_1)
136 {
137 addOperator(kind::STRING_ITOS, "str.from-int");
138 addOperator(kind::STRING_STOI, "str.to-int");
139 addOperator(kind::STRING_IN_REGEXP, "str.in-re");
140 addOperator(kind::STRING_TO_REGEXP, "str.to-re");
141 }
142 else
143 {
144 addOperator(kind::STRING_ITOS, "int.to.str");
145 addOperator(kind::STRING_STOI, "str.to.int");
146 addOperator(kind::STRING_IN_REGEXP, "str.in.re");
147 addOperator(kind::STRING_TO_REGEXP, "str.to.re");
148 }
149
150 addOperator(kind::REGEXP_CONCAT, "re.++");
151 addOperator(kind::REGEXP_UNION, "re.union");
152 addOperator(kind::REGEXP_INTER, "re.inter");
153 addOperator(kind::REGEXP_STAR, "re.*");
154 addOperator(kind::REGEXP_PLUS, "re.+");
155 addOperator(kind::REGEXP_OPT, "re.opt");
156 addOperator(kind::REGEXP_RANGE, "re.range");
157 addOperator(kind::REGEXP_LOOP, "re.loop");
158 addOperator(kind::STRING_CODE, "str.code");
159 addOperator(kind::STRING_LT, "str.<");
160 addOperator(kind::STRING_LEQ, "str.<=");
161 }
162
163 void Smt2::addFloatingPointOperators() {
164 addOperator(kind::FLOATINGPOINT_FP, "fp");
165 addOperator(kind::FLOATINGPOINT_EQ, "fp.eq");
166 addOperator(kind::FLOATINGPOINT_ABS, "fp.abs");
167 addOperator(kind::FLOATINGPOINT_NEG, "fp.neg");
168 addOperator(kind::FLOATINGPOINT_PLUS, "fp.add");
169 addOperator(kind::FLOATINGPOINT_SUB, "fp.sub");
170 addOperator(kind::FLOATINGPOINT_MULT, "fp.mul");
171 addOperator(kind::FLOATINGPOINT_DIV, "fp.div");
172 addOperator(kind::FLOATINGPOINT_FMA, "fp.fma");
173 addOperator(kind::FLOATINGPOINT_SQRT, "fp.sqrt");
174 addOperator(kind::FLOATINGPOINT_REM, "fp.rem");
175 addOperator(kind::FLOATINGPOINT_RTI, "fp.roundToIntegral");
176 addOperator(kind::FLOATINGPOINT_MIN, "fp.min");
177 addOperator(kind::FLOATINGPOINT_MAX, "fp.max");
178 addOperator(kind::FLOATINGPOINT_LEQ, "fp.leq");
179 addOperator(kind::FLOATINGPOINT_LT, "fp.lt");
180 addOperator(kind::FLOATINGPOINT_GEQ, "fp.geq");
181 addOperator(kind::FLOATINGPOINT_GT, "fp.gt");
182 addOperator(kind::FLOATINGPOINT_ISN, "fp.isNormal");
183 addOperator(kind::FLOATINGPOINT_ISSN, "fp.isSubnormal");
184 addOperator(kind::FLOATINGPOINT_ISZ, "fp.isZero");
185 addOperator(kind::FLOATINGPOINT_ISINF, "fp.isInfinite");
186 addOperator(kind::FLOATINGPOINT_ISNAN, "fp.isNaN");
187 addOperator(kind::FLOATINGPOINT_ISNEG, "fp.isNegative");
188 addOperator(kind::FLOATINGPOINT_ISPOS, "fp.isPositive");
189 addOperator(kind::FLOATINGPOINT_TO_REAL, "fp.to_real");
190
191 Parser::addOperator(kind::FLOATINGPOINT_TO_FP_GENERIC);
192 Parser::addOperator(kind::FLOATINGPOINT_TO_FP_IEEE_BITVECTOR);
193 Parser::addOperator(kind::FLOATINGPOINT_TO_FP_FLOATINGPOINT);
194 Parser::addOperator(kind::FLOATINGPOINT_TO_FP_REAL);
195 Parser::addOperator(kind::FLOATINGPOINT_TO_FP_SIGNED_BITVECTOR);
196 Parser::addOperator(kind::FLOATINGPOINT_TO_FP_UNSIGNED_BITVECTOR);
197 Parser::addOperator(kind::FLOATINGPOINT_TO_UBV);
198 Parser::addOperator(kind::FLOATINGPOINT_TO_SBV);
199 }
200
201 void Smt2::addSepOperators() {
202 addOperator(kind::SEP_STAR, "sep");
203 addOperator(kind::SEP_PTO, "pto");
204 addOperator(kind::SEP_WAND, "wand");
205 addOperator(kind::SEP_EMP, "emp");
206 Parser::addOperator(kind::SEP_STAR);
207 Parser::addOperator(kind::SEP_PTO);
208 Parser::addOperator(kind::SEP_WAND);
209 Parser::addOperator(kind::SEP_EMP);
210 }
211
212 void Smt2::addTheory(Theory theory) {
213 switch(theory) {
214 case THEORY_ARRAYS:
215 addOperator(kind::SELECT, "select");
216 addOperator(kind::STORE, "store");
217 break;
218
219 case THEORY_BITVECTORS:
220 addBitvectorOperators();
221 break;
222
223 case THEORY_CORE:
224 defineType("Bool", getExprManager()->booleanType());
225 defineVar("true", getExprManager()->mkConst(true));
226 defineVar("false", getExprManager()->mkConst(false));
227 Parser::addOperator(kind::AND);
228 Parser::addOperator(kind::DISTINCT);
229 Parser::addOperator(kind::EQUAL);
230 Parser::addOperator(kind::IMPLIES);
231 Parser::addOperator(kind::ITE);
232 Parser::addOperator(kind::NOT);
233 Parser::addOperator(kind::OR);
234 Parser::addOperator(kind::XOR);
235 break;
236
237 case THEORY_REALS_INTS:
238 defineType("Real", getExprManager()->realType());
239 Parser::addOperator(kind::DIVISION);
240 addOperator(kind::TO_INTEGER, "to_int");
241 addOperator(kind::IS_INTEGER, "is_int");
242 addOperator(kind::TO_REAL, "to_real");
243 // falling through on purpose, to add Ints part of Reals_Ints
244 case THEORY_INTS:
245 defineType("Int", getExprManager()->integerType());
246 addArithmeticOperators();
247 addOperator(kind::INTS_DIVISION, "div");
248 addOperator(kind::INTS_MODULUS, "mod");
249 addOperator(kind::ABS, "abs");
250 Parser::addOperator(kind::DIVISIBLE);
251 break;
252
253 case THEORY_REALS:
254 defineType("Real", getExprManager()->realType());
255 addArithmeticOperators();
256 Parser::addOperator(kind::DIVISION);
257 break;
258
259 case THEORY_TRANSCENDENTALS: addTranscendentalOperators(); break;
260
261 case THEORY_QUANTIFIERS:
262 break;
263
264 case THEORY_SETS:
265 addOperator(kind::UNION, "union");
266 addOperator(kind::INTERSECTION, "intersection");
267 addOperator(kind::SETMINUS, "setminus");
268 addOperator(kind::SUBSET, "subset");
269 addOperator(kind::MEMBER, "member");
270 addOperator(kind::SINGLETON, "singleton");
271 addOperator(kind::INSERT, "insert");
272 addOperator(kind::CARD, "card");
273 addOperator(kind::COMPLEMENT, "complement");
274 addOperator(kind::JOIN, "join");
275 addOperator(kind::PRODUCT, "product");
276 addOperator(kind::TRANSPOSE, "transpose");
277 addOperator(kind::TCLOSURE, "tclosure");
278 break;
279
280 case THEORY_DATATYPES:
281 {
282 const std::vector<Type> types;
283 defineType("Tuple", getExprManager()->mkTupleType(types));
284 Parser::addOperator(kind::APPLY_CONSTRUCTOR);
285 Parser::addOperator(kind::APPLY_TESTER);
286 Parser::addOperator(kind::APPLY_SELECTOR);
287 Parser::addOperator(kind::APPLY_SELECTOR_TOTAL);
288 break;
289 }
290
291 case THEORY_STRINGS:
292 defineType("String", getExprManager()->stringType());
293 defineType("RegLan", getExprManager()->regExpType());
294 defineType("Int", getExprManager()->integerType());
295 addStringOperators();
296 break;
297
298 case THEORY_UF:
299 Parser::addOperator(kind::APPLY_UF);
300 break;
301
302 case THEORY_FP:
303 defineType("RoundingMode", getExprManager()->roundingModeType());
304 defineType("Float16", getExprManager()->mkFloatingPointType(5, 11));
305 defineType("Float32", getExprManager()->mkFloatingPointType(8, 24));
306 defineType("Float64", getExprManager()->mkFloatingPointType(11, 53));
307 defineType("Float128", getExprManager()->mkFloatingPointType(15, 113));
308 addFloatingPointOperators();
309 break;
310
311 case THEORY_SEP:
312 addSepOperators();
313 break;
314
315 default:
316 std::stringstream ss;
317 ss << "internal error: unsupported theory " << theory;
318 throw ParserException(ss.str());
319 }
320 }
321
322 void Smt2::addOperator(Kind kind, const std::string& name) {
323 Debug("parser") << "Smt2::addOperator( " << kind << ", " << name << " )"
324 << std::endl;
325 Parser::addOperator(kind);
326 operatorKindMap[name] = kind;
327 }
328
329 Kind Smt2::getOperatorKind(const std::string& name) const {
330 // precondition: isOperatorEnabled(name)
331 return operatorKindMap.find(name)->second;
332 }
333
334 bool Smt2::isOperatorEnabled(const std::string& name) const {
335 return operatorKindMap.find(name) != operatorKindMap.end();
336 }
337
338 bool Smt2::isTheoryEnabled(Theory theory) const {
339 switch(theory) {
340 case THEORY_ARRAYS:
341 return d_logic.isTheoryEnabled(theory::THEORY_ARRAYS);
342 case THEORY_BITVECTORS:
343 return d_logic.isTheoryEnabled(theory::THEORY_BV);
344 case THEORY_CORE:
345 return true;
346 case THEORY_DATATYPES:
347 return d_logic.isTheoryEnabled(theory::THEORY_DATATYPES);
348 case THEORY_INTS:
349 return d_logic.isTheoryEnabled(theory::THEORY_ARITH) &&
350 d_logic.areIntegersUsed() && ( !d_logic.areRealsUsed() );
351 case THEORY_REALS:
352 return d_logic.isTheoryEnabled(theory::THEORY_ARITH) &&
353 ( !d_logic.areIntegersUsed() ) && d_logic.areRealsUsed();
354 case THEORY_REALS_INTS:
355 return d_logic.isTheoryEnabled(theory::THEORY_ARITH) &&
356 d_logic.areIntegersUsed() && d_logic.areRealsUsed();
357 case THEORY_QUANTIFIERS:
358 return d_logic.isQuantified();
359 case THEORY_SETS:
360 return d_logic.isTheoryEnabled(theory::THEORY_SETS);
361 case THEORY_STRINGS:
362 return d_logic.isTheoryEnabled(theory::THEORY_STRINGS);
363 case THEORY_UF:
364 return d_logic.isTheoryEnabled(theory::THEORY_UF);
365 case THEORY_FP:
366 return d_logic.isTheoryEnabled(theory::THEORY_FP);
367 case THEORY_SEP:
368 return d_logic.isTheoryEnabled(theory::THEORY_SEP);
369 default:
370 std::stringstream ss;
371 ss << "internal error: unsupported theory " << theory;
372 throw ParserException(ss.str());
373 }
374 }
375
376 bool Smt2::logicIsSet() {
377 return d_logicSet;
378 }
379
380 Expr Smt2::getExpressionForNameAndType(const std::string& name, Type t) {
381 if(sygus() && name[0]=='-' &&
382 name.find_first_not_of("0123456789", 1) == std::string::npos) {
383 //allow unary minus in sygus
384 return getExprManager()->mkConst(Rational(name));
385 }else if(isAbstractValue(name)) {
386 return mkAbstractValue(name);
387 }else{
388 return Parser::getExpressionForNameAndType(name, t);
389 }
390 }
391
392 Expr Smt2::mkDefineFunRec(
393 const std::string& fname,
394 const std::vector<std::pair<std::string, Type> >& sortedVarNames,
395 Type t,
396 std::vector<Expr>& flattenVars)
397 {
398 std::vector<Type> sorts;
399 for (const std::pair<std::string, CVC4::Type>& svn : sortedVarNames)
400 {
401 sorts.push_back(svn.second);
402 }
403
404 // make the flattened function type, add bound variables
405 // to flattenVars if the defined function was given a function return type.
406 Type ft = mkFlatFunctionType(sorts, t, flattenVars);
407
408 // allow overloading
409 return mkVar(fname, ft, ExprManager::VAR_FLAG_NONE, true);
410 }
411
412 void Smt2::pushDefineFunRecScope(
413 const std::vector<std::pair<std::string, Type> >& sortedVarNames,
414 Expr func,
415 const std::vector<Expr>& flattenVars,
416 std::vector<Expr>& bvs,
417 bool bindingLevel)
418 {
419 pushScope(bindingLevel);
420
421 // bound variables are those that are explicitly named in the preamble
422 // of the define-fun(s)-rec command, we define them here
423 for (const std::pair<std::string, CVC4::Type>& svn : sortedVarNames)
424 {
425 Expr v = mkBoundVar(svn.first, svn.second);
426 bvs.push_back(v);
427 }
428
429 bvs.insert(bvs.end(), flattenVars.begin(), flattenVars.end());
430 }
431
432 void Smt2::reset() {
433 d_logicSet = false;
434 d_logic = LogicInfo();
435 operatorKindMap.clear();
436 d_lastNamedTerm = std::pair<Expr, std::string>();
437 this->Parser::reset();
438
439 if( !strictModeEnabled() ) {
440 addTheory(Smt2::THEORY_CORE);
441 }
442 }
443
444 void Smt2::resetAssertions() {
445 // Remove all declarations except the ones at level 0.
446 while (this->scopeLevel() > 0) {
447 this->popScope();
448 }
449 }
450
451 void Smt2::setLogic(std::string name) {
452
453 if(sygus()) {
454 // non-smt2-standard sygus logic names go here (http://sygus.seas.upenn.edu/files/sygus.pdf Section 3.2)
455 if(name == "Arrays") {
456 name = "A";
457 }else if(name == "Reals") {
458 name = "LRA";
459 }
460 }
461
462 d_logicSet = true;
463 if(logicIsForced()) {
464 d_logic = getForcedLogic();
465 } else {
466 d_logic = name;
467 }
468
469 // if sygus is enabled, we must enable UF, datatypes, integer arithmetic and
470 // higher-order
471 if(sygus()) {
472 if (!d_logic.isQuantified())
473 {
474 warning("Logics in sygus are assumed to contain quantifiers.");
475 warning("Omit QF_ from the logic to avoid this warning.");
476 }
477 // get unlocked copy, modify, copy and relock
478 LogicInfo log(d_logic.getUnlockedCopy());
479 log.enableQuantifiers();
480 log.enableTheory(theory::THEORY_UF);
481 log.enableTheory(theory::THEORY_DATATYPES);
482 log.enableIntegers();
483 log.enableHigherOrder();
484 d_logic = log;
485 d_logic.lock();
486 }
487
488 // Core theory belongs to every logic
489 addTheory(THEORY_CORE);
490
491 if(d_logic.isTheoryEnabled(theory::THEORY_UF)) {
492 addTheory(THEORY_UF);
493 }
494
495 if(d_logic.isTheoryEnabled(theory::THEORY_ARITH)) {
496 if(d_logic.areIntegersUsed()) {
497 if(d_logic.areRealsUsed()) {
498 addTheory(THEORY_REALS_INTS);
499 } else {
500 addTheory(THEORY_INTS);
501 }
502 } else if(d_logic.areRealsUsed()) {
503 addTheory(THEORY_REALS);
504 }
505
506 if (d_logic.areTranscendentalsUsed())
507 {
508 addTheory(THEORY_TRANSCENDENTALS);
509 }
510 }
511
512 if(d_logic.isTheoryEnabled(theory::THEORY_ARRAYS)) {
513 addTheory(THEORY_ARRAYS);
514 }
515
516 if(d_logic.isTheoryEnabled(theory::THEORY_BV)) {
517 addTheory(THEORY_BITVECTORS);
518 }
519
520 if(d_logic.isTheoryEnabled(theory::THEORY_DATATYPES)) {
521 addTheory(THEORY_DATATYPES);
522 }
523
524 if(d_logic.isTheoryEnabled(theory::THEORY_SETS)) {
525 addTheory(THEORY_SETS);
526 }
527
528 if(d_logic.isTheoryEnabled(theory::THEORY_STRINGS)) {
529 addTheory(THEORY_STRINGS);
530 }
531
532 if(d_logic.isQuantified()) {
533 addTheory(THEORY_QUANTIFIERS);
534 }
535
536 if (d_logic.isTheoryEnabled(theory::THEORY_FP)) {
537 addTheory(THEORY_FP);
538 }
539
540 if (d_logic.isTheoryEnabled(theory::THEORY_SEP)) {
541 addTheory(THEORY_SEP);
542 }
543
544 }/* Smt2::setLogic() */
545
546 void Smt2::setInfo(const std::string& flag, const SExpr& sexpr) {
547 // TODO: ???
548 }
549
550 void Smt2::setOption(const std::string& flag, const SExpr& sexpr) {
551 // TODO: ???
552 }
553
554 void Smt2::checkThatLogicIsSet() {
555 if( ! logicIsSet() ) {
556 if(strictModeEnabled()) {
557 parseError("set-logic must appear before this point.");
558 } else {
559 warning("No set-logic command was given before this point.");
560 warning("CVC4 will make all theories available.");
561 warning("Consider setting a stricter logic for (likely) better performance.");
562 warning("To suppress this warning in the future use (set-logic ALL).");
563
564 setLogic("ALL");
565
566 Command* c = new SetBenchmarkLogicCommand("ALL");
567 c->setMuted(true);
568 preemptCommand(c);
569 }
570 }
571 }
572
573 /* The include are managed in the lexer but called in the parser */
574 // Inspired by http://www.antlr3.org/api/C/interop.html
575
576 static bool newInputStream(const std::string& filename, pANTLR3_LEXER lexer) {
577 Debug("parser") << "Including " << filename << std::endl;
578 // Create a new input stream and take advantage of built in stream stacking
579 // in C target runtime.
580 //
581 pANTLR3_INPUT_STREAM in;
582 #ifdef CVC4_ANTLR3_OLD_INPUT_STREAM
583 in = antlr3AsciiFileStreamNew((pANTLR3_UINT8) filename.c_str());
584 #else /* CVC4_ANTLR3_OLD_INPUT_STREAM */
585 in = antlr3FileStreamNew((pANTLR3_UINT8) filename.c_str(), ANTLR3_ENC_8BIT);
586 #endif /* CVC4_ANTLR3_OLD_INPUT_STREAM */
587 if( in == NULL ) {
588 Debug("parser") << "Can't open " << filename << std::endl;
589 return false;
590 }
591 // Same thing as the predefined PUSHSTREAM(in);
592 lexer->pushCharStream(lexer, in);
593 // restart it
594 //lexer->rec->state->tokenStartCharIndex = -10;
595 //lexer->emit(lexer);
596
597 // Note that the input stream is not closed when it EOFs, I don't bother
598 // to do it here, but it is up to you to track streams created like this
599 // and destroy them when the whole parse session is complete. Remember that you
600 // don't want to do this until all tokens have been manipulated all the way through
601 // your tree parsers etc as the token does not store the text it just refers
602 // back to the input stream and trying to get the text for it will abort if you
603 // close the input stream too early.
604
605 //TODO what said before
606 return true;
607 }
608
609 void Smt2::includeFile(const std::string& filename) {
610 // security for online version
611 if(!canIncludeFile()) {
612 parseError("include-file feature was disabled for this run.");
613 }
614
615 // Get the lexer
616 AntlrInput* ai = static_cast<AntlrInput*>(getInput());
617 pANTLR3_LEXER lexer = ai->getAntlr3Lexer();
618 // get the name of the current stream "Does it work inside an include?"
619 const std::string inputName = ai->getInputStreamName();
620
621 // Find the directory of the current input file
622 std::string path;
623 size_t pos = inputName.rfind('/');
624 if(pos != std::string::npos) {
625 path = std::string(inputName, 0, pos + 1);
626 }
627 path.append(filename);
628 if(!newInputStream(path, lexer)) {
629 parseError("Couldn't open include file `" + path + "'");
630 }
631 }
632
633 void Smt2::mkSygusConstantsForType( const Type& type, std::vector<CVC4::Expr>& ops ) {
634 if( type.isInteger() ){
635 ops.push_back(getExprManager()->mkConst(Rational(0)));
636 ops.push_back(getExprManager()->mkConst(Rational(1)));
637 }else if( type.isBitVector() ){
638 unsigned sz = ((BitVectorType)type).getSize();
639 BitVector bval0(sz, (unsigned int)0);
640 ops.push_back( getExprManager()->mkConst(bval0) );
641 BitVector bval1(sz, (unsigned int)1);
642 ops.push_back( getExprManager()->mkConst(bval1) );
643 }else if( type.isBoolean() ){
644 ops.push_back(getExprManager()->mkConst(true));
645 ops.push_back(getExprManager()->mkConst(false));
646 }
647 //TODO : others?
648 }
649
650 // This method adds N operators to ops[index], N names to cnames[index] and N type argument vectors to cargs[index] (where typically N=1)
651 // This method may also add new elements pairwise into datatypes/sorts/ops/cnames/cargs in the case of non-flat gterms.
652 void Smt2::processSygusGTerm( CVC4::SygusGTerm& sgt, int index,
653 std::vector< CVC4::Datatype >& datatypes,
654 std::vector< CVC4::Type>& sorts,
655 std::vector< std::vector<CVC4::Expr> >& ops,
656 std::vector< std::vector<std::string> >& cnames,
657 std::vector< std::vector< std::vector< CVC4::Type > > >& cargs,
658 std::vector< bool >& allow_const,
659 std::vector< std::vector< std::string > >& unresolved_gterm_sym,
660 std::vector<CVC4::Expr>& sygus_vars,
661 std::map< CVC4::Type, CVC4::Type >& sygus_to_builtin, std::map< CVC4::Type, CVC4::Expr >& sygus_to_builtin_expr,
662 CVC4::Type& ret, bool isNested ){
663 if( sgt.d_gterm_type==SygusGTerm::gterm_op || sgt.d_gterm_type==SygusGTerm::gterm_let ){
664 Debug("parser-sygus") << "Add " << sgt.d_expr << " to datatype " << index
665 << ", isLet = "
666 << (sgt.d_gterm_type == SygusGTerm::gterm_let)
667 << std::endl;
668 Kind oldKind;
669 Kind newKind = kind::UNDEFINED_KIND;
670 //convert to UMINUS if one child of MINUS
671 if( sgt.d_children.size()==1 && sgt.d_expr==getExprManager()->operatorOf(kind::MINUS) ){
672 oldKind = kind::MINUS;
673 newKind = kind::UMINUS;
674 }
675 if( newKind!=kind::UNDEFINED_KIND ){
676 Expr newExpr = getExprManager()->operatorOf(newKind);
677 Debug("parser-sygus") << "Replace " << sgt.d_expr << " with " << newExpr << std::endl;
678 sgt.d_expr = newExpr;
679 std::string oldName = kind::kindToString(oldKind);
680 std::string newName = kind::kindToString(newKind);
681 size_t pos = 0;
682 if((pos = sgt.d_name.find(oldName, pos)) != std::string::npos){
683 sgt.d_name.replace(pos, oldName.length(), newName);
684 }
685 }
686 ops[index].push_back( sgt.d_expr );
687 cnames[index].push_back( sgt.d_name );
688 cargs[index].push_back( std::vector< CVC4::Type >() );
689 for( unsigned i=0; i<sgt.d_children.size(); i++ ){
690 std::stringstream ss;
691 ss << datatypes[index].getName() << "_" << ops[index].size() << "_arg_" << i;
692 std::string sub_dname = ss.str();
693 //add datatype for child
694 Type null_type;
695 pushSygusDatatypeDef( null_type, sub_dname, datatypes, sorts, ops, cnames, cargs, allow_const, unresolved_gterm_sym );
696 int sub_dt_index = datatypes.size()-1;
697 //process child
698 Type sub_ret;
699 processSygusGTerm( sgt.d_children[i], sub_dt_index, datatypes, sorts, ops, cnames, cargs, allow_const, unresolved_gterm_sym,
700 sygus_vars, sygus_to_builtin, sygus_to_builtin_expr, sub_ret, true );
701 //process the nested gterm (either pop the last datatype, or flatten the argument)
702 Type tt = processSygusNestedGTerm( sub_dt_index, sub_dname, datatypes, sorts, ops, cnames, cargs, allow_const, unresolved_gterm_sym,
703 sygus_to_builtin, sygus_to_builtin_expr, sub_ret );
704 cargs[index].back().push_back(tt);
705 }
706 //if let, must create operator
707 if( sgt.d_gterm_type==SygusGTerm::gterm_let ){
708 processSygusLetConstructor( sgt.d_let_vars, index, datatypes, sorts, ops, cnames, cargs,
709 sygus_vars, sygus_to_builtin, sygus_to_builtin_expr );
710 }
711 }else if( sgt.d_gterm_type==SygusGTerm::gterm_constant ){
712 if( sgt.getNumChildren()!=0 ){
713 parseError("Bad syntax for Sygus Constant.");
714 }
715 std::vector< Expr > consts;
716 mkSygusConstantsForType( sgt.d_type, consts );
717 Debug("parser-sygus") << "...made " << consts.size() << " constants." << std::endl;
718 for( unsigned i=0; i<consts.size(); i++ ){
719 std::stringstream ss;
720 ss << consts[i];
721 Debug("parser-sygus") << "...add for constant " << ss.str() << std::endl;
722 ops[index].push_back( consts[i] );
723 cnames[index].push_back( ss.str() );
724 cargs[index].push_back( std::vector< CVC4::Type >() );
725 }
726 allow_const[index] = true;
727 }else if( sgt.d_gterm_type==SygusGTerm::gterm_variable || sgt.d_gterm_type==SygusGTerm::gterm_input_variable ){
728 if( sgt.getNumChildren()!=0 ){
729 parseError("Bad syntax for Sygus Variable.");
730 }
731 Debug("parser-sygus") << "...process " << sygus_vars.size() << " variables." << std::endl;
732 for( unsigned i=0; i<sygus_vars.size(); i++ ){
733 if( sygus_vars[i].getType()==sgt.d_type ){
734 std::stringstream ss;
735 ss << sygus_vars[i];
736 Debug("parser-sygus") << "...add for variable " << ss.str() << std::endl;
737 ops[index].push_back( sygus_vars[i] );
738 cnames[index].push_back( ss.str() );
739 cargs[index].push_back( std::vector< CVC4::Type >() );
740 }
741 }
742 }else if( sgt.d_gterm_type==SygusGTerm::gterm_nested_sort ){
743 ret = sgt.d_type;
744 }else if( sgt.d_gterm_type==SygusGTerm::gterm_unresolved ){
745 if( isNested ){
746 if( isUnresolvedType(sgt.d_name) ){
747 ret = getSort(sgt.d_name);
748 }else{
749 //nested, unresolved symbol...fail
750 std::stringstream ss;
751 ss << "Cannot handle nested unresolved symbol " << sgt.d_name << std::endl;
752 parseError(ss.str());
753 }
754 }else{
755 //will resolve when adding constructors
756 unresolved_gterm_sym[index].push_back(sgt.d_name);
757 }
758 }else if( sgt.d_gterm_type==SygusGTerm::gterm_ignore ){
759
760 }
761 }
762
763 bool Smt2::pushSygusDatatypeDef( Type t, std::string& dname,
764 std::vector< CVC4::Datatype >& datatypes,
765 std::vector< CVC4::Type>& sorts,
766 std::vector< std::vector<CVC4::Expr> >& ops,
767 std::vector< std::vector<std::string> >& cnames,
768 std::vector< std::vector< std::vector< CVC4::Type > > >& cargs,
769 std::vector< bool >& allow_const,
770 std::vector< std::vector< std::string > >& unresolved_gterm_sym ){
771 sorts.push_back(t);
772 datatypes.push_back(Datatype(dname));
773 ops.push_back(std::vector<Expr>());
774 cnames.push_back(std::vector<std::string>());
775 cargs.push_back(std::vector<std::vector<CVC4::Type> >());
776 allow_const.push_back(false);
777 unresolved_gterm_sym.push_back(std::vector< std::string >());
778 return true;
779 }
780
781 bool Smt2::popSygusDatatypeDef( std::vector< CVC4::Datatype >& datatypes,
782 std::vector< CVC4::Type>& sorts,
783 std::vector< std::vector<CVC4::Expr> >& ops,
784 std::vector< std::vector<std::string> >& cnames,
785 std::vector< std::vector< std::vector< CVC4::Type > > >& cargs,
786 std::vector< bool >& allow_const,
787 std::vector< std::vector< std::string > >& unresolved_gterm_sym ){
788 sorts.pop_back();
789 datatypes.pop_back();
790 ops.pop_back();
791 cnames.pop_back();
792 cargs.pop_back();
793 allow_const.pop_back();
794 unresolved_gterm_sym.pop_back();
795 return true;
796 }
797
798 Type Smt2::processSygusNestedGTerm( int sub_dt_index, std::string& sub_dname, std::vector< CVC4::Datatype >& datatypes,
799 std::vector< CVC4::Type>& sorts,
800 std::vector< std::vector<CVC4::Expr> >& ops,
801 std::vector< std::vector<std::string> >& cnames,
802 std::vector< std::vector< std::vector< CVC4::Type > > >& cargs,
803 std::vector< bool >& allow_const,
804 std::vector< std::vector< std::string > >& unresolved_gterm_sym,
805 std::map< CVC4::Type, CVC4::Type >& sygus_to_builtin,
806 std::map< CVC4::Type, CVC4::Expr >& sygus_to_builtin_expr, Type sub_ret ) {
807 Type t = sub_ret;
808 Debug("parser-sygus") << "Argument is ";
809 if( t.isNull() ){
810 //then, it is the datatype we constructed, which should have a single constructor
811 t = mkUnresolvedType(sub_dname);
812 Debug("parser-sygus") << "inline flattening of (auxiliary, local) datatype " << t << std::endl;
813 Debug("parser-sygus") << ": to compute type, construct ground term witnessing the grammar, #cons=" << cargs[sub_dt_index].size() << std::endl;
814 if( cargs[sub_dt_index].empty() ){
815 parseError(std::string("Internal error : datatype for nested gterm does not have a constructor."));
816 }
817 Expr sop = ops[sub_dt_index][0];
818 Type curr_t;
819 if( sop.getKind() != kind::BUILTIN && ( sop.isConst() || cargs[sub_dt_index][0].empty() ) ){
820 curr_t = sop.getType();
821 Debug("parser-sygus") << ": it is constant/0-arg cons " << sop << " with type " << sop.getType() << ", debug=" << sop.isConst() << " " << cargs[sub_dt_index][0].size() << std::endl;
822 // only cache if it is a singleton datatype (has unique expr)
823 if (ops[sub_dt_index].size() == 1)
824 {
825 sygus_to_builtin_expr[t] = sop;
826 // store that term sop has dedicated sygus type t
827 if (d_sygus_bound_var_type.find(sop) == d_sygus_bound_var_type.end())
828 {
829 d_sygus_bound_var_type[sop] = t;
830 }
831 }
832 }else{
833 std::vector< Expr > children;
834 if( sop.getKind() != kind::BUILTIN ){
835 children.push_back( sop );
836 }
837 for( unsigned i=0; i<cargs[sub_dt_index][0].size(); i++ ){
838 std::map< CVC4::Type, CVC4::Expr >::iterator it = sygus_to_builtin_expr.find( cargs[sub_dt_index][0][i] );
839 if( it==sygus_to_builtin_expr.end() ){
840 if( sygus_to_builtin.find( cargs[sub_dt_index][0][i] )==sygus_to_builtin.end() ){
841 std::stringstream ss;
842 ss << "Missing builtin type for type " << cargs[sub_dt_index][0][i] << "!" << std::endl;
843 ss << "Builtin types are currently : " << std::endl;
844 for( std::map< CVC4::Type, CVC4::Type >::iterator itb = sygus_to_builtin.begin(); itb != sygus_to_builtin.end(); ++itb ){
845 ss << " " << itb->first << " -> " << itb->second << std::endl;
846 }
847 parseError(ss.str());
848 }
849 Type bt = sygus_to_builtin[cargs[sub_dt_index][0][i]];
850 Debug("parser-sygus") << ": child " << i << " introduce type elem for " << cargs[sub_dt_index][0][i] << " " << bt << std::endl;
851 std::stringstream ss;
852 ss << t << "_x_" << i;
853 Expr bv = mkBoundVar(ss.str(), bt);
854 children.push_back( bv );
855 d_sygus_bound_var_type[bv] = cargs[sub_dt_index][0][i];
856 }else{
857 Debug("parser-sygus") << ": child " << i << " existing sygus to builtin expr : " << it->second << std::endl;
858 children.push_back( it->second );
859 }
860 }
861 Kind sk = sop.getKind() != kind::BUILTIN ? kind::APPLY : getExprManager()->operatorToKind(sop);
862 Debug("parser-sygus") << ": operator " << sop << " with " << sop.getKind() << " " << sk << std::endl;
863 Expr e = getExprManager()->mkExpr( sk, children );
864 Debug("parser-sygus") << ": constructed " << e << ", which has type " << e.getType() << std::endl;
865 curr_t = e.getType();
866 sygus_to_builtin_expr[t] = e;
867 }
868 sorts[sub_dt_index] = curr_t;
869 sygus_to_builtin[t] = curr_t;
870 }else{
871 Debug("parser-sygus") << "simple argument " << t << std::endl;
872 Debug("parser-sygus") << "...removing " << datatypes.back().getName() << std::endl;
873 //otherwise, datatype was unecessary
874 //pop argument datatype definition
875 popSygusDatatypeDef( datatypes, sorts, ops, cnames, cargs, allow_const, unresolved_gterm_sym );
876 }
877 return t;
878 }
879
880 void Smt2::processSygusLetConstructor( std::vector< CVC4::Expr >& let_vars,
881 int index,
882 std::vector< CVC4::Datatype >& datatypes,
883 std::vector< CVC4::Type>& sorts,
884 std::vector< std::vector<CVC4::Expr> >& ops,
885 std::vector< std::vector<std::string> >& cnames,
886 std::vector< std::vector< std::vector< CVC4::Type > > >& cargs,
887 std::vector<CVC4::Expr>& sygus_vars,
888 std::map< CVC4::Type, CVC4::Type >& sygus_to_builtin,
889 std::map< CVC4::Type, CVC4::Expr >& sygus_to_builtin_expr ) {
890 std::vector< CVC4::Expr > let_define_args;
891 Expr let_body;
892 int dindex = cargs[index].size()-1;
893 Debug("parser-sygus") << "Process let constructor for datatype " << datatypes[index].getName() << ", #subtypes = " << cargs[index][dindex].size() << std::endl;
894 for( unsigned i=0; i<cargs[index][dindex].size(); i++ ){
895 Debug("parser-sygus") << " " << i << " : " << cargs[index][dindex][i] << std::endl;
896 if( i+1==cargs[index][dindex].size() ){
897 std::map< CVC4::Type, CVC4::Expr >::iterator it = sygus_to_builtin_expr.find( cargs[index][dindex][i] );
898 if( it!=sygus_to_builtin_expr.end() ){
899 let_body = it->second;
900 }else{
901 std::stringstream ss;
902 ss << datatypes[index].getName() << "_body";
903 let_body = mkBoundVar(ss.str(), sygus_to_builtin[cargs[index][dindex][i]]);
904 d_sygus_bound_var_type[let_body] = cargs[index][dindex][i];
905 }
906 }
907 }
908 Debug("parser-sygus") << std::endl;
909 Debug("parser-sygus") << "Body is " << let_body << std::endl;
910 Debug("parser-sygus") << "# let vars = " << let_vars.size() << std::endl;
911 for( unsigned i=0; i<let_vars.size(); i++ ){
912 Debug("parser-sygus") << " let var " << i << " : " << let_vars[i] << " " << let_vars[i].getType() << std::endl;
913 let_define_args.push_back( let_vars[i] );
914 }
915 /*
916 Debug("parser-sygus") << "index = " << index << ", start index = " << start_index << ", #Current datatypes = " << datatypes.size() << std::endl;
917 for( unsigned i=start_index; i<datatypes.size(); i++ ){
918 Debug("parser-sygus") << " datatype " << i << " : " << datatypes[i].getName() << ", #cons = " << cargs[i].size() << std::endl;
919 if( !cargs[i].empty() ){
920 Debug("parser-sygus") << " operator 0 is " << ops[i][0] << std::endl;
921 Debug("parser-sygus") << " cons 0 has " << cargs[i][0].size() << " sub fields." << std::endl;
922 for( unsigned j=0; j<cargs[i][0].size(); j++ ){
923 Type bt = sygus_to_builtin[cargs[i][0][j]];
924 Debug("parser-sygus") << " cons 0, selector " << j << " : " << cargs[i][0][j] << " " << bt << std::endl;
925 }
926 }
927 }
928 */
929 //last argument is the return, pop
930 cargs[index][dindex].pop_back();
931 collectSygusLetArgs( let_body, cargs[index][dindex], let_define_args );
932
933 Debug("parser-sygus") << "Make define-fun with "
934 << cargs[index][dindex].size()
935 << " operator arguments and " << let_define_args.size()
936 << " provided arguments..." << std::endl;
937 if (cargs[index][dindex].size() != let_define_args.size())
938 {
939 std::stringstream ss;
940 ss << "Wrong number of let body terms." << std::endl;
941 parseError(ss.str());
942 }
943 std::vector<CVC4::Type> fsorts;
944 for( unsigned i=0; i<cargs[index][dindex].size(); i++ ){
945 Debug("parser-sygus") << " " << i << " : " << let_define_args[i] << " " << let_define_args[i].getType() << " " << cargs[index][dindex][i] << std::endl;
946 fsorts.push_back(let_define_args[i].getType());
947 }
948
949 Type ft = getExprManager()->mkFunctionType(fsorts, let_body.getType());
950 std::stringstream ss;
951 ss << datatypes[index].getName() << "_let";
952 Expr let_func = mkFunction(ss.str(), ft, ExprManager::VAR_FLAG_DEFINED);
953 d_sygus_defined_funs.push_back( let_func );
954 preemptCommand( new DefineFunctionCommand(ss.str(), let_func, let_define_args, let_body) );
955
956 ops[index].pop_back();
957 ops[index].push_back( let_func );
958 cnames[index].pop_back();
959 cnames[index].push_back(ss.str());
960
961 //mark function as let constructor
962 d_sygus_let_func_to_vars[let_func].insert( d_sygus_let_func_to_vars[let_func].end(), let_define_args.begin(), let_define_args.end() );
963 d_sygus_let_func_to_body[let_func] = let_body;
964 d_sygus_let_func_to_num_input_vars[let_func] = let_vars.size();
965 }
966
967
968 void Smt2::collectSygusLetArgs( CVC4::Expr e, std::vector< CVC4::Type >& sygusArgs, std::vector< CVC4::Expr >& builtinArgs ) {
969 if( e.getKind()==kind::BOUND_VARIABLE ){
970 if( std::find( builtinArgs.begin(), builtinArgs.end(), e )==builtinArgs.end() ){
971 builtinArgs.push_back( e );
972 sygusArgs.push_back( d_sygus_bound_var_type[e] );
973 if( d_sygus_bound_var_type[e].isNull() ){
974 std::stringstream ss;
975 ss << "While constructing body of let gterm, can't map " << e << " to sygus type." << std::endl;
976 parseError(ss.str());
977 }
978 }
979 }else{
980 for( unsigned i=0; i<e.getNumChildren(); i++ ){
981 collectSygusLetArgs( e[i], sygusArgs, builtinArgs );
982 }
983 }
984 }
985
986 void Smt2::setSygusStartIndex( std::string& fun, int startIndex,
987 std::vector< CVC4::Datatype >& datatypes,
988 std::vector< CVC4::Type>& sorts,
989 std::vector< std::vector<CVC4::Expr> >& ops ) {
990 if( startIndex>0 ){
991 CVC4::Datatype tmp_dt = datatypes[0];
992 Type tmp_sort = sorts[0];
993 std::vector< Expr > tmp_ops;
994 tmp_ops.insert( tmp_ops.end(), ops[0].begin(), ops[0].end() );
995 datatypes[0] = datatypes[startIndex];
996 sorts[0] = sorts[startIndex];
997 ops[0].clear();
998 ops[0].insert( ops[0].end(), ops[startIndex].begin(), ops[startIndex].end() );
999 datatypes[startIndex] = tmp_dt;
1000 sorts[startIndex] = tmp_sort;
1001 ops[startIndex].clear();
1002 ops[startIndex].insert( ops[startIndex].begin(), tmp_ops.begin(), tmp_ops.end() );
1003 }else if( startIndex<0 ){
1004 std::stringstream ss;
1005 ss << "warning: no symbol named Start for synth-fun " << fun << std::endl;
1006 warning(ss.str());
1007 }
1008 }
1009
1010 void Smt2::mkSygusDatatype( CVC4::Datatype& dt, std::vector<CVC4::Expr>& ops,
1011 std::vector<std::string>& cnames, std::vector< std::vector< CVC4::Type > >& cargs,
1012 std::vector<std::string>& unresolved_gterm_sym,
1013 std::map< CVC4::Type, CVC4::Type >& sygus_to_builtin ) {
1014 Debug("parser-sygus") << "Making sygus datatype " << dt.getName() << std::endl;
1015 Debug("parser-sygus") << " add constructors..." << std::endl;
1016
1017 Debug("parser-sygus") << "SMT2 sygus parser : Making constructors for sygus datatype " << dt.getName() << std::endl;
1018 Debug("parser-sygus") << " add constructors..." << std::endl;
1019 // size of cnames changes, this loop must check size
1020 for (unsigned i = 0; i < cnames.size(); i++)
1021 {
1022 bool is_dup = false;
1023 bool is_dup_op = false;
1024 for (unsigned j = 0; j < i; j++)
1025 {
1026 if( ops[i]==ops[j] ){
1027 is_dup_op = true;
1028 if( cargs[i].size()==cargs[j].size() ){
1029 is_dup = true;
1030 for( unsigned k=0; k<cargs[i].size(); k++ ){
1031 if( cargs[i][k]!=cargs[j][k] ){
1032 is_dup = false;
1033 break;
1034 }
1035 }
1036 }
1037 if( is_dup ){
1038 break;
1039 }
1040 }
1041 }
1042 Debug("parser-sygus") << "SYGUS CONS " << i << " : ";
1043 if( is_dup ){
1044 Debug("parser-sygus") << "--> Duplicate gterm : " << ops[i] << std::endl;
1045 ops.erase( ops.begin() + i, ops.begin() + i + 1 );
1046 cnames.erase( cnames.begin() + i, cnames.begin() + i + 1 );
1047 cargs.erase( cargs.begin() + i, cargs.begin() + i + 1 );
1048 i--;
1049 }
1050 else
1051 {
1052 std::shared_ptr<SygusPrintCallback> spc;
1053 if (is_dup_op)
1054 {
1055 Debug("parser-sygus") << "--> Duplicate gterm operator : " << ops[i]
1056 << std::endl;
1057 // make into define-fun
1058 std::vector<Type> ltypes;
1059 for (unsigned j = 0, size = cargs[i].size(); j < size; j++)
1060 {
1061 ltypes.push_back(sygus_to_builtin[cargs[i][j]]);
1062 }
1063 std::vector<Expr> largs;
1064 Expr lbvl = makeSygusBoundVarList(dt, i, ltypes, largs);
1065
1066 // make the let_body
1067 std::vector<Expr> children;
1068 if (ops[i].getKind() != kind::BUILTIN)
1069 {
1070 children.push_back(ops[i]);
1071 }
1072 children.insert(children.end(), largs.begin(), largs.end());
1073 Kind sk = ops[i].getKind() != kind::BUILTIN
1074 ? kind::APPLY
1075 : getExprManager()->operatorToKind(ops[i]);
1076 Expr body = getExprManager()->mkExpr(sk, children);
1077 // replace by lambda
1078 ops[i] = getExprManager()->mkExpr(kind::LAMBDA, lbvl, body);
1079 Debug("parser-sygus") << " ...replace op : " << ops[i] << std::endl;
1080 // callback prints as the expression
1081 spc = std::make_shared<printer::SygusExprPrintCallback>(body, largs);
1082 }
1083 else
1084 {
1085 std::map<Expr, Expr>::iterator it =
1086 d_sygus_let_func_to_body.find(ops[i]);
1087 if (it != d_sygus_let_func_to_body.end())
1088 {
1089 Debug("parser-sygus") << "--> Let expression " << ops[i] << std::endl;
1090 Expr let_body = it->second;
1091 std::vector<Expr> let_args = d_sygus_let_func_to_vars[ops[i]];
1092 unsigned let_num_input_args =
1093 d_sygus_let_func_to_num_input_vars[ops[i]];
1094 // the operator is just the body for the arguments
1095 std::vector<Type> ltypes;
1096 for (unsigned j = 0, size = let_args.size(); j < size; j++)
1097 {
1098 ltypes.push_back(let_args[j].getType());
1099 }
1100 std::vector<Expr> largs;
1101 Expr lbvl = makeSygusBoundVarList(dt, i, ltypes, largs);
1102 Expr sbody = let_body.substitute(let_args, largs);
1103 ops[i] = getExprManager()->mkExpr(kind::LAMBDA, lbvl, sbody);
1104 Debug("parser-sygus") << " ...replace op : " << ops[i] << std::endl;
1105 // callback prints as a let expression
1106 spc = std::make_shared<printer::SygusLetExprPrintCallback>(
1107 let_body, let_args, let_num_input_args);
1108 }
1109 else if (ops[i].getType().isBitVector() && ops[i].isConst())
1110 {
1111 Debug("parser-sygus") << "--> Bit-vector constant " << ops[i] << " ("
1112 << cnames[i] << ")" << std::endl;
1113 // Since there are multiple output formats for bit-vectors and
1114 // we are required by sygus standards to print in the exact input
1115 // format given by the user, we use a print callback to custom print
1116 // the given name.
1117 spc = std::make_shared<printer::SygusNamedPrintCallback>(cnames[i]);
1118 }
1119 else if (isDefinedFunction(ops[i]))
1120 {
1121 Debug("parser-sygus") << "--> Defined function " << ops[i]
1122 << std::endl;
1123 // turn f into (lammbda (x) (f x))
1124 // in a degenerate case, ops[i] may be a defined constant,
1125 // in which case we do not replace by a lambda.
1126 if (ops[i].getType().isFunction())
1127 {
1128 std::vector<Type> ftypes =
1129 static_cast<FunctionType>(ops[i].getType()).getArgTypes();
1130 std::vector<Expr> largs;
1131 Expr lbvl = makeSygusBoundVarList(dt, i, ftypes, largs);
1132 largs.insert(largs.begin(), ops[i]);
1133 Expr body = getExprManager()->mkExpr(kind::APPLY, largs);
1134 ops[i] = getExprManager()->mkExpr(kind::LAMBDA, lbvl, body);
1135 Debug("parser-sygus") << " ...replace op : " << ops[i]
1136 << std::endl;
1137 }
1138 else
1139 {
1140 ops[i] = getExprManager()->mkExpr(kind::APPLY, ops[i]);
1141 Debug("parser-sygus") << " ...replace op : " << ops[i]
1142 << std::endl;
1143 }
1144 // keep a callback to say it should be printed with the defined name
1145 spc = std::make_shared<printer::SygusNamedPrintCallback>(cnames[i]);
1146 }
1147 else
1148 {
1149 Debug("parser-sygus") << "--> Default case " << ops[i] << std::endl;
1150 }
1151 }
1152 // must rename to avoid duplication
1153 std::stringstream ss;
1154 ss << dt.getName() << "_" << i << "_" << cnames[i];
1155 cnames[i] = ss.str();
1156 Debug("parser-sygus") << " construct the datatype " << cnames[i] << "..."
1157 << std::endl;
1158 // add the sygus constructor
1159 dt.addSygusConstructor(ops[i], cnames[i], cargs[i], spc);
1160 Debug("parser-sygus") << " finished constructing the datatype"
1161 << std::endl;
1162 }
1163 }
1164
1165 Debug("parser-sygus") << " add constructors for unresolved symbols..." << std::endl;
1166 if( !unresolved_gterm_sym.empty() ){
1167 std::vector< Type > types;
1168 Debug("parser-sygus") << "...resolve " << unresolved_gterm_sym.size() << " symbols..." << std::endl;
1169 for( unsigned i=0; i<unresolved_gterm_sym.size(); i++ ){
1170 Debug("parser-sygus") << " resolve : " << unresolved_gterm_sym[i] << std::endl;
1171 if( isUnresolvedType(unresolved_gterm_sym[i]) ){
1172 Debug("parser-sygus") << " it is an unresolved type." << std::endl;
1173 Type t = getSort(unresolved_gterm_sym[i]);
1174 if( std::find( types.begin(), types.end(), t )==types.end() ){
1175 types.push_back( t );
1176 //identity element
1177 Type bt = dt.getSygusType();
1178 Debug("parser-sygus") << ": make identity function for " << bt << ", argument type " << t << std::endl;
1179
1180 std::stringstream ss;
1181 ss << t << "_x";
1182 Expr var = mkBoundVar(ss.str(), bt);
1183 std::vector<Expr> lchildren;
1184 lchildren.push_back(
1185 getExprManager()->mkExpr(kind::BOUND_VAR_LIST, var));
1186 lchildren.push_back(var);
1187 Expr id_op = getExprManager()->mkExpr(kind::LAMBDA, lchildren);
1188
1189 // empty sygus callback (should not be printed)
1190 std::shared_ptr<SygusPrintCallback> sepc =
1191 std::make_shared<printer::SygusEmptyPrintCallback>();
1192
1193 //make the sygus argument list
1194 std::vector< Type > id_carg;
1195 id_carg.push_back( t );
1196 dt.addSygusConstructor(id_op, unresolved_gterm_sym[i], id_carg, sepc);
1197
1198 //add to operators
1199 ops.push_back( id_op );
1200 }
1201 }else{
1202 Debug("parser-sygus") << " ignore. (likely a free let variable)" << std::endl;
1203 }
1204 }
1205 }
1206 }
1207
1208 Expr Smt2::makeSygusBoundVarList(Datatype& dt,
1209 unsigned i,
1210 const std::vector<Type>& ltypes,
1211 std::vector<Expr>& lvars)
1212 {
1213 for (unsigned j = 0, size = ltypes.size(); j < size; j++)
1214 {
1215 std::stringstream ss;
1216 ss << dt.getName() << "_x_" << i << "_" << j;
1217 Expr v = mkBoundVar(ss.str(), ltypes[j]);
1218 lvars.push_back(v);
1219 }
1220 return getExprManager()->mkExpr(kind::BOUND_VAR_LIST, lvars);
1221 }
1222
1223 InputLanguage Smt2::getLanguage() const
1224 {
1225 ExprManager* em = getExprManager();
1226 return em->getOptions().getInputLanguage();
1227 }
1228
1229 }/* CVC4::parser namespace */
1230 }/* CVC4 namespace */