Reimplement folly::Function to improve compile times.
[folly.git] / folly / Function.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * @author Eric Niebler (eniebler@fb.com), Sven Over (over@fb.com)
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * Acknowledgements: Giuseppe Ottaviano (ott@fb.com)
19  */
20
21 /**
22  * @class Function
23  *
24  * @brief A polymorphic function wrapper that is not copyable and does not
25  *    require the wrapped function to be copy constructible.
26  *
27  * `folly::Function` is a polymorphic function wrapper, similar to
28  * `std::function`. The template parameters of the `folly::Function` define
29  * the parameter signature of the wrapped callable, but not the specific
30  * type of the embedded callable. E.g. a `folly::Function<int(int)>`
31  * can wrap callables that return an `int` when passed an `int`. This can be a
32  * function pointer or any class object implementing one or both of
33  *
34  *     int operator(int);
35  *     int operator(int) const;
36  *
37  * If both are defined, the non-const one takes precedence.
38  *
39  * Unlike `std::function`, a `folly::Function` can wrap objects that are not
40  * copy constructible. As a consequence of this, `folly::Function` itself
41  * is not copyable, either.
42  *
43  * Another difference is that, unlike `std::function`, `folly::Function` treats
44  * const-ness of methods correctly. While a `std::function` allows to wrap
45  * an object that only implements a non-const `operator()` and invoke
46  * a const-reference of the `std::function`, `folly::Function` requires you to
47  * declare a function type as const in order to be able to execute it on a
48  * const-reference.
49  *
50  * For example:
51  *
52  *     class Foo {
53  *      public:
54  *       void operator()() {
55  *         // mutates the Foo object
56  *       }
57  *     };
58  *
59  *     class Bar {
60  *       std::function<void(void)> foo_; // wraps a Foo object
61  *      public:
62  *       void mutateFoo() const
63  *       {
64  *         foo_();
65  *       }
66  *     };
67  *
68  * Even though `mutateFoo` is a const-method, so it can only reference `foo_`
69  * as const, it is able to call the non-const `operator()` of the Foo
70  * object that is embedded in the foo_ function.
71  *
72  * `folly::Function` will not allow you to do that. You will have to decide
73  * whether you need to invoke your wrapped callable from a const reference
74  * (like in the example above), in which case it will only wrap a
75  * `operator() const`. If your functor does not implement that,
76  * compilation will fail. If you do not require to be able to invoke the
77  * wrapped function in a const context, you can wrap any functor that
78  * implements either or both of const and non-const `operator()`.
79  *
80  * The template parameter of `folly::Function`, the `FunctionType`, can be
81  * const-qualified. Be aware that the const is part of the function signature.
82  * It does not mean that the function type is a const type.
83  *
84  *   using FunctionType = R(Args...);
85  *   using ConstFunctionType = R(Args...) const;
86  *
87  * In this example, `FunctionType` and `ConstFunctionType` are different
88  * types. `ConstFunctionType` is not the same as `const FunctionType`.
89  * As a matter of fact, trying to use the latter should emit a compiler
90  * warning or error, because it has no defined meaning.
91  *
92  *     // This will not compile:
93  *     folly::Function<void(void) const> func = Foo();
94  *     // because Foo does not have a member function of the form:
95  *     //   void operator()() const;
96  *
97  *     // This will compile just fine:
98  *     folly::Function<void(void)> func = Foo();
99  *     // and it will wrap the existing member function:
100  *     //   void operator()();
101  *
102  * When should a const function type be used? As a matter of fact, you will
103  * probably not need to use const function types very often. See the following
104  * example:
105  *
106  *     class Bar {
107  *       folly::Function<void()> func_;
108  *       folly::Function<void() const> constFunc_;
109  *
110  *       void someMethod() {
111  *         // Can call func_.
112  *         func_();
113  *         // Can call constFunc_.
114  *         constFunc_();
115  *       }
116  *
117  *       void someConstMethod() const {
118  *         // Can call constFunc_.
119  *         constFunc_();
120  *         // However, cannot call func_ because a non-const method cannot
121  *         // be called from a const one.
122  *       }
123  *     };
124  *
125  * As you can see, whether the `folly::Function`'s function type should
126  * be declared const or not is identical to whether a corresponding method
127  * would be declared const or not.
128  *
129  * You only require a `folly::Function` to hold a const function type, if you
130  * intend to invoke it from within a const context. This is to ensure that
131  * you cannot mutate its inner state when calling in a const context.
132  *
133  * This is how the const/non-const choice relates to lambda functions:
134  *
135  *     // Non-mutable lambdas: can be stored in a non-const...
136  *     folly::Function<void(int)> print_number =
137  *       [] (int number) { std::cout << number << std::endl; };
138  *
139  *     // ...as well as in a const folly::Function
140  *     folly::Function<void(int) const> print_number_const =
141  *       [] (int number) { std::cout << number << std::endl; };
142  *
143  *     // Mutable lambda: can only be stored in a non-const folly::Function:
144  *     int number = 0;
145  *     folly::Function<void()> print_number =
146  *       [number] () mutable { std::cout << ++number << std::endl; };
147  *     // Trying to store the above mutable lambda in a
148  *     // `folly::Function<void() const>` would lead to a compiler error:
149  *     // error: no viable conversion from '(lambda at ...)' to
150  *     // 'folly::Function<void () const>'
151  *
152  * Casting between const and non-const `folly::Function`s:
153  * conversion from const to non-const signatures happens implicitly. Any
154  * function that takes a `folly::Function<R(Args...)>` can be passed
155  * a `folly::Function<R(Args...) const>` without explicit conversion.
156  * This is safe, because casting from const to non-const only entails giving
157  * up the ability to invoke the function from a const context.
158  * Casting from a non-const to a const signature is potentially dangerous,
159  * as it means that a function that may change its inner state when invoked
160  * is made possible to call from a const context. Therefore this cast does
161  * not happen implicitly. The function `folly::constCastFunction` can
162  * be used to perform the cast.
163  *
164  *     // Mutable lambda: can only be stored in a non-const folly::Function:
165  *     int number = 0;
166  *     folly::Function<void()> print_number =
167  *       [number] () mutable { std::cout << ++number << std::endl; };
168  *
169  *     // const-cast to a const folly::Function:
170  *     folly::Function<void() const> print_number_const =
171  *       constCastFunction(std::move(print_number));
172  *
173  * When to use const function types?
174  * Generally, only when you need them. When you use a `folly::Function` as a
175  * member of a struct or class, only use a const function signature when you
176  * need to invoke the function from const context.
177  * When passing a `folly::Function` to a function, the function should accept
178  * a non-const `folly::Function` whenever possible, i.e. when it does not
179  * need to pass on or store a const `folly::Function`. This is the least
180  * possible constraint: you can always pass a const `folly::Function` when
181  * the function accepts a non-const one.
182  *
183  * How does the const behaviour compare to `std::function`?
184  * `std::function` can wrap object with non-const invokation behaviour but
185  * exposes them as const. The equivalent behaviour can be achieved with
186  * `folly::Function` like so:
187  *
188  *     std::function<void(void)> stdfunc = someCallable;
189  *
190  *     folly::Function<void(void) const> uniqfunc = constCastFunction(
191  *       folly::Function<void(void)>(someCallable)
192  *     );
193  *
194  * You need to wrap the callable first in a non-const `folly::Function` to
195  * select a non-const invoke operator (or the const one if no non-const one is
196  * present), and then move it into a const `folly::Function` using
197  * `constCastFunction`.
198  * The name of `constCastFunction` should warn you that something
199  * potentially dangerous is happening. As a matter of fact, using
200  * `std::function` always involves this potentially dangerous aspect, which
201  * is why it is not considered fully const-safe or even const-correct.
202  * However, in most of the cases you will not need the dangerous aspect at all.
203  * Either you do not require invokation of the function from a const context,
204  * in which case you do not need to use `constCastFunction` and just
205  * use the inner `folly::Function` in the example above, i.e. just use a
206  * non-const `folly::Function`. Or, you may need invokation from const, but
207  * the callable you are wrapping does not mutate its state (e.g. it is a class
208  * object and implements `operator() const`, or it is a normal,
209  * non-mutable lambda), in which case you can wrap the callable in a const
210  * `folly::Function` directly, without using `constCastFunction`.
211  * Only if you require invokation from a const context of a callable that
212  * may mutate itself when invoked you have to go through the above procedure.
213  * However, in that case what you do is potentially dangerous and requires
214  * the equivalent of a `const_cast`, hence you need to call
215  * `constCastFunction`.
216  */
217
218 #pragma once
219
220 #include <functional>
221 #include <memory>
222 #include <new>
223 #include <type_traits>
224 #include <utility>
225
226 #include <folly/CppAttributes.h>
227
228 namespace folly {
229
230 namespace impl {
231 template <typename FunctionType, bool Const = false>
232 class Function;
233
234 template <typename ReturnType, typename... Args>
235 Function<ReturnType(Args...), true> constCastFunction(
236     Function<ReturnType(Args...), false>&&) noexcept;
237 }
238
239 namespace detail {
240 namespace function {
241
242 enum class Op { MOVE, NUKE, FULL, HEAP };
243
244 union Data {
245   void* big;
246   typename std::aligned_storage<6 * sizeof(void*)>::type small;
247 };
248
249 struct Tag {};
250
251 template <bool If, typename T>
252 using ConstIf = typename std::conditional<If, const T, T>::type;
253
254 template <typename Fun, typename FunT = typename std::decay<Fun>::type>
255 using IsSmall = std::integral_constant<
256     bool,
257     (sizeof(FunT) <= sizeof(Data::small) &&
258 #if defined(__GNUC__) && !defined(__clang__)
259      // GCC has a name mangling bug that causes hard errors if we use noexcept
260      // directly here. Last tested at gcc 5.3.0.
261      // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70790
262      std::is_nothrow_move_constructible<FunT>::value
263 #else
264      // Same as is_nothrow_move_constructible, but w/ no template instantiation.
265      noexcept(FunT(std::declval<FunT&&>()))
266 #endif
267      )>;
268
269 template <typename T>
270 bool isNullPtrFn(T* p) {
271   return p == nullptr;
272 }
273 template <typename T>
274 std::false_type isNullPtrFn(T&&) {
275   return {};
276 }
277
278 template <typename ReturnType, typename... Args>
279 ReturnType uninitCall(Data&, Args&&...) {
280   throw std::bad_function_call();
281 }
282 inline bool uninitNoop(Op, Data*, Data*) {
283   return false;
284 }
285 } // namespace function
286 } // namespace detail
287
288 namespace impl {
289
290 template <typename ReturnType, typename... Args, bool Const>
291 class Function<ReturnType(Args...), Const> final {
292   using Data = detail::function::Data;
293   using Op = detail::function::Op;
294   using Tag = detail::function::Tag;
295   using Call = ReturnType (*)(Data&, Args&&...);
296   using Exec = bool (*)(Op, Data*, Data*);
297
298   template <typename T>
299   using ConstIf = detail::function::ConstIf<Const, T>;
300   template <typename Fun>
301   using IsSmall = detail::function::IsSmall<Fun>;
302
303   Data data_;
304   Call call_;
305   Exec exec_;
306
307   friend Function<ReturnType(Args...), true> constCastFunction<>(
308       Function<ReturnType(Args...), false>&&) noexcept;
309   friend class Function<ReturnType(Args...), !Const>;
310
311   template <typename Fun, typename FunT = typename std::decay<Fun>::type>
312   Function(
313       Fun&& fun,
314       typename std::enable_if<IsSmall<Fun>::value, Tag>::
315           type) noexcept(noexcept(FunT(std::declval<Fun>())))
316       : Function() {
317     struct Ops {
318       static ReturnType call(Data& p, Args&&... args) {
319         return static_cast<ReturnType>((*static_cast<ConstIf<FunT>*>(
320             (void*)&p.small))(static_cast<Args&&>(args)...));
321       }
322       static bool exec(Op o, Data* src, Data* dst) {
323         switch (o) {
324           case Op::MOVE:
325             ::new ((void*)&dst->small)
326                 FunT(std::move(*static_cast<FunT*>((void*)&src->small)));
327             FOLLY_FALLTHROUGH;
328           case Op::NUKE:
329             static_cast<FunT*>((void*)&src->small)->~FunT();
330             break;
331           case Op::FULL:
332             return true;
333           case Op::HEAP:
334             break;
335         }
336         return false;
337       }
338     };
339     if (!detail::function::isNullPtrFn(fun)) {
340       ::new (&data_.small) FunT(static_cast<Fun&&>(fun));
341       exec_ = &Ops::exec;
342       call_ = &Ops::call;
343     }
344   }
345
346   template <typename Fun, typename FunT = typename std::decay<Fun>::type>
347   Function(Fun&& fun, typename std::enable_if<!IsSmall<Fun>::value, Tag>::type)
348       : Function() {
349     struct Ops {
350       static ReturnType call(Data& p, Args&&... args) {
351         return static_cast<ReturnType>((*static_cast<ConstIf<FunT>*>(p.big))(
352             static_cast<Args&&>(args)...));
353       }
354       static bool exec(Op o, Data* src, Data* dst) {
355         switch (o) {
356           case Op::MOVE:
357             dst->big = src->big;
358             src->big = nullptr;
359             break;
360           case Op::NUKE:
361             delete static_cast<FunT*>(src->big);
362             break;
363           case Op::FULL:
364           case Op::HEAP:
365             break;
366         }
367         return true;
368       }
369     };
370     data_.big = new FunT(static_cast<Fun&&>(fun));
371     call_ = &Ops::call;
372     exec_ = &Ops::exec;
373   }
374   template <typename F, typename G = typename std::decay<F>::type>
375   using ResultOf = decltype(static_cast<ReturnType>(
376       std::declval<ConstIf<G>&>()(std::declval<Args>()...)));
377
378  public:
379   /**
380    * Default constructor. Constructs an empty Function.
381    */
382   Function() noexcept
383       : call_(&detail::function::uninitCall<ReturnType, Args...>),
384         exec_(&detail::function::uninitNoop) {}
385
386   // not copyable
387   // NOTE: Deleting the non-const copy constructor is unusual but necessary to
388   // prevent copies from non-const `Function` object from selecting the
389   // perfect forwarding implicit converting constructor below
390   // (i.e., `template <typename Fun> Function(Fun&&)`).
391   Function(Function&) = delete;
392   Function(const Function&) = delete;
393
394   /**
395    * Move constructor
396    */
397   Function(Function&& that) noexcept : Function() {
398     that.exec_(Op::MOVE, &that.data_, &data_);
399     std::swap(call_, that.call_);
400     std::swap(exec_, that.exec_);
401   }
402
403   /**
404    * Constructs an empty `Function`.
405    */
406   /* implicit */ Function(std::nullptr_t) noexcept : Function() {}
407
408   /**
409    * Constructs a new `Function` from any callable object. This
410    * handles function pointers, pointers to static member functions,
411    * `std::reference_wrapper` objects, `std::function` objects, and arbitrary
412    * objects that implement `operator()` if the parameter signature
413    * matches (i.e. it returns R when called with Args...).
414    * For a `Function` with a const function type, the object must be
415    * callable from a const-reference, i.e. implement `operator() const`.
416    * For a `Function` with a non-const function type, the object will
417    * be called from a non-const reference, which means that it will execute
418    * a non-const `operator()` if it is defined, and falls back to
419    * `operator() const` otherwise.
420    *
421    * \note `typename = ResultOf<Fun>` prevents this overload from being
422    * selected by overload resolution when `fun` is not a compatible function.
423    */
424   template <class Fun, typename = ResultOf<Fun>>
425   /* implicit */ Function(Fun&& fun) noexcept(
426       noexcept(Function(std::declval<Fun>(), Tag{})))
427       : Function(static_cast<Fun&&>(fun), Tag{}) {}
428
429   /**
430    * For moving a `Function<X(Ys..) const>` into a `Function<X(Ys...)>`.
431    */
432   template <
433       bool OtherConst,
434       typename std::enable_if<!Const && OtherConst, int>::type = 0>
435   Function(Function<ReturnType(Args...), OtherConst>&& that) noexcept
436       : Function() {
437     that.exec_(Op::MOVE, &that.data_, &data_);
438     std::swap(call_, that.call_);
439     std::swap(exec_, that.exec_);
440   }
441
442   /**
443    * If `ptr` is null, constructs an empty `Function`. Otherwise,
444    * this constructor is equivalent to `Function(std::mem_fn(ptr))`.
445    */
446   template <
447       typename Member,
448       typename Class,
449       // Prevent this overload from being selected when `ptr` is not a
450       // compatible member function pointer.
451       typename = decltype(Function(std::mem_fn((Member Class::*)0)))>
452   /* implicit */ Function(Member Class::*ptr) noexcept : Function() {
453     if (ptr) {
454       *this = std::mem_fn(ptr);
455     }
456   }
457
458   ~Function() {
459     exec_(Op::NUKE, &data_, nullptr);
460   }
461
462   Function& operator=(Function&) = delete;
463   Function& operator=(const Function&) = delete;
464
465   /**
466    * Move assignment operator
467    */
468   Function& operator=(Function&& that) noexcept {
469     if (&that != this) {
470       // Q: Why is is safe to destroy and reconstruct this object in place?
471       // A: Two reasons: First, `Function` is a final class, so in doing this
472       //    we aren't slicing off any derived parts. And second, the move
473       //    operation is guaranteed not to throw so we always leave the object
474       //    in a valid state.
475       this->~Function();
476       ::new (this) Function(std::move(that));
477     }
478     return *this;
479   }
480
481   /**
482    * Assigns a callable object to this `Function`. If the operation fails,
483    * `*this` is left unmodified.
484    *
485    * \note `typename = ResultOf<Fun>` prevents this overload from being
486    * selected by overload resolution when `fun` is not a compatible function.
487    */
488   template <class Fun, typename = ResultOf<Fun>>
489   Function& operator=(Fun&& fun) noexcept(
490       noexcept(/* implicit */ Function(std::declval<Fun>()))) {
491     // Doing this in place is more efficient when we can do so safely.
492     if (noexcept(/* implicit */ Function(std::declval<Fun>()))) {
493       // Q: Why is is safe to destroy and reconstruct this object in place?
494       // A: See the explanation in the move assignment operator.
495       this->~Function();
496       ::new (this) Function(static_cast<Fun&&>(fun));
497     } else {
498       // Construct a temporary and (nothrow) swap.
499       Function(static_cast<Fun&&>(fun)).swap(*this);
500     }
501     return *this;
502   }
503
504   /**
505    * Clears this `Function`.
506    */
507   Function& operator=(std::nullptr_t) noexcept {
508     return (*this = Function());
509   }
510
511   /**
512    * If `ptr` is null, clears this `Function`. Otherwise, this assignment
513    * operator is equivalent to `*this = std::mem_fn(ptr)`.
514    */
515   template <typename Member, typename Class>
516   auto operator=(Member Class::*ptr) noexcept
517       // Prevent this overload from being selected when `ptr` is not a
518       // compatible member function pointer.
519       -> decltype(operator=(std::mem_fn(ptr))) {
520     return ptr ? (*this = std::mem_fn(ptr)) : (*this = Function());
521   }
522
523   /**
524    * Call the wrapped callable object with the specified arguments.
525    * If this `Function` object is a const `folly::Function` object,
526    * this overload shall not participate in overload resolution.
527    */
528   template <
529       // `True` makes `operator()` a template so we can SFINAE on `Const`,
530       // which is non-deduced here.
531       bool True = true,
532       typename std::enable_if<True && !Const, int>::type = 0>
533   ReturnType operator()(Args... args) {
534     return call_(data_, static_cast<Args&&>(args)...);
535   }
536
537   /**
538    * Call the wrapped callable object with the specified arguments.
539    * If this `Function` object is not a const `folly::Function` object,
540    * this overload shall not participate in overload resolution.
541    */
542   template <
543       // `True` makes `operator()` a template so we can SFINAE on `Const`,
544       // which is non-deduced here.
545       bool True = true,
546       typename std::enable_if<True && Const, int>::type = 0>
547   ReturnType operator()(Args... args) const {
548     return call_(const_cast<Data&>(data_), static_cast<Args&&>(args)...);
549   }
550
551   /**
552    * Exchanges the callable objects of `*this` and `that`.
553    */
554   void swap(Function& that) noexcept {
555     std::swap(*this, that);
556   }
557
558   /**
559    * Returns `true` if this `Function` contains a callable, i.e. is
560    * non-empty.
561    */
562   explicit operator bool() const noexcept {
563     return exec_(Op::FULL, nullptr, nullptr);
564   }
565
566   /**
567    * Returns `true` if this `Function` stores the callable on the
568    * heap. If `false` is returned, there has been no additional memory
569    * allocation and the callable is stored inside the `Function`
570    * object itself.
571    */
572   bool hasAllocatedMemory() const noexcept {
573     return exec_(Op::HEAP, nullptr, nullptr);
574   }
575
576   /**
577    * Construct a `std::function` by moving in the contents of this `Function`.
578    * Note that the returned `std::function` will share its state (i.e. captured
579    * data) across all copies you make of it, so be very careful when copying.
580    */
581   std::function<ReturnType(Args...)> asStdFunction() && {
582     struct Impl {
583       std::shared_ptr<Function> sp_;
584       ReturnType operator()(Args&&... args) const {
585         return (*sp_)(static_cast<Args&&>(args)...);
586       }
587     };
588     return Impl{std::make_shared<Function>(std::move(*this))};
589   }
590 };
591
592 template <typename FunctionType, bool Const>
593 void swap(
594     Function<FunctionType, Const>& lhs,
595     Function<FunctionType, Const>& rhs) noexcept {
596   lhs.swap(rhs);
597 }
598
599 template <typename FunctionType, bool Const>
600 bool operator==(const Function<FunctionType, Const>& fn, std::nullptr_t) {
601   return !fn;
602 }
603
604 template <typename FunctionType, bool Const>
605 bool operator==(std::nullptr_t, const Function<FunctionType, Const>& fn) {
606   return !fn;
607 }
608
609 template <typename FunctionType, bool Const>
610 bool operator!=(const Function<FunctionType, Const>& fn, std::nullptr_t) {
611   return !(fn == nullptr);
612 }
613
614 template <typename FunctionType, bool Const>
615 bool operator!=(std::nullptr_t, const Function<FunctionType, Const>& fn) {
616   return !(nullptr == fn);
617 }
618
619 template <typename ReturnType, typename... Args>
620 Function<ReturnType(Args...), true> constCastFunction(
621     Function<ReturnType(Args...), false>&& that) noexcept {
622   Function<ReturnType(Args...), true> fn{};
623   that.exec_(detail::function::Op::MOVE, &that.data_, &fn.data_);
624   std::swap(fn.call_, that.call_);
625   std::swap(fn.exec_, that.exec_);
626   return fn;
627 }
628
629 template <typename FunctionType>
630 Function<FunctionType, true> constCastFunction(
631     Function<FunctionType, true>&& that) noexcept {
632   return std::move(that);
633 }
634
635 template <typename FunctionType>
636 struct MakeFunction {};
637
638 template <typename ReturnType, typename... Args>
639 struct MakeFunction<ReturnType(Args...)> {
640   using type = Function<ReturnType(Args...), false>;
641 };
642
643 template <typename ReturnType, typename... Args>
644 struct MakeFunction<ReturnType(Args...) const> {
645   using type = Function<ReturnType(Args...), true>;
646 };
647 } // namespace impl
648
649 /* using override */ using impl::constCastFunction;
650
651 template <typename FunctionType>
652 using Function = typename impl::MakeFunction<FunctionType>::type;
653 }