Remove extra ';' from used macros in Traits.h
[folly.git] / folly / Traits.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 // @author: Andrei Alexandrescu
18
19 #pragma once
20
21 #include <memory>
22 #include <limits>
23 #include <type_traits>
24 #include <functional>
25
26 #include <folly/Portability.h>
27
28 // libc++ doesn't provide this header, nor does msvc
29 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
30 // This file appears in two locations: inside fbcode and in the
31 // libstdc++ source code (when embedding fbstring as std::string).
32 // To aid in this schizophrenic use, two macros are defined in
33 // c++config.h:
34 //   _LIBSTDCXX_FBSTRING - Set inside libstdc++.  This is useful to
35 //      gate use inside fbcode v. libstdc++
36 #include <bits/c++config.h>
37 #endif
38
39 #include <boost/type_traits.hpp>
40 #include <boost/mpl/has_xxx.hpp>
41
42 namespace folly {
43
44 /**
45  * IsRelocatable<T>::value describes the ability of moving around
46  * memory a value of type T by using memcpy (as opposed to the
47  * conservative approach of calling the copy constructor and then
48  * destroying the old temporary. Essentially for a relocatable type,
49  * the following two sequences of code should be semantically
50  * equivalent:
51  *
52  * void move1(T * from, T * to) {
53  *   new(to) T(from);
54  *   (*from).~T();
55  * }
56  *
57  * void move2(T * from, T * to) {
58  *   memcpy(to, from, sizeof(T));
59  * }
60  *
61  * Most C++ types are relocatable; the ones that aren't would include
62  * internal pointers or (very rarely) would need to update remote
63  * pointers to pointers tracking them. All C++ primitive types and
64  * type constructors are relocatable.
65  *
66  * This property can be used in a variety of optimizations. Currently
67  * fbvector uses this property intensively.
68  *
69  * The default conservatively assumes the type is not
70  * relocatable. Several specializations are defined for known
71  * types. You may want to add your own specializations. Do so in
72  * namespace folly and make sure you keep the specialization of
73  * IsRelocatable<SomeStruct> in the same header as SomeStruct.
74  *
75  * You may also declare a type to be relocatable by including
76  *    `typedef std::true_type IsRelocatable;`
77  * in the class header.
78  *
79  * It may be unset in a base class by overriding the typedef to false_type.
80  */
81 /*
82  * IsTriviallyCopyable describes the value semantics property. C++11 contains
83  * the type trait is_trivially_copyable; however, it is not yet implemented
84  * in gcc (as of 4.7.1), and the user may wish to specify otherwise.
85  */
86 /*
87  * IsZeroInitializable describes the property that default construction is the
88  * same as memset(dst, 0, sizeof(T)).
89  */
90
91 namespace traits_detail {
92
93 #define FOLLY_HAS_TRUE_XXX(name)                                             \
94   BOOST_MPL_HAS_XXX_TRAIT_DEF(name)                                          \
95   template <class T>                                                         \
96   struct name##_is_true : std::is_same<typename T::name, std::true_type> {}; \
97   template <class T>                                                         \
98   struct has_true_##name : std::conditional<                                 \
99                                has_##name<T>::value,                         \
100                                name##_is_true<T>,                            \
101                                std::false_type>::type {};
102
103 FOLLY_HAS_TRUE_XXX(IsRelocatable)
104 FOLLY_HAS_TRUE_XXX(IsZeroInitializable)
105 FOLLY_HAS_TRUE_XXX(IsTriviallyCopyable)
106
107 #undef FOLLY_HAS_TRUE_XXX
108 }
109
110 template <class T> struct IsTriviallyCopyable
111   : std::integral_constant<bool,
112       !std::is_class<T>::value ||
113       // TODO: add alternate clause is_trivially_copyable, when available
114       traits_detail::has_true_IsTriviallyCopyable<T>::value
115     > {};
116
117 template <class T> struct IsRelocatable
118   : std::integral_constant<bool,
119       !std::is_class<T>::value ||
120       // TODO add this line (and some tests for it) when we upgrade to gcc 4.7
121       //std::is_trivially_move_constructible<T>::value ||
122       IsTriviallyCopyable<T>::value ||
123       traits_detail::has_true_IsRelocatable<T>::value
124     > {};
125
126 template <class T> struct IsZeroInitializable
127   : std::integral_constant<bool,
128       !std::is_class<T>::value ||
129       traits_detail::has_true_IsZeroInitializable<T>::value
130     > {};
131
132 template <typename...>
133 struct Conjunction : std::true_type {};
134 template <typename T>
135 struct Conjunction<T> : T {};
136 template <typename T, typename... TList>
137 struct Conjunction<T, TList...>
138     : std::conditional<T::value, Conjunction<TList...>, T>::type {};
139
140 template <typename...>
141 struct Disjunction : std::false_type {};
142 template <typename T>
143 struct Disjunction<T> : T {};
144 template <typename T, typename... TList>
145 struct Disjunction<T, TList...>
146     : std::conditional<T::value, T, Disjunction<TList...>>::type {};
147
148 template <typename T>
149 struct Negation : std::integral_constant<bool, !T::value> {};
150
151 } // namespace folly
152
153 /**
154  * Use this macro ONLY inside namespace folly. When using it with a
155  * regular type, use it like this:
156  *
157  * // Make sure you're at namespace ::folly scope
158  * template<> FOLLY_ASSUME_RELOCATABLE(MyType)
159  *
160  * When using it with a template type, use it like this:
161  *
162  * // Make sure you're at namespace ::folly scope
163  * template<class T1, class T2>
164  * FOLLY_ASSUME_RELOCATABLE(MyType<T1, T2>)
165  */
166 #define FOLLY_ASSUME_RELOCATABLE(...) \
167   struct IsRelocatable<  __VA_ARGS__ > : std::true_type {};
168
169 /**
170  * Use this macro ONLY inside namespace boost. When using it with a
171  * regular type, use it like this:
172  *
173  * // Make sure you're at namespace ::boost scope
174  * template<> FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(MyType)
175  *
176  * When using it with a template type, use it like this:
177  *
178  * // Make sure you're at namespace ::boost scope
179  * template<class T1, class T2>
180  * FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(MyType<T1, T2>)
181  */
182 #define FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(...) \
183   struct has_nothrow_constructor<  __VA_ARGS__ > : ::boost::true_type {};
184
185 /**
186  * The FOLLY_ASSUME_FBVECTOR_COMPATIBLE* macros below encode two
187  * assumptions: first, that the type is relocatable per IsRelocatable
188  * above, and that it has a nothrow constructor. Most types can be
189  * assumed to satisfy both conditions, but it is the responsibility of
190  * the user to state that assumption. User-defined classes will not
191  * work with fbvector (see FBVector.h) unless they state this
192  * combination of properties.
193  *
194  * Use FOLLY_ASSUME_FBVECTOR_COMPATIBLE with regular types like this:
195  *
196  * FOLLY_ASSUME_FBVECTOR_COMPATIBLE(MyType)
197  *
198  * The versions FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1, _2, _3, and _4
199  * allow using the macro for describing templatized classes with 1, 2,
200  * 3, and 4 template parameters respectively. For template classes
201  * just use the macro with the appropriate number and pass the name of
202  * the template to it. Example:
203  *
204  * template <class T1, class T2> class MyType { ... };
205  * ...
206  * // Make sure you're at global scope
207  * FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(MyType)
208  */
209
210 // Use this macro ONLY at global level (no namespace)
211 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE(...)                           \
212   namespace folly { template<> FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__) }   \
213   namespace boost { \
214   template<> FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__) }
215 // Use this macro ONLY at global level (no namespace)
216 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(...)                         \
217   namespace folly {                                                     \
218   template <class T1> FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1>) }       \
219     namespace boost {                                                   \
220     template <class T1> FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1>) }
221 // Use this macro ONLY at global level (no namespace)
222 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(...)                 \
223   namespace folly {                                             \
224   template <class T1, class T2>                                 \
225   FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2>) }               \
226     namespace boost {                                           \
227     template <class T1, class T2>                               \
228     FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1, T2>) }
229 // Use this macro ONLY at global level (no namespace)
230 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(...)                         \
231   namespace folly {                                                     \
232   template <class T1, class T2, class T3>                               \
233   FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2, T3>) }                   \
234     namespace boost {                                                   \
235     template <class T1, class T2, class T3>                             \
236     FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1, T2, T3>) }
237 // Use this macro ONLY at global level (no namespace)
238 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_4(...)                         \
239   namespace folly {                                                     \
240   template <class T1, class T2, class T3, class T4>                     \
241   FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2, T3, T4>) }               \
242     namespace boost {                                                   \
243     template <class T1, class T2, class T3, class T4>                   \
244     FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1, T2, T3, T4>) }
245
246 /**
247  * Instantiate FOLLY_ASSUME_FBVECTOR_COMPATIBLE for a few types. It is
248  * safe to assume that pair is compatible if both of its components
249  * are. Furthermore, all STL containers can be assumed to comply,
250  * although that is not guaranteed by the standard.
251  */
252
253 FOLLY_NAMESPACE_STD_BEGIN
254
255 template <class T, class U>
256   struct pair;
257 #ifndef _GLIBCXX_USE_FB
258 FOLLY_GLIBCXX_NAMESPACE_CXX11_BEGIN
259 template <class T, class R, class A>
260   class basic_string;
261 FOLLY_GLIBCXX_NAMESPACE_CXX11_END
262 #else
263 template <class T, class R, class A, class S>
264   class basic_string;
265 #endif
266 template <class T, class A>
267   class vector;
268 template <class T, class A>
269   class deque;
270 FOLLY_GLIBCXX_NAMESPACE_CXX11_BEGIN
271 template <class T, class A>
272   class list;
273 FOLLY_GLIBCXX_NAMESPACE_CXX11_END
274 template <class T, class C, class A>
275   class set;
276 template <class K, class V, class C, class A>
277   class map;
278 template <class T>
279   class shared_ptr;
280
281 FOLLY_NAMESPACE_STD_END
282
283 namespace boost {
284
285 template <class T> class shared_ptr;
286
287 template <class T, class U>
288 struct has_nothrow_constructor< std::pair<T, U> >
289     : std::integral_constant<bool,
290         has_nothrow_constructor<T>::value &&
291         has_nothrow_constructor<U>::value> {};
292
293 } // namespace boost
294
295 namespace folly {
296
297 // STL commonly-used types
298 template <class T, class U>
299 struct IsRelocatable< std::pair<T, U> >
300     : std::integral_constant<bool,
301         IsRelocatable<T>::value &&
302         IsRelocatable<U>::value> {};
303
304 // Is T one of T1, T2, ..., Tn?
305 template <class T, class... Ts>
306 struct IsOneOf {
307   enum { value = false };
308 };
309
310 template <class T, class T1, class... Ts>
311 struct IsOneOf<T, T1, Ts...> {
312   enum { value = std::is_same<T, T1>::value || IsOneOf<T, Ts...>::value };
313 };
314
315 /*
316  * Complementary type traits for integral comparisons.
317  *
318  * For instance, `if(x < 0)` yields an error in clang for unsigned types
319  *  when -Werror is used due to -Wtautological-compare
320  *
321  *
322  * @author: Marcelo Juchem <marcelo@fb.com>
323  */
324
325 namespace detail {
326
327 template <typename T, bool>
328 struct is_negative_impl {
329   constexpr static bool check(T x) { return x < 0; }
330 };
331
332 template <typename T>
333 struct is_negative_impl<T, false> {
334   constexpr static bool check(T) { return false; }
335 };
336
337 // folly::to integral specializations can end up generating code
338 // inside what are really static ifs (not executed because of the templated
339 // types) that violate -Wsign-compare and/or -Wbool-compare so suppress them
340 // in order to not prevent all calling code from using it.
341 #pragma GCC diagnostic push
342 #pragma GCC diagnostic ignored "-Wsign-compare"
343 #if __GNUC_PREREQ(5, 0)
344 #pragma GCC diagnostic ignored "-Wbool-compare"
345 #endif
346
347 template <typename RHS, RHS rhs, typename LHS>
348 bool less_than_impl(LHS const lhs) {
349   return
350     rhs > std::numeric_limits<LHS>::max() ? true :
351     rhs <= std::numeric_limits<LHS>::min() ? false :
352     lhs < rhs;
353 }
354
355 template <typename RHS, RHS rhs, typename LHS>
356 bool greater_than_impl(LHS const lhs) {
357   return
358     rhs > std::numeric_limits<LHS>::max() ? false :
359     rhs < std::numeric_limits<LHS>::min() ? true :
360     lhs > rhs;
361 }
362
363 #pragma GCC diagnostic pop
364
365 } // namespace detail {
366
367 // same as `x < 0`
368 template <typename T>
369 constexpr bool is_negative(T x) {
370   return folly::detail::is_negative_impl<T, std::is_signed<T>::value>::check(x);
371 }
372
373 // same as `x <= 0`
374 template <typename T>
375 constexpr bool is_non_positive(T x) { return !x || folly::is_negative(x); }
376
377 // same as `x > 0`
378 template <typename T>
379 constexpr bool is_positive(T x) { return !is_non_positive(x); }
380
381 // same as `x >= 0`
382 template <typename T>
383 constexpr bool is_non_negative(T x) {
384   return !x || is_positive(x);
385 }
386
387 template <typename RHS, RHS rhs, typename LHS>
388 bool less_than(LHS const lhs) {
389   return detail::less_than_impl<
390     RHS, rhs, typename std::remove_reference<LHS>::type
391   >(lhs);
392 }
393
394 template <typename RHS, RHS rhs, typename LHS>
395 bool greater_than(LHS const lhs) {
396   return detail::greater_than_impl<
397     RHS, rhs, typename std::remove_reference<LHS>::type
398   >(lhs);
399 }
400
401 /**
402  * Like std::piecewise_construct, a tag type & instance used for in-place
403  * construction of non-movable contained types, e.g. by Synchronized.
404  */
405 struct construct_in_place_t {};
406 constexpr construct_in_place_t construct_in_place{};
407
408 } // namespace folly
409
410 // gcc-5.0 changed string's implementation in libgcc to be non-relocatable
411 #if __GNUC__ < 5
412 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(std::basic_string)
413 #endif
414 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::vector)
415 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::list)
416 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::deque)
417 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::unique_ptr)
418 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::shared_ptr)
419 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::function)
420
421 // Boost
422 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(boost::shared_ptr)
423
424 #define FOLLY_CREATE_HAS_MEMBER_TYPE_TRAITS(classname, type_name) \
425   template <typename T> \
426   struct classname { \
427     template <typename C> \
428     constexpr static bool test(typename C::type_name*) { return true; } \
429     template <typename> \
430     constexpr static bool test(...) { return false; } \
431     constexpr static bool value = test<T>(nullptr); \
432   }
433
434 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, cv_qual) \
435   template <typename TTheClass_, typename RTheReturn_, typename... TTheArgs_> \
436   class classname<TTheClass_, RTheReturn_(TTheArgs_...) cv_qual> { \
437     template < \
438       typename UTheClass_, RTheReturn_ (UTheClass_::*)(TTheArgs_...) cv_qual \
439     > struct sfinae {}; \
440     template <typename UTheClass_> \
441     constexpr static bool test(sfinae<UTheClass_, &UTheClass_::func_name>*) \
442     { return true; } \
443     template <typename> \
444     constexpr static bool test(...) { return false; } \
445   public: \
446     constexpr static bool value = test<TTheClass_>(nullptr); \
447   }
448
449 /*
450  * The FOLLY_CREATE_HAS_MEMBER_FN_TRAITS is used to create traits
451  * classes that check for the existence of a member function with
452  * a given name and signature. It currently does not support
453  * checking for inherited members.
454  *
455  * Such classes receive two template parameters: the class to be checked
456  * and the signature of the member function. A static boolean field
457  * named `value` (which is also constexpr) tells whether such member
458  * function exists.
459  *
460  * Each traits class created is bound only to the member name, not to
461  * its signature nor to the type of the class containing it.
462  *
463  * Say you need to know if a given class has a member function named
464  * `test` with the following signature:
465  *
466  *    int test() const;
467  *
468  * You'd need this macro to create a traits class to check for a member
469  * named `test`, and then use this traits class to check for the signature:
470  *
471  * namespace {
472  *
473  * FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_test_traits, test);
474  *
475  * } // unnamed-namespace
476  *
477  * void some_func() {
478  *   cout << "Does class Foo have a member int test() const? "
479  *     << boolalpha << has_test_traits<Foo, int() const>::value;
480  * }
481  *
482  * You can use the same traits class to test for a completely different
483  * signature, on a completely different class, as long as the member name
484  * is the same:
485  *
486  * void some_func() {
487  *   cout << "Does class Foo have a member int test()? "
488  *     << boolalpha << has_test_traits<Foo, int()>::value;
489  *   cout << "Does class Foo have a member int test() const? "
490  *     << boolalpha << has_test_traits<Foo, int() const>::value;
491  *   cout << "Does class Bar have a member double test(const string&, long)? "
492  *     << boolalpha << has_test_traits<Bar, double(const string&, long)>::value;
493  * }
494  *
495  * @author: Marcelo Juchem <marcelo@fb.com>
496  */
497 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(classname, func_name) \
498   template <typename, typename> class classname; \
499   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, ); \
500   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, const); \
501   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL( \
502       classname, func_name, /* nolint */ volatile); \
503   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL( \
504       classname, func_name, /* nolint */ volatile const)