add flatbuffers

commit 6da1cf79d90eb242e7da5318241d42279a3df3ba
Author: Max Burke <max@urbanlogiq.com>
Date:   Sun Jan 19 14:47:28 2020 -0800

    [rust] Add use declarations to Rust-generated bindings for imported FB definitions (#5645)

    * Bugfix for Rust generation of union fields named with language keywords
This commit is contained in:
carbon
2024-05-31 14:12:12 +08:00
parent 3e2ce5494f
commit 93b1517102
685 changed files with 147856 additions and 0 deletions

View File

@ -0,0 +1,91 @@
load("@rules_cc//cc:defs.bzl", "cc_library")
package(
default_visibility = ["//visibility:public"],
)
filegroup(
name = "common_headers",
srcs = [
"config.h",
"schema_interface.h",
],
)
cc_library(
name = "cpp_generator",
srcs = [
"cpp_generator.cc",
],
hdrs = [
"cpp_generator.h",
":common_headers",
],
include_prefix = "src/compiler",
strip_include_prefix = "/grpc/src/compiler",
deps = [
"//:flatbuffers",
],
)
cc_library(
name = "go_generator",
srcs = [
"go_generator.cc",
],
hdrs = [
"go_generator.h",
":common_headers",
],
include_prefix = "src/compiler",
strip_include_prefix = "/grpc/src/compiler",
deps = [
"//:flatbuffers",
],
)
cc_library(
name = "java_generator",
srcs = [
"java_generator.cc",
],
hdrs = [
"java_generator.h",
":common_headers",
],
include_prefix = "src/compiler",
strip_include_prefix = "/grpc/src/compiler",
deps = [
"//:flatbuffers",
],
)
cc_library(
name = "python_generator",
hdrs = [
"python_generator.h",
],
include_prefix = "src/compiler",
strip_include_prefix = "/grpc/src/compiler",
deps = [
":python_generator_private",
],
)
cc_library(
name = "python_generator_private",
srcs = [
"python_generator.cc",
],
hdrs = [
"python_generator.h",
"python_private_generator.h",
":common_headers",
],
include_prefix = "src/compiler",
strip_include_prefix = "/grpc/src/compiler",
visibility = ["//visibility:private"],
deps = [
"//:flatbuffers",
],
)

View File

@ -0,0 +1,40 @@
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SRC_COMPILER_CONFIG_H
#define SRC_COMPILER_CONFIG_H
// This file is here only because schema_interface.h, which is copied from gRPC,
// includes it. There is nothing for Flatbuffers to configure.
#endif // SRC_COMPILER_CONFIG_H

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,138 @@
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
#define GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
// cpp_generator.h/.cc do not directly depend on GRPC/ProtoBuf, such that they
// can be used to generate code for other serialization systems, such as
// FlatBuffers.
#include <memory>
#include <vector>
#include "src/compiler/config.h"
#include "src/compiler/schema_interface.h"
#ifndef GRPC_CUSTOM_STRING
#include <string>
#define GRPC_CUSTOM_STRING std::string
#endif
namespace grpc {
typedef GRPC_CUSTOM_STRING string;
} // namespace grpc
namespace grpc_cpp_generator {
// Contains all the parameters that are parsed from the command line.
struct Parameters {
// Puts the service into a namespace
grpc::string services_namespace;
// Use system includes (<>) or local includes ("")
bool use_system_headers;
// Prefix to any grpc include
grpc::string grpc_search_path;
// Generate GMOCK code to facilitate unit testing.
bool generate_mock_code;
};
// Return the prologue of the generated header file.
grpc::string GetHeaderPrologue(grpc_generator::File *file,
const Parameters &params);
// Return the includes needed for generated header file.
grpc::string GetHeaderIncludes(grpc_generator::File *file,
const Parameters &params);
// Return the includes needed for generated source file.
grpc::string GetSourceIncludes(grpc_generator::File *file,
const Parameters &params);
// Return the epilogue of the generated header file.
grpc::string GetHeaderEpilogue(grpc_generator::File *file,
const Parameters &params);
// Return the prologue of the generated source file.
grpc::string GetSourcePrologue(grpc_generator::File *file,
const Parameters &params);
// Return the services for generated header file.
grpc::string GetHeaderServices(grpc_generator::File *file,
const Parameters &params);
// Return the services for generated source file.
grpc::string GetSourceServices(grpc_generator::File *file,
const Parameters &params);
// Return the epilogue of the generated source file.
grpc::string GetSourceEpilogue(grpc_generator::File *file,
const Parameters &params);
// Return the prologue of the generated mock file.
grpc::string GetMockPrologue(grpc_generator::File *file,
const Parameters &params);
// Return the includes needed for generated mock file.
grpc::string GetMockIncludes(grpc_generator::File *file,
const Parameters &params);
// Return the services for generated mock file.
grpc::string GetMockServices(grpc_generator::File *file,
const Parameters &params);
// Return the epilogue of generated mock file.
grpc::string GetMockEpilogue(grpc_generator::File *file,
const Parameters &params);
// Return the prologue of the generated mock file.
grpc::string GetMockPrologue(grpc_generator::File *file,
const Parameters &params);
// Return the includes needed for generated mock file.
grpc::string GetMockIncludes(grpc_generator::File *file,
const Parameters &params);
// Return the services for generated mock file.
grpc::string GetMockServices(grpc_generator::File *file,
const Parameters &params);
// Return the epilogue of generated mock file.
grpc::string GetMockEpilogue(grpc_generator::File *file,
const Parameters &params);
} // namespace grpc_cpp_generator
#endif // GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H

View File

@ -0,0 +1,446 @@
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation AN/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <map>
#include <cctype>
#include <sstream>
#include "src/compiler/go_generator.h"
template <class T>
grpc::string as_string(T x) {
std::ostringstream out;
out << x;
return out.str();
}
inline bool ClientOnlyStreaming(const grpc_generator::Method *method) {
return method->ClientStreaming() && !method->ServerStreaming();
}
inline bool ServerOnlyStreaming(const grpc_generator::Method *method) {
return !method->ClientStreaming() && method->ServerStreaming();
}
namespace grpc_go_generator {
// Returns string with first letter to lowerCase
grpc::string unexportName(grpc::string s) {
if (s.empty())
return s;
s[0] = static_cast<char>(std::tolower(s[0]));
return s;
}
// Returns string with first letter to uppercase
grpc::string exportName(grpc::string s) {
if (s.empty())
return s;
s[0] = static_cast<char>(std::toupper(s[0]));
return s;
}
// Generates imports for the service
void GenerateImports(grpc_generator::File *file, grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
vars["filename"] = file->filename();
printer->Print("//Generated by gRPC Go plugin\n");
printer->Print("//If you make any local changes, they will be lost\n");
printer->Print(vars, "//source: $filename$\n\n");
printer->Print(vars, "package $Package$\n\n");
if (file->additional_headers() != "") {
printer->Print(file->additional_headers().c_str());
printer->Print("\n\n");
}
printer->Print("import (\n");
printer->Indent();
printer->Print(vars, "$context$ \"context\"\n");
printer->Print(vars, "$grpc$ \"google.golang.org/grpc\"\n");
printer->Outdent();
printer->Print(")\n\n");
}
// Generates Server method signature source
void GenerateServerMethodSignature(const grpc_generator::Method *method, grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
vars["Method"] = exportName(method->name());
vars["Request"] = method->get_input_type_name();
vars["Response"] = (vars["CustomMethodIO"] == "") ? method->get_output_type_name() : vars["CustomMethodIO"];
if (method->NoStreaming()) {
printer->Print(vars, "$Method$($context$.Context, *$Request$) (*$Response$, error)");
} else if (ServerOnlyStreaming(method)) {
printer->Print(vars, "$Method$(*$Request$, $Service$_$Method$Server) error");
} else {
printer->Print(vars, "$Method$($Service$_$Method$Server) error");
}
}
void GenerateServerMethod(const grpc_generator::Method *method, grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
vars["Method"] = exportName(method->name());
vars["Request"] = method->get_input_type_name();
vars["Response"] = (vars["CustomMethodIO"] == "") ? method->get_output_type_name() : vars["CustomMethodIO"];
vars["FullMethodName"] = "/" + vars["ServicePrefix"] + "." + vars["Service"] + "/" + vars["Method"];
vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
if (method->NoStreaming()) {
printer->Print(vars, "func $Handler$(srv interface{}, ctx $context$.Context,\n\tdec func(interface{}) error, interceptor $grpc$.UnaryServerInterceptor) (interface{}, error) {\n");
printer->Indent();
printer->Print(vars, "in := new($Request$)\n");
printer->Print("if err := dec(in); err != nil { return nil, err }\n");
printer->Print(vars, "if interceptor == nil { return srv.($Service$Server).$Method$(ctx, in) }\n");
printer->Print(vars, "info := &$grpc$.UnaryServerInfo{\n");
printer->Indent();
printer->Print("Server: srv,\n");
printer->Print(vars, "FullMethod: \"$FullMethodName$\",\n");
printer->Outdent();
printer->Print("}\n\n");
printer->Print(vars, "handler := func(ctx $context$.Context, req interface{}) (interface{}, error) {\n");
printer->Indent();
printer->Print(vars, "return srv.($Service$Server).$Method$(ctx, req.(* $Request$))\n");
printer->Outdent();
printer->Print("}\n");
printer->Print("return interceptor(ctx, in, info, handler)\n");
printer->Outdent();
printer->Print("}\n\n");
return;
}
vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Server";
printer->Print(vars, "func $Handler$(srv interface{}, stream $grpc$.ServerStream) error {\n");
printer->Indent();
if (ServerOnlyStreaming(method)) {
printer->Print(vars, "m := new($Request$)\n");
printer->Print(vars, "if err := stream.RecvMsg(m); err != nil { return err }\n");
printer->Print(vars, "return srv.($Service$Server).$Method$(m, &$StreamType${stream})\n");
} else {
printer->Print(vars, "return srv.($Service$Server).$Method$(&$StreamType${stream})\n");
}
printer->Outdent();
printer->Print("}\n\n");
bool genSend = method->BidiStreaming() || ServerOnlyStreaming(method);
bool genRecv = method->BidiStreaming() || ClientOnlyStreaming(method);
bool genSendAndClose = ClientOnlyStreaming(method);
printer->Print(vars, "type $Service$_$Method$Server interface { \n");
printer->Indent();
if (genSend) {
printer->Print(vars, "Send(* $Response$) error\n");
}
if (genRecv) {
printer->Print(vars, "Recv() (* $Request$, error)\n");
}
if (genSendAndClose) {
printer->Print(vars, "SendAndClose(* $Response$) error\n");
}
printer->Print(vars, "$grpc$.ServerStream\n");
printer->Outdent();
printer->Print("}\n\n");
printer->Print(vars, "type $StreamType$ struct {\n");
printer->Indent();
printer->Print(vars, "$grpc$.ServerStream\n");
printer->Outdent();
printer->Print("}\n\n");
if (genSend) {
printer->Print(vars, "func (x *$StreamType$) Send(m *$Response$) error {\n");
printer->Indent();
printer->Print("return x.ServerStream.SendMsg(m)\n");
printer->Outdent();
printer->Print("}\n\n");
}
if (genRecv) {
printer->Print(vars, "func (x *$StreamType$) Recv() (*$Request$, error) {\n");
printer->Indent();
printer->Print(vars, "m := new($Request$)\n");
printer->Print("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }\n");
printer->Print("return m, nil\n");
printer->Outdent();
printer->Print("}\n\n");
}
if (genSendAndClose) {
printer->Print(vars, "func (x *$StreamType$) SendAndClose(m *$Response$) error {\n");
printer->Indent();
printer->Print("return x.ServerStream.SendMsg(m)\n");
printer->Outdent();
printer->Print("}\n\n");
}
}
// Generates Client method signature source
void GenerateClientMethodSignature(const grpc_generator::Method *method, grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
vars["Method"] = exportName(method->name());
vars["Request"] = ", in *" + ((vars["CustomMethodIO"] == "") ? method->get_input_type_name() : vars["CustomMethodIO"]);
if (ClientOnlyStreaming(method) || method->BidiStreaming()) {
vars["Request"] = "";
}
vars["Response"] = "* " + method->get_output_type_name();
if (ClientOnlyStreaming(method) || method->BidiStreaming() || ServerOnlyStreaming(method)) {
vars["Response"] = vars["Service"] + "_" + vars["Method"] + "Client" ;
}
printer->Print(vars, "$Method$(ctx $context$.Context$Request$, \n\topts... $grpc$.CallOption) ($Response$, error)");
}
// Generates Client method source
void GenerateClientMethod(const grpc_generator::Method *method, grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
printer->Print(vars, "func (c *$ServiceUnexported$Client) ");
GenerateClientMethodSignature(method, printer, vars);
printer->Print(" {\n");
printer->Indent();
vars["Method"] = exportName(method->name());
vars["Request"] = (vars["CustomMethodIO"] == "") ? method->get_input_type_name() : vars["CustomMethodIO"];
vars["Response"] = method->get_output_type_name();
vars["FullMethodName"] = "/" + vars["ServicePrefix"] + "." + vars["Service"] + "/" + vars["Method"];
if (method->NoStreaming()) {
printer->Print(vars, "out := new($Response$)\n");
printer->Print(vars, "err := $grpc$.Invoke(ctx, \"$FullMethodName$\", in, out, c.cc, opts...)\n");
printer->Print("if err != nil { return nil, err }\n");
printer->Print("return out, nil\n");
printer->Outdent();
printer->Print("}\n\n");
return;
}
vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Client";
printer->Print(vars, "stream, err := $grpc$.NewClientStream(ctx, &$MethodDesc$, c.cc, \"$FullMethodName$\", opts...)\n");
printer->Print("if err != nil { return nil, err }\n");
printer->Print(vars, "x := &$StreamType${stream}\n");
if (ServerOnlyStreaming(method)) {
printer->Print("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }\n");
printer->Print("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }\n");
}
printer->Print("return x,nil\n");
printer->Outdent();
printer->Print("}\n\n");
bool genSend = method->BidiStreaming() || ClientOnlyStreaming(method);
bool genRecv = method->BidiStreaming() || ServerOnlyStreaming(method);
bool genCloseAndRecv = ClientOnlyStreaming(method);
//Stream interface
printer->Print(vars, "type $Service$_$Method$Client interface {\n");
printer->Indent();
if (genSend) {
printer->Print(vars, "Send(*$Request$) error\n");
}
if (genRecv) {
printer->Print(vars, "Recv() (*$Response$, error)\n");
}
if (genCloseAndRecv) {
printer->Print(vars, "CloseAndRecv() (*$Response$, error)\n");
}
printer->Print(vars, "$grpc$.ClientStream\n");
printer->Outdent();
printer->Print("}\n\n");
//Stream Client
printer->Print(vars, "type $StreamType$ struct{\n");
printer->Indent();
printer->Print(vars, "$grpc$.ClientStream\n");
printer->Outdent();
printer->Print("}\n\n");
if (genSend) {
printer->Print(vars, "func (x *$StreamType$) Send(m *$Request$) error {\n");
printer->Indent();
printer->Print("return x.ClientStream.SendMsg(m)\n");
printer->Outdent();
printer->Print("}\n\n");
}
if (genRecv) {
printer->Print(vars, "func (x *$StreamType$) Recv() (*$Response$, error) {\n");
printer->Indent();
printer->Print(vars, "m := new($Response$)\n");
printer->Print("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }\n");
printer->Print("return m, nil\n");
printer->Outdent();
printer->Print("}\n\n");
}
if (genCloseAndRecv) {
printer->Print(vars, "func (x *$StreamType$) CloseAndRecv() (*$Response$, error) {\n");
printer->Indent();
printer->Print("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }\n");
printer->Print(vars, "m := new ($Response$)\n");
printer->Print("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }\n");
printer->Print("return m, nil\n");
printer->Outdent();
printer->Print("}\n\n");
}
}
// Generates client API for the service
void GenerateService(const grpc_generator::Service *service, grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string> vars) {
vars["Service"] = exportName(service->name());
// Client Interface
printer->Print(vars, "// Client API for $Service$ service\n");
printer->Print(vars, "type $Service$Client interface{\n");
printer->Indent();
for (int i = 0; i < service->method_count(); i++) {
GenerateClientMethodSignature(service->method(i).get(), printer, vars);
printer->Print("\n");
}
printer->Outdent();
printer->Print("}\n\n");
// Client structure
vars["ServiceUnexported"] = unexportName(vars["Service"]);
printer->Print(vars, "type $ServiceUnexported$Client struct {\n");
printer->Indent();
printer->Print(vars, "cc *$grpc$.ClientConn\n");
printer->Outdent();
printer->Print("}\n\n");
// NewClient
printer->Print(vars, "func New$Service$Client(cc *$grpc$.ClientConn) $Service$Client {\n");
printer->Indent();
printer->Print(vars, "return &$ServiceUnexported$Client{cc}");
printer->Outdent();
printer->Print("\n}\n\n");
int unary_methods = 0, streaming_methods = 0;
vars["ServiceDesc"] = "_" + vars["Service"] + "_serviceDesc";
for (int i = 0; i < service->method_count(); i++) {
auto method = service->method(i);
if (method->NoStreaming()) {
vars["MethodDesc"] = vars["ServiceDesc"] + ".Method[" + as_string(unary_methods) + "]";
unary_methods++;
} else {
vars["MethodDesc"] = vars["ServiceDesc"] + ".Streams[" + as_string(streaming_methods) + "]";
streaming_methods++;
}
GenerateClientMethod(method.get(), printer, vars);
}
//Server Interface
printer->Print(vars, "// Server API for $Service$ service\n");
printer->Print(vars, "type $Service$Server interface {\n");
printer->Indent();
for (int i = 0; i < service->method_count(); i++) {
GenerateServerMethodSignature(service->method(i).get(), printer, vars);
printer->Print("\n");
}
printer->Outdent();
printer->Print("}\n\n");
// Server registration.
printer->Print(vars, "func Register$Service$Server(s *$grpc$.Server, srv $Service$Server) {\n");
printer->Indent();
printer->Print(vars, "s.RegisterService(&$ServiceDesc$, srv)\n");
printer->Outdent();
printer->Print("}\n\n");
for (int i = 0; i < service->method_count(); i++) {
GenerateServerMethod(service->method(i).get(), printer, vars);
printer->Print("\n");
}
//Service Descriptor
printer->Print(vars, "var $ServiceDesc$ = $grpc$.ServiceDesc{\n");
printer->Indent();
printer->Print(vars, "ServiceName: \"$ServicePrefix$.$Service$\",\n");
printer->Print(vars, "HandlerType: (*$Service$Server)(nil),\n");
printer->Print(vars, "Methods: []$grpc$.MethodDesc{\n");
printer->Indent();
for (int i = 0; i < service->method_count(); i++) {
auto method = service->method(i);
vars["Method"] = method->name();
vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
if (method->NoStreaming()) {
printer->Print("{\n");
printer->Indent();
printer->Print(vars, "MethodName: \"$Method$\",\n");
printer->Print(vars, "Handler: $Handler$, \n");
printer->Outdent();
printer->Print("},\n");
}
}
printer->Outdent();
printer->Print("},\n");
printer->Print(vars, "Streams: []$grpc$.StreamDesc{\n");
printer->Indent();
for (int i = 0; i < service->method_count(); i++) {
auto method = service->method(i);
vars["Method"] = method->name();
vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
if (!method->NoStreaming()) {
printer->Print("{\n");
printer->Indent();
printer->Print(vars, "StreamName: \"$Method$\",\n");
printer->Print(vars, "Handler: $Handler$, \n");
if (ClientOnlyStreaming(method.get())) {
printer->Print("ClientStreams: true,\n");
} else if (ServerOnlyStreaming(method.get())) {
printer->Print("ServerStreams: true,\n");
} else {
printer->Print("ServerStreams: true,\n");
printer->Print("ClientStreams: true,\n");
}
printer->Outdent();
printer->Print("},\n");
}
}
printer->Outdent();
printer->Print("},\n");
printer->Outdent();
printer->Print("}\n\n");
}
// Returns source for the service
grpc::string GenerateServiceSource(grpc_generator::File *file,
const grpc_generator::Service *service,
grpc_go_generator::Parameters *parameters) {
grpc::string out;
auto p = file->CreatePrinter(&out);
auto printer = p.get();
std::map<grpc::string, grpc::string> vars;
vars["Package"] = parameters->package_name;
vars["ServicePrefix"] = parameters->service_prefix;
vars["grpc"] = "grpc";
vars["context"] = "context";
GenerateImports(file, printer, vars);
if (parameters->custom_method_io_type != "") {
vars["CustomMethodIO"] = parameters->custom_method_io_type;
}
GenerateService(service, printer, vars);
return out;
}
}// Namespace grpc_go_generator

View File

@ -0,0 +1,64 @@
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
#define GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
//go generator is used to generate GRPC code for serialization system, such as flatbuffers
#include <memory>
#include <vector>
#include "src/compiler/schema_interface.h"
namespace grpc_go_generator {
struct Parameters {
//Defines the custom parameter types for methods
//eg: flatbuffers uses flatbuffers.Builder as input for the client and output for the server
grpc::string custom_method_io_type;
//Package name for the service
grpc::string package_name;
//Prefix for RPC Calls
grpc::string service_prefix;
};
// Return the source of the generated service file.
grpc::string GenerateServiceSource(grpc_generator::File *file,
const grpc_generator::Service *service,
grpc_go_generator::Parameters *parameters);
}
#endif // GRPC_INTERNAL_COMPILER_GO_GENERATOR_H

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,85 @@
/*
* Copyright 2016 Google Inc. All rights reserved.
*
* 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.
*/
#ifndef NET_GRPC_COMPILER_JAVA_GENERATOR_H_
#define NET_GRPC_COMPILER_JAVA_GENERATOR_H_
#include <stdlib.h> // for abort()
#include <iostream>
#include <map>
#include <string>
#include "src/compiler/schema_interface.h"
class LogMessageVoidify {
public:
LogMessageVoidify() {}
// This has to be an operator with a precedence lower than << but
// higher than ?:
void operator&(std::ostream&) {}
};
class LogHelper {
std::ostream* os_;
public:
LogHelper(std::ostream* os) : os_(os) {}
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning( \
disable : 4722) // the flow of control terminates in a destructor
// (needed to compile ~LogHelper where destructor emits abort intentionally -
// inherited from grpc/java code generator).
#endif
~LogHelper() {
*os_ << std::endl;
::abort();
}
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
std::ostream& get_os() const { return *os_; }
};
// Abort the program after logging the mesage if the given condition is not
// true. Otherwise, do nothing.
#define GRPC_CODEGEN_CHECK(x) \
(x) ? (void)0 \
: LogMessageVoidify() & LogHelper(&std::cerr).get_os() \
<< "CHECK FAILED: " << __FILE__ << ":" \
<< __LINE__ << ": "
// Abort the program after logging the mesage.
#define GRPC_CODEGEN_FAIL GRPC_CODEGEN_CHECK(false)
namespace grpc_java_generator {
struct Parameters {
// //Defines the custom parameter types for methods
// //eg: flatbuffers uses flatbuffers.Builder as input for the client
// and output for the server grpc::string custom_method_io_type;
// Package name for the service
grpc::string package_name;
};
// Return the source of the generated service file.
grpc::string GenerateServiceSource(grpc_generator::File* file,
const grpc_generator::Service* service,
grpc_java_generator::Parameters* parameters);
} // namespace grpc_java_generator
#endif // NET_GRPC_COMPILER_JAVA_GENERATOR_H_

View File

@ -0,0 +1,624 @@
/*
*
* Copyright 2015 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.
*
*/
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <ostream>
#include <set>
#include <sstream>
#include <tuple>
#include <vector>
#include "flatbuffers/util.h"
#include "src/compiler/python_generator.h"
#include "src/compiler/python_private_generator.h"
using std::make_pair;
using std::map;
using std::pair;
using std::replace;
using std::tuple;
using std::vector;
using std::set;
namespace grpc_python_generator {
grpc::string generator_file_name;
typedef map<grpc::string, grpc::string> StringMap;
typedef vector<grpc::string> StringVector;
typedef tuple<grpc::string, grpc::string> StringPair;
typedef set<StringPair> StringPairSet;
// Provides RAII indentation handling. Use as:
// {
// IndentScope raii_my_indent_var_name_here(my_py_printer);
// // constructor indented my_py_printer
// ...
// // destructor called at end of scope, un-indenting my_py_printer
// }
class IndentScope {
public:
explicit IndentScope(grpc_generator::Printer* printer) : printer_(printer) {
printer_->Indent();
}
~IndentScope() { printer_->Outdent(); }
private:
grpc_generator::Printer* printer_;
};
inline grpc::string StringReplace(grpc::string str, const grpc::string& from,
const grpc::string& to, bool replace_all) {
size_t pos = 0;
do {
pos = str.find(from, pos);
if (pos == grpc::string::npos) {
break;
}
str.replace(pos, from.length(), to);
pos += to.length();
} while (replace_all);
return str;
}
inline grpc::string StringReplace(grpc::string str, const grpc::string& from,
const grpc::string& to) {
return StringReplace(str, from, to, true);
}
grpc::string ModuleName(const grpc::string& filename,
const grpc::string& import_prefix) {
grpc::string basename = flatbuffers::StripExtension(filename);
basename = StringReplace(basename, "-", "_");
basename = StringReplace(basename, "/", ".");
return import_prefix + basename + "_fb";
}
grpc::string ModuleAlias(const grpc::string& filename,
const grpc::string& import_prefix) {
grpc::string module_name = ModuleName(filename, import_prefix);
// We can't have dots in the module name, so we replace each with _dot_.
// But that could lead to a collision between a.b and a_dot_b, so we also
// duplicate each underscore.
module_name = StringReplace(module_name, "_", "__");
module_name = StringReplace(module_name, ".", "_dot_");
return module_name;
}
PrivateGenerator::PrivateGenerator(const GeneratorConfiguration& config_,
const grpc_generator::File* file_)
: config(config_), file(file_) {}
void PrivateGenerator::PrintBetaServicer(const grpc_generator::Service* service,
grpc_generator::Printer* out) {
StringMap service_dict;
service_dict["Service"] = service->name();
out->Print("\n\n");
out->Print(service_dict, "class Beta$Service$Servicer(object):\n");
{
IndentScope raii_class_indent(out);
out->Print(
"\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
"\nIt is recommended to use the GA API (classes and functions in this\n"
"file not marked beta) for all further purposes. This class was "
"generated\n"
"only to ease transition from grpcio<0.15.0 to "
"grpcio>=0.15.0.\"\"\"\n");
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
grpc::string arg_name =
method->ClientStreaming() ? "request_iterator" : "request";
StringMap method_dict;
method_dict["Method"] = method->name();
method_dict["ArgName"] = arg_name;
out->Print(method_dict, "def $Method$(self, $ArgName$, context):\n");
{
IndentScope raii_method_indent(out);
out->Print("context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)\n");
}
}
}
}
void PrivateGenerator::PrintBetaStub(const grpc_generator::Service* service,
grpc_generator::Printer* out) {
StringMap service_dict;
service_dict["Service"] = service->name();
out->Print("\n\n");
out->Print(service_dict, "class Beta$Service$Stub(object):\n");
{
IndentScope raii_class_indent(out);
out->Print(
"\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
"\nIt is recommended to use the GA API (classes and functions in this\n"
"file not marked beta) for all further purposes. This class was "
"generated\n"
"only to ease transition from grpcio<0.15.0 to "
"grpcio>=0.15.0.\"\"\"\n");
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
grpc::string arg_name =
method->ClientStreaming() ? "request_iterator" : "request";
StringMap method_dict;
method_dict["Method"] = method->name();
method_dict["ArgName"] = arg_name;
out->Print(method_dict,
"def $Method$(self, $ArgName$, timeout, metadata=None, "
"with_call=False, protocol_options=None):\n");
{
IndentScope raii_method_indent(out);
out->Print("raise NotImplementedError()\n");
}
if (!method->ServerStreaming()) {
out->Print(method_dict, "$Method$.future = None\n");
}
}
}
}
void PrivateGenerator::PrintBetaServerFactory(
const grpc::string& package_qualified_service_name,
const grpc_generator::Service* service, grpc_generator::Printer* out) {
StringMap service_dict;
service_dict["Service"] = service->name();
out->Print("\n\n");
out->Print(service_dict,
"def beta_create_$Service$_server(servicer, pool=None, "
"pool_size=None, default_timeout=None, maximum_timeout=None):\n");
{
IndentScope raii_create_server_indent(out);
out->Print(
"\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
"\nIt is recommended to use the GA API (classes and functions in this\n"
"file not marked beta) for all further purposes. This function was\n"
"generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"
"\"\"\"\n");
StringMap method_implementation_constructors;
StringMap input_message_modules_and_classes;
StringMap output_message_modules_and_classes;
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
const grpc::string method_implementation_constructor =
grpc::string(method->ClientStreaming() ? "stream_" : "unary_") +
grpc::string(method->ServerStreaming() ? "stream_" : "unary_") +
"inline";
grpc::string input_message_module_and_class = method->get_fb_builder();
grpc::string output_message_module_and_class = method->get_fb_builder();
method_implementation_constructors.insert(
make_pair(method->name(), method_implementation_constructor));
input_message_modules_and_classes.insert(
make_pair(method->name(), input_message_module_and_class));
output_message_modules_and_classes.insert(
make_pair(method->name(), output_message_module_and_class));
}
StringMap method_dict;
method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
// out->Print("request_deserializers = {\n");
// for (StringMap::iterator name_and_input_module_class_pair =
// input_message_modules_and_classes.begin();
// name_and_input_module_class_pair !=
// input_message_modules_and_classes.end();
// name_and_input_module_class_pair++) {
// method_dict["MethodName"] = name_and_input_module_class_pair->first;
// method_dict["InputTypeModuleAndClass"] =
// name_and_input_module_class_pair->second;
// IndentScope raii_indent(out);
// out->Print(method_dict,
// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
// "$InputTypeModuleAndClass$.FromString,\n");
// }
// out->Print("}\n");
// out->Print("response_serializers = {\n");
// for (StringMap::iterator name_and_output_module_class_pair =
// output_message_modules_and_classes.begin();
// name_and_output_module_class_pair !=
// output_message_modules_and_classes.end();
// name_and_output_module_class_pair++) {
// method_dict["MethodName"] = name_and_output_module_class_pair->first;
// method_dict["OutputTypeModuleAndClass"] =
// name_and_output_module_class_pair->second;
// IndentScope raii_indent(out);
// out->Print(method_dict,
// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
// "$OutputTypeModuleAndClass$.SerializeToString,\n");
// }
// out->Print("}\n");
out->Print("method_implementations = {\n");
for (StringMap::iterator name_and_implementation_constructor =
method_implementation_constructors.begin();
name_and_implementation_constructor !=
method_implementation_constructors.end();
name_and_implementation_constructor++) {
method_dict["Method"] = name_and_implementation_constructor->first;
method_dict["Constructor"] = name_and_implementation_constructor->second;
IndentScope raii_descriptions_indent(out);
const grpc::string method_name =
name_and_implementation_constructor->first;
out->Print(method_dict,
"(\'$PackageQualifiedServiceName$\', \'$Method$\'): "
"face_utilities.$Constructor$(servicer.$Method$),\n");
}
out->Print("}\n");
out->Print(
"server_options = beta_implementations.server_options("
"thread_pool=pool, thread_pool_size=pool_size, "
"default_timeout=default_timeout, "
"maximum_timeout=maximum_timeout)\n");
out->Print(
"return beta_implementations.server(method_implementations, "
"options=server_options)\n");
//"request_deserializers=request_deserializers, "
//"response_serializers=response_serializers, "
}
}
void PrivateGenerator::PrintBetaStubFactory(
const grpc::string& package_qualified_service_name,
const grpc_generator::Service* service, grpc_generator::Printer* out) {
StringMap dict;
dict["Service"] = service->name();
out->Print("\n\n");
out->Print(dict,
"def beta_create_$Service$_stub(channel, host=None,"
" metadata_transformer=None, pool=None, pool_size=None):\n");
{
IndentScope raii_create_server_indent(out);
out->Print(
"\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
"\nIt is recommended to use the GA API (classes and functions in this\n"
"file not marked beta) for all further purposes. This function was\n"
"generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"
"\"\"\"\n");
StringMap method_cardinalities;
StringMap input_message_modules_and_classes;
StringMap output_message_modules_and_classes;
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
const grpc::string method_cardinality =
grpc::string(method->ClientStreaming() ? "STREAM" : "UNARY") +
"_" +
grpc::string(method->ServerStreaming() ? "STREAM" : "UNARY");
grpc::string input_message_module_and_class = method->get_fb_builder();
grpc::string output_message_module_and_class = method->get_fb_builder();
method_cardinalities.insert(
make_pair(method->name(), method_cardinality));
input_message_modules_and_classes.insert(
make_pair(method->name(), input_message_module_and_class));
output_message_modules_and_classes.insert(
make_pair(method->name(), output_message_module_and_class));
}
StringMap method_dict;
method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
// out->Print("request_serializers = {\n");
// for (StringMap::iterator name_and_input_module_class_pair =
// input_message_modules_and_classes.begin();
// name_and_input_module_class_pair !=
// input_message_modules_and_classes.end();
// name_and_input_module_class_pair++) {
// method_dict["MethodName"] = name_and_input_module_class_pair->first;
// method_dict["InputTypeModuleAndClass"] =
// name_and_input_module_class_pair->second;
// IndentScope raii_indent(out);
// out->Print(method_dict,
// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
// "$InputTypeModuleAndClass$.SerializeToString,\n");
// }
// out->Print("}\n");
// out->Print("response_deserializers = {\n");
// for (StringMap::iterator name_and_output_module_class_pair =
// output_message_modules_and_classes.begin();
// name_and_output_module_class_pair !=
// output_message_modules_and_classes.end();
// name_and_output_module_class_pair++) {
// method_dict["MethodName"] = name_and_output_module_class_pair->first;
// method_dict["OutputTypeModuleAndClass"] =
// name_and_output_module_class_pair->second;
// IndentScope raii_indent(out);
// out->Print(method_dict,
// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
// "$OutputTypeModuleAndClass$.FromString,\n");
// }
// out->Print("}\n");
out->Print("cardinalities = {\n");
for (StringMap::iterator name_and_cardinality =
method_cardinalities.begin();
name_and_cardinality != method_cardinalities.end();
name_and_cardinality++) {
method_dict["Method"] = name_and_cardinality->first;
method_dict["Cardinality"] = name_and_cardinality->second;
IndentScope raii_descriptions_indent(out);
out->Print(method_dict,
"\'$Method$\': cardinality.Cardinality.$Cardinality$,\n");
}
out->Print("}\n");
out->Print(
"stub_options = beta_implementations.stub_options("
"host=host, metadata_transformer=metadata_transformer, "
"thread_pool=pool, thread_pool_size=pool_size)\n");
out->Print(method_dict,
"return beta_implementations.dynamic_stub(channel, "
"\'$PackageQualifiedServiceName$\', "
"cardinalities, options=stub_options)\n");
// "request_serializers=request_serializers, "
//"response_deserializers=response_deserializers, "
}
}
void PrivateGenerator::PrintStub(
const grpc::string& package_qualified_service_name,
const grpc_generator::Service* service, grpc_generator::Printer* out) {
StringMap dict;
dict["Service"] = service->name();
out->Print("\n\n");
out->Print(dict, "class $Service$Stub(object):\n");
{
IndentScope raii_class_indent(out);
out->Print("\n");
out->Print("def __init__(self, channel):\n");
{
IndentScope raii_init_indent(out);
out->Print("\"\"\"Constructor.\n");
out->Print("\n");
out->Print("Args:\n");
{
IndentScope raii_args_indent(out);
out->Print("channel: A grpc.Channel.\n");
}
out->Print("\"\"\"\n");
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
grpc::string multi_callable_constructor =
grpc::string(method->ClientStreaming() ? "stream" : "unary") +
"_" +
grpc::string(method->ServerStreaming() ? "stream" : "unary");
grpc::string request_module_and_class = method->get_fb_builder();
grpc::string response_module_and_class = method->get_fb_builder();
StringMap method_dict;
method_dict["Method"] = method->name();
method_dict["MultiCallableConstructor"] = multi_callable_constructor;
out->Print(method_dict,
"self.$Method$ = channel.$MultiCallableConstructor$(\n");
{
method_dict["PackageQualifiedService"] =
package_qualified_service_name;
method_dict["RequestModuleAndClass"] = request_module_and_class;
method_dict["ResponseModuleAndClass"] = response_module_and_class;
IndentScope raii_first_attribute_indent(out);
IndentScope raii_second_attribute_indent(out);
out->Print(method_dict, "'/$PackageQualifiedService$/$Method$',\n");
out->Print(method_dict,"\n");
out->Print(
method_dict,"\n");
out->Print(")\n");
}
}
}
}
}
void PrivateGenerator::PrintServicer(const grpc_generator::Service* service,
grpc_generator::Printer* out) {
StringMap service_dict;
service_dict["Service"] = service->name();
out->Print("\n\n");
out->Print(service_dict, "class $Service$Servicer(object):\n");
{
IndentScope raii_class_indent(out);
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
grpc::string arg_name =
method->ClientStreaming() ? "request_iterator" : "request";
StringMap method_dict;
method_dict["Method"] = method->name();
method_dict["ArgName"] = arg_name;
out->Print("\n");
out->Print(method_dict, "def $Method$(self, $ArgName$, context):\n");
{
IndentScope raii_method_indent(out);
out->Print("context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n");
out->Print("context.set_details('Method not implemented!')\n");
out->Print("raise NotImplementedError('Method not implemented!')\n");
}
}
}
}
void PrivateGenerator::PrintAddServicerToServer(
const grpc::string& package_qualified_service_name,
const grpc_generator::Service* service, grpc_generator::Printer* out) {
StringMap service_dict;
service_dict["Service"] = service->name();
out->Print("\n\n");
out->Print(service_dict,
"def add_$Service$Servicer_to_server(servicer, server):\n");
{
IndentScope raii_class_indent(out);
out->Print("rpc_method_handlers = {\n");
{
IndentScope raii_dict_first_indent(out);
IndentScope raii_dict_second_indent(out);
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
grpc::string method_handler_constructor =
grpc::string(method->ClientStreaming() ? "stream" : "unary") +
"_" +
grpc::string(method->ServerStreaming() ? "stream" : "unary") +
"_rpc_method_handler";
grpc::string request_module_and_class = method->get_fb_builder();
grpc::string response_module_and_class = method->get_fb_builder();
StringMap method_dict;
method_dict["Method"] = method->name();
method_dict["MethodHandlerConstructor"] = method_handler_constructor;
method_dict["RequestModuleAndClass"] = request_module_and_class;
method_dict["ResponseModuleAndClass"] = response_module_and_class;
out->Print(method_dict,
"'$Method$': grpc.$MethodHandlerConstructor$(\n");
{
IndentScope raii_call_first_indent(out);
IndentScope raii_call_second_indent(out);
out->Print(method_dict, "servicer.$Method$,\n");
out->Print(
method_dict,"\n");
out->Print(
method_dict,
"\n");
}
out->Print("),\n");
}
}
StringMap method_dict;
method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
out->Print("}\n");
out->Print("generic_handler = grpc.method_handlers_generic_handler(\n");
{
IndentScope raii_call_first_indent(out);
IndentScope raii_call_second_indent(out);
out->Print(method_dict,
"'$PackageQualifiedServiceName$', rpc_method_handlers)\n");
}
out->Print("server.add_generic_rpc_handlers((generic_handler,))\n");
}
}
void PrivateGenerator::PrintBetaPreamble(grpc_generator::Printer* out) {
StringMap var;
var["Package"] = config.beta_package_root;
out->Print(var,
"from $Package$ import implementations as beta_implementations\n");
out->Print(var, "from $Package$ import interfaces as beta_interfaces\n");
out->Print("from grpc.framework.common import cardinality\n");
out->Print(
"from grpc.framework.interfaces.face import utilities as "
"face_utilities\n");
}
void PrivateGenerator::PrintPreamble(grpc_generator::Printer* out) {
StringMap var;
var["Package"] = config.grpc_package_root;
out->Print(var, "import $Package$\n");
out->Print("\n");
StringPairSet imports_set;
for (int i = 0; i < file->service_count(); ++i) {
auto service = file->service(i);
for (int j = 0; j < service->method_count(); ++j) {
auto method = service.get()->method(j);
grpc::string input_type_file_name = method->get_fb_builder();
grpc::string input_module_name =
ModuleName(input_type_file_name, config.import_prefix);
grpc::string input_module_alias =
ModuleAlias(input_type_file_name, config.import_prefix);
imports_set.insert(
std::make_tuple(input_module_name, input_module_alias));
grpc::string output_type_file_name = method->get_fb_builder();
grpc::string output_module_name =
ModuleName(output_type_file_name, config.import_prefix);
grpc::string output_module_alias =
ModuleAlias(output_type_file_name, config.import_prefix);
imports_set.insert(
std::make_tuple(output_module_name, output_module_alias));
}
}
for (StringPairSet::iterator it = imports_set.begin();
it != imports_set.end(); ++it) {
var["ModuleName"] = std::get<0>(*it);
var["ModuleAlias"] = std::get<1>(*it);
out->Print(var, "import $ModuleName$ as $ModuleAlias$\n");
}
}
void PrivateGenerator::PrintGAServices(grpc_generator::Printer* out) {
grpc::string package = file->package();
if (!package.empty()) {
package = package.append(".");
}
out->Print(file->additional_headers().c_str());
for (int i = 0; i < file->service_count(); ++i) {
auto service = file->service(i);
grpc::string package_qualified_service_name = package + service->name();
PrintStub(package_qualified_service_name, service.get(), out);
PrintServicer(service.get(), out);
PrintAddServicerToServer(package_qualified_service_name, service.get(),
out);
}
}
void PrivateGenerator::PrintBetaServices(grpc_generator::Printer* out) {
grpc::string package = file->package();
if (!package.empty()) {
package = package.append(".");
}
for (int i = 0; i < file->service_count(); ++i) {
auto service = file->service(i);
grpc::string package_qualified_service_name = package + service->name();
PrintBetaServicer(service.get(), out);
PrintBetaStub(service.get(), out);
PrintBetaServerFactory(package_qualified_service_name, service.get(), out);
PrintBetaStubFactory(package_qualified_service_name, service.get(), out);
}
}
grpc::string PrivateGenerator::GetGrpcServices() {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
auto out = file->CreatePrinter(&output);
out->Print(
"# Generated by the gRPC Python protocol compiler plugin. "
"DO NOT EDIT!\n");
StringMap var;
var["Package"] = config.grpc_package_root;
out->Print(var, "import $Package$\n");
PrintGAServices(out.get());
out->Print("try:\n");
{
IndentScope raii_dict_try_indent(out.get());
out->Print(
"# THESE ELEMENTS WILL BE DEPRECATED.\n"
"# Please use the generated *_pb2_grpc.py files instead.\n");
out->Print(var, "import $Package$\n");
PrintBetaPreamble(out.get());
PrintGAServices(out.get());
PrintBetaServices(out.get());
}
out->Print("except ImportError:\n");
{
IndentScope raii_dict_except_indent(out.get());
out->Print("pass");
}
}
return output;
}
} // namespace grpc_python_generator

View File

@ -0,0 +1,40 @@
/*
*
* Copyright 2015 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.
*
*/
#ifndef GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H
#define GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H
#include <utility>
#include "src/compiler/schema_interface.h"
namespace grpc_python_generator {
// Data pertaining to configuration of the generator with respect to anything
// that may be used internally at Google.
struct GeneratorConfiguration {
grpc::string grpc_package_root;
// TODO(https://github.com/grpc/grpc/issues/8622): Drop this.
grpc::string beta_package_root;
// TODO(https://github.com/google/protobuf/issues/888): Drop this.
grpc::string import_prefix;
};
} // namespace grpc_python_generator
#endif // GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H

View File

@ -0,0 +1,72 @@
/*
*
* Copyright 2015 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.
*
*/
#ifndef GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
#define GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
#include <iostream>
#include <vector>
#include "src/compiler/python_generator.h"
#include "src/compiler/schema_interface.h"
namespace grpc_python_generator {
// Tucks all generator state in an anonymous namespace away from
// PythonGrpcGenerator and the header file, mostly to encourage future changes
// to not require updates to the grpcio-tools C++ code part. Assumes that it is
// only ever used from a single thread.
struct PrivateGenerator {
const GeneratorConfiguration& config;
const grpc_generator::File* file;
PrivateGenerator(const GeneratorConfiguration& config,
const grpc_generator::File* file);
grpc::string GetGrpcServices();
private:
void PrintPreamble(grpc_generator::Printer* out);
void PrintBetaPreamble(grpc_generator::Printer* out);
void PrintGAServices(grpc_generator::Printer* out);
void PrintBetaServices(grpc_generator::Printer* out);
void PrintAddServicerToServer(
const grpc::string& package_qualified_service_name,
const grpc_generator::Service* service, grpc_generator::Printer* out);
void PrintServicer(const grpc_generator::Service* service,
grpc_generator::Printer* out);
void PrintStub(const grpc::string& package_qualified_service_name,
const grpc_generator::Service* service,
grpc_generator::Printer* out);
void PrintBetaServicer(const grpc_generator::Service* service,
grpc_generator::Printer* out);
void PrintBetaServerFactory(
const grpc::string& package_qualified_service_name,
const grpc_generator::Service* service, grpc_generator::Printer* out);
void PrintBetaStub(const grpc_generator::Service* service,
grpc_generator::Printer* out);
void PrintBetaStubFactory(const grpc::string& package_qualified_service_name,
const grpc_generator::Service* service,
grpc_generator::Printer* out);
};
} // namespace grpc_python_generator
#endif // GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H

View File

@ -0,0 +1,114 @@
/*
*
* Copyright 2015 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.
*
*/
#ifndef GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
#define GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
#include <memory>
#include <vector>
#include "src/compiler/config.h"
#ifndef GRPC_CUSTOM_STRING
# include <string>
# define GRPC_CUSTOM_STRING std::string
#endif
namespace grpc {
typedef GRPC_CUSTOM_STRING string;
} // namespace grpc
namespace grpc_generator {
// A common interface for objects having comments in the source.
// Return formatted comments to be inserted in generated code.
struct CommentHolder {
virtual ~CommentHolder() {}
virtual grpc::string GetLeadingComments(const grpc::string prefix) const = 0;
virtual grpc::string GetTrailingComments(const grpc::string prefix) const = 0;
virtual std::vector<grpc::string> GetAllComments() const = 0;
};
// An abstract interface representing a method.
struct Method : public CommentHolder {
virtual ~Method() {}
virtual grpc::string name() const = 0;
virtual grpc::string input_type_name() const = 0;
virtual grpc::string output_type_name() const = 0;
virtual bool get_module_and_message_path_input(
grpc::string *str, grpc::string generator_file_name,
bool generate_in_pb2_grpc, grpc::string import_prefix) const = 0;
virtual bool get_module_and_message_path_output(
grpc::string *str, grpc::string generator_file_name,
bool generate_in_pb2_grpc, grpc::string import_prefix) const = 0;
virtual grpc::string get_input_type_name() const = 0;
virtual grpc::string get_output_type_name() const = 0;
virtual grpc::string get_fb_builder() const = 0;
virtual bool NoStreaming() const = 0;
virtual bool ClientStreaming() const = 0;
virtual bool ServerStreaming() const = 0;
virtual bool BidiStreaming() const = 0;
};
// An abstract interface representing a service.
struct Service : public CommentHolder {
virtual ~Service() {}
virtual grpc::string name() const = 0;
virtual int method_count() const = 0;
virtual std::unique_ptr<const Method> method(int i) const = 0;
};
struct Printer {
virtual ~Printer() {}
virtual void Print(const std::map<grpc::string, grpc::string> &vars,
const char *template_string) = 0;
virtual void Print(const char *string) = 0;
virtual void Indent() = 0;
virtual void Outdent() = 0;
};
// An interface that allows the source generated to be output using various
// libraries/idls/serializers.
struct File : public CommentHolder {
virtual ~File() {}
virtual grpc::string filename() const = 0;
virtual grpc::string filename_without_ext() const = 0;
virtual grpc::string package() const = 0;
virtual std::vector<grpc::string> package_parts() const = 0;
virtual grpc::string additional_headers() const = 0;
virtual int service_count() const = 0;
virtual std::unique_ptr<const Service> service(int i) const = 0;
virtual std::unique_ptr<Printer> CreatePrinter(grpc::string *str) const = 0;
};
} // namespace grpc_generator
#endif // GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H