diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0b78f1d119..269db2bd96 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -127,7 +127,10 @@ jobs: shell: bash run: | sudo apt-get update - sudo apt-get install -y flex bison libgmp-dev libmpfr-dev + sudo apt-get install -y flex bison libgmp-dev libmpfr-dev g++-14 + # Space::clone needs deducing this, which GCC 13 lacks. + echo "CC=gcc-14" >> "$GITHUB_ENV" + echo "CXX=g++-14" >> "$GITHUB_ENV" - name: Check generated source freshness # Ubuntu LTS keeps Bison 3.8.2 and Flex 2.6.4, while Homebrew moves on. @@ -446,6 +449,10 @@ jobs: build-cmake-qt5-gist-smoke: runs-on: ubuntu-24.04 + env: + # Space::clone needs deducing this, which GCC 13 lacks. + CC: gcc-14 + CXX: g++-14 steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 @@ -459,7 +466,7 @@ jobs: shell: bash run: | sudo apt-get update - sudo apt-get install -y qtbase5-dev qtbase5-dev-tools libgl1-mesa-dev + sudo apt-get install -y qtbase5-dev qtbase5-dev-tools libgl1-mesa-dev g++-14 - name: Configure CMake with Qt 5/Gist shell: bash diff --git a/AGENTS.md b/AGENTS.md index 8a99a365cd..0926753db8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,6 +48,17 @@ when that is clearer. Gecode builds as C++23. Add abstractions only when they solve a concrete maintenance or correctness problem. +Some downcasts cannot fail because a Gecode protocol fixes the dynamic type: +the space passed to `Space::constrain` and `Space::compare`, the choice passed +to `Brancher::commit`, and the advisor passed to `Propagator::advise`, among +others listed in the documentation of `down_cast` (`gecode/support/cast.hpp`). +Write such casts with `down_cast`, which asserts the type in debug builds. +Existing `static_cast`s at these sites are correct as well. Do not replace +either with `dynamic_cast` and an error path, and do not report them as +unchecked casts. Use `dynamic_cast` only where the type is genuinely unknown. +`Space::clone()` returns the static type of the cloned space, so cloning a +model needs no cast. + ## Implementing propagators, branchers, and engines Propagators: diff --git a/changelog.in b/changelog.in index 53a9dbd351..c3d098e2cb 100644 --- a/changelog.in +++ b/changelog.in @@ -76,6 +76,31 @@ Date: unreleased This release contains breaking changes. See the entries below for the changes downstream code needs. +[ENTRY] +Module: kernel +What: change +Rank: minor +[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. + +[ENTRY] +Module: support +What: new +Rank: minor +[DESCRIPTION] +Add down_cast for downcasts whose target type a Gecode protocol guarantees, +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. + [ENTRY] Module: flatzinc What: change diff --git a/docs/cmake-build.md b/docs/cmake-build.md index 0c7a800912..eb4618e9b0 100644 --- a/docs/cmake-build.md +++ b/docs/cmake-build.md @@ -7,9 +7,11 @@ For modelling and search, use MPG and the API reference linked from the ## Requirements - CMake 3.21 or newer -- A compiler with C++23 mode. 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. +- 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`. diff --git a/examples/bacp.cpp b/examples/bacp.cpp index 2107a821aa..bfbca1281f 100644 --- a/examples/bacp.cpp +++ b/examples/bacp.cpp @@ -175,7 +175,7 @@ class BACP : public IntMinimizeScript { /// Value selection function for load branching static int load(const Space& home, IntVar x, int) { - const BACP& b = static_cast(home); + const BACP& b = down_cast(home); IntVarValues values(x); int val = -1; int best = Int::Limits::max + 1; @@ -192,7 +192,7 @@ class BACP : public IntMinimizeScript { /// Value selection function for reverse load branching static int load_rev(const Space& home, IntVar x, int) { - const BACP& b = static_cast(home); + const BACP& b = down_cast(home); IntVarValues values(x); int val = -1; int best = Int::Limits::min - 1; diff --git a/examples/bin-packing.cpp b/examples/bin-packing.cpp index d0b2c95845..2122658d80 100644 --- a/examples/bin-packing.cpp +++ b/examples/bin-packing.cpp @@ -364,7 +364,7 @@ class CDBF : public Brancher { /// Perform commit for choice \a _c and alternative \a a ExecStatus commit(Space& home, const Gecode::Choice& _c, unsigned int a) override { - const Choice& c = static_cast(_c); + const Choice& c = down_cast(_c); // This catches also the case that the choice has a single aternative only if (a == 0) { GECODE_ME_CHECK(bin[c.item].eq(home, c.same[0])); @@ -383,7 +383,7 @@ class CDBF : public Brancher { /// Print explanation void print(const Space&, const Gecode::Choice& _c, unsigned int a, std::ostream& o) const override { - const Choice& c = static_cast(_c); + const Choice& c = down_cast(_c); if (a == 0) { o << "bin[" << c.item << "] = " << c.same[0]; } else { diff --git a/examples/car-sequencing.cpp b/examples/car-sequencing.cpp index 1bf9b29647..d9552de5b5 100644 --- a/examples/car-sequencing.cpp +++ b/examples/car-sequencing.cpp @@ -355,7 +355,7 @@ class CarSequencing : public Script { /// Return cost void constrain(const Space& _best) override { - const CarSequencing& best = static_cast(_best); + const CarSequencing& best = down_cast(_best); rel(*this, stall_count, IRT_LT, best.stall_count.val()); } @@ -363,7 +363,7 @@ class CarSequencing : public Script { /// Compare objective values SpaceComparison compare(const Space& _other) const override { - const CarSequencing& other = static_cast(_other); + const CarSequencing& other = down_cast(_other); return compare_int(stall_count.val(), other.stall_count.val(), Sense::Minimize); } diff --git a/examples/cartesian-heart.cpp b/examples/cartesian-heart.cpp index 9bb9f016b7..f780056ae1 100644 --- a/examples/cartesian-heart.cpp +++ b/examples/cartesian-heart.cpp @@ -88,7 +88,7 @@ class CartesianHeart : public Script { /// Add constraints to current model to get next solution (not too close) void constrain(const Space& _b) override { - const CartesianHeart& b = static_cast(_b); + const CartesianHeart& b = down_cast(_b); rel(*this, (f[0] >= (b.f[0].max() + step)) || (f[1] >= (b.f[1].max() + step)) || (f[1] <= (b.f[1].min() - step))); } @@ -103,7 +103,7 @@ class CartesianHeart : public Script { */ SpaceComparison compare(const Space& _other) const override { - const CartesianHeart& b = static_cast(_other); + const CartesianHeart& b = down_cast(_other); bool apart = (f[0].min() >= (b.f[0].max() + step)) || (f[1].min() >= (b.f[1].max() + step)) || (f[1].max() <= (b.f[1].min() - step)); return apart ? SpaceComparison::Better : SpaceComparison::Worse; diff --git a/examples/crossword.cpp b/examples/crossword.cpp index 8b145295f8..d8ffdc600a 100644 --- a/examples/crossword.cpp +++ b/examples/crossword.cpp @@ -243,7 +243,7 @@ class Crossword : public Script { /// Print brancher information when branching on letters static void print_letters(const Space& home, const Brancher&, unsigned int a, IntVar, int i, const int& n, std::ostream& os) { - const Crossword& c = static_cast(home); + const Crossword& c = down_cast(home); int x = i % c.w, y = i / c.w; os << "letters[" << x << "," << y << "] " << ((a == 0) ? "=" : "!=") << " " << static_cast(n); } diff --git a/examples/fifteen-puzzle.cpp b/examples/fifteen-puzzle.cpp index 47a94d51ce..8a283ad4b8 100644 --- a/examples/fifteen-puzzle.cpp +++ b/examples/fifteen-puzzle.cpp @@ -245,7 +245,7 @@ class OpenPuzzle : public Script { : Script(opt), tiles(*this, IntSet(0, 15), 16 * (opt.limit() + 1)), path( *this, IntSet(0, 15), - [](Space& home, OpenIntVarList x, int i) { static_cast(home).transition(x, i); }, + [](Space& home, OpenIntVarList x, int i) { down_cast(home).transition(x, i); }, opt.limit() + 1) { const Board initial = initial_board(opt); rel(*this, tiles.length() == 16 * path.length()); @@ -255,7 +255,7 @@ class OpenPuzzle : public Script { IntValBranch value_branch = INT_VAL_MIN(); if (opt.branching() == PuzzleOptions::BRANCH_MANHATTAN) value_branch = INT_VAL([](const Space& home, IntVar next, int i) { - const OpenPuzzle& s = static_cast(home); + const OpenPuzzle& s = down_cast(home); return manhattan_value(s.state(i - 1), s.path[i - 1].val(), next); }); branch(*this, path, INT_VAR_NONE(), value_branch); @@ -301,7 +301,7 @@ class OpenPuzzle : public Script { } void constrain(const Space& solution) override { - const OpenPuzzle& best = static_cast(solution); + const OpenPuzzle& best = down_cast(solution); rel(*this, path.length() < best.path.length().val()); } void @@ -342,11 +342,11 @@ class FixedPuzzle : public Script { IntValBranch value_branch = INT_VAL_MIN(); if (opt.branching() == PuzzleOptions::BRANCH_MANHATTAN) value_branch = INT_VAL([](const Space& home, IntVar next, int i) { - const FixedPuzzle& s = static_cast(home); + const FixedPuzzle& s = down_cast(home); return manhattan_value(s.state(i - 1), s.path[i - 1].val(), next); }); branch(*this, path, INT_VAR_NONE(), value_branch, [](const Space& home, IntVar, int i) { - const FixedPuzzle& s = static_cast(home); + const FixedPuzzle& s = down_cast(home); const int depth = s.depth(); return values(s.state(depth)) != goal() && i == depth + 1; }); @@ -383,7 +383,7 @@ class FixedPuzzle : public Script { } void constrain(const Space& solution) override { - const FixedPuzzle& best = static_cast(solution); + const FixedPuzzle& best = down_cast(solution); rel(*this, length < best.length.val()); } void @@ -406,7 +406,7 @@ run(PuzzleOptions& opt) { case PuzzleOptions::SEARCH_ASTAR: case PuzzleOptions::SEARCH_CABS: { Search::HeuristicGuidance guidance( - Sense::Minimize, [](const Space& home) -> std::int64_t { return static_cast(home).bound(); }); + Sense::Minimize, [](const Space& home) -> std::int64_t { return down_cast(home).bound(); }); opt.guidance(&guidance); if (opt.search() == PuzzleOptions::SEARCH_ASTAR) Script::run(opt); diff --git a/examples/job-shop.cpp b/examples/job-shop.cpp index b90279fe76..fe1b468670 100644 --- a/examples/job-shop.cpp +++ b/examples/job-shop.cpp @@ -511,7 +511,7 @@ class JobShopSolve : public JobShopBase { /// Trampoline function for AFC-based cost static double afc_merit(const Space& home, BoolVar x, int i) { - return static_cast(home).afc(x, i); + return down_cast(home).afc(x, i); } /// Action information IntAction iaction; @@ -524,7 +524,7 @@ class JobShopSolve : public JobShopBase { /// Trampoline function for Action-based cost static double action_merit(const Space& home, BoolVar, int i) { - return static_cast(home).action(i); + return down_cast(home).action(i); } /// CHB information IntCHB ichb; @@ -537,7 +537,7 @@ class JobShopSolve : public JobShopBase { /// Trampoline function for CHB-based cost static double chb_merit(const Space& home, BoolVar, int i) { - return static_cast(home).chb(i); + return down_cast(home).chb(i); } /// Random number generator for probing and relaxation Rnd rnd; @@ -730,7 +730,7 @@ solve(const JobShopOptions& opt) { std::cout << "\t\tBounds: [" << l << "," << u << "]" << '\n' << std::flush; for (unsigned int p = 0; p < opt.probes(); p++) { - JobShopProbe* jsp = static_cast(root->clone()); + JobShopProbe* jsp = root->clone(); jsp->branch(p, rnd.split(p)); DFS dfs(jsp, so); JobShopProbe* s = dfs.next(); @@ -783,7 +783,7 @@ solve(const JobShopOptions& opt) { bool stopped = false; while (l < u) { std::cout << "\t\tBounds: [" << l << "," << u << "]" << '\n' << std::flush; - JobShopSolve* jss = static_cast(model->clone()); + JobShopSolve* jss = model->clone(); int m = (l + u) / 2; rel(*jss, jss->cost() >= l); rel(*jss, jss->cost() <= m); diff --git a/examples/knights.cpp b/examples/knights.cpp index e748ce3cba..19fd2bdc6e 100644 --- a/examples/knights.cpp +++ b/examples/knights.cpp @@ -125,7 +125,7 @@ class Warnsdorff : public Brancher { /// Perform commit for choice \a _c and alternative \a a ExecStatus commit(Space& home, const Gecode::Choice& _c, unsigned int a) override { - const Choice& c = static_cast(_c); + const Choice& c = down_cast(_c); if (a == 0) return me_failed(x[c.pos].eq(home, c.val)) ? ES_FAILED : ES_OK; return me_failed(x[c.pos].nq(home, c.val)) ? ES_FAILED : ES_OK; @@ -133,7 +133,7 @@ class Warnsdorff : public Brancher { /// Print explanation void print(const Space&, const Gecode::Choice& _c, unsigned int a, std::ostream& o) const override { - const Choice& c = static_cast(_c); + const Choice& c = down_cast(_c); o << "x[" << c.pos << "] " << ((a == 0) ? "=" : "!=") << " " << c.val; } /// Copy brancher @@ -345,7 +345,7 @@ class KnightsInspector : public Gist::Inspector { /// Inspect space \a s void inspect(const Space& s) override { - const Knights& k = static_cast(s); + const Knights& k = down_cast(s); const int half_unit = unit / 2; if (!scene) diff --git a/examples/photo.cpp b/examples/photo.cpp index 1101a1d711..166e8d11d3 100644 --- a/examples/photo.cpp +++ b/examples/photo.cpp @@ -131,7 +131,7 @@ class Photo : public IntMinimizeScript { void spoke(SpokeContext& sc) override { if ((sc.engine() == MetaEngine::Restart) && (sc.last() != nullptr) && (p > 0.0)) { - const Photo& l = static_cast(*sc.last()); + const Photo& l = down_cast(*sc.last()); relax(*this, pos, l.pos, rnd.split(sc), p); sc.coverage(SpokeCoverage::Partial); } diff --git a/examples/queen-armies.cpp b/examples/queen-armies.cpp index 73367fc614..a4c445c871 100644 --- a/examples/queen-armies.cpp +++ b/examples/queen-armies.cpp @@ -185,7 +185,7 @@ class QueenArmies : public IntMaximizeScript { /// Check status of brancher, return true if alternatives left. bool status(const Space& home) const override { - const QueenArmies& q = static_cast(home); + const QueenArmies& q = down_cast(home); for (int i = start; i < q.n * q.n; ++i) if (!q.white_matrix[i].assigned()) { start = i; @@ -197,7 +197,7 @@ class QueenArmies : public IntMaximizeScript { /// Return choice Gecode::Choice* choice(Space& home) override { - const QueenArmies& q = static_cast(home); + const QueenArmies& q = down_cast(home); int maxsize = -1; int pos = -1; @@ -229,15 +229,15 @@ class QueenArmies : public IntMaximizeScript { */ ExecStatus commit(Space& home, const Gecode::Choice& _c, unsigned int a) override { - QueenArmies& q = static_cast(home); - const Choice& c = static_cast(_c); + QueenArmies& q = down_cast(home); + const Choice& c = down_cast(_c); bool val = (a == 0) ? c.val : !c.val; return me_failed(Int::BoolView(q.white_matrix[c.pos]).eq(q, val)) ? ES_FAILED : ES_OK; } /// Print explanation void print(const Space&, const Gecode::Choice& _c, unsigned int a, std::ostream& o) const override { - const Choice& c = static_cast(_c); + const Choice& c = down_cast(_c); bool val = (a == 0) ? c.val : !c.val; o << "w[" << c.pos << "] = " << val; } diff --git a/examples/queens.cpp b/examples/queens.cpp index f5b8d15f09..0619703496 100644 --- a/examples/queens.cpp +++ b/examples/queens.cpp @@ -132,7 +132,7 @@ class QueensInspector : public Gist::Inspector { /// Inspect space \a s void inspect(const Space& s) override { - const Queens& q = static_cast(s); + const Queens& q = down_cast(s); const int inset = unit / 4; const int diameter = unit / 2; diff --git a/examples/radiotherapy.cpp b/examples/radiotherapy.cpp index c8c35968ae..ed6cdf66ae 100644 --- a/examples/radiotherapy.cpp +++ b/examples/radiotherapy.cpp @@ -231,7 +231,7 @@ class Radiotherapy : public IntMinimizeScript { }; /// Construct brancher NestedSearch(Space& home) : Brancher(home), done(false) { - Radiotherapy& rt = static_cast(home); + Radiotherapy& rt = down_cast(home); // Set up ordering of rows. As a heuristic, pre-order the rows // with the potentially cheapest ones first. index.init(rt.rd.m + 1); @@ -271,7 +271,7 @@ class Radiotherapy : public IntMinimizeScript { Gecode::Choice* choice(Space& home) override { done = true; - Radiotherapy& rt = static_cast(home); + Radiotherapy& rt = down_cast(home); std::cout << "*"; @@ -279,7 +279,7 @@ class Radiotherapy : public IntMinimizeScript { bool fail = false; for (int i = 0; i < rt.rd.m; i++) { // Create fresh clone for row i - Radiotherapy* row = static_cast(rt.clone()); + Radiotherapy* row = rt.clone(); // Branch over row i branch(*row, get_row(row, index[i].idx), INT_VAR_NONE(), INT_VAL_SPLIT_MIN()); @@ -311,12 +311,12 @@ class Radiotherapy : public IntMinimizeScript { /// Perform commit for choice \a _c and alternative \a a ExecStatus commit(Space&, const Gecode::Choice& _c, unsigned int) override { - return static_cast(_c).fail ? ES_FAILED : ES_OK; + return down_cast(_c).fail ? ES_FAILED : ES_OK; } /// Print explanation void print(const Space&, const Gecode::Choice& _c, unsigned int, std::ostream& o) const override { - const Choice& c = static_cast(_c); + const Choice& c = down_cast(_c); o << (c.fail ? "fail" : "ok"); } /// Copy brancher diff --git a/examples/steel-mill.cpp b/examples/steel-mill.cpp index 056d6f9846..dbbd996fb5 100644 --- a/examples/steel-mill.cpp +++ b/examples/steel-mill.cpp @@ -394,7 +394,7 @@ class SteelMill : public IntMinimizeScript { /// Check status of brancher, return true if alternatives left. bool status(const Space& home) const override { - const SteelMill& sm = static_cast(home); + const SteelMill& sm = down_cast(home); for (unsigned int i = start; i < sm.norders; ++i) if (!sm.slab[i].assigned()) { start = i; @@ -406,7 +406,7 @@ class SteelMill : public IntMinimizeScript { /// Return choice Gecode::Choice* choice(Space& home) override { - SteelMill& sm = static_cast(home); + SteelMill& sm = down_cast(home); assert(!sm.slab[start].assigned()); // Find order with a) minimum size, b) largest weight unsigned int size = sm.norders; @@ -442,8 +442,8 @@ class SteelMill : public IntMinimizeScript { /// Perform commit for choice \a _c and alternative \a a ExecStatus commit(Space& home, const Gecode::Choice& _c, unsigned int a) override { - SteelMill& sm = static_cast(home); - const Choice& c = static_cast(_c); + SteelMill& sm = down_cast(home); + const Choice& c = down_cast(_c); if (a) return me_failed(Int::IntView(sm.slab[c.pos]).nq(home, c.val)) ? ES_FAILED : ES_OK; return me_failed(Int::IntView(sm.slab[c.pos]).eq(home, c.val)) ? ES_FAILED : ES_OK; @@ -451,7 +451,7 @@ class SteelMill : public IntMinimizeScript { /// Print explanation void print(const Space&, const Gecode::Choice& _c, unsigned int a, std::ostream& o) const override { - const Choice& c = static_cast(_c); + const Choice& c = down_cast(_c); o << "slab[" << c.pos << "] " << ((a == 0) ? "=" : "!=") << " " << c.val; } /// Copy brancher diff --git a/examples/tsptw.cpp b/examples/tsptw.cpp index 40e26442e9..409dd17e09 100644 --- a/examples/tsptw.cpp +++ b/examples/tsptw.cpp @@ -368,11 +368,11 @@ main(int argc, char* argv[]) { case TSPTW::SEARCH_ASTAR: case TSPTW::SEARCH_CABS: { Search::HeuristicGuidance g( - Sense::Minimize, [](const Space& s) -> std::int64_t { return static_cast(s).cost().min(); }); + Sense::Minimize, [](const Space& s) -> std::int64_t { return down_cast(s).cost().min(); }); g.dominates = [](const Space& a, const Space& b) { - return static_cast(a).dominates(static_cast(b)); + return down_cast(a).dominates(down_cast(b)); }; - g.dominance_key = [](const Space& s) { return static_cast(s).key(); }; + g.dominance_key = [](const Space& s) { return down_cast(s).key(); }; opt.guidance(&g); if (opt.search() == TSPTW::SEARCH_ASTAR) IntMinimizeScript::run(opt); diff --git a/gecode/flatzinc/flatzinc.cpp b/gecode/flatzinc/flatzinc.cpp index 73eeb90b20..23ed74d828 100644 --- a/gecode/flatzinc/flatzinc.cpp +++ b/gecode/flatzinc/flatzinc.cpp @@ -215,7 +215,7 @@ namespace Gecode::FlatZinc { Choice* choice(Space& home) override { done = true; - FlatZincSpace& fzs = static_cast(*home.clone()); + FlatZincSpace& fzs = *down_cast(home).clone(); fzs.need_aux_vars = false; branch(fzs, fzs.iv_aux, int_varsel, int_valsel); branch(fzs, fzs.bv_aux, bool_varsel, bool_valsel); diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 7aaf50ba87..f36fc6e742 100644 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1246,6 +1246,9 @@ namespace Gecode { * static or member functions of views as the actual delta * information is both domain and view dependent. * + * The kernel passes only advisors that belong to this propagator, so + * an override converts \a a to its own advisor class with down_cast. + * */ GECODE_KERNEL_EXPORT virtual ExecStatus advise(Space& home, Advisor& a, const Delta& d); @@ -1566,6 +1569,11 @@ namespace Gecode { * * The current brancher in the space \a home performs a commit from * the information provided by the choice \a c and the alternative \a a. + * + * The kernel passes only choices created by choice() of this brancher + * or of a brancher it was cloned from, so an override converts \a c + * to its own choice class with down_cast. The same holds for ngl() + * and print(). */ virtual ExecStatus commit(Space& home, const Choice& c, unsigned int a) = 0; /** @@ -1887,7 +1895,9 @@ namespace Gecode { * 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. + * the hook runs: clone the solution to keep it. The solution is a + * clone of the same root space as the space the hook runs on, so it + * has the same dynamic type: convert it with down_cast. */ const Space* last() const; /** @@ -2399,7 +2409,11 @@ namespace Gecode { /** * \brief Copying member function * - * Must create a new object using the constructor for cloning. + * Must create a new object of the same class as this space using the + * constructor for cloning, so every class derived from Space that can + * be cloned overrides copy(). The kernel and the search engines rely + * on clones having the same dynamic type as the original (see + * down_cast). * * Should not be used directly, use Space::clone to create a clone * of a Space. @@ -2413,6 +2427,10 @@ namespace Gecode { * Must constrain this space to be better than the so far best * solution \a best. * + * Search only passes a \a best that is a clone of the same root + * space as this space, so it has the same dynamic type. An override + * converts it with down_cast and needs no check of its own. + * * The default function does nothing. * * \ingroup TaskModelScript @@ -2426,6 +2444,10 @@ namespace Gecode { * either. The result must agree with constrain: solutions admitted by * constrain(b) are better than b, and a better b admits no more solutions. * + * Search only passes an \a other that is a clone of the same root + * space as this space, so it has the same dynamic type. An override + * converts it with down_cast and needs no check of its own. + * * The default function throws SpaceNoComparison, so a space overriding * constrain must also override compare. * @@ -2582,18 +2604,23 @@ namespace Gecode { * failed, an exception of type SpaceFailed is thrown. If the space * is not stable, an exception of SpaceNotStable is thrown. * - * Otherwise, a clone of the space is returned and the statistics - * information \a stat is updated. + * Otherwise, a clone of the space is returned. The clone has the same + * dynamic type as this space (see copy()). The result has the static + * type of the object clone() is called on: for a \c Model \c m, + * \c m.clone() returns a \c Model*, and cloning through a \c Space* + * returns a \c Space*. Convert the latter with down_cast when the + * model type is known. * * Throws an exception of type SpaceNotCloned when the copy constructor * of the Space class is not invoked during cloning. * * \ingroup TaskSearch */ - /// Clone space without collecting statistics - Space* clone() const; - /// Clone space - Space* clone(CloneStatistics& stat) const; + template + Self* clone(this const Self& self); + /// Clone space and update the statistics \a stat, see clone() + template + Self* clone(this const Self& self, CloneStatistics& stat); /** * \brief Commit choice \a c for alternative \a a @@ -3740,18 +3767,21 @@ namespace Gecode { pc.p.bid_sc = (n << sc_bits) | (pc.p.bid_sc & ((1U << sc_bits) - 1U)); } - forceinline Space* - Space::clone() const { + template + forceinline Self* + Space::clone(this const Self& self) { CloneStatistics stat; - return clone(stat); + return self.Space::clone(stat); } - forceinline Space* - Space::clone(CloneStatistics&) const { + template + forceinline Self* + Space::clone(this const Self& self, CloneStatistics&) { // Clone is only const for search engines. During cloning, several data // structures are updated (e.g. forwarding pointers), so we have to - // cast away the constness. - return const_cast(this)->_clone(); + // cast away the constness. Cloning preserves the dynamic type. + auto& home = const_cast(static_cast(self)); + return down_cast(home._clone()); } forceinline void diff --git a/gecode/search/base.hpp b/gecode/search/base.hpp index f1046c7d7a..1581a49ccb 100644 --- a/gecode/search/base.hpp +++ b/gecode/search/base.hpp @@ -43,7 +43,7 @@ namespace Gecode::Search { template forceinline T* Base::next() { - return dynamic_cast(e->next()); + return down_cast(e->next()); } template forceinline Statistics diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 28801aa472..8798be6c6f 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -459,8 +459,8 @@ namespace Gecode { return; } - // Check whether a clone must be used - T* hub = opt.clone ? dynamic_cast(s->clone()) : s; + // Check whether a clone must be used (qualified, as T may hide clone) + T* hub = opt.clone ? s->Space::clone() : s; opt.clone = false; bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; @@ -536,8 +536,8 @@ namespace Gecode { return; } - // Check whether a clone must be used - T* hub = opt.clone ? dynamic_cast(s->clone()) : s; + // Check whether a clone must be used (qualified, as T may hide clone) + T* hub = opt.clone ? s->Space::clone() : s; opt.clone = false; bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; diff --git a/gecode/support/cast.hpp b/gecode/support/cast.hpp index 7c2da79795..1969691b92 100644 --- a/gecode/support/cast.hpp +++ b/gecode/support/cast.hpp @@ -30,18 +30,99 @@ * */ +#include +#include +#include +#include + namespace Gecode { /// Cast \a p into pointer of type \a T template T ptr_cast(void* p); + /** + * \brief Cast \a from to a derived type that a Gecode protocol guarantees + * + * Use down_cast where Gecode guarantees the dynamic type of an object + * passed through a base-class pointer or reference, so that the cast + * cannot fail: + * - the space passed to Space::constrain or Space::compare has the same + * dynamic type as the space the function is called on, because search + * passes only clones of one root space; + * - the solution returned by MetaContext::last() has the same dynamic + * type as the space the meta-search hook runs on; + * - the space passed to a branching function, such as a merit, value, + * commit, filter, or print function, is the space the brancher was + * posted in, or a clone of it; + * - the choice passed to Brancher::commit, Brancher::ngl, or + * Brancher::print was created by that brancher or by a brancher it + * was cloned from; + * - the advisor passed to Propagator::advise belongs to that + * propagator. + * + * These are guarantees, not assumptions to be checked. A failing cast is + * a bug in Gecode or in a Space::copy that does not create an object of + * its own class, never bad input, so code calling down_cast needs no + * check or error path of its own. Use \c dynamic_cast only where the + * dynamic type is genuinely 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. + * + * \ingroup FuncSupport + */ + template + [[nodiscard]] To down_cast(From* from) noexcept; + /** + * \brief Cast \a from to a derived type that a Gecode protocol guarantees + * + * The reference form of down_cast(From*). + * + * \ingroup FuncSupport + */ + template + [[nodiscard]] To down_cast(From& from) noexcept; + template forceinline T ptr_cast(void* p) { return static_cast(p); } + template + forceinline To + down_cast(From* from) noexcept { + static_assert(std::is_pointer_v, "down_cast of a pointer needs a pointer target type"); + static_assert(std::derived_from, From>, + "down_cast target type must be publicly derived from the source type"); + if constexpr (requires(From* f) { static_cast(f); }) { + if constexpr (std::is_polymorphic_v) + assert((from == nullptr) || (dynamic_cast(from) == from)); + return static_cast(from); + } else { + // Only dynamic_cast can cast through a virtual base + To to = dynamic_cast(from); + assert((from == nullptr) || (to != nullptr)); + return to; + } + } + + template + forceinline To + down_cast(From& from) noexcept { + static_assert(std::is_lvalue_reference_v, "down_cast of a reference needs a reference target type"); + return *down_cast*>(std::addressof(from)); + } + } // namespace Gecode // STATISTICS: support-any diff --git a/test/afc.cpp b/test/afc.cpp index e123e18e96..c8ce6aefef 100644 --- a/test/afc.cpp +++ b/test/afc.cpp @@ -118,7 +118,7 @@ namespace Test { } int j = space(s); (void)s[j]->status(); - s[i] = static_cast(s[j]->clone()); + s[i] = s[j]->clone(); n_s++; } break; @@ -229,7 +229,7 @@ namespace Test { if (s.post().afc() != 0.0) return false; (void)s.status(); - std::unique_ptr c(static_cast(s.clone())); + std::unique_ptr c(s.clone()); if (c->post().afc() != 1.0) return false; } @@ -258,7 +258,7 @@ namespace Test { } a.disable(*s); (void)s->status(); - std::unique_ptr c(static_cast(s->clone())); + std::unique_ptr c(s->clone()); // The first call marks the shared pool; the second really unshares. s->afc_unshare(); c->afc_unshare(); @@ -289,7 +289,7 @@ namespace Test { p = &s.post(); } (void)s.status(); - std::unique_ptr c(static_cast(s.clone())); + std::unique_ptr c(s.clone()); // Force rescaling on failure for the ordinary propagator. IntAFC afc(*c, IntVarArgs() << c->x << c->y, 1.0e-300, false); c->afc_unshare(); diff --git a/test/assign.cpp b/test/assign.cpp index 0f59233ea3..7c42ef321c 100644 --- a/test/assign.cpp +++ b/test/assign.cpp @@ -164,7 +164,7 @@ namespace Test::Assign { (void)root->status(); for (int val = 0; val < n_int_assign; val++) { - IntTestSpace* clone = static_cast(root->clone()); + IntTestSpace* clone = root->clone(); Gecode::Search::Options o; o.a_d = _rand(10); o.c_d = _rand(10); @@ -224,7 +224,7 @@ namespace Test::Assign { (void)root->status(); for (int val = n_bool_assign; val--;) { - BoolTestSpace* clone = static_cast(root->clone()); + BoolTestSpace* clone = root->clone(); Gecode::Search::Options o; o.a_d = _rand(10); o.c_d = _rand(10); @@ -302,7 +302,7 @@ namespace Test::Assign { (void)root->status(); for (int val = n_set_assign; val--;) { - SetTestSpace* clone = static_cast(root->clone()); + SetTestSpace* clone = root->clone(); Gecode::Search::Options o; o.a_d = _rand(10); o.c_d = _rand(10); @@ -399,7 +399,7 @@ namespace Test::Assign { (void)root->status(); for (int val = n_float_assign; val--;) { - FloatTestSpace* clone = static_cast(root->clone()); + FloatTestSpace* clone = root->clone(); Gecode::Search::Options o; o.a_d = _rand(10); o.c_d = _rand(10); diff --git a/test/branch.cpp b/test/branch.cpp index 1e1f99c27c..537f323559 100644 --- a/test/branch.cpp +++ b/test/branch.cpp @@ -386,7 +386,7 @@ namespace Test::Branch { break; } - IntTestSpace* c = static_cast(root->clone()); + IntTestSpace* c = root->clone(); if ((vara == 0) && (val < 11)) { for (int i = 0; i < c->x.size(); i++) @@ -685,7 +685,7 @@ namespace Test::Branch { break; } - BoolTestSpace* c = static_cast(root->clone()); + BoolTestSpace* c = root->clone(); if (vara == 0) { for (int i = 0; i < c->x.size(); i++) @@ -896,7 +896,7 @@ namespace Test::Branch { break; } - SetTestSpace* c = static_cast(root->clone()); + SetTestSpace* c = root->clone(); if (vara == 0) { for (int i = 0; i < c->x.size(); i++) @@ -1172,7 +1172,7 @@ namespace Test::Branch { break; } - FloatTestSpace* c = static_cast(root->clone()); + FloatTestSpace* c = root->clone(); if (vara == 0) { for (int i = 0; i < c->x.size(); i++) branch(*c, c->x[i], fvb); diff --git a/test/fault.cpp b/test/fault.cpp index 0555ce51d1..a325192e6d 100644 --- a/test/fault.cpp +++ b/test/fault.cpp @@ -492,7 +492,7 @@ namespace Test::Fault { Support::FailPoint::reset(); if (s.h.value() != 42) return false; - LocalCopySpace* c = static_cast(s.clone()); + LocalCopySpace* c = s.clone(); bool ok = (c != nullptr) && (c->h.value() == 42); delete c; return ok; @@ -521,7 +521,7 @@ namespace Test::Fault { Support::FailPoint::reset(); if (!s.advisors_point_to_source()) return false; - AdvisorCopySpace* c = static_cast(s.clone()); + AdvisorCopySpace* c = s.clone(); bool ok = (c != nullptr); delete c; return ok && s.advisors_point_to_source(); diff --git a/test/flatzinc.cpp b/test/flatzinc.cpp index efa53beb73..ebf2302b2e 100644 --- a/test/flatzinc.cpp +++ b/test/flatzinc.cpp @@ -86,11 +86,11 @@ namespace Test::FlatZinc { std::unique_ptr fg(Gecode::FlatZinc::parse(ss, p, olog)); if (!fg || (fg->status() == Gecode::SS_FAILED)) return false; - std::unique_ptr best(static_cast(fg->clone())); + std::unique_ptr best(fg->clone()); Gecode::rel(*best, best->fv[0], Gecode::FRT_EQ, 0.5); if (best->status() == Gecode::SS_FAILED) return false; - std::unique_ptr s(static_cast(fg->clone())); + std::unique_ptr s(fg->clone()); s->constrain(*best); if ((s->status() == Gecode::SS_FAILED) || s->fv[0].assigned()) return false; diff --git a/test/float.cpp b/test/float.cpp index 790b58b9db..80959edc77 100644 --- a/test/float.cpp +++ b/test/float.cpp @@ -375,7 +375,7 @@ namespace Test::Float { if (Base::fixpoint(rand)) { if (failed() || !test_fixpoint) return true; - TestSpace* c = static_cast(clone()); + TestSpace* c = clone(); if (opt.log) olog << ind(3) << "Testing fixpoint on copy" << '\n'; c->post(); @@ -519,7 +519,7 @@ namespace Test::Float { if (opt.log) olog << ind(3) << "Copy" << '\n'; if (s->status() != SS_FAILED) { - sc = static_cast(s->clone()); + sc = s->clone(); } else { sc = s; s = nullptr; @@ -852,7 +852,7 @@ namespace Test::Float { if (sol == MT_TRUE) { START_TEST("Search"); if (!search_s->failed()) { - TestSpace* ss = static_cast(search_s->clone()); + TestSpace* ss = search_s->clone(); ss->drop_until(a); delete e_s; e_s = new DFS(ss, search_o); @@ -875,7 +875,7 @@ namespace Test::Float { if (test_search) { test = "Search"; if (!search_s->failed()) { - TestSpace* ss = static_cast(search_s->clone()); + TestSpace* ss = search_s->clone(); ss->drop_until(a); delete e_s; e_s = new DFS(ss, search_o); diff --git a/test/float/arithmetic.cpp b/test/float/arithmetic.cpp index 8a60cdfa84..4105a60343 100644 --- a/test/float/arithmetic.cpp +++ b/test/float/arithmetic.cpp @@ -688,13 +688,13 @@ namespace Test::Float::Arithmetic { olog << "Pow wide base failed for n=" << n << '\n'; return false; } - ZeroSpace* clone = static_cast(delayed.clone()); + ZeroSpace* clone = delayed.clone(); Gecode::rel(*clone, clone->x, Gecode::FRT_EQ, 0.0); if (n == 0) { const bool zero_rejected = (direct.status() == Gecode::SS_FAILED) && (clone->status() == Gecode::SS_FAILED); delete clone; - ZeroSpace* non_zero = static_cast(delayed.clone()); + ZeroSpace* non_zero = delayed.clone(); Gecode::rel(*non_zero, non_zero->x, Gecode::FRT_EQ, 0.5); const bool non_zero_accepted = (non_zero->status() != Gecode::SS_FAILED) && (non_zero->y.min() == 1.0) && (non_zero->y.max() == 1.0); @@ -719,7 +719,7 @@ namespace Test::Float::Arithmetic { olog << "Pow zero result failed for n=" << n << '\n'; return false; } - ZeroResultSpace* clone = static_cast(initial.clone()); + ZeroResultSpace* clone = initial.clone(); if (!direct) Gecode::rel(*clone, clone->y, Gecode::FRT_EQ, 0.0); const bool contracted = @@ -741,7 +741,7 @@ namespace Test::Float::Arithmetic { const bool actor_retained = (initial.status() != Gecode::SS_FAILED) && (initial.y.min() == 1.0) && (initial.y.max() == 1.0) && (Gecode::PropagatorGroup::all.size(initial) > 0); - AdjacentZeroSpace* clone = static_cast(initial.clone()); + AdjacentZeroSpace* clone = initial.clone(); const bool clone_retained = (clone->status() != Gecode::SS_FAILED) && (clone->y.min() == 1.0) && (clone->y.max() == 1.0) && (Gecode::PropagatorGroup::all.size(*clone) > 0); delete clone; @@ -773,7 +773,7 @@ namespace Test::Float::Arithmetic { olog << "Pow fixpoint instance failed" << '\n'; return false; } - FixpointSpace* twice = static_cast(once.clone()); + FixpointSpace* twice = once.clone(); Gecode::pow(*twice, twice->x, 2, twice->y); const bool fixpoint = (twice->status() != Gecode::SS_FAILED) && (once.x.min() == twice->x.min()) && (once.x.max() == twice->x.max()) && (once.y.min() == twice->y.min()) && @@ -822,7 +822,7 @@ namespace Test::Float::Arithmetic { << '\n'; return false; } - MultSpace* clone = static_cast(s.clone()); + MultSpace* clone = s.clone(); Gecode::mult(*clone, clone->x, clone->y, clone->z); const bool fixpoint = (clone->status() != Gecode::SS_FAILED) && (clone->x.min() == s.x.min()) && (clone->x.max() == s.x.max()) && (clone->y.min() == s.y.min()) && diff --git a/test/int.cpp b/test/int.cpp index cc95d87d1d..c8b91c8c65 100644 --- a/test/int.cpp +++ b/test/int.cpp @@ -336,7 +336,7 @@ namespace Test::Int { if (Base::fixpoint(rand)) { if (failed() || !test_fixpoint) return true; - TestSpace* c = static_cast(clone()); + TestSpace* c = clone(); if (opt.log) olog << ind(3) << "Testing fixpoint on copy" << '\n'; c->post(); @@ -516,7 +516,7 @@ namespace Test::Int { if (opt.log) olog << ind(3) << "Copy" << '\n'; if (s->status() != SS_FAILED) { - sc = static_cast(s->clone()); + sc = s->clone(); } else { sc = s; s = nullptr; @@ -632,7 +632,7 @@ namespace Test::Int { START_TEST("Prune (disable)"); { TestSpace* s = new TestSpace(arity, dom, this); - TestSpace* c = static_cast(s->clone()); + TestSpace* c = s->clone(); s->post(); c->post(); while (!s->failed() && !s->assigned()) @@ -761,7 +761,7 @@ namespace Test::Int { { START_TEST("Prune reified, <=>, disable"); TestSpace* s = new TestSpace(arity, dom, this, RM_EQV); - TestSpace* c = static_cast(s->clone()); + TestSpace* c = s->clone(); s->post(); c->post(); while (!s->failed() && (!s->assigned() || !s->r.var().assigned())) @@ -903,7 +903,7 @@ namespace Test::Int { { START_TEST("Prune reified, =>, disable"); TestSpace* s = new TestSpace(arity, dom, this, RM_IMP); - TestSpace* c = static_cast(s->clone()); + TestSpace* c = s->clone(); s->post(); c->post(); while (!s->failed() && (!s->assigned() || (!sol && !s->r.var().assigned()))) @@ -1045,7 +1045,7 @@ namespace Test::Int { { START_TEST("Prune reified, <=, disable"); TestSpace* s = new TestSpace(arity, dom, this, RM_RIMP); - TestSpace* c = static_cast(s->clone()); + TestSpace* c = s->clone(); s->post(); c->post(); while (!s->failed() && (!s->assigned() || (sol && !s->r.var().assigned()))) @@ -1288,7 +1288,7 @@ namespace Test::Int { IntArgs sizes(arity); for (int i = 0; i < arity; i++) sizes[i] = static_cast(s.x[i].size()); - std::unique_ptr c(static_cast(s.clone())); + std::unique_ptr c(s.clone()); if (!complete(*c)) return false; if ((s.list.known_length() != before) || (s.list.length().min() != length_min) || diff --git a/test/int/arithmetic.cpp b/test/int/arithmetic.cpp index 4072608b04..a1940918cd 100644 --- a/test/int/arithmetic.cpp +++ b/test/int/arithmetic.cpp @@ -433,7 +433,7 @@ namespace Test::Int::Arithmetic { if (home.status() == SS_FAILED) return arithmetic_failed("initial propagation: home.x, home.c, home.y, home.m", Gecode::IntVarArgs() << home.x << home.c << home.y << home.m); - std::unique_ptr clone(static_cast(home.clone())); + std::unique_ptr clone(home.clone()); PropagatorGroup::all.disable(*clone); rel(*clone, clone->b, IRT_EQ, 1); PropagatorGroup::all.enable(*clone); @@ -441,7 +441,7 @@ namespace Test::Int::Arithmetic { return arithmetic_failed("activation after cloning, kind " + str(kind) + ": x, c, y, m", Gecode::IntVarArgs() << clone->x << clone->c << clone->y << clone->m); // Clone the activated actor before fixing a variable modulus. - std::unique_ptr child(static_cast(clone->clone())); + std::unique_ptr child(clone->clone()); rel(*child, child->m, IRT_EQ, kind == 4 ? 5 : 13); if ((child->status() == SS_FAILED) || !child->x.assigned() || (child->x.val() != (kind == 4 ? 3 : 6)) || home.b.assigned() || (home.x.size() != 4) || clone->m.assigned()) @@ -914,7 +914,7 @@ namespace Test::Int::Arithmetic { if (home.status() == SS_FAILED) return arithmetic_failed("initial clone state: home.x, home.q, home.y", Gecode::IntVarArgs() << home.x << home.q << home.y); - CloneSpace* clone = static_cast(home.clone()); + CloneSpace* clone = home.clone(); PropagatorGroup::all.disable(*clone); rel(home, home.x, IRT_NQ, 0); rel(*clone, clone->x, IRT_NQ, 0); diff --git a/test/int/cumulative.cpp b/test/int/cumulative.cpp index cd162a5f7e..b115799124 100644 --- a/test/int/cumulative.cpp +++ b/test/int/cumulative.cpp @@ -556,7 +556,7 @@ namespace Test::Int::Cumulative { VariableCapacityFixture root; if (root.status() == Gecode::SS_FAILED) return false; - std::unique_ptr clone(static_cast(root.clone())); + std::unique_ptr clone(root.clone()); Gecode::rel(*clone, clone->capacity, Gecode::IRT_EQ, 3); return clone->status() == Gecode::SS_FAILED; } diff --git a/test/int/extensional.cpp b/test/int/extensional.cpp index 9b20176839..bc2438fa41 100644 --- a/test/int/extensional.cpp +++ b/test/int/extensional.cpp @@ -930,7 +930,7 @@ namespace Test::Int::Extensional { source.list.append(source, source.x[0]); if ((source.status() == SS_FAILED) || (source.x[0].size() != 2)) return false; - OpenRegularSpace* clone = static_cast(source.clone()); + OpenRegularSpace* clone = source.clone(); rel(*clone, clone->list.length(), IRT_LQ, 3); const bool clone_ok = (clone->status() != SS_FAILED) && clone->x[0].assigned() && (clone->x[0].val() == 0); delete clone; @@ -1017,7 +1017,7 @@ namespace Test::Int::Extensional { if (source.status() == SS_FAILED) return false; - OpenRegularSpace* clone = static_cast(source.clone()); + OpenRegularSpace* clone = source.clone(); clone->list.append(*clone, clone->x[1]); clone->list.close(*clone); const bool clone_ok = (clone->status() != SS_FAILED) && (clone->list.known_length() == 2); @@ -1766,7 +1766,7 @@ namespace Test::Int::Extensional { return false; } - CloneSpace* clone = static_cast(source->clone()); + CloneSpace* clone = source->clone(); PropagatorGroup::all.enable(*clone); const bool clone_ok = (clone->status() != SS_FAILED) && clone->x[1].assigned() && (clone->x[1].val() == 1); @@ -1812,7 +1812,7 @@ namespace Test::Int::Extensional { return s.x[1].size() == 3; }; - CloneSpace* clone = static_cast(source->clone()); + CloneSpace* clone = source->clone(); PropagatorGroup::all.enable(*clone); const bool clone_ok = verify(*clone); delete clone; diff --git a/test/int/min-distance.cpp b/test/int/min-distance.cpp index 293136f303..e5206aec78 100644 --- a/test/int/min-distance.cpp +++ b/test/int/min-distance.cpp @@ -142,7 +142,7 @@ namespace Test::Int::MinDistance { rel(forward, forward.x[0], IRT_EQ, 0); if ((forward.status() == SS_FAILED) || (forward.x[1].min() != 2) || (forward.z.max() != 3)) return false; - std::unique_ptr clone(static_cast(forward.clone())); + std::unique_ptr clone(forward.clone()); rel(*clone, clone->x[1], IRT_EQ, 2); if ((clone->status() == SS_FAILED) || !clone->z.assigned() || (clone->z.val() != 2) || forward.z.assigned()) @@ -173,7 +173,7 @@ namespace Test::Int::MinDistance { dom(original, original.x, 0, 2); if (original.status() == SS_FAILED) return false; - clone.reset(static_cast(original.clone())); + clone.reset(original.clone()); } if (lifetime.expired() || (clone->status() == SS_FAILED)) return false; diff --git a/test/int/open-var-list.cpp b/test/int/open-var-list.cpp index 7ddcb52bf3..b9c59db56e 100644 --- a/test/int/open-var-list.cpp +++ b/test/int/open-var-list.cpp @@ -82,7 +82,7 @@ namespace Test::Int::OpenList { if (!source.list[i].assigned() || (source.list[i].val() != i)) return false; - OpenListSpace* clone = static_cast(source.clone()); + OpenListSpace* clone = source.clone(); rel(*clone, clone->list.length(), IRT_GQ, 5); const bool clone_ok = (clone->status() != SS_FAILED) && (clone->list.known_length() == 5) && clone->list[4].assigned() && (clone->list[4].val() == 4); @@ -311,7 +311,7 @@ namespace Test::Int::OpenList { const Choice* restored = source.choice(archive); bool valid = restored->alternatives() == (multi ? 3U : 2U); for (unsigned int a = 0; a < restored->alternatives(); a++) { - SelectorChoiceSpace* clone = static_cast(source.clone()); + SelectorChoiceSpace* clone = source.clone(); clone->commit(*restored, a); const int expected[] = {5, 2, 0}; valid &= !clone->failed() && !clone->list[0].assigned() && !clone->list[1].assigned(); @@ -321,7 +321,7 @@ namespace Test::Int::OpenList { valid &= !clone->list[2].in(5); delete clone; } - SelectorChoiceSpace* excluded = static_cast(source.clone()); + SelectorChoiceSpace* excluded = source.clone(); NGL* literal = excluded->ngl(*restored, 0); valid &= (literal != nullptr) && (literal->status(*excluded) == NGL::NONE); if (literal) @@ -445,7 +445,7 @@ namespace Test::Int::OpenList { source.list.append(source, first); if ((source.list.known_length() != 5) || (source.status() == SS_FAILED)) return false; - std::unique_ptr> clone(static_cast*>(source.clone())); + std::unique_ptr> clone(source.clone()); if (!clone->rejects(3)) return false; clone->list.append(*clone, Var(*clone, 0, 1)); @@ -513,7 +513,7 @@ namespace Test::Int::OpenList { FactorySpace source; if (source.status() == SS_FAILED) return false; - FactorySpace* clone = static_cast(source.clone()); + FactorySpace* clone = source.clone(); #ifdef GECODE_HAS_SET_VARS clone->sets.materialize(*clone, 3); clone->sets.close(*clone); @@ -729,7 +729,7 @@ namespace Test::Int::OpenList { (source.negative[0].min() != -7) || (source.negative[0].max() != -2)) return false; - std::unique_ptr clone(static_cast(source.clone())); + std::unique_ptr clone(source.clone()); clone->negative.materialize(*clone, 3); if (me_failed(clone->negative[0].eq(*clone, -5)) || me_failed(clone->direct.length().eq(*clone, 3)) || (clone->status() == SS_FAILED) || (clone->list.known_length() != 3) || @@ -935,7 +935,7 @@ namespace Test::Int::OpenList { if ((source.status() == SS_FAILED) || (source.list[0].min() != 5) || (source.list[1].min() != 6) || (source.list[0].max() != 7) || (source.list[1].max() != 7)) return false; - std::unique_ptr clone(static_cast(source.clone())); + std::unique_ptr clone(source.clone()); clone->list.materialize(*clone, 3); if ((clone->status() == SS_FAILED) || (clone->list[2].min() != 5) || (clone->list[2].max() != 7) || (source.list.known_length() != 2)) @@ -1033,7 +1033,7 @@ namespace Test::Int::OpenList { if ((source.status() == SS_FAILED) || !source.list[0].assigned()) return false; - std::unique_ptr clone(static_cast(source.clone())); + std::unique_ptr clone(source.clone()); clone->list.materialize(*clone, 2); clone->list.close(*clone); if (kind == Constraint::Kind::MIN_MAX) @@ -1165,8 +1165,8 @@ namespace Test::Int::OpenList { return false; if (source.status() == SS_FAILED) return false; - std::unique_ptr clone(static_cast(source.clone())); - std::unique_ptr sibling(static_cast(source.clone())); + std::unique_ptr clone(source.clone()); + std::unique_ptr sibling(source.clone()); std::set clone_expected(expected); const IntSet growth({{-30, -29}, {-20, -19}, {14, 14}, {18, 18}, {26, 26}, {28, 28}, {30, 30}}); if (!add(*clone, clone_expected, IntSet(26, 26)) || !add(*clone, clone_expected, growth) || @@ -1194,7 +1194,7 @@ namespace Test::Int::OpenList { source.list.append(source, IntVar(source, 1, 1)); if (source.status() == SS_FAILED) return false; - std::unique_ptr duplicate(static_cast(source.clone())); + std::unique_ptr duplicate(source.clone()); // Reverse the chain so each assignment needs another pruning wave. for (int lower = 3; lower >= 1; lower--) source.list.append(source, IntVar(source, lower, lower + 1)); @@ -1247,7 +1247,7 @@ namespace Test::Int::OpenList { EmptyDistinctSpace source(Gecode::Int::Limits::max, ipl); if (source.status() != SS_SOLVED) return false; - std::unique_ptr duplicate(static_cast(source.clone())); + std::unique_ptr duplicate(source.clone()); source.list.append(source, IntVar(source, 1, 1)); source.list.append(source, IntVar(source, 0, 1)); if ((source.status() == SS_FAILED) || !source.list[1].assigned() || (source.list[1].val() != 0)) @@ -1361,7 +1361,7 @@ namespace Test::Int::OpenList { delete source; return false; } - CallbackSpace* clone = static_cast(source->clone()); + CallbackSpace* clone = source->clone(); delete source; const bool retained = (domain.use_count() > 1) && (transition.use_count() > 1); delete clone; @@ -1512,7 +1512,7 @@ namespace Test::Int::OpenList { const Choice* choice = source.choice(); bool valid = true; for (unsigned int alternative = 0; alternative < 2; alternative++) { - CallbackSpace* clone = static_cast(source.clone()); + CallbackSpace* clone = source.clone(); rel(*clone, clone->list.length(), IRT_GQ, 2); clone->commit(*choice, alternative); valid &= !clone->failed() && (clone->list.known_length() == 1) && clone->list[0].assigned() && @@ -1546,7 +1546,7 @@ namespace Test::Int::OpenList { if (source.status() != SS_BRANCH) return false; std::unique_ptr first(source.choice()); - std::unique_ptr replay(static_cast(source.clone())); + std::unique_ptr replay(source.clone()); source.commit(*first, 0); if ((source.status() != SS_BRANCH) || (source.list.known_length() != 2)) return false; @@ -1701,7 +1701,7 @@ namespace Test::Int::OpenList { rel(source, source.list[0], IRT_EQ, 1); if (source.status() == SS_FAILED) return false; - std::unique_ptr clone(static_cast(source.clone())); + std::unique_ptr clone(source.clone()); clone->list.materialize(*clone, 2); rel(*clone, clone->list[1], IRT_EQ, 1); if ((clone->status() == SS_FAILED) || !clone->list.length().assigned() || @@ -1720,7 +1720,7 @@ namespace Test::Int::OpenList { rel(later, later.list[1], IRT_EQ, 2); if ((later.status() == SS_FAILED) || later.list[0].assigned()) return false; - std::unique_ptr invalid(static_cast(later.clone())); + std::unique_ptr invalid(later.clone()); rel(*invalid, invalid->list[0], IRT_EQ, 2); if (invalid->status() != SS_FAILED) return false; diff --git a/test/random.cpp b/test/random.cpp index e25823d456..b2323bfab8 100644 --- a/test/random.cpp +++ b/test/random.cpp @@ -334,13 +334,13 @@ namespace Test::Random { archive_replay(Model& root) { using namespace Gecode; while (root.status() == SS_BRANCH) { - std::unique_ptr before(static_cast(root.clone())); + std::unique_ptr before(root.clone()); std::unique_ptr choice(root.choice()); if (!owners_agree(root, *before)) return false; for (unsigned int a = choice->alternatives(); a--;) { - std::unique_ptr direct(static_cast(root.clone())); - std::unique_ptr replay(static_cast(before->clone())); + std::unique_ptr direct(root.clone()); + std::unique_ptr replay(before->clone()); Archive archive; choice->archive(archive); std::unique_ptr restored(replay->choice(archive)); @@ -613,9 +613,9 @@ namespace Test::Random { Permutation root(Rnd(3)); if (root.status() != SS_BRANCH) return false; - std::unique_ptr asset(static_cast(root.clone())); + std::unique_ptr asset(root.clone()); asset->random_split(spoke_context(MetaEngine::Portfolio, 0, 1)); - std::unique_ptr restart(static_cast(root.clone())); + std::unique_ptr restart(root.clone()); restart->random_split(spoke_context(MetaEngine::Restart, 1, 0)); return first_solutions(*asset, 1) != first_solutions(*restart, 1); } @@ -627,10 +627,10 @@ namespace Test::Random { Permutation root(Rnd(3)); if (root.status() != SS_BRANCH) return false; - std::unique_ptr first(static_cast(root.clone())); + std::unique_ptr first(root.clone()); first->random_split(spoke_context(MetaEngine::Portfolio, 0, 0)); first->random_split(spoke_context(MetaEngine::Portfolio, 0, 1)); - std::unique_ptr second(static_cast(root.clone())); + std::unique_ptr second(root.clone()); second->random_split(spoke_context(MetaEngine::Portfolio, 0, 1)); second->random_split(spoke_context(MetaEngine::Portfolio, 0, 0)); return first_solutions(*first, 1) != first_solutions(*second, 1); diff --git a/test/region.cpp b/test/region.cpp index 2249cd06a1..8f35bb5102 100644 --- a/test/region.cpp +++ b/test/region.cpp @@ -33,6 +33,9 @@ #include #include +#include +#include + #include "test/test.hh" namespace Test { @@ -79,6 +82,85 @@ namespace Test { } }; + /// Space class that reaches Space through a virtual base + class VirtualBase : public virtual Gecode::Space { + public: + /// Initialize space + VirtualBase() = default; + /// Constructor for cloning \a s + // NOLINTNEXTLINE(modernize-use-equals-default) + VirtualBase(VirtualBase& s) : Gecode::Space(s) {} + }; + + /// Space derived from Space through a virtual base + class VirtualSpace : public VirtualBase { + public: + /// A value to check that cloning copies the space + int value = 0; + /// Initialize space + VirtualSpace() = default; + /// Constructor for cloning \a s + VirtualSpace(VirtualSpace& s) : Gecode::Space(s), VirtualBase(s), value(s.value) {} + /// Copy space during cloning + Gecode::Space* + copy() override { + return new VirtualSpace(*this); + } + }; + + /// Polymorphic base class without a usable address-of operator + class NoAddressBase { + public: + /// Destructor + virtual ~NoAddressBase() = default; + /// Unusable address-of operator + void operator&() const = delete; + }; + + /// Class derived from a base class without address-of operator + class NoAddressDerived : public NoAddressBase { + public: + /// A value to check the cast + int value = 3; + }; + + /// %Test that cloning returns the static type of the cloned space + class SpaceCloneTyped : public Test::Base { + public: + /// Initialize test + SpaceCloneTyped() : Test::Base("Space::Clone::Typed") {} + /// Cast a reference whose type has no usable address-of operator + static bool + no_address_cast() { + NoAddressDerived derived; + const NoAddressBase& base = derived; + return Gecode::down_cast(base).value == 3; + } + /// Perform actual tests + bool + run() override { + using namespace Gecode; + EmptySpace home; + const Space& erased_home = home; + static_assert(std::is_same_v); + static_assert(std::is_same_v); + const std::unique_ptr typed(home.clone()); + const std::unique_ptr erased(erased_home.clone()); + + VirtualSpace virtual_home; + virtual_home.value = 7; + const Space& erased_virtual = virtual_home; + const std::unique_ptr virtual_typed(virtual_home.clone()); + const std::unique_ptr virtual_erased(erased_virtual.clone()); + + return (dynamic_cast(erased.get()) != nullptr) && (virtual_typed->value == 7) && + (down_cast(*virtual_erased).value == 7) && + (down_cast(static_cast(nullptr)) == nullptr) && no_address_cast(); + } + }; + + SpaceCloneTyped space_clone_typed; + /// %Test for growing space memory from an empty block class SpaceReallocEmpty : public Test::Base { public: diff --git a/test/search.cpp b/test/search.cpp index 33bc6a993b..7ccef9ae8b 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -2178,7 +2178,7 @@ namespace Test::Search { #endif UnsupportedObjective unsupported; - UnsupportedObjective* um = static_cast(unsupported.clone()); + UnsupportedObjective* um = unsupported.clone(); Gecode::Search::Engine* missing = Gecode::Search::make_bab_engine(um, Gecode::Search::Options()); delete um; missing->constrain(unsupported); @@ -3973,6 +3973,53 @@ namespace Test::Search { PBSBuilderStop pbs_builder_stop; + /// Both portfolio constructors accept a model whose clone() hides Space::clone + class PBSHiddenClone : public Base { + /// Model whose own clone() returns a Space* + class Model : public SolveImmediate { + public: + /// Constructor for space creation + Model() : SolveImmediate(HTB_NONE, HTB_NONE, HTB_NONE) {} + /// Constructor for cloning \a s + // NOLINTNEXTLINE(modernize-use-equals-default) + Model(Model& s) : SolveImmediate(s) {} + /// Copy during cloning + Space* + copy() override { + return new Model(*this); + } + /// Clone as a Space, hiding the typed Space::clone + Space* + clone() const { + return Space::clone(); + } + }; + /// Return whether \a pbs finds a solution + static bool + solves(Gecode::PBS& pbs) { + const std::unique_ptr s(pbs.next()); + return s != nullptr; + } + + public: + PBSHiddenClone() : Base("Search::PBS::HiddenClone") {} + bool + run() override { + Model root; + Gecode::Search::Options o; + o.assets = 2; + o.threads = 1; + Gecode::PBS assets(&root, o); + Gecode::SEBs sebs(2); + sebs[0] = Gecode::dfs(); + sebs[1] = Gecode::dfs(); + Gecode::PBS builders(&root, sebs, o); + return solves(assets) && solves(builders); + } + }; + + PBSHiddenClone pbs_hidden_clone; + /// An exhausted asset ends a portfolio whose other asset never ends class PBSExhaustedAsset : public Base { /// Stop after many checks, in case the portfolio does not end diff --git a/test/set.cpp b/test/set.cpp index 4d58feb236..19013f5311 100644 --- a/test/set.cpp +++ b/test/set.cpp @@ -359,7 +359,7 @@ namespace Test::Set { SetTestSpace::check_fixpoint() { if (failed()) return true; - SetTestSpace* c = static_cast(clone()); + SetTestSpace* c = clone(); if (opt.log) olog << ind(3) << "Testing fixpoint on copy" << '\n'; c->post(); @@ -752,7 +752,7 @@ namespace Test::Set { if (opt.log) olog << ind(3) << "Copy" << '\n'; if (s->status() != Gecode::SS_FAILED) { - sc = static_cast(s->clone()); + sc = s->clone(); } else { sc = s; s = nullptr;