source: src/Common/utility.h@ b7c89aa

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 b7c89aa was 5cbacf1, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Refactor eval into Common

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