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
51QT_BEGIN_NAMESPACE
52class QObject;
53
54namespace 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 // Traits to detect if there is a conversion between two types,
261 // and that conversion does not include a narrowing conversion.
262 template <typename T>
263 struct NarrowingDetector { T t[1]; }; // from P0608
264
265 template <typename From, typename To, typename Enable = void>
266 struct IsConvertibleWithoutNarrowing : std::false_type {};
267
268 template <typename From, typename To>
269 struct IsConvertibleWithoutNarrowing<From, To,
270 std::void_t< decltype( NarrowingDetector<To>{ {std::declval<From>()} } ) >
271 > : std::true_type {};
272
273 // Check for the actual arguments. If they are exactly the same,
274 // then don't bother checking for narrowing; as a by-product,
275 // this solves the problem of incomplete types (which must be supported,
276 // or they would error out in the trait above).
277 template <typename From, typename To, typename Enable = void>
278 struct AreArgumentsConvertibleWithoutNarrowingBase : std::false_type {};
279
280 template <typename From, typename To>
281 struct AreArgumentsConvertibleWithoutNarrowingBase<From, To,
282 std::enable_if_t<
283 std::disjunction_v<std::is_same<From, To>, IsConvertibleWithoutNarrowing<From, To>>
284 >
285 > : std::true_type {};
286
287 /*
288 Logic that check if the arguments of the slot matches the argument of the signal.
289 To be used like this:
290 static_assert(CheckCompatibleArguments<FunctionPointer<Signal>::Arguments, FunctionPointer<Slot>::Arguments>::value)
291 */
292 template<typename A1, typename A2> struct AreArgumentsCompatible {
293 static int test(const typename RemoveRef<A2>::Type&);
294 static char test(...);
295 static const typename RemoveRef<A1>::Type &dummy();
296 enum { value = sizeof(test(dummy())) == sizeof(int) };
297#ifdef QT_NO_NARROWING_CONVERSIONS_IN_CONNECT
298 using AreArgumentsConvertibleWithoutNarrowing = AreArgumentsConvertibleWithoutNarrowingBase<std::decay_t<A1>, std::decay_t<A2>>;
299 static_assert(AreArgumentsConvertibleWithoutNarrowing::value, "Signal and slot arguments are not compatible (narrowing)");
300#endif
301 };
302 template<typename A1, typename A2> struct AreArgumentsCompatible<A1, A2&> { enum { value = false }; };
303 template<typename A> struct AreArgumentsCompatible<A&, A&> { enum { value = true }; };
304 // void as a return value
305 template<typename A> struct AreArgumentsCompatible<void, A> { enum { value = true }; };
306 template<typename A> struct AreArgumentsCompatible<A, void> { enum { value = true }; };
307 template<> struct AreArgumentsCompatible<void, void> { enum { value = true }; };
308
309 template <typename List1, typename List2> struct CheckCompatibleArguments { enum { value = false }; };
310 template <> struct CheckCompatibleArguments<List<>, List<>> { enum { value = true }; };
311 template <typename List1> struct CheckCompatibleArguments<List1, List<>> { enum { value = true }; };
312 template <typename Arg1, typename Arg2, typename... Tail1, typename... Tail2>
313 struct CheckCompatibleArguments<List<Arg1, Tail1...>, List<Arg2, Tail2...>>
314 {
315 enum { value = AreArgumentsCompatible<typename RemoveConstRef<Arg1>::Type, typename RemoveConstRef<Arg2>::Type>::value
316 && CheckCompatibleArguments<List<Tail1...>, List<Tail2...>>::value };
317 };
318
319 /*
320 Find the maximum number of arguments a functor object can take and be still compatible with
321 the arguments from the signal.
322 Value is the number of arguments, or -1 if nothing matches.
323 */
324 template <typename Functor, typename ArgList> struct ComputeFunctorArgumentCount;
325
326 template <typename Functor, typename ArgList, bool Done> struct ComputeFunctorArgumentCountHelper
327 { enum { Value = -1 }; };
328 template <typename Functor, typename First, typename... ArgList>
329 struct ComputeFunctorArgumentCountHelper<Functor, List<First, ArgList...>, false>
330 : ComputeFunctorArgumentCount<Functor,
331 typename List_Left<List<First, ArgList...>, sizeof...(ArgList)>::Value> {};
332
333 template <typename Functor, typename... ArgList> struct ComputeFunctorArgumentCount<Functor, List<ArgList...>>
334 {
335 template <typename D> static D dummy();
336 template <typename F> static auto test(F f) -> decltype(((f.operator()((dummy<ArgList>())...)), int()));
337 static char test(...);
338 enum {
339 Ok = sizeof(test(dummy<Functor>())) == sizeof(int),
340 Value = Ok ? int(sizeof...(ArgList)) : int(ComputeFunctorArgumentCountHelper<Functor, List<ArgList...>, Ok>::Value)
341 };
342 };
343
344 /* get the return type of a functor, given the signal argument list */
345 template <typename Functor, typename ArgList> struct FunctorReturnType;
346 template <typename Functor, typename ... ArgList> struct FunctorReturnType<Functor, List<ArgList...>> {
347 template <typename D> static D dummy();
348 typedef decltype(dummy<Functor>().operator()((dummy<ArgList>())...)) Value;
349 };
350
351 // internal base class (interface) containing functions required to call a slot managed by a pointer to function.
352 class QSlotObjectBase {
353 QAtomicInt m_ref;
354 // don't use virtual functions here; we don't want the
355 // compiler to create tons of per-polymorphic-class stuff that
356 // we'll never need. We just use one function pointer.
357 typedef void (*ImplFn)(int which, QSlotObjectBase* this_, QObject *receiver, void **args, bool *ret);
358 const ImplFn m_impl;
359 protected:
360 enum Operation {
361 Destroy,
362 Call,
363 Compare,
364
365 NumOperations
366 };
367 public:
368 explicit QSlotObjectBase(ImplFn fn) : m_ref(1), m_impl(fn) {}
369
370 inline int ref() noexcept { return m_ref.ref(); }
371 inline void destroyIfLastRef() noexcept
372 { if (!m_ref.deref()) m_impl(Destroy, this, nullptr, nullptr, nullptr); }
373
374 inline bool compare(void **a) { bool ret = false; m_impl(Compare, this, nullptr, a, &ret); return ret; }
375 inline void call(QObject *r, void **a) { m_impl(Call, this, r, a, nullptr); }
376 protected:
377 ~QSlotObjectBase() {}
378 private:
379 Q_DISABLE_COPY_MOVE(QSlotObjectBase)
380 };
381
382 // implementation of QSlotObjectBase for which the slot is a pointer to member function of a QObject
383 // Args and R are the List of arguments and the return type of the signal to which the slot is connected.
384 template<typename Func, typename Args, typename R> class QSlotObject : public QSlotObjectBase
385 {
386 typedef QtPrivate::FunctionPointer<Func> FuncType;
387 Func function;
388 static void impl(int which, QSlotObjectBase *this_, QObject *r, void **a, bool *ret)
389 {
390 switch (which) {
391 case Destroy:
392 delete static_cast<QSlotObject*>(this_);
393 break;
394 case Call:
395 FuncType::template call<Args, R>(static_cast<QSlotObject*>(this_)->function, static_cast<typename FuncType::Object *>(r), a);
396 break;
397 case Compare:
398 *ret = *reinterpret_cast<Func *>(a) == static_cast<QSlotObject*>(this_)->function;
399 break;
400 case NumOperations: ;
401 }
402 }
403 public:
404 explicit QSlotObject(Func f) : QSlotObjectBase(&impl), function(f) {}
405 };
406 // implementation of QSlotObjectBase for which the slot is a functor (or lambda)
407 // N is the number of arguments
408 // Args and R are the List of arguments and the return type of the signal to which the slot is connected.
409 template<typename Func, int N, typename Args, typename R> class QFunctorSlotObject : public QSlotObjectBase
410 {
411 typedef QtPrivate::Functor<Func, N> FuncType;
412 Func function;
413 static void impl(int which, QSlotObjectBase *this_, QObject *r, void **a, bool *ret)
414 {
415 switch (which) {
416 case Destroy:
417 delete static_cast<QFunctorSlotObject*>(this_);
418 break;
419 case Call:
420 FuncType::template call<Args, R>(static_cast<QFunctorSlotObject*>(this_)->function, r, a);
421 break;
422 case Compare: // not implemented
423 case NumOperations:
424 Q_UNUSED(ret);
425 }
426 }
427 public:
428 explicit QFunctorSlotObject(Func f) : QSlotObjectBase(&impl), function(std::move(f)) {}
429 };
430
431 // typedefs for readability for when there are no parameters
432 template <typename Func>
433 using QSlotObjectWithNoArgs = QSlotObject<Func,
434 QtPrivate::List<>,
435 typename QtPrivate::FunctionPointer<Func>::ReturnType>;
436
437 template <typename Func, typename R>
438 using QFunctorSlotObjectWithNoArgs = QFunctorSlotObject<Func, 0, QtPrivate::List<>, R>;
439
440 template <typename Func>
441 using QFunctorSlotObjectWithNoArgsImplicitReturn = QFunctorSlotObjectWithNoArgs<Func, typename QtPrivate::FunctionPointer<Func>::ReturnType>;
442}
443
444QT_END_NAMESPACE
445
446