-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen_seq.py
285 lines (260 loc) · 9.95 KB
/
gen_seq.py
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
#!/usr/bin/env python3
# Copyright 2023 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from mako.template import Template
seq_state = Template(
"""
<%def name="decl(promise_name, i, n)">
using Promise${i} = ${promise_name};
% if i < n-1:
using NextFactory${i} = OncePromiseFactory<typename Promise${i}::Result, F${i}>;
${decl(f"typename NextFactory{i}::Promise", i+1, n)}
% endif
</%def>
<%def name="state(i, n)">
% if i == 0:
Promise0 current_promise;
NextFactory0 next_factory;
% elif i == n-1:
union {
struct { ${state(i-1, n)} } prior;
Promise${i} current_promise;
};
% else:
union {
struct { ${state(i-1, n)} } prior;
P${i} current_promise;
};
NextFactory${i} next_factory;
% endif
</%def>
template <template<typename> class Traits, typename P, ${",".join(f"typename F{i}" for i in range(0,n-1))}>
struct SeqState<Traits, P, ${",".join(f"F{i}" for i in range(0,n-1))}> {
<% name="PromiseLike<P>" %>
% for i in range(0,n-1):
using Promise${i} = ${name};
using PromiseResult${i} = typename Promise${i}::Result;
using PromiseResultTraits${i} = Traits<PromiseResult${i}>;
using NextFactory${i} = OncePromiseFactory<typename PromiseResultTraits${i}::UnwrappedType, F${i}>;
<% name=f"typename NextFactory{i}::Promise" %>\\
% endfor
using Promise${n-1} = ${name};
using PromiseResult${n-1} = typename Promise${n-1}::Result;
using PromiseResultTraits${n-1} = Traits<PromiseResult${n-1}>;
using Result = typename PromiseResultTraits${n-1}::WrappedType;
% if n == 1:
Promise0 current_promise;
% else:
% for i in range(0,n-1):
struct Running${i} {
% if i != 0:
union {
GPR_NO_UNIQUE_ADDRESS Running${i-1} prior;
% endif
GPR_NO_UNIQUE_ADDRESS Promise${i} current_promise;
% if i != 0:
};
% endif
GPR_NO_UNIQUE_ADDRESS NextFactory${i} next_factory;
};
% endfor
union {
GPR_NO_UNIQUE_ADDRESS Running${n-2} prior;
GPR_NO_UNIQUE_ADDRESS Promise${n-1} current_promise;
};
% endif
enum class State : uint8_t { ${",".join(f"kState{i}" for i in range(0,n))} };
GPR_NO_UNIQUE_ADDRESS State state = State::kState0;
SeqState(P&& p, ${",".join(f"F{i}&& f{i}" for i in range(0,n-1))}) noexcept {
Construct(&${"prior."*(n-1)}current_promise, std::forward<P>(p));
% for i in range(0,n-1):
Construct(&${"prior."*(n-1-i)}next_factory, std::forward<F${i}>(f${i}));
% endfor
}
~SeqState() {
switch (state) {
% for i in range(0,n-1):
case State::kState${i}:
Destruct(&${"prior."*(n-1-i)}current_promise);
goto tail${i};
% endfor
case State::kState${n-1}:
Destruct(¤t_promise);
return;
}
% for i in range(0,n-1):
tail${i}:
Destruct(&${"prior."*(n-1-i)}next_factory);
% endfor
}
SeqState(const SeqState& other) noexcept : state(other.state) {
GPR_ASSERT(state == State::kState0);
Construct(&${"prior."*(n-1-i)}current_promise,
other.${"prior."*(n-1-i)}current_promise);
% for i in range(0,n-1):
Construct(&${"prior."*(n-1-i)}next_factory,
other.${"prior."*(n-1-i)}next_factory);
% endfor
}
SeqState& operator=(const SeqState& other) = delete;
SeqState(SeqState&& other) noexcept : state(other.state) {
switch (state) {
% for i in range(0,n-1):
case State::kState${i}:
Construct(&${"prior."*(n-1-i)}current_promise,
std::move(other.${"prior."*(n-1-i)}current_promise));
goto tail${i};
% endfor
case State::kState${n-1}:
Construct(¤t_promise, std::move(other.current_promise));
return;
}
% for i in range(0,n-1):
tail${i}:
Construct(&${"prior."*(n-1-i)}next_factory,
std::move(other.${"prior."*(n-1-i)}next_factory));
% endfor
}
SeqState& operator=(SeqState&& other) = delete;
Poll<Result> PollOnce() {
switch (state) {
% for i in range(0,n-1):
case State::kState${i}: {
if (grpc_trace_promise_primitives.enabled()) {
gpr_log(GPR_DEBUG, "seq[%p]: begin poll step ${i+1}/${n}", this);
}
auto result = ${"prior."*(n-1-i)}current_promise();
PromiseResult${i}* p = result.value_if_ready();
if (grpc_trace_promise_primitives.enabled()) {
gpr_log(GPR_DEBUG, "seq[%p]: poll step ${i+1}/${n} gets %s", this,
p != nullptr? (PromiseResultTraits${i}::IsOk(*p)? "ready" : "early-error") : "pending");
}
if (p == nullptr) return Pending{};
if (!PromiseResultTraits${i}::IsOk(*p)) {
return PromiseResultTraits${i}::template ReturnValue<Result>(std::move(*p));
}
Destruct(&${"prior."*(n-1-i)}current_promise);
auto next_promise = PromiseResultTraits${i}::CallFactory(&${"prior."*(n-1-i)}next_factory, std::move(*p));
Destruct(&${"prior."*(n-1-i)}next_factory);
Construct(&${"prior."*(n-2-i)}current_promise, std::move(next_promise));
state = State::kState${i+1};
}
ABSL_FALLTHROUGH_INTENDED;
% endfor
default:
case State::kState${n-1}: {
if (grpc_trace_promise_primitives.enabled()) {
gpr_log(GPR_DEBUG, "seq[%p]: begin poll step ${n}/${n}", this);
}
auto result = current_promise();
if (grpc_trace_promise_primitives.enabled()) {
gpr_log(GPR_DEBUG, "seq[%p]: poll step ${n}/${n} gets %s", this, result.ready()? "ready" : "pending");
}
auto* p = result.value_if_ready();
if (p == nullptr) return Pending{};
return Result(std::move(*p));
}
}
}
};"""
)
front_matter = """
#ifndef GRPC_SRC_CORE_LIB_PROMISE_DETAIL_SEQ_STATE_H
#define GRPC_SRC_CORE_LIB_PROMISE_DETAIL_SEQ_STATE_H
// This file is generated by tools/codegen/core/gen_seq.py
#include <grpc/support/port_platform.h>
#include <stdint.h>
#include <utility>
#include "absl/base/attributes.h"
#include <grpc/support/log.h>
#include "src/core/lib/gprpp/construct_destruct.h"
#include "src/core/lib/promise/detail/promise_factory.h"
#include "src/core/lib/promise/detail/promise_like.h"
#include "src/core/lib/promise/poll.h"
#include "src/core/lib/promise/trace.h"
// A sequence under some traits for some set of callables P, Fs.
// P should be a promise-like object that yields a value.
// Fs... should be promise-factory-like objects that take the value from the
// previous step and yield a promise. Note that most of the machinery in
// PromiseFactory exists to make it possible for those promise-factory-like
// objects to be anything that's convenient.
// Traits defines how we move from one step to the next. Traits sets up the
// wrapping and escape handling for the sequence.
// Promises return wrapped values that the trait can inspect and unwrap before
// passing them to the next element of the sequence. The trait can
// also interpret a wrapped value as an escape value, which terminates
// evaluation of the sequence immediately yielding a result. Traits for type T
// have the members:
// * type UnwrappedType - the type after removing wrapping from T (i.e. for
// TrySeq, T=StatusOr<U> yields UnwrappedType=U).
// * type WrappedType - the type after adding wrapping if it doesn't already
// exist (i.e. for TrySeq if T is not Status/StatusOr/void, then
// WrappedType=StatusOr<T>; if T is Status then WrappedType=Status (it's
// already wrapped!))
// * template <typename Next> void CallFactory(Next* next_factory, T&& value) -
// call promise factory next_factory with the result of unwrapping value, and
// return the resulting promise.
// * template <typename Result, typename RunNext> Poll<Result>
// CheckResultAndRunNext(T prior, RunNext run_next) - examine the value of
// prior, and decide to escape or continue. If escaping, return the final
// sequence value of type Poll<Result>. If continuing, return the value of
// run_next(std::move(prior)).
//
// A state contains the current promise, and the promise factory to turn the
// result of the current promise into the next state's promise. We play a shell
// game such that the prior state and our current promise are kept in a union,
// and the next promise factory is kept alongside in the state struct.
// Recursively this guarantees that the next functions get initialized once, and
// destroyed once, and don't need to be moved around in between, which avoids a
// potential O(n**2) loop of next factory moves had we used a variant of states
// here. The very first state does not have a prior state, and so that state has
// a partial specialization below. The final state does not have a next state;
// that state is inlined in BasicSeq since that was simpler to type.
namespace grpc_core {
namespace promise_detail {
template <template<typename> class Traits, typename P, typename... Fs>
struct SeqState;
"""
end_matter = """
} // namespace promise_detail
} // namespace grpc_core
#endif // GRPC_SRC_CORE_LIB_PROMISE_DETAIL_SEQ_STATE_H
"""
# utility: print a big comment block into a set of files
def put_banner(files, banner):
for f in files:
for line in banner:
print("// %s" % line, file=f)
print("", file=f)
with open(sys.argv[0]) as my_source:
copyright = []
for line in my_source:
if line[0] != "#":
break
for line in my_source:
if line[0] == "#":
copyright.append(line)
break
for line in my_source:
if line[0] != "#":
break
copyright.append(line)
copyright = [line[2:].rstrip() for line in copyright]
with open("src/core/lib/promise/detail/seq_state.h", "w") as f:
put_banner([f], copyright)
print(front_matter, file=f)
for n in range(2, 10):
print(seq_state.render(n=n), file=f)
print(end_matter, file=f)