• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file or at
6 // https://developers.google.com/open-source/licenses/bsd
7 
8 #include "google/protobuf/compiler/csharp/csharp_field_base.h"
9 
10 #include <cmath>
11 #include <limits>
12 #include <sstream>
13 #include <string>
14 
15 #include "google/protobuf/compiler/code_generator.h"
16 #include "absl/log/absl_log.h"
17 #include "google/protobuf/compiler/csharp/csharp_helpers.h"
18 #include "google/protobuf/compiler/csharp/names.h"
19 #include "google/protobuf/descriptor.h"
20 #include "google/protobuf/descriptor.pb.h"
21 #include "google/protobuf/io/coded_stream.h"
22 #include "google/protobuf/io/printer.h"
23 #include "google/protobuf/wire_format.h"
24 
25 // Must be last.
26 #include "google/protobuf/port_def.inc"
27 
28 namespace google {
29 namespace protobuf {
30 namespace compiler {
31 namespace csharp {
32 
SetCommonFieldVariables(absl::flat_hash_map<absl::string_view,std::string> * variables)33 void FieldGeneratorBase::SetCommonFieldVariables(
34     absl::flat_hash_map<absl::string_view, std::string>* variables) {
35   // Note: this will be valid even though the tag emitted for packed and unpacked versions of
36   // repeated fields varies by wire format. The wire format is encoded in the bottom 3 bits, which
37   // never effects the tag size.
38   int tag_size = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type());
39   int part_tag_size = tag_size;
40   if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) {
41     part_tag_size /= 2;
42   }
43   uint tag = internal::WireFormat::MakeTag(descriptor_);
44   uint8_t tag_array[5];
45   io::CodedOutputStream::WriteTagToArray(tag, tag_array);
46   std::string tag_bytes = absl::StrCat(tag_array[0]);
47   for (int i = 1; i < part_tag_size; i++) {
48     absl::StrAppend(&tag_bytes, ", ", tag_array[i]);
49   }
50 
51   (*variables)["tag"] = absl::StrCat(tag);
52   (*variables)["tag_size"] = absl::StrCat(tag_size);
53   (*variables)["tag_bytes"] = tag_bytes;
54 
55   if (descriptor_->type() == FieldDescriptor::Type::TYPE_GROUP) {
56     tag = internal::WireFormatLite::MakeTag(
57         descriptor_->number(),
58         internal::WireFormatLite::WIRETYPE_END_GROUP);
59     io::CodedOutputStream::WriteTagToArray(tag, tag_array);
60     tag_bytes = absl::StrCat(tag_array[0]);
61     for (int i = 1; i < part_tag_size; i++) {
62       absl::StrAppend(&tag_bytes, ", ", tag_array[i]);
63     }
64 
65     variables_["end_tag"] = absl::StrCat(tag);
66     variables_["end_tag_bytes"] = tag_bytes;
67   }
68 
69   (*variables)["access_level"] = "public";
70 
71   (*variables)["property_name"] = property_name();
72   (*variables)["type_name"] = type_name();
73   (*variables)["extended_type"] = GetClassName(descriptor_->containing_type());
74   (*variables)["name"] = name();
75   (*variables)["descriptor_name"] = descriptor_->name();
76   (*variables)["default_value"] = default_value();
77   (*variables)["capitalized_type_name"] = capitalized_type_name();
78   (*variables)["number"] = number();
79   if (has_default_value() && !SupportsPresenceApi(descriptor_)) {
80     variables->insert({"name_def_message",
81                        absl::StrCat((*variables)["name"],
82                                     "_ = ", (*variables)["default_value"])});
83   } else {
84     variables->insert(
85         {"name_def_message", absl::StrCat((*variables)["name"], "_")});
86   }
87   if (SupportsPresenceApi(descriptor_)) {
88     variables->insert({"has_property_check",
89                        absl::StrCat("Has", (*variables)["property_name"])});
90     variables->insert(
91         {"other_has_property_check",
92          absl::StrCat("other.Has", (*variables)["property_name"])});
93     variables->insert({"has_not_property_check",
94                        absl::StrCat("!", (*variables)["has_property_check"])});
95     variables->insert(
96         {"other_has_not_property_check",
97          absl::StrCat("!", (*variables)["other_has_property_check"])});
98     if (presenceIndex_ != -1) {
99         const int hasBitsNumber = presenceIndex_ / 32;
100         const int hasBitsMask = 1 << (presenceIndex_ % 32);
101         (*variables)["has_field_check"] = absl::StrCat(
102             "(_hasBits", hasBitsNumber, " & ", hasBitsMask, ") != 0");
103         (*variables)["set_has_field"] =
104             absl::StrCat("_hasBits", hasBitsNumber, " |= ", hasBitsMask);
105         (*variables)["clear_has_field"] =
106             absl::StrCat("_hasBits", hasBitsNumber, " &= ~", hasBitsMask);
107     }
108   } else {
109     variables->insert({"has_property_check",
110                        absl::StrCat((*variables)["property_name"],
111                                     " != ", (*variables)["default_value"])});
112     variables->insert({"other_has_property_check",
113                        absl::StrCat("other.", (*variables)["property_name"],
114                                     " != ", (*variables)["default_value"])});
115   }
116 }
117 
SetCommonOneofFieldVariables(absl::flat_hash_map<absl::string_view,std::string> * variables)118 void FieldGeneratorBase::SetCommonOneofFieldVariables(
119     absl::flat_hash_map<absl::string_view, std::string>* variables) {
120   (*variables)["oneof_name"] = oneof_name();
121   if (SupportsPresenceApi(descriptor_)) {
122     (*variables)["has_property_check"] = absl::StrCat("Has", property_name());
123   } else {
124     (*variables)["has_property_check"] =
125         absl::StrCat(oneof_name(), "Case_ == ", oneof_property_name(),
126                      "OneofCase.", oneof_case_name());
127   }
128   (*variables)["oneof_case_name"] = oneof_case_name();
129   (*variables)["oneof_property_name"] = oneof_property_name();
130 }
131 
FieldGeneratorBase(const FieldDescriptor * descriptor,int presenceIndex,const Options * options)132 FieldGeneratorBase::FieldGeneratorBase(const FieldDescriptor* descriptor,
133                                        int presenceIndex, const Options* options)
134     : SourceGeneratorBase(options),
135       descriptor_(descriptor),
136       presenceIndex_(presenceIndex) {
137   SetCommonFieldVariables(&variables_);
138 }
139 
~FieldGeneratorBase()140 FieldGeneratorBase::~FieldGeneratorBase() {
141 }
142 
GenerateFreezingCode(io::Printer * printer)143 void FieldGeneratorBase::GenerateFreezingCode(io::Printer* printer) {
144   // No-op: only message fields and repeated fields need
145   // special handling for freezing, so default to not generating any code.
146 }
147 
GenerateCodecCode(io::Printer * printer)148 void FieldGeneratorBase::GenerateCodecCode(io::Printer* printer) {
149     // No-op: expect this to be overridden by appropriate types.
150     // Could fail if we get called here though...
151 }
152 
GenerateExtensionCode(io::Printer * printer)153 void FieldGeneratorBase::GenerateExtensionCode(io::Printer* printer) {
154   // No-op: only message fields, enum fields, primitives,
155   // and repeated fields need this default is to not generate any code
156 }
157 
GenerateParsingCode(io::Printer * printer,bool use_parse_context)158 void FieldGeneratorBase::GenerateParsingCode(io::Printer* printer, bool use_parse_context) {
159   // for some field types the value of "use_parse_context" doesn't matter,
160   // so we fallback to the default implementation.
161   GenerateParsingCode(printer);
162 }
163 
GenerateSerializationCode(io::Printer * printer,bool use_write_context)164 void FieldGeneratorBase::GenerateSerializationCode(io::Printer* printer, bool use_write_context) {
165   // for some field types the value of "use_write_context" doesn't matter,
166   // so we fallback to the default implementation.
167   GenerateSerializationCode(printer);
168 }
169 
AddDeprecatedFlag(io::Printer * printer)170 void FieldGeneratorBase::AddDeprecatedFlag(io::Printer* printer) {
171   if (descriptor_->options().deprecated()) {
172     printer->Print("[global::System.ObsoleteAttribute]\n");
173   } else if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE &&
174            descriptor_->message_type()->options().deprecated()) {
175     printer->Print("[global::System.ObsoleteAttribute]\n");
176   }
177 }
178 
AddPublicMemberAttributes(io::Printer * printer)179 void FieldGeneratorBase::AddPublicMemberAttributes(io::Printer* printer) {
180   AddDeprecatedFlag(printer);
181   WriteGeneratedCodeAttributes(printer);
182 }
183 
oneof_case_name()184 std::string FieldGeneratorBase::oneof_case_name() {
185   return GetOneofCaseName(descriptor_);
186 }
187 
oneof_property_name()188 std::string FieldGeneratorBase::oneof_property_name() {
189   return UnderscoresToCamelCase(descriptor_->containing_oneof()->name(), true);
190 }
191 
oneof_name()192 std::string FieldGeneratorBase::oneof_name() {
193   return UnderscoresToCamelCase(descriptor_->containing_oneof()->name(), false);
194 }
195 
property_name()196 std::string FieldGeneratorBase::property_name() {
197   return GetPropertyName(descriptor_);
198 }
199 
name()200 std::string FieldGeneratorBase::name() {
201   return UnderscoresToCamelCase(GetFieldName(descriptor_), false);
202 }
203 
type_name()204 std::string FieldGeneratorBase::type_name() {
205   return type_name(descriptor_);
206 }
207 
type_name(const FieldDescriptor * descriptor)208 std::string FieldGeneratorBase::type_name(const FieldDescriptor* descriptor) {
209   switch (descriptor->type()) {
210     case FieldDescriptor::TYPE_ENUM:
211       return GetClassName(descriptor->enum_type());
212     case FieldDescriptor::TYPE_MESSAGE:
213     case FieldDescriptor::TYPE_GROUP:
214       if (IsWrapperType(descriptor)) {
215         const FieldDescriptor* wrapped_field =
216             descriptor->message_type()->field(0);
217         std::string wrapped_field_type_name = type_name(wrapped_field);
218         // String and ByteString go to the same type; other wrapped types
219         // go to the nullable equivalent.
220         if (wrapped_field->type() == FieldDescriptor::TYPE_STRING ||
221             wrapped_field->type() == FieldDescriptor::TYPE_BYTES) {
222           return wrapped_field_type_name;
223         } else {
224           return absl::StrCat(wrapped_field_type_name, "?");
225         }
226       }
227       return GetClassName(descriptor->message_type());
228     case FieldDescriptor::TYPE_DOUBLE:
229       return "double";
230     case FieldDescriptor::TYPE_FLOAT:
231       return "float";
232     case FieldDescriptor::TYPE_INT64:
233       return "long";
234     case FieldDescriptor::TYPE_UINT64:
235       return "ulong";
236     case FieldDescriptor::TYPE_INT32:
237       return "int";
238     case FieldDescriptor::TYPE_FIXED64:
239       return "ulong";
240     case FieldDescriptor::TYPE_FIXED32:
241       return "uint";
242     case FieldDescriptor::TYPE_BOOL:
243       return "bool";
244     case FieldDescriptor::TYPE_STRING:
245       return "string";
246     case FieldDescriptor::TYPE_BYTES:
247       return "pb::ByteString";
248     case FieldDescriptor::TYPE_UINT32:
249       return "uint";
250     case FieldDescriptor::TYPE_SFIXED32:
251       return "int";
252     case FieldDescriptor::TYPE_SFIXED64:
253       return "long";
254     case FieldDescriptor::TYPE_SINT32:
255       return "int";
256     case FieldDescriptor::TYPE_SINT64:
257       return "long";
258     default:
259       ABSL_LOG(FATAL) << "Unknown field type.";
260       return "";
261   }
262 }
263 
has_default_value()264 bool FieldGeneratorBase::has_default_value() {
265   switch (descriptor_->type()) {
266     case FieldDescriptor::TYPE_ENUM:
267     case FieldDescriptor::TYPE_MESSAGE:
268     case FieldDescriptor::TYPE_GROUP:
269       return true;
270     case FieldDescriptor::TYPE_DOUBLE:
271       return descriptor_->default_value_double() != 0.0;
272     case FieldDescriptor::TYPE_FLOAT:
273       return descriptor_->default_value_float() != 0.0;
274     case FieldDescriptor::TYPE_INT64:
275       return descriptor_->default_value_int64() != 0L;
276     case FieldDescriptor::TYPE_UINT64:
277       return descriptor_->default_value_uint64() != 0L;
278     case FieldDescriptor::TYPE_INT32:
279       return descriptor_->default_value_int32() != 0;
280     case FieldDescriptor::TYPE_FIXED64:
281       return descriptor_->default_value_uint64() != 0L;
282     case FieldDescriptor::TYPE_FIXED32:
283       return descriptor_->default_value_uint32() != 0;
284     case FieldDescriptor::TYPE_BOOL:
285       return descriptor_->default_value_bool();
286     case FieldDescriptor::TYPE_STRING:
287       return true;
288     case FieldDescriptor::TYPE_BYTES:
289       return true;
290     case FieldDescriptor::TYPE_UINT32:
291       return descriptor_->default_value_uint32() != 0;
292     case FieldDescriptor::TYPE_SFIXED32:
293       return descriptor_->default_value_int32() != 0;
294     case FieldDescriptor::TYPE_SFIXED64:
295       return descriptor_->default_value_int64() != 0L;
296     case FieldDescriptor::TYPE_SINT32:
297       return descriptor_->default_value_int32() != 0;
298     case FieldDescriptor::TYPE_SINT64:
299       return descriptor_->default_value_int64() != 0L;
300     default:
301       ABSL_LOG(FATAL) << "Unknown field type.";
302       return true;
303   }
304 }
305 
AllPrintableAscii(absl::string_view text)306 bool AllPrintableAscii(absl::string_view text) {
307   for(int i = 0; i < text.size(); i++) {
308     if (text[i] < 0x20 || text[i] > 0x7e) {
309       return false;
310     }
311   }
312   return true;
313 }
314 
GetStringDefaultValueInternal(const FieldDescriptor * descriptor)315 std::string FieldGeneratorBase::GetStringDefaultValueInternal(const FieldDescriptor* descriptor) {
316     if (descriptor->default_value_string().empty())
317         return "\"\"";
318     return absl::StrCat(
319         "global::System.Text.Encoding.UTF8.GetString(global::System."
320         "Convert.FromBase64String(\"",
321         StringToBase64(descriptor->default_value_string()), "\"), 0, ",
322         descriptor->default_value_string().length(), ")");
323 }
324 
GetBytesDefaultValueInternal(const FieldDescriptor * descriptor)325 std::string FieldGeneratorBase::GetBytesDefaultValueInternal(const FieldDescriptor* descriptor) {
326     if (descriptor->default_value_string().empty())
327         return "pb::ByteString.Empty";
328     return absl::StrCat("pb::ByteString.FromBase64(\"",
329                         StringToBase64(descriptor->default_value_string()),
330                         "\")");
331 }
332 
default_value()333 std::string FieldGeneratorBase::default_value() {
334     return default_value(descriptor_);
335 }
336 
default_value(const FieldDescriptor * descriptor)337 std::string FieldGeneratorBase::default_value(const FieldDescriptor* descriptor) {
338   switch (descriptor->type()) {
339     case FieldDescriptor::TYPE_ENUM:
340       return absl::StrCat(
341           GetClassName(descriptor->default_value_enum()->type()), ".",
342           GetEnumValueName(descriptor->default_value_enum()->type()->name(),
343                            descriptor->default_value_enum()->name()));
344     case FieldDescriptor::TYPE_MESSAGE:
345     case FieldDescriptor::TYPE_GROUP:
346       if (IsWrapperType(descriptor)) {
347         const FieldDescriptor* wrapped_field = descriptor->message_type()->field(0);
348         return default_value(wrapped_field);
349       } else {
350         return "null";
351       }
352     case FieldDescriptor::TYPE_DOUBLE: {
353       double value = descriptor->default_value_double();
354       if (value == std::numeric_limits<double>::infinity()) {
355         return "double.PositiveInfinity";
356       } else if (value == -std::numeric_limits<double>::infinity()) {
357         return "double.NegativeInfinity";
358       } else if (std::isnan(value)) {
359         return "double.NaN";
360       }
361       return absl::StrCat(value, "D");
362     }
363     case FieldDescriptor::TYPE_FLOAT: {
364       float value = descriptor->default_value_float();
365       if (value == std::numeric_limits<float>::infinity()) {
366         return "float.PositiveInfinity";
367       } else if (value == -std::numeric_limits<float>::infinity()) {
368         return "float.NegativeInfinity";
369       } else if (std::isnan(value)) {
370         return "float.NaN";
371       }
372       return absl::StrCat(value, "F");
373     }
374     case FieldDescriptor::TYPE_INT64:
375       return absl::StrCat(descriptor->default_value_int64(), "L");
376     case FieldDescriptor::TYPE_UINT64:
377       return absl::StrCat(descriptor->default_value_uint64(), "UL");
378     case FieldDescriptor::TYPE_INT32:
379       return absl::StrCat(descriptor->default_value_int32());
380     case FieldDescriptor::TYPE_FIXED64:
381       return absl::StrCat(descriptor->default_value_uint64(), "UL");
382     case FieldDescriptor::TYPE_FIXED32:
383       return absl::StrCat(descriptor->default_value_uint32());
384     case FieldDescriptor::TYPE_BOOL:
385       if (descriptor->default_value_bool()) {
386         return "true";
387       } else {
388         return "false";
389       }
390     case FieldDescriptor::TYPE_STRING:
391       return GetStringDefaultValueInternal(descriptor);
392     case FieldDescriptor::TYPE_BYTES:
393       return GetBytesDefaultValueInternal(descriptor);
394     case FieldDescriptor::TYPE_UINT32:
395       return absl::StrCat(descriptor->default_value_uint32());
396     case FieldDescriptor::TYPE_SFIXED32:
397       return absl::StrCat(descriptor->default_value_int32());
398     case FieldDescriptor::TYPE_SFIXED64:
399       return absl::StrCat(descriptor->default_value_int64(), "L");
400     case FieldDescriptor::TYPE_SINT32:
401       return absl::StrCat(descriptor->default_value_int32());
402     case FieldDescriptor::TYPE_SINT64:
403       return absl::StrCat(descriptor->default_value_int64(), "L");
404     default:
405       ABSL_LOG(FATAL) << "Unknown field type.";
406       return "";
407   }
408 }
409 
number()410 std::string FieldGeneratorBase::number() {
411   return absl::StrCat(descriptor_->number());
412 }
413 
capitalized_type_name()414 std::string FieldGeneratorBase::capitalized_type_name() {
415   switch (descriptor_->type()) {
416     case FieldDescriptor::TYPE_ENUM:
417       return "Enum";
418     case FieldDescriptor::TYPE_MESSAGE:
419       return "Message";
420     case FieldDescriptor::TYPE_GROUP:
421       return "Group";
422     case FieldDescriptor::TYPE_DOUBLE:
423       return "Double";
424     case FieldDescriptor::TYPE_FLOAT:
425       return "Float";
426     case FieldDescriptor::TYPE_INT64:
427       return "Int64";
428     case FieldDescriptor::TYPE_UINT64:
429       return "UInt64";
430     case FieldDescriptor::TYPE_INT32:
431       return "Int32";
432     case FieldDescriptor::TYPE_FIXED64:
433       return "Fixed64";
434     case FieldDescriptor::TYPE_FIXED32:
435       return "Fixed32";
436     case FieldDescriptor::TYPE_BOOL:
437       return "Bool";
438     case FieldDescriptor::TYPE_STRING:
439       return "String";
440     case FieldDescriptor::TYPE_BYTES:
441       return "Bytes";
442     case FieldDescriptor::TYPE_UINT32:
443       return "UInt32";
444     case FieldDescriptor::TYPE_SFIXED32:
445       return "SFixed32";
446     case FieldDescriptor::TYPE_SFIXED64:
447       return "SFixed64";
448     case FieldDescriptor::TYPE_SINT32:
449       return "SInt32";
450     case FieldDescriptor::TYPE_SINT64:
451       return "SInt64";
452     default:
453       ABSL_LOG(FATAL) << "Unknown field type.";
454       return "";
455   }
456 }
457 
458 }  // namespace csharp
459 }  // namespace compiler
460 }  // namespace protobuf
461 }  // namespace google
462 
463 #include "google/protobuf/port_undef.inc"
464