Bitcoin Core 29.99.0
P2P Digital Currency
gen.cpp
Go to the documentation of this file.
1// Copyright (c) The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <mp/config.h>
6#include <mp/util.h>
7
8#include <algorithm>
9#include <capnp/schema.h>
10#include <capnp/schema-parser.h>
11#include <cerrno>
12#include <cstdint>
13#include <cstdio>
14#include <cstdlib>
15#include <fstream>
16#include <functional>
17#include <initializer_list>
18#include <iostream>
19#include <kj/array.h>
20#include <kj/common.h>
21#include <kj/filesystem.h>
22#include <kj/memory.h>
23#include <kj/string.h>
24#include <map>
25#include <set>
26#include <sstream>
27#include <stdexcept>
28#include <string>
29#include <system_error>
30#include <unistd.h>
31#include <utility>
32#include <vector>
33
34#define PROXY_BIN "mpgen"
35#define PROXY_DECL "mp/proxy.h"
36#define PROXY_TYPES "mp/proxy-types.h"
37
38constexpr uint64_t NAMESPACE_ANNOTATION_ID = 0xb9c6f99ebf805f2cull; // From c++.capnp
39constexpr uint64_t INCLUDE_ANNOTATION_ID = 0xb899f3c154fdb458ull; // From proxy.capnp
40constexpr uint64_t INCLUDE_TYPES_ANNOTATION_ID = 0xbcec15648e8a0cf1ull; // From proxy.capnp
41constexpr uint64_t WRAP_ANNOTATION_ID = 0xe6f46079b7b1405eull; // From proxy.capnp
42constexpr uint64_t COUNT_ANNOTATION_ID = 0xd02682b319f69b38ull; // From proxy.capnp
43constexpr uint64_t EXCEPTION_ANNOTATION_ID = 0x996a183200992f88ull; // From proxy.capnp
44constexpr uint64_t NAME_ANNOTATION_ID = 0xb594888f63f4dbb9ull; // From proxy.capnp
45constexpr uint64_t SKIP_ANNOTATION_ID = 0x824c08b82695d8ddull; // From proxy.capnp
46
47template <typename Reader>
48static bool AnnotationExists(const Reader& reader, uint64_t id)
49{
50 for (const auto annotation : reader.getAnnotations()) {
51 if (annotation.getId() == id) {
52 return true;
53 }
54 }
55 return false;
56}
57
58template <typename Reader>
59static bool GetAnnotationText(const Reader& reader, uint64_t id, kj::StringPtr* result)
60{
61 for (const auto annotation : reader.getAnnotations()) {
62 if (annotation.getId() == id) {
63 *result = annotation.getValue().getText();
64 return true;
65 }
66 }
67 return false;
68}
69
70template <typename Reader>
71static bool GetAnnotationInt32(const Reader& reader, uint64_t id, int32_t* result)
72{
73 for (const auto annotation : reader.getAnnotations()) {
74 if (annotation.getId() == id) {
75 *result = annotation.getValue().getInt32();
76 return true;
77 }
78 }
79 return false;
80}
81
82static void ForEachMethod(const capnp::InterfaceSchema& interface, const std::function<void(const capnp::InterfaceSchema& interface, const capnp::InterfaceSchema::Method)>& callback) // NOLINT(misc-no-recursion)
83{
84 for (const auto super : interface.getSuperclasses()) {
85 ForEachMethod(super, callback);
86 }
87 for (const auto method : interface.getMethods()) {
88 callback(interface, method);
89 }
90}
91
92using CharSlice = kj::ArrayPtr<const char>;
93
94// Overload for any type with a string .begin(), like kj::StringPtr and kj::ArrayPtr<char>.
95template <class OutputStream, class Array, const char* Enable = decltype(std::declval<Array>().begin())()>
96static OutputStream& operator<<(OutputStream& os, const Array& array)
97{
98 os.write(array.begin(), array.size());
99 return os;
100}
101
102struct Format
103{
104 template <typename Value>
105 Format& operator<<(Value&& value)
106 {
107 m_os << value;
108 return *this;
109 }
110 operator std::string() const { return m_os.str(); }
111 std::ostringstream m_os;
112};
113
114static std::string Cap(kj::StringPtr str)
115{
116 std::string result = str;
117 if (!result.empty() && 'a' <= result[0] && result[0] <= 'z') result[0] -= 'a' - 'A';
118 return result;
119}
120
121static bool BoxedType(const ::capnp::Type& type)
122{
123 return !(type.isVoid() || type.isBool() || type.isInt8() || type.isInt16() || type.isInt32() || type.isInt64() ||
124 type.isUInt8() || type.isUInt16() || type.isUInt32() || type.isUInt64() || type.isFloat32() ||
125 type.isFloat64() || type.isEnum());
126}
127
128// src_file is path to .capnp file to generate stub code from.
129//
130// src_prefix can be used to generate outputs in a different directory than the
131// source directory. For example if src_file is "/a/b/c/d/file.canp", and
132// src_prefix is "/a/b", then output files will be "c/d/file.capnp.h"
133// "c/d/file.capnp.cxx" "c/d/file.capnp.proxy.h", etc. This is equivalent to
134// the capnp "--src-prefix" option (see "capnp help compile").
135//
136// include_prefix can be used to control relative include paths used in
137// generated files. For example if src_file is "/a/b/c/d/file.canp" and
138// include_prefix is "/a/b/c" include lines like
139// "#include <d/file.capnp.proxy.h>" "#include <d/file.capnp.proxy-types.h>"i
140// will be generated.
141static void Generate(kj::StringPtr src_prefix,
142 kj::StringPtr include_prefix,
143 kj::StringPtr src_file,
144 const std::vector<kj::StringPtr>& import_paths,
145 const kj::ReadableDirectory& src_dir,
146 const std::vector<kj::Own<const kj::ReadableDirectory>>& import_dirs)
147{
148 std::string output_path;
149 if (src_prefix == kj::StringPtr{"."}) {
150 output_path = src_file;
151 } else if (!src_file.startsWith(src_prefix) || src_file.size() <= src_prefix.size() ||
152 src_file[src_prefix.size()] != '/') {
153 throw std::runtime_error("src_prefix is not src_file prefix");
154 } else {
155 output_path = src_file.slice(src_prefix.size() + 1);
156 }
157
158 std::string include_path;
159 if (include_prefix == kj::StringPtr{"."}) {
160 include_path = src_file;
161 } else if (!src_file.startsWith(include_prefix) || src_file.size() <= include_prefix.size() ||
162 src_file[include_prefix.size()] != '/') {
163 throw std::runtime_error("include_prefix is not src_file prefix");
164 } else {
165 include_path = src_file.slice(include_prefix.size() + 1);
166 }
167
168 std::string include_base = include_path;
169 const std::string::size_type p = include_base.rfind('.');
170 if (p != std::string::npos) include_base.erase(p);
171
172 std::vector<std::string> args;
173 args.emplace_back(capnp_PREFIX "/bin/capnp");
174 args.emplace_back("compile");
175 args.emplace_back("--src-prefix=");
176 args.back().append(src_prefix.cStr(), src_prefix.size());
177 for (const auto& import_path : import_paths) {
178 args.emplace_back("--import-path=");
179 args.back().append(import_path.cStr(), import_path.size());
180 }
181 args.emplace_back("--output=" capnp_PREFIX "/bin/capnpc-c++");
182 args.emplace_back(src_file);
183 const int pid = fork();
184 if (pid == -1) {
185 throw std::system_error(errno, std::system_category(), "fork");
186 }
187 if (!pid) {
189 }
190 const int status = mp::WaitProcess(pid);
191 if (status) {
192 throw std::runtime_error("Invoking " capnp_PREFIX "/bin/capnp failed");
193 }
194
195 const capnp::SchemaParser parser;
196 auto directory_pointers = kj::heapArray<const kj::ReadableDirectory*>(import_dirs.size());
197 for (size_t i = 0; i < import_dirs.size(); ++i) {
198 directory_pointers[i] = import_dirs[i].get();
199 }
200 auto file_schema = parser.parseFromDirectory(src_dir, kj::Path::parse(output_path), directory_pointers);
201
202 std::ofstream cpp_server(output_path + ".proxy-server.c++");
203 cpp_server << "// Generated by " PROXY_BIN " from " << src_file << "\n\n";
204 cpp_server << "// IWYU pragma: no_include <kj/memory.h>\n";
205 cpp_server << "// IWYU pragma: no_include <memory>\n";
206 cpp_server << "// IWYU pragma: begin_keep\n";
207 cpp_server << "#include <" << include_path << ".proxy.h>\n";
208 cpp_server << "#include <" << include_path << ".proxy-types.h>\n";
209 cpp_server << "#include <capnp/generated-header-support.h>\n";
210 cpp_server << "#include <cstring>\n";
211 cpp_server << "#include <kj/async.h>\n";
212 cpp_server << "#include <kj/common.h>\n";
213 cpp_server << "#include <kj/exception.h>\n";
214 cpp_server << "#include <mp/proxy.h>\n";
215 cpp_server << "#include <mp/util.h>\n";
216 cpp_server << "#include <" << PROXY_TYPES << ">\n";
217 cpp_server << "// IWYU pragma: end_keep\n\n";
218 cpp_server << "namespace mp {\n";
219
220 std::ofstream cpp_client(output_path + ".proxy-client.c++");
221 cpp_client << "// Generated by " PROXY_BIN " from " << src_file << "\n\n";
222 cpp_client << "// IWYU pragma: no_include <kj/memory.h>\n";
223 cpp_client << "// IWYU pragma: no_include <memory>\n";
224 cpp_client << "// IWYU pragma: begin_keep\n";
225 cpp_client << "#include <" << include_path << ".h>\n";
226 cpp_client << "#include <" << include_path << ".proxy.h>\n";
227 cpp_client << "#include <" << include_path << ".proxy-types.h>\n";
228 cpp_client << "#include <capnp/generated-header-support.h>\n";
229 cpp_client << "#include <cstring>\n";
230 cpp_client << "#include <kj/common.h>\n";
231 cpp_client << "#include <mp/proxy.h>\n";
232 cpp_client << "#include <mp/util.h>\n";
233 cpp_client << "#include <" << PROXY_TYPES << ">\n";
234 cpp_client << "// IWYU pragma: end_keep\n\n";
235 cpp_client << "namespace mp {\n";
236
237 std::ofstream cpp_types(output_path + ".proxy-types.c++");
238 cpp_types << "// Generated by " PROXY_BIN " from " << src_file << "\n\n";
239 cpp_types << "// IWYU pragma: no_include \"mp/proxy.h\"\n";
240 cpp_types << "// IWYU pragma: no_include \"mp/proxy-io.h\"\n";
241 cpp_types << "#include <" << include_path << ".proxy.h>\n";
242 cpp_types << "#include <" << include_path << ".proxy-types.h> // IWYU pragma: keep\n";
243 cpp_types << "#include <" << PROXY_TYPES << ">\n\n";
244 cpp_types << "namespace mp {\n";
245
246 std::string guard = output_path;
247 std::ranges::transform(guard, guard.begin(), [](unsigned char c) -> unsigned char {
248 if ('0' <= c && c <= '9') return c;
249 if ('A' <= c && c <= 'Z') return c;
250 if ('a' <= c && c <= 'z') return c - 'a' + 'A';
251 return '_';
252 });
253
254 std::ofstream inl(output_path + ".proxy-types.h");
255 inl << "// Generated by " PROXY_BIN " from " << src_file << "\n\n";
256 inl << "#ifndef " << guard << "_PROXY_TYPES_H\n";
257 inl << "#define " << guard << "_PROXY_TYPES_H\n\n";
258 inl << "// IWYU pragma: no_include \"mp/proxy.h\"\n";
259 inl << "#include <mp/proxy.h> // IWYU pragma: keep\n";
260 inl << "#include <" << include_path << ".proxy.h> // IWYU pragma: keep\n";
261 for (const auto annotation : file_schema.getProto().getAnnotations()) {
262 if (annotation.getId() == INCLUDE_TYPES_ANNOTATION_ID) {
263 inl << "#include \"" << annotation.getValue().getText() << "\" // IWYU pragma: export\n";
264 }
265 }
266 inl << "namespace mp {\n";
267
268 std::ofstream h(output_path + ".proxy.h");
269 h << "// Generated by " PROXY_BIN " from " << src_file << "\n\n";
270 h << "#ifndef " << guard << "_PROXY_H\n";
271 h << "#define " << guard << "_PROXY_H\n\n";
272 h << "#include <" << include_path << ".h> // IWYU pragma: keep\n";
273 for (const auto annotation : file_schema.getProto().getAnnotations()) {
274 if (annotation.getId() == INCLUDE_ANNOTATION_ID) {
275 h << "#include \"" << annotation.getValue().getText() << "\" // IWYU pragma: export\n";
276 }
277 }
278 h << "#include <" << PROXY_DECL << ">\n\n";
279 h << "#if defined(__GNUC__)\n";
280 h << "#pragma GCC diagnostic push\n";
281 h << "#if !defined(__has_warning)\n";
282 h << "#pragma GCC diagnostic ignored \"-Wsuggest-override\"\n";
283 h << "#elif __has_warning(\"-Wsuggest-override\")\n";
284 h << "#pragma GCC diagnostic ignored \"-Wsuggest-override\"\n";
285 h << "#endif\n";
286 h << "#endif\n";
287 h << "namespace mp {\n";
288
289 kj::StringPtr message_namespace;
290 GetAnnotationText(file_schema.getProto(), NAMESPACE_ANNOTATION_ID, &message_namespace);
291
292 std::string base_name = include_base;
293 const size_t output_slash = base_name.rfind('/');
294 if (output_slash != std::string::npos) {
295 base_name.erase(0, output_slash + 1);
296 }
297
298 std::ostringstream methods;
299 std::set<kj::StringPtr> accessors_done;
300 std::ostringstream accessors;
301 std::ostringstream dec;
302 std::ostringstream def_server;
303 std::ostringstream def_client;
304 std::ostringstream int_client;
305 std::ostringstream def_types;
306
307 auto add_accessor = [&](kj::StringPtr name) {
308 if (!accessors_done.insert(name).second) return;
309 const std::string cap = Cap(name);
310 accessors << "struct " << cap << "\n";
311 accessors << "{\n";
312 accessors << " template<typename S> static auto get(S&& s) -> decltype(s.get" << cap << "()) { return s.get" << cap << "(); }\n";
313 accessors << " template<typename S> static bool has(S&& s) { return s.has" << cap << "(); }\n";
314 accessors << " template<typename S, typename A> static void set(S&& s, A&& a) { s.set" << cap
315 << "(std::forward<A>(a)); }\n";
316 accessors << " template<typename S, typename... A> static decltype(auto) init(S&& s, A&&... a) { return s.init"
317 << cap << "(std::forward<A>(a)...); }\n";
318 accessors << " template<typename S> static bool getWant(S&& s) { return s.getWant" << cap << "(); }\n";
319 accessors << " template<typename S> static void setWant(S&& s) { s.setWant" << cap << "(true); }\n";
320 accessors << " template<typename S> static bool getHas(S&& s) { return s.getHas" << cap << "(); }\n";
321 accessors << " template<typename S> static void setHas(S&& s) { s.setHas" << cap << "(true); }\n";
322 accessors << "};\n";
323 };
324
325 for (const auto node_nested : file_schema.getProto().getNestedNodes()) {
326 kj::StringPtr node_name = node_nested.getName();
327 const auto& node = file_schema.getNested(node_name);
328 kj::StringPtr proxied_class_type;
329 GetAnnotationText(node.getProto(), WRAP_ANNOTATION_ID, &proxied_class_type);
330
331 if (node.getProto().isStruct()) {
332 const auto& struc = node.asStruct();
333 std::ostringstream generic_name;
334 generic_name << node_name;
335 dec << "template<";
336 bool first_param = true;
337 for (const auto param : node.getProto().getParameters()) {
338 if (first_param) {
339 first_param = false;
340 generic_name << "<";
341 } else {
342 dec << ", ";
343 generic_name << ", ";
344 }
345 dec << "typename " << param.getName();
346 generic_name << "" << param.getName();
347 }
348 if (!first_param) generic_name << ">";
349 dec << ">\n";
350 dec << "struct ProxyStruct<" << message_namespace << "::" << generic_name.str() << ">\n";
351 dec << "{\n";
352 dec << " using Struct = " << message_namespace << "::" << generic_name.str() << ";\n";
353 for (const auto field : struc.getFields()) {
354 auto field_name = field.getProto().getName();
355 add_accessor(field_name);
356 dec << " using " << Cap(field_name) << "Accessor = Accessor<" << base_name
357 << "_fields::" << Cap(field_name) << ", FIELD_IN | FIELD_OUT";
358 if (BoxedType(field.getType())) dec << " | FIELD_BOXED";
359 dec << ">;\n";
360 }
361 dec << " using Accessors = std::tuple<";
362 size_t i = 0;
363 for (const auto field : struc.getFields()) {
364 if (AnnotationExists(field.getProto(), SKIP_ANNOTATION_ID)) {
365 continue;
366 }
367 if (i) dec << ", ";
368 dec << Cap(field.getProto().getName()) << "Accessor";
369 ++i;
370 }
371 dec << ">;\n";
372 dec << " static constexpr size_t fields = " << i << ";\n";
373 dec << "};\n";
374
375 if (proxied_class_type.size()) {
376 inl << "template<>\n";
377 inl << "struct ProxyType<" << proxied_class_type << ">\n";
378 inl << "{\n";
379 inl << "public:\n";
380 inl << " using Struct = " << message_namespace << "::" << node_name << ";\n";
381 size_t i = 0;
382 for (const auto field : struc.getFields()) {
383 if (AnnotationExists(field.getProto(), SKIP_ANNOTATION_ID)) {
384 continue;
385 }
386 auto field_name = field.getProto().getName();
387 auto member_name = field_name;
388 GetAnnotationText(field.getProto(), NAME_ANNOTATION_ID, &member_name);
389 inl << " static decltype(auto) get(std::integral_constant<size_t, " << i << ">) { return "
390 << "&" << proxied_class_type << "::" << member_name << "; }\n";
391 ++i;
392 }
393 inl << " static constexpr size_t fields = " << i << ";\n";
394 inl << "};\n";
395 }
396 }
397
398 if (proxied_class_type.size() && node.getProto().isInterface()) {
399 const auto& interface = node.asInterface();
400
401 std::ostringstream client;
402 client << "template<>\nstruct ProxyClient<" << message_namespace << "::" << node_name << "> final : ";
403 client << "public ProxyClientCustom<" << message_namespace << "::" << node_name << ", "
404 << proxied_class_type << ">\n{\n";
405 client << "public:\n";
406 client << " using ProxyClientCustom::ProxyClientCustom;\n";
407 client << " ~ProxyClient();\n";
408
409 std::ostringstream server;
410 server << "template<>\nstruct ProxyServer<" << message_namespace << "::" << node_name << "> : public "
411 << "ProxyServerCustom<" << message_namespace << "::" << node_name << ", " << proxied_class_type
412 << ">\n{\n";
413 server << "public:\n";
414 server << " using ProxyServerCustom::ProxyServerCustom;\n";
415 server << " ~ProxyServer();\n";
416
417 const std::ostringstream client_construct;
418 const std::ostringstream client_destroy;
419
420 int method_ordinal = 0;
421 ForEachMethod(interface, [&] (const capnp::InterfaceSchema& method_interface, const capnp::InterfaceSchema::Method& method) {
422 const kj::StringPtr method_name = method.getProto().getName();
423 kj::StringPtr proxied_method_name = method_name;
424 GetAnnotationText(method.getProto(), NAME_ANNOTATION_ID, &proxied_method_name);
425
426 const std::string method_prefix = Format() << message_namespace << "::" << method_interface.getShortDisplayName()
427 << "::" << Cap(method_name);
428 const bool is_construct = method_name == kj::StringPtr{"construct"};
429 const bool is_destroy = method_name == kj::StringPtr{"destroy"};
430
431 struct Field
432 {
433 ::capnp::StructSchema::Field param;
434 bool param_is_set = false;
435 ::capnp::StructSchema::Field result;
436 bool result_is_set = false;
437 int args = 0;
438 bool retval = false;
439 bool optional = false;
440 bool requested = false;
441 bool skip = false;
442 kj::StringPtr exception;
443 };
444
445 std::vector<Field> fields;
446 std::map<kj::StringPtr, int> field_idx; // name -> args index
447 bool has_result = false;
448
449 auto add_field = [&](const ::capnp::StructSchema::Field& schema_field, bool param) {
450 if (AnnotationExists(schema_field.getProto(), SKIP_ANNOTATION_ID)) {
451 return;
452 }
453
454 auto field_name = schema_field.getProto().getName();
455 auto inserted = field_idx.emplace(field_name, fields.size());
456 if (inserted.second) {
457 fields.emplace_back();
458 }
459 auto& field = fields[inserted.first->second];
460 if (param) {
461 field.param = schema_field;
462 field.param_is_set = true;
463 } else {
464 field.result = schema_field;
465 field.result_is_set = true;
466 }
467
468 if (!param && field_name == kj::StringPtr{"result"}) {
469 field.retval = true;
470 has_result = true;
471 }
472
473 GetAnnotationText(schema_field.getProto(), EXCEPTION_ANNOTATION_ID, &field.exception);
474
475 int32_t count = 1;
476 if (!GetAnnotationInt32(schema_field.getProto(), COUNT_ANNOTATION_ID, &count)) {
477 if (schema_field.getType().isStruct()) {
478 GetAnnotationInt32(schema_field.getType().asStruct().getProto(),
480 } else if (schema_field.getType().isInterface()) {
481 GetAnnotationInt32(schema_field.getType().asInterface().getProto(),
483 }
484 }
485
486
487 if (inserted.second && !field.retval && !field.exception.size()) {
488 field.args = count;
489 }
490 };
491
492 for (const auto schema_field : method.getParamType().getFields()) {
493 add_field(schema_field, true);
494 }
495 for (const auto schema_field : method.getResultType().getFields()) {
496 add_field(schema_field, false);
497 }
498 for (auto& field : field_idx) {
499 auto has_field = field_idx.find("has" + Cap(field.first));
500 if (has_field != field_idx.end()) {
501 fields[has_field->second].skip = true;
502 fields[field.second].optional = true;
503 }
504 auto want_field = field_idx.find("want" + Cap(field.first));
505 if (want_field != field_idx.end() && fields[want_field->second].param_is_set) {
506 fields[want_field->second].skip = true;
507 fields[field.second].requested = true;
508 }
509 }
510
511 if (!is_construct && !is_destroy && (&method_interface == &interface)) {
512 methods << "template<>\n";
513 methods << "struct ProxyMethod<" << method_prefix << "Params>\n";
514 methods << "{\n";
515 methods << " static constexpr auto impl = &" << proxied_class_type
516 << "::" << proxied_method_name << ";\n";
517 methods << "};\n\n";
518 }
519
520 std::ostringstream client_args;
521 std::ostringstream client_invoke;
522 std::ostringstream server_invoke_start;
523 std::ostringstream server_invoke_end;
524 int argc = 0;
525 for (const auto& field : fields) {
526 if (field.skip) continue;
527
528 const auto& f = field.param_is_set ? field.param : field.result;
529 auto field_name = f.getProto().getName();
530 auto field_type = f.getType();
531
532 std::ostringstream field_flags;
533 if (!field.param_is_set) {
534 field_flags << "FIELD_OUT";
535 } else if (field.result_is_set) {
536 field_flags << "FIELD_IN | FIELD_OUT";
537 } else {
538 field_flags << "FIELD_IN";
539 }
540 if (field.optional) field_flags << " | FIELD_OPTIONAL";
541 if (field.requested) field_flags << " | FIELD_REQUESTED";
542 if (BoxedType(field_type)) field_flags << " | FIELD_BOXED";
543
544 add_accessor(field_name);
545
546 std::ostringstream fwd_args;
547 for (int i = 0; i < field.args; ++i) {
548 if (argc > 0) client_args << ",";
549
550 // Add to client method parameter list.
551 client_args << "M" << method_ordinal << "::Param<" << argc << "> " << field_name;
552 if (field.args > 1) client_args << i;
553
554 // Add to MakeClientParam argument list using Fwd helper for perfect forwarding.
555 if (i > 0) fwd_args << ", ";
556 fwd_args << "M" << method_ordinal << "::Fwd<" << argc << ">(" << field_name;
557 if (field.args > 1) fwd_args << i;
558 fwd_args << ")";
559
560 ++argc;
561 }
562 client_invoke << ", ";
563
564 if (field.exception.size()) {
565 client_invoke << "ClientException<" << field.exception << ", ";
566 } else {
567 client_invoke << "MakeClientParam<";
568 }
569
570 client_invoke << "Accessor<" << base_name << "_fields::" << Cap(field_name) << ", "
571 << field_flags.str() << ">>(";
572
573 if (field.retval) {
574 client_invoke << field_name;
575 } else {
576 client_invoke << fwd_args.str();
577 }
578 client_invoke << ")";
579
580 if (field.exception.size()) {
581 server_invoke_start << "Make<ServerExcept, " << field.exception;
582 } else if (field.retval) {
583 server_invoke_start << "Make<ServerRet";
584 } else {
585 server_invoke_start << "MakeServerField<" << field.args;
586 }
587 server_invoke_start << ", Accessor<" << base_name << "_fields::" << Cap(field_name) << ", "
588 << field_flags.str() << ">>(";
589 server_invoke_end << ")";
590 }
591
592 const std::string static_str{is_construct || is_destroy ? "static " : ""};
593 const std::string super_str{is_construct || is_destroy ? "Super& super" : ""};
594 const std::string self_str{is_construct || is_destroy ? "super" : "*this"};
595
596 client << " using M" << method_ordinal << " = ProxyClientMethodTraits<" << method_prefix
597 << "Params>;\n";
598 client << " " << static_str << "typename M" << method_ordinal << "::Result " << method_name << "("
599 << super_str << client_args.str() << ")";
600 client << ";\n";
601 def_client << "ProxyClient<" << message_namespace << "::" << node_name << ">::M" << method_ordinal
602 << "::Result ProxyClient<" << message_namespace << "::" << node_name << ">::" << method_name
603 << "(" << super_str << client_args.str() << ") {\n";
604 if (has_result) {
605 def_client << " typename M" << method_ordinal << "::Result result;\n";
606 }
607 def_client << " clientInvoke(" << self_str << ", &" << message_namespace << "::" << node_name
608 << "::Client::" << method_name << "Request" << client_invoke.str() << ");\n";
609 if (has_result) def_client << " return result;\n";
610 def_client << "}\n";
611
612 server << " kj::Promise<void> " << method_name << "(" << Cap(method_name)
613 << "Context call_context) override;\n";
614
615 def_server << "kj::Promise<void> ProxyServer<" << message_namespace << "::" << node_name
616 << ">::" << method_name << "(" << Cap(method_name)
617 << "Context call_context) {\n"
618 " return serverInvoke(*this, call_context, "
619 << server_invoke_start.str();
620 if (is_destroy) {
621 def_server << "ServerDestroy()";
622 } else {
623 def_server << "ServerCall()";
624 }
625 def_server << server_invoke_end.str() << ");\n}\n";
626 ++method_ordinal;
627 });
628
629 client << "};\n";
630 server << "};\n";
631 dec << "\n" << client.str() << "\n" << server.str() << "\n";
632 KJ_IF_MAYBE(bracket, proxied_class_type.findFirst('<')) {
633 // Skip ProxyType definition for complex type expressions which
634 // could lead to duplicate definitions. They can be defined
635 // manually if actually needed.
636 } else {
637 dec << "template<>\nstruct ProxyType<" << proxied_class_type << ">\n{\n";
638 dec << " using Type = " << proxied_class_type << ";\n";
639 dec << " using Message = " << message_namespace << "::" << node_name << ";\n";
640 dec << " using Client = ProxyClient<Message>;\n";
641 dec << " using Server = ProxyServer<Message>;\n";
642 dec << "};\n";
643 int_client << "ProxyTypeRegister t" << node_nested.getId() << "{TypeList<" << proxied_class_type << ">{}};\n";
644 }
645 def_types << "ProxyClient<" << message_namespace << "::" << node_name
646 << ">::~ProxyClient() { clientDestroy(*this); " << client_destroy.str() << " }\n";
647 def_types << "ProxyServer<" << message_namespace << "::" << node_name
648 << ">::~ProxyServer() { serverDestroy(*this); }\n";
649 }
650 }
651
652 h << methods.str() << "namespace " << base_name << "_fields {\n"
653 << accessors.str() << "} // namespace " << base_name << "_fields\n"
654 << dec.str();
655
656 cpp_server << def_server.str();
657 cpp_server << "} // namespace mp\n";
658
659 cpp_client << def_client.str();
660 cpp_client << "namespace {\n" << int_client.str() << "} // namespace\n";
661 cpp_client << "} // namespace mp\n";
662
663 cpp_types << def_types.str();
664 cpp_types << "} // namespace mp\n";
665
666 inl << "} // namespace mp\n";
667 inl << "#endif\n";
668
669 h << "} // namespace mp\n";
670 h << "#if defined(__GNUC__)\n";
671 h << "#pragma GCC diagnostic pop\n";
672 h << "#endif\n";
673 h << "#endif\n";
674}
675
676int main(int argc, char** argv)
677{
678 if (argc < 3) {
679 std::cerr << "Usage: " << PROXY_BIN << " SRC_PREFIX INCLUDE_PREFIX SRC_FILE [IMPORT_PATH...]\n";
680 exit(1);
681 }
682 std::vector<kj::StringPtr> import_paths;
683 std::vector<kj::Own<const kj::ReadableDirectory>> import_dirs;
684 auto fs = kj::newDiskFilesystem();
685 auto cwd = fs->getCurrentPath();
686 kj::Own<const kj::ReadableDirectory> src_dir;
687 KJ_IF_MAYBE(dir, fs->getRoot().tryOpenSubdir(cwd.evalNative(argv[1]))) {
688 src_dir = kj::mv(*dir);
689 } else {
690 throw std::runtime_error(std::string("Failed to open src_prefix prefix directory: ") + argv[1]);
691 }
692 for (int i = 4; i < argc; ++i) {
693 KJ_IF_MAYBE(dir, fs->getRoot().tryOpenSubdir(cwd.evalNative(argv[i]))) {
694 import_paths.emplace_back(argv[i]);
695 import_dirs.emplace_back(kj::mv(*dir));
696 } else {
697 throw std::runtime_error(std::string("Failed to open import directory: ") + argv[i]);
698 }
699 }
700 for (const char* path : {CMAKE_INSTALL_PREFIX "/include", capnp_PREFIX "/include"}) {
701 KJ_IF_MAYBE(dir, fs->getRoot().tryOpenSubdir(cwd.evalNative(path))) {
702 import_paths.emplace_back(path);
703 import_dirs.emplace_back(kj::mv(*dir));
704 }
705 // No exception thrown if _PREFIX directories do not exist
706 }
707 Generate(argv[1], argv[2], argv[3], import_paths, *src_dir, import_dirs);
708 return 0;
709}
ArgsManager & args
Definition: bitcoind.cpp:277
kj::ArrayPtr< const char > CharSlice
Definition: gen.cpp:92
constexpr uint64_t EXCEPTION_ANNOTATION_ID
Definition: gen.cpp:43
constexpr uint64_t NAME_ANNOTATION_ID
Definition: gen.cpp:44
static OutputStream & operator<<(OutputStream &os, const Array &array)
Definition: gen.cpp:96
static void ForEachMethod(const capnp::InterfaceSchema &interface, const std::function< void(const capnp::InterfaceSchema &interface, const capnp::InterfaceSchema::Method)> &callback)
Definition: gen.cpp:82
constexpr uint64_t SKIP_ANNOTATION_ID
Definition: gen.cpp:45
int main(int argc, char **argv)
Definition: gen.cpp:676
constexpr uint64_t WRAP_ANNOTATION_ID
Definition: gen.cpp:41
constexpr uint64_t INCLUDE_ANNOTATION_ID
Definition: gen.cpp:39
static void Generate(kj::StringPtr src_prefix, kj::StringPtr include_prefix, kj::StringPtr src_file, const std::vector< kj::StringPtr > &import_paths, const kj::ReadableDirectory &src_dir, const std::vector< kj::Own< const kj::ReadableDirectory > > &import_dirs)
Definition: gen.cpp:141
static bool GetAnnotationInt32(const Reader &reader, uint64_t id, int32_t *result)
Definition: gen.cpp:71
static bool BoxedType(const ::capnp::Type &type)
Definition: gen.cpp:121
#define PROXY_TYPES
Definition: gen.cpp:36
#define PROXY_BIN
Definition: gen.cpp:34
constexpr uint64_t INCLUDE_TYPES_ANNOTATION_ID
Definition: gen.cpp:40
constexpr uint64_t NAMESPACE_ANNOTATION_ID
Definition: gen.cpp:38
static bool AnnotationExists(const Reader &reader, uint64_t id)
Definition: gen.cpp:48
static std::string Cap(kj::StringPtr str)
Definition: gen.cpp:114
static bool GetAnnotationText(const Reader &reader, uint64_t id, kj::StringPtr *result)
Definition: gen.cpp:59
#define PROXY_DECL
Definition: gen.cpp:35
constexpr uint64_t COUNT_ANNOTATION_ID
Definition: gen.cpp:42
int WaitProcess(int pid)
Wait for a process to exit and return its exit code.
Definition: util.cpp:146
void ExecProcess(const std::vector< std::string > &args)
Call execvp with vector args.
Definition: util.cpp:132
Definition: messages.h:20
const char * name
Definition: rest.cpp:50
Definition: gen.cpp:103
Format & operator<<(Value &&value)
Definition: gen.cpp:105
std::ostringstream m_os
Definition: gen.cpp:111
static int count