source: src/Common/utility.h @ 019b2d3

ADTast-experimental
Last change on this file since 019b2d3 was 7491f97, checked in by Andrew Beach <ajbeach@…>, 19 months ago

Renaming and comments in group_iterate_t to help clarity.

  • Property mode set to 100644
File size: 18.3 KB
RevLine 
[51587aa]1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
[60089f4]7// utility.h --
[51587aa]8//
9// Author           : Richard C. Bilson
10// Created On       : Mon May 18 07:44:20 2015
[298fe57]11// Last Modified By : Andrew Beach
12// Last Modified On : Mon Apr 25 14:26:00 2022
13// Update Count     : 51
[51587aa]14//
[01aeade]15
[6b0b624]16#pragma once
[51b7345]17
[234b1cb]18#include <cassert>
[e491159]19#include <cctype>
[940bba3]20#include <algorithm>
[2e30d47]21#include <functional>
[51b7345]22#include <iostream>
23#include <iterator>
24#include <list>
[e491159]25#include <memory>
26#include <sstream>
27#include <string>
[55a68c3]28#include <type_traits>
[fbecee5]29#include <utility>
[234b1cb]30#include <vector>
[8abca06]31#include <cstring>                                                                              // memcmp
[be9288a]32
[50377a4]33#include "Common/Indenter.h"
34
[5cbacf1]35class Expression;
36
[c1ed2ee]37/// bring std::move into global scope
38using std::move;
39
40/// partner to move that copies any copyable type
41template<typename T>
42T copy( const T & x ) { return x; }
43
[51b7345]44template< typename T >
[01aeade]45static inline T * maybeClone( const T *orig ) {
46        if ( orig ) {
47                return orig->clone();
48        } else {
49                return 0;
50        } // if
[51b7345]51}
52
[a7741435]53template< typename T, typename U >
[e04ef3a]54struct maybeBuild_t {
55        static T * doit( const U *orig ) {
56                if ( orig ) {
57                        return orig->build();
58                } else {
59                        return 0;
60                } // if
61        }
62};
63
[51b7345]64template< typename T, typename U >
[01aeade]65static inline T * maybeBuild( const U *orig ) {
[e04ef3a]66        return maybeBuild_t<T,U>::doit(orig);
[51b7345]67}
68
[7ecbb7e]69template< typename T, typename U >
70static inline T * maybeMoveBuild( const U *orig ) {
71        T* ret = maybeBuild<T>(orig);
72        delete orig;
73        return ret;
74}
75
[51b7345]76template< typename Input_iterator >
[01aeade]77void printEnums( Input_iterator begin, Input_iterator end, const char * const *name_array, std::ostream &os ) {
78        for ( Input_iterator i = begin; i != end; ++i ) {
79                os << name_array[ *i ] << ' ';
80        } // for
[51b7345]81}
82
83template< typename Container >
[8abee136]84void deleteAll( const Container &container ) {
85        for ( const auto &i : container ) {
86                delete i;
[01aeade]87        } // for
[51b7345]88}
89
90template< typename Container >
[50377a4]91void printAll( const Container &container, std::ostream &os, Indenter indent = {} ) {
[01aeade]92        for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
93                if ( *i ) {
[50377a4]94                        os << indent;
95                        (*i)->print( os, indent );
[60089f4]96                        // need an endl after each element because it's not easy to know when each individual item should end
[01aeade]97                        os << std::endl;
98                } // if
99        } // for
[51b7345]100}
101
102template< typename SrcContainer, typename DestContainer >
[01aeade]103void cloneAll( const SrcContainer &src, DestContainer &dest ) {
104        typename SrcContainer::const_iterator in = src.begin();
105        std::back_insert_iterator< DestContainer > out( dest );
106        while ( in != src.end() ) {
107                *out++ = (*in++)->clone();
108        } // while
[51b7345]109}
110
[54c9000]111template< typename SrcContainer, typename DestContainer, typename Predicate >
112void cloneAll_if( const SrcContainer &src, DestContainer &dest, Predicate pred ) {
113        std::back_insert_iterator< DestContainer > out( dest );
114        for ( auto x : src ) {
115                if ( pred(x) ) {
116                        *out++ = x->clone();
117                }
118        } // while
119}
120
[51b7345]121template< typename Container >
[01aeade]122void assertAll( const Container &container ) {
123        int count = 0;
124        for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
125                if ( !(*i) ) {
126                        std::cerr << count << " is null" << std::endl;
127                } // if
128        } // for
129}
130
[51b7345]131template < typename T >
[01aeade]132std::list<T> tail( std::list<T> l ) {
133        if ( ! l.empty() ) {
134                std::list<T> ret(++(l.begin()), l.end());
135                return ret;
136        } // if
[51b7345]137}
138
139template < typename T >
140std::list<T> flatten( std::list < std::list<T> > l) {
[01aeade]141        typedef std::list <T> Ts;
[51b7345]142
[01aeade]143        Ts ret;
[51b7345]144
[a08ba92]145        switch ( l.size() ) {
[01aeade]146          case 0:
147                return ret;
148          case 1:
149                return l.front();
150          default:
151                ret = flatten(tail(l));
152                ret.insert(ret.begin(), l.front().begin(), l.front().end());
153                return ret;
154        } // switch
[51b7345]155}
156
[234b1cb]157/// Splice src onto the end of dst, clearing src
158template< typename T >
159void splice( std::vector< T > & dst, std::vector< T > & src ) {
160        dst.reserve( dst.size() + src.size() );
161        for ( T & x : src ) { dst.emplace_back( std::move( x ) ); }
162        src.clear();
163}
164
165/// Splice src onto the begining of dst, clearing src
166template< typename T >
167void spliceBegin( std::vector< T > & dst, std::vector< T > & src ) {
168        splice( src, dst );
169        dst.swap( src );
170}
171
[60089f4]172template < typename T >
[2298f728]173void toString_single( std::ostream & os, const T & value ) {
[79970ed]174        os << value;
175}
176
177template < typename T, typename... Params >
[2298f728]178void toString_single( std::ostream & os, const T & value, const Params & ... params ) {
[79970ed]179        os << value;
180        toString_single( os, params ... );
181}
182
183template < typename ... Params >
[2298f728]184std::string toString( const Params & ... params ) {
[5f2f2d7]185        std::ostringstream os;
[79970ed]186        toString_single( os, params... );
[5f2f2d7]187        return os.str();
[51b7345]188}
189
[babeeda]190#define toCString( ... ) toString( __VA_ARGS__ ).c_str()
191
[3c13c03]192// replace element of list with all elements of another list
[51b7345]193template< typename T >
194void replace( std::list< T > &org, typename std::list< T >::iterator pos, std::list< T > &with ) {
[01aeade]195        typename std::list< T >::iterator next = pos; advance( next, 1 );
[51b7345]196
[01aeade]197        //if ( next != org.end() ) {
[a08ba92]198        org.erase( pos );
199        org.splice( next, with );
200        //}
[51b7345]201
[01aeade]202        return;
[51b7345]203}
204
[3c13c03]205// replace range of a list with a single element
206template< typename T >
207void replace( std::list< T > &org, typename std::list< T >::iterator begin, typename std::list< T >::iterator end, const T & with ) {
208        org.insert( begin, with );
209        org.erase( begin, end );
210}
211
[940bba3]212template< typename... Args >
213auto filter(Args&&... args) -> decltype(std::copy_if(std::forward<Args>(args)...)) {
214  return std::copy_if(std::forward<Args>(args)...);
[51b7345]215}
216
[2bf9c37]217template <typename E, typename UnaryPredicate, template< typename, typename...> class Container, typename... Args >
218void filter( Container< E *, Args... > & container, UnaryPredicate pred, bool doDelete ) {
219        auto i = begin( container );
220        while ( i != end( container ) ) {
221                auto it = next( i );
222                if ( pred( *i ) ) {
223                        if ( doDelete ) {
224                                delete *i;
225                        } // if
226                        container.erase( i );
227                } // if
228                i = it;
229        } // while
230}
231
[298fe57]232template<typename Container, typename Pred>
233void erase_if( Container & cont, Pred && pred ) {
234        auto keep_end = std::remove_if( cont.begin(), cont.end(), pred );
235        cont.erase( keep_end, cont.end() );
236}
237
[940bba3]238template< typename... Args >
239auto zip(Args&&... args) -> decltype(zipWith(std::forward<Args>(args)..., std::make_pair)) {
240  return zipWith(std::forward<Args>(args)..., std::make_pair);
[51b7345]241}
242
243template< class InputIterator1, class InputIterator2, class OutputIterator, class BinFunction >
244void zipWith( InputIterator1 b1, InputIterator1 e1, InputIterator2 b2, InputIterator2 e2, OutputIterator out, BinFunction func ) {
[01aeade]245        while ( b1 != e1 && b2 != e2 )
246                *out++ = func(*b1++, *b2++);
[51b7345]247}
248
[d939274]249// it's nice to actually be able to increment iterators by an arbitrary amount
[940bba3]250template< class InputIt, class Distance >
251InputIt operator+( InputIt it, Distance n ) {
252        advance(it, n);
253        return it;
[d939274]254}
255
[79970ed]256template< typename T >
257void warn_single( const T & arg ) {
258        std::cerr << arg << std::endl;
259}
260
261template< typename T, typename... Params >
262void warn_single(const T & arg, const Params & ... params ) {
263        std::cerr << arg;
264        warn_single( params... );
265}
266
267template< typename... Params >
268void warn( const Params & ... params ) {
269        std::cerr << "Warning: ";
270        warn_single( params... );
271}
272
[8abca06]273// determines if pref is a prefix of str
274static inline bool isPrefix( const std::string & str, const std::string & pref, unsigned int start = 0 ) {
[bc3127d]275        if ( pref.size() > str.size() ) return false;
[8abca06]276    return 0 == memcmp( str.c_str() + start, pref.c_str(), pref.size() );
277        // return prefix == full.substr(0, prefix.size()); // for future, requires c++17
[bc3127d]278}
279
[940bba3]280// -----------------------------------------------------------------------------
281// Ref Counted Singleton class
282// Objects that inherit from this class will have at most one reference to it
283// but if all references die, the object will be deleted.
284
[e491159]285template< typename ThisType >
286class RefCountSingleton {
287  public:
288        static std::shared_ptr<ThisType> get() {
289                if( global_instance.expired() ) {
290                        std::shared_ptr<ThisType> new_instance = std::make_shared<ThisType>();
291                        global_instance = new_instance;
292                        return std::move(new_instance);
293                }
294                return global_instance.lock();
295        }
296  private:
297        static std::weak_ptr<ThisType> global_instance;
298};
299
[1f75e2d]300template< typename ThisType >
301std::weak_ptr<ThisType> RefCountSingleton<ThisType>::global_instance;
302
[940bba3]303// -----------------------------------------------------------------------------
[c8dfcd3]304// RAII object to regulate "save and restore" behaviour, e.g.
305// void Foo::bar() {
306//   ValueGuard<int> guard(var); // var is a member of type Foo
307//   var = ...;
308// } // var's original value is restored
309template< typename T >
310struct ValueGuard {
311        T old;
312        T& ref;
313
314        ValueGuard(T& inRef) : old(inRef), ref(inRef) {}
315        ~ValueGuard() { ref = old; }
316};
317
[134322e]318template< typename T >
319struct ValueGuardPtr {
320        T old;
321        T* ref;
322
323        ValueGuardPtr(T * inRef) : old( inRef ? *inRef : T() ), ref(inRef) {}
[1b65595]324        ValueGuardPtr(const ValueGuardPtr& other) = delete;
325        ValueGuardPtr(ValueGuardPtr&& other) : old(other.old), ref(other.ref) { other.ref = nullptr; }
[134322e]326        ~ValueGuardPtr() { if( ref ) *ref = old; }
327};
328
[234223f]329template< typename aT >
330struct FuncGuard {
331        aT m_after;
332
333        template< typename bT >
334        FuncGuard( bT before, aT after ) : m_after( after ) {
335                before();
336        }
337
338        ~FuncGuard() {
339                m_after();
340        }
341};
342
343template< typename bT, typename aT >
344FuncGuard<aT> makeFuncGuard( bT && before, aT && after ) {
345        return FuncGuard<aT>( std::forward<bT>(before), std::forward<aT>(after) );
346}
347
[134322e]348template< typename T >
349struct ValueGuardPtr< std::list< T > > {
350        std::list< T > old;
351        std::list< T >* ref;
352
353        ValueGuardPtr( std::list< T > * inRef) : old(), ref(inRef) {
354                if( ref ) { swap( *ref, old ); }
355        }
356        ~ValueGuardPtr() { if( ref ) { swap( *ref, old ); } }
357};
358
[940bba3]359// -----------------------------------------------------------------------------
360// Helper struct and function to support
361// for ( val : reverseIterate( container ) ) {}
362// syntax to have a for each that iterates backwards
363
[44f6341]364template< typename T >
[4a9ccc3]365struct reverse_iterate_t {
[44f6341]366        T& ref;
367
[4a9ccc3]368        reverse_iterate_t( T & ref ) : ref(ref) {}
[44f6341]369
[490fb92e]370        // this does NOT work on const T!!!
371        // typedef typename T::reverse_iterator iterator;
372        auto begin() { return ref.rbegin(); }
373        auto end() { return ref.rend(); }
[44f6341]374};
375
376template< typename T >
[4a9ccc3]377reverse_iterate_t< T > reverseIterate( T & ref ) {
378        return reverse_iterate_t< T >( ref );
[44f6341]379}
380
[f8143a6]381template< typename T >
382struct enumerate_t {
383        template<typename val_t>
384        struct value_t {
385                val_t & val;
386                size_t idx;
387        };
388
389        template< typename iter_t, typename val_t >
390        struct iterator_t {
391                iter_t it;
392                size_t idx;
393
394                iterator_t( iter_t _it, size_t _idx ) : it(_it), idx(_idx) {}
395
396                value_t<val_t> operator*() const { return value_t<val_t>{ *it, idx }; }
397
398                bool operator==(const iterator_t & o) const { return o.it == it; }
399                bool operator!=(const iterator_t & o) const { return o.it != it; }
400
401                iterator_t & operator++() {
402                        it++;
403                        idx++;
404                        return *this;
405                }
406
407                using difference_type   = typename std::iterator_traits< iter_t >::difference_type;
408                using value_type        = value_t<val_t>;
409                using pointer           = value_t<val_t> *;
410                using reference         = value_t<val_t> &;
411                using iterator_category = std::forward_iterator_tag;
412        };
413
414        T & ref;
415
416        using iterator = iterator_t< typename T::iterator, typename T::value_type >;
417        using const_iterator = iterator_t< typename T::const_iterator, const typename T::value_type >;
418
419        iterator begin() { return iterator( ref.begin(), 0 ); }
420        iterator end()   { return iterator( ref.end(), ref.size() ); }
421
422        const_iterator begin() const { return const_iterator( ref.cbegin(), 0 ); }
423        const_iterator end()   const { return const_iterator( ref.cend(), ref.size() ); }
424
425        const_iterator cbegin() const { return const_iterator( ref.cbegin(), 0 ); }
426        const_iterator cend()   const { return const_iterator( ref.cend(), ref.size() ); }
427};
428
429template< typename T >
430enumerate_t<T> enumerate( T & ref ) {
431        return enumerate_t< T >{ ref };
432}
433
434template< typename T >
435const enumerate_t< const T > enumerate( const T & ref ) {
436        return enumerate_t< const T >{ ref };
437}
438
[3ad7978]439template< typename OutType, typename Range, typename Functor >
440OutType map_range( const Range& range, Functor&& functor ) {
441        OutType out;
442
443        std::transform(
444                begin( range ),
445                end( range ),
446                std::back_inserter( out ),
447                std::forward< Functor >( functor )
448        );
449
450        return out;
451}
452
[4a9ccc3]453// -----------------------------------------------------------------------------
[5ce0659]454// Helper struct and function to support:
455// for ( auto val : group_iterate( container1, container2, ... ) ) { ... }
456// This iteraters through multiple containers of the same size.
457
458template<typename... Args>
459class group_iterate_t {
460        using Iterables = std::tuple<Args...>;
461        Iterables iterables;
462
[7491f97]463        // Getting the iterator and value types this way preserves const.
[5ce0659]464        template<size_t I> using Iter = decltype(std::get<I>(iterables).begin());
465        template<size_t I> using Data = decltype(*std::get<I>(iterables).begin());
466        template<typename> struct base_iterator;
467
[7491f97]468        // This inner template puts the sequence of `0, 1, ... sizeof...(Args)-1`
469        // into a pack. These are the indexes into the tuples, so unpacking can
470        // go over each element of the tuple.
471        // The std::integer_sequence is just used to build that sequence.
472        // A library reference will probably explain it better than I can.
473        template<std::size_t... Indices>
474        struct base_iterator<std::integer_sequence<std::size_t, Indices...>> {
475                using value_type = std::tuple< Data<Indices>... >;
476                std::tuple<Iter<Indices>...> iterators;
477
478                base_iterator( Iter<Indices>... is ) : iterators( is... ) {}
[5ce0659]479                base_iterator operator++() {
[7491f97]480                        return base_iterator( ++std::get<Indices>( iterators )... );
[5ce0659]481                }
482                bool operator!=( const base_iterator& other ) const {
483                        return iterators != other.iterators;
484                }
485                value_type operator*() const {
[7491f97]486                        return std::tie( *std::get<Indices>( iterators )... );
[5ce0659]487                }
[6411b7d]488
[5ce0659]489                static base_iterator make_begin( Iterables & data ) {
[7491f97]490                        return base_iterator( std::get<Indices>( data ).begin()... );
[5ce0659]491                }
492                static base_iterator make_end( Iterables & data ) {
[7491f97]493                        return base_iterator( std::get<Indices>( data ).end()... );
[4a9ccc3]494                }
495        };
[50377a4]496
[6411b7d]497public:
[5ce0659]498        group_iterate_t( const Args &... args ) : iterables( args... ) {}
[6411b7d]499
[5ce0659]500        using iterator = base_iterator<decltype(
501                std::make_integer_sequence<std::size_t, sizeof...(Args)>())>;
[6411b7d]502
[5ce0659]503        iterator begin() { return iterator::make_begin( iterables ); }
504        iterator end() { return iterator::make_end( iterables ); }
[6411b7d]505};
506
[5ce0659]507// Helpers for the bounds checks (the non-varatic part of group_iterate):
[6411b7d]508static inline void runGroupBoundsCheck(size_t size0, size_t size1) {
509        assertf( size0 == size1,
510                "group iteration requires containers of the same size: <%zd, %zd>.",
511                size0, size1 );
512}
513
514static inline void runGroupBoundsCheck(size_t size0, size_t size1, size_t size2) {
515        assertf( size0 == size1 && size1 == size2,
516                "group iteration requires containers of the same size: <%zd, %zd, %zd>.",
517                size0, size1, size2 );
518}
519
[5ce0659]520/// Performs bounds check to ensure that all arguments are of the same length.
[4a9ccc3]521template< typename... Args >
[55a68c3]522group_iterate_t<Args...> group_iterate( Args &&... args ) {
[6411b7d]523        runGroupBoundsCheck( args.size()... );
524        return group_iterate_t<Args...>( std::forward<Args>( args )... );
[6d267ca]525}
526
[5ce0659]527/// Does not perform a bounds check - requires user to ensure that iteration terminates when appropriate.
[6d267ca]528template< typename... Args >
529group_iterate_t<Args...> unsafe_group_iterate( Args &&... args ) {
[6411b7d]530        return group_iterate_t<Args...>( std::forward<Args>( args )... );
[4a9ccc3]531}
[294647b]532
[108f3cdb]533// -----------------------------------------------------------------------------
534// Helper struct and function to support
535// for ( val : lazy_map( container1, f ) ) {}
536// syntax to have a for each that iterates a container, mapping each element by applying f
537template< typename T, typename Func >
538struct lambda_iterate_t {
[4639b0d]539        const T & ref;
540        std::function<Func> f;
[108f3cdb]541
542        struct iterator {
543                typedef decltype(begin(ref)) Iter;
544                Iter it;
[4639b0d]545                std::function<Func> f;
546                iterator( Iter it, std::function<Func> f ) : it(it), f(f) {}
[108f3cdb]547                iterator & operator++() {
548                        ++it; return *this;
549                }
550                bool operator!=( const iterator &other ) const { return it != other.it; }
551                auto operator*() const -> decltype(f(*it)) { return f(*it); }
552        };
553
[4639b0d]554        lambda_iterate_t( const T & ref, std::function<Func> f ) : ref(ref), f(f) {}
[108f3cdb]555
556        auto begin() const -> decltype(iterator(std::begin(ref), f)) { return iterator(std::begin(ref), f); }
557        auto end() const   -> decltype(iterator(std::end(ref), f)) { return iterator(std::end(ref), f); }
558};
559
560template< typename... Args >
[4639b0d]561lambda_iterate_t<Args...> lazy_map( const Args &... args ) {
562        return lambda_iterate_t<Args...>( args...);
[108f3cdb]563}
564
[9dc31c10]565// -----------------------------------------------------------------------------
[f14d956]566// O(1) polymorphic integer ilog2, using clz, which returns the number of leading 0-bits, starting at the most
[9dc31c10]567// significant bit (single instruction on x86)
568
569template<typename T>
[d28a03e]570inline
[b6d7f44]571#if defined(__GNUC__) && __GNUC__ > 4
[d28a03e]572constexpr
573#endif
574T ilog2(const T & t) {
575        if(std::is_integral<T>::value) {
[9dc31c10]576                const constexpr int r = sizeof(t) * __CHAR_BIT__ - 1;
[d28a03e]577                if( sizeof(T) == sizeof(unsigned       int) ) return r - __builtin_clz  ( t );
578                if( sizeof(T) == sizeof(unsigned      long) ) return r - __builtin_clzl ( t );
579                if( sizeof(T) == sizeof(unsigned long long) ) return r - __builtin_clzll( t );
580        }
581        assert(false);
[9dc31c10]582        return -1;
[01b8ccf1]583} // ilog2
[108f3cdb]584
[5cbacf1]585// -----------------------------------------------------------------------------
586/// evaluates expr as a long long int. If second is false, expr could not be evaluated
[77d2432]587std::pair<long long int, bool> eval(const Expression * expr);
[108f3cdb]588
[87701b6]589namespace ast {
590        class Expr;
591}
592
593std::pair<long long int, bool> eval(const ast::Expr * expr);
594
[fbecee5]595// -----------------------------------------------------------------------------
[87701b6]596/// Reorders the input range in-place so that the minimal-value elements according to the
597/// comparator are in front;
[fbecee5]598/// returns the iterator after the last minimal-value element.
599template<typename Iter, typename Compare>
600Iter sort_mins( Iter begin, Iter end, Compare& lt ) {
601        if ( begin == end ) return end;
[87701b6]602
[fbecee5]603        Iter min_pos = begin;
604        for ( Iter i = begin + 1; i != end; ++i ) {
605                if ( lt( *i, *min_pos ) ) {
606                        // new minimum cost; swap into first position
607                        min_pos = begin;
608                        std::iter_swap( min_pos, i );
609                } else if ( ! lt( *min_pos, *i ) ) {
610                        // duplicate minimum cost; swap into next minimum position
611                        ++min_pos;
612                        std::iter_swap( min_pos, i );
613                }
614        }
615        return ++min_pos;
616}
617
618template<typename Iter, typename Compare>
619inline Iter sort_mins( Iter begin, Iter end, Compare&& lt ) {
620        return sort_mins( begin, end, lt );
621}
622
623/// sort_mins defaulted to use std::less
624template<typename Iter>
625inline Iter sort_mins( Iter begin, Iter end ) {
626        return sort_mins( begin, end, std::less<typename std::iterator_traits<Iter>::value_type>{} );
627}
628
[51587aa]629// Local Variables: //
630// tab-width: 4 //
631// mode: c++ //
632// compile-command: "make install" //
633// End: //
Note: See TracBrowser for help on using the repository browser.