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