Revert "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  * A traits class to check for incomplete types.
295  *
296  * Example:
297  *
298  *  struct FullyDeclared {}; // complete type
299  *  struct ForwardDeclared; // incomplete type
300  *
301  *  is_complete<int>::value // evaluates to true
302  *  is_complete<FullyDeclared>::value // evaluates to true
303  *  is_complete<ForwardDeclared>::value // evaluates to false
304  *
305  *  struct ForwardDeclared {}; // declared, at last
306  *
307  *  is_complete<ForwardDeclared>::value // now it evaluates to true
308  *
309  * @author: Marcelo Juchem <marcelo@fb.com>
310  */
311 template <typename T>
312 class is_complete {
313   template <unsigned long long> struct sfinae {};
314   template <typename U>
315   constexpr static bool test(sfinae<sizeof(U)>*) { return true; }
316   template <typename> constexpr static bool test(...) { return false; }
317 public:
318   constexpr static bool value = test<T>(nullptr);
319 };
320
321 /*
322  * Complementary type traits for integral comparisons.
323  *
324  * For instance, `if(x < 0)` yields an error in clang for unsigned types
325  *  when -Werror is used due to -Wtautological-compare
326  *
327  *
328  * @author: Marcelo Juchem <marcelo@fb.com>
329  */
330
331 namespace detail {
332
333 template <typename T, bool>
334 struct is_negative_impl {
335   constexpr static bool check(T x) { return x < 0; }
336 };
337
338 template <typename T>
339 struct is_negative_impl<T, false> {
340   constexpr static bool check(T x) { return false; }
341 };
342
343 // folly::to integral specializations can end up generating code
344 // inside what are really static ifs (not executed because of the templated
345 // types) that violate -Wsign-compare so suppress them in order to not prevent
346 // all calling code from using it.
347 #pragma GCC diagnostic push
348 #pragma GCC diagnostic ignored "-Wsign-compare"
349
350 template <typename RHS, RHS rhs, typename LHS>
351 bool less_than_impl(
352   typename std::enable_if<
353     (rhs <= std::numeric_limits<LHS>::max()
354       && rhs > std::numeric_limits<LHS>::min()),
355     LHS
356   >::type const lhs
357 ) {
358   return lhs < rhs;
359 }
360
361 template <typename RHS, RHS rhs, typename LHS>
362 bool less_than_impl(
363   typename std::enable_if<
364     (rhs > std::numeric_limits<LHS>::max()),
365     LHS
366   >::type const
367 ) {
368   return true;
369 }
370
371 template <typename RHS, RHS rhs, typename LHS>
372 bool less_than_impl(
373   typename std::enable_if<
374     (rhs <= std::numeric_limits<LHS>::min()),
375     LHS
376   >::type const
377 ) {
378   return false;
379 }
380
381 #pragma GCC diagnostic pop
382
383 template <typename RHS, RHS rhs, typename LHS>
384 bool greater_than_impl(
385   typename std::enable_if<
386     (rhs <= std::numeric_limits<LHS>::max()
387       && rhs >= std::numeric_limits<LHS>::min()),
388     LHS
389   >::type const lhs
390 ) {
391   return lhs > rhs;
392 }
393
394 template <typename RHS, RHS rhs, typename LHS>
395 bool greater_than_impl(
396   typename std::enable_if<
397     (rhs > std::numeric_limits<LHS>::max()),
398     LHS
399   >::type const
400 ) {
401   return false;
402 }
403
404 template <typename RHS, RHS rhs, typename LHS>
405 bool greater_than_impl(
406   typename std::enable_if<
407     (rhs < std::numeric_limits<LHS>::min()),
408     LHS
409   >::type const
410 ) {
411   return true;
412 }
413
414 } // namespace detail {
415
416 // same as `x < 0`
417 template <typename T>
418 constexpr bool is_negative(T x) {
419   return folly::detail::is_negative_impl<T, std::is_signed<T>::value>::check(x);
420 }
421
422 // same as `x <= 0`
423 template <typename T>
424 constexpr bool is_non_positive(T x) { return !x || folly::is_negative(x); }
425
426 // same as `x > 0`
427 template <typename T>
428 constexpr bool is_positive(T x) { return !is_non_positive(x); }
429
430 // same as `x >= 0`
431 template <typename T>
432 constexpr bool is_non_negative(T x) {
433   return !x || is_positive(x);
434 }
435
436 template <typename RHS, RHS rhs, typename LHS>
437 bool less_than(LHS const lhs) {
438   return detail::less_than_impl<
439     RHS, rhs, typename std::remove_reference<LHS>::type
440   >(lhs);
441 }
442
443 template <typename RHS, RHS rhs, typename LHS>
444 bool greater_than(LHS const lhs) {
445   return detail::greater_than_impl<
446     RHS, rhs, typename std::remove_reference<LHS>::type
447   >(lhs);
448 }
449
450 } // namespace folly
451
452 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(std::basic_string);
453 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::vector);
454 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::list);
455 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::deque);
456 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::unique_ptr);
457 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::shared_ptr);
458 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::function);
459
460 // Boost
461 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(boost::shared_ptr);
462
463 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, cv_qual) \
464   template <typename TTheClass_, typename RTheReturn_, typename... TTheArgs_> \
465   class classname<TTheClass_, RTheReturn_(TTheArgs_...) cv_qual> { \
466     template < \
467       typename UTheClass_, RTheReturn_ (UTheClass_::*)(TTheArgs_...) cv_qual \
468     > struct sfinae {}; \
469     template <typename UTheClass_> \
470     constexpr static bool test(sfinae<UTheClass_, &UTheClass_::func_name>*) \
471     { return true; } \
472     template <typename> \
473     constexpr static bool test(...) { return false; } \
474   public: \
475     constexpr static bool value = test<TTheClass_>(nullptr); \
476   }
477
478 /*
479  * The FOLLY_CREATE_HAS_MEMBER_FN_TRAITS is used to create traits
480  * classes that check for the existence of a member function with
481  * a given name and signature. It currently does not support
482  * checking for inherited members.
483  *
484  * Such classes receive two template parameters: the class to be checked
485  * and the signature of the member function. A static boolean field
486  * named `value` (which is also constexpr) tells whether such member
487  * function exists.
488  *
489  * Each traits class created is bound only to the member name, not to
490  * its signature nor to the type of the class containing it.
491  *
492  * Say you need to know if a given class has a member function named
493  * `test` with the following signature:
494  *
495  *    int test() const;
496  *
497  * You'd need this macro to create a traits class to check for a member
498  * named `test`, and then use this traits class to check for the signature:
499  *
500  * namespace {
501  *
502  * FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_test_traits, test);
503  *
504  * } // unnamed-namespace
505  *
506  * void some_func() {
507  *   cout << "Does class Foo have a member int test() const? "
508  *     << boolalpha << has_test_traits<Foo, int() const>::value;
509  * }
510  *
511  * You can use the same traits class to test for a completely different
512  * signature, on a completely different class, as long as the member name
513  * is the same:
514  *
515  * void some_func() {
516  *   cout << "Does class Foo have a member int test()? "
517  *     << boolalpha << has_test_traits<Foo, int()>::value;
518  *   cout << "Does class Foo have a member int test() const? "
519  *     << boolalpha << has_test_traits<Foo, int() const>::value;
520  *   cout << "Does class Bar have a member double test(const string&, long)? "
521  *     << boolalpha << has_test_traits<Bar, double(const string&, long)>::value;
522  * }
523  *
524  * @author: Marcelo Juchem <marcelo@fb.com>
525  */
526 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(classname, func_name) \
527   template <typename, typename> class classname; \
528   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, ); \
529   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, const); \
530   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL( \
531       classname, func_name, /* nolint */ volatile); \
532   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL( \
533       classname, func_name, /* nolint */ volatile const)
534
535 #endif //FOLLY_BASE_TRAITS_H_