source: src/Common/utility.h @ 234b1cb

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 234b1cb was 234b1cb, checked in by Aaron Moss <a3moss@…>, 5 years ago

Port TupleAssignment? to new AST

  • Property mode set to 100644
File size: 14.9 KB
Line 
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//
7// utility.h --
8//
9// Author           : Richard C. Bilson
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Sun May  6 22:24:16 2018
13// Update Count     : 40
14//
15
16#pragma once
17
18#include <cassert>
19#include <cctype>
20#include <algorithm>
21#include <functional>
22#include <iostream>
23#include <iterator>
24#include <list>
25#include <memory>
26#include <sstream>
27#include <string>
28#include <type_traits>
29#include <utility>
30#include <vector>
31
32#include "Common/Indenter.h"
33
34class Expression;
35
36template< typename T >
37static inline T * maybeClone( const T *orig ) {
38        if ( orig ) {
39                return orig->clone();
40        } else {
41                return 0;
42        } // if
43}
44
45template< typename T, typename U >
46struct maybeBuild_t {
47        static T * doit( const U *orig ) {
48                if ( orig ) {
49                        return orig->build();
50                } else {
51                        return 0;
52                } // if
53        }
54};
55
56template< typename T, typename U >
57static inline T * maybeBuild( const U *orig ) {
58        return maybeBuild_t<T,U>::doit(orig);
59}
60
61template< typename T, typename U >
62static inline T * maybeMoveBuild( const U *orig ) {
63        T* ret = maybeBuild<T>(orig);
64        delete orig;
65        return ret;
66}
67
68template< typename Input_iterator >
69void printEnums( Input_iterator begin, Input_iterator end, const char * const *name_array, std::ostream &os ) {
70        for ( Input_iterator i = begin; i != end; ++i ) {
71                os << name_array[ *i ] << ' ';
72        } // for
73}
74
75template< typename Container >
76void deleteAll( const Container &container ) {
77        for ( const auto &i : container ) {
78                delete i;
79        } // for
80}
81
82template< typename Container >
83void printAll( const Container &container, std::ostream &os, Indenter indent = {} ) {
84        for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
85                if ( *i ) {
86                        os << indent;
87                        (*i)->print( os, indent );
88                        // need an endl after each element because it's not easy to know when each individual item should end
89                        os << std::endl;
90                } // if
91        } // for
92}
93
94template< typename SrcContainer, typename DestContainer >
95void cloneAll( const SrcContainer &src, DestContainer &dest ) {
96        typename SrcContainer::const_iterator in = src.begin();
97        std::back_insert_iterator< DestContainer > out( dest );
98        while ( in != src.end() ) {
99                *out++ = (*in++)->clone();
100        } // while
101}
102
103template< typename SrcContainer, typename DestContainer, typename Predicate >
104void cloneAll_if( const SrcContainer &src, DestContainer &dest, Predicate pred ) {
105        std::back_insert_iterator< DestContainer > out( dest );
106        for ( auto x : src ) {
107                if ( pred(x) ) {
108                        *out++ = x->clone();
109                }
110        } // while
111}
112
113template< typename Container >
114void assertAll( const Container &container ) {
115        int count = 0;
116        for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
117                if ( !(*i) ) {
118                        std::cerr << count << " is null" << std::endl;
119                } // if
120        } // for
121}
122
123template < typename T >
124std::list<T> tail( std::list<T> l ) {
125        if ( ! l.empty() ) {
126                std::list<T> ret(++(l.begin()), l.end());
127                return ret;
128        } // if
129}
130
131template < typename T >
132std::list<T> flatten( std::list < std::list<T> > l) {
133        typedef std::list <T> Ts;
134
135        Ts ret;
136
137        switch ( l.size() ) {
138          case 0:
139                return ret;
140          case 1:
141                return l.front();
142          default:
143                ret = flatten(tail(l));
144                ret.insert(ret.begin(), l.front().begin(), l.front().end());
145                return ret;
146        } // switch
147}
148
149/// Splice src onto the end of dst, clearing src
150template< typename T >
151void splice( std::vector< T > & dst, std::vector< T > & src ) {
152        dst.reserve( dst.size() + src.size() );
153        for ( T & x : src ) { dst.emplace_back( std::move( x ) ); }
154        src.clear();
155}
156
157/// Splice src onto the begining of dst, clearing src
158template< typename T >
159void spliceBegin( std::vector< T > & dst, std::vector< T > & src ) {
160        splice( src, dst );
161        dst.swap( src );
162}
163
164template < typename T >
165void toString_single( std::ostream & os, const T & value ) {
166        os << value;
167}
168
169template < typename T, typename... Params >
170void toString_single( std::ostream & os, const T & value, const Params & ... params ) {
171        os << value;
172        toString_single( os, params ... );
173}
174
175template < typename ... Params >
176std::string toString( const Params & ... params ) {
177        std::ostringstream os;
178        toString_single( os, params... );
179        return os.str();
180}
181
182#define toCString( ... ) toString( __VA_ARGS__ ).c_str()
183
184// replace element of list with all elements of another list
185template< typename T >
186void replace( std::list< T > &org, typename std::list< T >::iterator pos, std::list< T > &with ) {
187        typename std::list< T >::iterator next = pos; advance( next, 1 );
188
189        //if ( next != org.end() ) {
190        org.erase( pos );
191        org.splice( next, with );
192        //}
193
194        return;
195}
196
197// replace range of a list with a single element
198template< typename T >
199void replace( std::list< T > &org, typename std::list< T >::iterator begin, typename std::list< T >::iterator end, const T & with ) {
200        org.insert( begin, with );
201        org.erase( begin, end );
202}
203
204template< typename... Args >
205auto filter(Args&&... args) -> decltype(std::copy_if(std::forward<Args>(args)...)) {
206  return std::copy_if(std::forward<Args>(args)...);
207}
208
209template <typename E, typename UnaryPredicate, template< typename, typename...> class Container, typename... Args >
210void filter( Container< E *, Args... > & container, UnaryPredicate pred, bool doDelete ) {
211        auto i = begin( container );
212        while ( i != end( container ) ) {
213                auto it = next( i );
214                if ( pred( *i ) ) {
215                        if ( doDelete ) {
216                                delete *i;
217                        } // if
218                        container.erase( i );
219                } // if
220                i = it;
221        } // while
222}
223
224template< typename... Args >
225auto zip(Args&&... args) -> decltype(zipWith(std::forward<Args>(args)..., std::make_pair)) {
226  return zipWith(std::forward<Args>(args)..., std::make_pair);
227}
228
229template< class InputIterator1, class InputIterator2, class OutputIterator, class BinFunction >
230void zipWith( InputIterator1 b1, InputIterator1 e1, InputIterator2 b2, InputIterator2 e2, OutputIterator out, BinFunction func ) {
231        while ( b1 != e1 && b2 != e2 )
232                *out++ = func(*b1++, *b2++);
233}
234
235// it's nice to actually be able to increment iterators by an arbitrary amount
236template< class InputIt, class Distance >
237InputIt operator+( InputIt it, Distance n ) {
238        advance(it, n);
239        return it;
240}
241
242template< typename T >
243void warn_single( const T & arg ) {
244        std::cerr << arg << std::endl;
245}
246
247template< typename T, typename... Params >
248void warn_single(const T & arg, const Params & ... params ) {
249        std::cerr << arg;
250        warn_single( params... );
251}
252
253template< typename... Params >
254void warn( const Params & ... params ) {
255        std::cerr << "Warning: ";
256        warn_single( params... );
257}
258
259/// determines if `pref` is a prefix of `str`
260static inline bool isPrefix( const std::string & str, const std::string & pref ) {
261        if ( pref.size() > str.size() ) return false;
262        auto its = std::mismatch( pref.begin(), pref.end(), str.begin() );
263        return its.first == pref.end();
264}
265
266// -----------------------------------------------------------------------------
267// Ref Counted Singleton class
268// Objects that inherit from this class will have at most one reference to it
269// but if all references die, the object will be deleted.
270
271template< typename ThisType >
272class RefCountSingleton {
273  public:
274        static std::shared_ptr<ThisType> get() {
275                if( global_instance.expired() ) {
276                        std::shared_ptr<ThisType> new_instance = std::make_shared<ThisType>();
277                        global_instance = new_instance;
278                        return std::move(new_instance);
279                }
280                return global_instance.lock();
281        }
282  private:
283        static std::weak_ptr<ThisType> global_instance;
284};
285
286template< typename ThisType >
287std::weak_ptr<ThisType> RefCountSingleton<ThisType>::global_instance;
288
289// -----------------------------------------------------------------------------
290// RAII object to regulate "save and restore" behaviour, e.g.
291// void Foo::bar() {
292//   ValueGuard<int> guard(var); // var is a member of type Foo
293//   var = ...;
294// } // var's original value is restored
295template< typename T >
296struct ValueGuard {
297        T old;
298        T& ref;
299
300        ValueGuard(T& inRef) : old(inRef), ref(inRef) {}
301        ~ValueGuard() { ref = old; }
302};
303
304template< typename T >
305struct ValueGuardPtr {
306        T old;
307        T* ref;
308
309        ValueGuardPtr(T * inRef) : old( inRef ? *inRef : T() ), ref(inRef) {}
310        ~ValueGuardPtr() { if( ref ) *ref = old; }
311};
312
313template< typename aT >
314struct FuncGuard {
315        aT m_after;
316
317        template< typename bT >
318        FuncGuard( bT before, aT after ) : m_after( after ) {
319                before();
320        }
321
322        ~FuncGuard() {
323                m_after();
324        }
325};
326
327template< typename bT, typename aT >
328FuncGuard<aT> makeFuncGuard( bT && before, aT && after ) {
329        return FuncGuard<aT>( std::forward<bT>(before), std::forward<aT>(after) );
330}
331
332template< typename T >
333struct ValueGuardPtr< std::list< T > > {
334        std::list< T > old;
335        std::list< T >* ref;
336
337        ValueGuardPtr( std::list< T > * inRef) : old(), ref(inRef) {
338                if( ref ) { swap( *ref, old ); }
339        }
340        ~ValueGuardPtr() { if( ref ) { swap( *ref, old ); } }
341};
342
343// -----------------------------------------------------------------------------
344// Helper struct and function to support
345// for ( val : reverseIterate( container ) ) {}
346// syntax to have a for each that iterates backwards
347
348template< typename T >
349struct reverse_iterate_t {
350        T& ref;
351
352        reverse_iterate_t( T & ref ) : ref(ref) {}
353
354        typedef typename T::reverse_iterator iterator;
355        iterator begin() { return ref.rbegin(); }
356        iterator end() { return ref.rend(); }
357};
358
359template< typename T >
360reverse_iterate_t< T > reverseIterate( T & ref ) {
361        return reverse_iterate_t< T >( ref );
362}
363
364template< typename OutType, typename Range, typename Functor >
365OutType map_range( const Range& range, Functor&& functor ) {
366        OutType out;
367
368        std::transform(
369                begin( range ),
370                end( range ),
371                std::back_inserter( out ),
372                std::forward< Functor >( functor )
373        );
374
375        return out;
376}
377
378// -----------------------------------------------------------------------------
379// Helper struct and function to support
380// for ( val : group_iterate( container1, container2, ... ) ) {}
381// syntax to have a for each that iterates multiple containers of the same length
382// TODO: update to use variadic arguments
383
384template< typename T1, typename T2 >
385struct group_iterate_t {
386private:
387        std::tuple<T1, T2> args;
388public:
389        group_iterate_t( bool skipBoundsCheck, const T1 & v1, const T2 & v2 ) : args(v1, v2) {
390                assertf(skipBoundsCheck || v1.size() == v2.size(), "group iteration requires containers of the same size: <%zd, %zd>.", v1.size(), v2.size());
391        };
392
393        typedef std::tuple<decltype(*std::get<0>(args).begin()), decltype(*std::get<1>(args).begin())> value_type;
394        typedef decltype(std::get<0>(args).begin()) T1Iter;
395        typedef decltype(std::get<1>(args).begin()) T2Iter;
396
397        struct iterator {
398                typedef std::tuple<T1Iter, T2Iter> IterTuple;
399                IterTuple it;
400                iterator( T1Iter i1, T2Iter i2 ) : it( i1, i2 ) {}
401                iterator operator++() {
402                        return iterator( ++std::get<0>(it), ++std::get<1>(it) );
403                }
404                bool operator!=( const iterator &other ) const { return it != other.it; }
405                value_type operator*() const { return std::tie( *std::get<0>(it), *std::get<1>(it) ); }
406        };
407
408        iterator begin() { return iterator( std::get<0>(args).begin(), std::get<1>(args).begin() ); }
409        iterator end() { return iterator( std::get<0>(args).end(), std::get<1>(args).end() ); }
410};
411
412/// performs bounds check to ensure that all arguments are of the same length.
413template< typename... Args >
414group_iterate_t<Args...> group_iterate( Args &&... args ) {
415        return group_iterate_t<Args...>(false, std::forward<Args>( args )...);
416}
417
418/// does not perform a bounds check - requires user to ensure that iteration terminates when appropriate.
419template< typename... Args >
420group_iterate_t<Args...> unsafe_group_iterate( Args &&... args ) {
421        return group_iterate_t<Args...>(true, std::forward<Args>( args )...);
422}
423
424// -----------------------------------------------------------------------------
425// Helper struct and function to support
426// for ( val : lazy_map( container1, f ) ) {}
427// syntax to have a for each that iterates a container, mapping each element by applying f
428template< typename T, typename Func >
429struct lambda_iterate_t {
430        const T & ref;
431        std::function<Func> f;
432
433        struct iterator {
434                typedef decltype(begin(ref)) Iter;
435                Iter it;
436                std::function<Func> f;
437                iterator( Iter it, std::function<Func> f ) : it(it), f(f) {}
438                iterator & operator++() {
439                        ++it; return *this;
440                }
441                bool operator!=( const iterator &other ) const { return it != other.it; }
442                auto operator*() const -> decltype(f(*it)) { return f(*it); }
443        };
444
445        lambda_iterate_t( const T & ref, std::function<Func> f ) : ref(ref), f(f) {}
446
447        auto begin() const -> decltype(iterator(std::begin(ref), f)) { return iterator(std::begin(ref), f); }
448        auto end() const   -> decltype(iterator(std::end(ref), f)) { return iterator(std::end(ref), f); }
449};
450
451template< typename... Args >
452lambda_iterate_t<Args...> lazy_map( const Args &... args ) {
453        return lambda_iterate_t<Args...>( args...);
454}
455
456// -----------------------------------------------------------------------------
457// O(1) polymorphic integer ilog2, using clz, which returns the number of leading 0-bits, starting at the most
458// significant bit (single instruction on x86)
459
460template<typename T>
461inline
462#if defined(__GNUC__) && __GNUC__ > 4
463constexpr
464#endif
465T ilog2(const T & t) {
466        if(std::is_integral<T>::value) {
467                const constexpr int r = sizeof(t) * __CHAR_BIT__ - 1;
468                if( sizeof(T) == sizeof(unsigned       int) ) return r - __builtin_clz  ( t );
469                if( sizeof(T) == sizeof(unsigned      long) ) return r - __builtin_clzl ( t );
470                if( sizeof(T) == sizeof(unsigned long long) ) return r - __builtin_clzll( t );
471        }
472        assert(false);
473        return -1;
474} // ilog2
475
476// -----------------------------------------------------------------------------
477/// evaluates expr as a long long int. If second is false, expr could not be evaluated
478std::pair<long long int, bool> eval(Expression * expr);
479
480namespace ast {
481        class Expr;
482}
483
484std::pair<long long int, bool> eval(const ast::Expr * expr);
485
486// -----------------------------------------------------------------------------
487/// Reorders the input range in-place so that the minimal-value elements according to the
488/// comparator are in front;
489/// returns the iterator after the last minimal-value element.
490template<typename Iter, typename Compare>
491Iter sort_mins( Iter begin, Iter end, Compare& lt ) {
492        if ( begin == end ) return end;
493
494        Iter min_pos = begin;
495        for ( Iter i = begin + 1; i != end; ++i ) {
496                if ( lt( *i, *min_pos ) ) {
497                        // new minimum cost; swap into first position
498                        min_pos = begin;
499                        std::iter_swap( min_pos, i );
500                } else if ( ! lt( *min_pos, *i ) ) {
501                        // duplicate minimum cost; swap into next minimum position
502                        ++min_pos;
503                        std::iter_swap( min_pos, i );
504                }
505        }
506        return ++min_pos;
507}
508
509template<typename Iter, typename Compare>
510inline Iter sort_mins( Iter begin, Iter end, Compare&& lt ) {
511        return sort_mins( begin, end, lt );
512}
513
514/// sort_mins defaulted to use std::less
515template<typename Iter>
516inline Iter sort_mins( Iter begin, Iter end ) {
517        return sort_mins( begin, end, std::less<typename std::iterator_traits<Iter>::value_type>{} );
518}
519
520// Local Variables: //
521// tab-width: 4 //
522// mode: c++ //
523// compile-command: "make install" //
524// End: //
Note: See TracBrowser for help on using the repository browser.