Minor additions for sygus (#1419)
[cvc5.git] / src / expr / datatype.cpp
1 /********************* */
2 /*! \file datatype.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Andrew Reynolds, Morgan Deters, Tim King
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2017 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 A class representing a Datatype definition
13 **
14 ** A class representing a Datatype definition for the theory of
15 ** inductive datatypes.
16 **/
17 #include "expr/datatype.h"
18
19 #include <string>
20 #include <sstream>
21
22 #include "base/cvc4_assert.h"
23 #include "expr/attribute.h"
24 #include "expr/expr_manager.h"
25 #include "expr/expr_manager_scope.h"
26 #include "expr/matcher.h"
27 #include "expr/node.h"
28 #include "expr/node_manager.h"
29 #include "expr/type.h"
30 #include "options/set_language.h"
31 #include "options/datatypes_options.h"
32
33 using namespace std;
34
35 namespace CVC4 {
36
37 namespace expr {
38 namespace attr {
39 struct DatatypeIndexTag {};
40 struct DatatypeConsIndexTag {};
41 struct DatatypeFiniteTag {};
42 struct DatatypeFiniteComputedTag {};
43 struct DatatypeUFiniteTag {};
44 struct DatatypeUFiniteComputedTag {};
45 }/* CVC4::expr::attr namespace */
46 }/* CVC4::expr namespace */
47
48 typedef expr::Attribute<expr::attr::DatatypeIndexTag, uint64_t> DatatypeIndexAttr;
49 typedef expr::Attribute<expr::attr::DatatypeConsIndexTag, uint64_t> DatatypeConsIndexAttr;
50 typedef expr::Attribute<expr::attr::DatatypeFiniteTag, bool> DatatypeFiniteAttr;
51 typedef expr::Attribute<expr::attr::DatatypeFiniteComputedTag, bool> DatatypeFiniteComputedAttr;
52 typedef expr::Attribute<expr::attr::DatatypeUFiniteTag, bool> DatatypeUFiniteAttr;
53 typedef expr::Attribute<expr::attr::DatatypeUFiniteComputedTag, bool> DatatypeUFiniteComputedAttr;
54
55 Datatype::~Datatype(){
56 delete d_record;
57 }
58
59 const Datatype& Datatype::datatypeOf(Expr item) {
60 ExprManagerScope ems(item);
61 TypeNode t = Node::fromExpr(item).getType();
62 switch(t.getKind()) {
63 case kind::CONSTRUCTOR_TYPE:
64 return DatatypeType(t[t.getNumChildren() - 1].toType()).getDatatype();
65 case kind::SELECTOR_TYPE:
66 case kind::TESTER_TYPE:
67 return DatatypeType(t[0].toType()).getDatatype();
68 default:
69 Unhandled("arg must be a datatype constructor, selector, or tester");
70 }
71 }
72
73 size_t Datatype::indexOf(Expr item) {
74 ExprManagerScope ems(item);
75 PrettyCheckArgument(item.getType().isConstructor() ||
76 item.getType().isTester() ||
77 item.getType().isSelector(),
78 item,
79 "arg must be a datatype constructor, selector, or tester");
80 TNode n = Node::fromExpr(item);
81 if( item.getKind()==kind::APPLY_TYPE_ASCRIPTION ){
82 return indexOf( item[0] );
83 }else{
84 Assert(n.hasAttribute(DatatypeIndexAttr()));
85 return n.getAttribute(DatatypeIndexAttr());
86 }
87 }
88
89 size_t Datatype::cindexOf(Expr item) {
90 ExprManagerScope ems(item);
91 PrettyCheckArgument(item.getType().isSelector(),
92 item,
93 "arg must be a datatype selector");
94 TNode n = Node::fromExpr(item);
95 if( item.getKind()==kind::APPLY_TYPE_ASCRIPTION ){
96 return cindexOf( item[0] );
97 }else{
98 Assert(n.hasAttribute(DatatypeConsIndexAttr()));
99 return n.getAttribute(DatatypeConsIndexAttr());
100 }
101 }
102
103 void Datatype::resolve(ExprManager* em,
104 const std::map<std::string, DatatypeType>& resolutions,
105 const std::vector<Type>& placeholders,
106 const std::vector<Type>& replacements,
107 const std::vector< SortConstructorType >& paramTypes,
108 const std::vector< DatatypeType >& paramReplacements)
109 throw(IllegalArgumentException, DatatypeResolutionException) {
110
111 PrettyCheckArgument(em != NULL, em, "cannot resolve a Datatype with a NULL expression manager");
112 PrettyCheckArgument(!d_resolved, this, "cannot resolve a Datatype twice");
113 PrettyCheckArgument(resolutions.find(d_name) != resolutions.end(), resolutions,
114 "Datatype::resolve(): resolutions doesn't contain me!");
115 PrettyCheckArgument(placeholders.size() == replacements.size(), placeholders,
116 "placeholders and replacements must be the same size");
117 PrettyCheckArgument(paramTypes.size() == paramReplacements.size(), paramTypes,
118 "paramTypes and paramReplacements must be the same size");
119 PrettyCheckArgument(getNumConstructors() > 0, *this, "cannot resolve a Datatype that has no constructors");
120 DatatypeType self = (*resolutions.find(d_name)).second;
121 PrettyCheckArgument(&self.getDatatype() == this, resolutions, "Datatype::resolve(): resolutions doesn't contain me!");
122 d_resolved = true;
123 size_t index = 0;
124 for(std::vector<DatatypeConstructor>::iterator i = d_constructors.begin(), i_end = d_constructors.end(); i != i_end; ++i) {
125 (*i).resolve(em, self, resolutions, placeholders, replacements, paramTypes, paramReplacements, index);
126 Node::fromExpr((*i).d_constructor).setAttribute(DatatypeIndexAttr(), index);
127 Node::fromExpr((*i).d_tester).setAttribute(DatatypeIndexAttr(), index++);
128 }
129 d_self = self;
130
131 d_involvesExt = false;
132 d_involvesUt = false;
133 for(const_iterator i = begin(); i != end(); ++i) {
134 if( (*i).involvesExternalType() ){
135 d_involvesExt = true;
136 }
137 if( (*i).involvesUninterpretedType() ){
138 d_involvesUt = true;
139 }
140 }
141
142 if( d_isRecord ){
143 std::vector< std::pair<std::string, Type> > fields;
144 for( unsigned i=0; i<(*this)[0].getNumArgs(); i++ ){
145 fields.push_back( std::pair<std::string, Type>( (*this)[0][i].getName(), (*this)[0][i].getRangeType() ) );
146 }
147 d_record = new Record(fields);
148 }
149
150 //make the sygus evaluation function
151 if( isSygus() ){
152 PrettyCheckArgument(d_params.empty(), this, "sygus types cannot be parametric");
153 NodeManager* nm = NodeManager::fromExprManager(em);
154 std::string name = "eval_" + getName();
155 std::vector<TypeNode> evalType;
156 evalType.push_back(TypeNode::fromType(d_self));
157 if( !d_sygus_bvl.isNull() ){
158 for(size_t j = 0; j < d_sygus_bvl.getNumChildren(); ++j) {
159 evalType.push_back(TypeNode::fromType(d_sygus_bvl[j].getType()));
160 }
161 }
162 evalType.push_back(TypeNode::fromType(d_sygus_type));
163 TypeNode eval_func_type = nm->mkFunctionType(evalType);
164 d_sygus_eval = nm->mkSkolem(name, eval_func_type, "sygus evaluation function").toExpr();
165 }
166 }
167
168 void Datatype::addConstructor(const DatatypeConstructor& c) {
169 PrettyCheckArgument(!d_resolved, this,
170 "cannot add a constructor to a finalized Datatype");
171 d_constructors.push_back(c);
172 }
173
174
175 void Datatype::setSygus( Type st, Expr bvl, bool allow_const, bool allow_all ){
176 PrettyCheckArgument(!d_resolved, this,
177 "cannot set sygus type to a finalized Datatype");
178 d_sygus_type = st;
179 d_sygus_bvl = bvl;
180 d_sygus_allow_const = allow_const || allow_all;
181 d_sygus_allow_all = allow_all;
182 }
183
184 void Datatype::addSygusConstructor(Expr op,
185 std::string& cname,
186 std::vector<Type>& cargs,
187 std::shared_ptr<SygusPrintCallback> spc,
188 int weight)
189 {
190 Debug("dt-sygus") << "--> Add constructor " << cname << " to " << getName() << std::endl;
191 Debug("dt-sygus") << " sygus op : " << op << std::endl;
192 std::string name = getName() + "_" + cname;
193 std::string testerId("is-");
194 testerId.append(name);
195 unsigned cweight = weight >= 0 ? weight : (cargs.empty() ? 0 : 1);
196 DatatypeConstructor c(name, testerId, cweight);
197 c.setSygus(op, spc);
198 for( unsigned j=0; j<cargs.size(); j++ ){
199 Debug("parser-sygus-debug") << " arg " << j << " : " << cargs[j] << std::endl;
200 std::stringstream sname;
201 sname << name << "_" << j;
202 c.addArg(sname.str(), cargs[j]);
203 }
204 addConstructor(c);
205 }
206
207 void Datatype::setTuple() {
208 PrettyCheckArgument(!d_resolved, this, "cannot set tuple to a finalized Datatype");
209 d_isTuple = true;
210 }
211
212 void Datatype::setRecord() {
213 PrettyCheckArgument(!d_resolved, this, "cannot set record to a finalized Datatype");
214 d_isRecord = true;
215 }
216
217 Cardinality Datatype::getCardinality( Type t ) const throw(IllegalArgumentException) {
218 PrettyCheckArgument(isResolved(), this, "this datatype is not yet resolved");
219 Assert( t.isDatatype() && ((DatatypeType)t).getDatatype()==*this );
220 std::vector< Type > processing;
221 computeCardinality( t, processing );
222 return d_card;
223 }
224
225 Cardinality Datatype::getCardinality() const throw(IllegalArgumentException) {
226 PrettyCheckArgument(!isParametric(), this, "for getCardinality, this datatype cannot be parametric");
227 return getCardinality( d_self );
228 }
229
230 Cardinality Datatype::computeCardinality( Type t, std::vector< Type >& processing ) const throw(IllegalArgumentException){
231 PrettyCheckArgument(isResolved(), this, "this datatype is not yet resolved");
232 if( std::find( processing.begin(), processing.end(), d_self )!=processing.end() ){
233 d_card = Cardinality::INTEGERS;
234 }else{
235 processing.push_back( d_self );
236 Cardinality c = 0;
237 for(const_iterator i = begin(), i_end = end(); i != i_end; ++i) {
238 c += (*i).computeCardinality( t, processing );
239 }
240 d_card = c;
241 processing.pop_back();
242 }
243 return d_card;
244 }
245
246 bool Datatype::isRecursiveSingleton( Type t ) const throw(IllegalArgumentException) {
247 PrettyCheckArgument(isResolved(), this, "this datatype is not yet resolved");
248 Assert( t.isDatatype() && ((DatatypeType)t).getDatatype()==*this );
249 if( d_card_rec_singleton.find( t )==d_card_rec_singleton.end() ){
250 if( isCodatatype() ){
251 Assert( d_card_u_assume[t].empty() );
252 std::vector< Type > processing;
253 if( computeCardinalityRecSingleton( t, processing, d_card_u_assume[t] ) ){
254 d_card_rec_singleton[t] = 1;
255 }else{
256 d_card_rec_singleton[t] = -1;
257 }
258 if( d_card_rec_singleton[t]==1 ){
259 Trace("dt-card") << "Datatype " << getName() << " is recursive singleton, dependent upon " << d_card_u_assume[t].size() << " uninterpreted sorts: " << std::endl;
260 for( unsigned i=0; i<d_card_u_assume[t].size(); i++ ){
261 Trace("dt-card") << " " << d_card_u_assume[t][i] << std::endl;
262 }
263 Trace("dt-card") << std::endl;
264 }
265 }else{
266 d_card_rec_singleton[t] = -1;
267 }
268 }
269 return d_card_rec_singleton[t]==1;
270 }
271
272 bool Datatype::isRecursiveSingleton() const throw(IllegalArgumentException) {
273 PrettyCheckArgument(!isParametric(), this, "for isRecursiveSingleton, this datatype cannot be parametric");
274 return isRecursiveSingleton( d_self );
275 }
276
277 unsigned Datatype::getNumRecursiveSingletonArgTypes( Type t ) const throw(IllegalArgumentException) {
278 Assert( d_card_rec_singleton.find( t )!=d_card_rec_singleton.end() );
279 Assert( isRecursiveSingleton( t ) );
280 return d_card_u_assume[t].size();
281 }
282
283 unsigned Datatype::getNumRecursiveSingletonArgTypes() const throw(IllegalArgumentException) {
284 PrettyCheckArgument(!isParametric(), this, "for getNumRecursiveSingletonArgTypes, this datatype cannot be parametric");
285 return getNumRecursiveSingletonArgTypes( d_self );
286 }
287
288 Type Datatype::getRecursiveSingletonArgType( Type t, unsigned i ) const throw(IllegalArgumentException) {
289 Assert( d_card_rec_singleton.find( t )!=d_card_rec_singleton.end() );
290 Assert( isRecursiveSingleton( t ) );
291 return d_card_u_assume[t][i];
292 }
293
294 Type Datatype::getRecursiveSingletonArgType( unsigned i ) const throw(IllegalArgumentException) {
295 PrettyCheckArgument(!isParametric(), this, "for getRecursiveSingletonArgType, this datatype cannot be parametric");
296 return getRecursiveSingletonArgType( d_self, i );
297 }
298
299 bool Datatype::computeCardinalityRecSingleton( Type t, std::vector< Type >& processing, std::vector< Type >& u_assume ) const throw(IllegalArgumentException){
300 if( std::find( processing.begin(), processing.end(), d_self )!=processing.end() ){
301 return true;
302 }else{
303 if( d_card_rec_singleton[t]==0 ){
304 //if not yet computed
305 if( d_constructors.size()==1 ){
306 bool success = false;
307 processing.push_back( d_self );
308 for(unsigned i = 0; i<d_constructors[0].getNumArgs(); i++ ) {
309 Type tc = ((SelectorType)d_constructors[0][i].getType()).getRangeType();
310 //if it is an uninterpreted sort, then we depend on it having cardinality one
311 if( tc.isSort() ){
312 if( std::find( u_assume.begin(), u_assume.end(), tc )==u_assume.end() ){
313 u_assume.push_back( tc );
314 }
315 //if it is a datatype, recurse
316 }else if( tc.isDatatype() ){
317 const Datatype & dt = ((DatatypeType)tc).getDatatype();
318 if( !dt.computeCardinalityRecSingleton( t, processing, u_assume ) ){
319 return false;
320 }else{
321 success = true;
322 }
323 //if it is a builtin type, it must have cardinality one
324 }else if( !tc.getCardinality().isOne() ){
325 return false;
326 }
327 }
328 processing.pop_back();
329 return success;
330 }else{
331 return false;
332 }
333 }else if( d_card_rec_singleton[t]==-1 ){
334 return false;
335 }else{
336 for( unsigned i=0; i<d_card_u_assume[t].size(); i++ ){
337 if( std::find( u_assume.begin(), u_assume.end(), d_card_u_assume[t][i] )==u_assume.end() ){
338 u_assume.push_back( d_card_u_assume[t][i] );
339 }
340 }
341 return true;
342 }
343 }
344 }
345
346 bool Datatype::isFinite( Type t ) const throw(IllegalArgumentException) {
347 PrettyCheckArgument(isResolved(), this, "this datatype is not yet resolved");
348 Assert( t.isDatatype() && ((DatatypeType)t).getDatatype()==*this );
349
350 // we're using some internals, so we have to set up this library context
351 ExprManagerScope ems(d_self);
352 TypeNode self = TypeNode::fromType(d_self);
353 // is this already in the cache ?
354 if(self.getAttribute(DatatypeFiniteComputedAttr())) {
355 return self.getAttribute(DatatypeFiniteAttr());
356 }
357 for(const_iterator i = begin(), i_end = end(); i != i_end; ++i) {
358 if(! (*i).isFinite( t )) {
359 self.setAttribute(DatatypeFiniteComputedAttr(), true);
360 self.setAttribute(DatatypeFiniteAttr(), false);
361 return false;
362 }
363 }
364 self.setAttribute(DatatypeFiniteComputedAttr(), true);
365 self.setAttribute(DatatypeFiniteAttr(), true);
366 return true;
367 }
368 bool Datatype::isFinite() const throw(IllegalArgumentException) {
369 PrettyCheckArgument(isResolved() && !isParametric(), this, "this datatype must be resolved and not parametric");
370 return isFinite( d_self );
371 }
372
373 bool Datatype::isInterpretedFinite( Type t ) const throw(IllegalArgumentException) {
374 PrettyCheckArgument(isResolved(), this, "this datatype is not yet resolved");
375 Assert( t.isDatatype() && ((DatatypeType)t).getDatatype()==*this );
376 // we're using some internals, so we have to set up this library context
377 ExprManagerScope ems(d_self);
378 TypeNode self = TypeNode::fromType(d_self);
379 // is this already in the cache ?
380 if(self.getAttribute(DatatypeUFiniteComputedAttr())) {
381 return self.getAttribute(DatatypeUFiniteAttr());
382 }
383 //start by assuming it is not
384 self.setAttribute(DatatypeUFiniteComputedAttr(), true);
385 self.setAttribute(DatatypeUFiniteAttr(), false);
386 for(const_iterator i = begin(), i_end = end(); i != i_end; ++i) {
387 if(! (*i).isInterpretedFinite( t )) {
388 return false;
389 }
390 }
391 self.setAttribute(DatatypeUFiniteComputedAttr(), true);
392 self.setAttribute(DatatypeUFiniteAttr(), true);
393 return true;
394 }
395 bool Datatype::isInterpretedFinite() const throw(IllegalArgumentException) {
396 PrettyCheckArgument(isResolved() && !isParametric(), this, "this datatype must be resolved and not parametric");
397 return isInterpretedFinite( d_self );
398 }
399
400 bool Datatype::isWellFounded() const throw(IllegalArgumentException) {
401 PrettyCheckArgument(isResolved(), this, "this datatype is not yet resolved");
402 if( d_well_founded==0 ){
403 // we're using some internals, so we have to set up this library context
404 ExprManagerScope ems(d_self);
405 std::vector< Type > processing;
406 if( computeWellFounded( processing ) ){
407 d_well_founded = 1;
408 }else{
409 d_well_founded = -1;
410 }
411 }
412 return d_well_founded==1;
413 }
414
415 bool Datatype::computeWellFounded( std::vector< Type >& processing ) const throw(IllegalArgumentException) {
416 PrettyCheckArgument(isResolved(), this, "this datatype is not yet resolved");
417 if( std::find( processing.begin(), processing.end(), d_self )!=processing.end() ){
418 return d_isCo;
419 }else{
420 processing.push_back( d_self );
421 for(const_iterator i = begin(), i_end = end(); i != i_end; ++i) {
422 if( (*i).computeWellFounded( processing ) ){
423 processing.pop_back();
424 return true;
425 }else{
426 Trace("dt-wf") << "Constructor " << (*i).getName() << " is not well-founded." << std::endl;
427 }
428 }
429 processing.pop_back();
430 Trace("dt-wf") << "Datatype " << getName() << " is not well-founded." << std::endl;
431 return false;
432 }
433 }
434
435 Expr Datatype::mkGroundTerm( Type t ) const throw(IllegalArgumentException) {
436 PrettyCheckArgument(isResolved(), this, "this datatype is not yet resolved");
437 ExprManagerScope ems(d_self);
438 Debug("datatypes") << "mkGroundTerm of type " << t << std::endl;
439 // is this already in the cache ?
440 std::map< Type, Expr >::iterator it = d_ground_term.find( t );
441 if( it != d_ground_term.end() ){
442 Debug("datatypes") << "\nin cache: " << d_self << " => " << it->second << std::endl;
443 return it->second;
444 } else {
445 std::vector< Type > processing;
446 Expr groundTerm = computeGroundTerm( t, processing );
447 if(!groundTerm.isNull() ) {
448 // we found a ground-term-constructing constructor!
449 d_ground_term[t] = groundTerm;
450 Debug("datatypes") << "constructed: " << getName() << " => " << groundTerm << std::endl;
451 }
452 if( groundTerm.isNull() ){
453 if( !d_isCo ){
454 // if we get all the way here, we aren't well-founded
455 IllegalArgument(*this, "datatype is not well-founded, cannot construct a ground term!");
456 }else{
457 return groundTerm;
458 }
459 }else{
460 return groundTerm;
461 }
462 }
463 }
464
465 Expr getSubtermWithType( Expr e, Type t, bool isTop ){
466 if( !isTop && e.getType()==t ){
467 return e;
468 }else{
469 for( unsigned i=0; i<e.getNumChildren(); i++ ){
470 Expr se = getSubtermWithType( e[i], t, false );
471 if( !se.isNull() ){
472 return se;
473 }
474 }
475 return Expr();
476 }
477 }
478
479 Expr Datatype::computeGroundTerm( Type t, std::vector< Type >& processing ) const throw(IllegalArgumentException) {
480 if( std::find( processing.begin(), processing.end(), t )==processing.end() ){
481 processing.push_back( t );
482 for( unsigned r=0; r<2; r++ ){
483 for(const_iterator i = begin(), i_end = end(); i != i_end; ++i) {
484 //do nullary constructors first
485 if( ((*i).getNumArgs()==0)==(r==0)){
486 Debug("datatypes") << "Try constructing for " << (*i).getName() << ", processing = " << processing.size() << std::endl;
487 Expr e = (*i).computeGroundTerm( t, processing, d_ground_term );
488 if( !e.isNull() ){
489 //must check subterms for the same type to avoid infinite loops in type enumeration
490 Expr se = getSubtermWithType( e, t, true );
491 if( !se.isNull() ){
492 Debug("datatypes") << "Take subterm " << se << std::endl;
493 e = se;
494 }
495 processing.pop_back();
496 return e;
497 }else{
498 Debug("datatypes") << "...failed." << std::endl;
499 }
500 }
501 }
502 }
503 processing.pop_back();
504 }else{
505 Debug("datatypes") << "...already processing " << t << " " << d_self << std::endl;
506 }
507 return Expr();
508 }
509
510 DatatypeType Datatype::getDatatypeType() const throw(IllegalArgumentException) {
511 PrettyCheckArgument(isResolved(), *this, "Datatype must be resolved to get its DatatypeType");
512 PrettyCheckArgument(!d_self.isNull(), *this);
513 return DatatypeType(d_self);
514 }
515
516 DatatypeType Datatype::getDatatypeType(const std::vector<Type>& params)
517 const throw(IllegalArgumentException) {
518 PrettyCheckArgument(isResolved(), *this, "Datatype must be resolved to get its DatatypeType");
519 PrettyCheckArgument(!d_self.isNull() && DatatypeType(d_self).isParametric(), this);
520 return DatatypeType(d_self).instantiate(params);
521 }
522
523 bool Datatype::operator==(const Datatype& other) const throw() {
524 // two datatypes are == iff the name is the same and they have
525 // exactly matching constructors (in the same order)
526
527 if(this == &other) {
528 return true;
529 }
530
531 if(isResolved() != other.isResolved()) {
532 return false;
533 }
534
535 if( d_name != other.d_name ||
536 getNumConstructors() != other.getNumConstructors() ) {
537 return false;
538 }
539 for(const_iterator i = begin(), j = other.begin(); i != end(); ++i, ++j) {
540 Assert(j != other.end());
541 // two constructors are == iff they have the same name, their
542 // constructors and testers are equal and they have exactly
543 // matching args (in the same order)
544 if((*i).getName() != (*j).getName() ||
545 (*i).getNumArgs() != (*j).getNumArgs()) {
546 return false;
547 }
548 // testing equivalence of constructors and testers is harder b/c
549 // this constructor might not be resolved yet; only compare them
550 // if they are both resolved
551 Assert(isResolved() == !(*i).d_constructor.isNull() &&
552 isResolved() == !(*i).d_tester.isNull() &&
553 (*i).d_constructor.isNull() == (*j).d_constructor.isNull() &&
554 (*i).d_tester.isNull() == (*j).d_tester.isNull());
555 if(!(*i).d_constructor.isNull() && (*i).d_constructor != (*j).d_constructor) {
556 return false;
557 }
558 if(!(*i).d_tester.isNull() && (*i).d_tester != (*j).d_tester) {
559 return false;
560 }
561 for(DatatypeConstructor::const_iterator k = (*i).begin(), l = (*j).begin(); k != (*i).end(); ++k, ++l) {
562 Assert(l != (*j).end());
563 if((*k).getName() != (*l).getName()) {
564 return false;
565 }
566 // testing equivalence of selectors is harder b/c args might not
567 // be resolved yet
568 Assert(isResolved() == (*k).isResolved() &&
569 (*k).isResolved() == (*l).isResolved());
570 if((*k).isResolved()) {
571 // both are resolved, so simply compare the selectors directly
572 if((*k).d_selector != (*l).d_selector) {
573 return false;
574 }
575 } else {
576 // neither is resolved, so compare their (possibly unresolved)
577 // types; we don't know if they'll be resolved the same way,
578 // so we can't ever say unresolved types are equal
579 if(!(*k).d_selector.isNull() && !(*l).d_selector.isNull()) {
580 if((*k).d_selector.getType() != (*l).d_selector.getType()) {
581 return false;
582 }
583 } else {
584 if((*k).isUnresolvedSelf() && (*l).isUnresolvedSelf()) {
585 // Fine, the selectors are equal if the rest of the
586 // enclosing datatypes are equal...
587 } else {
588 return false;
589 }
590 }
591 }
592 }
593 }
594 return true;
595 }
596
597 const DatatypeConstructor& Datatype::operator[](size_t index) const {
598 PrettyCheckArgument(index < getNumConstructors(), index, "index out of bounds");
599 return d_constructors[index];
600 }
601
602 const DatatypeConstructor& Datatype::operator[](std::string name) const {
603 for(const_iterator i = begin(); i != end(); ++i) {
604 if((*i).getName() == name) {
605 return *i;
606 }
607 }
608 IllegalArgument(name, "No such constructor `%s' of datatype `%s'", name.c_str(), d_name.c_str());
609 }
610
611
612 Expr Datatype::getSharedSelector( Type dtt, Type t, unsigned index ) const{
613 PrettyCheckArgument(isResolved(), this, "this datatype is not yet resolved");
614 std::map< Type, std::map< Type, std::map< unsigned, Expr > > >::iterator itd = d_shared_sel.find( dtt );
615 if( itd!=d_shared_sel.end() ){
616 std::map< Type, std::map< unsigned, Expr > >::iterator its = itd->second.find( t );
617 if( its!=itd->second.end() ){
618 std::map< unsigned, Expr >::iterator it = its->second.find( index );
619 if( it!=its->second.end() ){
620 return it->second;
621 }
622 }
623 }
624 //make the shared selector
625 Expr s;
626 NodeManager* nm = NodeManager::fromExprManager( d_self.getExprManager() );
627 std::stringstream ss;
628 ss << "sel_" << index;
629 s = nm->mkSkolem(ss.str(), nm->mkSelectorType(TypeNode::fromType(dtt), TypeNode::fromType(t)), "is a shared selector", NodeManager::SKOLEM_NO_NOTIFY).toExpr();
630 d_shared_sel[dtt][t][index] = s;
631 Trace("dt-shared-sel") << "Made " << s << " of type " << dtt << " -> " << t << std::endl;
632 return s;
633 }
634
635 Expr Datatype::getConstructor(std::string name) const {
636 return (*this)[name].getConstructor();
637 }
638
639 Type Datatype::getSygusType() const {
640 return d_sygus_type;
641 }
642
643 Expr Datatype::getSygusVarList() const {
644 return d_sygus_bvl;
645 }
646
647 bool Datatype::getSygusAllowConst() const {
648 return d_sygus_allow_const;
649 }
650
651 bool Datatype::getSygusAllowAll() const {
652 return d_sygus_allow_all;
653 }
654
655 Expr Datatype::getSygusEvaluationFunc() const {
656 return d_sygus_eval;
657 }
658
659 bool Datatype::involvesExternalType() const{
660 return d_involvesExt;
661 }
662
663 bool Datatype::involvesUninterpretedType() const{
664 return d_involvesUt;
665 }
666
667 void DatatypeConstructor::resolve(ExprManager* em, DatatypeType self,
668 const std::map<std::string, DatatypeType>& resolutions,
669 const std::vector<Type>& placeholders,
670 const std::vector<Type>& replacements,
671 const std::vector< SortConstructorType >& paramTypes,
672 const std::vector< DatatypeType >& paramReplacements, size_t cindex)
673 throw(IllegalArgumentException, DatatypeResolutionException) {
674
675 PrettyCheckArgument(em != NULL, em, "cannot resolve a Datatype with a NULL expression manager");
676 PrettyCheckArgument(!isResolved(),
677 "cannot resolve a Datatype constructor twice; "
678 "perhaps the same constructor was added twice, "
679 "or to two datatypes?");
680
681 // we're using some internals, so we have to set up this library context
682 ExprManagerScope ems(*em);
683
684 NodeManager* nm = NodeManager::fromExprManager(em);
685 TypeNode selfTypeNode = TypeNode::fromType(self);
686 size_t index = 0;
687 for(std::vector<DatatypeConstructorArg>::iterator i = d_args.begin(), i_end = d_args.end(); i != i_end; ++i) {
688 if((*i).d_selector.isNull()) {
689 // the unresolved type wasn't created here; do name resolution
690 string typeName = (*i).d_name.substr((*i).d_name.find('\0') + 1);
691 (*i).d_name.resize((*i).d_name.find('\0'));
692 if(typeName == "") {
693 (*i).d_selector = nm->mkSkolem((*i).d_name, nm->mkSelectorType(selfTypeNode, selfTypeNode), "is a selector", NodeManager::SKOLEM_EXACT_NAME | NodeManager::SKOLEM_NO_NOTIFY).toExpr();
694 } else {
695 map<string, DatatypeType>::const_iterator j = resolutions.find(typeName);
696 if(j == resolutions.end()) {
697 stringstream msg;
698 msg << "cannot resolve type \"" << typeName << "\" "
699 << "in selector \"" << (*i).d_name << "\" "
700 << "of constructor \"" << d_name << "\"";
701 throw DatatypeResolutionException(msg.str());
702 } else {
703 (*i).d_selector = nm->mkSkolem((*i).d_name, nm->mkSelectorType(selfTypeNode, TypeNode::fromType((*j).second)), "is a selector", NodeManager::SKOLEM_EXACT_NAME | NodeManager::SKOLEM_NO_NOTIFY).toExpr();
704 }
705 }
706 } else {
707 // the type for the selector already exists; may need
708 // complex-type substitution
709 Type range = (*i).d_selector.getType();
710 if(!placeholders.empty()) {
711 range = range.substitute(placeholders, replacements);
712 }
713 if(!paramTypes.empty() ) {
714 range = doParametricSubstitution( range, paramTypes, paramReplacements );
715 }
716 (*i).d_selector = nm->mkSkolem((*i).d_name, nm->mkSelectorType(selfTypeNode, TypeNode::fromType(range)), "is a selector", NodeManager::SKOLEM_EXACT_NAME | NodeManager::SKOLEM_NO_NOTIFY).toExpr();
717 }
718 Node::fromExpr((*i).d_selector).setAttribute(DatatypeConsIndexAttr(), cindex);
719 Node::fromExpr((*i).d_selector).setAttribute(DatatypeIndexAttr(), index++);
720 (*i).d_resolved = true;
721 }
722
723 Assert(index == getNumArgs());
724
725 // Set constructor/tester last, since DatatypeConstructor::isResolved()
726 // returns true when d_tester is not the null Expr. If something
727 // fails above, we want Constuctor::isResolved() to remain "false".
728 // Further, mkConstructorType() iterates over the selectors, so
729 // should get the results of any resolutions we did above.
730 d_tester = nm->mkSkolem(getTesterName(), nm->mkTesterType(selfTypeNode), "is a tester", NodeManager::SKOLEM_EXACT_NAME | NodeManager::SKOLEM_NO_NOTIFY).toExpr();
731 d_constructor = nm->mkSkolem(getName(), nm->mkConstructorType(*this, selfTypeNode), "is a constructor", NodeManager::SKOLEM_EXACT_NAME | NodeManager::SKOLEM_NO_NOTIFY).toExpr();
732 // associate constructor with all selectors
733 for(std::vector<DatatypeConstructorArg>::iterator i = d_args.begin(), i_end = d_args.end(); i != i_end; ++i) {
734 (*i).d_constructor = d_constructor;
735 }
736 }
737
738 Type DatatypeConstructor::doParametricSubstitution( Type range,
739 const std::vector< SortConstructorType >& paramTypes,
740 const std::vector< DatatypeType >& paramReplacements ) {
741 TypeNode typn = TypeNode::fromType( range );
742 if(typn.getNumChildren() == 0) {
743 return range;
744 } else {
745 std::vector< Type > origChildren;
746 std::vector< Type > children;
747 for(TypeNode::const_iterator i = typn.begin(), iend = typn.end();i != iend; ++i) {
748 origChildren.push_back( (*i).toType() );
749 children.push_back( doParametricSubstitution( (*i).toType(), paramTypes, paramReplacements ) );
750 }
751 for( unsigned i = 0; i < paramTypes.size(); ++i ) {
752 if( paramTypes[i].getArity() == origChildren.size() ) {
753 Type tn = paramTypes[i].instantiate( origChildren );
754 if( range == tn ) {
755 return paramReplacements[i].instantiate( children );
756 }
757 }
758 }
759 NodeBuilder<> nb(typn.getKind());
760 for( unsigned i = 0; i < children.size(); ++i ) {
761 nb << TypeNode::fromType( children[i] );
762 }
763 return nb.constructTypeNode().toType();
764 }
765 }
766
767 DatatypeConstructor::DatatypeConstructor(std::string name)
768 : // We don't want to introduce a new data member, because eventually
769 // we're going to be a constant stuffed inside a node. So we stow
770 // the tester name away inside the constructor name until
771 // resolution.
772 d_name(name + '\0' + "is_" + name), // default tester name is "is_FOO"
773 d_tester(),
774 d_args(),
775 d_sygus_pc(nullptr),
776 d_weight(1)
777 {
778 PrettyCheckArgument(name != "", name, "cannot construct a datatype constructor without a name");
779 }
780
781 DatatypeConstructor::DatatypeConstructor(std::string name,
782 std::string tester,
783 unsigned weight)
784 : // We don't want to introduce a new data member, because eventually
785 // we're going to be a constant stuffed inside a node. So we stow
786 // the tester name away inside the constructor name until
787 // resolution.
788 d_name(name + '\0' + tester),
789 d_tester(),
790 d_args(),
791 d_sygus_pc(nullptr),
792 d_weight(weight)
793 {
794 PrettyCheckArgument(name != "", name, "cannot construct a datatype constructor without a name");
795 PrettyCheckArgument(!tester.empty(), tester, "cannot construct a datatype constructor without a tester");
796 }
797
798 void DatatypeConstructor::setSygus(Expr op,
799 std::shared_ptr<SygusPrintCallback> spc)
800 {
801 PrettyCheckArgument(
802 !isResolved(), this, "cannot modify a finalized Datatype constructor");
803 d_sygus_op = op;
804 d_sygus_pc = spc;
805 }
806
807 void DatatypeConstructor::addArg(std::string selectorName, Type selectorType) {
808 // We don't want to introduce a new data member, because eventually
809 // we're going to be a constant stuffed inside a node. So we stow
810 // the selector type away inside a var until resolution (when we can
811 // create the proper selector type)
812 PrettyCheckArgument(!isResolved(), this, "cannot modify a finalized Datatype constructor");
813 PrettyCheckArgument(!selectorType.isNull(), selectorType, "cannot add a null selector type");
814
815 // we're using some internals, so we have to set up this library context
816 ExprManagerScope ems(selectorType);
817
818 Expr type = NodeManager::currentNM()->mkSkolem("unresolved_" + selectorName, TypeNode::fromType(selectorType), "is an unresolved selector type placeholder", NodeManager::SKOLEM_EXACT_NAME | NodeManager::SKOLEM_NO_NOTIFY).toExpr();
819 Debug("datatypes") << type << endl;
820 d_args.push_back(DatatypeConstructorArg(selectorName, type));
821 }
822
823 void DatatypeConstructor::addArg(std::string selectorName, DatatypeUnresolvedType selectorType) {
824 // We don't want to introduce a new data member, because eventually
825 // we're going to be a constant stuffed inside a node. So we stow
826 // the selector type away after a NUL in the name string until
827 // resolution (when we can create the proper selector type)
828 PrettyCheckArgument(!isResolved(), this, "cannot modify a finalized Datatype constructor");
829 PrettyCheckArgument(selectorType.getName() != "", selectorType, "cannot add a null selector type");
830 d_args.push_back(DatatypeConstructorArg(selectorName + '\0' + selectorType.getName(), Expr()));
831 }
832
833 void DatatypeConstructor::addArg(std::string selectorName, DatatypeSelfType) {
834 // We don't want to introduce a new data member, because eventually
835 // we're going to be a constant stuffed inside a node. So we mark
836 // the name string with a NUL to indicate that we have a
837 // self-selecting selector until resolution (when we can create the
838 // proper selector type)
839 PrettyCheckArgument(!isResolved(), this, "cannot modify a finalized Datatype constructor");
840 d_args.push_back(DatatypeConstructorArg(selectorName + '\0', Expr()));
841 }
842
843 std::string DatatypeConstructor::getName() const throw() {
844 return d_name.substr(0, d_name.find('\0'));
845 }
846
847 std::string DatatypeConstructor::getTesterName() const throw() {
848 return d_name.substr(d_name.find('\0') + 1);
849 }
850
851 Expr DatatypeConstructor::getConstructor() const {
852 PrettyCheckArgument(isResolved(), this, "this datatype constructor is not yet resolved");
853 return d_constructor;
854 }
855
856 Type DatatypeConstructor::getSpecializedConstructorType(Type returnType) const {
857 PrettyCheckArgument(isResolved(), this, "this datatype constructor is not yet resolved");
858 PrettyCheckArgument(returnType.isDatatype(), this, "cannot get specialized constructor type for non-datatype type");
859 ExprManagerScope ems(d_constructor);
860 const Datatype& dt = Datatype::datatypeOf(d_constructor);
861 PrettyCheckArgument(dt.isParametric(), this, "this datatype constructor is not parametric");
862 DatatypeType dtt = dt.getDatatypeType();
863 Matcher m(dtt);
864 m.doMatching( TypeNode::fromType(dtt), TypeNode::fromType(returnType) );
865 vector<Type> subst;
866 m.getMatches(subst);
867 vector<Type> params = dt.getParameters();
868 return d_constructor.getType().substitute(params, subst);
869 }
870
871 Expr DatatypeConstructor::getTester() const {
872 PrettyCheckArgument(isResolved(), this, "this datatype constructor is not yet resolved");
873 return d_tester;
874 }
875
876 Expr DatatypeConstructor::getSygusOp() const {
877 PrettyCheckArgument(isResolved(), this, "this datatype constructor is not yet resolved");
878 return d_sygus_op;
879 }
880
881 bool DatatypeConstructor::isSygusIdFunc() const {
882 PrettyCheckArgument(isResolved(), this, "this datatype constructor is not yet resolved");
883 return (d_sygus_op.getKind() == kind::LAMBDA
884 && d_sygus_op[0].getNumChildren() == 1
885 && d_sygus_op[0][0] == d_sygus_op[1]);
886 }
887
888 unsigned DatatypeConstructor::getWeight() const
889 {
890 PrettyCheckArgument(
891 isResolved(), this, "this datatype constructor is not yet resolved");
892 return d_weight;
893 }
894
895 std::shared_ptr<SygusPrintCallback> DatatypeConstructor::getSygusPrintCallback() const
896 {
897 PrettyCheckArgument(
898 isResolved(), this, "this datatype constructor is not yet resolved");
899 return d_sygus_pc;
900 }
901
902 Cardinality DatatypeConstructor::getCardinality( Type t ) const throw(IllegalArgumentException) {
903 PrettyCheckArgument(isResolved(), this, "this datatype constructor is not yet resolved");
904
905 Cardinality c = 1;
906
907 for(const_iterator i = begin(), i_end = end(); i != i_end; ++i) {
908 c *= SelectorType((*i).getSelector().getType()).getRangeType().getCardinality();
909 }
910
911 return c;
912 }
913
914 /** compute the cardinality of this datatype */
915 Cardinality DatatypeConstructor::computeCardinality( Type t, std::vector< Type >& processing ) const throw(IllegalArgumentException){
916 Cardinality c = 1;
917 std::vector< Type > instTypes;
918 std::vector< Type > paramTypes;
919 if( DatatypeType(t).isParametric() ){
920 paramTypes = DatatypeType(t).getDatatype().getParameters();
921 instTypes = DatatypeType(t).getParamTypes();
922 }
923 for(const_iterator i = begin(), i_end = end(); i != i_end; ++i) {
924 Type tc = SelectorType((*i).getSelector().getType()).getRangeType();
925 if( DatatypeType(t).isParametric() ){
926 tc = tc.substitute( paramTypes, instTypes );
927 }
928 if( tc.isDatatype() ){
929 const Datatype& dt = ((DatatypeType)tc).getDatatype();
930 c *= dt.computeCardinality( t, processing );
931 }else{
932 c *= tc.getCardinality();
933 }
934 }
935 return c;
936 }
937
938 bool DatatypeConstructor::computeWellFounded( std::vector< Type >& processing ) const throw(IllegalArgumentException){
939 for(const_iterator i = begin(), i_end = end(); i != i_end; ++i) {
940 Type t = SelectorType((*i).getSelector().getType()).getRangeType();
941 if( t.isDatatype() ){
942 const Datatype& dt = ((DatatypeType)t).getDatatype();
943 if( !dt.computeWellFounded( processing ) ){
944 return false;
945 }
946 }
947 }
948 return true;
949 }
950
951
952 bool DatatypeConstructor::isFinite( Type t ) const throw(IllegalArgumentException) {
953 PrettyCheckArgument(isResolved(), this, "this datatype constructor is not yet resolved");
954
955 // we're using some internals, so we have to set up this library context
956 ExprManagerScope ems(d_constructor);
957 TNode self = Node::fromExpr(d_constructor);
958 // is this already in the cache ?
959 if(self.getAttribute(DatatypeFiniteComputedAttr())) {
960 return self.getAttribute(DatatypeFiniteAttr());
961 }
962 std::vector< Type > instTypes;
963 std::vector< Type > paramTypes;
964 if( DatatypeType(t).isParametric() ){
965 paramTypes = DatatypeType(t).getDatatype().getParameters();
966 instTypes = DatatypeType(t).getParamTypes();
967 }
968 for(const_iterator i = begin(), i_end = end(); i != i_end; ++i) {
969 Type tc = (*i).getRangeType();
970 if( DatatypeType(t).isParametric() ){
971 tc = tc.substitute( paramTypes, instTypes );
972 }
973 if(! tc.getCardinality().isFinite()) {
974 self.setAttribute(DatatypeFiniteComputedAttr(), true);
975 self.setAttribute(DatatypeFiniteAttr(), false);
976 return false;
977 }
978 }
979 self.setAttribute(DatatypeFiniteComputedAttr(), true);
980 self.setAttribute(DatatypeFiniteAttr(), true);
981 return true;
982 }
983
984 bool DatatypeConstructor::isInterpretedFinite( Type t ) const throw(IllegalArgumentException) {
985 PrettyCheckArgument(isResolved(), this, "this datatype constructor is not yet resolved");
986 // we're using some internals, so we have to set up this library context
987 ExprManagerScope ems(d_constructor);
988 TNode self = Node::fromExpr(d_constructor);
989 // is this already in the cache ?
990 if(self.getAttribute(DatatypeUFiniteComputedAttr())) {
991 return self.getAttribute(DatatypeUFiniteAttr());
992 }
993 std::vector< Type > instTypes;
994 std::vector< Type > paramTypes;
995 if( DatatypeType(t).isParametric() ){
996 paramTypes = DatatypeType(t).getDatatype().getParameters();
997 instTypes = DatatypeType(t).getParamTypes();
998 }
999 for(const_iterator i = begin(), i_end = end(); i != i_end; ++i) {
1000 Type tc = (*i).getRangeType();
1001 if( DatatypeType(t).isParametric() ){
1002 tc = tc.substitute( paramTypes, instTypes );
1003 }
1004 TypeNode tcn = TypeNode::fromType( tc );
1005 if(!tcn.isInterpretedFinite()) {
1006 self.setAttribute(DatatypeUFiniteComputedAttr(), true);
1007 self.setAttribute(DatatypeUFiniteAttr(), false);
1008 return false;
1009 }
1010 }
1011 self.setAttribute(DatatypeUFiniteComputedAttr(), true);
1012 self.setAttribute(DatatypeUFiniteAttr(), true);
1013 return true;
1014 }
1015
1016 Expr DatatypeConstructor::computeGroundTerm( Type t, std::vector< Type >& processing, std::map< Type, Expr >& gt ) const throw(IllegalArgumentException) {
1017 // we're using some internals, so we have to set up this library context
1018 ExprManagerScope ems(d_constructor);
1019
1020 std::vector<Expr> groundTerms;
1021 groundTerms.push_back(getConstructor());
1022
1023 // for each selector, get a ground term
1024 std::vector< Type > instTypes;
1025 std::vector< Type > paramTypes;
1026 if( DatatypeType(t).isParametric() ){
1027 paramTypes = DatatypeType(t).getDatatype().getParameters();
1028 instTypes = DatatypeType(t).getParamTypes();
1029 }
1030 for(const_iterator i = begin(), i_end = end(); i != i_end; ++i) {
1031 Type selType = SelectorType((*i).getSelector().getType()).getRangeType();
1032 if( DatatypeType(t).isParametric() ){
1033 selType = selType.substitute( paramTypes, instTypes );
1034 }
1035 Expr arg;
1036 if( selType.isDatatype() ){
1037 std::map< Type, Expr >::iterator itgt = gt.find( selType );
1038 if( itgt != gt.end() ){
1039 arg = itgt->second;
1040 }else{
1041 const Datatype & dt = DatatypeType(selType).getDatatype();
1042 arg = dt.computeGroundTerm( selType, processing );
1043 }
1044 }else{
1045 arg = selType.mkGroundTerm();
1046 }
1047 if( arg.isNull() ){
1048 Debug("datatypes") << "...unable to construct arg of " << (*i).getName() << std::endl;
1049 return Expr();
1050 }else{
1051 Debug("datatypes") << "...constructed arg " << arg.getType() << std::endl;
1052 groundTerms.push_back(arg);
1053 }
1054 }
1055
1056 Expr groundTerm = getConstructor().getExprManager()->mkExpr(kind::APPLY_CONSTRUCTOR, groundTerms);
1057 if( groundTerm.getType()!=t ){
1058 Assert( Datatype::datatypeOf( d_constructor ).isParametric() );
1059 //type is ambiguous, must apply type ascription
1060 Debug("datatypes-gt") << "ambiguous type for " << groundTerm << ", ascribe to " << t << std::endl;
1061 groundTerms[0] = getConstructor().getExprManager()->mkExpr(kind::APPLY_TYPE_ASCRIPTION,
1062 getConstructor().getExprManager()->mkConst(AscriptionType(getSpecializedConstructorType(t))),
1063 groundTerms[0]);
1064 groundTerm = getConstructor().getExprManager()->mkExpr(kind::APPLY_CONSTRUCTOR, groundTerms);
1065 }
1066 return groundTerm;
1067 }
1068
1069 void DatatypeConstructor::computeSharedSelectors( Type domainType ) const {
1070 if( d_shared_selectors[domainType].size()<getNumArgs() ){
1071 TypeNode ctype;
1072 if( DatatypeType(domainType).isParametric() ){
1073 ctype = TypeNode::fromType( getSpecializedConstructorType( domainType ) );
1074 }else{
1075 ctype = TypeNode::fromType( d_constructor.getType() );
1076 }
1077 Assert( ctype.isConstructor() );
1078 Assert( ctype.getNumChildren()-1==getNumArgs() );
1079 //compute the shared selectors
1080 const Datatype& dt = Datatype::datatypeOf(d_constructor);
1081 std::map< TypeNode, unsigned > counter;
1082 for( unsigned j=0; j<ctype.getNumChildren()-1; j++ ){
1083 TypeNode t = ctype[j];
1084 Expr ss = dt.getSharedSelector( domainType, t.toType(), counter[t] );
1085 d_shared_selectors[domainType].push_back( ss );
1086 Assert( d_shared_selector_index[domainType].find( ss )==d_shared_selector_index[domainType].end() );
1087 d_shared_selector_index[domainType][ss] = j;
1088 counter[t]++;
1089 }
1090 }
1091 }
1092
1093
1094 const DatatypeConstructorArg& DatatypeConstructor::operator[](size_t index) const {
1095 PrettyCheckArgument(index < getNumArgs(), index, "index out of bounds");
1096 return d_args[index];
1097 }
1098
1099 const DatatypeConstructorArg& DatatypeConstructor::operator[](std::string name) const {
1100 for(const_iterator i = begin(); i != end(); ++i) {
1101 if((*i).getName() == name) {
1102 return *i;
1103 }
1104 }
1105 IllegalArgument(name, "No such arg `%s' of constructor `%s'", name.c_str(), d_name.c_str());
1106 }
1107
1108 Expr DatatypeConstructor::getSelector(std::string name) const {
1109 return (*this)[name].getSelector();
1110 }
1111
1112 bool DatatypeConstructor::involvesExternalType() const{
1113 for(const_iterator i = begin(); i != end(); ++i) {
1114 if(! SelectorType((*i).getSelector().getType()).getRangeType().isDatatype()) {
1115 return true;
1116 }
1117 }
1118 return false;
1119 }
1120
1121 bool DatatypeConstructor::involvesUninterpretedType() const{
1122 for(const_iterator i = begin(); i != end(); ++i) {
1123 if(SelectorType((*i).getSelector().getType()).getRangeType().isSort()) {
1124 return true;
1125 }
1126 }
1127 return false;
1128 }
1129
1130 DatatypeConstructorArg::DatatypeConstructorArg(std::string name, Expr selector) :
1131 d_name(name),
1132 d_selector(selector),
1133 d_resolved(false) {
1134 PrettyCheckArgument(name != "", name, "cannot construct a datatype constructor arg without a name");
1135 }
1136
1137 std::string DatatypeConstructorArg::getName() const throw() {
1138 string name = d_name;
1139 const size_t nul = name.find('\0');
1140 if(nul != string::npos) {
1141 name.resize(nul);
1142 }
1143 return name;
1144 }
1145
1146 Expr DatatypeConstructorArg::getSelector() const {
1147 PrettyCheckArgument(isResolved(), this, "cannot get a selector for an unresolved datatype constructor");
1148 return d_selector;
1149 }
1150
1151 Expr DatatypeConstructor::getSelectorInternal( Type domainType, size_t index ) const {
1152 PrettyCheckArgument(isResolved(), this, "cannot get an internal selector for an unresolved datatype constructor");
1153 PrettyCheckArgument(index < getNumArgs(), index, "index out of bounds");
1154 if( options::dtSharedSelectors() ){
1155 computeSharedSelectors( domainType );
1156 Assert( d_shared_selectors[domainType].size()==getNumArgs() );
1157 return d_shared_selectors[domainType][index];
1158 }else{
1159 return d_args[index].getSelector();
1160 }
1161 }
1162
1163 int DatatypeConstructor::getSelectorIndexInternal( Expr sel ) const {
1164 PrettyCheckArgument(isResolved(), this, "cannot get an internal selector index for an unresolved datatype constructor");
1165 if( options::dtSharedSelectors() ){
1166 Assert( sel.getType().isSelector() );
1167 Type domainType = ((SelectorType)sel.getType()).getDomain();
1168 computeSharedSelectors( domainType );
1169 std::map< Expr, unsigned >::iterator its = d_shared_selector_index[domainType].find( sel );
1170 if( its!=d_shared_selector_index[domainType].end() ){
1171 return (int)its->second;
1172 }
1173 }else{
1174 unsigned sindex = Datatype::indexOf(sel);
1175 if( getNumArgs() > sindex && d_args[sindex].getSelector() == sel ){
1176 return (int)sindex;
1177 }
1178 }
1179 return -1;
1180 }
1181
1182 Expr DatatypeConstructorArg::getConstructor() const {
1183 PrettyCheckArgument(isResolved(), this,
1184 "cannot get a associated constructor for argument of an unresolved datatype constructor");
1185 return d_constructor;
1186 }
1187
1188 SelectorType DatatypeConstructorArg::getType() const {
1189 return getSelector().getType();
1190 }
1191
1192 Type DatatypeConstructorArg::getRangeType() const {
1193 return getType().getRangeType();
1194 }
1195
1196 bool DatatypeConstructorArg::isUnresolvedSelf() const throw() {
1197 return d_selector.isNull() && d_name.size() == d_name.find('\0') + 1;
1198 }
1199
1200 static const int s_printDatatypeNamesOnly = std::ios_base::xalloc();
1201
1202 std::string DatatypeConstructorArg::getTypeName() const {
1203 Type t;
1204 if(isResolved()) {
1205 t = SelectorType(d_selector.getType()).getRangeType();
1206 } else {
1207 if(d_selector.isNull()) {
1208 string typeName = d_name.substr(d_name.find('\0') + 1);
1209 return (typeName == "") ? "[self]" : typeName;
1210 } else {
1211 t = d_selector.getType();
1212 }
1213 }
1214
1215 // Unfortunately, in the case of complex selector types, we can
1216 // enter nontrivial recursion here. Make sure that doesn't happen.
1217 stringstream ss;
1218 ss << language::SetLanguage(language::output::LANG_CVC4);
1219 ss.iword(s_printDatatypeNamesOnly) = 1;
1220 t.toStream(ss);
1221 return ss.str();
1222 }
1223
1224 std::ostream& operator<<(std::ostream& os, const Datatype& dt) {
1225 // These datatype things are recursive! Be very careful not to
1226 // print an infinite chain of them.
1227 long& printNameOnly = os.iword(s_printDatatypeNamesOnly);
1228 Debug("datatypes-output") << "printNameOnly is " << printNameOnly << std::endl;
1229 if(printNameOnly) {
1230 return os << dt.getName();
1231 }
1232
1233 class Scope {
1234 long& d_ref;
1235 long d_oldValue;
1236 public:
1237 Scope(long& ref, long value) : d_ref(ref), d_oldValue(ref) { d_ref = value; }
1238 ~Scope() { d_ref = d_oldValue; }
1239 } scope(printNameOnly, 1);
1240 // when scope is destructed, the value pops back
1241
1242 Debug("datatypes-output") << "printNameOnly is now " << printNameOnly << std::endl;
1243
1244 // can only output datatypes in the CVC4 native language
1245 language::SetLanguage::Scope ls(os, language::output::LANG_CVC4);
1246
1247 os << "DATATYPE " << dt.getName();
1248 if(dt.isParametric()) {
1249 os << '[';
1250 for(size_t i = 0; i < dt.getNumParameters(); ++i) {
1251 if(i > 0) {
1252 os << ',';
1253 }
1254 os << dt.getParameter(i);
1255 }
1256 os << ']';
1257 }
1258 os << " =" << endl;
1259 Datatype::const_iterator i = dt.begin(), i_end = dt.end();
1260 if(i != i_end) {
1261 os << " ";
1262 do {
1263 os << *i << endl;
1264 if(++i != i_end) {
1265 os << "| ";
1266 }
1267 } while(i != i_end);
1268 }
1269 os << "END;" << endl;
1270
1271 return os;
1272 }
1273
1274 std::ostream& operator<<(std::ostream& os, const DatatypeConstructor& ctor) {
1275 // can only output datatypes in the CVC4 native language
1276 language::SetLanguage::Scope ls(os, language::output::LANG_CVC4);
1277
1278 os << ctor.getName();
1279
1280 DatatypeConstructor::const_iterator i = ctor.begin(), i_end = ctor.end();
1281 if(i != i_end) {
1282 os << "(";
1283 do {
1284 os << *i;
1285 if(++i != i_end) {
1286 os << ", ";
1287 }
1288 } while(i != i_end);
1289 os << ")";
1290 }
1291
1292 return os;
1293 }
1294
1295 std::ostream& operator<<(std::ostream& os, const DatatypeConstructorArg& arg) {
1296 // can only output datatypes in the CVC4 native language
1297 language::SetLanguage::Scope ls(os, language::output::LANG_CVC4);
1298
1299 os << arg.getName() << ": " << arg.getTypeName();
1300
1301 return os;
1302 }
1303
1304 DatatypeIndexConstant::DatatypeIndexConstant(unsigned index) throw(IllegalArgumentException) : d_index(index){
1305
1306 }
1307
1308 std::ostream& operator<<(std::ostream& out, const DatatypeIndexConstant& dic) {
1309 return out << "index_" << dic.getIndex();
1310 }
1311
1312 }/* CVC4 namespace */