1 /*
2  *
3  * Copyright 2015 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 <cctype>
20 #include <map>
21 #include <vector>
22 
23 #include "src/compiler/config.h"
24 #include "src/compiler/ruby_generator.h"
25 #include "src/compiler/ruby_generator_helpers-inl.h"
26 #include "src/compiler/ruby_generator_map-inl.h"
27 #include "src/compiler/ruby_generator_string-inl.h"
28 
29 using grpc::protobuf::FileDescriptor;
30 using grpc::protobuf::MethodDescriptor;
31 using grpc::protobuf::ServiceDescriptor;
32 using grpc::protobuf::io::Printer;
33 using grpc::protobuf::io::StringOutputStream;
34 using std::map;
35 using std::vector;
36 
37 namespace grpc_ruby_generator {
38 namespace {
39 
40 // Prints out the method using the ruby gRPC DSL.
PrintMethod(const MethodDescriptor * method,const grpc::string & package,Printer * out)41 void PrintMethod(const MethodDescriptor* method, const grpc::string& package,
42                  Printer* out) {
43   grpc::string input_type =
44       RubyTypeOf(method->input_type()->full_name(), package);
45   if (method->client_streaming()) {
46     input_type = "stream(" + input_type + ")";
47   }
48   grpc::string output_type =
49       RubyTypeOf(method->output_type()->full_name(), package);
50   if (method->server_streaming()) {
51     output_type = "stream(" + output_type + ")";
52   }
53   std::map<grpc::string, grpc::string> method_vars = ListToDict({
54       "mth.name",
55       method->name(),
56       "input.type",
57       input_type,
58       "output.type",
59       output_type,
60   });
61   out->Print(GetRubyComments(method, true).c_str());
62   out->Print(method_vars, "rpc :$mth.name$, $input.type$, $output.type$\n");
63   out->Print(GetRubyComments(method, false).c_str());
64 }
65 
66 // Prints out the service using the ruby gRPC DSL.
PrintService(const ServiceDescriptor * service,const grpc::string & package,Printer * out)67 void PrintService(const ServiceDescriptor* service, const grpc::string& package,
68                   Printer* out) {
69   if (service->method_count() == 0) {
70     return;
71   }
72 
73   // Begin the service module
74   std::map<grpc::string, grpc::string> module_vars = ListToDict({
75       "module.name",
76       Modularize(service->name()),
77   });
78   out->Print(module_vars, "module $module.name$\n");
79   out->Indent();
80 
81   out->Print(GetRubyComments(service, true).c_str());
82   out->Print("class Service\n");
83 
84   // Write the indented class body.
85   out->Indent();
86   out->Print("\n");
87   out->Print("include GRPC::GenericService\n");
88   out->Print("\n");
89   out->Print("self.marshal_class_method = :encode\n");
90   out->Print("self.unmarshal_class_method = :decode\n");
91   std::map<grpc::string, grpc::string> pkg_vars =
92       ListToDict({"service_full_name", service->full_name()});
93   out->Print(pkg_vars, "self.service_name = '$service_full_name$'\n");
94   out->Print("\n");
95   for (int i = 0; i < service->method_count(); ++i) {
96     PrintMethod(service->method(i), package, out);
97   }
98   out->Outdent();
99 
100   out->Print("end\n");
101   out->Print("\n");
102   out->Print("Stub = Service.rpc_stub_class\n");
103 
104   // End the service module
105   out->Outdent();
106   out->Print("end\n");
107   out->Print(GetRubyComments(service, false).c_str());
108 }
109 
110 }  // namespace
111 
112 // The following functions are copied directly from the source for the protoc
113 // ruby generator
114 // to ensure compatibility (with the exception of int and string type changes).
115 // See
116 // https://github.com/google/protobuf/blob/master/src/google/protobuf/compiler/ruby/ruby_generator.cc#L250
117 // TODO: keep up to date with protoc code generation, though this behavior isn't
118 // expected to change
IsLower(char ch)119 bool IsLower(char ch) { return ch >= 'a' && ch <= 'z'; }
120 
ToUpper(char ch)121 char ToUpper(char ch) { return IsLower(ch) ? (ch - 'a' + 'A') : ch; }
122 
123 // Package names in protobuf are snake_case by convention, but Ruby module
124 // names must be PascalCased.
125 //
126 //   foo_bar_baz -> FooBarBaz
PackageToModule(const grpc::string & name)127 grpc::string PackageToModule(const grpc::string& name) {
128   bool next_upper = true;
129   grpc::string result;
130   result.reserve(name.size());
131 
132   for (grpc::string::size_type i = 0; i < name.size(); i++) {
133     if (name[i] == '_') {
134       next_upper = true;
135     } else {
136       if (next_upper) {
137         result.push_back(ToUpper(name[i]));
138       } else {
139         result.push_back(name[i]);
140       }
141       next_upper = false;
142     }
143   }
144 
145   return result;
146 }
147 // end copying of protoc generator for ruby code
148 
GetServices(const FileDescriptor * file)149 grpc::string GetServices(const FileDescriptor* file) {
150   grpc::string output;
151   {
152     // Scope the output stream so it closes and finalizes output to the string.
153 
154     StringOutputStream output_stream(&output);
155     Printer out(&output_stream, '$');
156 
157     // Don't write out any output if there no services, to avoid empty service
158     // files being generated for proto files that don't declare any.
159     if (file->service_count() == 0) {
160       return output;
161     }
162 
163     std::string package_name;
164 
165     if (file->options().has_ruby_package()) {
166       package_name = file->options().ruby_package();
167     } else {
168       package_name = file->package();
169     }
170 
171     // Write out a file header.
172     std::map<grpc::string, grpc::string> header_comment_vars = ListToDict({
173         "file.name",
174         file->name(),
175         "file.package",
176         package_name,
177     });
178     out.Print("# Generated by the protocol buffer compiler.  DO NOT EDIT!\n");
179     out.Print(header_comment_vars,
180               "# Source: $file.name$ for package '$file.package$'\n");
181 
182     grpc::string leading_comments = GetRubyComments(file, true);
183     if (!leading_comments.empty()) {
184       out.Print("# Original file comments:\n");
185       out.PrintRaw(leading_comments.c_str());
186     }
187 
188     out.Print("\n");
189     out.Print("require 'grpc'\n");
190     // Write out require statemment to import the separately generated file
191     // that defines the messages used by the service. This is generated by the
192     // main ruby plugin.
193     std::map<grpc::string, grpc::string> dep_vars = ListToDict({
194         "dep.name",
195         MessagesRequireName(file),
196     });
197     out.Print(dep_vars, "require '$dep.name$'\n");
198 
199     // Write out services within the modules
200     out.Print("\n");
201     std::vector<grpc::string> modules = Split(package_name, '.');
202     for (size_t i = 0; i < modules.size(); ++i) {
203       std::map<grpc::string, grpc::string> module_vars = ListToDict({
204           "module.name",
205           PackageToModule(modules[i]),
206       });
207       out.Print(module_vars, "module $module.name$\n");
208       out.Indent();
209     }
210     for (int i = 0; i < file->service_count(); ++i) {
211       auto service = file->service(i);
212       PrintService(service, file->package(), &out);
213     }
214     for (size_t i = 0; i < modules.size(); ++i) {
215       out.Outdent();
216       out.Print("end\n");
217     }
218 
219     out.Print(GetRubyComments(file, false).c_str());
220   }
221   return output;
222 }
223 
224 }  // namespace grpc_ruby_generator
225