File: heap_bind.h

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (353 lines) | stat: -rw-r--r-- 12,636 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_BIND_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_BIND_H_

#include "base/functional/function_ref.h"
#include "base/types/is_instantiation.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/member.h"
#include "third_party/blink/renderer/platform/heap/trace_traits.h"

// Synopsys:
//
// HeapCallback<Signature> HeapBind(Functor, Args...)
//
// Example:
//
// class A : publlic GarbageCollected<A> {
//  public:
//   void Frobnicate(const String& s, int a);
//   void Trace(Visitor* visitor) const;
// };
//
// HeapCallback<void(int)> callback =
//     HeapBind(&A::Frobnicate, MakeGarbageCollected<A>(), "foo");
// ...
// callback.Run(42);
//
// Notes and limitations:
// - HeapCallback<Signature> DISALLOW_NEW() (similar to Member<>) and must
//    be traced;
// - There's no Persistent<> counterpart to HeapCallback<>. If you want to
//    use it in a non-GC class, just use regular base::Bind();
// - Supported Callables are standalone functions, pointer to members,
//    captureless lambdas and HeapCallbacks.
// - There's no support for weak receivers (yet);
// - Methods must accept GarbageCollected classes by pointers if these are to be
// bound;
// - Only pointers to GarbageCollected types can be bound;
// - base::Unretained() is not supported;

namespace blink::bindings {

// Implementation notes:
// `HeapCallback<>` is essentially a `Member<>`-like wrapper for a pointer
// to `HeapCallback::Closure<>`, which is a pure interface implemented by
// `HeapCallbackClosureImpl<>.` The latter stores actual functor and state,
// and is the only one that knows the type of bound arguments. The former
// two are specialized by callback _signature_, which is essentially a
// function signature of the `HeapCallback::Run()` method.
namespace internal {
template <typename Functor, typename BoundArgs, typename FreeArgs>
class HeapCallbackClosureImpl;
}  // namespace internal

template <typename CallbackSignature>
class HeapCallback;

template <typename Ret, typename... Args>
class HeapCallback<Ret(Args...)> final {
  DISALLOW_NEW();

  class Closure;

  template <typename Functor, typename BoundArgs, typename FreeArgs>
  friend class internal::HeapCallbackClosureImpl;

 public:
  HeapCallback() = default;
  explicit HeapCallback(Closure* closure) : closure_(closure) {}
  explicit operator bool() const { return !!closure_; }

  bool operator==(const HeapCallback& r) const = default;
  bool operator!=(const HeapCallback& r) const = default;

  Ret Run(Args... args) {
    DCHECK(closure_);
    return closure_->Run(std::forward<Args>(args)...);
  }
  void Trace(Visitor* visitor) const { visitor->Trace(closure_); }

 private:
  Member<Closure> closure_;
};

template <typename Ret, typename... Args>
class HeapCallback<Ret(Args...)>::Closure
    : public GarbageCollected<HeapCallback<Ret(Args...)>::Closure> {
 public:
  using SignatureType = Ret(Args...);

  virtual Ret Run(Args... args) = 0;
  virtual void Trace(Visitor* visitor) const {}
  // Required for properly destroying bound non-trivially destructable types.
  virtual ~Closure() = default;
};

namespace internal {

// A trivial wrapper around individual bound argument, which just selects an
// appropriate backing type (e.g. a Member<> for GC'ed types) and traces it
// (if required).
template <typename Arg>
class ArgStorage final {
  DISALLOW_NEW();

 private:
  static_assert(!std::is_reference_v<Arg>);  // Caller should remove_cvref.
  using StorageType = std::conditional_t<std::is_pointer_v<Arg>,
                                         Member<std::remove_pointer_t<Arg>>,
                                         Arg>;
  using PassType = std::conditional_t<std::is_pointer_v<Arg>, Arg, Arg&>;

 public:
  static_assert(!IsGarbageCollectedType<std::remove_pointer_t<Arg>>::value ||
                    std::is_pointer_v<Arg>,
                "GarbageCollected classes should be bound as pointers");
  static_assert(!std::is_pointer_v<Arg> ||
                    IsGarbageCollectedType<std::remove_pointer_t<Arg>>::value,
                "Only pointers to GarbageCollected types may be bound");

  template <typename PassedType>
  explicit ArgStorage(PassedType&& arg)
      : storage_(std::forward<PassedType>(arg)) {}

  void Trace(Visitor* visitor) const {
    blink::TraceIfNeeded<StorageType>::Trace(visitor, storage_);
  }

  PassType Unwrap() {
    if constexpr (std::is_pointer_v<Arg>) {
      return storage_.Get();
    } else {
      return storage_;
    }
  }

 private:
  StorageType storage_;
};

// A tuple of ArgStorage for all arguments.
template <bool arg0_is_nullable, typename Tuple, typename IndexSequence>
class BoundState;

template <bool arg0_is_nullable, typename... Args, size_t... index>
class BoundState<arg0_is_nullable,
                 std::tuple<Args...>,
                 std::integer_sequence<size_t, index...>>
    final {
  DISALLOW_NEW();

 public:
  template <typename... PassedArgs>
  BoundState(PassedArgs&&... args)
      : storage_(std::forward<PassedArgs>(args)...) {
    if constexpr (!arg0_is_nullable && sizeof...(args) > 0) {
      CHECK(std::get<0>(storage_).Unwrap())
          << "Receiver argument must not be null";
    }
  }

  void Trace(Visitor* visitor) const {
    (...,
     blink::TraceIfNeeded<typename std::tuple_element<
         index, StorageType>::type>::Trace(visitor, std::get<index>(storage_)));
  }

  template <typename Functor, typename... FreeArgs>
  auto Run(Functor&& functor, FreeArgs&&... free_args) {
    if constexpr (base::is_instantiation<HeapCallback,
                                         std::remove_cvref_t<Functor>>) {
      return std::forward<Functor>(functor).Run(
          std::get<index>(storage_).Unwrap()...,
          std::forward<FreeArgs>(free_args)...);
    } else {
      return std::invoke(std::forward<Functor>(functor),
                         std::get<index>(storage_).Unwrap()...,
                         std::forward<FreeArgs>(free_args)...);
    }
  }

 private:
  using StorageType = std::tuple<ArgStorage<std::remove_cvref_t<Args>>...>;
  StorageType storage_;
};

// `FunctorTraits<>` are internally specialized for different functors and
// help with properly extracting types for return value and arguments, as well
// as some other properties (such as whether we should null-check receiver
// args). The supported types include standalone functions, methods and
// callabcle classes, including captureless lambdas.
template <typename Functor>
struct FunctorTraits;

template <typename R, typename... Args>
struct FunctorTraits<R (*)(Args...)> {
  using return_t = R;
  using args_t = std::tuple<Args...>;
  static constexpr bool is_first_arg_nullable = true;
};
template <typename R, typename C, typename... Args>
struct FunctorTraits<R (C::*)(Args...)> {
  using return_t = R;
  using args_t = std::tuple<C*, Args...>;
  static constexpr bool is_first_arg_nullable = false;
};
template <typename R, typename C, typename... Args>
struct FunctorTraits<R (C::*)(Args...) const> {
  using return_t = R;
  using args_t = std::tuple<const C*, Args...>;
  static constexpr bool is_first_arg_nullable = false;
};
template <typename R, typename... Args>
struct FunctorTraits<HeapCallback<R(Args...)>> {
  using return_t = R;
  using args_t = std::tuple<Args...>;
  static constexpr bool is_first_arg_nullable = true;
};

template <typename Functor>
struct FunctorTraitsForCallable;
template <typename R, typename C, typename... Args>
struct FunctorTraitsForCallable<R (C::*)(Args...) const>
    : public FunctorTraits<R (*)(Args...)> {
  static_assert(!base::is_instantiation<base::FunctionRef, C>,
                "base::FunctionRef<> can't be bound");
  static_assert(std::is_empty_v<C>, "Capturing lambdas can't be bound");
};

// This covers everything with a non-overloaded operator(), including
// lambdas.
template <typename C>
concept IsCallable = requires { decltype (&C::operator())(); };

template <typename C>
  requires(IsCallable<C> && !std::is_function_v<C>)
struct FunctorTraits<C>
    : public FunctorTraitsForCallable<decltype(&C::operator())> {};

// HeapCallbackClosureImpl carries actual functor and the bound arguments.
template <typename Functor, typename BoundArgs, typename FreeArgs>
class HeapCallbackClosureImpl;

template <typename Functor, typename... BoundArgs, typename... FreeArgs>
class HeapCallbackClosureImpl<Functor,
                              std::tuple<BoundArgs...>,
                              std::tuple<FreeArgs...>>
    final : public HeapCallback<typename FunctorTraits<Functor>::return_t(
                FreeArgs...)>::Closure {
 private:
  using return_t = typename FunctorTraits<Functor>::return_t;

 public:
  template <typename... PassedArgs>
  HeapCallbackClosureImpl(Functor functor, PassedArgs&&... args)
      : functor_(functor), state_(std::forward<PassedArgs>(args)...) {
    CHECK(functor_);
  }

  HeapCallbackClosureImpl(const HeapCallbackClosureImpl& r) = delete;
  HeapCallbackClosureImpl(HeapCallbackClosureImpl&& r) = delete;

  return_t Run(FreeArgs... args) final {
    return state_.Run(functor_, std::move(args)...);
  }

  void Trace(Visitor* visitor) const final {
    blink::TraceIfNeeded<Functor>::Trace(visitor, functor_);
    state_.Trace(visitor);
  }

 private:
  Functor functor_;
  BoundState<FunctorTraits<Functor>::is_first_arg_nullable,
             std::tuple<BoundArgs...>,
             std::make_index_sequence<sizeof...(BoundArgs)>>
      state_;
};

// SplitAtN<> takes a tuple and splits it two tuples after Nth element
// (first N elements go to head_t, the rest go into tail_t).
template <size_t N, typename Head, typename Tail>
struct SplitAtN;

template <typename... HeadArgs, typename... TailArgs>
struct SplitAtN<0, std::tuple<HeadArgs...>, std::tuple<TailArgs...>> {
  using head_t = std::tuple<HeadArgs...>;
  using tail_t = std::tuple<TailArgs...>;
};

template <size_t N, typename... HeadArgs, typename CAR, typename... TailArgs>
  requires(N > 0)
struct SplitAtN<N, std::tuple<HeadArgs...>, std::tuple<CAR, TailArgs...>>
    : public SplitAtN<N - 1,
                      std::tuple<HeadArgs..., CAR>,
                      std::tuple<TailArgs...>> {};

// SplitArgs<> takes a functor and a pack of bound args and utilizes
// SplitAtN<> to split functor args into bound and free ones.
template <typename Functor, typename... BoundArgs>
class SplitArgs {
 private:
  using split_args_t = SplitAtN<sizeof...(BoundArgs),
                                std::tuple<>,
                                typename FunctorTraits<Functor>::args_t>;

 public:
  using bound_args_t = typename split_args_t::head_t;
  using free_args_t = typename split_args_t::tail_t;
};

}  // namespace internal

template <typename Functor, typename... BoundArgs>
[[nodiscard]] auto HeapBind(Functor functor, BoundArgs&&... args) {
  using SplitArgs = internal::SplitArgs<Functor, BoundArgs...>;
  using ClosureType =
      internal::HeapCallbackClosureImpl<Functor,
                                        typename SplitArgs::bound_args_t,
                                        typename SplitArgs::free_args_t>;
  // force-instantiate closure type to trigger all possible asserts there.
  static_assert(std::is_function_v<typename ClosureType::SignatureType>);
  using SignatureType = typename ClosureType::SignatureType;
  using CallbackType = HeapCallback<SignatureType>;
  // Don't do extra wrapping if there's nothing to bind.
  if constexpr (sizeof...(BoundArgs) == 0 &&
                std::is_same_v<std::remove_cvref_t<Functor>, CallbackType>) {
    return functor;
  }

  return CallbackType(MakeGarbageCollected<ClosureType>(
      functor, std::forward<BoundArgs>(args)...));
}

template <typename Ret, typename... Preargs, typename... Args>
HeapCallback<Ret(Preargs..., Args...)> IgnoreArgs(
    HeapCallback<Ret(Args...)> callback) {
  return callback ? HeapBind(
                        [](HeapCallback<Ret(Args...)> callback, Preargs...,
                           Args&&... args) {
                          return callback.Run(std::forward<Args>(args)...);
                        },
                        callback)
                  : HeapCallback<Ret(Preargs..., Args...)>();
}

}  // namespace blink::bindings

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_BIND_H_