diff --git a/changelog.in b/changelog.in index 396fa85613..543c60f69a 100644 --- a/changelog.in +++ b/changelog.in @@ -73,892 +73,653 @@ Version: 7.0.0 Date: unreleased [DESCRIPTION] -This release contains breaking changes. See the entries below for the -changes downstream code needs. +This major release moves %Gecode to C++23 and CMake, removing the Autoconf +and Makefile build systems as well as Qt 5 support. Public APIs adopt +snake_case naming, descriptive enum constants (including IRT_LT, FRT_LT, and +SRT_LT), scoped enums (enum class), trivially copyable handles and FloatVal, +const-reference or move parameter passing, and typed Space::clone(). -[ENTRY] -Module: gist -What: removed -Rank: minor -[DESCRIPTION] -Remove Qt 5 support. Gist and the Qt-backed FlatZinc features now -require Qt 6. +Search and meta-search have major changes: hub() and spoke() with explicit +contexts replace master(), slave(), and MetaInfo; end_reason() replaces +stopped(); Space::compare() ranks solutions in best-solution search; +portfolio assets get independent cutoffs and whole-portfolio stop checks; and +Rnd is replaced by splittable random generators with complete state +save/restore. + +Float variables now use a native %Gecode interval library instead of the +bundled Boost interval copy, with optimization-safe directed rounding. See +docs/gecode-7-migration.md for how to update existing %Gecode 6 code. [ENTRY] -Module: kernel +Module: other What: change -Rank: minor +Rank: major [DESCRIPTION] -Space::clone returns the static type of the space it is called on, so cloning -a Model, or through a Model*, returns a Model* and needs no cast. Cloning through -a Space* still returns a Space*. Space::clone is now a member function template -with an explicit object parameter, so pointers to members to it no longer work. -The address of a specialization, such as the one for Space itself, is an -ordinary function pointer of type Space* (*)(const Space&). Gecode and code -including its headers need GCC 14, Clang 18, AppleClang 17, or MSVC 19.32 or -newer. +Require C++23 with explicit object parameters (GCC 14, Clang 18, +AppleClang 17, or MSVC 19.32 or newer), adopt snake_case for functions, +variables, and members (such as no_overlap, bin_packing, and modevent_delta), +and format C/C++ sources with clang-format 22 (four-space indentation, +120-column limit). +[MORE] +Constants and constant-like helpers (ME_INT_VAL, ES_SUBSUMED, +INT_VAR_SIZE_MIN) keep UPPER_CASE; types keep PascalCase. EditorConfig +replaces per-file indentation headers, and misc/check.py provides formatting, +clang-tidy, and extended check commands. See docs/code-style.md and +docs/gecode-7-migration.md. [ENTRY] -Module: support -What: new -Rank: minor +Module: other +What: removed +Rank: major [DESCRIPTION] -Add down_cast for downcasts whose target type is known, such as the space -passed to Space::constrain and Space::compare, the choice passed to -Brancher::commit, and the advisor passed to Propagator::advise. It -asserts the type with dynamic_cast when assertions are enabled and is a -static_cast otherwise. +Remove the Autoconf and Makefile build systems; build, install, and +regenerate Gecode with CMake. [ENTRY] -Module: flatzinc +Module: other What: change -Rank: minor -[DESCRIPTION] -Derive FlatZinc::Error and FlatZinc::AST::TypeError from std::exception, so that -a handler for std::exception also catches them. AST::TypeError::what now returns -const char* instead of std::string. - -[ENTRY] -Module: flatzinc -What: bug -Rank: minor +Rank: major [DESCRIPTION] -Give FlatZinc::BranchPlugin a virtual destructor, so that a plugin deleted -through its interface is destroyed correctly. +Rename strict-less relation constants (IRT_LE, FRT_LE, SRT_LE to IRT_LT, +FRT_LT, SRT_LT) and other abbreviated enum constants to descriptive names, +without compatibility aliases. Less-or-equal constants keep the _LQ suffix. +[MORE] +Public renames include RestartMode (RM_* to RESTART_*), ReifyMode (RM_PMI to +RM_RIMP), TaskType (TT_FIXP/S/E to TT_FIXED_PROCESSING/START/END), SetRelType +(SRT_DISJ/CMPL to SRT_DISJOINT/COMPLEMENT), SetOpType (SOT_DUNION/INTER to +SOT_DISJOINT_UNION/INTERSECTION), ScriptMode (SM_STAT to SM_STATISTICS), +SearchTracer::EngineType (AOE to OTHER), and abbreviated test and internal +enum constants. See docs/gecode-7-migration.md. [ENTRY] Module: other What: change Rank: major [DESCRIPTION] -Give abbreviated constants descriptive names, and remove the old spellings -without compatibility aliases. Values and semantics are unchanged, as are the -command-line option values and the "AOE" that StdSearchTracer prints. -[MORE] -The public renames are: -RestartMode: RM_NONE, RM_CONSTANT, RM_LINEAR, RM_LUBY, and RM_GEOMETRIC to -RESTART_NONE, RESTART_CONSTANT, RESTART_LINEAR, RESTART_LUBY, and -RESTART_GEOMETRIC, because ReifyMode also uses the prefix RM_. -ReifyMode: RM_PMI to RM_RIMP. -TaskType: TT_FIXP, TT_FIXS, and TT_FIXE to TT_FIXED_PROCESSING, TT_FIXED_START, -and TT_FIXED_END. -SetRelType: SRT_DISJ and SRT_CMPL to SRT_DISJOINT and SRT_COMPLEMENT. -SetOpType: SOT_DUNION and SOT_INTER to SOT_DISJOINT_UNION and SOT_INTERSECTION. -ScriptMode: SM_STAT to SM_STATISTICS. -MetaInfo::RestartReason: RR_NO, RR_SOL, RR_CMPL, and RR_LIM to RR_NONE, -RR_SOLUTION, RR_COMPLETE, and RR_LIMIT. -SearchTracer::EngineType: AOE to OTHER. -The test component renames are: -Test::Float::AssignmentType: CPLT_ASSIGNMENT to COMPLETE_ASSIGNMENT. -Test::MatchType: MT_ANY, MT_NOT, and MT_FIRST to MATCH_ANY, MATCH_NOT, and -MATCH_FIRST. -The internal renames are: -Int::GCC::Edge::EdgeFlag: EF_MRKLB, EF_MRKUB, EF_LM, EF_UM, and EF_DEL to -EF_MARKED_LBC, EF_MARKED_UBC, EF_MATCHED_LBC, EF_MATCHED_UBC, and EF_DELETED. -Int::NValues::RangeEventType: RET_FST and RET_LST to RET_START and RET_FINISH. -Support::IntType: IT_SHRT to IT_SHORT. -Int::BoolTest: BT_COMP to BT_COMPLEMENT. -Int::Cumulatives::EventType: EVENT_CHCK and EVENT_PRUN to EVENT_CHECK and -EVENT_PRUNE. +Convert existing public and internal enums to enum class, keeping unqualified +constant names usable via using enum (or static constexpr aliases in class +templates). Enum values no longer convert implicitly to int or mix across +enums; convert explicitly with std::to_underlying or static_cast. See +docs/gecode-7-migration.md. [ENTRY] Module: other What: change Rank: major [DESCRIPTION] -Make 68 enums enum class, with using enum at their scope or, in class templates, -static constexpr aliases, so existing spellings such as IRT_EQ, -Gecode::SS_FAILED, and IntVarBranch::SEL_RND still compile. Their values stop converting to int and stop mixing with other enums. -Code that stores such a value in an int, does arithmetic or bitwise operations -on it, streams it, uses it as an array index or a bit position such as -1 << RM_EQV, or compares it with an integer no longer compiles. Convert -explicitly with std::to_underlying or static_cast. Installed headers now use -std::to_underlying, so code that does not build through the exported CMake -targets needs C++23 as well. +Pass owned and reference-counted parameters and FloatVal by const reference +instead of by value, or by value and move when stored. Propagators overriding +solution_distribution or domain_size_sum must now take SendMarginal or +InDecision by const reference. [MORE] -The scoped enums are: -Kernel: ExecStatus, SpaceStatus, ActorProperty, PropCost::ActualCost, -PropCost::Mod, ViewTraceInfo::What, PropagateTraceInfo::Status, -PostTraceInfo::Status, NGL::Status, MetaInfo::Type, MetaInfo::RestartReason, -TFE::NodeType. -Search: SearchTracer::EngineType, SearchTracer::NodeType, -Search::HeuristicGuidance::Sense, Search::Beam::Offer, -Search::Seq::ExpansionStep::State, Search::Par::Engine::Cmd, -CPProfiler::NodeStatus, CPProfiler::MessageMarshalling::Field. -Integer: ReifyMode, IntRelType, BoolOpType, IntPropLevel, TaskType, -TupleSet::Data::State, IntVarBranch::Select, BoolVarBranch::Select, -IntValBranch::Select, BoolValBranch::Select, IntAssign::Select, -BoolAssign::Select, Int::Cumulatives::EventType (formerly the typedef ev_t), -Int::Extensional::CompactStatus::StatusType, Int::GCC::BC, -Int::NValues::RangeEventType, Int::Sequence::TakesStatus, Int::SortTaskOrder, -Int::Event::Type, Int::RelTest, Int::BoolTest. -Set: SetRelType, SetOpType, SetVarBranch::Select, SetValBranch::Select, -SetAssign::Select. -Float: FloatRelType, FloatVarBranch::Select, FloatValBranch::Select, -FloatAssign::Select, Float::RelTest. -MiniModel: LinIntExpr::NodeType, LinFloatExpr::NodeType, SetExpr::NodeType, -BoolExpr::NodeType. -Driver: ScriptMode, RestartMode. -FlatZinc: FlatZinc::FlatZincSpace::Meth, FlatZinc::IntBoolVarBranch::Select, -FlatZinc::SymbolType. -Gist, support, and iterators: Gist::NodeStatus, Support::BitSetStatus, -Support::IntType, Iter::Ranges::CompareStatus. -Test component: Test::MatchType, Test::Int::ConTestLevel, -Test::Float::MaybeType, Test::Float::AssignmentType. - -[ENTRY] -Module: int -What: change -Rank: major -[DESCRIPTION] -IntPropLevel is enum class with underlying type unsigned int and gains -operator|, operator&, and operator|=, so levels combine without casts. Test a -bit with (ipl & IPL_BASIC) != IPL_DEF, since the result no longer converts to -bool. Remove IPL_BITS_, which was a bit-field width rather than a level. +Affects branch, assign, relax, trace, extensional (DFA), element +(IntSharedArray), float constraints and expressions taking FloatVal, and +branching/Action/CHB constructors taking Rnd, AFC, Action, CHB, or merit +functions. Arguments passed by value and moved must now be movable. Shallow +handles (variables, views, variable arrays) stay passed by value. [ENTRY] -Module: driver -What: new +Module: other +What: performance Rank: minor [DESCRIPTION] -Add the class template Driver::EnumOption, a string-valued option whose values -are the enumerators of an enum type, so scripts can offer enum class choices -without casting to int. The mode and restart options of Options and -FlatZincOptions use it. +Move owned branching and open-list callbacks through constructors instead of +copying them, avoid argument-array copies in examples, reserve worker-control +storage, and buffer multi-line output while flushing complete records. [ENTRY] -Module: kernel -What: change +Module: gist +What: removed Rank: minor [DESCRIPTION] -The Rnd constructor taking a seed is explicit. Code that passes a number where -a Rnd is expected, such as INT_VAR_RND(1U), must now write Rnd(1U). The implicit -conversion also accepted floating-point values, which hid the bug in -IntBoolVarBranch fixed in this release. +Remove Qt 5 support. Gist and Qt-backed FlatZinc features now require Qt 6. [ENTRY] -Module: flatzinc -What: bug -Rank: minor +Module: kernel +What: new +Rank: major [DESCRIPTION] -IntBoolVarBranch keeps its decay factor, which was discarded so that AFC and -action used a decay of 1. The default branchers follow the -decay option, which -only search annotations honoured before. +Replace the random number generator by splittable value-type engines with +complete state save/restore: SplitMix for Rnd, or any engine through +RndGenerator. Randomized brancher selectors split their state on commit so +cloning, recomputation, and meta-search spokes keep deterministic streams. +[MORE] +Rnd's seed constructor is now explicit: write INT_VAL_RND(Rnd(42)) instead of +INT_VAL_RND(42), opt.rnd() instead of Rnd(opt.seed()), and state()/state(text) +instead of seed(). Drivers accept -state with a complete state, and seed/state +options may be given only once. Copying an Rnd no longer advances the +original; pass a distinct split (such as rnd.split(sc) in spoke()) to each +consumer. Seeded sequences change. [ENTRY] -Module: flatzinc -What: bug +Module: kernel +What: change Rank: minor [DESCRIPTION] -Choices from set_search and set_default_search print the relations of their -value selection. Before, set_search printed none, and set_default_search printed -"in" and "not in" the wrong way round for outdomain_min and outdomain_max. +Space::clone() now returns the static type of the space it is called on, so +cloning a model needs no cast (cloning through a Space* still returns Space*). +[MORE] +Space::clone() is now a member function template with an explicit object +parameter, so pointers to member to it no longer work; the address of a +specialization such as for Space is Space* (*)(const Space&). [ENTRY] -Module: flatzinc -What: bug -Rank: minor +Module: kernel +What: change +Rank: major [DESCRIPTION] -Searching for an extension to introduced variables follows the default search -annotations after the space has been cloned, and no longer leaks the random -number generator of a random selection. +Make shallow handles (Home, groups, Pos, Reify, LocalHandle, variables, +VarArray, ViewArray, open lists, and AFC) trivially copyable. +[MORE] +Their copy members are now implicit or defaulted, AFC and LocalHandle drop +their destructors, and VarArray::operator= and ViewArray::operator= return +non-const references. [ENTRY] -Module: int -What: bug -Rank: minor +Module: kernel +What: removed +Rank: major [DESCRIPTION] -The assign overloads for integer and Boolean variables with tie-breaking -variable selection link. The Boolean overload now takes BoolBranchFilter and -BoolVarValPrint arguments, as the overload without tie-breaking does. +Delete copy assignment of Home and Space. Construct a new Home instead of +assigning one, and clone() a Space to copy it. [ENTRY] -Module: int -What: bug +Module: kernel +What: change Rank: minor [DESCRIPTION] -Assigning integer and Boolean variables follows the variable selection, which -was ignored unless a tie-breaking selection was also in effect. Models that -pass a selection to assign, such as the job-shop example, now assign variables -in that order and can find different solutions first. +Default trivial and member-wise special members on their first declaration +and mark forbidden copy members public = delete across the library. +[MORE] +Because a defaulted default constructor is not user-provided, const +default-initialization without an initializer (such as const +Gecode::IntSetRanges r;) no longer compiles for classes with uninitialized +fields, including most range and value iterators, SetRel, FreeList, +Float::OffsetView, and Search::TraceRecorder::ID. Initialize the object or +drop const. [ENTRY] -Module: set -What: bug +Module: kernel +What: change Rank: minor [DESCRIPTION] -Assigning set variables follows the variable selection, which was ignored -unless a tie-breaking selection was also in effect. +Remove redundant operator!= definitions (relying on C++20 rewriting) and +replace Int::LDSB::Literal::operator< with a defaulted operator<=>. Write +expressions such as a != b rather than calling operator!=(a, b) directly. +[MORE] +Removed from PropagatorGroup, BrancherGroup, IntSet, DFA, +Support::BitSetData, space_allocator, region_allocator, Int::BinPacking::Item, +and concrete integer, set, and float views. ConstView, VarImpView, +DerivedView, and TupleSet keep operator!= to avoid ambiguity. [ENTRY] -Module: float +Module: kernel What: bug Rank: minor [DESCRIPTION] -Assigning float variables follows the variable selection, which was ignored -unless a tie-breaking selection was also in effect. +Fix shrinking in Space::realloc and Region::realloc (the removed tail size +had the wrong sign), and fix pointer element sizing in Space::realloc. [ENTRY] -Module: int +Module: kernel What: bug Rank: minor [DESCRIPTION] -values_reflect for the domain of an integer variable links. +Define GECODE_FREELIST32_SIZE_MAX and GECODE_FREELIST64_SIZE_MAX as unquoted +numbers in config.hpp. [ENTRY] -Module: set +Module: kernel What: bug Rank: minor [DESCRIPTION] -The default constructors of SetVarGlbValues, SetVarLubValues, and -SetVarUnknownValues link. +Avoid zero-byte heap allocations and null memcpy calls for empty Action, CHB, +Archive, and Space::realloc from an empty block. [ENTRY] -Module: float -What: bug +Module: support +What: new Rank: minor [DESCRIPTION] -Constructing FloatValArgs from an initializer list links. +Add down_cast for downcasts whose target type is known (such as in +Space::constrain, Space::compare, Brancher::commit, and Propagator::advise). +It checks with dynamic_cast when assertions are enabled and uses static_cast +otherwise. [ENTRY] -Module: search -What: bug +Module: support +What: change Rank: minor [DESCRIPTION] -The declaration of the pbs engine builder takes the engine as a template -argument, as its definition does. Calling it with only the space type failed -to link and is now a compile error. +Require positive sizes in Heap allocation and reallocation (ralloc, rrealloc, +alloc, realloc); zero-byte requests now assert in Debug builds, and +Heap::rrealloc no longer frees on size zero (use rfree instead). +[MORE] +Reallocating from zero objects to a positive count remains valid. Heap::copy +also requires non-null pointers even for zero objects. [ENTRY] -Module: int -What: bug +Module: support +What: removed Rank: minor [DESCRIPTION] -Multi-dimensional bin_packing throws Int::OutOfLimits for fewer than one -dimension. It divided by zero for zero dimensions, and a negative number of -dimensions now gives Int::OutOfLimits instead of Int::ArgumentSizeMismatch. +Remove the Autoconf PACKAGE_* macros and GECODE_HAS_BUILTIN_FFSLL / +GECODE_HAS_BUILTIN_POPCOUNTLL from config.hpp. Use GECODE_VERSION, +GECODE_VERSION_NUMBER, or Gecode_VERSION from CMake; bitsets now use +std::countr_zero and std::popcount. +[MORE] +CMake generates config.hpp with configure_file; feature macros previously +defined empty (such as GECODE_HAS_FLOAT_VARS) are now defined as 1. [ENTRY] -Module: int -What: bug +Module: support +What: removed Rank: minor [DESCRIPTION] -Two-dimensional element throws Int::TooFewArguments for an empty array, as -one-dimensional element does, instead of Int::VariableEmptyDomain from an -internal variable or Int::ArgumentSizeMismatch. It throws -Int::ArgumentSizeMismatch for a width or height that is not positive and when -the product overflows, where it could post a failing or wrong constraint. +Remove MSVC auto-linking, gecode/support/auto-link.hpp, and the +GECODE_NO_AUTOLINK, GECODE_LIBRARY_NAME, GECODE_DLL_USERPREFIX, +GECODE_DLL_USERSUFFIX, and GECODE_LIBRARY_VERSION macros. Link through the +Gecode:: CMake targets. [ENTRY] -Module: set -What: bug -Rank: minor +Module: search +What: change +Rank: major [DESCRIPTION] -Two-dimensional element throws Set::ArgumentSizeMismatch for a width or height -that is not positive and when the product overflows, where it could post a -failing or wrong constraint. +Add Space::compare() to rank solutions without modifying them. Best-solution +search uses compare() to choose incumbents while constrain() continues to +prune search; models with a custom constrain() must now also override +compare(). +[MORE] +compare() returns SpaceComparison (Better, Equivalent, Worse, Incomparable); +compare_int(), compare_float(), and compare_lex() compare standard objectives +for a Sense (Minimize, Maximize). Mismatched objectives throw +SpaceIncompatibleObjectives, incomparable solutions throw +Search::Incomparable, and negative float steps are rejected. Exceptions from +parallel portfolio assets or compare() in parallel BAB are now rethrown by +next(). See docs/gecode-7-migration.md. [ENTRY] -Module: set -What: documentation -Rank: minor +Module: search +What: change +Rank: major [DESCRIPTION] -Document the exceptions that sequence and element with an integer index throw -for an empty array and for sets outside the limits. +Replace the meta-search hooks master() and slave() and class MetaInfo by +hub(HubContext&) and spoke(SpokeContext&), without compatibility aliases. +[MORE] +hub() sets a MetaDecision and spoke() declares a SpokeCoverage instead of +returning a Boolean. RBS also calls hub() at search start and after an +incomplete episode. See docs/gecode-7-migration.md. [ENTRY] -Module: kernel +Module: search What: change Rank: major [DESCRIPTION] -Make Home, the groups, Pos, Reify, LocalHandle, the variables, the variable -arrays, ViewArray, the open variable and view lists, and AFC with its -subclasses trivially copyable. Their copy constructors and copy assignments -are now implicit or defaulted, and the AFC classes and LocalHandle no longer -declare a destructor. Copies behave as before, but the ABI changes, and the -compiler may now pass these types in registers. +Replace stopped() on search engines (and experimental limited()) by +end_reason(). [MORE] -VarArray::operator= and ViewArray::operator= now return a non-const -reference. +end_reason() distinguishes EndReason::Exhausted (proof), +EndReason::Incomplete (ended without proof), and EndReason::Limit (stopped). +FlatZinc reports optimality or unsatisfiability only when exhausted. See +docs/gecode-7-migration.md. [ENTRY] -Module: kernel -What: removed +Module: search +What: change Rank: major [DESCRIPTION] -Delete the copy assignment of Home and of Space. Assigning one Home to -another copy-assigned the whole Space that the home refers to. A Home never -changes its space; construct a new Home instead. To copy a Space, clone it. +Give each restart-based asset of a portfolio its own copy of the cutoff via +the new pure virtual Search::Cutoff::copy(). +[MORE] +Custom cutoff generators must implement copy(). Copies of Cutoff::rnd() use +distinct seeds. See docs/gecode-7-migration.md. [ENTRY] -Module: kernel +Module: search What: change Rank: minor [DESCRIPTION] -Default special members that only construct, copy, or destroy members, and -delete with = delete the members that must not be called. Across the -library, default constructors, copy constructors, copy assignments, and -destructors with empty or member-wise bodies are now defaulted on their first -declaration; among them are those of the variables, most views, FloatVal, -IntSet, TupleSet, DFA, Action, CHB, the argument arrays, and the range and -value iterators. Behaviour is unchanged, but the ABI changes: several -members that the libraries exported, such as the copy constructors of -TupleSet, Action, and CHB, are now inline. -[MORE] -Copy members that were private and undefined, such as those of Search::Base, -Support::BitSetBase, Set::GLBndSet, and FlatZinc::Printer, are now public -and deleted, so copying one is reported as a call to a deleted function. +Check the stop object of a portfolio against combined whole-portfolio +statistics instead of per asset. See docs/gecode-7-migration.md. -A defaulted default constructor is no longer user-provided. A class with -such a constructor and a field without an initializer can no longer be -default-initialized as a const object: `const Gecode::IntSetRanges r;` no -longer compiles. Initialize the object, or drop the const. This affects -most range and value iterators: IntSetRanges, IntSetValues, IntVarValues, -SetVarGlbRanges, SetVarLubRanges, SetVarUnknownRanges, the iterators in -Iter::Ranges and Iter::Values, and the range and value iterators of views -such as Int::ViewRanges and Set::UnknownRanges. It also affects SetRel, -FreeList, Float::OffsetView, and Search::TraceRecorder::ID. +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Keep other portfolio assets running when an engine builder's stop object +stops its engine, parking the stopped asset until the next call to next(). [ENTRY] -Module: kernel +Module: search What: change Rank: minor [DESCRIPTION] -Remove operator!= where it only negated operator==, and replace the -operator< of Int::LDSB::Literal with a defaulted operator<=>. C++20 rewrites -`a != b` as `!(a == b)` and `a < b` through operator<=>, so these expressions -keep their results. A call that names the operator, such as -`operator!=(a, b)` or `a.operator<(b)`, no longer compiles; write the -expression instead. -[MORE] -operator!= is removed from PropagatorGroup, BrancherGroup, IntSet, DFA, -Support::BitSetData, space_allocator, region_allocator, -Int::BinPacking::Item, and the integer, set, and float views. The kernel's -ConstView, VarImpView, and DerivedView templates keep theirs, and so does -TupleSet: without it, `true != t` would be ambiguous between its int -constructor and its bool conversion. -Support::BitSetData::operator== is now defaulted and takes its argument by -const reference. Int::LDSB::Literal now also has ==, !=, <=, >, and >=. +Run all assets of a parallel portfolio even when there are more assets than +threads (excess assets were previously dropped). [ENTRY] -Module: kernel -What: bug +Module: search +What: change Rank: minor [DESCRIPTION] -Fix shrinking with Space::realloc and Region::realloc. The size of the removed -tail was computed with the wrong sign, so shrinking destroyed objects past the -block and handed memory outside it to the space. Space::realloc for pointers -also used the size of the pointed-to type, which lost pointers on growing. +Report limited discrepancy search at its discrepancy limit as +EndReason::Incomplete. [ENTRY] -Module: int -What: bug +Module: search +What: change Rank: minor [DESCRIPTION] -Fix operator== of Int::CachedView. It used a member that the view does not -have, so comparing two cached integer views did not compile. It now compares -the base views, like Set::CachedView. +Throw Search::SpokeNoBrancher when a non-failed PBS spoke has no branchers +after spoke() although the hub had branchers. [ENTRY] -Module: support -What: removed +Module: search +What: bug Rank: minor [DESCRIPTION] -Remove the Autoconf leftovers PACKAGE_BUGREPORT, PACKAGE_NAME, -PACKAGE_STRING, PACKAGE_TARNAME, PACKAGE_URL, and PACKAGE_VERSION from the -installed gecode/support/config.hpp. Use GECODE_VERSION or -GECODE_VERSION_NUMBER instead, or Gecode_VERSION from the CMake package. -[MORE] -CMake now generates config.hpp with configure_file. Feature macros that were -defined as empty, such as GECODE_HAS_FLOAT_VARS, are now defined as 1; tests -of whether they are defined behave as before. +End a portfolio as soon as a non-partial asset exhausts its search space +instead of waiting for the remaining assets to stop. [ENTRY] -Module: support -What: removed +Module: search +What: bug Rank: minor [DESCRIPTION] -Remove GECODE_HAS_BUILTIN_FFSLL and GECODE_HAS_BUILTIN_POPCOUNTLL from the -installed gecode/support/config.hpp. Bitsets now use std::countr_zero and -std::popcount. +Constrain the hub of restart-based branch-and-bound in the engine itself so +hub() overrides that skip the default do not lose the bound. [ENTRY] -Module: support -What: removed +Module: search +What: bug Rank: minor [DESCRIPTION] -Remove MSVC auto-linking, together with the header gecode/support/auto-link.hpp -and the macros GECODE_NO_AUTOLINK, GECODE_LIBRARY_NAME, GECODE_DLL_USERPREFIX, -GECODE_DLL_USERSUFFIX, and GECODE_LIBRARY_VERSION. CMake builds always -disabled it. Consumers link through the Gecode:: CMake targets. +Propagate the PBS hub with status() after hub() and before cloning spokes, so +hub() may post constraints without throwing SpaceNotStable. [ENTRY] -Module: kernel +Module: search What: bug Rank: minor [DESCRIPTION] -Define the GECODE_FREELIST32_SIZE_MAX and GECODE_FREELIST64_SIZE_MAX build -options as numbers in config.hpp. A quoted value broke compilation. +Prevent branchers posted by hub() from reusing the identity of branchers +posted earlier by spoke(), which could post no-goods on the wrong brancher. [ENTRY] -Module: int +Module: search What: bug Rank: minor [DESCRIPTION] -Post nothing for no_overlap with zero rectangles. Debug builds aborted with a -failed assertion in the memory manager. +Delete the RBS spoke if spoke() throws an exception on restart. [ENTRY] -Module: int +Module: search What: bug Rank: minor [DESCRIPTION] -Decide count with an array of counts (global cardinality) and bin_packing -with no variables or items when posting: every count and load becomes 0. -Count with variables but no values fails. Branching with LDSB symmetries, -for integer, Boolean, and set variables, ignores symmetries over no -variables or values and accepts an empty Symmetries. Debug builds aborted -with failed assertions. Distinct over an open list with maximum length 0 -also posts nothing. +Advance the underlying generator in Cutoff::repeat() instead of repeating its +first value forever. [ENTRY] -Module: set +Module: search What: bug Rank: minor [DESCRIPTION] -Post nothing for channel_sorted, channel with Boolean variables, and union -or disjoint-union element over constant sets when the array is empty, and -make the set variables empty. Debug builds aborted with failed assertions. -Element over set variables, rel with union or disjoint union and a constant -set, and weights also post nothing for empty arrays. +Match the pbs engine builder declaration to its definition so it takes the +engine as a template argument. [ENTRY] -Module: float +Module: search What: bug -Rank: major +Rank: minor [DESCRIPTION] -Keep directed rounding sound under compiler optimization. Float::Rounding -and FloatVal arithmetic could return a bound on the wrong side of the exact -result: optimizers folded constants in round-to-nearest, shared one square -root or quotient between both bounds, and fused the negated multiplication, -even in Clang Debug builds. Each operand and result now passes through an -optimization barrier, so neither Gecode nor applications need floating-point -compiler flags. x87 arithmetic is no longer supported: 32-bit x86 builds with -GCC, which uses x87 by default, need -msse2 -mfpmath=sse. -[MORE] -The barrier is an empty volatile asm statement with GCC and Clang on AArch64 -and x86-64, and a volatile store and reload elsewhere. Integer rounding uses -floor and ceil, which do not depend on the rounding mode. The even-root -bounds of pow and nroot use the same rounding operations. +Post nothing for relax() with empty variable arrays instead of aborting on an +assertion in Debug builds. [ENTRY] -Module: float +Module: int What: change Rank: major [DESCRIPTION] -Implement interval arithmetic in Gecode itself, as the new type -Float::Interval with its free functions in namespace Gecode::Float. Gecode -no longer contains, or installs, its renamed copy of the Boost interval -library and Boost's LICENSE_1_0.txt, and it takes on no external dependency in -their place. Bounds, comparison results, and search behave as before, with -two exceptions: dividing by an interval with one zero bound keeps the sign -of a dividend that ends at zero, such as [-1,0]/[0,1], instead of giving the -whole line, and fmod returns its argument unshifted, instead of a result -such as [inf,inf], when the number of periods is not finite. The -empty-interval exception is still a std::runtime_error, but its message is -now "Gecode::Float::Interval: empty interval". -[MORE] -The interval code is Gecode code under Gecode's MIT license. +Make IntPropLevel an enum class with underlying type unsigned int and add +operator|, operator&, and operator|=. Test bits with (ipl & IPL_BASIC) != +IPL_DEF; remove IPL_BITS_. [ENTRY] -Module: float +Module: int What: bug Rank: minor [DESCRIPTION] -Keep every divisor in div when the dividend and the quotient can both be -zero. With the dividend and the quotient in [0,1], div removed the negative -divisors, although 0/x=0 holds for every nonzero x. +Fix linking of tie-breaking assign() overloads (aligning the Boolean overload +to take BoolBranchFilter and BoolVarValPrint) and values_reflect(). [ENTRY] -Module: float -What: change -Rank: major +Module: int +What: bug +Rank: minor [DESCRIPTION] -Make Float::RoundingBase and Float::Rounding plain Gecode classes. Their -arithmetic members are unchanged. RoundingBase no longer derives from a Boost -rounding class: init, upward, downward, and to_nearest are now protected, -and toward_zero, get_rounding_mode, set_rounding_mode, to_int, conv_down, -conv_up, force_rounding, and rounding_mode are gone. Rounding is a scope that -saves the caller's rounding mode and restores it; it cannot be copied and no -longer has the mode member or unprotected_rounding typedef of Boost's -save_state. The typedef RoundingControl is gone, FloatVal::FloatValImpType is -now Float::Interval, and FloatVal's protected typedefs R and P are gone. +Honor the variable selection passed to assign() for integer and Boolean +variables even when no tie-breaking selection is given. [ENTRY] -Module: float -What: change -Rank: major +Module: int +What: bug +Rank: minor [DESCRIPTION] -Make FloatVal trivially copyable. Its layout is unchanged, but on AArch64 and -SysV x86-64 it is now passed and returned by value in registers instead of -through memory. A program built against older headers must be rebuilt: the -symbol names are unchanged, so the dynamic linker does not catch the -mismatch. Two exported functions take a FloatVal by value and are affected: -FloatValArgs::create and Float::Linear::post. +Reject invalid dimensions in multi-dimensional bin_packing (throwing +Int::OutOfLimits for fewer than one dimension) and 2D element (throwing +Int::TooFewArguments for empty arrays and Int::ArgumentSizeMismatch for +non-positive or overflowing dimensions). [ENTRY] -Module: search +Module: int What: bug Rank: minor [DESCRIPTION] -Post nothing for relax with empty variable arrays. Debug builds aborted with -a failed assertion. +Handle empty arrays when posting no_overlap, count (global cardinality), +bin_packing, LDSB branching (int, Bool, set), and open-list distinct instead +of aborting on assertions in Debug builds. [ENTRY] -Module: kernel +Module: int What: bug Rank: minor [DESCRIPTION] -Action and CHB information over an empty array, including branching with -ACTION or CHB merits on no variables, requests no heap memory for its values -and posts no recorder propagator. It previously requested zero bytes, which -the C library may answer with a null pointer and thus a MemoryExhausted -exception. +Fix Int::CachedView::operator== to compare base views (previously failed to +compile). [ENTRY] -Module: kernel +Module: int What: bug Rank: minor [DESCRIPTION] -Copying or assigning an empty Archive requests no heap memory, and growing -space memory with Space::realloc from an empty block copies nothing. They -previously requested zero bytes or passed a null pointer to memcpy. +Avoid zero-byte heap allocations for arity-zero TupleSets, and allow +constructing an empty IntSet from an empty initializer list. [ENTRY] -Module: int +Module: set What: bug Rank: minor [DESCRIPTION] -Tuple sets of arity zero request no heap memory for tuples and values, also -when they grow or are finalized with a dense representation. They previously -requested zero bytes, which the C library may answer with a null pointer and -thus a MemoryExhausted exception. An IntSet built from an empty initializer -list is the empty set; Debug builds aborted with a failed assertion. +Honor the variable selection passed to assign() for set variables even when +no tie-breaking selection is given. [ENTRY] -Module: flatzinc +Module: set What: bug Rank: minor [DESCRIPTION] -Integer and set variables declared with an empty set literal, such as var {} -or var set of {}, request no heap memory. The final states of a regular -constraint given as an interval with a maximum below its minimum are treated -as empty; such an interval previously requested zero bytes or a huge size and -could write before the allocated block. +Fix linking of the default constructors of SetVarGlbValues, SetVarLubValues, +and SetVarUnknownValues. [ENTRY] -Module: example +Module: set What: bug Rank: minor [DESCRIPTION] -A dictionary file holding no accepted word and no final newline requests no -heap memory in the crossword and word-square examples. +Throw Set::ArgumentSizeMismatch for non-positive or overflowing dimensions in +2D element. [ENTRY] -Module: support -What: change +Module: set +What: bug Rank: minor [DESCRIPTION] -Every request for heap memory must ask for more than zero bytes. Code that -asks the heap for zero bytes, through Heap::ralloc, Heap::rrealloc, or the -typed alloc and realloc, now fails an assertion in Debug builds. Reallocating -from zero objects to a positive number stays valid. Heap::rrealloc no longer -returns a null pointer for size zero; free the block with rfree instead. -[MORE] -The C library may answer a request for zero bytes with a null pointer, which -the heap reports as MemoryExhausted, and reallocating to zero bytes is -implementation-defined in C17. Heap::copy also needs non-null pointers, even -for zero objects, because it passes them to memcpy. +Handle empty arrays when posting channel_sorted, Boolean channel, element, +union/disjoint-union rel with a constant set, and weights. [ENTRY] -Module: other -What: performance +Module: set +What: documentation Rank: minor [DESCRIPTION] -Move owned branching and open-variable-list callbacks through constructors -instead of copying them repeatedly. Avoid copying read-only argument arrays -in examples, reserve worker-control thread storage, and buffer multi-line -output while flushing complete solutions, progress, and protocol messages. -[MORE] -Expand clang-tidy checks for hidden copies, container operations, missed moves, -stream flushing, and correctness errors. +Document the exceptions thrown by sequence and integer-indexed element for +empty arrays and out-of-limits sets. [ENTRY] -Module: other +Module: float What: change Rank: major [DESCRIPTION] -Pass owned and reference-counted parameters, and FloatVal, by const -reference instead of by value. Values that a function keeps and whose type -has a real move constructor, such as callbacks and branching configurations, -stay by value and are moved into place. This changes the exact signatures -and the ABI of many public functions: branch and assign with their -value-selection arguments, the variable- and value-selection functions and -constructors taking Rnd, AFC, Action, CHB, or merit functions, the Action -and CHB constructors taking merit functions, relax, trace, extensional with -a DFA, element with an IntSharedArray, and floating-point posting functions -and expressions taking a FloatVal. Calls compile unchanged, except that an -argument passed by value and moved must now be movable: a type with a -deleted move constructor no longer compiles there. Propagators that override -solution_distribution or domain_size_sum must take their SendMarginal or -InDecision argument by const reference. +Implement interval arithmetic natively in Gecode (Float::Interval) and remove +the bundled Boost interval library and Boost LICENSE_1_0.txt, with no new +external dependency. [MORE] -Enable clang-tidy's performance-unnecessary-value-param check. Variables, -views, variable arrays, and other shallow handles stay passed by value. +Two edge-case fixes accompany the switch: dividing by an interval with one +zero bound keeps the sign of a dividend ending at zero (such as +[-1,0]/[0,1]), and fmod returns its argument unshifted when the period count +is not finite. The empty-interval exception message is now +"Gecode::Float::Interval: empty interval". [ENTRY] -Module: other +Module: float What: change Rank: major [DESCRIPTION] -Rename the strict-less relation constants IRT_LE, FRT_LE, and SRT_LE to -IRT_LT, FRT_LT, and SRT_LT. Remove the old spellings without compatibility -aliases to avoid confusion with less-or-equal. Relation values and semantics -are unchanged; the less-or-equal constants retain the _LQ suffix. +Make Float::RoundingBase and Float::Rounding plain Gecode classes without +Boost base classes or typedefs; their arithmetic members are unchanged. +[MORE] +Rounding is now non-copyable. RoundingControl, unprotected_rounding, +Rounding::mode, FloatVal::R, FloatVal::P, and the old Boost rounding helpers +(toward_zero, get_rounding_mode, set_rounding_mode, to_int, conv_down, +conv_up, force_rounding, rounding_mode) are removed; init, upward, downward, +and to_nearest are protected. FloatVal::FloatValImpType is now +Float::Interval. [ENTRY] -Module: other +Module: float What: change Rank: major [DESCRIPTION] -Require C++23 and adopt four-space indentation and a 120-column limit with -clang-format 22. -Functions, variables, and members use snake_case; types retain PascalCase. -Constants and functions that stand for constant values, such as ME_INT_VAL, -ES_SUBSUMED, and INT_VAR_SIZE_MIN, retain UPPER_CASE. Public API names -change, including no_overlap, bin_packing, and modevent_delta. -Update downstream source code before recompiling. -[MORE] -Add formatting, clang-tidy, and extended repository check commands. Extended -checks include generated sources, CTest suites, installed-package consumers, -and documentation. EditorConfig replaces per-file indentation headers. +Make FloatVal trivially copyable (changes its calling convention to registers +on AArch64 and SysV x86-64). [ENTRY] -Module: other -What: removed +Module: float +What: bug Rank: major [DESCRIPTION] -Remove the Autoconf and maintained Makefile build systems. Build, install, -and regenerate Gecode with CMake. Generated-source checks continue to cover -variable headers and the FlatZinc parser and lexer. +Keep directed rounding sound under compiler optimization using optimization +barriers on operands and results, so no special floating-point compiler flags +are needed. Drop x87 support; 32-bit x86 GCC builds need -msse2 -mfpmath=sse. +[MORE] +Uses an empty volatile asm barrier with GCC/Clang on AArch64 and x86-64 and +volatile reload elsewhere; integer rounding uses floor and ceil. [ENTRY] -Module: search +Module: float What: bug Rank: minor [DESCRIPTION] -Advance the generator that a cutoff generator from Cutoff::repeat() -repeats. -[MORE] -It read the current value of that generator without advancing it, so after -the first value it repeated the same value forever. +Keep negative divisors in div when both dividend and quotient can be zero. [ENTRY] -Module: search +Module: float What: bug Rank: minor [DESCRIPTION] -Delete the spoke of restart-based search when spoke() throws an exception at -a restart. +Honor the variable selection passed to assign() for float variables even when +no tie-breaking selection is given. [ENTRY] -Module: search +Module: float What: bug Rank: minor [DESCRIPTION] -Do not let a brancher that hub() posts take the identity of a brancher that -spoke() posted earlier. -[MORE] -Restart-based search then posted the no-goods of that spoke for the wrong -brancher, which could lose solutions. +Fix linking of the FloatValArgs initializer-list constructor. [ENTRY] -Module: search -What: change +Module: driver +What: new Rank: minor [DESCRIPTION] -Throw Search::SpokeNoBrancher when a spoke of portfolio search has no -brancher but the hub had branchers, unless the spoke failed. -[MORE] -The default hub() removes all branchers, so a spoke() that forgot to post -the branching of its asset returned the unassigned spoke as a solution. +Add Driver::EnumOption, a string-valued option backed by an enum type so +scripts can offer enum class choices without casting to int; used by the mode +and restart options in Options and FlatZincOptions. [ENTRY] -Module: search -What: bug +Module: flatzinc +What: change Rank: minor [DESCRIPTION] -Propagate the hub of portfolio search after hub() and before cloning the -spokes. -[MORE] -A hub() that posted a constraint made the portfolio throw SpaceNotStable. +Derive FlatZinc::Error and FlatZinc::AST::TypeError from std::exception; +AST::TypeError::what() now returns const char* instead of std::string. [ENTRY] -Module: search +Module: flatzinc What: bug Rank: minor [DESCRIPTION] -Constrain the hub of restart-based branch-and-bound search with each -solution in the engine itself. -[MORE] -The default hub() did it, so an override that did not call the default lost -the bound and found the same solutions again. +Give FlatZinc::BranchPlugin a virtual destructor. [ENTRY] -Module: search -What: change +Module: flatzinc +What: bug Rank: minor [DESCRIPTION] -Keep the other assets of a portfolio running when the stop object of an -engine builder stops its engine. -[MORE] -The whole portfolio stopped instead. The stopped asset is now parked until -the next call to next(). +Preserve the decay factor in IntBoolVarBranch and honor -decay in default +branchers. [ENTRY] -Module: search -What: change +Module: flatzinc +What: bug Rank: minor [DESCRIPTION] -Check the stop object of a portfolio with the statistics of the whole -portfolio. -[MORE] -It was checked for each asset with the statistics of that asset. See -docs/gecode-7-migration.md. +Print value-selection relations for set_search choices and fix inverted "in" +/ "not in" labels for outdomain_min and outdomain_max in set_default_search. [ENTRY] -Module: search -What: change +Module: flatzinc +What: bug Rank: minor [DESCRIPTION] -Run every asset of a parallel portfolio, also when there are more assets -than threads. -[MORE] -Parallel portfolio search ran only as many assets as it had threads and -silently dropped the others. +Honor default search annotations on introduced variables after cloning, and +fix a random generator leak in random selection. [ENTRY] -Module: search +Module: flatzinc What: bug Rank: minor [DESCRIPTION] -End a portfolio when an asset exhausts its search space. -[MORE] -The exhausted asset proves that no further solution exists, so the other -assets no longer run until they are stopped. An asset whose spoke declares -SpokeCoverage::Partial is still dropped. +Avoid zero-byte heap allocations for empty variable domains (var {}, var set +of {}) and empty final-state intervals in regular. [ENTRY] -Module: search -What: change +Module: example +What: bug Rank: minor [DESCRIPTION] -Report limited discrepancy search at its discrepancy limit as incomplete. - -[ENTRY] -Module: search -What: change -Rank: major -[DESCRIPTION] -Replace stopped() of search engines by end_reason(). -[MORE] -end_reason() tells why next() returned no solution: EndReason::Exhausted is a -proof, EndReason::Incomplete is an end without one, and EndReason::Limit is a -stop. stopped() and the experimental limited() are removed. FlatZinc reports -optimality or unsatisfiability only for an exhausted search. See -docs/gecode-7-migration.md. - -[ENTRY] -Module: search -What: change -Rank: major -[DESCRIPTION] -Give each restart-based asset of a portfolio its own copy of the cutoff. -[MORE] -Cutoff has a new pure virtual function copy(), which custom cutoff generators -must implement. Copies of a random cutoff use different seeds, so the assets -can restart at different times. A portfolio with a single asset that does not -declare SpokeCoverage::Partial uses the cutoff itself. See -docs/gecode-7-migration.md. - -[ENTRY] -Module: search -What: change -Rank: major -[DESCRIPTION] -Replace the meta-search Space hooks master() and slave() and the class -MetaInfo by hub(HubContext&) and spoke(SpokeContext&). -[MORE] -hub() sets a MetaDecision and spoke() declares a SpokeCoverage instead of -returning a Boolean. Restart-based search also calls hub() when search -starts and after an episode that ends without a proof. There are no -compatibility aliases, also not for the FlatZincSpace override of slave(). -See docs/gecode-7-migration.md. - -[ENTRY] -Module: search -What: change -Rank: major -[DESCRIPTION] -Add Space::compare(), which ranks two solutions without modifying them. -Best-solution search uses it to choose between solutions, while constrain() -still prunes the search. Optimization models with a custom constrain() must now -also override compare(). -[MORE] -Parallel BAB, portfolios, external incumbents, and the experimental A* and CABS -engines all choose their incumbent with compare(). It returns the scoped enum -SpaceComparison (Better, Equivalent, Worse, Incomparable), and the scoped enum -Sense (Minimize, Maximize) gives the optimization direction. compare_int(), -compare_float(), and compare_lex() compare integer, float, and lexicographic -objective values for a given Sense. - -Comparing solutions whose objectives differ in direction, float step, or size -throws SpaceIncompatibleObjectives, and search engines throw -Search::Incomparable when compare() reports incomparable solutions. -FloatMinimizeSpace, FloatMaximizeSpace, and FlatZinc reject a negative float -step, which would admit solutions that are not better. An exception thrown in -an asset of a parallel portfolio, or by compare() in parallel BAB, is now -rethrown by next() instead of terminating the program. - -[ENTRY] -Module: kernel -What: new -Rank: major -[DESCRIPTION] -Replaced the random number generator by splittable engines with complete -state save/restore: SplitMix for Rnd, or any engine through RndGenerator. -The randomized selectors of Gecode's branchers split their state on commit, -so cloning and recomputation make the same random decisions at a node, and -meta search gives the branchers of each spoke their own stream. Parallel -scheduling and weakly monotonic propagation can still change the search. -[MORE] -Rnd is a value type with an explicit seed constructor: write -INT_VAL_RND(Rnd(42)) instead of INT_VAL_RND(42). Use state() and -state(text) instead of seed(), and opt.rnd() instead of Rnd(opt.seed()). -Drivers accept -state with a complete state, and a seed or state option -may be given only once. Seeded sequences change. A copy of an Rnd no -longer advances the original, so relax() and other functions taking an Rnd -by value draw the same numbers from the same generator: pass a distinct -split to each call. A generator owned by the model is copied into every -spoke: split it with rnd.split(sc) in spoke(), for example -relax(*this, x, sx, rnd.split(sc), p). +Avoid zero-byte heap allocations for empty dictionaries in the crossword and +word-square examples. [ENTRY] Module: test What: change Rank: minor [DESCRIPTION] -The test option -replay takes the complete random state printed for a +The -replay test option now takes the complete random state printed for a failed iteration. [RELEASE] diff --git a/docs/cmake-build.md b/docs/cmake-build.md index c0738cdfec..92c67640e4 100644 --- a/docs/cmake-build.md +++ b/docs/cmake-build.md @@ -1,30 +1,30 @@ # CMake build and package reference -This reference covers CMake builds, installation, and downstream packages. -For modelling and search, use MPG and the API reference linked from the -[README](../README.md). +This document covers building, testing, and installing Gecode with CMake, and +consuming the installed package from downstream projects. For modelling and +search, see *Modeling and Programming with Gecode* (MPG) and the API reference +linked from the [README](../README.md). ## Requirements - CMake 3.21 or newer -- A compiler with C++23 mode and explicit object parameters (deducing this): - GCC 14, Clang 18, AppleClang 17, or MSVC 19.32 (Visual Studio 2022 17.2) or - newer. Use features supported across the GCC, Clang, AppleClang, and MSVC - builds; enabling the language mode does not imply that every C++23 library - feature is available. -- `uv` on `PATH` for generated-script paths: documentation generation, - `GECODE_REGENERATE_VARIMP=ON`, and manual helper execution. Ordinary CMake - builds can use the checked-in generated headers without `uv`. -- Python 3.11 or newer for helper scripts run through `uv`. -- Optional dependencies based on enabled modules: - - MPFR for float support with MPFR - - Qt 6 Core for FlatZinc plugin support when Qt support is enabled or - auto-detected - - Qt 6 Gui, Widgets, and PrintSupport for Gist - -## Quick Start - -Single-config generators (Unix Makefiles / Ninja): +- A C++23 compiler with explicit object parameters (deducing `this`): GCC 14, + Clang 18, AppleClang 17, or MSVC 19.32 (Visual Studio 2022 17.2) or newer. + Stay within the C++23 library subset supported across these toolchains. +- Optional, depending on enabled features: + - MPFR for float variables with MPFR support + - Qt 6 Core for Qt-backed FlatZinc plugins, plus Gui, Widgets, and + PrintSupport for Gist + - `uv` and Python 3.11 or newer for building documentation, running + `misc/check.py`, or regenerating variable headers (ordinary builds use the + checked-in headers and need neither) + - Bash, GNU Bison 3.8.2, and Flex 2.6.4 to regenerate the FlatZinc parser + and lexer + - Doxygen 1.18.0 or newer (and optionally Graphviz `dot`) for the `doc` target + +## Building and installing + +Single-config generators (Ninja, Unix Makefiles): ```bash cmake -S . -B build -DCMAKE_BUILD_TYPE=Release @@ -33,7 +33,8 @@ cmake --build build --target check cmake --install build --prefix /path/to/install ``` -Multi-config generators (Visual Studio / Xcode): +Multi-config generators (Visual Studio, Xcode) select the configuration at +build and install time with `--config` instead of `CMAKE_BUILD_TYPE`: ```bash cmake -S . -B build @@ -42,31 +43,11 @@ cmake --build build --config Release --target check cmake --install build --config Release --prefix /path/to/install ``` -## Regenerating checked-in sources - -Ordinary builds use checked-in variable headers and FlatZinc parser sources. -After editing their inputs, run: - -```bash -cmake --build build --target regenerate -bash .github/ci/generated-source-freshness.sh --check -``` - -Regeneration requires Bash, GNU Bison 3.8.2, Flex 2.6.4, and `uv`. The same -helper accepts `--update` when no CMake build directory is configured. - -## Visual Studio + vcpkg (MPFR) - -This repository includes a vcpkg manifest (`vcpkg.json`) and CMake presets -for a ready-to-run Visual Studio path with MPFR enabled. - -Prerequisites: - -- Visual Studio 2022 with C++ toolchain -- CMake 3.21 or newer -- `VCPKG_ROOT` set to your vcpkg checkout +### Visual Studio with vcpkg -Preset flow: +The repository includes a vcpkg manifest (`vcpkg.json`) and CMake presets +(`CMakePresets.json`) for x64 Visual Studio 2022 builds with MPFR. With +`VCPKG_ROOT` pointing to a vcpkg checkout: ```powershell cmake --preset vs2022-vcpkg @@ -74,7 +55,7 @@ cmake --build --preset vs2022-vcpkg-release cmake --build --preset vs2022-vcpkg-check ``` -Equivalent command-line flow (without presets): +Without presets, pass the vcpkg toolchain directly: ```powershell cmake -S . -B build/vs2022-vcpkg -G "Visual Studio 17 2022" -A x64 ` @@ -82,190 +63,151 @@ cmake -S . -B build/vs2022-vcpkg -G "Visual Studio 17 2022" -A x64 ` -DVCPKG_TARGET_TRIPLET=x64-windows ` -DGECODE_ENABLE_MPFR=ON -DGECODE_ENABLE_QT=OFF -DGECODE_ENABLE_GIST=OFF cmake --build build/vs2022-vcpkg --config Release -cmake --build build/vs2022-vcpkg --config Release --target check cmake --install build/vs2022-vcpkg --config Release --prefix C:/path/to/install ``` -Visual Studio is a multi-config generator, so use `--config Release` (or -`Debug`) for build/install/check commands rather than `CMAKE_BUILD_TYPE`. +## Configuration options + +`BUILD_SHARED_LIBS` selects the default library kind (`ON` sets +`GECODE_BUILD_SHARED=ON`, `OFF` sets `GECODE_BUILD_STATIC=ON`); setting either +`GECODE_BUILD_*` variable directly overrides it. + +Three defaults depend on whether Gecode is built standalone or added as a +subproject via `add_subdirectory` or `FetchContent`: + +| Option | Top-level | Subproject | Notes | +|---|---|---|---| +| `GECODE_ENABLE_EXAMPLES` | `ON` | `OFF` | Build example models | +| `BUILD_TESTING` | `ON` | `OFF` | Build `gecode-test`; when `OFF`, `check` still exists and reports skipped | +| `GECODE_INSTALL` | `ON` | `OFF` | Enable install and package export rules | + +Other configuration options: + +| Option | Default | Notes | +|---|---|---| +| `GECODE_BUILD_SHARED` | `ON` | Build shared libraries | +| `GECODE_BUILD_STATIC` | `OFF` | Build static libraries | +| `GECODE_ENABLE_SEARCH` | `ON` | Search engines | +| `GECODE_ENABLE_INT_VARS` | `ON` | Integer and Boolean variables | +| `GECODE_ENABLE_SET_VARS` | `ON` | Finite integer set variables | +| `GECODE_ENABLE_FLOAT_VARS` | `ON` | Floating-point variables | +| `GECODE_ENABLE_MINIMODEL` | `ON` | Direct modelling support | +| `GECODE_ENABLE_INSTANCE` | `ON` | Instance file reader (enabled with driver) | +| `GECODE_ENABLE_DRIVER` | `ON` | Command-line script driver | +| `GECODE_ENABLE_FLATZINC` | `ON` | FlatZinc interpreter and MiniZinc library | +| `GECODE_ENABLE_MPFR` | `ON` | MPFR backend for float constraints (`find_package(MPFR)`) | +| `GECODE_ENABLE_QT` | `AUTO` | Qt 6 support (`AUTO`, `ON`, or `OFF`) | +| `GECODE_ENABLE_GIST` | `AUTO` (`OFF` on macOS) | Gist graphical search tool (`AUTO`, `ON`, or `OFF`) | +| `GECODE_ENABLE_THREAD` | `ON` | Multithreaded search | +| `GECODE_ENABLE_OSX_UNFAIR_MUTEX` | `ON` | Use `os_unfair_lock` on macOS | +| `GECODE_ENABLE_CPPROFILER` | `ON` | CPProfiler support | +| `GECODE_ENABLE_CBS` | `OFF` | Counting-based search | +| `GECODE_ENABLE_EXPERIMENTAL` | `OFF` | Preview APIs (`AStar`, `CABS`); may change or be removed | +| `GECODE_ENABLE_ALLOCATOR` | `ON` | Gecode's heap allocator | +| `GECODE_ENABLE_MIMALLOC` | `OFF` | Private embedded mimalloc backend | +| `GECODE_ENABLE_AUDIT` | `OFF` | Internal consistency audits | +| `GECODE_ENABLE_FAULT_INJECTION` | `OFF` | Test-only failpoints (`check-fault`) | +| `GECODE_SANITIZER` | empty | `address`, `undefined`, `address-undefined`, or `thread` | +| `GECODE_ENABLE_GCC_VISIBILITY` | `ON` | Symbol visibility attributes | +| `GECODE_FREELIST32_SIZE_MAX` | empty | Override 32-bit freelist cap | +| `GECODE_FREELIST64_SIZE_MAX` | empty | Override 64-bit freelist cap | +| `GECODE_REGENERATE_VARIMP` | `OFF` | Regenerate `var-type.hpp` and `var-imp.hpp` during build | +| `GECODE_WITH_VIS` | empty | Comma-separated `.vis` files (relative to source dir); implies `GECODE_REGENERATE_VARIMP=ON` | +| `GECODE_LIB_PREFIX` / `_SUFFIX` | empty | Prefix or suffix for generated library basenames | +| `GECODE_DOC_DOT` / `_SEARCH` / `_TAGFILE` | `ON` / `OFF` / `ON` | Doxygen `doc` switches: Graphviz graphs, search engine, and `doc/gecode-doc.tag` | + +Higher-level modules automatically enable the lower-level modules they need +(minimodel enables int and search; examples and FlatZinc enable the core +modelling modules). Configuration prints a summary of enabled and disabled +features after dependency discovery. + +Notes on specific options: + +- **Qt and Gist**: `ON` fails configuration if Qt 6 is missing; `AUTO` enables + support when found. Enabling Qt-backed FlatZinc plugins adds a public Qt 6 + Core dependency to `Gecode::gecodeflatzinc`. On macOS, Gist defaults to `OFF` + because older Qt packages can reference removed system frameworks; enable it + explicitly with a current Qt 6 build. +- **mimalloc (`GECODE_ENABLE_MIMALLOC=ON`)**: downloads and embeds mimalloc + 3.5.3 for Gecode heap and space storage in both shared and static libraries + without affecting application `malloc` or `new`. Embedded symbols carry a + `gecode_` prefix and stay hidden in shared libraries. Requires + `GECODE_ENABLE_ALLOCATOR=ON`, is incompatible with `GECODE_SANITIZER` and + `GECODE_PEAKHEAP`, and requires rebuilding downstream consumers when toggled. +- **Deprecated aliases**: `ENABLE_THREADS`, `ENABLE_GIST`, `BUILD_EXAMPLES`, + and `ENABLE_CPPROFILER` still work with a warning; use the `GECODE_*` names + above. -## Test Targets +## Regenerating checked-in sources -When `BUILD_TESTING=ON`, CMake builds the `gecode-test` test runner on demand. -The standard `check` target runs the basic integrity suite: +Ordinary builds use the checked-in variable headers (`gecode/kernel/var-type.hpp`, +`gecode/kernel/var-imp.hpp`) and FlatZinc parser sources. After changing a +generator input, regenerate and verify freshness: ```bash -cmake --build build --target check +cmake --build build --target regenerate +bash .github/ci/generated-source-freshness.sh --check ``` -Two additional targets expose broader tag-based suites: +Pass `--update` to the freshness script to regenerate without a configured +CMake build directory. + +## Testing and sanitizers + +When `BUILD_TESTING=ON`, CMake provides three tag-based test targets backed by +`gecode-test`: ```bash -cmake --build build --target check-standard -cmake --build build --target check-sweep +cmake --build build --target check # fast integrity suite +cmake --build build --target check-standard # full standard suite +cmake --build build --target check-sweep # heavy sweep suite ``` -`check-standard` runs the standard test suite. `check-sweep` runs tests tagged as -heavy sweep tests and is intended for deliberate, longer-running validation. - -Use `gecode-test -help` for runner options and `gecode-test -list-with-tags` -to inspect test assignments. - -## Build Conventions and Key Options - -### Common CMake options - -- `BUILD_SHARED_LIBS`: conventional default selector - - `ON` default behavior: `GECODE_BUILD_SHARED=ON`, `GECODE_BUILD_STATIC=OFF` - - `OFF` default behavior: `GECODE_BUILD_SHARED=OFF`, `GECODE_BUILD_STATIC=ON` -- `BUILD_TESTING`: controls whether `gecode-test` is built and whether `check` - runs the test subset. The `check` target still exists when tests are disabled, - but reports that checks are skipped. -- `GECODE_INSTALL`: controls install and export rules; defaults to `ON` for - top-level builds and `OFF` for subprojects. -- `CMAKE_BUILD_TYPE` / multi-config `--config`: standard build mode control - -### Feature and toolchain options - -| Option / mechanism | Notes | -|---|---| -| `GECODE_BUILD_SHARED` | Default `ON` | -| `GECODE_BUILD_STATIC` | Default `OFF` | -| `GECODE_ENABLE_THREAD` | Default `ON` | -| `GECODE_ENABLE_OSX_UNFAIR_MUTEX` | Default `ON` | -| `GECODE_ENABLE_QT` | `AUTO` by default; requires Qt 6 | -| `GECODE_ENABLE_GIST` | `AUTO` by default except macOS; disabled automatically if Qt GUI support is unavailable | -| `GECODE_ENABLE_CPPROFILER` | Default `ON` | -| `GECODE_ENABLE_CBS` | Default `OFF` | -| `GECODE_ENABLE_EXAMPLES` | Default `ON` for top-level builds, `OFF` for subprojects | -| `GECODE_ENABLE_EXPERIMENTAL` | Default `OFF`; enables preview APIs | -| `GECODE_ENABLE_SEARCH` | Default `ON` | -| `GECODE_ENABLE_INT_VARS` | Default `ON` | -| `GECODE_ENABLE_SET_VARS` | Default `ON` | -| `GECODE_ENABLE_FLOAT_VARS` | Default `ON` | -| `GECODE_ENABLE_MINIMODEL` | Default `ON` | -| `GECODE_ENABLE_INSTANCE` | Default `ON`; enabled with the driver | -| `GECODE_ENABLE_DRIVER` | Default `ON` | -| `GECODE_ENABLE_FLATZINC` | Default `ON` | -| `GECODE_ENABLE_MPFR` | Default `ON`; uses `find_package(MPFR)` | -| `GECODE_ENABLE_ALLOCATOR` | Default `ON` | -| `GECODE_ENABLE_AUDIT` | Default `OFF` | -| `GECODE_ENABLE_FAULT_INJECTION` | Test-only, process-global failpoints in an isolated single-threaded `check-fault` suite; default `OFF` | -| `GECODE_SANITIZER` | `address`, `undefined`, `address-undefined`, or `thread`; currently requires GCC/Clang-style flags | -| `GECODE_ENABLE_GCC_VISIBILITY` | Default `ON` | -| `GECODE_FREELIST32_SIZE_MAX` | Cache string | -| `GECODE_FREELIST64_SIZE_MAX` | Cache string | -| `GECODE_WITH_VIS` | Comma-separated list | -| `GECODE_LIB_PREFIX` | Prefixes generated library basenames | -| `GECODE_LIB_SUFFIX` | Suffixes generated library basenames | -| `CMAKE_BUILD_TYPE=Debug` (or multi-config `Debug`) | Use standard CMake build-type workflows | -| `CMAKE_BUILD_TYPE=MinSizeRel` or compiler size flags | Use standard size-optimized build settings | -| Toolchain/CMake compile+link flags | Configure profiling via standard compiler flags | -| Toolchain/CMake coverage flags | Configure coverage instrumentation via compiler/linker flags | -| `CMAKE_PREFIX_PATH`, `MPFR_ROOT`, toolchain include/link paths | Use CMake package and toolchain discovery | -| Toolchain include/link paths | GMP is resolved through MPFR/toolchain linkage | -| `GECODE_DOC_DOT`, `GECODE_DOC_SEARCH`, `GECODE_DOC_TAGFILE` | Requires Doxygen 1.18.0 or newer; helper pages require `uv` | -| `GECODE_ENABLE_MIMALLOC` | Default `OFF`; private allocator backend | - -Higher-level modules enable the lower-level modules they require. Examples -and FlatZinc require the core modelling modules; minimodel requires int and -search support. - -`GECODE_ENABLE_QT` and `GECODE_ENABLE_GIST` accept `AUTO`, `ON`, and `OFF`. -`ON` requires their dependencies; `AUTO` uses them when available. Enabling -Qt-backed FlatZinc plugin support can add a public Qt Core dependency to -`Gecode::gecodeflatzinc`. - -`GECODE_ENABLE_EXPERIMENTAL=ON` enables preview APIs, including AStar and CABS. -It is disabled by default. Preview APIs may change or be removed in future -feature releases. - -### Allocator, testing, and documentation options - -- `GECODE_ENABLE_MIMALLOC`: downloads and embeds mimalloc 3.5.3 for Gecode heap - and space storage in shared and static libraries. Default `OFF`. Requires - `GECODE_ENABLE_ALLOCATOR=ON`; incompatible with `GECODE_SANITIZER` and - `GECODE_PEAKHEAP`. Application `malloc` and `new` are unaffected. - Embedded mimalloc symbols use a `gecode_` prefix to avoid conflicts with - an application's own mimalloc; they remain hidden in shared libraries. - Rebuild consumers when changing backends. -- `GECODE_ENABLE_FAULT_INJECTION`: builds deterministic allocation and copy - failpoints together with the `Fault::*` regression suite. This facility is - test-only, process-global, isolated to the dedicated single-threaded fault - test executable, CMake-only, and disabled by default. -- `GECODE_SANITIZER`: selects `address`, `undefined`, `address-undefined`, or - `thread` instrumentation. These modes currently require a compiler that - accepts GCC/Clang sanitizer flags. -- `GECODE_DOC_DOT`, `GECODE_DOC_SEARCH`, `GECODE_DOC_TAGFILE`: configure the - Doxygen `doc` target. Building docs requires Doxygen 1.18.0 or newer and - `uv`; Graphviz `dot` is used when available and `GECODE_DOC_DOT=ON`. - -A directly set `GECODE_BUILD_SHARED` or `GECODE_BUILD_STATIC` overrides the -`BUILD_SHARED_LIBS` default. Configuration reports the enabled and disabled -features after dependency discovery. For Qt, Gist, MPFR, visibility, macOS -mutexes, Graphviz, and tests, it also reports the requested setting. - -CMake uses the checked-in `gecode/kernel/var-type.hpp` and `var-imp.hpp` by -default. `GECODE_REGENERATE_VARIMP=ON` regenerates them. A nonempty -`GECODE_WITH_VIS` list enables regeneration automatically; relative -specification paths are resolved from the source directory. - -Top-level defaults: - -- `GECODE_ENABLE_EXAMPLES=ON` -- `BUILD_TESTING=ON` -- `GECODE_INSTALL=ON` - -Subproject defaults (`add_subdirectory`): - -- `GECODE_ENABLE_EXAMPLES=OFF` -- `BUILD_TESTING=OFF` (unless enabled by parent project) -- `GECODE_INSTALL=OFF` - -### Fault injection and sanitizers - -Fault injection is test-only and process-global. Its tests run in a dedicated, -isolated single-threaded executable and must not share a test process with -ordinary tests. The CMake targets enforce this: +Run `gecode-test -help` for runner options and `gecode-test -list-with-tags` to +inspect tag assignments. The FlatZinc blackbox tests run only when the +`GECODE_TEST_BLACKBOX_EXEC`, `_DLL`, and `_LOG` variables set by `check` are +present. + +### Fault injection + +`GECODE_ENABLE_FAULT_INJECTION=ON` enables deterministic allocation and copy +failpoints for the `Fault::*` suite. Because the failpoints are process-global, +their tests run in a separate single-threaded executable (`-threads 1`) and are +serialized by CTest; the failpoint mechanism is test-only and not a public API: ```bash cmake -S . -B build/fault -DGECODE_ENABLE_FAULT_INJECTION=ON cmake --build build/fault --target check-fault ``` -The ordinary `check` target also runs `check-fault` when fault injection is -enabled. CTest registers the fault suite as a separate process with -`-threads 1` and serializes it with the fault-injection resource lock. The -FailPoint facility is not a supported application API. +When fault injection is enabled, `check` also runs `check-fault`. + +### Sanitizers -For a sanitizer build, configure a separate build directory. For example: +`GECODE_SANITIZER` currently requires a compiler accepting GCC/Clang sanitizer +flags. Configure a dedicated build directory: ```bash -cmake -S . -B build/asan-ubsan \ +cmake -S . -B build/asan-ubsan -DCMAKE_BUILD_TYPE=RelWithDebInfo \ -DGECODE_SANITIZER=address-undefined cmake --build build/asan-ubsan --target check ``` -On macOS, `std::thread` stacks are 512 KiB, while the main thread has 8 MiB, and -the check targets run `gecode-test` on worker threads. In a Debug build with -AddressSanitizer, forced inlining gives some propagators a frame of about -400 KiB, so a test can overflow its worker stack. This is a limit of that build, -not unbounded recursion. Use an optimized sanitizer build, or run the `check` -selection on the main thread: +On macOS, `std::thread` stacks are 512 KiB (versus 8 MiB on the main thread). +In an unoptimized Debug AddressSanitizer build, forced inlining pushes some +propagator frames near 400 KiB and can overflow a worker thread stack. Use an +optimized sanitizer build as above, or run the `check` selection on the main +thread: ```bash build/asan-ubsan/bin/gecode-test -iter 2 -threads 1 -fixprob 1 -tag check ``` -The FlatZinc blackbox tests run only when the `GECODE_TEST_BLACKBOX_EXEC`, -`_DLL`, and `_LOG` variables that `check` sets are present. - -## Using Gecode From Other CMake Projects +## Using Gecode from other CMake projects -### Recommended aggregate target - -`Gecode::gecode` links the exported aggregate target. Use it unless the -consumer needs explicit module linkage. +Point CMake at an installation with `-DCMAKE_PREFIX_PATH=/path/to/install` or +`-DGecode_ROOT=/path/to/install`, then link the aggregate target +`Gecode::gecode`: ```cmake find_package(Gecode CONFIG REQUIRED) @@ -273,14 +215,10 @@ add_executable(app main.cpp) target_link_libraries(app PRIVATE Gecode::gecode) ``` -### Component targets - -Canonical component names: - -- `support`, `kernel`, `search`, `int`, `set`, `float`, `minimodel`, `instance`, `driver`, - `flatzinc`, `gist`, `test` - -Example: +For explicit module linkage, request components from `support`, `kernel`, +`search`, `int`, `set`, `float`, `minimodel`, `instance`, `driver`, `flatzinc`, +`gist`, and `test` (legacy `gecode*` component names such as `gecodedriver` are +also accepted): ```cmake find_package(Gecode CONFIG REQUIRED COMPONENTS driver) @@ -288,17 +226,15 @@ add_executable(app main.cpp) target_link_libraries(app PRIVATE Gecode::gecodedriver) ``` -### Test component for custom propagators +Check the installed version via `Gecode_VERSION` from `find_package(Gecode)` +rather than parsing `gecode/support/config.hpp`. Packagers wanting no Qt +dependency in the exported package should configure with +`-DGECODE_ENABLE_QT=OFF -DGECODE_ENABLE_GIST=OFF`. -A Gecode installation configured with `BUILD_TESTING=ON` exports the `test` -component. It lets downstream projects check custom integer, Boolean, set, and -float propagators with Gecode's test runner. +### Test component for custom propagators -- Always available targets: `Gecode::gecodetest`, `Gecode::gecodetestint` -- Set target when configured: `Gecode::gecodetestset` -- Float target when configured: `Gecode::gecodetestfloat` -- Installed headers follow the same configuration: `test/test.*`, `test/int.*`, - `test/set.*`, and `test/float.*` +An installation built with `BUILD_TESTING=ON` exports the `test` component so +downstream projects can test custom propagators with Gecode's test harness: ```cmake find_package(Gecode CONFIG REQUIRED COMPONENTS test) @@ -306,88 +242,23 @@ add_executable(custom-propagator-test custom-propagator-test.cpp) target_link_libraries(custom-propagator-test PRIVATE Gecode::gecodetestint) ``` -Use `Gecode::gecodetestset` or `Gecode::gecodetestfloat` for those variable -families. The targets supply the runner and their Gecode dependencies. With -`add_subdirectory` or `FetchContent`, enable `BUILD_TESTING` before adding Gecode. -When both library variants are installed, targets ending in `_shared` or -`_static` select a variant explicitly. Use one variant throughout the test -executable so registration and execution share the same registry. - -See the test API in [`test/int.hh`](../test/int.hh) and -[`test/test.hh`](../test/test.hh) for an example, consistency controls, and -`Test::run_registered_tests`. The runner's `-help` lists execution and replay -options. - -Legacy component spellings are also accepted in `COMPONENTS`: - -- `gecodesupport`, `gecodekernel`, `gecodesearch`, `gecodeint`, `gecodeset`, - `gecodefloat`, `gecodeminimodel`, `gecodeinstance`, `gecodedriver`, `gecodeflatzinc`, - `gecodegist` - -### Package location hints - -Use one of: - -- `-DCMAKE_PREFIX_PATH=/path/to/install` -- `-DGecode_ROOT=/path/to/install` - -Packagers that want to avoid any Qt dependency in the exported package should -configure with: - -```bash -cmake -S . -B build -DGECODE_ENABLE_QT=OFF -DGECODE_ENABLE_GIST=OFF -``` - -### Version checks - -Use `Gecode_VERSION` from package config: - -```cmake -find_package(Gecode CONFIG REQUIRED) -message(STATUS "Gecode version: ${Gecode_VERSION}") -``` - -Do not rely on parsing installed headers such as `config.hpp` for version checks. - -## Migration Notes - -### Deprecated cache variable aliases - -| Deprecated | Replacement | -|---|---| -| `ENABLE_THREADS` | `GECODE_ENABLE_THREAD` | -| `ENABLE_GIST` | `GECODE_ENABLE_GIST` | -| `BUILD_EXAMPLES` | `GECODE_ENABLE_EXAMPLES` | -| `ENABLE_CPPROFILER` | `GECODE_ENABLE_CPPROFILER` | - -Deprecation horizon: - -- These aliases are accepted for the 6.x line to preserve migration compatibility. -- New configurations should use the `GECODE_*` names. +Exported test targets and headers follow the enabled variable modules: +`Gecode::gecodetest` and `Gecode::gecodetestint` (`test/test.*`, `test/int.*`), +plus `Gecode::gecodetestset` (`test/set.*`) and `Gecode::gecodetestfloat` +(`test/float.*`) when built. When both shared and static variants are installed, +select one explicitly with `_shared` or `_static` suffixes across the whole test +executable so test registration and execution share one registry. See +[`test/int.hh`](../test/int.hh) and [`test/test.hh`](../test/test.hh) for the +test API and `Test::run_registered_tests`. ## Troubleshooting -- `Target "..." links to Gecode::gecode but the target was not found`: - - Ensure you are using an installation built with this CMake export layout. - - Check `CMAKE_PREFIX_PATH` / `Gecode_ROOT` points to the intended install. -- `find_package(Gecode COMPONENTS ...)` fails: - - Verify requested component is enabled in the installed build. - - For optional modules (`flatzinc`, `gist`, `float` with MPFR), ensure dependencies were available. - - The `test` component requires `BUILD_TESTING` to be true in the installed package's configuration. -- Qt/Gist issues: - - `GECODE_ENABLE_QT=ON` and `GECODE_ENABLE_GIST=ON` are requirement modes; - use `AUTO` when dependency discovery should be best-effort. - - `GECODE_ENABLE_GIST=ON` requires Qt discovery and a usable Qt link - interface. - - Gecode requires Qt 6. - - On macOS, Gist defaults to `OFF`; enable it explicitly once the local - Qt/OpenGL framework setup is known to link. Current macOS SDKs require a - current Qt 6 build; older Qt packages can still reference removed system - frameworks. -- MPFR issues: - - Use `CMAKE_PREFIX_PATH`, `MPFR_ROOT`, or toolchain include/link paths so - `find_package(MPFR)` succeeds. - - Installed packages built with MPFR first try config-mode MPFR discovery, - then the installed `FindMPFR.cmake`. vcpkg consumers can rely on the active - vcpkg toolchain or `VCPKG_ROOT`/`VCPKG_TARGET_TRIPLET` to provide the MPFR - and GMP roots. +- **`Gecode::gecode` not found**: check that `CMAKE_PREFIX_PATH` or + `Gecode_ROOT` points to an installation built with CMake. +- **`find_package(Gecode COMPONENTS ...)` fails**: confirm the requested module + was enabled when Gecode was built (and `BUILD_TESTING=ON` for `test`). +- **MPFR not found**: pass `CMAKE_PREFIX_PATH` or `MPFR_ROOT` so + `find_package(MPFR)` finds MPFR and GMP. Exported packages built with MPFR try + config-mode MPFR discovery first, then the installed `FindMPFR.cmake`; vcpkg + consumers can rely on their active vcpkg toolchain or + `VCPKG_ROOT`/`VCPKG_TARGET_TRIPLET`. diff --git a/docs/code-style.md b/docs/code-style.md index bce3c6c615..547b4fec5d 100644 --- a/docs/code-style.md +++ b/docs/code-style.md @@ -1,141 +1,155 @@ # Code style -Use clang-format **22** for first-party C and C++ sources. `.clang-format` -defines the exact formatting; `.editorconfig` supplies the matching editor -defaults. +First-party C and C++ sources are formatted with clang-format **22** according +to `.clang-format`; `.editorconfig` supplies the matching editor defaults. ## Formatting -C++ uses four-space indentation and a 120-column limit. Braces stay on the -opening line, namespace bodies remain indented, and pointer and reference -markers bind to the type. Function definitions retain a separate -return-type line. Include order and comment wrapping are preserved. Comment -indentation follows the surrounding code, including copyright notices and -Doxygen text. +C++ uses four-space indentation and a 120-column line limit, with opening +braces on the same line, indented namespace bodies, pointer and reference +markers bound to the type, and a separate return-type line on function +definitions. Include order and comment wrapping are preserved; comment +indentation follows the surrounding code, including copyright headers and +Doxygen blocks. Four-space indentation separates nested control flow, and 120 +columns leaves room for namespace-qualified calls, templates, and scheduling +expressions without awkward wrapping. -Four spaces distinguish nested control flow. The 120-column limit leaves room -for namespace-qualified calls, templates, and generated scheduling expressions. -A comparison across six representative files produced 9,411 lines at 100 columns -and 9,299 at 120, versus 9,665 at 80. Only 146 additional lines exceeded 100 -columns at 120, so the wider limit mainly avoids awkward wrapping. Continuation -indentation stays at four spaces; comments retain their existing wrapping. +Python uses four spaces; CMake and YAML use two. Keep editor settings in +`.editorconfig` rather than per-file indentation comments. -Python uses four spaces; CMake and YAML use two. Editor settings belong in -`.editorconfig` rather than per-file indentation headers. +### Generated files -## Generated files +The variable-header generator formats its output with clang-format 22 (via +`CLANG_FORMAT`, `clang-format-22`, or `clang-format` on `PATH`); ordinary builds +use the checked-in headers and need no LLVM tools. Edit generator inputs and +regenerate rather than editing checked-in outputs by hand. -The variable-header generator formats its output with clang-format 22. Set -`CLANG_FORMAT` to its executable, or put `clang-format-22` or `clang-format` -on `PATH`. Builds using the checked-in headers do not require this tool. -Apply changes to the generator or its inputs, regenerate the outputs, and -check freshness. Formatting the checked-in outputs alone would make the next -regeneration undo the change. - -The generated FlatZinc parser and lexer retain Bison and Flex formatting; -their upstream scaffolding is excluded from clang-format. Regenerate these -files from `.yxx` and `.lxx` inputs rather than editing the output by hand. +The generated FlatZinc parser and lexer keep Bison and Flex formatting and are +excluded from clang-format; edit their `.yxx` and `.lxx` inputs instead. ## Naming -Functions, variables, and members use `snake_case`. Types retain `PascalCase` -and macros `UPPER_CASE`. Enum constants use `UPPER_CASE` or `PascalCase`: -existing constants keep their case, and a new enum uses `PascalCase`, as in -`EndReason::Limit`, unless `UPPER_CASE` suits it better. Existing private-member -leading or trailing underscores are accepted when the name itself is snake_case. - -Constants may use `UPPER_CASE`, and so may functions that stand for constant -values. Modification events and propagation conditions (`ME_INT_VAL`, -`PC_INT_DOM`), propagator status helpers (`ES_SUBSUMED`, `ES_FIX_PARTIAL`), -and branching selectors (`INT_VAR_SIZE_MIN()`, `INT_VAL_MIN()`) belong to the -same vocabulary as the enum constants they appear with, such as `ES_FIX` and -`IRT_EQ`, and keep their spelling. -Names should separate words and describe their purpose. A casing check cannot -identify word boundaries in names such as `dfsengine` and `modeventdelta`; -those require explicit review. - -Representative API changes include: - -| Previous spelling | Current spelling | -|---|---| -| `IRT_LE`, `FRT_LE`, `SRT_LE` | `IRT_LT`, `FRT_LT`, `SRT_LT` | -| `RM_NONE`, `RM_CONSTANT`, `RM_LINEAR`, `RM_LUBY`, `RM_GEOMETRIC` | `RESTART_NONE`, `RESTART_CONSTANT`, `RESTART_LINEAR`, `RESTART_LUBY`, `RESTART_GEOMETRIC` | -| `RM_PMI` | `RM_RIMP` | -| `TT_FIXP`, `TT_FIXS`, `TT_FIXE` | `TT_FIXED_PROCESSING`, `TT_FIXED_START`, `TT_FIXED_END` | -| `SRT_DISJ`, `SRT_CMPL` | `SRT_DISJOINT`, `SRT_COMPLEMENT` | -| `SOT_DUNION`, `SOT_INTER` | `SOT_DISJOINT_UNION`, `SOT_INTERSECTION` | -| `SM_STAT` | `SM_STATISTICS` | -| `RR_NO`, `RR_SOL`, `RR_CMPL`, `RR_LIM` | `RR_NONE`, `RR_SOLUTION`, `RR_COMPLETE`, `RR_LIMIT` | -| `SearchTracer::AOE` | `SearchTracer::OTHER` | -| `CPLT_ASSIGNMENT` | `COMPLETE_ASSIGNMENT` | -| `MT_ANY`, `MT_NOT`, `MT_FIRST` | `MATCH_ANY`, `MATCH_NOT`, `MATCH_FIRST` | -| `EF_MRKLB`, `EF_MRKUB`, `EF_LM`, `EF_UM`, `EF_DEL` | `EF_MARKED_LBC`, `EF_MARKED_UBC`, `EF_MATCHED_LBC`, `EF_MATCHED_UBC`, `EF_DELETED` | -| `RET_FST`, `RET_LST` | `RET_START`, `RET_FINISH` | -| `IT_SHRT` | `IT_SHORT` | -| `BT_COMP` | `BT_COMPLEMENT` | -| `EVENT_CHCK`, `EVENT_PRUN` | `EVENT_CHECK`, `EVENT_PRUNE` | -| `nooverlap(...)` | `no_overlap(...)` | -| `binpacking(...)` | `bin_packing(...)` | -| `modeventdelta(...)` | `modevent_delta(...)` | -| `dfsengine(...)` | `make_dfs_engine(...)` | -| `clearall(value)` | `clear_all(value)` | -| `arg2intvarargs(...)` | `to_int_var_args(...)` | - -Strict-less relation constants use `_LT`; `_LQ` continues to mean less-or-equal. -The former `_LE` names have no compatibility aliases, and neither do the other -former constant spellings in the table. - -Qt overrides and other external interfaces retain the spellings their APIs -require. Parser tokens and protocol strings remain unchanged. - -## Enums - -New enums are `enum class`. Use a plain `enum` only where an existing API -requires it, or where the values are bits or bit positions held in an `int`, -as with `TraceEvent`. - -A public enum converted from a plain enum keeps its `UPPER_CASE` constants -usable without qualification through `using enum`, on the line after the enum -and at the same scope: - -```cpp -enum class IntRelType { IRT_EQ, IRT_NQ, ... }; -using enum IntRelType; -``` +- Functions, variables, parameters, and members use `snake_case`. Existing + leading or trailing underscores on private members are fine when the stem is + `snake_case`. +- Types use `PascalCase`; macros use `UPPER_CASE`. `forceinline` stays + lowercase so it reads like `inline`. +- Constants and functions that stand for constant values (`ME_INT_VAL`, + `PC_INT_DOM`, `ES_SUBSUMED`, `INT_VAR_SIZE_MIN()`) may use `UPPER_CASE`. +- Enum constants use `PascalCase` in new scoped enums (e.g., + `EndReason::Limit`), or `UPPER_CASE` in converted legacy enums. +- Separate words clearly; a casing linter cannot catch run-together names such + as `dfsengine` or `modeventdelta`. +- External interfaces (Qt overrides, parser tokens, protocol strings) keep the + spellings their APIs require. -`using enum` cannot name a dependent type, so an enum in a class template -declares one `static constexpr` alias per constant instead, as -`CompactStatus::StatusType` does. +For the Gecode 6 to 7 API renames, see +[Gecode 7 migration notes](gecode-7-migration.md). -A new enum names its constants in `PascalCase` and is always used qualified, -as in `MetaEvent::Solution`, so it has no `using enum`. +## C++ conventions -Give an enum operators only if its values form a real bit set. `IntPropLevel` -is the one such enum, with `operator|`, `operator&`, and `operator|=`. Test a -bit with `(ipl & IPL_BASIC) != IPL_DEF`. Its underlying type is unsigned -because `IntPropLevels` stores levels in bit-fields, where a signed type would -change their values. +### Enums -All other conversions are explicit: `std::to_underlying` or `static_cast` for -an array index, a bit position, or a packed field, and `static_cast` back to -the enum. A command-line option that chooses an enum value is a -`Driver::EnumOption`, which needs no casts. +New enums are `enum class` with `PascalCase` constants used qualified (such as +`MetaEvent::Solution`). Use a plain `enum` only when an existing API requires +it or when values are bit masks stored in an `int` (such as `TraceEvent`). -## Parameter lists and forceinline +Legacy public enums converted to `enum class` keep their unqualified +`UPPER_CASE` constants available via `using enum` on the following line at the +same scope: -An empty parameter list is `()`, also in function pointer types and -`std::function` signatures. `(void)` is a C spelling and stays only in C -sources, where it means something different. -`modernize-redundant-void-arg` enforces the rule. A cast to `void` that discards -a value, such as `(void)new (p) T()`, is a different construct and stays. +```cpp +enum class IntRelType { IRT_EQ, IRT_NQ, ... }; +using enum IntRelType; +``` -`forceinline` stays lowercase, although it is a macro, so that it reads like -`inline`. +In a class template, where `using enum` cannot name a dependent type, declare +`static constexpr` aliases instead (as in `CompactStatus::StatusType`). + +Give an enum bitwise operators only when it models a bit set (`IntPropLevel`, +with an unsigned underlying type because `IntPropLevels` stores it in +bit-fields; test bits with `(ipl & IPL_BASIC) != IPL_DEF`). All other integer +conversions use `std::to_underlying` or `static_cast`; command-line options +selecting an enum value use `Driver::EnumOption`, which needs no casts. + +### Parameter lists and value passing + +Empty parameter lists are `()`, never `(void)`, including in function pointer +types and `std::function` signatures. `(void)` stays only in C sources; casts +such as `(void)new (p) T()` are value discards, not parameter lists. + +Pass non-trivial read-only parameters by `const&`. When the callee takes +ownership and the type has a cheap move (`std::function`, `std::string`, +`std::vector`, branching configurations), take it by value and `std::move` it +into place. + +Gecode's shallow handles are trivially copyable and passed by value: `Home`, +propagator/brancher groups, `Pos`, `Reify`, variables, variable arrays, +`ViewArray`, open variable/view lists, `LocalHandle`, `AFC`, and views. Keep +them trivial by declaring no copy/move members or destructor (or defaulting +them on their first declaration); `test/array.cpp` checks this property. +Owned and reference-counted types (`SharedHandle` subclasses such as `IntSet`, +`TupleSet`, `DFA`, `Rnd`, `Action`, `CHB`; `SharedArray`, `*Args`, `REG`, +strings, callbacks) and `FloatVal` follow the `const&` / move rule above. + +### Special members + +Follow the rule of zero when members already copy, move, and destroy +themselves. When a special member must be declared, write `= default` on its +first declaration (an out-of-line `= default` is user-provided and breaks +triviality; virtual destructors may stay out of line to anchor the vtable). +Forbid operations with a public `= delete`, not an undefined private member. + +Hand-written bodies with `// NOLINTNEXTLINE(modernize-use-equals-default)` stay +only where defaulting changes semantics: cloning constructors (`Space(Space&)`, +which write forwarding pointers into their source), empty default constructors +that intentionally avoid zero-initialization under `T()` or `alloc(n)`, and +constructors that are empty only in some build configurations. + +### Comparisons + +Use C++20 defaulted `bool operator==(const T&) const = default;` for +field-wise equality and `auto operator<=>(const T&) const = default;` (with +``) for lexicographical field-order comparison, without declaring +`operator!=` or redundant relational operators. Write expressions (`a != b`), +not explicit calls (`operator!=(a, b)`). + +Keep hand-written `operator==`/`operator<` for non-field-wise equality or +custom sort keys, modelling-expression operators (`IntVar < IntVar`), and +`FloatVal` interval comparisons. Keep `operator!=` only where C++20's reversed +candidates would cause ambiguity: `ConstView`, `VarImpView`, `DerivedView`, +and `TupleSet` (where `true != t` would otherwise be ambiguous between its +`int` constructor and `bool` conversion). + +### Explicit object parameters (deducing `this`) + +Keep a const/non-const overload pair unless merging with +`template auto& f(this Self&& self)` eliminates a multi-statement +duplicated body (beyond `assert`) or a `const_cast` forwarding idiom without +changing accepted receivers or return types. Note four constraints: + +- Member lookup through `self` happens in the receiver's class, which breaks + private inheritance that re-exports a member via `using` (this is why + `Matrix::operator()` keeps its overload pair). +- Storage reached through a pointer does not inherit `const` from `self`; use + `std::forward_like`. +- Explicit-object members cannot be `virtual` or `static`, and their address is + a plain function pointer rather than a pointer to member. +- Because the merged member is a template, its definition must live in a header. + +### Streams and `noexcept` + +Use `'\n'` inside formatted records; flush explicitly only for complete +solutions, progress updates, protocol responses, or diagnostics. Explicit +`(void)` casts are accepted for reviewed unused return values such as ownership +handoffs. Never add `noexcept` to a potentially throwing operation just to +silence a diagnostic; check allocation-failure and interval-rounding semantics +first. ## Checking changes -Put LLVM 22 tools on `PATH`, or set `CLANG_FORMAT` and `CLANG_TIDY` to their -executables. The checker rejects other major versions. Use: +Put LLVM 22 tools on `PATH` (or set `CLANG_FORMAT` and `CLANG_TIDY`; other +major versions are rejected): ```sh uv run misc/check.py format @@ -144,236 +158,101 @@ uv run misc/check.py lint --build-dir build/local uv run misc/check.py all --build-dir build/local --jobs 4 ``` -CMake provides `format`, `check-format`, `check-lint`, and `check-extended` -targets for the same commands. Formatting checks need no configured build. -Lint requires a Ninja or Makefiles compilation database configured with -`-DCMAKE_EXPORT_COMPILE_COMMANDS=ON`; it checks compiled sources and their -maintained headers. The command reports sources outside that build so optional -modules cannot silently disappear from the coverage report. -Bison/Flex grammar syntax is reviewed manually; clang-tidy checks the owned C++ -action ranges in their generated translation units. - -The extended command also checks the changelog and generated-source freshness, -builds the configured targets, runs CTest integrity and enabled fault suites, -installs into `check-install` under the build directory, and builds, tests, and lints the -allocator and public-test-component package consumers. It also builds the -documentation (Doxygen 1.18.0 or newer). The full `check-standard` and -`check-sweep` suites remain separate targets: the standard suite alone contains -over 54,000 cases and defaults to five iterations per case. -Besides LLVM 22, the extended check requires uv, Bison 3.8.2, Flex 2.6.4, Ninja, -and Doxygen 1.18.0 or newer. Configure with `BUILD_TESTING`, `GECODE_INSTALL`, -`GECODE_ENABLE_ALLOCATOR`, search, integer variables, minimodel, and driver -enabled. Lint always analyzes assertions by undefining `NDEBUG`, regardless of -the selected build type. Ordinary compilation and runtime tests retain the -configured build settings. -Enable optional and experimental modules in the build when checking them; -platform-specific code also needs its corresponding CI toolchain. Normal -builds use checked-in generated sources and do not require LLVM tools. - -Performance checks cover hidden loop copies, associative-container lookup, -vector growth, string operations, and missed moves as well as unnecessary -copies. Use `'\n'` inside a formatted record. Flush explicitly when publishing -a solution, progress update, protocol response, or complete diagnostic; a -printer should not flush each row of a multi-line solution. -The unused-return-value check accepts explicit `(void)` discards for reviewed -operations such as ownership handoff after successful engine construction. - -`performance-unnecessary-value-param` reports parameters that are copied but -only read. Take such a parameter by `const&`. When the callee keeps the value -and the type has a real move constructor, such as `std::function`, -`std::string`, `std::vector`, or a branching configuration, take it by value -and `std::move` it into place instead. - -Gecode's shallow handles are trivially copyable, so the check never reports -them: `Home`, the groups, `Pos`, `Reify`, the variables (`IntVar` and so -on), the variable arrays and `ViewArray`, the open variable and view lists, -`LocalHandle`, `AFC`, and the views. Copying one copies a few pointers or ids, -with no reference count or allocation, and Gecode code relies on their value -semantics. Keep them so: define no copy member, move member, or destructor -for a handle that only copies its members, or default it on its first -declaration. `test/array.cpp` asserts the property. Owned and reference-counted -types are not exempt: `SharedHandle` types such as `IntSet`, `TupleSet`, -`DFA`, `Rnd`, `Action`, and `CHB`, `SharedArray`, the `*Args` arrays, `REG`, -strings, and callbacks. Their copies touch a reference count or allocate, so -they follow the rule above. `FloatVal` is trivially copyable, so the check -does not report it, but it is two doubles, not a handle: pass it by `const&`. - -Special members follow the rule of zero: a class whose members copy, move, -and destroy themselves declares no copy member, move member, or destructor. -Where a special member must be declared, for example a default constructor -beside other constructors or a virtual destructor, write `= default` instead -of an empty body or a member-wise copy, on the member's first declaration in -the class. A member defaulted out of line is user-provided and keeps the -class non-trivial. Virtual destructors may stay out of line: their class is -never trivial, and one defined in a .cpp file decides where the vtable is -emitted. A member that must not be called is a public `= delete`, not a -private member without a definition. `modernize-use-equals-default` and -`modernize-use-equals-delete` enforce these rules. - -Some hand-written members stay, each after a -`// NOLINTNEXTLINE(modernize-use-equals-default)` line. Cloning constructors -such as `Space(Space&)` are copy constructors despite their non-const -parameter, so the compiler declares no implicit copy or move constructor beside -them. They take their source by non-const reference because cloning writes -forwarding pointers into it, and they update their variables with `update()`. -An empty default constructor stays where defaulting it would change what -value-initialization does: `T()`, `T{}`, and the `alloc(n)` functions of -spaces, regions, and the heap zero a class whose default constructor is not -user-provided, while the empty constructor leaves fields without an initializer -untouched. A constructor whose body is empty only in some configurations stays -as well. - -Comparisons use the C++20 forms. A class whose equality compares every field -declares `bool operator==(const T&) const = default;`. A class ordered -lexicographically by its fields in declaration order declares -`auto operator<=>(const T&) const = default;` instead, which also provides -`==`; its header includes ``. Declare no `operator!=` and no `<`, -`<=`, `>`, or `>=` beside them: the compiler rewrites `a != b` as -`!(a == b)` and the relational operators through `operator<=>`, in either -argument order. A hand-written `operator==` stays where equality is not -field-wise, for example a deep comparison of a shared object or a comparison -of the address an allocator refers to, and it gets no `operator!=` either. A -hand-written `operator<` stays where the order is not the field order, such -as a sort key. Operators that build modelling expressions, such as -`IntVar < IntVar`, keep all their operators, and so do the possibly/certainly -interval comparisons of `FloatVal`. The kernel's heterogeneous `ConstView`, -`VarImpView`, and `DerivedView` templates keep `operator!=`: without it, their -reversed `operator==` candidates would join every view comparison. A class -with both an implicit converting constructor and an implicit conversion -operator keeps `operator!=` as well. `TupleSet` is one: without its -`operator!=`, `true != t` is ambiguous between its `int` constructor and its -`bool` conversion. Rewriting -covers only operator expressions, so write `a != b`, not `operator!=(a, b)` or -`a.operator<(b)`. No clang-tidy check enforces this rule. - -A const/non-const overload pair stays a pair unless one member with an -explicit object parameter, `template auto& f(this Self&& self)`, -removes a duplicated body of more than one statement, not counting `assert`, -or a `const_cast` forwarding idiom. A pair whose bodies are one statement each -stays: the merged template is not shorter. Merge only when the merged member -returns the same type and accepts the same receivers as the pair, including -rvalues and calls through derived classes. A member reached through `self` -is looked up in the receiver's class, so a derived class can hide it, and a -class that inherits privately and re-exports the member with `using` makes -the base inaccessible, so the call no longer compiles. Storage reached -through a pointer does not inherit const from `self`; return it through -`std::forward_like`. An explicit-object member cannot be virtual or -static, takes no trailing cv or ref qualifier, and its address is a plain -function pointer rather than a member pointer. The merged member is a -template over `Self`, so its definition must be visible to callers: a pair -defined in a .cpp file moves to a header. `Matrix::operator()` keeps its pair -for the derived-class reason: its two bodies duplicate a range check, but a -merged member would reject a privately derived matrix. No clang-tidy check -enforces this rule. - -Never add `noexcept` to a potentially throwing operation just to satisfy a -diagnostic. Review `noexcept` guarantees, destructor triviality, and math -promotion against allocation-failure handling and interval-rounding semantics. +CMake exposes the same steps as `format`, `check-format`, `check-lint`, and +`check-extended`. + +`lint` requires a Ninja or Makefiles build configured with +`-DCMAKE_EXPORT_COMPILE_COMMANDS=ON`; it checks compiled sources, maintained +headers, and the owned C++ action ranges inside the generated FlatZinc parser +and lexer, and lists any sources outside the build so disabled modules are +visible. Lint undefines `NDEBUG` so assertions are always analyzed. + +`all` / `check-extended` runs formatting, lint, changelog and generated-source +freshness checks, build, CTest integrity and enabled fault suites, package +installation and downstream consumer tests, and Doxygen (`1.18.0+`). It needs +LLVM 22, `uv`, Bison 3.8.2, Flex 2.6.4, Ninja, Doxygen 1.18.0+, and a build +with `BUILD_TESTING`, `GECODE_INSTALL`, `GECODE_ENABLE_ALLOCATOR`, search, int, +minimodel, and driver enabled. The full `check-standard` and `check-sweep` +suites remain separate targets. ## Clang-tidy check selection -`.clang-tidy` enables the `bugprone`, `concurrency`, `misc`, `modernize`, -`performance`, `portability`, and `readability` groups as a whole, and the -analyzer groups `core`, `cplusplus`, `deadcode`, `nullability`, `optin`, -`security`, `unix`, and `valist`. Checks from `cert`, `cppcoreguidelines`, -`google`, and `hicpp` are named one by one. When a new diagnostic appears, fix -the code. Use a `NOLINT` naming the check and the reason only for a false -positive or a deliberate exception. Add an exclusion only for a reason like -those below. - -Review fix-its before committing them, and build the tests with them. -`modernize-use-using` drops `const` from aliases such as `const_iterator`. -`modernize-use-integer-sign-comparison` turns `x != static_cast(-1)` -into a comparison that is always true. `readability-simplify-boolean-expr` -rewrites tests that exercise the comparison operators themselves. -`modernize-loop-convert` calls the element of every loop `i`; give it a name -that fits. - -These checks are excluded because the code is deliberately written the way they -reject: - -- `bugprone-derived-method-shadowing-base-method`: static polymorphism. -- `bugprone-multi-level-implicit-pointer-conversion`: allocator templates. -- `bugprone-signed-char-misuse`: `signed char` is a small integer here. -- `bugprone-throwing-static-initialization`: tests register through statics. -- `concurrency-mt-unsafe`: `exit` and `getenv` run before threads start. -- `misc-confusable-identifiers`: `I` as a template parameter next to `l`. -- `misc-multiple-inheritance`, `misc-no-recursion`, - `misc-non-private-member-variables-in-classes`: common and intended. -- `misc-new-delete-overloads`: delete-only overloads are intended. -- `misc-use-anonymous-namespace`: `static` is allowed. -- `modernize-avoid-c-arrays`: fixed tables and space-allocated arrays. -- `modernize-use-std-numbers`: rounded or specification-defined constants, such - as the TSPLIB value of pi. -- `performance-enum-size`: would change layouts and ABI. -- `performance-no-int-to-ptr`: pointer tagging. -- `portability-template-virtual-member-function`: reports every virtual member - that a translation unit leaves uninstantiated, and the MSVC builds compile - them anyway. -- `readability-convert-member-functions-to-static`, - `readability-make-member-function-const`: views implement a shared interface - whose members mutate in some views only. -- `readability-implicit-bool-conversion`: `if (p)` is the local idiom. - -These checks are excluded because following them makes the code worse or their -reports are mostly noise: - -- `bugprone-branch-clone`: parallel cases read better, and none of its reports - was a bug. -- `bugprone-easily-swappable-parameters`: nearly every posting function. -- `bugprone-implicit-widening-of-multiplication-result`: values are int-sized by - design. -- `bugprone-inc-dec-in-conditions`: reports sequenced `&&` conditions. -- `bugprone-macro-parentheses`: macro arguments are names or types. -- `bugprone-narrowing-conversions`: casts would silence the reports, not verify - them. -- `bugprone-switch-missing-default-case`: option values and tests. -- `bugprone-unchecked-string-to-number-conversion`: command-line parsing, where - a change would alter behaviour. -- `misc-const-correctness`: `const` on shallow handles misleads. -- `misc-header-include-cycle`, `misc-include-cleaner`: umbrella headers and - `.hpp` files that are not self-contained by design. -- `misc-static-assert`: only reports `GECODE_NEVER`, which is `assert(false)`. -- `modernize-pass-by-value`: most parameters are handles and views with no - cheaper move, and the rest are strings on setup paths. -- `modernize-return-braced-init-list`, `modernize-use-auto`, - `modernize-use-designated-initializers`, - `modernize-use-trailing-return-type`: the written types and forms are useful - at the declaration. -- `modernize-use-default-member-init`: constructor lists keep all of an actor's - state in one place, and a default initializer adds stores to clone - constructors that leave members unset on purpose. -- `modernize-use-nodiscard`: applies to nearly every accessor. -- `readability-avoid-nested-conditional-operator`: compact view code. -- `readability-braces-around-statements`, `readability-identifier-length`, - `readability-isolate-declaration`, `readability-magic-numbers`, - `readability-math-missing-parentheses`, `readability-named-parameter`: these - contradict the existing style. -- `readability-function-cognitive-complexity`, `readability-function-size`: - propagators are long by nature. -- `readability-redundant-declaration`: documented repeats, and its fix-it breaks - templates. -- `readability-use-anyofallof`: the loops are clearer. - -These analyzer checks are excluded after review of their reports: - -- `clang-analyzer-cplusplus.NewDeleteLeaks`: tests register self-owning objects - with `(void)new`. -- `clang-analyzer-optin.core.EnumCastOutOfRange`: flag combinations. -- `clang-analyzer-optin.cplusplus.UninitializedObject`: `Delta` and similar - types leave fields unset on purpose. -- `clang-analyzer-optin.performance.Padding`: its one report is a small static - table whose field order follows the table's columns. -- `clang-analyzer-security.ArrayBound`: cannot see loop invariants or trailing - arrays. -- `clang-analyzer-unix.Malloc`: cannot see reference counts. - -`cppcoreguidelines-prefer-member-initializer` is not enabled: it moves -statements across side effects, such as `e >> n` before an allocation of size -`n`, and into initializer lists guarded by `#ifdef`. The other checks of -`cppcoreguidelines`, `cert`, `google`, and `hicpp` are not enabled because they -are aliases of enabled checks, restate a rejected check, or forbid techniques -that the kernel depends on, such as raw memory and pointer arithmetic. The -`abseil`, `altera`, `android`, `boost`, `darwin`, `fuchsia`, `linuxkernel`, -`llvm`, `llvmlibc`, `mpi`, `objc`, `openmp`, and `zircon` groups target other -projects and platforms. +`.clang-tidy` enables `bugprone`, `concurrency`, `misc`, `modernize`, +`performance`, `portability`, `readability`, and the analyzer groups `core`, +`cplusplus`, `deadcode`, `nullability`, `optin`, `security`, `unix`, and +`valist`, plus individual checks from `cert`, `cppcoreguidelines`, `google`, +and `hicpp`. Fix new diagnostics in code; use `NOLINT(check)` with a reason +only for false positives or deliberate exceptions. + +Review fix-its before committing and rebuild the tests: +`modernize-use-using` can drop `const` from aliases such as `const_iterator`; +`modernize-use-integer-sign-comparison` can turn +`x != static_cast(-1)` into an always-true comparison; +`readability-simplify-boolean-expr` rewrites tests that directly exercise +comparison operators; and `modernize-loop-convert` names every loop variable +`i`. + +### Excluded checks + +Excluded because Gecode deliberately relies on the pattern: + +| Check(s) | Reason | +|---|---| +| `bugprone-derived-method-shadowing-base-method` | Static polymorphism | +| `bugprone-multi-level-implicit-pointer-conversion` | Allocator templates | +| `bugprone-signed-char-misuse` | `signed char` used as a small integer | +| `bugprone-throwing-static-initialization` | Static test registration | +| `concurrency-mt-unsafe` | `exit` and `getenv` run before threads start | +| `misc-confusable-identifiers` | Template parameter `I` next to `l` | +| `misc-multiple-inheritance`, `misc-no-recursion`, `misc-non-private-member-variables-in-classes` | Intended across kernel and propagators | +| `misc-new-delete-overloads` | Delete-only overloads are intended | +| `misc-use-anonymous-namespace` | File-local `static` is allowed | +| `modernize-avoid-c-arrays` | Fixed tables and space-allocated arrays | +| `modernize-use-std-numbers` | Spec-defined constants (e.g., TSPLIB pi) | +| `performance-enum-size` | Changing underlying sizes alters ABI and layouts | +| `performance-no-int-to-ptr` | Pointer tagging | +| `portability-template-virtual-member-function` | Reports uninstantiated virtuals that MSVC compiles | +| `readability-convert-member-functions-to-static`, `readability-make-member-function-const` | Views share an interface that mutates only in some views | +| `readability-implicit-bool-conversion` | `if (p)` is the local idiom | + +Excluded because the reports are mostly noise or worsen readability: + +| Check(s) | Reason | +|---|---| +| `bugprone-branch-clone` | Parallel cases read better | +| `bugprone-easily-swappable-parameters` | Flags nearly every constraint posting function | +| `bugprone-implicit-widening-of-multiplication-result` | Values are `int`-sized by design | +| `bugprone-inc-dec-in-conditions` | Flags sequenced `&&` conditions | +| `bugprone-macro-parentheses` | Macro arguments are names or types | +| `bugprone-narrowing-conversions` | Silencing casts would not verify bounds | +| `bugprone-switch-missing-default-case` | Option values and tests | +| `bugprone-unchecked-string-to-number-conversion` | Changing command-line parsing alters behavior | +| `misc-const-correctness` | `const` on shallow handles is misleading | +| `misc-header-include-cycle`, `misc-include-cleaner` | Umbrella headers and non-self-contained `.hpp` files | +| `misc-static-assert` | Only flags `GECODE_NEVER` (`assert(false)`) | +| `modernize-pass-by-value` | Most parameters are handles/views or cold setup strings | +| `modernize-return-braced-init-list`, `modernize-use-auto`, `modernize-use-designated-initializers`, `modernize-use-trailing-return-type` | Explicit types and forms are clearer at declarations | +| `modernize-use-default-member-init` | Keeps actor state together and avoids extra stores in clone constructors | +| `modernize-use-nodiscard` | Applies to nearly every accessor | +| `readability-avoid-nested-conditional-operator`, `readability-use-anyofallof` | Existing forms are clearer | +| `readability-braces-around-statements`, `readability-identifier-length`, `readability-isolate-declaration`, `readability-magic-numbers`, `readability-math-missing-parentheses`, `readability-named-parameter` | Contradict Gecode style | +| `readability-function-cognitive-complexity`, `readability-function-size` | Propagators are long by nature | +| `readability-redundant-declaration` | Documented repeats; fix-it breaks templates | + +Excluded analyzer checks: + +| Check | Reason | +|---|---| +| `clang-analyzer-cplusplus.NewDeleteLeaks` | Tests register self-owning objects with `(void)new` | +| `clang-analyzer-optin.core.EnumCastOutOfRange` | Flag combinations | +| `clang-analyzer-optin.cplusplus.UninitializedObject` | `Delta` and similar types leave fields unset deliberately | +| `clang-analyzer-optin.performance.Padding` | One small static table ordered by columns | +| `clang-analyzer-security.ArrayBound` | Cannot track loop invariants or trailing arrays | +| `clang-analyzer-unix.Malloc` | Cannot track reference counts | + +`cppcoreguidelines-prefer-member-initializer` is left off because it moves +statements across side effects (such as `e >> n` before allocating `n` +elements) and into `#ifdef`-guarded initializer lists. The remaining checks in +`cppcoreguidelines`, `cert`, `google`, and `hicpp` duplicate enabled checks or +forbid raw memory and pointer arithmetic that the kernel relies on; groups such +as `abseil`, `boost`, `llvm`, and `objc` target other projects or platforms. diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 8053b8cc5a..59f8e6c6b3 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -1,8 +1,110 @@ # Gecode 7 migration notes -## Meta-search hooks: hub() and spoke() take contexts +Gecode 7 is a major release with source- and build-level breaking changes. This +guide summarizes how to adapt Gecode 6 code; see `changelog.in` for the full +list of changes. + +## Build and toolchain requirements + +- **C++23**: Gecode and code including its headers require C++23 with explicit + object parameters (deducing `this`): GCC 14, Clang 18, AppleClang 17, or + MSVC 19.32 (Visual Studio 2022 17.2) or newer. +- **CMake only**: Autoconf and Makefile builds are removed. See the + [CMake build reference](cmake-build.md). +- **Qt 6**: Qt 5 support is removed; Gist and Qt-backed FlatZinc features + require Qt 6. +- **Linking and `config.hpp`**: MSVC auto-linking + (`gecode/support/auto-link.hpp`) and the Autoconf `PACKAGE_*` and + `GECODE_HAS_BUILTIN_*` macros are removed. Link through `Gecode::*` CMake + targets and check `Gecode_VERSION` or `GECODE_VERSION`. +- **32-bit x86 floats**: x87 arithmetic is no longer supported; 32-bit x86 GCC + builds need `-msse2 -mfpmath=sse`. + +## Naming and enum constants + +Functions, variables, and member functions use `snake_case`, and abbreviated +enum constants use descriptive names. Strict-less relation constants use `_LT`, +while less-or-equal keeps `_LQ`. None of the old spellings have compatibility +aliases. + +| Gecode 6 | Gecode 7 | +|---|---| +| `IRT_LE`, `FRT_LE`, `SRT_LE` | `IRT_LT`, `FRT_LT`, `SRT_LT` | +| `RM_NONE`, `RM_CONSTANT`, `RM_LINEAR`, `RM_LUBY`, `RM_GEOMETRIC` | `RESTART_NONE`, `RESTART_CONSTANT`, `RESTART_LINEAR`, `RESTART_LUBY`, `RESTART_GEOMETRIC` | +| `RM_PMI` | `RM_RIMP` | +| `TT_FIXP`, `TT_FIXS`, `TT_FIXE` | `TT_FIXED_PROCESSING`, `TT_FIXED_START`, `TT_FIXED_END` | +| `SRT_DISJ`, `SRT_CMPL` | `SRT_DISJOINT`, `SRT_COMPLEMENT` | +| `SOT_DUNION`, `SOT_INTER` | `SOT_DISJOINT_UNION`, `SOT_INTERSECTION` | +| `SM_STAT` | `SM_STATISTICS` | +| `SearchTracer::AOE` | `SearchTracer::OTHER` | +| `CPLT_ASSIGNMENT` (test) | `COMPLETE_ASSIGNMENT` | +| `MT_ANY`, `MT_NOT`, `MT_FIRST` (test) | `MATCH_ANY`, `MATCH_NOT`, `MATCH_FIRST` | +| `nooverlap`, `binpacking`, `modeventdelta` | `no_overlap`, `bin_packing`, `modevent_delta` | +| `dfsengine`, `clearall`, `arg2intvarargs` | `make_dfs_engine`, `clear_all`, `to_int_var_args` | + +## Scoped enums + +Existing public enums are now `enum class`, with `using enum` at their scope so +unqualified spellings such as `IRT_EQ`, `SS_FAILED`, and `IntVarBranch::SEL_RND` +still compile. Their values no longer convert implicitly to `int` or `bool`, or +mix with other enums; convert explicitly with `std::to_underlying` or +`static_cast`. + +`IntPropLevel` is an `enum class` with underlying type `unsigned int` and +defines `|`, `&`, and `|=`. Test bits explicitly with +`(ipl & IPL_BASIC) != IPL_DEF`. `IPL_BITS_` is removed. For command-line +options choosing an enum value, use `Driver::EnumOption` instead of casting +to `int`. + +## Optimization, cloning, and downcasts + +Best-solution search now ranks solutions with `Space::compare()` while +`constrain()` continues to prune search. The standard optimization base classes +(`IntMinimizeSpace`, `FloatMaximizeSpace`, and so on) implement `compare()`. +Models with a custom `constrain()` must also override `compare()`, returning +`SpaceComparison` (`Better`, `Equivalent`, `Worse`, or `Incomparable`). The +helpers `compare_int()`, `compare_float()`, and `compare_lex()` cover standard +objectives with `Sense::Minimize` or `Sense::Maximize`: -The hooks `master()` and `slave()` and the class `MetaInfo` are replaced: +```cpp +void constrain(const Space& best) override { + const auto& b = down_cast(best); + rel(*this, cost, IRT_LT, b.cost.val()); +} + +SpaceComparison compare(const Space& other) const override { + const auto& o = down_cast(other); + return compare_int(cost.val(), o.cost.val(), Sense::Minimize); +} +``` + +`down_cast` checks the type with `dynamic_cast` when assertions are enabled +and compiles to `static_cast` otherwise; use it where the dynamic type is +known, such as in `constrain()`, `compare()`, `Brancher::commit()`, and +`Propagator::advise()`. + +`Space::clone()` now returns the static type of the space it is called on, so +cloning a `Model` returns `Model*` without a cast (cloning through a `Space*` +still returns `Space*`). Because `clone()` is a template with an explicit object +parameter, pointers to member to it no longer work. + +## Random number generation (`Rnd`) + +`Rnd` is now a splittable value type (SplitMix by default, or any engine via +`RndGenerator`) with complete state save/restore: + +- The seed constructor is `explicit`: write `INT_VAL_RND(Rnd(42))` instead of + `INT_VAL_RND(42)`, and `opt.rnd()` instead of `Rnd(opt.seed())`. +- Use `state()` and `state(text)` instead of `seed()`. +- Copying an `Rnd` no longer advances the original. Pass a distinct split to + each consumer (for example `relax(*this, x, sx, rnd.split(sc), p)` in + `spoke()`). +- Seeded sequences differ from Gecode 6. + +## Meta-search hooks: `hub()` and `spoke()` + +`master()`, `slave()`, and `MetaInfo` are replaced with no compatibility +aliases (including `FlatZincSpace::slave()`): ```cpp // Gecode 6 @@ -14,176 +116,108 @@ void hub(Gecode::HubContext& hc) override; void spoke(Gecode::SpokeContext& sc) override; ``` -There are no compatibility aliases. `MetaInfo` no longer exists, so an old -override fails to compile. Restart-based search (RBS) calls `hub()` on its -hub and `spoke()` on each spoke, a clone of the hub that one episode -searches. Portfolio-based search (PBS) calls `hub()` once and `spoke()` on -the spoke of each asset. - -Both contexts provide what `MetaInfo` provided: - -| Gecode 6 | Gecode 7 | -|----------------------------------------|----------------------------------------------------| -| `mi.type()`: `RESTART`, `PORTFOLIO` | `engine()`: `MetaEngine::Restart`, `Portfolio` | -| `mi.reason()`: `RR_INIT` | `event()`: `MetaEvent::Start` | -| `RR_SOL` | `MetaEvent::Solution` | -| `RR_LIM` | `MetaEvent::Limit` | -| `RR_CMPL` | `MetaEvent::Exhausted` | -| (none) | `MetaEvent::Incomplete`, such as LDS at its limit | -| `RR_NO` (portfolio) | `MetaEvent::Start` | -| `mi.restart()` | `episode()` | -| `mi.fail()` | `statistics().fail` | -| `mi.solution()` | none: `event()` tells whether there was a solution | -| `mi.last()` | `last()` | -| `mi.nogoods()` | `nogoods()` | -| `mi.asset()` | `asset()`, and `assets()` for their number | - -`episode()` counts from zero and increases by one for every new spoke, -whatever ended the previous episode. In `hub()` it is the episode that -ended, in `spoke()` the episode that starts. `statistics()` holds the -statistics of the episode that ended. `last()` is only valid while the hook -runs; clone the solution to keep it. - -The return values become explicit decisions: - -| Gecode 6 | Gecode 7 | -|----------------------------------------|--------------------------------------------------------| -| `master()` returns `true` | `hc.decision(MetaDecision::Restart)`, the default | -| `master()` returns `false` after a solution | `hc.decision(MetaDecision::Continue)` | -| (none) | `hc.decision(MetaDecision::Continue)` after a limit | -| (none) | `hc.decision(MetaDecision::Finish)` | -| `slave()` returns `true` | nothing, `SpokeCoverage::Full` is the default | -| `slave()` returns `false` | `sc.coverage(SpokeCoverage::Partial)` | -| (none) | `sc.coverage(SpokeCoverage::Reduced)` | - -`Continue` is only legal after `MetaEvent::Solution` and `MetaEvent::Limit`; -setting it for another event throws `IllegalMetaDecision`. `Finish` ends the -engine with `EndReason::Incomplete`. To prove that no further solution -exists, fail the hub. - -The coverage tells the engine what a spoke covers of the hub's search space: - -- `Full`: the spoke adds only branching and constraints that the hub - implies. Exhausting it is a proof, and its no-goods hold in the hub. -- `Reduced`: the spoke prunes solutions but keeps one, or an optimal one, if - any exists, such as symmetry breaking. Exhausting it is a proof, but its - no-goods do not hold in the hub. Search for all solutions misses the - solutions that the spoke prunes. -- `Partial`: the spoke searches part of the hub's search space, such as a - large neighbourhood. Exhausting it is no proof, and its no-goods do not - hold in the hub. - -The engine trusts the declared coverage. A spoke that declares more than it -covers, such as `Full` for a spoke that removes solutions, gives undefined -results. - -`nogoods()` is empty unless the spoke of the episode that ended was `Full`. -PBS honours the coverage of each asset: an asset whose `Partial` spoke -exhausts is dropped instead of ending the portfolio. - -Other changes to the hooks: - -- RBS calls `hub()` with `MetaEvent::Start` before it clones the first - spoke. Gecode 6 did not call `master()` then. -- For a best solution engine such as `RBS`, the engine constrains - the hub with the last solution before it calls `hub()`. The default - `hub()` no longer calls `constrain()`, and an override that does not call - the default keeps the bound. For other engines, such as `RBS`, - RBS no longer calls `constrain()` at all. -- After an episode that ends without a proof, such as LDS at its - discrepancy limit, RBS calls `hub()` with `MetaEvent::Incomplete`. By - default, it finishes when the spoke was `Full` or `Reduced`, as a new - spoke would repeat the same search, and restarts when it was `Partial`. - Both `Restart` and `Finish` are legal. -- PBS calls `status()` on the hub after `hub()`, so `hub()` can post - constraints. In Gecode 6, cloning such a hub threw `SpaceNotStable`. -- The default PBS `hub()` still removes all branchers, so `spoke()` must post - the branching of each asset. When the hub had branchers but a spoke has - none after `spoke()`, PBS throws `Search::SpokeNoBrancher` instead of - returning the unassigned spoke as a solution. - -The examples show typical overrides: - -- `examples/crossword.cpp`: a `hub()` that posts no-goods and continues - after a solution instead of restarting. -- `examples/photo.cpp`: an RBS `spoke()` that relaxes the last solution for - large neighbourhood search and declares `SpokeCoverage::Partial`. -- `examples/qcp.cpp`: a PBS `spoke()` that posts a different branching for - each asset. - -## Cutoff generators implement copy() - -`Search::Cutoff` has a new pure virtual member function: - -```cpp -virtual Gecode::Search::Cutoff* copy(void) const; -``` - -It returns a copy of the generator in its current state that continues the -sequence on its own. A copy of `Cutoff::rnd()` uses a different seed, so -the assets can restart at different times (unless every value of the range -is the same). A portfolio of restart-based engines, `PBS`, gives -each asset its own copy of the cutoff in its options and deletes the -original once the portfolio is built. A portfolio of a single asset whose -spoke does not declare `SpokeCoverage::Partial` needs no portfolio engine -and passes the cutoff itself to that asset. -In Gecode 6.6, the assets drew their values from one shared cutoff sequence. - -A custom cutoff generator must implement `copy()`. For a generator whose -state is plain data, the copy constructor suffices: +RBS calls `hub()` on its hub and `spoke()` on each spoke (a clone searched for +one episode); PBS calls `hub()` once and `spoke()` on each asset's spoke. + +Context accessors: + +| Gecode 6 (`MetaInfo`) | Gecode 7 (`HubContext` / `SpokeContext`) | +|---|---| +| `mi.type()`: `RESTART`, `PORTFOLIO` | `engine()`: `MetaEngine::Restart`, `Portfolio` | +| `mi.reason()`: `RR_INIT` / `RR_NO` | `event()`: `MetaEvent::Start` | +| `RR_SOL`, `RR_LIM`, `RR_CMPL` | `MetaEvent::Solution`, `Limit`, `Exhausted` | +| (none) | `MetaEvent::Incomplete` (e.g., LDS at its limit) | +| `mi.restart()`, `mi.fail()` | `episode()`, `statistics().fail` | +| `mi.solution()` | check `event()` | +| `mi.last()`, `mi.nogoods()` | `last()`, `nogoods()` | +| `mi.asset()` | `asset()`, and `assets()` for the count | + +`episode()` starts at zero and increments for every new spoke; it names the +ended episode in `hub()` and the starting episode in `spoke()`. `last()` is +valid only while the hook runs; clone it to keep it. + +Decisions and spoke coverage replace the Boolean return values: + +| Gecode 6 | Gecode 7 | +|---|---| +| `master()` returns `true` | `hc.decision(MetaDecision::Restart)` (default) | +| `master()` returns `false` | `hc.decision(MetaDecision::Continue)` (legal after `Solution` or `Limit`) | +| (none) | `hc.decision(MetaDecision::Finish)` (ends with `EndReason::Incomplete`) | +| `slave()` returns `true` | `SpokeCoverage::Full` (default) | +| `slave()` returns `false` | `sc.coverage(SpokeCoverage::Partial)` | +| (none) | `sc.coverage(SpokeCoverage::Reduced)` | + +Setting `Continue` on another event throws `IllegalMetaDecision`. To prove no +further solution exists, fail the hub instead of choosing `Finish`. + +Coverage tells the engine what a spoke covers of the hub's search space (the +engine trusts the declaration): + +- `Full`: only branching and hub-implied constraints. Exhausting it is a proof, + and its no-goods hold in the hub. +- `Reduced`: prunes solutions while keeping at least one (or one optimal) + solution, such as symmetry breaking. Exhausting it is a proof, but its + no-goods do not hold in the hub. +- `Partial`: searches a subset of the hub's space, such as LNS. Exhausting it + is not a proof, and its no-goods do not hold in the hub. + +`nogoods()` is empty unless the ended spoke was `Full`, and PBS drops an +exhausted `Partial` asset instead of ending the portfolio. Other behavioral +changes: + +- RBS calls `hub()` with `MetaEvent::Start` before cloning the first spoke, and + with `MetaEvent::Incomplete` after an incomplete episode (defaulting to + `Finish` for `Full`/`Reduced` and `Restart` for `Partial`). +- For best-solution engines (`RBS`), RBS constrains the hub before + calling `hub()`, so overrides that skip the default `hub()` keep the bound; + `RBS` no longer calls `constrain()`. +- PBS propagates the hub (`status()`) after `hub()`, so `hub()` may post + constraints. If the hub had branchers and a spoke has none after `spoke()`, + PBS throws `Search::SpokeNoBrancher` instead of returning an unassigned + solution. + +See `examples/crossword.cpp` (posting no-goods and continuing), +`examples/photo.cpp` (LNS with `SpokeCoverage::Partial`), and +`examples/qcp.cpp` (per-asset PBS branching). + +## `Cutoff::copy()` + +`Search::Cutoff` adds a pure virtual `copy()` member function so each asset in +a `PBS` portfolio gets its own cutoff sequence (with distinct seeds for +`Cutoff::rnd()`): ```cpp Gecode::Search::Cutoff* -MyCutoff::copy(void) const { - return new MyCutoff(*this); +MyCutoff::copy() const { + return new MyCutoff(*this); } ``` -A generator that owns other generators copies them with their own -`copy()`. +Cutoffs owning child generators copy them with `copy()`. -## stopped() is replaced by end_reason() +## `end_reason()` replaces `stopped()` -`Search::Engine::stopped()` and `Search::Base::stopped()` are removed, -and so is the experimental `limited()`. After `next()` returns no solution, -`end_reason()` tells why: +`Search::Engine::stopped()`, `Search::Base::stopped()`, and the experimental +`limited()` are removed. After `next()` returns `nullptr`, inspect +`end_reason()` (`Gecode::Search::EndReason`): -```cpp -enum class Gecode::Search::EndReason : unsigned char { - NotEnded, Exhausted, Incomplete, Limit -}; -``` +| Gecode 6 | Gecode 7 | +|---|---| +| `stopped()` is `true` | `end_reason() == EndReason::Limit` | +| `stopped()` is `false` after no solution | `EndReason::Exhausted` or `EndReason::Incomplete` | +| `limited()` is `true` (`AStar`, `CABS`) | `EndReason::Incomplete` | +| last `next()` returned a solution | `EndReason::NotEnded` | + +Use `EndReason::Exhausted` when a proof of unsatisfiability or optimality is +required; `EndReason::Incomplete` ends without a proof (for example LDS at its +discrepancy limit) and cannot be resumed. To resume after `EndReason::Limit`, +reset or raise the stop object before calling `next()` again. -| Gecode 6 | Gecode 7 | -|-----------------------------------------------|-------------------------------------------------| -| `stopped()` is true | `end_reason() == EndReason::Limit` | -| `stopped()` is false after no solution | `end_reason() == EndReason::Exhausted` or `EndReason::Incomplete` | -| `limited()` is true (AStar, CABS) | `end_reason() == EndReason::Incomplete` | -| last `next()` returned a solution | `end_reason() == EndReason::NotEnded` | - -`Exhausted` means that the engine explored everything it was asked to -explore: there is no further solution, and the last solution of a -branch-and-bound search is optimal. `Incomplete` means that the engine ended -on its own without that proof, for example limited discrepancy search at its -discrepancy limit or CABS at its width limit. Calling `next()` again does not -continue an incomplete search. `Limit` means that a stop object stopped the -engine, and calling `next()` again continues the search. - -Code that used `!stopped()` as a proof, such as reporting optimality, should -test for `EndReason::Exhausted`. Code that resumes a search after a limit -should test for `EndReason::Limit`, and first lift the limit: a stop object -that still fires, such as an expired `TimeStop`, stops the search again -right away. Reset the `TimeStop` or raise the limit of a `NodeStop` or -`FailStop` before calling `next()` again. - -## Portfolio stop objects see the whole portfolio - -The stop object in the options of `PBS` is now checked with the statistics -of the whole portfolio, the sum over all assets. In Gecode 6, it was checked -for each asset with the statistics of that asset, so a failure limit of -`n` for a portfolio of `k` assets allowed up to `k * n` failures. A stop -object that should limit each asset on its own belongs in the options of an -engine builder: +## Portfolio stop objects + +`PBS` now checks its own stop object against the combined statistics of the +whole portfolio rather than per asset. Put per-asset limits in the options of +each engine builder: ```cpp Gecode::Search::Options a, b; @@ -192,3 +226,24 @@ b.stop = &lds_stop; Gecode::SEBs sebs({Gecode::dfs(a), Gecode::lds(b)}); Gecode::PBS engine(model, sebs, portfolio_options); ``` + +## Other API and module changes + +- **Parameter passing**: owned and reference-counted types (`IntSet`, `DFA`, + `Rnd`, `Action`, `CHB`, `*Args`, etc.) and `FloatVal` are passed by `const&`, + or by value and moved (so non-movable types no longer compile there). + Propagators overriding `solution_distribution` or `domain_size_sum` must take + their `SendMarginal` or `InDecision` parameter by `const&`. +- **Special members and operators**: copy assignment of `Home` and `Space` is + deleted. Because range and value iterators (`IntSetRanges`, `IntVarValues`, + etc.) now use defaulted constructors, `const IntSetRanges r;` no longer + compiles without an initializer. Redundant `operator!=` definitions are + removed; write `a != b` rather than `operator!=(a, b)`. +- **Heap contract**: `Heap` allocation and reallocation require positive sizes; + use `rfree()` instead of `rrealloc(..., 0)`. +- **Float**: Gecode's native `Float::Interval` replaces the bundled Boost + interval library. `Float::RoundingBase` and `Float::Rounding` drop the Boost + rounding API (`RoundingControl`, `unprotected_rounding`, `get_rounding_mode`, + etc.), and `FloatVal::FloatValImpType` is now `Float::Interval`. +- **FlatZinc**: `FlatZinc::Error` and `FlatZinc::AST::TypeError` derive from + `std::exception`; `AST::TypeError::what()` returns `const char*`. diff --git a/gecode/float.hh b/gecode/float.hh index b2f94c1db3..c5072fa4d5 100644 --- a/gecode/float.hh +++ b/gecode/float.hh @@ -144,49 +144,27 @@ namespace Gecode { namespace Gecode::Float { /** - * \brief Floating point rounding operations without state saving + * \brief Floating-point rounding operations without state saving * - * Every lower bound is rounded toward \f$-\infty\f$ and every upper bound - * toward \f$+\infty\f$, also when the compiler optimizes and when the - * operands are compile-time constants. + * Rounds lower bounds toward \f$-\infty\f$ and upper bounds toward + * \f$+\infty\f$ without requiring `-frounding-math`, `/fp:strict`, or + * `#pragma STDC FENV_ACCESS`. Operands and results pass through barrier() + * (an empty volatile `asm` register constraint on GCC/Clang, or a volatile + * round-trip on other compilers) to prevent constant folding, result + * sharing across directions, and reordering across mode changes. Assumes + * IEEE binary64 arithmetic in SSE2 or AArch64 registers; x87 arithmetic + * and `-ffast-math` are unsupported. * - * Neither Gecode nor applications need floating-point compiler flags or - * pragmas for this: no `-frounding-math`, `-ffp-model=strict`, - * `/fp:strict`, or `#pragma STDC FENV_ACCESS`. Compilers assume - * round-to-nearest without them, so each operand and each result of the - * arithmetic operations passes through barrier(). With GCC and Clang the - * barrier is an empty `__asm__ __volatile__` statement with the value as a - * floating-point register operand (`"+w"` on AArch64, `"+x"` on x86-64). - * Other compilers, including MSVC, use a volatile store and reload. The - * barrier hides the value from the optimizer, so constants are not - * folded, one result is not shared between the two directions, a negation - * is not fused into the operation, and no operation moves across a - * rounding-mode change. This relies on GCC and Clang keeping volatile - * `asm` statements, and every compiler keeping volatile accesses, in - * order with the opaque calls that change the mode (`fesetround` or - * `_control87`). IEEE binary64 arithmetic in SSE2 or AArch64 registers is - * assumed; x87 arithmetic and `-ffast-math` are not supported. - * - * The rounding mode is read and set with `std::fegetround` and - * `std::fesetround`. Under GECODE_FLOAT_MODE_CONTROL87 (cl.exe on x86 and - * x64) it is read and set with `_control87`, which also masks all - * floating-point exceptions while Gecode sets a mode and, on x86, selects - * 64-bit precision and affine infinity; restoring a mode writes back the - * caller's bits. Without GECODE_FLOAT_DIRECTED_PER_OPERATION, the mode - * stays upward between operations. An upper bound is computed directly, - * and a lower bound as the negated upper bound of the negated operation; - * sqrt_down() and median() switch the mode and switch back to upward. - * With it (MSVC on x64, or on x86 with SSE), each operation sets its own - * direction. int_down() and int_up() use `std::floor` and `std::ceil`, - * which do not depend on the mode. - * - * A RoundingBase sets no mode on construction. Without - * GECODE_FLOAT_DIRECTED_PER_OPERATION, its operations need the upward - * mode, so use a Rounding, which sets that mode and restores the - * caller's mode on destruction. - * - * The test Float::Arithmetic::DirectedRounding checks the bounds with - * literal and runtime operands under every caller mode. + * Uses `std::fegetround`/`std::fesetround`, or `_control87` under + * GECODE_FLOAT_MODE_CONTROL87 (MSVC on x86/x64, masking FP exceptions and + * selecting 64-bit precision on x86 while active). Without + * GECODE_FLOAT_DIRECTED_PER_OPERATION, operations assume upward rounding + * between calls (computing lower bounds via negation, except sqrt_down() + * and median() which switch temporarily); with it, each operation sets + * its own direction. int_down() and int_up() use `std::floor` and + * `std::ceil`. RoundingBase never changes the mode on construction; use + * Rounding to save the caller's mode, enter upward mode when required, + * and restore the saved mode on destruction. * * \ingroup TaskModelFloatVars */ diff --git a/gecode/float/interval.hpp b/gecode/float/interval.hpp index f611a8e8df..b742d91fb6 100644 --- a/gecode/float/interval.hpp +++ b/gecode/float/interval.hpp @@ -38,51 +38,26 @@ namespace Gecode::Float { /** - * \brief Closed interval of floating-point numbers with directed rounding + * \brief Closed floating-point interval with directed rounding * - * An interval \f$[l,u]\f$ stands for every real number between its - * bounds. Arithmetic rounds each lower bound toward \f$-\infty\f$ and each - * upper bound toward \f$+\infty\f$, so a result contains the exact result - * of the operation for all members of its operands. + * Represents \f$[l,u]\f$ with \f$l\leq u\f$. Arithmetic rounds lower bounds + * toward \f$-\infty\f$ and upper bounds toward \f$+\infty\f$, so each + * result encloses the exact image of its operands. Trivially copyable. * - * Contract: - * - An interval is never empty. Interval(l,u) and assign() throw - * std::runtime_error unless \f$l\leq u\f$, which also rejects NaN - * bounds. An operation whose exact result is empty throws the same - * exception: division by \f$[0,0]\f$ or by 0, pow() of \f$[0,0]\f$ - * with an exponent of at most 0, sqrt() of an interval without a - * nonnegative member, log() of one without a positive member, an even - * nth_root() of a negative interval, a disjoint intersect(), and - * asin(), acos(), acosh(), and atanh() outside their domains. - * - Interval(v) and unchecked() check nothing. Results keep NaN bounds, - * for example from \f$0\cdot\infty\f$ or \f$\infty-\infty\f$. - * - Each operation that rounds opens one Rounding for its whole - * computation, so the caller's rounding mode is restored afterwards, - * also when the operation throws. - * - There are no comparison operators. FloatVal's relations hold only - * when they hold for all members of both operands, such as - * certainly_less(), while its equality compares bounds, as equal() - * does. Named functions keep the two meanings apart. + * Intervals are never empty: Interval(l,u) and assign() throw + * std::runtime_error unless \f$l\leq u\f$ (rejecting NaN bounds). + * Operations whose exact result is empty throw the same exception: + * division by \f$[0,0]\f$ or 0, pow() of \f$[0,0]\f$ with nonpositive + * exponent, sqrt() without a nonnegative member, log() without a positive + * member, even nth_root() of a negative interval, disjoint intersect(), + * and asin(), acos(), acosh(), and atanh() outside their domains. + * Interval(v) and unchecked() perform no checks and preserve NaN bounds + * (e.g. from \f$0\cdot\infty\f$ or \f$\infty-\infty\f$). * - * \par Design decision - * Gecode implements the interval arithmetic it needs itself, for double - * bounds, with no external dependency. Directed rounding switches the - * floating-point rounding mode through RoundingBase and Rounding. The - * measured alternatives were a script-refreshed copy of Boost 1.92.0's - * interval library, the 2012 copy of Boost 1.47.0 made reproducible, and - * outward rounding with std::nextafter, either always widening or - * widening only by the sign of an error term. The nextafter variants - * loosen bounds, which was not accepted, and an installed Boost was ruled - * out as a dependency. This implementation was chosen because it - * reproduces the Boost copy's bounds, truth values, and search statistics - * bit for bit on arm64 and x86-64. Without the copy, Gecode installs 95 - * fewer headers and no third-party code, exports the same symbols, and - * runs as fast or faster. The interval type is trivially copyable. - * - * \par Acknowledgement - * The operations reproduce the results of the Boost Interval Arithmetic - * Library (Boost.Interval), which Gecode has used since 2012 and which - * served as the reference during development. + * Rounding operations open a Rounding scope and restore the caller's + * rounding mode on return or exception. Named comparisons (such as + * certainly_less() and equal()) are used instead of operators to separate + * memberwise relations from bound equality. Results match Boost.Interval. * * \ingroup TaskModelFloatVars */ diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index ae93966056..002a7c0874 100644 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1718,16 +1718,13 @@ namespace Gecode { /** * \defgroup TaskModelScriptMeta Meta search hooks * - * A meta search engine keeps a \e hub space and searches clones of it, - * the \e spokes, with an inner engine. Restart-based search (RBS) runs - * one spoke after the other, each search of a spoke being an - * \e episode. Portfolio-based search (PBS) runs one spoke for each of - * its assets. + * A meta search engine keeps a \e hub space and searches clones of it + * (\e spokes) with an inner engine: RBS runs spokes sequentially in + * \e episodes; PBS runs one spoke per asset. * - * The engines call Space::hub() on the hub and Space::spoke() on each - * spoke. A HubContext or SpokeContext tells the hook why it is called, - * and the hook answers through it: hub() with a MetaDecision, spoke() - * with a SpokeCoverage. + * Engines call Space::hub() on the hub with a HubContext (answered via + * MetaDecision) and Space::spoke() on each spoke with a SpokeContext + * (answered via SpokeCoverage). * * \ingroup TaskModelScript */ @@ -1740,32 +1737,25 @@ namespace Gecode { }; /** - * \brief Why a meta search engine calls a hook + * \brief Event triggering a meta search hook * - * In Space::hub(), the event that ended the episode, or \c Start before - * the first one. In Space::spoke(), the event that ended the previous - * episode, or \c Start for the first episode and for the assets of a - * portfolio. + * In Space::hub(), the event that ended the episode (or \c Start before + * the first). In Space::spoke(), the event that ended the previous episode + * (or \c Start for the first episode and for portfolio assets). */ enum class MetaEvent : unsigned char { - Start, ///< Search starts: no episode has run yet - Solution, ///< The episode found a solution - /** - * The episode exhausted its spoke. This is a proof only for a spoke - * of SpokeCoverage::Full or SpokeCoverage::Reduced, and then the - * engine has already ended: a hook only sees this event after a - * spoke of SpokeCoverage::Partial. - */ + Start, ///< Search starts; no episode has run yet + Solution, ///< Episode found a solution + /// Episode exhausted a SpokeCoverage::Partial spoke (Full/Reduced end the engine directly) Exhausted, - Incomplete, ///< The inner engine ended without a proof (such as LDS) - Limit, ///< The episode reached the cutoff + Incomplete, ///< Inner engine ended without a proof (e.g. LDS) + Limit, ///< Episode reached the cutoff }; /** - * \brief What a meta search engine does after Space::hub() returns + * \brief Action a meta search engine takes after Space::hub() returns * - * The engine sets the default before it calls hub(). Which decisions are - * legal depends on the event: + * The engine sets a default before calling hub(). Legality by event: * * | Event | Restart | Continue | Finish | * |---------------|-----------|----------|-----------| @@ -1775,28 +1765,21 @@ namespace Gecode { * | \c Exhausted | default | illegal | legal | * | \c Incomplete | see below | illegal | see below | * - * After \c Incomplete, the default is \c Finish when the spoke of the - * episode has SpokeCoverage::Full or SpokeCoverage::Reduced, as a new - * spoke would repeat the same search, and \c Restart when it has - * SpokeCoverage::Partial. - * - * Setting an illegal decision throws IllegalMetaDecision. PBS calls - * hub() only with MetaEvent::Start. + * After \c Incomplete, the default is \c Finish for SpokeCoverage::Full or + * SpokeCoverage::Reduced, and \c Restart for SpokeCoverage::Partial. + * Setting an illegal decision throws IllegalMetaDecision. PBS calls hub() + * only with MetaEvent::Start. */ enum class MetaDecision : unsigned char { /// Search a new spoke (at \c Start: start search) Restart, /** - * Continue the current episode: after \c Solution, search the same - * spoke for the next solution; after \c Limit, resume the same spoke - * with the next cutoff as a fresh budget. - * - * The spoke is not rebuilt, so constraints that hub() posts reach only - * the spokes of later episodes, and exhausting the spoke proves that - * the hub had no further solution when the spoke was created. In best - * solution search the engine still constrains the spoke with each new - * solution. A hook that restricts the hub in a way that the current - * spoke must respect selects \c Restart instead. + * Continue the current spoke: after \c Solution, search for the next + * solution; after \c Limit, resume with the next cutoff as a fresh + * budget. Constraints posted in hub() affect only later spokes (though + * best-solution search still constrains the current spoke with each + * solution); select \c Restart if the current spoke must respect new + * hub constraints. */ Continue, /// End the engine: next() returns nullptr with EndReason::Incomplete @@ -1804,34 +1787,23 @@ namespace Gecode { }; /** - * \brief How much of the hub's search space a spoke covers - * - * Space::spoke() declares the coverage of its spoke. It decides whether - * exhausting the spoke proves that the hub has no further solution, and - * whether the no-goods recorded in the spoke hold in the hub. + * \brief Fraction of the hub's search space covered by a spoke * - * The engine trusts the declaration: a spoke that declares more coverage - * than it has, such as a spoke that removes solutions but declares - * \c Full, gives undefined results. + * Declared in Space::spoke(). Determines whether exhausting the spoke + * proves that the hub has no further solutions and whether spoke no-goods + * hold in the hub. Overstating coverage yields undefined results. */ enum class SpokeCoverage : unsigned char { - /** - * The spoke adds only branching and constraints that the hub - * implies: exhaustion is a proof, and its no-goods hold in the hub - */ + /// Adds only branching and implied constraints: exhaustion is a proof, no-goods hold in the hub Full, /** - * The spoke prunes solutions but keeps one, or an optimal one, if - * any exists, such as symmetry breaking or dominance: exhaustion is - * a proof, but its no-goods do not hold in the hub. Search for all - * solutions misses the solutions that the spoke prunes. + * Prunes solutions while preserving at least one (or an optimal one) + * if any exists, e.g. symmetry breaking or dominance: exhaustion is a + * proof, but no-goods do not hold in the hub and all-solutions search + * misses pruned solutions. */ Reduced, - /** - * The spoke explores part of the hub's search space, such as a large - * neighbourhood search fragment: exhaustion is no proof, and its - * no-goods do not hold in the hub - */ + /// Explores a subset of the hub (e.g. LNS): exhaustion is no proof and no-goods do not hold Partial, }; @@ -1875,12 +1847,10 @@ namespace Gecode { /// Return why the hook is called MetaEvent event() const; /** - * \brief Return the episode, counting from zero + * \brief Return the zero-based episode index (always 0 for PBS) * - * Each new spoke of RBS starts a new episode, whatever ended the - * previous one. In hub(), this is the episode that ended (zero for - * \c Start); in spoke(), the episode that starts. PBS always passes - * zero. + * Increments on each new RBS spoke: in hub(), the finished episode + * (0 for \c Start); in spoke(), the starting episode. */ unsigned long int episode() const; /// Return the asset of a portfolio, counting from zero (zero for RBS) @@ -1888,12 +1858,11 @@ namespace Gecode { /// Return the number of assets of a portfolio (one for RBS) unsigned int assets() const; /** - * \brief Return the best solution the engine knows, or nullptr if none + * \brief Return the best solution known to the engine, or nullptr * - * This is the most recent solution of the engine, or a better one that - * constrain() passed to the engine since, for example from another - * asset of a portfolio. The engine owns the solution, and the pointer is valid only while - * the hook runs: clone the solution to keep it. + * Either the engine's latest solution or a better one passed via + * constrain(). Owned by the engine and valid only during the hook; + * clone it to retain it. */ const Space* last() const; /** @@ -2428,17 +2397,15 @@ namespace Gecode { */ GECODE_KERNEL_EXPORT virtual void constrain(const Space& best); /** - * \brief Compare function for best solution search - * - * Must return whether this solution is better than, equivalent to, - * worse than, or incomparable with solution \a other, without modifying - * either. The result must agree with constrain: solutions admitted by - * constrain(b) are better than b, and a better b admits no more solutions. + * \brief Compare solutions for best-solution search * - * An override can convert \a other to its own class with down_cast. - * - * The default function throws SpaceNoComparison, so a space overriding - * constrain must also override compare. + * Returns whether this solution is better than, equivalent to, worse + * than, or incomparable with \a other without modifying either. Must + * agree with constrain(): solutions admitted by constrain(b) are + * better than b, and a better b admits no more solutions. An override + * can convert \a other to its own class with down_cast. Throws + * SpaceNoComparison by default, so any override of constrain() must + * also override compare(). * * \ingroup TaskModelScript */ @@ -2446,36 +2413,24 @@ namespace Gecode { /** * \brief Hub hook for meta search engines * - * Restart-based search (RBS) calls hub() on its hub when search - * starts and whenever an episode ends with a solution, at the - * cutoff, or without a proof (see MetaEvent). An episode that - * exhausts a spoke of SpokeCoverage::Full or SpokeCoverage::Reduced - * ends RBS with Search::EndReason::Exhausted instead. - * Portfolio-based search (PBS) calls hub() once, with - * MetaEvent::Start, before it creates the assets. - * - * The hook may post constraints in the hub and sets what the engine - * does next with \a hc.decision() (see MetaDecision for the legal - * decisions and the default). The constraints reach the current spoke - * only with MetaDecision::Restart, which searches a new spoke. If the hub fails, the engine ends - * with Search::EndReason::Exhausted whatever the decision: failing - * the hub is how a hook declares that no further solution exists. - * - * In best solution search, RBS constrains the hub with each new - * solution before it calls hub(), so an override cannot lose the - * bound by not calling the default. - * - * The default hook posts \a hc.nogoods() for RBS. For PBS, it - * removes all branchers, so spoke() must post the branching of each - * asset. - * - * No-goods refer to the branchers that created their choices. RBS - * keeps a brancher that hub() posts from taking the identity of a - * brancher that spoke() posted, so the no-goods of a spoke are never - * posted for the wrong brancher. This does not cover branchers that - * other branchers post while a spoke is searched: if there are such - * branchers and the spoke has SpokeCoverage::Full, hub() must not - * post branchers. + * RBS calls hub() on the hub at \c Start and after episodes ending + * with a solution, cutoff, partial exhaustion, or incomplete search + * (exhausting a \c Full or \c Reduced spoke ends RBS directly with + * Search::EndReason::Exhausted). PBS calls hub() once at \c Start + * before creating assets. + * + * May post constraints in the hub and choose the next action via + * \a hc.decision() (see MetaDecision); new constraints reach spokes + * only on MetaDecision::Restart. Failing the hub ends the engine with + * Search::EndReason::Exhausted regardless of decision. In best-solution + * search, RBS constrains the hub with each new solution before calling + * hub(). + * + * Default: posts \a hc.nogoods() for RBS; removes all branchers for + * PBS so spoke() defines each asset's branching. RBS reserves brancher + * ids used in spoke() so hub branchers do not collide with spoke + * no-goods, except for branchers posted dynamically during search (if + * present in a \c Full spoke, hub() must not post branchers). * * \ingroup TaskModelScript */ @@ -2484,24 +2439,16 @@ namespace Gecode { /** * \brief Spoke hook for meta search engines * - * RBS calls spoke() on each new spoke, a clone of the hub, before - * searching it: for the first episode with MetaEvent::Start, and - * for each later episode with the event that ended the previous - * one. PBS calls spoke() once on the spoke of each asset, the hub - * or a clone of it, with MetaEvent::Start and the asset number. - * - * The hook may post constraints and branching in the spoke and - * declares with \a sc.coverage() how much of the hub's search space - * the spoke covers (see SpokeCoverage, the default is Full). Large - * neighbourhood search, for example, fixes part of \a sc.last() and - * declares SpokeCoverage::Partial. The no-goods recorded while - * searching a spoke only hold in the hub for SpokeCoverage::Full, so - * RBS passes no no-goods to hub() for any other spoke. + * RBS calls spoke() on each newly cloned spoke before searching it + * (with MetaEvent::Start on the first episode and the preceding + * episode's event thereafter). PBS calls spoke() once per asset with + * MetaEvent::Start and the asset index. * - * PBS throws Search::SpokeNoBrancher if the hub had branchers before - * hub() and a spoke that has not failed has none after spoke(). - * - * The default hook does nothing. + * May post constraints and branchers and set \a sc.coverage() (default + * SpokeCoverage::Full; only \c Full spokes contribute no-goods to + * hub()). PBS throws Search::SpokeNoBrancher if the hub had branchers + * before hub() and a non-failed spoke has none after spoke(). Default + * does nothing. * * \ingroup TaskModelScript */ @@ -2723,18 +2670,15 @@ namespace Gecode { GECODE_KERNEL_EXPORT void print(const Choice& c, unsigned int a, std::ostream& o) const; /** - * \brief Give the random selectors of all branchers the stream of spoke \a c - * - * Meta search engines call this on every spoke after Space::spoke() - * returns, so spokes cloned from one hub do not repeat its random - * decisions, and branchers that spoke() posts are included. It splits - * by a separator that no alternative uses, one for RBS and another for - * PBS, and then by the high and low 32 bits of the episode (RBS) or - * the asset (PBS). Zero splits as well, so each level of nested engines - * adds its own splits and nested spokes (0,1) and (1,0) differ. The - * first spoke thus does not repeat a search without a meta engine. - * Generators that the model owns are not split here; split them with + * \brief Split all branchers' random selectors for spoke \a c + * + * Called by meta search engines after Space::spoke() so spokes cloned + * from one hub (and branchers posted in spoke()) draw independent + * streams. Splits by an engine-specific separator and the 64-bit + * episode (RBS) or asset (PBS), including index 0 so nested engines + * remain distinct. Model-owned generators are not split here; use * RndGenerator::split(const MetaContext&). + * * \ingroup TaskSearch */ GECODE_KERNEL_EXPORT diff --git a/gecode/kernel/data/rnd.hpp b/gecode/kernel/data/rnd.hpp index b081fb83f8..ad3f731195 100644 --- a/gecode/kernel/data/rnd.hpp +++ b/gecode/kernel/data/rnd.hpp @@ -37,37 +37,30 @@ namespace Gecode { /** - * \brief Small value-type random generator owned by its consumer + * \brief Value-type random number generator * - * Copying preserves complete state in independent storage, and split() - * derives a different stream: + * Copying preserves the full state in independent storage, and split() + * derives an independent stream: * \code * Rnd parent(42); * Rnd same = parent; * Rnd child = parent.split(1); * \endcode * - * Branching descriptions and selectors own their copies. A brancher keys - * each selector's copy by the brancher's id and the selector's role, so - * passing one generator to several selectors or branchers gives them - * independent streams. Selectors draw from a copy of their state and - * replace the state by its split for the alternative on commit. The state - * at a node is therefore determined by the posted state and the path, and - * cloning and recomputation reproduce it. Restart and portfolio engines - * split the selectors' state for each spoke; see Space::random_split(). - * Replay does not promise identical parallel scheduling, solution order, - * or search trees under weakly monotonic propagation. + * Branchers key each selector's copy by brancher id and selector role, + * draw from a copy of the state, and replace it by its split for the + * committed alternative on commit. The state at any node is therefore + * determined by the posted state and path, and reproduced by cloning and + * recomputation (excluding nondeterminism from parallel scheduling or + * weakly monotonic propagation). Meta engines split brancher selectors per + * spoke via Space::random_split(). * - * A generator that the model owns is copied with the space, so every - * spoke starts from the hub's state. A model drawing from it in - * Space::spoke(), for example to relax a solution, must split it with - * split(const MetaContext&), or every spoke draws the same numbers. A - * custom brancher using a model-owned generator must make its state a - * function of the path, for example by splitting it on commit. Space - * cloning does not copy mutable state in shared callback captures. + * Generators owned by a model are copied with the space; split them with + * split(const MetaContext&) in Space::spoke() so spokes draw independent + * streams, and make custom brancher state a function of the path. Rnd uses + * Support::SplitMix; any engine satisfying Support::Random can be used + * with RndGenerator. * - * Rnd uses the SplitMix engine. Any engine that meets the Support::Random - * contract, including splitting, can be used as RndGenerator. * \ingroup TaskModel */ template @@ -87,12 +80,10 @@ namespace Gecode { return RndGenerator(r.split(a)); } /** - * \brief Return a generator for the spoke of meta search context \a c + * \brief Return a generator split for the spoke of \a c * - * Splits as Space::random_split() splits the selectors of branchers. - * A model that draws from a generator it owns in Space::spoke(), for - * example to relax a solution, uses this so that every spoke draws - * differently. + * Matches Space::random_split() for brancher selectors; use this on + * model-owned generators in Space::spoke() so spokes draw differently. */ RndGenerator split(const MetaContext& c) const { diff --git a/gecode/search.hh b/gecode/search.hh index 32a4cd1175..19367f6cb1 100644 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -486,10 +486,9 @@ namespace Gecode::Search { /** * \brief Return a copy of this generator in its current state * - * The copy continues the sequence independently of this generator, - * except that a copy of a random generator draws its own sequence - * (see CutoffRandom::copy()). A portfolio of restart-based engines - * gives each asset its own copy. + * Continues the sequence independently (except CutoffRandom::copy(), + * which derives a new random sequence). Used by PBS to give each + * restart-based asset its own cutoff. */ virtual Cutoff* copy() const = 0; /// Destructor @@ -646,14 +645,11 @@ namespace Gecode::Search { /// Increment and return the next cutoff value unsigned long long int operator++() override; /** - * \brief Return a copy of this generator with its own random sequence + * \brief Return a copy with an independent random sequence * - * The copy draws its values, starting with its current one, from a - * seed that depends on the state of this generator and on how many - * copies of it have been made before. Copies made one after the - * other thus draw from different seeds, so that the assets of a - * portfolio usually restart at different times, and the same program - * creates the same sequences. + * Derives a deterministic seed from this generator's state and copy + * count so successive copies (e.g. portfolio assets) draw distinct + * sequences reproducibly. */ Cutoff* copy() const override; }; @@ -747,55 +743,44 @@ namespace Gecode::Search { /** * \brief External control for the requested number of search workers * - * A worker control is a copyable handle. Copies share the same request - * and can be used concurrently. An empty handle disables adjustment. - * DFS and BAB support worker control, as do experimental AStar and CABS. - * The resolved Options::threads value fixes the engine's worker capacity. - * Requests range from zero to that capacity; zero pauses search without - * discarding its state. This also applies to an engine with capacity one. - * Without thread support, use controls from one thread; attaching a zero - * request or calling request(0) raises InvalidWorkerRequest. + * Copyable handle sharing one concurrent worker request (an empty handle + * disables adjustment). Supported by DFS, BAB, and experimental AStar and + * CABS. Resolved Options::threads fixes the worker capacity (including 1); + * requests range from 0 (pause without discarding state) to capacity. + * Without thread support, use from one thread only; attaching or + * requesting 0 throws InvalidWorkerRequest. * - * For example, the caller can keep a handle for an external scheduler: * \code * Search::Options options; * options.threads = 8; * Search::WorkerControl control(2); * options.worker_control = control; - * DFS engine(root,options); + * DFS engine(root, options); * - * // Safe from another thread while engine.next() is running. + * // Safe from another thread while engine.next() is running: * control.request(6); * control.request(0); // Pause * control.request(1); // Resume * \endcode * - * Requests take effect cooperatively at scheduler boundaries. A decrease - * lets excess workers finish their current search action before parking. - * An increase wakes parked workers. Parked operating-system threads retain - * their stacks and search state, so capacity should cover the largest - * allocation the engine may receive. Adjustment preserves search correctness; - * parallel exploration order and search statistics remain nondeterministic. + * Changes take effect cooperatively at scheduler boundaries: excess + * workers park after finishing their current action (retaining their + * stacks and state, so capacity should cover the largest allocation), and + * increases wake parked workers. Search correctness is preserved; parallel + * exploration order and statistics remain nondeterministic. * - * A shared control identity can attach to one leaf engine only. Sharing it - * between engines, attaching it to an enclosing meta-engine, or reusing it - * after engine destruction raises WorkerControlInUse. Copies may outlive - * the engine; subsequent in-range requests are harmless. Engine destruction - * detaches its state but does not make the identity reusable. + * A control identity attaches to one leaf engine only; sharing it across + * engines, attaching it to a meta-engine, or reusing it after engine + * destruction throws WorkerControlInUse. Copies may outlive the engine + * with harmless in-range requests. * - * Restart-based search retains its DFS or BAB leaf control across restarts. - * For portfolio search, give each asset a distinct control through its - * engine builder. Controlled assets require a parallel outer PBS; sequential - * PBS rejects them with WorkerControlInUse before consuming roots or builders. - * PBS completes each next() round after every active asset reports. A paused - * asset observes the internal round stop and reports without resuming search; - * if all active assets are paused, next() waits until one resumes. - * - * The caller enforces any shared worker budget. Decrease one asset's request - * before increasing another's to keep the requested sum within that budget. - * Workers finishing their current actions can still cause temporary - * oversubscription. Gecode provides no acknowledgement that a decrease has - * taken effect and chooses no allocation policy. + * RBS retains its leaf control across restarts. In PBS, give each asset a + * distinct control via its engine builder in a parallel outer PBS + * (sequential PBS throws WorkerControlInUse); paused assets report on + * round stops without resuming, and next() waits if all active assets are + * paused. Any shared worker budget is enforced by the caller (decrease + * before increasing; transient oversubscription is possible, with no + * decrease acknowledgement or allocation policy). * * \ingroup TaskModelSearch */ @@ -1091,34 +1076,23 @@ namespace Gecode::Search { namespace Gecode::Search { /** - * \brief Why the last call to next() of a search engine returned no solution - * - * A search engine reports the reason with end_reason(). Only - * Exhausted is a proof: the space that the engine was given has no - * further solutions (no better ones for best solution search). Any - * other reason after next() returned nullptr means that the engine - * ended without such a proof. + * \brief Reason the last call to next() returned nullptr * - * A meta engine (restart-based or portfolio search) reports Limit - * for a stop object installed above it, not for its own cutoffs or - * slices. A portfolio also reports Limit when the stop objects of - * its assets have parked every asset that remains (see PBS), and - * calling next() again resumes them. + * Reported by end_reason(). Only Exhausted proves that no further (or + * better) solutions exist. Meta engines report Limit for an outer stop + * object (not internal cutoffs or slices), or in PBS when all remaining + * assets are parked by their own stop objects; calling next() resumes. * * \ingroup TaskModelSearch */ enum class EndReason : unsigned char { /// next() has not been called, or the last call returned a solution NotEnded, - /// The search space is exhausted, calling next() again finds nothing + /// Search space exhausted; subsequent next() calls return nullptr Exhausted, - /** - * Search finished without exhausting its search space, for example - * at the discrepancy limit of LDS or the width limit of CABS. There - * may be further solutions, but calling next() again finds none. - */ + /// Finished without proof (e.g. LDS discrepancy or CABS width limit); subsequent next() calls return nullptr Incomplete, - /// A stop object stopped search, calling next() again resumes it + /// Stopped by a stop object; calling next() again resumes search Limit, }; @@ -1514,24 +1488,13 @@ namespace Gecode { /** * \brief Meta-engine performing restart-based search * - * The engine uses the Cutoff sequence supplied in the options \a o to - * periodically restart the search of engine \a E. - * - * The class \a T can override the member functions - * \code virtual void hub(HubContext& hc) \endcode - * and - * \code virtual void spoke(SpokeContext& sc) \endcode - * - * The engine calls hub() on its hub when search starts and when an - * episode ends while search continues: after a solution, at the - * cutoff, and when the search of a spoke ends without a proof. When a - * spoke with SpokeCoverage::Full or SpokeCoverage::Reduced exhausts its - * search space, search ends without a call to hub(). The engine calls - * hub() for a solution in the next call to next(). The engine calls - * spoke() on each spoke it clones from the hub. When \a E is a best - * solution engine, the engine constrains the hub by each solution - * before it calls hub(). See Space::hub() and Space::spoke() for - * details. + * Periodically restarts engine \a E using the Cutoff sequence in \a o. + * Class \a T may override Space::hub(HubContext&) and + * Space::spoke(SpokeContext&); hub() is called at start and after episodes + * that do not exhaust a \c Full or \c Reduced spoke (for a solution, on + * the next call to next()), and spoke() is called on each cloned spoke. + * For best-solution engines, the hub is constrained by each solution + * before hub() runs. See Space::hub() and Space::spoke() for details. * * \ingroup TaskModelSearch */ @@ -1554,25 +1517,9 @@ namespace Gecode { /** * \brief Perform restart-based search * - * The engine uses the Cutoff sequence supplied in the options \a o to - * periodically restart the search of engine \a E. - * - * The class \a T can override the member functions - * \code virtual void hub(HubContext& hc) \endcode - * and - * \code virtual void spoke(SpokeContext& sc) \endcode - * - * The engine calls hub() on its hub when search starts and when an - * episode ends while search continues: after a solution, at the - * cutoff, and when the search of a spoke ends without a proof. When a - * spoke with SpokeCoverage::Full or SpokeCoverage::Reduced exhausts its - * search space, search ends without a call to hub(). The engine calls - * hub() for a solution in the next call to next(). The engine calls - * spoke() on each spoke it clones from the hub. When \a E is a best - * solution engine, the engine constrains the hub by each solution - * before it calls hub(). As rbs() calls next() only once, hub() is not - * called for the solution it returns. See Space::hub() and - * Space::spoke() for details. + * Runs RBS on \a s with options \a o and returns the first solution + * (or nullptr). Because next() is called once, Space::hub() is not called + * for the returned solution. See RBS, Space::hub(), and Space::spoke(). * * \ingroup TaskModelSearch */ @@ -1614,63 +1561,38 @@ namespace Gecode::Search::Meta { namespace Gecode { /** - * \brief Meta engine using a portfolio of search engines - * - * The engine will run a portfolio with a number of assets as defined - * by the options \a o. With more than one thread in \a o, every asset - * runs in its own thread, also when there are more assets than threads, - * and the threads are divided evenly among the assets, with at least - * one thread for each asset. With one thread, the assets take turns in - * slices of failures (see Search::Options::slice). - * - * The stop object in \a o is checked with the statistics of the whole - * portfolio, that is, the sum of the statistics of all assets. The - * asset that checks contributes the statistics it checks with, which - * for a parallel asset are those of one worker, as for any parallel - * engine. With one thread, every other asset is paused and contributes - * its current statistics, for a parallel asset those of all its - * workers. With more threads, every other asset contributes the - * statistics with which it last checked its stop object, or its final - * statistics once it has ended. When the stop object stops search, - * end_reason() returns Search::EndReason::Limit and calling next() - * again resumes all assets. + * \brief Meta-engine using a portfolio of search engines * - * For best-solution assets, a solution replaces the incumbent only if - * Space::compare reports SpaceComparison::Better. - * An external worker control in \a o is supported only for a single - * homogeneous asset. Multiple controlled assets require explicit engine - * builders, each with its own control and immutable worker capacity. - * PBS does not allocate workers or adjust those controls. + * Runs a portfolio of assets configured by \a o. With multiple threads, + * every asset runs in its own thread (even when assets exceed threads), + * dividing threads evenly with at least one per asset. With one thread, + * assets interleave in failure slices (Search::Options::slice). * - * When the assets are restart-based engines, the portfolio takes - * ownership of the cutoff in \a o and gives each asset its own copy - * (see Cutoff::copy()). The exception is a single asset whose spoke has - * SpokeCoverage::Full or SpokeCoverage::Reduced: it runs as the - * restart-based engine itself, which takes the cutoff in \a o and so - * also its random sequence. If the constructor throws an exception, - * the caller keeps the cutoff. + * The stop object in \a o is checked against summed statistics across all + * assets (current statistics when single-threaded; latest checked or final + * statistics of other assets when multi-threaded). Stopping yields + * Search::EndReason::Limit and calling next() resumes all assets. * - * The spoke of each asset declares its coverage in Space::spoke() (see - * SpokeCoverage). When an asset whose spoke has SpokeCoverage::Full or - * SpokeCoverage::Reduced exhausts its search space, the portfolio ends - * and end_reason() returns Search::EndReason::Exhausted. An asset that - * ends without a proof is dropped while the other assets continue: an - * asset whose spoke has SpokeCoverage::Partial and exhausts its search - * space, or an engine such as LDS at its discrepancy limit. When every - * asset has been dropped, end_reason() returns - * Search::EndReason::Incomplete. + * Best-solution assets update the incumbent only when Space::compare() + * returns SpaceComparison::Better. An external worker control in \a o is + * allowed only for a single homogeneous asset; multiple controlled assets + * require explicit engine builders with distinct controls. For + * restart-based assets, PBS takes ownership of the cutoff in \a o (kept by + * the caller if construction throws) and gives each asset a Cutoff::copy(), + * except a single \c Full or \c Reduced asset, which uses the cutoff + * directly. * - * The class \a T can override the member functions - * \code virtual void hub(HubContext& hc) \endcode - * and - * \code virtual void spoke(SpokeContext& sc) \endcode + * Exhausting an asset with SpokeCoverage::Full or SpokeCoverage::Reduced + * ends the portfolio with Search::EndReason::Exhausted. Assets ending + * without proof (SpokeCoverage::Partial exhaustion or incomplete engines + * such as LDS) are dropped; if all assets are dropped, end_reason() + * returns Search::EndReason::Incomplete. * - * The engine calls hub() once on its hub with MetaEvent::Start, then - * Space::status() on the hub, and then spoke() on the spoke of each - * asset. When the hub had branchers before hub() but a spoke that has - * not failed has none after spoke(), the engine throws - * Search::SpokeNoBrancher. See - * Space::hub() and Space::spoke() for details. + * Class \a T may override Space::hub(HubContext&) (called once at + * MetaEvent::Start, followed by Space::status()) and + * Space::spoke(SpokeContext&) (called once per asset). Throws + * Search::SpokeNoBrancher if the hub had branchers before hub() and a + * non-failed spoke has none after spoke(). * * \ingroup TaskModelSearch */ @@ -1686,24 +1608,17 @@ namespace Gecode { /// Initialize with engines running copies of \a s with options \a o PBS(T* s, const Search::Options& o = Search::Options::def); /** - * Initialize with engine builders \a sebs + * \brief Initialize with engine builders \a sebs * - * The stop object of \a o is checked with the statistics of the whole - * portfolio, the stop object of a builder with the statistics of the - * engine it builds. When the stop object of a builder stops its - * engine, that asset is parked while the other assets continue. When - * only parked assets remain, end_reason() returns - * Search::EndReason::Limit, and the parked assets resume with the - * next call to next(). + * The stop object in \a o checks summed portfolio statistics, while a + * builder's stop object checks its own engine and parks only that + * asset; if all remaining assets are parked, end_reason() returns + * Search::EndReason::Limit and next() resumes them. * - * The outer options must not contain a worker control. Each builder can - * instead supply a distinct control for its underlying engine. - * In parallel PBS, the engine of every builder runs in its own thread, - * also when there are more builders than outer threads; each builder's - * options set its own engine's thread count. - * - * With experimental search, AStar and CABS builders can be used - * together with BAB builders. + * \a o must not carry a worker control; supply distinct controls on + * individual builders instead. In parallel PBS, each builder runs in + * its own thread using its own thread count. With experimental search, + * AStar and CABS builders can be combined with BAB builders. */ PBS(T* s, SEBs& sebs, const Search::Options& o = Search::Options::def); /// Constrain future portfolio solutions to be better than \a b @@ -1715,23 +1630,9 @@ namespace Gecode { /** * \brief Run a portfolio of search engines * - * The engine will run a portfolio with a number of assets as defined - * by the options \a o. See PBS for how the assets use the threads in - * \a o. - * An external worker control is supported only when \a o selects one - * asset. PBS does not implement worker-allocation policy. - * - * The class \a T can override the member functions - * \code virtual void hub(HubContext& hc) \endcode - * and - * \code virtual void spoke(SpokeContext& sc) \endcode - * - * The engine calls hub() once on its hub with MetaEvent::Start, then - * Space::status() on the hub, and then spoke() on the spoke of each - * asset. When the hub had branchers before hub() but a spoke that has - * not failed has none after spoke(), the engine throws - * Search::SpokeNoBrancher. See - * Space::hub() and Space::spoke() for details. + * Runs PBS on \a s with options \a o and returns the first solution + * (or nullptr). External worker control in \a o is supported only for a + * single asset. See PBS, Space::hub(), and Space::spoke() for details. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/worker-control.hh b/gecode/search/worker-control.hh index 490418f1ec..a14c99d249 100644 --- a/gecode/search/worker-control.hh +++ b/gecode/search/worker-control.hh @@ -42,13 +42,12 @@ namespace Gecode::Search { /// Detach \a control from its leaf engine static void detach(WorkerControl& control); /** - * \brief Prepare \a control for another engine with the same capacity + * \brief Prepare detached \a control for reuse at the same capacity * - * The owner must have destroyed the previous engine and joined its - * workers. Requests and event storage survive the transition. Preparing - * an attached control raises WorkerControlInUse; otherwise this operation - * is idempotent. Attaching the prepared control with a different capacity - * raises InvalidWorkerRequest. This is an internal engine-owner operation. + * Preserves requests and event storage after the previous engine's + * workers have been joined. Idempotent when detached; throws + * WorkerControlInUse if attached, and a later attach() with a + * different capacity throws InvalidWorkerRequest. */ static void prepare_reuse(WorkerControl& control); /// Return the request generation diff --git a/gecode/support/cast.hpp b/gecode/support/cast.hpp index c31d2e3caf..54ffa08ca8 100644 --- a/gecode/support/cast.hpp +++ b/gecode/support/cast.hpp @@ -45,22 +45,18 @@ namespace Gecode { * \brief Cast \a from to a derived type that it is known to have * * Use down_cast where the dynamic type of an object passed through a - * base-class pointer or reference is known, such as the space passed to - * Space::constrain, the choice passed to Brancher::commit, or the advisor - * passed to Propagator::advise. The code calling down_cast is responsible - * for the type being right, so it needs no error path. Use - * \c dynamic_cast where the dynamic type is genuinely unknown. + * base-class pointer or reference is known, such as in Space::constrain, + * Space::compare, Brancher::commit, or Propagator::advise. The caller is + * responsible for the type being right; use \c dynamic_cast when the + * dynamic type is unknown. * - * With assertions enabled and a polymorphic source type, the cast is - * checked by an assertion using \c dynamic_cast. Otherwise it is a plain - * \c static_cast, which UBSan can verify with \c -fsanitize=vptr. A cast - * through a virtual base, where \c static_cast is ill-formed, uses - * \c dynamic_cast. - * - * \a To is a pointer type for a pointer argument and an lvalue reference - * type for a reference argument, and it must keep the argument's const - * qualification, as in down_cast(other). A null - * pointer is returned unchanged. + * Checks polymorphic casts with an assertion using \c dynamic_cast when + * assertions are enabled, and otherwise uses \c static_cast (or + * \c dynamic_cast when casting through a virtual base). \a To must be a + * pointer for pointer arguments or an lvalue reference for reference + * arguments, preserving const qualification (e.g. + * down_cast(other)). Null pointers are returned + * unchanged. * * \ingroup FuncSupport */ diff --git a/gecode/support/random.hpp b/gecode/support/random.hpp index e6dc03d16b..932776cda0 100644 --- a/gecode/support/random.hpp +++ b/gecode/support/random.hpp @@ -232,14 +232,14 @@ namespace Gecode::Support { return z ^ (z >> 31); } - /** \brief Splittable SplitMix with two 64-bit state words + /** + * \brief Splittable SplitMix engine with two 64-bit state words * - * Implements the SplitMix design of Steele, Lea, and Flood (OOPSLA 2014), - * using Stafford's Mix13 output permutation and the MurmurHash3 finalizer - * for gamma selection. Indexed splitting returns the child of the (a+1)th - * successive split without changing the parent. For a 32-bit alternative - * index, the inputs s + (2*a+1)*gamma are distinct: gamma is odd and the - * offsets span less than 2^64. Mix13 is bijective, so child states differ. + * Implements SplitMix (Steele, Lea, Flood, OOPSLA 2014) with Stafford's + * Mix13 output permutation and the MurmurHash3 finalizer for gamma. + * split(a) returns the (a+1)th child without modifying the parent; because + * gamma is odd and Mix13 is bijective, all 32-bit indices yield distinct + * child states. * * \ingroup FuncSupport */ @@ -306,22 +306,18 @@ namespace Gecode::Support { } }; - /** \brief One-word xorshift64* engine with hashed indexed splitting + /** + * \brief One-word xorshift64* engine with hashed indexed splitting + * + * Uses shifts (12, 25, 27) and Vigna's multiplier. Seeding initializes the + * state via Mix13(v + g) so related seeds do not produce correlated linear + * streams (mapping a zero hash to the state of seed 0); restoring a zero + * state throws std::invalid_argument. * - * Uses shifts 12, 25, 27 and Vigna's multiplier, for the odd constant g. - * Seed v starts from Mix13(v + g), the first SplitMix64 output for v, as - * the recurrence is linear and related raw seeds would give related - * streams. The one seed hashing to zero shares the state of seed 0. - * Restoring zero state is an error. + * split(a) hashes s + (2a+1)*g with Mix13 (substituting (2a+1)*g if the + * sum is zero), forming a bijection on nonzero states with distinct + * sibling states and no additive collisions across split chains. * - * Alternative a hashes s + (2a+1)*g with Mix13. For a 32-bit index these - * inputs are distinct, as in SplitMix, and Mix13 is bijective, so sibling - * states differ. Only a zero input hashes to zero; that sibling hashes - * (2a+1)*g instead, the input of the excluded state zero. Each split is - * thus a bijection on nonzero states, so distinct nodes stay distinct - * along equal alternative sequences. Unlike jumps along the recurrence, - * which add up so that split(0) of split(0) equals split(1), hashed states - * of other nodes coincide only by chance. * \ingroup FuncSupport */ class Xorshift64Star { @@ -383,24 +379,21 @@ namespace Gecode::Support { } }; - /** \brief Value-type generator with reproducible bounded draws and state + /** + * \brief Value-type generator with reproducible bounded draws and state + * + * \a Engine must provide a nonempty `State = std::array` + * holding all state and parameters, `uint64_t` seeding in its constructor + * and seed(), name(), and next() with output in `[min(), max()]` where + * `min() <= 1` and `max() == UINT64_MAX`. state() captures full state; + * state(const State&) validates before mutating and restores draws and + * splits exactly. Copying preserves state independently. * - * Engine supplies a nonempty State = std::array containing - * all mutable state and stream parameters. It accepts a uint64_t seed in - * its constructor and seed(), with a defined rule for every seed. Its - * next(), min(), and max() describe raw output in [0,UINT64_MAX] or - * [1,UINT64_MAX]. name() identifies the algorithm and state format. + * Engines used in search also provide `split(uint32_t) const`, returning a + * child without modifying the parent. Distinct indices must produce + * distinct states, and distinct split chains must not systematically + * collide (additive jumps do not qualify). * - * state() captures complete state. state(const State&) must validate - * before mutation and restore subsequent draws and splits exactly, - * without seed expansion. Copying preserves state independently. - * Search engines additionally supply split(uint32_t) const, returning - * a child without changing the parent. Different sibling indices must - * produce distinct states, not merely different first outputs. Branching, - * posting, and meta search derive streams by chains of splits, so chains - * along different paths should give equal states only by chance; a jump - * by an index-dependent distance does not qualify. This does not require - * non-overlapping streams across an unbounded tree. * \ingroup FuncSupport */ template