1 /*
2 *
3 * Copyright 2016 gRPC authors.
4 *
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
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
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.
16 *
17 */
18
19 #include "src/compiler/node_generator.h"
20
21 #include <map>
22
23 #include "src/compiler/config.h"
24 #include "src/compiler/generator_helpers.h"
25 #include "src/compiler/node_generator_helpers.h"
26
27 using grpc::protobuf::Descriptor;
28 using grpc::protobuf::FileDescriptor;
29 using grpc::protobuf::MethodDescriptor;
30 using grpc::protobuf::ServiceDescriptor;
31 using grpc::protobuf::io::Printer;
32 using grpc::protobuf::io::StringOutputStream;
33 using std::map;
34
35 namespace grpc_node_generator {
36 namespace {
37
38 // Returns the alias we assign to the module of the given .proto filename
39 // when importing. Copied entirely from
40 // github:google/protobuf/src/google/protobuf/compiler/js/js_generator.cc#L154
ModuleAlias(const std::string filename)41 std::string ModuleAlias(const std::string filename) {
42 // This scheme could technically cause problems if a file includes any 2 of:
43 // foo/bar_baz.proto
44 // foo_bar_baz.proto
45 // foo_bar/baz.proto
46 //
47 // We'll worry about this problem if/when we actually see it. This name isn't
48 // exposed to users so we can change it later if we need to.
49 std::string basename = grpc_generator::StripProto(filename);
50 basename = grpc_generator::StringReplace(basename, "-", "$");
51 basename = grpc_generator::StringReplace(basename, "/", "_");
52 basename = grpc_generator::StringReplace(basename, ".", "_");
53 return basename + "_pb";
54 }
55
56 // Given a filename like foo/bar/baz.proto, returns the corresponding JavaScript
57 // message file foo/bar/baz.js
GetJSMessageFilename(const std::string & filename)58 std::string GetJSMessageFilename(const std::string& filename) {
59 std::string name = filename;
60 return grpc_generator::StripProto(name) + "_pb.js";
61 }
62
63 // Given a filename like foo/bar/baz.proto, returns the root directory
64 // path ../../
GetRootPath(const std::string & from_filename,const std::string & to_filename)65 std::string GetRootPath(const std::string& from_filename,
66 const std::string& to_filename) {
67 if (to_filename.find("google/protobuf") == 0) {
68 // Well-known types (.proto files in the google/protobuf directory) are
69 // assumed to come from the 'google-protobuf' npm package. We may want to
70 // generalize this exception later by letting others put generated code in
71 // their own npm packages.
72 return "google-protobuf/";
73 }
74 size_t slashes = std::count(from_filename.begin(), from_filename.end(), '/');
75 if (slashes == 0) {
76 return "./";
77 }
78 std::string result = "";
79 for (size_t i = 0; i < slashes; i++) {
80 result += "../";
81 }
82 return result;
83 }
84
85 // Return the relative path to load to_file from the directory containing
86 // from_file, assuming that both paths are relative to the same directory
GetRelativePath(const std::string & from_file,const std::string & to_file)87 std::string GetRelativePath(const std::string& from_file,
88 const std::string& to_file) {
89 return GetRootPath(from_file, to_file) + to_file;
90 }
91
92 /* Finds all message types used in all services in the file, and returns them
93 * as a map of fully qualified message type name to message descriptor */
GetAllMessages(const FileDescriptor * file)94 map<std::string, const Descriptor*> GetAllMessages(const FileDescriptor* file) {
95 map<std::string, const Descriptor*> message_types;
96 for (int service_num = 0; service_num < file->service_count();
97 service_num++) {
98 const ServiceDescriptor* service = file->service(service_num);
99 for (int method_num = 0; method_num < service->method_count();
100 method_num++) {
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[std::string(input_type->full_name())] = input_type;
105 message_types[std::string(output_type->full_name())] = output_type;
106 }
107 }
108 return message_types;
109 }
110
MessageIdentifierName(const std::string & name)111 std::string MessageIdentifierName(const std::string& name) {
112 return grpc_generator::StringReplace(name, ".", "_");
113 }
114
NodeObjectPath(const Descriptor * descriptor)115 std::string NodeObjectPath(const Descriptor* descriptor) {
116 std::string module_alias =
117 ModuleAlias(std::string(descriptor->file()->name()));
118 std::string name(descriptor->full_name());
119 grpc_generator::StripPrefix(&name,
120 std::string(descriptor->file()->package()) + ".");
121 return module_alias + "." + name;
122 }
123
124 // Prints out the message serializer and deserializer functions
PrintMessageTransformer(const Descriptor * descriptor,Printer * out,const Parameters & params)125 void PrintMessageTransformer(const Descriptor* descriptor, Printer* out,
126 const Parameters& params) {
127 map<std::string, std::string> template_vars;
128 std::string full_name(descriptor->full_name());
129 template_vars["identifier_name"] = MessageIdentifierName(full_name);
130 template_vars["name"] = full_name;
131 template_vars["node_name"] = NodeObjectPath(descriptor);
132 // Print the serializer
133 out->Print(template_vars, "function serialize_$identifier_name$(arg) {\n");
134 out->Indent();
135 out->Print(template_vars, "if (!(arg instanceof $node_name$)) {\n");
136 out->Indent();
137 out->Print(template_vars,
138 "throw new Error('Expected argument of type $name$');\n");
139 out->Outdent();
140 out->Print("}\n");
141 if (params.minimum_node_version > 5) {
142 // Node version is > 5, we should use Buffer.from
143 out->Print("return Buffer.from(arg.serializeBinary());\n");
144 } else {
145 out->Print("return new Buffer(arg.serializeBinary());\n");
146 }
147 out->Outdent();
148 out->Print("}\n\n");
149
150 // Print the deserializer
151 out->Print(template_vars,
152 "function deserialize_$identifier_name$(buffer_arg) {\n");
153 out->Indent();
154 out->Print(
155 template_vars,
156 "return $node_name$.deserializeBinary(new Uint8Array(buffer_arg));\n");
157 out->Outdent();
158 out->Print("}\n\n");
159 }
160
PrintMethod(const MethodDescriptor * method,Printer * out)161 void PrintMethod(const MethodDescriptor* method, Printer* out) {
162 const Descriptor* input_type = method->input_type();
163 const Descriptor* output_type = method->output_type();
164 map<std::string, std::string> vars;
165 vars["service_name"] = method->service()->full_name();
166 vars["name"] = method->name();
167 vars["input_type"] = NodeObjectPath(input_type);
168 vars["input_type_id"] =
169 MessageIdentifierName(std::string(input_type->full_name()));
170 vars["output_type"] = NodeObjectPath(output_type);
171 vars["output_type_id"] =
172 MessageIdentifierName(std::string(output_type->full_name()));
173 vars["client_stream"] = method->client_streaming() ? "true" : "false";
174 vars["server_stream"] = method->server_streaming() ? "true" : "false";
175 out->Print("{\n");
176 out->Indent();
177 out->Print(vars, "path: '/$service_name$/$name$',\n");
178 out->Print(vars, "requestStream: $client_stream$,\n");
179 out->Print(vars, "responseStream: $server_stream$,\n");
180 out->Print(vars, "requestType: $input_type$,\n");
181 out->Print(vars, "responseType: $output_type$,\n");
182 out->Print(vars, "requestSerialize: serialize_$input_type_id$,\n");
183 out->Print(vars, "requestDeserialize: deserialize_$input_type_id$,\n");
184 out->Print(vars, "responseSerialize: serialize_$output_type_id$,\n");
185 out->Print(vars, "responseDeserialize: deserialize_$output_type_id$,\n");
186 out->Outdent();
187 out->Print("}");
188 }
189
190 // Prints out the service descriptor object
PrintService(const ServiceDescriptor * service,Printer * out)191 void PrintService(const ServiceDescriptor* service, Printer* out) {
192 map<std::string, std::string> template_vars;
193 out->Print(GetNodeComments(service, true).c_str());
194 template_vars["name"] = service->name();
195 out->Print(template_vars, "var $name$Service = exports.$name$Service = {\n");
196 out->Indent();
197 for (int i = 0; i < service->method_count(); i++) {
198 std::string method_name = grpc_generator::LowercaseFirstLetter(
199 std::string(service->method(i)->name()));
200 out->Print(GetNodeComments(service->method(i), true).c_str());
201 out->Print("$method_name$: ", "method_name", method_name);
202 PrintMethod(service->method(i), out);
203 out->Print(",\n");
204 out->Print(GetNodeComments(service->method(i), false).c_str());
205 }
206 out->Outdent();
207 out->Print("};\n\n");
208 out->Print(template_vars,
209 "exports.$name$Client = "
210 "grpc.makeGenericClientConstructor($name$Service);\n");
211 out->Print(GetNodeComments(service, false).c_str());
212 }
213
PrintImports(const FileDescriptor * file,Printer * out)214 void PrintImports(const FileDescriptor* file, Printer* out) {
215 out->Print("var grpc = require('grpc');\n");
216 if (file->message_type_count() > 0) {
217 std::string file_path =
218 GetRelativePath(std::string(file->name()),
219 GetJSMessageFilename(std::string(file->name())));
220 out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
221 ModuleAlias(std::string(file->name())), "file_path", file_path);
222 }
223
224 for (int i = 0; i < file->dependency_count(); i++) {
225 std::string file_path = GetRelativePath(
226 std::string(file->name()),
227 GetJSMessageFilename(std::string(file->dependency(i)->name())));
228 out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
229 ModuleAlias(std::string(file->dependency(i)->name())),
230 "file_path", file_path);
231 }
232 out->Print("\n");
233 }
234
PrintTransformers(const FileDescriptor * file,Printer * out,const Parameters & params)235 void PrintTransformers(const FileDescriptor* file, Printer* out,
236 const Parameters& params) {
237 map<std::string, const Descriptor*> messages = GetAllMessages(file);
238 for (std::map<std::string, const Descriptor*>::iterator it = messages.begin();
239 it != messages.end(); it++) {
240 PrintMessageTransformer(it->second, out, params);
241 }
242 out->Print("\n");
243 }
244
PrintServices(const FileDescriptor * file,Printer * out)245 void PrintServices(const FileDescriptor* file, Printer* out) {
246 for (int i = 0; i < file->service_count(); i++) {
247 PrintService(file->service(i), out);
248 }
249 }
250 } // namespace
251
GenerateFile(const FileDescriptor * file,const Parameters & params)252 std::string GenerateFile(const FileDescriptor* file, const Parameters& params) {
253 std::string output;
254 {
255 StringOutputStream output_stream(&output);
256 Printer out(&output_stream, '$');
257
258 if (file->service_count() == 0) {
259 return output;
260 }
261 out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");
262
263 std::string leading_comments = GetNodeComments(file, true);
264 if (!leading_comments.empty()) {
265 out.Print("// Original file comments:\n");
266 out.PrintRaw(leading_comments.c_str());
267 }
268
269 out.Print("'use strict';\n");
270
271 PrintImports(file, &out);
272
273 PrintTransformers(file, &out, params);
274
275 PrintServices(file, &out);
276
277 out.Print(GetNodeComments(file, false).c_str());
278 }
279 return output;
280 }
281
282 } // namespace grpc_node_generator
283