source: src/Common/utility.h@ 6840e7c

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 6840e7c was 50377a4, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Refactor tree print code to use Indenter

  • Property mode set to 100644
File size: 11.9 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
[21f0aa8]11// Last Modified By : Andrew Beach
12// Last Modified On : Thr Aug 17 11:38:00 2017
13// Update Count : 34
[51587aa]14//
[01aeade]15
[6b0b624]16#pragma once
[51b73452]17
[e491159]18#include <cctype>
[940bba3]19#include <algorithm>
[51b73452]20#include <iostream>
21#include <iterator>
22#include <list>
[e491159]23#include <memory>
24#include <sstream>
25#include <string>
[55a68c3]26#include <type_traits>
[51b73452]27
[294647b]28#include <cassert>
[be9288a]29
[50377a4]30#include "Common/Indenter.h"
31
[51b73452]32template< typename T >
[01aeade]33static inline T * maybeClone( const T *orig ) {
34 if ( orig ) {
35 return orig->clone();
36 } else {
37 return 0;
38 } // if
[51b73452]39}
40
[a7741435]41template< typename T, typename U >
[e04ef3a]42struct maybeBuild_t {
43 static T * doit( const U *orig ) {
44 if ( orig ) {
45 return orig->build();
46 } else {
47 return 0;
48 } // if
49 }
50};
51
[51b73452]52template< typename T, typename U >
[01aeade]53static inline T * maybeBuild( const U *orig ) {
[e04ef3a]54 return maybeBuild_t<T,U>::doit(orig);
[51b73452]55}
56
[7ecbb7e]57template< typename T, typename U >
58static inline T * maybeMoveBuild( const U *orig ) {
59 T* ret = maybeBuild<T>(orig);
60 delete orig;
61 return ret;
62}
63
[51b73452]64template< typename Input_iterator >
[01aeade]65void printEnums( Input_iterator begin, Input_iterator end, const char * const *name_array, std::ostream &os ) {
66 for ( Input_iterator i = begin; i != end; ++i ) {
67 os << name_array[ *i ] << ' ';
68 } // for
[51b73452]69}
70
71template< typename Container >
[01aeade]72void deleteAll( Container &container ) {
73 for ( typename Container::iterator i = container.begin(); i != container.end(); ++i ) {
74 delete *i;
75 } // for
[51b73452]76}
77
78template< typename Container >
[50377a4]79void printAll( const Container &container, std::ostream &os, Indenter indent = {} ) {
[01aeade]80 for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
81 if ( *i ) {
[50377a4]82 os << indent;
83 (*i)->print( os, indent );
[60089f4]84 // need an endl after each element because it's not easy to know when each individual item should end
[01aeade]85 os << std::endl;
86 } // if
87 } // for
[51b73452]88}
89
90template< typename SrcContainer, typename DestContainer >
[01aeade]91void cloneAll( const SrcContainer &src, DestContainer &dest ) {
92 typename SrcContainer::const_iterator in = src.begin();
93 std::back_insert_iterator< DestContainer > out( dest );
94 while ( in != src.end() ) {
95 *out++ = (*in++)->clone();
96 } // while
[51b73452]97}
98
99template< typename Container >
[01aeade]100void assertAll( const Container &container ) {
101 int count = 0;
102 for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
103 if ( !(*i) ) {
104 std::cerr << count << " is null" << std::endl;
105 } // if
106 } // for
107}
108
[51b73452]109template < typename T >
[01aeade]110std::list<T> tail( std::list<T> l ) {
111 if ( ! l.empty() ) {
112 std::list<T> ret(++(l.begin()), l.end());
113 return ret;
114 } // if
[51b73452]115}
116
117template < typename T >
118std::list<T> flatten( std::list < std::list<T> > l) {
[01aeade]119 typedef std::list <T> Ts;
[51b73452]120
[01aeade]121 Ts ret;
[51b73452]122
[a08ba92]123 switch ( l.size() ) {
[01aeade]124 case 0:
125 return ret;
126 case 1:
127 return l.front();
128 default:
129 ret = flatten(tail(l));
130 ret.insert(ret.begin(), l.front().begin(), l.front().end());
131 return ret;
132 } // switch
[51b73452]133}
134
[60089f4]135template < typename T >
[2298f728]136void toString_single( std::ostream & os, const T & value ) {
[79970ed]137 os << value;
138}
139
140template < typename T, typename... Params >
[2298f728]141void toString_single( std::ostream & os, const T & value, const Params & ... params ) {
[79970ed]142 os << value;
143 toString_single( os, params ... );
144}
145
146template < typename ... Params >
[2298f728]147std::string toString( const Params & ... params ) {
[5f2f2d7]148 std::ostringstream os;
[79970ed]149 toString_single( os, params... );
[5f2f2d7]150 return os.str();
[51b73452]151}
152
[3c13c03]153// replace element of list with all elements of another list
[51b73452]154template< typename T >
155void replace( std::list< T > &org, typename std::list< T >::iterator pos, std::list< T > &with ) {
[01aeade]156 typename std::list< T >::iterator next = pos; advance( next, 1 );
[51b73452]157
[01aeade]158 //if ( next != org.end() ) {
[a08ba92]159 org.erase( pos );
160 org.splice( next, with );
161 //}
[51b73452]162
[01aeade]163 return;
[51b73452]164}
165
[3c13c03]166// replace range of a list with a single element
167template< typename T >
168void replace( std::list< T > &org, typename std::list< T >::iterator begin, typename std::list< T >::iterator end, const T & with ) {
169 org.insert( begin, with );
170 org.erase( begin, end );
171}
172
[940bba3]173template< typename... Args >
174auto filter(Args&&... args) -> decltype(std::copy_if(std::forward<Args>(args)...)) {
175 return std::copy_if(std::forward<Args>(args)...);
[51b73452]176}
177
[2bf9c37]178template <typename E, typename UnaryPredicate, template< typename, typename...> class Container, typename... Args >
179void filter( Container< E *, Args... > & container, UnaryPredicate pred, bool doDelete ) {
180 auto i = begin( container );
181 while ( i != end( container ) ) {
182 auto it = next( i );
183 if ( pred( *i ) ) {
184 if ( doDelete ) {
185 delete *i;
186 } // if
187 container.erase( i );
188 } // if
189 i = it;
190 } // while
191}
192
[940bba3]193template< typename... Args >
194auto zip(Args&&... args) -> decltype(zipWith(std::forward<Args>(args)..., std::make_pair)) {
195 return zipWith(std::forward<Args>(args)..., std::make_pair);
[51b73452]196}
197
198template< class InputIterator1, class InputIterator2, class OutputIterator, class BinFunction >
199void zipWith( InputIterator1 b1, InputIterator1 e1, InputIterator2 b2, InputIterator2 e2, OutputIterator out, BinFunction func ) {
[01aeade]200 while ( b1 != e1 && b2 != e2 )
201 *out++ = func(*b1++, *b2++);
[51b73452]202}
203
[d939274]204// it's nice to actually be able to increment iterators by an arbitrary amount
[940bba3]205template< class InputIt, class Distance >
206InputIt operator+( InputIt it, Distance n ) {
207 advance(it, n);
208 return it;
[d939274]209}
210
[79970ed]211template< typename T >
212void warn_single( const T & arg ) {
213 std::cerr << arg << std::endl;
214}
215
216template< typename T, typename... Params >
217void warn_single(const T & arg, const Params & ... params ) {
218 std::cerr << arg;
219 warn_single( params... );
220}
221
222template< typename... Params >
223void warn( const Params & ... params ) {
224 std::cerr << "Warning: ";
225 warn_single( params... );
226}
227
[bc3127d]228/// determines if `pref` is a prefix of `str`
229static inline bool isPrefix( const std::string & str, const std::string & pref ) {
230 if ( pref.size() > str.size() ) return false;
231 auto its = std::mismatch( pref.begin(), pref.end(), str.begin() );
232 return its.first == pref.end();
233}
234
[940bba3]235// -----------------------------------------------------------------------------
236// Ref Counted Singleton class
237// Objects that inherit from this class will have at most one reference to it
238// but if all references die, the object will be deleted.
239
[e491159]240template< typename ThisType >
241class RefCountSingleton {
242 public:
243 static std::shared_ptr<ThisType> get() {
244 if( global_instance.expired() ) {
245 std::shared_ptr<ThisType> new_instance = std::make_shared<ThisType>();
246 global_instance = new_instance;
247 return std::move(new_instance);
248 }
249 return global_instance.lock();
250 }
251 private:
252 static std::weak_ptr<ThisType> global_instance;
253};
254
[1f75e2d]255template< typename ThisType >
256std::weak_ptr<ThisType> RefCountSingleton<ThisType>::global_instance;
257
[940bba3]258// -----------------------------------------------------------------------------
[c8dfcd3]259// RAII object to regulate "save and restore" behaviour, e.g.
260// void Foo::bar() {
261// ValueGuard<int> guard(var); // var is a member of type Foo
262// var = ...;
263// } // var's original value is restored
264template< typename T >
265struct ValueGuard {
266 T old;
267 T& ref;
268
269 ValueGuard(T& inRef) : old(inRef), ref(inRef) {}
270 ~ValueGuard() { ref = old; }
271};
272
[134322e]273template< typename T >
274struct ValueGuardPtr {
275 T old;
276 T* ref;
277
278 ValueGuardPtr(T * inRef) : old( inRef ? *inRef : T() ), ref(inRef) {}
279 ~ValueGuardPtr() { if( ref ) *ref = old; }
280};
281
[234223f]282template< typename aT >
283struct FuncGuard {
284 aT m_after;
285
286 template< typename bT >
287 FuncGuard( bT before, aT after ) : m_after( after ) {
288 before();
289 }
290
291 ~FuncGuard() {
292 m_after();
293 }
294};
295
296template< typename bT, typename aT >
297FuncGuard<aT> makeFuncGuard( bT && before, aT && after ) {
298 return FuncGuard<aT>( std::forward<bT>(before), std::forward<aT>(after) );
299}
300
[134322e]301template< typename T >
302struct ValueGuardPtr< std::list< T > > {
303 std::list< T > old;
304 std::list< T >* ref;
305
306 ValueGuardPtr( std::list< T > * inRef) : old(), ref(inRef) {
307 if( ref ) { swap( *ref, old ); }
308 }
309 ~ValueGuardPtr() { if( ref ) { swap( *ref, old ); } }
310};
311
[940bba3]312// -----------------------------------------------------------------------------
313// Helper struct and function to support
314// for ( val : reverseIterate( container ) ) {}
315// syntax to have a for each that iterates backwards
316
[44f6341]317template< typename T >
[4a9ccc3]318struct reverse_iterate_t {
[44f6341]319 T& ref;
320
[4a9ccc3]321 reverse_iterate_t( T & ref ) : ref(ref) {}
[44f6341]322
323 typedef typename T::reverse_iterator iterator;
324 iterator begin() { return ref.rbegin(); }
325 iterator end() { return ref.rend(); }
326};
327
328template< typename T >
[4a9ccc3]329reverse_iterate_t< T > reverseIterate( T & ref ) {
330 return reverse_iterate_t< T >( ref );
[44f6341]331}
332
[3ad7978]333template< typename OutType, typename Range, typename Functor >
334OutType map_range( const Range& range, Functor&& functor ) {
335 OutType out;
336
337 std::transform(
338 begin( range ),
339 end( range ),
340 std::back_inserter( out ),
341 std::forward< Functor >( functor )
342 );
343
344 return out;
345}
346
[4a9ccc3]347// -----------------------------------------------------------------------------
348// Helper struct and function to support
349// for ( val : group_iterate( container1, container2, ... ) ) {}
350// syntax to have a for each that iterates multiple containers of the same length
[55a68c3]351// TODO: update to use variadic arguments
[4a9ccc3]352
353template< typename T1, typename T2 >
354struct group_iterate_t {
[50377a4]355private:
356 std::tuple<T1, T2> args;
357public:
[6d267ca]358 group_iterate_t( bool skipBoundsCheck, const T1 & v1, const T2 & v2 ) : args(v1, v2) {
[3c09d47]359 assertf(skipBoundsCheck || v1.size() == v2.size(), "group iteration requires containers of the same size: <%zd, %zd>.", v1.size(), v2.size());
[4a9ccc3]360 };
361
[50377a4]362 typedef std::tuple<decltype(*std::get<0>(args).begin()), decltype(*std::get<1>(args).begin())> value_type;
363 typedef decltype(std::get<0>(args).begin()) T1Iter;
364 typedef decltype(std::get<1>(args).begin()) T2Iter;
365
[4a9ccc3]366 struct iterator {
367 typedef std::tuple<T1Iter, T2Iter> IterTuple;
368 IterTuple it;
369 iterator( T1Iter i1, T2Iter i2 ) : it( i1, i2 ) {}
370 iterator operator++() {
371 return iterator( ++std::get<0>(it), ++std::get<1>(it) );
372 }
373 bool operator!=( const iterator &other ) const { return it != other.it; }
[55a68c3]374 value_type operator*() const { return std::tie( *std::get<0>(it), *std::get<1>(it) ); }
[4a9ccc3]375 };
[50377a4]376
[4a9ccc3]377 iterator begin() { return iterator( std::get<0>(args).begin(), std::get<1>(args).begin() ); }
378 iterator end() { return iterator( std::get<0>(args).end(), std::get<1>(args).end() ); }
379};
380
[6d267ca]381/// performs bounds check to ensure that all arguments are of the same length.
[4a9ccc3]382template< typename... Args >
[55a68c3]383group_iterate_t<Args...> group_iterate( Args &&... args ) {
[6d267ca]384 return group_iterate_t<Args...>(false, std::forward<Args>( args )...);
385}
386
387/// does not perform a bounds check - requires user to ensure that iteration terminates when appropriate.
388template< typename... Args >
389group_iterate_t<Args...> unsafe_group_iterate( Args &&... args ) {
390 return group_iterate_t<Args...>(true, std::forward<Args>( args )...);
[4a9ccc3]391}
[294647b]392
[108f3cdb]393// -----------------------------------------------------------------------------
394// Helper struct and function to support
395// for ( val : lazy_map( container1, f ) ) {}
396// syntax to have a for each that iterates a container, mapping each element by applying f
397template< typename T, typename Func >
398struct lambda_iterate_t {
[4639b0d]399 const T & ref;
400 std::function<Func> f;
[108f3cdb]401
402 struct iterator {
403 typedef decltype(begin(ref)) Iter;
404 Iter it;
[4639b0d]405 std::function<Func> f;
406 iterator( Iter it, std::function<Func> f ) : it(it), f(f) {}
[108f3cdb]407 iterator & operator++() {
408 ++it; return *this;
409 }
410 bool operator!=( const iterator &other ) const { return it != other.it; }
411 auto operator*() const -> decltype(f(*it)) { return f(*it); }
412 };
413
[4639b0d]414 lambda_iterate_t( const T & ref, std::function<Func> f ) : ref(ref), f(f) {}
[108f3cdb]415
416 auto begin() const -> decltype(iterator(std::begin(ref), f)) { return iterator(std::begin(ref), f); }
417 auto end() const -> decltype(iterator(std::end(ref), f)) { return iterator(std::end(ref), f); }
418};
419
420template< typename... Args >
[4639b0d]421lambda_iterate_t<Args...> lazy_map( const Args &... args ) {
422 return lambda_iterate_t<Args...>( args...);
[108f3cdb]423}
424
425
426
[51587aa]427// Local Variables: //
428// tab-width: 4 //
429// mode: c++ //
430// compile-command: "make install" //
431// End: //
Note: See TracBrowser for help on using the repository browser.