Node RePairAssocCommutativeOperators::case_assoccomm(TNode n){ Kind k = n.getKind(); Assert(isAssociateCommutative(k)); Assert(n.getMetaKind() != kind::metakind::PARAMETERIZED); unsigned N = n.getNumChildren(); Assert(N >= 2); Node last = rePairAssocCommutativeOperators( n[N-1]); Node nextToLast = rePairAssocCommutativeOperators(n[N-2]); NodeManager* nm = NodeManager::currentNM(); Node last2 = nm->mkNode(k, nextToLast, last); if(N <= 2){ return last2; } else{ Assert(N > 2); Node prevRound = last2; for(unsigned prevPos = N-2; prevPos > 0; --prevPos){ unsigned currPos = prevPos-1; Node curr = rePairAssocCommutativeOperators(n[currPos]); Node round = nm->mkNode(k, curr, prevRound); prevRound = round; } return prevRound; } }
void PseudoBooleanProcessor::learnGeqSub(Node geq) { Assert(geq.getKind() == kind::GEQ); const bool negated = false; bool success = decomposeAssertion(geq, negated); if (!success) { Debug("pbs::rewrites") << "failed " << std::endl; return; } Assert(d_off.value().isIntegral()); Integer off = d_off.value().ceiling(); // \sum pos >= \sum neg + off // for now special case everything we want // target easy clauses if (d_pos.size() == 1 && d_neg.size() == 1 && off.isZero()) { // x >= y // |- (y >= 1) => (x >= 1) Node x = d_pos.front(); Node y = d_neg.front(); Node xGeq1 = mkGeqOne(x); Node yGeq1 = mkGeqOne(y); Node imp = yGeq1.impNode(xGeq1); addSub(geq, imp); } else if (d_pos.size() == 0 && d_neg.size() == 2 && off.isNegativeOne()) { // 0 >= (x + y -1) // |- 1 >= x + y // |- (or (not (x >= 1)) (not (y >= 1))) Node x = d_neg[0]; Node y = d_neg[1]; Node xGeq1 = mkGeqOne(x); Node yGeq1 = mkGeqOne(y); Node cases = (xGeq1.notNode()).orNode(yGeq1.notNode()); addSub(geq, cases); } else if (d_pos.size() == 2 && d_neg.size() == 1 && off.isZero()) { // (x + y) >= z // |- (z >= 1) => (or (x >= 1) (y >=1 )) Node x = d_pos[0]; Node y = d_pos[1]; Node z = d_neg[0]; Node xGeq1 = mkGeqOne(x); Node yGeq1 = mkGeqOne(y); Node zGeq1 = mkGeqOne(z); NodeManager* nm = NodeManager::currentNM(); Node dis = nm->mkNode(kind::OR, zGeq1.notNode(), xGeq1, yGeq1); addSub(geq, dis); } }
Node UfModelTreeNode::getFunctionValue(std::vector<Node>& args, int index, Node argDefaultValue, bool simplify) { if(!d_data.empty()) { Node defaultValue = argDefaultValue; if(d_data.find(Node::null()) != d_data.end()) { defaultValue = d_data[Node::null()].getFunctionValue(args, index + 1, argDefaultValue, simplify); } vector<Node> caseArgs; map<Node, Node> caseValues; for(map< Node, UfModelTreeNode>::iterator it = d_data.begin(); it != d_data.end(); ++it) { if(!it->first.isNull()) { Node val = it->second.getFunctionValue(args, index + 1, defaultValue, simplify); caseArgs.push_back(it->first); caseValues[it->first] = val; } } NodeManager* nm = NodeManager::currentNM(); Node retNode = defaultValue; if(!simplify) { // "non-simplifying" mode - expand function values to things like: // IF (x=0 AND y=0 AND z=0) THEN value1 // ELSE IF (x=0 AND y=0 AND z=1) THEN value2 // [...etc...] for(int i = (int)caseArgs.size() - 1; i >= 0; --i) { Node val = caseValues[ caseArgs[ i ] ]; if(val.getKind() == ITE) { // use a stack to reverse the order, since we're traversing outside-in stack<TNode> stk; do { stk.push(val); val = val[2]; } while(val.getKind() == ITE); AlwaysAssert(val == defaultValue, "default values don't match when constructing function definition!"); while(!stk.empty()) { val = stk.top(); stk.pop(); retNode = nm->mkNode(ITE, nm->mkNode(AND, args[index].eqNode(caseArgs[i]), val[0]), val[1], retNode); } } else { retNode = nm->mkNode(ITE, args[index].eqNode(caseArgs[i]), caseValues[caseArgs[i]], retNode); } } } else { // "simplifying" mode - condense function values for(int i = (int)caseArgs.size() - 1; i >= 0; --i) { retNode = nm->mkNode(ITE, args[index].eqNode(caseArgs[i]), caseValues[caseArgs[i]], retNode); } } return retNode; } else { Assert(!d_value.isNull()); return d_value; } }
void RaftStatImpl::default_method(::google::protobuf::RpcController* controller, const ::braft::IndexRequest* /*request*/, ::braft::IndexResponse* /*response*/, ::google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); brpc::Controller* cntl = (brpc::Controller*)controller; std::string group_id = cntl->http_request().unresolved_path(); std::vector<scoped_refptr<NodeImpl> > nodes; NodeManager* nm = NodeManager::GetInstance(); if (group_id.empty()) { nm->get_all_nodes(&nodes); } else { nm->get_nodes_by_group_id(group_id, &nodes); } const bool html = brpc::UseHTML(cntl->http_request()); if (html) { cntl->http_response().set_content_type("text/html"); } else { cntl->http_response().set_content_type("text/plain"); } butil::IOBufBuilder os; if (html) { os << "<!DOCTYPE html><html><head>\n" << "<script language=\"javascript\" type=\"text/javascript\" src=\"/js/jquery_min\"></script>\n" << brpc::TabsHead() << "</head><body>"; cntl->server()->PrintTabsBody(os, "raft"); } if (nodes.empty()) { if (html) { os << "</body></html>"; } os.move_to(cntl->response_attachment()); return; } std::string prev_group_id; const char *newline = html ? "<br>" : "\r\n"; for (size_t i = 0; i < nodes.size(); ++i) { const NodeId node_id = nodes[i]->node_id(); group_id = node_id.group_id; if (group_id != prev_group_id) { if (html) { os << "<h1>" << group_id << "</h1>"; } else { os << "[" << group_id << "]" << newline; } prev_group_id = group_id; } nodes[i]->describe(os, html); os << newline; } if (html) { os << "</body></html>"; } os.move_to(cntl->response_attachment()); }
// static RewriteResponse TheorySetsRewriter::preRewrite(TNode node) { NodeManager* nm = NodeManager::currentNM(); // do nothing if(node.getKind() == kind::EQUAL && node[0] == node[1]) return RewriteResponse(REWRITE_DONE, nm->mkConst(true)); // Further optimization, if constants but differing ones return RewriteResponse(REWRITE_DONE, node); }
RESULT Builder::build(const char* context, const char* ops, const char* braces, const char* blanks ) { if( table_ops.load(ops) && table_braces.load(braces) && table_blanks.load(blanks) ) { NodeManager* mgr = NodeManager::getSingleton(); if( mgr->getHeader() ) { return read( mgr->getHeader() ); } } return E_BUILD_CONFIG; }
Node InequalityGraph::makeDiseqSplitLemma(TNode diseq) { Assert(diseq.getKind() == kind::NOT && diseq[0].getKind() == kind::EQUAL); NodeManager* nm = NodeManager::currentNM(); TNode a = diseq[0][0]; TNode b = diseq[0][1]; Node a_lt_b = nm->mkNode(kind::BITVECTOR_ULT, a, b); Node b_lt_a = nm->mkNode(kind::BITVECTOR_ULT, b, a); Node eq = diseq[0]; Node lemma = nm->mkNode(kind::OR, a_lt_b, b_lt_a, eq); return lemma; }
bool DtInstantiator::processEqualTerms(CegInstantiator* ci, SolvedForm& sf, Node pv, std::vector<Node>& eqc, CegInstEffort effort) { Trace("cegqi-dt-debug") << "try based on constructors in equivalence class." << std::endl; // look in equivalence class for a constructor NodeManager* nm = NodeManager::currentNM(); for (unsigned k = 0, size = eqc.size(); k < size; k++) { Node n = eqc[k]; if (n.getKind() == APPLY_CONSTRUCTOR) { Trace("cegqi-dt-debug") << "...try based on constructor term " << n << std::endl; std::vector<Node> children; children.push_back(n.getOperator()); const Datatype& dt = static_cast<DatatypeType>(d_type.toType()).getDatatype(); unsigned cindex = Datatype::indexOf(n.getOperator().toExpr()); // now must solve for selectors applied to pv for (unsigned j = 0, nargs = dt[cindex].getNumArgs(); j < nargs; j++) { Node c = nm->mkNode( APPLY_SELECTOR_TOTAL, Node::fromExpr(dt[cindex].getSelectorInternal(d_type.toType(), j)), pv); ci->pushStackVariable(c); children.push_back(c); } Node val = nm->mkNode(kind::APPLY_CONSTRUCTOR, children); TermProperties pv_prop_dt; if (ci->constructInstantiationInc(pv, val, pv_prop_dt, sf)) { return true; } // cleanup for (unsigned j = 0, nargs = dt[cindex].getNumArgs(); j < nargs; j++) { ci->popStackVariable(); } break; } } return false; }
ProgramPtr Program::remEntryPoints(NodeManager& manager, const ProgramPtr& program, const ExpressionList& entryPoints) { ExpressionList list; for_each(program->getEntryPoints(), [&list, &entryPoints](const ExpressionPtr& cur) { if(!contains(entryPoints, cur, equal_target<ExpressionPtr>())) { list.push_back(cur); } }); return manager.get(Program(list)); }
void InequalityGraph::getAllValuesInModel(std::vector<Node>& assignments) { NodeManager* nm = NodeManager::currentNM(); for (ModelValues::const_iterator it = d_modelValues.begin(); it != d_modelValues.end(); ++it) { TermId id = (*it).first; BitVector value = (*it).second.value; TNode var = getTermNode(id); Node constant = utils::mkConst(value); Node assignment = nm->mkNode(kind::EQUAL, var, constant); assignments.push_back(assignment); Debug("bitvector-model") << " " << var << " => " << constant << "\n"; } }
Node NaryBuilder::zeroArity(Kind k){ using namespace kind; NodeManager* nm = NodeManager::currentNM(); switch(k){ case AND: return nm->mkConst(true); case OR: return nm->mkConst(false); case PLUS: return nm->mkConst(Rational(0)); case MULT: return nm->mkConst(Rational(1)); default: return Node::null(); } }
bool CoreSolver::decomposeFact(TNode fact) { Debug("bv-slicer") << "CoreSolver::decomposeFact fact=" << fact << endl; // FIXME: are this the right things to assert? // assert decompositions since the equality engine does not know the semantics of // concat: // a == a_1 concat ... concat a_k // b == b_1 concat ... concat b_k TNode eq = fact.getKind() == kind::NOT? fact[0] : fact; TNode a = eq[0]; TNode b = eq[1]; Node new_a = getBaseDecomposition(a); Node new_b = getBaseDecomposition(b); Assert (utils::getSize(new_a) == utils::getSize(new_b) && utils::getSize(new_a) == utils::getSize(a)); NodeManager* nm = NodeManager::currentNM(); Node a_eq_new_a = nm->mkNode(kind::EQUAL, a, new_a); Node b_eq_new_b = nm->mkNode(kind::EQUAL, b, new_b); bool ok = true; ok = assertFactToEqualityEngine(a_eq_new_a, utils::mkTrue()); if (!ok) return false; ok = assertFactToEqualityEngine(b_eq_new_b, utils::mkTrue()); if (!ok) return false; ok = assertFactToEqualityEngine(fact, fact); if (!ok) return false; if (fact.getKind() == kind::EQUAL) { // assert the individual equalities as well // a_i == b_i if (new_a.getKind() == kind::BITVECTOR_CONCAT && new_b.getKind() == kind::BITVECTOR_CONCAT) { Assert (new_a.getNumChildren() == new_b.getNumChildren()); for (unsigned i = 0; i < new_a.getNumChildren(); ++i) { Node eq_i = nm->mkNode(kind::EQUAL, new_a[i], new_b[i]); ok = assertFactToEqualityEngine(eq_i, fact); if (!ok) return false; } } } return true; }
Node InferBoundsResult::getLiteral() const{ const Rational& q = getValue().getNoninfinitesimalPart(); NodeManager* nm = NodeManager::currentNM(); Node qnode = nm->mkConst(q); Kind k; if(d_upperBound){ // x <= q + c*delta Assert(getValue().infinitesimalSgn() <= 0); k = boundIsRational() ? kind::LEQ : kind::LT; }else{ // x >= q + c*delta Assert(getValue().infinitesimalSgn() >= 0); k = boundIsRational() ? kind::GEQ : kind::GT; } Node atom = nm->mkNode(k, getTerm(), qnode); Node lit = Rewriter::rewrite(atom); return lit; }
Node AbstractionModule::getSignatureSkolem(TNode node) { Assert (node.getKind() == kind::VARIABLE); unsigned bitwidth = utils::getSize(node); if (d_signatureSkolems.find(bitwidth) == d_signatureSkolems.end()) { d_signatureSkolems[bitwidth] = vector<Node>(); } vector<Node>& skolems = d_signatureSkolems[bitwidth]; // get the index of bv variables of this size unsigned index = getBitwidthIndex(bitwidth); Assert (skolems.size() + 1 >= index ); if (skolems.size() == index) { ostringstream os; os << "sig_" <<bitwidth <<"_" << index; NodeManager* nm = NodeManager::currentNM(); skolems.push_back(nm->mkSkolem(os.str(), nm->mkBitVectorType(bitwidth), "skolem for computing signatures")); } ++(d_signatureIndices[bitwidth]); return skolems[index]; }
void Builder::parse( const char* content ) { NodeManager* mgr = NodeManager::getSingleton(); const char* last = content; int width; while( *content ) { if( (width = isBlank(content)) > 0 ) { content += width; } else if( (width = isOp( content )) > 0 ) { mgr->createOperator(content, width); mgr->createOperand(content, content-last); last = content; content += width; } else if( (width = isBrace( content )) > 0 ) { mgr->createBrace(content, width); last = content; content += width; } content ++; } }
void Builder::unserialize(const char* file) { NodeManager* mgr = NodeManager::getSingleton(); vector<Node*> nodes; const char* last = file; int width; while( file ) { if( (width = Config::hasDelimiter( file )) > 0 ) { nodes.push_back( mgr->unserialize( file, file - last ) ); last = file; file += width; } file ++; } Node* node; for( int i = 0 ; i < nodes.size() ; i ++ ) { node = nodes.at(i); if( node ) { node->addLeft( nodes.at(2*i) ); node->addRight( nodes.at(2*i+1) ); } } root = nodes.at(0); }
EqualityStatus InequalitySolver::getEqualityStatus(TNode a, TNode b) { if (!isComplete()) return EQUALITY_UNKNOWN; NodeManager* nm = NodeManager::currentNM(); Node a_lt_b = nm->mkNode(kind::BITVECTOR_ULT, a, b); Node b_lt_a = nm->mkNode(kind::BITVECTOR_ULT, b, a); // if an inequality containing the terms has been asserted then we know // the equality is false if (d_assertionSet.contains(a_lt_b) || d_assertionSet.contains(b_lt_a)) { return EQUALITY_FALSE; } if (!d_inequalityGraph.hasValueInModel(a) || !d_inequalityGraph.hasValueInModel(b)) { return EQUALITY_UNKNOWN; } // TODO: check if this disequality is entailed by inequalities via // transitivity BitVector a_val = d_inequalityGraph.getValueInModel(a); BitVector b_val = d_inequalityGraph.getValueInModel(b); if (a_val == b_val) { return EQUALITY_TRUE_IN_MODEL; } else { return EQUALITY_FALSE_IN_MODEL; } }
insieme::core::TypePtr autoReturnType(NodeManager& nodeMan, const CompoundStmtPtr& body) { auto debug = false; if(debug) { std::cout << "{{{{{{ autoReturnType ----\n"; } // find all returns TypePtr newReturnType = nodeMan.getLangBasic().getUnit(); auto returns = analysis::getFreeNodes(body, NT_ReturnStmt, toVector(NT_LambdaExpr, NT_JobExpr, NT_ReturnStmt)); if(debug) { std::cout << "{{{{{{{{{{{{{ Returns: " << returns << "\n"; } // if no returns, unit is fine if(!returns.empty()) { auto typeList = ::transform(returns, [](const NodePtr& ret) { return ret.as<ReturnStmtPtr>()->getReturnExpr()->getType(); }); if(debug) { std::cout << "{{{{{{{{{{{{{ typeList: " << typeList << "\n"; } newReturnType = types::getSmallestCommonSuperType(typeList); if(debug) { std::cout << "{{{{{{{{{{{{{ returnType: " << newReturnType << "\n"; } assert_true(newReturnType) << "Return type deduction, multiple return types have no common supertype."; } return newReturnType; }
Node SymmetryBreaker::generateSymBkConstraints(const vector<vector<Node>>& parts) { vector<Node> constraints; NodeManager* nm = NodeManager::currentNM(); for (const vector<Node>& part : parts) { if (part.size() >= 2) { Kind kd = getOrderKind(part[0]); if (kd == UNDEFINED_KIND) { // no symmetry breaking possible continue; } if (kd != EQUAL) { for (unsigned int i = 0; i < part.size() - 1; ++i) { // Generate less than or equal to constraints: part[i] <= part[i+1] Node constraint = nm->mkNode(kd, part[i], part[i + 1]); constraints.push_back(constraint); Trace("sym-bk") << "[sym-bk] Generate a symmetry breaking constraint: " << constraint << endl; } } else if (part.size() >= 3) { for (unsigned int i = 0; i < part.size(); ++i) { for (unsigned int j = i + 2; j < part.size(); ++j) { // Generate consecutive constraints v_i = v_j => v_i = v_{j-1}, // for all 0 <= i < j-1 < j < part.size() Node constraint = nm->mkNode(IMPLIES, nm->mkNode(kd, part[i], part[j]), nm->mkNode(kd, part[i], part[j - 1])); constraints.push_back(constraint); Trace("sym-bk") << "[sym-bk] Generate a symmetry breaking constraint: " << constraint << endl; } if (i >= 1) { for (unsigned int j = i + 1; j < part.size(); ++j) { Node lhs = nm->mkNode(kd, part[i], part[j]); Node rhs = nm->mkNode(kd, part[i], part[i - 1]); int prev_seg_start_index = 2*i - j - 1; // Since prev_seg_len is always less than i - 1, we just need to make // sure prev_seg_len is greater than or equal to 0 if(prev_seg_start_index >= 0) { rhs = nm->mkNode( OR, rhs, nm->mkNode(kd, part[i - 1], part[prev_seg_start_index])); } // Generate length order constraints // v_i = v_j => (v_{i} = v_{i-1} OR v_{i-1} = x_{(i-1)-(j-i)}) // for all 1 <= i < j < part.size() and (i-1)-(j-i) >= 0 Node constraint = nm->mkNode(IMPLIES, lhs, rhs); constraints.push_back(constraint); Trace("sym-bk") << "[sym-bk] Generate a symmetry breaking constraint: " << constraint << endl; } } } } } } if(constraints.empty()) { return d_trueNode; } else if(constraints.size() == 1) { return constraints[0]; } return nm->mkNode(AND, constraints); }
int main(int argc, char **argv) { // TODO: Properly parse and handle any arguments if (argc > 1) { for (int argi = 0; argi < argc; argi++) { if (!strcmp(argv[argi], "--version") || !strcmp(argv[argi], "-v")) { cout << gVersionString << endl; } if (!strcmp(argv[argi], "--gensql")) { cout << gConfig.getDefaultSQL(string(argv[0]), gVersionString) << endl; } if (!strcmp(argv[argi], "--gentex")) { cout << gConfig.getTeX(string(argv[0]), gVersionString) << endl; } } return 0; } sockaddr_in si_me; sockaddr_in si_other; int aSocket; char buf[BUFLEN]; LOG(ALERT) << argv[0] << " (re)starting"; srand ( time(NULL) + (int)getpid() ); my_udp_port = gConfig.getNum("SubscriberRegistry.Port"); gSubscriberRegistry.init(); gNodeManager.setAppLogicHandler(&nmHandler); gNodeManager.start(45064); // init osip lib osip_t *osip; int i=osip_init(&osip); if (i!=0) { LOG(ALERT) << "cannot init sip lib"; exit(1); } if ((aSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { LOG(ALERT) << "can't initialize socket"; exit(1); } memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(my_udp_port); si_me.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(aSocket, (sockaddr*)&si_me, sizeof(si_me)) == -1) { LOG(ALERT) << "can't bind socket on port " << my_udp_port; exit(1); } LOG(NOTICE) << "binding on port " << my_udp_port; while (true) { gConfig.purge(); socklen_t slen = sizeof(si_other); memset(buf, 0, BUFLEN); if (recvfrom(aSocket, buf, BUFLEN, 0, (sockaddr*)&si_other, &slen) == -1) { LOG(ERR) << "recvfrom problem"; continue; } LOG(INFO) << " receiving " << buf; char *dest = processBuffer(buf); if (dest == NULL) { continue; } if (sendto(aSocket, dest, strlen(dest), 0, (sockaddr*)&si_other, sizeof(si_other)) == -1) { LOG(ERR) << "sendto problem"; continue; } osip_free(dest); } close(aSocket); return 0; }
void AbstractionModule::finalizeSignatures() { NodeManager* nm = NodeManager::currentNM(); Debug("bv-abstraction") << "AbstractionModule::finalizeSignatures num signatures = " << d_signatures.size() <<"\n"; TNodeSet new_signatures; // "unify" signatures for (SignatureMap::const_iterator ss = d_signatures.begin(); ss != d_signatures.end(); ++ss) { for (SignatureMap::const_iterator tt = ss; tt != d_signatures.end(); ++tt) { TNode t = getGeneralization(tt->first); TNode s = getGeneralization(ss->first); if (t != s) { int status = comparePatterns(s, t); Assert (status); if (status < 0) continue; if (status == 1) { storeGeneralization(t, s); } else { storeGeneralization(s, t); } } } } // keep only most general signatures for (SignatureMap::iterator it = d_signatures.begin(); it != d_signatures.end(); ) { TNode sig = it->first; TNode gen = getGeneralization(sig); if (sig != gen) { Assert (d_signatures.find(gen) != d_signatures.end()); // update the count d_signatures[gen]+= d_signatures[sig]; d_signatures.erase(it++); } else { ++it; } } // remove signatures that are not frequent enough for (SignatureMap::iterator it = d_signatures.begin(); it != d_signatures.end(); ) { if (it->second <= 7) { d_signatures.erase(it++); } else { ++it; } } for (SignatureMap::const_iterator it = d_signatures.begin(); it != d_signatures.end(); ++it) { TNode signature = it->first; // we already processed this signature Assert (d_signatureToFunc.find(signature) == d_signatureToFunc.end()); Debug("bv-abstraction") << "Processing signature " << signature << " count " << it->second << "\n"; std::vector<TypeNode> arg_types; TNodeSet seen; collectArgumentTypes(signature, arg_types, seen); Assert (signature.getType().isBoolean()); // make function return a bitvector of size 1 //Node bv_function = utils::mkNode(kind::ITE, signature, utils::mkConst(1, 1u), utils::mkConst(1, 0u)); TypeNode range = NodeManager::currentNM()->mkBitVectorType(1); TypeNode abs_type = nm->mkFunctionType(arg_types, range); Node abs_func = nm->mkSkolem("abs_$$", abs_type, "abstraction function for bv theory"); Debug("bv-abstraction") << " abstracted by function " << abs_func << "\n"; // NOTE: signature expression type is BOOLEAN d_signatureToFunc[signature] = abs_func; d_funcToSignature[abs_func] = signature; } d_statistics.d_numFunctionsAbstracted.setData(d_signatureToFunc.size()); Debug("bv-abstraction") << "AbstractionModule::finalizeSignatures abstracted " << d_signatureToFunc.size() << " signatures. \n"; }
Node DtInstantiator::solve_dt(Node v, Node a, Node b, Node sa, Node sb) { Trace("cegqi-arith-debug2") << "Solve dt : " << v << " " << a << " " << b << " " << sa << " " << sb << std::endl; Node ret; if (!a.isNull() && a == v) { ret = sb; } else if (!b.isNull() && b == v) { ret = sa; } else if (!a.isNull() && a.getKind() == APPLY_CONSTRUCTOR) { if (!b.isNull() && b.getKind() == APPLY_CONSTRUCTOR) { if (a.getOperator() == b.getOperator()) { for (unsigned i = 0, nchild = a.getNumChildren(); i < nchild; i++) { Node s = solve_dt(v, a[i], b[i], sa[i], sb[i]); if (!s.isNull()) { return s; } } } } else { NodeManager* nm = NodeManager::currentNM(); unsigned cindex = Datatype::indexOf(a.getOperator().toExpr()); TypeNode tn = a.getType(); const Datatype& dt = static_cast<DatatypeType>(tn.toType()).getDatatype(); for (unsigned i = 0, nchild = a.getNumChildren(); i < nchild; i++) { Node nn = nm->mkNode( APPLY_SELECTOR_TOTAL, Node::fromExpr(dt[cindex].getSelectorInternal(tn.toType(), i)), sb); Node s = solve_dt(v, a[i], Node::null(), sa[i], nn); if (!s.isNull()) { return s; } } } } else if (!b.isNull() && b.getKind() == APPLY_CONSTRUCTOR) { // flip sides return solve_dt(v, b, a, sb, sa); } if (!ret.isNull()) { // ensure does not contain v if (expr::hasSubterm(ret, v)) { ret = Node::null(); } } return ret; }
Node RemoveITE::run(TNode node, std::vector<Node>& output, IteSkolemMap& iteSkolemMap) { // Current node Debug("ite") << "removeITEs(" << node << ")" << endl; // The result may be cached already NodeManager *nodeManager = NodeManager::currentNM(); ITECache::iterator i = d_iteCache.find(node); if(i != d_iteCache.end()) { Node cachedRewrite = (*i).second; Debug("ite") << "removeITEs: in-cache: " << cachedRewrite << endl; return cachedRewrite.isNull() ? Node(node) : cachedRewrite; } // If an ITE replace it if(node.getKind() == kind::ITE) { TypeNode nodeType = node.getType(); if(!nodeType.isBoolean()) { // Make the skolem to represent the ITE Node skolem = nodeManager->mkSkolem("termITE_$$", nodeType, "a variable introduced due to term-level ITE removal"); // The new assertion Node newAssertion = nodeManager->mkNode(kind::ITE, node[0], skolem.eqNode(node[1]), skolem.eqNode(node[2])); Debug("ite") << "removeITEs(" << node << ") => " << newAssertion << endl; // Attach the skolem d_iteCache[node] = skolem; // Remove ITEs from the new assertion, rewrite it and push it to the output newAssertion = run(newAssertion, output, iteSkolemMap); iteSkolemMap[skolem] = output.size(); output.push_back(newAssertion); // The representation is now the skolem return skolem; } } // If not an ITE, go deep if( node.getKind() != kind::FORALL && node.getKind() != kind::EXISTS && node.getKind() != kind::REWRITE_RULE ) { vector<Node> newChildren; bool somethingChanged = false; if(node.getMetaKind() == kind::metakind::PARAMETERIZED) { newChildren.push_back(node.getOperator()); } // Remove the ITEs from the children for(TNode::const_iterator it = node.begin(), end = node.end(); it != end; ++it) { Node newChild = run(*it, output, iteSkolemMap); somethingChanged |= (newChild != *it); newChildren.push_back(newChild); } // If changes, we rewrite if(somethingChanged) { Node cachedRewrite = nodeManager->mkNode(node.getKind(), newChildren); d_iteCache[node] = cachedRewrite; return cachedRewrite; } else { d_iteCache[node] = Node::null(); return node; } } else { d_iteCache[node] = Node::null(); return node; } }
int main(int argc, char ** argv){ NodeType type; if(strcmp(argv[1],"sink")==0){ type = SINK; } if(strcmp(argv[1],"camera")==0){ type = CAMERA; } if(strcmp(argv[1],"cooperator")==0){ type = COOPERATOR; } NodeManager *nodeMng; RadioSystem *radioSys; TaskManager *taskMng; S2GInterface *s2ginterface; MessageParser *msg_parser; //ConnectionManager *connMng; boost::asio::io_service io_service; switch(type){ case SINK:{ //create the main components nodeMng = new NodeManager(SINK, argv[6]); msg_parser = new MessageParser(); radioSys = new RadioSystem(nodeMng, msg_parser,argv[3],argv[4],argv[5]); taskMng = new TaskManager(nodeMng); nodeMng->set_radioSystem(radioSys); nodeMng->set_taskManager(taskMng); //start the task manager taskMng->start(); //start a telosb receiver radioSys->startTelosbReceiver(argv[2], argv[6]); //start the sink2gui interface tcp::resolver resolver(io_service); tcp::resolver::query query("localhost", "1234"); tcp::resolver::iterator iterator = resolver.resolve(query); s2ginterface = new S2GInterface(nodeMng, msg_parser, io_service, iterator); s2ginterface->startInterface(); nodeMng->set_s2gInterface(s2ginterface); break; } case CAMERA:{ nodeMng = new NodeManager(CAMERA, argv[6]); msg_parser = new MessageParser(); radioSys = new RadioSystem(nodeMng,msg_parser,argv[3],argv[4],argv[5]); taskMng = new TaskManager(nodeMng); //connMng = new ConnectionManager(); nodeMng->set_radioSystem(radioSys); nodeMng->set_taskManager(taskMng); //start the task manager taskMng->start(); //start a telosb receiver radioSys->startTelosbReceiver(argv[2], argv[6]); //start the WiFi manager radioSys->startWiFiReceiver(); radioSys->joinTelosbReceiver(); break; } case COOPERATOR:{ nodeMng = new NodeManager(COOPERATOR,argv[6]); msg_parser = new MessageParser(); radioSys = new RadioSystem(nodeMng,msg_parser,argv[3],argv[4],argv[5]); taskMng = new TaskManager(nodeMng); nodeMng->set_radioSystem(radioSys); nodeMng->set_taskManager(taskMng); //start the task manager taskMng->start(); radioSys->startWiFiReceiver(); //ALEXIS 15/12 WIFI CLASS break; } default: break; } taskMng->join(); return 0; }
std::map<NodePtr,precedence_container> create_precedence_map(NodeManager& nm) { auto& lang = nm.getLangBasic(); auto& refs = nm.getLangExtension<lang::ReferenceExtension>(); std::map<NodePtr, precedence_container> m; m[refs.getGenPostInc()] = {2,0}; m[refs.getGenPostDec()] = {2,0}; m[lang.getBoolLNot()] = {3,1}; m[lang.getSignedIntNot()] = {3,1}; m[lang.getUnsignedIntNot()] = {3,1}; m[refs.getGenPreInc()] = {3,1}; m[refs.getGenPreDec()] = {3,1}; m[lang.getSignedIntMul()] = {5,0}; m[lang.getGenMul()] = {5,0}; m[lang.getUnsignedIntMul()] = {5,0}; m[lang.getRealMul()] = {5,0}; m[lang.getCharMul()] = {5,0}; m[lang.getSignedIntMod()] = {5,0}; m[lang.getGenMod()] = {5,0}; m[lang.getUnsignedIntMod()] = {5,0}; m[lang.getCharMod()] = {5,0}; m[lang.getSignedIntDiv()] = {5,0}; m[lang.getGenDiv()] = {5,0}; m[lang.getUnsignedIntDiv()] = {5,0}; m[lang.getRealDiv()] = {5,0}; m[lang.getCharDiv()] = {5,0}; m[lang.getSignedIntAdd()] = {6,0}; m[lang.getGenAdd()] = {6,0}; m[lang.getUnsignedIntAdd()] = {6,0}; m[lang.getRealAdd()] = {6,0}; m[lang.getCharAdd()] = {6,0}; m[lang.getSignedIntSub()] = {6,0}; m[lang.getGenSub()] = {6,0}; m[lang.getUnsignedIntSub()] = {6,0}; m[lang.getRealSub()] = {6,0}; m[lang.getCharSub()] = {6,0}; m[lang.getSignedIntLShift()] = {7,0}; m[lang.getGenLShift()] = {7,0}; m[lang.getSignedIntRShift()] = {7,0}; m[lang.getGenRShift()] = {7,0}; m[lang.getUnsignedIntLShift()] = {7,0}; m[lang.getUnsignedIntRShift()] = {7,0}; m[lang.getSignedIntLt()] = {8,0}; m[lang.getGenLt()] = {8,0}; m[lang.getRealLt()] = {8,0}; m[lang.getUnsignedIntLt()] = {8,0}; m[lang.getCharLt()] = {8,0}; m[lang.getSignedIntLe()] = {8,0}; m[lang.getGenLe()] = {8,0}; m[lang.getRealLe()] = {8,0}; m[lang.getUnsignedIntLe()] = {8,0}; m[lang.getCharLe()] = {8,0}; m[lang.getSignedIntGt()] = {8,0}; m[lang.getGenGt()] = {8,0}; m[lang.getRealGt()] = {8,0}; m[lang.getUnsignedIntGt()] = {8,0}; m[lang.getCharGt()] = {8,0}; m[lang.getSignedIntGe()] = {8,0}; m[lang.getGenGe()] = {8,0}; m[lang.getRealGe()] = {8,0}; m[lang.getUnsignedIntGe()] = {8,0}; m[lang.getCharGe()] = {8,0}; m[lang.getSignedIntEq()] = {9,0}; m[lang.getGenEq()] = {9,0}; m[lang.getRealEq()] = {9,0}; m[lang.getUnsignedIntEq()] = {9,0}; m[lang.getCharEq()] = {9,0}; m[lang.getBoolEq()] = {9,0}; m[lang.getTypeEq()] = {9,0}; m[lang.getSignedIntNe()] = {9,0}; m[lang.getGenNe()] = {9,0}; m[lang.getUnsignedIntNe()] = {9,0}; m[lang.getCharNe()] = {9,0}; m[lang.getBoolNe()] = {9,0}; m[lang.getRealNe()] = {9,0}; m[lang.getSignedIntAnd()] = {10,0}; m[lang.getGenAnd()] = {10,0}; m[lang.getUnsignedIntAnd()] = {10,0}; m[lang.getBoolAnd()] = {10,0}; m[lang.getSignedIntXor()] = {11,0}; m[lang.getGenXor()] = {11,0}; m[lang.getUnsignedIntXor()] = {11,0}; m[lang.getBoolXor()] = {11,0}; m[lang.getSignedIntOr()] = {12,0}; m[lang.getGenOr()] = {12,0}; m[lang.getUnsignedIntOr()] = {12,0}; m[lang.getBoolOr()] = {12,0}; m[lang.getBoolLAnd()] = {13,0}; m[lang.getBoolLOr()] = {14,0}; return m; }
Node BVToBool::convertBvTerm(TNode node) { Assert(node.getType().isBitVector() && node.getType().getBitVectorSize() == 1); if (hasBoolCache(node)) return getBoolCache(node); NodeManager* nm = NodeManager::currentNM(); if (!isConvertibleBvTerm(node)) { ++(d_statistics.d_numTermsForcedLifted); Node result = nm->mkNode(kind::EQUAL, node, d_one); addToBoolCache(node, result); Debug("bv-to-bool") << "BVToBool::convertBvTerm " << node << " => " << result << "\n"; return result; } if (node.getNumChildren() == 0) { Assert(node.getKind() == kind::CONST_BITVECTOR); Node result = node == d_one ? bv::utils::mkTrue() : bv::utils::mkFalse(); // addToCache(node, result); Debug("bv-to-bool") << "BVToBool::convertBvTerm " << node << " => " << result << "\n"; return result; } ++(d_statistics.d_numTermsLifted); Kind kind = node.getKind(); if (kind == kind::ITE) { Node cond = liftNode(node[0]); Node true_branch = convertBvTerm(node[1]); Node false_branch = convertBvTerm(node[2]); Node result = nm->mkNode(kind::ITE, cond, true_branch, false_branch); addToBoolCache(node, result); Debug("bv-to-bool") << "BVToBool::convertBvTerm " << node << " => " << result << "\n"; return result; } Kind new_kind; // special case for XOR as it has to be binary // while BITVECTOR_XOR can be n-ary if (kind == kind::BITVECTOR_XOR) { new_kind = kind::XOR; Node result = convertBvTerm(node[0]); for (unsigned i = 1; i < node.getNumChildren(); ++i) { Node converted = convertBvTerm(node[i]); result = nm->mkNode(kind::XOR, result, converted); } Debug("bv-to-bool") << "BVToBool::convertBvTerm " << node << " => " << result << "\n"; return result; } if (kind == kind::BITVECTOR_COMP) { Node result = nm->mkNode(kind::EQUAL, node[0], node[1]); addToBoolCache(node, result); Debug("bv-to-bool") << "BVToBool::convertBvTerm " << node << " => " << result << "\n"; return result; } switch (kind) { case kind::BITVECTOR_OR: new_kind = kind::OR; break; case kind::BITVECTOR_AND: new_kind = kind::AND; break; case kind::BITVECTOR_NOT: new_kind = kind::NOT; break; default: Unhandled(); } NodeBuilder<> builder(new_kind); for (unsigned i = 0; i < node.getNumChildren(); ++i) { builder << convertBvTerm(node[i]); } Node result = builder; addToBoolCache(node, result); Debug("bv-to-bool") << "BVToBool::convertBvTerm " << node << " => " << result << "\n"; return result; }
ProgramPtr Program::get(NodeManager& manager, const ExpressionList& entryPoints) { return manager.get(Program(entryPoints)); }
PreprocessingPassResult SygusAbduct::applyInternal( AssertionPipeline* assertionsToPreprocess) { NodeManager* nm = NodeManager::currentNM(); Trace("sygus-abduct") << "Run sygus abduct..." << std::endl; Trace("sygus-abduct-debug") << "Collect symbols..." << std::endl; std::unordered_set<Node, NodeHashFunction> symset; std::vector<Node>& asserts = assertionsToPreprocess->ref(); // do we have any assumptions, e.g. via check-sat-assuming? bool usingAssumptions = (assertionsToPreprocess->getNumAssumptions() > 0); // The following is our set of "axioms". We construct this set only when the // usingAssumptions (above) is true. In this case, our input formula is // partitioned into Fa ^ Fc as described in the header of this class, where: // - The conjunction of assertions marked as assumptions are the negated // conjecture Fc, and // - The conjunction of all other assertions are the axioms Fa. std::vector<Node> axioms; for (size_t i = 0, size = asserts.size(); i < size; i++) { expr::getSymbols(asserts[i], symset); // if we are not an assumption, add it to the set of axioms if (usingAssumptions && i < assertionsToPreprocess->getAssumptionsStart()) { axioms.push_back(asserts[i]); } } Trace("sygus-abduct-debug") << "...finish, got " << symset.size() << " symbols." << std::endl; Trace("sygus-abduct-debug") << "Setup symbols..." << std::endl; std::vector<Node> syms; std::vector<Node> vars; std::vector<Node> varlist; std::vector<TypeNode> varlistTypes; for (const Node& s : symset) { TypeNode tn = s.getType(); if (tn.isFirstClass()) { std::stringstream ss; ss << s; Node var = nm->mkBoundVar(tn); syms.push_back(s); vars.push_back(var); Node vlv = nm->mkBoundVar(ss.str(), tn); varlist.push_back(vlv); varlistTypes.push_back(tn); } } Trace("sygus-abduct-debug") << "...finish" << std::endl; Trace("sygus-abduct-debug") << "Make abduction predicate..." << std::endl; // make the abduction predicate to synthesize TypeNode abdType = varlistTypes.empty() ? nm->booleanType() : nm->mkPredicateType(varlistTypes); Node abd = nm->mkBoundVar("A", abdType); Trace("sygus-abduct-debug") << "...finish" << std::endl; Trace("sygus-abduct-debug") << "Make abduction predicate app..." << std::endl; std::vector<Node> achildren; achildren.push_back(abd); achildren.insert(achildren.end(), vars.begin(), vars.end()); Node abdApp = vars.empty() ? abd : nm->mkNode(APPLY_UF, achildren); Trace("sygus-abduct-debug") << "...finish" << std::endl; Trace("sygus-abduct-debug") << "Set attributes..." << std::endl; // set the sygus bound variable list Node abvl = nm->mkNode(BOUND_VAR_LIST, varlist); abd.setAttribute(theory::SygusSynthFunVarListAttribute(), abvl); Trace("sygus-abduct-debug") << "...finish" << std::endl; Trace("sygus-abduct-debug") << "Make conjecture body..." << std::endl; Node input = asserts.size() == 1 ? asserts[0] : nm->mkNode(AND, asserts); input = input.substitute(syms.begin(), syms.end(), vars.begin(), vars.end()); // A(x) => ~input( x ) input = nm->mkNode(OR, abdApp.negate(), input.negate()); Trace("sygus-abduct-debug") << "...finish" << std::endl; Trace("sygus-abduct-debug") << "Make conjecture..." << std::endl; Node res = input.negate(); if (!vars.empty()) { Node bvl = nm->mkNode(BOUND_VAR_LIST, vars); // exists x. ~( A( x ) => ~input( x ) ) res = nm->mkNode(EXISTS, bvl, res); } // sygus attribute Node sygusVar = nm->mkSkolem("sygus", nm->booleanType()); theory::SygusAttribute ca; sygusVar.setAttribute(ca, true); Node instAttr = nm->mkNode(INST_ATTRIBUTE, sygusVar); std::vector<Node> iplc; iplc.push_back(instAttr); if (!axioms.empty()) { Node aconj = axioms.size() == 1 ? axioms[0] : nm->mkNode(AND, axioms); aconj = aconj.substitute(syms.begin(), syms.end(), vars.begin(), vars.end()); Trace("sygus-abduct") << "---> Assumptions: " << aconj << std::endl; Node sc = nm->mkNode(AND, aconj, abdApp); Node vbvl = nm->mkNode(BOUND_VAR_LIST, vars); sc = nm->mkNode(EXISTS, vbvl, sc); Node sygusScVar = nm->mkSkolem("sygus_sc", nm->booleanType()); sygusScVar.setAttribute(theory::SygusSideConditionAttribute(), sc); instAttr = nm->mkNode(INST_ATTRIBUTE, sygusScVar); // build in the side condition // exists x. A( x ) ^ input_axioms( x ) // as an additional annotation on the sygus conjecture. In other words, // the abducts A we procedure must be consistent with our axioms. iplc.push_back(instAttr); } Node instAttrList = nm->mkNode(INST_PATTERN_LIST, iplc); Node fbvl = nm->mkNode(BOUND_VAR_LIST, abd); // forall A. exists x. ~( A( x ) => ~input( x ) ) res = nm->mkNode(FORALL, fbvl, res, instAttrList); Trace("sygus-abduct-debug") << "...finish" << std::endl; res = theory::Rewriter::rewrite(res); Trace("sygus-abduct") << "Generate: " << res << std::endl; Node trueNode = nm->mkConst(true); assertionsToPreprocess->replace(0, res); for (size_t i = 1, size = assertionsToPreprocess->size(); i < size; ++i) { assertionsToPreprocess->replace(i, trueNode); } return PreprocessingPassResult::NO_CONFLICT; }
Node TheoryModel::getModelValue(TNode n, bool hasBoundVars) const { Assert(n.getKind() != kind::FORALL && n.getKind() != kind::EXISTS); if(n.getKind() == kind::LAMBDA) { NodeManager* nm = NodeManager::currentNM(); Node body = getModelValue(n[1], true); // This is a bit ugly, but cache inside simplifier can change, so can't be const // The ite simplifier is needed to get rid of artifacts created by Boolean terms body = const_cast<ITESimplifier*>(&d_iteSimp)->simpITE(body); body = Rewriter::rewrite(body); return nm->mkNode(kind::LAMBDA, n[0], body); } if(n.isConst() || (hasBoundVars && n.getKind() == kind::BOUND_VARIABLE)) { return n; } TypeNode t = n.getType(); if (t.isFunction() || t.isPredicate()) { if (d_enableFuncModels) { std::map< Node, Node >::const_iterator it = d_uf_models.find(n); if (it != d_uf_models.end()) { // Existing function return it->second; } // Unknown function symbol: return LAMBDA x. c, where c is the first constant in the enumeration of the range type vector<TypeNode> argTypes = t.getArgTypes(); vector<Node> args; NodeManager* nm = NodeManager::currentNM(); for (unsigned i = 0; i < argTypes.size(); ++i) { args.push_back(nm->mkBoundVar(argTypes[i])); } Node boundVarList = nm->mkNode(kind::BOUND_VAR_LIST, args); TypeEnumerator te(t.getRangeType()); return nm->mkNode(kind::LAMBDA, boundVarList, *te); } // TODO: if func models not enabled, throw an error? Unreachable(); } if (n.getNumChildren() > 0) { std::vector<Node> children; if (n.getKind() == APPLY_UF) { Node op = getModelValue(n.getOperator(), hasBoundVars); children.push_back(op); } else if (n.getMetaKind() == kind::metakind::PARAMETERIZED) { children.push_back(n.getOperator()); } //evaluate the children for (unsigned i = 0; i < n.getNumChildren(); ++i) { Node val = getModelValue(n[i], hasBoundVars); children.push_back(val); } Node val = Rewriter::rewrite(NodeManager::currentNM()->mkNode(n.getKind(), children)); Assert(hasBoundVars || val.isConst()); return val; } if (!d_equalityEngine.hasTerm(n)) { // Unknown term - return first enumerated value for this type TypeEnumerator te(n.getType()); return *te; } Node val = d_equalityEngine.getRepresentative(n); Assert(d_reps.find(val) != d_reps.end()); std::map< Node, Node >::const_iterator it = d_reps.find( val ); if( it!=d_reps.end() ){ return it->second; }else{ return Node::null(); } }
Node PseudoBooleanProcessor::mkGeqOne(Node v) { NodeManager* nm = NodeManager::currentNM(); return nm->mkNode(kind::GEQ, v, mkRationalNode(Rational(1))); }