3 * Copyright 2016 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
21 #include "src/compiler/config.h"
22 #include "src/compiler/generator_helpers.h"
23 #include "src/compiler/node_generator.h"
24 #include "src/compiler/node_generator_helpers.h"
26 using grpc::protobuf::Descriptor;
27 using grpc::protobuf::FileDescriptor;
28 using grpc::protobuf::MethodDescriptor;
29 using grpc::protobuf::ServiceDescriptor;
30 using grpc::protobuf::io::Printer;
31 using grpc::protobuf::io::StringOutputStream;
34 namespace grpc_node_generator {
37 // Returns the alias we assign to the module of the given .proto filename
38 // when importing. Copied entirely from
39 // github:google/protobuf/src/google/protobuf/compiler/js/js_generator.cc#L154
40 grpc::string ModuleAlias(const grpc::string filename) {
41 // This scheme could technically cause problems if a file includes any 2 of:
46 // We'll worry about this problem if/when we actually see it. This name isn't
47 // exposed to users so we can change it later if we need to.
48 grpc::string basename = grpc_generator::StripProto(filename);
49 basename = grpc_generator::StringReplace(basename, "-", "$");
50 basename = grpc_generator::StringReplace(basename, "/", "_");
51 basename = grpc_generator::StringReplace(basename, ".", "_");
52 return basename + "_pb";
55 // Given a filename like foo/bar/baz.proto, returns the corresponding JavaScript
56 // message file foo/bar/baz.js
57 grpc::string GetJSMessageFilename(const grpc::string& filename) {
58 grpc::string name = filename;
59 return grpc_generator::StripProto(name) + "_pb.js";
62 // Given a filename like foo/bar/baz.proto, returns the root directory
64 grpc::string GetRootPath(const grpc::string& from_filename,
65 const grpc::string& to_filename) {
66 if (to_filename.find("google/protobuf") == 0) {
67 // Well-known types (.proto files in the google/protobuf directory) are
68 // assumed to come from the 'google-protobuf' npm package. We may want to
69 // generalize this exception later by letting others put generated code in
70 // their own npm packages.
71 return "google-protobuf/";
73 size_t slashes = std::count(from_filename.begin(), from_filename.end(), '/');
77 grpc::string result = "";
78 for (size_t i = 0; i < slashes; i++) {
84 // Return the relative path to load to_file from the directory containing
85 // from_file, assuming that both paths are relative to the same directory
86 grpc::string GetRelativePath(const grpc::string& from_file,
87 const grpc::string& to_file) {
88 return GetRootPath(from_file, to_file) + to_file;
91 /* Finds all message types used in all services in the file, and returns them
92 * as a map of fully qualified message type name to message descriptor */
93 map<grpc::string, const Descriptor*> GetAllMessages(
94 const FileDescriptor* file) {
95 map<grpc::string, const Descriptor*> message_types;
96 for (int service_num = 0; service_num < file->service_count();
98 const ServiceDescriptor* service = file->service(service_num);
99 for (int method_num = 0; method_num < service->method_count();
101 const MethodDescriptor* method = service->method(method_num);
102 const Descriptor* input_type = method->input_type();
103 const Descriptor* output_type = method->output_type();
104 message_types[input_type->full_name()] = input_type;
105 message_types[output_type->full_name()] = output_type;
108 return message_types;
111 grpc::string MessageIdentifierName(const grpc::string& name) {
112 return grpc_generator::StringReplace(name, ".", "_");
115 grpc::string NodeObjectPath(const Descriptor* descriptor) {
116 grpc::string module_alias = ModuleAlias(descriptor->file()->name());
117 grpc::string name = descriptor->full_name();
118 grpc_generator::StripPrefix(&name, descriptor->file()->package() + ".");
119 return module_alias + "." + name;
122 // Prints out the message serializer and deserializer functions
123 void PrintMessageTransformer(const Descriptor* descriptor, Printer* out,
124 const Parameters& params) {
125 map<grpc::string, grpc::string> template_vars;
126 grpc::string full_name = descriptor->full_name();
127 template_vars["identifier_name"] = MessageIdentifierName(full_name);
128 template_vars["name"] = full_name;
129 template_vars["node_name"] = NodeObjectPath(descriptor);
130 // Print the serializer
131 out->Print(template_vars, "function serialize_$identifier_name$(arg) {\n");
133 out->Print(template_vars, "if (!(arg instanceof $node_name$)) {\n");
135 out->Print(template_vars,
136 "throw new Error('Expected argument of type $name$');\n");
139 if (params.minimum_node_version > 5) {
140 // Node version is > 5, we should use Buffer.from
141 out->Print("return Buffer.from(arg.serializeBinary());\n");
143 out->Print("return new Buffer(arg.serializeBinary());\n");
148 // Print the deserializer
149 out->Print(template_vars,
150 "function deserialize_$identifier_name$(buffer_arg) {\n");
154 "return $node_name$.deserializeBinary(new Uint8Array(buffer_arg));\n");
159 void PrintMethod(const MethodDescriptor* method, Printer* out) {
160 const Descriptor* input_type = method->input_type();
161 const Descriptor* output_type = method->output_type();
162 map<grpc::string, grpc::string> vars;
163 vars["service_name"] = method->service()->full_name();
164 vars["name"] = method->name();
165 vars["input_type"] = NodeObjectPath(input_type);
166 vars["input_type_id"] = MessageIdentifierName(input_type->full_name());
167 vars["output_type"] = NodeObjectPath(output_type);
168 vars["output_type_id"] = MessageIdentifierName(output_type->full_name());
169 vars["client_stream"] = method->client_streaming() ? "true" : "false";
170 vars["server_stream"] = method->server_streaming() ? "true" : "false";
173 out->Print(vars, "path: '/$service_name$/$name$',\n");
174 out->Print(vars, "requestStream: $client_stream$,\n");
175 out->Print(vars, "responseStream: $server_stream$,\n");
176 out->Print(vars, "requestType: $input_type$,\n");
177 out->Print(vars, "responseType: $output_type$,\n");
178 out->Print(vars, "requestSerialize: serialize_$input_type_id$,\n");
179 out->Print(vars, "requestDeserialize: deserialize_$input_type_id$,\n");
180 out->Print(vars, "responseSerialize: serialize_$output_type_id$,\n");
181 out->Print(vars, "responseDeserialize: deserialize_$output_type_id$,\n");
186 // Prints out the service descriptor object
187 void PrintService(const ServiceDescriptor* service, Printer* out) {
188 map<grpc::string, grpc::string> template_vars;
189 out->Print(GetNodeComments(service, true).c_str());
190 template_vars["name"] = service->name();
191 out->Print(template_vars, "var $name$Service = exports.$name$Service = {\n");
193 for (int i = 0; i < service->method_count(); i++) {
194 grpc::string method_name =
195 grpc_generator::LowercaseFirstLetter(service->method(i)->name());
196 out->Print(GetNodeComments(service->method(i), true).c_str());
197 out->Print("$method_name$: ", "method_name", method_name);
198 PrintMethod(service->method(i), out);
200 out->Print(GetNodeComments(service->method(i), false).c_str());
203 out->Print("};\n\n");
204 out->Print(template_vars,
205 "exports.$name$Client = "
206 "grpc.makeGenericClientConstructor($name$Service);\n");
207 out->Print(GetNodeComments(service, false).c_str());
210 void PrintImports(const FileDescriptor* file, Printer* out) {
211 out->Print("var grpc = require('grpc');\n");
212 if (file->message_type_count() > 0) {
213 grpc::string file_path =
214 GetRelativePath(file->name(), GetJSMessageFilename(file->name()));
215 out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
216 ModuleAlias(file->name()), "file_path", file_path);
219 for (int i = 0; i < file->dependency_count(); i++) {
220 grpc::string file_path = GetRelativePath(
221 file->name(), GetJSMessageFilename(file->dependency(i)->name()));
222 out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
223 ModuleAlias(file->dependency(i)->name()), "file_path",
229 void PrintTransformers(const FileDescriptor* file, Printer* out,
230 const Parameters& params) {
231 map<grpc::string, const Descriptor*> messages = GetAllMessages(file);
232 for (std::map<grpc::string, const Descriptor*>::iterator it =
234 it != messages.end(); it++) {
235 PrintMessageTransformer(it->second, out, params);
240 void PrintServices(const FileDescriptor* file, Printer* out) {
241 for (int i = 0; i < file->service_count(); i++) {
242 PrintService(file->service(i), out);
247 grpc::string GenerateFile(const FileDescriptor* file,
248 const Parameters& params) {
251 StringOutputStream output_stream(&output);
252 Printer out(&output_stream, '$');
254 if (file->service_count() == 0) {
257 out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");
259 grpc::string leading_comments = GetNodeComments(file, true);
260 if (!leading_comments.empty()) {
261 out.Print("// Original file comments:\n");
262 out.PrintRaw(leading_comments.c_str());
265 out.Print("'use strict';\n");
267 PrintImports(file, &out);
269 PrintTransformers(file, &out, params);
271 PrintServices(file, &out);
273 out.Print(GetNodeComments(file, false).c_str());
278 } // namespace grpc_node_generator