dep-selector-0.0.8/0000755000175000017500000000000011765170155013421 5ustar tfheentfheendep-selector-0.0.8/metadata.yml0000644000175000017500000000424611765170155015732 0ustar tfheentfheen--- !ruby/object:Gem::Specification name: dep_selector version: !ruby/object:Gem::Version prerelease: false segments: - 0 - 0 - 8 version: 0.0.8 platform: ruby authors: - Christopher Walters - Mark Anderson autorequire: bindir: bin cert_chain: [] date: 2011-05-06 00:00:00 -07:00 default_executable: dependencies: [] description: Given packages, versions, and a dependency graph, find a valid assignment of package versions email: - cw@opscode.com - mark@opscode.com executables: [] extensions: - ext/dep_gecode/extconf.rb extra_rdoc_files: [] files: - lib/dep_selector/densely_packed_set.rb - lib/dep_selector/dep_selector_version.rb - lib/dep_selector/dependency.rb - lib/dep_selector/dependency_graph.rb - lib/dep_selector/error_reporter/simple_tree_traverser.rb - lib/dep_selector/error_reporter.rb - lib/dep_selector/exceptions.rb - lib/dep_selector/gecode_wrapper.rb - lib/dep_selector/package.rb - lib/dep_selector/package_version.rb - lib/dep_selector/selector.rb - lib/dep_selector/solution_constraint.rb - lib/dep_selector/version.rb - lib/dep_selector/version_constraint.rb - lib/dep_selector.rb - ext/dep_gecode/dep_selector_swig.i - ext/dep_gecode/dep_selector_swig_wrap.cxx - ext/dep_gecode/dep_selector_to_gecode.h - ext/dep_gecode/dep_selector_to_gecode_interface.h - ext/dep_gecode/dep_selector_to_gecode.cpp - ext/dep_gecode/dep_selector_to_gecode_interface.cpp - ext/dep_gecode/extconf.rb - ext/dep_gecode/lib/dep_selector_to_gecode.rb has_rdoc: false homepage: http://github.com/algorist/dep_selector licenses: - Apache v2 post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version segments: - 0 version: "0" required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version segments: - 0 version: "0" requirements: - gecode, version 3.5 or greater - g++ rubyforge_project: rubygems_version: 1.3.6 signing_key: specification_version: 3 summary: Given packages, versions, and a dependency graph, find a valid assignment of package versions test_files: [] dep-selector-0.0.8/ext/0000755000175000017500000000000011765170155014221 5ustar tfheentfheendep-selector-0.0.8/ext/dep_gecode/0000755000175000017500000000000011765170155016277 5ustar tfheentfheendep-selector-0.0.8/ext/dep_gecode/extconf.rb0000644000175000017500000000361011765170155020272 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # GECODE needs to be built with # ./configure --with-architectures=i386,x86_64 # to work properly here. require 'mkmf' $LIBS << " -lstdc++" # $CFLAGS << "-g" gecode_installed = have_library('gecodesearch') && have_library('gecodeint') && have_library('gecodekernel') && have_library('gecodesupport') && have_library('gecodeminimodel') unless gecode_installed STDERR.puts <3.5 must be installed (http://www.gecode.org/). OSX: brew install gecode For convenience, we have built Gecode for Debian/Ubuntu ( is lucid or maverick): Add the following two lines to /etc/apt/sources.list.d/opscode.list: deb http://apt.opscode.com main deb-src http://apt.opscode.com main Then run: curl http://apt.opscode.com/packages@opscode.com.gpg.key | sudo apt-key add - sudo apt-get update sudo apt-get install libgecode-dev Other distributions can build from source. ========================================================================================= EOS raise "Gecode not installed" end create_makefile('dep_gecode') dep-selector-0.0.8/ext/dep_gecode/dep_selector_swig_wrap.cxx0000644000175000017500000022621411765170155023564 0ustar tfheentfheen/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.31 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #define SWIGRUBY #ifdef __cplusplus template class SwigValueWrapper { T *tt; public: SwigValueWrapper() : tt(0) { } SwigValueWrapper(const SwigValueWrapper& rhs) : tt(new T(*rhs.tt)) { } SwigValueWrapper(const T& t) : tt(new T(t)) { } ~SwigValueWrapper() { delete tt; } SwigValueWrapper& operator=(const T& t) { delete tt; tt = new T(t); return *this; } operator T&() const { return *tt; } T *operator&() { return tt; } private: SwigValueWrapper& operator=(const SwigValueWrapper& rhs); }; #endif /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) # if (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) # if (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* ----------------------------------------------------------------------------- * swigrun.swg * * This file contains generic CAPI SWIG runtime support for pointer * type checking. * ----------------------------------------------------------------------------- */ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ #define SWIG_RUNTIME_VERSION "3" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE # define SWIG_QUOTE_STRING(x) #x # define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) # define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) #else # define SWIG_TYPE_TABLE_NAME #endif /* You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the swig runtime code. In 99.9% of the cases, swig just needs to declare them as 'static'. But only do this if is strictly necessary, ie, if you have problems with your compiler or so. */ #ifndef SWIGRUNTIME # define SWIGRUNTIME SWIGINTERN #endif #ifndef SWIGRUNTIMEINLINE # define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE #endif /* Generic buffer size */ #ifndef SWIG_BUFFER_SIZE # define SWIG_BUFFER_SIZE 1024 #endif /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 /* Flags/methods for returning states. The swig conversion methods, as ConvertPtr, return and integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). Use the following macros/flags to set or process the returning states. In old swig versions, you usually write code as: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { // success code } else { //fail code } Now you can be more explicit as: int res = SWIG_ConvertPtr(obj,vptr,ty.flags); if (SWIG_IsOK(res)) { // success code } else { // fail code } that seems to be the same, but now you can also do Type *ptr; int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); if (SWIG_IsOK(res)) { // success code if (SWIG_IsNewObj(res) { ... delete *ptr; } else { ... } } else { // fail code } I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that requires also to SWIG_ConvertPtr to return new result values, as int SWIG_ConvertPtr(obj, ptr,...) { if () { if () { *ptr = ; return SWIG_NEWOBJ; } else { *ptr = ; return SWIG_OLDOBJ; } } else { return SWIG_BADOBJ; } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the swig errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code allows to return the 'cast rank', for example, if you have this int food(double) int fooi(int); and you call food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ #define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) #define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) /* The NewMask denotes the object was created (using new/malloc) */ #define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) /* The TmpMask is for in/out typemaps that use temporal objects */ #define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) /* Simple returning values */ #define SWIG_BADOBJ (SWIG_ERROR) #define SWIG_OLDOBJ (SWIG_OK) #define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) #define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) /* Check, add and del mask methods */ #define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) #define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) #define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) #define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) #define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) #define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) /* Cast-Rank Mode */ #if defined(SWIG_CASTRANK_MODE) # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif # ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif #include #ifdef __cplusplus extern "C" { #endif typedef void *(*swig_converter_func)(void *); typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store inforomation on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ struct swig_cast_info *cast; /* linked list of types that can cast into this type */ void *clientdata; /* language specific type data */ int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { swig_type_info *type; /* pointer to type that is equivalent to this type */ swig_converter_func converter; /* function to cast the void pointers */ struct swig_cast_info *next; /* pointer to next cast in linked list */ struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ size_t size; /* Number of types in this module */ struct swig_module_info *next; /* Pointer to next element in circularly linked list */ swig_type_info **type_initial; /* Array of initially generated type structures */ swig_cast_info **cast_initial; /* Array of initially generated casting structures */ void *clientdata; /* Language specific module data */ } swig_module_info; /* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class" == "Class", etc. Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) { for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { while ((*f1 == ' ') && (f1 != l1)) ++f1; while ((*f2 == ' ') && (f2 != l2)) ++f2; if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; } return (l1 - f1) - (l2 - f2); } /* Check type equivalence in a name list like ||... Return 0 if not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like ||... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCompare(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* think of this as a c++ template<> or a scheme macro */ #define SWIG_TypeCheck_Template(comparison, ty) \ if (ty) { \ swig_cast_info *iter = ty->cast; \ while (iter) { \ if (comparison) { \ if (iter == ty->cast) return iter; \ /* Move iter to the top of the linked list */ \ iter->prev->next = iter->next; \ if (iter->next) \ iter->next->prev = iter->prev; \ iter->next = ty->cast; \ iter->prev = 0; \ if (ty->cast) ty->cast->prev = iter; \ ty->cast = iter; \ return iter; \ } \ iter = iter->next; \ } \ } \ return 0 /* Check the typename */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty); } /* Same as previous function, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) { SWIG_TypeCheck_Template(iter->type == from, into); } /* Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr); } /* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { swig_type_info *lastty = ty; if (!ty || !ty->dcast) return ty; while (ty && (ty->dcast)) { ty = (*ty->dcast)(ptr); if (ty) lastty = ty; } return lastty; } /* Return the name associated with this type */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { return ty->name; } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { /* The "str" field contains the equivalent pretty names of the type, separated by vertical-bar characters. We choose to print the last name, as it is often (?) the most specific. */ if (!type) return NULL; if (type->str != NULL) { const char *last_name = type->str; const char *s; for (s = type->str; *s; s++) if (*s == '|') last_name = s+1; return last_name; } else return type->name; } /* Set the clientdata field for a type */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } } cast = cast->next; } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { swig_module_info *iter = start; do { if (iter->size) { register size_t l = 0; register size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ register size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { register int compare = strcmp(name, iname); if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { r = i - 1; } else { break; } } else if (compare > 0) { l = i + 1; } } else { break; /* should never happen */ } } while (l <= r); } iter = iter->next; } while (iter != end); return 0; } /* Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); if (ret) { return ret; } else { /* STEP 2: If the type hasn't been found, do a complete search of the str field (the human readable name) */ swig_module_info *iter = start; do { register size_t i = 0; for (; i < iter->size; ++i) { if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) return iter->types[i]; } iter = iter->next; } while (iter != end); } /* neither found a match */ return 0; } /* Pack binary data into a string */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; register const unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } /* Unpack binary data from a string */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register char d = *(c++); register unsigned char uu; if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } /* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { char *r = buff; if ((2*sizeof(void *) + 2) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,&ptr,sizeof(void *)); if (strlen(name) + 1 > (bsz - (r - buff))) return 0; strcpy(r,name); return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { *ptr = (void *) 0; return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { char *r = buff; size_t lname = (name ? strlen(name) : 0); if ((2*sz + 2 + lname) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); if (lname) { strncpy(r,name,lname+1); } else { *r = 0; } return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { memset(ptr,0,sz); return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus } #endif /* Errors in SWIG */ #define SWIG_UnknownError -1 #define SWIG_IOError -2 #define SWIG_RuntimeError -3 #define SWIG_IndexError -4 #define SWIG_TypeError -5 #define SWIG_DivisionByZero -6 #define SWIG_OverflowError -7 #define SWIG_SyntaxError -8 #define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 #define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 #include /* Ruby 1.7 defines NUM2LL(), LL2NUM() and ULL2NUM() macros */ #ifndef NUM2LL #define NUM2LL(x) NUM2LONG((x)) #endif #ifndef LL2NUM #define LL2NUM(x) INT2NUM((long) (x)) #endif #ifndef ULL2NUM #define ULL2NUM(x) UINT2NUM((unsigned long) (x)) #endif /* Ruby 1.7 doesn't (yet) define NUM2ULL() */ #ifndef NUM2ULL #ifdef HAVE_LONG_LONG #define NUM2ULL(x) rb_num2ull((x)) #else #define NUM2ULL(x) NUM2ULONG(x) #endif #endif /* RSTRING_LEN, etc are new in Ruby 1.9, but ->ptr and ->len no longer work */ /* Define these for older versions so we can just write code the new way */ #ifndef RSTRING_LEN # define RSTRING_LEN(x) RSTRING(x)->len #endif #ifndef RSTRING_PTR # define RSTRING_PTR(x) RSTRING(x)->ptr #endif #ifndef RARRAY_LEN # define RARRAY_LEN(x) RARRAY(x)->len #endif #ifndef RARRAY_PTR # define RARRAY_PTR(x) RARRAY(x)->ptr #endif /* * Need to be very careful about how these macros are defined, especially * when compiling C++ code or C code with an ANSI C compiler. * * VALUEFUNC(f) is a macro used to typecast a C function that implements * a Ruby method so that it can be passed as an argument to API functions * like rb_define_method() and rb_define_singleton_method(). * * VOIDFUNC(f) is a macro used to typecast a C function that implements * either the "mark" or "free" stuff for a Ruby Data object, so that it * can be passed as an argument to API functions like Data_Wrap_Struct() * and Data_Make_Struct(). */ #ifdef __cplusplus # ifndef RUBY_METHOD_FUNC /* These definitions should work for Ruby 1.4.6 */ # define PROTECTFUNC(f) ((VALUE (*)()) f) # define VALUEFUNC(f) ((VALUE (*)()) f) # define VOIDFUNC(f) ((void (*)()) f) # else # ifndef ANYARGS /* These definitions should work for Ruby 1.6 */ # define PROTECTFUNC(f) ((VALUE (*)()) f) # define VALUEFUNC(f) ((VALUE (*)()) f) # define VOIDFUNC(f) ((RUBY_DATA_FUNC) f) # else /* These definitions should work for Ruby 1.7+ */ # define PROTECTFUNC(f) ((VALUE (*)(VALUE)) f) # define VALUEFUNC(f) ((VALUE (*)(ANYARGS)) f) # define VOIDFUNC(f) ((RUBY_DATA_FUNC) f) # endif # endif #else # define VALUEFUNC(f) (f) # define VOIDFUNC(f) (f) #endif /* Don't use for expressions have side effect */ #ifndef RB_STRING_VALUE #define RB_STRING_VALUE(s) (TYPE(s) == T_STRING ? (s) : (*(volatile VALUE *)&(s) = rb_str_to_str(s))) #endif #ifndef StringValue #define StringValue(s) RB_STRING_VALUE(s) #endif #ifndef StringValuePtr #define StringValuePtr(s) RSTRING_PTR(RB_STRING_VALUE(s)) #endif #ifndef StringValueLen #define StringValueLen(s) RSTRING_LEN(RB_STRING_VALUE(s)) #endif #ifndef SafeStringValue #define SafeStringValue(v) do {\ StringValue(v);\ rb_check_safe_str(v);\ } while (0) #endif #ifndef HAVE_RB_DEFINE_ALLOC_FUNC #define rb_define_alloc_func(klass, func) rb_define_singleton_method((klass), "new", VALUEFUNC((func)), -1) #define rb_undef_alloc_func(klass) rb_undef_method(CLASS_OF((klass)), "new") #endif /* ----------------------------------------------------------------------------- * error manipulation * ----------------------------------------------------------------------------- */ /* Define some additional error types */ #define SWIG_ObjectPreviouslyDeletedError -100 /* Define custom exceptions for errors that do not map to existing Ruby exceptions. Note this only works for C++ since a global cannot be initialized by a funtion in C. For C, fallback to rb_eRuntimeError.*/ SWIGINTERN VALUE getNullReferenceError(void) { static int init = 0; static VALUE rb_eNullReferenceError ; if (!init) { init = 1; rb_eNullReferenceError = rb_define_class("NullReferenceError", rb_eRuntimeError); } return rb_eNullReferenceError; } SWIGINTERN VALUE getObjectPreviouslyDeletedError(void) { static int init = 0; static VALUE rb_eObjectPreviouslyDeleted ; if (!init) { init = 1; rb_eObjectPreviouslyDeleted = rb_define_class("ObjectPreviouslyDeleted", rb_eRuntimeError); } return rb_eObjectPreviouslyDeleted; } SWIGINTERN VALUE SWIG_Ruby_ErrorType(int SWIG_code) { VALUE type; switch (SWIG_code) { case SWIG_MemoryError: type = rb_eNoMemError; break; case SWIG_IOError: type = rb_eIOError; break; case SWIG_RuntimeError: type = rb_eRuntimeError; break; case SWIG_IndexError: type = rb_eIndexError; break; case SWIG_TypeError: type = rb_eTypeError; break; case SWIG_DivisionByZero: type = rb_eZeroDivError; break; case SWIG_OverflowError: type = rb_eRangeError; break; case SWIG_SyntaxError: type = rb_eSyntaxError; break; case SWIG_ValueError: type = rb_eArgError; break; case SWIG_SystemError: type = rb_eFatal; break; case SWIG_AttributeError: type = rb_eRuntimeError; break; case SWIG_NullReferenceError: type = getNullReferenceError(); break; case SWIG_ObjectPreviouslyDeletedError: type = getObjectPreviouslyDeletedError(); break; case SWIG_UnknownError: type = rb_eRuntimeError; break; default: type = rb_eRuntimeError; } return type; } /* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * rubytracking.swg * * This file contains support for tracking mappings from * Ruby objects to C++ objects. This functionality is needed * to implement mark functions for Ruby's mark and sweep * garbage collector. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #endif /* Global Ruby hash table to store Trackings from C/C++ structs to Ruby Objects. */ static VALUE swig_ruby_trackings; /* Global variable that stores a reference to the ruby hash table delete function. */ static ID swig_ruby_hash_delete = 0; /* Setup a Ruby hash table to store Trackings */ SWIGRUNTIME void SWIG_RubyInitializeTrackings(void) { /* Create a ruby hash table to store Trackings from C++ objects to Ruby objects. Also make sure to tell the garabage collector about the hash table. */ swig_ruby_trackings = rb_hash_new(); rb_gc_register_address(&swig_ruby_trackings); /* Now store a reference to the hash table delete function so that we only have to look it up once.*/ swig_ruby_hash_delete = rb_intern("delete"); } /* Get a Ruby number to reference a pointer */ SWIGRUNTIME VALUE SWIG_RubyPtrToReference(void* ptr) { /* We cast the pointer to an unsigned long and then store a reference to it using a Ruby number object. */ /* Convert the pointer to a Ruby number */ unsigned long value = (unsigned long) ptr; return LONG2NUM(value); } /* Get a Ruby number to reference an object */ SWIGRUNTIME VALUE SWIG_RubyObjectToReference(VALUE object) { /* We cast the object to an unsigned long and then store a reference to it using a Ruby number object. */ /* Convert the Object to a Ruby number */ unsigned long value = (unsigned long) object; return LONG2NUM(value); } /* Get a Ruby object from a previously stored reference */ SWIGRUNTIME VALUE SWIG_RubyReferenceToObject(VALUE reference) { /* The provided Ruby number object is a reference to the Ruby object we want.*/ /* First convert the Ruby number to a C number */ unsigned long value = NUM2LONG(reference); return (VALUE) value; } /* Add a Tracking from a C/C++ struct to a Ruby object */ SWIGRUNTIME void SWIG_RubyAddTracking(void* ptr, VALUE object) { /* In a Ruby hash table we store the pointer and the associated Ruby object. The trick here is that we cannot store the Ruby object directly - if we do then it cannot be garbage collected. So instead we typecast it as a unsigned long and convert it to a Ruby number object.*/ /* Get a reference to the pointer as a Ruby number */ VALUE key = SWIG_RubyPtrToReference(ptr); /* Get a reference to the Ruby object as a Ruby number */ VALUE value = SWIG_RubyObjectToReference(object); /* Store the mapping to the global hash table. */ rb_hash_aset(swig_ruby_trackings, key, value); } /* Get the Ruby object that owns the specified C/C++ struct */ SWIGRUNTIME VALUE SWIG_RubyInstanceFor(void* ptr) { /* Get a reference to the pointer as a Ruby number */ VALUE key = SWIG_RubyPtrToReference(ptr); /* Now lookup the value stored in the global hash table */ VALUE value = rb_hash_aref(swig_ruby_trackings, key); if (value == Qnil) { /* No object exists - return nil. */ return Qnil; } else { /* Convert this value to Ruby object */ return SWIG_RubyReferenceToObject(value); } } /* Remove a Tracking from a C/C++ struct to a Ruby object. It is very important to remove objects once they are destroyed since the same memory address may be reused later to create a new object. */ SWIGRUNTIME void SWIG_RubyRemoveTracking(void* ptr) { /* Get a reference to the pointer as a Ruby number */ VALUE key = SWIG_RubyPtrToReference(ptr); /* Delete the object from the hash table by calling Ruby's do this we need to call the Hash.delete method.*/ rb_funcall(swig_ruby_trackings, swig_ruby_hash_delete, 1, key); } /* This is a helper method that unlinks a Ruby object from its underlying C++ object. This is needed if the lifetime of the Ruby object is longer than the C++ object */ SWIGRUNTIME void SWIG_RubyUnlinkObjects(void* ptr) { VALUE object = SWIG_RubyInstanceFor(ptr); if (object != Qnil) { DATA_PTR(object) = 0; } } #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * Ruby API portion that goes into the runtime * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #endif SWIGINTERN VALUE SWIG_Ruby_AppendOutput(VALUE target, VALUE o) { if (NIL_P(target)) { target = o; } else { if (TYPE(target) != T_ARRAY) { VALUE o2 = target; target = rb_ary_new(); rb_ary_push(target, o2); } rb_ary_push(target, o); } return target; } #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * rubyrun.swg * * This file contains the runtime support for Ruby modules * and includes code for managing global variables and pointer * type checking. * ----------------------------------------------------------------------------- */ /* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 /* for raw pointers */ #define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Ruby_ConvertPtrAndOwn(obj, pptr, type, flags, 0) #define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Ruby_ConvertPtrAndOwn(obj, pptr, type, flags, own) #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Ruby_NewPointerObj(ptr, type, flags) #define SWIG_AcquirePtr(ptr, own) SWIG_Ruby_AcquirePtr(ptr, own) #define swig_owntype ruby_owntype /* for raw packed data */ #define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Ruby_ConvertPacked(obj, ptr, sz, ty, flags) #define SWIG_NewPackedObj(ptr, sz, type) SWIG_Ruby_NewPackedObj(ptr, sz, type) /* for class or struct pointers */ #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) #define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) /* for C or C++ function pointers */ #define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_ConvertPtr(obj, pptr, type, 0) #define SWIG_NewFunctionPtrObj(ptr, type) SWIG_NewPointerObj(ptr, type, 0) /* for C++ member pointers, ie, member methods */ #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Ruby_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIG_Ruby_NewPackedObj(ptr, sz, type) /* Runtime API */ #define SWIG_GetModule(clientdata) SWIG_Ruby_GetModule() #define SWIG_SetModule(clientdata, pointer) SWIG_Ruby_SetModule(pointer) /* Error manipulation */ #define SWIG_ErrorType(code) SWIG_Ruby_ErrorType(code) #define SWIG_Error(code, msg) rb_raise(SWIG_Ruby_ErrorType(code), msg) #define SWIG_fail goto fail /* Ruby-specific SWIG API */ #define SWIG_InitRuntime() SWIG_Ruby_InitRuntime() #define SWIG_define_class(ty) SWIG_Ruby_define_class(ty) #define SWIG_NewClassInstance(value, ty) SWIG_Ruby_NewClassInstance(value, ty) #define SWIG_MangleStr(value) SWIG_Ruby_MangleStr(value) #define SWIG_CheckConvert(value, ty) SWIG_Ruby_CheckConvert(value, ty) /* ----------------------------------------------------------------------------- * pointers/data manipulation * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* cc-mode */ #endif #endif typedef struct { VALUE klass; VALUE mImpl; void (*mark)(void *); void (*destroy)(void *); int trackObjects; } swig_class; static VALUE _mSWIG = Qnil; static VALUE _cSWIG_Pointer = Qnil; static VALUE swig_runtime_data_type_pointer = Qnil; SWIGRUNTIME VALUE getExceptionClass(void) { static int init = 0; static VALUE rubyExceptionClass ; if (!init) { init = 1; rubyExceptionClass = rb_const_get(_mSWIG, rb_intern("Exception")); } return rubyExceptionClass; } /* This code checks to see if the Ruby object being raised as part of an exception inherits from the Ruby class Exception. If so, the object is simply returned. If not, then a new Ruby exception object is created and that will be returned to Ruby.*/ SWIGRUNTIME VALUE SWIG_Ruby_ExceptionType(swig_type_info *desc, VALUE obj) { VALUE exceptionClass = getExceptionClass(); if (rb_obj_is_kind_of(obj, exceptionClass)) { return obj; } else { return rb_exc_new3(rb_eRuntimeError, rb_obj_as_string(obj)); } } /* Initialize Ruby runtime support */ SWIGRUNTIME void SWIG_Ruby_InitRuntime(void) { if (_mSWIG == Qnil) { _mSWIG = rb_define_module("SWIG"); } } /* Define Ruby class for C type */ SWIGRUNTIME void SWIG_Ruby_define_class(swig_type_info *type) { VALUE klass; char *klass_name = (char *) malloc(4 + strlen(type->name) + 1); sprintf(klass_name, "TYPE%s", type->name); if (NIL_P(_cSWIG_Pointer)) { _cSWIG_Pointer = rb_define_class_under(_mSWIG, "Pointer", rb_cObject); rb_undef_method(CLASS_OF(_cSWIG_Pointer), "new"); } klass = rb_define_class_under(_mSWIG, klass_name, _cSWIG_Pointer); free((void *) klass_name); } /* Create a new pointer object */ SWIGRUNTIME VALUE SWIG_Ruby_NewPointerObj(void *ptr, swig_type_info *type, int flags) { int own = flags & SWIG_POINTER_OWN; char *klass_name; swig_class *sklass; VALUE klass; VALUE obj; if (!ptr) return Qnil; if (type->clientdata) { sklass = (swig_class *) type->clientdata; /* Are we tracking this class and have we already returned this Ruby object? */ if (sklass->trackObjects) { obj = SWIG_RubyInstanceFor(ptr); /* Check the object's type and make sure it has the correct type. It might not in cases where methods do things like downcast methods. */ if (obj != Qnil) { VALUE value = rb_iv_get(obj, "__swigtype__"); char* type_name = RSTRING_PTR(value); if (strcmp(type->name, type_name) == 0) { return obj; } } } /* Create a new Ruby object */ obj = Data_Wrap_Struct(sklass->klass, VOIDFUNC(sklass->mark), (own ? VOIDFUNC(sklass->destroy) : 0), ptr); /* If tracking is on for this class then track this object. */ if (sklass->trackObjects) { SWIG_RubyAddTracking(ptr, obj); } } else { klass_name = (char *) malloc(4 + strlen(type->name) + 1); sprintf(klass_name, "TYPE%s", type->name); klass = rb_const_get(_mSWIG, rb_intern(klass_name)); free((void *) klass_name); obj = Data_Wrap_Struct(klass, 0, 0, ptr); } rb_iv_set(obj, "__swigtype__", rb_str_new2(type->name)); return obj; } /* Create a new class instance (always owned) */ SWIGRUNTIME VALUE SWIG_Ruby_NewClassInstance(VALUE klass, swig_type_info *type) { VALUE obj; swig_class *sklass = (swig_class *) type->clientdata; obj = Data_Wrap_Struct(klass, VOIDFUNC(sklass->mark), VOIDFUNC(sklass->destroy), 0); rb_iv_set(obj, "__swigtype__", rb_str_new2(type->name)); return obj; } /* Get type mangle from class name */ SWIGRUNTIMEINLINE char * SWIG_Ruby_MangleStr(VALUE obj) { VALUE stype = rb_iv_get(obj, "__swigtype__"); return StringValuePtr(stype); } /* Acquire a pointer value */ typedef void (*ruby_owntype)(void*); SWIGRUNTIME ruby_owntype SWIG_Ruby_AcquirePtr(VALUE obj, ruby_owntype own) { if (obj) { ruby_owntype oldown = RDATA(obj)->dfree; RDATA(obj)->dfree = own; return oldown; } else { return 0; } } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Ruby_ConvertPtrAndOwn(VALUE obj, void **ptr, swig_type_info *ty, int flags, ruby_owntype *own) { char *c; swig_cast_info *tc; void *vptr = 0; /* Grab the pointer */ if (NIL_P(obj)) { *ptr = 0; return SWIG_OK; } else { if (TYPE(obj) != T_DATA) { return SWIG_ERROR; } Data_Get_Struct(obj, void, vptr); } if (own) *own = RDATA(obj)->dfree; /* Check to see if the input object is giving up ownership of the underlying C struct or C++ object. If so then we need to reset the destructor since the Ruby object no longer owns the underlying C++ object.*/ if (flags & SWIG_POINTER_DISOWN) { /* Is tracking on for this class? */ int track = 0; if (ty && ty->clientdata) { swig_class *sklass = (swig_class *) ty->clientdata; track = sklass->trackObjects; } if (track) { /* We are tracking objects for this class. Thus we change the destructor * to SWIG_RubyRemoveTracking. This allows us to * remove the mapping from the C++ to Ruby object * when the Ruby object is garbage collected. If we don't * do this, then it is possible we will return a reference * to a Ruby object that no longer exists thereby crashing Ruby. */ RDATA(obj)->dfree = SWIG_RubyRemoveTracking; } else { RDATA(obj)->dfree = 0; } } /* Do type-checking if type info was provided */ if (ty) { if (ty->clientdata) { if (rb_obj_is_kind_of(obj, ((swig_class *) (ty->clientdata))->klass)) { if (vptr == 0) { /* The object has already been deleted */ return SWIG_ObjectPreviouslyDeletedError; } *ptr = vptr; return SWIG_OK; } } if ((c = SWIG_MangleStr(obj)) == NULL) { return SWIG_ERROR; } tc = SWIG_TypeCheck(c, ty); if (!tc) { return SWIG_ERROR; } *ptr = SWIG_TypeCast(tc, vptr); } else { *ptr = vptr; } return SWIG_OK; } /* Check convert */ SWIGRUNTIMEINLINE int SWIG_Ruby_CheckConvert(VALUE obj, swig_type_info *ty) { char *c = SWIG_MangleStr(obj); if (!c) return 0; return SWIG_TypeCheck(c,ty) != 0; } SWIGRUNTIME VALUE SWIG_Ruby_NewPackedObj(void *ptr, int sz, swig_type_info *type) { char result[1024]; char *r = result; if ((2*sz + 1 + strlen(type->name)) > 1000) return 0; *(r++) = '_'; r = SWIG_PackData(r, ptr, sz); strcpy(r, type->name); return rb_str_new2(result); } /* Convert a packed value value */ SWIGRUNTIME int SWIG_Ruby_ConvertPacked(VALUE obj, void *ptr, int sz, swig_type_info *ty) { swig_cast_info *tc; const char *c; if (TYPE(obj) != T_STRING) goto type_error; c = StringValuePtr(obj); /* Pointer values must start with leading underscore */ if (*c != '_') goto type_error; c++; c = SWIG_UnpackData(c, ptr, sz); if (ty) { tc = SWIG_TypeCheck(c, ty); if (!tc) goto type_error; } return SWIG_OK; type_error: return SWIG_ERROR; } SWIGRUNTIME swig_module_info * SWIG_Ruby_GetModule(void) { VALUE pointer; swig_module_info *ret = 0; VALUE verbose = rb_gv_get("VERBOSE"); /* temporarily disable warnings, since the pointer check causes warnings with 'ruby -w' */ rb_gv_set("VERBOSE", Qfalse); /* first check if pointer already created */ pointer = rb_gv_get("$swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); if (pointer != Qnil) { Data_Get_Struct(pointer, swig_module_info, ret); } /* reinstate warnings */ rb_gv_set("VERBOSE", verbose); return ret; } SWIGRUNTIME void SWIG_Ruby_SetModule(swig_module_info *pointer) { /* register a new class */ VALUE cl = rb_define_class("swig_runtime_data", rb_cObject); /* create and store the structure pointer to a global variable */ swig_runtime_data_type_pointer = Data_Wrap_Struct(cl, 0, 0, pointer); rb_define_readonly_variable("$swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, &swig_runtime_data_type_pointer); } #ifdef __cplusplus #if 0 { /* cc-mode */ #endif } #endif #define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) #define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else /* -------- TYPES TABLE (BEGIN) -------- */ #define SWIGTYPE_p_VersionProblem swig_types[0] #define SWIGTYPE_p_char swig_types[1] static swig_type_info *swig_types[3]; static swig_module_info swig_module = {swig_types, 2, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #define SWIG_init Init_dep_gecode #define SWIG_name "Dep_gecode" static VALUE mDep_gecode; #define SWIGVERSION 0x010331 #define SWIG_VERSION SWIGVERSION #define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) #define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) #include #include "dep_selector_to_gecode_interface.h" #include #ifndef LLONG_MIN # define LLONG_MIN LONG_LONG_MIN #endif #ifndef LLONG_MAX # define LLONG_MAX LONG_LONG_MAX #endif #ifndef ULLONG_MAX # define ULLONG_MAX ULONG_LONG_MAX #endif SWIGINTERN VALUE SWIG_ruby_failed(void) { return Qnil; } /*@SWIG:%ruby_aux_method@*/ SWIGINTERN VALUE SWIG_AUX_NUM2LONG(VALUE *args) { VALUE obj = args[0]; VALUE type = TYPE(obj); long *res = (long *)(args[1]); *res = type == T_FIXNUM ? NUM2LONG(obj) : rb_big2long(obj); return obj; } /*@SWIG@*/ SWIGINTERN int SWIG_AsVal_long (VALUE obj, long* val) { VALUE type = TYPE(obj); if ((type == T_FIXNUM) || (type == T_BIGNUM)) { long v; VALUE a[2]; a[0] = obj; a[1] = (VALUE)(&v); if (rb_rescue(RUBY_METHOD_FUNC(SWIG_AUX_NUM2LONG), (VALUE)a, RUBY_METHOD_FUNC(SWIG_ruby_failed), 0) != Qnil) { if (val) *val = v; return SWIG_OK; } } return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_int (VALUE obj, int *val) { long v; int res = SWIG_AsVal_long (obj, &v); if (SWIG_IsOK(res)) { if ((v < INT_MIN || v > INT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = static_cast< int >(v); } } return res; } SWIGINTERN int SWIG_AsVal_bool (VALUE obj, bool *val) { if (obj == Qtrue) { if (val) *val = true; return SWIG_OK; } else if (obj == Qfalse) { if (val) *val = false; return SWIG_OK; } else { int res = 0; if (SWIG_AsVal_int (obj, &res) == SWIG_OK) { if (val) *val = res ? true : false; return SWIG_OK; } } return SWIG_TypeError; } #define SWIG_From_long LONG2NUM SWIGINTERNINLINE VALUE SWIG_From_int (int value) { return SWIG_From_long (value); } SWIGINTERNINLINE VALUE SWIG_From_bool (bool value) { return value ? Qtrue : Qfalse; } SWIGINTERN VALUE _wrap_VersionProblemCreate(int argc, VALUE *argv, VALUE self) { int arg1 ; bool arg2 ; bool arg3 ; VersionProblem *result = 0 ; int val1 ; int ecode1 = 0 ; bool val2 ; int ecode2 = 0 ; bool val3 ; int ecode3 = 0 ; VALUE vresult = Qnil; if ((argc < 3) || (argc > 3)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 3)",argc); SWIG_fail; } ecode1 = SWIG_AsVal_int(argv[0], &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "VersionProblemCreate" "', argument " "1"" of type '" "int""'"); } arg1 = static_cast< int >(val1); ecode2 = SWIG_AsVal_bool(argv[1], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "VersionProblemCreate" "', argument " "2"" of type '" "bool""'"); } arg2 = static_cast< bool >(val2); ecode3 = SWIG_AsVal_bool(argv[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "VersionProblemCreate" "', argument " "3"" of type '" "bool""'"); } arg3 = static_cast< bool >(val3); result = (VersionProblem *)VersionProblemCreate(arg1,arg2,arg3); vresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_VersionProblem, 0 | 0 ); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_VersionProblemDestroy(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; void *argp1 = 0 ; int res1 = 0 ; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "VersionProblemDestroy" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); VersionProblemDestroy(arg1); return Qnil; fail: return Qnil; } SWIGINTERN VALUE _wrap_VersionProblemSize(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "VersionProblemSize" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); result = (int)VersionProblemSize(arg1); vresult = SWIG_From_int(static_cast< int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_VersionProblemPackageCount(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "VersionProblemPackageCount" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); result = (int)VersionProblemPackageCount(arg1); vresult = SWIG_From_int(static_cast< int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_AddPackage(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int arg2 ; int arg3 ; int arg4 ; int result; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; int val3 ; int ecode3 = 0 ; int val4 ; int ecode4 = 0 ; VALUE vresult = Qnil; if ((argc < 4) || (argc > 4)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 4)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "AddPackage" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); ecode2 = SWIG_AsVal_int(argv[1], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "AddPackage" "', argument " "2"" of type '" "int""'"); } arg2 = static_cast< int >(val2); ecode3 = SWIG_AsVal_int(argv[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "AddPackage" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); ecode4 = SWIG_AsVal_int(argv[3], &val4); if (!SWIG_IsOK(ecode4)) { SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "AddPackage" "', argument " "4"" of type '" "int""'"); } arg4 = static_cast< int >(val4); result = (int)AddPackage(arg1,arg2,arg3,arg4); vresult = SWIG_From_int(static_cast< int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_AddVersionConstraint(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int arg2 ; int arg3 ; int arg4 ; int arg5 ; int arg6 ; bool result; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; int val3 ; int ecode3 = 0 ; int val4 ; int ecode4 = 0 ; int val5 ; int ecode5 = 0 ; int val6 ; int ecode6 = 0 ; VALUE vresult = Qnil; if ((argc < 6) || (argc > 6)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 6)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "AddVersionConstraint" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); ecode2 = SWIG_AsVal_int(argv[1], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "AddVersionConstraint" "', argument " "2"" of type '" "int""'"); } arg2 = static_cast< int >(val2); ecode3 = SWIG_AsVal_int(argv[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "AddVersionConstraint" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); ecode4 = SWIG_AsVal_int(argv[3], &val4); if (!SWIG_IsOK(ecode4)) { SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "AddVersionConstraint" "', argument " "4"" of type '" "int""'"); } arg4 = static_cast< int >(val4); ecode5 = SWIG_AsVal_int(argv[4], &val5); if (!SWIG_IsOK(ecode5)) { SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "AddVersionConstraint" "', argument " "5"" of type '" "int""'"); } arg5 = static_cast< int >(val5); ecode6 = SWIG_AsVal_int(argv[5], &val6); if (!SWIG_IsOK(ecode6)) { SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "AddVersionConstraint" "', argument " "6"" of type '" "int""'"); } arg6 = static_cast< int >(val6); result = (bool)AddVersionConstraint(arg1,arg2,arg3,arg4,arg5,arg6); vresult = SWIG_From_bool(static_cast< bool >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_MarkPackageSuspicious(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; if ((argc < 2) || (argc > 2)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MarkPackageSuspicious" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); ecode2 = SWIG_AsVal_int(argv[1], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MarkPackageSuspicious" "', argument " "2"" of type '" "int""'"); } arg2 = static_cast< int >(val2); MarkPackageSuspicious(arg1,arg2); return Qnil; fail: return Qnil; } SWIGINTERN VALUE _wrap_MarkPackageRequired(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; if ((argc < 2) || (argc > 2)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MarkPackageRequired" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); ecode2 = SWIG_AsVal_int(argv[1], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MarkPackageRequired" "', argument " "2"" of type '" "int""'"); } arg2 = static_cast< int >(val2); MarkPackageRequired(arg1,arg2); return Qnil; fail: return Qnil; } SWIGINTERN VALUE _wrap_MarkPackagePreferredToBeAtLatest(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int arg2 ; int arg3 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; int val3 ; int ecode3 = 0 ; if ((argc < 3) || (argc > 3)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 3)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MarkPackagePreferredToBeAtLatest" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); ecode2 = SWIG_AsVal_int(argv[1], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MarkPackagePreferredToBeAtLatest" "', argument " "2"" of type '" "int""'"); } arg2 = static_cast< int >(val2); ecode3 = SWIG_AsVal_int(argv[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "MarkPackagePreferredToBeAtLatest" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); MarkPackagePreferredToBeAtLatest(arg1,arg2,arg3); return Qnil; fail: return Qnil; } SWIGINTERN VALUE _wrap_GetPackageVersion(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int arg2 ; int result; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; VALUE vresult = Qnil; if ((argc < 2) || (argc > 2)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetPackageVersion" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); ecode2 = SWIG_AsVal_int(argv[1], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "GetPackageVersion" "', argument " "2"" of type '" "int""'"); } arg2 = static_cast< int >(val2); result = (int)GetPackageVersion(arg1,arg2); vresult = SWIG_From_int(static_cast< int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_GetPackageDisabledState(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int arg2 ; bool result; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; VALUE vresult = Qnil; if ((argc < 2) || (argc > 2)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetPackageDisabledState" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); ecode2 = SWIG_AsVal_int(argv[1], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "GetPackageDisabledState" "', argument " "2"" of type '" "int""'"); } arg2 = static_cast< int >(val2); result = (bool)GetPackageDisabledState(arg1,arg2); vresult = SWIG_From_bool(static_cast< bool >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_GetPackageMax(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int arg2 ; int result; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; VALUE vresult = Qnil; if ((argc < 2) || (argc > 2)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetPackageMax" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); ecode2 = SWIG_AsVal_int(argv[1], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "GetPackageMax" "', argument " "2"" of type '" "int""'"); } arg2 = static_cast< int >(val2); result = (int)GetPackageMax(arg1,arg2); vresult = SWIG_From_int(static_cast< int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_GetPackageMin(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int arg2 ; int result; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; VALUE vresult = Qnil; if ((argc < 2) || (argc > 2)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetPackageMin" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); ecode2 = SWIG_AsVal_int(argv[1], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "GetPackageMin" "', argument " "2"" of type '" "int""'"); } arg2 = static_cast< int >(val2); result = (int)GetPackageMin(arg1,arg2); vresult = SWIG_From_int(static_cast< int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_GetDisabledVariableCount(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetDisabledVariableCount" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); result = (int)GetDisabledVariableCount(arg1); vresult = SWIG_From_int(static_cast< int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_VersionProblemDump(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; void *argp1 = 0 ; int res1 = 0 ; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "VersionProblemDump" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); VersionProblemDump(arg1); return Qnil; fail: return Qnil; } SWIGINTERN VALUE _wrap_VersionProblemPrintPackageVar(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; if ((argc < 2) || (argc > 2)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "VersionProblemPrintPackageVar" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); ecode2 = SWIG_AsVal_int(argv[1], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "VersionProblemPrintPackageVar" "', argument " "2"" of type '" "int""'"); } arg2 = static_cast< int >(val2); VersionProblemPrintPackageVar(arg1,arg2); return Qnil; fail: return Qnil; } SWIGINTERN VALUE _wrap_Solve(int argc, VALUE *argv, VALUE self) { VersionProblem *arg1 = (VersionProblem *) 0 ; VersionProblem *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_VersionProblem, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Solve" "', argument " "1"" of type '" "VersionProblem *""'"); } arg1 = reinterpret_cast< VersionProblem * >(argp1); result = (VersionProblem *)Solve(arg1); vresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_VersionProblem, 0 | 0 ); return vresult; fail: return Qnil; } /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static swig_type_info _swigt__p_VersionProblem = {"_p_VersionProblem", "VersionProblem *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_VersionProblem, &_swigt__p_char, }; static swig_cast_info _swigc__p_VersionProblem[] = { {&_swigt__p_VersionProblem, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_VersionProblem, _swigc__p_char, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; int found; clientdata = clientdata; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ found=0; iter=module_head; do { if (iter==&swig_module) { found=1; break; } iter=iter->next; } while (iter!= module_head); /* if the is found in the list, then all is done and we may leave */ if (found) return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #ifdef __cplusplus extern "C" #endif SWIGEXPORT void Init_dep_gecode(void) { size_t i; SWIG_InitRuntime(); mDep_gecode = rb_define_module("Dep_gecode"); SWIG_InitializeModule(0); for (i = 0; i < swig_module.size; i++) { SWIG_define_class(swig_module.types[i]); } SWIG_RubyInitializeTrackings(); rb_define_module_function(mDep_gecode, "VersionProblemCreate", VALUEFUNC(_wrap_VersionProblemCreate), -1); rb_define_module_function(mDep_gecode, "VersionProblemDestroy", VALUEFUNC(_wrap_VersionProblemDestroy), -1); rb_define_module_function(mDep_gecode, "VersionProblemSize", VALUEFUNC(_wrap_VersionProblemSize), -1); rb_define_module_function(mDep_gecode, "VersionProblemPackageCount", VALUEFUNC(_wrap_VersionProblemPackageCount), -1); rb_define_module_function(mDep_gecode, "AddPackage", VALUEFUNC(_wrap_AddPackage), -1); rb_define_module_function(mDep_gecode, "AddVersionConstraint", VALUEFUNC(_wrap_AddVersionConstraint), -1); rb_define_module_function(mDep_gecode, "MarkPackageSuspicious", VALUEFUNC(_wrap_MarkPackageSuspicious), -1); rb_define_module_function(mDep_gecode, "MarkPackageRequired", VALUEFUNC(_wrap_MarkPackageRequired), -1); rb_define_module_function(mDep_gecode, "MarkPackagePreferredToBeAtLatest", VALUEFUNC(_wrap_MarkPackagePreferredToBeAtLatest), -1); rb_define_module_function(mDep_gecode, "GetPackageVersion", VALUEFUNC(_wrap_GetPackageVersion), -1); rb_define_module_function(mDep_gecode, "GetPackageDisabledState", VALUEFUNC(_wrap_GetPackageDisabledState), -1); rb_define_module_function(mDep_gecode, "GetPackageMax", VALUEFUNC(_wrap_GetPackageMax), -1); rb_define_module_function(mDep_gecode, "GetPackageMin", VALUEFUNC(_wrap_GetPackageMin), -1); rb_define_module_function(mDep_gecode, "GetDisabledVariableCount", VALUEFUNC(_wrap_GetDisabledVariableCount), -1); rb_define_module_function(mDep_gecode, "VersionProblemDump", VALUEFUNC(_wrap_VersionProblemDump), -1); rb_define_module_function(mDep_gecode, "VersionProblemPrintPackageVar", VALUEFUNC(_wrap_VersionProblemPrintPackageVar), -1); rb_define_module_function(mDep_gecode, "Solve", VALUEFUNC(_wrap_Solve), -1); } dep-selector-0.0.8/ext/dep_gecode/dep_selector_to_gecode.h0000644000175000017500000001070111765170155023127 0ustar tfheentfheen// // Author:: Christopher Walters () // Author:: Mark Anderson () // Copyright:: Copyright (c) 2010-2011 Opscode, Inc. // License:: Apache License, Version 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef dep_selector_to_gecode_h #define dep_selector_to_gecode_h #include "dep_selector_to_gecode_interface.h" #include #include #include #include #include #include using namespace Gecode; // TODO: // Allow retrieval of multiple solutions // Understand how assign versions where necessary, and not assign unnecessary versions. // Understand how to assign empty versions // // Extend: // Add optimization functions // Allow non-contiguous ranges in package dependencies. // TODO: Add locking struct VersionProblemPool { std::set elems; VersionProblemPool(); ~VersionProblemPool(); void Add(VersionProblem * vp); void Delete(VersionProblem *vp); void ShowAll(); void DeleteAll(); }; class VersionProblem : public Space { public: static const int UNRESOLVED_VARIABLE; static const int MIN_TRUST_LEVEL; static const int MAX_TRUST_LEVEL; static const int MAX_PREFERRED_WEIGHT; VersionProblem(int packageCount, bool dumpStats = true, bool debug = false); // Clone constructor; check gecode rules for this... VersionProblem(bool share, VersionProblem & s); virtual ~VersionProblem(); int Size(); int PackageCount(); IntVar & GetPackageVersionVar(int packageId); virtual int AddPackage(int minVersion, int maxVersion, int currentVersion); virtual bool AddVersionConstraint(int packageId, int version, int dependentPackageId, int minDependentVersion, int maxDependentVersion); // We may wish to indicate that some packages have suspicious constraints, and when chosing packages to disable we // would disable them first. void MarkPackageSuspicious(int packageId); void MarkPackageRequired(int packageId); // Packages marked by this method are preferentially chosen at // latest according to weights void MarkPackagePreferredToBeAtLatest(int packageId, int weight); void Finalize(); virtual void constrain(const Space & _best_known_solution); int GetPackageVersion(int packageId); bool GetPackageDisabledState(int packageId); int GetMax(int packageId); int GetMin(int packageId); int GetDisabledVariableCount(); // Support for gecode virtual Space* copy(bool share); // Debug and utility functions void Print(std::ostream &out); void PrintPackageVar(std::ostream & out, int packageId) ; static VersionProblem *InnerSolve(VersionProblem * problem, int & itercount); static VersionProblem *Solve(VersionProblem *problem); protected: int size; int version_constraint_count; int cur_package; bool dump_stats; bool debug_logging; bool finalized; BoolVarArgs version_flags; IntVarArray package_versions; BoolVarArray disabled_package_variables; IntVar total_disabled; IntVar total_required_disabled; IntVar total_induced_disabled; IntVar total_suspicious_disabled; BoolVarArray at_latest; IntVar total_preferred_at_latest; IntVar total_not_preferred_at_latest; int * preferred_at_latest_weights; int * is_required; int * is_suspicious; VersionProblemPool *pool; bool CheckPackageId(int id); void AddPackagesPreferredToBeAtLatestObjectiveFunction(const VersionProblem & best_known_solution); void ConstrainVectorLessThanBest(IntVarArgs & current, IntVarArgs & best); void BuildCostVector(IntVarArgs & costVector) const; friend class VersionProblemPool; }; template void PrintVarAligned(const char * message, T & var); template void PrintVarAligned(const char * message, S & var1, T & var2); class Solver { public: Solver(VersionProblem *s); VersionProblem GetNextSolution(); private: Restart solver; }; #endif // dep_selector_to_gecode_h dep-selector-0.0.8/ext/dep_gecode/dep_selector_swig.i0000644000175000017500000000434611765170155022161 0ustar tfheentfheen// // Author:: Christopher Walters () // Author:: Mark Anderson () // Copyright:: Copyright (c) 2010-2011 Opscode, Inc. // License:: Apache License, Version 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // // swig -c++ -ruby dep_selector_swig.i // %module "dep_gecode" %{ #include "dep_selector_to_gecode_interface.h" %} class VersionProblem; VersionProblem * VersionProblemCreate(int packageCount, bool dumpStats, bool debug); void VersionProblemDestroy(VersionProblem * vp); int VersionProblemSize(VersionProblem *p); int VersionProblemPackageCount(VersionProblem *p); // Return ID # int AddPackage(VersionProblem *problem, int min, int max, int currentVersion); // Add constraint for package pkg @ version, // that dependentPackage is at version [minDependentVersion,maxDependentVersion] // Returns false if system becomes insoluble. bool AddVersionConstraint(VersionProblem *problem, int packageId, int version, int dependentPackageId, int minDependentVersion, int maxDependentVersion); void MarkPackageSuspicious(VersionProblem *problem, int packageId); void MarkPackageRequired(VersionProblem *problem, int packageId); void MarkPackagePreferredToBeAtLatest(VersionProblem *problem, int packageId, int weight); int GetPackageVersion(VersionProblem *problem, int packageId); bool GetPackageDisabledState(VersionProblem *problem, int packageId); int GetPackageMax(VersionProblem *problem, int packageId); int GetPackageMin(VersionProblem *problem, int packageId); int GetDisabledVariableCount(VersionProblem *problem); void VersionProblemDump(VersionProblem * problem); void VersionProblemPrintPackageVar(VersionProblem * problem, int packageId); VersionProblem * Solve(VersionProblem * problem); dep-selector-0.0.8/ext/dep_gecode/dep_selector_to_gecode_interface.h0000644000175000017500000000476011765170155025157 0ustar tfheentfheen// // Author:: Christopher Walters () // Author:: Mark Anderson () // Copyright:: Copyright (c) 2010-2011 Opscode, Inc. // License:: Apache License, Version 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef dep_selector_to_gecode_interface_h #define dep_selector_to_gecode_interface_h // Conceptual Api #ifdef __cplusplus extern "C" { #endif // __cplusplus #ifdef __cplusplus class VersionProblem; #else typedef struct VersionProblem VersionProblem; #endif // __cplusplus VersionProblem * VersionProblemCreate(int packageCount, bool dumpStats, bool debug); void VersionProblemDestroy(VersionProblem * vp); int VersionProblemSize(VersionProblem *p); int VersionProblemPackageCount(VersionProblem *p); // Return ID # int AddPackage(VersionProblem *problem, int min, int max, int currentVersion); // Add constraint for package pkg @ version, // that dependentPackage is at version [minDependentVersion,maxDependentVersion] // Returns false if system becomes insoluble. bool AddVersionConstraint(VersionProblem *problem, int packageId, int version, int dependentPackageId, int minDependentVersion, int maxDependentVersion); void MarkPackageSuspicious(VersionProblem *problem, int packageId); void MarkPackageRequired(VersionProblem *problem, int packageId); void MarkPackagePreferredToBeAtLatest(VersionProblem *problem, int packageId, int weight); int GetPackageVersion(VersionProblem *problem, int packageId); bool GetPackageDisabledState(VersionProblem *problem, int packageId); int GetPackageMax(VersionProblem *problem, int packageId); int GetPackageMin(VersionProblem *problem, int packageId); int GetDisabledVariableCount(VersionProblem *problem); void VersionProblemDump(VersionProblem * problem); void VersionProblemPrintPackageVar(VersionProblem * problem, int packageId); VersionProblem * Solve(VersionProblem * problem); #ifdef __cplusplus } #endif // __cplusplus #endif // dep_selector_to_gecode_interface_h dep-selector-0.0.8/ext/dep_gecode/dep_selector_to_gecode_interface.cpp0000644000175000017500000000616311765170155025511 0ustar tfheentfheen// // Author:: Christopher Walters () // Author:: Mark Anderson () // Copyright:: Copyright (c) 2010-2011 Opscode, Inc. // License:: Apache License, Version 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include #include "dep_selector_to_gecode_interface.h" #include "dep_selector_to_gecode.h" //#include "version_problem_oc_ih.h" // // TODO: // Trap all exceptions // insure proper memory behaviour // FFI friendly VersionProblem * VersionProblemCreate(int packageCount, bool dump_stats, bool debug) { return new VersionProblem(packageCount, dump_stats, debug); } void VersionProblemDestroy(VersionProblem * p) { delete p; } int VersionProblemSize(VersionProblem *p) { return p->Size(); } int VersionProblemPackageCount(VersionProblem *p) { return p->PackageCount(); } void VersionProblemDump(VersionProblem *p) { p->Print(std::cout); std::cout.flush(); } void VersionProblemPrintPackageVar(VersionProblem *p, int packageId) { p->PrintPackageVar(std::cout, packageId); std::cout.flush(); } // Return ID # int AddPackage(VersionProblem *problem, int min, int max, int currentVersion) { problem->AddPackage(min,max,currentVersion); } // Add constraint for package pkg @ version, // that dependentPackage is at version [minDependentVersion,maxDependentVersion] // Returns false if system becomes insoluble. bool AddVersionConstraint(VersionProblem *problem, int packageId, int version, int dependentPackageId, int minDependentVersion, int maxDependentVersion) { problem->AddVersionConstraint(packageId, version, dependentPackageId, minDependentVersion, maxDependentVersion); } void MarkPackageSuspicious(VersionProblem *problem, int packageId) { problem->MarkPackageSuspicious(packageId); } void MarkPackagePreferredToBeAtLatest(VersionProblem *problem, int packageId, int weight) { problem->MarkPackagePreferredToBeAtLatest(packageId, weight); } void MarkPackageRequired(VersionProblem *problem, int packageId) { problem->MarkPackageRequired(packageId); } int GetPackageVersion(VersionProblem *problem, int packageId) { problem->GetPackageVersion(packageId); } bool GetPackageDisabledState(VersionProblem *problem, int packageId) { problem->GetPackageDisabledState(packageId); } int GetPackageMax(VersionProblem *problem, int packageId) { problem->GetMax(packageId); } int GetPackageMin(VersionProblem *problem, int packageId) { problem->GetMin(packageId); } int GetDisabledVariableCount(VersionProblem *problem) { problem->GetDisabledVariableCount(); } VersionProblem * Solve(VersionProblem * problem) { return VersionProblem::Solve(problem); } dep-selector-0.0.8/ext/dep_gecode/lib/0000755000175000017500000000000011765170155017045 5ustar tfheentfheendep-selector-0.0.8/ext/dep_gecode/lib/dep_selector_to_gecode.rb0000644000175000017500000000034011765170155024047 0ustar tfheentfheen#!/usr/bin/ruby require "ffi" module VersionProblem extend FFI:Library # ffi_lib FFI:Library:???? attach_function 'VersionProblemCreate', [ ], :pointer attach_function 'VersionProblemDump', [ :pointer ], :void end dep-selector-0.0.8/ext/dep_gecode/dep_selector_to_gecode.cpp0000644000175000017500000006105511765170155023472 0ustar tfheentfheen// // Author:: Christopher Walters () // Author:: Mark Anderson () // Copyright:: Copyright (c) 2010-2011 Opscode, Inc. // License:: Apache License, Version 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include #include #include #include #include #include "dep_selector_to_gecode.h" #include #include #include //#define MEMORY_DEBUG //#define DEBUG #define DEBUG_STREAM std::cerr //#define USE_DUMB_BRANCHING #define VECTOR_CONSTRAIN using namespace Gecode; const int VersionProblem::UNRESOLVED_VARIABLE = INT_MIN; const int VersionProblem::MIN_TRUST_LEVEL = 0; const int VersionProblem::MAX_TRUST_LEVEL = 10; const int VersionProblem::MAX_PREFERRED_WEIGHT = 10; VersionProblemPool::VersionProblemPool() : elems() { } VersionProblemPool::~VersionProblemPool() { DeleteAll(); } void VersionProblemPool::Add(VersionProblem * vp) { vp->pool = this; #ifdef MEMORY_DEBUG DEBUG_STREAM << "Pool add\t" << vp << std::endl << std::flush; #endif // MEMORY_DEBUG elems.insert(vp); } void VersionProblemPool::Delete(VersionProblem *vp) { if (vp->pool != 0) { #ifdef MEMORY_DEBUG DEBUG_STREAM << "Pool del\t" << vp << std::endl << std::flush; #endif // MEMORY_DEBUG elems.erase(vp); vp->pool = 0; } } void VersionProblemPool::ShowAll() { DEBUG_STREAM << "ShowAll =====================================================" << std::endl << std::flush; std::set::iterator i; for(i = elems.begin(); i != elems.end(); i++) { #ifdef MEMORY_DEBUG DEBUG_STREAM << "ShowAll has\t\t\t" << *i << std::endl << std::flush; #endif // MEMORY_DEBUG } DEBUG_STREAM << "ShowAll =====================================================" << std::endl << std::flush; } void VersionProblemPool::DeleteAll() { #ifdef MEMORY_DEBUG ShowAll(); #endif std::set::iterator i; for(i = elems.begin(); i != elems.end(); i++) { VersionProblem *vp = *i; vp->pool = 0; delete *i; } elems.clear(); #ifdef MEMORY_DEBUG DEBUG_STREAM << "DeleteAll ===================================================" << std::endl << std::flush; #endif } VersionProblem::VersionProblem(int packageCount, bool dumpStats, bool debug) : size(packageCount), version_constraint_count(0), dump_stats(dumpStats), debug_logging(debug), finalized(false), cur_package(0), package_versions(*this, packageCount), disabled_package_variables(*this, packageCount, 0, 1), total_disabled(*this, 0, packageCount*MAX_TRUST_LEVEL), total_required_disabled(*this, 0, packageCount), total_induced_disabled(*this, 0, packageCount), total_suspicious_disabled(*this, 0, packageCount), is_required(new int[packageCount]), is_suspicious(new int[packageCount]), at_latest(*this, packageCount, 0, 1), // These domains could be narrowed a bit; check later total_preferred_at_latest(*this, -packageCount*MAX_PREFERRED_WEIGHT, packageCount*MAX_PREFERRED_WEIGHT), total_not_preferred_at_latest(*this, -packageCount, packageCount), preferred_at_latest_weights(new int[packageCount]), pool(0) { for (int i = 0; i < packageCount; i++) { preferred_at_latest_weights[i] = 0; is_required[i] = 0; is_suspicious[i] = 0; } if (debug_logging) { DEBUG_STREAM << "Creating VersionProblem with args" << packageCount <<" "<< dumpStats <<" "<< debug << std::endl; DEBUG_STREAM.flush(); } } VersionProblem::VersionProblem(bool share, VersionProblem & s) : Space(share, s), size(s.size), version_constraint_count(s.version_constraint_count), dump_stats(s.dump_stats), finalized(s.finalized), cur_package(s.cur_package), disabled_package_variables(s.disabled_package_variables), total_disabled(s.total_disabled), total_required_disabled(s.total_required_disabled), total_induced_disabled(s.total_induced_disabled), total_suspicious_disabled(s.total_suspicious_disabled), is_required(NULL), is_suspicious(NULL), at_latest(s.at_latest), total_preferred_at_latest(s.total_preferred_at_latest), total_not_preferred_at_latest(s.total_preferred_at_latest), preferred_at_latest_weights(NULL), pool(s.pool) { package_versions.update(*this, share, s.package_versions); disabled_package_variables.update(*this, share, s.disabled_package_variables); total_disabled.update(*this, share, s.total_disabled); total_required_disabled.update(*this, share, s.total_required_disabled); total_induced_disabled.update(*this, share, s.total_induced_disabled); total_suspicious_disabled.update(*this, share, s.total_suspicious_disabled); at_latest.update(*this, share, s.at_latest); total_preferred_at_latest.update(*this, share, s.total_preferred_at_latest); total_not_preferred_at_latest.update(*this, share, s.total_not_preferred_at_latest); pool->Add(this); #ifdef MEMORY_DEBUG DEBUG_STREAM << "C VersionProblem(bool, VP)\t" << this << std::endl << std::flush; #endif } // Support for gecode Space* VersionProblem::copy(bool share) { return new VersionProblem(share,*this); } VersionProblem::~VersionProblem() { delete[] preferred_at_latest_weights; delete[] is_required; delete[] is_suspicious; if (pool!= 0) { pool->Delete(this); } #ifdef MEMORY_DEBUG DEBUG_STREAM << "D VersionProblem\t\t" << this << std::endl << std::flush; #endif } int VersionProblem::Size() { return size; } int VersionProblem::PackageCount() { return cur_package; } int VersionProblem::AddPackage(int minVersion, int maxVersion, int currentVersion) { if (cur_package == size) { return -1; } if (debug_logging) { DEBUG_STREAM << "Adding package id " << cur_package << '/' << size << ": min = " << minVersion << ", max = " << maxVersion << ", current version " << currentVersion << std::endl; DEBUG_STREAM.flush(); } int index = cur_package; cur_package++; // IntVar version(*this, minVersion, maxVersion); package_versions[index] = IntVar(*this, minVersion, maxVersion); // register the binding of package to version that corresponds to the package's latest rel(*this, package_versions[index], IRT_EQ, maxVersion, at_latest[index]); return index; } bool VersionProblem::AddVersionConstraint(int packageId, int version, int dependentPackageId, int minDependentVersion, int maxDependentVersion) { BoolVar version_match(*this, 0, 1); BoolVar depend_match(*this, 0, 1); BoolVar predicated_depend_match(*this, 0, 1); version_constraint_count++; if (debug_logging) { DEBUG_STREAM << "Add VC for " << packageId << " @ " << version << " depPkg " << dependentPackageId; DEBUG_STREAM << " [ " << minDependentVersion << ", " << maxDependentVersion << " ]" << std::endl; DEBUG_STREAM.flush(); } //version_flags << version_match; // Constrain pred to reify package @ version rel(*this, package_versions[packageId], IRT_EQ, version, version_match); // Add the predicated version constraints imposed on dependent package // package_versions[dependendPackageId] in domain [minDependentVersion,maxDependentVersion] <=> depend_match dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match); // disabled_package_variables[dependentPackageId] OR depend_match <=> predicated_depend_match // rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, version_match); rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match); rel(*this, version_match, BOT_IMP, predicated_depend_match, 1); } void VersionProblem::MarkPackageSuspicious(int packageId) { is_suspicious[packageId] = 1; } void VersionProblem::MarkPackageRequired(int packageId) { is_required[packageId] = 1; } void VersionProblem::MarkPackagePreferredToBeAtLatest(int packageId, int weight) { preferred_at_latest_weights[packageId] = std::max(MAX_PREFERRED_WEIGHT, std::min(0, weight)); } void VersionProblem::Finalize() { if (debug_logging) { DEBUG_STREAM << "Finalization Started" << std::endl; DEBUG_STREAM.flush(); } finalized = true; // Setup constraint for cost // We wish to minimize the total number of disabled packages, by priority ranks IntArgs disabled_required_weights(size, is_required); linear(*this, disabled_required_weights, disabled_package_variables, IRT_EQ, total_required_disabled); if (debug_logging) { DEBUG_STREAM << "disabled_required_weights: " << disabled_required_weights << std::endl; DEBUG_STREAM << "total_required_disabled: " << total_required_disabled << std::endl; } IntArgs disabled_induced_weights(size); for (int i = 0; i < size; i++) { disabled_induced_weights[i] = !(is_required[i] || is_suspicious[i]); } linear(*this, disabled_induced_weights, disabled_package_variables, IRT_EQ, total_induced_disabled); if (debug_logging) { DEBUG_STREAM << " disabled_induced_weights: " << disabled_induced_weights << std::endl; DEBUG_STREAM << "total_induce d_disabled: " << total_induced_disabled << std::endl; } IntArgs disabled_suspicious_weights(size, is_suspicious); linear(*this, disabled_suspicious_weights, disabled_package_variables, IRT_EQ, total_suspicious_disabled); if (debug_logging) { DEBUG_STREAM << "disabled_suspicious_weights: " << disabled_suspicious_weights << std::endl; DEBUG_STREAM << "total_suspicious_disabled: " << total_suspicious_disabled << std::endl; } linear(*this, disabled_package_variables, IRT_EQ, total_disabled); if (debug_logging) { DEBUG_STREAM << "total_disabled: " << total_disabled << std::endl; } // Setup computation for total_preferred_at_latest // We wish to maximize the total number of packages at their latest versions in the preferred tier of packages // We negate the weights in the cost function to make it fit into the context of a minimization problem. for (int i = 0; i < size; i++) { preferred_at_latest_weights[i] = -preferred_at_latest_weights[i]; } IntArgs preferred_at_latest_weights_args(size, preferred_at_latest_weights); linear(*this, preferred_at_latest_weights_args, at_latest, IRT_EQ, total_preferred_at_latest); if (debug_logging) { DEBUG_STREAM << " preferred_at_latest_weights_args: " << preferred_at_latest_weights_args << std::endl; DEBUG_STREAM << "total_prefer red_at_latest: " << total_preferred_at_latest << std::endl; } // Setup computation for remaining variables // We wish to maximize the total number of packages at their latest version in the non-preferred tier of packages // We negate the weights in the cost function to make it fit into the context of a minimization problem. IntArgs not_preferred_at_latest_weights_args = IntArgs::create(size, 0, 0); for (int i = 0; i < size; i++) { if (preferred_at_latest_weights[i] == 0) { not_preferred_at_latest_weights_args[i] = -1; } } linear(*this, not_preferred_at_latest_weights_args, at_latest, IRT_EQ, total_not_preferred_at_latest); if (debug_logging) { DEBUG_STREAM << " not_preferred_at_latest_weights_args: " << not_preferred_at_latest_weights_args << std::endl; DEBUG_STREAM << "total_not_preferred_at_latest: " << total_not_preferred_at_latest << std::endl; } // Cleanup // Assign a dummy variable to elements greater than actually used. for (int i = cur_package; i < size; i++) { package_versions[i] = IntVar(*this, -1, -1); disabled_package_variables[i] = BoolVar(*this, 1, 1); } #ifdef USE_DUMB_BRANCHING if (debug_logging) { DEBUG_STREAM << "Adding branching (POOR)" << std::endl; DEBUG_STREAM.flush(); } // This branching starts as far as possible from the solution, in order to exercise the optimization functions. branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MAX); branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MIN); branch(*this, total_required_disabled, INT_VAL_MAX); branch(*this, total_induced_disabled, INT_VAL_MAX); branch(*this, total_suspicious_disabled, INT_VAL_MAX); branch(*this, total_disabled, INT_VAL_MAX); branch(*this, at_latest, INT_VAR_SIZE_MIN, INT_VAL_MIN); branch(*this, total_preferred_at_latest, INT_VAL_MIN); branch(*this, total_not_preferred_at_latest, INT_VAL_MIN); #else // USE_DUMB_BRANCHING if (debug_logging) { DEBUG_STREAM << "Adding branching (BEST)" << std::endl; DEBUG_STREAM.flush(); } // This branching is meant to start with most probable solution branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN); branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX); branch(*this, total_required_disabled, INT_VAL_MIN); branch(*this, total_induced_disabled, INT_VAL_MIN); branch(*this, total_suspicious_disabled, INT_VAL_MIN); branch(*this, total_disabled, INT_VAL_MIN); branch(*this, at_latest, INT_VAR_SIZE_MIN, INT_VAL_MAX); branch(*this, total_preferred_at_latest, INT_VAL_MAX); branch(*this, total_not_preferred_at_latest, INT_VAL_MAX); #endif // USE_DUMB_BRANCHING if (debug_logging) { DEBUG_STREAM << " Finalization Done" << std::endl; DEBUG_STREAM.flush(); } } //////////////////////////////////////////////////////////////////////// // A general note about constrain functions //////////////////////////////////////////////////////////////////////// // // Constrain functions take a space ('best_known_solution') that is has an assignment of variables // and operate in the context of a fresh space, not yet fully assigned. Their purpose is to add // constraints such that the assignments in the fresh space will either yield a better solution, or // none at all if the best_known_solution is the best possible. // #ifdef TOTAL_DISABLED_COST // // Very simple constraint function that only minimizes total disabled packages. This is left here // for debugging purposes. Turn this on to test that the basic system can be solved. // void VersionProblem::constrain(const Space & _best_known_solution) { const VersionProblem& best_known_solution = static_cast(_best_known_solution); // add first-level objective function minimization (failing packages, weighted) // new constraint: total_disabled < best_known_total_disabled_value) int best_known_total_disabled_value = best_known_solution.total_disabled.val(); rel(*this, total_disabled, IRT_LE, best_known_total_disabled_value); if (debug_logging) { PrintVarAligned("Con strain: total_disabled: ", total_disabled); } } #endif // TOTAL_DISABLED_COST // _best_known_soln is the most recent satisfying assignment of // variables that Gecode has found. This method examines the solution // and adds additional constraints that are applied after restarting // the search, which means that the next time a solution that's found // must be strictly better than the current best known solution. // // Our model requires us to have a series of objective functions where // each successive objective function is evaluated if and only if all // higher precedent objective functions are tied. // // [TODO: DESCRIBE WHAT THE ACTUAL SERIES OF OBJECTIVE FUNCTIONS IS] // // Lower precedent objective functions are modeled as the consequent // of an implication whose antecedent is the conjunction of all the // higher precedent objective functions being assigned to their best // known value; thus, the optimal value of an objection function // "activates" the next highest objective function. This has the // effect of isolating the logic of each objective function such that // it is only applied to the set of equally preferable solutions under // the higher precedent objective functions. The objective function // then applies its constraints, the solution space is restarted and // walks the space until it finds another, more constrained solution. #ifdef VECTOR_CONSTRAIN // // The vector constrain function assembles multiple cost functions into a vector cost, and then // constrains the vector cost to be less than the vector cost of the current best_known_solution. // The less than operation here is a pairwise comparison in order of decreasing precedence; only if // higher precedence elements are tied will the lower precedence elements be consulted. The elements // are in increasing order of precedence. // // In this case the lowest precedence cost is total_not_preferred_at_latest, followed by total_preferred_at_latest // and finally total_disabled. // void VersionProblem::constrain(const Space & _best_known_solution) { const VersionProblem& best_known_solution = static_cast(_best_known_solution); IntVarArgs current(5); IntVarArgs best(5); BuildCostVector(current); best_known_solution.BuildCostVector(best); ConstrainVectorLessThanBest(current, best); } #endif // VECTOR_CONSTRAIN void VersionProblem::BuildCostVector(IntVarArgs & costVector) const { costVector[0] = total_not_preferred_at_latest; costVector[1] = total_preferred_at_latest; costVector[2] = total_suspicious_disabled; costVector[3] = total_induced_disabled; costVector[4] = total_required_disabled; } IntVar & VersionProblem::GetPackageVersionVar(int packageId) { if (packageId < cur_package) { return package_versions[packageId]; } else { if (debug_logging) { DEBUG_STREAM << "Bad package Id " << packageId << " >= " << cur_package << std::endl; DEBUG_STREAM.flush(); } // return 0; } } int VersionProblem::GetPackageVersion(int packageId) { IntVar & var = GetPackageVersionVar(packageId); if (1 == var.size()) return var.val(); return UNRESOLVED_VARIABLE; } bool VersionProblem::GetPackageDisabledState(int packageId) { return disabled_package_variables[packageId].val() == 1; } int VersionProblem::GetMax(int packageId) { return GetPackageVersionVar(packageId).max(); } int VersionProblem::GetMin(int packageId) { return GetPackageVersionVar(packageId).min(); } int VersionProblem::GetDisabledVariableCount() { if (total_disabled.min() == total_disabled.max()) { return total_disabled.min(); } else { return UNRESOLVED_VARIABLE; } } // Utility void VersionProblem::Print(std::ostream & out) { out << "Version problem dump: " << cur_package << "/" << size << " packages used/allocated" << std::endl; out << "Disabled Variables: " << disabled_package_variables << std::endl; out << "Total Disabled variables (required): " << total_required_disabled << std::endl; out << "Total Disabled variables: (induced): " << total_induced_disabled << std::endl; out << "Total Disabled variables: (suspicious): " << total_suspicious_disabled << std::endl; out << "Total Disabled variables: " << total_disabled << std::endl; out << "at_latest: " << at_latest << std::endl; out << "total_preferred_at_latest: " << total_preferred_at_latest << std::endl; out << "total_not_preferred_at_latest: " << total_not_preferred_at_latest << std::endl; for (int i = 0; i < cur_package; i++) { out << "\t"; PrintPackageVar(out, i); out << std::endl; } out.flush(); } // TODO: Validate package ids ! void VersionProblem::PrintPackageVar(std::ostream & out, int packageId) { IntVar & var = GetPackageVersionVar(packageId); out << "PackageId: " << packageId << " Sltn: " << var << " disabled: " << disabled_package_variables[packageId] << " at latest: " << at_latest[packageId]; } bool VersionProblem::CheckPackageId(int id) { return (id < size); } // We want to sort vectors // This constrains current to be less than best by a process analogous to subtraction // we compute current - best, pairwise with borrows from less significant elements. We require it to be less than zero by requiring the most // significant element to generate a borrow. // void VersionProblem::ConstrainVectorLessThanBest(IntVarArgs & current, IntVarArgs & best) { BoolVarArray borrow(*this, current.size()+1, 0, 1); // No borrows can happen at the least significant element. rel(*this, borrow[0], IRT_EQ, 0); for (int i = 0; i < current.size(); i++) { // If best+borrow is greater than current (equivalently current-(best+borrow) is < 0) then a more significant element // must have decreased, so we propagate a borrow to the next most significant element. int best_val = best[i].val(); IntVar delta = expr(*this, current[i] - best_val - borrow[i]); // (delta < 0) <=> borrow[i+1] rel(*this, delta, IRT_LE, 0, borrow[i+1]); if (debug_logging) { DEBUG_STREAM << " ConstrainVector: borrow[" << i+1 << "] " << borrow[i+1] << ",\tdelta " << delta << std::endl; DEBUG_STREAM << "ConstrainV ector: current[" << i << "] " << current[i] << ",\tbest_val " << best_val << std::endl; } } // must borrow off past the most significant element. rel(*this, borrow[current.size()], IRT_EQ, 1); } VersionProblem * VersionProblem::InnerSolve(VersionProblem * problem, int &itercount) { Gecode::Support::Timer timer; timer.start(); #ifdef MEMORY_DEBUG DEBUG_STREAM << "Creating solver" << std::endl << std::flush; #endif VersionProblem *best_solution = NULL; Restart solver(problem); #ifdef MEMORY_DEBUG DEBUG_STREAM << "Starting Solve" << std::endl << std::flush; #endif while (VersionProblem *solution = solver.next()) { #ifdef MEMORY_DEBUG DEBUG_STREAM << "Solver Next " << solution << std::endl << std::flush; #endif if (best_solution != NULL) { delete best_solution; } best_solution = solution; ++itercount; if (problem->debug_logging) { DEBUG_STREAM << "Trial Solution #" << itercount << "===============================" << std::endl; const Search::Statistics & stats = solver.statistics(); DEBUG_STREAM << "Solver stats: Prop:" << stats.propagate << " Fail:" << stats.fail << " Node:" << stats.node; DEBUG_STREAM << " Depth:" << stats.depth << " memory:" << stats.memory << std::endl; solution->Print(DEBUG_STREAM); } } double elapsed_time = timer.stop(); if (problem->dump_stats) { std::cerr << "dep_selector solve: "; std::cerr << (best_solution ? "SOLVED" : "FAILED") << " "; std::cerr << problem->size << " packages, " << problem->version_constraint_count << " constraints, "; std::cerr << "Time: " << elapsed_time << "ms "; const Search::Statistics & final_stats = solver.statistics(); std::cerr << "Stats: " << itercount << " steps, "; std::cerr << final_stats.memory << " bytes, "; std::cerr << final_stats.propagate << " props, " << final_stats.node << " nodes, " << final_stats.depth << " depth "; std::cerr << std::endl << std::flush; } return best_solution; } VersionProblem * VersionProblem::Solve(VersionProblem * problem) { problem->Finalize(); problem->status(); VersionProblemPool *pool = new VersionProblemPool(); problem->pool = pool; if (problem->debug_logging) { DEBUG_STREAM << " Before solve" << std::endl; problem->Print(DEBUG_STREAM); } int itercount = 0; VersionProblem *best_solution = InnerSolve(problem, itercount); if (problem->debug_logging) { DEBUG_STREAM << "Solver Best Solution " << best_solution << std::endl << std::flush; } pool->Delete(best_solution); problem->pool = 0; pool->DeleteAll(); delete pool; return best_solution; } // // Debug output // template void PrintVarAligned(const char * message, T & var) { DEBUG_STREAM.width(40); DEBUG_STREAM << std::left << message << var << std::endl; DEBUG_STREAM.width(0); } template void PrintVarAligned(const char * message, S & var1, T & var2) { DEBUG_STREAM.width(40); DEBUG_STREAM << std::left << message << var1 << " " << var2 << std::endl; DEBUG_STREAM.width(0); } //template void PrintVarAligned(const char * message, int & var); // // Version Problem // // // // dep-selector-0.0.8/lib/0000755000175000017500000000000011765170155014167 5ustar tfheentfheendep-selector-0.0.8/lib/dep_selector/0000755000175000017500000000000011765170155016637 5ustar tfheentfheendep-selector-0.0.8/lib/dep_selector/package_version.rb0000644000175000017500000000417211765170155022330 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module DepSelector class PackageVersion attr_accessor :package, :version, :dependencies def initialize(package, version) @package = package @version = version @dependencies = [] end def generate_gecode_wrapper_constraints pkg_densely_packed_version = package.densely_packed_versions.index(version) dependencies.each do |dep| dep_pkg_range = dep.package.densely_packed_versions[dep.constraint] package.dependency_graph.gecode_wrapper.add_version_constraint(package.gecode_package_id, pkg_densely_packed_version, dep.package.gecode_package_id, dep_pkg_range.min, dep_pkg_range.max) end end def to_s(incl_densely_packed_versions = false) components = [] components << "#{version}" if incl_densely_packed_versions components << " (#{package.densely_packed_versions.index(version)})" end components << " -> [#{dependencies.map{|d|d.to_s(incl_densely_packed_versions)}.join(', ')}]" components.join end def hash # Didn't put any thought or research into this, probably can be # done better to_s.hash end def eql?(o) o.class == self.class && package == o.package && version == o.version && dependencies == o.dependencies end alias :== :eql? def to_hash { :package_name => package.name, :version => version } end end end dep-selector-0.0.8/lib/dep_selector/selector.rb0000644000175000017500000002727311765170155021017 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'dep_selector/dependency_graph' require 'dep_selector/exceptions' require 'dep_selector/error_reporter' require 'dep_selector/error_reporter/simple_tree_traverser' # A Selector contains the a DependencyGraph, which is populated with # the dependency relationships, and an array of solution # constraints. When a solution is asked for (via #find_solution), # either a valid assignment is returned or the first solution # constraint that makes a solution impossible. module DepSelector class Selector attr_accessor :dep_graph, :error_reporter DEFAULT_ERROR_REPORTER = ErrorReporter::SimpleTreeTraverser.new def initialize(dep_graph, error_reporter = DEFAULT_ERROR_REPORTER) @dep_graph = dep_graph @error_reporter = error_reporter end # Based on solution_constraints, this method tries to find an # assignment of PackageVersions that is compatible with the # DependencyGraph. If one cannot be found, the constraints are # added one at a time until the first unsatisfiable constraint is # detected. Once the unsatisfiable solution constraint is # identified, required non-existent packages and the most # constrained packages are identified and thrown in a # NoSolutionExists exception. # # If a solution constraint refers to a package that doesn't exist # or the constraint matches no versions, it is considered # invalid. All invalid solution constraints are collected and # raised in an InvalidSolutionConstraints exception. If # valid_packages is non-nil, it is considered the authoritative # list of extant Packages; otherwise, Package#valid? is used. This # is useful if the dependency graph represents an already filtered # set of packages such that a Package actually exists in your # domain but is added to the dependency graph with no versions, in # which case Package#valid? would return false even though we # don't want to report that the package is non-existent. def find_solution(solution_constraints, valid_packages = nil) # this is a performance optimization so that packages that are # completely unreachable by the solution constraints don't get # added to the CSP packages_to_include_in_solve = trim_unreachable_packages(dep_graph, solution_constraints) begin # first, try to solve the whole set of constraints solve(dep_graph.clone, solution_constraints, valid_packages, packages_to_include_in_solve) rescue Exceptions::NoSolutionFound # since we're here, solving the whole system failed, so add # the solution_constraints one-by-one and try to solve in # order to find the constraint that breaks the system in order # to give helpful debugging info # # TODO [cw,2010/11/28]: for an efficiency gain, instead of # continually re-building the problem and looking for a # solution, turn solution_constraints into a Generator and # iteratively add and solve in order to re-use # propagations. This will require separating setting up the # constraints from searching for the solution. solution_constraints.each_index do |idx| workspace = dep_graph.clone begin solve(workspace, solution_constraints[0..idx], valid_packages, packages_to_include_in_solve) rescue Exceptions::NoSolutionFound => nsf disabled_packages = packages_to_include_in_solve.inject([]) do |acc, elt| pkg = workspace.package(elt.name) acc << pkg if nsf.unsatisfiable_problem.is_package_disabled?(pkg.gecode_package_id) acc end # disambiguate between packages disabled becuase they # don't exist and those that have otherwise problematic # constraints disabled_non_existent_packages = [] disabled_most_constrained_packages = [] disabled_packages.each do |disabled_pkg| disabled_collection = if disabled_pkg.valid? || (valid_packages && valid_packages.include?(disabled_pkg)) disabled_most_constrained_packages else disabled_non_existent_packages end disabled_collection << disabled_pkg end # Pick the first non-existent or most-constrained package # that was required or the package whose constraints had # to be disabled in order to find a solution and generate # feedback for it. We only report feedback for one # package, because it is in fact actionable and dispalying # feedback for every disabled package would probably be # too long. The full set of disabled packages is # accessible in the NoSolutionExists exception. disabled_package_to_report_on = disabled_non_existent_packages.first || disabled_most_constrained_packages.first feedback = error_reporter.give_feedback(dep_graph, solution_constraints, idx, disabled_package_to_report_on) raise Exceptions::NoSolutionExists.new(feedback, solution_constraints[idx], disabled_non_existent_packages, disabled_most_constrained_packages) end end end end private # Given a workspace (a clone of the dependency graph) and an array # of SolutionConstraints, this method attempts to find a # satisfiable set of pairs. def solve(workspace, solution_constraints, valid_packages, packages_to_include_in_solve) # map packages in packages_to_include_in_solve into # corresponding workspace packages and generate constraints # imposed by the dependency graph packages_in_solve = packages_to_include_in_solve.map{|pkg| workspace.package(pkg.name)} workspace.generate_gecode_wrapper_constraints(packages_in_solve) # validate solution_constraints and generate its constraints process_soln_constraints(workspace, solution_constraints, valid_packages) # solve and trim the solution down to only the soln = workspace.gecode_wrapper.solve trim_solution(solution_constraints, soln, workspace) end # This method validates SolutionConstraints and adds their # corresponding constraints to the workspace. def process_soln_constraints(workspace, solution_constraints, valid_packages) gecode = workspace.gecode_wrapper # create shadow package whose dependencies are the solution constraints soln_constraints_pkg_id = gecode.add_package(0, 0, 0) soln_constraints_on_non_existent_packages = [] soln_constraints_that_match_no_versions = [] # generate constraints imposed by solution_constraints solution_constraints.each do |soln_constraint| # look up the package in the cloned dep_graph that corresponds to soln_constraint pkg_name = soln_constraint.package.name pkg = workspace.package(pkg_name) constraint = soln_constraint.constraint # record invalid solution constraints and raise an exception # afterwards unless pkg.valid? || (valid_packages && valid_packages.include?(pkg)) soln_constraints_on_non_existent_packages << soln_constraint next end if pkg[constraint].empty? soln_constraints_that_match_no_versions << soln_constraint next end pkg_id = pkg.gecode_package_id gecode.mark_preferred_to_be_at_latest(pkg_id, 10) gecode.mark_required(pkg_id) if constraint acceptable_versions = pkg.densely_packed_versions[constraint] gecode.add_version_constraint(soln_constraints_pkg_id, 0, pkg_id, acceptable_versions.min, acceptable_versions.max) else # this restricts the domain of the variable to >= 0, which # means -1, the shadow package, cannot be assigned, meaning # the package must be bound to an actual version gecode.add_version_constraint(soln_constraints_pkg_id, 0, pkg_id, 0, pkg.densely_packed_versions.range.max) end end if soln_constraints_on_non_existent_packages.any? || soln_constraints_that_match_no_versions.any? raise Exceptions::InvalidSolutionConstraints.new(soln_constraints_on_non_existent_packages, soln_constraints_that_match_no_versions) end end # Given an assignment of versions to packages, filter down to only # the required assignments def trim_solution(soln_constraints, soln, workspace) trimmed_soln = {} soln_constraints.each do |soln_constraint| package = workspace.package(soln_constraint.package.name) expand_package(trimmed_soln, package, soln) end trimmed_soln end def expand_package(trimmed_soln, package, soln) # don't expand packages that we've already expanded return if trimmed_soln.has_key?(package.name) # add the package's assignment to the trimmed solution densely_packed_version = soln.get_package_version(package.gecode_package_id) version = package.densely_packed_versions.sorted_elements[densely_packed_version] trimmed_soln[package.name] = version # expand the package's dependencies pkg_version = package[version] pkg_version.dependencies.each do |pkg_dep| expand_package(trimmed_soln, pkg_dep.package, soln) end end # Given a workspace and solution constraints, this method returns # an array that includes only packages that can be induced by the # solution constraints. def trim_unreachable_packages(workspace, soln_constraints) reachable_packages = [] soln_constraints.each do |soln_constraint| find_reachable_packages(workspace, soln_constraint.package, soln_constraint.constraint, reachable_packages) end reachable_packages end def find_reachable_packages(workspace, curr_pkg, version_constraint, reachable_packages) # TODO [cw, 2011/3/11]: if we really want to minimize the number # of packages we add to reachable_packages, we should go back to # expanding only the versions of curr_pkg that meet # version_constraint and modify the early exit in this method to # trigger on PackageVersions, not just Package. # don't follow circular paths or duplicate work return if reachable_packages.include?(curr_pkg) # add curr_pkg to reachable_packages and expand its versions' # dependencies reachable_packages << curr_pkg curr_pkg.versions.each do |curr_pkg_ver| curr_pkg_ver.dependencies.each do |dep| find_reachable_packages(workspace, dep.package, dep.constraint, reachable_packages) end end end end end dep-selector-0.0.8/lib/dep_selector/solution_constraint.rb0000644000175000017500000000151411765170155023305 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'dep_selector/dependency' class DepSelector::SolutionConstraint < DepSelector::Dependency ; end dep-selector-0.0.8/lib/dep_selector/gecode_wrapper.rb0000644000175000017500000001445111765170155022157 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "dep_gecode" require 'dep_selector/exceptions' module DepSelector class GecodeWrapper attr_reader :gecode_problem DontCareConstraint = -1 NoMatchConstraint = -2 DumpStatistics = true DebugLogsOn = false # This insures that we properly deallocate the c++ class at the heart of dep_gecode. # modeled after http://www.mikeperham.com/2010/02/24/the-trouble-with-ruby-finalizers/ def initialize(problem_or_package_count) if (problem_or_package_count.is_a?(Numeric)) @gecode_problem = Dep_gecode.VersionProblemCreate(problem_or_package_count, DumpStatistics, DebugLogsOn) else @gecode_problem = problem_or_package_count end ObjectSpace.define_finalizer(self, self.class.finalize(@gecode_problem)) end def self.finalize(gecode_problem) proc { Dep_gecode.VersionProblemDestroy(gecode_problem) } end def check_package_id(package_id, param_name) raise "Gecode #{param_name} is out of range #{package_id}" unless (package_id >= 0 && package_id < self.size()) end def size() raise "Gecode internal failure" if gecode_problem.nil? Dep_gecode.VersionProblemSize(gecode_problem) end def package_count() raise "Gecode internal failure" if gecode_problem.nil? Dep_gecode.VersionProblemPackageCount(gecode_problem) end def add_package(min, max, current_version) raise "Gecode internal failure" if gecode_problem.nil? Dep_gecode.AddPackage(gecode_problem, min, max, current_version) end def add_version_constraint(package_id, version, dependent_package_id, min_dependent_version, max_dependent_version) raise "Gecode internal failure" if gecode_problem.nil? check_package_id(package_id, "package_id") check_package_id(dependent_package_id, "dependent_package_id") # Valid package versions are between -1 and its max (-1 means # don't care, meaning it doesn't need to be assigned). To # indicate constraints that match no versions, -2 is used, since # it's not a valid assignment of the variable; thus, any branch # that assigns -2 will fail. # # This mechanism is also used when a dependent package has no # versions, which only happens if the dependency's package is # auto-vivified when creating the parent PackageVersion's # dependency but with no corresponding set of PackageVersions # (i.e. it's an invalid deendency, because it does not exist in # the dependency graph). Again, we won't abort immediately, but # we'll add a constraint to the package that makes exploring # that portion of the solution space unsatisfiable. Thus it is # impossible to find solutions dependent on non-existent # packages. min = min_dependent_version || NoMatchConstraint max = max_dependent_version || NoMatchConstraint Dep_gecode.AddVersionConstraint(gecode_problem, package_id, version, dependent_package_id, min, max) # if the package was constrained to no versions, hint to the # solver that in the event of failure, it should prefer to # indicate constraints on dependent_package_id as the culprit if min == NoMatchConstraint && max == NoMatchConstraint Dep_gecode.MarkPackageSuspicious(gecode_problem, dependent_package_id) end end def get_package_version(package_id) raise "Gecode internal failure" if gecode_problem.nil? check_package_id(package_id, "package_id") Dep_gecode.GetPackageVersion(gecode_problem, package_id) end def is_package_disabled?(package_id) raise "Gecode internal failure" if gecode_problem.nil? check_package_id(package_id, "package_id") Dep_gecode.GetPackageDisabledState(gecode_problem, package_id); end def get_package_max(package_id) raise "Gecode internal failure" if gecode_problem.nil? check_package_id(package_id, "package_id") Dep_gecode.GetPackageMax(gecode_problem, package_id) end def get_package_min(package_id) raise "Gecode internal failure" if gecode_problem.nil? check_package_id(package_id, "package_id") Dep_gecode.GetPackageMin(gecode_problem, package_id) end def dump() raise "Gecode internal failure" if gecode_problem.nil? Dep_gecode.VersionProblemDump(gecode_problem) end def dump_package_var(package_id) raise "Gecode internal failure" if gecode_problem.nil? check_package_id(package_id, "package_id") Dep_gecode.VersionProblemPrintPackageVar(gecode_problem, package_id) end def package_disabled_count raise "Gecode internal failure (package disabled count)" if gecode_problem.nil? Dep_gecode.GetDisabledVariableCount(gecode_problem) end def mark_required(package_id) raise "Gecode internal failure (mark_required)" if gecode_problem.nil? check_package_id(package_id, "package_id") Dep_gecode.MarkPackageRequired(gecode_problem, package_id); end def mark_preferred_to_be_at_latest(package_id, weight) raise "Gecode internal failure (mark_preferred_to_be_at_latest)" if gecode_problem.nil? check_package_id(package_id, "package_id") Dep_gecode.MarkPackagePreferredToBeAtLatest(gecode_problem, package_id, weight); end def solve() raise "Gecode internal failure (solve)" if gecode_problem.nil? solution = GecodeWrapper.new(Dep_gecode.Solve(gecode_problem)) raise "Gecode internal failure (no solution found)" if (solution.nil?) raise Exceptions::NoSolutionFound.new(solution) if solution.package_disabled_count > 0 solution end end end dep-selector-0.0.8/lib/dep_selector/version.rb0000644000175000017500000000346711765170155020663 0ustar tfheentfheen# # Author:: Seth Falcon () # Author:: Christopher Walters () # Copyright:: Copyright 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'dep_selector/exceptions' module DepSelector class Version include Comparable attr_reader :major, :minor, :patch def initialize(str="") @major, @minor, @patch = parse(str) end def inspect "#{@major}.#{@minor}.#{@patch}" end def to_s "#{@major}.#{@minor}.#{@patch}" end def <=>(v) [:major, :minor, :patch].each do |method| ans = (self.send(method) <=> v.send(method)) return ans if ans != 0 end 0 end def hash # Didn't put any thought or research into this, probably can be # done better to_s.hash end # For hash def eql?(other) other.is_a?(Version) && self == other end private def parse(str="") @major, @minor, @patch = case str.to_s when /^(\d+)\.(\d+)\.(\d+)$/ [ $1.to_i, $2.to_i, $3.to_i ] when /^(\d+)\.(\d+)$/ [ $1.to_i, $2.to_i, 0 ] else msg = "'#{str.to_s}' does not match 'x.y.z' or 'x.y'" raise Exceptions::InvalidVersion.new msg end end end end dep-selector-0.0.8/lib/dep_selector/package.rb0000644000175000017500000001062611765170155020564 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'dep_selector/package_version' require 'dep_selector/densely_packed_set' module DepSelector class Package attr_reader :dependency_graph, :name, :versions def initialize(dependency_graph, name) @dependency_graph = dependency_graph @name = name @versions = [] end def add_version(version) versions << (pv = PackageVersion.new(self, version)) pv end # Note: only invoke this method after all PackageVersions have been added def densely_packed_versions @densely_packed_versions ||= DenselyPackedSet.new(versions.map{|pkg_version| pkg_version.version}) end # Given a version, this method returns the corresonding # PackageVersion. Given a version constraint, this method returns # an array of matching PackageVersions. #-- # TODO [cw,2011/2/4]: rationalize this with DenselyPackedSet#[] def [](version_or_constraint) # version constraints must abide the include? contract if version_or_constraint.respond_to?(:include?) versions.select do |ver| version_or_constraint.include?(ver) end else versions.find{|pkg_version| pkg_version.version == version_or_constraint} end end # A Package is considered valid if it has at least one version def valid? versions.any? end def to_s(incl_densely_packed_versions = false) components = [] components << "Package #{name}" if incl_densely_packed_versions components << " (#{densely_packed_versions.range})" end versions.each{|version| components << "\n #{version.to_s(incl_densely_packed_versions)}"} components.flatten.join end # Note: only invoke this method after all PackageVersions have been added def gecode_package_id # Note: gecode does naive bounds propagation at every post, # which means that any package with exactly one version is # considered bound and its dependencies propagated even though # there might not be a solution constraint that requires that # package to be bound, which means that otherwise-irrelevant # constraints (e.g. A1->B1 when the solution constraint is B=2 # and there is nothing to induce a dependency on A) can cause # unsatisfiability. Therefore, we want every package to have at # least two versions, one of which is neither the target of # other packages' dependencies nor induces other # dependencies. Package version id -1 serves this purpose. # # TODO [cw, 2011/2/22]: Do we likewise want to leave packages # with no versions (the target of an invalid dependency) with # two versions in order to allow the solver to explore the # invalid portion of the state space instead of naively limiting # it for the purposes of having failure count heuristics? max = densely_packed_versions.range.max || -1 @gecode_package_id ||= dependency_graph.gecode_wrapper.add_package(-1, max, 0) end def generate_gecode_wrapper_constraints # if this is a valid package (has versions), we don't need to # explicitly call gecode_package_id, because they will do it for # us; however, if this package isn't valid (it only exists as an # invalid dependency and thus has no versions), the solver gets # confused, because we won't have generated its package id by # the time it starts solving. gecode_package_id versions.each{|version| version.generate_gecode_wrapper_constraints } end def eql?(o) # TODO [cw,2011/2/7]: this is really shallow. should implement # == for DependencyGraph self.class == o.class && name == o.name end alias :== :eql? end end dep-selector-0.0.8/lib/dep_selector/dependency.rb0000644000175000017500000000262511765170155021307 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'dep_selector/version_constraint' module DepSelector class Dependency attr_reader :package, :constraint def initialize(package, constraint=nil) @package = package @constraint = constraint || VersionConstraint.new end def to_s(incl_densely_packed_versions = false) range = package.densely_packed_versions[constraint] "(#{package.name} #{constraint.to_s}#{incl_densely_packed_versions ? " (#{range})" : ''})" end def ==(o) o.respond_to?(:package) && package == o.package && o.respond_to?(:constraint) && constraint == o.constraint end def eql?(o) self.class == o.class && self == o end end end dep-selector-0.0.8/lib/dep_selector/error_reporter.rb0000644000175000017500000000166611765170155022250 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module DepSelector class ErrorReporter def give_feedback(workspace, solution_constraints, unsatisfiable_constraint_idx, most_constrained_package) raise "Sub-class must implement" end end end dep-selector-0.0.8/lib/dep_selector/exceptions.rb0000644000175000017500000000523611765170155021353 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module DepSelector module Exceptions # This exception is what the client of dep_selector should # catch. It contains the solution constraint that introduces # unsatisfiability, as well as the set of packages that are # required to be disabled due to class NoSolutionExists < StandardError attr_reader :message, :unsatisfiable_solution_constraint, :disabled_non_existent_packages, :disabled_most_constrained_packages def initialize(message, unsatisfiable_solution_constraint, disabled_non_existent_packages = [], disabled_most_constrained_packages = []) @message = message @unsatisfiable_solution_constraint = unsatisfiable_solution_constraint @disabled_non_existent_packages = disabled_non_existent_packages @disabled_most_constrained_packages = disabled_most_constrained_packages end end # This exception is thrown by gecode_wrapper and only used # internally class NoSolutionFound < StandardError attr_reader :unsatisfiable_problem def initialize(unsatisfiable_problem=nil) @unsatisfiable_problem = unsatisfiable_problem end end # This exception is thrown during Selector#find_solution if any of # the solution constraints make finding solution impossible. The # two cases are if a solution constraint references a package that # doesn't exist or if the constraint on an extant package matches # no versions. class InvalidSolutionConstraints < ArgumentError attr_reader :non_existent_packages, :constrained_to_no_versions def initialize(non_existent_packages, constrained_to_no_versions) @non_existent_packages = non_existent_packages @constrained_to_no_versions = constrained_to_no_versions end end class InvalidVersion < ArgumentError ; end class InvalidVersionConstraint < ArgumentError; end end end dep-selector-0.0.8/lib/dep_selector/version_constraint.rb0000644000175000017500000000654411765170155023126 0ustar tfheentfheen# # Author:: Seth Falcon () # Copyright:: Copyright 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'dep_selector/version' require 'dep_selector/exceptions' module DepSelector class VersionConstraint DEFAULT_CONSTRAINT = ">= 0.0.0" STANDARD_OPS = %w(< > <= >=) OPS = %w(< > = <= >= ~>) PATTERN = /^(#{OPS.join('|')}) (.+)$/ attr_reader :op, :version def initialize(constraint_spec=nil) constraint_spec ||= DEFAULT_CONSTRAINT case constraint_spec when nil parse(DEFAULT_CONSTRAINT) when Array parse_from_array(constraint_spec) when String parse(constraint_spec) else msg = "VersionConstraint should be created from a String. You gave: #{constraint_spec.inspect}" raise Exceptions::InvalidVersionConstraint, msg end end def include?(v) version = if v.respond_to? :version Version.new(v.version.to_s) else Version.new(v.to_s) end do_op(version) end def inspect "(#{@op} #{@version})" end def to_s "#{@op} #{@version}" end def eql?(o) o.class == self.class && @op == o.op && @version == o.version end alias_method :==, :eql? private def do_op(other_version) if STANDARD_OPS.include? @op other_version.send(@op.to_sym, @version) elsif @op == '=' other_version == @version elsif @op == '~>' if @missing_patch_level (other_version.major == @version.major && other_version.minor >= @version.minor) else (other_version.major == @version.major && other_version.minor == @version.minor && other_version.patch >= @version.patch) end else # should never happen raise "bad op #{@op}" end end def parse_from_array(constraint_spec) if constraint_spec.empty? parse(DEFAULT_CONSTRAINT) elsif constraint_spec.size == 1 parse(constraint_spec.first) else msg = "only one version constraint operation is supported, but you gave #{constraint_spec.size} " msg << "['#{constraint_spec.join(', ')}']" raise Exceptions::InvalidVersionConstraint, msg end end def parse(str) @missing_patch_level = false if str.index(" ").nil? && str =~ /^[0-9]/ # try for lone version, implied '=' @version = Version.new(str) @op = "=" elsif PATTERN.match str @op = $1 raw_version = $2 @version = Version.new(raw_version) if raw_version.split('.').count == 2 @missing_patch_level = true end else raise Exceptions::InvalidVersionConstraint, "'#{str}'" end end end end dep-selector-0.0.8/lib/dep_selector/dependency_graph.rb0000644000175000017500000000513711765170155022471 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'dep_selector/package' require 'dep_selector/gecode_wrapper' # DependencyGraphs contain Packages, which in turn contain # PackageVersions. Packages are created at access-time through # #package module DepSelector class DependencyGraph attr_reader :packages def initialize @packages = {} end def package(name) packages.has_key?(name) ? packages[name] : (packages[name]=Package.new(self, name)) end def each_package packages.each do |name, pkg| yield pkg end end def gecode_wrapper raise "Must invoke generate_gecode_wrapper_constraints before attempting to access gecode_wrapper" unless @gecode_wrapper @gecode_wrapper end # Note: only invoke this method once all Packages and # PackageVersions have been added. def generate_gecode_wrapper_constraints(packages_to_include_in_solve=nil) unless @gecode_wrapper packages_in_solve = if packages_to_include_in_solve packages_to_include_in_solve else packages.map{ |name, pkg| pkg } end # In addition to all the packages that the user specified, # there is a "ghost" package that contains the solution # constraints. See Selector#solve for more information. @gecode_wrapper = GecodeWrapper.new(packages_in_solve.size + 1) packages_in_solve.each{ |pkg| pkg.generate_gecode_wrapper_constraints } end end def gecode_model_vars packages.inject({}){|acc, elt| acc[elt.first] = elt.last.gecode_model_var ; acc } end def to_s(incl_densely_packed_versions = false) packages.keys.sort.map{|name| packages[name].to_s(incl_densely_packed_versions)}.join("\n") end # TODO [cw,2010/11/23]: this is a simple but inefficient impl. Do # it for realz. def clone Marshal.load(Marshal.dump(self)) end end end dep-selector-0.0.8/lib/dep_selector/error_reporter/0000755000175000017500000000000011765170155021712 5ustar tfheentfheendep-selector-0.0.8/lib/dep_selector/error_reporter/simple_tree_traverser.rb0000644000175000017500000001627711765170155026661 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'dep_selector/error_reporter' # This error reporter simply maps the versions of packages explicitly # included in the list of solution constraints to the restrictions # placed on the most constrained package. module DepSelector class ErrorReporter class SimpleTreeTraverser < ErrorReporter def give_feedback(dep_graph, soln_constraints, unsatisfiable_constraint_idx, most_constrained_pkg) unsatisfiable_soln_constraint = soln_constraints[unsatisfiable_constraint_idx] feedback = "Unable to satisfy constraints on package #{most_constrained_pkg.name}" feedback << ", which does not exist," unless most_constrained_pkg.valid? feedback << " due to solution constraint #{unsatisfiable_soln_constraint}. " all_paths = paths_from_soln_constraints_to_pkg_constraints(dep_graph, soln_constraints, most_constrained_pkg) collapsed_paths = collapse_adjacent_paths(all_paths).map{|collapsed_path| "[#{print_path(collapsed_path).join(' -> ')}]"} feedback << "Solution constraints that may result in a constraint on #{most_constrained_pkg.name}: #{collapsed_paths.join(', ')}" end private def paths_from_soln_constraints_to_pkg_constraints(dep_graph, soln_constraints, most_constrained_pkg) all_paths = [] soln_constraints.each do |soln_constraint| paths_to_pkg(dep_graph, soln_constraint.package, soln_constraint.constraint, most_constrained_pkg, [], all_paths) end all_paths end def paths_to_pkg(dep_graph, curr_pkg, version_constraint, target_pkg, curr_path, all_paths) if curr_pkg == target_pkg # register the culminating constraint all_paths.push(Array.new(curr_path).push(SolutionConstraint.new(curr_pkg, version_constraint))) return end # curr_pkg has no versions, it is invalid so don't recurse if curr_pkg.versions.empty? # TODO [cw, 2011/2/17]: find a way to track these invalid # packages and return as potential conflict-causing # constraints. return end if curr_path.select{|elt| elt.package == curr_pkg}.any? # TODO [cw, 2011/2/18]: this indicates a circular dependency # in the dependency graph. This might be useful warning # information to report to the user. return end # determine all versions of curr_pkg that match # version_constraint and recurse into them curr_pkg[version_constraint].each do |curr_pkg_ver| curr_path.push(curr_pkg_ver) curr_pkg_ver.dependencies.each do |dep| paths_to_pkg(dep_graph, dep.package, dep.constraint, target_pkg, curr_path, all_paths) end curr_path.pop end end # This is a simple collapsing function. For each adjacent path, # if there is only one element different between the two paths # and their packages are the same (meaning only the version # binding is different), then the elements are considered # collasable. The merged path has all the common elements and a # set containing the two version bindings in place of the # contentious path item. def collapse_adjacent_paths(paths) return paths if paths.length < 2 paths.inject([]) do |collapsed_paths, path| merge_path_into_collapsed_paths(collapsed_paths, path) end end def print_path(path) path.map do |step| if step.respond_to? :version "(#{step.package.name} = #{step.version})" elsif step.respond_to? :constraint step.to_s elsif step.kind_of?(Array) # TODO [cw, 2011/2/23]: consider detecting complete # ranges here instead of calling each out individually "(#{step.first.package.name} = {#{step.map{|elt| "#{elt.version}"}.join(',')}})" else raise "don't know how to print step" end end end # collapses path_under_consideration onto the end of # collapsed_paths or adds a new path to be used in the next # round(s) of collapsing. # # Note: collapsed_paths is side-effected def merge_path_into_collapsed_paths(collapsed_paths, path_under_consideration) curr_collapsed_path = collapsed_paths.last # if there is no curr_collapsed_path or it isn't the same # length as path_under_consideration, then they cannot # possibly be mergeable if curr_collapsed_path.nil? || curr_collapsed_path.length != path_under_consideration.length # TODO [cw.2011/2/7]: do we need this to be a new array, or # can we save ourselves a little memory and work by just # pushing the reference to path_under_consideration? return collapsed_paths << Array.new(path_under_consideration) end # lengths are equal, so find the first path element where # curr_collapsed_path and path_under_consideration diverge, if # that is the only unequal element, it's for the same package, # and they are both PackageVersion objects then merge; # otherwise, this is a new path # # TODO [cw,2011/2/7]: should we merge even if they're not for # the same package? unequal_idx = nil merged_set = nil mergeable = true path_under_consideration.each_with_index do |path_element, curr_idx| if path_element != curr_collapsed_path[curr_idx] unless unequal_idx merged_set = [curr_collapsed_path[curr_idx]].flatten if merged_set.first.package == path_element.package && merged_set.first.is_a?(PackageVersion) && path_element.is_a?(PackageVersion) merged_set << path_element else mergeable = false break end unequal_idx = curr_idx else # this is the second place they are unequal. fast-fail, # because we know we can't merge the paths. mergeable = false break end end end if unequal_idx && mergeable curr_collapsed_path[unequal_idx] = merged_set else collapsed_paths << Array.new(path_under_consideration) end collapsed_paths end end end end dep-selector-0.0.8/lib/dep_selector/dep_selector_version.rb0000644000175000017500000000005311765170155023377 0ustar tfheentfheenmodule DepSelector VERSION = "0.0.8" end dep-selector-0.0.8/lib/dep_selector/densely_packed_set.rb0000644000175000017500000000357111765170155023017 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'dep_selector/exceptions' module DepSelector class DenselyPackedSet attr_reader :sorted_elements def initialize(elements) @sorted_elements = elements.sort @element_to_index = {} @sorted_elements.each_with_index{|elt, idx| @element_to_index[elt] = idx} end def range Range.new(0, @sorted_elements.size-1) end def index(element) unless @element_to_index.has_key?(element) msg = "#{element} is not a valid version for this package" raise Exceptions::InvalidVersion.new(msg) end @element_to_index[element] end def [](constraint) # TODO [cw/mark,2010/11/22]: don't actually need an array here, re-write range = [] started = false done = false sorted_elements.each_with_index do |element, idx| if constraint.include?(element) raise "Currently only handle continuous gap between #{range.last} and #{idx} for #{constraint.to_s} over #{@sorted_elements.join(', ')}" if (range.any? && range.last+1 != idx) range << idx end end range.empty? ? [] : Range.new(range.first, range.last) end end end dep-selector-0.0.8/lib/dep_selector.rb0000644000175000017500000000231311765170155017163 0ustar tfheentfheen# # Author:: Christopher Walters () # Author:: Mark Anderson () # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'dep_selector/dep_selector_version' require 'dep_selector/selector' require 'dep_selector/dependency_graph' require 'dep_selector/package' require 'dep_selector/package_version' require 'dep_selector/dependency' require 'dep_selector/solution_constraint' require 'dep_selector/version' require 'dep_selector/version_constraint' require 'dep_selector/exceptions' # error reporting require 'dep_selector/error_reporter' require 'dep_selector/error_reporter/simple_tree_traverser'