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