1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Copyright (C) 2013 Olivier Goffart <ogoffart@woboq.com>
5 ** Contact: https://www.qt.io/licensing/
6 **
7 ** This file is part of the QtCore module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** Commercial License Usage
11 ** Licensees holding valid commercial Qt licenses may use this file in
12 ** accordance with the commercial license agreement provided with the
13 ** Software or, alternatively, in accordance with the terms contained in
14 ** a written agreement between you and The Qt Company. For licensing terms
15 ** and conditions see https://www.qt.io/terms-conditions. For further
16 ** information use the contact form at https://www.qt.io/contact-us.
17 **
18 ** GNU Lesser General Public License Usage
19 ** Alternatively, this file may be used under the terms of the GNU Lesser
20 ** General Public License version 3 as published by the Free Software
21 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
22 ** packaging of this file. Please review the following information to
23 ** ensure the GNU Lesser General Public License version 3 requirements
24 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25 **
26 ** GNU General Public License Usage
27 ** Alternatively, this file may be used under the terms of the GNU
28 ** General Public License version 2.0 or (at your option) the GNU General
29 ** Public license version 3 or any later version approved by the KDE Free
30 ** Qt Foundation. The licenses are as published by the Free Software
31 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32 ** included in the packaging of this file. Please review the following
33 ** information to ensure the GNU General Public License requirements will
34 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35 ** https://www.gnu.org/licenses/gpl-3.0.html.
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40 
41 #ifndef QOBJECTDEFS_H
42 #error Do not include qobjectdefs_impl.h directly
43 #include <QtCore/qnamespace.h>
44 #endif
45 
46 #if 0
47 #pragma qt_sync_skip_header_check
48 #pragma qt_sync_stop_processing
49 #endif
50 
51 QT_BEGIN_NAMESPACE
52 class QObject;
53 
54 namespace QtPrivate {
55     template <typename T> struct RemoveRef { typedef T Type; };
56     template <typename T> struct RemoveRef<T&> { typedef T Type; };
57     template <typename T> struct RemoveConstRef { typedef T Type; };
58     template <typename T> struct RemoveConstRef<const T&> { typedef T Type; };
59 
60     /*
61        The following List classes are used to help to handle the list of arguments.
62        It follow the same principles as the lisp lists.
63        List_Left<L,N> take a list and a number as a parameter and returns (via the Value typedef,
64        the list composed of the first N element of the list
65      */
66     // With variadic template, lists are represented using a variadic template argument instead of the lisp way
67     template <typename...> struct List {};
68     template <typename Head, typename... Tail> struct List<Head, Tail...> { typedef Head Car; typedef List<Tail...> Cdr; };
69     template <typename, typename> struct List_Append;
70     template <typename... L1, typename...L2> struct List_Append<List<L1...>, List<L2...>> { typedef List<L1..., L2...> Value; };
71     template <typename L, int N> struct List_Left {
72         typedef typename List_Append<List<typename L::Car>,typename List_Left<typename L::Cdr, N - 1>::Value>::Value Value;
73     };
74     template <typename L> struct List_Left<L, 0> { typedef List<> Value; };
75     // List_Select<L,N> returns (via typedef Value) the Nth element of the list L
76     template <typename L, int N> struct List_Select { typedef typename List_Select<typename L::Cdr, N - 1>::Value Value; };
77     template <typename L> struct List_Select<L,0> { typedef typename L::Car Value; };
78 
79     /*
80        trick to set the return value of a slot that works even if the signal or the slot returns void
81        to be used like     function(), ApplyReturnValue<ReturnType>(&return_value)
82        if function() returns a value, the operator,(T, ApplyReturnValue<ReturnType>) is called, but if it
83        returns void, the builtin one is used without an error.
84     */
85     template <typename T>
86     struct ApplyReturnValue {
87         void *data;
88         explicit ApplyReturnValue(void *data_) : data(data_) {}
89     };
90     template<typename T, typename U>
91     void operator,(T &&value, const ApplyReturnValue<U> &container) {
92         if (container.data)
93             *reinterpret_cast<U *>(container.data) = std::forward<T>(value);
94     }
95     template<typename T>
96     void operator,(T, const ApplyReturnValue<void> &) {}
97 
98 
99     /*
100       The FunctionPointer<Func> struct is a type trait for function pointer.
101         - ArgumentCount  is the number of argument, or -1 if it is unknown
102         - the Object typedef is the Object of a pointer to member function
103         - the Arguments typedef is the list of argument (in a QtPrivate::List)
104         - the Function typedef is an alias to the template parameter Func
105         - the call<Args, R>(f,o,args) method is used to call that slot
106             Args is the list of argument of the signal
107             R is the return type of the signal
108             f is the function pointer
109             o is the receiver object
110             and args is the array of pointer to arguments, as used in qt_metacall
111 
112        The Functor<Func,N> struct is the helper to call a functor of N argument.
113        its call function is the same as the FunctionPointer::call function.
114      */
115     template<class T> using InvokeGenSeq = typename T::Type;
116 
117     template<int...> struct IndexesList { using Type = IndexesList; };
118 
119     template<int N, class S1, class S2> struct ConcatSeqImpl;
120 
121     template<int N, int... I1, int... I2>
122     struct ConcatSeqImpl<N, IndexesList<I1...>, IndexesList<I2...>>
123         : IndexesList<I1..., (N + I2)...>{};
124 
125     template<int N, class S1, class S2>
126     using ConcatSeq = InvokeGenSeq<ConcatSeqImpl<N, S1, S2>>;
127 
128     template<int N> struct GenSeq;
129     template<int N> using makeIndexSequence = InvokeGenSeq<GenSeq<N>>;
130 
131     template<int N>
132     struct GenSeq : ConcatSeq<N/2, makeIndexSequence<N/2>, makeIndexSequence<N - N/2>>{};
133 
134     template<> struct GenSeq<0> : IndexesList<>{};
135     template<> struct GenSeq<1> : IndexesList<0>{};
136 
137     template<int N>
138     struct Indexes { using Value = makeIndexSequence<N>; };
139 
140     template<typename Func> struct FunctionPointer { enum {ArgumentCount = -1, IsPointerToMemberFunction = false}; };
141 
142     template <typename, typename, typename, typename> struct FunctorCall;
143     template <int... II, typename... SignalArgs, typename R, typename Function>
144     struct FunctorCall<IndexesList<II...>, List<SignalArgs...>, R, Function> {
145         static void call(Function &f, void **arg) {
146             f((*reinterpret_cast<typename RemoveRef<SignalArgs>::Type *>(arg[II+1]))...), ApplyReturnValue<R>(arg[0]);
147         }
148     };
149     template <int... II, typename... SignalArgs, typename R, typename... SlotArgs, typename SlotRet, class Obj>
150     struct FunctorCall<IndexesList<II...>, List<SignalArgs...>, R, SlotRet (Obj::*)(SlotArgs...)> {
151         static void call(SlotRet (Obj::*f)(SlotArgs...), Obj *o, void **arg) {
152             (o->*f)((*reinterpret_cast<typename RemoveRef<SignalArgs>::Type *>(arg[II+1]))...), ApplyReturnValue<R>(arg[0]);
153         }
154     };
155     template <int... II, typename... SignalArgs, typename R, typename... SlotArgs, typename SlotRet, class Obj>
156     struct FunctorCall<IndexesList<II...>, List<SignalArgs...>, R, SlotRet (Obj::*)(SlotArgs...) const> {
157         static void call(SlotRet (Obj::*f)(SlotArgs...) const, Obj *o, void **arg) {
158             (o->*f)((*reinterpret_cast<typename RemoveRef<SignalArgs>::Type *>(arg[II+1]))...), ApplyReturnValue<R>(arg[0]);
159         }
160     };
161 #if defined(__cpp_noexcept_function_type) && __cpp_noexcept_function_type >= 201510
162     template <int... II, typename... SignalArgs, typename R, typename... SlotArgs, typename SlotRet, class Obj>
163     struct FunctorCall<IndexesList<II...>, List<SignalArgs...>, R, SlotRet (Obj::*)(SlotArgs...) noexcept> {
164         static void call(SlotRet (Obj::*f)(SlotArgs...) noexcept, Obj *o, void **arg) {
165             (o->*f)((*reinterpret_cast<typename RemoveRef<SignalArgs>::Type *>(arg[II+1]))...), ApplyReturnValue<R>(arg[0]);
166         }
167     };
168     template <int... II, typename... SignalArgs, typename R, typename... SlotArgs, typename SlotRet, class Obj>
169     struct FunctorCall<IndexesList<II...>, List<SignalArgs...>, R, SlotRet (Obj::*)(SlotArgs...) const noexcept> {
170         static void call(SlotRet (Obj::*f)(SlotArgs...) const noexcept, Obj *o, void **arg) {
171             (o->*f)((*reinterpret_cast<typename RemoveRef<SignalArgs>::Type *>(arg[II+1]))...), ApplyReturnValue<R>(arg[0]);
172         }
173     };
174 #endif
175 
176     template<class Obj, typename Ret, typename... Args> struct FunctionPointer<Ret (Obj::*) (Args...)>
177     {
178         typedef Obj Object;
179         typedef List<Args...>  Arguments;
180         typedef Ret ReturnType;
181         typedef Ret (Obj::*Function) (Args...);
182         enum {ArgumentCount = sizeof...(Args), IsPointerToMemberFunction = true};
183         template <typename SignalArgs, typename R>
184         static void call(Function f, Obj *o, void **arg) {
185             FunctorCall<typename Indexes<ArgumentCount>::Value, SignalArgs, R, Function>::call(f, o, arg);
186         }
187     };
188     template<class Obj, typename Ret, typename... Args> struct FunctionPointer<Ret (Obj::*) (Args...) const>
189     {
190         typedef Obj Object;
191         typedef List<Args...>  Arguments;
192         typedef Ret ReturnType;
193         typedef Ret (Obj::*Function) (Args...) const;
194         enum {ArgumentCount = sizeof...(Args), IsPointerToMemberFunction = true};
195         template <typename SignalArgs, typename R>
196         static void call(Function f, Obj *o, void **arg) {
197             FunctorCall<typename Indexes<ArgumentCount>::Value, SignalArgs, R, Function>::call(f, o, arg);
198         }
199     };
200 
201     template<typename Ret, typename... Args> struct FunctionPointer<Ret (*) (Args...)>
202     {
203         typedef List<Args...> Arguments;
204         typedef Ret ReturnType;
205         typedef Ret (*Function) (Args...);
206         enum {ArgumentCount = sizeof...(Args), IsPointerToMemberFunction = false};
207         template <typename SignalArgs, typename R>
208         static void call(Function f, void *, void **arg) {
209             FunctorCall<typename Indexes<ArgumentCount>::Value, SignalArgs, R, Function>::call(f, arg);
210         }
211     };
212 
213 #if defined(__cpp_noexcept_function_type) && __cpp_noexcept_function_type >= 201510
214     template<class Obj, typename Ret, typename... Args> struct FunctionPointer<Ret (Obj::*) (Args...) noexcept>
215     {
216         typedef Obj Object;
217         typedef List<Args...>  Arguments;
218         typedef Ret ReturnType;
219         typedef Ret (Obj::*Function) (Args...) noexcept;
220         enum {ArgumentCount = sizeof...(Args), IsPointerToMemberFunction = true};
221         template <typename SignalArgs, typename R>
222         static void call(Function f, Obj *o, void **arg) {
223             FunctorCall<typename Indexes<ArgumentCount>::Value, SignalArgs, R, Function>::call(f, o, arg);
224         }
225     };
226     template<class Obj, typename Ret, typename... Args> struct FunctionPointer<Ret (Obj::*) (Args...) const noexcept>
227     {
228         typedef Obj Object;
229         typedef List<Args...>  Arguments;
230         typedef Ret ReturnType;
231         typedef Ret (Obj::*Function) (Args...) const noexcept;
232         enum {ArgumentCount = sizeof...(Args), IsPointerToMemberFunction = true};
233         template <typename SignalArgs, typename R>
234         static void call(Function f, Obj *o, void **arg) {
235             FunctorCall<typename Indexes<ArgumentCount>::Value, SignalArgs, R, Function>::call(f, o, arg);
236         }
237     };
238 
239     template<typename Ret, typename... Args> struct FunctionPointer<Ret (*) (Args...) noexcept>
240     {
241         typedef List<Args...> Arguments;
242         typedef Ret ReturnType;
243         typedef Ret (*Function) (Args...) noexcept;
244         enum {ArgumentCount = sizeof...(Args), IsPointerToMemberFunction = false};
245         template <typename SignalArgs, typename R>
246         static void call(Function f, void *, void **arg) {
247             FunctorCall<typename Indexes<ArgumentCount>::Value, SignalArgs, R, Function>::call(f, arg);
248         }
249     };
250 #endif
251 
252     template<typename Function, int N> struct Functor
253     {
254         template <typename SignalArgs, typename R>
255         static void call(Function &f, void *, void **arg) {
256             FunctorCall<typename Indexes<N>::Value, SignalArgs, R, Function>::call(f, arg);
257         }
258     };
259 
260     /*
261         Logic that checks if the underlying type of an enum is signed or not.
262         Needs an external, explicit check that E is indeed an enum. Works
263         around the fact that it's undefined behavior to instantiate
264         std::underlying_type on non-enums (cf. §20.13.7.6 [meta.trans.other]).
265     */
266     template<typename E, typename Enable = void>
267     struct IsEnumUnderlyingTypeSigned : std::false_type
268     {
269     };
270 
271     template<typename E>
272     struct IsEnumUnderlyingTypeSigned<E, typename std::enable_if<std::is_enum<E>::value>::type>
273             : std::integral_constant<bool, std::is_signed<typename std::underlying_type<E>::type>::value>
274     {
275     };
276 
277     /*
278        Logic that checks if the argument of the slot does not narrow the
279        argument of the signal when used in list initialization. Cf. §8.5.4.7
280        [dcl.init.list] for the definition of narrowing.
281        For incomplete From/To types, there's no narrowing.
282     */
283     template<typename From, typename To, typename Enable = void>
284     struct AreArgumentsNarrowedBase : std::false_type
285     {
286     };
287 
288     template <typename T>
289     using is_bool = std::is_same<bool, typename std::decay<T>::type>;
290 
291     template<typename From, typename To>
292     struct AreArgumentsNarrowedBase<From, To, typename std::enable_if<sizeof(From) && sizeof(To)>::type>
293         : std::integral_constant<bool,
294               (std::is_floating_point<From>::value && std::is_integral<To>::value) ||
295               (std::is_floating_point<From>::value && std::is_floating_point<To>::value && sizeof(From) > sizeof(To)) ||
296               ((std::is_pointer<From>::value || std::is_member_pointer<From>::value) && QtPrivate::is_bool<To>::value) ||
297               ((std::is_integral<From>::value || std::is_enum<From>::value) && std::is_floating_point<To>::value) ||
298               (std::is_integral<From>::value && std::is_integral<To>::value
299                && (sizeof(From) > sizeof(To)
300                    || (std::is_signed<From>::value ? !std::is_signed<To>::value
301                        : (std::is_signed<To>::value && sizeof(From) == sizeof(To))))) ||
302               (std::is_enum<From>::value && std::is_integral<To>::value
303                && (sizeof(From) > sizeof(To)
304                    || (IsEnumUnderlyingTypeSigned<From>::value ? !std::is_signed<To>::value
305                        : (std::is_signed<To>::value && sizeof(From) == sizeof(To)))))
306               >
307     {
308     };
309 
310     /*
311        Logic that check if the arguments of the slot matches the argument of the signal.
312        To be used like this:
313        Q_STATIC_ASSERT(CheckCompatibleArguments<FunctionPointer<Signal>::Arguments, FunctionPointer<Slot>::Arguments>::value)
314     */
315     template<typename A1, typename A2> struct AreArgumentsCompatible {
316         static int test(const typename RemoveRef<A2>::Type&);
317         static char test(...);
318         static const typename RemoveRef<A1>::Type &dummy();
319         enum { value = sizeof(test(dummy())) == sizeof(int) };
320 #ifdef QT_NO_NARROWING_CONVERSIONS_IN_CONNECT
321         using AreArgumentsNarrowed = AreArgumentsNarrowedBase<typename RemoveRef<A1>::Type, typename RemoveRef<A2>::Type>;
322         Q_STATIC_ASSERT_X(!AreArgumentsNarrowed::value, "Signal and slot arguments are not compatible (narrowing)");
323 #endif
324     };
325     template<typename A1, typename A2> struct AreArgumentsCompatible<A1, A2&> { enum { value = false }; };
326     template<typename A> struct AreArgumentsCompatible<A&, A&> { enum { value = true }; };
327     // void as a return value
328     template<typename A> struct AreArgumentsCompatible<void, A> { enum { value = true }; };
329     template<typename A> struct AreArgumentsCompatible<A, void> { enum { value = true }; };
330     template<> struct AreArgumentsCompatible<void, void> { enum { value = true }; };
331 
332     template <typename List1, typename List2> struct CheckCompatibleArguments { enum { value = false }; };
333     template <> struct CheckCompatibleArguments<List<>, List<>> { enum { value = true }; };
334     template <typename List1> struct CheckCompatibleArguments<List1, List<>> { enum { value = true }; };
335     template <typename Arg1, typename Arg2, typename... Tail1, typename... Tail2>
336     struct CheckCompatibleArguments<List<Arg1, Tail1...>, List<Arg2, Tail2...>>
337     {
338         enum { value = AreArgumentsCompatible<typename RemoveConstRef<Arg1>::Type, typename RemoveConstRef<Arg2>::Type>::value
339                     && CheckCompatibleArguments<List<Tail1...>, List<Tail2...>>::value };
340     };
341 
342     /*
343        Find the maximum number of arguments a functor object can take and be still compatible with
344        the arguments from the signal.
345        Value is the number of arguments, or -1 if nothing matches.
346      */
347     template <typename Functor, typename ArgList> struct ComputeFunctorArgumentCount;
348 
349     template <typename Functor, typename ArgList, bool Done> struct ComputeFunctorArgumentCountHelper
350     { enum { Value = -1 }; };
351     template <typename Functor, typename First, typename... ArgList>
352     struct ComputeFunctorArgumentCountHelper<Functor, List<First, ArgList...>, false>
353         : ComputeFunctorArgumentCount<Functor,
354             typename List_Left<List<First, ArgList...>, sizeof...(ArgList)>::Value> {};
355 
356     template <typename Functor, typename... ArgList> struct ComputeFunctorArgumentCount<Functor, List<ArgList...>>
357     {
358         template <typename D> static D dummy();
359         template <typename F> static auto test(F f) -> decltype(((f.operator()((dummy<ArgList>())...)), int()));
360         static char test(...);
361         enum {
362             Ok = sizeof(test(dummy<Functor>())) == sizeof(int),
363             Value = Ok ? int(sizeof...(ArgList)) : int(ComputeFunctorArgumentCountHelper<Functor, List<ArgList...>, Ok>::Value)
364         };
365     };
366 
367     /* get the return type of a functor, given the signal argument list  */
368     template <typename Functor, typename ArgList> struct FunctorReturnType;
369     template <typename Functor, typename ... ArgList> struct FunctorReturnType<Functor, List<ArgList...>> {
370         template <typename D> static D dummy();
371         typedef decltype(dummy<Functor>().operator()((dummy<ArgList>())...)) Value;
372     };
373 
374     // internal base class (interface) containing functions required to call a slot managed by a pointer to function.
375     class QSlotObjectBase {
376         QAtomicInt m_ref;
377         // don't use virtual functions here; we don't want the
378         // compiler to create tons of per-polymorphic-class stuff that
379         // we'll never need. We just use one function pointer.
380         typedef void (*ImplFn)(int which, QSlotObjectBase* this_, QObject *receiver, void **args, bool *ret);
381         const ImplFn m_impl;
382     protected:
383         enum Operation {
384             Destroy,
385             Call,
386             Compare,
387 
388             NumOperations
389         };
390     public:
391         explicit QSlotObjectBase(ImplFn fn) : m_ref(1), m_impl(fn) {}
392 
393         inline int ref() noexcept { return m_ref.ref(); }
394         inline void destroyIfLastRef() noexcept
395         { if (!m_ref.deref()) m_impl(Destroy, this, nullptr, nullptr, nullptr); }
396 
397         inline bool compare(void **a) { bool ret = false; m_impl(Compare, this, nullptr, a, &ret); return ret; }
398         inline void call(QObject *r, void **a)  { m_impl(Call,    this, r, a, nullptr); }
399     protected:
400         ~QSlotObjectBase() {}
401     private:
402         Q_DISABLE_COPY_MOVE(QSlotObjectBase)
403     };
404 
405     // implementation of QSlotObjectBase for which the slot is a pointer to member function of a QObject
406     // Args and R are the List of arguments and the return type of the signal to which the slot is connected.
407     template<typename Func, typename Args, typename R> class QSlotObject : public QSlotObjectBase
408     {
409         typedef QtPrivate::FunctionPointer<Func> FuncType;
410         Func function;
411         static void impl(int which, QSlotObjectBase *this_, QObject *r, void **a, bool *ret)
412         {
413             switch (which) {
414             case Destroy:
415                 delete static_cast<QSlotObject*>(this_);
416                 break;
417             case Call:
418                 FuncType::template call<Args, R>(static_cast<QSlotObject*>(this_)->function, static_cast<typename FuncType::Object *>(r), a);
419                 break;
420             case Compare:
421                 *ret = *reinterpret_cast<Func *>(a) == static_cast<QSlotObject*>(this_)->function;
422                 break;
423             case NumOperations: ;
424             }
425         }
426     public:
427         explicit QSlotObject(Func f) : QSlotObjectBase(&impl), function(f) {}
428     };
429     // implementation of QSlotObjectBase for which the slot is a functor (or lambda)
430     // N is the number of arguments
431     // Args and R are the List of arguments and the return type of the signal to which the slot is connected.
432     template<typename Func, int N, typename Args, typename R> class QFunctorSlotObject : public QSlotObjectBase
433     {
434         typedef QtPrivate::Functor<Func, N> FuncType;
435         Func function;
436         static void impl(int which, QSlotObjectBase *this_, QObject *r, void **a, bool *ret)
437         {
438             switch (which) {
439             case Destroy:
440                 delete static_cast<QFunctorSlotObject*>(this_);
441                 break;
442             case Call:
443                 FuncType::template call<Args, R>(static_cast<QFunctorSlotObject*>(this_)->function, r, a);
444                 break;
445             case Compare: // not implemented
446             case NumOperations:
447                 Q_UNUSED(ret);
448             }
449         }
450     public:
451         explicit QFunctorSlotObject(Func f) : QSlotObjectBase(&impl), function(std::move(f)) {}
452     };
453 
454     // typedefs for readability for when there are no parameters
455     template <typename Func>
456     using QSlotObjectWithNoArgs = QSlotObject<Func,
457                                               QtPrivate::List<>,
458                                               typename QtPrivate::FunctionPointer<Func>::ReturnType>;
459 
460     template <typename Func, typename R>
461     using QFunctorSlotObjectWithNoArgs = QFunctorSlotObject<Func, 0, QtPrivate::List<>, R>;
462 
463     template <typename Func>
464     using QFunctorSlotObjectWithNoArgsImplicitReturn = QFunctorSlotObjectWithNoArgs<Func, typename QtPrivate::FunctionPointer<Func>::ReturnType>;
465 }
466 
467 QT_END_NAMESPACE
468 
469