graph.hh 36.5 KB
Newer Older
1
// -*- coding: utf-8 -*-
Maximilien Colange's avatar
Maximilien Colange committed
2
// Copyright (C) 2014-2018 Laboratoire de Recherche et
3
// Développement de l'Epita.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//
// This file is part of Spot, a model checking library.
//
// Spot is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Spot is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

20
#pragma once
21

22
#include <spot/misc/common.hh>
23 24 25
#include <vector>
#include <type_traits>
#include <tuple>
26
#include <cassert>
27
#include <iterator>
28
#include <algorithm>
29
#include <map>
30
#include <iostream>
31 32 33

namespace spot
{
34
  template <typename State_Data, typename Edge_Data>
35
  class SPOT_API digraph;
36 37 38

  namespace internal
  {
39
#ifndef SWIG
40 41 42 43 44 45 46 47 48 49
    template <typename Of, typename ...Args>
    struct first_is_base_of
    {
      static const bool value = false;
    };

    template <typename Of, typename Arg1, typename ...Args>
    struct first_is_base_of<Of, Arg1, Args...>
    {
      static const bool value =
50
        std::is_base_of<Of, typename std::decay<Arg1>::type>::value;
51
    };
52
#endif
53

54 55 56 57 58 59 60
    // The boxed_label class stores Data as an attribute called
    // "label" if boxed is true.  It is an empty class if Data is
    // void, and it simply inherits from Data if boxed is false.
    //
    // The data() method offers an homogeneous access to the Data
    // instance.
    template <typename Data, bool boxed = !std::is_class<Data>::value>
61
    struct SPOT_API boxed_label
62
    {
63
      typedef Data data_t;
64 65
      Data label;

66
#ifndef SWIG
67
      template <typename... Args,
68 69 70 71 72
                typename = typename std::enable_if<
                  !first_is_base_of<boxed_label, Args...>::value>::type>
        boxed_label(Args&&... args)
        noexcept(std::is_nothrow_constructible<Data, Args...>::value)
        : label{std::forward<Args>(args)...}
73 74
      {
      }
75
#endif
76 77 78 79

      // if Data is a POD type, G++ 4.8.2 wants default values for all
      // label fields unless we define this default constructor here.
      explicit boxed_label()
80
        noexcept(std::is_nothrow_constructible<Data>::value)
81 82 83 84 85
      {
      }

      Data& data()
      {
86
        return label;
87 88 89 90
      }

      const Data& data() const
      {
91
        return label;
92
      }
93 94 95

      bool operator<(const boxed_label& other) const
      {
96
        return label < other.label;
97
      }
98 99 100
    };

    template <>
101
    struct SPOT_API boxed_label<void, true>: public std::tuple<>
102
    {
103 104 105
      typedef std::tuple<> data_t;
      std::tuple<>& data()
      {
106
        return *this;
107 108 109 110
      }

      const std::tuple<>& data() const
      {
111
        return *this;
112 113
      }

114 115 116
    };

    template <typename Data>
117
    struct SPOT_API boxed_label<Data, false>: public Data
118
    {
119 120
      typedef Data data_t;

121
#ifndef SWIG
122
      template <typename... Args,
123 124 125 126 127
                typename = typename std::enable_if<
                  !first_is_base_of<boxed_label, Args...>::value>::type>
        boxed_label(Args&&... args)
        noexcept(std::is_nothrow_constructible<Data, Args...>::value)
        : Data{std::forward<Args>(args)...}
128 129
      {
      }
130
#endif
131

132
      // if Data is a POD type, G++ 4.8.2 wants default values for all
133 134
      // label fields unless we define this default constructor here.
      explicit boxed_label()
135
        noexcept(std::is_nothrow_constructible<Data>::value)
136 137 138 139 140
      {
      }

      Data& data()
      {
141
        return *this;
142 143 144 145
      }

      const Data& data() const
      {
146
        return *this;
147 148 149 150 151 152 153 154 155 156
      }
    };

    //////////////////////////////////////////////////
    // State storage for digraphs
    //////////////////////////////////////////////////

    // We have two implementations, one with attached State_Data, and
    // one without.

157
    template <typename Edge, typename State_Data>
158
    struct SPOT_API distate_storage final: public State_Data
159
    {
160
      Edge succ = 0; // First outgoing edge (used when iterating)
161 162
      Edge succ_tail = 0;        // Last outgoing edge (used for
                                // appending new edges)
163
#ifndef SWIG
164
      template <typename... Args,
165 166
                typename = typename std::enable_if<
                  !first_is_base_of<distate_storage, Args...>::value>::type>
167
      distate_storage(Args&&... args)
168 169
        noexcept(std::is_nothrow_constructible<State_Data, Args...>::value)
        : State_Data{std::forward<Args>(args)...}
170 171
      {
      }
172
#endif
173 174 175
    };

    //////////////////////////////////////////////////
176
    // Edge storage
177 178 179 180
    //////////////////////////////////////////////////

    // Again two implementation: one with label, and one without.

181
    template <typename StateIn,
182
              typename StateOut, typename Edge, typename Edge_Data>
183
    struct SPOT_API edge_storage final: public Edge_Data
184
    {
185
      typedef Edge edge;
186

187 188 189 190
      StateOut dst;                // destination
      Edge next_succ;        // next outgoing edge with same
                                // source, or 0
      StateIn src;                // source
191

192
      explicit edge_storage()
193 194
        noexcept(std::is_nothrow_constructible<Edge_Data>::value)
        : Edge_Data{}
195 196 197
      {
      }

198
#ifndef SWIG
199
      template <typename... Args>
200
      edge_storage(StateOut dst, Edge next_succ,
201 202 203 204 205 206
                    StateIn src, Args&&... args)
        noexcept(std::is_nothrow_constructible<Edge_Data, Args...>::value
                 && std::is_nothrow_constructible<StateOut, StateOut>::value
                 && std::is_nothrow_constructible<Edge, Edge>::value)
        : Edge_Data{std::forward<Args>(args)...},
        dst(dst), next_succ(next_succ), src(src)
207 208
      {
      }
209
#endif
210

211
      bool operator<(const edge_storage& other) const
212
      {
213 214 215 216 217 218 219 220 221 222
        if (src < other.src)
          return true;
        if (src > other.src)
          return false;
        // This might be costly if the destination is a vector
        if (dst < other.dst)
          return true;
        if (dst > other.dst)
          return false;
        return this->data() < other.data();
223
      }
224

225
      bool operator==(const edge_storage& other) const
226 227 228 229 230
      {
        return src == other.src &&
          dst == other.dst &&
          this->data() == other.data();
      }
231 232 233
    };

    //////////////////////////////////////////////////
234
    // Edge iterator
235 236
    //////////////////////////////////////////////////

237 238
    // This holds a graph and a edge number that is the start of
    // a list, and it iterates over all the edge_storage_t elements
239 240 241
    // of that list.

    template <typename Graph>
242
    class SPOT_API edge_iterator
243 244
    {
    public:
245 246 247 248 249 250 251 252 253
      typedef typename std::conditional<std::is_const<Graph>::value,
                                        const typename Graph::edge_storage_t,
                                        typename Graph::edge_storage_t>::type
        value_type;
      typedef value_type& reference;
      typedef value_type* pointer;
      typedef std::ptrdiff_t difference_type;
      typedef std::forward_iterator_tag iterator_category;

254
      typedef typename Graph::edge edge;
255

256
      edge_iterator() noexcept
257
        : g_(nullptr), t_(0)
258 259 260
      {
      }

261
      edge_iterator(Graph* g, edge t) noexcept
262
        : g_(g), t_(t)
263 264 265
      {
      }

266
      bool operator==(edge_iterator o) const
267
      {
268
        return t_ == o.t_;
269 270
      }

271
      bool operator!=(edge_iterator o) const
272
      {
273
        return t_ != o.t_;
274 275
      }

276
      reference operator*() const
277
      {
278
        return g_->edge_storage(t_);
279 280
      }

281
      pointer      operator->() const
282
      {
283
        return &g_->edge_storage(t_);
284 285
      }

286
      edge_iterator operator++()
287
      {
288 289
        t_ = operator*().next_succ;
        return *this;
290 291
      }

292
      edge_iterator operator++(int)
293
      {
294 295 296
        edge_iterator ti = *this;
        t_ = operator*().next_succ;
        return ti;
297 298
      }

299 300
      operator bool() const
      {
301
        return t_;
302 303
      }

304
      edge trans() const
305
      {
306
        return t_;
307 308
      }

309 310
    protected:
      Graph* g_;
311
      edge t_;
312 313
    };

314
    template <typename Graph>
315
    class SPOT_API killer_edge_iterator: public edge_iterator<Graph>
316
    {
317
      typedef edge_iterator<Graph> super;
318 319
    public:
      typedef typename Graph::state_storage_t state_storage_t;
320
      typedef typename Graph::edge edge;
321

322
      killer_edge_iterator(Graph* g, edge t, state_storage_t& src) noexcept
323
        : super(g, t), src_(src), prev_(0)
324 325 326
      {
      }

327
      killer_edge_iterator operator++()
328
      {
329 330 331
        prev_ = this->t_;
        this->t_ = this->operator*().next_succ;
        return *this;
332 333
      }

334
      killer_edge_iterator operator++(int)
335
      {
336 337 338
        killer_edge_iterator ti = *this;
        ++*this;
        return ti;
339 340
      }

341
      // Erase the current edge and advance the iterator.
342 343
      void erase()
      {
344
        edge next = this->operator*().next_succ;
345

346 347 348 349 350 351 352 353 354 355 356 357 358
        // Update source state and previous edges
        if (prev_)
          {
            this->g_->edge_storage(prev_).next_succ = next;
          }
        else
          {
            if (src_.succ == this->t_)
              src_.succ = next;
          }
        if (src_.succ_tail == this->t_)
          {
            src_.succ_tail = prev_;
359
            SPOT_ASSERT(next == 0);
360
          }
361

362 363
        // Erased edges have themselves as next_succ.
        this->operator*().next_succ = this->t_;
364

365 366
        // Advance iterator to next edge.
        this->t_ = next;
367

368
        ++this->g_->killed_edge_;
369 370 371 372
      }

    protected:
      state_storage_t& src_;
373
      edge prev_;
374 375 376
    };


377 378 379 380
    //////////////////////////////////////////////////
    // State OUT
    //////////////////////////////////////////////////

381
    // Fake container listing the outgoing edges of a state.
382 383

    template <typename Graph>
384
    class SPOT_API state_out
385 386
    {
    public:
387
      typedef typename Graph::edge edge;
388
      state_out(Graph* g, edge t) noexcept
389
        : g_(g), t_(t)
390 391 392
      {
      }

393
      edge_iterator<Graph> begin() const
394
      {
395
        return {g_, t_};
396 397
      }

398
      edge_iterator<Graph> end() const
399
      {
400
        return {};
401 402
      }

403
      void recycle(edge t)
404
      {
405
        t_ = t;
406 407
      }

408 409
    protected:
      Graph* g_;
410
      edge t_;
411 412
    };

413 414 415 416 417
    //////////////////////////////////////////////////
    // all_trans
    //////////////////////////////////////////////////

    template <typename Graph>
418
    class SPOT_API all_edge_iterator
419
    {
420 421 422 423 424 425 426 427 428
    public:
      typedef typename std::conditional<std::is_const<Graph>::value,
                                        const typename Graph::edge_storage_t,
                                        typename Graph::edge_storage_t>::type
        value_type;
      typedef value_type& reference;
      typedef value_type* pointer;
      typedef std::ptrdiff_t difference_type;
      typedef std::forward_iterator_tag iterator_category;
429

430
    protected:
431
      typedef typename std::conditional<std::is_const<Graph>::value,
432 433 434
                                        const typename Graph::edge_vector_t,
                                        typename Graph::edge_vector_t>::type
        tv_t;
435 436 437 438 439 440

      unsigned t_;
      tv_t& tv_;

      void skip_()
      {
441 442 443 444
        unsigned s = tv_.size();
        do
          ++t_;
        while (t_ < s && tv_[t_].next_succ == t_);
445 446 447
      }

    public:
448
      all_edge_iterator(unsigned pos, tv_t& tv) noexcept
449
        : t_(pos), tv_(tv)
450
      {
451
        skip_();
452 453
      }

454
      all_edge_iterator(tv_t& tv) noexcept
455
        : t_(tv.size()), tv_(tv)
456 457 458
      {
      }

459
      all_edge_iterator& operator++()
460
      {
461 462
        skip_();
        return *this;
463 464
      }

465
      all_edge_iterator operator++(int)
466
      {
467 468 469
        all_edge_iterator old = *this;
        ++*this;
        return old;
470 471
      }

472
      bool operator==(all_edge_iterator o) const
473
      {
474
        return t_ == o.t_;
475 476
      }

477
      bool operator!=(all_edge_iterator o) const
478
      {
479
        return t_ != o.t_;
480 481
      }

482
      reference operator*() const
483
      {
484
        return tv_[t_];
485 486
      }

487
      pointer operator->() const
488
      {
489
        return &tv_[t_];
490
      }
491 492 493 494 495 496
    };


    template <typename Graph>
    class SPOT_API all_trans
    {
497
    public:
498
      typedef typename std::conditional<std::is_const<Graph>::value,
499 500 501
                                        const typename Graph::edge_vector_t,
                                        typename Graph::edge_vector_t>::type
        tv_t;
502
      typedef all_edge_iterator<Graph> iter_t;
503
    private:
504 505 506
      tv_t& tv_;
    public:

507
      all_trans(tv_t& tv) noexcept
508
        : tv_(tv)
509 510 511
      {
      }

512
      iter_t begin() const
513
      {
514
        return {0, tv_};
515 516
      }

517
      iter_t end() const
518
      {
519
        return {tv_};
520 521 522
      }
    };

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
    class SPOT_API const_universal_dests
    {
    private:
      const unsigned* begin_;
      const unsigned* end_;
      unsigned tmp_;
    public:
      const_universal_dests(const unsigned* begin, const unsigned* end) noexcept
        : begin_(begin), end_(end)
      {
      }

      const_universal_dests(unsigned state) noexcept
        : begin_(&tmp_), end_(&tmp_ + 1), tmp_(state)
      {
      }

      const unsigned* begin() const
      {
        return begin_;
      }

      const unsigned* end() const
      {
        return end_;
      }
    };
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576

    template<class G>
    class univ_dest_mapper
    {
      std::map<std::vector<unsigned>, unsigned> uniq_;
      G& g_;
    public:

      univ_dest_mapper(G& graph)
        : g_(graph)
      {
      }

      template<class I>
      unsigned new_univ_dests(I begin, I end)
      {
        std::vector<unsigned> tmp(begin, end);
        std::sort(tmp.begin(), tmp.end());
        tmp.erase(std::unique(tmp.begin(), tmp.end()), tmp.end());
        auto p = uniq_.emplace(tmp, 0);
        if (p.second)
          p.first->second = g_.new_univ_dests(tmp.begin(), tmp.end());
        return p.first->second;
      }

    };

577
  } // namespace internal
578

579

580 581 582 583
  /// \brief A directed graph
  ///
  /// \tparam State_Data data to attach to states
  /// \tparam Edge_Data data to attach to edges
584
  template <typename State_Data, typename Edge_Data>
585 586
  class digraph
  {
587 588 589
    friend class internal::edge_iterator<digraph>;
    friend class internal::edge_iterator<const digraph>;
    friend class internal::killer_edge_iterator<digraph>;
590

591
  public:
592 593
    typedef internal::edge_iterator<digraph> iterator;
    typedef internal::edge_iterator<const digraph> const_iterator;
594

595
    // Extra data to store on each state or edge.
596
    typedef State_Data state_data_t;
597
    typedef Edge_Data edge_data_t;
598

599
    // State and edges are identified by their indices in some
600 601
    // vector.
    typedef unsigned state;
602
    typedef unsigned edge;
603

604
    typedef internal::distate_storage<edge,
605
                                      internal::boxed_label<State_Data>>
606
      state_storage_t;
607 608
    typedef internal::edge_storage<state, state, edge,
                                   internal::boxed_label<Edge_Data>>
609
      edge_storage_t;
610
    typedef std::vector<state_storage_t> state_vector;
611
    typedef std::vector<edge_storage_t> edge_vector_t;
612 613 614 615 616

    // A sequence of universal destination groups of the form:
    //   (n state_1 state_2 ... state_n)*
    typedef std::vector<unsigned> dests_vector_t;

617 618
  protected:
    state_vector states_;
619
    edge_vector_t edges_;
620
    dests_vector_t dests_;      // Only used by alternating automata.
621 622
    // Number of erased edges.
    unsigned killed_edge_;
623
  public:
624
    /// \brief Construct an empty graph
625 626
    ///
    /// Construct an empty graph, and reserve space for \a max_states
627
    /// states and \a max_trans edges.  These are not hard
628 629 630
    /// limits, but just hints to pre-allocate a data structure that
    /// may hold that much items.
    digraph(unsigned max_states = 10, unsigned max_trans = 0)
631
      : killed_edge_(0)
632 633 634
    {
      states_.reserve(max_states);
      if (max_trans == 0)
635
        max_trans = max_states * 2;
636 637 638 639 640 641
      edges_.reserve(max_trans + 1);
      // Edge number 0 is not used, because we use this index
      // to mark the absence of a edge.
      edges_.resize(1);
      // This causes edge 0 to be considered as dead.
      edges_[0].next_succ = 0;
642 643
    }

644
    /// The number of states in the automaton
645 646 647 648 649
    unsigned num_states() const
    {
      return states_.size();
    }

650 651 652
    /// \brief The number of edges in the automaton
    ///
    /// Killed edges are omitted.
653
    unsigned num_edges() const
654
    {
655
      return edges_.size() - killed_edge_ - 1;
656 657
    }

658 659 660 661 662 663 664 665 666 667 668 669
    /// Whether the automaton uses only existential branching.
    bool is_existential() const
    {
      return dests_.empty();
    }

#ifndef SWIG
    /// \brief Whether the automaton has universal branching
    ///
    /// The name of this function is confusing since non-deterministic
    /// automata should be a subclass of alternating automata.
    SPOT_DEPRECATED("use !is_existential() instead")
670 671
    bool is_alternating() const
    {
672
      return !is_existential();
673
    }
674
#endif
675

676 677 678 679 680
    /// \brief Create a new states
    ///
    /// All arguments are forwarded to the State_Data constructor.
    ///
    /// \return a state number
681 682 683 684 685 686 687 688
    template <typename... Args>
    state new_state(Args&&... args)
    {
      state s = states_.size();
      states_.emplace_back(std::forward<Args>(args)...);
      return s;
    }

689 690 691 692 693 694
    /// \brief Create n new states
    ///
    /// All arguments are forwarded to the State_Data constructor of
    /// each of the n states.
    ///
    /// \return the first state number
695 696 697 698
    template <typename... Args>
    state new_states(unsigned n, Args&&... args)
    {
      state s = states_.size();
699
      states_.reserve(s + n);
700
      while (n--)
701
        states_.emplace_back(std::forward<Args>(args)...);
702 703 704
      return s;
    }

705 706 707 708 709
    /// @{
    /// \brief return a reference to the storage of a state
    ///
    /// The storage includes any of the user-supplied State_Data, plus
    /// some custom fields needed to find the outgoing transitions.
710 711 712 713 714 715 716 717 718 719 720
    state_storage_t&
    state_storage(state s)
    {
      return states_[s];
    }

    const state_storage_t&
    state_storage(state s) const
    {
      return states_[s];
    }
721
    ///@}
722

723 724 725 726 727
    ///@{
    /// \brief return the State_Data associated to a state
    ///
    /// This does not use State_Data& as return type, because
    /// State_Data might be void.
728
    typename state_storage_t::data_t&
729 730 731 732 733
    state_data(state s)
    {
      return states_[s].data();
    }

734
    const typename state_storage_t::data_t&
735 736 737 738
    state_data(state s) const
    {
      return states_[s].data();
    }
739
    ///@}
740

741 742 743 744 745
    ///@{
    /// \brief return a reference to the storage of an edge
    ///
    /// The storage includes any of the user-supplied Edge_Data, plus
    /// some custom fields needed to find the next transitions.
746 747
    edge_storage_t&
    edge_storage(edge s)
748
    {
749
      return edges_[s];
750 751
    }

752 753
    const edge_storage_t&
    edge_storage(edge s) const
754
    {
755
      return edges_[s];
756
    }
757
    ///@}
758

759 760 761 762 763
    ///@{
    /// \brief return the Edgeg_Data of an edge.
    ///
    /// This does not use Edge_Data& as return type, because
    /// Edge_Data might be void.
764 765
    typename edge_storage_t::data_t&
    edge_data(edge s)
766
    {
767
      return edges_[s].data();
768 769
    }

770 771
    const typename edge_storage_t::data_t&
    edge_data(edge s) const
772
    {
773
      return edges_[s].data();
774
    }
775
    ///@}
776

777 778 779 780 781
    /// \brief Create a new edge
    ///
    /// \param src the source state
    /// \param dst the destination state
    /// \param args arguments to forward to the Edge_Data constructor
782
    template <typename... Args>
783
    edge
784
    new_edge(state src, state dst, Args&&... args)
785
    {
786 787
      edge t = edges_.size();
      edges_.emplace_back(dst, 0, src, std::forward<Args>(args)...);
788

789
      edge st = states_[src].succ_tail;
790
      SPOT_ASSERT(st < t || !st);
791
      if (!st)
792
        states_[src].succ = t;
793
      else
794
        edges_[st].next_succ = t;
795 796 797 798
      states_[src].succ_tail = t;
      return t;
    }

799 800 801 802
    /// \brief Create a new universal destination group
    ///
    /// The resulting state number can be used as the destination of
    /// an edge.
803 804 805
    ///
    /// \param dst_begin start of a non-empty container of destination states
    /// \param dst_end end of a non-empty container of destination states
806 807 808
    template <typename I>
    state
    new_univ_dests(I dst_begin, I dst_end)
809 810 811
    {
      unsigned sz = std::distance(dst_begin, dst_end);
      if (sz == 1)
812
        return *dst_begin;
813 814 815 816
      SPOT_ASSERT(sz > 1);
      unsigned d = dests_.size();
      dests_.emplace_back(sz);
      dests_.insert(dests_.end(), dst_begin, dst_end);
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
      return ~d;
    }

    /// \brief Create a new universal edge
    ///
    /// \param src the source state
    /// \param dst_begin start of a non-empty container of destination states
    /// \param dst_end end of a non-empty container of destination states
    /// \param args arguments to forward to the Edge_Data constructor
    template <typename I, typename... Args>
    edge
    new_univ_edge(state src, I dst_begin, I dst_end, Args&&... args)
    {
      return new_edge(src, new_univ_dests(dst_begin, dst_end),
                      std::forward<Args>(args)...);
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
    }

    /// \brief Create a new universal edge
    ///
    /// \param src the source state
    /// \param dsts a non-empty list of destination states
    /// \param args arguments to forward to the Edge_Data constructor
    template <typename... Args>
    edge
    new_univ_edge(state src, const std::initializer_list<state>& dsts,
                  Args&&... args)
    {
      return new_univ_edge(src, dsts.begin(), dsts.end(),
                           std::forward<Args>(args)...);
    }

    internal::const_universal_dests univ_dests(state src) const
    {
      if ((int)src < 0)
        {
          unsigned pos = ~src;
          const unsigned* d = dests_.data();
          d += pos;
          unsigned num = *d;
          return { d + 1, d + num + 1 };
        }
      else
        {
          return src;
        }
    }

    internal::const_universal_dests univ_dests(const edge_storage_t& e) const
    {
      return univ_dests(e.dst);
    }

869
    /// Convert a storage reference into a state number
870
    state index_of_state(const state_storage_t& ss) const
871
    {
872
      SPOT_ASSERT(!states_.empty());
873 874 875
      return &ss - &states_.front();
    }

876
    /// Conveart a storage reference into an edge number
877
    edge index_of_edge(const edge_storage_t& tt) const
878
    {
879
      SPOT_ASSERT(!edges_.empty());
880
      return &tt - &edges_.front();
881 882
    }

883 884
    /// @{
    /// \brief Return a fake container with all edges leaving \a src
885 886 887 888 889 890
    internal::state_out<digraph>
    out(state src)
    {
      return {this, states_[src].succ};
    }

891 892 893 894 895 896
    internal::state_out<digraph>
    out(state_storage_t& src)
    {
      return out(index_of_state(src));
    }

897 898 899 900 901 902
    internal::state_out<const digraph>
    out(state src) const
    {
      return {this, states_[src].succ};
    }

903 904
    internal::state_out<const digraph>
    out(state_storage_t& src) const
905
    {
906
      return out(index_of_state(src));
907
    }
908
    /// @}
909

910 911 912 913
    /// @{
    ///
    /// \brief Return a fake container with all edges leaving \a src,
    /// allowing erasure.
914
    internal::killer_edge_iterator<digraph>
915
    out_iteraser(state_storage_t& src)
916
    {
917 918 919
      return {this, src.succ, src};
    }

920
    internal::killer_edge_iterator<digraph>
921 922 923
    out_iteraser(state src)
    {
      return out_iteraser(state_storage(src));
924
    }
925
    ///@}
926

927 928 929
    /// @{
    ///
    /// \brief Return the vector of states.
930 931 932 933 934 935 936 937 938
    const state_vector& states() const
    {
      return states_;
    }

    state_vector& states()
    {
      return states_;
    }
939
    /// @}
940

941 942 943 944
    /// @{
    ///
    /// \brief Return a fake container with all edges (exluding erased
    /// edges)
945
    internal::all_trans<const digraph> edges() const
946
    {
947
      return edges_;
948 949
    }

950
    internal::all_trans<digraph> edges()
951
    {
952
      return edges_;
953
    }
954
    /// @}
955

956 957 958 959 960 961 962 963
    /// @{
    /// \brief Return the vector of all edges.
    ///
    /// When using this method, beware that the first entry (edge #0)
    /// is not a real edge, and that any edge with next_succ pointing
    /// to itself is an erased edge.
    ///
    /// You should probably use edges() instead.
964
    const edge_vector_t& edge_vector() const
965
    {
966
      return edges_;
967 968
    }

969
    edge_vector_t& edge_vector()
970
    {
971
      return edges_;
972
    }
973
    /// @}
974

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
    /// \brief Test whether the given edge is valid.
    ///
    /// An edge is valid if its number is less than the total number
    /// of edges, and it does not correspond to an erased (dead) edge.
    ///
    /// \see is_dead_edge()
    bool is_valid_edge(edge t) const
    {
      // Erased edges have their next_succ pointing to
      // themselves.
      return (t < edges_.size() &&
              edges_[t].next_succ != t);
    }

    /// @{
    /// \brief Tests whether an edge has been erased.
    ///
    /// \see is_valid_edge
993
    bool is_dead_edge(unsigned t) const
994
    {
995
      return edges_[t].next_succ == t;
996 997
    }

998
    bool is_dead_edge(const edge_storage_t& t) const
999
    {
1000
      return t.next_succ == index_of_edge(t);
1001
    }
1002
    /// @}
1003

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    /// @{
    /// \brief The vector used to store universal destinations.
    ///
    /// The actual way those destinations are stored is an
    /// implementation detail you should not rely on.
    const dests_vector_t& dests_vector() const
    {
      return dests_;
    }

    dests_vector_t& dests_vector()
    {
      return dests_;
    }
    /// @}
1019

1020
    /// Dump the state and edge storage for debugging
1021 1022
    void dump_storage(std::ostream& o) const
    {
1023
      unsigned tend = edges_.size();
1024
      for (unsigned t = 1; t < tend; ++t)
1025 1026
        {
          o << 't' << t << ": (s"
1027 1028 1029 1030 1031 1032 1033
            << edges_[t].src << ", ";
          int d = edges_[t].dst;
          if (d < 0)
            o << 'd' << ~d;
          else
            o << 's' << d;
          o << ") t" << edges_[t].next_succ << '\n';
1034
        }
1035 1036
      unsigned send = states_.size();
      for (unsigned s = 0; s < send; ++s)
1037 1038 1039 1040 1041
        {
          o << 's' << s << ": t"
            << states_[s].succ << " t"
            << states_[s].succ_tail << '\n';
        }
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
      unsigned dend = dests_.size();
      unsigned size = 0;
      for (unsigned s = 0; s < dend; ++s)
        {
          o << 'd' << s << ": ";
          if (size == 0)
            {
              o << '#';
              size = dests_[s];
            }
          else
            {
              o << 's';
              --size;
            }
          o << dests_[s] << '\n';
        }
1059
    }
1060

1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
    enum dump_storage_items {
      DSI_GraphHeader = 1,
      DSI_GraphFooter = 2,
      DSI_StatesHeader = 4,
      DSI_StatesBody = 8,
      DSI_StatesFooter = 16,
      DSI_States = DSI_StatesHeader | DSI_StatesBody | DSI_StatesFooter,
      DSI_EdgesHeader = 32,
      DSI_EdgesBody = 64,
      DSI_EdgesFooter = 128,
      DSI_Edges = DSI_EdgesHeader | DSI_EdgesBody | DSI_EdgesFooter,
      DSI_DestsHeader = 256,
      DSI_DestsBody = 512,
      DSI_DestsFooter = 1024,
      DSI_Dests = DSI_DestsHeader | DSI_DestsBody | DSI_DestsFooter,
      DSI_All =
      DSI_GraphHeader | DSI_States | DSI_Edges | DSI_Dests | DSI_GraphFooter,
    };

    /// Dump the state and edge storage for debugging
    void dump_storage_as_dot(std::ostream& o, int dsi = DSI_All) const
    {
      if (dsi & DSI_GraphHeader)
        o << "digraph g { \nnode [shape=plaintext]\n";
      unsigned send = states_.size();
      if (dsi & DSI_StatesHeader)
        {
          o << ("states [label=<\n"
                "<table border='0' cellborder='1' cellspacing='0'>\n"
                "<tr><td sides='b' bgcolor='yellow' port='s'>states</td>\n");
          for (unsigned s = 0; s < send; ++s)
            o << "<td sides='b' bgcolor='yellow' port='s" << s << "'>"
              << s << "</td>\n";
          o << "</tr>\n";
        }
      if (dsi & DSI_StatesBody)
        {
          o << "<tr><td port='ss'>succ</td>\n";
          for (unsigned s = 0; s < send; ++s)
            {
              o << "<td port='ss" << s;
              if (states_[s].succ)
                o << "' bgcolor='cyan";
              o << "'>" << states_[s].succ << "</td>\n";
            }
          o << "</tr><tr><td port='st'>succ_tail</td>\n";
          for (unsigned s = 0; s < send; ++s)
            {
              o << "<td port='st" << s;
              if (states_[s].succ_tail)
                o << "' bgcolor='cyan";
              o << "'>" << states_[s].succ_tail << "</td>\n";
            }
          o << "</tr>\n";
        }
      if (dsi & DSI_StatesFooter)
        o << "</table>>]\n";
      unsigned eend = edges_.size();
      if (dsi & DSI_EdgesHeader)
        {
          o << ("edges [label=<\n"
                "<table border='0' cellborder='1' cellspacing='0'>\n"
                "<tr><td sides='b' bgcolor='cyan' port='e'>edges</td>\n");
          for (unsigned e = 1; e < eend; ++e)
            {
              o << "<td sides='b' bgcolor='"
                << (e != edges_[e].next_succ ? "cyan" : "gray")
                << "' port='e" << e << "'>" << e << "</td>\n";
            }
          o << "</tr>";
        }
      if (dsi & DSI_EdgesBody)
        {
          o << "<tr><td port='ed'>dst</td>\n";
          for (unsigned e = 1; e < eend; ++e)
            {
              o << "<td port='ed" << e;
              int d = edges_[e].dst;
              if (d < 0)
                o << "' bgcolor='pink'>~" << ~d;
              else
                o << "' bgcolor='yellow'>" << d;
              o << "</td>\n";
            }
          o << "</tr><tr><td port='en'>next_succ</td>\n";
          for (unsigned e = 1; e < eend; ++e)
            {
              o << "<td port='en" << e;
              if (edges_[e].next_succ)
                {
                  if (edges_[e].next_succ != e)
                    o << "' bgcolor='cyan";
                  else
                    o << "' bgcolor='gray";
                }
              o << "'>" << edges_[e].next_succ << "</td>\n";
            }
          o << "</tr><tr><td port='es'>src</td>\n";
          for (unsigned e = 1; e < eend; ++e)
            o << "<td port='es" << e << "' bgcolor='yellow'>"
              << edges_[e].src << "</td>\n";
          o << "</tr>\n";
        }
      if (dsi & DSI_EdgesFooter)
        o << "</table>>]\n";
      if (!dests_.empty())
        {
          unsigned dend = dests_.size();
          if (dsi & DSI_DestsHeader)
            {
              o << ("dests [label=<\n"
                    "<table border='0' cellborder='1' cellspacing='0'>\n"
                    "<tr><td sides='b' bgcolor='pink' port='d'>dests</td>\n");
              unsigned d = 0;
              while (d < dend)
                {
                  o << "<td sides='b' bgcolor='pink' port='d"
                    << d << "'>~" << d << "</td>\n";
                  unsigned cnt = dests_[d];
                  d += cnt + 1;
                  while (cnt--)
                    o << "<td sides='b'></td>\n";
                }
              o << "</tr>\n";
            }
          if (dsi & DSI_DestsBody)
            {
              o << "<tr><td port='dd'>#cnt/dst</td>\n";
              unsigned d = 0;
              while (d < dend)
                {
                  unsigned cnt = dests_[d];
                  o << "<td port='d'>#" << cnt << "</td>\n";
                  ++d;
                  while (cnt--)
                    {
                      o << "<td bgcolor='yellow' port='dd"
                        << d << "'>" << dests_[d] << "</td>\n";
                      ++d;
                    }
                }
              o << "</tr>\n";
            }
          if (dsi & DSI_DestsFooter)
            o << "</table>>]\n";
        }
      if (dsi & DSI_GraphFooter)
        o << "}\n";
    }

1211 1212 1213 1214 1215
    /// \brief Remove all dead edges.
    ///
    /// The edges_ vector is left in a state that is incorrect and
    /// should eventually be fixed by a call to chain_edges_() before
    /// any iteration on the successor of a state is performed.
1216
    void remove_dead_edges_()
1217
    {
1218
      if (killed_edge_ == 0)
1219
        return;
1220
      auto i = std::remove_if(edges_.begin() + 1, edges_.end(),
1221 1222 1223
                              [this](const edge_storage_t& t) {
                                return this->is_dead_edge(t);
                              });
1224 1225
      edges_.erase(i, edges_.end());
      killed_edge_ = 0;
1226
    }
1227

Maximilien Colange's avatar
Maximilien Colange committed
1228
    /// \brief Sort all edges according to a predicate
1229 1230 1231 1232
    ///
    /// This will invalidate all iterators, and also destroy edge
    /// chains.  Call chain_edges_() immediately afterwards unless you
    /// know what you are doing.
1233 1234
    template<class Predicate = std::less<edge_storage_t>>
    void sort_edges_(Predicate p = Predicate())
1235 1236 1237
    {
      //std::cerr << "\nbefore\n";
      //dump_storage(std::cerr);
1238
      std::stable_sort(edges_.begin() + 1, edges_.end(), p);
1239
    }
1240

1241 1242 1243 1244
    /// \brief Reconstruct the chain of outgoing edges
    ///
    /// Should be called only when it is known that all edges
    /// with the same destination are consecutive in the vector.
1245
    void chain_edges_()
1246 1247
    {
      state last_src = -1U;
1248 1249
      edge tend = edges_.size();
      for (edge t = 1; t < tend; ++t)
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
        {
          state src = edges_[t].src;
          if (src != last_src)
            {
              states_[src].succ = t;
              if (last_src != -1U)
                {
                  states_[last_src].succ_tail = t - 1;
                  edges_[t - 1].next_succ = 0;
                }
              while (++last_src != src)
                {
                  states_[last_src].succ = 0;
                  states_[last_src].succ_tail = 0;
                }
            }
          else
            {
              edges_[t - 1].next_succ = t;
            }
        }
1271
      if (last_src != -1U)
1272 1273 1274 1275
        {
          states_[last_src].succ_tail = tend - 1;
          edges_[tend - 1].next_succ = 0;
        }
1276 1277
      unsigned send = states_.size();
      while (++last_src != send)
1278 1279 1280 1281
        {
          states_[last_src].succ = 0;
          states_[last_src].succ_tail = 0;
        }
1282 1283
      //std::cerr << "\nafter\n";
      //dump_storage(std::cerr);
1284 1285
    }

1286 1287 1288 1289 1290
    /// \brief Rename all the states in the edge vector.
    ///
    /// The edges_ vector is left in a state that is incorrect and
    /// should eventually be fixed by a call to chain_edges_() before
    /// any iteration on the successor of a state is performed.
1291 1292
    void rename_states_(const std::vector<unsigned>& newst)
    {
1293
      SPOT_ASSERT(newst.size() == states_.size());
1294
      unsigned tend = edges_.size();
1295
      for (unsigned t = 1; t < tend; t++)
1296 1297 1298 1299
        {
          edges_[t].dst = newst[edges_[t].dst];
          edges_[t].src = newst[edges_[t].src];
        }
1300 1301
    }

1302 1303 1304 1305
    /// \brief Rename and remove states.
    ///
    /// \param newst A vector indicating how each state should be renumbered.
    /// Use -1U to erase a state.
1306
    /// \param used_states the number of states used (after renumbering)
1307 1308
    void defrag_states(std::vector<unsigned>&& newst, unsigned used_states)
    {
1309
      SPOT_ASSERT(newst.size() >= states_.size());
1310
      SPOT_ASSERT(used_states > 0);
1311

1312 1313 1314
      //std::cerr << "\nbefore defrag\n";
      //dump_storage(std::cerr);

1315 1316 1317
      // Shift all states in states_, as indicated by newst.
      unsigned send = states_.size();
      for (state s = 0; s < send; ++s)
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
        {
          state dst = newst[s];
          if (dst == s)
            continue;
          if (dst == -1U)
            {
              // This is an erased state.  Mark all its edges as
              // dead (i.e., t.next_succ should point to t for each of
              // them).
              auto t = states_[s].succ;
              while (t)
                std::swap(t, edges_[t].next_succ);
              continue;
            }
          states_[dst] = std::move(states_[s]);
        }
1334 1335
      states_.resize(used_states);

1336
      // Shift all edges in edges_.  The algorithm is
1337 1338
      // similar to remove_if, but it also keeps the correspondence
      // between the old and new index as newidx[old] = new.
1339 1340
      unsigned tend = edges_.size();
      std::vector<edge> newidx(tend);
1341
      unsigned dest = 1;
1342
      for (edge t = 1; t < tend; ++t)
1343 1344 1345 1346 1347 1348 1349 1350
        {
          if (is_dead_edge(t))
            continue;
          if (t != dest)
            edges_[dest] = std::move(edges_[t]);
          newidx[t] = dest;
          ++dest;
        }
1351 1352
      edges_.resize(dest);
      killed_edge_ = 0;
1353

1354 1355
      // Adjust next_succ and dst pointers in all edges.
      for (edge t = 1; t < dest; ++t)
1356 1357 1358
        {
          auto& tr = edges_[t];
          tr.src = newst[tr.src];
1359 1360
          tr.dst = newst[tr.dst];
          tr.next_succ = newidx[tr.next_succ];
1361