node_generator.cc 9.8 KB

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