诸暨麻将添加redis
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

2512 satır
90 KiB

  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // Author: jschorr@google.com (Joseph Schorr)
  31. // Based on original Protocol Buffers design by
  32. // Sanjay Ghemawat, Jeff Dean, and others.
  33. #include <google/protobuf/text_format.h>
  34. #include <float.h>
  35. #include <math.h>
  36. #include <stdio.h>
  37. #include <algorithm>
  38. #include <climits>
  39. #include <limits>
  40. #include <vector>
  41. #include <google/protobuf/stubs/stringprintf.h>
  42. #include <google/protobuf/any.h>
  43. #include <google/protobuf/descriptor.pb.h>
  44. #include <google/protobuf/io/coded_stream.h>
  45. #include <google/protobuf/io/tokenizer.h>
  46. #include <google/protobuf/io/zero_copy_stream.h>
  47. #include <google/protobuf/io/zero_copy_stream_impl.h>
  48. #include <google/protobuf/descriptor.h>
  49. #include <google/protobuf/dynamic_message.h>
  50. #include <google/protobuf/map_field.h>
  51. #include <google/protobuf/message.h>
  52. #include <google/protobuf/port_def.inc>
  53. #include <google/protobuf/repeated_field.h>
  54. #include <google/protobuf/unknown_field_set.h>
  55. #include <google/protobuf/wire_format_lite.h>
  56. #include <google/protobuf/stubs/strutil.h>
  57. #include <google/protobuf/io/strtod.h>
  58. #include <google/protobuf/stubs/map_util.h>
  59. #include <google/protobuf/stubs/stl_util.h>
  60. namespace google {
  61. namespace protobuf {
  62. namespace {
  63. inline bool IsHexNumber(const std::string& str) {
  64. return (str.length() >= 2 && str[0] == '0' &&
  65. (str[1] == 'x' || str[1] == 'X'));
  66. }
  67. inline bool IsOctNumber(const std::string& str) {
  68. return (str.length() >= 2 && str[0] == '0' &&
  69. (str[1] >= '0' && str[1] < '8'));
  70. }
  71. } // namespace
  72. std::string Message::DebugString() const {
  73. std::string debug_string;
  74. TextFormat::Printer printer;
  75. printer.SetExpandAny(true);
  76. printer.PrintToString(*this, &debug_string);
  77. return debug_string;
  78. }
  79. std::string Message::ShortDebugString() const {
  80. std::string debug_string;
  81. TextFormat::Printer printer;
  82. printer.SetSingleLineMode(true);
  83. printer.SetExpandAny(true);
  84. printer.PrintToString(*this, &debug_string);
  85. // Single line mode currently might have an extra space at the end.
  86. if (debug_string.size() > 0 && debug_string[debug_string.size() - 1] == ' ') {
  87. debug_string.resize(debug_string.size() - 1);
  88. }
  89. return debug_string;
  90. }
  91. std::string Message::Utf8DebugString() const {
  92. std::string debug_string;
  93. TextFormat::Printer printer;
  94. printer.SetUseUtf8StringEscaping(true);
  95. printer.SetExpandAny(true);
  96. printer.PrintToString(*this, &debug_string);
  97. return debug_string;
  98. }
  99. void Message::PrintDebugString() const { printf("%s", DebugString().c_str()); }
  100. // ===========================================================================
  101. // Implementation of the parse information tree class.
  102. void TextFormat::ParseInfoTree::RecordLocation(
  103. const FieldDescriptor* field, TextFormat::ParseLocation location) {
  104. locations_[field].push_back(location);
  105. }
  106. TextFormat::ParseInfoTree* TextFormat::ParseInfoTree::CreateNested(
  107. const FieldDescriptor* field) {
  108. // Owned by us in the map.
  109. auto& vec = nested_[field];
  110. vec.emplace_back(new TextFormat::ParseInfoTree());
  111. return vec.back().get();
  112. }
  113. void CheckFieldIndex(const FieldDescriptor* field, int index) {
  114. if (field == nullptr) {
  115. return;
  116. }
  117. if (field->is_repeated() && index == -1) {
  118. GOOGLE_LOG(DFATAL) << "Index must be in range of repeated field values. "
  119. << "Field: " << field->name();
  120. } else if (!field->is_repeated() && index != -1) {
  121. GOOGLE_LOG(DFATAL) << "Index must be -1 for singular fields."
  122. << "Field: " << field->name();
  123. }
  124. }
  125. TextFormat::ParseLocation TextFormat::ParseInfoTree::GetLocation(
  126. const FieldDescriptor* field, int index) const {
  127. CheckFieldIndex(field, index);
  128. if (index == -1) {
  129. index = 0;
  130. }
  131. const std::vector<TextFormat::ParseLocation>* locations =
  132. FindOrNull(locations_, field);
  133. if (locations == nullptr || index >= locations->size()) {
  134. return TextFormat::ParseLocation();
  135. }
  136. return (*locations)[index];
  137. }
  138. TextFormat::ParseInfoTree* TextFormat::ParseInfoTree::GetTreeForNested(
  139. const FieldDescriptor* field, int index) const {
  140. CheckFieldIndex(field, index);
  141. if (index == -1) {
  142. index = 0;
  143. }
  144. auto it = nested_.find(field);
  145. if (it == nested_.end() || index >= it->second.size()) {
  146. return nullptr;
  147. }
  148. return it->second[index].get();
  149. }
  150. namespace {
  151. // These functions implement the behavior of the "default" TextFormat::Finder,
  152. // they are defined as standalone to be called when finder_ is nullptr.
  153. const FieldDescriptor* DefaultFinderFindExtension(Message* message,
  154. const std::string& name) {
  155. const Descriptor* descriptor = message->GetDescriptor();
  156. return descriptor->file()->pool()->FindExtensionByPrintableName(descriptor,
  157. name);
  158. }
  159. const FieldDescriptor* DefaultFinderFindExtensionByNumber(
  160. const Descriptor* descriptor, int number) {
  161. return descriptor->file()->pool()->FindExtensionByNumber(descriptor, number);
  162. }
  163. const Descriptor* DefaultFinderFindAnyType(const Message& message,
  164. const std::string& prefix,
  165. const std::string& name) {
  166. if (prefix != internal::kTypeGoogleApisComPrefix &&
  167. prefix != internal::kTypeGoogleProdComPrefix) {
  168. return nullptr;
  169. }
  170. return message.GetDescriptor()->file()->pool()->FindMessageTypeByName(name);
  171. }
  172. } // namespace
  173. // ===========================================================================
  174. // Internal class for parsing an ASCII representation of a Protocol Message.
  175. // This class makes use of the Protocol Message compiler's tokenizer found
  176. // in //net/proto2/io/public/tokenizer.h. Note that class's Parse
  177. // method is *not* thread-safe and should only be used in a single thread at
  178. // a time.
  179. // Makes code slightly more readable. The meaning of "DO(foo)" is
  180. // "Execute foo and fail if it fails.", where failure is indicated by
  181. // returning false. Borrowed from parser.cc (Thanks Kenton!).
  182. #define DO(STATEMENT) \
  183. if (STATEMENT) { \
  184. } else { \
  185. return false; \
  186. }
  187. class TextFormat::Parser::ParserImpl {
  188. public:
  189. // Determines if repeated values for non-repeated fields and
  190. // oneofs are permitted, e.g., the string "foo: 1 foo: 2" for a
  191. // required/optional field named "foo", or "baz: 1 qux: 2"
  192. // where "baz" and "qux" are members of the same oneof.
  193. enum SingularOverwritePolicy {
  194. ALLOW_SINGULAR_OVERWRITES = 0, // the last value is retained
  195. FORBID_SINGULAR_OVERWRITES = 1, // an error is issued
  196. };
  197. ParserImpl(const Descriptor* root_message_type,
  198. io::ZeroCopyInputStream* input_stream,
  199. io::ErrorCollector* error_collector,
  200. const TextFormat::Finder* finder, ParseInfoTree* parse_info_tree,
  201. SingularOverwritePolicy singular_overwrite_policy,
  202. bool allow_case_insensitive_field, bool allow_unknown_field,
  203. bool allow_unknown_extension, bool allow_unknown_enum,
  204. bool allow_field_number, bool allow_relaxed_whitespace,
  205. bool allow_partial, int recursion_limit)
  206. : error_collector_(error_collector),
  207. finder_(finder),
  208. parse_info_tree_(parse_info_tree),
  209. tokenizer_error_collector_(this),
  210. tokenizer_(input_stream, &tokenizer_error_collector_),
  211. root_message_type_(root_message_type),
  212. singular_overwrite_policy_(singular_overwrite_policy),
  213. allow_case_insensitive_field_(allow_case_insensitive_field),
  214. allow_unknown_field_(allow_unknown_field),
  215. allow_unknown_extension_(allow_unknown_extension),
  216. allow_unknown_enum_(allow_unknown_enum),
  217. allow_field_number_(allow_field_number),
  218. allow_partial_(allow_partial),
  219. recursion_limit_(recursion_limit),
  220. had_errors_(false) {
  221. // For backwards-compatibility with proto1, we need to allow the 'f' suffix
  222. // for floats.
  223. tokenizer_.set_allow_f_after_float(true);
  224. // '#' starts a comment.
  225. tokenizer_.set_comment_style(io::Tokenizer::SH_COMMENT_STYLE);
  226. if (allow_relaxed_whitespace) {
  227. tokenizer_.set_require_space_after_number(false);
  228. tokenizer_.set_allow_multiline_strings(true);
  229. }
  230. // Consume the starting token.
  231. tokenizer_.Next();
  232. }
  233. ~ParserImpl() {}
  234. // Parses the ASCII representation specified in input and saves the
  235. // information into the output pointer (a Message). Returns
  236. // false if an error occurs (an error will also be logged to
  237. // GOOGLE_LOG(ERROR)).
  238. bool Parse(Message* output) {
  239. // Consume fields until we cannot do so anymore.
  240. while (true) {
  241. if (LookingAtType(io::Tokenizer::TYPE_END)) {
  242. return !had_errors_;
  243. }
  244. DO(ConsumeField(output));
  245. }
  246. }
  247. bool ParseField(const FieldDescriptor* field, Message* output) {
  248. bool suc;
  249. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  250. suc = ConsumeFieldMessage(output, output->GetReflection(), field);
  251. } else {
  252. suc = ConsumeFieldValue(output, output->GetReflection(), field);
  253. }
  254. return suc && LookingAtType(io::Tokenizer::TYPE_END);
  255. }
  256. void ReportError(int line, int col, const std::string& message) {
  257. had_errors_ = true;
  258. if (error_collector_ == nullptr) {
  259. if (line >= 0) {
  260. GOOGLE_LOG(ERROR) << "Error parsing text-format "
  261. << root_message_type_->full_name() << ": " << (line + 1)
  262. << ":" << (col + 1) << ": " << message;
  263. } else {
  264. GOOGLE_LOG(ERROR) << "Error parsing text-format "
  265. << root_message_type_->full_name() << ": " << message;
  266. }
  267. } else {
  268. error_collector_->AddError(line, col, message);
  269. }
  270. }
  271. void ReportWarning(int line, int col, const std::string& message) {
  272. if (error_collector_ == nullptr) {
  273. if (line >= 0) {
  274. GOOGLE_LOG(WARNING) << "Warning parsing text-format "
  275. << root_message_type_->full_name() << ": " << (line + 1)
  276. << ":" << (col + 1) << ": " << message;
  277. } else {
  278. GOOGLE_LOG(WARNING) << "Warning parsing text-format "
  279. << root_message_type_->full_name() << ": " << message;
  280. }
  281. } else {
  282. error_collector_->AddWarning(line, col, message);
  283. }
  284. }
  285. private:
  286. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ParserImpl);
  287. // Reports an error with the given message with information indicating
  288. // the position (as derived from the current token).
  289. void ReportError(const std::string& message) {
  290. ReportError(tokenizer_.current().line, tokenizer_.current().column,
  291. message);
  292. }
  293. // Reports a warning with the given message with information indicating
  294. // the position (as derived from the current token).
  295. void ReportWarning(const std::string& message) {
  296. ReportWarning(tokenizer_.current().line, tokenizer_.current().column,
  297. message);
  298. }
  299. // Consumes the specified message with the given starting delimiter.
  300. // This method checks to see that the end delimiter at the conclusion of
  301. // the consumption matches the starting delimiter passed in here.
  302. bool ConsumeMessage(Message* message, const std::string delimiter) {
  303. while (!LookingAt(">") && !LookingAt("}")) {
  304. DO(ConsumeField(message));
  305. }
  306. // Confirm that we have a valid ending delimiter.
  307. DO(Consume(delimiter));
  308. return true;
  309. }
  310. // Consume either "<" or "{".
  311. bool ConsumeMessageDelimiter(std::string* delimiter) {
  312. if (TryConsume("<")) {
  313. *delimiter = ">";
  314. } else {
  315. DO(Consume("{"));
  316. *delimiter = "}";
  317. }
  318. return true;
  319. }
  320. // Consumes the current field (as returned by the tokenizer) on the
  321. // passed in message.
  322. bool ConsumeField(Message* message) {
  323. const Reflection* reflection = message->GetReflection();
  324. const Descriptor* descriptor = message->GetDescriptor();
  325. std::string field_name;
  326. bool reserved_field = false;
  327. const FieldDescriptor* field = nullptr;
  328. int start_line = tokenizer_.current().line;
  329. int start_column = tokenizer_.current().column;
  330. const FieldDescriptor* any_type_url_field;
  331. const FieldDescriptor* any_value_field;
  332. if (internal::GetAnyFieldDescriptors(*message, &any_type_url_field,
  333. &any_value_field) &&
  334. TryConsume("[")) {
  335. std::string full_type_name, prefix;
  336. DO(ConsumeAnyTypeUrl(&full_type_name, &prefix));
  337. DO(Consume("]"));
  338. TryConsume(":"); // ':' is optional between message labels and values.
  339. std::string serialized_value;
  340. const Descriptor* value_descriptor =
  341. finder_ ? finder_->FindAnyType(*message, prefix, full_type_name)
  342. : DefaultFinderFindAnyType(*message, prefix, full_type_name);
  343. if (value_descriptor == nullptr) {
  344. ReportError("Could not find type \"" + prefix + full_type_name +
  345. "\" stored in google.protobuf.Any.");
  346. return false;
  347. }
  348. DO(ConsumeAnyValue(value_descriptor, &serialized_value));
  349. if (singular_overwrite_policy_ == FORBID_SINGULAR_OVERWRITES) {
  350. // Fail if any_type_url_field has already been specified.
  351. if ((!any_type_url_field->is_repeated() &&
  352. reflection->HasField(*message, any_type_url_field)) ||
  353. (!any_value_field->is_repeated() &&
  354. reflection->HasField(*message, any_value_field))) {
  355. ReportError("Non-repeated Any specified multiple times.");
  356. return false;
  357. }
  358. }
  359. reflection->SetString(message, any_type_url_field,
  360. std::string(prefix + full_type_name));
  361. reflection->SetString(message, any_value_field, serialized_value);
  362. return true;
  363. }
  364. if (TryConsume("[")) {
  365. // Extension.
  366. DO(ConsumeFullTypeName(&field_name));
  367. DO(Consume("]"));
  368. field = finder_ ? finder_->FindExtension(message, field_name)
  369. : DefaultFinderFindExtension(message, field_name);
  370. if (field == nullptr) {
  371. if (!allow_unknown_field_ && !allow_unknown_extension_) {
  372. ReportError("Extension \"" + field_name +
  373. "\" is not defined or "
  374. "is not an extension of \"" +
  375. descriptor->full_name() + "\".");
  376. return false;
  377. } else {
  378. ReportWarning("Ignoring extension \"" + field_name +
  379. "\" which is not defined or is not an extension of \"" +
  380. descriptor->full_name() + "\".");
  381. }
  382. }
  383. } else {
  384. DO(ConsumeIdentifier(&field_name));
  385. int32 field_number;
  386. if (allow_field_number_ &&
  387. safe_strto32(field_name, &field_number)) {
  388. if (descriptor->IsExtensionNumber(field_number)) {
  389. field = finder_
  390. ? finder_->FindExtensionByNumber(descriptor, field_number)
  391. : DefaultFinderFindExtensionByNumber(descriptor,
  392. field_number);
  393. } else if (descriptor->IsReservedNumber(field_number)) {
  394. reserved_field = true;
  395. } else {
  396. field = descriptor->FindFieldByNumber(field_number);
  397. }
  398. } else {
  399. field = descriptor->FindFieldByName(field_name);
  400. // Group names are expected to be capitalized as they appear in the
  401. // .proto file, which actually matches their type names, not their
  402. // field names.
  403. if (field == nullptr) {
  404. std::string lower_field_name = field_name;
  405. LowerString(&lower_field_name);
  406. field = descriptor->FindFieldByName(lower_field_name);
  407. // If the case-insensitive match worked but the field is NOT a group,
  408. if (field != nullptr &&
  409. field->type() != FieldDescriptor::TYPE_GROUP) {
  410. field = nullptr;
  411. }
  412. }
  413. // Again, special-case group names as described above.
  414. if (field != nullptr && field->type() == FieldDescriptor::TYPE_GROUP &&
  415. field->message_type()->name() != field_name) {
  416. field = nullptr;
  417. }
  418. if (field == nullptr && allow_case_insensitive_field_) {
  419. std::string lower_field_name = field_name;
  420. LowerString(&lower_field_name);
  421. field = descriptor->FindFieldByLowercaseName(lower_field_name);
  422. }
  423. if (field == nullptr) {
  424. reserved_field = descriptor->IsReservedName(field_name);
  425. }
  426. }
  427. if (field == nullptr && !reserved_field) {
  428. if (!allow_unknown_field_) {
  429. ReportError("Message type \"" + descriptor->full_name() +
  430. "\" has no field named \"" + field_name + "\".");
  431. return false;
  432. } else {
  433. ReportWarning("Message type \"" + descriptor->full_name() +
  434. "\" has no field named \"" + field_name + "\".");
  435. }
  436. }
  437. }
  438. // Skips unknown or reserved fields.
  439. if (field == nullptr) {
  440. GOOGLE_CHECK(allow_unknown_field_ || allow_unknown_extension_ || reserved_field);
  441. // Try to guess the type of this field.
  442. // If this field is not a message, there should be a ":" between the
  443. // field name and the field value and also the field value should not
  444. // start with "{" or "<" which indicates the beginning of a message body.
  445. // If there is no ":" or there is a "{" or "<" after ":", this field has
  446. // to be a message or the input is ill-formed.
  447. if (TryConsume(":") && !LookingAt("{") && !LookingAt("<")) {
  448. return SkipFieldValue();
  449. } else {
  450. return SkipFieldMessage();
  451. }
  452. }
  453. if (singular_overwrite_policy_ == FORBID_SINGULAR_OVERWRITES) {
  454. // Fail if the field is not repeated and it has already been specified.
  455. if (!field->is_repeated() && reflection->HasField(*message, field)) {
  456. ReportError("Non-repeated field \"" + field_name +
  457. "\" is specified multiple times.");
  458. return false;
  459. }
  460. // Fail if the field is a member of a oneof and another member has already
  461. // been specified.
  462. const OneofDescriptor* oneof = field->containing_oneof();
  463. if (oneof != nullptr && reflection->HasOneof(*message, oneof)) {
  464. const FieldDescriptor* other_field =
  465. reflection->GetOneofFieldDescriptor(*message, oneof);
  466. ReportError("Field \"" + field_name +
  467. "\" is specified along with "
  468. "field \"" +
  469. other_field->name() +
  470. "\", another member "
  471. "of oneof \"" +
  472. oneof->name() + "\".");
  473. return false;
  474. }
  475. }
  476. // Perform special handling for embedded message types.
  477. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  478. // ':' is optional here.
  479. bool consumed_semicolon = TryConsume(":");
  480. if (consumed_semicolon && field->options().weak() &&
  481. LookingAtType(io::Tokenizer::TYPE_STRING)) {
  482. // we are getting a bytes string for a weak field.
  483. std::string tmp;
  484. DO(ConsumeString(&tmp));
  485. MessageFactory* factory =
  486. finder_ ? finder_->FindExtensionFactory(field) : nullptr;
  487. reflection->MutableMessage(message, field, factory)
  488. ->ParseFromString(tmp);
  489. goto label_skip_parsing;
  490. }
  491. } else {
  492. // ':' is required here.
  493. DO(Consume(":"));
  494. }
  495. if (field->is_repeated() && TryConsume("[")) {
  496. // Short repeated format, e.g. "foo: [1, 2, 3]".
  497. if (!TryConsume("]")) {
  498. // "foo: []" is treated as empty.
  499. while (true) {
  500. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  501. // Perform special handling for embedded message types.
  502. DO(ConsumeFieldMessage(message, reflection, field));
  503. } else {
  504. DO(ConsumeFieldValue(message, reflection, field));
  505. }
  506. if (TryConsume("]")) {
  507. break;
  508. }
  509. DO(Consume(","));
  510. }
  511. }
  512. } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  513. DO(ConsumeFieldMessage(message, reflection, field));
  514. } else {
  515. DO(ConsumeFieldValue(message, reflection, field));
  516. }
  517. label_skip_parsing:
  518. // For historical reasons, fields may optionally be separated by commas or
  519. // semicolons.
  520. TryConsume(";") || TryConsume(",");
  521. if (field->options().deprecated()) {
  522. ReportWarning("text format contains deprecated field \"" + field_name +
  523. "\"");
  524. }
  525. // If a parse info tree exists, add the location for the parsed
  526. // field.
  527. if (parse_info_tree_ != nullptr) {
  528. RecordLocation(parse_info_tree_, field,
  529. ParseLocation(start_line, start_column));
  530. }
  531. return true;
  532. }
  533. // Skips the next field including the field's name and value.
  534. bool SkipField() {
  535. if (TryConsume("[")) {
  536. // Extension name or type URL.
  537. DO(ConsumeTypeUrlOrFullTypeName());
  538. DO(Consume("]"));
  539. } else {
  540. std::string field_name;
  541. DO(ConsumeIdentifier(&field_name));
  542. }
  543. // Try to guess the type of this field.
  544. // If this field is not a message, there should be a ":" between the
  545. // field name and the field value and also the field value should not
  546. // start with "{" or "<" which indicates the beginning of a message body.
  547. // If there is no ":" or there is a "{" or "<" after ":", this field has
  548. // to be a message or the input is ill-formed.
  549. if (TryConsume(":") && !LookingAt("{") && !LookingAt("<")) {
  550. DO(SkipFieldValue());
  551. } else {
  552. DO(SkipFieldMessage());
  553. }
  554. // For historical reasons, fields may optionally be separated by commas or
  555. // semicolons.
  556. TryConsume(";") || TryConsume(",");
  557. return true;
  558. }
  559. bool ConsumeFieldMessage(Message* message, const Reflection* reflection,
  560. const FieldDescriptor* field) {
  561. if (--recursion_limit_ < 0) {
  562. ReportError("Message is too deep");
  563. return false;
  564. }
  565. // If the parse information tree is not nullptr, create a nested one
  566. // for the nested message.
  567. ParseInfoTree* parent = parse_info_tree_;
  568. if (parent != nullptr) {
  569. parse_info_tree_ = CreateNested(parent, field);
  570. }
  571. std::string delimiter;
  572. DO(ConsumeMessageDelimiter(&delimiter));
  573. MessageFactory* factory =
  574. finder_ ? finder_->FindExtensionFactory(field) : nullptr;
  575. if (field->is_repeated()) {
  576. DO(ConsumeMessage(reflection->AddMessage(message, field, factory),
  577. delimiter));
  578. } else {
  579. DO(ConsumeMessage(reflection->MutableMessage(message, field, factory),
  580. delimiter));
  581. }
  582. ++recursion_limit_;
  583. // Reset the parse information tree.
  584. parse_info_tree_ = parent;
  585. return true;
  586. }
  587. // Skips the whole body of a message including the beginning delimiter and
  588. // the ending delimiter.
  589. bool SkipFieldMessage() {
  590. std::string delimiter;
  591. DO(ConsumeMessageDelimiter(&delimiter));
  592. while (!LookingAt(">") && !LookingAt("}")) {
  593. DO(SkipField());
  594. }
  595. DO(Consume(delimiter));
  596. return true;
  597. }
  598. bool ConsumeFieldValue(Message* message, const Reflection* reflection,
  599. const FieldDescriptor* field) {
  600. // Define an easy to use macro for setting fields. This macro checks
  601. // to see if the field is repeated (in which case we need to use the Add
  602. // methods or not (in which case we need to use the Set methods).
  603. #define SET_FIELD(CPPTYPE, VALUE) \
  604. if (field->is_repeated()) { \
  605. reflection->Add##CPPTYPE(message, field, VALUE); \
  606. } else { \
  607. reflection->Set##CPPTYPE(message, field, VALUE); \
  608. }
  609. switch (field->cpp_type()) {
  610. case FieldDescriptor::CPPTYPE_INT32: {
  611. int64 value;
  612. DO(ConsumeSignedInteger(&value, kint32max));
  613. SET_FIELD(Int32, static_cast<int32>(value));
  614. break;
  615. }
  616. case FieldDescriptor::CPPTYPE_UINT32: {
  617. uint64 value;
  618. DO(ConsumeUnsignedInteger(&value, kuint32max));
  619. SET_FIELD(UInt32, static_cast<uint32>(value));
  620. break;
  621. }
  622. case FieldDescriptor::CPPTYPE_INT64: {
  623. int64 value;
  624. DO(ConsumeSignedInteger(&value, kint64max));
  625. SET_FIELD(Int64, value);
  626. break;
  627. }
  628. case FieldDescriptor::CPPTYPE_UINT64: {
  629. uint64 value;
  630. DO(ConsumeUnsignedInteger(&value, kuint64max));
  631. SET_FIELD(UInt64, value);
  632. break;
  633. }
  634. case FieldDescriptor::CPPTYPE_FLOAT: {
  635. double value;
  636. DO(ConsumeDouble(&value));
  637. SET_FIELD(Float, io::SafeDoubleToFloat(value));
  638. break;
  639. }
  640. case FieldDescriptor::CPPTYPE_DOUBLE: {
  641. double value;
  642. DO(ConsumeDouble(&value));
  643. SET_FIELD(Double, value);
  644. break;
  645. }
  646. case FieldDescriptor::CPPTYPE_STRING: {
  647. std::string value;
  648. DO(ConsumeString(&value));
  649. SET_FIELD(String, value);
  650. break;
  651. }
  652. case FieldDescriptor::CPPTYPE_BOOL: {
  653. if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) {
  654. uint64 value;
  655. DO(ConsumeUnsignedInteger(&value, 1));
  656. SET_FIELD(Bool, value);
  657. } else {
  658. std::string value;
  659. DO(ConsumeIdentifier(&value));
  660. if (value == "true" || value == "True" || value == "t") {
  661. SET_FIELD(Bool, true);
  662. } else if (value == "false" || value == "False" || value == "f") {
  663. SET_FIELD(Bool, false);
  664. } else {
  665. ReportError("Invalid value for boolean field \"" + field->name() +
  666. "\". Value: \"" + value + "\".");
  667. return false;
  668. }
  669. }
  670. break;
  671. }
  672. case FieldDescriptor::CPPTYPE_ENUM: {
  673. std::string value;
  674. int64 int_value = kint64max;
  675. const EnumDescriptor* enum_type = field->enum_type();
  676. const EnumValueDescriptor* enum_value = nullptr;
  677. if (LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) {
  678. DO(ConsumeIdentifier(&value));
  679. // Find the enumeration value.
  680. enum_value = enum_type->FindValueByName(value);
  681. } else if (LookingAt("-") ||
  682. LookingAtType(io::Tokenizer::TYPE_INTEGER)) {
  683. DO(ConsumeSignedInteger(&int_value, kint32max));
  684. value = StrCat(int_value); // for error reporting
  685. enum_value = enum_type->FindValueByNumber(int_value);
  686. } else {
  687. ReportError("Expected integer or identifier, got: " +
  688. tokenizer_.current().text);
  689. return false;
  690. }
  691. if (enum_value == nullptr) {
  692. if (int_value != kint64max &&
  693. reflection->SupportsUnknownEnumValues()) {
  694. SET_FIELD(EnumValue, int_value);
  695. return true;
  696. } else if (!allow_unknown_enum_) {
  697. ReportError("Unknown enumeration value of \"" + value +
  698. "\" for "
  699. "field \"" +
  700. field->name() + "\".");
  701. return false;
  702. } else {
  703. ReportWarning("Unknown enumeration value of \"" + value +
  704. "\" for "
  705. "field \"" +
  706. field->name() + "\".");
  707. return true;
  708. }
  709. }
  710. SET_FIELD(Enum, enum_value);
  711. break;
  712. }
  713. case FieldDescriptor::CPPTYPE_MESSAGE: {
  714. // We should never get here. Put here instead of a default
  715. // so that if new types are added, we get a nice compiler warning.
  716. GOOGLE_LOG(FATAL) << "Reached an unintended state: CPPTYPE_MESSAGE";
  717. break;
  718. }
  719. }
  720. #undef SET_FIELD
  721. return true;
  722. }
  723. bool SkipFieldValue() {
  724. if (LookingAtType(io::Tokenizer::TYPE_STRING)) {
  725. while (LookingAtType(io::Tokenizer::TYPE_STRING)) {
  726. tokenizer_.Next();
  727. }
  728. return true;
  729. }
  730. if (TryConsume("[")) {
  731. while (true) {
  732. if (!LookingAt("{") && !LookingAt("<")) {
  733. DO(SkipFieldValue());
  734. } else {
  735. DO(SkipFieldMessage());
  736. }
  737. if (TryConsume("]")) {
  738. break;
  739. }
  740. DO(Consume(","));
  741. }
  742. return true;
  743. }
  744. // Possible field values other than string:
  745. // 12345 => TYPE_INTEGER
  746. // -12345 => TYPE_SYMBOL + TYPE_INTEGER
  747. // 1.2345 => TYPE_FLOAT
  748. // -1.2345 => TYPE_SYMBOL + TYPE_FLOAT
  749. // inf => TYPE_IDENTIFIER
  750. // -inf => TYPE_SYMBOL + TYPE_IDENTIFIER
  751. // TYPE_INTEGER => TYPE_IDENTIFIER
  752. // Divides them into two group, one with TYPE_SYMBOL
  753. // and the other without:
  754. // Group one:
  755. // 12345 => TYPE_INTEGER
  756. // 1.2345 => TYPE_FLOAT
  757. // inf => TYPE_IDENTIFIER
  758. // TYPE_INTEGER => TYPE_IDENTIFIER
  759. // Group two:
  760. // -12345 => TYPE_SYMBOL + TYPE_INTEGER
  761. // -1.2345 => TYPE_SYMBOL + TYPE_FLOAT
  762. // -inf => TYPE_SYMBOL + TYPE_IDENTIFIER
  763. // As we can see, the field value consists of an optional '-' and one of
  764. // TYPE_INTEGER, TYPE_FLOAT and TYPE_IDENTIFIER.
  765. bool has_minus = TryConsume("-");
  766. if (!LookingAtType(io::Tokenizer::TYPE_INTEGER) &&
  767. !LookingAtType(io::Tokenizer::TYPE_FLOAT) &&
  768. !LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) {
  769. std::string text = tokenizer_.current().text;
  770. ReportError("Cannot skip field value, unexpected token: " + text);
  771. return false;
  772. }
  773. // Combination of '-' and TYPE_IDENTIFIER may result in an invalid field
  774. // value while other combinations all generate valid values.
  775. // We check if the value of this combination is valid here.
  776. // TYPE_IDENTIFIER after a '-' should be one of the float values listed
  777. // below:
  778. // inf, inff, infinity, nan
  779. if (has_minus && LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) {
  780. std::string text = tokenizer_.current().text;
  781. LowerString(&text);
  782. if (text != "inf" &&
  783. text != "infinity" && text != "nan") {
  784. ReportError("Invalid float number: " + text);
  785. return false;
  786. }
  787. }
  788. tokenizer_.Next();
  789. return true;
  790. }
  791. // Returns true if the current token's text is equal to that specified.
  792. bool LookingAt(const std::string& text) {
  793. return tokenizer_.current().text == text;
  794. }
  795. // Returns true if the current token's type is equal to that specified.
  796. bool LookingAtType(io::Tokenizer::TokenType token_type) {
  797. return tokenizer_.current().type == token_type;
  798. }
  799. // Consumes an identifier and saves its value in the identifier parameter.
  800. // Returns false if the token is not of type IDENTFIER.
  801. bool ConsumeIdentifier(std::string* identifier) {
  802. if (LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) {
  803. *identifier = tokenizer_.current().text;
  804. tokenizer_.Next();
  805. return true;
  806. }
  807. // If allow_field_numer_ or allow_unknown_field_ is true, we should able
  808. // to parse integer identifiers.
  809. if ((allow_field_number_ || allow_unknown_field_ ||
  810. allow_unknown_extension_) &&
  811. LookingAtType(io::Tokenizer::TYPE_INTEGER)) {
  812. *identifier = tokenizer_.current().text;
  813. tokenizer_.Next();
  814. return true;
  815. }
  816. ReportError("Expected identifier, got: " + tokenizer_.current().text);
  817. return false;
  818. }
  819. // Consume a string of form "<id1>.<id2>....<idN>".
  820. bool ConsumeFullTypeName(std::string* name) {
  821. DO(ConsumeIdentifier(name));
  822. while (TryConsume(".")) {
  823. std::string part;
  824. DO(ConsumeIdentifier(&part));
  825. *name += ".";
  826. *name += part;
  827. }
  828. return true;
  829. }
  830. bool ConsumeTypeUrlOrFullTypeName() {
  831. std::string discarded;
  832. DO(ConsumeIdentifier(&discarded));
  833. while (TryConsume(".") || TryConsume("/")) {
  834. DO(ConsumeIdentifier(&discarded));
  835. }
  836. return true;
  837. }
  838. // Consumes a string and saves its value in the text parameter.
  839. // Returns false if the token is not of type STRING.
  840. bool ConsumeString(std::string* text) {
  841. if (!LookingAtType(io::Tokenizer::TYPE_STRING)) {
  842. ReportError("Expected string, got: " + tokenizer_.current().text);
  843. return false;
  844. }
  845. text->clear();
  846. while (LookingAtType(io::Tokenizer::TYPE_STRING)) {
  847. io::Tokenizer::ParseStringAppend(tokenizer_.current().text, text);
  848. tokenizer_.Next();
  849. }
  850. return true;
  851. }
  852. // Consumes a uint64 and saves its value in the value parameter.
  853. // Returns false if the token is not of type INTEGER.
  854. bool ConsumeUnsignedInteger(uint64* value, uint64 max_value) {
  855. if (!LookingAtType(io::Tokenizer::TYPE_INTEGER)) {
  856. ReportError("Expected integer, got: " + tokenizer_.current().text);
  857. return false;
  858. }
  859. if (!io::Tokenizer::ParseInteger(tokenizer_.current().text, max_value,
  860. value)) {
  861. ReportError("Integer out of range (" + tokenizer_.current().text + ")");
  862. return false;
  863. }
  864. tokenizer_.Next();
  865. return true;
  866. }
  867. // Consumes an int64 and saves its value in the value parameter.
  868. // Note that since the tokenizer does not support negative numbers,
  869. // we actually may consume an additional token (for the minus sign) in this
  870. // method. Returns false if the token is not an integer
  871. // (signed or otherwise).
  872. bool ConsumeSignedInteger(int64* value, uint64 max_value) {
  873. bool negative = false;
  874. if (TryConsume("-")) {
  875. negative = true;
  876. // Two's complement always allows one more negative integer than
  877. // positive.
  878. ++max_value;
  879. }
  880. uint64 unsigned_value;
  881. DO(ConsumeUnsignedInteger(&unsigned_value, max_value));
  882. if (negative) {
  883. if ((static_cast<uint64>(kint64max) + 1) == unsigned_value) {
  884. *value = kint64min;
  885. } else {
  886. *value = -static_cast<int64>(unsigned_value);
  887. }
  888. } else {
  889. *value = static_cast<int64>(unsigned_value);
  890. }
  891. return true;
  892. }
  893. // Consumes a double and saves its value in the value parameter.
  894. // Accepts decimal numbers only, rejects hex or oct numbers.
  895. bool ConsumeUnsignedDecimalAsDouble(double* value, uint64 max_value) {
  896. if (!LookingAtType(io::Tokenizer::TYPE_INTEGER)) {
  897. ReportError("Expected integer, got: " + tokenizer_.current().text);
  898. return false;
  899. }
  900. const std::string& text = tokenizer_.current().text;
  901. if (IsHexNumber(text) || IsOctNumber(text)) {
  902. ReportError("Expect a decimal number, got: " + text);
  903. return false;
  904. }
  905. uint64 uint64_value;
  906. if (io::Tokenizer::ParseInteger(text, max_value, &uint64_value)) {
  907. *value = static_cast<double>(uint64_value);
  908. } else {
  909. // Uint64 overflow, attempt to parse as a double instead.
  910. *value = io::Tokenizer::ParseFloat(text);
  911. }
  912. tokenizer_.Next();
  913. return true;
  914. }
  915. // Consumes a double and saves its value in the value parameter.
  916. // Note that since the tokenizer does not support negative numbers,
  917. // we actually may consume an additional token (for the minus sign) in this
  918. // method. Returns false if the token is not a double
  919. // (signed or otherwise).
  920. bool ConsumeDouble(double* value) {
  921. bool negative = false;
  922. if (TryConsume("-")) {
  923. negative = true;
  924. }
  925. // A double can actually be an integer, according to the tokenizer.
  926. // Therefore, we must check both cases here.
  927. if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) {
  928. // We have found an integer value for the double.
  929. DO(ConsumeUnsignedDecimalAsDouble(value, kuint64max));
  930. } else if (LookingAtType(io::Tokenizer::TYPE_FLOAT)) {
  931. // We have found a float value for the double.
  932. *value = io::Tokenizer::ParseFloat(tokenizer_.current().text);
  933. // Mark the current token as consumed.
  934. tokenizer_.Next();
  935. } else if (LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) {
  936. std::string text = tokenizer_.current().text;
  937. LowerString(&text);
  938. if (text == "inf" ||
  939. text == "infinity") {
  940. *value = std::numeric_limits<double>::infinity();
  941. tokenizer_.Next();
  942. } else if (text == "nan") {
  943. *value = std::numeric_limits<double>::quiet_NaN();
  944. tokenizer_.Next();
  945. } else {
  946. ReportError("Expected double, got: " + text);
  947. return false;
  948. }
  949. } else {
  950. ReportError("Expected double, got: " + tokenizer_.current().text);
  951. return false;
  952. }
  953. if (negative) {
  954. *value = -*value;
  955. }
  956. return true;
  957. }
  958. // Consumes Any::type_url value, of form "type.googleapis.com/full.type.Name"
  959. // or "type.googleprod.com/full.type.Name"
  960. bool ConsumeAnyTypeUrl(std::string* full_type_name, std::string* prefix) {
  961. // TODO(saito) Extend Consume() to consume multiple tokens at once, so that
  962. // this code can be written as just DO(Consume(kGoogleApisTypePrefix)).
  963. DO(ConsumeIdentifier(prefix));
  964. while (TryConsume(".")) {
  965. std::string url;
  966. DO(ConsumeIdentifier(&url));
  967. *prefix += "." + url;
  968. }
  969. DO(Consume("/"));
  970. *prefix += "/";
  971. DO(ConsumeFullTypeName(full_type_name));
  972. return true;
  973. }
  974. // A helper function for reconstructing Any::value. Consumes a text of
  975. // full_type_name, then serializes it into serialized_value.
  976. bool ConsumeAnyValue(const Descriptor* value_descriptor,
  977. std::string* serialized_value) {
  978. DynamicMessageFactory factory;
  979. const Message* value_prototype = factory.GetPrototype(value_descriptor);
  980. if (value_prototype == nullptr) {
  981. return false;
  982. }
  983. std::unique_ptr<Message> value(value_prototype->New());
  984. std::string sub_delimiter;
  985. DO(ConsumeMessageDelimiter(&sub_delimiter));
  986. DO(ConsumeMessage(value.get(), sub_delimiter));
  987. if (allow_partial_) {
  988. value->AppendPartialToString(serialized_value);
  989. } else {
  990. if (!value->IsInitialized()) {
  991. ReportError(
  992. "Value of type \"" + value_descriptor->full_name() +
  993. "\" stored in google.protobuf.Any has missing required fields");
  994. return false;
  995. }
  996. value->AppendToString(serialized_value);
  997. }
  998. return true;
  999. }
  1000. // Consumes a token and confirms that it matches that specified in the
  1001. // value parameter. Returns false if the token found does not match that
  1002. // which was specified.
  1003. bool Consume(const std::string& value) {
  1004. const std::string& current_value = tokenizer_.current().text;
  1005. if (current_value != value) {
  1006. ReportError("Expected \"" + value + "\", found \"" + current_value +
  1007. "\".");
  1008. return false;
  1009. }
  1010. tokenizer_.Next();
  1011. return true;
  1012. }
  1013. // Attempts to consume the supplied value. Returns false if a the
  1014. // token found does not match the value specified.
  1015. bool TryConsume(const std::string& value) {
  1016. if (tokenizer_.current().text == value) {
  1017. tokenizer_.Next();
  1018. return true;
  1019. } else {
  1020. return false;
  1021. }
  1022. }
  1023. // An internal instance of the Tokenizer's error collector, used to
  1024. // collect any base-level parse errors and feed them to the ParserImpl.
  1025. class ParserErrorCollector : public io::ErrorCollector {
  1026. public:
  1027. explicit ParserErrorCollector(TextFormat::Parser::ParserImpl* parser)
  1028. : parser_(parser) {}
  1029. ~ParserErrorCollector() override {}
  1030. void AddError(int line, int column, const std::string& message) override {
  1031. parser_->ReportError(line, column, message);
  1032. }
  1033. void AddWarning(int line, int column, const std::string& message) override {
  1034. parser_->ReportWarning(line, column, message);
  1035. }
  1036. private:
  1037. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ParserErrorCollector);
  1038. TextFormat::Parser::ParserImpl* parser_;
  1039. };
  1040. io::ErrorCollector* error_collector_;
  1041. const TextFormat::Finder* finder_;
  1042. ParseInfoTree* parse_info_tree_;
  1043. ParserErrorCollector tokenizer_error_collector_;
  1044. io::Tokenizer tokenizer_;
  1045. const Descriptor* root_message_type_;
  1046. SingularOverwritePolicy singular_overwrite_policy_;
  1047. const bool allow_case_insensitive_field_;
  1048. const bool allow_unknown_field_;
  1049. const bool allow_unknown_extension_;
  1050. const bool allow_unknown_enum_;
  1051. const bool allow_field_number_;
  1052. const bool allow_partial_;
  1053. int recursion_limit_;
  1054. bool had_errors_;
  1055. };
  1056. // ===========================================================================
  1057. // Internal class for writing text to the io::ZeroCopyOutputStream. Adapted
  1058. // from the Printer found in //net/proto2/io/public/printer.h
  1059. class TextFormat::Printer::TextGenerator
  1060. : public TextFormat::BaseTextGenerator {
  1061. public:
  1062. explicit TextGenerator(io::ZeroCopyOutputStream* output,
  1063. int initial_indent_level)
  1064. : output_(output),
  1065. buffer_(nullptr),
  1066. buffer_size_(0),
  1067. at_start_of_line_(true),
  1068. failed_(false),
  1069. indent_level_(initial_indent_level),
  1070. initial_indent_level_(initial_indent_level) {}
  1071. ~TextGenerator() {
  1072. // Only BackUp() if we're sure we've successfully called Next() at least
  1073. // once.
  1074. if (!failed_ && buffer_size_ > 0) {
  1075. output_->BackUp(buffer_size_);
  1076. }
  1077. }
  1078. // Indent text by two spaces. After calling Indent(), two spaces will be
  1079. // inserted at the beginning of each line of text. Indent() may be called
  1080. // multiple times to produce deeper indents.
  1081. void Indent() override { ++indent_level_; }
  1082. // Reduces the current indent level by two spaces, or crashes if the indent
  1083. // level is zero.
  1084. void Outdent() override {
  1085. if (indent_level_ == 0 || indent_level_ < initial_indent_level_) {
  1086. GOOGLE_LOG(DFATAL) << " Outdent() without matching Indent().";
  1087. return;
  1088. }
  1089. --indent_level_;
  1090. }
  1091. size_t GetCurrentIndentationSize() const override {
  1092. return 2 * indent_level_;
  1093. }
  1094. // Print text to the output stream.
  1095. void Print(const char* text, size_t size) override {
  1096. if (indent_level_ > 0) {
  1097. size_t pos = 0; // The number of bytes we've written so far.
  1098. for (size_t i = 0; i < size; i++) {
  1099. if (text[i] == '\n') {
  1100. // Saw newline. If there is more text, we may need to insert an
  1101. // indent here. So, write what we have so far, including the '\n'.
  1102. Write(text + pos, i - pos + 1);
  1103. pos = i + 1;
  1104. // Setting this true will cause the next Write() to insert an indent
  1105. // first.
  1106. at_start_of_line_ = true;
  1107. }
  1108. }
  1109. // Write the rest.
  1110. Write(text + pos, size - pos);
  1111. } else {
  1112. Write(text, size);
  1113. if (size > 0 && text[size - 1] == '\n') {
  1114. at_start_of_line_ = true;
  1115. }
  1116. }
  1117. }
  1118. // True if any write to the underlying stream failed. (We don't just
  1119. // crash in this case because this is an I/O failure, not a programming
  1120. // error.)
  1121. bool failed() const { return failed_; }
  1122. private:
  1123. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TextGenerator);
  1124. void Write(const char* data, size_t size) {
  1125. if (failed_) return;
  1126. if (size == 0) return;
  1127. if (at_start_of_line_) {
  1128. // Insert an indent.
  1129. at_start_of_line_ = false;
  1130. WriteIndent();
  1131. if (failed_) return;
  1132. }
  1133. while (size > buffer_size_) {
  1134. // Data exceeds space in the buffer. Copy what we can and request a
  1135. // new buffer.
  1136. if (buffer_size_ > 0) {
  1137. memcpy(buffer_, data, buffer_size_);
  1138. data += buffer_size_;
  1139. size -= buffer_size_;
  1140. }
  1141. void* void_buffer = nullptr;
  1142. failed_ = !output_->Next(&void_buffer, &buffer_size_);
  1143. if (failed_) return;
  1144. buffer_ = reinterpret_cast<char*>(void_buffer);
  1145. }
  1146. // Buffer is big enough to receive the data; copy it.
  1147. memcpy(buffer_, data, size);
  1148. buffer_ += size;
  1149. buffer_size_ -= size;
  1150. }
  1151. void WriteIndent() {
  1152. if (indent_level_ == 0) {
  1153. return;
  1154. }
  1155. GOOGLE_DCHECK(!failed_);
  1156. int size = GetCurrentIndentationSize();
  1157. while (size > buffer_size_) {
  1158. // Data exceeds space in the buffer. Write what we can and request a new
  1159. // buffer.
  1160. if (buffer_size_ > 0) {
  1161. memset(buffer_, ' ', buffer_size_);
  1162. }
  1163. size -= buffer_size_;
  1164. void* void_buffer;
  1165. failed_ = !output_->Next(&void_buffer, &buffer_size_);
  1166. if (failed_) return;
  1167. buffer_ = reinterpret_cast<char*>(void_buffer);
  1168. }
  1169. // Buffer is big enough to receive the data; copy it.
  1170. memset(buffer_, ' ', size);
  1171. buffer_ += size;
  1172. buffer_size_ -= size;
  1173. }
  1174. io::ZeroCopyOutputStream* const output_;
  1175. char* buffer_;
  1176. int buffer_size_;
  1177. bool at_start_of_line_;
  1178. bool failed_;
  1179. int indent_level_;
  1180. int initial_indent_level_;
  1181. };
  1182. // ===========================================================================
  1183. // Implementation of the default Finder for extensions.
  1184. TextFormat::Finder::~Finder() {}
  1185. const FieldDescriptor* TextFormat::Finder::FindExtension(
  1186. Message* message, const std::string& name) const {
  1187. return DefaultFinderFindExtension(message, name);
  1188. }
  1189. const FieldDescriptor* TextFormat::Finder::FindExtensionByNumber(
  1190. const Descriptor* descriptor, int number) const {
  1191. return DefaultFinderFindExtensionByNumber(descriptor, number);
  1192. }
  1193. const Descriptor* TextFormat::Finder::FindAnyType(
  1194. const Message& message, const std::string& prefix,
  1195. const std::string& name) const {
  1196. return DefaultFinderFindAnyType(message, prefix, name);
  1197. }
  1198. MessageFactory* TextFormat::Finder::FindExtensionFactory(
  1199. const FieldDescriptor* field) const {
  1200. return nullptr;
  1201. }
  1202. // ===========================================================================
  1203. TextFormat::Parser::Parser()
  1204. : error_collector_(nullptr),
  1205. finder_(nullptr),
  1206. parse_info_tree_(nullptr),
  1207. allow_partial_(false),
  1208. allow_case_insensitive_field_(false),
  1209. allow_unknown_field_(false),
  1210. allow_unknown_extension_(false),
  1211. allow_unknown_enum_(false),
  1212. allow_field_number_(false),
  1213. allow_relaxed_whitespace_(false),
  1214. allow_singular_overwrites_(false),
  1215. recursion_limit_(std::numeric_limits<int>::max()) {}
  1216. TextFormat::Parser::~Parser() {}
  1217. namespace {
  1218. bool CheckParseInputSize(StringPiece input,
  1219. io::ErrorCollector* error_collector) {
  1220. if (input.size() > INT_MAX) {
  1221. error_collector->AddError(
  1222. -1, 0,
  1223. StrCat("Input size too large: ", static_cast<int64>(input.size()),
  1224. " bytes", " > ", INT_MAX, " bytes."));
  1225. return false;
  1226. }
  1227. return true;
  1228. }
  1229. } // namespace
  1230. bool TextFormat::Parser::Parse(io::ZeroCopyInputStream* input,
  1231. Message* output) {
  1232. output->Clear();
  1233. ParserImpl::SingularOverwritePolicy overwrites_policy =
  1234. allow_singular_overwrites_ ? ParserImpl::ALLOW_SINGULAR_OVERWRITES
  1235. : ParserImpl::FORBID_SINGULAR_OVERWRITES;
  1236. ParserImpl parser(output->GetDescriptor(), input, error_collector_, finder_,
  1237. parse_info_tree_, overwrites_policy,
  1238. allow_case_insensitive_field_, allow_unknown_field_,
  1239. allow_unknown_extension_, allow_unknown_enum_,
  1240. allow_field_number_, allow_relaxed_whitespace_,
  1241. allow_partial_, recursion_limit_);
  1242. return MergeUsingImpl(input, output, &parser);
  1243. }
  1244. bool TextFormat::Parser::ParseFromString(const std::string& input,
  1245. Message* output) {
  1246. DO(CheckParseInputSize(input, error_collector_));
  1247. io::ArrayInputStream input_stream(input.data(), input.size());
  1248. return Parse(&input_stream, output);
  1249. }
  1250. bool TextFormat::Parser::Merge(io::ZeroCopyInputStream* input,
  1251. Message* output) {
  1252. ParserImpl parser(output->GetDescriptor(), input, error_collector_, finder_,
  1253. parse_info_tree_, ParserImpl::ALLOW_SINGULAR_OVERWRITES,
  1254. allow_case_insensitive_field_, allow_unknown_field_,
  1255. allow_unknown_extension_, allow_unknown_enum_,
  1256. allow_field_number_, allow_relaxed_whitespace_,
  1257. allow_partial_, recursion_limit_);
  1258. return MergeUsingImpl(input, output, &parser);
  1259. }
  1260. bool TextFormat::Parser::MergeFromString(const std::string& input,
  1261. Message* output) {
  1262. DO(CheckParseInputSize(input, error_collector_));
  1263. io::ArrayInputStream input_stream(input.data(), input.size());
  1264. return Merge(&input_stream, output);
  1265. }
  1266. bool TextFormat::Parser::MergeUsingImpl(io::ZeroCopyInputStream* /* input */,
  1267. Message* output,
  1268. ParserImpl* parser_impl) {
  1269. if (!parser_impl->Parse(output)) return false;
  1270. if (!allow_partial_ && !output->IsInitialized()) {
  1271. std::vector<std::string> missing_fields;
  1272. output->FindInitializationErrors(&missing_fields);
  1273. parser_impl->ReportError(-1, 0,
  1274. "Message missing required fields: " +
  1275. Join(missing_fields, ", "));
  1276. return false;
  1277. }
  1278. return true;
  1279. }
  1280. bool TextFormat::Parser::ParseFieldValueFromString(const std::string& input,
  1281. const FieldDescriptor* field,
  1282. Message* output) {
  1283. io::ArrayInputStream input_stream(input.data(), input.size());
  1284. ParserImpl parser(
  1285. output->GetDescriptor(), &input_stream, error_collector_, finder_,
  1286. parse_info_tree_, ParserImpl::ALLOW_SINGULAR_OVERWRITES,
  1287. allow_case_insensitive_field_, allow_unknown_field_,
  1288. allow_unknown_extension_, allow_unknown_enum_, allow_field_number_,
  1289. allow_relaxed_whitespace_, allow_partial_, recursion_limit_);
  1290. return parser.ParseField(field, output);
  1291. }
  1292. /* static */ bool TextFormat::Parse(io::ZeroCopyInputStream* input,
  1293. Message* output) {
  1294. return Parser().Parse(input, output);
  1295. }
  1296. /* static */ bool TextFormat::Merge(io::ZeroCopyInputStream* input,
  1297. Message* output) {
  1298. return Parser().Merge(input, output);
  1299. }
  1300. /* static */ bool TextFormat::ParseFromString(const std::string& input,
  1301. Message* output) {
  1302. return Parser().ParseFromString(input, output);
  1303. }
  1304. /* static */ bool TextFormat::MergeFromString(const std::string& input,
  1305. Message* output) {
  1306. return Parser().MergeFromString(input, output);
  1307. }
  1308. #undef DO
  1309. // ===========================================================================
  1310. TextFormat::BaseTextGenerator::~BaseTextGenerator() {}
  1311. namespace {
  1312. // A BaseTextGenerator that writes to a string.
  1313. class StringBaseTextGenerator : public TextFormat::BaseTextGenerator {
  1314. public:
  1315. void Print(const char* text, size_t size) override {
  1316. output_.append(text, size);
  1317. }
  1318. // Some compilers do not support ref-qualifiers even in C++11 mode.
  1319. // Disable the optimization for now and revisit it later.
  1320. #if 0 // LANG_CXX11
  1321. std::string Consume() && { return std::move(output_); }
  1322. #else // !LANG_CXX11
  1323. const std::string& Get() { return output_; }
  1324. #endif // LANG_CXX11
  1325. private:
  1326. std::string output_;
  1327. };
  1328. } // namespace
  1329. // The default implementation for FieldValuePrinter. We just delegate the
  1330. // implementation to the default FastFieldValuePrinter to avoid duplicating the
  1331. // logic.
  1332. TextFormat::FieldValuePrinter::FieldValuePrinter() {}
  1333. TextFormat::FieldValuePrinter::~FieldValuePrinter() {}
  1334. #if 0 // LANG_CXX11
  1335. #define FORWARD_IMPL(fn, ...) \
  1336. StringBaseTextGenerator generator; \
  1337. delegate_.fn(__VA_ARGS__, &generator); \
  1338. return std::move(generator).Consume()
  1339. #else // !LANG_CXX11
  1340. #define FORWARD_IMPL(fn, ...) \
  1341. StringBaseTextGenerator generator; \
  1342. delegate_.fn(__VA_ARGS__, &generator); \
  1343. return generator.Get()
  1344. #endif // LANG_CXX11
  1345. std::string TextFormat::FieldValuePrinter::PrintBool(bool val) const {
  1346. FORWARD_IMPL(PrintBool, val);
  1347. }
  1348. std::string TextFormat::FieldValuePrinter::PrintInt32(int32 val) const {
  1349. FORWARD_IMPL(PrintInt32, val);
  1350. }
  1351. std::string TextFormat::FieldValuePrinter::PrintUInt32(uint32 val) const {
  1352. FORWARD_IMPL(PrintUInt32, val);
  1353. }
  1354. std::string TextFormat::FieldValuePrinter::PrintInt64(int64 val) const {
  1355. FORWARD_IMPL(PrintInt64, val);
  1356. }
  1357. std::string TextFormat::FieldValuePrinter::PrintUInt64(uint64 val) const {
  1358. FORWARD_IMPL(PrintUInt64, val);
  1359. }
  1360. std::string TextFormat::FieldValuePrinter::PrintFloat(float val) const {
  1361. FORWARD_IMPL(PrintFloat, val);
  1362. }
  1363. std::string TextFormat::FieldValuePrinter::PrintDouble(double val) const {
  1364. FORWARD_IMPL(PrintDouble, val);
  1365. }
  1366. std::string TextFormat::FieldValuePrinter::PrintString(
  1367. const std::string& val) const {
  1368. FORWARD_IMPL(PrintString, val);
  1369. }
  1370. std::string TextFormat::FieldValuePrinter::PrintBytes(
  1371. const std::string& val) const {
  1372. return PrintString(val);
  1373. }
  1374. std::string TextFormat::FieldValuePrinter::PrintEnum(
  1375. int32 val, const std::string& name) const {
  1376. FORWARD_IMPL(PrintEnum, val, name);
  1377. }
  1378. std::string TextFormat::FieldValuePrinter::PrintFieldName(
  1379. const Message& message, const Reflection* reflection,
  1380. const FieldDescriptor* field) const {
  1381. FORWARD_IMPL(PrintFieldName, message, reflection, field);
  1382. }
  1383. std::string TextFormat::FieldValuePrinter::PrintMessageStart(
  1384. const Message& message, int field_index, int field_count,
  1385. bool single_line_mode) const {
  1386. FORWARD_IMPL(PrintMessageStart, message, field_index, field_count,
  1387. single_line_mode);
  1388. }
  1389. std::string TextFormat::FieldValuePrinter::PrintMessageEnd(
  1390. const Message& message, int field_index, int field_count,
  1391. bool single_line_mode) const {
  1392. FORWARD_IMPL(PrintMessageEnd, message, field_index, field_count,
  1393. single_line_mode);
  1394. }
  1395. #undef FORWARD_IMPL
  1396. TextFormat::FastFieldValuePrinter::FastFieldValuePrinter() {}
  1397. TextFormat::FastFieldValuePrinter::~FastFieldValuePrinter() {}
  1398. void TextFormat::FastFieldValuePrinter::PrintBool(
  1399. bool val, BaseTextGenerator* generator) const {
  1400. if (val) {
  1401. generator->PrintLiteral("true");
  1402. } else {
  1403. generator->PrintLiteral("false");
  1404. }
  1405. }
  1406. void TextFormat::FastFieldValuePrinter::PrintInt32(
  1407. int32 val, BaseTextGenerator* generator) const {
  1408. generator->PrintString(StrCat(val));
  1409. }
  1410. void TextFormat::FastFieldValuePrinter::PrintUInt32(
  1411. uint32 val, BaseTextGenerator* generator) const {
  1412. generator->PrintString(StrCat(val));
  1413. }
  1414. void TextFormat::FastFieldValuePrinter::PrintInt64(
  1415. int64 val, BaseTextGenerator* generator) const {
  1416. generator->PrintString(StrCat(val));
  1417. }
  1418. void TextFormat::FastFieldValuePrinter::PrintUInt64(
  1419. uint64 val, BaseTextGenerator* generator) const {
  1420. generator->PrintString(StrCat(val));
  1421. }
  1422. void TextFormat::FastFieldValuePrinter::PrintFloat(
  1423. float val, BaseTextGenerator* generator) const {
  1424. generator->PrintString(!std::isnan(val) ? SimpleFtoa(val) : "nan");
  1425. }
  1426. void TextFormat::FastFieldValuePrinter::PrintDouble(
  1427. double val, BaseTextGenerator* generator) const {
  1428. generator->PrintString(!std::isnan(val) ? SimpleDtoa(val) : "nan");
  1429. }
  1430. void TextFormat::FastFieldValuePrinter::PrintEnum(
  1431. int32 val, const std::string& name, BaseTextGenerator* generator) const {
  1432. generator->PrintString(name);
  1433. }
  1434. void TextFormat::FastFieldValuePrinter::PrintString(
  1435. const std::string& val, BaseTextGenerator* generator) const {
  1436. generator->PrintLiteral("\"");
  1437. generator->PrintString(CEscape(val));
  1438. generator->PrintLiteral("\"");
  1439. }
  1440. void TextFormat::FastFieldValuePrinter::PrintBytes(
  1441. const std::string& val, BaseTextGenerator* generator) const {
  1442. PrintString(val, generator);
  1443. }
  1444. void TextFormat::FastFieldValuePrinter::PrintFieldName(
  1445. const Message& message, int field_index, int field_count,
  1446. const Reflection* reflection, const FieldDescriptor* field,
  1447. BaseTextGenerator* generator) const {
  1448. PrintFieldName(message, reflection, field, generator);
  1449. }
  1450. void TextFormat::FastFieldValuePrinter::PrintFieldName(
  1451. const Message& message, const Reflection* reflection,
  1452. const FieldDescriptor* field, BaseTextGenerator* generator) const {
  1453. if (field->is_extension()) {
  1454. generator->PrintLiteral("[");
  1455. generator->PrintString(field->PrintableNameForExtension());
  1456. generator->PrintLiteral("]");
  1457. } else if (field->type() == FieldDescriptor::TYPE_GROUP) {
  1458. // Groups must be serialized with their original capitalization.
  1459. generator->PrintString(field->message_type()->name());
  1460. } else {
  1461. generator->PrintString(field->name());
  1462. }
  1463. }
  1464. void TextFormat::FastFieldValuePrinter::PrintMessageStart(
  1465. const Message& message, int field_index, int field_count,
  1466. bool single_line_mode, BaseTextGenerator* generator) const {
  1467. if (single_line_mode) {
  1468. generator->PrintLiteral(" { ");
  1469. } else {
  1470. generator->PrintLiteral(" {\n");
  1471. }
  1472. }
  1473. void TextFormat::FastFieldValuePrinter::PrintMessageEnd(
  1474. const Message& message, int field_index, int field_count,
  1475. bool single_line_mode, BaseTextGenerator* generator) const {
  1476. if (single_line_mode) {
  1477. generator->PrintLiteral("} ");
  1478. } else {
  1479. generator->PrintLiteral("}\n");
  1480. }
  1481. }
  1482. namespace {
  1483. // A legacy compatibility wrapper. Takes ownership of the delegate.
  1484. class FieldValuePrinterWrapper : public TextFormat::FastFieldValuePrinter {
  1485. public:
  1486. explicit FieldValuePrinterWrapper(
  1487. const TextFormat::FieldValuePrinter* delegate)
  1488. : delegate_(delegate) {}
  1489. void SetDelegate(const TextFormat::FieldValuePrinter* delegate) {
  1490. delegate_.reset(delegate);
  1491. }
  1492. void PrintBool(bool val,
  1493. TextFormat::BaseTextGenerator* generator) const override {
  1494. generator->PrintString(delegate_->PrintBool(val));
  1495. }
  1496. void PrintInt32(int32 val,
  1497. TextFormat::BaseTextGenerator* generator) const override {
  1498. generator->PrintString(delegate_->PrintInt32(val));
  1499. }
  1500. void PrintUInt32(uint32 val,
  1501. TextFormat::BaseTextGenerator* generator) const override {
  1502. generator->PrintString(delegate_->PrintUInt32(val));
  1503. }
  1504. void PrintInt64(int64 val,
  1505. TextFormat::BaseTextGenerator* generator) const override {
  1506. generator->PrintString(delegate_->PrintInt64(val));
  1507. }
  1508. void PrintUInt64(uint64 val,
  1509. TextFormat::BaseTextGenerator* generator) const override {
  1510. generator->PrintString(delegate_->PrintUInt64(val));
  1511. }
  1512. void PrintFloat(float val,
  1513. TextFormat::BaseTextGenerator* generator) const override {
  1514. generator->PrintString(delegate_->PrintFloat(val));
  1515. }
  1516. void PrintDouble(double val,
  1517. TextFormat::BaseTextGenerator* generator) const override {
  1518. generator->PrintString(delegate_->PrintDouble(val));
  1519. }
  1520. void PrintString(const std::string& val,
  1521. TextFormat::BaseTextGenerator* generator) const override {
  1522. generator->PrintString(delegate_->PrintString(val));
  1523. }
  1524. void PrintBytes(const std::string& val,
  1525. TextFormat::BaseTextGenerator* generator) const override {
  1526. generator->PrintString(delegate_->PrintBytes(val));
  1527. }
  1528. void PrintEnum(int32 val, const std::string& name,
  1529. TextFormat::BaseTextGenerator* generator) const override {
  1530. generator->PrintString(delegate_->PrintEnum(val, name));
  1531. }
  1532. void PrintFieldName(const Message& message, int field_index, int field_count,
  1533. const Reflection* reflection,
  1534. const FieldDescriptor* field,
  1535. TextFormat::BaseTextGenerator* generator) const override {
  1536. generator->PrintString(
  1537. delegate_->PrintFieldName(message, reflection, field));
  1538. }
  1539. void PrintFieldName(const Message& message, const Reflection* reflection,
  1540. const FieldDescriptor* field,
  1541. TextFormat::BaseTextGenerator* generator) const override {
  1542. generator->PrintString(
  1543. delegate_->PrintFieldName(message, reflection, field));
  1544. }
  1545. void PrintMessageStart(
  1546. const Message& message, int field_index, int field_count,
  1547. bool single_line_mode,
  1548. TextFormat::BaseTextGenerator* generator) const override {
  1549. generator->PrintString(delegate_->PrintMessageStart(
  1550. message, field_index, field_count, single_line_mode));
  1551. }
  1552. void PrintMessageEnd(
  1553. const Message& message, int field_index, int field_count,
  1554. bool single_line_mode,
  1555. TextFormat::BaseTextGenerator* generator) const override {
  1556. generator->PrintString(delegate_->PrintMessageEnd(
  1557. message, field_index, field_count, single_line_mode));
  1558. }
  1559. private:
  1560. std::unique_ptr<const TextFormat::FieldValuePrinter> delegate_;
  1561. };
  1562. // Our own specialization: for UTF8 escaped strings.
  1563. class FastFieldValuePrinterUtf8Escaping
  1564. : public TextFormat::FastFieldValuePrinter {
  1565. public:
  1566. void PrintString(const std::string& val,
  1567. TextFormat::BaseTextGenerator* generator) const override {
  1568. generator->PrintLiteral("\"");
  1569. generator->PrintString(strings::Utf8SafeCEscape(val));
  1570. generator->PrintLiteral("\"");
  1571. }
  1572. void PrintBytes(const std::string& val,
  1573. TextFormat::BaseTextGenerator* generator) const override {
  1574. return FastFieldValuePrinter::PrintString(val, generator);
  1575. }
  1576. };
  1577. } // namespace
  1578. TextFormat::Printer::Printer()
  1579. : initial_indent_level_(0),
  1580. single_line_mode_(false),
  1581. use_field_number_(false),
  1582. use_short_repeated_primitives_(false),
  1583. hide_unknown_fields_(false),
  1584. print_message_fields_in_index_order_(false),
  1585. expand_any_(false),
  1586. truncate_string_field_longer_than_(0LL),
  1587. finder_(nullptr) {
  1588. SetUseUtf8StringEscaping(false);
  1589. }
  1590. void TextFormat::Printer::SetUseUtf8StringEscaping(bool as_utf8) {
  1591. SetDefaultFieldValuePrinter(as_utf8 ? new FastFieldValuePrinterUtf8Escaping()
  1592. : new FastFieldValuePrinter());
  1593. }
  1594. void TextFormat::Printer::SetDefaultFieldValuePrinter(
  1595. const FieldValuePrinter* printer) {
  1596. default_field_value_printer_.reset(new FieldValuePrinterWrapper(printer));
  1597. }
  1598. void TextFormat::Printer::SetDefaultFieldValuePrinter(
  1599. const FastFieldValuePrinter* printer) {
  1600. default_field_value_printer_.reset(printer);
  1601. }
  1602. bool TextFormat::Printer::RegisterFieldValuePrinter(
  1603. const FieldDescriptor* field, const FieldValuePrinter* printer) {
  1604. if (field == nullptr || printer == nullptr) {
  1605. return false;
  1606. }
  1607. std::unique_ptr<FieldValuePrinterWrapper> wrapper(
  1608. new FieldValuePrinterWrapper(nullptr));
  1609. auto pair = custom_printers_.insert(std::make_pair(field, nullptr));
  1610. if (pair.second) {
  1611. wrapper->SetDelegate(printer);
  1612. pair.first->second = std::move(wrapper);
  1613. return true;
  1614. } else {
  1615. return false;
  1616. }
  1617. }
  1618. bool TextFormat::Printer::RegisterFieldValuePrinter(
  1619. const FieldDescriptor* field, const FastFieldValuePrinter* printer) {
  1620. if (field == nullptr || printer == nullptr) {
  1621. return false;
  1622. }
  1623. auto pair = custom_printers_.insert(std::make_pair(field, nullptr));
  1624. if (pair.second) {
  1625. pair.first->second.reset(printer);
  1626. return true;
  1627. } else {
  1628. return false;
  1629. }
  1630. }
  1631. bool TextFormat::Printer::RegisterMessagePrinter(
  1632. const Descriptor* descriptor, const MessagePrinter* printer) {
  1633. if (descriptor == nullptr || printer == nullptr) {
  1634. return false;
  1635. }
  1636. auto pair =
  1637. custom_message_printers_.insert(std::make_pair(descriptor, nullptr));
  1638. if (pair.second) {
  1639. pair.first->second.reset(printer);
  1640. return true;
  1641. } else {
  1642. return false;
  1643. }
  1644. }
  1645. bool TextFormat::Printer::PrintToString(const Message& message,
  1646. std::string* output) const {
  1647. GOOGLE_DCHECK(output) << "output specified is nullptr";
  1648. output->clear();
  1649. io::StringOutputStream output_stream(output);
  1650. return Print(message, &output_stream);
  1651. }
  1652. bool TextFormat::Printer::PrintUnknownFieldsToString(
  1653. const UnknownFieldSet& unknown_fields, std::string* output) const {
  1654. GOOGLE_DCHECK(output) << "output specified is nullptr";
  1655. output->clear();
  1656. io::StringOutputStream output_stream(output);
  1657. return PrintUnknownFields(unknown_fields, &output_stream);
  1658. }
  1659. bool TextFormat::Printer::Print(const Message& message,
  1660. io::ZeroCopyOutputStream* output) const {
  1661. TextGenerator generator(output, initial_indent_level_);
  1662. Print(message, &generator);
  1663. // Output false if the generator failed internally.
  1664. return !generator.failed();
  1665. }
  1666. bool TextFormat::Printer::PrintUnknownFields(
  1667. const UnknownFieldSet& unknown_fields,
  1668. io::ZeroCopyOutputStream* output) const {
  1669. TextGenerator generator(output, initial_indent_level_);
  1670. PrintUnknownFields(unknown_fields, &generator);
  1671. // Output false if the generator failed internally.
  1672. return !generator.failed();
  1673. }
  1674. namespace {
  1675. // Comparison functor for sorting FieldDescriptors by field index.
  1676. // Normal fields have higher precedence than extensions.
  1677. struct FieldIndexSorter {
  1678. bool operator()(const FieldDescriptor* left,
  1679. const FieldDescriptor* right) const {
  1680. if (left->is_extension() && right->is_extension()) {
  1681. return left->number() < right->number();
  1682. } else if (left->is_extension()) {
  1683. return false;
  1684. } else if (right->is_extension()) {
  1685. return true;
  1686. } else {
  1687. return left->index() < right->index();
  1688. }
  1689. }
  1690. };
  1691. } // namespace
  1692. bool TextFormat::Printer::PrintAny(const Message& message,
  1693. TextGenerator* generator) const {
  1694. const FieldDescriptor* type_url_field;
  1695. const FieldDescriptor* value_field;
  1696. if (!internal::GetAnyFieldDescriptors(message, &type_url_field,
  1697. &value_field)) {
  1698. return false;
  1699. }
  1700. const Reflection* reflection = message.GetReflection();
  1701. // Extract the full type name from the type_url field.
  1702. const std::string& type_url = reflection->GetString(message, type_url_field);
  1703. std::string url_prefix;
  1704. std::string full_type_name;
  1705. if (!internal::ParseAnyTypeUrl(type_url, &url_prefix, &full_type_name)) {
  1706. return false;
  1707. }
  1708. // Print the "value" in text.
  1709. const Descriptor* value_descriptor =
  1710. finder_ ? finder_->FindAnyType(message, url_prefix, full_type_name)
  1711. : DefaultFinderFindAnyType(message, url_prefix, full_type_name);
  1712. if (value_descriptor == nullptr) {
  1713. GOOGLE_LOG(WARNING) << "Proto type " << type_url << " not found";
  1714. return false;
  1715. }
  1716. DynamicMessageFactory factory;
  1717. std::unique_ptr<Message> value_message(
  1718. factory.GetPrototype(value_descriptor)->New());
  1719. std::string serialized_value = reflection->GetString(message, value_field);
  1720. if (!value_message->ParseFromString(serialized_value)) {
  1721. GOOGLE_LOG(WARNING) << type_url << ": failed to parse contents";
  1722. return false;
  1723. }
  1724. generator->PrintLiteral("[");
  1725. generator->PrintString(type_url);
  1726. generator->PrintLiteral("]");
  1727. const FastFieldValuePrinter* printer = GetFieldPrinter(value_field);
  1728. printer->PrintMessageStart(message, -1, 0, single_line_mode_, generator);
  1729. generator->Indent();
  1730. Print(*value_message, generator);
  1731. generator->Outdent();
  1732. printer->PrintMessageEnd(message, -1, 0, single_line_mode_, generator);
  1733. return true;
  1734. }
  1735. void TextFormat::Printer::Print(const Message& message,
  1736. TextGenerator* generator) const {
  1737. const Reflection* reflection = message.GetReflection();
  1738. if (!reflection) {
  1739. // This message does not provide any way to describe its structure.
  1740. // Parse it again in an UnknownFieldSet, and display this instead.
  1741. UnknownFieldSet unknown_fields;
  1742. {
  1743. std::string serialized = message.SerializeAsString();
  1744. io::ArrayInputStream input(serialized.data(), serialized.size());
  1745. unknown_fields.ParseFromZeroCopyStream(&input);
  1746. }
  1747. PrintUnknownFields(unknown_fields, generator);
  1748. return;
  1749. }
  1750. const Descriptor* descriptor = message.GetDescriptor();
  1751. auto itr = custom_message_printers_.find(descriptor);
  1752. if (itr != custom_message_printers_.end()) {
  1753. itr->second->Print(message, single_line_mode_, generator);
  1754. return;
  1755. }
  1756. if (descriptor->full_name() == internal::kAnyFullTypeName && expand_any_ &&
  1757. PrintAny(message, generator)) {
  1758. return;
  1759. }
  1760. std::vector<const FieldDescriptor*> fields;
  1761. if (descriptor->options().map_entry()) {
  1762. fields.push_back(descriptor->field(0));
  1763. fields.push_back(descriptor->field(1));
  1764. } else {
  1765. reflection->ListFields(message, &fields);
  1766. }
  1767. if (print_message_fields_in_index_order_) {
  1768. std::sort(fields.begin(), fields.end(), FieldIndexSorter());
  1769. }
  1770. for (int i = 0; i < fields.size(); i++) {
  1771. PrintField(message, reflection, fields[i], generator);
  1772. }
  1773. if (!hide_unknown_fields_) {
  1774. PrintUnknownFields(reflection->GetUnknownFields(message), generator);
  1775. }
  1776. }
  1777. void TextFormat::Printer::PrintFieldValueToString(const Message& message,
  1778. const FieldDescriptor* field,
  1779. int index,
  1780. std::string* output) const {
  1781. GOOGLE_DCHECK(output) << "output specified is nullptr";
  1782. output->clear();
  1783. io::StringOutputStream output_stream(output);
  1784. TextGenerator generator(&output_stream, initial_indent_level_);
  1785. PrintFieldValue(message, message.GetReflection(), field, index, &generator);
  1786. }
  1787. class MapEntryMessageComparator {
  1788. public:
  1789. explicit MapEntryMessageComparator(const Descriptor* descriptor)
  1790. : field_(descriptor->field(0)) {}
  1791. bool operator()(const Message* a, const Message* b) {
  1792. const Reflection* reflection = a->GetReflection();
  1793. switch (field_->cpp_type()) {
  1794. case FieldDescriptor::CPPTYPE_BOOL: {
  1795. bool first = reflection->GetBool(*a, field_);
  1796. bool second = reflection->GetBool(*b, field_);
  1797. return first < second;
  1798. }
  1799. case FieldDescriptor::CPPTYPE_INT32: {
  1800. int32 first = reflection->GetInt32(*a, field_);
  1801. int32 second = reflection->GetInt32(*b, field_);
  1802. return first < second;
  1803. }
  1804. case FieldDescriptor::CPPTYPE_INT64: {
  1805. int64 first = reflection->GetInt64(*a, field_);
  1806. int64 second = reflection->GetInt64(*b, field_);
  1807. return first < second;
  1808. }
  1809. case FieldDescriptor::CPPTYPE_UINT32: {
  1810. uint32 first = reflection->GetUInt32(*a, field_);
  1811. uint32 second = reflection->GetUInt32(*b, field_);
  1812. return first < second;
  1813. }
  1814. case FieldDescriptor::CPPTYPE_UINT64: {
  1815. uint64 first = reflection->GetUInt64(*a, field_);
  1816. uint64 second = reflection->GetUInt64(*b, field_);
  1817. return first < second;
  1818. }
  1819. case FieldDescriptor::CPPTYPE_STRING: {
  1820. std::string first = reflection->GetString(*a, field_);
  1821. std::string second = reflection->GetString(*b, field_);
  1822. return first < second;
  1823. }
  1824. default:
  1825. GOOGLE_LOG(DFATAL) << "Invalid key for map field.";
  1826. return true;
  1827. }
  1828. }
  1829. private:
  1830. const FieldDescriptor* field_;
  1831. };
  1832. namespace internal {
  1833. class MapFieldPrinterHelper {
  1834. public:
  1835. // DynamicMapSorter::Sort cannot be used because it enfores syncing with
  1836. // repeated field.
  1837. static bool SortMap(const Message& message, const Reflection* reflection,
  1838. const FieldDescriptor* field, MessageFactory* factory,
  1839. std::vector<const Message*>* sorted_map_field);
  1840. static void CopyKey(const MapKey& key, Message* message,
  1841. const FieldDescriptor* field_desc);
  1842. static void CopyValue(const MapValueRef& value, Message* message,
  1843. const FieldDescriptor* field_desc);
  1844. };
  1845. // Returns true if elements contained in sorted_map_field need to be released.
  1846. bool MapFieldPrinterHelper::SortMap(
  1847. const Message& message, const Reflection* reflection,
  1848. const FieldDescriptor* field, MessageFactory* factory,
  1849. std::vector<const Message*>* sorted_map_field) {
  1850. bool need_release = false;
  1851. const MapFieldBase& base = *reflection->GetMapData(message, field);
  1852. if (base.IsRepeatedFieldValid()) {
  1853. const RepeatedPtrField<Message>& map_field =
  1854. reflection->GetRepeatedPtrField<Message>(message, field);
  1855. for (int i = 0; i < map_field.size(); ++i) {
  1856. sorted_map_field->push_back(
  1857. const_cast<RepeatedPtrField<Message>*>(&map_field)->Mutable(i));
  1858. }
  1859. } else {
  1860. // TODO(teboring): For performance, instead of creating map entry message
  1861. // for each element, just store map keys and sort them.
  1862. const Descriptor* map_entry_desc = field->message_type();
  1863. const Message* prototype = factory->GetPrototype(map_entry_desc);
  1864. for (MapIterator iter =
  1865. reflection->MapBegin(const_cast<Message*>(&message), field);
  1866. iter != reflection->MapEnd(const_cast<Message*>(&message), field);
  1867. ++iter) {
  1868. Message* map_entry_message = prototype->New();
  1869. CopyKey(iter.GetKey(), map_entry_message, map_entry_desc->field(0));
  1870. CopyValue(iter.GetValueRef(), map_entry_message,
  1871. map_entry_desc->field(1));
  1872. sorted_map_field->push_back(map_entry_message);
  1873. }
  1874. need_release = true;
  1875. }
  1876. MapEntryMessageComparator comparator(field->message_type());
  1877. std::stable_sort(sorted_map_field->begin(), sorted_map_field->end(),
  1878. comparator);
  1879. return need_release;
  1880. }
  1881. void MapFieldPrinterHelper::CopyKey(const MapKey& key, Message* message,
  1882. const FieldDescriptor* field_desc) {
  1883. const Reflection* reflection = message->GetReflection();
  1884. switch (field_desc->cpp_type()) {
  1885. case FieldDescriptor::CPPTYPE_DOUBLE:
  1886. case FieldDescriptor::CPPTYPE_FLOAT:
  1887. case FieldDescriptor::CPPTYPE_ENUM:
  1888. case FieldDescriptor::CPPTYPE_MESSAGE:
  1889. GOOGLE_LOG(ERROR) << "Not supported.";
  1890. break;
  1891. case FieldDescriptor::CPPTYPE_STRING:
  1892. reflection->SetString(message, field_desc, key.GetStringValue());
  1893. return;
  1894. case FieldDescriptor::CPPTYPE_INT64:
  1895. reflection->SetInt64(message, field_desc, key.GetInt64Value());
  1896. return;
  1897. case FieldDescriptor::CPPTYPE_INT32:
  1898. reflection->SetInt32(message, field_desc, key.GetInt32Value());
  1899. return;
  1900. case FieldDescriptor::CPPTYPE_UINT64:
  1901. reflection->SetUInt64(message, field_desc, key.GetUInt64Value());
  1902. return;
  1903. case FieldDescriptor::CPPTYPE_UINT32:
  1904. reflection->SetUInt32(message, field_desc, key.GetUInt32Value());
  1905. return;
  1906. case FieldDescriptor::CPPTYPE_BOOL:
  1907. reflection->SetBool(message, field_desc, key.GetBoolValue());
  1908. return;
  1909. }
  1910. }
  1911. void MapFieldPrinterHelper::CopyValue(const MapValueRef& value,
  1912. Message* message,
  1913. const FieldDescriptor* field_desc) {
  1914. const Reflection* reflection = message->GetReflection();
  1915. switch (field_desc->cpp_type()) {
  1916. case FieldDescriptor::CPPTYPE_DOUBLE:
  1917. reflection->SetDouble(message, field_desc, value.GetDoubleValue());
  1918. return;
  1919. case FieldDescriptor::CPPTYPE_FLOAT:
  1920. reflection->SetFloat(message, field_desc, value.GetFloatValue());
  1921. return;
  1922. case FieldDescriptor::CPPTYPE_ENUM:
  1923. reflection->SetEnumValue(message, field_desc, value.GetEnumValue());
  1924. return;
  1925. case FieldDescriptor::CPPTYPE_MESSAGE: {
  1926. Message* sub_message = value.GetMessageValue().New();
  1927. sub_message->CopyFrom(value.GetMessageValue());
  1928. reflection->SetAllocatedMessage(message, sub_message, field_desc);
  1929. return;
  1930. }
  1931. case FieldDescriptor::CPPTYPE_STRING:
  1932. reflection->SetString(message, field_desc, value.GetStringValue());
  1933. return;
  1934. case FieldDescriptor::CPPTYPE_INT64:
  1935. reflection->SetInt64(message, field_desc, value.GetInt64Value());
  1936. return;
  1937. case FieldDescriptor::CPPTYPE_INT32:
  1938. reflection->SetInt32(message, field_desc, value.GetInt32Value());
  1939. return;
  1940. case FieldDescriptor::CPPTYPE_UINT64:
  1941. reflection->SetUInt64(message, field_desc, value.GetUInt64Value());
  1942. return;
  1943. case FieldDescriptor::CPPTYPE_UINT32:
  1944. reflection->SetUInt32(message, field_desc, value.GetUInt32Value());
  1945. return;
  1946. case FieldDescriptor::CPPTYPE_BOOL:
  1947. reflection->SetBool(message, field_desc, value.GetBoolValue());
  1948. return;
  1949. }
  1950. }
  1951. } // namespace internal
  1952. void TextFormat::Printer::PrintField(const Message& message,
  1953. const Reflection* reflection,
  1954. const FieldDescriptor* field,
  1955. TextGenerator* generator) const {
  1956. if (use_short_repeated_primitives_ && field->is_repeated() &&
  1957. field->cpp_type() != FieldDescriptor::CPPTYPE_STRING &&
  1958. field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
  1959. PrintShortRepeatedField(message, reflection, field, generator);
  1960. return;
  1961. }
  1962. int count = 0;
  1963. if (field->is_repeated()) {
  1964. count = reflection->FieldSize(message, field);
  1965. } else if (reflection->HasField(message, field) ||
  1966. field->containing_type()->options().map_entry()) {
  1967. count = 1;
  1968. }
  1969. DynamicMessageFactory factory;
  1970. std::vector<const Message*> sorted_map_field;
  1971. bool need_release = false;
  1972. bool is_map = field->is_map();
  1973. if (is_map) {
  1974. need_release = internal::MapFieldPrinterHelper::SortMap(
  1975. message, reflection, field, &factory, &sorted_map_field);
  1976. }
  1977. for (int j = 0; j < count; ++j) {
  1978. const int field_index = field->is_repeated() ? j : -1;
  1979. PrintFieldName(message, field_index, count, reflection, field, generator);
  1980. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  1981. const FastFieldValuePrinter* printer = GetFieldPrinter(field);
  1982. const Message& sub_message =
  1983. field->is_repeated()
  1984. ? (is_map ? *sorted_map_field[j]
  1985. : reflection->GetRepeatedMessage(message, field, j))
  1986. : reflection->GetMessage(message, field);
  1987. printer->PrintMessageStart(sub_message, field_index, count,
  1988. single_line_mode_, generator);
  1989. generator->Indent();
  1990. Print(sub_message, generator);
  1991. generator->Outdent();
  1992. printer->PrintMessageEnd(sub_message, field_index, count,
  1993. single_line_mode_, generator);
  1994. } else {
  1995. generator->PrintLiteral(": ");
  1996. // Write the field value.
  1997. PrintFieldValue(message, reflection, field, field_index, generator);
  1998. if (single_line_mode_) {
  1999. generator->PrintLiteral(" ");
  2000. } else {
  2001. generator->PrintLiteral("\n");
  2002. }
  2003. }
  2004. }
  2005. if (need_release) {
  2006. for (int j = 0; j < sorted_map_field.size(); ++j) {
  2007. delete sorted_map_field[j];
  2008. }
  2009. }
  2010. }
  2011. void TextFormat::Printer::PrintShortRepeatedField(
  2012. const Message& message, const Reflection* reflection,
  2013. const FieldDescriptor* field, TextGenerator* generator) const {
  2014. // Print primitive repeated field in short form.
  2015. int size = reflection->FieldSize(message, field);
  2016. PrintFieldName(message, /*field_index=*/-1, /*field_count=*/size, reflection,
  2017. field, generator);
  2018. generator->PrintLiteral(": [");
  2019. for (int i = 0; i < size; i++) {
  2020. if (i > 0) generator->PrintLiteral(", ");
  2021. PrintFieldValue(message, reflection, field, i, generator);
  2022. }
  2023. if (single_line_mode_) {
  2024. generator->PrintLiteral("] ");
  2025. } else {
  2026. generator->PrintLiteral("]\n");
  2027. }
  2028. }
  2029. void TextFormat::Printer::PrintFieldName(const Message& message,
  2030. int field_index, int field_count,
  2031. const Reflection* reflection,
  2032. const FieldDescriptor* field,
  2033. TextGenerator* generator) const {
  2034. // if use_field_number_ is true, prints field number instead
  2035. // of field name.
  2036. if (use_field_number_) {
  2037. generator->PrintString(StrCat(field->number()));
  2038. return;
  2039. }
  2040. const FastFieldValuePrinter* printer = GetFieldPrinter(field);
  2041. printer->PrintFieldName(message, field_index, field_count, reflection, field,
  2042. generator);
  2043. }
  2044. void TextFormat::Printer::PrintFieldValue(const Message& message,
  2045. const Reflection* reflection,
  2046. const FieldDescriptor* field,
  2047. int index,
  2048. TextGenerator* generator) const {
  2049. GOOGLE_DCHECK(field->is_repeated() || (index == -1))
  2050. << "Index must be -1 for non-repeated fields";
  2051. const FastFieldValuePrinter* printer = GetFieldPrinter(field);
  2052. switch (field->cpp_type()) {
  2053. #define OUTPUT_FIELD(CPPTYPE, METHOD) \
  2054. case FieldDescriptor::CPPTYPE_##CPPTYPE: \
  2055. printer->Print##METHOD( \
  2056. field->is_repeated() \
  2057. ? reflection->GetRepeated##METHOD(message, field, index) \
  2058. : reflection->Get##METHOD(message, field), \
  2059. generator); \
  2060. break
  2061. OUTPUT_FIELD(INT32, Int32);
  2062. OUTPUT_FIELD(INT64, Int64);
  2063. OUTPUT_FIELD(UINT32, UInt32);
  2064. OUTPUT_FIELD(UINT64, UInt64);
  2065. OUTPUT_FIELD(FLOAT, Float);
  2066. OUTPUT_FIELD(DOUBLE, Double);
  2067. OUTPUT_FIELD(BOOL, Bool);
  2068. #undef OUTPUT_FIELD
  2069. case FieldDescriptor::CPPTYPE_STRING: {
  2070. std::string scratch;
  2071. const std::string& value =
  2072. field->is_repeated()
  2073. ? reflection->GetRepeatedStringReference(message, field, index,
  2074. &scratch)
  2075. : reflection->GetStringReference(message, field, &scratch);
  2076. const std::string* value_to_print = &value;
  2077. std::string truncated_value;
  2078. if (truncate_string_field_longer_than_ > 0 &&
  2079. truncate_string_field_longer_than_ < value.size()) {
  2080. truncated_value = value.substr(0, truncate_string_field_longer_than_) +
  2081. "...<truncated>...";
  2082. value_to_print = &truncated_value;
  2083. }
  2084. if (field->type() == FieldDescriptor::TYPE_STRING) {
  2085. printer->PrintString(*value_to_print, generator);
  2086. } else {
  2087. GOOGLE_DCHECK_EQ(field->type(), FieldDescriptor::TYPE_BYTES);
  2088. printer->PrintBytes(*value_to_print, generator);
  2089. }
  2090. break;
  2091. }
  2092. case FieldDescriptor::CPPTYPE_ENUM: {
  2093. int enum_value =
  2094. field->is_repeated()
  2095. ? reflection->GetRepeatedEnumValue(message, field, index)
  2096. : reflection->GetEnumValue(message, field);
  2097. const EnumValueDescriptor* enum_desc =
  2098. field->enum_type()->FindValueByNumber(enum_value);
  2099. if (enum_desc != nullptr) {
  2100. printer->PrintEnum(enum_value, enum_desc->name(), generator);
  2101. } else {
  2102. // Ordinarily, enum_desc should not be null, because proto2 has the
  2103. // invariant that set enum field values must be in-range, but with the
  2104. // new integer-based API for enums (or the RepeatedField<int> loophole),
  2105. // it is possible for the user to force an unknown integer value. So we
  2106. // simply use the integer value itself as the enum value name in this
  2107. // case.
  2108. printer->PrintEnum(enum_value, StringPrintf("%d", enum_value),
  2109. generator);
  2110. }
  2111. break;
  2112. }
  2113. case FieldDescriptor::CPPTYPE_MESSAGE:
  2114. Print(field->is_repeated()
  2115. ? reflection->GetRepeatedMessage(message, field, index)
  2116. : reflection->GetMessage(message, field),
  2117. generator);
  2118. break;
  2119. }
  2120. }
  2121. /* static */ bool TextFormat::Print(const Message& message,
  2122. io::ZeroCopyOutputStream* output) {
  2123. return Printer().Print(message, output);
  2124. }
  2125. /* static */ bool TextFormat::PrintUnknownFields(
  2126. const UnknownFieldSet& unknown_fields, io::ZeroCopyOutputStream* output) {
  2127. return Printer().PrintUnknownFields(unknown_fields, output);
  2128. }
  2129. /* static */ bool TextFormat::PrintToString(const Message& message,
  2130. std::string* output) {
  2131. return Printer().PrintToString(message, output);
  2132. }
  2133. /* static */ bool TextFormat::PrintUnknownFieldsToString(
  2134. const UnknownFieldSet& unknown_fields, std::string* output) {
  2135. return Printer().PrintUnknownFieldsToString(unknown_fields, output);
  2136. }
  2137. /* static */ void TextFormat::PrintFieldValueToString(
  2138. const Message& message, const FieldDescriptor* field, int index,
  2139. std::string* output) {
  2140. return Printer().PrintFieldValueToString(message, field, index, output);
  2141. }
  2142. /* static */ bool TextFormat::ParseFieldValueFromString(
  2143. const std::string& input, const FieldDescriptor* field, Message* message) {
  2144. return Parser().ParseFieldValueFromString(input, field, message);
  2145. }
  2146. void TextFormat::Printer::PrintUnknownFields(
  2147. const UnknownFieldSet& unknown_fields, TextGenerator* generator) const {
  2148. for (int i = 0; i < unknown_fields.field_count(); i++) {
  2149. const UnknownField& field = unknown_fields.field(i);
  2150. std::string field_number = StrCat(field.number());
  2151. switch (field.type()) {
  2152. case UnknownField::TYPE_VARINT:
  2153. generator->PrintString(field_number);
  2154. generator->PrintLiteral(": ");
  2155. generator->PrintString(StrCat(field.varint()));
  2156. if (single_line_mode_) {
  2157. generator->PrintLiteral(" ");
  2158. } else {
  2159. generator->PrintLiteral("\n");
  2160. }
  2161. break;
  2162. case UnknownField::TYPE_FIXED32: {
  2163. generator->PrintString(field_number);
  2164. generator->PrintLiteral(": 0x");
  2165. generator->PrintString(
  2166. StrCat(strings::Hex(field.fixed32(), strings::ZERO_PAD_8)));
  2167. if (single_line_mode_) {
  2168. generator->PrintLiteral(" ");
  2169. } else {
  2170. generator->PrintLiteral("\n");
  2171. }
  2172. break;
  2173. }
  2174. case UnknownField::TYPE_FIXED64: {
  2175. generator->PrintString(field_number);
  2176. generator->PrintLiteral(": 0x");
  2177. generator->PrintString(
  2178. StrCat(strings::Hex(field.fixed64(), strings::ZERO_PAD_16)));
  2179. if (single_line_mode_) {
  2180. generator->PrintLiteral(" ");
  2181. } else {
  2182. generator->PrintLiteral("\n");
  2183. }
  2184. break;
  2185. }
  2186. case UnknownField::TYPE_LENGTH_DELIMITED: {
  2187. generator->PrintString(field_number);
  2188. const std::string& value = field.length_delimited();
  2189. UnknownFieldSet embedded_unknown_fields;
  2190. if (!value.empty() && embedded_unknown_fields.ParseFromString(value)) {
  2191. // This field is parseable as a Message.
  2192. // So it is probably an embedded message.
  2193. if (single_line_mode_) {
  2194. generator->PrintLiteral(" { ");
  2195. } else {
  2196. generator->PrintLiteral(" {\n");
  2197. generator->Indent();
  2198. }
  2199. PrintUnknownFields(embedded_unknown_fields, generator);
  2200. if (single_line_mode_) {
  2201. generator->PrintLiteral("} ");
  2202. } else {
  2203. generator->Outdent();
  2204. generator->PrintLiteral("}\n");
  2205. }
  2206. } else {
  2207. // This field is not parseable as a Message.
  2208. // So it is probably just a plain string.
  2209. generator->PrintLiteral(": \"");
  2210. generator->PrintString(CEscape(value));
  2211. if (single_line_mode_) {
  2212. generator->PrintLiteral("\" ");
  2213. } else {
  2214. generator->PrintLiteral("\"\n");
  2215. }
  2216. }
  2217. break;
  2218. }
  2219. case UnknownField::TYPE_GROUP:
  2220. generator->PrintString(field_number);
  2221. if (single_line_mode_) {
  2222. generator->PrintLiteral(" { ");
  2223. } else {
  2224. generator->PrintLiteral(" {\n");
  2225. generator->Indent();
  2226. }
  2227. PrintUnknownFields(field.group(), generator);
  2228. if (single_line_mode_) {
  2229. generator->PrintLiteral("} ");
  2230. } else {
  2231. generator->Outdent();
  2232. generator->PrintLiteral("}\n");
  2233. }
  2234. break;
  2235. }
  2236. }
  2237. }
  2238. } // namespace protobuf
  2239. } // namespace google