Down integrate to Github (#5839)

* Down integrate to github
pull/5848/head
Hao Nguyen 6 years ago committed by GitHub
parent f5e8ee41dd
commit d0f91c863a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      Makefile.am
  2. 11
      conformance/text_format_conformance_suite.cc
  3. 3
      conformance/text_format_failure_list_python.txt
  4. 3
      java/core/generate-test-sources-build.xml
  5. 7
      java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
  6. 119
      java/core/src/main/java/com/google/protobuf/Descriptors.java
  7. 13
      java/core/src/main/java/com/google/protobuf/MessageReflection.java
  8. 94
      java/core/src/main/java/com/google/protobuf/RopeByteString.java
  9. 83
      java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
  10. 15
      java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java
  11. 4
      java/core/src/test/java/com/google/protobuf/ServiceTest.java
  12. 62
      java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java
  13. 33
      java/core/src/test/proto/com/google/protobuf/proto2_unknown_enum_values.proto
  14. 8
      js/compatibility_tests/v3.1.0/message_test.js
  15. 97
      js/message.js
  16. 59
      js/message_test.js
  17. 10
      js/test.proto
  18. 2
      python/google/protobuf/internal/enum_type_wrapper.py
  19. 7
      python/google/protobuf/internal/json_format_test.py
  20. 21
      python/google/protobuf/internal/message_test.py
  21. 8
      python/google/protobuf/internal/text_format_test.py
  22. 38
      python/google/protobuf/internal/type_checkers.py
  23. 8
      python/google/protobuf/pyext/descriptor_database.h
  24. 2
      python/google/protobuf/pyext/descriptor_pool.h
  25. 3
      python/google/protobuf/pyext/message.cc
  26. 4
      python/google/protobuf/pyext/message.h
  27. 4
      python/google/protobuf/pyext/proto2_api_test.proto
  28. 8
      src/google/protobuf/any.cc
  29. 2
      src/google/protobuf/any.h
  30. 219
      src/google/protobuf/any.pb.cc
  31. 193
      src/google/protobuf/any.pb.h
  32. 12
      src/google/protobuf/any_lite.cc
  33. 4
      src/google/protobuf/any_test.cc
  34. 769
      src/google/protobuf/api.pb.cc
  35. 648
      src/google/protobuf/api.pb.h
  36. 25
      src/google/protobuf/arena.h
  37. 166
      src/google/protobuf/arena_unittest.cc
  38. 29
      src/google/protobuf/arenastring.h
  39. 50
      src/google/protobuf/arenastring_unittest.cc
  40. 31
      src/google/protobuf/compiler/annotation_test_util.cc
  41. 3
      src/google/protobuf/compiler/annotation_test_util.h
  42. 28
      src/google/protobuf/compiler/code_generator.cc
  43. 306
      src/google/protobuf/compiler/command_line_interface.cc
  44. 20
      src/google/protobuf/compiler/command_line_interface.h
  45. 243
      src/google/protobuf/compiler/command_line_interface_unittest.cc
  46. 41
      src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
  47. 23
      src/google/protobuf/compiler/cpp/cpp_enum.cc
  48. 3
      src/google/protobuf/compiler/cpp/cpp_enum.h
  49. 20
      src/google/protobuf/compiler/cpp/cpp_enum_field.cc
  50. 14
      src/google/protobuf/compiler/cpp/cpp_extension.cc
  51. 11
      src/google/protobuf/compiler/cpp/cpp_field.cc
  52. 5
      src/google/protobuf/compiler/cpp/cpp_field.h
  53. 186
      src/google/protobuf/compiler/cpp/cpp_file.cc
  54. 14
      src/google/protobuf/compiler/cpp/cpp_file.h
  55. 12
      src/google/protobuf/compiler/cpp/cpp_generator.cc
  56. 6
      src/google/protobuf/compiler/cpp/cpp_generator.h
  57. 280
      src/google/protobuf/compiler/cpp/cpp_helpers.cc
  58. 131
      src/google/protobuf/compiler/cpp/cpp_helpers.h
  59. 12
      src/google/protobuf/compiler/cpp/cpp_map_field.cc
  60. 279
      src/google/protobuf/compiler/cpp/cpp_message.cc
  61. 13
      src/google/protobuf/compiler/cpp/cpp_message_field.cc
  62. 14
      src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc
  63. 2
      src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
  64. 32
      src/google/protobuf/compiler/cpp/cpp_service.cc
  65. 1
      src/google/protobuf/compiler/cpp/cpp_service.h
  66. 244
      src/google/protobuf/compiler/cpp/cpp_string_field.cc
  67. 167
      src/google/protobuf/compiler/cpp/cpp_unittest.inc
  68. 20
      src/google/protobuf/compiler/cpp/metadata_test.cc
  69. 2
      src/google/protobuf/compiler/csharp/csharp_generator.h
  70. 95
      src/google/protobuf/compiler/importer.cc
  71. 17
      src/google/protobuf/compiler/importer.h
  72. 56
      src/google/protobuf/compiler/importer_unittest.cc
  73. 12
      src/google/protobuf/compiler/java/java_context.cc
  74. 21
      src/google/protobuf/compiler/java/java_doc_comment.cc
  75. 8
      src/google/protobuf/compiler/java/java_enum.cc
  76. 12
      src/google/protobuf/compiler/java/java_enum_field.cc
  77. 12
      src/google/protobuf/compiler/java/java_enum_field_lite.cc
  78. 6
      src/google/protobuf/compiler/java/java_enum_lite.cc
  79. 11
      src/google/protobuf/compiler/java/java_extension.cc
  80. 8
      src/google/protobuf/compiler/java/java_extension.h
  81. 2
      src/google/protobuf/compiler/java/java_extension_lite.cc
  82. 8
      src/google/protobuf/compiler/java/java_field.cc
  83. 62
      src/google/protobuf/compiler/java/java_file.cc
  84. 17
      src/google/protobuf/compiler/java/java_generator.cc
  85. 6
      src/google/protobuf/compiler/java/java_generator.h
  86. 135
      src/google/protobuf/compiler/java/java_helpers.cc
  87. 17
      src/google/protobuf/compiler/java/java_helpers.h
  88. 21
      src/google/protobuf/compiler/java/java_map_field.cc
  89. 19
      src/google/protobuf/compiler/java/java_map_field_lite.cc
  90. 16
      src/google/protobuf/compiler/java/java_message.cc
  91. 6
      src/google/protobuf/compiler/java/java_message_builder.cc
  92. 2
      src/google/protobuf/compiler/java/java_message_builder_lite.cc
  93. 12
      src/google/protobuf/compiler/java/java_message_field.cc
  94. 12
      src/google/protobuf/compiler/java/java_message_field_lite.cc
  95. 10
      src/google/protobuf/compiler/java/java_message_lite.cc
  96. 121
      src/google/protobuf/compiler/java/java_name_resolver.cc
  97. 26
      src/google/protobuf/compiler/java/java_name_resolver.h
  98. 16
      src/google/protobuf/compiler/java/java_plugin_unittest.cc
  99. 11
      src/google/protobuf/compiler/java/java_primitive_field.cc
  100. 13
      src/google/protobuf/compiler/java/java_primitive_field_lite.cc
  101. Some files were not shown because too many files have changed in this diff Show More

@ -371,6 +371,7 @@ java_EXTRA_DIST=
java/core/src/test/proto/com/google/protobuf/outer_class_name_test.proto \
java/core/src/test/proto/com/google/protobuf/outer_class_name_test2.proto \
java/core/src/test/proto/com/google/protobuf/outer_class_name_test3.proto \
java/core/src/test/proto/com/google/protobuf/proto2_unknown_enum_values.proto \
java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto \
java/core/src/test/proto/com/google/protobuf/test_check_utf8.proto \
java/core/src/test/proto/com/google/protobuf/test_check_utf8_size.proto \

@ -221,11 +221,12 @@ void TextFormatConformanceTestSuite::RunSuiteImpl() {
"optional_float: 4294967296");
RunValidTextFormatTest("FloatFieldLargerThanInt64", REQUIRED,
"optional_float: 9223372036854775808");
ExpectParseFailure("FloatFieldTooLarge", REQUIRED,
"optional_int32: 3.4028235e+39");
ExpectParseFailure("FloatFieldTooSmall", REQUIRED,
"optional_int32: 1.17549e-39");
RunValidTextFormatTest("FloatFieldTooLarge", REQUIRED,
"optional_float: 3.4028235e+39");
RunValidTextFormatTest("FloatFieldTooSmall", REQUIRED,
"optional_float: 1.17549e-39");
RunValidTextFormatTest("FloatFieldLargerThanUint64", REQUIRED,
"optional_float: 18446744073709551616");
// Group fields
RunValidTextFormatTestProto2("GroupFieldNoColon", REQUIRED,

@ -0,0 +1,3 @@
# This is the list of text format conformance tests that are known to fail right
# now.
# TODO: These should be fixed.

@ -30,7 +30,8 @@
<arg value="${test.proto.dir}/com/google/protobuf/non_nested_extension_lite.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/outer_class_name_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/outer_class_name_test2.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/outer_class_name_test3.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/outer_class_name_test3.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/proto2_unknown_enum_values.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/test_bad_identifiers.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/test_check_utf8.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/test_check_utf8_size.proto"/>

@ -32,6 +32,7 @@ package com.google.protobuf;
import static com.google.protobuf.WireFormat.FIXED32_SIZE;
import static com.google.protobuf.WireFormat.FIXED64_SIZE;
import static com.google.protobuf.WireFormat.MAX_VARINT32_SIZE;
import static com.google.protobuf.WireFormat.MAX_VARINT_SIZE;
import static java.lang.Math.max;
@ -1263,7 +1264,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public final void writeUInt32NoTag(int value) throws IOException {
if (HAS_UNSAFE_ARRAY_OPERATIONS && spaceLeft() >= MAX_VARINT_SIZE) {
if (HAS_UNSAFE_ARRAY_OPERATIONS && spaceLeft() >= MAX_VARINT32_SIZE) {
while (true) {
if ((value & ~0x7F) == 0) {
UnsafeUtil.putByte(buffer, position++, (byte) value);
@ -2447,7 +2448,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeUInt32NoTag(int value) throws IOException {
flushIfNotAvailable(MAX_VARINT_SIZE);
flushIfNotAvailable(MAX_VARINT32_SIZE);
bufferUInt32NoTag(value);
}
@ -2750,7 +2751,7 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeUInt32NoTag(int value) throws IOException {
flushIfNotAvailable(MAX_VARINT_SIZE);
flushIfNotAvailable(MAX_VARINT32_SIZE);
bufferUInt32NoTag(value);
}

@ -314,14 +314,7 @@ public final class Descriptors {
return result;
}
/**
* This method is to be called by generated code only. It is equivalent to {@code buildFrom}
* except that the {@code FileDescriptorProto} is encoded in protocol buffer wire format.
*/
public static void internalBuildGeneratedFileFrom(
final String[] descriptorDataParts,
final FileDescriptor[] dependencies,
final InternalDescriptorAssigner descriptorAssigner) {
private static byte[] latin1Cat(final String[] strings) {
// Hack: We can't embed a raw byte array inside generated Java code
// (at least, not efficiently), but we can embed Strings. So, the
// protocol compiler embeds the FileDescriptorProto as a giant
@ -330,16 +323,45 @@ public final class Descriptors {
// characters, each one representing a byte of the FileDescriptorProto's
// serialized form. So, if we convert it to bytes in ISO-8859-1, we
// should get the original bytes that we want.
// descriptorData may contain multiple strings in order to get around the
// Java 64k string literal limit.
// Literal strings are limited to 64k, so it may be split into multiple strings.
if (strings.length == 1) {
return strings[0].getBytes(Internal.ISO_8859_1);
}
StringBuilder descriptorData = new StringBuilder();
for (String part : descriptorDataParts) {
for (String part : strings) {
descriptorData.append(part);
}
return descriptorData.toString().getBytes(Internal.ISO_8859_1);
}
final byte[] descriptorBytes;
descriptorBytes = descriptorData.toString().getBytes(Internal.ISO_8859_1);
private static FileDescriptor[] findDescriptors(
final Class<?> descriptorOuterClass,
final String[] dependencyClassNames,
final String[] dependencyFileNames) {
List<FileDescriptor> descriptors = new ArrayList<FileDescriptor>();
for (int i = 0; i < dependencyClassNames.length; i++) {
try {
Class<?> clazz = descriptorOuterClass.getClassLoader().loadClass(dependencyClassNames[i]);
descriptors.add((FileDescriptor) clazz.getField("descriptor").get(null));
} catch (Exception e) {
// We allow unknown dependencies by default. If a dependency cannot
// be found we only generate a warning.
logger.warning("Descriptors for \"" + dependencyFileNames[i] + "\" can not be found.");
}
}
return descriptors.toArray(new FileDescriptor[0]);
}
/**
* This method is for backward compatibility with generated code which passed an
* InternalDescriptorAssigner.
*/
@Deprecated
public static void internalBuildGeneratedFileFrom(
final String[] descriptorDataParts,
final FileDescriptor[] dependencies,
final InternalDescriptorAssigner descriptorAssigner) {
final byte[] descriptorBytes = latin1Cat(descriptorDataParts);
FileDescriptorProto proto;
try {
@ -375,29 +397,61 @@ public final class Descriptors {
}
/**
* This method is to be called by generated code only. It uses Java reflection to load the
* dependencies' descriptors.
* This method is to be called by generated code only. It is equivalent to {@code buildFrom}
* except that the {@code FileDescriptorProto} is encoded in protocol buffer wire format.
*/
public static FileDescriptor internalBuildGeneratedFileFrom(
final String[] descriptorDataParts,
final FileDescriptor[] dependencies) {
final byte[] descriptorBytes = latin1Cat(descriptorDataParts);
FileDescriptorProto proto;
try {
proto = FileDescriptorProto.parseFrom(descriptorBytes);
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(
"Failed to parse protocol buffer descriptor for generated code.", e);
}
try {
// When building descriptors for generated code, we allow unknown
// dependencies by default.
return buildFrom(proto, dependencies, true);
} catch (DescriptorValidationException e) {
throw new IllegalArgumentException(
"Invalid embedded descriptor for \"" + proto.getName() + "\".", e);
}
}
/**
* This method is for backward compatibility with generated code which passed an
* InternalDescriptorAssigner.
*/
@Deprecated
public static void internalBuildGeneratedFileFrom(
final String[] descriptorDataParts,
final Class<?> descriptorOuterClass,
final String[] dependencies,
final String[] dependencyClassNames,
final String[] dependencyFileNames,
final InternalDescriptorAssigner descriptorAssigner) {
List<FileDescriptor> descriptors = new ArrayList<FileDescriptor>();
for (int i = 0; i < dependencies.length; i++) {
try {
Class<?> clazz = descriptorOuterClass.getClassLoader().loadClass(dependencies[i]);
descriptors.add((FileDescriptor) clazz.getField("descriptor").get(null));
} catch (Exception e) {
// We allow unknown dependencies by default. If a dependency cannot
// be found we only generate a warning.
logger.warning("Descriptors for \"" + dependencyFileNames[i] + "\" can not be found.");
}
}
FileDescriptor[] descriptorArray = new FileDescriptor[descriptors.size()];
descriptors.toArray(descriptorArray);
internalBuildGeneratedFileFrom(descriptorDataParts, descriptorArray, descriptorAssigner);
FileDescriptor[] dependencies = findDescriptors(
descriptorOuterClass, dependencyClassNames, dependencyFileNames);
internalBuildGeneratedFileFrom(
descriptorDataParts, dependencies, descriptorAssigner);
}
/**
* This method is to be called by generated code only. It uses Java reflection to load the
* dependencies' descriptors.
*/
public static FileDescriptor internalBuildGeneratedFileFrom(
final String[] descriptorDataParts,
final Class<?> descriptorOuterClass,
final String[] dependencyClassNames,
final String[] dependencyFileNames) {
FileDescriptor[] dependencies = findDescriptors(
descriptorOuterClass, dependencyClassNames, dependencyFileNames);
return internalBuildGeneratedFileFrom(descriptorDataParts, dependencies);
}
/**
@ -427,7 +481,10 @@ public final class Descriptors {
* extensions which might be used in the descriptor -- that is, extensions of the various
* "Options" messages defined in descriptor.proto. The callback may also return null to indicate
* that no extensions are used in the descriptor.
*
* This interface is deprecated. Use the return value of internalBuildGeneratedFrom() instead.
*/
@Deprecated
public interface InternalDescriptorAssigner {
ExtensionRegistry assignDescriptors(FileDescriptor root);
}

@ -804,12 +804,15 @@ class MessageReflection {
field, field.getEnumType().findValueByNumberCreatingIfUnknown(rawValue));
} else {
final Object value = field.getEnumType().findValueByNumber(rawValue);
// If the number isn't recognized as a valid value for this enum,
// add it to the unknown fields.
if (value == null) {
// If the number isn't recognized as a valid value for this
// enum, drop it (don't even add it to unknownFields).
return true;
if (unknownFields != null) {
unknownFields.mergeVarintField(fieldNumber, rawValue);
}
} else {
target.addRepeatedField(field, value);
}
target.addRepeatedField(field, value);
}
}
} else {
@ -841,7 +844,7 @@ class MessageReflection {
} else {
value = field.getEnumType().findValueByNumber(rawValue);
// If the number isn't recognized as a valid value for this enum,
// drop it.
// add it to the unknown fields.
if (value == null) {
if (unknownFields != null) {
unknownFields.mergeVarintField(fieldNumber, rawValue);

@ -77,36 +77,58 @@ final class RopeByteString extends ByteString {
* in deeper binary trees.
*
* <p>For 32-bit integers, this array has length 46.
*
* <p>The correctness of this constant array is validated in tests.
*/
private static final int[] minLengthByDepth;
static {
// Dynamically generate the list of Fibonacci numbers the first time this
// class is accessed.
List<Integer> numbers = new ArrayList<Integer>();
// we skip the first Fibonacci number (1). So instead of: 1 1 2 3 5 8 ...
// we have: 1 2 3 5 8 ...
int f1 = 1;
int f2 = 1;
// get all the values until we roll over.
while (f2 > 0) {
numbers.add(f2);
int temp = f1 + f2;
f1 = f2;
f2 = temp;
}
// we include this here so that we can index this array to [x + 1] in the
// loops below.
numbers.add(Integer.MAX_VALUE);
minLengthByDepth = new int[numbers.size()];
for (int i = 0; i < minLengthByDepth.length; i++) {
// unbox all the values
minLengthByDepth[i] = numbers.get(i);
}
}
static final int[] minLengthByDepth = {
1,
1,
2,
3,
5,
8,
13,
21,
34,
55,
89,
144,
233,
377,
610,
987,
1597,
2584,
4181,
6765,
10946,
17711,
28657,
46368,
75025,
121393,
196418,
317811,
514229,
832040,
1346269,
2178309,
3524578,
5702887,
9227465,
14930352,
24157817,
39088169,
63245986,
102334155,
165580141,
267914296,
433494437,
701408733,
1134903170,
1836311903,
Integer.MAX_VALUE
};
private final int totalLength;
private final ByteString left;
@ -686,11 +708,19 @@ final class RopeByteString extends ByteString {
* <p>This iterator is used to implement {@link RopeByteString#equalsFragments(ByteString)}.
*/
private static final class PieceIterator implements Iterator<LeafByteString> {
private final ArrayDeque<RopeByteString> breadCrumbs = new ArrayDeque<>();
private final ArrayDeque<RopeByteString> breadCrumbs;
private LeafByteString next;
private PieceIterator(ByteString root) {
next = getLeafByLeft(root);
if (root instanceof RopeByteString) {
RopeByteString rbs = (RopeByteString) root;
breadCrumbs = new ArrayDeque<>(rbs.getTreeDepth());
breadCrumbs.push(rbs);
next = getLeafByLeft(rbs.left);
} else {
breadCrumbs = null;
next = (LeafByteString) root;
}
}
private LeafByteString getLeafByLeft(ByteString root) {
@ -707,7 +737,7 @@ final class RopeByteString extends ByteString {
while (true) {
// Almost always, we go through this loop exactly once. However, if
// we discover an empty string in the rope, we toss it and try again.
if (breadCrumbs.isEmpty()) {
if (breadCrumbs == null || breadCrumbs.isEmpty()) {
return null;
} else {
LeafByteString result = getLeafByLeft(breadCrumbs.pop().right);

@ -48,7 +48,7 @@ final class UnsafeUtil {
supportsUnsafeByteBufferOperations();
private static final boolean HAS_UNSAFE_ARRAY_OPERATIONS = supportsUnsafeArrayOperations();
private static final long BYTE_ARRAY_BASE_OFFSET = arrayBaseOffset(byte[].class);
static final long BYTE_ARRAY_BASE_OFFSET = arrayBaseOffset(byte[].class);
// Micro-optimization: we can assume a scale of 1 and skip the multiply
// private static final long BYTE_ARRAY_INDEX_SCALE = 1;
@ -72,6 +72,13 @@ final class UnsafeUtil {
private static final long BUFFER_ADDRESS_OFFSET = fieldOffset(bufferAddressField());
private static final int STRIDE = 8;
private static final int STRIDE_ALIGNMENT_MASK = STRIDE - 1;
private static final int BYTE_ARRAY_ALIGNMENT =
(int) (BYTE_ARRAY_BASE_OFFSET & STRIDE_ALIGNMENT_MASK);
static final boolean IS_BIG_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
private UnsafeUtil() {}
static boolean hasUnsafeArrayOperations() {
@ -382,6 +389,80 @@ final class UnsafeUtil {
return field != null && field.getType() == long.class ? field : null;
}
/**
* Returns the index of the first byte where left and right differ, in the range [0, 8]. If {@code
* left == right}, the result will be 8, otherwise less than 8.
*
* <p>This counts from the *first* byte, which may be the most or least significant byte depending
* on the system endianness.
*/
private static int firstDifferingByteIndexNativeEndian(long left, long right) {
int n =
IS_BIG_ENDIAN
? Long.numberOfLeadingZeros(left ^ right)
: Long.numberOfTrailingZeros(left ^ right);
return n >> 3;
}
/**
* Returns the lowest {@code index} such that {@code 0 <= index < length} and {@code left[leftOff
* + index] != right[rightOff + index]}. If no such value exists -- if {@code left} and {@code
* right} match up to {@code length} bytes from their respective offsets -- returns -1.
*
* <p>{@code leftOff + length} must be less than or equal to {@code left.length}, and the same for
* {@code right}.
*/
static int mismatch(byte[] left, int leftOff, byte[] right, int rightOff, int length) {
if (leftOff < 0
|| rightOff < 0
|| length < 0
|| leftOff + length > left.length
|| rightOff + length > right.length) {
throw new IndexOutOfBoundsException();
}
int index = 0;
if (HAS_UNSAFE_ARRAY_OPERATIONS) {
int leftAlignment = (BYTE_ARRAY_ALIGNMENT + leftOff) & STRIDE_ALIGNMENT_MASK;
// Most CPUs handle getting chunks of bytes better on addresses that are a multiple of 4
// or 8.
// We walk one byte at a time until the left address, at least, is a multiple of 8.
// If the right address is, too, so much the better.
for (;
index < length && (leftAlignment & STRIDE_ALIGNMENT_MASK) != 0;
index++, leftAlignment++) {
if (left[leftOff + index] != right[rightOff + index]) {
return index;
}
}
// Stride! Grab eight bytes at a time from left and right and check them for equality.
int strideLength = ((length - index) & ~STRIDE_ALIGNMENT_MASK) + index;
// strideLength is the point where we want to stop striding: it differs from index by
// a multiple of STRIDE, and it's the largest such number <= length.
for (; index < strideLength; index += STRIDE) {
long leftLongWord = getLong(left, BYTE_ARRAY_BASE_OFFSET + leftOff + index);
long rightLongWord = getLong(right, BYTE_ARRAY_BASE_OFFSET + rightOff + index);
if (leftLongWord != rightLongWord) {
// one of these eight bytes differ! use a helper to find out which one
return index + firstDifferingByteIndexNativeEndian(leftLongWord, rightLongWord);
}
}
}
// If we were able to stride, there are at most STRIDE - 1 bytes left to compare.
// If we weren't, then this loop covers the whole thing.
for (; index < length; index++) {
if (left[leftOff + index] != right[rightOff + index]) {
return index;
}
}
return -1;
}
/**
* Returns the offset of the provided field, or {@code -1} if {@code sun.misc.Unsafe} is not
* available.

@ -62,6 +62,21 @@ public class RopeByteStringTest extends LiteralByteStringTest {
expectedHashCode = -1214197238;
}
public void testMinLengthByDepth() {
// minLengthByDepth should match the Fibonacci sequence
int a = 1;
int b = 1;
int i;
for (i = 0; a > 0; i++) {
assertEquals(a, RopeByteString.minLengthByDepth[i]);
int c = a + b;
a = b;
b = c;
}
assertEquals(Integer.MAX_VALUE, RopeByteString.minLengthByDepth[i]);
assertEquals(i + 1, RopeByteString.minLengthByDepth.length);
}
@Override
public void testGetTreeDepth() {
assertEquals(

@ -32,7 +32,6 @@ package com.google.protobuf;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.Descriptors.MethodDescriptor;
import google.protobuf.no_generic_services_test.UnittestNoGenericServices;
import protobuf_unittest.MessageWithNoOuter;
import protobuf_unittest.ServiceWithNoOuter;
import protobuf_unittest.UnittestProto.BarRequest;
@ -41,6 +40,7 @@ import protobuf_unittest.UnittestProto.FooRequest;
import protobuf_unittest.UnittestProto.FooResponse;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestService;
import protobuf_unittest.no_generic_services_test.UnittestNoGenericServices;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
@ -227,7 +227,7 @@ public class ServiceTest extends TestCase {
// Build a list of the class names nested in UnittestNoGenericServices.
String outerName =
"google.protobuf.no_generic_services_test.UnittestNoGenericServices";
"protobuf_unittest.no_generic_services_test.UnittestNoGenericServices";
Class<?> outerClass = Class.forName(outerName);
Set<String> innerClassNames = new HashSet<String>();

@ -35,6 +35,10 @@ import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.FieldPresenceTestProto.TestAllTypes;
import com.google.protobuf.Proto2UnknownEnumValuesTestProto.Proto2EnumMessage;
import com.google.protobuf.Proto2UnknownEnumValuesTestProto.Proto2EnumMessageWithEnumSubset;
import com.google.protobuf.Proto2UnknownEnumValuesTestProto.Proto2TestEnum;
import com.google.protobuf.Proto2UnknownEnumValuesTestProto.Proto2TestEnumSubset;
import com.google.protobuf.TextFormat.ParseException;
import junit.framework.TestCase;
@ -42,6 +46,7 @@ import junit.framework.TestCase;
* Unit tests for protos that keep unknown enum values rather than discard them as unknown fields.
*/
public class UnknownEnumValueTest extends TestCase {
public void testUnknownEnumValues() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
builder.setOptionalNestedEnumValue(4321);
@ -245,4 +250,61 @@ public class UnknownEnumValueTest extends TestCase {
// expected.
}
}
public void testUnknownEnumValuesInProto2() throws Exception {
Proto2EnumMessage.Builder sourceMessage = Proto2EnumMessage.newBuilder();
sourceMessage
.addRepeatedPackedEnum(Proto2TestEnum.ZERO)
.addRepeatedPackedEnum(Proto2TestEnum.TWO) // Unknown in parsed proto
.addRepeatedPackedEnum(Proto2TestEnum.ONE);
Proto2EnumMessageWithEnumSubset destMessage =
Proto2EnumMessageWithEnumSubset.parseFrom(sourceMessage.build().toByteArray());
// Known enum values should be preserved.
assertEquals(2, destMessage.getRepeatedPackedEnumCount());
assertEquals(Proto2TestEnumSubset.TESTENUM_SUBSET_ZERO, destMessage.getRepeatedPackedEnum(0));
assertEquals(Proto2TestEnumSubset.TESTENUM_SUBSET_ONE, destMessage.getRepeatedPackedEnum(1));
// Unknown enum values should be found in UnknownFieldSet.
UnknownFieldSet unknown = destMessage.getUnknownFields();
assertEquals(
Proto2TestEnum.TWO_VALUE,
unknown
.getField(Proto2EnumMessageWithEnumSubset.REPEATED_PACKED_ENUM_FIELD_NUMBER)
.getVarintList()
.get(0)
.longValue());
}
public void testUnknownEnumValuesInProto2WithDynamicMessage() throws Exception {
Descriptor descriptor = Proto2EnumMessageWithEnumSubset.getDescriptor();
FieldDescriptor repeatedPackedField = descriptor.findFieldByName("repeated_packed_enum");
Proto2EnumMessage.Builder sourceMessage = Proto2EnumMessage.newBuilder();
sourceMessage
.addRepeatedPackedEnum(Proto2TestEnum.ZERO)
.addRepeatedPackedEnum(Proto2TestEnum.TWO) // Unknown in parsed proto
.addRepeatedPackedEnum(Proto2TestEnum.ONE);
DynamicMessage message =
DynamicMessage.parseFrom(
Proto2EnumMessageWithEnumSubset.getDescriptor(), sourceMessage.build().toByteArray());
// Known enum values should be preserved.
assertEquals(2, message.getRepeatedFieldCount(repeatedPackedField));
EnumValueDescriptor enumValue0 =
(EnumValueDescriptor) message.getRepeatedField(repeatedPackedField, 0);
EnumValueDescriptor enumValue1 =
(EnumValueDescriptor) message.getRepeatedField(repeatedPackedField, 1);
assertEquals(Proto2TestEnumSubset.TESTENUM_SUBSET_ZERO_VALUE, enumValue0.getNumber());
assertEquals(Proto2TestEnumSubset.TESTENUM_SUBSET_ONE_VALUE, enumValue1.getNumber());
// Unknown enum values should be found in UnknownFieldSet.
UnknownFieldSet unknown = message.getUnknownFields();
assertEquals(
Proto2TestEnum.TWO_VALUE,
unknown.getField(repeatedPackedField.getNumber()).getVarintList().get(0).longValue());
}
}

@ -28,10 +28,33 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "binary_json_conformance_suite.h"
#include "conformance_test.h"
syntax = "proto2";
int main(int argc, char *argv[]) {
google::protobuf::BinaryAndJsonConformanceSuite suite;
return google::protobuf::ForkPipeRunner::Run(argc, argv, &suite);
package proto2_unknown_enum_values;
option java_package = "com.google.protobuf";
option java_outer_classname = "Proto2UnknownEnumValuesTestProto";
enum Proto2TestEnum {
ZERO = 0;
ONE = 1;
TWO = 2;
}
message Proto2EnumMessage {
repeated Proto2TestEnum repeated_packed_enum = 1 [packed = true];
}
// An enum containing a subset of the values of Proto2TestEnum, to test
// parsing unknown packed enum values
enum Proto2TestEnumSubset {
TESTENUM_SUBSET_ZERO = 0;
TESTENUM_SUBSET_ONE = 1;
// No enum value with number 2.
}
// Test messages for packed enum, with identical field number as
// Proto2Message, to test parsing unknown packed enums.
message Proto2EnumMessageWithEnumSubset {
repeated Proto2TestEnumSubset repeated_packed_enum = 1 [packed = true];
}

@ -102,14 +102,14 @@ describe('Message test suite', function() {
});
it('testComplexConversion', function() {
var data1 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, 1];
var data2 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, 1];
var data1 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, true];
var data2 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, true];
var foo = new proto.jspb.test.Complex(data1);
var bar = new proto.jspb.test.Complex(data2);
var result = foo.toObject();
assertObjectEquals({
aString: 'a',
anOutOfOrderBool: 1,
anOutOfOrderBool: true,
aNestedMessage: {
anInt: 11
},
@ -121,7 +121,7 @@ describe('Message test suite', function() {
result = foo.toObject(true /* opt_includeInstance */);
assertObjectEquals({
aString: 'a',
anOutOfOrderBool: 1,
anOutOfOrderBool: true,
aNestedMessage: {
anInt: 11,
$jspbMessageInstance: foo.getANestedMessage()

@ -268,12 +268,12 @@ jspb.Message.prototype.messageId_;
/**
* Repeated float or double fields which have been converted to include only
* numbers and not strings holding "NaN", "Infinity" and "-Infinity".
* Repeated fields that have been converted to their proper type. This is used
* for numbers stored as strings (typically "NaN", "Infinity" and "-Infinity")
* and for booleans stored as numbers (0 or 1).
* @private {!Object<number,boolean>|undefined}
*/
jspb.Message.prototype.convertedFloatingPointFields_;
jspb.Message.prototype.convertedPrimitiveFields_;
/**
* Repeated fields numbers.
@ -368,7 +368,7 @@ jspb.Message.initialize = function(
msg.arrayIndexOffset_ = messageId === 0 ? -1 : 0;
msg.array = data;
jspb.Message.initPivotAndExtensionObject_(msg, suggestedPivot);
msg.convertedFloatingPointFields_ = {};
msg.convertedPrimitiveFields_ = {};
if (!jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS) {
// TODO(jakubvrana): This is same for all instances, move to prototype.
@ -718,6 +718,20 @@ jspb.Message.getOptionalFloatingPointField = function(msg, fieldNumber) {
};
/**
* Gets the value of an optional boolean field.
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @return {?boolean|undefined} The field's value.
* @protected
*/
jspb.Message.getBooleanField = function(msg, fieldNumber) {
var value = jspb.Message.getField(msg, fieldNumber);
// TODO(b/122673075): always return null when the value is null-ish.
return value == null ? (value) : !!value;
};
/**
* Gets the value of a repeated float or double field.
* @param {!jspb.Message} msg A jspb proto.
@ -727,20 +741,42 @@ jspb.Message.getOptionalFloatingPointField = function(msg, fieldNumber) {
*/
jspb.Message.getRepeatedFloatingPointField = function(msg, fieldNumber) {
var values = jspb.Message.getRepeatedField(msg, fieldNumber);
if (!msg.convertedFloatingPointFields_) {
msg.convertedFloatingPointFields_ = {};
if (!msg.convertedPrimitiveFields_) {
msg.convertedPrimitiveFields_ = {};
}
if (!msg.convertedFloatingPointFields_[fieldNumber]) {
if (!msg.convertedPrimitiveFields_[fieldNumber]) {
for (var i = 0; i < values.length; i++) {
// Converts "NaN", "Infinity" and "-Infinity" to their corresponding
// numbers.
values[i] = +values[i];
}
msg.convertedFloatingPointFields_[fieldNumber] = true;
msg.convertedPrimitiveFields_[fieldNumber] = true;
}
return /** @type {!Array<number>} */ (values);
};
/**
* Gets the value of a repeated boolean field.
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @return {!Array<boolean>} The field's value.
* @protected
*/
jspb.Message.getRepeatedBooleanField = function(msg, fieldNumber) {
var values = jspb.Message.getRepeatedField(msg, fieldNumber);
if (!msg.convertedPrimitiveFields_) {
msg.convertedPrimitiveFields_ = {};
}
if (!msg.convertedPrimitiveFields_[fieldNumber]) {
for (var i = 0; i < values.length; i++) {
// Converts 0 and 1 to their corresponding booleans.
values[i] = !!values[i];
}
msg.convertedPrimitiveFields_[fieldNumber] = true;
}
return /** @type {!Array<boolean>} */ (values);
};
/**
* Coerce a 'bytes' field to a base 64 string.
@ -849,6 +885,49 @@ jspb.Message.getFieldWithDefault = function(msg, fieldNumber, defaultValue) {
};
/**
* Gets the value of a boolean field, with proto3 (non-nullable primitives)
* semantics. Returns `defaultValue` if the field is not otherwise set.
* @template T
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @param {boolean} defaultValue The default value.
* @return {boolean} The field's value.
* @protected
*/
jspb.Message.getBooleanFieldWithDefault = function(
msg, fieldNumber, defaultValue) {
var value = jspb.Message.getBooleanField(msg, fieldNumber);
if (value == null) {
return defaultValue;
} else {
return value;
}
};
/**
* Gets the value of a floating point field, with proto3 (non-nullable
* primitives) semantics. Returns `defaultValue` if the field is not otherwise
* set.
* @template T
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @param {number} defaultValue The default value.
* @return {number} The field's value.
* @protected
*/
jspb.Message.getFloatingPointFieldWithDefault = function(
msg, fieldNumber, defaultValue) {
var value = jspb.Message.getOptionalFloatingPointField(msg, fieldNumber);
if (value == null) {
return defaultValue;
} else {
return value;
}
};
/**
* Alias for getFieldWithDefault used by older generated code.
* @template T

@ -86,6 +86,7 @@ goog.require('proto.jspb.exttest.floatingMsgField');
goog.require('proto.jspb.exttest.floatingMsgFieldTwo');
// CommonJS-LoadFromFile: test_pb proto.jspb.test
goog.require('proto.jspb.test.BooleanFields');
goog.require('proto.jspb.test.CloneExtension');
goog.require('proto.jspb.test.Complex');
goog.require('proto.jspb.test.DefaultValues');
@ -157,10 +158,11 @@ describe('Message test suite', function() {
assertObjectEquals(
{
aString: 'a',
anOutOfOrderBool: 1,
anOutOfOrderBool: true,
aNestedMessage: {anInt: 11},
aRepeatedMessageList: [{anInt: 22}, {anInt: 33}],
aRepeatedStringList: ['s1', 's2']
aRepeatedStringList: ['s1', 's2'],
aFloatingPointField: undefined,
},
result);
@ -169,7 +171,7 @@ describe('Message test suite', function() {
assertObjectEquals(
{
aString: 'a',
anOutOfOrderBool: 1,
anOutOfOrderBool: true,
aNestedMessage:
{anInt: 11, $jspbMessageInstance: foo.getANestedMessage()},
aRepeatedMessageList: [
@ -177,6 +179,7 @@ describe('Message test suite', function() {
{anInt: 33, $jspbMessageInstance: foo.getARepeatedMessageList()[1]}
],
aRepeatedStringList: ['s1', 's2'],
aFloatingPointField: undefined,
$jspbMessageInstance: foo
},
result);
@ -200,7 +203,8 @@ describe('Message test suite', function() {
aNestedMessage: {anInt: undefined},
// Note: JsPb converts undefined repeated fields to empty arrays.
aRepeatedMessageList: [],
aRepeatedStringList: []
aRepeatedStringList: [],
aFloatingPointField: undefined,
},
result);
@ -869,6 +873,53 @@ describe('Message test suite', function() {
assertNan(message.getDefaultDoubleField());
});
it('testFloatingPointsAreConvertedFromStringInput', function() {
var assertInf = function(x) {
assertTrue(
'Expected ' + x + ' (' + goog.typeOf(x) + ') to be Infinity.',
x === Infinity);
};
var message = new proto.jspb.test.FloatingPointFields([
Infinity, 'Infinity', ['Infinity', Infinity], 'Infinity', 'Infinity',
'Infinity', ['Infinity', Infinity], 'Infinity'
]);
assertInf(message.getOptionalFloatField());
assertInf(message.getRequiredFloatField());
assertInf(message.getRepeatedFloatFieldList()[0]);
assertInf(message.getRepeatedFloatFieldList()[1]);
assertInf(message.getDefaultFloatField());
assertInf(message.getOptionalDoubleField());
assertInf(message.getRequiredDoubleField());
assertInf(message.getRepeatedDoubleFieldList()[0]);
assertInf(message.getRepeatedDoubleFieldList()[1]);
assertInf(message.getDefaultDoubleField());
});
it('testBooleansAreConvertedFromNumberInput', function() {
var assertBooleanFieldTrue = function(x) {
assertTrue(
'Expected ' + x + ' (' + goog.typeOf(x) + ') to be True.',
x === true);
};
var message = new proto.jspb.test.BooleanFields([1, 1, [true, 1]]);
assertBooleanFieldTrue(message.getOptionalBooleanField());
assertBooleanFieldTrue(message.getRequiredBooleanField());
assertBooleanFieldTrue(message.getRepeatedBooleanFieldList()[0]);
assertBooleanFieldTrue(message.getRepeatedBooleanFieldList()[1]);
assertBooleanFieldTrue(message.getDefaultBooleanField());
var assertBooleanFieldFalse = function(x) {
assertTrue(
'Expected ' + x + ' (' + goog.typeOf(x) + ') to be False.',
x === false);
};
message = new proto.jspb.test.BooleanFields([0, 0, [0, 0]]);
assertBooleanFieldFalse(message.getOptionalBooleanField());
assertBooleanFieldFalse(message.getRequiredBooleanField());
assertBooleanFieldFalse(message.getRepeatedBooleanFieldList()[0]);
assertBooleanFieldFalse(message.getRepeatedBooleanFieldList()[1]);
});
it('testExtensionReverseOrder', function() {
var message2 =
new proto.jspb.exttest.reverse.TestExtensionReverseOrderMessage2;

@ -93,10 +93,11 @@ message Complex {
required int32 an_int = 2;
}
required string a_string = 1;
required bool an_out_of_order_bool = 9;
optional bool an_out_of_order_bool = 9;
optional Nested a_nested_message = 4;
repeated Nested a_repeated_message = 5;
repeated string a_repeated_string = 7;
optional double a_floating_point_field = 10;
}
message OuterMessage {
@ -163,6 +164,13 @@ message FloatingPointFields {
optional double default_double_field = 8 [default = 2.0];
}
message BooleanFields {
optional bool optional_boolean_field = 1;
required bool required_boolean_field = 2;
repeated bool repeated_boolean_field = 3;
optional bool default_boolean_field = 4 [default = true];
}
message TestClone {
optional string str = 1;
optional Simple1 simple1 = 3;

@ -89,7 +89,7 @@ class EnumTypeWrapper(object):
for value_descriptor in self._enum_type.values]
def __getattr__(self, name):
"""Returns the value coresponding to the given enum name."""
"""Returns the value corresponding to the given enum name."""
if name in self._enum_type.values_by_name:
return self._enum_type.values_by_name[name].number
raise AttributeError

@ -794,6 +794,13 @@ class JsonFormatTest(JsonFormatBase):
json_format.Parse(text, parsed_message)
self.assertTrue(math.isnan(parsed_message.float_value))
def testParseDoubleToFloat(self):
message = json_format_proto3_pb2.TestMessage()
text = ('{"repeatedFloatValue": [3.4028235e+39, 1.4028235e-39]\n}')
json_format.Parse(text, message)
self.assertEqual(message.repeated_float_value[0], float('inf'))
self.assertAlmostEqual(message.repeated_float_value[1], 1.4028235e-39)
def testParseEmptyText(self):
self.CheckError('',
r'Failed to load JSON: (Expecting value)|(No JSON).')

@ -346,6 +346,27 @@ class MessageTest(BaseTestCase):
message.ParseFromString(message.SerializeToString())
self.assertTrue(message.optional_float == -kMostNegExponentOneSigBit)
# Max 4 bytes float value
max_float = float.fromhex('0x1.fffffep+127')
message.optional_float = max_float
self.assertAlmostEqual(message.optional_float, max_float)
serialized_data = message.SerializeToString()
message.ParseFromString(serialized_data)
self.assertAlmostEqual(message.optional_float, max_float)
# Test set double to float field.
message.optional_float = 3.4028235e+39
self.assertEqual(message.optional_float, float('inf'))
serialized_data = message.SerializeToString()
message.ParseFromString(serialized_data)
self.assertEqual(message.optional_float, float('inf'))
message.optional_float = -3.4028235e+39
self.assertEqual(message.optional_float, float('-inf'))
message.optional_float = 1.4028235e-39
self.assertAlmostEqual(message.optional_float, 1.4028235e-39)
def testExtremeDoubleValues(self, message_module):
message = message_module.TestAllTypes()

@ -497,6 +497,14 @@ class TextFormatParserTests(TextFormatBase):
text_format.Parse(text, msg2)
self.assertEqual(msg2.optional_string, u'café')
def testParseDoubleToFloat(self, message_module):
message = message_module.TestAllTypes()
text = ('repeated_float: 3.4028235e+39\n'
'repeated_float: 1.4028235e-39\n')
text_format.Parse(text, message)
self.assertEqual(message.repeated_float[0], float('inf'))
self.assertAlmostEqual(message.repeated_float[1], 1.4028235e-39)
def testParseExotic(self, message_module):
message = message_module.TestAllTypes()
text = ('repeated_int64: -9223372036854775808\n'

@ -230,6 +230,41 @@ class Uint64ValueChecker(IntValueChecker):
_TYPE = long
# The max 4 bytes float is about 3.4028234663852886e+38
_FLOAT_MAX = float.fromhex('0x1.fffffep+127')
_FLOAT_MIN = -_FLOAT_MAX
_INF = float('inf')
_NEG_INF = float('-inf')
class FloatValueChecker(object):
"""Checker used for float fields. Performs type-check and range check.
Values exceeding a 32-bit float will be converted to inf/-inf.
"""
def CheckValue(self, proposed_value):
"""Check and convert proposed_value to float."""
if not isinstance(proposed_value, numbers.Real):
message = ('%.1024r has type %s, but expected one of: numbers.Real' %
(proposed_value, type(proposed_value)))
raise TypeError(message)
converted_value = float(proposed_value)
# This inf rounding matches the C++ proto SafeDoubleToFloat logic.
if converted_value > _FLOAT_MAX:
return _INF
if converted_value < _FLOAT_MIN:
return _NEG_INF
return converted_value
# TODO(jieluo): convert to 4 bytes float (c style float) at setters:
# return struct.unpack('f', struct.pack('f', converted_value))
def DefaultValue(self):
return 0.0
# Type-checkers for all scalar CPPTYPEs.
_VALUE_CHECKERS = {
_FieldDescriptor.CPPTYPE_INT32: Int32ValueChecker(),
@ -238,8 +273,7 @@ _VALUE_CHECKERS = {
_FieldDescriptor.CPPTYPE_UINT64: Uint64ValueChecker(),
_FieldDescriptor.CPPTYPE_DOUBLE: TypeCheckerWithDefault(
0.0, float, numbers.Real),
_FieldDescriptor.CPPTYPE_FLOAT: TypeCheckerWithDefault(
0.0, float, numbers.Real),
_FieldDescriptor.CPPTYPE_FLOAT: FloatValueChecker(),
_FieldDescriptor.CPPTYPE_BOOL: TypeCheckerWithDefault(
False, bool, numbers.Integral),
_FieldDescriptor.CPPTYPE_STRING: TypeCheckerWithDefault(b'', bytes),

@ -48,18 +48,18 @@ class PyDescriptorDatabase : public DescriptorDatabase {
// with a copy of FileDescriptorProto.
// Find a file by file name.
bool FindFileByName(const std::string& filename,
bool FindFileByName(const string& filename,
FileDescriptorProto* output);
// Find the file that declares the given fully-qualified symbol name.
bool FindFileContainingSymbol(const std::string& symbol_name,
bool FindFileContainingSymbol(const string& symbol_name,
FileDescriptorProto* output);
// Find the file which defines an extension extending the given message type
// with the given field number.
// Containing_type must be a fully-qualified type name.
// Python objects are not required to implement this method.
bool FindFileContainingExtension(const std::string& containing_type,
bool FindFileContainingExtension(const string& containing_type,
int field_number,
FileDescriptorProto* output);
@ -67,7 +67,7 @@ class PyDescriptorDatabase : public DescriptorDatabase {
// containing_type, and appends them to output in an undefined
// order.
// Python objects are not required to implement this method.
bool FindAllExtensionNumbers(const std::string& containing_type,
bool FindAllExtensionNumbers(const string& containing_type,
std::vector<int>* output);
private:

@ -89,7 +89,7 @@ namespace cdescriptor_pool {
// Looks up a message by name.
// Returns a message Descriptor, or NULL if not found.
const Descriptor* FindMessageTypeByName(PyDescriptorPool* self,
const std::string& name);
const string& name);
// The functions below are also exposed as methods of the DescriptorPool type.

@ -47,6 +47,7 @@
#endif
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/io/strtod.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/descriptor.pb.h>
@ -756,7 +757,7 @@ bool CheckAndGetFloat(PyObject* arg, float* value) {
if (!CheckAndGetDouble(arg, &double_value)) {
return false;
}
*value = static_cast<float>(double_value);
*value = io::SafeDoubleToFloat(double_value);
return true;
}

@ -332,7 +332,7 @@ bool CheckAndSetString(
bool append,
int index);
PyObject* ToStringObject(const FieldDescriptor* descriptor,
const std::string& value);
const string& value);
// Check if the passed field descriptor belongs to the given message.
// If not, return false and set a Python exception (a KeyError)
@ -346,14 +346,12 @@ Message* PyMessage_GetMutableMessagePointer(PyObject* msg);
bool InitProto2MessageModule(PyObject *m);
#if LANG_CXX11
// These are referenced by repeated_scalar_container, and must
// be explicitly instantiated.
extern template bool CheckAndGetInteger<int32>(PyObject*, int32*);
extern template bool CheckAndGetInteger<int64>(PyObject*, int64*);
extern template bool CheckAndGetInteger<uint32>(PyObject*, uint32*);
extern template bool CheckAndGetInteger<uint64>(PyObject*, uint64*);
#endif
} // namespace python
} // namespace protobuf

@ -30,10 +30,10 @@
syntax = "proto2";
import "google/protobuf/internal/cpp/proto1_api_test.proto";
package google.protobuf.python.internal;
import "google/protobuf/internal/cpp/proto1_api_test.proto";
message TestNestedProto1APIMessage {
optional int32 a = 1;
optional TestMessage.NestedMessage b = 2;

@ -35,6 +35,8 @@
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/message.h>
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
namespace internal {
@ -44,12 +46,12 @@ void AnyMetadata::PackFrom(const Message& message) {
}
void AnyMetadata::PackFrom(const Message& message,
const string& type_url_prefix) {
const std::string& type_url_prefix) {
type_url_->SetNoArena(
&::google::protobuf::internal::GetEmptyString(),
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString(),
GetTypeUrl(message.GetDescriptor()->full_name(), type_url_prefix));
message.SerializeToString(value_->MutableNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()));
}
bool AnyMetadata::UnpackTo(Message* message) const {

@ -52,7 +52,7 @@ extern const char kTypeGoogleApisComPrefix[]; // "type.googleapis.com/".
extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/".
std::string GetTypeUrl(StringPiece message_name,
StringPiece type_url_prefix);
StringPiece type_url_prefix);
// Helper class used to implement google::protobuf::Any.
class PROTOBUF_EXPORT AnyMetadata {

@ -8,7 +8,7 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
@ -16,54 +16,52 @@
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
PROTOBUF_NAMESPACE_OPEN
class AnyDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Any> _instance;
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<Any> _instance;
} _Any_default_instance_;
} // namespace protobuf
} // namespace google
PROTOBUF_NAMESPACE_CLOSE
static void InitDefaultsAny_google_2fprotobuf_2fany_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::protobuf::_Any_default_instance_;
new (ptr) ::google::protobuf::Any();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
void* ptr = &PROTOBUF_NAMESPACE_ID::_Any_default_instance_;
new (ptr) PROTOBUF_NAMESPACE_ID::Any();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::google::protobuf::Any::InitAsDefaultInstance();
PROTOBUF_NAMESPACE_ID::Any::InitAsDefaultInstance();
}
PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Any_google_2fprotobuf_2fany_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAny_google_2fprotobuf_2fany_2eproto}, {}};
PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Any_google_2fprotobuf_2fany_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAny_google_2fprotobuf_2fany_2eproto}, {}};
void InitDefaults_google_2fprotobuf_2fany_2eproto() {
::google::protobuf::internal::InitSCC(&scc_info_Any_google_2fprotobuf_2fany_2eproto.base);
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Any_google_2fprotobuf_2fany_2eproto.base);
}
static ::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2fany_2eproto[1];
static constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto = nullptr;
static constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fany_2eproto = nullptr;
static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fany_2eproto[1];
static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto = nullptr;
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fany_2eproto = nullptr;
const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fany_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fany_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::protobuf::Any, _internal_metadata_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Any, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::protobuf::Any, type_url_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Any, value_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Any, type_url_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::Any, value_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::Any)},
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(PROTOBUF_NAMESPACE_ID::Any)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Any_default_instance_),
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&PROTOBUF_NAMESPACE_ID::_Any_default_instance_),
};
static ::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fany_2eproto = {
static ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fany_2eproto = {
{}, AddDescriptors_google_2fprotobuf_2fany_2eproto, "google/protobuf/any.proto", schemas,
file_default_instances, TableStruct_google_2fprotobuf_2fany_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2fany_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto, file_level_service_descriptors_google_2fprotobuf_2fany_2eproto,
@ -77,50 +75,49 @@ const char descriptor_table_protodef_google_2fprotobuf_2fany_2eproto[] =
"\003GPB\252\002\036Google.Protobuf.WellKnownTypesb\006p"
"roto3"
;
static ::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_2eproto = {
static ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_2eproto = {
false, InitDefaults_google_2fprotobuf_2fany_2eproto,
descriptor_table_protodef_google_2fprotobuf_2fany_2eproto,
"google/protobuf/any.proto", &assign_descriptors_table_google_2fprotobuf_2fany_2eproto, 205,
};
void AddDescriptors_google_2fprotobuf_2fany_2eproto() {
static constexpr ::google::protobuf::internal::InitFunc deps[1] =
static constexpr ::PROTOBUF_NAMESPACE_ID::internal::InitFunc deps[1] =
{
};
::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fany_2eproto, deps, 0);
::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fany_2eproto, deps, 0);
}
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_google_2fprotobuf_2fany_2eproto = []() { AddDescriptors_google_2fprotobuf_2fany_2eproto(); return true; }();
namespace google {
namespace protobuf {
PROTOBUF_NAMESPACE_OPEN
// ===================================================================
void Any::InitAsDefaultInstance() {
}
void Any::PackFrom(const ::google::protobuf::Message& message) {
void Any::PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message) {
_any_metadata_.PackFrom(message);
}
void Any::PackFrom(const ::google::protobuf::Message& message,
const ::std::string& type_url_prefix) {
void Any::PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message,
const std::string& type_url_prefix) {
_any_metadata_.PackFrom(message, type_url_prefix);
}
bool Any::UnpackTo(::google::protobuf::Message* message) const {
bool Any::UnpackTo(::PROTOBUF_NAMESPACE_ID::Message* message) const {
return _any_metadata_.UnpackTo(message);
}
bool Any::GetAnyFieldDescriptors(
const ::google::protobuf::Message& message,
const ::google::protobuf::FieldDescriptor** type_url_field,
const ::google::protobuf::FieldDescriptor** value_field) {
return ::google::protobuf::internal::GetAnyFieldDescriptors(
const ::PROTOBUF_NAMESPACE_ID::Message& message,
const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** type_url_field,
const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** value_field) {
return ::PROTOBUF_NAMESPACE_ID::internal::GetAnyFieldDescriptors(
message, type_url_field, value_field);
}
bool Any::ParseAnyTypeUrl(const string& type_url,
string* full_type_name) {
return ::google::protobuf::internal::ParseAnyTypeUrl(type_url,
std::string* full_type_name) {
return ::PROTOBUF_NAMESPACE_ID::internal::ParseAnyTypeUrl(type_url,
full_type_name);
}
@ -134,31 +131,31 @@ const int Any::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Any::Any()
: ::google::protobuf::Message(), _internal_metadata_(nullptr), _any_metadata_(&type_url_, &value_) {
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr), _any_metadata_(&type_url_, &value_) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Any)
}
Any::Any(const Any& from)
: ::google::protobuf::Message(),
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr),
_any_metadata_(&type_url_, &value_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.type_url().size() > 0) {
type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_url_);
type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.type_url_);
}
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.value().size() > 0) {
value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_);
value_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.value_);
}
// @@protoc_insertion_point(copy_constructor:google.protobuf.Any)
}
void Any::SharedCtor() {
::google::protobuf::internal::InitSCC(
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(
&scc_info_Any_google_2fprotobuf_2fany_2eproto.base);
type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
Any::~Any() {
@ -167,48 +164,49 @@ Any::~Any() {
}
void Any::SharedDtor() {
type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
type_url_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void Any::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Any& Any::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_Any_google_2fprotobuf_2fany_2eproto.base);
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Any_google_2fprotobuf_2fany_2eproto.base);
return *internal_default_instance();
}
void Any::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Any)
::google::protobuf::uint32 cached_has_bits = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
value_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* Any::_InternalParse(const char* ptr, ::google::protobuf::internal::ParseContext* ctx) {
const char* Any::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::google::protobuf::uint32 tag;
ptr = ::google::protobuf::internal::ReadTag(ptr, &tag);
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// string type_url = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::internal::InlineGreedyStringParserUTF8(mutable_type_url(), ptr, ctx, "google.protobuf.Any.type_url");
if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) != 10) goto handle_unusual;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_type_url(), ptr, ctx, "google.protobuf.Any.type_url");
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// bytes value = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
ptr = ::google::protobuf::internal::InlineGreedyStringParser(mutable_value(), ptr, ctx);
if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) != 18) goto handle_unusual;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(mutable_value(), ptr, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
@ -229,23 +227,23 @@ const char* Any::_InternalParse(const char* ptr, ::google::protobuf::internal::P
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Any::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Any)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string type_url = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString(
input, this->mutable_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE,
"google.protobuf.Any.type_url"));
} else {
goto handle_unusual;
@ -255,8 +253,8 @@ bool Any::MergePartialFromCodedStream(
// bytes value = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
goto handle_unusual;
@ -269,7 +267,7 @@ bool Any::MergePartialFromCodedStream(
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
@ -286,60 +284,60 @@ failure:
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Any::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Any)
::google::protobuf::uint32 cached_has_bits = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string type_url = 1;
if (this->type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Any.type_url");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->type_url(), output);
}
// bytes value = 2;
if (this->value().size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesMaybeAliased(
2, this->value(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Any)
}
::google::protobuf::uint8* Any::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
::PROTOBUF_NAMESPACE_ID::uint8* Any::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Any)
::google::protobuf::uint32 cached_has_bits = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string type_url = 1;
if (this->type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Any.type_url");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray(
1, this->type_url(), target);
}
// bytes value = 2;
if (this->value().size() > 0) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesToArray(
2, this->value(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Any)
@ -352,41 +350,41 @@ size_t Any::ByteSizeLong() const {
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string type_url = 1;
if (this->type_url().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->type_url());
}
// bytes value = 2;
if (this->value().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
this->value());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Any::MergeFrom(const ::google::protobuf::Message& from) {
void Any::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Any)
GOOGLE_DCHECK_NE(&from, this);
const Any* source =
::google::protobuf::DynamicCastToGenerated<Any>(
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<Any>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Any)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Any)
MergeFrom(*source);
@ -397,20 +395,20 @@ void Any::MergeFrom(const Any& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Any)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.type_url().size() > 0) {
type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_url_);
type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.type_url_);
}
if (from.value().size() > 0) {
value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_);
value_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.value_);
}
}
void Any::CopyFrom(const ::google::protobuf::Message& from) {
void Any::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Any)
if (&from == this) return;
Clear();
@ -435,28 +433,25 @@ void Any::Swap(Any* other) {
void Any::InternalSwap(Any* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
type_url_.Swap(&other->type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
type_url_.Swap(&other->type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
value_.Swap(&other->value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
::google::protobuf::Metadata Any::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fany_2eproto);
::PROTOBUF_NAMESPACE_ID::Metadata Any::GetMetadata() const {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fany_2eproto);
return ::file_level_metadata_google_2fprotobuf_2fany_2eproto[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
namespace google {
namespace protobuf {
template<> PROTOBUF_NOINLINE ::google::protobuf::Any* Arena::CreateMaybeMessage< ::google::protobuf::Any >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::Any >(arena);
PROTOBUF_NAMESPACE_CLOSE
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Any* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Any >(Arena* arena) {
return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::Any >(arena);
}
} // namespace protobuf
} // namespace google
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>

@ -1,8 +1,8 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/any.proto
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
#include <limits>
#include <string>
@ -35,51 +35,53 @@
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto PROTOBUF_EXPORT
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fany_2eproto {
static const ::google::protobuf::internal::ParseTableField entries[]
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::google::protobuf::internal::ParseTable schema[1]
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::google::protobuf::internal::FieldMetadata field_metadata[];
static const ::google::protobuf::internal::SerializationTable serialization_table[];
static const ::google::protobuf::uint32 offsets[];
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fany_2eproto();
namespace google {
namespace protobuf {
PROTOBUF_NAMESPACE_OPEN
class Any;
class AnyDefaultTypeInternal;
PROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_;
template<> PROTOBUF_EXPORT ::google::protobuf::Any* Arena::CreateMaybeMessage<::google::protobuf::Any>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
namespace protobuf {
PROTOBUF_NAMESPACE_CLOSE
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::Any* Arena::CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::Any>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
PROTOBUF_NAMESPACE_OPEN
// ===================================================================
class PROTOBUF_EXPORT Any final :
public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ {
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ {
public:
Any();
virtual ~Any();
Any(const Any& from);
inline Any& operator=(const Any& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
Any(Any&& from) noexcept
: Any() {
*this = ::std::move(from);
}
inline Any& operator=(const Any& from) {
CopyFrom(from);
return *this;
}
inline Any& operator=(Any&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
@ -88,8 +90,8 @@ class PROTOBUF_EXPORT Any final :
}
return *this;
}
#endif
static const ::google::protobuf::Descriptor* descriptor() {
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return default_instance().GetDescriptor();
}
static const Any& default_instance();
@ -104,19 +106,19 @@ class PROTOBUF_EXPORT Any final :
// implements Any -----------------------------------------------
void PackFrom(const ::google::protobuf::Message& message);
void PackFrom(const ::google::protobuf::Message& message,
const ::std::string& type_url_prefix);
bool UnpackTo(::google::protobuf::Message* message) const;
void PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message);
void PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message,
const std::string& type_url_prefix);
bool UnpackTo(::PROTOBUF_NAMESPACE_ID::Message* message) const;
static bool GetAnyFieldDescriptors(
const ::google::protobuf::Message& message,
const ::google::protobuf::FieldDescriptor** type_url_field,
const ::google::protobuf::FieldDescriptor** value_field);
const ::PROTOBUF_NAMESPACE_ID::Message& message,
const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** type_url_field,
const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** value_field);
template<typename T> bool Is() const {
return _any_metadata_.Is<T>();
}
static bool ParseAnyTypeUrl(const string& type_url,
string* full_type_name);
std::string* full_type_name);
void Swap(Any* other);
friend void swap(Any& a, Any& b) {
a.Swap(&b);
@ -128,11 +130,11 @@ class PROTOBUF_EXPORT Any final :
return CreateMaybeMessage<Any>(nullptr);
}
Any* New(::google::protobuf::Arena* arena) const final {
Any* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<Any>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const Any& from);
void MergeFrom(const Any& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
@ -140,15 +142,15 @@ class PROTOBUF_EXPORT Any final :
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::google::protobuf::internal::ParseContext* ctx) final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const final;
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
@ -156,12 +158,12 @@ class PROTOBUF_EXPORT Any final :
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(Any* other);
friend class ::google::protobuf::internal::AnyMetadata;
static ::google::protobuf::StringPiece FullMessageName() {
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "google.protobuf.Any";
}
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
@ -169,7 +171,7 @@ class PROTOBUF_EXPORT Any final :
}
public:
::google::protobuf::Metadata GetMetadata() const final;
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@ -178,40 +180,36 @@ class PROTOBUF_EXPORT Any final :
// string type_url = 1;
void clear_type_url();
static const int kTypeUrlFieldNumber = 1;
const ::std::string& type_url() const;
void set_type_url(const ::std::string& value);
#if LANG_CXX11
void set_type_url(::std::string&& value);
#endif
const std::string& type_url() const;
void set_type_url(const std::string& value);
void set_type_url(std::string&& value);
void set_type_url(const char* value);
void set_type_url(const char* value, size_t size);
::std::string* mutable_type_url();
::std::string* release_type_url();
void set_allocated_type_url(::std::string* type_url);
std::string* mutable_type_url();
std::string* release_type_url();
void set_allocated_type_url(std::string* type_url);
// bytes value = 2;
void clear_value();
static const int kValueFieldNumber = 2;
const ::std::string& value() const;
void set_value(const ::std::string& value);
#if LANG_CXX11
void set_value(::std::string&& value);
#endif
const std::string& value() const;
void set_value(const std::string& value);
void set_value(std::string&& value);
void set_value(const char* value);
void set_value(const void* value, size_t size);
::std::string* mutable_value();
::std::string* release_value();
void set_allocated_value(::std::string* value);
std::string* mutable_value();
std::string* release_value();
void set_allocated_value(std::string* value);
// @@protoc_insertion_point(class_scope:google.protobuf.Any)
private:
class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr type_url_;
::google::protobuf::internal::ArenaStringPtr value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::internal::AnyMetadata _any_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_url_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr value_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata _any_metadata_;
friend struct ::TableStruct_google_2fprotobuf_2fany_2eproto;
};
// ===================================================================
@ -227,107 +225,103 @@ class PROTOBUF_EXPORT Any final :
// string type_url = 1;
inline void Any::clear_type_url() {
type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& Any::type_url() const {
inline const std::string& Any::type_url() const {
// @@protoc_insertion_point(field_get:google.protobuf.Any.type_url)
return type_url_.GetNoArena();
}
inline void Any::set_type_url(const ::std::string& value) {
inline void Any::set_type_url(const std::string& value) {
type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Any.type_url)
}
#if LANG_CXX11
inline void Any::set_type_url(::std::string&& value) {
inline void Any::set_type_url(std::string&& value) {
type_url_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.type_url)
}
#endif
inline void Any::set_type_url(const char* value) {
GOOGLE_DCHECK(value != nullptr);
type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Any.type_url)
}
inline void Any::set_type_url(const char* value, size_t size) {
type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.type_url)
}
inline ::std::string* Any::mutable_type_url() {
inline std::string* Any::mutable_type_url() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Any.type_url)
return type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return type_url_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* Any::release_type_url() {
inline std::string* Any::release_type_url() {
// @@protoc_insertion_point(field_release:google.protobuf.Any.type_url)
return type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return type_url_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline void Any::set_allocated_type_url(::std::string* type_url) {
inline void Any::set_allocated_type_url(std::string* type_url) {
if (type_url != nullptr) {
} else {
}
type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_url);
type_url_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), type_url);
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.type_url)
}
// bytes value = 2;
inline void Any::clear_value() {
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& Any::value() const {
inline const std::string& Any::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Any.value)
return value_.GetNoArena();
}
inline void Any::set_value(const ::std::string& value) {
inline void Any::set_value(const std::string& value) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Any.value)
}
#if LANG_CXX11
inline void Any::set_value(::std::string&& value) {
inline void Any::set_value(std::string&& value) {
value_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.value)
}
#endif
inline void Any::set_value(const char* value) {
GOOGLE_DCHECK(value != nullptr);
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Any.value)
}
inline void Any::set_value(const void* value, size_t size) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.value)
}
inline ::std::string* Any::mutable_value() {
inline std::string* Any::mutable_value() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Any.value)
return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return value_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* Any::release_value() {
inline std::string* Any::release_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Any.value)
return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return value_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline void Any::set_allocated_value(::std::string* value) {
inline void Any::set_allocated_value(std::string* value) {
if (value != nullptr) {
} else {
}
value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
value_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.value)
}
@ -337,10 +331,9 @@ inline void Any::set_allocated_value(::std::string* value) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto

@ -40,8 +40,8 @@ namespace google {
namespace protobuf {
namespace internal {
string GetTypeUrl(StringPiece message_name,
StringPiece type_url_prefix) {
std::string GetTypeUrl(StringPiece message_name,
StringPiece type_url_prefix) {
if (!type_url_prefix.empty() &&
type_url_prefix[type_url_prefix.size() - 1] == '/') {
return StrCat(type_url_prefix, message_name);
@ -101,10 +101,10 @@ bool AnyMetadata::InternalIs(StringPiece type_name) const {
HasSuffixString(type_url, type_name);
}
bool ParseAnyTypeUrl(const string& type_url, string* url_prefix,
string* full_type_name) {
bool ParseAnyTypeUrl(const std::string& type_url, std::string* url_prefix,
std::string* full_type_name) {
size_t pos = type_url.find_last_of("/");
if (pos == string::npos || pos + 1 == type_url.size()) {
if (pos == std::string::npos || pos + 1 == type_url.size()) {
return false;
}
if (url_prefix) {
@ -114,7 +114,7 @@ bool ParseAnyTypeUrl(const string& type_url, string* url_prefix,
return true;
}
bool ParseAnyTypeUrl(const string& type_url, string* full_type_name) {
bool ParseAnyTypeUrl(const std::string& type_url, std::string* full_type_name) {
return ParseAnyTypeUrl(type_url, nullptr, full_type_name);
}

@ -44,7 +44,7 @@ TEST(AnyTest, TestPackAndUnpack) {
protobuf_unittest::TestAny message;
message.mutable_any_value()->PackFrom(submessage);
string data = message.SerializeAsString();
std::string data = message.SerializeAsString();
ASSERT_TRUE(message.ParseFromString(data));
EXPECT_TRUE(message.has_any_value());
@ -73,7 +73,7 @@ TEST(AnyTest, TestPackAndUnpackAny) {
protobuf_unittest::TestAny message;
message.mutable_any_value()->PackFrom(any);
string data = message.SerializeAsString();
std::string data = message.SerializeAsString();
ASSERT_TRUE(message.ParseFromString(data));
EXPECT_TRUE(message.has_any_value());

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -35,6 +35,7 @@
#include <limits>
#include <type_traits>
#include <utility>
#ifdef max
#undef max // Visual Studio defines this macro
#endif
@ -244,10 +245,7 @@ struct ArenaOptions {
// well as protobuf container types like RepeatedPtrField and Map. The protocol
// is internal to protobuf and is not guaranteed to be stable. Non-proto types
// should not rely on this protocol.
//
// Do NOT subclass Arena. This class will be marked as final when C++11 is
// enabled.
class PROTOBUF_EXPORT Arena {
class PROTOBUF_EXPORT Arena final {
public:
// Arena constructor taking custom options. See ArenaOptions below for
// descriptions of the options available.
@ -442,7 +440,11 @@ class PROTOBUF_EXPORT Arena {
sizeof(char)>
is_arena_constructable;
template <typename U>
template <typename U,
typename std::enable_if<
std::is_same<Arena*, decltype(std::declval<const U>()
.GetArena())>::value,
int>::type = 0>
static char HasGetArena(decltype(&U::GetArena));
template <typename U>
static double HasGetArena(...);
@ -480,6 +482,9 @@ class PROTOBUF_EXPORT Arena {
};
private:
template <typename T>
struct has_get_arena : InternalHelper<T>::has_get_arena {};
template <typename T, typename... Args>
PROTOBUF_ALWAYS_INLINE static T* CreateMessageInternal(Arena* arena,
Args&&... args) {
@ -673,15 +678,15 @@ class PROTOBUF_EXPORT Arena {
}
template <typename T,
typename std::enable_if<!is_arena_constructable<T>::value &&
InternalHelper<T>::has_get_arena::value,
has_get_arena<T>::value,
int>::type = 0>
PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) {
return value->GetArena();
}
template <typename T, typename std::enable_if<
!is_arena_constructable<T>::value &&
!InternalHelper<T>::has_get_arena::value,
int>::type = 0>
template <typename T,
typename std::enable_if<!is_arena_constructable<T>::value &&
!has_get_arena<T>::value,
int>::type = 0>
PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) {
return nullptr;
}

@ -59,10 +59,11 @@
using proto2_arena_unittest::ArenaMessage;
using protobuf_unittest::TestAllTypes;
using protobuf_unittest::TestAllExtensions;
using protobuf_unittest::TestOneof2;
using protobuf_unittest::TestAllTypes;
using protobuf_unittest::TestEmptyMessage;
using protobuf_unittest::TestOneof2;
using protobuf_unittest_no_arena::TestNoArenaMessage;
namespace google {
namespace protobuf {
@ -112,14 +113,14 @@ class PleaseDontCopyMe {
// A class that takes four different types as constructor arguments.
class MustBeConstructedWithOneThroughFour {
public:
MustBeConstructedWithOneThroughFour(
int one, const char* two, const string& three,
const PleaseDontCopyMe* four)
MustBeConstructedWithOneThroughFour(int one, const char* two,
const std::string& three,
const PleaseDontCopyMe* four)
: one_(one), two_(two), three_(three), four_(four) {}
int one_;
const char* const two_;
string three_;
std::string three_;
const PleaseDontCopyMe* four_;
private:
@ -129,21 +130,29 @@ class MustBeConstructedWithOneThroughFour {
// A class that takes eight different types as constructor arguments.
class MustBeConstructedWithOneThroughEight {
public:
MustBeConstructedWithOneThroughEight(
int one, const char* two, const string& three,
const PleaseDontCopyMe* four, int five, const char* six,
const string& seven, const string& eight)
: one_(one), two_(two), three_(three), four_(four), five_(five),
six_(six), seven_(seven), eight_(eight) {}
MustBeConstructedWithOneThroughEight(int one, const char* two,
const std::string& three,
const PleaseDontCopyMe* four, int five,
const char* six,
const std::string& seven,
const std::string& eight)
: one_(one),
two_(two),
three_(three),
four_(four),
five_(five),
six_(six),
seven_(seven),
eight_(eight) {}
int one_;
const char* const two_;
string three_;
std::string three_;
const PleaseDontCopyMe* four_;
int five_;
const char* const six_;
string seven_;
string eight_;
std::string seven_;
std::string eight_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MustBeConstructedWithOneThroughEight);
@ -152,16 +161,14 @@ class MustBeConstructedWithOneThroughEight {
TEST(ArenaTest, ArenaConstructable) {
EXPECT_TRUE(Arena::is_arena_constructable<TestAllTypes>::type::value);
EXPECT_TRUE(Arena::is_arena_constructable<const TestAllTypes>::type::value);
EXPECT_FALSE(Arena::is_arena_constructable<
protobuf_unittest_no_arena::TestNoArenaMessage>::type::value);
EXPECT_FALSE(Arena::is_arena_constructable<TestNoArenaMessage>::type::value);
EXPECT_FALSE(Arena::is_arena_constructable<Arena>::type::value);
}
TEST(ArenaTest, DestructorSkippable) {
EXPECT_TRUE(Arena::is_destructor_skippable<TestAllTypes>::type::value);
EXPECT_TRUE(Arena::is_destructor_skippable<const TestAllTypes>::type::value);
EXPECT_FALSE(Arena::is_destructor_skippable<
protobuf_unittest_no_arena::TestNoArenaMessage>::type::value);
EXPECT_FALSE(Arena::is_destructor_skippable<TestNoArenaMessage>::type::value);
EXPECT_FALSE(Arena::is_destructor_skippable<Arena>::type::value);
}
@ -171,12 +178,12 @@ TEST(ArenaTest, BasicCreate) {
EXPECT_TRUE(Arena::Create<int64>(&arena) != NULL);
EXPECT_TRUE(Arena::Create<float>(&arena) != NULL);
EXPECT_TRUE(Arena::Create<double>(&arena) != NULL);
EXPECT_TRUE(Arena::Create<string>(&arena) != NULL);
EXPECT_TRUE(Arena::Create<std::string>(&arena) != NULL);
arena.Own(new int32);
arena.Own(new int64);
arena.Own(new float);
arena.Own(new double);
arena.Own(new string);
arena.Own(new std::string);
arena.Own<int>(NULL);
Notifier notifier;
SimpleDataType* data = Arena::Create<SimpleDataType>(&arena);
@ -190,8 +197,8 @@ TEST(ArenaTest, BasicCreate) {
TEST(ArenaTest, CreateAndConstCopy) {
Arena arena;
const string s("foo");
const string* s_copy = Arena::Create<string>(&arena, s);
const std::string s("foo");
const std::string* s_copy = Arena::Create<std::string>(&arena, s);
EXPECT_TRUE(s_copy != NULL);
EXPECT_EQ("foo", s);
EXPECT_EQ("foo", *s_copy);
@ -199,8 +206,8 @@ TEST(ArenaTest, CreateAndConstCopy) {
TEST(ArenaTest, CreateAndNonConstCopy) {
Arena arena;
string s("foo");
const string* s_copy = Arena::Create<string>(&arena, s);
std::string s("foo");
const std::string* s_copy = Arena::Create<std::string>(&arena, s);
EXPECT_TRUE(s_copy != NULL);
EXPECT_EQ("foo", s);
EXPECT_EQ("foo", *s_copy);
@ -208,8 +215,8 @@ TEST(ArenaTest, CreateAndNonConstCopy) {
TEST(ArenaTest, CreateAndMove) {
Arena arena;
string s("foo");
const string* s_move = Arena::Create<string>(&arena, std::move(s));
std::string s("foo");
const std::string* s_move = Arena::Create<std::string>(&arena, std::move(s));
EXPECT_TRUE(s_move != NULL);
EXPECT_TRUE(s.empty()); // NOLINT
EXPECT_EQ("foo", *s_move);
@ -217,7 +224,7 @@ TEST(ArenaTest, CreateAndMove) {
TEST(ArenaTest, CreateWithFourConstructorArguments) {
Arena arena;
const string three("3");
const std::string three("3");
const PleaseDontCopyMe four(4);
const MustBeConstructedWithOneThroughFour* new_object =
Arena::Create<MustBeConstructedWithOneThroughFour>(
@ -231,10 +238,10 @@ TEST(ArenaTest, CreateWithFourConstructorArguments) {
TEST(ArenaTest, CreateWithEightConstructorArguments) {
Arena arena;
const string three("3");
const std::string three("3");
const PleaseDontCopyMe four(4);
const string seven("7");
const string eight("8");
const std::string seven("7");
const std::string eight("8");
const MustBeConstructedWithOneThroughEight* new_object =
Arena::Create<MustBeConstructedWithOneThroughEight>(
&arena, 1, "2", three, &four, 5, "6", seven, eight);
@ -251,14 +258,14 @@ TEST(ArenaTest, CreateWithEightConstructorArguments) {
class PleaseMoveMe {
public:
explicit PleaseMoveMe(const string& value) : value_(value) {}
explicit PleaseMoveMe(const std::string& value) : value_(value) {}
PleaseMoveMe(PleaseMoveMe&&) = default;
PleaseMoveMe(const PleaseMoveMe&) = delete;
const string& value() const { return value_; }
const std::string& value() const { return value_; }
private:
string value_;
std::string value_;
};
TEST(ArenaTest, CreateWithMoveArguments) {
@ -411,7 +418,7 @@ TEST(ArenaTest, ReflectionSwapFields) {
reflection->SwapFields(arena1_message, arena2_message, fields);
EXPECT_EQ(&arena1, arena1_message->GetArena());
EXPECT_EQ(&arena2, arena2_message->GetArena());
string output;
std::string output;
arena1_message->SerializeToString(&output);
EXPECT_EQ(0, output.size());
TestUtil::ExpectAllFieldsSet(*arena2_message);
@ -461,7 +468,7 @@ TEST(ArenaTest, SetAllocatedMessage) {
arena_message->set_allocated_optional_nested_message(nested);
EXPECT_EQ(118, arena_message->optional_nested_message().bb());
protobuf_unittest_no_arena::TestNoArenaMessage no_arena_message;
TestNoArenaMessage no_arena_message;
EXPECT_FALSE(no_arena_message.has_arena_message());
no_arena_message.set_allocated_arena_message(NULL);
EXPECT_FALSE(no_arena_message.has_arena_message());
@ -485,7 +492,7 @@ TEST(ArenaTest, ReleaseMessage) {
TEST(ArenaTest, SetAllocatedString) {
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
string* allocated_str = new string("hello");
std::string* allocated_str = new std::string("hello");
arena_message->set_allocated_optional_string(allocated_str);
EXPECT_EQ("hello", arena_message->optional_string());
}
@ -494,7 +501,7 @@ TEST(ArenaTest, ReleaseString) {
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->set_optional_string("hello");
std::unique_ptr<string> released_str(
std::unique_ptr<std::string> released_str(
arena_message->release_optional_string());
EXPECT_EQ("hello", *released_str);
@ -510,7 +517,7 @@ TEST(ArenaTest, SwapBetweenArenasWithAllFieldsSet) {
TestAllTypes* arena2_message = Arena::CreateMessage<TestAllTypes>(&arena2);
TestUtil::SetAllFields(arena2_message);
arena2_message->Swap(arena1_message);
string output;
std::string output;
arena2_message->SerializeToString(&output);
EXPECT_EQ(0, output.size());
}
@ -548,7 +555,7 @@ TEST(ArenaTest, SwapBetweenArenasUsingReflection) {
TestUtil::SetAllFields(arena2_message);
const Reflection* r = arena2_message->GetReflection();
r->Swap(arena1_message, arena2_message);
string output;
std::string output;
arena2_message->SerializeToString(&output);
EXPECT_EQ(0, output.size());
}
@ -571,7 +578,7 @@ TEST(ArenaTest, SwapBetweenArenaAndNonArenaUsingReflection) {
TEST(ArenaTest, ReleaseFromArenaMessageMakesCopy) {
TestAllTypes::NestedMessage* nested_msg = NULL;
string* nested_string = NULL;
std::string* nested_string = NULL;
{
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
@ -763,7 +770,7 @@ TEST(ArenaTest, AddAllocatedToRepeatedField) {
// Heap-arena case for strings (which are not arena-allocated).
arena1_message->Clear();
for (int i = 0; i < 10; i++) {
string* s = new string("Test");
std::string* s = new std::string("Test");
arena1_message->mutable_repeated_string()->
AddAllocated(s);
// Should not copy.
@ -862,19 +869,21 @@ TEST(ArenaTest, ReleaseLastRepeatedField) {
// no delete -- |released| is on the arena.
}
// Test string case as well. ReleaseLast() in this case must copy the string,
// even though it was originally heap-allocated and its pointer was simply
// appended to the repeated field's internal vector, because the string was
// placed on the arena's destructor list and cannot be removed from that list
// (so the arena permanently owns the original instance).
// Test string case as well. ReleaseLast() in this case must copy the
// string, even though it was originally heap-allocated and its pointer
// was simply appended to the repeated field's internal vector, because the
// string was placed on the arena's destructor list and cannot be removed
// from that list (so the arena permanently owns the original instance).
arena_message->Clear();
for (int i = 0; i < 10; i++) {
string* s = new string("Test");
std::string* s = new std::string("Test");
arena_message->mutable_repeated_string()->AddAllocated(s);
}
for (int i = 0; i < 10; i++) {
const string* orig_element = &arena_message->repeated_string(10 - 1 - i);
string* released = arena_message->mutable_repeated_string()->ReleaseLast();
const std::string* orig_element =
&arena_message->repeated_string(10 - 1 - i);
std::string* released =
arena_message->mutable_repeated_string()->ReleaseLast();
EXPECT_NE(released, orig_element);
EXPECT_EQ("Test", *released);
delete released;
@ -889,7 +898,7 @@ TEST(ArenaTest, UnsafeArenaReleaseAdd) {
Arena arena;
TestAllTypes* message1 = Arena::CreateMessage<TestAllTypes>(&arena);
TestAllTypes* message2 = Arena::CreateMessage<TestAllTypes>(&arena);
string* arena_string = Arena::Create<string>(&arena);
std::string* arena_string = Arena::Create<std::string>(&arena);
*arena_string = kContent;
message1->unsafe_arena_set_allocated_optional_string(arena_string);
@ -902,7 +911,7 @@ TEST(ArenaTest, UnsafeArenaAddAllocated) {
Arena arena;
TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
for (int i = 0; i < 10; i++) {
string* arena_string = Arena::Create<string>(&arena);
std::string* arena_string = Arena::Create<std::string>(&arena);
message->mutable_repeated_string()->UnsafeArenaAddAllocated(arena_string);
EXPECT_EQ(arena_string, message->mutable_repeated_string(i));
}
@ -912,7 +921,7 @@ TEST(ArenaTest, UnsafeArenaRelease) {
Arena arena;
TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
string* s = new string("test string");
std::string* s = new std::string("test string");
message->unsafe_arena_set_allocated_optional_string(s);
EXPECT_TRUE(message->has_optional_string());
EXPECT_EQ("test string", message->optional_string());
@ -920,7 +929,7 @@ TEST(ArenaTest, UnsafeArenaRelease) {
EXPECT_FALSE(message->has_optional_string());
delete s;
s = new string("test string");
s = new std::string("test string");
message->unsafe_arena_set_allocated_oneof_string(s);
EXPECT_TRUE(message->has_oneof_string());
EXPECT_EQ("test string", message->oneof_string());
@ -934,9 +943,9 @@ TEST(ArenaTest, OneofMerge) {
TestAllTypes* message0 = Arena::CreateMessage<TestAllTypes>(&arena);
TestAllTypes* message1 = Arena::CreateMessage<TestAllTypes>(&arena);
message0->unsafe_arena_set_allocated_oneof_string(new string("x"));
message0->unsafe_arena_set_allocated_oneof_string(new std::string("x"));
ASSERT_TRUE(message0->has_oneof_string());
message1->unsafe_arena_set_allocated_oneof_string(new string("y"));
message1->unsafe_arena_set_allocated_oneof_string(new std::string("y"));
ASSERT_TRUE(message1->has_oneof_string());
EXPECT_EQ("x", message0->oneof_string());
EXPECT_EQ("y", message1->oneof_string());
@ -1005,8 +1014,8 @@ void TestSwapRepeatedField(Arena* arena1, Arena* arena2) {
field1.Swap(&field2);
EXPECT_EQ(5, field1.size());
EXPECT_EQ(10, field2.size());
EXPECT_TRUE(string("field1") == field2.Get(0).optional_string());
EXPECT_TRUE(string("field2") == field1.Get(0).optional_string());
EXPECT_TRUE(std::string("field1") == field2.Get(0).optional_string());
EXPECT_TRUE(std::string("field2") == field1.Get(0).optional_string());
// Ensure that fields retained their original order:
for (int i = 0; i < field1.size(); i++) {
EXPECT_EQ(i, field1.Get(i).optional_int32());
@ -1044,8 +1053,8 @@ TEST(ArenaTest, ExtensionsOnArena) {
Arena::CreateMessage<TestAllExtensions>(&arena);
message_ext->SetExtension(
protobuf_unittest::optional_int32_extension, 42);
message_ext->SetExtension(
protobuf_unittest::optional_string_extension, string("test"));
message_ext->SetExtension(protobuf_unittest::optional_string_extension,
std::string("test"));
message_ext->MutableExtension(
protobuf_unittest::optional_nested_message_extension)->set_bb(42);
}
@ -1157,7 +1166,7 @@ TEST(ArenaTest, MutableMessageReflection) {
void FillArenaAwareFields(TestAllTypes* message) {
string test_string = "hello world";
std::string test_string = "hello world";
message->set_optional_int32(42);
message->set_optional_string(test_string);
message->set_optional_bytes(test_string);
@ -1213,7 +1222,7 @@ TEST(ArenaTest, MessageLiteOnArena) {
TestAllTypes initial_message;
FillArenaAwareFields(&initial_message);
string serialized;
std::string serialized;
initial_message.SerializeToString(&serialized);
{
@ -1236,14 +1245,14 @@ TEST(ArenaTest, MessageLiteOnArena) {
// (even if this was not its original intent).
TEST(ArenaTest, RepeatedFieldWithNonPODType) {
{
RepeatedField<string> field_on_heap;
RepeatedField<std::string> field_on_heap;
for (int i = 0; i < 100; i++) {
*field_on_heap.Add() = "test string long enough to exceed inline buffer";
}
}
{
Arena arena;
RepeatedField<string> field_on_arena(&arena);
RepeatedField<std::string> field_on_arena(&arena);
for (int i = 0; i < 100; i++) {
*field_on_arena.Add() = "test string long enough to exceed inline buffer";
}
@ -1339,6 +1348,33 @@ TEST(ArenaTest, GetArenaShouldReturnNullForNonArenaAllocatedMessages) {
EXPECT_EQ(NULL, Arena::GetArena(const_pointer_to_message));
}
TEST(ArenaTest, GetArenaShouldReturnNullForNonArenaCompatibleTypes) {
TestNoArenaMessage message;
const TestNoArenaMessage* const_pointer_to_message = &message;
EXPECT_EQ(nullptr, Arena::GetArena(&message));
EXPECT_EQ(nullptr, Arena::GetArena(const_pointer_to_message));
// Test that GetArena returns nullptr for types that have a GetArena method
// that doesn't return Arena*.
struct {
int GetArena() const { return 0; }
} has_get_arena_method_wrong_return_type;
EXPECT_EQ(nullptr, Arena::GetArena(&has_get_arena_method_wrong_return_type));
// Test that GetArena returns nullptr for types that have a GetArena alias.
struct {
using GetArena = Arena*;
} has_get_arena_alias;
EXPECT_EQ(nullptr, Arena::GetArena(&has_get_arena_alias));
// Test that GetArena returns nullptr for types that have a GetArena data
// member.
struct {
Arena GetArena;
} has_get_arena_data_member;
EXPECT_EQ(nullptr, Arena::GetArena(&has_get_arena_data_member));
}
TEST(ArenaTest, AddCleanup) {
Arena arena;
for (int i = 0; i < 100; i++) {
@ -1351,7 +1387,7 @@ TEST(ArenaTest, UnsafeSetAllocatedOnArena) {
TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
EXPECT_FALSE(message->has_optional_string());
string owned_string = "test with long enough content to heap-allocate";
std::string owned_string = "test with long enough content to heap-allocate";
message->unsafe_arena_set_allocated_optional_string(&owned_string);
EXPECT_TRUE(message->has_optional_string());

@ -67,7 +67,7 @@ class TaggedPtr {
struct PROTOBUF_EXPORT ArenaStringPtr {
inline void Set(const ::std::string* default_value,
const ::std::string& value, ::google::protobuf::Arena* arena) {
const ::std::string& value, Arena* arena) {
if (ptr_ == default_value) {
CreateInstance(arena, &value);
} else {
@ -76,8 +76,7 @@ struct PROTOBUF_EXPORT ArenaStringPtr {
}
inline void SetLite(const ::std::string* default_value,
const ::std::string& value,
::google::protobuf::Arena* arena) {
const ::std::string& value, Arena* arena) {
Set(default_value, value, arena);
}
@ -85,7 +84,7 @@ struct PROTOBUF_EXPORT ArenaStringPtr {
inline const ::std::string& Get() const { return *ptr_; }
inline ::std::string* Mutable(const ::std::string* default_value,
::google::protobuf::Arena* arena) {
Arena* arena) {
if (ptr_ == default_value) {
CreateInstance(arena, default_value);
}
@ -97,7 +96,7 @@ struct PROTOBUF_EXPORT ArenaStringPtr {
// retains ownership. Clears this field back to NULL state. Used to implement
// release_<field>() methods on generated classes.
inline ::std::string* Release(const ::std::string* default_value,
::google::protobuf::Arena* arena) {
Arena* arena) {
if (ptr_ == default_value) {
return NULL;
}
@ -105,8 +104,8 @@ struct PROTOBUF_EXPORT ArenaStringPtr {
}
// Similar to Release, but ptr_ cannot be the default_value.
inline ::std::string* ReleaseNonDefault(
const ::std::string* default_value, ::google::protobuf::Arena* arena) {
inline ::std::string* ReleaseNonDefault(const ::std::string* default_value,
Arena* arena) {
GOOGLE_DCHECK(!IsDefault(default_value));
::std::string* released = NULL;
if (arena != NULL) {
@ -126,7 +125,7 @@ struct PROTOBUF_EXPORT ArenaStringPtr {
// state. Used to implement unsafe_arena_release_<field>() methods on
// generated classes.
inline ::std::string* UnsafeArenaRelease(const ::std::string* default_value,
::google::protobuf::Arena* /* arena */) {
Arena* /* arena */) {
if (ptr_ == default_value) {
return NULL;
}
@ -139,7 +138,7 @@ struct PROTOBUF_EXPORT ArenaStringPtr {
// destructor is registered with the arena. Used to implement
// set_allocated_<field> in generated classes.
inline void SetAllocated(const ::std::string* default_value,
::std::string* value, ::google::protobuf::Arena* arena) {
::std::string* value, Arena* arena) {
if (arena == NULL && ptr_ != default_value) {
Destroy(default_value, arena);
}
@ -159,7 +158,7 @@ struct PROTOBUF_EXPORT ArenaStringPtr {
// to implement unsafe_arena_set_allocated_<field> in generated classes.
inline void UnsafeArenaSetAllocated(const ::std::string* default_value,
::std::string* value,
::google::protobuf::Arena* /* arena */) {
Arena* /* arena */) {
if (value != NULL) {
ptr_ = value;
} else {
@ -201,8 +200,7 @@ struct PROTOBUF_EXPORT ArenaStringPtr {
}
// Frees storage (if not on an arena).
inline void Destroy(const ::std::string* default_value,
::google::protobuf::Arena* arena) {
inline void Destroy(const ::std::string* default_value, Arena* arena) {
if (arena == NULL && ptr_ != default_value) {
delete ptr_;
}
@ -213,7 +211,7 @@ struct PROTOBUF_EXPORT ArenaStringPtr {
// the user) will always be the empty string. Assumes that |default_value|
// is an empty string.
inline void ClearToEmpty(const ::std::string* default_value,
::google::protobuf::Arena* /* arena */) {
Arena* /* arena */) {
if (ptr_ == default_value) {
// Already set to default (which is empty) -- do nothing.
} else {
@ -234,7 +232,7 @@ struct PROTOBUF_EXPORT ArenaStringPtr {
// overhead of heap operations. After this returns, the content (as seen by
// the user) will always be equal to |default_value|.
inline void ClearToDefault(const ::std::string* default_value,
::google::protobuf::Arena* /* arena */) {
Arena* /* arena */) {
if (ptr_ == default_value) {
// Already set to default -- do nothing.
} else {
@ -370,8 +368,7 @@ struct PROTOBUF_EXPORT ArenaStringPtr {
::std::string* ptr_;
PROTOBUF_NOINLINE
void CreateInstance(::google::protobuf::Arena* arena,
const ::std::string* initial_value) {
void CreateInstance(Arena* arena, const ::std::string* initial_value) {
GOOGLE_DCHECK(initial_value != NULL);
// uses "new ::std::string" when arena is nullptr
ptr_ = Arena::Create< ::std::string >(arena, *initial_value);

@ -52,85 +52,83 @@ namespace protobuf {
using internal::ArenaStringPtr;
static string WrapString(const char* value) {
return value;
}
static std::string WrapString(const char* value) { return value; }
// Test ArenaStringPtr with arena == NULL.
TEST(ArenaStringPtrTest, ArenaStringPtrOnHeap) {
ArenaStringPtr field;
::std::string default_value = "default";
std::string default_value = "default";
field.UnsafeSetDefault(&default_value);
EXPECT_EQ(string("default"), field.Get());
EXPECT_EQ(std::string("default"), field.Get());
field.Set(&default_value, WrapString("Test short"), NULL);
EXPECT_EQ(string("Test short"), field.Get());
EXPECT_EQ(std::string("Test short"), field.Get());
field.Set(&default_value, WrapString("Test long long long long value"), NULL);
EXPECT_EQ(string("Test long long long long value"), field.Get());
field.Set(&default_value, string(""), NULL);
EXPECT_EQ(std::string("Test long long long long value"), field.Get());
field.Set(&default_value, std::string(""), NULL);
field.Destroy(&default_value, NULL);
ArenaStringPtr field2;
field2.UnsafeSetDefault(&default_value);
::std::string* mut = field2.Mutable(&default_value, NULL);
std::string* mut = field2.Mutable(&default_value, NULL);
EXPECT_EQ(mut, field2.Mutable(&default_value, NULL));
EXPECT_EQ(mut, &field2.Get());
EXPECT_NE(&default_value, mut);
EXPECT_EQ(string("default"), *mut);
EXPECT_EQ(std::string("default"), *mut);
*mut = "Test long long long long value"; // ensure string allocates storage
EXPECT_EQ(string("Test long long long long value"), field2.Get());
EXPECT_EQ(std::string("Test long long long long value"), field2.Get());
field2.Destroy(&default_value, NULL);
}
TEST(ArenaStringPtrTest, ArenaStringPtrOnArena) {
Arena arena;
ArenaStringPtr field;
::std::string default_value = "default";
std::string default_value = "default";
field.UnsafeSetDefault(&default_value);
EXPECT_EQ(string("default"), field.Get());
EXPECT_EQ(std::string("default"), field.Get());
field.Set(&default_value, WrapString("Test short"), &arena);
EXPECT_EQ(string("Test short"), field.Get());
EXPECT_EQ(std::string("Test short"), field.Get());
field.Set(&default_value, WrapString("Test long long long long value"),
&arena);
EXPECT_EQ(string("Test long long long long value"), field.Get());
field.Set(&default_value, string(""), &arena);
EXPECT_EQ(std::string("Test long long long long value"), field.Get());
field.Set(&default_value, std::string(""), &arena);
field.Destroy(&default_value, &arena);
ArenaStringPtr field2;
field2.UnsafeSetDefault(&default_value);
::std::string* mut = field2.Mutable(&default_value, &arena);
std::string* mut = field2.Mutable(&default_value, &arena);
EXPECT_EQ(mut, field2.Mutable(&default_value, &arena));
EXPECT_EQ(mut, &field2.Get());
EXPECT_NE(&default_value, mut);
EXPECT_EQ(string("default"), *mut);
EXPECT_EQ(std::string("default"), *mut);
*mut = "Test long long long long value"; // ensure string allocates storage
EXPECT_EQ(string("Test long long long long value"), field2.Get());
EXPECT_EQ(std::string("Test long long long long value"), field2.Get());
field2.Destroy(&default_value, &arena);
}
TEST(ArenaStringPtrTest, ArenaStringPtrOnArenaNoSSO) {
Arena arena;
ArenaStringPtr field;
::std::string default_value = "default";
std::string default_value = "default";
field.UnsafeSetDefault(&default_value);
EXPECT_EQ(string("default"), field.Get());
EXPECT_EQ(std::string("default"), field.Get());
// Avoid triggering the SSO optimization by setting the string to something
// larger than the internal buffer.
field.Set(&default_value, WrapString("Test long long long long value"),
&arena);
EXPECT_EQ(string("Test long long long long value"), field.Get());
field.Set(&default_value, string(""), &arena);
EXPECT_EQ(std::string("Test long long long long value"), field.Get());
field.Set(&default_value, std::string(""), &arena);
field.Destroy(&default_value, &arena);
ArenaStringPtr field2;
field2.UnsafeSetDefault(&default_value);
::std::string* mut = field2.Mutable(&default_value, &arena);
std::string* mut = field2.Mutable(&default_value, &arena);
EXPECT_EQ(mut, field2.Mutable(&default_value, &arena));
EXPECT_EQ(mut, &field2.Get());
EXPECT_NE(&default_value, mut);
EXPECT_EQ(string("default"), *mut);
EXPECT_EQ(std::string("default"), *mut);
*mut = "Test long long long long value"; // ensure string allocates storage
EXPECT_EQ(string("Test long long long long value"), field2.Get());
EXPECT_EQ(std::string("Test long long long long value"), field2.Get());
field2.Destroy(&default_value, &arena);
}

@ -57,8 +57,9 @@ class DescriptorCapturingGenerator : public CodeGenerator {
explicit DescriptorCapturingGenerator(FileDescriptorProto* file)
: file_(file) {}
virtual bool Generate(const FileDescriptor* file, const string& parameter,
GeneratorContext* context, string* error) const {
virtual bool Generate(const FileDescriptor* file,
const std::string& parameter, GeneratorContext* context,
std::string* error) const {
file->CopyTo(file_);
return true;
}
@ -68,21 +69,21 @@ class DescriptorCapturingGenerator : public CodeGenerator {
};
} // namespace
void AddFile(const string& filename, const string& data) {
void AddFile(const std::string& filename, const std::string& data) {
GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/" + filename, data,
true));
}
bool RunProtoCompiler(const string& filename,
const string& plugin_specific_args,
bool RunProtoCompiler(const std::string& filename,
const std::string& plugin_specific_args,
CommandLineInterface* cli, FileDescriptorProto* file) {
cli->SetInputsAreProtoPathRelative(true);
DescriptorCapturingGenerator capturing_generator(file);
cli->RegisterGenerator("--capture_out", &capturing_generator, "");
string proto_path = "-I" + TestTempDir();
string capture_out = "--capture_out=" + TestTempDir();
std::string proto_path = "-I" + TestTempDir();
std::string capture_out = "--capture_out=" + TestTempDir();
const char* argv[] = {"protoc", proto_path.c_str(),
plugin_specific_args.c_str(), capture_out.c_str(),
@ -91,15 +92,15 @@ bool RunProtoCompiler(const string& filename,
return cli->Run(5, argv) == 0;
}
bool DecodeMetadata(const string& path, GeneratedCodeInfo* info) {
string data;
bool DecodeMetadata(const std::string& path, GeneratedCodeInfo* info) {
std::string data;
GOOGLE_CHECK_OK(File::GetContents(path, &data, true));
io::ArrayInputStream input(data.data(), data.size());
return info->ParseFromZeroCopyStream(&input);
}
void FindAnnotationsOnPath(
const GeneratedCodeInfo& info, const string& source_file,
const GeneratedCodeInfo& info, const std::string& source_file,
const std::vector<int>& path,
std::vector<const GeneratedCodeInfo::Annotation*>* annotations) {
for (int i = 0; i < info.annotation_size(); ++i) {
@ -121,7 +122,7 @@ void FindAnnotationsOnPath(
}
const GeneratedCodeInfo::Annotation* FindAnnotationOnPath(
const GeneratedCodeInfo& info, const string& source_file,
const GeneratedCodeInfo& info, const std::string& source_file,
const std::vector<int>& path) {
std::vector<const GeneratedCodeInfo::Annotation*> annotations;
FindAnnotationsOnPath(info, source_file, path, &annotations);
@ -132,9 +133,9 @@ const GeneratedCodeInfo::Annotation* FindAnnotationOnPath(
}
bool AtLeastOneAnnotationMatchesSubstring(
const string& file_content,
const std::string& file_content,
const std::vector<const GeneratedCodeInfo::Annotation*>& annotations,
const string& expected_text) {
const std::string& expected_text) {
for (std::vector<const GeneratedCodeInfo::Annotation*>::const_iterator
i = annotations.begin(),
e = annotations.end();
@ -152,9 +153,9 @@ bool AtLeastOneAnnotationMatchesSubstring(
return false;
}
bool AnnotationMatchesSubstring(const string& file_content,
bool AnnotationMatchesSubstring(const std::string& file_content,
const GeneratedCodeInfo::Annotation* annotation,
const string& expected_text) {
const std::string& expected_text) {
std::vector<const GeneratedCodeInfo::Annotation*> annotations;
annotations.push_back(annotation);
return AtLeastOneAnnotationMatchesSubstring(file_content, annotations,

@ -52,7 +52,8 @@ struct ExpectedOutput {
std::string file_path;
std::string file_content;
GeneratedCodeInfo file_info;
explicit ExpectedOutput(const std::string& file_path) : file_path(file_path) {}
explicit ExpectedOutput(const std::string& file_path)
: file_path(file_path) {}
};
// Creates a file with name `filename` and content `data` in temp test

@ -46,11 +46,10 @@ namespace compiler {
CodeGenerator::~CodeGenerator() {}
bool CodeGenerator::GenerateAll(
const std::vector<const FileDescriptor*>& files,
const string& parameter,
GeneratorContext* generator_context,
string* error) const {
bool CodeGenerator::GenerateAll(const std::vector<const FileDescriptor*>& files,
const std::string& parameter,
GeneratorContext* generator_context,
std::string* error) const {
// Default implemenation is just to call the per file method, and prefix any
// error string with the file to provide context.
bool succeeded = true;
@ -74,13 +73,13 @@ bool CodeGenerator::GenerateAll(
GeneratorContext::~GeneratorContext() {}
io::ZeroCopyOutputStream*
GeneratorContext::OpenForAppend(const string& filename) {
io::ZeroCopyOutputStream* GeneratorContext::OpenForAppend(
const std::string& filename) {
return NULL;
}
io::ZeroCopyOutputStream* GeneratorContext::OpenForInsert(
const string& filename, const string& insertion_point) {
const std::string& filename, const std::string& insertion_point) {
GOOGLE_LOG(FATAL) << "This GeneratorContext does not support insertion.";
return NULL; // make compiler happy
}
@ -98,14 +97,15 @@ void GeneratorContext::GetCompilerVersion(Version* version) const {
}
// Parses a set of comma-delimited name/value pairs.
void ParseGeneratorParameter(const string& text,
std::vector<std::pair<string, string> >* output) {
std::vector<string> parts = Split(text, ",", true);
void ParseGeneratorParameter(
const std::string& text,
std::vector<std::pair<std::string, std::string> >* output) {
std::vector<std::string> parts = Split(text, ",", true);
for (int i = 0; i < parts.size(); i++) {
string::size_type equals_pos = parts[i].find_first_of('=');
std::pair<string, string> value;
if (equals_pos == string::npos) {
std::string::size_type equals_pos = parts[i].find_first_of('=');
std::pair<std::string, std::string> value;
if (equals_pos == std::string::npos) {
value.first = parts[i];
value.second = "";
} else {

@ -116,7 +116,7 @@ static const char* kDefaultDirectDependenciesViolationMsg =
// Returns true if the text looks like a Windows-style absolute path, starting
// with a drive letter. Example: "C:\foo". TODO(kenton): Share this with
// copy in importer.cc?
static bool IsWindowsAbsolutePath(const string& text) {
static bool IsWindowsAbsolutePath(const std::string& text) {
#if defined(_WIN32) || defined(__CYGWIN__)
return text.size() >= 3 && text[1] == ':' &&
isalpha(text[0]) &&
@ -147,13 +147,13 @@ void SetFdToBinaryMode(int fd) {
// (Text and binary are the same on non-Windows platforms.)
}
void AddTrailingSlash(string* path) {
void AddTrailingSlash(std::string* path) {
if (!path->empty() && path->at(path->size() - 1) != '/') {
path->push_back('/');
}
}
bool VerifyDirectoryExists(const string& path) {
bool VerifyDirectoryExists(const std::string& path) {
if (path.empty()) return true;
if (access(path.c_str(), F_OK) == -1) {
@ -168,12 +168,13 @@ bool VerifyDirectoryExists(const string& path) {
// parent if necessary, and so on. The full file name is actually
// (prefix + filename), but we assume |prefix| already exists and only create
// directories listed in |filename|.
bool TryCreateParentDirectory(const string& prefix, const string& filename) {
bool TryCreateParentDirectory(const std::string& prefix,
const std::string& filename) {
// Recursively create parent directories to the output file.
// On Windows, both '/' and '\' are valid path separators.
std::vector<string> parts =
std::vector<std::string> parts =
Split(filename, "/\\", true);
string path_so_far = prefix;
std::string path_so_far = prefix;
for (int i = 0; i < parts.size() - 1; i++) {
path_so_far += parts[i];
if (mkdir(path_so_far.c_str(), 0777) != 0) {
@ -190,7 +191,7 @@ bool TryCreateParentDirectory(const string& prefix, const string& filename) {
}
// Get the absolute path of this protoc binary.
bool GetProtocAbsolutePath(string* path) {
bool GetProtocAbsolutePath(std::string* path) {
#ifdef _WIN32
char buffer[MAX_PATH];
int len = GetModuleFileNameA(NULL, buffer, MAX_PATH);
@ -218,51 +219,55 @@ bool GetProtocAbsolutePath(string* path) {
// Whether a path is where google/protobuf/descriptor.proto and other well-known
// type protos are installed.
bool IsInstalledProtoPath(const string& path) {
bool IsInstalledProtoPath(const std::string& path) {
// Checking the descriptor.proto file should be good enough.
string file_path = path + "/google/protobuf/descriptor.proto";
std::string file_path = path + "/google/protobuf/descriptor.proto";
return access(file_path.c_str(), F_OK) != -1;
}
// Add the paths where google/protobuf/descriptor.proto and other well-known
// type protos are installed.
void AddDefaultProtoPaths(std::vector<std::pair<string, string> >* paths) {
void AddDefaultProtoPaths(
std::vector<std::pair<std::string, std::string> >* paths) {
// TODO(xiaofeng): The code currently only checks relative paths of where
// the protoc binary is installed. We probably should make it handle more
// cases than that.
string path;
std::string path;
if (!GetProtocAbsolutePath(&path)) {
return;
}
// Strip the binary name.
size_t pos = path.find_last_of("/\\");
if (pos == string::npos || pos == 0) {
if (pos == std::string::npos || pos == 0) {
return;
}
path = path.substr(0, pos);
// Check the binary's directory.
if (IsInstalledProtoPath(path)) {
paths->push_back(std::pair<string, string>("", path));
paths->push_back(std::pair<std::string, std::string>("", path));
return;
}
// Check if there is an include subdirectory.
if (IsInstalledProtoPath(path + "/include")) {
paths->push_back(std::pair<string, string>("", path + "/include"));
paths->push_back(
std::pair<std::string, std::string>("", path + "/include"));
return;
}
// Check if the upper level directory has an "include" subdirectory.
pos = path.find_last_of("/\\");
if (pos == string::npos || pos == 0) {
if (pos == std::string::npos || pos == 0) {
return;
}
path = path.substr(0, pos);
if (IsInstalledProtoPath(path + "/include")) {
paths->push_back(std::pair<string, string>("", path + "/include"));
paths->push_back(
std::pair<std::string, std::string>("", path + "/include"));
return;
}
}
string PluginName(const string& plugin_prefix, const string& directive) {
string PluginName(const std::string& plugin_prefix,
const std::string& directive) {
// Assuming the directive starts with "--" and ends with "_out" or "_opt",
// strip the "--" and "_out/_opt" and add the plugin prefix.
return plugin_prefix + "gen-" + directive.substr(2, directive.size() - 6);
@ -281,53 +286,47 @@ class CommandLineInterface::ErrorPrinter
~ErrorPrinter() {}
// implements MultiFileErrorCollector ------------------------------
void AddError(const string& filename, int line, int column,
const string& message) {
void AddError(const std::string& filename, int line, int column,
const std::string& message) {
found_errors_ = true;
AddErrorOrWarning(filename, line, column, message, "error", std::cerr);
}
void AddWarning(const string& filename, int line, int column,
const string& message) {
void AddWarning(const std::string& filename, int line, int column,
const std::string& message) {
AddErrorOrWarning(filename, line, column, message, "warning", std::clog);
}
// implements io::ErrorCollector -----------------------------------
void AddError(int line, int column, const string& message) {
void AddError(int line, int column, const std::string& message) {
AddError("input", line, column, message);
}
void AddWarning(int line, int column, const string& message) {
void AddWarning(int line, int column, const std::string& message) {
AddErrorOrWarning("input", line, column, message, "warning", std::clog);
}
// implements DescriptorPool::ErrorCollector-------------------------
void AddError(
const string& filename,
const string& element_name,
const Message* descriptor,
ErrorLocation location,
const string& message) {
void AddError(const std::string& filename, const std::string& element_name,
const Message* descriptor, ErrorLocation location,
const std::string& message) {
AddErrorOrWarning(filename, -1, -1, message, "error", std::cerr);
}
void AddWarning(
const string& filename,
const string& element_name,
const Message* descriptor,
ErrorLocation location,
const string& message) {
void AddWarning(const std::string& filename, const std::string& element_name,
const Message* descriptor, ErrorLocation location,
const std::string& message) {
AddErrorOrWarning(filename, -1, -1, message, "warning", std::clog);
}
bool FoundErrors() const { return found_errors_; }
private:
void AddErrorOrWarning(const string& filename, int line, int column,
const string& message, const string& type,
void AddErrorOrWarning(const std::string& filename, int line, int column,
const std::string& message, const std::string& type,
std::ostream& out) {
// Print full path when running under MSVS
string dfile;
std::string dfile;
if (format_ == CommandLineInterface::ERROR_FORMAT_MSVS &&
tree_ != NULL &&
tree_->VirtualFileToDiskFile(filename, &dfile)) {
@ -374,24 +373,24 @@ class CommandLineInterface::GeneratorContextImpl : public GeneratorContext {
// Write all files in the directory to disk at the given output location,
// which must end in a '/'.
bool WriteAllToDisk(const string& prefix);
bool WriteAllToDisk(const std::string& prefix);
// Write the contents of this directory to a ZIP-format archive with the
// given name.
bool WriteAllToZip(const string& filename);
bool WriteAllToZip(const std::string& filename);
// Add a boilerplate META-INF/MANIFEST.MF file as required by the Java JAR
// format, unless one has already been written.
void AddJarManifest();
// Get name of all output files.
void GetOutputFilenames(std::vector<string>* output_filenames);
void GetOutputFilenames(std::vector<std::string>* output_filenames);
// implements GeneratorContext --------------------------------------
io::ZeroCopyOutputStream* Open(const string& filename);
io::ZeroCopyOutputStream* OpenForAppend(const string& filename);
io::ZeroCopyOutputStream* OpenForInsert(
const string& filename, const string& insertion_point);
io::ZeroCopyOutputStream* Open(const std::string& filename);
io::ZeroCopyOutputStream* OpenForAppend(const std::string& filename);
io::ZeroCopyOutputStream* OpenForInsert(const std::string& filename,
const std::string& insertion_point);
void ListParsedFiles(std::vector<const FileDescriptor*>* output) {
*output = parsed_files_;
}
@ -401,7 +400,7 @@ class CommandLineInterface::GeneratorContextImpl : public GeneratorContext {
// map instead of unordered_map so that files are written in order (good when
// writing zips).
std::map<string, string*> files_;
std::map<std::string, std::string*> files_;
const std::vector<const FileDescriptor*>& parsed_files_;
bool had_error_;
};
@ -409,10 +408,11 @@ class CommandLineInterface::GeneratorContextImpl : public GeneratorContext {
class CommandLineInterface::MemoryOutputStream
: public io::ZeroCopyOutputStream {
public:
MemoryOutputStream(GeneratorContextImpl* directory, const string& filename,
bool append_mode);
MemoryOutputStream(GeneratorContextImpl* directory, const string& filename,
const string& insertion_point);
MemoryOutputStream(GeneratorContextImpl* directory,
const std::string& filename, bool append_mode);
MemoryOutputStream(GeneratorContextImpl* directory,
const std::string& filename,
const std::string& insertion_point);
virtual ~MemoryOutputStream();
// implements ZeroCopyOutputStream ---------------------------------
@ -430,11 +430,11 @@ class CommandLineInterface::MemoryOutputStream
// Where to insert the string when it's done.
GeneratorContextImpl* directory_;
string filename_;
string insertion_point_;
std::string filename_;
std::string insertion_point_;
// The string we're building.
string data_;
std::string data_;
// Whether we should append the output stream to the existing file.
bool append_mode_;
@ -455,7 +455,7 @@ CommandLineInterface::GeneratorContextImpl::~GeneratorContextImpl() {
}
bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk(
const string& prefix) {
const std::string& prefix) {
if (had_error_) {
return false;
}
@ -464,16 +464,17 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk(
return false;
}
for (std::map<string, string*>::const_iterator iter = files_.begin();
for (std::map<std::string, std::string*>::const_iterator iter =
files_.begin();
iter != files_.end(); ++iter) {
const string& relative_filename = iter->first;
const std::string& relative_filename = iter->first;
const char* data = iter->second->data();
int size = iter->second->size();
if (!TryCreateParentDirectory(prefix, relative_filename)) {
return false;
}
string filename = prefix + relative_filename;
std::string filename = prefix + relative_filename;
// Create the output file.
int file_descriptor;
@ -530,7 +531,7 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk(
}
bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip(
const string& filename) {
const std::string& filename) {
if (had_error_) {
return false;
}
@ -552,7 +553,8 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip(
io::FileOutputStream stream(file_descriptor);
ZipWriter zip_writer(&stream);
for (std::map<string, string*>::const_iterator iter = files_.begin();
for (std::map<std::string, std::string*>::const_iterator iter =
files_.begin();
iter != files_.end(); ++iter) {
zip_writer.Write(iter->first, *iter->second);
}
@ -571,9 +573,9 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip(
}
void CommandLineInterface::GeneratorContextImpl::AddJarManifest() {
string** map_slot = &files_["META-INF/MANIFEST.MF"];
std::string** map_slot = &files_["META-INF/MANIFEST.MF"];
if (*map_slot == NULL) {
*map_slot = new string(
*map_slot = new std::string(
"Manifest-Version: 1.0\n"
"Created-By: 1.6.0 (protoc)\n"
"\n");
@ -581,58 +583,57 @@ void CommandLineInterface::GeneratorContextImpl::AddJarManifest() {
}
void CommandLineInterface::GeneratorContextImpl::GetOutputFilenames(
std::vector<string>* output_filenames) {
for (std::map<string, string*>::iterator iter = files_.begin();
std::vector<std::string>* output_filenames) {
for (std::map<std::string, std::string*>::iterator iter = files_.begin();
iter != files_.end(); ++iter) {
output_filenames->push_back(iter->first);
}
}
io::ZeroCopyOutputStream* CommandLineInterface::GeneratorContextImpl::Open(
const string& filename) {
const std::string& filename) {
return new MemoryOutputStream(this, filename, false);
}
io::ZeroCopyOutputStream*
CommandLineInterface::GeneratorContextImpl::OpenForAppend(
const string& filename) {
const std::string& filename) {
return new MemoryOutputStream(this, filename, true);
}
io::ZeroCopyOutputStream*
CommandLineInterface::GeneratorContextImpl::OpenForInsert(
const string& filename, const string& insertion_point) {
const std::string& filename, const std::string& insertion_point) {
return new MemoryOutputStream(this, filename, insertion_point);
}
// -------------------------------------------------------------------
CommandLineInterface::MemoryOutputStream::MemoryOutputStream(
GeneratorContextImpl* directory, const string& filename, bool append_mode)
GeneratorContextImpl* directory, const std::string& filename,
bool append_mode)
: directory_(directory),
filename_(filename),
append_mode_(append_mode),
inner_(new io::StringOutputStream(&data_)) {
}
inner_(new io::StringOutputStream(&data_)) {}
CommandLineInterface::MemoryOutputStream::MemoryOutputStream(
GeneratorContextImpl* directory, const string& filename,
const string& insertion_point)
GeneratorContextImpl* directory, const std::string& filename,
const std::string& insertion_point)
: directory_(directory),
filename_(filename),
insertion_point_(insertion_point),
inner_(new io::StringOutputStream(&data_)) {
}
inner_(new io::StringOutputStream(&data_)) {}
void CommandLineInterface::MemoryOutputStream::UpdateMetadata(
size_t insertion_offset, size_t insertion_length) {
std::map<string, string*>::iterator meta_file =
std::map<std::string, std::string*>::iterator meta_file =
directory_->files_.find(filename_ + ".meta");
if (meta_file == directory_->files_.end() || !meta_file->second) {
// No metadata was recorded for this file.
return;
}
string* encoded_data = meta_file->second;
std::string* encoded_data = meta_file->second;
GeneratedCodeInfo metadata;
bool is_text_format = false;
if (!metadata.ParseFromString(*encoded_data)) {
@ -667,7 +668,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
inner_.reset();
// Insert into the directory.
string** map_slot = &directory_->files_[filename_];
std::string** map_slot = &directory_->files_[filename_];
if (insertion_point_.empty()) {
// This was just a regular Open().
@ -682,7 +683,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
return;
}
*map_slot = new string;
*map_slot = new std::string;
(*map_slot)->swap(data_);
} else {
// This was an OpenForInsert().
@ -700,14 +701,14 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
directory_->had_error_ = true;
return;
}
string* target = *map_slot;
std::string* target = *map_slot;
// Find the insertion point.
string magic_string = strings::Substitute(
"@@protoc_insertion_point($0)", insertion_point_);
string::size_type pos = target->find(magic_string);
std::string magic_string =
strings::Substitute("@@protoc_insertion_point($0)", insertion_point_);
std::string::size_type pos = target->find(magic_string);
if (pos == string::npos) {
if (pos == std::string::npos) {
std::cerr << filename_ << ": insertion point \"" << insertion_point_
<< "\" not found." << std::endl;
directory_->had_error_ = true;
@ -724,7 +725,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
// intentional because it means that multiple insertions at the same point
// will end up in the expected order in the final output.
pos = target->find_last_of('\n', pos);
if (pos == string::npos) {
if (pos == std::string::npos) {
// Insertion point is on the first line.
pos = 0;
} else {
@ -734,7 +735,8 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
}
// Extract indent.
string indent_(*target, pos, target->find_first_not_of(" \t", pos) - pos);
std::string indent_(*target, pos,
target->find_first_not_of(" \t", pos) - pos);
if (indent_.empty()) {
// No indent. This makes things easier.
@ -752,7 +754,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
UpdateMetadata(pos, data_.size() + indent_size);
// Now copy in the data.
string::size_type data_pos = 0;
std::string::size_type data_pos = 0;
char* target_ptr = ::google::protobuf::string_as_array(target) + pos;
while (data_pos < data_.size()) {
// Copy indent.
@ -762,7 +764,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
// Copy line from data_.
// We already guaranteed that data_ ends with a newline (above), so this
// search can't fail.
string::size_type line_length =
std::string::size_type line_length =
data_.find_first_of('\n', data_pos) + 1 - data_pos;
memcpy(target_ptr, data_.data() + data_pos, line_length);
target_ptr += line_length;
@ -795,9 +797,9 @@ CommandLineInterface::CommandLineInterface()
disallow_services_(false) {}
CommandLineInterface::~CommandLineInterface() {}
void CommandLineInterface::RegisterGenerator(const string& flag_name,
void CommandLineInterface::RegisterGenerator(const std::string& flag_name,
CodeGenerator* generator,
const string& help_text) {
const std::string& help_text) {
GeneratorInfo info;
info.flag_name = flag_name;
info.generator = generator;
@ -805,10 +807,9 @@ void CommandLineInterface::RegisterGenerator(const string& flag_name,
generators_by_flag_name_[flag_name] = info;
}
void CommandLineInterface::RegisterGenerator(const string& flag_name,
const string& option_flag_name,
CodeGenerator* generator,
const string& help_text) {
void CommandLineInterface::RegisterGenerator(
const std::string& flag_name, const std::string& option_flag_name,
CodeGenerator* generator, const std::string& help_text) {
GeneratorInfo info;
info.flag_name = flag_name;
info.option_flag_name = option_flag_name;
@ -818,7 +819,7 @@ void CommandLineInterface::RegisterGenerator(const string& flag_name,
generators_by_option_name_[option_flag_name] = info;
}
void CommandLineInterface::AllowPlugins(const string& exe_name_prefix) {
void CommandLineInterface::AllowPlugins(const std::string& exe_name_prefix) {
plugin_prefix_ = exe_name_prefix;
}
@ -893,7 +894,7 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
// Generate output.
if (mode_ == MODE_COMPILE) {
for (int i = 0; i < output_directives_.size(); i++) {
string output_location = output_directives_[i].output_location;
std::string output_location = output_directives_[i].output_location;
if (!HasSuffixString(output_location, ".zip") &&
!HasSuffixString(output_location, ".jar")) {
AddTrailingSlash(&output_location);
@ -915,7 +916,7 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
// Write all output to disk.
for (GeneratorContextMap::iterator iter = output_directories.begin();
iter != output_directories.end(); ++iter) {
const string& location = iter->first;
const std::string& location = iter->first;
GeneratorContextImpl* directory = iter->second;
if (HasSuffixString(location, "/")) {
if (!directory->WriteAllToDisk(location)) {
@ -1145,7 +1146,7 @@ void CommandLineInterface::Clear() {
}
bool CommandLineInterface::MakeProtoProtoPathRelative(
DiskSourceTree* source_tree, string* proto,
DiskSourceTree* source_tree, std::string* proto,
DescriptorDatabase* fallback_database) {
// If it's in the fallback db, don't report non-existent file errors.
FileDescriptorProto fallback_file;
@ -1156,7 +1157,7 @@ bool CommandLineInterface::MakeProtoProtoPathRelative(
// If the input file path is not a physical file path, it must be a virtual
// path.
if (access(proto->c_str(), F_OK) < 0) {
string disk_file;
std::string disk_file;
if (source_tree->VirtualFileToDiskFile(*proto, &disk_file) ||
in_fallback_database) {
return true;
@ -1166,7 +1167,7 @@ bool CommandLineInterface::MakeProtoProtoPathRelative(
}
}
string virtual_file, shadowing_disk_file;
std::string virtual_file, shadowing_disk_file;
switch (source_tree->DiskFileToVirtualFile(
*proto, &virtual_file, &shadowing_disk_file)) {
case DiskSourceTree::SUCCESS:
@ -1188,7 +1189,7 @@ bool CommandLineInterface::MakeProtoProtoPathRelative(
return false;
case DiskSourceTree::NO_MAPPING: {
// Try to interpret the path as a virtual path.
string disk_file;
std::string disk_file;
if (source_tree->VirtualFileToDiskFile(*proto, &disk_file) ||
in_fallback_database) {
return true;
@ -1225,15 +1226,15 @@ bool CommandLineInterface::MakeInputsBeProtoPathRelative(
}
bool CommandLineInterface::ExpandArgumentFile(const string& file,
std::vector<string>* arguments) {
bool CommandLineInterface::ExpandArgumentFile(
const std::string& file, std::vector<std::string>* arguments) {
// The argument file is searched in the working directory only. We don't
// use the proto import path here.
std::ifstream file_stream(file.c_str());
if (!file_stream.is_open()) {
return false;
}
string argument;
std::string argument;
// We don't support any kind of shell expansion right now.
while (std::getline(file_stream, argument)) {
arguments->push_back(argument);
@ -1245,7 +1246,7 @@ CommandLineInterface::ParseArgumentStatus
CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
executable_name_ = argv[0];
std::vector<string> arguments;
std::vector<std::string> arguments;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '@') {
if (!ExpandArgumentFile(argv[i] + 1, &arguments)) {
@ -1266,7 +1267,7 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
// Iterate through all arguments and parse them.
for (int i = 0; i < arguments.size(); ++i) {
string name, value;
std::string name, value;
if (ParseArgument(arguments[i].c_str(), &name, &value)) {
// Returned true => Use the next argument as the flag value.
@ -1290,7 +1291,8 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
// Make sure each plugin option has a matching plugin output.
bool foundUnknownPluginOption = false;
for (std::map<string, string>::const_iterator i = plugin_parameters_.begin();
for (std::map<std::string, std::string>::const_iterator i =
plugin_parameters_.begin();
i != plugin_parameters_.end(); ++i) {
if (plugins_.find(i->first) != plugins_.end()) {
continue;
@ -1299,7 +1301,7 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
for (std::vector<OutputDirective>::const_iterator j = output_directives_.begin();
j != output_directives_.end(); ++j) {
if (j->generator == NULL) {
string plugin_name = PluginName(plugin_prefix_ , j->name);
std::string plugin_name = PluginName(plugin_prefix_, j->name);
if (plugin_name == i->first) {
foundImplicitPlugin = true;
break;
@ -1324,7 +1326,7 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
// Don't use make_pair as the old/default standard library on Solaris
// doesn't support it without explicit template parameters, which are
// incompatible with C++0x's make_pair.
proto_path_.push_back(std::pair<string, string>("", "."));
proto_path_.push_back(std::pair<std::string, std::string>("", "."));
}
// Check some error cases.
@ -1365,8 +1367,8 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
return PARSE_ARGUMENT_DONE_AND_CONTINUE;
}
bool CommandLineInterface::ParseArgument(const char* arg,
string* name, string* value) {
bool CommandLineInterface::ParseArgument(const char* arg, std::string* name,
std::string* value) {
bool parsed_value = false;
if (arg[0] != '-') {
@ -1379,7 +1381,7 @@ bool CommandLineInterface::ParseArgument(const char* arg,
// value.
const char* equals_pos = strchr(arg, '=');
if (equals_pos != NULL) {
*name = string(arg, equals_pos - arg);
*name = std::string(arg, equals_pos - arg);
*value = equals_pos + 1;
parsed_value = true;
} else {
@ -1395,7 +1397,7 @@ bool CommandLineInterface::ParseArgument(const char* arg,
*value = arg;
parsed_value = true;
} else {
*name = string(arg, 2);
*name = std::string(arg, 2);
*value = arg + 2;
parsed_value = !value->empty();
}
@ -1427,8 +1429,8 @@ bool CommandLineInterface::ParseArgument(const char* arg,
}
CommandLineInterface::ParseArgumentStatus
CommandLineInterface::InterpretArgument(const string& name,
const string& value) {
CommandLineInterface::InterpretArgument(const std::string& name,
const std::string& value) {
if (name.empty()) {
// Not a flag. Just a filename.
if (value.empty()) {
@ -1447,16 +1449,16 @@ CommandLineInterface::InterpretArgument(const string& name,
// Java's -classpath (and some other languages) delimits path components
// with colons. Let's accept that syntax too just to make things more
// intuitive.
std::vector<string> parts = Split(
std::vector<std::string> parts = Split(
value, CommandLineInterface::kPathSeparator,
true);
for (int i = 0; i < parts.size(); i++) {
string virtual_path;
string disk_path;
std::string virtual_path;
std::string disk_path;
string::size_type equals_pos = parts[i].find_first_of('=');
if (equals_pos == string::npos) {
std::string::size_type equals_pos = parts[i].find_first_of('=');
if (equals_pos == std::string::npos) {
virtual_path = "";
disk_path = parts[i];
} else {
@ -1486,7 +1488,8 @@ CommandLineInterface::InterpretArgument(const string& name,
// Don't use make_pair as the old/default standard library on Solaris
// doesn't support it without explicit template parameters, which are
// incompatible with C++0x's make_pair.
proto_path_.push_back(std::pair<string, string>(virtual_path, disk_path));
proto_path_.push_back(
std::pair<std::string, std::string>(virtual_path, disk_path));
}
} else if (name == "--direct_dependencies") {
@ -1499,7 +1502,8 @@ CommandLineInterface::InterpretArgument(const string& name,
}
direct_dependencies_explicitly_set_ = true;
std::vector<string> direct = Split(value, ":", true);
std::vector<std::string> direct =
Split(value, ":", true);
GOOGLE_DCHECK(direct_dependencies_.empty());
direct_dependencies_.insert(direct.begin(), direct.end());
@ -1585,7 +1589,7 @@ CommandLineInterface::InterpretArgument(const string& name,
std::cout << version_info_ << std::endl;
}
std::cout << "libprotoc "
<< protobuf::internal::VersionString(PROTOBUF_VERSION)
<< internal::VersionString(PROTOBUF_VERSION)
<< std::endl;
return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler.
@ -1638,14 +1642,14 @@ CommandLineInterface::InterpretArgument(const string& name,
return PARSE_ARGUMENT_FAIL;
}
string plugin_name;
string path;
std::string plugin_name;
std::string path;
string::size_type equals_pos = value.find_first_of('=');
if (equals_pos == string::npos) {
std::string::size_type equals_pos = value.find_first_of('=');
if (equals_pos == std::string::npos) {
// Use the basename of the file.
string::size_type slash_pos = value.find_last_of('/');
if (slash_pos == string::npos) {
std::string::size_type slash_pos = value.find_last_of('/');
if (slash_pos == std::string::npos) {
plugin_name = value;
} else {
plugin_name = value.substr(slash_pos + 1);
@ -1682,13 +1686,14 @@ CommandLineInterface::InterpretArgument(const string& name,
// Check if it's a generator option flag.
generator_info = FindOrNull(generators_by_option_name_, name);
if (generator_info != NULL) {
string* parameters = &generator_parameters_[generator_info->flag_name];
std::string* parameters =
&generator_parameters_[generator_info->flag_name];
if (!parameters->empty()) {
parameters->append(",");
}
parameters->append(value);
} else if (HasPrefixString(name, "--") && HasSuffixString(name, "_opt")) {
string* parameters =
std::string* parameters =
&plugin_parameters_[PluginName(plugin_prefix_, name)];
if (!parameters->empty()) {
parameters->append(",");
@ -1717,8 +1722,8 @@ CommandLineInterface::InterpretArgument(const string& name,
// Split value at ':' to separate the generator parameter from the
// filename. However, avoid doing this if the colon is part of a valid
// Windows-style absolute path.
string::size_type colon_pos = value.find_first_of(':');
if (colon_pos == string::npos || IsWindowsAbsolutePath(value)) {
std::string::size_type colon_pos = value.find_first_of(':');
if (colon_pos == std::string::npos || IsWindowsAbsolutePath(value)) {
directive.output_location = value;
} else {
directive.parameter = value.substr(0, colon_pos);
@ -1811,7 +1816,8 @@ void CommandLineInterface::PrintHelpText() {
// but fixing this nicely (e.g. splitting on spaces) is probably more
// trouble than it's worth.
std::cout << " " << iter->first << "=OUT_DIR "
<< string(19 - iter->first.size(), ' ') // Spaces for alignment.
<< std::string(19 - iter->first.size(),
' ') // Spaces for alignment.
<< iter->second.help_text << std::endl;
}
std::cout <<
@ -1835,15 +1841,15 @@ bool CommandLineInterface::GenerateOutput(
const OutputDirective& output_directive,
GeneratorContext* generator_context) {
// Call the generator.
string error;
std::string error;
if (output_directive.generator == NULL) {
// This is a plugin.
GOOGLE_CHECK(HasPrefixString(output_directive.name, "--") &&
HasSuffixString(output_directive.name, "_out"))
<< "Bad name for plugin generator: " << output_directive.name;
string plugin_name = PluginName(plugin_prefix_ , output_directive.name);
string parameters = output_directive.parameter;
std::string plugin_name = PluginName(plugin_prefix_, output_directive.name);
std::string parameters = output_directive.parameter;
if (!plugin_parameters_[plugin_name].empty()) {
if (!parameters.empty()) {
parameters.append(",");
@ -1858,7 +1864,7 @@ bool CommandLineInterface::GenerateOutput(
}
} else {
// Regular generator.
string parameters = output_directive.parameter;
std::string parameters = output_directive.parameter;
if (!generator_parameters_[output_directive.name].empty()) {
if (!parameters.empty()) {
parameters.append(",");
@ -1891,15 +1897,15 @@ bool CommandLineInterface::GenerateDependencyManifestFile(
file_set.mutable_file());
}
std::vector<string> output_filenames;
std::vector<std::string> output_filenames;
for (GeneratorContextMap::const_iterator iter = output_directories.begin();
iter != output_directories.end(); ++iter) {
const string& location = iter->first;
const std::string& location = iter->first;
GeneratorContextImpl* directory = iter->second;
std::vector<string> relative_output_filenames;
std::vector<std::string> relative_output_filenames;
directory->GetOutputFilenames(&relative_output_filenames);
for (int i = 0; i < relative_output_filenames.size(); i++) {
string output_filename = location + relative_output_filenames[i];
std::string output_filename = location + relative_output_filenames[i];
if (output_filename.compare(0, 2, "./") == 0) {
output_filename = output_filename.substr(2);
}
@ -1932,8 +1938,8 @@ bool CommandLineInterface::GenerateDependencyManifestFile(
for (int i = 0; i < file_set.file_size(); i++) {
const FileDescriptorProto& file = file_set.file(i);
const string& virtual_file = file.name();
string disk_file;
const std::string& virtual_file = file.name();
std::string disk_file;
if (source_tree &&
source_tree->VirtualFileToDiskFile(virtual_file, &disk_file)) {
printer.Print(" $disk_file$", "disk_file", disk_file);
@ -1950,13 +1956,11 @@ bool CommandLineInterface::GenerateDependencyManifestFile(
bool CommandLineInterface::GeneratePluginOutput(
const std::vector<const FileDescriptor*>& parsed_files,
const string& plugin_name,
const string& parameter,
GeneratorContext* generator_context,
string* error) {
const std::string& plugin_name, const std::string& parameter,
GeneratorContext* generator_context, std::string* error) {
CodeGeneratorRequest request;
CodeGeneratorResponse response;
string processed_parameter = parameter;
std::string processed_parameter = parameter;
// Build the request.
@ -1990,7 +1994,7 @@ bool CommandLineInterface::GeneratePluginOutput(
subprocess.Start(plugin_name, Subprocess::SEARCH_PATH);
}
string communicate_error;
std::string communicate_error;
if (!subprocess.Communicate(request, &response, &communicate_error)) {
*error = strings::Substitute("$0: $1", plugin_name, communicate_error);
return false;
@ -2003,7 +2007,7 @@ bool CommandLineInterface::GeneratePluginOutput(
const CodeGeneratorResponse::File& output_file = response.file(i);
if (!output_file.insertion_point().empty()) {
string filename = output_file.name();
std::string filename = output_file.name();
// Open a file for insert.
// We reset current_output to NULL first so that the old file is closed
// before the new one is opened.
@ -2257,9 +2261,9 @@ void GatherOccupiedFieldRanges(
// Utility function for PrintFreeFieldNumbers.
// Actually prints the formatted free field numbers for given message name and
// occupied ranges.
void FormatFreeFieldNumbers(const string& name,
void FormatFreeFieldNumbers(const std::string& name,
const std::set<FieldRange>& ranges) {
string output;
std::string output;
StringAppendF(&output, "%-35s free:", name.c_str());
int next_free_number = 1;
for (std::set<FieldRange>::const_iterator i = ranges.begin();

@ -128,8 +128,7 @@ class PROTOC_EXPORT CommandLineInterface {
// protoc --foo_out=enable_bar:outdir
// The text before the colon is passed to CodeGenerator::Generate() as the
// "parameter".
void RegisterGenerator(const std::string& flag_name,
CodeGenerator* generator,
void RegisterGenerator(const std::string& flag_name, CodeGenerator* generator,
const std::string& help_text);
// Register a code generator for a language.
@ -199,9 +198,7 @@ class PROTOC_EXPORT CommandLineInterface {
// Provides some text which will be printed when the --version flag is
// used. The version of libprotoc will also be printed on the next line
// after this text.
void SetVersionInfo(const std::string& text) {
version_info_ = text;
}
void SetVersionInfo(const std::string& text) { version_info_ = text; }
private:
@ -210,14 +207,16 @@ class PROTOC_EXPORT CommandLineInterface {
class ErrorPrinter;
class GeneratorContextImpl;
class MemoryOutputStream;
typedef std::unordered_map<std::string, GeneratorContextImpl*> GeneratorContextMap;
typedef std::unordered_map<std::string, GeneratorContextImpl*>
GeneratorContextMap;
// Clear state from previous Run().
void Clear();
// Remaps the proto file so that it is relative to one of the directories
// in proto_path_. Returns false if an error occurred.
bool MakeProtoProtoPathRelative(DiskSourceTree* source_tree, std::string* proto,
bool MakeProtoProtoPathRelative(DiskSourceTree* source_tree,
std::string* proto,
DescriptorDatabase* fallback_database);
// Remaps each file in input_files_ so that it is relative to one of the
@ -238,7 +237,8 @@ class PROTOC_EXPORT CommandLineInterface {
// Read an argument file and append the file's content to the list of
// arguments. Return false if the file cannot be read.
bool ExpandArgumentFile(const std::string& file, std::vector<std::string>* arguments);
bool ExpandArgumentFile(const std::string& file,
std::vector<std::string>* arguments);
// Parses a command-line argument into a name/value pair. Returns
// true if the next argument in the argv should be used as the value,
@ -388,7 +388,7 @@ class PROTOC_EXPORT CommandLineInterface {
ErrorFormat error_format_;
std::vector<std::pair<std::string, std::string> >
proto_path_; // Search path for proto files.
proto_path_; // Search path for proto files.
std::vector<std::string> input_files_; // Names of the input proto files.
// Names of proto files which are allowed to be imported. Used by build
@ -403,7 +403,7 @@ class PROTOC_EXPORT CommandLineInterface {
// output_directives_ lists all the files we are supposed to output and what
// generator to use for each.
struct OutputDirective {
std::string name; // E.g. "--foo_out"
std::string name; // E.g. "--foo_out"
CodeGenerator* generator; // NULL for plugins
std::string parameter;
std::string output_location;

@ -86,7 +86,7 @@ using google::protobuf::internal::win32::write;
namespace {
bool FileExists(const string& path) {
bool FileExists(const std::string& path) {
return File::Exists(path);
}
@ -98,8 +98,8 @@ class CommandLineInterfaceTest : public testing::Test {
// Runs the CommandLineInterface with the given command line. The
// command is automatically split on spaces, and the string "$tmpdir"
// is replaced with TestTempDir().
void Run(const string& command);
void RunWithArgs(std::vector<string> args);
void Run(const std::string& command);
void RunWithArgs(std::vector<std::string> args);
// -----------------------------------------------------------------
// Methods to set up the test (called before Run()).
@ -112,10 +112,10 @@ class CommandLineInterfaceTest : public testing::Test {
// Create a temp file within temp_directory_ with the given name.
// The containing directory is also created if necessary.
void CreateTempFile(const string& name, const string& contents);
void CreateTempFile(const std::string& name, const std::string& contents);
// Create a subdirectory within temp_directory_.
void CreateTempDir(const string& name);
void CreateTempDir(const std::string& name);
#ifdef PROTOBUF_OPENSOURCE
// Change working directory to temp directory.
@ -137,27 +137,27 @@ class CommandLineInterfaceTest : public testing::Test {
// Checks that Run() returned non-zero and the stderr output is exactly
// the text given. expected_test may contain references to "$tmpdir",
// which will be replaced by the temporary directory path.
void ExpectErrorText(const string& expected_text);
void ExpectErrorText(const std::string& expected_text);
// Checks that Run() returned non-zero and the stderr contains the given
// substring.
void ExpectErrorSubstring(const string& expected_substring);
void ExpectErrorSubstring(const std::string& expected_substring);
// Like ExpectErrorSubstring, but checks that Run() returned zero.
void ExpectErrorSubstringWithZeroReturnCode(
const string& expected_substring);
const std::string& expected_substring);
// Checks that the captured stdout is the same as the expected_text.
void ExpectCapturedStdout(const string& expected_text);
void ExpectCapturedStdout(const std::string& expected_text);
// Checks that Run() returned zero and the stdout contains the given
// substring.
void ExpectCapturedStdoutSubstringWithZeroReturnCode(
const string& expected_substring);
const std::string& expected_substring);
// Returns true if ExpectErrorSubstring(expected_substring) would pass, but
// does not fail otherwise.
bool HasAlternateErrorSubstring(const string& expected_substring);
bool HasAlternateErrorSubstring(const std::string& expected_substring);
// Checks that MockCodeGenerator::Generate() was called in the given
// context (or the generator in test_plugin.cc, which produces the same
@ -168,37 +168,38 @@ class CommandLineInterfaceTest : public testing::Test {
// generate given these inputs. message_name is the name of the first
// message that appeared in the proto file; this is just to make extra
// sure that the correct file was parsed.
void ExpectGenerated(const string& generator_name,
const string& parameter,
const string& proto_name,
const string& message_name);
void ExpectGenerated(const string& generator_name,
const string& parameter,
const string& proto_name,
const string& message_name,
const string& output_directory);
void ExpectGeneratedWithMultipleInputs(const string& generator_name,
const string& all_proto_names,
const string& proto_name,
const string& message_name);
void ExpectGeneratedWithInsertions(const string& generator_name,
const string& parameter,
const string& insertions,
const string& proto_name,
const string& message_name);
void CheckGeneratedAnnotations(const string& name, const string& file);
void ExpectNullCodeGeneratorCalled(const string& parameter);
void ReadDescriptorSet(const string& filename,
void ExpectGenerated(const std::string& generator_name,
const std::string& parameter,
const std::string& proto_name,
const std::string& message_name);
void ExpectGenerated(const std::string& generator_name,
const std::string& parameter,
const std::string& proto_name,
const std::string& message_name,
const std::string& output_directory);
void ExpectGeneratedWithMultipleInputs(const std::string& generator_name,
const std::string& all_proto_names,
const std::string& proto_name,
const std::string& message_name);
void ExpectGeneratedWithInsertions(const std::string& generator_name,
const std::string& parameter,
const std::string& insertions,
const std::string& proto_name,
const std::string& message_name);
void CheckGeneratedAnnotations(const std::string& name,
const std::string& file);
void ExpectNullCodeGeneratorCalled(const std::string& parameter);
void ReadDescriptorSet(const std::string& filename,
FileDescriptorSet* descriptor_set);
void WriteDescriptorSet(const string& filename,
void WriteDescriptorSet(const std::string& filename,
const FileDescriptorSet* descriptor_set);
void ExpectFileContent(const string& filename,
const string& content);
void ExpectFileContent(const std::string& filename,
const std::string& content);
private:
// The object we are testing.
@ -211,16 +212,16 @@ class CommandLineInterfaceTest : public testing::Test {
// protection against accidentally deleting user files (since we recursively
// delete this directory during the test). This is the full path of that
// directory.
string temp_directory_;
std::string temp_directory_;
// The result of Run().
int return_code_;
// The captured stderr output.
string error_text_;
std::string error_text_;
// The captured stdout.
string captured_stdout_;
std::string captured_stdout_;
// Pointers which need to be deleted later.
std::vector<CodeGenerator*> mock_generators_to_delete_;
@ -234,13 +235,11 @@ class CommandLineInterfaceTest::NullCodeGenerator : public CodeGenerator {
~NullCodeGenerator() {}
mutable bool called_;
mutable string parameter_;
mutable std::string parameter_;
// implements CodeGenerator ----------------------------------------
bool Generate(const FileDescriptor* file,
const string& parameter,
GeneratorContext* context,
string* error) const {
bool Generate(const FileDescriptor* file, const std::string& parameter,
GeneratorContext* context, std::string* error) const {
called_ = true;
parameter_ = parameter;
return true;
@ -292,14 +291,14 @@ void CommandLineInterfaceTest::TearDown() {
mock_generators_to_delete_.clear();
}
void CommandLineInterfaceTest::Run(const string& command) {
void CommandLineInterfaceTest::Run(const std::string& command) {
RunWithArgs(Split(command, " ", true));
}
void CommandLineInterfaceTest::RunWithArgs(std::vector<string> args) {
void CommandLineInterfaceTest::RunWithArgs(std::vector<std::string> args) {
if (!disallow_plugins_) {
cli_.AllowPlugins("prefix-");
string plugin_path;
std::string plugin_path;
#ifdef GOOGLE_PROTOBUF_TEST_PLUGIN_PATH
plugin_path = GOOGLE_PROTOBUF_TEST_PLUGIN_PATH;
#else
@ -361,13 +360,12 @@ void CommandLineInterfaceTest::RunWithArgs(std::vector<string> args) {
// -------------------------------------------------------------------
void CommandLineInterfaceTest::CreateTempFile(
const string& name,
const string& contents) {
void CommandLineInterfaceTest::CreateTempFile(const std::string& name,
const std::string& contents) {
// Create parent directory, if necessary.
string::size_type slash_pos = name.find_last_of('/');
if (slash_pos != string::npos) {
string dir = name.substr(0, slash_pos);
std::string::size_type slash_pos = name.find_last_of('/');
if (slash_pos != std::string::npos) {
std::string dir = name.substr(0, slash_pos);
if (!FileExists(temp_directory_ + "/" + dir)) {
GOOGLE_CHECK_OK(File::RecursivelyCreateDir(temp_directory_ + "/" + dir,
0777));
@ -375,13 +373,13 @@ void CommandLineInterfaceTest::CreateTempFile(
}
// Write file.
string full_name = temp_directory_ + "/" + name;
std::string full_name = temp_directory_ + "/" + name;
GOOGLE_CHECK_OK(File::SetContents(
full_name, StringReplace(contents, "$tmpdir", temp_directory_, true),
true));
}
void CommandLineInterfaceTest::CreateTempDir(const string& name) {
void CommandLineInterfaceTest::CreateTempDir(const std::string& name) {
GOOGLE_CHECK_OK(File::RecursivelyCreateDir(temp_directory_ + "/" + name,
0777));
}
@ -393,56 +391,51 @@ void CommandLineInterfaceTest::ExpectNoErrors() {
EXPECT_EQ("", error_text_);
}
void CommandLineInterfaceTest::ExpectErrorText(const string& expected_text) {
void CommandLineInterfaceTest::ExpectErrorText(
const std::string& expected_text) {
EXPECT_NE(0, return_code_);
EXPECT_EQ(StringReplace(expected_text, "$tmpdir", temp_directory_, true),
error_text_);
}
void CommandLineInterfaceTest::ExpectErrorSubstring(
const string& expected_substring) {
const std::string& expected_substring) {
EXPECT_NE(0, return_code_);
EXPECT_PRED_FORMAT2(testing::IsSubstring, expected_substring, error_text_);
}
void CommandLineInterfaceTest::ExpectErrorSubstringWithZeroReturnCode(
const string& expected_substring) {
const std::string& expected_substring) {
EXPECT_EQ(0, return_code_);
EXPECT_PRED_FORMAT2(testing::IsSubstring, expected_substring, error_text_);
}
bool CommandLineInterfaceTest::HasAlternateErrorSubstring(
const string& expected_substring) {
const std::string& expected_substring) {
EXPECT_NE(0, return_code_);
return error_text_.find(expected_substring) != string::npos;
return error_text_.find(expected_substring) != std::string::npos;
}
void CommandLineInterfaceTest::ExpectGenerated(
const string& generator_name,
const string& parameter,
const string& proto_name,
const string& message_name) {
const std::string& generator_name, const std::string& parameter,
const std::string& proto_name, const std::string& message_name) {
MockCodeGenerator::ExpectGenerated(
generator_name, parameter, "", proto_name, message_name, proto_name,
temp_directory_);
}
void CommandLineInterfaceTest::ExpectGenerated(
const string& generator_name,
const string& parameter,
const string& proto_name,
const string& message_name,
const string& output_directory) {
const std::string& generator_name, const std::string& parameter,
const std::string& proto_name, const std::string& message_name,
const std::string& output_directory) {
MockCodeGenerator::ExpectGenerated(
generator_name, parameter, "", proto_name, message_name, proto_name,
temp_directory_ + "/" + output_directory);
}
void CommandLineInterfaceTest::ExpectGeneratedWithMultipleInputs(
const string& generator_name,
const string& all_proto_names,
const string& proto_name,
const string& message_name) {
const std::string& generator_name, const std::string& all_proto_names,
const std::string& proto_name, const std::string& message_name) {
MockCodeGenerator::ExpectGenerated(
generator_name, "", "", proto_name, message_name,
all_proto_names,
@ -450,32 +443,30 @@ void CommandLineInterfaceTest::ExpectGeneratedWithMultipleInputs(
}
void CommandLineInterfaceTest::ExpectGeneratedWithInsertions(
const string& generator_name,
const string& parameter,
const string& insertions,
const string& proto_name,
const string& message_name) {
const std::string& generator_name, const std::string& parameter,
const std::string& insertions, const std::string& proto_name,
const std::string& message_name) {
MockCodeGenerator::ExpectGenerated(
generator_name, parameter, insertions, proto_name, message_name,
proto_name, temp_directory_);
}
void CommandLineInterfaceTest::CheckGeneratedAnnotations(const string& name,
const string& file) {
void CommandLineInterfaceTest::CheckGeneratedAnnotations(
const std::string& name, const std::string& file) {
MockCodeGenerator::CheckGeneratedAnnotations(name, file, temp_directory_);
}
void CommandLineInterfaceTest::ExpectNullCodeGeneratorCalled(
const string& parameter) {
const std::string& parameter) {
EXPECT_TRUE(null_generator_->called_);
EXPECT_EQ(parameter, null_generator_->parameter_);
}
void CommandLineInterfaceTest::ReadDescriptorSet(
const string& filename, FileDescriptorSet* descriptor_set) {
string path = temp_directory_ + "/" + filename;
string file_contents;
const std::string& filename, FileDescriptorSet* descriptor_set) {
std::string path = temp_directory_ + "/" + filename;
std::string file_contents;
GOOGLE_CHECK_OK(File::GetContents(path, &file_contents, true));
if (!descriptor_set->ParseFromString(file_contents)) {
@ -484,28 +475,28 @@ void CommandLineInterfaceTest::ReadDescriptorSet(
}
void CommandLineInterfaceTest::WriteDescriptorSet(
const string& filename, const FileDescriptorSet* descriptor_set) {
string binary_proto;
const std::string& filename, const FileDescriptorSet* descriptor_set) {
std::string binary_proto;
GOOGLE_CHECK(descriptor_set->SerializeToString(&binary_proto));
CreateTempFile(filename, binary_proto);
}
void CommandLineInterfaceTest::ExpectCapturedStdout(
const string& expected_text) {
const std::string& expected_text) {
EXPECT_EQ(expected_text, captured_stdout_);
}
void CommandLineInterfaceTest::ExpectCapturedStdoutSubstringWithZeroReturnCode(
const string& expected_substring) {
const std::string& expected_substring) {
EXPECT_EQ(0, return_code_);
EXPECT_PRED_FORMAT2(
testing::IsSubstring, expected_substring, captured_stdout_);
}
void CommandLineInterfaceTest::ExpectFileContent(
const string& filename, const string& content) {
string path = temp_directory_ + "/" + filename;
string file_contents;
void CommandLineInterfaceTest::ExpectFileContent(const std::string& filename,
const std::string& content) {
std::string path = temp_directory_ + "/" + filename;
std::string file_contents;
GOOGLE_CHECK_OK(File::GetContents(path, &file_contents, true));
EXPECT_EQ(StringReplace(content, "$tmpdir", temp_directory_, true),
@ -729,9 +720,8 @@ TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport_DescriptorSetIn) {
Run(strings::Substitute(
"protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir "
"--descriptor_set_in=$0 foo.proto bar.proto",
string("$tmpdir/foo_and_bar.bin") +
CommandLineInterface::kPathSeparator +
"$tmpdir/baz_and_bat.bin"));
std::string("$tmpdir/foo_and_bar.bin") +
CommandLineInterface::kPathSeparator + "$tmpdir/baz_and_bat.bin"));
ExpectNoErrors();
ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
@ -746,9 +736,8 @@ TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport_DescriptorSetIn) {
Run(strings::Substitute(
"protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir "
"--descriptor_set_in=$0 baz.proto bat.proto",
string("$tmpdir/foo_and_bar.bin") +
CommandLineInterface::kPathSeparator +
"$tmpdir/baz_and_bat.bin"));
std::string("$tmpdir/foo_and_bar.bin") +
CommandLineInterface::kPathSeparator + "$tmpdir/baz_and_bat.bin"));
ExpectNoErrors();
ExpectGeneratedWithMultipleInputs("test_generator", "baz.proto,bat.proto",
@ -805,9 +794,8 @@ TEST_F(CommandLineInterfaceTest,
Run(strings::Substitute(
"protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir "
"--descriptor_set_in=$0 bar.proto",
string("$tmpdir/foo_and_bar.bin") +
CommandLineInterface::kPathSeparator +
"$tmpdir/foo_and_baz.bin"));
std::string("$tmpdir/foo_and_bar.bin") +
CommandLineInterface::kPathSeparator + "$tmpdir/foo_and_baz.bin"));
ExpectNoErrors();
ExpectGenerated("test_generator", "", "bar.proto", "Bar");
@ -1101,9 +1089,8 @@ TEST_F(CommandLineInterfaceTest, ColonDelimitedPath) {
Run(strings::Substitute(
"protocol_compiler --test_out=$$tmpdir --proto_path=$0 foo.proto",
string("$tmpdir/a") +
CommandLineInterface::kPathSeparator +
"$tmpdir/b"));
std::string("$tmpdir/a") + CommandLineInterface::kPathSeparator +
"$tmpdir/b"));
ExpectNoErrors();
ExpectGenerated("test_generator", "", "foo.proto", "Foo");
@ -1298,7 +1285,7 @@ TEST_F(CommandLineInterfaceTest, DirectDependencies_CustomErrorMessage) {
"syntax = \"proto2\";\n"
"message Bar { optional string text = 1; }");
std::vector<string> commands;
std::vector<std::string> commands;
commands.push_back("protocol_compiler");
commands.push_back("--test_out=$tmpdir");
commands.push_back("--proto_path=$tmpdir");
@ -1512,7 +1499,7 @@ TEST_F(CommandLineInterfaceTest, WriteDependencyManifestFile) {
" optional Foo foo = 1;\n"
"}\n");
string current_working_directory = getcwd(NULL, 0);
std::string current_working_directory = getcwd(NULL, 0);
SwitchToTempDirectory();
Run("protocol_compiler --dependency_out=manifest --test_out=. "
@ -1838,7 +1825,7 @@ TEST_F(CommandLineInterfaceTest, OutputWriteError) {
"syntax = \"proto2\";\n"
"message Foo {}\n");
string output_file =
std::string output_file =
MockCodeGenerator::GetOutputFileName("test_generator", "foo.proto");
// Create a directory blocking our output location.
@ -1867,7 +1854,7 @@ TEST_F(CommandLineInterfaceTest, PluginOutputWriteError) {
"syntax = \"proto2\";\n"
"message Foo {}\n");
string output_file =
std::string output_file =
MockCodeGenerator::GetOutputFileName("test_plugin", "foo.proto");
// Create a directory blocking our output location.
@ -2279,13 +2266,13 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
close(duped_stdin_);
}
void RedirectStdinFromText(const string& input) {
string filename = TestTempDir() + "/test_stdin";
void RedirectStdinFromText(const std::string& input) {
std::string filename = TestTempDir() + "/test_stdin";
GOOGLE_CHECK_OK(File::SetContents(filename, input, true));
GOOGLE_CHECK(RedirectStdinFromFile(filename));
}
bool RedirectStdinFromFile(const string& filename) {
bool RedirectStdinFromFile(const std::string& filename) {
int fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) return false;
dup2(fd, STDIN_FILENO);
@ -2294,8 +2281,8 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
}
// Remove '\r' characters from text.
string StripCR(const string& text) {
string result;
std::string StripCR(const std::string& text) {
std::string result;
for (int i = 0; i < text.size(); i++) {
if (text[i] != '\r') {
@ -2309,8 +2296,8 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
enum Type { TEXT, BINARY };
enum ReturnCode { SUCCESS, ERROR };
bool Run(const string& command) {
std::vector<string> args;
bool Run(const std::string& command) {
std::vector<std::string> args;
args.push_back("protoc");
SplitStringUsing(command, " ", &args);
switch (GetParam()) {
@ -2343,8 +2330,8 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
return result == 0;
}
void ExpectStdoutMatchesBinaryFile(const string& filename) {
string expected_output;
void ExpectStdoutMatchesBinaryFile(const std::string& filename) {
std::string expected_output;
GOOGLE_CHECK_OK(File::GetContents(filename, &expected_output, true));
// Don't use EXPECT_EQ because we don't want to print raw binary data to
@ -2352,18 +2339,18 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
EXPECT_TRUE(captured_stdout_ == expected_output);
}
void ExpectStdoutMatchesTextFile(const string& filename) {
string expected_output;
void ExpectStdoutMatchesTextFile(const std::string& filename) {
std::string expected_output;
GOOGLE_CHECK_OK(File::GetContents(filename, &expected_output, true));
ExpectStdoutMatchesText(expected_output);
}
void ExpectStdoutMatchesText(const string& expected_text) {
void ExpectStdoutMatchesText(const std::string& expected_text) {
EXPECT_EQ(StripCR(expected_text), StripCR(captured_stdout_));
}
void ExpectStderrMatchesText(const string& expected_text) {
void ExpectStderrMatchesText(const std::string& expected_text) {
EXPECT_EQ(StripCR(expected_text), StripCR(captured_stderr_));
}
@ -2384,7 +2371,7 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
file_descriptor_set.add_file());
GOOGLE_DCHECK(file_descriptor_set.IsInitialized());
string binary_proto;
std::string binary_proto;
GOOGLE_CHECK(file_descriptor_set.SerializeToString(&binary_proto));
GOOGLE_CHECK_OK(File::SetContents(
unittest_proto_descriptor_set_filename_,
@ -2393,9 +2380,9 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
}
int duped_stdin_;
string captured_stdout_;
string captured_stderr_;
string unittest_proto_descriptor_set_filename_;
std::string captured_stdout_;
std::string captured_stderr_;
std::string unittest_proto_descriptor_set_filename_;
};
TEST_P(EncodeDecodeTest, Encode) {
@ -2436,7 +2423,7 @@ TEST_P(EncodeDecodeTest, DecodeRaw) {
protobuf_unittest::TestAllTypes message;
message.set_optional_int32(123);
message.set_optional_string("foo");
string data;
std::string data;
message.SerializeToString(&data);
RedirectStdinFromText(data);

@ -72,11 +72,11 @@ class MockErrorCollector : public MultiFileErrorCollector {
MockErrorCollector() {}
~MockErrorCollector() {}
string text_;
std::string text_;
// implements ErrorCollector ---------------------------------------
void AddError(const string& filename, int line, int column,
const string& message) {
void AddError(const std::string& filename, int line, int column,
const std::string& message) {
strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
filename, line, column, message);
}
@ -87,13 +87,14 @@ class MockGeneratorContext : public GeneratorContext {
MockGeneratorContext() {}
~MockGeneratorContext() { STLDeleteValues(&files_); }
void ExpectFileMatches(const string& virtual_filename,
const string& physical_filename) {
string* expected_contents = FindPtrOrNull(files_, virtual_filename);
void ExpectFileMatches(const std::string& virtual_filename,
const std::string& physical_filename) {
std::string* expected_contents =
FindPtrOrNull(files_, virtual_filename);
ASSERT_TRUE(expected_contents != NULL)
<< "Generator failed to generate file: " << virtual_filename;
string actual_contents;
std::string actual_contents;
GOOGLE_CHECK_OK(
File::GetContents(TestUtil::TestSourceDir() + "/" + physical_filename,
&actual_contents, true))
@ -102,11 +103,11 @@ class MockGeneratorContext : public GeneratorContext {
#ifdef WRITE_FILES // Define to debug mismatched files.
GOOGLE_CHECK_OK(
File::SetContents("/tmp/1.cc", *expected_contents, true));
GOOGLE_CHECK_OK(File::SetContents("/tmp/2.cc", actual_contents, true));
File::SetContents("/tmp/expected.cc", *expected_contents, true));
GOOGLE_CHECK_OK(File::SetContents("/tmp/actual.cc", actual_contents, true));
#endif
EXPECT_EQ(*expected_contents, actual_contents)
ASSERT_EQ(*expected_contents, actual_contents)
<< physical_filename
<< " needs to be regenerated. Please run "
"generate_descriptor_proto.sh. "
@ -115,16 +116,16 @@ class MockGeneratorContext : public GeneratorContext {
// implements GeneratorContext --------------------------------------
virtual io::ZeroCopyOutputStream* Open(const string& filename) {
string** map_slot = &files_[filename];
virtual io::ZeroCopyOutputStream* Open(const std::string& filename) {
std::string** map_slot = &files_[filename];
delete *map_slot;
*map_slot = new string;
*map_slot = new std::string;
return new io::StringOutputStream(*map_slot);
}
private:
std::map<string, string*> files_;
std::map<std::string, std::string*> files_;
};
const char kDescriptorParameter[] = "dllexport_decl=PROTOBUF_EXPORT";
@ -139,8 +140,8 @@ const char* test_protos[][2] = {
TEST(BootstrapTest, GeneratedFilesMatch) {
// We need a mapping from the actual file to virtual and actual path
// of the data to compare to.
std::map<string, string> vpath_map;
std::map<string, string> rpath_map;
std::map<std::string, std::string> vpath_map;
std::map<std::string, std::string> rpath_map;
rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto2"] =
"net/proto2/z_generated_example/test_messages_proto2";
rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto3"] =
@ -155,7 +156,7 @@ TEST(BootstrapTest, GeneratedFilesMatch) {
MockErrorCollector error_collector;
Importer importer(&source_tree, &error_collector);
const FileDescriptor* file =
importer.Import(file_parameter[0] + string(".proto"));
importer.Import(file_parameter[0] + std::string(".proto"));
ASSERT_TRUE(file != nullptr)
<< "Can't import file " << file_parameter[0] + string(".proto") << "\n";
EXPECT_EQ("", error_collector.text_);
@ -165,12 +166,12 @@ TEST(BootstrapTest, GeneratedFilesMatch) {
generator.set_opensource_runtime(true);
generator.set_runtime_include_base(GOOGLE_PROTOBUF_RUNTIME_INCLUDE_BASE);
#endif
string error;
std::string error;
ASSERT_TRUE(generator.Generate(file, file_parameter[1], &context, &error));
string vpath =
std::string vpath =
FindWithDefault(vpath_map, file_parameter[0], file_parameter[0]);
string rpath =
std::string rpath =
FindWithDefault(rpath_map, file_parameter[0], file_parameter[0]);
context.ExpectFileMatches(vpath + ".pb.cc", rpath + ".pb.cc");
context.ExpectFileMatches(vpath + ".pb.h", rpath + ".pb.h");

@ -60,7 +60,7 @@ bool ShouldGenerateArraySize(const EnumDescriptor* descriptor) {
} // namespace
EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor,
const std::map<string, string>& vars,
const std::map<std::string, std::string>& vars,
const Options& options)
: descriptor_(descriptor),
classname_(ClassName(descriptor, false)),
@ -68,7 +68,7 @@ EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor,
generate_array_size_(ShouldGenerateArraySize(descriptor)),
variables_(vars) {
variables_["classname"] = classname_;
variables_["classtype"] = QualifiedClassName(descriptor_);
variables_["classtype"] = QualifiedClassName(descriptor_, options);
variables_["short_name"] = descriptor_->name();
variables_["enumbase"] = options_.proto_h ? " : int" : "";
variables_["nested_name"] = descriptor_->name();
@ -110,7 +110,7 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
}
}
if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
if (descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
// For new enum semantics: generate min and max sentinel values equal to
// INT32_MIN and INT32_MAX
if (descriptor_->value_count() > 0) format(",\n");
@ -148,7 +148,7 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
// TODO(haberman): consider removing this in favor of the stricter
// version below. Would this break our compatibility guarantees?
format(
"inline const $string$& $classname$_Name($classname$ value) {\n"
"inline const std::string& $classname$_Name($classname$ value) {\n"
" return ::$proto_ns$::internal::NameOfEnum(\n"
" $classname$_descriptor(), value);\n"
"}\n");
@ -158,7 +158,7 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
// an integral type.
format(
"template<typename T>\n"
"inline const $string$& $classname$_Name(T enum_t_value) {\n"
"inline const std::string& $classname$_Name(T enum_t_value) {\n"
" static_assert(::std::is_same<T, $classname$>::value ||\n"
" ::std::is_integral<T>::value,\n"
" \"Incorrect type passed to function $classname$_Name.\");\n"
@ -168,7 +168,7 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
}
format(
"inline bool $classname$_Parse(\n"
" const $string$& name, $classname$* value) {\n"
" const std::string& name, $classname$* value) {\n"
" return ::$proto_ns$::internal::ParseNamedEnum<$classname$>(\n"
" $classname$_descriptor(), name, value);\n"
"}\n");
@ -195,7 +195,7 @@ void EnumGenerator::GenerateSymbolImports(io::Printer* printer) const {
format("typedef $classname$ $nested_name$;\n");
for (int j = 0; j < descriptor_->value_count(); j++) {
string deprecated_attr = DeprecatedAttribute(
std::string deprecated_attr = DeprecatedAttribute(
options_, descriptor_->value(j)->options().deprecated());
format(
"$1$static constexpr $nested_name$ ${2$$3$$}$ =\n"
@ -230,7 +230,7 @@ void EnumGenerator::GenerateSymbolImports(io::Printer* printer) const {
// TODO(haberman): consider removing this in favor of the stricter
// version below. Would this break our compatibility guarantees?
format(
"static inline const $string$& "
"static inline const std::string& "
"$nested_name$_Name($nested_name$ value) {"
"\n"
" return $classname$_Name(value);\n"
@ -241,7 +241,8 @@ void EnumGenerator::GenerateSymbolImports(io::Printer* printer) const {
// an integral type.
format(
"template<typename T>\n"
"static inline const $string$& $nested_name$_Name(T enum_t_value) {\n"
"static inline const std::string& $nested_name$_Name(T enum_t_value) "
"{\n"
" static_assert(::std::is_same<T, $nested_name$>::value ||\n"
" ::std::is_integral<T>::value,\n"
" \"Incorrect type passed to function $nested_name$_Name.\");\n"
@ -249,7 +250,7 @@ void EnumGenerator::GenerateSymbolImports(io::Printer* printer) const {
"}\n");
}
format(
"static inline bool $nested_name$_Parse(const $string$& name,\n"
"static inline bool $nested_name$_Parse(const std::string& name,\n"
" $nested_name$* value) {\n"
" return $classname$_Parse(name, value);\n"
"}\n");
@ -295,7 +296,7 @@ void EnumGenerator::GenerateMethods(int idx, io::Printer* printer) {
"\n");
if (descriptor_->containing_type() != NULL) {
string parent = ClassName(descriptor_->containing_type(), false);
std::string parent = ClassName(descriptor_->containing_type(), false);
// Before C++17, we must define the static constants which were
// declared in the header, to give the linker a place to put them.
// But pre-2015 MSVC++ insists that we not.

@ -58,7 +58,8 @@ class EnumGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
EnumGenerator(const EnumDescriptor* descriptor,
const std::map<std::string, std::string>& vars, const Options& options);
const std::map<std::string, std::string>& vars,
const Options& options);
~EnumGenerator();
// Generate header code defining the enum. This code should be placed

@ -46,11 +46,11 @@ namespace cpp {
namespace {
void SetEnumVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables,
std::map<std::string, std::string>* variables,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
const EnumValueDescriptor* default_value = descriptor->default_value_enum();
(*variables)["type"] = ClassName(descriptor->enum_type(), true);
(*variables)["type"] = QualifiedClassName(descriptor->enum_type(), options);
(*variables)["default"] = Int32ToString(default_value->number());
(*variables)["full_name"] = descriptor->full_name();
}
@ -90,7 +90,7 @@ void EnumFieldGenerator::GenerateInlineAccessorDefinitions(
" return static_cast< $type$ >($name$_);\n"
"}\n"
"inline void $classname$::set_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
if (!HasPreservingUnknownEnumSemantics(descriptor_)) {
format(" assert($type$_IsValid(value));\n");
}
format(
@ -134,7 +134,7 @@ void EnumFieldGenerator::GenerateMergeFromCodedStream(
"DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n"
" int, ::$proto_ns$::internal::WireFormatLite::TYPE_ENUM>(\n"
" input, &value)));\n");
if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
if (HasPreservingUnknownEnumSemantics(descriptor_)) {
format("set_$name$(static_cast< $type$ >(value));\n");
} else {
format(
@ -202,7 +202,7 @@ void EnumOneofFieldGenerator::GenerateInlineAccessorDefinitions(
" return static_cast< $type$ >($default$);\n"
"}\n"
"inline void $classname$::set_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
if (!HasPreservingUnknownEnumSemantics(descriptor_)) {
format(" assert($type$_IsValid(value));\n");
}
format(
@ -273,7 +273,7 @@ void RepeatedEnumFieldGenerator::GenerateInlineAccessorDefinitions(
" return static_cast< $type$ >($name$_.Get(index));\n"
"}\n"
"inline void $classname$::set_$name$(int index, $type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
if (!HasPreservingUnknownEnumSemantics(descriptor_)) {
format(" assert($type$_IsValid(value));\n");
}
format(
@ -281,7 +281,7 @@ void RepeatedEnumFieldGenerator::GenerateInlineAccessorDefinitions(
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"inline void $classname$::add_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
if (!HasPreservingUnknownEnumSemantics(descriptor_)) {
format(" assert($type$_IsValid(value));\n");
}
format(
@ -332,7 +332,7 @@ void RepeatedEnumFieldGenerator::GenerateMergeFromCodedStream(
"DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n"
" int, ::$proto_ns$::internal::WireFormatLite::TYPE_ENUM>(\n"
" input, &value)));\n");
if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
if (HasPreservingUnknownEnumSemantics(descriptor_)) {
format("add_$name$(static_cast< $type$ >(value));\n");
} else {
format(
@ -359,7 +359,7 @@ void RepeatedEnumFieldGenerator::GenerateMergeFromCodedStreamWithPacking(
Formatter format(printer, variables_);
if (!descriptor_->is_packed()) {
// This path is rarely executed, so we use a non-inlined implementation.
if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
if (HasPreservingUnknownEnumSemantics(descriptor_)) {
format(
"DO_((::$proto_ns$::internal::"
"WireFormatLite::ReadPackedEnumPreserveUnknowns(\n"
@ -398,7 +398,7 @@ void RepeatedEnumFieldGenerator::GenerateMergeFromCodedStreamWithPacking(
" DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n"
" int, ::$proto_ns$::internal::WireFormatLite::TYPE_ENUM>(\n"
" input, &value)));\n");
if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
if (HasPreservingUnknownEnumSemantics(descriptor_)) {
format(" add_$name$(static_cast< $type$ >(value));\n");
} else {
format(

@ -51,7 +51,7 @@ namespace {
// Returns the fully-qualified class name of the message that this field
// extends. This function is used in the Google-internal code to handle some
// legacy cases.
string ExtendeeClassName(const FieldDescriptor* descriptor) {
std::string ExtendeeClassName(const FieldDescriptor* descriptor) {
const Descriptor* extendee = descriptor->containing_type();
return ClassName(extendee, true);
}
@ -92,17 +92,17 @@ ExtensionGenerator::ExtensionGenerator(const FieldDescriptor* descriptor,
SetCommonVars(options, &variables_);
variables_["extendee"] = ExtendeeClassName(descriptor_);
variables_["type_traits"] = type_traits_;
string name = descriptor_->name();
std::string name = descriptor_->name();
variables_["name"] = name;
variables_["constant_name"] = FieldConstantName(descriptor_);
variables_["field_type"] =
StrCat(static_cast<int>(descriptor_->type()));
variables_["packed"] = descriptor_->options().packed() ? "true" : "false";
string scope =
std::string scope =
IsScoped() ? ClassName(descriptor_->extension_scope(), false) + "::" : "";
variables_["scope"] = scope;
string scoped_name = scope + name;
std::string scoped_name = scope + name;
variables_["scoped_name"] = scoped_name;
variables_["number"] = StrCat(descriptor_->number());
}
@ -119,7 +119,7 @@ void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) const {
// If this is a class member, it needs to be declared "static". Otherwise,
// it needs to be "extern". In the latter case, it also needs the DLL
// export/import specifier.
string qualifier;
std::string qualifier;
if (!IsScoped()) {
qualifier = "extern";
if (!options_.dllexport_decl.empty()) {
@ -149,7 +149,7 @@ void ExtensionGenerator::GenerateDefinition(io::Printer* printer) {
}
Formatter format(printer, variables_);
string default_str;
std::string default_str;
// If this is a class member, it needs to be declared in its class scope.
if (descriptor_->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
// We need to declare a global string which will contain the default value.
@ -158,7 +158,7 @@ void ExtensionGenerator::GenerateDefinition(io::Printer* printer) {
// replace :: with _ in the name and declare it as a global.
default_str =
StringReplace(variables_["scoped_name"], "::", "_", true) + "_default";
format("const ::std::string $1$($2$);\n", default_str,
format("const std::string $1$($2$);\n", default_str,
DefaultValue(options_, descriptor_));
} else {
default_str = DefaultValue(options_, descriptor_);

@ -57,10 +57,10 @@ namespace cpp {
using internal::WireFormat;
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables,
std::map<std::string, std::string>* variables,
const Options& options) {
SetCommonVars(options, variables);
(*variables)["ns"] = Namespace(descriptor);
(*variables)["ns"] = Namespace(descriptor, options);
(*variables)["name"] = FieldName(descriptor);
(*variables)["index"] = StrCat(descriptor->index());
(*variables)["number"] = StrCat(descriptor->number());
@ -102,9 +102,10 @@ void FieldGenerator::SetHasBitIndex(int32 has_bit_index) {
strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8), "u;");
}
void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables) {
const string prefix = descriptor->containing_oneof()->name() + "_.";
void SetCommonOneofFieldVariables(
const FieldDescriptor* descriptor,
std::map<std::string, std::string>* variables) {
const std::string prefix = descriptor->containing_oneof()->name() + "_.";
(*variables)["oneof_name"] = descriptor->containing_oneof()->name();
(*variables)["field_member"] =
StrCat(prefix, (*variables)["name"], "_");

@ -64,8 +64,9 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
std::map<std::string, std::string>* variables,
const Options& options);
void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor,
std::map<std::string, std::string>* variables);
void SetCommonOneofFieldVariables(
const FieldDescriptor* descriptor,
std::map<std::string, std::string>* variables);
class FieldGenerator {
public:

@ -74,7 +74,7 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options)
UniqueName("file_level_service_descriptors", file_, options_);
variables_["add_descriptors"] = UniqueName("AddDescriptors", file_, options_);
variables_["filename"] = file_->name();
variables_["package_ns"] = Namespace(file_);
variables_["package_ns"] = Namespace(file_, options);
variables_["init_defaults"] = UniqueName("InitDefaults", file_, options_);
std::vector<const Descriptor*> msgs = FlattenMessagesInFile(file);
@ -120,11 +120,11 @@ void FileGenerator::GenerateMacroUndefs(io::Printer* printer) {
file_->name() != "google/protobuf/compiler/plugin.proto") {
return;
}
std::vector<string> names_to_undef;
std::vector<std::string> names_to_undef;
std::vector<const FieldDescriptor*> fields;
ListAllFields(file_, &fields);
for (int i = 0; i < fields.size(); i++) {
const string& name = fields[i]->name();
const std::string& name = fields[i]->name();
static const char* kMacroNames[] = {"major", "minor"};
for (int i = 0; i < GOOGLE_ARRAYSIZE(kMacroNames); ++i) {
if (name == kMacroNames[i]) {
@ -156,6 +156,15 @@ void FileGenerator::GenerateHeader(io::Printer* printer) {
format("class TagMapper;\n");
}
// For Any support with lite protos, we need to friend AnyMetadata, so we
// forward-declare it here.
format(
"PROTOBUF_NAMESPACE_OPEN\n"
"namespace internal {\n"
"class AnyMetadata;\n"
"} // namespace internal\n"
"PROTOBUF_NAMESPACE_CLOSE\n");
if (!options_.opensource_runtime) {
// EmbeddedMessageHolder is a proxy class to provide access into arena
// constructors for proto1 message objects.
@ -173,7 +182,7 @@ void FileGenerator::GenerateHeader(io::Printer* printer) {
GenerateForwardDeclarations(printer);
{
NamespaceOpener ns(Namespace(file_), format);
NamespaceOpener ns(Namespace(file_, options_), format);
format("\n");
@ -215,14 +224,13 @@ void FileGenerator::GenerateHeader(io::Printer* printer) {
}
void FileGenerator::GenerateProtoHeader(io::Printer* printer,
const string& info_path) {
const std::string& info_path) {
Formatter format(printer, variables_);
if (!options_.proto_h) {
return;
}
string filename_identifier = FilenameIdentifier(file_->name());
GenerateTopHeaderGuard(printer, filename_identifier);
GenerateTopHeaderGuard(printer, false);
if (!options_.opensource_runtime) {
format(
@ -247,7 +255,7 @@ void FileGenerator::GenerateProtoHeader(io::Printer* printer,
if (IsProto1(dep, options_)) {
extension = ".pb.h";
}
string dependency = StripProto(dep->name()) + extension;
std::string dependency = StripProto(dep->name()) + extension;
format("#include \"$1$\"\n", dependency);
}
@ -257,18 +265,16 @@ void FileGenerator::GenerateProtoHeader(io::Printer* printer,
GenerateHeader(printer);
GenerateBottomHeaderGuard(printer, filename_identifier);
GenerateBottomHeaderGuard(printer, false);
}
void FileGenerator::GeneratePBHeader(io::Printer* printer,
const string& info_path) {
const std::string& info_path) {
Formatter format(printer, variables_);
string filename_identifier =
FilenameIdentifier(file_->name() + (options_.proto_h ? ".pb.h" : ""));
GenerateTopHeaderGuard(printer, filename_identifier);
GenerateTopHeaderGuard(printer, true);
if (options_.proto_h) {
string target_basename = StripProto(file_->name());
std::string target_basename = StripProto(file_->name());
if (!options_.opensource_runtime) {
GetBootstrapBasename(options_, target_basename, &target_basename);
}
@ -293,7 +299,7 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer,
GenerateHeader(printer);
} else {
{
NamespaceOpener ns(Namespace(file_), format);
NamespaceOpener ns(Namespace(file_, options_), format);
format(
"\n"
"// @@protoc_insertion_point(namespace_scope)\n");
@ -304,17 +310,17 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer,
"\n");
}
GenerateBottomHeaderGuard(printer, filename_identifier);
GenerateBottomHeaderGuard(printer, true);
}
void FileGenerator::DoIncludeFile(const string& google3_name, bool do_export,
io::Printer* printer) {
void FileGenerator::DoIncludeFile(const std::string& google3_name,
bool do_export, io::Printer* printer) {
Formatter format(printer, variables_);
const string prefix = "net/proto2/";
const std::string prefix = "net/proto2/";
GOOGLE_CHECK(google3_name.find(prefix) == 0) << google3_name;
if (options_.opensource_runtime) {
string path = google3_name.substr(prefix.size());
std::string path = google3_name.substr(prefix.size());
path = StringReplace(path, "internal/", "", false);
path = StringReplace(path, "proto/", "", false);
@ -336,10 +342,10 @@ void FileGenerator::DoIncludeFile(const string& google3_name, bool do_export,
format("\n");
}
string FileGenerator::CreateHeaderInclude(const string& basename,
const FileDescriptor* file) {
std::string FileGenerator::CreateHeaderInclude(const std::string& basename,
const FileDescriptor* file) {
bool use_system_include = false;
string name = basename;
std::string name = basename;
if (options_.opensource_runtime) {
if (IsWellKnownMessage(file)) {
@ -351,8 +357,8 @@ string FileGenerator::CreateHeaderInclude(const string& basename,
}
}
string left = "\"";
string right = "\"";
std::string left = "\"";
std::string right = "\"";
if (use_system_include) {
left = "<";
right = ">";
@ -362,7 +368,7 @@ string FileGenerator::CreateHeaderInclude(const string& basename,
void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
Formatter format(printer, variables_);
string target_basename = StripProto(file_->name());
std::string target_basename = StripProto(file_->name());
if (!options_.opensource_runtime) {
GetBootstrapBasename(options_, target_basename, &target_basename);
}
@ -384,7 +390,7 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
IncludeFile("net/proto2/io/public/coded_stream.h", printer);
// TODO(gerbens) This is to include parse_context.h, we need a better way
IncludeFile("net/proto2/public/extension_set.h", printer);
IncludeFile("net/proto2/public/wire_format_lite_inl.h", printer);
IncludeFile("net/proto2/public/wire_format_lite.h", printer);
// Unknown fields implementation in lite mode uses StringOutputStream
if (!UseUnknownFieldSet(file_, options_) && !message_generators_.empty()) {
@ -408,7 +414,7 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
for (int i = 0; i < file_->dependency_count(); i++) {
const FileDescriptor* dep = file_->dependency(i);
const char* extension = ".proto.h";
string basename = StripProto(dep->name());
std::string basename = StripProto(dep->name());
// Do not import weak deps.
if (!options_.opensource_runtime && IsDepWeak(dep)) continue;
// The proto1 compiler only generates .pb.h files, so even if we are
@ -419,7 +425,7 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
if (IsBootstrapProto(options_, file_)) {
GetBootstrapBasename(options_, basename, &basename);
}
string dependency = basename + extension;
std::string dependency = basename + extension;
format("#include \"$1$\"\n", dependency);
}
}
@ -451,9 +457,9 @@ void FileGenerator::GenerateInternalForwardDeclarations(
// To ensure determinism and minimize the number of namespace statements,
// we output the forward declarations sorted on namespace and type / function
// name.
std::set<string> global_namespace_decls;
std::set<std::string> global_namespace_decls;
// weak defaults
std::set<std::pair<string, string> > messages;
std::set<std::pair<std::string, std::string> > messages;
for (int i = 0; i < fields.size(); ++i) {
const FieldDescriptor* field = fields[i];
const Descriptor* msg = field->message_type();
@ -463,20 +469,21 @@ void FileGenerator::GenerateInternalForwardDeclarations(
GOOGLE_CHECK(!options_.opensource_runtime);
is_weak = true;
}
string weak_attr;
std::string weak_attr;
if (is_weak) {
global_namespace_decls.insert(
"void " + UniqueName("AddDescriptors", msg, options_) +
"() __attribute__((weak))");
messages.insert(std::make_pair(Namespace(msg), ClassName(msg)));
messages.insert(std::make_pair(Namespace(msg, options_), ClassName(msg)));
weak_attr = " __attribute__((weak))";
}
string dllexport = UniqueName("PROTOBUF_INTERNAL_EXPORT", msg, options_);
std::string dllexport =
UniqueName("PROTOBUF_INTERNAL_EXPORT", msg, options_);
if (IsProto1(msg->file(), options_) || IsWeak(field, options_)) {
dllexport = "";
}
auto scc = scc_analyzer->GetSCC(msg);
string repr =
std::string repr =
UniqueName(ClassName(scc->GetRepresentative()), msg, options_);
global_namespace_decls.insert(StrCat(
"extern ", dllexport, weak_attr, " ::", ProtobufNamespace(options),
@ -485,7 +492,7 @@ void FileGenerator::GenerateInternalForwardDeclarations(
format("\n");
for (const string& decl : global_namespace_decls) {
for (const std::string& decl : global_namespace_decls) {
format("$1$;\n", decl);
}
@ -521,7 +528,7 @@ void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) {
}
{ // package namespace
NamespaceOpener ns(Namespace(file_), format);
NamespaceOpener ns(Namespace(file_, options_), format);
// Define default instances
GenerateSourceDefaultInstance(idx, printer);
@ -563,7 +570,7 @@ void FileGenerator::GenerateGlobalSource(io::Printer* printer) {
}
}
NamespaceOpener ns(Namespace(file_), format);
NamespaceOpener ns(Namespace(file_, options_), format);
// Generate enums.
for (int i = 0; i < enum_generators_.size(); i++) {
@ -595,7 +602,7 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
printer);
{
NamespaceOpener ns(Namespace(file_), format);
NamespaceOpener ns(Namespace(file_, options_), format);
// Define default instances
for (int i = 0; i < message_generators_.size(); i++) {
@ -624,7 +631,7 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
format("void $init_defaults$() {\n");
for (int i = 0; i < message_generators_.size(); i++) {
if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue;
string scc_name =
std::string scc_name =
UniqueName(ClassName(message_generators_[i]->descriptor_),
message_generators_[i]->descriptor_, options_);
format(" ::$proto_ns$::internal::InitSCC(&scc_info_$1$.base);\n",
@ -639,7 +646,7 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
}
{
NamespaceOpener ns(Namespace(file_), format);
NamespaceOpener ns(Namespace(file_, options_), format);
// Actually implement the protos
@ -774,7 +781,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
format(
"reinterpret_cast<const "
"::$proto_ns$::Message*>(&$1$::_$2$_default_instance_),\n",
Namespace(descriptor), // 1
Namespace(descriptor, options_), // 1
ClassName(descriptor)); // 2
}
format.Outdent();
@ -814,13 +821,13 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
// Embed the descriptor. We simply serialize the entire
// FileDescriptorProto/ and embed it as a string literal, which is parsed and
// built into real descriptors at initialization time.
const string protodef_name =
const std::string protodef_name =
UniqueName("descriptor_table_protodef", file_, options_);
format( "const char $1$[] =\n", protodef_name);
format.Indent();
FileDescriptorProto file_proto;
file_->CopyTo(&file_proto);
string file_data;
std::string file_data;
file_proto.SerializeToString(&file_data);
{
@ -885,7 +892,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) {
Formatter format(printer, variables_);
const string scc_name = ClassName(scc->GetRepresentative());
const std::string scc_name = ClassName(scc->GetRepresentative());
// We use static and not anonymous namespace because symbol names are
// substantially shorter.
format("static void InitDefaults$1$() {\n",
@ -916,14 +923,16 @@ void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) {
message_generators_[i]->GenerateFieldDefaultInstances(printer);
format(
"{\n"
" void* ptr = &$1$::_$2$_default_instance_;\n"
" new (ptr) $1$::$2$();\n",
Namespace(message_generators_[i]->descriptor_), // 1
ClassName(message_generators_[i]->descriptor_)); // 2
" void* ptr = &$1$;\n"
" new (ptr) $2$();\n",
DefaultInstanceName(message_generators_[i]->descriptor_, options_),
QualifiedClassName(message_generators_[i]->descriptor_, options_));
if (options_.opensource_runtime &&
!IsMapEntryMessage(message_generators_[i]->descriptor_)) {
format(
" ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);\n");
" "
"::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);"
"\n");
}
format("}\n");
}
@ -936,7 +945,7 @@ void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) {
continue;
}
format("$1$::InitAsDefaultInstance();\n",
QualifiedClassName(message_generators_[i]->descriptor_));
QualifiedClassName(message_generators_[i]->descriptor_, options_));
}
format.Outdent();
format("}\n\n");
@ -1080,7 +1089,7 @@ class FileGenerator::ForwardDeclarations {
void Print(const Formatter& format, const Options& options) const {
for (const auto& p : enums_) {
const string& enumname = p.first;
const std::string& enumname = p.first;
const EnumDescriptor* enum_desc = p.second;
format(
"enum ${1$$2$$}$ : int;\n"
@ -1088,7 +1097,7 @@ class FileGenerator::ForwardDeclarations {
enum_desc, enumname);
}
for (const auto& p : classes_) {
const string& classname = p.first;
const std::string& classname = p.first;
const Descriptor* class_desc = p.second;
format(
"class ${1$$2$$}$;\n"
@ -1102,18 +1111,19 @@ class FileGenerator::ForwardDeclarations {
}
}
void PrintTopLevelDecl(const Formatter& format) const {
void PrintTopLevelDecl(const Formatter& format,
const Options& options) const {
for (const auto& pair : classes_) {
format(
"template<> $dllexport_decl $"
"$1$* Arena::CreateMaybeMessage<$1$>(Arena*);\n",
QualifiedClassName(pair.second));
QualifiedClassName(pair.second, options));
}
}
private:
std::map<string, const Descriptor*> classes_;
std::map<string, const EnumDescriptor*> enums_;
std::map<std::string, const Descriptor*> classes_;
std::map<std::string, const EnumDescriptor*> enums_;
};
static void PublicImportDFS(const FileDescriptor* fd,
@ -1148,42 +1158,46 @@ void FileGenerator::GenerateForwardDeclarations(io::Printer* printer) {
std::unordered_set<const FileDescriptor*> public_set;
PublicImportDFS(file_, &public_set);
std::map<string, ForwardDeclarations> decls;
std::map<std::string, ForwardDeclarations> decls;
for (int i = 0; i < classes.size(); i++) {
const Descriptor* d = classes[i];
if (d && !public_set.count(d->file())) decls[Namespace(d)].AddMessage(d);
if (d && !public_set.count(d->file()))
decls[Namespace(d, options_)].AddMessage(d);
}
for (int i = 0; i < enums.size(); i++) {
const EnumDescriptor* d = enums[i];
if (d && !public_set.count(d->file())) decls[Namespace(d)].AddEnum(d);
if (d && !public_set.count(d->file()))
decls[Namespace(d, options_)].AddEnum(d);
}
NamespaceOpener ns(format);
for (const auto& pair : decls) {
ns.ChangeTo(pair.first);
pair.second.Print(format, options_);
{
NamespaceOpener ns(format);
for (const auto& pair : decls) {
ns.ChangeTo(pair.first);
pair.second.Print(format, options_);
}
}
ns.ChangeTo(variables_["proto_ns"]);
format("PROTOBUF_NAMESPACE_OPEN\n");
for (const auto& pair : decls) {
pair.second.PrintTopLevelDecl(format);
pair.second.PrintTopLevelDecl(format, options_);
}
format("PROTOBUF_NAMESPACE_CLOSE\n");
}
void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer,
const string& filename_identifier) {
void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer, bool pb_h) {
Formatter format(printer, variables_);
// Generate top of header.
format(
"// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"// source: $filename$\n"
"\n"
"#ifndef PROTOBUF_INCLUDED_$1$\n"
"#define PROTOBUF_INCLUDED_$1$\n"
"#ifndef $1$\n"
"#define $1$\n"
"\n"
"#include <limits>\n"
"#include <string>\n",
filename_identifier);
IncludeGuard(file_, pb_h, options_));
if (!options_.opensource_runtime && !enum_generators_.empty()) {
// Add header to provide std::is_integral for safe Enum_Name() function.
format("#include <type_traits>\n");
@ -1191,10 +1205,10 @@ void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer,
format("\n");
}
void FileGenerator::GenerateBottomHeaderGuard(
io::Printer* printer, const string& filename_identifier) {
void FileGenerator::GenerateBottomHeaderGuard(io::Printer* printer, bool pb_h) {
Formatter format(printer, variables_);
format("#endif // PROTOBUF_INCLUDED_$1$\n", filename_identifier);
format("#endif // $GOOGLE_PROTOBUF$_INCLUDED_$1$\n",
IncludeGuard(file_, pb_h, options_));
}
void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) {
@ -1302,31 +1316,11 @@ void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) {
if (IsAnyMessage(file_, options_)) {
IncludeFile("net/proto2/internal/any.h", printer);
} else {
// For Any support with lite protos, we need to friend AnyMetadata, so we
// forward-declare it here.
if (options_.opensource_runtime) {
format(
"namespace google {\n"
"namespace protobuf {\n"
"namespace internal {\n"
"class AnyMetadata;\n"
"} // namespace internal\n"
"} // namespace protobuf\n"
"} // namespace google\n");
} else {
format(
"namespace google {\nnamespace protobuf {\n"
"namespace internal {\n"
"class AnyMetadata;\n"
"} // namespace internal\n"
"} // namespace protobuf\n} // namespace google\n");
}
}
}
void FileGenerator::GenerateMetadataPragma(io::Printer* printer,
const string& info_path) {
const std::string& info_path) {
Formatter format(printer, variables_);
if (!info_path.empty() && !options_.annotation_pragma_name.empty() &&
!options_.annotation_guard_name.empty()) {
@ -1343,7 +1337,7 @@ void FileGenerator::GenerateMetadataPragma(io::Printer* printer,
void FileGenerator::GenerateDependencyIncludes(io::Printer* printer) {
Formatter format(printer, variables_);
for (int i = 0; i < file_->dependency_count(); i++) {
string basename = StripProto(file_->dependency(i)->name());
std::string basename = StripProto(file_->dependency(i)->name());
// Do not import weak deps.
if (IsDepWeak(file_->dependency(i))) continue;

@ -94,14 +94,15 @@ class FileGenerator {
void IncludeFile(const std::string& google3_name, io::Printer* printer) {
DoIncludeFile(google3_name, false, printer);
}
void IncludeFileAndExport(const std::string& google3_name, io::Printer* printer) {
void IncludeFileAndExport(const std::string& google3_name,
io::Printer* printer) {
DoIncludeFile(google3_name, true, printer);
}
void DoIncludeFile(const std::string& google3_name, bool do_export,
io::Printer* printer);
std::string CreateHeaderInclude(const std::string& basename,
const FileDescriptor* file);
const FileDescriptor* file);
void GenerateInternalForwardDeclarations(
const std::vector<const FieldDescriptor*>& fields, const Options& options,
MessageSCCAnalyzer* scc_analyzer, io::Printer* printer);
@ -116,10 +117,8 @@ class FileGenerator {
void GenerateForwardDeclarations(io::Printer* printer);
// Generates top or bottom of a header file.
void GenerateTopHeaderGuard(io::Printer* printer,
const std::string& filename_identifier);
void GenerateBottomHeaderGuard(io::Printer* printer,
const std::string& filename_identifier);
void GenerateTopHeaderGuard(io::Printer* printer, bool pb_h);
void GenerateBottomHeaderGuard(io::Printer* printer, bool pb_h);
// Generates #include directives.
void GenerateLibraryIncludes(io::Printer* printer);
@ -127,7 +126,8 @@ class FileGenerator {
// Generate a pragma to pull in metadata using the given info_path (if
// non-empty). info_path should be relative to printer's output.
void GenerateMetadataPragma(io::Printer* printer, const std::string& info_path);
void GenerateMetadataPragma(io::Printer* printer,
const std::string& info_path);
// Generates a couple of different pieces before definitions:
void GenerateGlobalStateFunctionDeclarations(io::Printer* printer);

@ -56,10 +56,10 @@ CppGenerator::CppGenerator() {}
CppGenerator::~CppGenerator() {}
bool CppGenerator::Generate(const FileDescriptor* file,
const string& parameter,
const std::string& parameter,
GeneratorContext* generator_context,
string* error) const {
std::vector<std::pair<string, string> > options;
std::string* error) const {
std::vector<std::pair<std::string, std::string> > options;
ParseGeneratorParameter(parameter, &options);
// -----------------------------------------------------------------
@ -125,7 +125,7 @@ bool CppGenerator::Generate(const FileDescriptor* file,
// -----------------------------------------------------------------
string basename = StripProto(file->name());
std::string basename = StripProto(file->name());
if (MaybeBootstrap(file_options, generator_context, file_options.bootstrap,
&basename)) {
@ -141,7 +141,7 @@ bool CppGenerator::Generate(const FileDescriptor* file,
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
&annotations);
string info_path = basename + ".proto.h.meta";
std::string info_path = basename + ".proto.h.meta";
io::Printer printer(output.get(), '$', file_options.annotate_headers
? &annotation_collector
: NULL);
@ -160,7 +160,7 @@ bool CppGenerator::Generate(const FileDescriptor* file,
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
&annotations);
string info_path = basename + ".pb.h.meta";
std::string info_path = basename + ".pb.h.meta";
io::Printer printer(output.get(), '$', file_options.annotate_headers
? &annotation_collector
: NULL);

@ -80,10 +80,8 @@ class PROTOC_EXPORT CppGenerator : public CodeGenerator {
}
// implements CodeGenerator ----------------------------------------
bool Generate(const FileDescriptor* file,
const std::string& parameter,
GeneratorContext* generator_context,
std::string* error) const;
bool Generate(const FileDescriptor* file, const std::string& parameter,
GeneratorContext* generator_context, std::string* error) const;
private:
bool opensource_runtime_ = true;

@ -42,6 +42,7 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/compiler/scc.h>
#include <google/protobuf/io/printer.h>
@ -68,11 +69,11 @@ static const char kAnyMessageName[] = "Any";
static const char kAnyProtoFile[] = "google/protobuf/any.proto";
static const char kGoogleProtobufPrefix[] = "google/protobuf/";
string DotsToUnderscores(const string& name) {
std::string DotsToUnderscores(const std::string& name) {
return StringReplace(name, ".", "_", true);
}
string DotsToColons(const string& name) {
std::string DotsToColons(const std::string& name) {
return StringReplace(name, ".", "::", true);
}
@ -161,15 +162,15 @@ static const char* const kKeywordList[] = { //
"xor",
"xor_eq"};
static std::unordered_set<string>* MakeKeywordsMap() {
auto* result = new std::unordered_set<string>();
static std::unordered_set<std::string>* MakeKeywordsMap() {
auto* result = new std::unordered_set<std::string>();
for (const auto keyword : kKeywordList) {
result->emplace(keyword);
}
return result;
}
static std::unordered_set<string>& kKeywords = *MakeKeywordsMap();
static std::unordered_set<std::string>& kKeywords = *MakeKeywordsMap();
// Returns whether the provided descriptor has an extension. This includes its
// nested types.
@ -200,8 +201,8 @@ char Base63Char(int value) {
// Given a c identifier has 63 legal characters we can't implement base64
// encoding. So we return the k least significant "digits" in base 63.
template <typename I>
string Base63(I n, int k) {
string res;
std::string Base63(I n, int k) {
std::string res;
while (k-- > 0) {
res += Base63Char(static_cast<int>(n % 63));
n /= 63;
@ -209,27 +210,23 @@ string Base63(I n, int k) {
return res;
}
string IntTypeName(const Options& options, const string& type) {
std::string IntTypeName(const Options& options, const std::string& type) {
if (options.opensource_runtime) {
return "::google::protobuf::" + type;
return "::PROTOBUF_NAMESPACE_ID::" + type;
} else {
return "::" + type;
}
}
string StringTypeName(const Options& options) {
return options.opensource_runtime ? "::std::string" : "::std::string";
}
void SetIntVar(const Options& options, const string& type,
std::map<string, string>* variables) {
void SetIntVar(const Options& options, const std::string& type,
std::map<std::string, std::string>* variables) {
(*variables)[type] = IntTypeName(options, type);
}
} // namespace
void SetCommonVars(const Options& options,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
(*variables)["proto_ns"] = ProtobufNamespace(options);
// Warning: there is some clever naming/splitting here to avoid extract script
@ -262,11 +259,12 @@ void SetCommonVars(const Options& options,
SetIntVar(options, "uint64", variables);
SetIntVar(options, "int32", variables);
SetIntVar(options, "int64", variables);
(*variables)["string"] = StringTypeName(options);
(*variables)["string"] = "std::string";
}
string UnderscoresToCamelCase(const string& input, bool cap_next_letter) {
string result;
std::string UnderscoresToCamelCase(const std::string& input,
bool cap_next_letter) {
std::string result;
// Note: I distrust ctype.h due to locales.
for (int i = 0; i < input.size(); i++) {
if ('a' <= input[i] && input[i] <= 'z') {
@ -319,16 +317,16 @@ bool CanInitializeByZeroing(const FieldDescriptor* field) {
}
}
string ClassName(const Descriptor* descriptor) {
std::string ClassName(const Descriptor* descriptor) {
const Descriptor* parent = descriptor->containing_type();
string res;
std::string res;
if (parent) res += ClassName(parent) + "_";
res += descriptor->name();
if (IsMapEntryMessage(descriptor)) res += "_DoNotUse";
return res;
}
string ClassName(const EnumDescriptor* enum_descriptor) {
std::string ClassName(const EnumDescriptor* enum_descriptor) {
if (enum_descriptor->containing_type() == nullptr) {
return enum_descriptor->name();
} else {
@ -337,43 +335,72 @@ string ClassName(const EnumDescriptor* enum_descriptor) {
}
}
string QualifiedClassName(const Descriptor* d) {
return Namespace(d) + "::" + ClassName(d);
std::string QualifiedClassName(const Descriptor* d, const Options& options) {
return QualifiedFileLevelSymbol(d->file(), ClassName(d), options);
}
std::string QualifiedClassName(const EnumDescriptor* d,
const Options& options) {
return QualifiedFileLevelSymbol(d->file(), ClassName(d), options);
}
std::string QualifiedClassName(const Descriptor* d) {
return QualifiedClassName(d, Options());
}
string QualifiedClassName(const EnumDescriptor* d) {
return Namespace(d) + "::" + ClassName(d);
std::string QualifiedClassName(const EnumDescriptor* d) {
return QualifiedClassName(d, Options());
}
string Namespace(const string& package) {
std::string Namespace(const std::string& package) {
if (package.empty()) return "";
return "::" + DotsToColons(package);
}
string Namespace(const Descriptor* d) { return Namespace(d->file()); }
std::string Namespace(const FileDescriptor* d, const Options& options) {
std::string ret = Namespace(d->package());
if (IsWellKnownMessage(d) && options.opensource_runtime) {
// Written with string concatenation to prevent rewriting of
// ::google::protobuf.
ret = StringReplace(ret, "::google::" "protobuf", "PROTOBUF_NAMESPACE_ID",
false);
}
return ret;
}
std::string Namespace(const Descriptor* d, const Options& options) {
return Namespace(d->file(), options);
}
string Namespace(const FieldDescriptor* d) { return Namespace(d->file()); }
std::string Namespace(const FieldDescriptor* d, const Options& options) {
return Namespace(d->file(), options);
}
string Namespace(const EnumDescriptor* d) { return Namespace(d->file()); }
std::string Namespace(const EnumDescriptor* d, const Options& options) {
return Namespace(d->file(), options);
}
string DefaultInstanceName(const Descriptor* descriptor) {
string prefix = descriptor->file()->package().empty() ? "" : "::";
return prefix + DotsToColons(descriptor->file()->package()) + "::_" +
ClassName(descriptor, false) + "_default_instance_";
std::string DefaultInstanceName(const Descriptor* descriptor,
const Options& options) {
return QualifiedFileLevelSymbol(
descriptor->file(),
"_" + ClassName(descriptor, false) + "_default_instance_", options);
}
string ReferenceFunctionName(const Descriptor* descriptor) {
return QualifiedClassName(descriptor) + "_ReferenceStrong";
std::string ReferenceFunctionName(const Descriptor* descriptor,
const Options& options) {
return QualifiedClassName(descriptor, options) + "_ReferenceStrong";
}
string SuperClassName(const Descriptor* descriptor, const Options& options) {
std::string SuperClassName(const Descriptor* descriptor,
const Options& options) {
return "::" + ProtobufNamespace(options) +
(HasDescriptorMethods(descriptor->file(), options) ? "::Message"
: "::MessageLite");
}
string FieldName(const FieldDescriptor* field) {
string result = field->name();
std::string FieldName(const FieldDescriptor* field) {
std::string result = field->name();
LowerString(&result);
if (kKeywords.count(result) > 0) {
result.append("_");
@ -381,8 +408,8 @@ string FieldName(const FieldDescriptor* field) {
return result;
}
string EnumValueName(const EnumValueDescriptor* enum_value) {
string result = enum_value->name();
std::string EnumValueName(const EnumValueDescriptor* enum_value) {
std::string result = enum_value->name();
if (kKeywords.count(result) > 0) {
result.append("_");
}
@ -413,9 +440,9 @@ int EstimateAlignmentSize(const FieldDescriptor* field) {
return -1; // Make compiler happy.
}
string FieldConstantName(const FieldDescriptor* field) {
string field_name = UnderscoresToCamelCase(field->name(), true);
string result = "k" + field_name + "FieldNumber";
std::string FieldConstantName(const FieldDescriptor* field) {
std::string field_name = UnderscoresToCamelCase(field->name(), true);
std::string result = "k" + field_name + "FieldNumber";
if (!field->is_extension() &&
field->containing_type()->FindFieldByCamelcaseName(
@ -429,13 +456,14 @@ string FieldConstantName(const FieldDescriptor* field) {
return result;
}
string FieldMessageTypeName(const FieldDescriptor* field) {
std::string FieldMessageTypeName(const FieldDescriptor* field,
const Options& options) {
// Note: The Google-internal version of Protocol Buffers uses this function
// as a hook point for hacks to support legacy code.
return ClassName(field->message_type(), true);
return QualifiedClassName(field->message_type(), options);
}
string StripProto(const string& filename) {
std::string StripProto(const std::string& filename) {
if (HasSuffixString(filename, ".protodevel")) {
return StripSuffixString(filename, ".protodevel");
} else {
@ -462,7 +490,7 @@ const char* PrimitiveTypeName(FieldDescriptor::CppType type) {
case FieldDescriptor::CPPTYPE_ENUM:
return "int";
case FieldDescriptor::CPPTYPE_STRING:
return "::std::string";
return "std::string";
case FieldDescriptor::CPPTYPE_MESSAGE:
return nullptr;
@ -474,8 +502,8 @@ const char* PrimitiveTypeName(FieldDescriptor::CppType type) {
return nullptr;
}
string PrimitiveTypeName(const Options& options,
FieldDescriptor::CppType type) {
std::string PrimitiveTypeName(const Options& options,
FieldDescriptor::CppType type) {
switch (type) {
case FieldDescriptor::CPPTYPE_INT32:
return IntTypeName(options, "int32");
@ -494,7 +522,7 @@ string PrimitiveTypeName(const Options& options,
case FieldDescriptor::CPPTYPE_ENUM:
return "int";
case FieldDescriptor::CPPTYPE_STRING:
return StringTypeName(options);
return "std::string";
case FieldDescriptor::CPPTYPE_MESSAGE:
return "";
@ -554,7 +582,7 @@ const char* DeclaredTypeMethodName(FieldDescriptor::Type type) {
return "";
}
string Int32ToString(int number) {
std::string Int32ToString(int number) {
if (number == kint32min) {
// This needs to be special-cased, see explanation here:
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52661
@ -564,7 +592,7 @@ string Int32ToString(int number) {
}
}
string Int64ToString(const string& macro_prefix, int64 number) {
std::string Int64ToString(const std::string& macro_prefix, int64 number) {
if (number == kint64min) {
// This needs to be special-cased, see explanation here:
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52661
@ -573,11 +601,11 @@ string Int64ToString(const string& macro_prefix, int64 number) {
return StrCat(macro_prefix, "_LONGLONG(", number, ")");
}
string UInt64ToString(const string& macro_prefix, uint64 number) {
std::string UInt64ToString(const std::string& macro_prefix, uint64 number) {
return StrCat(macro_prefix, "_ULONGLONG(", number, ")");
}
string DefaultValue(const FieldDescriptor* field) {
std::string DefaultValue(const FieldDescriptor* field) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT64:
return Int64ToString("GG", field->default_value_int64());
@ -588,7 +616,7 @@ string DefaultValue(const FieldDescriptor* field) {
}
}
string DefaultValue(const Options& options, const FieldDescriptor* field) {
std::string DefaultValue(const Options& options, const FieldDescriptor* field) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return Int32ToString(field->default_value_int32());
@ -619,7 +647,7 @@ string DefaultValue(const Options& options, const FieldDescriptor* field) {
} else if (value != value) {
return "std::numeric_limits<float>::quiet_NaN()";
} else {
string float_value = SimpleFtoa(value);
std::string float_value = SimpleFtoa(value);
// If floating point value contains a period (.) or an exponent
// (either E or e), then append suffix 'f' to make it a float
// literal.
@ -642,7 +670,7 @@ string DefaultValue(const Options& options, const FieldDescriptor* field) {
EscapeTrigraphs(CEscape(field->default_value_string())) +
"\"";
case FieldDescriptor::CPPTYPE_MESSAGE:
return "*" + FieldMessageTypeName(field) +
return "*" + FieldMessageTypeName(field, options) +
"::internal_default_instance()";
}
// Can't actually get here; make compiler happy. (We could add a default
@ -653,8 +681,8 @@ string DefaultValue(const Options& options, const FieldDescriptor* field) {
}
// Convert a file name into a valid identifier.
string FilenameIdentifier(const string& filename) {
string result;
std::string FilenameIdentifier(const std::string& filename) {
std::string result;
for (int i = 0; i < filename.size(); i++) {
if (ascii_isalnum(filename[i])) {
result.push_back(filename[i]);
@ -667,31 +695,34 @@ string FilenameIdentifier(const string& filename) {
return result;
}
string UniqueName(const string& name, const string& filename,
string UniqueName(const std::string& name, const std::string& filename,
const Options& options) {
return name + "_" + FilenameIdentifier(filename);
}
// Return the qualified C++ name for a file level symbol.
string QualifiedFileLevelSymbol(const string& package, const string& name) {
if (package.empty()) {
std::string QualifiedFileLevelSymbol(const FileDescriptor* file,
const std::string& name,
const Options& options) {
if (file->package().empty()) {
return StrCat("::", name);
}
return StrCat("::", DotsToColons(package), "::", name);
return StrCat(Namespace(file, options), "::", name);
}
// Escape C++ trigraphs by escaping question marks to \?
string EscapeTrigraphs(const string& to_escape) {
std::string EscapeTrigraphs(const std::string& to_escape) {
return StringReplace(to_escape, "?", "\\?", true);
}
// Escaped function name to eliminate naming conflict.
string SafeFunctionName(const Descriptor* descriptor,
const FieldDescriptor* field, const string& prefix) {
std::string SafeFunctionName(const Descriptor* descriptor,
const FieldDescriptor* field,
const std::string& prefix) {
// Do not use FieldName() since it will escape keywords.
string name = field->name();
std::string name = field->name();
LowerString(&name);
string function_name = prefix + name;
std::string function_name = prefix + name;
if (descriptor->FindFieldByName(function_name)) {
// Single underscore will also make it conflicting with the private data
// member. We use double underscore to escape function names.
@ -920,8 +951,22 @@ bool IsAnyMessage(const Descriptor* descriptor, const Options& options) {
IsAnyMessage(descriptor->file(), options);
}
bool IsWellKnownMessage(const FileDescriptor* descriptor) {
return !descriptor->name().compare(0, 16, kGoogleProtobufPrefix);
bool IsWellKnownMessage(const FileDescriptor* file) {
static const std::unordered_set<std::string> well_known_files{
"google/protobuf/any.proto",
"google/protobuf/api.proto",
"google/protobuf/compiler/plugin.proto",
"google/protobuf/descriptor.proto",
"google/protobuf/duration.proto",
"google/protobuf/empty.proto",
"google/protobuf/field_mask.proto",
"google/protobuf/source_context.proto",
"google/protobuf/struct.proto",
"google/protobuf/timestamp.proto",
"google/protobuf/type.proto",
"google/protobuf/wrappers.proto",
};
return well_known_files.find(file->name()) != well_known_files.end();
}
enum Utf8CheckMode {
@ -955,7 +1000,8 @@ static Utf8CheckMode GetUtf8CheckMode(const FieldDescriptor* field,
}
}
string GetUtf8Suffix(const FieldDescriptor* field, const Options& options) {
std::string GetUtf8Suffix(const FieldDescriptor* field,
const Options& options) {
switch (GetUtf8CheckMode(field, options)) {
case STRICT:
return "UTF8";
@ -1179,13 +1225,13 @@ void ListAllTypesForServices(const FileDescriptor* fd,
}
}
bool GetBootstrapBasename(const Options& options, const string& basename,
string* bootstrap_basename) {
bool GetBootstrapBasename(const Options& options, const std::string& basename,
std::string* bootstrap_basename) {
if (options.opensource_runtime || options.lite_implicit_weak_fields) {
return false;
}
std::unordered_map<string, string> bootstrap_mapping{
std::unordered_map<std::string, std::string> bootstrap_mapping{
{"net/proto2/proto/descriptor",
"net/proto2/internal/descriptor"},
{"net/proto2/compiler/proto/plugin",
@ -1204,13 +1250,13 @@ bool GetBootstrapBasename(const Options& options, const string& basename,
}
bool IsBootstrapProto(const Options& options, const FileDescriptor* file) {
string my_name = StripProto(file->name());
std::string my_name = StripProto(file->name());
return GetBootstrapBasename(options, my_name, &my_name);
}
bool MaybeBootstrap(const Options& options, GeneratorContext* generator_context,
bool bootstrap_flag, string* basename) {
string bootstrap_basename;
bool bootstrap_flag, std::string* basename) {
std::string bootstrap_basename;
if (!GetBootstrapBasename(options, *basename, &bootstrap_basename)) {
return false;
}
@ -1220,7 +1266,7 @@ bool MaybeBootstrap(const Options& options, GeneratorContext* generator_context,
*basename = bootstrap_basename;
return false;
} else {
string forward_to_basename = bootstrap_basename;
std::string forward_to_basename = bootstrap_basename;
// Generate forwarding headers and empty .pb.cc.
{
@ -1305,7 +1351,7 @@ class ParseLoopGenerator {
format_.Set("GOOGLE_PROTOBUF", MacroPrefix(options_));
format_.Set("kSlopBytes",
static_cast<int>(internal::ParseContext::kSlopBytes));
std::map<string, string> vars;
std::map<std::string, std::string> vars;
SetCommonVars(options_, &vars);
format_.AddMap(vars);
@ -1324,6 +1370,7 @@ class ParseLoopGenerator {
format_(
"const char* $classname$::_InternalParse(const char* ptr, "
"$pi_ns$::ParseContext* ctx) {\n"
" $p_ns$::Arena* arena = GetArena(); (void)arena;\n"
" while (!ctx->Done(&ptr)) {\n"
" $uint32$ tag;\n"
" ptr = $pi_ns$::ReadTag(ptr, &tag);\n"
@ -1338,7 +1385,7 @@ class ParseLoopGenerator {
// Print the field's (or oneof's) proto-syntax definition as a comment.
// We don't want to print group bodies so we cut off after the first
// line.
string def;
std::string def;
{
DebugStringOptions options;
options.elide_group_body = true;
@ -1419,20 +1466,30 @@ class ParseLoopGenerator {
using WireFormat = internal::WireFormat;
using WireFormatLite = internal::WireFormatLite;
void GenerateArenaString(const FieldDescriptor* field, const string& utf8,
const string& field_name) {
void GenerateArenaString(const FieldDescriptor* field,
const std::string& utf8, std::string field_name) {
if (!field_name.empty()) {
format_("static const char kFieldName[] = $1$;\n",
field_name.substr(2)); // remove ", "
field_name = ", kFieldName";
}
format_("if (arena != nullptr) {\n");
if (HasFieldPresence(field->file())) {
format_("HasBitSetters::set_has_$1$(this);\n", FieldName(field));
format_(" HasBitSetters::set_has_$1$(this);\n", FieldName(field));
}
format_(
"ptr = $pi_ns$::InlineCopyIntoArenaString$1$(&$2$_, ptr, ctx, "
"GetArenaNoVirtual()$3$);\n",
utf8, FieldName(field), field_name);
" ptr = $pi_ns$::InlineCopyIntoArenaString$1$(&$2$_, ptr, ctx, "
" arena$3$);\n"
"} else {\n"
" ptr = $pi_ns$::InlineGreedyStringParser$1$($4$_$2$(), ptr, ctx$3$);"
"\n}\n",
utf8, FieldName(field), field_name,
field->is_repeated() ? "add" : "mutable");
}
void GenerateStrings(const FieldDescriptor* field, bool check_utf8) {
string utf8;
string field_name;
std::string utf8;
std::string field_name;
if (check_utf8) {
utf8 = GetUtf8Suffix(field, options_);
if (!utf8.empty()) {
@ -1463,7 +1520,7 @@ class ParseLoopGenerator {
GenerateArenaString(field, utf8, field_name);
return;
}
string name;
std::string name;
switch (ctype) {
case FieldOptions::STRING:
name = "GreedyStringParser" + utf8;
@ -1483,11 +1540,11 @@ class ParseLoopGenerator {
void GenerateLengthDelim(const FieldDescriptor* field) {
if (!IsProto1(field->file(), options_) && field->is_packable()) {
string enum_validator;
if (!HasPreservingUnknownEnumSemantics(field->file()) &&
field->type() == FieldDescriptor::TYPE_ENUM) {
std::string enum_validator;
if (field->type() == FieldDescriptor::TYPE_ENUM &&
!HasPreservingUnknownEnumSemantics(field)) {
enum_validator = StrCat(
", ", QualifiedClassName(field->enum_type()),
", ", QualifiedClassName(field->enum_type(), options_),
"_IsValid, mutable_unknown_fields(), ", field->number());
}
format_(
@ -1515,7 +1572,21 @@ class ParseLoopGenerator {
break;
case FieldDescriptor::TYPE_MESSAGE: {
if (!IsProto1(field->file(), options_) && field->is_map()) {
format_("ptr = ctx->ParseMessage(&$1$_, ptr);\n", FieldName(field));
const FieldDescriptor* val =
field->message_type()->FindFieldByName("value");
GOOGLE_CHECK(val);
if (HasFieldPresence(field->file()) &&
val->type() == FieldDescriptor::TYPE_ENUM) {
format_(
"auto object = ::$proto_ns$::internal::InitEnumParseWrapper("
"&$1$_, $2$_IsValid, $3$, &_internal_metadata_);\n"
"ptr = ctx->ParseMessage(&object, ptr);\n",
FieldName(field), QualifiedClassName(val->enum_type()),
field->number());
} else {
format_("ptr = ctx->ParseMessage(&$1$_, ptr);\n",
FieldName(field));
}
} else if (!IsProto1(field->file(), options_) &&
IsLazy(field, options_)) {
if (field->containing_oneof() != nullptr) {
@ -1550,7 +1621,7 @@ class ParseLoopGenerator {
"CastToBase(&$1$_)->AddWeak(reinterpret_cast<const "
"::$proto_ns$::MessageLite*>(&$2$::_$3$_default_instance_)), "
"ptr);\n",
FieldName(field), Namespace(field->message_type()),
FieldName(field), Namespace(field->message_type(), options_),
ClassName(field->message_type()));
}
} else if (IsWeak(field, options_)) {
@ -1587,27 +1658,28 @@ class ParseLoopGenerator {
}
switch (wiretype) {
case WireFormatLite::WIRETYPE_VARINT: {
string type = PrimitiveTypeName(options_, field->cpp_type());
string prefix = field->is_repeated() ? "add" : "set";
std::string type = PrimitiveTypeName(options_, field->cpp_type());
std::string prefix = field->is_repeated() ? "add" : "set";
if (field->type() == FieldDescriptor::TYPE_ENUM &&
!IsProto1(field->file(), options_)) {
format_(
"$uint64$ val = $pi_ns$::ReadVarint(&ptr);\n"
"$GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr);\n");
if (!HasPreservingUnknownEnumSemantics(field->file())) {
if (!HasPreservingUnknownEnumSemantics(field)) {
format_(
"if (!$1$_IsValid(val)) {\n"
" $pi_ns$::WriteVarint($2$, val, "
"mutable_unknown_fields());\n"
" break;\n"
"}\n",
QualifiedClassName(field->enum_type()), field->number());
QualifiedClassName(field->enum_type(), options_),
field->number());
}
format_("$1$_$2$(static_cast<$3$>(val));\n", prefix, FieldName(field),
QualifiedClassName(field->enum_type()));
QualifiedClassName(field->enum_type(), options_));
} else {
int size = field->type() == FieldDescriptor::TYPE_SINT32 ? 32 : 64;
string zigzag;
std::string zigzag;
if ((field->type() == FieldDescriptor::TYPE_SINT32 ||
field->type() == FieldDescriptor::TYPE_SINT64) &&
!IsProto1(field->file(), options_)) {
@ -1622,8 +1694,8 @@ class ParseLoopGenerator {
}
case WireFormatLite::WIRETYPE_FIXED32:
case WireFormatLite::WIRETYPE_FIXED64: {
string prefix = field->is_repeated() ? "add" : "set";
string type = PrimitiveTypeName(options_, field->cpp_type());
std::string prefix = field->is_repeated() ? "add" : "set";
std::string type = PrimitiveTypeName(options_, field->cpp_type());
format_(
"$1$_$2$($pi_ns$::UnalignedLoad<$3$>(ptr));\n"
"ptr += sizeof($3$);\n",

@ -49,8 +49,8 @@
#include <google/protobuf/port.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/port_def.inc>
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
@ -58,14 +58,15 @@ namespace compiler {
namespace cpp {
inline std::string ProtobufNamespace(const Options& options) {
return options.opensource_runtime ? "google::protobuf" : "proto2";
return "PROTOBUF_NAMESPACE_ID";
}
inline std::string MacroPrefix(const Options& options) {
return options.opensource_runtime ? "GOOGLE_PROTOBUF" : "GOOGLE_PROTOBUF";
}
inline std::string DeprecatedAttribute(const Options& options, bool deprecated) {
inline std::string DeprecatedAttribute(const Options& options,
bool deprecated) {
return deprecated ? "PROTOBUF_DEPRECATED " : "";
}
@ -78,7 +79,8 @@ inline bool IsProto1(const FileDescriptor* file, const Options& options) {
return false;
}
void SetCommonVars(const Options& options, std::map<std::string, std::string>* variables);
void SetCommonVars(const Options& options,
std::map<std::string, std::string>* variables);
bool GetBootstrapBasename(const Options& options, const std::string& basename,
std::string* bootstrap_basename);
@ -90,14 +92,10 @@ bool IsBootstrapProto(const Options& options, const FileDescriptor* file);
// "<namespace>::some_name" is the correct fully qualified namespace.
// This means if the package is empty the namespace is "", and otherwise
// the namespace is "::foo::bar::...::baz" without trailing semi-colons.
std::string Namespace(const std::string& package);
inline std::string Namespace(const FileDescriptor* d) {
return Namespace(d->package());
}
std::string Namespace(const Descriptor* d);
std::string Namespace(const FieldDescriptor* d);
std::string Namespace(const EnumDescriptor* d);
std::string Namespace(const FileDescriptor* d, const Options& options);
std::string Namespace(const Descriptor* d, const Options& options);
std::string Namespace(const FieldDescriptor* d, const Options& options);
std::string Namespace(const EnumDescriptor* d, const Options& options);
// Returns true if it's safe to reset "field" to zero.
bool CanInitializeByZeroing(const FieldDescriptor* field);
@ -105,6 +103,9 @@ bool CanInitializeByZeroing(const FieldDescriptor* field);
std::string ClassName(const Descriptor* descriptor);
std::string ClassName(const EnumDescriptor* enum_descriptor);
std::string QualifiedClassName(const Descriptor* d, const Options& options);
std::string QualifiedClassName(const EnumDescriptor* d, const Options& options);
std::string QualifiedClassName(const Descriptor* d);
std::string QualifiedClassName(const EnumDescriptor* d);
@ -119,23 +120,28 @@ std::string QualifiedClassName(const EnumDescriptor* d);
// While the non-qualified version would be:
// Baz_Qux
inline std::string ClassName(const Descriptor* descriptor, bool qualified) {
return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor);
return qualified ? QualifiedClassName(descriptor, Options())
: ClassName(descriptor);
}
inline std::string ClassName(const EnumDescriptor* descriptor, bool qualified) {
return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor);
return qualified ? QualifiedClassName(descriptor, Options())
: ClassName(descriptor);
}
// Fully qualified name of the default_instance of this message.
std::string DefaultInstanceName(const Descriptor* descriptor);
std::string DefaultInstanceName(const Descriptor* descriptor,
const Options& options);
// Returns the name of a no-op function that we can call to introduce a linker
// dependency on the given message type. This is used to implement implicit weak
// fields.
std::string ReferenceFunctionName(const Descriptor* descriptor);
std::string ReferenceFunctionName(const Descriptor* descriptor,
const Options& options);
// Name of the base class: google::protobuf::Message or google::protobuf::MessageLite.
std::string SuperClassName(const Descriptor* descriptor, const Options& options);
std::string SuperClassName(const Descriptor* descriptor,
const Options& options);
// Get the (unqualified) name that should be used for this field in C++ code.
// The name is coerced to lower-case to emulate proto1 behavior. People
@ -154,7 +160,7 @@ int EstimateAlignmentSize(const FieldDescriptor* field);
// Get the unqualified name that should be used for a field's field
// number constant.
std::string FieldConstantName(const FieldDescriptor *field);
std::string FieldConstantName(const FieldDescriptor* field);
// Returns the scope where the field was defined (for extensions, this is
// different from the message type to which the field applies).
@ -165,14 +171,16 @@ inline const Descriptor* FieldScope(const FieldDescriptor* field) {
// Returns the fully-qualified type name field->message_type(). Usually this
// is just ClassName(field->message_type(), true);
std::string FieldMessageTypeName(const FieldDescriptor* field);
std::string FieldMessageTypeName(const FieldDescriptor* field,
const Options& options);
// Strips ".proto" or ".protodevel" from the end of a filename.
PROTOC_EXPORT std::string StripProto(const std::string& filename);
// Get the C++ type name for a primitive type (e.g. "double", "::google::protobuf::int32", etc.).
const char* PrimitiveTypeName(FieldDescriptor::CppType type);
std::string PrimitiveTypeName(const Options& options, FieldDescriptor::CppType type);
std::string PrimitiveTypeName(const Options& options,
FieldDescriptor::CppType type);
// Get the declared type name in CamelCase format, as is used e.g. for the
// methods of WireFormat. For example, TYPE_INT32 becomes "Int32".
@ -196,21 +204,22 @@ std::string FilenameIdentifier(const std::string& filename);
// For each .proto file generates a unique name. To prevent collisions of
// symbols in the global namespace
std::string UniqueName(const std::string& name, const std::string& filename,
const Options& options);
const Options& options);
inline std::string UniqueName(const std::string& name, const FileDescriptor* d,
const Options& options) {
const Options& options) {
return UniqueName(name, d->name(), options);
}
inline std::string UniqueName(const std::string& name, const Descriptor* d,
const Options& options) {
const Options& options) {
return UniqueName(name, d->file(), options);
}
inline std::string UniqueName(const std::string& name, const EnumDescriptor* d,
const Options& options) {
const Options& options) {
return UniqueName(name, d->file(), options);
}
inline std::string UniqueName(const std::string& name, const ServiceDescriptor* d,
const Options& options) {
inline std::string UniqueName(const std::string& name,
const ServiceDescriptor* d,
const Options& options) {
return UniqueName(name, d->file(), options);
}
@ -221,32 +230,38 @@ inline Options InternalRuntimeOptions() {
options.opensource_runtime = false;
return options;
}
inline std::string UniqueName(const std::string& name, const std::string& filename) {
inline std::string UniqueName(const std::string& name,
const std::string& filename) {
return UniqueName(name, filename, InternalRuntimeOptions());
}
inline std::string UniqueName(const std::string& name, const FileDescriptor* d) {
inline std::string UniqueName(const std::string& name,
const FileDescriptor* d) {
return UniqueName(name, d->name(), InternalRuntimeOptions());
}
inline std::string UniqueName(const std::string& name, const Descriptor* d) {
return UniqueName(name, d->file(), InternalRuntimeOptions());
}
inline std::string UniqueName(const std::string& name, const EnumDescriptor* d) {
inline std::string UniqueName(const std::string& name,
const EnumDescriptor* d) {
return UniqueName(name, d->file(), InternalRuntimeOptions());
}
inline std::string UniqueName(const std::string& name, const ServiceDescriptor* d) {
inline std::string UniqueName(const std::string& name,
const ServiceDescriptor* d) {
return UniqueName(name, d->file(), InternalRuntimeOptions());
}
// Return the qualified C++ name for a file level symbol.
std::string QualifiedFileLevelSymbol(const std::string& package, const std::string& name);
std::string QualifiedFileLevelSymbol(const FileDescriptor* file,
const std::string& name,
const Options& options);
// Escape C++ trigraphs by escaping question marks to \?
std::string EscapeTrigraphs(const std::string& to_escape);
// Escaped function name to eliminate naming conflict.
std::string SafeFunctionName(const Descriptor* descriptor,
const FieldDescriptor* field,
const std::string& prefix);
const FieldDescriptor* field,
const std::string& prefix);
// Returns true if generated messages have public unknown fields accessors
inline bool PublicUnknownFieldsAccessors(const Descriptor* message) {
@ -377,7 +392,8 @@ inline bool IsMapEntryMessage(const Descriptor* descriptor) {
// Returns true if the field's CPPTYPE is string or message.
bool IsStringOrMessage(const FieldDescriptor* field);
std::string UnderscoresToCamelCase(const std::string& input, bool cap_next_letter);
std::string UnderscoresToCamelCase(const std::string& input,
bool cap_next_letter);
inline bool HasFieldPresence(const FileDescriptor* file) {
return file->syntax() != FileDescriptor::SYNTAX_PROTO3;
@ -385,8 +401,8 @@ inline bool HasFieldPresence(const FileDescriptor* file) {
// Returns true if 'enum' semantics are such that unknown values are preserved
// in the enum field itself, rather than going to the UnknownFieldSet.
inline bool HasPreservingUnknownEnumSemantics(const FileDescriptor* file) {
return file->syntax() == FileDescriptor::SYNTAX_PROTO3;
inline bool HasPreservingUnknownEnumSemantics(const FieldDescriptor* field) {
return field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3;
}
inline bool SupportsArenas(const FileDescriptor* file) {
@ -420,6 +436,30 @@ bool IsAnyMessage(const Descriptor* descriptor, const Options& options);
bool IsWellKnownMessage(const FileDescriptor* descriptor);
inline std::string IncludeGuard(const FileDescriptor* file, bool pb_h,
const Options& options) {
// If we are generating a .pb.h file and the proto_h option is enabled, then
// the .pb.h gets an extra suffix.
std::string filename_identifier = FilenameIdentifier(
file->name() + (pb_h && options.proto_h ? ".pb.h" : ""));
if (IsWellKnownMessage(file)) {
// For well-known messages we need third_party/protobuf and net/proto2 to
// have distinct include guards, because some source files include both and
// both need to be defined (the third_party copies will be in the
// google::protobuf_opensource namespace).
return MacroPrefix(options) + "_INCLUDED_" + filename_identifier;
} else {
// Ideally this case would use distinct include guards for opensource and
// google3 protos also. (The behavior of "first #included wins" is not
// ideal). But unfortunately some legacy code includes both and depends on
// the identical include guards to avoid compile errors.
//
// We should clean this up so that this case can be removed.
return "GOOGLE_PROTOBUF_INCLUDED_" + filename_identifier;
}
}
inline FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file,
const Options& options) {
switch (options.enforce_mode) {
@ -553,7 +593,8 @@ bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options,
class PROTOC_EXPORT Formatter {
public:
explicit Formatter(io::Printer* printer) : printer_(printer) {}
Formatter(io::Printer* printer, const std::map<std::string, std::string>& vars)
Formatter(io::Printer* printer,
const std::map<std::string, std::string>& vars)
: printer_(printer), vars_(vars) {}
template <typename T>
@ -600,7 +641,9 @@ class PROTOC_EXPORT Formatter {
static std::string ToString(const FieldDescriptor* d) { return Payload(d); }
static std::string ToString(const Descriptor* d) { return Payload(d); }
static std::string ToString(const EnumDescriptor* d) { return Payload(d); }
static std::string ToString(const EnumValueDescriptor* d) { return Payload(d); }
static std::string ToString(const EnumValueDescriptor* d) {
return Payload(d);
}
template <typename Descriptor>
static std::string Payload(const Descriptor* descriptor) {
@ -635,11 +678,19 @@ class PROTOC_EXPORT NamespaceOpener {
common_idx++;
}
for (int i = name_stack_.size() - 1; i >= common_idx; i--) {
printer_->Print("} // namespace $ns$\n", "ns", name_stack_[i]);
if (name_stack_[i] == "PROTOBUF_NAMESPACE_ID") {
printer_->Print("PROTOBUF_NAMESPACE_CLOSE\n");
} else {
printer_->Print("} // namespace $ns$\n", "ns", name_stack_[i]);
}
}
name_stack_.swap(new_stack_);
for (int i = common_idx; i < name_stack_.size(); i++) {
printer_->Print("namespace $ns$ {\n", "ns", name_stack_[i]);
if (name_stack_[i] == "PROTOBUF_NAMESPACE_ID") {
printer_->Print("PROTOBUF_NAMESPACE_OPEN\n");
} else {
printer_->Print("namespace $ns$ {\n", "ns", name_stack_[i]);
}
}
}

@ -46,7 +46,7 @@ bool IsProto3Field(const FieldDescriptor* field_descriptor) {
}
void SetMessageVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables,
std::map<std::string, std::string>* variables,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
(*variables)["type"] = ClassName(descriptor->message_type(), false);
@ -64,7 +64,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
(*variables)["key_cpp"] = PrimitiveTypeName(options, key->cpp_type());
switch (val->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
(*variables)["val_cpp"] = FieldMessageTypeName(val);
(*variables)["val_cpp"] = FieldMessageTypeName(val, options);
(*variables)["wrapper"] = "MapEntryWrapper";
break;
case FieldDescriptor::CPPTYPE_ENUM:
@ -176,8 +176,8 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
descriptor_->message_type()->FindFieldByName("key");
const FieldDescriptor* value_field =
descriptor_->message_type()->FindFieldByName("value");
string key;
string value;
std::string key;
std::string value;
format(
"$map_classname$::Parser< ::$proto_ns$::internal::MapField$lite$<\n"
" $map_classname$,\n"
@ -199,7 +199,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
value = "entry->value()";
format("auto entry = parser.NewEntry();\n");
format(
"::std::string data;\n"
"std::string data;\n"
"DO_(::$proto_ns$::internal::WireFormatLite::ReadString(input, "
"&data));\n"
"DO_(entry->ParseFromString(data));\n"
@ -241,7 +241,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
static void GenerateSerializationLoop(const Formatter& format, bool string_key,
bool string_value, bool to_array,
bool is_deterministic) {
string ptr;
std::string ptr;
if (is_deterministic) {
format("for (size_type i = 0; i < n; i++) {\n");
ptr = string_key ? "items[static_cast<ptrdiff_t>(i)]"

@ -78,7 +78,7 @@ void PrintFieldComment(const Formatter& format, const T* field) {
DebugStringOptions options;
options.elide_group_body = true;
options.elide_oneof_body = true;
string def = field->DebugStringWithOptions(options);
std::string def = field->DebugStringWithOptions(options);
format("// $1$\n", def.substr(0, def.find_first_of('\n')));
}
@ -91,7 +91,7 @@ void PrintPresenceCheck(const Formatter& format, const FieldDescriptor* field,
*cached_has_bit_index = (has_bit_index / 32);
format("cached_has_bits = _has_bits_[$1$];\n", *cached_has_bit_index);
}
const string mask =
const std::string mask =
StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
format("if (cached_has_bits & 0x$1$u) {\n", mask);
} else {
@ -164,7 +164,8 @@ bool CanConstructByZeroing(const FieldDescriptor* field,
// considered non-default (will be sent over the wire), for message types
// without true field presence. Should only be called if
// !HasFieldPresence(message_descriptor).
bool EmitFieldNonDefaultCondition(io::Printer* printer, const string& prefix,
bool EmitFieldNonDefaultCondition(io::Printer* printer,
const std::string& prefix,
const FieldDescriptor* field) {
Formatter format(printer);
format.Set("prefix", prefix);
@ -203,15 +204,15 @@ bool HasHasMethod(const FieldDescriptor* field) {
// Collects map entry message type information.
void CollectMapInfo(const Options& options, const Descriptor* descriptor,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
GOOGLE_CHECK(IsMapEntryMessage(descriptor));
std::map<string, string>& vars = *variables;
std::map<std::string, std::string>& vars = *variables;
const FieldDescriptor* key = descriptor->FindFieldByName("key");
const FieldDescriptor* val = descriptor->FindFieldByName("value");
vars["key_cpp"] = PrimitiveTypeName(options, key->cpp_type());
switch (val->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
vars["val_cpp"] = FieldMessageTypeName(val);
vars["val_cpp"] = FieldMessageTypeName(val, options);
break;
case FieldDescriptor::CPPTYPE_ENUM:
vars["val_cpp"] = ClassName(val->enum_type(), true);
@ -251,40 +252,40 @@ bool ShouldMarkClassAsFinal(const Descriptor* descriptor,
bool ShouldMarkClearAsFinal(const Descriptor* descriptor,
const Options& options) {
static std::set<string> exclusions{
static std::set<std::string> exclusions{
};
const string name = ClassName(descriptor, true);
const std::string name = ClassName(descriptor, true);
return exclusions.find(name) == exclusions.end() ||
options.opensource_runtime;
}
bool ShouldMarkIsInitializedAsFinal(const Descriptor* descriptor,
const Options& options) {
static std::set<string> exclusions{
static std::set<std::string> exclusions{
};
const string name = ClassName(descriptor, true);
const std::string name = ClassName(descriptor, true);
return exclusions.find(name) == exclusions.end() ||
options.opensource_runtime;
}
bool ShouldMarkMergePartialAsFinal(const Descriptor* descriptor,
const Options& options) {
static std::set<string> exclusions{
static std::set<std::string> exclusions{
};
const string name = ClassName(descriptor, true);
const std::string name = ClassName(descriptor, true);
return exclusions.find(name) == exclusions.end() ||
options.opensource_runtime;
}
bool ShouldMarkNewAsFinal(const Descriptor* descriptor,
const Options& options) {
static std::set<string> exclusions{
static std::set<std::string> exclusions{
};
const string name = ClassName(descriptor, true);
const std::string name = ClassName(descriptor, true);
return exclusions.find(name) == exclusions.end() ||
options.opensource_runtime;
}
@ -342,8 +343,8 @@ bool TableDrivenParsingEnabled(const Descriptor* descriptor,
void SetUnknkownFieldsVariable(const Descriptor* descriptor,
const Options& options,
std::map<string, string>* variables) {
string proto_ns = ProtobufNamespace(options);
std::map<std::string, std::string>* variables) {
std::string proto_ns = ProtobufNamespace(options);
if (UseUnknownFieldSet(descriptor->file(), options)) {
(*variables)["unknown_fields_type"] = "::" + proto_ns + "::UnknownFieldSet";
} else {
@ -508,8 +509,8 @@ class ColdChunkSkipper {
// May open an external if check for a batch of cold fields. "from" is the
// prefix to _has_bits_ to allow MergeFrom to use "from._has_bits_".
// Otherwise, it should be "".
void OnStartChunk(int chunk, int cached_has_bit_index, const string& from,
io::Printer* printer);
void OnStartChunk(int chunk, int cached_has_bit_index,
const std::string& from, io::Printer* printer);
bool OnEndChunk(int chunk, io::Printer* printer);
private:
@ -523,7 +524,7 @@ class ColdChunkSkipper {
const std::vector<int>& has_bit_indices_;
const AccessInfoMap* access_info_map_;
const double cold_threshold_;
std::map<string, string> variables_;
std::map<std::string, std::string> variables_;
int limit_chunk_ = -1;
bool has_field_presence_;
};
@ -534,7 +535,8 @@ const double kColdRatio = 0.005;
bool ColdChunkSkipper::IsColdChunk(int chunk) { return false; }
void ColdChunkSkipper::OnStartChunk(int chunk, int cached_has_bit_index,
const string& from, io::Printer* printer) {
const std::string& from,
io::Printer* printer) {
Formatter format(printer, variables_);
if (!access_info_map_ || !has_field_presence_) {
return;
@ -602,11 +604,10 @@ bool ColdChunkSkipper::OnEndChunk(int chunk, io::Printer* printer) {
// ===================================================================
MessageGenerator::MessageGenerator(const Descriptor* descriptor,
const std::map<string, string>& vars,
int index_in_file_messages,
const Options& options,
MessageSCCAnalyzer* scc_analyzer)
MessageGenerator::MessageGenerator(
const Descriptor* descriptor,
const std::map<std::string, std::string>& vars, int index_in_file_messages,
const Options& options, MessageSCCAnalyzer* scc_analyzer)
: descriptor_(descriptor),
index_in_file_messages_(index_in_file_messages),
classname_(ClassName(descriptor, false)),
@ -622,8 +623,8 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor,
// Variables that apply to this class
variables_["classname"] = classname_;
variables_["classtype"] = QualifiedClassName(descriptor_);
string scc_name =
variables_["classtype"] = QualifiedClassName(descriptor_, options);
std::string scc_name =
ClassName(scc_analyzer_->GetSCC(descriptor_)->GetRepresentative());
variables_["scc_name"] = UniqueName(scc_name, descriptor_, options_);
variables_["full_name"] = descriptor_->full_name();
@ -721,7 +722,7 @@ void MessageGenerator::GenerateFieldAccessorDeclarations(io::Printer* printer) {
Formatter::SaveState save(&format);
std::map<string, string> vars;
std::map<std::string, std::string> vars;
SetCommonFieldVariables(field, &vars, options_);
format.AddMap(vars);
@ -892,7 +893,7 @@ void MessageGenerator::GenerateFieldAccessorDefinitions(io::Printer* printer) {
for (auto field : FieldRange(descriptor_)) {
PrintFieldComment(format, field);
std::map<string, string> vars;
std::map<std::string, std::string> vars;
SetCommonFieldVariables(field, &vars, options_);
Formatter::SaveState saver(&format);
@ -935,7 +936,7 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
ShouldMarkClassAsFinal(descriptor_, options_) ? "final": "");
if (IsMapEntryMessage(descriptor_)) {
std::map<string, string> vars;
std::map<std::string, std::string> vars;
CollectMapInfo(options_, descriptor_, &vars);
vars["lite"] =
HasDescriptorMethods(descriptor_->file(), options_) ? "" : "Lite";
@ -959,6 +960,55 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
" static const $classname$* internal_default_instance() { return "
"reinterpret_cast<const "
"$classname$*>(&_$classname$_default_instance_); }\n");
std::string suffix = GetUtf8Suffix(descriptor_->field(0), options_);
if (descriptor_->field(0)->type() == FieldDescriptor::TYPE_STRING &&
!suffix.empty()) {
if (suffix == "UTF8") {
format(
" bool ValidateKey() const {\n"
" return ::$proto_ns$::internal::WireFormatLite::"
"VerifyUtf8String(key().data(), key().size(), "
"::$proto_ns$::internal::WireFormatLite::PARSE, \"$1$\");\n"
" }\n",
descriptor_->field(0)->full_name());
} else {
GOOGLE_CHECK(suffix == "UTF8Verify");
format(
" bool ValidateKey() const {\n"
" ::$proto_ns$::internal::WireFormatLite::VerifyUtf8String(\n"
" key().data(), key().size(), ::$proto_ns$::internal::"
"WireFormatLite::PARSE, \"$1$\");\n"
" return true;\n"
" }\n",
descriptor_->field(0)->full_name());
}
} else {
format(" bool ValidateKey() const { return true; }\n");
}
if (descriptor_->field(1)->type() == FieldDescriptor::TYPE_STRING &&
!suffix.empty()) {
if (suffix == "UTF8") {
format(
" bool ValidateValue() const {\n"
" return ::$proto_ns$::internal::WireFormatLite::"
"VerifyUtf8String(value().data(), value().size(), "
"::$proto_ns$::internal::WireFormatLite::PARSE, \"$1$\");\n"
" }\n",
descriptor_->field(1)->full_name());
} else {
GOOGLE_CHECK(suffix == "UTF8Verify");
format(
" bool ValidateValue() const {\n"
" ::$proto_ns$::internal::WireFormatLite::VerifyUtf8String(\n"
" value().data(), value().size(), ::$proto_ns$::internal::"
"WireFormatLite::PARSE, \"$1$\");\n"
" return true;\n"
" }\n",
descriptor_->field(1)->full_name());
}
} else {
format(" bool ValidateValue() const { return true; }\n");
}
if (HasDescriptorMethods(descriptor_->file(), options_)) {
format(
" void MergeFrom(const ::$proto_ns$::Message& other) final;\n"
@ -983,28 +1033,15 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
"virtual ~$classname$();\n"
"\n"
"$classname$(const $classname$& from);\n"
"\n"
"inline $classname$& operator=(const $classname$& from) {\n"
" CopyFrom(from);\n"
" return *this;\n"
"}\n");
if (options_.table_driven_serialization) {
format(
"private:\n"
"const void* InternalGetTable() const;\n"
"public:\n"
"\n");
}
// Generate move constructor and move assignment operator.
format(
"#if LANG_CXX11\n"
"$classname$($classname$&& from) noexcept\n"
" : $classname$() {\n"
" *this = ::std::move(from);\n"
"}\n"
"\n"
"inline $classname$& operator=(const $classname$& from) {\n"
" CopyFrom(from);\n"
" return *this;\n"
"}\n"
"inline $classname$& operator=($classname$&& from) noexcept {\n"
" if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {\n"
" if (this != &from) InternalSwap(&from);\n"
@ -1013,9 +1050,17 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
" }\n"
" return *this;\n"
"}\n"
"#endif\n");
"\n");
if (options_.table_driven_serialization) {
format(
"private:\n"
"const void* InternalGetTable() const;\n"
"public:\n"
"\n");
}
std::map<string, string> vars;
std::map<std::string, std::string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
format.AddMap(vars);
if (PublicUnknownFieldsAccessors(descriptor_)) {
@ -1063,7 +1108,7 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
format("enum $1$Case {\n", UnderscoresToCamelCase(oneof->name(), true));
format.Indent();
for (auto field : FieldRange(oneof)) {
string oneof_enum_case_field_name =
std::string oneof_enum_case_field_name =
UnderscoresToCamelCase(field->name(), true);
format("k$1$ = $2$,\n", oneof_enum_case_field_name, // 1
field->number()); // 2
@ -1098,7 +1143,7 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
format(
"void PackFrom(const ::$proto_ns$::Message& message);\n"
"void PackFrom(const ::$proto_ns$::Message& message,\n"
" const $string$& type_url_prefix);\n"
" const std::string& type_url_prefix);\n"
"bool UnpackTo(::$proto_ns$::Message* message) const;\n"
"static bool GetAnyFieldDescriptors(\n"
" const ::$proto_ns$::Message& message,\n"
@ -1112,7 +1157,7 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
"}\n"
"template <typename T>\n"
"void PackFrom(const T& message,\n"
" const $string$& type_url_prefix) {\n"
" const std::string& type_url_prefix) {\n"
" _any_metadata_.PackFrom(message, type_url_prefix);"
"}\n"
"template <typename T>\n"
@ -1125,7 +1170,7 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
" return _any_metadata_.Is<T>();\n"
"}\n"
"static bool ParseAnyTypeUrl(const string& type_url,\n"
" string* full_type_name);\n");
" std::string* full_type_name);\n");
}
format.Set("new_final",
@ -1221,7 +1266,7 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
"static $1$ FullMessageName() {\n"
" return \"$full_name$\";\n"
"}\n",
options_.opensource_runtime ? "::google::protobuf::StringPiece"
options_.opensource_runtime ? "::PROTOBUF_NAMESPACE_ID::StringPiece"
: "::StringPiece");
if (SupportsArenas(descriptor_)) {
@ -1266,7 +1311,7 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
"\n");
} else {
format(
"$string$ GetTypeName() const final;\n"
"std::string GetTypeName() const final;\n"
"\n");
}
@ -1348,11 +1393,11 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
// output will be determined later.
bool need_to_emit_cached_size = true;
const string cached_size_decl =
const std::string cached_size_decl =
"mutable ::$proto_ns$::internal::CachedSize _cached_size_;\n";
const size_t sizeof_has_bits = HasBitsSize();
const string has_bits_decl =
const std::string has_bits_decl =
sizeof_has_bits == 0
? ""
: StrCat("::$proto_ns$::internal::HasBits<",
@ -1416,7 +1461,7 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
// For each oneof generate a union
for (auto oneof : OneOfRange(descriptor_)) {
string camel_oneof_name = UnderscoresToCamelCase(oneof->name(), true);
std::string camel_oneof_name = UnderscoresToCamelCase(oneof->name(), true);
format(
"union $1$Union {\n"
// explicit empty constructor is needed when union contains
@ -1644,8 +1689,8 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
uint32 tag = internal::WireFormatLite::MakeTag(
field->number(), WireFormat::WireTypeForFieldType(field->type()));
std::map<string, string> vars;
vars["classtype"] = QualifiedClassName(descriptor_);
std::map<std::string, std::string> vars;
vars["classtype"] = QualifiedClassName(descriptor_, options_);
vars["field_name"] = FieldName(field);
vars["tag"] = StrCat(tag);
vars["hasbit"] = StrCat(i);
@ -1708,12 +1753,12 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
}
string classfieldname = FieldName(field);
std::string classfieldname = FieldName(field);
if (field->containing_oneof()) {
classfieldname = field->containing_oneof()->name();
}
format.Set("field_name", classfieldname);
string ptr = "nullptr";
std::string ptr = "nullptr";
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
if (IsMapEntryMessage(field->message_type())) {
format(
@ -1726,7 +1771,7 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
"$3$>::MapFieldType, "
"$tablename$::serialization_table>))},\n",
tag, FindMessageIndexInFile(field->message_type()),
QualifiedClassName(field->message_type()));
QualifiedClassName(field->message_type(), options_));
continue;
} else if (!IsProto1(field->message_type()->file(), options_) &&
!field->message_type()->options().message_set_wire_format()) {
@ -1789,9 +1834,9 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
}
int num_field_metadata = 1 + sorted.size() + sorted_extensions.size();
num_field_metadata++;
string serializer = UseUnknownFieldSet(descriptor_->file(), options_)
? "UnknownFieldSetSerializer"
: "UnknownFieldSerializerLite";
std::string serializer = UseUnknownFieldSet(descriptor_->file(), options_)
? "UnknownFieldSetSerializer"
: "UnknownFieldSerializerLite";
format(
"{PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_), 0, ~0u, "
"::$proto_ns$::internal::FieldMetadata::kSpecial, reinterpret_cast<const "
@ -1825,7 +1870,7 @@ void MessageGenerator::GenerateDefaultInstanceInitializer(
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
(field->containing_oneof() == NULL ||
HasDescriptorMethods(descriptor_->file(), options_))) {
string name;
std::string name;
if (field->containing_oneof() || field->options().weak()) {
name = "_" + classname_ + "_default_instance_.";
} else {
@ -1835,10 +1880,6 @@ void MessageGenerator::GenerateDefaultInstanceInitializer(
name += FieldName(field);
format.Set("name", name);
if (IsWeak(field, options_)) {
const FileDescriptor* dependency = field->message_type()->file();
string default_instance = QualifiedFileLevelSymbol(
dependency->package(),
"_" + ClassName(field->message_type()) + "_default_instance_");
format(
"$package_ns$::$name$_ = reinterpret_cast<const "
"::$proto_ns$::Message*>(&$1$);\n"
@ -1846,13 +1887,13 @@ void MessageGenerator::GenerateDefaultInstanceInitializer(
" $package_ns$::$name$_ = "
"::$proto_ns$::Empty::internal_default_instance();\n"
"}\n",
default_instance); // 1
DefaultInstanceName(field->message_type(), options_)); // 1
continue;
}
format(
"$package_ns$::$name$_ = const_cast< $1$*>(\n"
" $1$::internal_default_instance());\n",
FieldMessageTypeName(field));
FieldMessageTypeName(field, options_));
} else if (field->containing_oneof() &&
HasDescriptorMethods(descriptor_->file(), options_)) {
field_generators_.get(field).GenerateConstructorCode(printer);
@ -1904,7 +1945,7 @@ void MessageGenerator::GenerateClassMethods(io::Printer* printer) {
"}\n"
"\n"
"void $classname$::PackFrom(const ::$proto_ns$::Message& message,\n"
" const $string$& type_url_prefix) {\n"
" const std::string& type_url_prefix) {\n"
" _any_metadata_.PackFrom(message, type_url_prefix);\n"
"}\n"
"\n"
@ -1921,7 +1962,7 @@ void MessageGenerator::GenerateClassMethods(io::Printer* printer) {
}
format(
"bool $classname$::ParseAnyTypeUrl(const string& type_url,\n"
" string* full_type_name) {\n"
" std::string* full_type_name) {\n"
" return ::$proto_ns$::internal::ParseAnyTypeUrl(type_url,\n"
" full_type_name);\n"
"}\n"
@ -1960,7 +2001,7 @@ void MessageGenerator::GenerateClassMethods(io::Printer* printer) {
field_generators_.get(field).GenerateNonInlineAccessorDefinitions(printer);
if (IsCrossFileMaybeMap(field)) {
Formatter::SaveState saver(&format);
std::map<string, string> vars;
std::map<std::string, std::string> vars;
SetCommonFieldVariables(field, &vars, options_);
if (field->containing_oneof()) {
SetCommonOneofFieldVariables(field, &vars);
@ -2035,7 +2076,7 @@ void MessageGenerator::GenerateClassMethods(io::Printer* printer) {
"\n");
} else {
format(
"$string$ $classname$::GetTypeName() const {\n"
"std::string $classname$::GetTypeName() const {\n"
" return \"$full_name$\";\n"
"}\n"
"\n");
@ -2124,7 +2165,7 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) {
const unsigned char tag_size =
WireFormat::TagSize(field->number(), field->type());
std::map<string, string> vars;
std::map<std::string, std::string> vars;
if (field->containing_oneof() != NULL) {
vars["name"] = field->containing_oneof()->name();
vars["presence"] = StrCat(field->containing_oneof()->index());
@ -2170,16 +2211,22 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) {
format("::$proto_ns$::internal::AuxillaryParseTableField(),\n");
}
std::map<string, string> vars;
std::map<std::string, std::string> vars;
SetCommonFieldVariables(field, &vars, options_);
format.AddMap(vars);
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_ENUM:
format(
"{::$proto_ns$::internal::AuxillaryParseTableField::enum_aux{"
"$1$_IsValid}},\n",
ClassName(field->enum_type(), true));
if (HasPreservingUnknownEnumSemantics(field)) {
format(
"{::$proto_ns$::internal::AuxillaryParseTableField::enum_aux{"
"nullptr}},\n");
} else {
format(
"{::$proto_ns$::internal::AuxillaryParseTableField::enum_aux{"
"$1$_IsValid}},\n",
ClassName(field->enum_type(), true));
}
last_field_number++;
break;
case FieldDescriptor::CPPTYPE_MESSAGE: {
@ -2187,27 +2234,28 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) {
format(
"{::$proto_ns$::internal::AuxillaryParseTableField::map_"
"aux{&::$proto_ns$::internal::ParseMap<$1$>}},\n",
QualifiedClassName(field->message_type()));
QualifiedClassName(field->message_type(), options_));
last_field_number++;
break;
}
format.Set("field_classname", ClassName(field->message_type(), false));
format.Set("ns", Namespace(field->message_type()));
format.Set("default_instance",
DefaultInstanceName(field->message_type(), options_));
format(
"{::$proto_ns$::internal::AuxillaryParseTableField::message_aux{\n"
" &$ns$::_$field_classname$_default_instance_}},\n");
" &$default_instance$}},\n");
last_field_number++;
break;
}
case FieldDescriptor::CPPTYPE_STRING: {
string default_val;
std::string default_val;
switch (EffectiveStringCType(field, options_)) {
case FieldOptions::STRING:
default_val = field->default_value_string().empty()
? "&::" + variables_["proto_ns"] +
"::internal::fixed_address_empty_string"
: "&" + QualifiedClassName(descriptor_) +
: "&" + QualifiedClassName(descriptor_, options_) +
"::" + MakeDefaultName(field);
break;
case FieldOptions::CORD:
@ -2290,7 +2338,7 @@ std::pair<size_t, size_t> MessageGenerator::GenerateOffsets(
} else if (HasFieldPresence(descriptor_->file())) {
entries += has_bit_indices_.size();
for (int i = 0; i < has_bit_indices_.size(); i++) {
const string index =
const std::string index =
has_bit_indices_[i] >= 0 ? StrCat(has_bit_indices_[i]) : "~0u";
format("$1$,\n", index);
}
@ -2441,7 +2489,7 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer,
}
}
string pod_template;
std::string pod_template;
if (copy_constructor) {
pod_template =
"::memcpy(&$first$_, &from.$first$_,\n"
@ -2467,8 +2515,8 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer,
if (it != runs.end() && it->second > 1) {
// Use a memset, then skip run_length fields.
const size_t run_length = it->second;
const string first_field_name = FieldName(field);
const string last_field_name =
const std::string first_field_name = FieldName(field);
const std::string last_field_name =
FieldName(optimized_order_[i + run_length - 1]);
format.Set("first", first_field_name);
@ -2491,9 +2539,9 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer,
void MessageGenerator::GenerateStructors(io::Printer* printer) {
Formatter format(printer, variables_);
string superclass;
std::string superclass;
superclass = SuperClassName(descriptor_, options_);
string initializer_with_arena = superclass + "()";
std::string initializer_with_arena = superclass + "()";
if (descriptor_->extension_range_count() > 0) {
initializer_with_arena += ",\n _extensions_(arena)";
@ -2510,7 +2558,7 @@ void MessageGenerator::GenerateStructors(io::Printer* printer) {
}
if (has_arena_constructor) {
initializer_with_arena +=
string(",\n ") + FieldName(field) + string("_(arena)");
std::string(",\n ") + FieldName(field) + std::string("_(arena)");
}
}
@ -2521,7 +2569,8 @@ void MessageGenerator::GenerateStructors(io::Printer* printer) {
initializer_with_arena += ", _weak_field_map_(arena)";
}
string initializer_null = superclass + "(), _internal_metadata_(nullptr)";
std::string initializer_null =
superclass + "(), _internal_metadata_(nullptr)";
if (IsAnyMessage(descriptor_, options_)) {
initializer_null += ", _any_metadata_(&type_url_, &value_)";
}
@ -2688,7 +2737,7 @@ bool MessageGenerator::MaybeGenerateOptionalFieldCondition(
int has_bit_index = has_bit_indices_[field->index()];
if (!field->options().weak() &&
expected_has_bits_index == has_bit_index / 32) {
const string mask =
const std::string mask =
StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
format("if (cached_has_bits & 0x$1$u) {\n", mask);
return true;
@ -2832,8 +2881,8 @@ void MessageGenerator::GenerateClear(io::Printer* printer) {
field_generators_.get(chunk[memset_run_start]);
generator.GenerateMessageClearingCode(printer);
} else {
const string first_field_name = FieldName(chunk[memset_run_start]);
const string last_field_name = FieldName(chunk[memset_run_end]);
const std::string first_field_name = FieldName(chunk[memset_run_start]);
const std::string last_field_name = FieldName(chunk[memset_run_end]);
format(
"::memset(&$1$_, 0, static_cast<size_t>(\n"
@ -3067,7 +3116,8 @@ void MessageGenerator::GenerateMergeFrom(io::Printer* printer) {
format(
"void $classname$::CheckTypeAndMergeFrom(\n"
" const ::$proto_ns$::MessageLite& from) {\n"
" MergeFrom(*::google::protobuf::down_cast<const $classname$*>(&from));\n"
" MergeFrom(*::$proto_ns$::internal::DownCast<const $classname$*>(\n"
" &from));\n"
"}\n"
"\n");
}
@ -3154,7 +3204,7 @@ void MessageGenerator::GenerateMergeFrom(io::Printer* printer) {
int has_bit_index = has_bit_indices_[field->index()];
if (!field->options().weak() &&
cached_has_bit_index == has_bit_index / 32) {
const string mask = StrCat(
const std::string mask = StrCat(
strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
format("if (cached_has_bits & 0x$1$u) {\n", mask);
@ -3311,7 +3361,7 @@ void MessageGenerator::GenerateCopyFrom(io::Printer* printer) {
}
void MessageGenerator::GenerateMergeFromCodedStream(io::Printer* printer) {
std::map<string, string> vars = variables_;
std::map<std::string, std::string> vars = variables_;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
Formatter format(printer, vars);
if (descriptor_->options().message_set_wire_format()) {
@ -3345,7 +3395,7 @@ void MessageGenerator::GenerateMergeFromCodedStream(io::Printer* printer) {
if (table_driven_) {
format.Indent();
const string lite =
const std::string lite =
UseUnknownFieldSet(descriptor_->file(), options_) ? "" : "Lite";
format(
@ -3685,7 +3735,7 @@ void MessageGenerator::GenerateSerializeOneField(io::Printer* printer,
// Attempt to use the state of cached_has_bits, if possible.
int has_bit_index = has_bit_indices_[field->index()];
if (cached_has_bits_index == has_bit_index / 32) {
const string mask =
const std::string mask =
StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
format("if (cached_has_bits & 0x$1$u) {\n", mask);
@ -3716,7 +3766,7 @@ void MessageGenerator::GenerateSerializeOneField(io::Printer* printer,
void MessageGenerator::GenerateSerializeOneExtensionRange(
io::Printer* printer, const Descriptor::ExtensionRange* range,
bool to_array) {
std::map<string, string> vars;
std::map<std::string, std::string> vars;
vars["start"] = StrCat(range->start);
vars["end"] = StrCat(range->end);
Formatter format(printer, vars);
@ -3740,7 +3790,7 @@ void MessageGenerator::GenerateSerializeWithCachedSizes(io::Printer* printer) {
"void $classname$::SerializeWithCachedSizes(\n"
" ::$proto_ns$::io::CodedOutputStream* output) const {\n"
" _extensions_.SerializeMessageSetWithCachedSizes(output);\n");
std::map<string, string> vars;
std::map<std::string, std::string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
format.AddMap(vars);
format(
@ -3778,7 +3828,7 @@ void MessageGenerator::GenerateSerializeWithCachedSizesToArray(
" target = _extensions_."
"InternalSerializeMessageSetWithCachedSizesToArray(target);\n");
GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_));
std::map<string, string> vars;
std::map<std::string, std::string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
format.AddMap(vars);
format(
@ -3942,7 +3992,7 @@ void MessageGenerator::GenerateSerializeWithCachedSizesBody(
}
}
std::map<string, string> vars;
std::map<std::string, std::string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
format.AddMap(vars);
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
@ -3987,18 +4037,19 @@ std::vector<uint32> MessageGenerator::RequiredFieldsBitMask() const {
// "for all i, (_has_bits_[i] & masks[i]) == masks[i]"
// masks is allowed to be shorter than _has_bits_, but at least one element of
// masks must be non-zero.
static string ConditionalToCheckBitmasks(const std::vector<uint32>& masks) {
std::vector<string> parts;
static std::string ConditionalToCheckBitmasks(
const std::vector<uint32>& masks) {
std::vector<std::string> parts;
for (int i = 0; i < masks.size(); i++) {
if (masks[i] == 0) continue;
string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8));
std::string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8));
// Each xor evaluates to 0 if the expected bits are present.
parts.push_back(
StrCat("((_has_bits_[", i, "] & ", m, ") ^ ", m, ")"));
}
GOOGLE_CHECK(!parts.empty());
// If we have multiple parts, each expected to be 0, then bitwise-or them.
string result =
std::string result =
parts.size() == 1
? parts[0]
: StrCat("(", Join(parts, "\n | "), ")");
@ -4010,7 +4061,7 @@ void MessageGenerator::GenerateByteSize(io::Printer* printer) {
if (descriptor_->options().message_set_wire_format()) {
// Special-case MessageSet.
std::map<string, string> vars;
std::map<std::string, std::string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
format.AddMap(vars);
format(
@ -4072,7 +4123,7 @@ void MessageGenerator::GenerateByteSize(io::Printer* printer) {
"\n");
}
std::map<string, string> vars;
std::map<std::string, std::string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
format.AddMap(vars);
if (UseUnknownFieldSet(descriptor_->file(), options_)) {

@ -51,7 +51,7 @@ namespace {
// Ordinarily a static_cast is enough to cast google::protobuf::MessageLite* to a class
// deriving from it, but we need a reinterpret_cast in cases where the generated
// message is forward-declared but its full definition is not visible.
string StaticCast(const string& type, const string& expression,
string StaticCast(const std::string& type, const std::string& expression,
bool implicit_weak_field) {
if (implicit_weak_field) {
return "static_cast< " + type + " >(" + expression + ")";
@ -60,7 +60,7 @@ string StaticCast(const string& type, const string& expression,
}
}
string ReinterpretCast(const string& type, const string& expression,
string ReinterpretCast(const std::string& type, const std::string& expression,
bool implicit_weak_field) {
if (implicit_weak_field) {
return "reinterpret_cast< " + type + " >(" + expression + ")";
@ -71,16 +71,17 @@ string ReinterpretCast(const string& type, const string& expression,
void SetMessageVariables(const FieldDescriptor* descriptor,
const Options& options, bool implicit_weak,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
SetCommonFieldVariables(descriptor, variables, options);
(*variables)["type"] = FieldMessageTypeName(descriptor);
(*variables)["type"] = FieldMessageTypeName(descriptor, options);
(*variables)["casted_member"] = ReinterpretCast(
(*variables)["type"] + "*", (*variables)["name"] + "_", implicit_weak);
(*variables)["type_default_instance"] =
DefaultInstanceName(descriptor->message_type());
DefaultInstanceName(descriptor->message_type(), options);
(*variables)["type_reference_function"] =
implicit_weak
? (" " + ReferenceFunctionName(descriptor->message_type()) + "();\n")
? (" " + ReferenceFunctionName(descriptor->message_type(), options) +
"();\n")
: "";
(*variables)["stream_writer"] =
(*variables)["declared_type"] +

@ -58,9 +58,8 @@ class TestGenerator : public CodeGenerator {
~TestGenerator() {}
virtual bool Generate(const FileDescriptor* file,
const string& parameter,
GeneratorContext* context,
string* error) const {
const std::string& parameter, GeneratorContext* context,
std::string* error) const {
TryInsert("test.pb.h", "includes", context);
TryInsert("test.pb.h", "namespace_scope", context);
TryInsert("test.pb.h", "global_scope", context);
@ -167,7 +166,8 @@ class TestGenerator : public CodeGenerator {
return true;
}
void TryInsert(const string& filename, const string& insertion_point,
void TryInsert(const std::string& filename,
const std::string& insertion_point,
GeneratorContext* context) const {
std::unique_ptr<io::ZeroCopyOutputStream> output(
context->OpenForInsert(filename, insertion_point));
@ -227,9 +227,9 @@ TEST(CppPluginTest, PluginTest) {
cli.RegisterGenerator("--cpp_out", &cpp_generator, "");
cli.RegisterGenerator("--test_out", &test_generator, "");
string proto_path = "-I" + TestTempDir();
string cpp_out = "--cpp_out=" + TestTempDir();
string test_out = "--test_out=" + TestTempDir();
std::string proto_path = "-I" + TestTempDir();
std::string cpp_out = "--cpp_out=" + TestTempDir();
std::string test_out = "--test_out=" + TestTempDir();
const char* argv[] = {
"protoc",

@ -81,7 +81,7 @@ int FixedSize(FieldDescriptor::Type type) {
}
void SetPrimitiveVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables,
std::map<std::string, std::string>* variables,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
(*variables)["type"] = PrimitiveTypeName(options, descriptor->cpp_type());

@ -44,18 +44,20 @@ namespace cpp {
namespace {
void InitMethodVariables(const MethodDescriptor* method, Formatter* format) {
void InitMethodVariables(const MethodDescriptor* method, const Options& options,
Formatter* format) {
format->Set("name", method->name());
format->Set("input_type", QualifiedClassName(method->input_type()));
format->Set("output_type", QualifiedClassName(method->output_type()));
format->Set("input_type", QualifiedClassName(method->input_type(), options));
format->Set("output_type",
QualifiedClassName(method->output_type(), options));
}
} // namespace
ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor,
const std::map<string, string>& vars,
const Options& options)
: descriptor_(descriptor), vars_(vars) {
ServiceGenerator::ServiceGenerator(
const ServiceDescriptor* descriptor,
const std::map<std::string, std::string>& vars, const Options& options)
: descriptor_(descriptor), vars_(vars), options_(options) {
vars_["classname"] = descriptor_->name();
vars_["full_name"] = descriptor_->full_name();
}
@ -153,7 +155,7 @@ void ServiceGenerator::GenerateMethodSignatures(VirtualOrNon virtual_or_non,
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor* method = descriptor_->method(i);
Formatter format(printer, vars_);
InitMethodVariables(method, &format);
InitMethodVariables(method, options_, &format);
format.Set("virtual", virtual_or_non == VIRTUAL ? "virtual " : "");
format(
"$virtual$void $name$(::$proto_ns$::RpcController* controller,\n"
@ -219,7 +221,7 @@ void ServiceGenerator::GenerateNotImplementedMethods(io::Printer* printer) {
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor* method = descriptor_->method(i);
Formatter format(printer, vars_);
InitMethodVariables(method, &format);
InitMethodVariables(method, options_, &format);
format(
"void $classname$::$name$(::$proto_ns$::RpcController* controller,\n"
" const $input_type$*,\n"
@ -248,15 +250,17 @@ void ServiceGenerator::GenerateCallMethod(io::Printer* printer) {
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor* method = descriptor_->method(i);
Formatter format(printer, vars_);
InitMethodVariables(method, &format);
InitMethodVariables(method, options_, &format);
// Note: down_cast does not work here because it only works on pointers,
// not references.
format(
" case $1$:\n"
" $name$(controller,\n"
" ::google::protobuf::down_cast<const $input_type$*>(request),\n"
" ::google::protobuf::down_cast< $output_type$*>(response),\n"
" ::$proto_ns$::internal::DownCast<const $input_type$*>(\n"
" request),\n"
" ::$proto_ns$::internal::DownCast<$output_type$*>(\n"
" response),\n"
" done);\n"
" break;\n",
i);
@ -293,7 +297,7 @@ void ServiceGenerator::GenerateGetPrototype(RequestOrResponse which,
format(
" case $1$:\n"
" return $2$::default_instance();\n",
i, QualifiedClassName(type));
i, QualifiedClassName(type, options_));
}
format(
@ -311,7 +315,7 @@ void ServiceGenerator::GenerateStubMethods(io::Printer* printer) {
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor* method = descriptor_->method(i);
Formatter format(printer, vars_);
InitMethodVariables(method, &format);
InitMethodVariables(method, options_, &format);
format(
"void $classname$_Stub::$name$(::$proto_ns$::RpcController* "
"controller,\n"

@ -110,6 +110,7 @@ class ServiceGenerator {
const ServiceDescriptor* descriptor_;
std::map<std::string, std::string> vars_;
const Options& options_;
int index_in_metadata_;

@ -48,19 +48,19 @@ namespace cpp {
namespace {
void SetStringVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables,
std::map<std::string, std::string>* variables,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
(*variables)["default"] = DefaultValue(options, descriptor);
(*variables)["default_length"] =
StrCat(descriptor->default_value_string().length());
string default_variable_string = MakeDefaultName(descriptor);
std::string default_variable_string = MakeDefaultName(descriptor);
(*variables)["default_variable_name"] = default_variable_string;
(*variables)["default_variable"] =
descriptor->default_value_string().empty()
? "&::" + (*variables)["proto_ns"] +
"::internal::GetEmptyStringAlreadyInited()"
: "&" + QualifiedClassName(descriptor->containing_type()) +
: "&" + QualifiedClassName(descriptor->containing_type(), options) +
"::" + default_variable_string + ".get()";
(*variables)["pointer_type"] =
descriptor->type() == FieldDescriptor::TYPE_BYTES ? "void" : "char";
@ -126,7 +126,7 @@ GenerateStaticMembers(io::Printer* printer) const {
// non-friend code.
format(
"public:\n"
"static ::$proto_ns$::internal::ExplicitlyConstructed<$string$>"
"static ::$proto_ns$::internal::ExplicitlyConstructed<std::string>"
" $default_variable_name$;\n"
"private:\n");
}
@ -164,28 +164,24 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
}
format(
"$deprecated_attr$const $string$& ${1$$name$$}$() const;\n"
"$deprecated_attr$void ${1$set_$name$$}$(const $string$& value);\n"
"#if LANG_CXX11\n"
"$deprecated_attr$void ${1$set_$name$$}$($string$&& value);\n"
"#endif\n"
"$deprecated_attr$const std::string& ${1$$name$$}$() const;\n"
"$deprecated_attr$void ${1$set_$name$$}$(const std::string& value);\n"
"$deprecated_attr$void ${1$set_$name$$}$(std::string&& value);\n"
"$deprecated_attr$void ${1$set_$name$$}$(const char* value);\n",
descriptor_);
if (!options_.opensource_runtime) {
format(
"$deprecated_attr$void ${1$set_$name$$}$(::StringPiece value);\n"
"#ifdef HAS_GLOBAL_STRING\n"
"$deprecated_attr$void ${1$set_$name$$}$(const ::std::string& value);\n"
"#endif\n",
"$deprecated_attr$void ${1$set_$name$$}$(::StringPiece value);\n",
descriptor_);
}
format(
"$deprecated_attr$void ${1$set_$name$$}$(const $pointer_type$* "
"value, size_t size)"
";\n"
"$deprecated_attr$$string$* ${1$mutable_$name$$}$();\n"
"$deprecated_attr$$string$* ${1$$release_name$$}$();\n"
"$deprecated_attr$void ${1$set_allocated_$name$$}$($string$* $name$);\n",
"$deprecated_attr$std::string* ${1$mutable_$name$$}$();\n"
"$deprecated_attr$std::string* ${1$$release_name$$}$();\n"
"$deprecated_attr$void ${1$set_allocated_$name$$}$(std::string* "
"$name$);\n",
descriptor_);
if (options_.opensource_runtime) {
if (SupportsArenas(descriptor_)) {
@ -194,13 +190,13 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
"for\"\n"
"\" string fields are deprecated and will be removed in a\"\n"
"\" future release.\")\n"
"$string$* ${1$unsafe_arena_release_$name$$}$();\n"
"std::string* ${1$unsafe_arena_release_$name$$}$();\n"
"$GOOGLE_PROTOBUF$_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors "
"for\"\n"
"\" string fields are deprecated and will be removed in a\"\n"
"\" future release.\")\n"
"void ${1$unsafe_arena_set_allocated_$name$$}$(\n"
" $string$* $name$);\n",
" std::string* $name$);\n",
descriptor_);
}
}
@ -217,23 +213,21 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
Formatter format(printer, variables_);
if (SupportsArenas(descriptor_)) {
format(
"inline const $string$& $classname$::$name$() const {\n"
"inline const std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.Get();\n"
"}\n"
"inline void $classname$::set_$name$(const $string$& value) {\n"
"inline void $classname$::set_$name$(const std::string& value) {\n"
" $set_hasbit$\n"
" $name$_.Set$lite$($default_variable$, value, GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
"inline void $classname$::set_$name$($string$&& value) {\n"
"inline void $classname$::set_$name$(std::string&& value) {\n"
" $set_hasbit$\n"
" $name$_.Set$lite$(\n"
" $default_variable$, ::std::move(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"#endif\n"
"inline void $classname$::set_$name$(const char* value) {\n"
" $null_check$"
" $set_hasbit$\n"
@ -248,16 +242,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $name$_.Set$lite$($default_variable$, value, "
"GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
"}\n"
"#ifdef HAS_GLOBAL_STRING\n"
"inline void $classname$::set_$name$(const ::std::string& value) {\n"
" $set_hasbit$\n"
" $name$_.Set$lite$($default_variable$, "
"::StringPiece(value.data(),\n"
" value.size()), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_std_string:$full_name$)\n"
"}\n"
"#endif\n");
"}\n");
}
format(
"inline "
@ -269,12 +254,12 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"inline $string$* $classname$::mutable_$name$() {\n"
"inline std::string* $classname$::mutable_$name$() {\n"
" $set_hasbit$\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable($default_variable$, GetArenaNoVirtual());\n"
"}\n"
"inline $string$* $classname$::$release_name$() {\n"
"inline std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n");
if (HasFieldPresence(descriptor_->file())) {
@ -294,7 +279,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
format(
"}\n"
"inline void $classname$::set_allocated_$name$($string$* $name$) {\n"
"inline void $classname$::set_allocated_$name$(std::string* $name$) {\n"
" if ($name$ != nullptr) {\n"
" $set_hasbit$\n"
" } else {\n"
@ -306,7 +291,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"}\n");
if (options_.opensource_runtime) {
format(
"inline $string$* $classname$::unsafe_arena_release_$name$() {\n"
"inline std::string* $classname$::unsafe_arena_release_$name$() {\n"
" // "
"@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
" $DCHK$(GetArenaNoVirtual() != nullptr);\n"
@ -315,7 +300,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" GetArenaNoVirtual());\n"
"}\n"
"inline void $classname$::unsafe_arena_set_allocated_$name$(\n"
" $string$* $name$) {\n"
" std::string* $name$) {\n"
" $DCHK$(GetArenaNoVirtual() != nullptr);\n"
" if ($name$ != nullptr) {\n"
" $set_hasbit$\n"
@ -331,23 +316,21 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
} else {
// No-arena case.
format(
"inline const $string$& $classname$::$name$() const {\n"
"inline const std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.GetNoArena();\n"
"}\n"
"inline void $classname$::set_$name$(const $string$& value) {\n"
"inline void $classname$::set_$name$(const std::string& value) {\n"
" $set_hasbit$\n"
" $name$_.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
"inline void $classname$::set_$name$($string$&& value) {\n"
"inline void $classname$::set_$name$(std::string&& value) {\n"
" $set_hasbit$\n"
" $name$_.SetNoArena(\n"
" $default_variable$, ::std::move(value));\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"#endif\n"
"inline void $classname$::set_$name$(const char* value) {\n"
" $null_check$"
" $set_hasbit$\n"
@ -360,15 +343,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $set_hasbit$\n"
" $name$_.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
"}\n"
"#ifdef HAS_GLOBAL_STRING\n"
"inline void $classname$::set_$name$(const ::std::string& value) {\n"
" $set_hasbit$\n"
" $name$_.SetNoArena($default_variable$,\n"
" ::StringPiece(value.data(), value.size()));\n"
" // @@protoc_insertion_point(field_set_std_string:$full_name$)\n"
"}\n"
"#endif\n");
"}\n");
}
format(
"inline "
@ -379,12 +354,12 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $string_piece$(reinterpret_cast<const char*>(value), size));\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"inline $string$* $classname$::mutable_$name$() {\n"
"inline std::string* $classname$::mutable_$name$() {\n"
" $set_hasbit$\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.MutableNoArena($default_variable$);\n"
"}\n"
"inline $string$* $classname$::$release_name$() {\n"
"inline std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n");
if (HasFieldPresence(descriptor_->file())) {
@ -402,7 +377,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
format(
"}\n"
"inline void $classname$::set_allocated_$name$($string$* $name$) {\n"
"inline void $classname$::set_allocated_$name$(std::string* $name$) {\n"
" if ($name$ != nullptr) {\n"
" $set_hasbit$\n"
" } else {\n"
@ -420,7 +395,7 @@ GenerateNonInlineAccessorDefinitions(io::Printer* printer) const {
if (!descriptor_->default_value_string().empty()) {
// Initialized in GenerateDefaultInstanceAllocator.
format(
"::$proto_ns$::internal::ExplicitlyConstructed<$string$> "
"::$proto_ns$::internal::ExplicitlyConstructed<std::string> "
"$classname$::$default_variable_name$;\n");
}
}
@ -599,7 +574,7 @@ GenerateDefaultInstanceAllocator(io::Printer* printer) const {
format(
"$ns$::$classname$::$default_variable_name$.DefaultConstruct();\n"
"*$ns$::$classname$::$default_variable_name$.get_mutable() = "
"$string$($default$, $default_length$);\n"
"std::string($default$, $default_length$);\n"
"::$proto_ns$::internal::OnShutdownDestroyString(\n"
" $ns$::$classname$::$default_variable_name$.get_mutable());\n");
}
@ -609,17 +584,17 @@ void StringFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
Formatter format(printer, variables_);
// The google3 version of proto2 has ArenaStrings and parses into them
// directly, but for the open-source release, we always parse into ::std::string
// directly, but for the open-source release, we always parse into std::string
// instances. Note that for lite, we do similarly to the open source release
// and use ::std::string, not ArenaString.
// and use std::string, not ArenaString.
if (!options_.opensource_runtime && !inlined_ &&
SupportsArenas(descriptor_) && !lite_) {
// If arena != NULL, the current string is either an ArenaString (no
// destructor necessary) or a materialized ::std::string (and is on the Arena's
// destructor list). No call to ArenaStringPtr::Destroy is needed.
// destructor necessary) or a materialized std::string (and is on the
// Arena's destructor list). No call to ArenaStringPtr::Destroy is needed.
format(
"if (arena != nullptr) {\n"
" ::$proto_ns$::internal::TaggedPtr<$string$> str =\n"
" ::$proto_ns$::internal::TaggedPtr<std::string> str =\n"
" ::$proto_ns$::internal::ReadArenaString(input, arena);\n"
" DO_(!str.IsNull());\n"
" $set_hasbit_io$\n"
@ -707,14 +682,14 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
Formatter format(printer, variables_);
if (SupportsArenas(descriptor_)) {
format(
"inline const $string$& $classname$::$name$() const {\n"
"inline const std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $field_member$.Get();\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
"inline void $classname$::set_$name$(const $string$& value) {\n"
"inline void $classname$::set_$name$(const std::string& value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@ -724,8 +699,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
"inline void $classname$::set_$name$($string$&& value) {\n"
"inline void $classname$::set_$name$(std::string&& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@ -736,7 +710,6 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $default_variable$, ::std::move(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"#endif\n"
"inline void $classname$::set_$name$(const char* value) {\n"
" $null_check$"
" if (!has_$name$()) {\n"
@ -759,20 +732,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $field_member$.Set$lite$($default_variable$, value,\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
"}\n"
"#ifdef HAS_GLOBAL_STRING\n"
"inline void $classname$::set_$name$(const ::std::string& value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $field_member$.Set$lite$($default_variable$,\n"
" ::StringPiece(value.data(), value.size()), "
"GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_std_string:$full_name$)\n"
"}\n"
"#endif\n");
"}\n");
}
format(
"inline "
@ -789,7 +749,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"inline $string$* $classname$::mutable_$name$() {\n"
"inline std::string* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@ -799,7 +759,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
"}\n"
"inline $string$* $classname$::$release_name$() {\n"
"inline std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
@ -809,7 +769,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" return nullptr;\n"
" }\n"
"}\n"
"inline void $classname$::set_allocated_$name$($string$* $name$) {\n"
"inline void $classname$::set_allocated_$name$(std::string* $name$) {\n"
" if (has_$oneof_name$()) {\n"
" clear_$oneof_name$();\n"
" }\n"
@ -821,7 +781,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"}\n");
if (options_.opensource_runtime) {
format(
"inline $string$* $classname$::unsafe_arena_release_$name$() {\n"
"inline std::string* $classname$::unsafe_arena_release_$name$() {\n"
" // "
"@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
" $DCHK$(GetArenaNoVirtual() != nullptr);\n"
@ -834,7 +794,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" }\n"
"}\n"
"inline void $classname$::unsafe_arena_set_allocated_$name$("
"$string$* $name$) {\n"
"std::string* $name$) {\n"
" $DCHK$(GetArenaNoVirtual() != nullptr);\n"
" if (!has_$name$()) {\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
@ -852,14 +812,14 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
} else {
// No-arena case.
format(
"inline const $string$& $classname$::$name$() const {\n"
"inline const std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $field_member$.GetNoArena();\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
"inline void $classname$::set_$name$(const $string$& value) {\n"
"inline void $classname$::set_$name$(const std::string& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@ -869,8 +829,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $field_member$.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
"inline void $classname$::set_$name$($string$&& value) {\n"
"inline void $classname$::set_$name$(std::string&& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@ -880,7 +839,6 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $field_member$.SetNoArena($default_variable$, ::std::move(value));\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"#endif\n"
"inline void $classname$::set_$name$(const char* value) {\n"
" $null_check$"
" if (!has_$name$()) {\n"
@ -902,19 +860,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" }\n"
" $field_member$.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
"}\n"
"#ifdef HAS_GLOBAL_STRING\n"
"inline void $classname$::set_$name$(const ::std::string& value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $field_member$.SetNoArena($default_variable$,\n"
" ::StringPiece(value.data(), value.size()));\n"
" // @@protoc_insertion_point(field_set_std_string:$full_name$)\n"
"}\n"
"#endif\n");
"}\n");
}
format(
"inline "
@ -929,7 +875,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" reinterpret_cast<const char*>(value), size));\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"inline $string$* $classname$::mutable_$name$() {\n"
"inline std::string* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@ -938,7 +884,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $field_member$.MutableNoArena($default_variable$);\n"
"}\n"
"inline $string$* $classname$::$release_name$() {\n"
"inline std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
@ -947,7 +893,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" return nullptr;\n"
" }\n"
"}\n"
"inline void $classname$::set_allocated_$name$($string$* $name$) {\n"
"inline void $classname$::set_allocated_$name$(std::string* $name$) {\n"
" if (has_$oneof_name$()) {\n"
" clear_$oneof_name$();\n"
" }\n"
@ -1005,8 +951,8 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
// See above: ArenaString is not included in the open-source release.
if (!options_.opensource_runtime && SupportsArenas(descriptor_) && !lite_) {
// If has_$name$(), then the current string is either an ArenaString (no
// destructor necessary) or a materialized ::std::string (and is on the Arena's
// destructor list). No call to ArenaStringPtr::Destroy is needed.
// destructor necessary) or a materialized std::string (and is on the
// Arena's destructor list). No call to ArenaStringPtr::Destroy is needed.
format(
"if (arena != nullptr) {\n"
" clear_$oneof_name$();\n"
@ -1014,7 +960,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" set_has_$name$();\n"
" }\n"
" ::$proto_ns$::internal::TaggedPtr<$string$> new_value =\n"
" ::$proto_ns$::internal::TaggedPtr<std::string> new_value =\n"
" ::$proto_ns$::internal::ReadArenaString(input, arena);\n"
" DO_(!new_value.IsNull());\n"
" $field_member$.UnsafeSetTaggedPointer(new_value);\n"
@ -1050,7 +996,7 @@ RepeatedStringFieldGenerator::~RepeatedStringFieldGenerator() {}
void RepeatedStringFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
Formatter format(printer, variables_);
format("::$proto_ns$::RepeatedPtrField<$string$> $name$_;\n");
format("::$proto_ns$::RepeatedPtrField<std::string> $name$_;\n");
}
void RepeatedStringFieldGenerator::
@ -1069,52 +1015,42 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
}
format(
"$deprecated_attr$const $string$& ${1$$name$$}$(int index) const;\n"
"$deprecated_attr$$string$* ${1$mutable_$name$$}$(int index);\n"
"$deprecated_attr$const std::string& ${1$$name$$}$(int index) const;\n"
"$deprecated_attr$std::string* ${1$mutable_$name$$}$(int index);\n"
"$deprecated_attr$void ${1$set_$name$$}$(int index, const "
"$string$& value);\n"
"#if LANG_CXX11\n"
"$deprecated_attr$void ${1$set_$name$$}$(int index, $string$&& value);\n"
"#endif\n"
"std::string& value);\n"
"$deprecated_attr$void ${1$set_$name$$}$(int index, std::string&& "
"value);\n"
"$deprecated_attr$void ${1$set_$name$$}$(int index, const "
"char* value);\n",
descriptor_);
if (!options_.opensource_runtime) {
format(
"$deprecated_attr$void ${1$set_$name$$}$(int index, "
"StringPiece value);\n"
"#ifdef HAS_GLOBAL_STRING\n"
"$deprecated_attr$void ${1$set_$name$$}$(int index, const "
"::std::string& value);\n"
"#endif\n",
"StringPiece value);\n",
descriptor_);
}
format(
"$deprecated_attr$void ${1$set_$name$$}$("
"int index, const $pointer_type$* value, size_t size);\n"
"$deprecated_attr$$string$* ${1$add_$name$$}$();\n"
"$deprecated_attr$void ${1$add_$name$$}$(const $string$& value);\n"
"#if LANG_CXX11\n"
"$deprecated_attr$void ${1$add_$name$$}$($string$&& value);\n"
"#endif\n"
"$deprecated_attr$std::string* ${1$add_$name$$}$();\n"
"$deprecated_attr$void ${1$add_$name$$}$(const std::string& value);\n"
"$deprecated_attr$void ${1$add_$name$$}$(std::string&& value);\n"
"$deprecated_attr$void ${1$add_$name$$}$(const char* value);\n",
descriptor_);
if (!options_.opensource_runtime) {
format(
"$deprecated_attr$void ${1$add_$name$$}$(StringPiece value);\n"
"#ifdef HAS_GLOBAL_STRING\n"
"$deprecated_attr$void ${1$add_$name$$}$(const ::std::string& value);\n"
"#endif\n",
"$deprecated_attr$void ${1$add_$name$$}$(StringPiece value);\n",
descriptor_);
}
format(
"$deprecated_attr$void ${1$add_$name$$}$(const $pointer_type$* "
"value, size_t size)"
";\n"
"$deprecated_attr$const ::$proto_ns$::RepeatedPtrField<$string$>& "
"$deprecated_attr$const ::$proto_ns$::RepeatedPtrField<std::string>& "
"${1$$name$$}$() "
"const;\n"
"$deprecated_attr$::$proto_ns$::RepeatedPtrField<$string$>* "
"$deprecated_attr$::$proto_ns$::RepeatedPtrField<std::string>* "
"${1$mutable_$name$$}$()"
";\n",
descriptor_);
@ -1131,34 +1067,33 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
Formatter format(printer, variables_);
if (options_.safe_boundary_check) {
format(
"inline const $string$& $classname$::$name$(int index) const {\n"
"inline const std::string& $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.InternalCheckedGet(\n"
" index, ::$proto_ns$::internal::GetEmptyStringAlreadyInited());\n"
"}\n");
} else {
format(
"inline const $string$& $classname$::$name$(int index) const {\n"
"inline const std::string& $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.Get(index);\n"
"}\n");
}
format(
"inline $string$* $classname$::mutable_$name$(int index) {\n"
"inline std::string* $classname$::mutable_$name$(int index) {\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable(index);\n"
"}\n"
"inline void $classname$::set_$name$(int index, const $string$& value) "
"inline void $classname$::set_$name$(int index, const std::string& "
"value) "
"{\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" $name$_.Mutable(index)->assign(value);\n"
"}\n"
"#if LANG_CXX11\n"
"inline void $classname$::set_$name$(int index, $string$&& value) {\n"
"inline void $classname$::set_$name$(int index, std::string&& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" $name$_.Mutable(index)->assign(std::move(value));\n"
"}\n"
"#endif\n"
"inline void $classname$::set_$name$(int index, const char* value) {\n"
" $null_check$"
" $name$_.Mutable(index)->assign(value);\n"
@ -1170,14 +1105,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"$classname$::set_$name$(int index, StringPiece value) {\n"
" $name$_.Mutable(index)->assign(value.data(), value.size());\n"
" // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
"}\n"
"#ifdef HAS_GLOBAL_STRING\n"
"inline void "
"$classname$::set_$name$(int index, const std::string& value) {\n"
" $name$_.Mutable(index)->assign(value.data(), value.size());\n"
" // @@protoc_insertion_point(field_set_std_string:$full_name$)\n"
"}\n"
"#endif\n");
"}\n");
}
format(
"inline void "
@ -1187,20 +1115,18 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" reinterpret_cast<const char*>(value), size);\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"inline $string$* $classname$::add_$name$() {\n"
"inline std::string* $classname$::add_$name$() {\n"
" // @@protoc_insertion_point(field_add_mutable:$full_name$)\n"
" return $name$_.Add();\n"
"}\n"
"inline void $classname$::add_$name$(const $string$& value) {\n"
"inline void $classname$::add_$name$(const std::string& value) {\n"
" $name$_.Add()->assign(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
"inline void $classname$::add_$name$($string$&& value) {\n"
"inline void $classname$::add_$name$(std::string&& value) {\n"
" $name$_.Add(std::move(value));\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n"
"#endif\n"
"inline void $classname$::add_$name$(const char* value) {\n"
" $null_check$"
" $name$_.Add()->assign(value);\n"
@ -1211,13 +1137,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"inline void $classname$::add_$name$(StringPiece value) {\n"
" $name$_.Add()->assign(value.data(), value.size());\n"
" // @@protoc_insertion_point(field_add_string_piece:$full_name$)\n"
"}\n"
"#ifdef HAS_GLOBAL_STRING\n"
"inline void $classname$::add_$name$(const ::std::string& value) {\n"
" $name$_.Add()->assign(value.data(), value.size());\n"
" // @@protoc_insertion_point(field_add_std_string:$full_name$)\n"
"}\n"
"#endif\n");
"}\n");
}
format(
"inline void "
@ -1225,12 +1145,12 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $name$_.Add()->assign(reinterpret_cast<const char*>(value), size);\n"
" // @@protoc_insertion_point(field_add_pointer:$full_name$)\n"
"}\n"
"inline const ::$proto_ns$::RepeatedPtrField<$string$>&\n"
"inline const ::$proto_ns$::RepeatedPtrField<std::string>&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
"inline ::$proto_ns$::RepeatedPtrField<$string$>*\n"
"inline ::$proto_ns$::RepeatedPtrField<std::string>*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"

@ -94,11 +94,11 @@ class MockErrorCollector : public MultiFileErrorCollector {
MockErrorCollector() {}
~MockErrorCollector() {}
string text_;
std::string text_;
// implements ErrorCollector ---------------------------------------
void AddError(const string& filename, int line, int column,
const string& message) {
void AddError(const std::string& filename, int line, int column,
const std::string& message) {
strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
filename, line, column, message);
}
@ -142,7 +142,7 @@ TEST(GENERATED_DESCRIPTOR_TEST_NAME, IdenticalDescriptors) {
// limit for string literal size
TEST(GENERATED_DESCRIPTOR_TEST_NAME, EnormousDescriptor) {
const Descriptor* generated_descriptor =
TestEnormousDescriptor::descriptor();
::protobuf_unittest::TestEnormousDescriptor::descriptor();
EXPECT_TRUE(generated_descriptor != NULL);
}
@ -241,8 +241,8 @@ TEST(GENERATED_MESSAGE_TEST_NAME, MutableStringDefault) {
TEST(GENERATED_MESSAGE_TEST_NAME, StringDefaults) {
UNITTEST::TestExtremeDefaultValues message;
// Check if '\000' can be used in default string value.
EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero());
EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero());
EXPECT_EQ(std::string("hel\000lo", 6), message.string_with_zero());
EXPECT_EQ(std::string("wor\000ld", 6), message.bytes_with_zero());
}
TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseString) {
@ -256,7 +256,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseString) {
message.set_default_string("blah");
EXPECT_TRUE(message.has_default_string());
std::unique_ptr<string> str(message.release_default_string());
std::unique_ptr<std::string> str(message.release_default_string());
EXPECT_FALSE(message.has_default_string());
ASSERT_TRUE(str != NULL);
EXPECT_EQ("blah", *str);
@ -290,7 +290,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedString) {
UNITTEST::TestAllTypes message;
EXPECT_FALSE(message.has_optional_string());
const string kHello("hello");
const std::string kHello("hello");
message.set_optional_string(kHello);
EXPECT_TRUE(message.has_optional_string());
@ -298,7 +298,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedString) {
EXPECT_FALSE(message.has_optional_string());
EXPECT_EQ("", message.optional_string());
message.set_allocated_optional_string(new string(kHello));
message.set_allocated_optional_string(new std::string(kHello));
EXPECT_TRUE(message.has_optional_string());
EXPECT_EQ(kHello, message.optional_string());
}
@ -402,70 +402,68 @@ TEST(GENERATED_MESSAGE_TEST_NAME, StringCharStarLength) {
EXPECT_EQ("wx", message.repeated_string(0));
}
#if LANG_CXX11
TEST(GENERATED_MESSAGE_TEST_NAME, StringMove) {
// Verify that we trigger the move behavior on a scalar setter.
protobuf_unittest_no_arena::TestAllTypes message;
{
string tmp(32, 'a');
std::string tmp(32, 'a');
const char* old_data = tmp.data();
message.set_optional_string(std::move(tmp));
const char* new_data = message.optional_string().data();
EXPECT_EQ(old_data, new_data);
EXPECT_EQ(string(32, 'a'), message.optional_string());
EXPECT_EQ(std::string(32, 'a'), message.optional_string());
string tmp2(32, 'b');
std::string tmp2(32, 'b');
old_data = tmp2.data();
message.set_optional_string(std::move(tmp2));
new_data = message.optional_string().data();
EXPECT_EQ(old_data, new_data);
EXPECT_EQ(string(32, 'b'), message.optional_string());
EXPECT_EQ(std::string(32, 'b'), message.optional_string());
}
// Verify that we trigger the move behavior on a oneof setter.
{
string tmp(32, 'a');
std::string tmp(32, 'a');
const char* old_data = tmp.data();
message.set_oneof_string(std::move(tmp));
const char* new_data = message.oneof_string().data();
EXPECT_EQ(old_data, new_data);
EXPECT_EQ(string(32, 'a'), message.oneof_string());
EXPECT_EQ(std::string(32, 'a'), message.oneof_string());
string tmp2(32, 'b');
std::string tmp2(32, 'b');
old_data = tmp2.data();
message.set_oneof_string(std::move(tmp2));
new_data = message.oneof_string().data();
EXPECT_EQ(old_data, new_data);
EXPECT_EQ(string(32, 'b'), message.oneof_string());
EXPECT_EQ(std::string(32, 'b'), message.oneof_string());
}
// Verify that we trigger the move behavior on a repeated setter.
{
string tmp(32, 'a');
std::string tmp(32, 'a');
const char* old_data = tmp.data();
message.add_repeated_string(std::move(tmp));
const char* new_data = message.repeated_string(0).data();
EXPECT_EQ(old_data, new_data);
EXPECT_EQ(string(32, 'a'), message.repeated_string(0));
EXPECT_EQ(std::string(32, 'a'), message.repeated_string(0));
string tmp2(32, 'b');
std::string tmp2(32, 'b');
old_data = tmp2.data();
message.set_repeated_string(0, std::move(tmp2));
new_data = message.repeated_string(0).data();
EXPECT_EQ(old_data, new_data);
EXPECT_EQ(string(32, 'b'), message.repeated_string(0));
EXPECT_EQ(std::string(32, 'b'), message.repeated_string(0));
}
}
#endif
TEST(GENERATED_MESSAGE_TEST_NAME, CopyFrom) {
@ -666,7 +664,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, UpcastCopyFrom) {
TestUtil::SetAllFields(&message1);
const Message* source = ::google::protobuf::implicit_cast<const Message*>(&message1);
const Message* source = implicit_cast<const Message*>(&message1);
message2.CopyFrom(*source);
TestUtil::ExpectAllFieldsSet(message2);
@ -727,7 +725,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, NonEmptyMergeFrom) {
// Test the generated SerializeWithCachedSizesToArray(),
TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToArray) {
UNITTEST::TestAllTypes message1, message2;
string data;
std::string data;
TestUtil::SetAllFields(&message1);
int size = message1.ByteSizeLong();
data.resize(size);
@ -741,7 +739,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToArray) {
TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToArray) {
UNITTEST::TestPackedTypes packed_message1, packed_message2;
string packed_data;
std::string packed_data;
TestUtil::SetPackedFields(&packed_message1);
int packed_size = packed_message1.ByteSizeLong();
packed_data.resize(packed_size);
@ -758,7 +756,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToStream) {
UNITTEST::TestAllTypes message1, message2;
TestUtil::SetAllFields(&message1);
int size = message1.ByteSizeLong();
string data;
std::string data;
data.resize(size);
{
// Allow the output stream to buffer only one byte at a time.
@ -777,7 +775,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToStream) {
UNITTEST::TestPackedTypes message1, message2;
TestUtil::SetPackedFields(&message1);
int size = message1.ByteSizeLong();
string data;
std::string data;
data.resize(size);
{
// Allow the output stream to buffer only one byte at a time.
@ -844,7 +842,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, ForeignNested) {
TEST(GENERATED_MESSAGE_TEST_NAME, ReallyLargeTagNumber) {
// Test that really large tag numbers don't break anything.
UNITTEST::TestReallyLargeTagNumber message1, message2;
string data;
std::string data;
// For the most part, if this compiles and runs then we're probably good.
// (The most likely cause for failure would be if something were attempting
@ -927,7 +925,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, TestEmbedOptimizedForSize) {
UNITTEST::TestEmbedOptimizedForSize message, message2;
message.mutable_optional_message()->set_i(1);
message.add_repeated_message()->mutable_msg()->set_c(2);
string data;
std::string data;
message.SerializeToString(&data);
ASSERT_TRUE(message2.ParseFromString(data));
EXPECT_EQ(1, message2.optional_message().i());
@ -956,7 +954,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, TestSpaceUsed) {
// Setting a string to a value larger than the string object itself should
// increase SpaceUsedLong(), because it cannot store the value internally.
message1.set_optional_string(string(sizeof(string) + 1, 'x'));
message1.set_optional_string(std::string(sizeof(std::string) + 1, 'x'));
int min_expected_increase = message1.optional_string().capacity();
EXPECT_LE(empty_message_size + min_expected_increase,
message1.SpaceUsedLong());
@ -986,14 +984,14 @@ TEST(GENERATED_MESSAGE_TEST_NAME, TestOneofSpaceUsed) {
// Setting a string in oneof to a small value should only increase
// SpaceUsedLong() by the size of a string object.
message1.set_foo_string("abc");
EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong());
EXPECT_LE(empty_message_size + sizeof(std::string), message1.SpaceUsedLong());
// Setting a string in oneof to a value larger than the string object itself
// should increase SpaceUsedLong(), because it cannot store the value
// internally.
message1.set_foo_string(string(sizeof(string) + 1, 'x'));
int min_expected_increase = message1.foo_string().capacity() +
sizeof(string);
message1.set_foo_string(std::string(sizeof(std::string) + 1, 'x'));
int min_expected_increase =
message1.foo_string().capacity() + sizeof(std::string);
EXPECT_LE(empty_message_size + min_expected_increase,
message1.SpaceUsedLong());
@ -1038,10 +1036,10 @@ TEST(GENERATED_MESSAGE_TEST_NAME, ExtensionConstantValues) {
}
TEST(GENERATED_MESSAGE_TEST_NAME, ParseFromTruncated) {
const string long_string = string(128, 'q');
const std::string long_string = std::string(128, 'q');
FileDescriptorProto p;
p.add_extension()->set_name(long_string);
const string msg = p.SerializeAsString();
const std::string msg = p.SerializeAsString();
int successful_count = 0;
for (int i = 0; i <= msg.size(); i++) {
if (p.ParseFromArray(msg.c_str(), i)) {
@ -1244,7 +1242,7 @@ class GENERATED_SERVICE_TEST_NAME : public testing::Test {
// ---------------------------------------------------------------
bool called_;
string method_;
std::string method_;
RpcController* controller_;
const Message* request_;
Message* response_;
@ -1304,14 +1302,14 @@ class GENERATED_SERVICE_TEST_NAME : public testing::Test {
ADD_FAILURE() << "Failed() not expected during this test.";
return false;
}
string ErrorText() const {
std::string ErrorText() const {
ADD_FAILURE() << "ErrorText() not expected during this test.";
return "";
}
void StartCancel() {
ADD_FAILURE() << "StartCancel() not expected during this test.";
}
void SetFailed(const string& reason) {
void SetFailed(const std::string& reason) {
ADD_FAILURE() << "SetFailed() not expected during this test.";
}
bool IsCanceled() const {
@ -1471,7 +1469,7 @@ TEST_F(GENERATED_SERVICE_TEST_NAME, NotImplemented) {
public:
ExpectUnimplementedController() : called_(false) {}
void SetFailed(const string& reason) {
void SetFailed(const std::string& reason) {
EXPECT_FALSE(called_);
called_ = true;
EXPECT_EQ("Method Foo() not implemented.", reason);
@ -1621,7 +1619,7 @@ TEST_F(OneofTest, SetString) {
message.clear_foo_string();
EXPECT_FALSE(message.has_foo_string());
message.set_foo_string(string("bar"));
message.set_foo_string(std::string("bar"));
EXPECT_TRUE(message.has_foo_string());
EXPECT_EQ(message.foo_string(), "bar");
message.clear_foo_string();
@ -1657,7 +1655,7 @@ TEST_F(OneofTest, ReleaseString) {
message.set_foo_string("blah");
EXPECT_TRUE(message.has_foo_string());
std::unique_ptr<string> str(message.release_foo_string());
std::unique_ptr<std::string> str(message.release_foo_string());
EXPECT_FALSE(message.has_foo_string());
ASSERT_TRUE(str != NULL);
EXPECT_EQ("blah", *str);
@ -1671,7 +1669,7 @@ TEST_F(OneofTest, SetAllocatedString) {
UNITTEST::TestOneof2 message;
EXPECT_FALSE(message.has_foo_string());
const string kHello("hello");
const std::string kHello("hello");
message.set_foo_string(kHello);
EXPECT_TRUE(message.has_foo_string());
@ -1679,7 +1677,7 @@ TEST_F(OneofTest, SetAllocatedString) {
EXPECT_FALSE(message.has_foo_string());
EXPECT_EQ("", message.foo_string());
message.set_allocated_foo_string(new string(kHello));
message.set_allocated_foo_string(new std::string(kHello));
EXPECT_TRUE(message.has_foo_string());
EXPECT_EQ(kHello, message.foo_string());
}
@ -1873,7 +1871,7 @@ TEST_F(OneofTest, UpcastCopyFrom) {
message1.mutable_foogroup()->set_a(123);
EXPECT_TRUE(message1.has_foogroup());
const Message* source = ::google::protobuf::implicit_cast<const Message*>(&message1);
const Message* source = implicit_cast<const Message*>(&message1);
message2.CopyFrom(*source);
EXPECT_TRUE(message2.has_foogroup());
@ -1888,21 +1886,21 @@ TEST_F(OneofTest, SerializationToArray) {
// Primitive type
{
UNITTEST::TestOneof2 message1, message2;
string data;
message1.set_foo_int(123);
int size = message1.ByteSizeLong();
data.resize(size);
uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
EXPECT_EQ(message2.foo_int(), 123);
std::string data;
message1.set_foo_int(123);
int size = message1.ByteSizeLong();
data.resize(size);
uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
EXPECT_EQ(message2.foo_int(), 123);
}
// String
{
UNITTEST::TestOneof2 message1, message2;
string data;
std::string data;
message1.set_foo_string("foo");
int size = message1.ByteSizeLong();
data.resize(size);
@ -1917,7 +1915,7 @@ TEST_F(OneofTest, SerializationToArray) {
// Bytes
{
UNITTEST::TestOneof2 message1, message2;
string data;
std::string data;
message1.set_foo_bytes("qux");
int size = message1.ByteSizeLong();
data.resize(size);
@ -1931,7 +1929,7 @@ TEST_F(OneofTest, SerializationToArray) {
// Enum
{
UNITTEST::TestOneof2 message1, message2;
string data;
std::string data;
message1.set_foo_enum(UNITTEST::TestOneof2::FOO);
int size = message1.ByteSizeLong();
data.resize(size);
@ -1945,7 +1943,7 @@ TEST_F(OneofTest, SerializationToArray) {
// Message
{
UNITTEST::TestOneof2 message1, message2;
string data;
std::string data;
message1.mutable_foo_message()->set_qux_int(234);
int size = message1.ByteSizeLong();
data.resize(size);
@ -1959,7 +1957,7 @@ TEST_F(OneofTest, SerializationToArray) {
// Group
{
UNITTEST::TestOneof2 message1, message2;
string data;
std::string data;
message1.mutable_foogroup()->set_a(345);
int size = message1.ByteSizeLong();
data.resize(size);
@ -1981,19 +1979,19 @@ TEST_F(OneofTest, SerializationToStream) {
// Primitive type
{
UNITTEST::TestOneof2 message1, message2;
string data;
message1.set_foo_int(123);
int size = message1.ByteSizeLong();
data.resize(size);
std::string data;
message1.set_foo_int(123);
int size = message1.ByteSizeLong();
data.resize(size);
{
// Allow the output stream to buffer only one byte at a time.
io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
EXPECT_EQ(size, output_stream.ByteCount());
}
{
// Allow the output stream to buffer only one byte at a time.
io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
EXPECT_EQ(size, output_stream.ByteCount());
}
EXPECT_TRUE(message2.ParseFromString(data));
EXPECT_EQ(message2.foo_int(), 123);
@ -2002,7 +2000,7 @@ TEST_F(OneofTest, SerializationToStream) {
// String
{
UNITTEST::TestOneof2 message1, message2;
string data;
std::string data;
message1.set_foo_string("foo");
int size = message1.ByteSizeLong();
data.resize(size);
@ -2024,7 +2022,7 @@ TEST_F(OneofTest, SerializationToStream) {
// Bytes
{
UNITTEST::TestOneof2 message1, message2;
string data;
std::string data;
message1.set_foo_bytes("qux");
int size = message1.ByteSizeLong();
data.resize(size);
@ -2045,7 +2043,7 @@ TEST_F(OneofTest, SerializationToStream) {
// Enum
{
UNITTEST::TestOneof2 message1, message2;
string data;
std::string data;
message1.set_foo_enum(UNITTEST::TestOneof2::FOO);
int size = message1.ByteSizeLong();
data.resize(size);
@ -2066,7 +2064,7 @@ TEST_F(OneofTest, SerializationToStream) {
// Message
{
UNITTEST::TestOneof2 message1, message2;
string data;
std::string data;
message1.mutable_foo_message()->set_qux_int(234);
int size = message1.ByteSizeLong();
data.resize(size);
@ -2087,7 +2085,7 @@ TEST_F(OneofTest, SerializationToStream) {
// Group
{
UNITTEST::TestOneof2 message1, message2;
string data;
std::string data;
message1.mutable_foogroup()->set_a(345);
int size = message1.ByteSizeLong();
data.resize(size);
@ -2153,12 +2151,12 @@ TEST(HELPERS_TEST_NAME, TestSCC) {
UNITTEST::TestMutualRecursionA a;
MessageSCCAnalyzer scc_analyzer((Options()));
const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor());
std::vector<string> names;
std::vector<std::string> names;
names.reserve(scc->descriptors.size());
for (int i = 0; i < scc->descriptors.size(); i++) {
names.push_back(scc->descriptors[i]->full_name());
}
string package = a.GetDescriptor()->file()->package();
std::string package = a.GetDescriptor()->file()->package();
ASSERT_EQ(names.size(), 4);
std::sort(names.begin(), names.end());
EXPECT_EQ(names[0], package + ".TestMutualRecursionA");
@ -2226,16 +2224,19 @@ namespace cpp_unittest {
TEST_F(GENERATED_SERVICE_TEST_NAME, NoGenericServices) {
// Verify that non-services in unittest_no_generic_services.proto were
// generated.
no_generic_services_test::TestMessage message;
::protobuf_unittest::no_generic_services_test::TestMessage message;
message.set_a(1);
message.SetExtension(no_generic_services_test::test_extension, 123);
no_generic_services_test::TestEnum e = no_generic_services_test::FOO;
message.SetExtension(
::protobuf_unittest::no_generic_services_test::test_extension, 123);
::protobuf_unittest::no_generic_services_test::TestEnum e =
::protobuf_unittest::no_generic_services_test::FOO;
EXPECT_EQ(e, 1);
// Verify that a ServiceDescriptor is generated for the service even if the
// class itself is not.
const FileDescriptor* file =
no_generic_services_test::TestMessage::descriptor()->file();
::google::protobuf::unittest::no_generic_services_test::TestMessage::descriptor()
->file();
ASSERT_EQ(1, file->service_count());
EXPECT_EQ("TestService", file->service(0)->name());

@ -56,14 +56,14 @@ class CppMetadataTest : public ::testing::Test {
// code from the previously added file with name `filename`. Returns true on
// success. If pb_h is non-null, expects a .pb.h and a .pb.h.meta (copied to
// pb_h and pb_h_info respecfively); similarly for proto_h and proto_h_info.
bool CaptureMetadata(const string& filename, FileDescriptorProto* file,
string* pb_h, GeneratedCodeInfo* pb_h_info,
string* proto_h, GeneratedCodeInfo* proto_h_info,
string* pb_cc) {
bool CaptureMetadata(const std::string& filename, FileDescriptorProto* file,
std::string* pb_h, GeneratedCodeInfo* pb_h_info,
std::string* proto_h, GeneratedCodeInfo* proto_h_info,
std::string* pb_cc) {
CommandLineInterface cli;
CppGenerator cpp_generator;
cli.RegisterGenerator("--cpp_out", &cpp_generator, "");
string cpp_out =
std::string cpp_out =
"--cpp_out=annotate_headers=true,"
"annotation_pragma_name=pragma_name,"
"annotation_guard_name=guard_name:" +
@ -76,7 +76,7 @@ class CppMetadataTest : public ::testing::Test {
return result;
}
string output_base = TestTempDir() + "/" + StripProto(filename);
std::string output_base = TestTempDir() + "/" + StripProto(filename);
if (pb_cc != NULL) {
GOOGLE_CHECK_OK(
@ -112,7 +112,7 @@ const char kSmallTestFile[] =
TEST_F(CppMetadataTest, CapturesEnumNames) {
FileDescriptorProto file;
GeneratedCodeInfo info;
string pb_h;
std::string pb_h;
atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
@ -129,19 +129,19 @@ TEST_F(CppMetadataTest, CapturesEnumNames) {
TEST_F(CppMetadataTest, AddsPragma) {
FileDescriptorProto file;
GeneratedCodeInfo info;
string pb_h;
std::string pb_h;
atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
EXPECT_TRUE(pb_h.find("#ifdef guard_name") != string::npos);
EXPECT_TRUE(pb_h.find("#pragma pragma_name \"test.pb.h.meta\"") !=
string::npos);
std::string::npos);
}
TEST_F(CppMetadataTest, CapturesMessageNames) {
FileDescriptorProto file;
GeneratedCodeInfo info;
string pb_h;
std::string pb_h;
atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));

@ -49,7 +49,7 @@ namespace csharp {
// it to support C# output, you can do so by registering an instance of this
// CodeGenerator with the CommandLineInterface in your main() function.
class PROTOC_EXPORT Generator
: public google::protobuf::compiler::CodeGenerator {
: public PROTOBUF_NAMESPACE_ID::compiler::CodeGenerator {
public:
virtual bool Generate(
const FileDescriptor* file,

@ -73,7 +73,7 @@ using google::protobuf::internal::win32::open;
// Returns true if the text looks like a Windows-style absolute path, starting
// with a drive letter. Example: "C:\foo". TODO(kenton): Share this with
// copy in command_line_interface.cc?
static bool IsWindowsAbsolutePath(const string& text) {
static bool IsWindowsAbsolutePath(const std::string& text) {
#if defined(_WIN32) || defined(__CYGWIN__)
return text.size() >= 3 && text[1] == ':' &&
isalpha(text[0]) &&
@ -93,17 +93,17 @@ MultiFileErrorCollector::~MultiFileErrorCollector() {}
class SourceTreeDescriptorDatabase::SingleFileErrorCollector
: public io::ErrorCollector {
public:
SingleFileErrorCollector(const string& filename,
SingleFileErrorCollector(const std::string& filename,
MultiFileErrorCollector* multi_file_error_collector)
: filename_(filename),
multi_file_error_collector_(multi_file_error_collector),
had_errors_(false) {}
: filename_(filename),
multi_file_error_collector_(multi_file_error_collector),
had_errors_(false) {}
~SingleFileErrorCollector() {}
bool had_errors() { return had_errors_; }
// implements ErrorCollector ---------------------------------------
void AddError(int line, int column, const string& message) override {
void AddError(int line, int column, const std::string& message) override {
if (multi_file_error_collector_ != NULL) {
multi_file_error_collector_->AddError(filename_, line, column, message);
}
@ -111,7 +111,7 @@ class SourceTreeDescriptorDatabase::SingleFileErrorCollector
}
private:
string filename_;
std::string filename_;
MultiFileErrorCollector* multi_file_error_collector_;
bool had_errors_;
};
@ -136,8 +136,8 @@ SourceTreeDescriptorDatabase::SourceTreeDescriptorDatabase(
SourceTreeDescriptorDatabase::~SourceTreeDescriptorDatabase() {}
bool SourceTreeDescriptorDatabase::FindFileByName(
const string& filename, FileDescriptorProto* output) {
bool SourceTreeDescriptorDatabase::FindFileByName(const std::string& filename,
FileDescriptorProto* output) {
std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_->Open(filename));
if (input == NULL) {
if (fallback_database_ != nullptr &&
@ -170,12 +170,12 @@ bool SourceTreeDescriptorDatabase::FindFileByName(
}
bool SourceTreeDescriptorDatabase::FindFileContainingSymbol(
const string& symbol_name, FileDescriptorProto* output) {
const std::string& symbol_name, FileDescriptorProto* output) {
return false;
}
bool SourceTreeDescriptorDatabase::FindFileContainingExtension(
const string& containing_type, int field_number,
const std::string& containing_type, int field_number,
FileDescriptorProto* output) {
return false;
}
@ -190,11 +190,9 @@ SourceTreeDescriptorDatabase::ValidationErrorCollector::
~ValidationErrorCollector() {}
void SourceTreeDescriptorDatabase::ValidationErrorCollector::AddError(
const string& filename,
const string& element_name,
const Message* descriptor,
ErrorLocation location,
const string& message) {
const std::string& filename, const std::string& element_name,
const Message* descriptor, ErrorLocation location,
const std::string& message) {
if (owner_->error_collector_ == NULL) return;
int line, column;
@ -203,11 +201,9 @@ void SourceTreeDescriptorDatabase::ValidationErrorCollector::AddError(
}
void SourceTreeDescriptorDatabase::ValidationErrorCollector::AddWarning(
const string& filename,
const string& element_name,
const Message* descriptor,
ErrorLocation location,
const string& message) {
const std::string& filename, const std::string& element_name,
const Message* descriptor, ErrorLocation location,
const std::string& message) {
if (owner_->error_collector_ == NULL) return;
int line, column;
@ -227,11 +223,11 @@ Importer::Importer(SourceTree* source_tree,
Importer::~Importer() {}
const FileDescriptor* Importer::Import(const string& filename) {
const FileDescriptor* Importer::Import(const std::string& filename) {
return pool_.FindFileByName(filename);
}
void Importer::AddUnusedImportTrackFile(const string& file_name) {
void Importer::AddUnusedImportTrackFile(const std::string& file_name) {
pool_.AddUnusedImportTrackFile(file_name);
}
@ -244,15 +240,13 @@ void Importer::ClearUnusedImportTrackFiles() {
SourceTree::~SourceTree() {}
string SourceTree::GetLastErrorMessage() {
return "File not found.";
}
std::string SourceTree::GetLastErrorMessage() { return "File not found."; }
DiskSourceTree::DiskSourceTree() {}
DiskSourceTree::~DiskSourceTree() {}
static inline char LastChar(const string& str) {
static inline char LastChar(const std::string& str) {
return str[str.size() - 1];
}
@ -275,7 +269,7 @@ static inline char LastChar(const string& str) {
// then if foo/bar is a symbolic link, foo/bar/baz.proto will canonicalize
// to a path which does not appear to be under foo, and thus the compiler
// will complain that baz.proto is not inside the --proto_path.
static string CanonicalizePath(string path) {
static std::string CanonicalizePath(std::string path) {
#ifdef _WIN32
// The Win32 API accepts forward slashes as a path delimiter even though
// backslashes are standard. Let's avoid confusion and use only forward
@ -288,8 +282,8 @@ static string CanonicalizePath(string path) {
}
#endif
std::vector<string> canonical_parts;
std::vector<string> parts = Split(
std::vector<std::string> canonical_parts;
std::vector<std::string> parts = Split(
path, "/", true); // Note: Removes empty parts.
for (int i = 0; i < parts.size(); i++) {
if (parts[i] == ".") {
@ -298,7 +292,7 @@ static string CanonicalizePath(string path) {
canonical_parts.push_back(parts[i]);
}
}
string result = Join(canonical_parts, "/");
std::string result = Join(canonical_parts, "/");
if (!path.empty() && path[0] == '/') {
// Restore leading slash.
result = '/' + result;
@ -311,7 +305,7 @@ static string CanonicalizePath(string path) {
return result;
}
static inline bool ContainsParentReference(const string& path) {
static inline bool ContainsParentReference(const std::string& path) {
return path == ".." || HasPrefixString(path, "../") ||
HasSuffixString(path, "/..") || path.find("/../") != string::npos;
}
@ -333,10 +327,9 @@ static inline bool ContainsParentReference(const string& path) {
// assert(!ApplyMapping("foo/bar", "baz", "qux", &result));
// assert(!ApplyMapping("foo/bar", "baz", "qux", &result));
// assert(!ApplyMapping("foobar", "foo", "baz", &result));
static bool ApplyMapping(const string& filename,
const string& old_prefix,
const string& new_prefix,
string* result) {
static bool ApplyMapping(const std::string& filename,
const std::string& old_prefix,
const std::string& new_prefix, std::string* result) {
if (old_prefix.empty()) {
// old_prefix matches any relative path.
if (ContainsParentReference(filename)) {
@ -372,7 +365,7 @@ static bool ApplyMapping(const string& filename,
if (after_prefix_start != -1) {
// Yep. So the prefixes are directories and the filename is a file
// inside them.
string after_prefix = filename.substr(after_prefix_start);
std::string after_prefix = filename.substr(after_prefix_start);
if (ContainsParentReference(after_prefix)) {
// We do not allow the file name to use "..".
return false;
@ -388,18 +381,17 @@ static bool ApplyMapping(const string& filename,
return false;
}
void DiskSourceTree::MapPath(const string& virtual_path,
const string& disk_path) {
void DiskSourceTree::MapPath(const std::string& virtual_path,
const std::string& disk_path) {
mappings_.push_back(Mapping(virtual_path, CanonicalizePath(disk_path)));
}
DiskSourceTree::DiskFileToVirtualFileResult
DiskSourceTree::DiskFileToVirtualFile(
const string& disk_file,
string* virtual_file,
string* shadowing_disk_file) {
DiskSourceTree::DiskFileToVirtualFile(const std::string& disk_file,
std::string* virtual_file,
std::string* shadowing_disk_file) {
int mapping_index = -1;
string canonical_disk_file = CanonicalizePath(disk_file);
std::string canonical_disk_file = CanonicalizePath(disk_file);
for (int i = 0; i < mappings_.size(); i++) {
// Apply the mapping in reverse.
@ -439,24 +431,23 @@ DiskSourceTree::DiskFileToVirtualFile(
return SUCCESS;
}
bool DiskSourceTree::VirtualFileToDiskFile(const string& virtual_file,
string* disk_file) {
bool DiskSourceTree::VirtualFileToDiskFile(const std::string& virtual_file,
std::string* disk_file) {
std::unique_ptr<io::ZeroCopyInputStream> stream(
OpenVirtualFile(virtual_file, disk_file));
return stream != NULL;
}
io::ZeroCopyInputStream* DiskSourceTree::Open(const string& filename) {
io::ZeroCopyInputStream* DiskSourceTree::Open(const std::string& filename) {
return OpenVirtualFile(filename, NULL);
}
string DiskSourceTree::GetLastErrorMessage() {
std::string DiskSourceTree::GetLastErrorMessage() {
return last_error_message_;
}
io::ZeroCopyInputStream* DiskSourceTree::OpenVirtualFile(
const string& virtual_file,
string* disk_file) {
const std::string& virtual_file, std::string* disk_file) {
if (virtual_file != CanonicalizePath(virtual_file) ||
ContainsParentReference(virtual_file)) {
// We do not allow importing of paths containing things like ".." or
@ -468,7 +459,7 @@ io::ZeroCopyInputStream* DiskSourceTree::OpenVirtualFile(
}
for (int i = 0; i < mappings_.size(); i++) {
string temp_disk_file;
std::string temp_disk_file;
if (ApplyMapping(virtual_file, mappings_[i].virtual_path,
mappings_[i].disk_path, &temp_disk_file)) {
io::ZeroCopyInputStream* stream = OpenDiskFile(temp_disk_file);
@ -492,7 +483,7 @@ io::ZeroCopyInputStream* DiskSourceTree::OpenVirtualFile(
}
io::ZeroCopyInputStream* DiskSourceTree::OpenDiskFile(
const string& filename) {
const std::string& filename) {
int file_descriptor;
do {
file_descriptor = open(filename.c_str(), O_RDONLY);

@ -129,8 +129,9 @@ class PROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase {
const Message* descriptor, ErrorLocation location,
const std::string& message) override;
void AddWarning(const std::string& filename, const std::string& element_name,
const Message* descriptor, ErrorLocation location,
void AddWarning(const std::string& filename,
const std::string& element_name, const Message* descriptor,
ErrorLocation location,
const std::string& message) override;
private:
@ -288,15 +289,15 @@ class PROTOBUF_EXPORT DiskSourceTree : public SourceTree {
// it is not useful.
// * NO_MAPPING: Indicates that no mapping was found which contains this
// file.
DiskFileToVirtualFileResult
DiskFileToVirtualFile(const std::string& disk_file,
std::string* virtual_file,
std::string* shadowing_disk_file);
DiskFileToVirtualFileResult DiskFileToVirtualFile(
const std::string& disk_file, std::string* virtual_file,
std::string* shadowing_disk_file);
// Given a virtual path, find the path to the file on disk.
// Return true and update disk_file with the on-disk path if the file exists.
// Return false and leave disk_file untouched if the file doesn't exist.
bool VirtualFileToDiskFile(const std::string& virtual_file, std::string* disk_file);
bool VirtualFileToDiskFile(const std::string& virtual_file,
std::string* disk_file);
// implements SourceTree -------------------------------------------
io::ZeroCopyInputStream* Open(const std::string& filename) override;
@ -310,7 +311,7 @@ class PROTOBUF_EXPORT DiskSourceTree : public SourceTree {
inline Mapping(const std::string& virtual_path_param,
const std::string& disk_path_param)
: virtual_path(virtual_path_param), disk_path(disk_path_param) {}
: virtual_path(virtual_path_param), disk_path(disk_path_param) {}
};
std::vector<Mapping> mappings_;
std::string last_error_message_;

@ -56,7 +56,7 @@ namespace compiler {
namespace {
bool FileExists(const string& path) {
bool FileExists(const std::string& path) {
return File::Exists(path);
}
@ -68,18 +68,18 @@ class MockErrorCollector : public MultiFileErrorCollector {
MockErrorCollector() {}
~MockErrorCollector() {}
string text_;
string warning_text_;
std::string text_;
std::string warning_text_;
// implements ErrorCollector ---------------------------------------
void AddError(const string& filename, int line, int column,
const string& message) {
void AddError(const std::string& filename, int line, int column,
const std::string& message) {
strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
filename, line, column, message);
}
void AddWarning(const string& filename, int line, int column,
const string& message) {
void AddWarning(const std::string& filename, int line, int column,
const std::string& message) {
strings::SubstituteAndAppend(&warning_text_, "$0:$1:$2: $3\n",
filename, line, column, message);
}
@ -93,12 +93,12 @@ class MockSourceTree : public SourceTree {
MockSourceTree() {}
~MockSourceTree() {}
void AddFile(const string& name, const char* contents) {
void AddFile(const std::string& name, const char* contents) {
files_[name] = contents;
}
// implements SourceTree -------------------------------------------
io::ZeroCopyInputStream* Open(const string& filename) {
io::ZeroCopyInputStream* Open(const std::string& filename) {
const char* contents = FindPtrOrNull(files_, filename);
if (contents == NULL) {
return NULL;
@ -107,12 +107,10 @@ class MockSourceTree : public SourceTree {
}
}
string GetLastErrorMessage() {
return "File not found.";
}
std::string GetLastErrorMessage() { return "File not found."; }
private:
std::unordered_map<string, const char*> files_;
std::unordered_map<std::string, const char*> files_;
};
// ===================================================================
@ -122,13 +120,13 @@ class ImporterTest : public testing::Test {
ImporterTest()
: importer_(&source_tree_, &error_collector_) {}
void AddFile(const string& filename, const char* text) {
void AddFile(const std::string& filename, const char* text) {
source_tree_.AddFile(filename, text);
}
// Return the collected error text
string error() const { return error_collector_.text_; }
string warning() const { return error_collector_.warning_text_; }
std::string error() const { return error_collector_.text_; }
std::string warning() const { return error_collector_.warning_text_; }
MockErrorCollector error_collector_;
MockSourceTree source_tree_;
@ -255,22 +253,22 @@ class DiskSourceTreeTest : public testing::Test {
}
}
void AddFile(const string& filename, const char* contents) {
void AddFile(const std::string& filename, const char* contents) {
GOOGLE_CHECK_OK(File::SetContents(filename, contents, true));
}
void AddSubdir(const string& dirname) {
void AddSubdir(const std::string& dirname) {
GOOGLE_CHECK_OK(File::CreateDir(dirname, 0777));
}
void ExpectFileContents(const string& filename,
void ExpectFileContents(const std::string& filename,
const char* expected_contents) {
std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename));
ASSERT_FALSE(input == NULL);
// Read all the data from the file.
string file_contents;
std::string file_contents;
const void* data;
int size;
while (input->Next(&data, &size)) {
@ -280,8 +278,8 @@ class DiskSourceTreeTest : public testing::Test {
EXPECT_EQ(expected_contents, file_contents);
}
void ExpectCannotOpenFile(const string& filename,
const string& error_message) {
void ExpectCannotOpenFile(const std::string& filename,
const std::string& error_message) {
std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename));
EXPECT_TRUE(input == NULL);
EXPECT_EQ(error_message, source_tree_.GetLastErrorMessage());
@ -290,7 +288,7 @@ class DiskSourceTreeTest : public testing::Test {
DiskSourceTree source_tree_;
// Paths of two on-disk directories to use during the test.
std::vector<string> dirnames_;
std::vector<std::string> dirnames_;
};
TEST_F(DiskSourceTreeTest, MapRoot) {
@ -394,8 +392,8 @@ TEST_F(DiskSourceTreeTest, DiskFileToVirtualFile) {
source_tree_.MapPath("bar", dirnames_[0]);
source_tree_.MapPath("bar", dirnames_[1]);
string virtual_file;
string shadowing_disk_file;
std::string virtual_file;
std::string shadowing_disk_file;
EXPECT_EQ(DiskSourceTree::NO_MAPPING,
source_tree_.DiskFileToVirtualFile(
@ -428,8 +426,8 @@ TEST_F(DiskSourceTreeTest, DiskFileToVirtualFileCanonicalization) {
source_tree_.MapPath("", "/qux");
source_tree_.MapPath("dir5", "/quux/");
string virtual_file;
string shadowing_disk_file;
std::string virtual_file;
std::string shadowing_disk_file;
// "../.." should not be considered to be under "..".
EXPECT_EQ(DiskSourceTree::NO_MAPPING,
@ -495,14 +493,14 @@ TEST_F(DiskSourceTreeTest, VirtualFileToDiskFile) {
source_tree_.MapPath("bar", dirnames_[1]);
// Existent files, shadowed and non-shadowed case.
string disk_file;
std::string disk_file;
EXPECT_TRUE(source_tree_.VirtualFileToDiskFile("bar/foo", &disk_file));
EXPECT_EQ(dirnames_[0] + "/foo", disk_file);
EXPECT_TRUE(source_tree_.VirtualFileToDiskFile("bar/quux", &disk_file));
EXPECT_EQ(dirnames_[1] + "/quux", disk_file);
// Nonexistent file in existent directory and vice versa.
string not_touched = "not touched";
std::string not_touched = "not touched";
EXPECT_FALSE(source_tree_.VirtualFileToDiskFile("bar/baz", &not_touched));
EXPECT_EQ("not touched", not_touched);
EXPECT_FALSE(source_tree_.VirtualFileToDiskFile("baz/foo", &not_touched));

@ -59,9 +59,9 @@ namespace {
// Whether two fields have conflicting accessors (assuming name1 and name2
// are different). name1 and name2 are field1 and field2's camel-case name
// respectively.
bool IsConflicting(const FieldDescriptor* field1, const string& name1,
const FieldDescriptor* field2, const string& name2,
string* info) {
bool IsConflicting(const FieldDescriptor* field1, const std::string& name1,
const FieldDescriptor* field2, const std::string& name2,
std::string* info) {
if (field1->is_repeated()) {
if (field2->is_repeated()) {
// Both fields are repeated.
@ -129,13 +129,13 @@ void Context::InitializeFieldGeneratorInfoForFields(
// Find out all fields that conflict with some other field in the same
// message.
std::vector<bool> is_conflict(fields.size());
std::vector<string> conflict_reason(fields.size());
std::vector<std::string> conflict_reason(fields.size());
for (int i = 0; i < fields.size(); ++i) {
const FieldDescriptor* field = fields[i];
const string& name = UnderscoresToCapitalizedCamelCase(field);
const std::string& name = UnderscoresToCapitalizedCamelCase(field);
for (int j = i + 1; j < fields.size(); ++j) {
const FieldDescriptor* other = fields[j];
const string& other_name = UnderscoresToCapitalizedCamelCase(other);
const std::string& other_name = UnderscoresToCapitalizedCamelCase(other);
if (name == other_name) {
is_conflict[i] = is_conflict[j] = true;
conflict_reason[i] = conflict_reason[j] =

@ -44,13 +44,13 @@ namespace protobuf {
namespace compiler {
namespace java {
string EscapeJavadoc(const string& input) {
string result;
std::string EscapeJavadoc(const std::string& input) {
std::string result;
result.reserve(input.size() * 2);
char prev = '*';
for (string::size_type i = 0; i < input.size(); i++) {
for (std::string::size_type i = 0; i < input.size(); i++) {
char c = input[i];
switch (c) {
case '*':
@ -104,8 +104,9 @@ string EscapeJavadoc(const string& input) {
static void WriteDocCommentBodyForLocation(
io::Printer* printer, const SourceLocation& location) {
string comments = location.leading_comments.empty() ?
location.trailing_comments : location.leading_comments;
std::string comments = location.leading_comments.empty()
? location.trailing_comments
: location.leading_comments;
if (!comments.empty()) {
// TODO(kenton): Ideally we should parse the comment text as Markdown and
// write it back as HTML, but this requires a Markdown parser. For now
@ -115,7 +116,7 @@ static void WriteDocCommentBodyForLocation(
// HTML-escape them so that they don't accidentally close the doc comment.
comments = EscapeJavadoc(comments);
std::vector<string> lines = Split(comments, "\n");
std::vector<std::string> lines = Split(comments, "\n");
while (!lines.empty() && lines.back().empty()) {
lines.pop_back();
}
@ -146,11 +147,11 @@ static void WriteDocCommentBody(
}
}
static string FirstLineOf(const string& value) {
string result = value;
static std::string FirstLineOf(const std::string& value) {
std::string result = value;
string::size_type pos = result.find_first_of('\n');
if (pos != string::npos) {
std::string::size_type pos = result.find_first_of('\n');
if (pos != std::string::npos) {
result.erase(pos);
}

@ -85,7 +85,7 @@ void EnumGenerator::Generate(io::Printer* printer) {
printer->Indent();
bool ordinal_is_index = true;
string index_text = "ordinal()";
std::string index_text = "ordinal()";
for (int i = 0; i < canonical_values_.size(); i++) {
if (canonical_values_[i]->index() != i) {
ordinal_is_index = false;
@ -95,7 +95,7 @@ void EnumGenerator::Generate(io::Printer* printer) {
}
for (int i = 0; i < canonical_values_.size(); i++) {
std::map<string, string> vars;
std::map<std::string, std::string> vars;
vars["name"] = canonical_values_[i]->name();
vars["index"] = StrCat(canonical_values_[i]->index());
vars["number"] = StrCat(canonical_values_[i]->number());
@ -129,7 +129,7 @@ void EnumGenerator::Generate(io::Printer* printer) {
// -----------------------------------------------------------------
for (int i = 0; i < aliases_.size(); i++) {
std::map<string, string> vars;
std::map<std::string, std::string> vars;
vars["classname"] = descriptor_->name();
vars["name"] = aliases_[i].value->name();
vars["canonical_name"] = aliases_[i].canonical_value->name();
@ -140,7 +140,7 @@ void EnumGenerator::Generate(io::Printer* printer) {
}
for (int i = 0; i < descriptor_->value_count(); i++) {
std::map<string, string> vars;
std::map<std::string, std::string> vars;
vars["name"] = descriptor_->value(i)->name();
vars["number"] = StrCat(descriptor_->value(i)->number());
vars["{"] = "";

@ -54,12 +54,10 @@ namespace java {
namespace {
void SetEnumVariables(const FieldDescriptor* descriptor,
int messageBitIndex,
int builderBitIndex,
const FieldGeneratorInfo* info,
void SetEnumVariables(const FieldDescriptor* descriptor, int messageBitIndex,
int builderBitIndex, const FieldGeneratorInfo* info,
ClassNameResolver* name_resolver,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
SetCommonFieldVariables(descriptor, info, variables);
(*variables)["type"] =
@ -369,7 +367,7 @@ GenerateHashCode(io::Printer* printer) const {
"hash = (53 * hash) + $name$_;\n");
}
string ImmutableEnumFieldGenerator::GetBoxedType() const {
std::string ImmutableEnumFieldGenerator::GetBoxedType() const {
return name_resolver_->GetImmutableClassName(descriptor_->enum_type());
}
@ -996,7 +994,7 @@ GenerateHashCode(io::Printer* printer) const {
"}\n");
}
string RepeatedImmutableEnumFieldGenerator::GetBoxedType() const {
std::string RepeatedImmutableEnumFieldGenerator::GetBoxedType() const {
return name_resolver_->GetImmutableClassName(descriptor_->enum_type());
}

@ -54,12 +54,10 @@ namespace java {
namespace {
void SetEnumVariables(const FieldDescriptor* descriptor,
int messageBitIndex,
int builderBitIndex,
const FieldGeneratorInfo* info,
void SetEnumVariables(const FieldDescriptor* descriptor, int messageBitIndex,
int builderBitIndex, const FieldGeneratorInfo* info,
ClassNameResolver* name_resolver,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
SetCommonFieldVariables(descriptor, info, variables);
(*variables)["type"] =
@ -352,7 +350,7 @@ GenerateHashCode(io::Printer* printer) const {
"hash = (53 * hash) + $name$_;\n");
}
string ImmutableEnumFieldLiteGenerator::GetBoxedType() const {
std::string ImmutableEnumFieldLiteGenerator::GetBoxedType() const {
return name_resolver_->GetImmutableClassName(descriptor_->enum_type());
}
@ -999,7 +997,7 @@ GenerateHashCode(io::Printer* printer) const {
"}\n");
}
string RepeatedImmutableEnumFieldLiteGenerator::GetBoxedType() const {
std::string RepeatedImmutableEnumFieldLiteGenerator::GetBoxedType() const {
return name_resolver_->GetImmutableClassName(descriptor_->enum_type());
}

@ -86,7 +86,7 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
printer->Indent();
for (int i = 0; i < canonical_values_.size(); i++) {
std::map<string, string> vars;
std::map<std::string, std::string> vars;
vars["name"] = canonical_values_[i]->name();
vars["number"] = StrCat(canonical_values_[i]->number());
WriteEnumValueDocComment(printer, canonical_values_[i]);
@ -110,7 +110,7 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
// -----------------------------------------------------------------
for (int i = 0; i < aliases_.size(); i++) {
std::map<string, string> vars;
std::map<std::string, std::string> vars;
vars["classname"] = descriptor_->name();
vars["name"] = aliases_[i].value->name();
vars["canonical_name"] = aliases_[i].canonical_value->name();
@ -121,7 +121,7 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
}
for (int i = 0; i < descriptor_->value_count(); i++) {
std::map<string, string> vars;
std::map<std::string, std::string> vars;
vars["name"] = descriptor_->value(i)->name();
vars["number"] = StrCat(descriptor_->value(i)->number());
vars["{"] = "";

@ -63,9 +63,10 @@ ImmutableExtensionGenerator::~ImmutableExtensionGenerator() {}
// Initializes the vars referenced in the generated code templates.
void ExtensionGenerator::InitTemplateVars(
const FieldDescriptor* descriptor, const string& scope, bool immutable,
ClassNameResolver* name_resolver, std::map<string, string>* vars_pointer) {
std::map<string, string> &vars = *vars_pointer;
const FieldDescriptor* descriptor, const std::string& scope, bool immutable,
ClassNameResolver* name_resolver,
std::map<std::string, std::string>* vars_pointer) {
std::map<std::string, std::string>& vars = *vars_pointer;
vars["scope"] = scope;
vars["name"] = UnderscoresToCamelCase(descriptor);
vars["containing_type"] =
@ -81,7 +82,7 @@ void ExtensionGenerator::InitTemplateVars(
vars["prototype"] = "null";
JavaType java_type = GetJavaType(descriptor);
string singular_type;
std::string singular_type;
switch (java_type) {
case JAVATYPE_MESSAGE:
singular_type = name_resolver->GetClassName(descriptor->message_type(),
@ -109,7 +110,7 @@ void ExtensionGenerator::InitTemplateVars(
}
void ImmutableExtensionGenerator::Generate(io::Printer* printer) {
std::map<string, string> vars;
std::map<std::string, std::string> vars;
const bool kUseImmutableNames = true;
InitTemplateVars(descriptor_, scope_, kUseImmutableNames, name_resolver_,
&vars);

@ -79,10 +79,10 @@ class ExtensionGenerator {
virtual int GenerateRegistrationCode(io::Printer* printer) = 0;
protected:
static void InitTemplateVars(const FieldDescriptor* descriptor,
const std::string& scope, bool immutable,
ClassNameResolver* name_resolver,
std::map<std::string, std::string>* vars_pointer);
static void InitTemplateVars(
const FieldDescriptor* descriptor, const std::string& scope,
bool immutable, ClassNameResolver* name_resolver,
std::map<std::string, std::string>* vars_pointer);
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);

@ -57,7 +57,7 @@ ImmutableExtensionLiteGenerator::ImmutableExtensionLiteGenerator(
ImmutableExtensionLiteGenerator::~ImmutableExtensionLiteGenerator() {}
void ImmutableExtensionLiteGenerator::Generate(io::Printer* printer) {
std::map<string, string> vars;
std::map<std::string, std::string> vars;
const bool kUseImmutableNames = true;
InitTemplateVars(descriptor_, scope_, kUseImmutableNames, name_resolver_,
&vars);

@ -248,7 +248,7 @@ FieldGeneratorMap<ImmutableFieldLiteGenerator>::~FieldGeneratorMap() {}
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
const FieldGeneratorInfo* info,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
(*variables)["field_name"] = descriptor->name();
(*variables)["name"] = info->name;
(*variables)["classname"] = descriptor->containing_type()->name();
@ -266,7 +266,7 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
void SetCommonOneofVariables(const FieldDescriptor* descriptor,
const OneofGeneratorInfo* info,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
(*variables)["oneof_name"] = info->name;
(*variables)["oneof_capitalized_name"] = info->capitalized_name;
(*variables)["oneof_index"] =
@ -279,9 +279,9 @@ void SetCommonOneofVariables(const FieldDescriptor* descriptor,
info->name + "Case_ == " + StrCat(descriptor->number());
}
void PrintExtraFieldInfo(const std::map<string, string>& variables,
void PrintExtraFieldInfo(const std::map<std::string, std::string>& variables,
io::Printer* printer) {
const std::map<string, string>::const_iterator it =
const std::map<std::string, std::string>::const_iterator it =
variables.find("disambiguated_reason");
if (it != variables.end() && !it->second.empty()) {
printer->Print(

@ -120,7 +120,7 @@ bool CollectExtensions(const Message& message,
void CollectExtensions(const FileDescriptorProto& file_proto,
const DescriptorPool& alternate_pool,
FieldDescriptorSet* extensions,
const string& file_data) {
const std::string& file_data) {
if (!CollectExtensions(file_proto, extensions)) {
// There are unknown fields in the file_proto, which are probably
// extensions. We need to parse the data into a dynamic message based on the
@ -208,12 +208,13 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options,
FileGenerator::~FileGenerator() {}
bool FileGenerator::Validate(string* error) {
bool FileGenerator::Validate(std::string* error) {
// Check that no class name matches the file's class name. This is a common
// problem that leads to Java compile errors that can be hard to understand.
// It's especially bad when using the java_multiple_files, since we would
// end up overwriting the outer class with one of the inner ones.
if (name_resolver_->HasConflictingClassName(file_, classname_)) {
if (name_resolver_->HasConflictingClassName(file_, classname_,
NameEquality::EXACT_EQUAL)) {
error->assign(file_->name());
error->append(
": Cannot generate Java output because the file's outer class name, \"");
@ -224,6 +225,20 @@ bool FileGenerator::Validate(string* error) {
"option to specify a different outer class name for the .proto file.");
return false;
}
// Similar to the check above, but ignore the case this time. This is not a
// problem on Linux, but will lead to Java compile errors on Windows / Mac
// because filenames are case-insensitive on those platforms.
if (name_resolver_->HasConflictingClassName(
file_, classname_, NameEquality::EQUAL_IGNORE_CASE)) {
GOOGLE_LOG(WARNING)
<< file_->name() << ": The file's outer class name, \"" << classname_
<< "\", matches the name of one of the types declared inside it when "
<< "case is ignored. This can cause compilation issues on Windows / "
<< "MacOS. Please either rename the type or use the "
<< "java_outer_classname option to specify a different outer class "
<< "name for the .proto file to be safe.";
}
// Print a warning if optimize_for = LITE_RUNTIME is used.
if (file_->options().optimize_for() == FileOptions::LITE_RUNTIME) {
GOOGLE_LOG(WARNING)
@ -430,7 +445,7 @@ void FileGenerator::GenerateDescriptorInitializationCodeForImmutable(
// reflections to find all extension fields
FileDescriptorProto file_proto;
file_->CopyTo(&file_proto);
string file_data;
std::string file_data;
file_proto.SerializeToString(&file_data);
FieldDescriptorSet extensions;
CollectExtensions(file_proto, *file_->pool(), &extensions, file_data);
@ -461,7 +476,7 @@ void FileGenerator::GenerateDescriptorInitializationCodeForImmutable(
// Force descriptor initialization of all dependencies.
for (int i = 0; i < file_->dependency_count(); i++) {
if (ShouldIncludeDependency(file_->dependency(i), true)) {
string dependency =
std::string dependency =
name_resolver_->GetImmutableClassName(file_->dependency(i));
printer->Print(
"$dependency$.getDescriptor();\n",
@ -501,7 +516,7 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer*
// custom options are only represented with immutable messages.
FileDescriptorProto file_proto;
file_->CopyTo(&file_proto);
string file_data;
std::string file_data;
file_proto.SerializeToString(&file_data);
FieldDescriptorSet extensions;
CollectExtensions(file_proto, *file_->pool(), &extensions, file_data);
@ -530,7 +545,7 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer*
FieldDescriptorSet::iterator it;
for (it = extensions.begin(); it != extensions.end(); it++) {
const FieldDescriptor* field = *it;
string scope;
std::string scope;
if (field->extension_scope() != NULL) {
scope = name_resolver_->GetMutableClassName(field->extension_scope()) +
".getDescriptor()";
@ -566,8 +581,8 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer*
// Force descriptor initialization of all dependencies.
for (int i = 0; i < file_->dependency_count(); i++) {
if (ShouldIncludeDependency(file_->dependency(i), false)) {
string dependency = name_resolver_->GetMutableClassName(
file_->dependency(i));
std::string dependency =
name_resolver_->GetMutableClassName(file_->dependency(i));
printer->Print(
"$dependency$.getDescriptor();\n",
"dependency", dependency);
@ -580,18 +595,17 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer*
}
template <typename GeneratorClass, typename DescriptorClass>
static void GenerateSibling(const string& package_dir,
const string& java_package,
const DescriptorClass* descriptor,
GeneratorContext* context,
std::vector<string>* file_list, bool annotate_code,
std::vector<string>* annotation_list,
const string& name_suffix,
GeneratorClass* generator,
void (GeneratorClass::*pfn)(io::Printer* printer)) {
string filename = package_dir + descriptor->name() + name_suffix + ".java";
static void GenerateSibling(
const std::string& package_dir, const std::string& java_package,
const DescriptorClass* descriptor, GeneratorContext* context,
std::vector<std::string>* file_list, bool annotate_code,
std::vector<std::string>* annotation_list, const std::string& name_suffix,
GeneratorClass* generator,
void (GeneratorClass::*pfn)(io::Printer* printer)) {
std::string filename =
package_dir + descriptor->name() + name_suffix + ".java";
file_list->push_back(filename);
string info_full_path = filename + ".pb.meta";
std::string info_full_path = filename + ".pb.meta";
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
&annotations);
@ -622,10 +636,10 @@ static void GenerateSibling(const string& package_dir,
}
}
void FileGenerator::GenerateSiblings(const string& package_dir,
GeneratorContext* context,
std::vector<string>* file_list,
std::vector<string>* annotation_list) {
void FileGenerator::GenerateSiblings(
const std::string& package_dir, GeneratorContext* context,
std::vector<std::string>* file_list,
std::vector<std::string>* annotation_list) {
if (MultipleJavaFiles(file_, immutable_api_)) {
for (int i = 0; i < file_->enum_type_count(); i++) {
if (HasDescriptorMethods(file_, context_->EnforceLite())) {

@ -59,14 +59,13 @@ JavaGenerator::JavaGenerator() {}
JavaGenerator::~JavaGenerator() {}
bool JavaGenerator::Generate(const FileDescriptor* file,
const string& parameter,
const std::string& parameter,
GeneratorContext* context,
string* error) const {
std::string* error) const {
// -----------------------------------------------------------------
// parse generator options
std::vector<std::pair<string, string> > options;
std::vector<std::pair<std::string, std::string> > options;
ParseGeneratorParameter(parameter, &options);
Options file_options;
@ -105,8 +104,8 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
// -----------------------------------------------------------------
std::vector<string> all_files;
std::vector<string> all_annotations;
std::vector<std::string> all_files;
std::vector<std::string> all_annotations;
std::vector<FileGenerator*> file_generators;
@ -131,13 +130,13 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
for (int i = 0; i < file_generators.size(); ++i) {
FileGenerator* file_generator = file_generators[i];
string package_dir = JavaPackageToDir(file_generator->java_package());
std::string package_dir = JavaPackageToDir(file_generator->java_package());
string java_filename = package_dir;
std::string java_filename = package_dir;
java_filename += file_generator->classname();
java_filename += ".java";
all_files.push_back(java_filename);
string info_full_path = java_filename + ".pb.meta";
std::string info_full_path = java_filename + ".pb.meta";
if (file_options.annotate_code) {
all_annotations.push_back(info_full_path);
}

@ -57,10 +57,8 @@ class PROTOC_EXPORT JavaGenerator : public CodeGenerator {
~JavaGenerator();
// implements CodeGenerator ----------------------------------------
bool Generate(const FileDescriptor* file,
const std::string& parameter,
GeneratorContext* context,
std::string* error) const;
bool Generate(const FileDescriptor* file, const std::string& parameter,
GeneratorContext* context, std::string* error) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(JavaGenerator);

@ -78,7 +78,7 @@ const char* kForbiddenWordList[] = {
const int kDefaultLookUpStartFieldNumber = 40;
bool IsForbidden(const string& field_name) {
bool IsForbidden(const std::string& field_name) {
for (int i = 0; i < GOOGLE_ARRAYSIZE(kForbiddenWordList); ++i) {
if (field_name == kForbiddenWordList[i]) {
return true;
@ -87,8 +87,8 @@ bool IsForbidden(const string& field_name) {
return false;
}
string FieldName(const FieldDescriptor* field) {
string field_name;
std::string FieldName(const FieldDescriptor* field) {
std::string field_name;
// Groups are hacky: The name of the field is just the lower-cased name
// of the group type. In Java, though, we would like to retain the original
// capitalization of the type name.
@ -123,11 +123,11 @@ bool ShouldUseTable(int lo, int hi, int number_of_fields) {
} // namespace
void PrintGeneratedAnnotation(io::Printer* printer, char delimiter,
const string& annotation_file) {
const std::string& annotation_file) {
if (annotation_file.empty()) {
return;
}
string ptemplate =
std::string ptemplate =
"@javax.annotation.Generated(value=\"protoc\", comments=\"annotations:";
ptemplate.push_back(delimiter);
ptemplate.append("annotation_file");
@ -138,10 +138,9 @@ void PrintGeneratedAnnotation(io::Printer* printer, char delimiter,
void PrintEnumVerifierLogic(io::Printer* printer,
const FieldDescriptor* descriptor,
const std::map<string, string>& variables,
const std::map<std::string, std::string>& variables,
const char* var_name,
const char* terminating_string,
bool enforce_lite) {
const char* terminating_string, bool enforce_lite) {
std::string enum_verifier_string =
(descriptor->enum_type()->file()->options().optimize_for() ==
FileOptions::LITE_RUNTIME) || enforce_lite
@ -159,8 +158,9 @@ void PrintEnumVerifierLogic(io::Printer* printer,
StrCat(enum_verifier_string, terminating_string).c_str());
}
string UnderscoresToCamelCase(const string& input, bool cap_next_letter) {
string result;
std::string UnderscoresToCamelCase(const std::string& input,
bool cap_next_letter) {
std::string result;
// Note: I distrust ctype.h due to locales.
for (int i = 0; i < input.size(); i++) {
if ('a' <= input[i] && input[i] <= 'z') {
@ -194,35 +194,35 @@ string UnderscoresToCamelCase(const string& input, bool cap_next_letter) {
return result;
}
string UnderscoresToCamelCase(const FieldDescriptor* field) {
std::string UnderscoresToCamelCase(const FieldDescriptor* field) {
return UnderscoresToCamelCase(FieldName(field), false);
}
string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) {
std::string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) {
return UnderscoresToCamelCase(FieldName(field), true);
}
string CapitalizedFieldName(const FieldDescriptor* field) {
std::string CapitalizedFieldName(const FieldDescriptor* field) {
return UnderscoresToCapitalizedCamelCase(field);
}
string UnderscoresToCamelCase(const MethodDescriptor* method) {
std::string UnderscoresToCamelCase(const MethodDescriptor* method) {
return UnderscoresToCamelCase(method->name(), false);
}
string UniqueFileScopeIdentifier(const Descriptor* descriptor) {
std::string UniqueFileScopeIdentifier(const Descriptor* descriptor) {
return "static_" + StringReplace(descriptor->full_name(), ".", "_", true);
}
string CamelCaseFieldName(const FieldDescriptor* field) {
string fieldName = UnderscoresToCamelCase(field);
std::string CamelCaseFieldName(const FieldDescriptor* field) {
std::string fieldName = UnderscoresToCamelCase(field);
if ('0' <= fieldName[0] && fieldName[0] <= '9') {
return '_' + fieldName;
}
return fieldName;
}
string StripProto(const string& filename) {
std::string StripProto(const std::string& filename) {
if (HasSuffixString(filename, ".protodevel")) {
return StripSuffixString(filename, ".protodevel");
} else {
@ -230,13 +230,13 @@ string StripProto(const string& filename) {
}
}
string FileClassName(const FileDescriptor* file, bool immutable) {
std::string FileClassName(const FileDescriptor* file, bool immutable) {
ClassNameResolver name_resolver;
return name_resolver.GetFileClassName(file, immutable);
}
string FileJavaPackage(const FileDescriptor* file, bool immutable) {
string result;
std::string FileJavaPackage(const FileDescriptor* file, bool immutable) {
std::string result;
if (file->options().has_java_package()) {
result = file->options().java_package();
@ -251,22 +251,21 @@ string FileJavaPackage(const FileDescriptor* file, bool immutable) {
return result;
}
string FileJavaPackage(const FileDescriptor* file) {
std::string FileJavaPackage(const FileDescriptor* file) {
return FileJavaPackage(file, true /* immutable */);
}
string JavaPackageToDir(string package_name) {
string package_dir =
StringReplace(package_name, ".", "/", true);
std::string JavaPackageToDir(std::string package_name) {
std::string package_dir = StringReplace(package_name, ".", "/", true);
if (!package_dir.empty()) package_dir += "/";
return package_dir;
}
// TODO(xiaofeng): This function is only kept for it's publicly referenced.
// It should be removed after mutable API up-integration.
string ToJavaName(const string& full_name,
const FileDescriptor* file) {
string result;
std::string ToJavaName(const std::string& full_name,
const FileDescriptor* file) {
std::string result;
if (file->options().java_multiple_files()) {
result = FileJavaPackage(file);
} else {
@ -285,48 +284,48 @@ string ToJavaName(const string& full_name,
return result;
}
string ClassName(const Descriptor* descriptor) {
std::string ClassName(const Descriptor* descriptor) {
ClassNameResolver name_resolver;
return name_resolver.GetClassName(descriptor, true);
}
string ClassName(const EnumDescriptor* descriptor) {
std::string ClassName(const EnumDescriptor* descriptor) {
ClassNameResolver name_resolver;
return name_resolver.GetClassName(descriptor, true);
}
string ClassName(const ServiceDescriptor* descriptor) {
std::string ClassName(const ServiceDescriptor* descriptor) {
ClassNameResolver name_resolver;
return name_resolver.GetClassName(descriptor, true);
}
string ClassName(const FileDescriptor* descriptor) {
std::string ClassName(const FileDescriptor* descriptor) {
ClassNameResolver name_resolver;
return name_resolver.GetClassName(descriptor, true);
}
string ExtraMessageInterfaces(const Descriptor* descriptor) {
string interfaces = "// @@protoc_insertion_point(message_implements:"
+ descriptor->full_name() + ")";
std::string ExtraMessageInterfaces(const Descriptor* descriptor) {
std::string interfaces = "// @@protoc_insertion_point(message_implements:" +
descriptor->full_name() + ")";
return interfaces;
}
string ExtraBuilderInterfaces(const Descriptor* descriptor) {
string interfaces = "// @@protoc_insertion_point(builder_implements:"
+ descriptor->full_name() + ")";
std::string ExtraBuilderInterfaces(const Descriptor* descriptor) {
std::string interfaces = "// @@protoc_insertion_point(builder_implements:" +
descriptor->full_name() + ")";
return interfaces;
}
string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor) {
string interfaces = "// @@protoc_insertion_point(interface_extends:"
+ descriptor->full_name() + ")";
std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor) {
std::string interfaces = "// @@protoc_insertion_point(interface_extends:" +
descriptor->full_name() + ")";
return interfaces;
}
string FieldConstantName(const FieldDescriptor *field) {
string name = field->name() + "_FIELD_NUMBER";
std::string FieldConstantName(const FieldDescriptor* field) {
std::string name = field->name() + "_FIELD_NUMBER";
UpperString(&name);
return name;
}
@ -459,7 +458,7 @@ const char* FieldTypeName(FieldDescriptor::Type field_type) {
return NULL;
}
bool AllAscii(const string& text) {
bool AllAscii(const std::string& text) {
for (int i = 0; i < text.size(); i++) {
if ((text[i] & 0x80) != 0) {
return false;
@ -468,8 +467,8 @@ bool AllAscii(const string& text) {
return true;
}
string DefaultValue(const FieldDescriptor* field, bool immutable,
ClassNameResolver* name_resolver) {
std::string DefaultValue(const FieldDescriptor* field, bool immutable,
ClassNameResolver* name_resolver) {
// Switch on CppType since we need to know which default_value_* method
// of FieldDescriptor to call.
switch (field->cpp_type()) {
@ -622,69 +621,69 @@ const char* bit_masks[] = {
"0x80000000",
};
string GetBitFieldName(int index) {
string varName = "bitField";
std::string GetBitFieldName(int index) {
std::string varName = "bitField";
varName += StrCat(index);
varName += "_";
return varName;
}
string GetBitFieldNameForBit(int bitIndex) {
std::string GetBitFieldNameForBit(int bitIndex) {
return GetBitFieldName(bitIndex / 32);
}
namespace {
string GenerateGetBitInternal(const string& prefix, int bitIndex) {
string varName = prefix + GetBitFieldNameForBit(bitIndex);
std::string GenerateGetBitInternal(const std::string& prefix, int bitIndex) {
std::string varName = prefix + GetBitFieldNameForBit(bitIndex);
int bitInVarIndex = bitIndex % 32;
string mask = bit_masks[bitInVarIndex];
string result = "((" + varName + " & " + mask + ") != 0)";
std::string mask = bit_masks[bitInVarIndex];
std::string result = "((" + varName + " & " + mask + ") != 0)";
return result;
}
string GenerateSetBitInternal(const string& prefix, int bitIndex) {
string varName = prefix + GetBitFieldNameForBit(bitIndex);
std::string GenerateSetBitInternal(const std::string& prefix, int bitIndex) {
std::string varName = prefix + GetBitFieldNameForBit(bitIndex);
int bitInVarIndex = bitIndex % 32;
string mask = bit_masks[bitInVarIndex];
string result = varName + " |= " + mask;
std::string mask = bit_masks[bitInVarIndex];
std::string result = varName + " |= " + mask;
return result;
}
} // namespace
string GenerateGetBit(int bitIndex) {
std::string GenerateGetBit(int bitIndex) {
return GenerateGetBitInternal("", bitIndex);
}
string GenerateSetBit(int bitIndex) {
std::string GenerateSetBit(int bitIndex) {
return GenerateSetBitInternal("", bitIndex);
}
string GenerateClearBit(int bitIndex) {
string varName = GetBitFieldNameForBit(bitIndex);
std::string GenerateClearBit(int bitIndex) {
std::string varName = GetBitFieldNameForBit(bitIndex);
int bitInVarIndex = bitIndex % 32;
string mask = bit_masks[bitInVarIndex];
string result = varName + " = (" + varName + " & ~" + mask + ")";
std::string mask = bit_masks[bitInVarIndex];
std::string result = varName + " = (" + varName + " & ~" + mask + ")";
return result;
}
string GenerateGetBitFromLocal(int bitIndex) {
std::string GenerateGetBitFromLocal(int bitIndex) {
return GenerateGetBitInternal("from_", bitIndex);
}
string GenerateSetBitToLocal(int bitIndex) {
std::string GenerateSetBitToLocal(int bitIndex) {
return GenerateSetBitInternal("to_", bitIndex);
}
string GenerateGetBitMutableLocal(int bitIndex) {
std::string GenerateGetBitMutableLocal(int bitIndex) {
return GenerateGetBitInternal("mutable_", bitIndex);
}
string GenerateSetBitMutableLocal(int bitIndex) {
std::string GenerateSetBitMutableLocal(int bitIndex) {
return GenerateSetBitInternal("mutable_", bitIndex);
}
@ -947,7 +946,7 @@ int GetExperimentalJavaFieldType(const FieldDescriptor* field) {
}
// Escape a UTF-16 character to be embedded in a Java string.
void EscapeUtf16ToString(uint16 code, string* output) {
void EscapeUtf16ToString(uint16 code, std::string* output) {
if (code == '\t') {
output->append("\\t");
} else if (code == '\b') {

@ -68,12 +68,12 @@ void PrintEnumVerifierLogic(io::Printer* printer,
const FieldDescriptor* descriptor,
const std::map<std::string, std::string>& variables,
const char* var_name,
const char* terminating_string,
bool enforce_lite);
const char* terminating_string, bool enforce_lite);
// Converts a name to camel-case. If cap_first_letter is true, capitalize the
// first letter.
std::string UnderscoresToCamelCase(const std::string& name, bool cap_first_letter);
std::string UnderscoresToCamelCase(const std::string& name,
bool cap_first_letter);
// Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes
// "fooBarBaz" or "FooBarBaz", respectively.
std::string UnderscoresToCamelCase(const FieldDescriptor* field);
@ -114,7 +114,7 @@ std::string JavaPackageToDir(std::string package_name);
// TODO(xiaofeng): this method is deprecated and should be removed in the
// future.
std::string ToJavaName(const std::string& full_name,
const FileDescriptor* file);
const FileDescriptor* file);
// TODO(xiaofeng): the following methods are kept for they are exposed
// publicly in //net/proto2/compiler/java/public/names.h. They return
@ -179,7 +179,8 @@ inline bool IsOwnFile(const ServiceDescriptor* descriptor, bool immutable) {
// annotation data for that descriptor. `suffix` is usually empty, but may
// (e.g.) be "OrBuilder" for some generated interfaces.
template <typename Descriptor>
std::string AnnotationFileName(const Descriptor* descriptor, const std::string& suffix) {
std::string AnnotationFileName(const Descriptor* descriptor,
const std::string& suffix) {
return descriptor->name() + suffix + ".java.pb.meta";
}
@ -195,7 +196,7 @@ void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer,
// Get the unqualified name that should be used for a field's field
// number constant.
std::string FieldConstantName(const FieldDescriptor *field);
std::string FieldConstantName(const FieldDescriptor* field);
// Returns the type of the FieldDescriptor.
// This does nothing interesting for the open source release, but is used for
@ -230,9 +231,9 @@ const char* FieldTypeName(const FieldDescriptor::Type field_type);
class ClassNameResolver;
std::string DefaultValue(const FieldDescriptor* field, bool immutable,
ClassNameResolver* name_resolver);
ClassNameResolver* name_resolver);
inline std::string ImmutableDefaultValue(const FieldDescriptor* field,
ClassNameResolver* name_resolver) {
ClassNameResolver* name_resolver) {
return DefaultValue(field, true, name_resolver);
}
bool IsDefaultValueJavaDefault(const FieldDescriptor* field);

@ -57,9 +57,8 @@ const FieldDescriptor* ValueField(const FieldDescriptor* descriptor) {
return message->FindFieldByName("value");
}
string TypeName(const FieldDescriptor* field,
ClassNameResolver* name_resolver,
bool boxed) {
std::string TypeName(const FieldDescriptor* field,
ClassNameResolver* name_resolver, bool boxed) {
if (GetJavaType(field) == JAVATYPE_MESSAGE) {
return name_resolver->GetImmutableClassName(field->message_type());
} else if (GetJavaType(field) == JAVATYPE_ENUM) {
@ -70,17 +69,15 @@ string TypeName(const FieldDescriptor* field,
}
}
string WireType(const FieldDescriptor* field) {
std::string WireType(const FieldDescriptor* field) {
return "com.google.protobuf.WireFormat.FieldType." +
string(FieldTypeName(field->type()));
std::string(FieldTypeName(field->type()));
}
void SetMessageVariables(const FieldDescriptor* descriptor,
int messageBitIndex,
int builderBitIndex,
const FieldGeneratorInfo* info,
void SetMessageVariables(const FieldDescriptor* descriptor, int messageBitIndex,
int builderBitIndex, const FieldGeneratorInfo* info,
Context* context,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
SetCommonFieldVariables(descriptor, info, variables);
ClassNameResolver* name_resolver = context->GetNameResolver();
@ -92,7 +89,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
const JavaType valueJavaType = GetJavaType(value);
(*variables)["key_type"] = TypeName(key, name_resolver, false);
string boxed_key_type = TypeName(key, name_resolver, true);
std::string boxed_key_type = TypeName(key, name_resolver, true);
(*variables)["boxed_key_type"] = boxed_key_type;
// Used for calling the serialization function.
(*variables)["short_key_type"] =
@ -787,7 +784,7 @@ GenerateHashCode(io::Printer* printer) const {
"}\n");
}
string ImmutableMapFieldGenerator::GetBoxedType() const {
std::string ImmutableMapFieldGenerator::GetBoxedType() const {
return name_resolver_->GetImmutableClassName(descriptor_->message_type());
}

@ -57,9 +57,8 @@ const FieldDescriptor* ValueField(const FieldDescriptor* descriptor) {
return message->FindFieldByName("value");
}
string TypeName(const FieldDescriptor* field,
ClassNameResolver* name_resolver,
bool boxed) {
std::string TypeName(const FieldDescriptor* field,
ClassNameResolver* name_resolver, bool boxed) {
if (GetJavaType(field) == JAVATYPE_MESSAGE) {
return name_resolver->GetImmutableClassName(field->message_type());
} else if (GetJavaType(field) == JAVATYPE_ENUM) {
@ -70,17 +69,15 @@ string TypeName(const FieldDescriptor* field,
}
}
string WireType(const FieldDescriptor* field) {
std::string WireType(const FieldDescriptor* field) {
return "com.google.protobuf.WireFormat.FieldType." +
string(FieldTypeName(field->type()));
std::string(FieldTypeName(field->type()));
}
void SetMessageVariables(const FieldDescriptor* descriptor,
int messageBitIndex,
int builderBitIndex,
const FieldGeneratorInfo* info,
void SetMessageVariables(const FieldDescriptor* descriptor, int messageBitIndex,
int builderBitIndex, const FieldGeneratorInfo* info,
Context* context,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
SetCommonFieldVariables(descriptor, info, variables);
ClassNameResolver* name_resolver = context->GetNameResolver();
@ -900,7 +897,7 @@ GenerateHashCode(io::Printer* printer) const {
"}\n");
}
string ImmutableMapFieldLiteGenerator::GetBoxedType() const {
std::string ImmutableMapFieldLiteGenerator::GetBoxedType() const {
return name_resolver_->GetImmutableClassName(descriptor_->message_type());
}

@ -66,8 +66,8 @@ using internal::WireFormat;
using internal::WireFormatLite;
namespace {
string MapValueImmutableClassdName(const Descriptor* descriptor,
ClassNameResolver* name_resolver) {
std::string MapValueImmutableClassdName(const Descriptor* descriptor,
ClassNameResolver* name_resolver) {
const FieldDescriptor* value_field = descriptor->FindFieldByName("value");
GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type());
return name_resolver->GetImmutableClassName(value_field->message_type());
@ -103,7 +103,7 @@ void ImmutableMessageGenerator::GenerateStaticVariables(
// the outermost class in the file. This way, they will be initialized in
// a deterministic order.
std::map<string, string> vars;
std::map<std::string, std::string> vars;
vars["identifier"] = UniqueFileScopeIdentifier(descriptor_);
vars["index"] = StrCat(descriptor_->index());
vars["classname"] = name_resolver_->GetImmutableClassName(descriptor_);
@ -147,7 +147,7 @@ void ImmutableMessageGenerator::GenerateStaticVariables(
int ImmutableMessageGenerator::GenerateStaticVariableInitializers(
io::Printer* printer) {
int bytecode_estimate = 0;
std::map<string, string> vars;
std::map<std::string, std::string> vars;
vars["identifier"] = UniqueFileScopeIdentifier(descriptor_);
vars["index"] = StrCat(descriptor_->index());
vars["classname"] = name_resolver_->GetImmutableClassName(descriptor_);
@ -184,7 +184,7 @@ int ImmutableMessageGenerator::GenerateStaticVariableInitializers(
void ImmutableMessageGenerator::
GenerateFieldAccessorTable(io::Printer* printer, int* bytecode_estimate) {
std::map<string, string> vars;
std::map<std::string, std::string> vars;
vars["identifier"] = UniqueFileScopeIdentifier(descriptor_);
if (MultipleJavaFiles(descriptor_->file(), /* immutable = */ true)) {
// We can only make these package-private since the classes that use them
@ -296,7 +296,7 @@ void ImmutableMessageGenerator::GenerateInterface(io::Printer* printer) {
void ImmutableMessageGenerator::Generate(io::Printer* printer) {
bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true);
std::map<string, string> variables;
std::map<std::string, std::string> variables;
variables["static"] = is_own_file ? " " : " static ";
variables["classname"] = descriptor_->name();
variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_);
@ -309,7 +309,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
/* immutable = */ true);
// The builder_type stores the super type name of the nested Builder class.
string builder_type;
std::string builder_type;
if (descriptor_->extension_range_count() > 0) {
printer->Print(
variables,
@ -405,7 +405,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
}
// oneof
std::map<string, string> vars;
std::map<std::string, std::string> vars;
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
vars["oneof_name"] = context_->GetOneofGeneratorInfo(
descriptor_->oneof_decl(i))->name;

@ -61,8 +61,8 @@ namespace compiler {
namespace java {
namespace {
string MapValueImmutableClassdName(const Descriptor* descriptor,
ClassNameResolver* name_resolver) {
std::string MapValueImmutableClassdName(const Descriptor* descriptor,
ClassNameResolver* name_resolver) {
const FieldDescriptor* value_field = descriptor->FindFieldByName("value");
GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type());
return name_resolver->GetImmutableClassName(value_field->message_type());
@ -115,7 +115,7 @@ Generate(io::Printer* printer) {
}
// oneof
std::map<string, string> vars;
std::map<std::string, std::string> vars;
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
vars["oneof_name"] = context_->GetOneofGeneratorInfo(
descriptor_->oneof_decl(i))->name;

@ -89,7 +89,7 @@ Generate(io::Printer* printer) {
GenerateCommonBuilderMethods(printer);
// oneof
std::map<string, string> vars;
std::map<std::string, std::string> vars;
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
vars["oneof_name"] = context_->GetOneofGeneratorInfo(
descriptor_->oneof_decl(i))->name;

@ -51,12 +51,10 @@ namespace java {
namespace {
void SetMessageVariables(const FieldDescriptor* descriptor,
int messageBitIndex,
int builderBitIndex,
const FieldGeneratorInfo* info,
void SetMessageVariables(const FieldDescriptor* descriptor, int messageBitIndex,
int builderBitIndex, const FieldGeneratorInfo* info,
ClassNameResolver* name_resolver,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
SetCommonFieldVariables(descriptor, info, variables);
(*variables)["type"] =
@ -517,7 +515,7 @@ GenerateHashCode(io::Printer* printer) const {
"hash = (53 * hash) + get$capitalized_name$().hashCode();\n");
}
string ImmutableMessageFieldGenerator::GetBoxedType() const {
std::string ImmutableMessageFieldGenerator::GetBoxedType() const {
return name_resolver_->GetImmutableClassName(descriptor_->message_type());
}
@ -1320,7 +1318,7 @@ GenerateHashCode(io::Printer* printer) const {
"}\n");
}
string RepeatedImmutableMessageFieldGenerator::GetBoxedType() const {
std::string RepeatedImmutableMessageFieldGenerator::GetBoxedType() const {
return name_resolver_->GetImmutableClassName(descriptor_->message_type());
}

@ -52,12 +52,10 @@ namespace java {
namespace {
void SetMessageVariables(const FieldDescriptor* descriptor,
int messageBitIndex,
int builderBitIndex,
const FieldGeneratorInfo* info,
void SetMessageVariables(const FieldDescriptor* descriptor, int messageBitIndex,
int builderBitIndex, const FieldGeneratorInfo* info,
ClassNameResolver* name_resolver,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
SetCommonFieldVariables(descriptor, info, variables);
(*variables)["type"] =
@ -375,7 +373,7 @@ GenerateHashCode(io::Printer* printer) const {
"hash = (53 * hash) + get$capitalized_name$().hashCode();\n");
}
string ImmutableMessageFieldLiteGenerator::GetBoxedType() const {
std::string ImmutableMessageFieldLiteGenerator::GetBoxedType() const {
return name_resolver_->GetImmutableClassName(descriptor_->message_type());
}
@ -976,7 +974,7 @@ GenerateHashCode(io::Printer* printer) const {
"}\n");
}
string RepeatedImmutableMessageFieldLiteGenerator::GetBoxedType() const {
std::string RepeatedImmutableMessageFieldLiteGenerator::GetBoxedType() const {
return name_resolver_->GetImmutableClassName(descriptor_->message_type());
}

@ -74,8 +74,8 @@ bool EnableExperimentalRuntimeForLite() {
#endif // !PROTOBUF_EXPERIMENT
}
string MapValueImmutableClassdName(const Descriptor* descriptor,
ClassNameResolver* name_resolver) {
std::string MapValueImmutableClassdName(const Descriptor* descriptor,
ClassNameResolver* name_resolver) {
const FieldDescriptor* value_field = descriptor->FindFieldByName("value");
GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type());
return name_resolver->GetImmutableClassName(value_field->message_type());
@ -175,7 +175,7 @@ void ImmutableMessageLiteGenerator::GenerateInterface(io::Printer* printer) {
void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true);
std::map<string, string> variables;
std::map<std::string, std::string> variables;
variables["static"] = is_own_file ? " " : " static ";
variables["classname"] = descriptor_->name();
variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_);
@ -188,7 +188,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
// The builder_type stores the super type name of the nested Builder class.
string builder_type;
std::string builder_type;
if (descriptor_->extension_range_count() > 0) {
printer->Print(variables,
"$deprecation$public $static$final class $classname$ extends\n"
@ -241,7 +241,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
}
// oneof
std::map<string, string> vars;
std::map<std::string, std::string> vars;
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
vars["oneof_name"] = context_->GetOneofGeneratorInfo(oneof)->name;

@ -37,6 +37,7 @@
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/stubs/substitute.h>
namespace google {
namespace protobuf {
namespace compiler {
@ -52,8 +53,8 @@ const char* kOuterClassNameSuffix = "OuterClass";
// Full name : foo.Bar.Baz
// Package name: foo
// After strip : Bar.Baz
string StripPackageName(const string& full_name,
const FileDescriptor* file) {
std::string StripPackageName(const std::string& full_name,
const FileDescriptor* file) {
if (file->package().empty()) {
return full_name;
} else {
@ -63,15 +64,15 @@ string StripPackageName(const string& full_name,
}
// Get the name of a message's Java class without package name prefix.
string ClassNameWithoutPackage(const Descriptor* descriptor,
bool immutable) {
std::string ClassNameWithoutPackage(const Descriptor* descriptor,
bool immutable) {
return StripPackageName(descriptor->full_name(),
descriptor->file());
}
// Get the name of an enum's Java class without package name prefix.
string ClassNameWithoutPackage(const EnumDescriptor* descriptor,
bool immutable) {
std::string ClassNameWithoutPackage(const EnumDescriptor* descriptor,
bool immutable) {
// Doesn't append "Mutable" for enum type's name.
const Descriptor* message_descriptor = descriptor->containing_type();
if (message_descriptor == NULL) {
@ -83,26 +84,42 @@ string ClassNameWithoutPackage(const EnumDescriptor* descriptor,
}
// Get the name of a service's Java class without package name prefix.
string ClassNameWithoutPackage(const ServiceDescriptor* descriptor,
bool immutable) {
string full_name = StripPackageName(descriptor->full_name(),
descriptor->file());
std::string ClassNameWithoutPackage(const ServiceDescriptor* descriptor,
bool immutable) {
std::string full_name =
StripPackageName(descriptor->full_name(), descriptor->file());
// We don't allow nested service definitions.
GOOGLE_CHECK(full_name.find('.') == string::npos);
GOOGLE_CHECK(full_name.find('.') == std::string::npos);
return full_name;
}
// Return true if a and b are equals (case insensitive).
NameEquality CheckNameEquality(const string& a, const string& b) {
if (ToUpper(a) == ToUpper(b)) {
if (a == b) {
return NameEquality::EXACT_EQUAL;
}
return NameEquality::EQUAL_IGNORE_CASE;
}
return NameEquality::NO_MATCH;
}
// Check whether a given message or its nested types has the given class name.
bool MessageHasConflictingClassName(const Descriptor* message,
const string& classname) {
if (message->name() == classname) return true;
const std::string& classname,
NameEquality equality_mode) {
if (CheckNameEquality(message->name(), classname) == equality_mode) {
return true;
}
for (int i = 0; i < message->nested_type_count(); ++i) {
if (MessageHasConflictingClassName(message->nested_type(i), classname)) {
if (MessageHasConflictingClassName(message->nested_type(i), classname,
equality_mode)) {
return true;
}
}
for (int i = 0; i < message->enum_type_count(); ++i) {
if (message->enum_type(i)->name() == classname) {
if (CheckNameEquality(message->enum_type(i)->name(), classname) ==
equality_mode) {
return true;
}
}
@ -117,11 +134,11 @@ ClassNameResolver::ClassNameResolver() {
ClassNameResolver::~ClassNameResolver() {
}
string ClassNameResolver::GetFileDefaultImmutableClassName(
std::string ClassNameResolver::GetFileDefaultImmutableClassName(
const FileDescriptor* file) {
string basename;
string::size_type last_slash = file->name().find_last_of('/');
if (last_slash == string::npos) {
std::string basename;
std::string::size_type last_slash = file->name().find_last_of('/');
if (last_slash == std::string::npos) {
basename = file->name();
} else {
basename = file->name().substr(last_slash + 1);
@ -129,15 +146,16 @@ string ClassNameResolver::GetFileDefaultImmutableClassName(
return UnderscoresToCamelCase(StripProto(basename), true);
}
string ClassNameResolver::GetFileImmutableClassName(
std::string ClassNameResolver::GetFileImmutableClassName(
const FileDescriptor* file) {
string& class_name = file_immutable_outer_class_names_[file];
std::string& class_name = file_immutable_outer_class_names_[file];
if (class_name.empty()) {
if (file->options().has_java_outer_classname()) {
class_name = file->options().java_outer_classname();
} else {
class_name = GetFileDefaultImmutableClassName(file);
if (HasConflictingClassName(file, class_name)) {
if (HasConflictingClassName(file, class_name,
NameEquality::EXACT_EQUAL)) {
class_name += kOuterClassNameSuffix;
}
}
@ -145,8 +163,8 @@ string ClassNameResolver::GetFileImmutableClassName(
return class_name;
}
string ClassNameResolver::GetFileClassName(const FileDescriptor* file,
bool immutable) {
std::string ClassNameResolver::GetFileClassName(const FileDescriptor* file,
bool immutable) {
if (immutable) {
return GetFileImmutableClassName(file);
} else {
@ -157,33 +175,37 @@ string ClassNameResolver::GetFileClassName(const FileDescriptor* file,
// Check whether there is any type defined in the proto file that has
// the given class name.
bool ClassNameResolver::HasConflictingClassName(
const FileDescriptor* file, const string& classname) {
const FileDescriptor* file, const std::string& classname,
NameEquality equality_mode) {
for (int i = 0; i < file->enum_type_count(); i++) {
if (file->enum_type(i)->name() == classname) {
if (CheckNameEquality(file->enum_type(i)->name(), classname) ==
equality_mode) {
return true;
}
}
for (int i = 0; i < file->service_count(); i++) {
if (file->service(i)->name() == classname) {
if (CheckNameEquality(file->service(i)->name(), classname) ==
equality_mode) {
return true;
}
}
for (int i = 0; i < file->message_type_count(); i++) {
if (MessageHasConflictingClassName(file->message_type(i), classname)) {
if (MessageHasConflictingClassName(file->message_type(i), classname,
equality_mode)) {
return true;
}
}
return false;
}
string ClassNameResolver::GetDescriptorClassName(
std::string ClassNameResolver::GetDescriptorClassName(
const FileDescriptor* descriptor) {
return GetFileImmutableClassName(descriptor);
}
string ClassNameResolver::GetClassName(const FileDescriptor* descriptor,
bool immutable) {
string result = FileJavaPackage(descriptor, immutable);
std::string ClassNameResolver::GetClassName(const FileDescriptor* descriptor,
bool immutable) {
std::string result = FileJavaPackage(descriptor, immutable);
if (!result.empty()) result += '.';
result += GetFileClassName(descriptor, immutable);
return result;
@ -191,11 +213,10 @@ string ClassNameResolver::GetClassName(const FileDescriptor* descriptor,
// Get the full name of a Java class by prepending the Java package name
// or outer class name.
string ClassNameResolver::GetClassFullName(const string& name_without_package,
const FileDescriptor* file,
bool immutable,
bool multiple_files) {
string result;
std::string ClassNameResolver::GetClassFullName(
const std::string& name_without_package, const FileDescriptor* file,
bool immutable, bool multiple_files) {
std::string result;
if (multiple_files) {
result = FileJavaPackage(file, immutable);
} else {
@ -208,33 +229,32 @@ string ClassNameResolver::GetClassFullName(const string& name_without_package,
return result;
}
string ClassNameResolver::GetClassName(const Descriptor* descriptor,
bool immutable) {
std::string ClassNameResolver::GetClassName(const Descriptor* descriptor,
bool immutable) {
return GetClassFullName(ClassNameWithoutPackage(descriptor, immutable),
descriptor->file(), immutable,
MultipleJavaFiles(descriptor->file(), immutable));
}
string ClassNameResolver::GetClassName(const EnumDescriptor* descriptor,
bool immutable) {
std::string ClassNameResolver::GetClassName(const EnumDescriptor* descriptor,
bool immutable) {
return GetClassFullName(ClassNameWithoutPackage(descriptor, immutable),
descriptor->file(), immutable,
MultipleJavaFiles(descriptor->file(), immutable));
}
string ClassNameResolver::GetClassName(const ServiceDescriptor* descriptor,
bool immutable) {
std::string ClassNameResolver::GetClassName(const ServiceDescriptor* descriptor,
bool immutable) {
return GetClassFullName(ClassNameWithoutPackage(descriptor, immutable),
descriptor->file(), immutable,
MultipleJavaFiles(descriptor->file(), immutable));
}
// Get the Java Class style full name of a message.
string ClassNameResolver::GetJavaClassFullName(
const string& name_without_package,
const FileDescriptor* file,
std::string ClassNameResolver::GetJavaClassFullName(
const std::string& name_without_package, const FileDescriptor* file,
bool immutable) {
string result;
std::string result;
if (MultipleJavaFiles(file, immutable)) {
result = FileJavaPackage(file, immutable);
if (!result.empty()) result += '.';
@ -246,21 +266,20 @@ string ClassNameResolver::GetJavaClassFullName(
return result;
}
string ClassNameResolver::GetExtensionIdentifierName(
std::string ClassNameResolver::GetExtensionIdentifierName(
const FieldDescriptor* descriptor, bool immutable) {
return GetClassName(descriptor->containing_type(), immutable) + "." +
descriptor->name();
}
string ClassNameResolver::GetJavaImmutableClassName(
std::string ClassNameResolver::GetJavaImmutableClassName(
const Descriptor* descriptor) {
return GetJavaClassFullName(
ClassNameWithoutPackage(descriptor, true),
descriptor->file(), true);
}
string ClassNameResolver::GetJavaImmutableClassName(
std::string ClassNameResolver::GetJavaImmutableClassName(
const EnumDescriptor* descriptor) {
return GetJavaClassFullName(
ClassNameWithoutPackage(descriptor, true),

@ -47,6 +47,9 @@ class ServiceDescriptor;
namespace compiler {
namespace java {
// Indicates how closely the two class names match.
enum NameEquality { NO_MATCH, EXACT_EQUAL, EQUAL_IGNORE_CASE };
// Used to get the Java class related names for a given descriptor. It caches
// the results to avoid redundant calculation across multiple name queries.
// Thread-safety note: This class is *not* thread-safe.
@ -66,7 +69,8 @@ class ClassNameResolver {
// Check whether there is any type defined in the proto file that has
// the given class name.
bool HasConflictingClassName(const FileDescriptor* file,
const std::string& classname);
const std::string& classname,
NameEquality equality_mode);
// Gets the name of the outer class that holds descriptor information.
// Descriptors are shared between immutable messages and mutable messages.
@ -80,18 +84,18 @@ class ClassNameResolver {
std::string GetClassName(const ServiceDescriptor* descriptor, bool immutable);
std::string GetClassName(const FileDescriptor* descriptor, bool immutable);
template<class DescriptorType>
template <class DescriptorType>
std::string GetImmutableClassName(const DescriptorType* descriptor) {
return GetClassName(descriptor, true);
}
template<class DescriptorType>
template <class DescriptorType>
std::string GetMutableClassName(const DescriptorType* descriptor) {
return GetClassName(descriptor, false);
}
// Gets the fully qualified name of an extension identifier.
std::string GetExtensionIdentifierName(const FieldDescriptor* descriptor,
bool immutable);
bool immutable);
// Gets the fully qualified name for generated classes in Java convention.
// Nested classes will be separated using '$' instead of '.'
@ -103,16 +107,14 @@ class ClassNameResolver {
// Get the full name of a Java class by prepending the Java package name
// or outer class name.
std::string GetClassFullName(const std::string& name_without_package,
const FileDescriptor* file,
bool immutable,
bool multiple_files);
const FileDescriptor* file, bool immutable,
bool multiple_files);
// Get the Java Class style full name of a message.
std::string GetJavaClassFullName(
const std::string& name_without_package,
const FileDescriptor* file,
bool immutable);
std::string GetJavaClassFullName(const std::string& name_without_package,
const FileDescriptor* file, bool immutable);
// Caches the result to provide better performance.
std::map<const FileDescriptor*, std::string> file_immutable_outer_class_names_;
std::map<const FileDescriptor*, std::string>
file_immutable_outer_class_names_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ClassNameResolver);
};

@ -58,10 +58,9 @@ class TestGenerator : public CodeGenerator {
~TestGenerator() {}
virtual bool Generate(const FileDescriptor* file,
const string& parameter,
GeneratorContext* context,
string* error) const {
string filename = "Test.java";
const std::string& parameter, GeneratorContext* context,
std::string* error) const {
std::string filename = "Test.java";
TryInsert(filename, "outer_class_scope", context);
TryInsert(filename, "class_scope:foo.Bar", context);
TryInsert(filename, "class_scope:foo.Bar.Baz", context);
@ -71,7 +70,8 @@ class TestGenerator : public CodeGenerator {
return true;
}
void TryInsert(const string& filename, const string& insertion_point,
void TryInsert(const std::string& filename,
const std::string& insertion_point,
GeneratorContext* context) const {
std::unique_ptr<io::ZeroCopyOutputStream> output(
context->OpenForInsert(filename, insertion_point));
@ -103,9 +103,9 @@ TEST(JavaPluginTest, PluginTest) {
cli.RegisterGenerator("--java_out", &java_generator, "");
cli.RegisterGenerator("--test_out", &test_generator, "");
string proto_path = "-I" + TestTempDir();
string java_out = "--java_out=" + TestTempDir();
string test_out = "--test_out=" + TestTempDir();
std::string proto_path = "-I" + TestTempDir();
std::string java_out = "--java_out=" + TestTempDir();
std::string test_out = "--test_out=" + TestTempDir();
const char* argv[] = {
"protoc",

@ -58,11 +58,10 @@ using internal::WireFormatLite;
namespace {
void SetPrimitiveVariables(const FieldDescriptor* descriptor,
int messageBitIndex,
int builderBitIndex,
int messageBitIndex, int builderBitIndex,
const FieldGeneratorInfo* info,
ClassNameResolver* name_resolver,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
SetCommonFieldVariables(descriptor, info, variables);
JavaType javaType = GetJavaType(descriptor);
@ -75,7 +74,7 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor,
javaType == JAVATYPE_FLOAT ||
javaType == JAVATYPE_INT ||
javaType == JAVATYPE_LONG) {
string capitalized_type = UnderscoresToCamelCase(
std::string capitalized_type = UnderscoresToCamelCase(
PrimitiveTypeName(javaType), /*cap_first_letter=*/true);
(*variables)["field_list_type"] =
"com.google.protobuf.Internal." + capitalized_type + "List";
@ -467,7 +466,7 @@ GenerateHashCode(io::Printer* printer) const {
}
}
string ImmutablePrimitiveFieldGenerator::GetBoxedType() const {
std::string ImmutablePrimitiveFieldGenerator::GetBoxedType() const {
return BoxedPrimitiveTypeName(GetJavaType(descriptor_));
}
@ -938,7 +937,7 @@ GenerateHashCode(io::Printer* printer) const {
"}\n");
}
string RepeatedImmutablePrimitiveFieldGenerator::GetBoxedType() const {
std::string RepeatedImmutablePrimitiveFieldGenerator::GetBoxedType() const {
return BoxedPrimitiveTypeName(GetJavaType(descriptor_));
}

@ -58,11 +58,10 @@ using internal::WireFormatLite;
namespace {
void SetPrimitiveVariables(const FieldDescriptor* descriptor,
int messageBitIndex,
int builderBitIndex,
int messageBitIndex, int builderBitIndex,
const FieldGeneratorInfo* info,
ClassNameResolver* name_resolver,
std::map<string, string>* variables) {
std::map<std::string, std::string>* variables) {
SetCommonFieldVariables(descriptor, info, variables);
JavaType javaType = GetJavaType(descriptor);
(*variables)["type"] = PrimitiveTypeName(javaType);
@ -77,8 +76,8 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor,
WireFormat::TagSize(descriptor->number(), GetType(descriptor)));
(*variables)["required"] = descriptor->is_required() ? "true" : "false";
string capitalized_type = UnderscoresToCamelCase(PrimitiveTypeName(javaType),
true /* cap_next_letter */);
std::string capitalized_type = UnderscoresToCamelCase(
PrimitiveTypeName(javaType), true /* cap_next_letter */);
switch (javaType) {
case JAVATYPE_INT:
case JAVATYPE_LONG:
@ -460,7 +459,7 @@ GenerateHashCode(io::Printer* printer) const {
}
}
string ImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const {
std::string ImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const {
return BoxedPrimitiveTypeName(GetJavaType(descriptor_));
}
@ -934,7 +933,7 @@ GenerateHashCode(io::Printer* printer) const {
"}\n");
}
string RepeatedImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const {
std::string RepeatedImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const {
return BoxedPrimitiveTypeName(GetJavaType(descriptor_));
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save