source: src/Common/utility.h @ 7c0ef42

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 7c0ef42 was f57668a, checked in by Andrew Beach <ajbeach@…>, 7 years ago

Foundation for adding line numbers to generated output.

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