This commit is contained in:
iranl
2025-06-25 22:52:12 +02:00
parent 5fe5614686
commit 6c74d62531
519 changed files with 191600 additions and 5 deletions

View File

@@ -0,0 +1,163 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <protoc-c/c_bytes_field.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
#include <protobuf-c/protobuf-c.pb.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
using internal::WireFormat;
void SetBytesVariables(const FieldDescriptor* descriptor,
std::map<std::string, std::string>* variables) {
(*variables)["name"] = FieldName(descriptor);
(*variables)["default"] =
"\"" + CEscape(descriptor->default_value_string()) + "\"";
(*variables)["deprecated"] = FieldDeprecated(descriptor);
}
// ===================================================================
BytesFieldGenerator::
BytesFieldGenerator(const FieldDescriptor* descriptor)
: FieldGenerator(descriptor) {
SetBytesVariables(descriptor, &variables_);
variables_["default_value"] = descriptor->has_default_value()
? GetDefaultValue()
: std::string("{0,NULL}");
}
BytesFieldGenerator::~BytesFieldGenerator() {}
void BytesFieldGenerator::GenerateStructMembers(io::Printer* printer) const
{
switch (descriptor_->label()) {
case FieldDescriptor::LABEL_REQUIRED:
printer->Print(variables_, "ProtobufCBinaryData $name$$deprecated$;\n");
break;
case FieldDescriptor::LABEL_OPTIONAL:
if (descriptor_->containing_oneof() == NULL && FieldSyntax(descriptor_) == 2)
printer->Print(variables_, "protobuf_c_boolean has_$name$$deprecated$;\n");
printer->Print(variables_, "ProtobufCBinaryData $name$$deprecated$;\n");
break;
case FieldDescriptor::LABEL_REPEATED:
printer->Print(variables_, "size_t n_$name$$deprecated$;\n");
printer->Print(variables_, "ProtobufCBinaryData *$name$$deprecated$;\n");
break;
}
}
void BytesFieldGenerator::GenerateDefaultValueDeclarations(io::Printer* printer) const
{
std::map<std::string, std::string> vars;
vars["default_value_data"] = FullNameToLower(descriptor_->full_name(), descriptor_->file())
+ "__default_value_data";
printer->Print(vars, "extern uint8_t $default_value_data$[];\n");
}
void BytesFieldGenerator::GenerateDefaultValueImplementations(io::Printer* printer) const
{
std::map<std::string, std::string> vars;
vars["default_value_data"] = FullNameToLower(descriptor_->full_name(), descriptor_->file())
+ "__default_value_data";
vars["escaped"] = CEscape(descriptor_->default_value_string());
printer->Print(vars, "uint8_t $default_value_data$[] = \"$escaped$\";\n");
}
std::string BytesFieldGenerator::GetDefaultValue(void) const
{
return "{ "
+ SimpleItoa(descriptor_->default_value_string().size())
+ ", "
+ FullNameToLower(descriptor_->full_name(), descriptor_->file())
+ "__default_value_data }";
}
void BytesFieldGenerator::GenerateStaticInit(io::Printer* printer) const
{
switch (descriptor_->label()) {
case FieldDescriptor::LABEL_REQUIRED:
printer->Print(variables_, "$default_value$");
break;
case FieldDescriptor::LABEL_OPTIONAL:
if (FieldSyntax(descriptor_) == 2)
printer->Print(variables_, "0, ");
printer->Print(variables_, "$default_value$");
break;
case FieldDescriptor::LABEL_REPEATED:
// no support for default?
printer->Print("0,NULL");
break;
}
}
void BytesFieldGenerator::GenerateDescriptorInitializer(io::Printer* printer) const
{
GenerateDescriptorInitializerGeneric(printer, true, "BYTES", "NULL");
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,100 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_BYTES_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_C_BYTES_FIELD_H__
#include <map>
#include <string>
#include <protoc-c/c_field.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
class BytesFieldGenerator : public FieldGenerator {
public:
explicit BytesFieldGenerator(const FieldDescriptor* descriptor);
~BytesFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateStructMembers(io::Printer* printer) const;
void GenerateDescriptorInitializer(io::Printer* printer) const;
void GenerateDefaultValueDeclarations(io::Printer* printer) const;
void GenerateDefaultValueImplementations(io::Printer* printer) const;
std::string GetDefaultValue(void) const;
void GenerateStaticInit(io::Printer* printer) const;
private:
std::map<std::string, std::string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(BytesFieldGenerator);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_STRING_FIELD_H__

View File

@@ -0,0 +1,334 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <set>
#include <map>
#include <protoc-c/c_enum.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor,
const std::string& dllexport_decl)
: descriptor_(descriptor),
dllexport_decl_(dllexport_decl) {
}
EnumGenerator::~EnumGenerator() {}
void EnumGenerator::GenerateDefinition(io::Printer* printer) {
std::map<std::string, std::string> vars;
vars["classname"] = FullNameToC(descriptor_->full_name(), descriptor_->file());
vars["shortname"] = descriptor_->name();
vars["uc_name"] = FullNameToUpper(descriptor_->full_name(), descriptor_->file());
SourceLocation sourceLoc;
descriptor_->GetSourceLocation(&sourceLoc);
PrintComment (printer, sourceLoc.leading_comments);
printer->Print(vars, "typedef enum _$classname$ {\n");
printer->Indent();
const EnumValueDescriptor* min_value = descriptor_->value(0);
const EnumValueDescriptor* max_value = descriptor_->value(0);
vars["opt_comma"] = ",";
vars["prefix"] = FullNameToUpper(descriptor_->full_name(), descriptor_->file()) + "__";
for (int i = 0; i < descriptor_->value_count(); i++) {
vars["name"] = descriptor_->value(i)->name();
vars["number"] = SimpleItoa(descriptor_->value(i)->number());
if (i + 1 == descriptor_->value_count())
vars["opt_comma"] = "";
SourceLocation valSourceLoc;
descriptor_->value(i)->GetSourceLocation(&valSourceLoc);
PrintComment (printer, valSourceLoc.leading_comments);
PrintComment (printer, valSourceLoc.trailing_comments);
printer->Print(vars, "$prefix$$name$ = $number$$opt_comma$\n");
if (descriptor_->value(i)->number() < min_value->number()) {
min_value = descriptor_->value(i);
}
if (descriptor_->value(i)->number() > max_value->number()) {
max_value = descriptor_->value(i);
}
}
printer->Print(vars, " PROTOBUF_C__FORCE_ENUM_TO_BE_INT_SIZE($uc_name$)\n");
printer->Outdent();
printer->Print(vars, "} $classname$;\n");
}
void EnumGenerator::GenerateDescriptorDeclarations(io::Printer* printer) {
std::map<std::string, std::string> vars;
if (dllexport_decl_.empty()) {
vars["dllexport"] = "";
} else {
vars["dllexport"] = dllexport_decl_ + " ";
}
vars["classname"] = FullNameToC(descriptor_->full_name(), descriptor_->file());
vars["lcclassname"] = FullNameToLower(descriptor_->full_name(), descriptor_->file());
printer->Print(vars,
"extern $dllexport$const ProtobufCEnumDescriptor $lcclassname$__descriptor;\n");
}
struct ValueIndex
{
int value;
unsigned index;
unsigned final_index; /* index in uniqified array of values */
const char *name;
};
void EnumGenerator::GenerateValueInitializer(io::Printer *printer, int index)
{
const EnumValueDescriptor *vd = descriptor_->value(index);
std::map<std::string, std::string> vars;
bool optimize_code_size = descriptor_->file()->options().has_optimize_for() &&
descriptor_->file()->options().optimize_for() ==
FileOptions_OptimizeMode_CODE_SIZE;
vars["enum_value_name"] = vd->name();
vars["c_enum_value_name"] = FullNameToUpper(descriptor_->full_name(), descriptor_->file()) + "__" + vd->name();
vars["value"] = SimpleItoa(vd->number());
if (optimize_code_size)
printer->Print(vars, " { NULL, NULL, $value$ }, /* CODE_SIZE */\n");
else
printer->Print(vars,
" { \"$enum_value_name$\", \"$c_enum_value_name$\", $value$ },\n");
}
static int compare_value_indices_by_value_then_index(const void *a, const void *b)
{
const ValueIndex *vi_a = (const ValueIndex *) a;
const ValueIndex *vi_b = (const ValueIndex *) b;
if (vi_a->value < vi_b->value) return -1;
if (vi_a->value > vi_b->value) return +1;
if (vi_a->index < vi_b->index) return -1;
if (vi_a->index > vi_b->index) return +1;
return 0;
}
static int compare_value_indices_by_name(const void *a, const void *b)
{
const ValueIndex *vi_a = (const ValueIndex *) a;
const ValueIndex *vi_b = (const ValueIndex *) b;
return strcmp (vi_a->name, vi_b->name);
}
void EnumGenerator::GenerateEnumDescriptor(io::Printer* printer) {
std::map<std::string, std::string> vars;
vars["fullname"] = descriptor_->full_name();
vars["lcclassname"] = FullNameToLower(descriptor_->full_name(), descriptor_->file());
vars["cname"] = FullNameToC(descriptor_->full_name(), descriptor_->file());
vars["shortname"] = descriptor_->name();
vars["packagename"] = descriptor_->file()->package();
vars["value_count"] = SimpleItoa(descriptor_->value_count());
bool optimize_code_size = descriptor_->file()->options().has_optimize_for() &&
descriptor_->file()->options().optimize_for() ==
FileOptions_OptimizeMode_CODE_SIZE;
// Sort by name and value, dropping duplicate values if they appear later.
// TODO: use a c++ paradigm for this!
NameIndex *name_index = new NameIndex[descriptor_->value_count()];
ValueIndex *value_index = new ValueIndex[descriptor_->value_count()];
for (int j = 0; j < descriptor_->value_count(); j++) {
const EnumValueDescriptor *vd = descriptor_->value(j);
name_index[j].index = j;
name_index[j].name = vd->name().c_str();
value_index[j].index = j;
value_index[j].value = vd->number();
value_index[j].name = vd->name().c_str();
}
qsort(value_index, descriptor_->value_count(),
sizeof(ValueIndex), compare_value_indices_by_value_then_index);
// only record unique values
int n_unique_values;
if (descriptor_->value_count() == 0) {
n_unique_values = 0; // should never happen
} else {
n_unique_values = 1;
value_index[0].final_index = 0;
for (int j = 1; j < descriptor_->value_count(); j++) {
if (value_index[j-1].value != value_index[j].value)
value_index[j].final_index = n_unique_values++;
else
value_index[j].final_index = n_unique_values - 1;
}
}
vars["unique_value_count"] = SimpleItoa(n_unique_values);
printer->Print(vars,
"static const ProtobufCEnumValue $lcclassname$__enum_values_by_number[$unique_value_count$] =\n"
"{\n");
if (descriptor_->value_count() > 0) {
GenerateValueInitializer(printer, value_index[0].index);
for (int j = 1; j < descriptor_->value_count(); j++) {
if (value_index[j-1].value != value_index[j].value) {
GenerateValueInitializer(printer, value_index[j].index);
}
}
}
printer->Print(vars, "};\n");
printer->Print(vars, "static const ProtobufCIntRange $lcclassname$__value_ranges[] = {\n");
unsigned n_ranges = 0;
if (descriptor_->value_count() > 0) {
unsigned range_start = 0;
unsigned range_len = 1;
int range_start_value = value_index[0].value;
int last_value = range_start_value;
for (int j = 1; j < descriptor_->value_count(); j++) {
if (value_index[j-1].value != value_index[j].value) {
if (last_value + 1 == value_index[j].value) {
range_len++;
} else {
// output range
vars["range_start_value"] = SimpleItoa(range_start_value);
vars["orig_index"] = SimpleItoa(range_start);
printer->Print (vars, "{$range_start_value$, $orig_index$},");
range_start_value = value_index[j].value;
range_start += range_len;
range_len = 1;
n_ranges++;
}
last_value = value_index[j].value;
}
}
{
vars["range_start_value"] = SimpleItoa(range_start_value);
vars["orig_index"] = SimpleItoa(range_start);
printer->Print (vars, "{$range_start_value$, $orig_index$},");
range_start += range_len;
n_ranges++;
}
{
vars["range_start_value"] = SimpleItoa(0);
vars["orig_index"] = SimpleItoa(range_start);
printer->Print (vars, "{$range_start_value$, $orig_index$}\n};\n");
}
}
vars["n_ranges"] = SimpleItoa(n_ranges);
if (!optimize_code_size) {
qsort(value_index, descriptor_->value_count(),
sizeof(ValueIndex), compare_value_indices_by_name);
printer->Print(vars,
"static const ProtobufCEnumValueIndex $lcclassname$__enum_values_by_name[$value_count$] =\n"
"{\n");
for (int j = 0; j < descriptor_->value_count(); j++) {
vars["index"] = SimpleItoa(value_index[j].final_index);
vars["name"] = value_index[j].name;
printer->Print (vars, " { \"$name$\", $index$ },\n");
}
printer->Print(vars, "};\n");
}
if (optimize_code_size) {
printer->Print(vars,
"const ProtobufCEnumDescriptor $lcclassname$__descriptor =\n"
"{\n"
" PROTOBUF_C__ENUM_DESCRIPTOR_MAGIC,\n"
" NULL,NULL,NULL,NULL, /* CODE_SIZE */\n"
" $unique_value_count$,\n"
" $lcclassname$__enum_values_by_number,\n"
" 0, NULL, /* CODE_SIZE */\n"
" $n_ranges$,\n"
" $lcclassname$__value_ranges,\n"
" NULL,NULL,NULL,NULL /* reserved[1234] */\n"
"};\n");
} else {
printer->Print(vars,
"const ProtobufCEnumDescriptor $lcclassname$__descriptor =\n"
"{\n"
" PROTOBUF_C__ENUM_DESCRIPTOR_MAGIC,\n"
" \"$fullname$\",\n"
" \"$shortname$\",\n"
" \"$cname$\",\n"
" \"$packagename$\",\n"
" $unique_value_count$,\n"
" $lcclassname$__enum_values_by_number,\n"
" $value_count$,\n"
" $lcclassname$__enum_values_by_name,\n"
" $n_ranges$,\n"
" $lcclassname$__value_ranges,\n"
" NULL,NULL,NULL,NULL /* reserved[1234] */\n"
"};\n");
}
delete[] value_index;
delete[] name_index;
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,118 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_ENUM_H__
#define GOOGLE_PROTOBUF_COMPILER_C_ENUM_H__
#include <string>
#include <google/protobuf/descriptor.h>
namespace google {
namespace protobuf {
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace c {
class EnumGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
explicit EnumGenerator(const EnumDescriptor* descriptor,
const std::string& dllexport_decl);
~EnumGenerator();
// Header stuff.
// Generate header code defining the enum. This code should be placed
// within the enum's package namespace, but NOT within any class, even for
// nested enums.
void GenerateDefinition(io::Printer* printer);
void GenerateDescriptorDeclarations(io::Printer* printer);
// Source file stuff.
// Generate the ProtobufCEnumDescriptor for this enum
void GenerateEnumDescriptor(io::Printer* printer);
// Generate static initializer for a ProtobufCEnumValue
// given the index of the value in the enum.
void GenerateValueInitializer(io::Printer *printer, int index);
private:
const EnumDescriptor* descriptor_;
std::string dllexport_decl_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_ENUM_H__

View File

@@ -0,0 +1,149 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <protoc-c/c_enum_field.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
using internal::WireFormat;
// TODO(kenton): Factor out a "SetCommonFieldVariables()" to get rid of
// repeat code between this and the other field types.
void SetEnumVariables(const FieldDescriptor* descriptor,
std::map<std::string, std::string>* variables) {
(*variables)["name"] = FieldName(descriptor);
(*variables)["type"] = FullNameToC(descriptor->enum_type()->full_name(), descriptor->enum_type()->file());
const EnumValueDescriptor* default_value = descriptor->default_value_enum();
(*variables)["default"] = FullNameToUpper(default_value->type()->full_name(), default_value->type()->file())
+ "__" + default_value->name();
(*variables)["deprecated"] = FieldDeprecated(descriptor);
}
// ===================================================================
EnumFieldGenerator::
EnumFieldGenerator(const FieldDescriptor* descriptor)
: FieldGenerator(descriptor)
{
SetEnumVariables(descriptor, &variables_);
}
EnumFieldGenerator::~EnumFieldGenerator() {}
void EnumFieldGenerator::GenerateStructMembers(io::Printer* printer) const
{
switch (descriptor_->label()) {
case FieldDescriptor::LABEL_REQUIRED:
printer->Print(variables_, "$type$ $name$$deprecated$;\n");
break;
case FieldDescriptor::LABEL_OPTIONAL:
if (descriptor_->containing_oneof() == NULL && FieldSyntax(descriptor_) == 2)
printer->Print(variables_, "protobuf_c_boolean has_$name$$deprecated$;\n");
printer->Print(variables_, "$type$ $name$$deprecated$;\n");
break;
case FieldDescriptor::LABEL_REPEATED:
printer->Print(variables_, "size_t n_$name$$deprecated$;\n");
printer->Print(variables_, "$type$ *$name$$deprecated$;\n");
break;
}
}
std::string EnumFieldGenerator::GetDefaultValue(void) const
{
return variables_.find("default")->second;
}
void EnumFieldGenerator::GenerateStaticInit(io::Printer* printer) const
{
switch (descriptor_->label()) {
case FieldDescriptor::LABEL_REQUIRED:
printer->Print(variables_, "$default$");
break;
case FieldDescriptor::LABEL_OPTIONAL:
if (FieldSyntax(descriptor_) == 2)
printer->Print(variables_, "0, ");
printer->Print(variables_, "$default$");
break;
case FieldDescriptor::LABEL_REPEATED:
// no support for default?
printer->Print("0,NULL");
break;
}
}
void EnumFieldGenerator::GenerateDescriptorInitializer(io::Printer* printer) const
{
std::string addr = "&" + FullNameToLower(descriptor_->enum_type()->full_name(), descriptor_->enum_type()->file()) + "__descriptor";
GenerateDescriptorInitializerGeneric(printer, true, "ENUM", addr);
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,98 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_ENUM_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_C_ENUM_FIELD_H__
#include <map>
#include <string>
#include <protoc-c/c_field.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
class EnumFieldGenerator : public FieldGenerator {
public:
explicit EnumFieldGenerator(const FieldDescriptor* descriptor);
~EnumFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateStructMembers(io::Printer* printer) const;
void GenerateDescriptorInitializer(io::Printer* printer) const;
std::string GetDefaultValue(void) const;
void GenerateStaticInit(io::Printer* printer) const;
private:
std::map<std::string, std::string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_ENUM_FIELD_H__

View File

@@ -0,0 +1,90 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <protoc-c/c_extension.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
ExtensionGenerator::ExtensionGenerator(const FieldDescriptor* descriptor,
const std::string& dllexport_decl)
: descriptor_(descriptor),
dllexport_decl_(dllexport_decl) {
}
ExtensionGenerator::~ExtensionGenerator() {}
void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) {
}
void ExtensionGenerator::GenerateDefinition(io::Printer* printer) {
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,110 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_EXTENSION_H__
#define GOOGLE_PROTOBUF_COMPILER_C_EXTENSION_H__
#include <string>
#include <google/protobuf/stubs/common.h>
namespace google {
namespace protobuf {
class FieldDescriptor; // descriptor.h
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace c {
// Generates code for an extension, which may be within the scope of some
// message or may be at file scope. This is much simpler than FieldGenerator
// since extensions are just simple identifiers with interesting types.
class ExtensionGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
explicit ExtensionGenerator(const FieldDescriptor* descriptor,
const std::string& dllexport_decl);
~ExtensionGenerator();
// Header stuff.
void GenerateDeclaration(io::Printer* printer);
// Source file stuff.
void GenerateDefinition(io::Printer* printer);
private:
const FieldDescriptor* descriptor_;
std::string type_traits_;
std::string dllexport_decl_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_H__

View File

@@ -0,0 +1,241 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <protoc-c/c_field.h>
#include <protoc-c/c_primitive_field.h>
#include <protoc-c/c_string_field.h>
#include <protoc-c/c_bytes_field.h>
#include <protoc-c/c_enum_field.h>
#include <protoc-c/c_message_field.h>
#include <protoc-c/c_helpers.h>
#include <protobuf-c/protobuf-c.pb.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/printer.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
FieldGenerator::~FieldGenerator()
{
}
static bool is_packable_type(FieldDescriptor::Type type)
{
return type == FieldDescriptor::TYPE_DOUBLE
|| type == FieldDescriptor::TYPE_FLOAT
|| type == FieldDescriptor::TYPE_INT64
|| type == FieldDescriptor::TYPE_UINT64
|| type == FieldDescriptor::TYPE_INT32
|| type == FieldDescriptor::TYPE_FIXED64
|| type == FieldDescriptor::TYPE_FIXED32
|| type == FieldDescriptor::TYPE_BOOL
|| type == FieldDescriptor::TYPE_UINT32
|| type == FieldDescriptor::TYPE_ENUM
|| type == FieldDescriptor::TYPE_SFIXED32
|| type == FieldDescriptor::TYPE_SFIXED64
|| type == FieldDescriptor::TYPE_SINT32
|| type == FieldDescriptor::TYPE_SINT64;
//TYPE_BYTES
//TYPE_STRING
//TYPE_GROUP
//TYPE_MESSAGE
}
void FieldGenerator::GenerateDescriptorInitializerGeneric(io::Printer* printer,
bool optional_uses_has,
const std::string &type_macro,
const std::string &descriptor_addr) const
{
std::map<std::string, std::string> variables;
const OneofDescriptor *oneof = descriptor_->containing_oneof();
const ProtobufCFileOptions opt = descriptor_->file()->options().GetExtension(pb_c_file);
variables["TYPE"] = type_macro;
variables["classname"] = FullNameToC(FieldScope(descriptor_)->full_name(), FieldScope(descriptor_)->file());
variables["name"] = FieldName(descriptor_);
if (opt.use_oneof_field_name())
variables["proto_name"] = oneof->name();
else
variables["proto_name"] = descriptor_->name();
variables["descriptor_addr"] = descriptor_addr;
variables["value"] = SimpleItoa(descriptor_->number());
if (oneof != NULL)
variables["oneofname"] = CamelToLower(oneof->name());
if (FieldSyntax(descriptor_) == 3 &&
descriptor_->label() == FieldDescriptor::LABEL_OPTIONAL) {
variables["LABEL"] = "NONE";
optional_uses_has = false;
} else {
variables["LABEL"] = CamelToUpper(GetLabelName(descriptor_->label()));
}
if (descriptor_->has_default_value()) {
variables["default_value"] = std::string("&")
+ FullNameToLower(descriptor_->full_name(), descriptor_->file())
+ "__default_value";
} else if (FieldSyntax(descriptor_) == 3 &&
descriptor_->type() == FieldDescriptor::TYPE_STRING) {
variables["default_value"] = "&protobuf_c_empty_string";
} else {
variables["default_value"] = "NULL";
}
variables["flags"] = "0";
if (descriptor_->label() == FieldDescriptor::LABEL_REPEATED
&& is_packable_type (descriptor_->type())
&& descriptor_->options().packed()) {
variables["flags"] += " | PROTOBUF_C_FIELD_FLAG_PACKED";
} else if (descriptor_->label() == FieldDescriptor::LABEL_REPEATED
&& is_packable_type (descriptor_->type())
&& FieldSyntax(descriptor_) == 3
&& !descriptor_->options().has_packed()) {
variables["flags"] += " | PROTOBUF_C_FIELD_FLAG_PACKED";
}
if (descriptor_->options().deprecated())
variables["flags"] += " | PROTOBUF_C_FIELD_FLAG_DEPRECATED";
if (oneof != NULL)
variables["flags"] += " | PROTOBUF_C_FIELD_FLAG_ONEOF";
printer->Print("{\n");
if (descriptor_->file()->options().has_optimize_for() &&
descriptor_->file()->options().optimize_for() ==
FileOptions_OptimizeMode_CODE_SIZE) {
printer->Print(" NULL, /* CODE_SIZE */\n");
} else {
printer->Print(variables, " \"$proto_name$\",\n");
}
printer->Print(variables,
" $value$,\n"
" PROTOBUF_C_LABEL_$LABEL$,\n"
" PROTOBUF_C_TYPE_$TYPE$,\n");
switch (descriptor_->label()) {
case FieldDescriptor::LABEL_REQUIRED:
printer->Print(variables, " 0, /* quantifier_offset */\n");
break;
case FieldDescriptor::LABEL_OPTIONAL:
if (oneof != NULL) {
printer->Print(variables, " offsetof($classname$, $oneofname$_case),\n");
} else if (optional_uses_has) {
printer->Print(variables, " offsetof($classname$, has_$name$),\n");
} else {
printer->Print(variables, " 0, /* quantifier_offset */\n");
}
break;
case FieldDescriptor::LABEL_REPEATED:
printer->Print(variables, " offsetof($classname$, n_$name$),\n");
break;
}
printer->Print(variables, " offsetof($classname$, $name$),\n");
printer->Print(variables, " $descriptor_addr$,\n");
printer->Print(variables, " $default_value$,\n");
printer->Print(variables, " $flags$, /* flags */\n");
printer->Print(variables, " 0,NULL,NULL /* reserved1,reserved2, etc */\n");
printer->Print("},\n");
}
FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor)
: descriptor_(descriptor),
field_generators_(
new std::unique_ptr<FieldGenerator>[descriptor->field_count()]) {
// Construct all the FieldGenerators.
for (int i = 0; i < descriptor->field_count(); i++) {
field_generators_[i].reset(MakeGenerator(descriptor->field(i)));
}
}
FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field) {
const ProtobufCFieldOptions opt = field->options().GetExtension(pb_c_field);
switch (field->type()) {
case FieldDescriptor::TYPE_MESSAGE:
return new MessageFieldGenerator(field);
case FieldDescriptor::TYPE_STRING:
if (opt.string_as_bytes())
return new BytesFieldGenerator(field);
else
return new StringFieldGenerator(field);
case FieldDescriptor::TYPE_BYTES:
return new BytesFieldGenerator(field);
case FieldDescriptor::TYPE_ENUM:
return new EnumFieldGenerator(field);
case FieldDescriptor::TYPE_GROUP:
return 0; // XXX
default:
return new PrimitiveFieldGenerator(field);
}
}
FieldGeneratorMap::~FieldGeneratorMap() {}
const FieldGenerator& FieldGeneratorMap::get(
const FieldDescriptor* field) const {
GOOGLE_CHECK_EQ(field->containing_type(), descriptor_);
return *field_generators_[field->index()];
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,133 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_C_FIELD_H__
#include <memory>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/descriptor.h>
namespace google {
namespace protobuf {
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace c {
class FieldGenerator {
public:
explicit FieldGenerator(const FieldDescriptor *descriptor) : descriptor_(descriptor) {}
virtual ~FieldGenerator();
// Generate definitions to be included in the structure.
virtual void GenerateStructMembers(io::Printer* printer) const = 0;
// Generate a static initializer for this field.
virtual void GenerateDescriptorInitializer(io::Printer* printer) const = 0;
virtual void GenerateDefaultValueDeclarations(io::Printer* printer) const { }
virtual void GenerateDefaultValueImplementations(io::Printer* printer) const { }
virtual std::string GetDefaultValue() const = 0;
// Generate members to initialize this field from a static initializer
virtual void GenerateStaticInit(io::Printer* printer) const = 0;
protected:
void GenerateDescriptorInitializerGeneric(io::Printer* printer,
bool optional_uses_has,
const std::string &type_macro,
const std::string &descriptor_addr) const;
const FieldDescriptor *descriptor_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);
};
// Convenience class which constructs FieldGenerators for a Descriptor.
class FieldGeneratorMap {
public:
explicit FieldGeneratorMap(const Descriptor* descriptor);
~FieldGeneratorMap();
const FieldGenerator& get(const FieldDescriptor* field) const;
private:
const Descriptor* descriptor_;
std::unique_ptr<std::unique_ptr<FieldGenerator>[]> field_generators_;
static FieldGenerator* MakeGenerator(const FieldDescriptor* field);
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_FIELD_H__

View File

@@ -0,0 +1,274 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2014, Dave Benson and the protobuf-c authors.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <protoc-c/c_file.h>
#include <protoc-c/c_enum.h>
#include <protoc-c/c_service.h>
#include <protoc-c/c_extension.h>
#include <protoc-c/c_helpers.h>
#include <protoc-c/c_message.h>
#include <google/protobuf/io/printer.h>
#include <protobuf-c/protobuf-c.pb.h>
#include "protobuf-c.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
// ===================================================================
FileGenerator::FileGenerator(const FileDescriptor* file,
const std::string& dllexport_decl)
: file_(file),
message_generators_(
new std::unique_ptr<MessageGenerator>[file->message_type_count()]),
enum_generators_(
new std::unique_ptr<EnumGenerator>[file->enum_type_count()]),
service_generators_(
new std::unique_ptr<ServiceGenerator>[file->service_count()]),
extension_generators_(
new std::unique_ptr<ExtensionGenerator>[file->extension_count()]) {
for (int i = 0; i < file->message_type_count(); i++) {
message_generators_[i].reset(
new MessageGenerator(file->message_type(i), dllexport_decl));
}
for (int i = 0; i < file->enum_type_count(); i++) {
enum_generators_[i].reset(
new EnumGenerator(file->enum_type(i), dllexport_decl));
}
for (int i = 0; i < file->service_count(); i++) {
service_generators_[i].reset(
new ServiceGenerator(file->service(i), dllexport_decl));
}
for (int i = 0; i < file->extension_count(); i++) {
extension_generators_[i].reset(
new ExtensionGenerator(file->extension(i), dllexport_decl));
}
}
FileGenerator::~FileGenerator() {}
void FileGenerator::GenerateHeader(io::Printer* printer) {
std::string filename_identifier = FilenameIdentifier(file_->name());
int min_header_version = 1000000;
#if defined(HAVE_PROTO3)
if (file_->syntax() == FileDescriptor::SYNTAX_PROTO3) {
min_header_version = 1003000;
}
#endif
// Generate top of header.
printer->Print(
"/* Generated by the protocol buffer compiler. DO NOT EDIT! */\n"
"/* Generated from: $filename$ */\n"
"\n"
"#ifndef PROTOBUF_C_$filename_identifier$__INCLUDED\n"
"#define PROTOBUF_C_$filename_identifier$__INCLUDED\n"
"\n"
"#include <protobuf-c/protobuf-c.h>\n"
"\n"
"PROTOBUF_C__BEGIN_DECLS\n"
"\n",
"filename", file_->name(),
"filename_identifier", filename_identifier);
// Verify the protobuf-c library header version is compatible with the
// protoc-c version before going any further.
printer->Print(
"#if PROTOBUF_C_VERSION_NUMBER < $min_header_version$\n"
"# error This file was generated by a newer version of protoc-c which is "
"incompatible with your libprotobuf-c headers. Please update your headers.\n"
"#elif $protoc_version$ < PROTOBUF_C_MIN_COMPILER_VERSION\n"
"# error This file was generated by an older version of protoc-c which is "
"incompatible with your libprotobuf-c headers. Please regenerate this file "
"with a newer version of protoc-c.\n"
"#endif\n"
"\n",
"min_header_version", SimpleItoa(min_header_version),
"protoc_version", SimpleItoa(PROTOBUF_C_VERSION_NUMBER));
for (int i = 0; i < file_->dependency_count(); i++) {
const ProtobufCFileOptions opt =
file_->dependency(i)->options().GetExtension(pb_c_file);
if (!opt.no_generate()) {
printer->Print(
"#include \"$dependency$.pb-c.h\"\n",
"dependency", StripProto(file_->dependency(i)->name()));
}
}
printer->Print("\n");
// Generate forward declarations of classes.
for (int i = 0; i < file_->message_type_count(); i++) {
message_generators_[i]->GenerateStructTypedef(printer);
}
printer->Print("\n");
// Generate enum definitions.
printer->Print("\n/* --- enums --- */\n\n");
for (int i = 0; i < file_->message_type_count(); i++) {
message_generators_[i]->GenerateEnumDefinitions(printer);
}
for (int i = 0; i < file_->enum_type_count(); i++) {
enum_generators_[i]->GenerateDefinition(printer);
}
// Generate class definitions.
printer->Print("\n/* --- messages --- */\n\n");
for (int i = 0; i < file_->message_type_count(); i++) {
message_generators_[i]->GenerateStructDefinition(printer);
}
for (int i = 0; i < file_->message_type_count(); i++) {
const ProtobufCFileOptions opt = file_->options().GetExtension(pb_c_file);
message_generators_[i]->GenerateHelperFunctionDeclarations(
printer,
opt.has_gen_pack_helpers(),
opt.gen_pack_helpers(),
opt.gen_init_helpers());
}
printer->Print("/* --- per-message closures --- */\n\n");
for (int i = 0; i < file_->message_type_count(); i++) {
message_generators_[i]->GenerateClosureTypedef(printer);
}
// Generate service definitions.
printer->Print("\n/* --- services --- */\n\n");
for (int i = 0; i < file_->service_count(); i++) {
service_generators_[i]->GenerateMainHFile(printer);
}
// Declare extension identifiers.
for (int i = 0; i < file_->extension_count(); i++) {
extension_generators_[i]->GenerateDeclaration(printer);
}
printer->Print("\n/* --- descriptors --- */\n\n");
for (int i = 0; i < file_->enum_type_count(); i++) {
enum_generators_[i]->GenerateDescriptorDeclarations(printer);
}
for (int i = 0; i < file_->message_type_count(); i++) {
message_generators_[i]->GenerateDescriptorDeclarations(printer);
}
for (int i = 0; i < file_->service_count(); i++) {
service_generators_[i]->GenerateDescriptorDeclarations(printer);
}
printer->Print(
"\n"
"PROTOBUF_C__END_DECLS\n"
"\n\n#endif /* PROTOBUF_C_$filename_identifier$__INCLUDED */\n",
"filename_identifier", filename_identifier);
}
void FileGenerator::GenerateSource(io::Printer* printer) {
printer->Print(
"/* Generated by the protocol buffer compiler. DO NOT EDIT! */\n"
"/* Generated from: $filename$ */\n"
"\n"
"/* Do not generate deprecated warnings for self */\n"
"#ifndef PROTOBUF_C__NO_DEPRECATED\n"
"#define PROTOBUF_C__NO_DEPRECATED\n"
"#endif\n"
"\n"
"#include \"$basename$.pb-c.h\"\n",
"filename", file_->name(),
"basename", StripProto(file_->name()));
const ProtobufCFileOptions opt = file_->options().GetExtension(pb_c_file);
for (int i = 0; i < file_->message_type_count(); i++) {
message_generators_[i]->GenerateHelperFunctionDefinitions(
printer,
opt.has_gen_pack_helpers(),
opt.gen_pack_helpers(),
opt.gen_init_helpers());
}
for (int i = 0; i < file_->message_type_count(); i++) {
message_generators_[i]->GenerateMessageDescriptor(printer,
opt.gen_init_helpers());
}
for (int i = 0; i < file_->enum_type_count(); i++) {
enum_generators_[i]->GenerateEnumDescriptor(printer);
}
for (int i = 0; i < file_->service_count(); i++) {
service_generators_[i]->GenerateCFile(printer);
}
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,115 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_FILE_H__
#define GOOGLE_PROTOBUF_COMPILER_C_FILE_H__
#include <memory>
#include <string>
#include <vector>
#include <google/protobuf/stubs/common.h>
#include <protoc-c/c_field.h>
namespace google {
namespace protobuf {
class FileDescriptor; // descriptor.h
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace c {
class EnumGenerator; // enum.h
class MessageGenerator; // message.h
class ServiceGenerator; // service.h
class ExtensionGenerator; // extension.h
class FileGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
explicit FileGenerator(const FileDescriptor* file,
const std::string& dllexport_decl);
~FileGenerator();
void GenerateHeader(io::Printer* printer);
void GenerateSource(io::Printer* printer);
private:
const FileDescriptor* file_;
std::unique_ptr<std::unique_ptr<MessageGenerator>[]> message_generators_;
std::unique_ptr<std::unique_ptr<EnumGenerator>[]> enum_generators_;
std::unique_ptr<std::unique_ptr<ServiceGenerator>[]> service_generators_;
std::unique_ptr<std::unique_ptr<ExtensionGenerator>[]> extension_generators_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_FILE_H__

View File

@@ -0,0 +1,176 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <protoc-c/c_generator.h>
#include <memory>
#include <vector>
#include <utility>
#include <protoc-c/c_file.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <protobuf-c/protobuf-c.pb.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
// Parses a set of comma-delimited name/value pairs, e.g.:
// "foo=bar,baz,qux=corge"
// parses to the pairs:
// ("foo", "bar"), ("baz", ""), ("qux", "corge")
void ParseOptions(const std::string& text, std::vector<std::pair<std::string, std::string> >* output) {
std::vector<std::string> parts;
SplitStringUsing(text, ",", &parts);
for (unsigned i = 0; i < parts.size(); i++) {
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 {
value.first = parts[i].substr(0, equals_pos);
value.second = parts[i].substr(equals_pos + 1);
}
output->push_back(value);
}
}
CGenerator::CGenerator() {}
CGenerator::~CGenerator() {}
bool CGenerator::Generate(const FileDescriptor* file,
const std::string& parameter,
OutputDirectory* output_directory,
std::string* error) const {
if (file->options().GetExtension(pb_c_file).no_generate())
return true;
std::vector<std::pair<std::string, std::string> > options;
ParseOptions(parameter, &options);
// -----------------------------------------------------------------
// parse generator options
// TODO(kenton): If we ever have more options, we may want to create a
// class that encapsulates them which we can pass down to all the
// generator classes. Currently we pass dllexport_decl down to all of
// them via the constructors, but we don't want to have to add another
// constructor parameter for every option.
// If the dllexport_decl option is passed to the compiler, we need to write
// it in front of every symbol that should be exported if this .proto is
// compiled into a Windows DLL. E.g., if the user invokes the protocol
// compiler as:
// protoc --cpp_out=dllexport_decl=FOO_EXPORT:outdir foo.proto
// then we'll define classes like this:
// class FOO_EXPORT Foo {
// ...
// }
// FOO_EXPORT is a macro which should expand to __declspec(dllexport) or
// __declspec(dllimport) depending on what is being compiled.
std::string dllexport_decl;
for (unsigned i = 0; i < options.size(); i++) {
if (options[i].first == "dllexport_decl") {
dllexport_decl = options[i].second;
} else {
*error = "Unknown generator option: " + options[i].first;
return false;
}
}
// -----------------------------------------------------------------
std::string basename = StripProto(file->name());
basename.append(".pb-c");
FileGenerator file_generator(file, dllexport_decl);
// Generate header.
{
std::unique_ptr<io::ZeroCopyOutputStream> output(
output_directory->Open(basename + ".h"));
io::Printer printer(output.get(), '$');
file_generator.GenerateHeader(&printer);
}
// Generate cc file.
{
std::unique_ptr<io::ZeroCopyOutputStream> output(
output_directory->Open(basename + ".c"));
io::Printer printer(output.get(), '$');
file_generator.GenerateSource(&printer);
}
return true;
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,106 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
// Generates C code for a given .proto file.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_GENERATOR_H__
#define GOOGLE_PROTOBUF_COMPILER_C_GENERATOR_H__
#include <string>
#include <google/protobuf/compiler/code_generator.h>
#if defined(_WIN32) && defined(PROTOBUF_C_USE_SHARED_LIB)
# define PROTOC_C_EXPORT __declspec(dllexport)
#else
# define PROTOC_C_EXPORT
#endif
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
// CodeGenerator implementation which generates a C++ source file and
// header. If you create your own protocol compiler binary and you want
// 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_C_EXPORT CGenerator : public CodeGenerator {
public:
CGenerator();
~CGenerator();
// implements CodeGenerator ----------------------------------------
bool Generate(const FileDescriptor* file,
const std::string& parameter,
OutputDirectory* output_directory,
std::string* error) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CGenerator);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_GENERATOR_H__

View File

@@ -0,0 +1,558 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <memory>
#include <vector>
#include <set>
#include <stdio.h> // for snprintf
#include <float.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/stubs/common.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
#if defined(_MSC_VER)
// FIXME: In the case where the generated string is longer than the buffer,
// _snprint() returns a negative value, where snprintf() returns the number
// of characters that *would* have been stored, had there been room.
// That is fundamental, as it allows snprintf() to be used to find the size
// necessary for the buffer, simply by calling it with the size of the buffer
// passed in as zero.
// Note: at the present moment return value isn't used in the code.
#define snprintf _snprintf
#pragma warning(disable:4800)
#pragma warning(disable:4996)
#endif
std::string DotsToUnderscores(const std::string& name) {
return StringReplace(name, ".", "_", true);
}
std::string DotsToColons(const std::string& name) {
return StringReplace(name, ".", "::", true);
}
std::string SimpleFtoa(float f) {
char buf[100];
snprintf(buf,sizeof(buf),"%.*g", FLT_DIG, f);
buf[sizeof(buf)-1] = 0; /* should NOT be necessary */
return buf;
}
std::string SimpleDtoa(double d) {
char buf[100];
snprintf(buf,sizeof(buf),"%.*g", DBL_DIG, d);
buf[sizeof(buf)-1] = 0; /* should NOT be necessary */
return buf;
}
std::string CamelToUpper(const std::string &name) {
bool was_upper = true; // suppress initial _
std::string rv = "";
int len = name.length();
for (int i = 0; i < len; i++) {
bool is_upper = isupper(name[i]);
if (is_upper) {
if (!was_upper)
rv += '_';
rv += name[i];
} else {
rv += toupper(name[i]);
}
was_upper = is_upper;
}
return rv;
}
std::string CamelToLower(const std::string &name) {
bool was_upper = true; // suppress initial _
std::string rv = "";
int len = name.length();
for (int i = 0; i < len; i++) {
bool is_upper = isupper(name[i]);
if (is_upper) {
if (!was_upper)
rv += '_';
rv += tolower(name[i]);
} else {
rv += name[i];
}
was_upper = is_upper;
}
return rv;
}
std::string ToUpper(const std::string &name) {
std::string rv = "";
int len = name.length();
for (int i = 0; i < len; i++) {
rv += toupper(name[i]);
}
return rv;
}
std::string ToLower(const std::string &name) {
std::string rv = "";
int len = name.length();
for (int i = 0; i < len; i++) {
rv += tolower(name[i]);
}
return rv;
}
std::string ToCamel(const std::string &name) {
std::string rv = "";
int len = name.length();
bool next_is_upper = true;
for (int i = 0; i < len; i++) {
if (name[i] == '_') {
next_is_upper = true;
} else if (next_is_upper) {
rv += toupper (name[i]);
next_is_upper = false;
} else {
rv += name[i];
}
}
return rv;
}
std::string OverrideFullName(const std::string &full_name,
const FileDescriptor *file) {
const ProtobufCFileOptions opt = file->options().GetExtension(pb_c_file);
if (!opt.has_c_package())
return full_name;
std::string new_name = opt.c_package();
if (file->package().empty())
new_name += ".";
return new_name + full_name.substr(file->package().length());
}
std::string FullNameToLower(const std::string &full_name,
const FileDescriptor *file) {
std::vector<std::string> pieces;
SplitStringUsing(OverrideFullName(full_name, file), ".", &pieces);
std::string rv = "";
for (unsigned i = 0; i < pieces.size(); i++) {
if (pieces[i] == "") continue;
if (rv != "") rv += "__";
rv += CamelToLower(pieces[i]);
}
return rv;
}
std::string FullNameToUpper(const std::string &full_name,
const FileDescriptor *file) {
std::vector<std::string> pieces;
SplitStringUsing(OverrideFullName(full_name, file), ".", &pieces);
std::string rv = "";
for (unsigned i = 0; i < pieces.size(); i++) {
if (pieces[i] == "") continue;
if (rv != "") rv += "__";
rv += CamelToUpper(pieces[i]);
}
return rv;
}
std::string FullNameToC(const std::string &full_name,
const FileDescriptor *file) {
std::vector<std::string> pieces;
SplitStringUsing(OverrideFullName(full_name, file), ".", &pieces);
std::string rv = "";
for (unsigned i = 0; i < pieces.size(); i++) {
if (pieces[i] == "") continue;
if (rv != "") rv += "__";
rv += ToCamel(pieces[i]);
}
return rv;
}
void PrintComment (io::Printer* printer, std::string comment)
{
if (!comment.empty())
{
std::vector<std::string> comment_lines;
SplitStringUsing (comment, "\r\n", &comment_lines);
printer->Print ("/*\n");
for (int i = 0; i < comment_lines.size(); i++)
{
if (!comment_lines[i].empty())
{
/* Make sure we don't inadvertently close the comment block */
if (comment_lines[i][0] == '/')
comment_lines[i] = ' ' + comment_lines[i];
/* Or cause other compiler issues. */
size_t delim_i;
while ((delim_i = comment_lines[i].find("/*")) != std::string::npos)
comment_lines[i][delim_i] = ' ';
while ((delim_i = comment_lines[i].find("*/")) != std::string::npos)
comment_lines[i][delim_i + 1] = ' ';
printer->Print (" *$line$\n", "line", comment_lines[i]);
}
}
printer->Print (" */\n");
}
}
std::string ConvertToSpaces(const std::string &input) {
return std::string(input.size(), ' ');
}
int compare_name_indices_by_name(const void *a, const void *b)
{
const NameIndex *ni_a = (const NameIndex *) a;
const NameIndex *ni_b = (const NameIndex *) b;
return strcmp (ni_a->name, ni_b->name);
}
std::string CEscape(const std::string& src);
const char* const kKeywordList[] = {
"and", "and_eq", "asm", "auto", "bitand", "bitor", "bool", "break", "case",
"catch", "char", "class", "compl", "const", "const_cast", "continue",
"default", "delete", "do", "double", "dynamic_cast", "else", "enum",
"explicit", "extern", "false", "float", "for", "friend", "goto", "if",
"inline", "int", "long", "mutable", "namespace", "new", "not", "not_eq",
"operator", "or", "or_eq", "private", "protected", "public", "register",
"reinterpret_cast", "return", "short", "signed", "sizeof", "static",
"static_cast", "struct", "switch", "template", "this", "throw", "true", "try",
"typedef", "typeid", "typename", "union", "unsigned", "using", "virtual",
"void", "volatile", "wchar_t", "while", "xor", "xor_eq"
};
std::set<std::string> MakeKeywordsMap() {
std::set<std::string> result;
for (int i = 0; i < GOOGLE_ARRAYSIZE(kKeywordList); i++) {
result.insert(kKeywordList[i]);
}
return result;
}
std::set<std::string> kKeywords = MakeKeywordsMap();
std::string FieldName(const FieldDescriptor* field) {
std::string result = ToLower(field->name());
if (kKeywords.count(result) > 0) {
result.append("_");
}
return result;
}
std::string FieldDeprecated(const FieldDescriptor* field) {
if (field->options().deprecated()) {
return " PROTOBUF_C__DEPRECATED";
}
return "";
}
std::string StripProto(const std::string& filename) {
if (HasSuffixString(filename, ".protodevel")) {
return StripSuffixString(filename, ".protodevel");
} else {
return StripSuffixString(filename, ".proto");
}
}
// Convert a file name into a valid identifier.
std::string FilenameIdentifier(const std::string& filename) {
std::string result;
for (unsigned i = 0; i < filename.size(); i++) {
if (isalnum(filename[i])) {
result.push_back(filename[i]);
} else {
// Not alphanumeric. To avoid any possibility of name conflicts we
// use the hex code for the character.
result.push_back('_');
char buffer[32];
result.append(FastHexToBuffer(static_cast<uint8>(filename[i]), buffer));
}
}
return result;
}
// Return the name of the BuildDescriptors() function for a given file.
std::string GlobalBuildDescriptorsName(const std::string& filename) {
return "proto_BuildDescriptors_" + FilenameIdentifier(filename);
}
std::string GetLabelName(FieldDescriptor::Label label) {
switch (label) {
case FieldDescriptor::LABEL_OPTIONAL: return "optional";
case FieldDescriptor::LABEL_REQUIRED: return "required";
case FieldDescriptor::LABEL_REPEATED: return "repeated";
}
return "bad-label";
}
unsigned
WriteIntRanges(io::Printer* printer, int n_values, const int *values, const std::string &name)
{
std::map<std::string, std::string> vars;
vars["name"] = name;
if (n_values > 0) {
int n_ranges = 1;
for (int i = 1; i < n_values; i++) {
if (values[i-1] + 1 != values[i])
n_ranges++;
}
vars["n_ranges"] = SimpleItoa(n_ranges);
printer->Print(vars, "static const ProtobufCIntRange $name$[$n_ranges$ + 1] =\n"
"{\n");
int last_range_start = 0;
for (int i = 1; i < n_values; i++) {
if (values[i-1] + 1 != values[i]) {
int count = i - last_range_start;
int expected = values[i-1] + 1;
vars["start_value"] = SimpleItoa(expected - count);
vars["orig_offset"] = SimpleItoa(last_range_start);
printer->Print (vars, " { $start_value$, $orig_offset$ },\n");
last_range_start = i;
}
}
// write last real entry
{
int i = n_values;
int count = i - last_range_start;
int expected = values[i-1] + 1;
vars["start_value"] = SimpleItoa(expected - count);
vars["orig_offset"] = SimpleItoa(last_range_start);
printer->Print (vars, " { $start_value$, $orig_offset$ },\n");
}
// write sentinel entry
vars["n_entries"] = SimpleItoa(n_values);
printer->Print (vars, " { 0, $n_entries$ }\n");
printer->Print (vars, "};\n");
return n_ranges;
} else {
printer->Print (vars, "#define $name$ NULL\n");
return 0;
}
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx
// XXXXXXXXX this stuff is copied from strutils.cc !!!! XXXXXXXXXXXXXXXXXXXXXXXXXXXXx
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx
// ----------------------------------------------------------------------
// StringReplace()
// Replace the "old" pattern with the "new" pattern in a string,
// and append the result to "res". If replace_all is false,
// it only replaces the first instance of "old."
// ----------------------------------------------------------------------
void StringReplace(const std::string& s, const std::string& oldsub,
const std::string& newsub, bool replace_all,
std::string* res) {
if (oldsub.empty()) {
res->append(s); // if empty, append the given string.
return;
}
std::string::size_type start_pos = 0;
std::string::size_type pos;
do {
pos = s.find(oldsub, start_pos);
if (pos == std::string::npos) {
break;
}
res->append(s, start_pos, pos - start_pos);
res->append(newsub);
start_pos = pos + oldsub.size(); // start searching again after the "old"
} while (replace_all);
res->append(s, start_pos, s.length() - start_pos);
}
// ----------------------------------------------------------------------
// StringReplace()
// Give me a string and two patterns "old" and "new", and I replace
// the first instance of "old" in the string with "new", if it
// exists. If "global" is true; call this repeatedly until it
// fails. RETURN a new string, regardless of whether the replacement
// happened or not.
// ----------------------------------------------------------------------
std::string StringReplace(const std::string& s, const std::string& oldsub,
const std::string& newsub, bool replace_all) {
std::string ret;
StringReplace(s, oldsub, newsub, replace_all, &ret);
return ret;
}
// ----------------------------------------------------------------------
// SplitStringUsing()
// Split a string using a character delimiter. Append the components
// to 'result'.
//
// Note: For multi-character delimiters, this routine will split on *ANY* of
// the characters in the string, not the entire string as a single delimiter.
// ----------------------------------------------------------------------
template <typename ITR>
static inline
void SplitStringToIteratorUsing(const std::string& full,
const char* delim,
ITR& result) {
// Optimize the common case where delim is a single character.
if (delim[0] != '\0' && delim[1] == '\0') {
char c = delim[0];
const char* p = full.data();
const char* end = p + full.size();
while (p != end) {
if (*p == c) {
++p;
} else {
const char* start = p;
while (++p != end && *p != c);
*result++ = std::string(start, p - start);
}
}
return;
}
std::string::size_type begin_index, end_index;
begin_index = full.find_first_not_of(delim);
while (begin_index != std::string::npos) {
end_index = full.find_first_of(delim, begin_index);
if (end_index == std::string::npos) {
*result++ = full.substr(begin_index);
return;
}
*result++ = full.substr(begin_index, (end_index - begin_index));
begin_index = full.find_first_not_of(delim, end_index);
}
}
void SplitStringUsing(const std::string& full,
const char* delim,
std::vector<std::string>* result) {
std::back_insert_iterator< std::vector<std::string> > it(*result);
SplitStringToIteratorUsing(full, delim, it);
}
char* FastHexToBuffer(int i, char* buffer)
{
snprintf(buffer, 16, "%x", i);
return buffer;
}
static int CEscapeInternal(const char* src, int src_len, char* dest,
int dest_len, bool use_hex) {
const char* src_end = src + src_len;
int used = 0;
bool last_hex_escape = false; // true if last output char was \xNN
for (; src < src_end; src++) {
if (dest_len - used < 2) // Need space for two letter escape
return -1;
bool is_hex_escape = false;
switch (*src) {
case '\n': dest[used++] = '\\'; dest[used++] = 'n'; break;
case '\r': dest[used++] = '\\'; dest[used++] = 'r'; break;
case '\t': dest[used++] = '\\'; dest[used++] = 't'; break;
case '\"': dest[used++] = '\\'; dest[used++] = '\"'; break;
case '\'': dest[used++] = '\\'; dest[used++] = '\''; break;
case '\\': dest[used++] = '\\'; dest[used++] = '\\'; break;
default:
// Note that if we emit \xNN and the src character after that is a hex
// digit then that digit must be escaped too to prevent it being
// interpreted as part of the character code by C.
if (!isprint(*src) || (last_hex_escape && isxdigit(*src))) {
if (dest_len - used < 4) // need space for 4 letter escape
return -1;
sprintf(dest + used, (use_hex ? "\\x%02x" : "\\%03o"),
static_cast<uint8>(*src));
is_hex_escape = use_hex;
used += 4;
} else {
dest[used++] = *src; break;
}
}
last_hex_escape = is_hex_escape;
}
if (dest_len - used < 1) // make sure that there is room for \0
return -1;
dest[used] = '\0'; // doesn't count towards return value though
return used;
}
std::string CEscape(const std::string& src) {
const int dest_length = src.size() * 4 + 1; // Maximum possible expansion
std::unique_ptr<char[]> dest(new char[dest_length]);
const int len = CEscapeInternal(src.data(), src.size(),
dest.get(), dest_length, false);
GOOGLE_DCHECK_GE(len, 0);
return std::string(dest.get(), len);
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,186 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_HELPERS_H__
#define GOOGLE_PROTOBUF_COMPILER_C_HELPERS_H__
#include <string>
#include <vector>
#include <sstream>
#include <google/protobuf/descriptor.h>
#include <protobuf-c/protobuf-c.pb.h>
#include <google/protobuf/io/printer.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
// --- Borrowed from stubs. ---
template <typename T> std::string SimpleItoa(T n) {
std::stringstream stream;
stream << n;
return stream.str();
}
std::string SimpleFtoa(float f);
std::string SimpleDtoa(double f);
void SplitStringUsing(const std::string &str, const char *delim, std::vector<std::string> *out);
std::string CEscape(const std::string& src);
std::string StringReplace(const std::string& s, const std::string& oldsub, const std::string& newsub, bool replace_all);
inline bool HasSuffixString(const std::string& str, const std::string& suffix) { return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; }
inline std::string StripSuffixString(const std::string& str, const std::string& suffix) { if (HasSuffixString(str, suffix)) { return str.substr(0, str.size() - suffix.size()); } else { return str; } }
char* FastHexToBuffer(int i, char* buffer);
// 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
// should be using lowercase-with-underscores style for proto field names
// anyway, so normally this just returns field->name().
std::string FieldName(const FieldDescriptor* field);
// Get macro string for deprecated field
std::string FieldDeprecated(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).
inline const Descriptor* FieldScope(const FieldDescriptor* field) {
return field->is_extension() ?
field->extension_scope() : field->containing_type();
}
// convert a CamelCase class name into an all uppercase affair
// with underscores separating words, e.g. MyClass becomes MY_CLASS.
std::string CamelToUpper(const std::string &class_name);
std::string CamelToLower(const std::string &class_name);
// lowercased, underscored name to camel case
std::string ToCamel(const std::string &name);
// lowercase the string
std::string ToLower(const std::string &class_name);
std::string ToUpper(const std::string &class_name);
// full_name() to lowercase with underscores
std::string FullNameToLower(const std::string &full_name, const FileDescriptor *file);
std::string FullNameToUpper(const std::string &full_name, const FileDescriptor *file);
// full_name() to c-typename (with underscores for packages, otherwise camel case)
std::string FullNameToC(const std::string &class_name, const FileDescriptor *file);
// Splits, indents, formats, and prints comment lines
void PrintComment (io::Printer* printer, std::string comment);
// make a string of spaces as long as input
std::string ConvertToSpaces(const std::string &input);
// Strips ".proto" or ".protodevel" from the end of a filename.
std::string StripProto(const std::string& filename);
// Get the C++ type name for a primitive type (e.g. "double", "::google::protobuf::int32", etc.).
// Note: non-built-in type names will be qualified, meaning they will start
// with a ::. If you are using the type as a template parameter, you will
// need to insure there is a space between the < and the ::, because the
// ridiculous C++ standard defines "<:" to be a synonym for "[".
const char* PrimitiveTypeName(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".
const char* DeclaredTypeMethodName(FieldDescriptor::Type type);
// Convert a file name into a valid identifier.
std::string FilenameIdentifier(const std::string& filename);
// Return the name of the BuildDescriptors() function for a given file.
std::string GlobalBuildDescriptorsName(const std::string& filename);
// return 'required', 'optional', or 'repeated'
std::string GetLabelName(FieldDescriptor::Label label);
// write IntRanges entries for a bunch of sorted values.
// returns the number of ranges there are to bsearch.
unsigned WriteIntRanges(io::Printer* printer, int n_values, const int *values, const std::string &name);
struct NameIndex
{
unsigned index;
const char *name;
};
int compare_name_indices_by_name(const void*, const void*);
// Return the syntax version of the file containing the field.
// This wrapper is needed to be able to compile against protobuf2.
inline int FieldSyntax(const FieldDescriptor* field) {
#ifdef HAVE_PROTO3
return field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ? 3 : 2;
#else
return 2;
#endif
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_HELPERS_H__

View File

@@ -0,0 +1,633 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <algorithm>
#include <map>
#include <memory>
#include <protoc-c/c_message.h>
#include <protoc-c/c_enum.h>
#include <protoc-c/c_extension.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format.h>
#include <protobuf-c/protobuf-c.pb.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
// ===================================================================
MessageGenerator::MessageGenerator(const Descriptor* descriptor,
const std::string& dllexport_decl)
: descriptor_(descriptor),
dllexport_decl_(dllexport_decl),
field_generators_(descriptor),
nested_generators_(new std::unique_ptr<MessageGenerator>[
descriptor->nested_type_count()]),
enum_generators_(new std::unique_ptr<EnumGenerator>[
descriptor->enum_type_count()]),
extension_generators_(new std::unique_ptr<ExtensionGenerator>[
descriptor->extension_count()]) {
for (int i = 0; i < descriptor->nested_type_count(); i++) {
nested_generators_[i].reset(
new MessageGenerator(descriptor->nested_type(i), dllexport_decl));
}
for (int i = 0; i < descriptor->enum_type_count(); i++) {
enum_generators_[i].reset(
new EnumGenerator(descriptor->enum_type(i), dllexport_decl));
}
for (int i = 0; i < descriptor->extension_count(); i++) {
extension_generators_[i].reset(
new ExtensionGenerator(descriptor->extension(i), dllexport_decl));
}
}
MessageGenerator::~MessageGenerator() {}
void MessageGenerator::
GenerateStructTypedef(io::Printer* printer) {
printer->Print("typedef struct $classname$ $classname$;\n",
"classname", FullNameToC(descriptor_->full_name(), descriptor_->file()));
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateStructTypedef(printer);
}
}
void MessageGenerator::
GenerateEnumDefinitions(io::Printer* printer) {
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateEnumDefinitions(printer);
}
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
enum_generators_[i]->GenerateDefinition(printer);
}
}
void MessageGenerator::
GenerateStructDefinition(io::Printer* printer) {
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateStructDefinition(printer);
}
std::map<std::string, std::string> vars;
vars["classname"] = FullNameToC(descriptor_->full_name(), descriptor_->file());
vars["lcclassname"] = FullNameToLower(descriptor_->full_name(), descriptor_->file());
vars["ucclassname"] = FullNameToUpper(descriptor_->full_name(), descriptor_->file());
vars["field_count"] = SimpleItoa(descriptor_->field_count());
if (dllexport_decl_.empty()) {
vars["dllexport"] = "";
} else {
vars["dllexport"] = dllexport_decl_ + " ";
}
// Generate the case enums for unions
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
const OneofDescriptor *oneof = descriptor_->oneof_decl(i);
vars["opt_comma"] = ",";
vars["oneofname"] = CamelToUpper(oneof->name());
vars["foneofname"] = FullNameToC(oneof->full_name(), oneof->file());
printer->Print("typedef enum {\n");
printer->Indent();
printer->Print(vars, "$ucclassname$__$oneofname$__NOT_SET = 0,\n");
for (int j = 0; j < oneof->field_count(); j++) {
const FieldDescriptor *field = oneof->field(j);
vars["fieldname"] = CamelToUpper(field->name());
vars["fieldnum"] = SimpleItoa(field->number());
bool isLast = j == oneof->field_count() - 1;
if (isLast) {
vars["opt_comma"] = "";
}
printer->Print(vars, "$ucclassname$__$oneofname$_$fieldname$ = $fieldnum$$opt_comma$\n");
}
printer->Print(vars, " PROTOBUF_C__FORCE_ENUM_TO_BE_INT_SIZE($ucclassname$__$oneofname$__CASE)\n");
printer->Outdent();
printer->Print(vars, "} $foneofname$Case;\n\n");
}
SourceLocation msgSourceLoc;
descriptor_->GetSourceLocation(&msgSourceLoc);
PrintComment (printer, msgSourceLoc.leading_comments);
const ProtobufCMessageOptions opt =
descriptor_->options().GetExtension(pb_c_msg);
vars["base"] = opt.base_field_name();
printer->Print(vars,
"struct $dllexport$ $classname$\n"
"{\n"
" ProtobufCMessage $base$;\n");
// Generate fields.
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor *field = descriptor_->field(i);
if (field->containing_oneof() == NULL) {
SourceLocation fieldSourceLoc;
field->GetSourceLocation(&fieldSourceLoc);
PrintComment (printer, fieldSourceLoc.leading_comments);
PrintComment (printer, fieldSourceLoc.trailing_comments);
field_generators_.get(field).GenerateStructMembers(printer);
}
}
// Generate unions from oneofs.
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
const OneofDescriptor *oneof = descriptor_->oneof_decl(i);
vars["oneofname"] = CamelToLower(oneof->name());
vars["foneofname"] = FullNameToC(oneof->full_name(), oneof->file());
printer->Print(vars, "$foneofname$Case $oneofname$_case;\n");
printer->Print("union {\n");
printer->Indent();
for (int j = 0; j < oneof->field_count(); j++) {
const FieldDescriptor *field = oneof->field(j);
SourceLocation fieldSourceLoc;
field->GetSourceLocation(&fieldSourceLoc);
PrintComment (printer, fieldSourceLoc.leading_comments);
PrintComment (printer, fieldSourceLoc.trailing_comments);
field_generators_.get(field).GenerateStructMembers(printer);
}
printer->Outdent();
printer->Print(vars, "};\n");
}
printer->Outdent();
printer->Print(vars, "};\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor *field = descriptor_->field(i);
if (field->has_default_value()) {
field_generators_.get(field).GenerateDefaultValueDeclarations(printer);
}
}
printer->Print(vars, "#define $ucclassname$__INIT \\\n"
" { PROTOBUF_C_MESSAGE_INIT (&$lcclassname$__descriptor) \\\n ");
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor *field = descriptor_->field(i);
if (field->containing_oneof() == NULL) {
printer->Print(", ");
field_generators_.get(field).GenerateStaticInit(printer);
}
}
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
const OneofDescriptor *oneof = descriptor_->oneof_decl(i);
vars["foneofname"] = FullNameToUpper(oneof->full_name(), oneof->file());
// Initialize the case enum
printer->Print(vars, ", $foneofname$__NOT_SET");
// Initialize the union
printer->Print(", {0}");
}
printer->Print(" }\n\n\n");
}
void MessageGenerator::
GenerateHelperFunctionDeclarations(io::Printer* printer,
bool is_pack_deep,
bool gen_pack,
bool gen_init)
{
const ProtobufCMessageOptions opt =
descriptor_->options().GetExtension(pb_c_msg);
// Override parent settings, if needed
if (opt.has_gen_pack_helpers())
gen_pack = opt.gen_pack_helpers();
if (opt.has_gen_init_helpers())
gen_init = opt.gen_init_helpers();
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
bool nested_pack = !is_pack_deep ? opt.gen_pack_helpers() : gen_pack;
nested_generators_[i]->GenerateHelperFunctionDeclarations(printer, true,
nested_pack,
gen_init);
}
std::map<std::string, std::string> vars;
vars["classname"] = FullNameToC(descriptor_->full_name(), descriptor_->file());
vars["lcclassname"] = FullNameToLower(descriptor_->full_name(), descriptor_->file());
if (gen_init) {
printer->Print(vars,
"/* $classname$ methods */\n"
"void $lcclassname$__init\n"
" ($classname$ *message);\n"
);
}
if (gen_pack) {
printer->Print(vars,
"size_t $lcclassname$__get_packed_size\n"
" (const $classname$ *message);\n"
"size_t $lcclassname$__pack\n"
" (const $classname$ *message,\n"
" uint8_t *out);\n"
"size_t $lcclassname$__pack_to_buffer\n"
" (const $classname$ *message,\n"
" ProtobufCBuffer *buffer);\n"
"$classname$ *\n"
" $lcclassname$__unpack\n"
" (ProtobufCAllocator *allocator,\n"
" size_t len,\n"
" const uint8_t *data);\n"
"void $lcclassname$__free_unpacked\n"
" ($classname$ *message,\n"
" ProtobufCAllocator *allocator);\n"
);
}
}
void MessageGenerator::
GenerateDescriptorDeclarations(io::Printer* printer) {
printer->Print("extern const ProtobufCMessageDescriptor $name$__descriptor;\n",
"name", FullNameToLower(descriptor_->full_name(), descriptor_->file()));
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateDescriptorDeclarations(printer);
}
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
enum_generators_[i]->GenerateDescriptorDeclarations(printer);
}
}
void MessageGenerator::GenerateClosureTypedef(io::Printer* printer)
{
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateClosureTypedef(printer);
}
std::map<std::string, std::string> vars;
vars["name"] = FullNameToC(descriptor_->full_name(), descriptor_->file());
printer->Print(vars,
"typedef void (*$name$_Closure)\n"
" (const $name$ *message,\n"
" void *closure_data);\n");
}
static int
compare_pfields_by_number (const void *a, const void *b)
{
const FieldDescriptor *pa = *(const FieldDescriptor **)a;
const FieldDescriptor *pb = *(const FieldDescriptor **)b;
if (pa->number() < pb->number()) return -1;
if (pa->number() > pb->number()) return +1;
return 0;
}
void MessageGenerator::
GenerateHelperFunctionDefinitions(io::Printer* printer,
bool is_pack_deep,
bool gen_pack,
bool gen_init)
{
const ProtobufCMessageOptions opt =
descriptor_->options().GetExtension(pb_c_msg);
// Override parent settings, if needed
if (opt.has_gen_pack_helpers())
gen_pack = opt.gen_pack_helpers();
if (opt.has_gen_init_helpers())
gen_init = opt.gen_init_helpers();
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
bool nested_pack = !is_pack_deep ? opt.gen_pack_helpers() : gen_pack;
nested_generators_[i]->GenerateHelperFunctionDefinitions(printer, true,
nested_pack,
gen_init);
}
std::map<std::string, std::string> vars;
vars["classname"] = FullNameToC(descriptor_->full_name(), descriptor_->file());
vars["lcclassname"] = FullNameToLower(descriptor_->full_name(), descriptor_->file());
vars["ucclassname"] = FullNameToUpper(descriptor_->full_name(), descriptor_->file());
vars["base"] = opt.base_field_name();
if (gen_init) {
printer->Print(vars,
"void $lcclassname$__init\n"
" ($classname$ *message)\n"
"{\n"
" static const $classname$ init_value = $ucclassname$__INIT;\n"
" *message = init_value;\n"
"}\n");
}
if (gen_pack) {
printer->Print(vars,
"size_t $lcclassname$__get_packed_size\n"
" (const $classname$ *message)\n"
"{\n"
" assert(message->$base$.descriptor == &$lcclassname$__descriptor);\n"
" return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message));\n"
"}\n"
"size_t $lcclassname$__pack\n"
" (const $classname$ *message,\n"
" uint8_t *out)\n"
"{\n"
" assert(message->$base$.descriptor == &$lcclassname$__descriptor);\n"
" return protobuf_c_message_pack ((const ProtobufCMessage*)message, out);\n"
"}\n"
"size_t $lcclassname$__pack_to_buffer\n"
" (const $classname$ *message,\n"
" ProtobufCBuffer *buffer)\n"
"{\n"
" assert(message->$base$.descriptor == &$lcclassname$__descriptor);\n"
" return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer);\n"
"}\n"
"$classname$ *\n"
" $lcclassname$__unpack\n"
" (ProtobufCAllocator *allocator,\n"
" size_t len,\n"
" const uint8_t *data)\n"
"{\n"
" return ($classname$ *)\n"
" protobuf_c_message_unpack (&$lcclassname$__descriptor,\n"
" allocator, len, data);\n"
"}\n"
"void $lcclassname$__free_unpacked\n"
" ($classname$ *message,\n"
" ProtobufCAllocator *allocator)\n"
"{\n"
" if(!message)\n"
" return;\n"
" assert(message->$base$.descriptor == &$lcclassname$__descriptor);\n"
" protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator);\n"
"}\n"
);
}
}
void MessageGenerator::
GenerateMessageDescriptor(io::Printer* printer, bool gen_init) {
std::map<std::string, std::string> vars;
vars["fullname"] = descriptor_->full_name();
vars["classname"] = FullNameToC(descriptor_->full_name(), descriptor_->file());
vars["lcclassname"] = FullNameToLower(descriptor_->full_name(), descriptor_->file());
vars["shortname"] = ToCamel(descriptor_->name());
vars["n_fields"] = SimpleItoa(descriptor_->field_count());
vars["packagename"] = descriptor_->file()->package();
bool optimize_code_size = descriptor_->file()->options().has_optimize_for() &&
descriptor_->file()->options().optimize_for() ==
FileOptions_OptimizeMode_CODE_SIZE;
const ProtobufCMessageOptions opt =
descriptor_->options().GetExtension(pb_c_msg);
// Override parent settings, if needed
if (opt.has_gen_init_helpers())
gen_init = opt.gen_init_helpers();
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateMessageDescriptor(printer, gen_init);
}
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
enum_generators_[i]->GenerateEnumDescriptor(printer);
}
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor *fd = descriptor_->field(i);
if (fd->has_default_value()) {
field_generators_.get(fd).GenerateDefaultValueImplementations(printer);
}
}
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor *fd = descriptor_->field(i);
const ProtobufCFieldOptions opt = fd->options().GetExtension(pb_c_field);
if (fd->has_default_value()) {
bool already_defined = false;
vars["name"] = fd->name();
vars["lcname"] = CamelToLower(fd->name());
vars["maybe_static"] = "static ";
vars["field_dv_ctype_suffix"] = "";
vars["default_value"] = field_generators_.get(fd).GetDefaultValue();
switch (fd->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
vars["field_dv_ctype"] = "int32_t";
break;
case FieldDescriptor::CPPTYPE_INT64:
vars["field_dv_ctype"] = "int64_t";
break;
case FieldDescriptor::CPPTYPE_UINT32:
vars["field_dv_ctype"] = "uint32_t";
break;
case FieldDescriptor::CPPTYPE_UINT64:
vars["field_dv_ctype"] = "uint64_t";
break;
case FieldDescriptor::CPPTYPE_FLOAT:
vars["field_dv_ctype"] = "float";
break;
case FieldDescriptor::CPPTYPE_DOUBLE:
vars["field_dv_ctype"] = "double";
break;
case FieldDescriptor::CPPTYPE_BOOL:
vars["field_dv_ctype"] = "protobuf_c_boolean";
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
// NOTE: not supported by protobuf
vars["maybe_static"] = "";
vars["field_dv_ctype"] = "{ ... }";
GOOGLE_LOG(DFATAL) << "Messages can't have default values!";
break;
case FieldDescriptor::CPPTYPE_STRING:
if (fd->type() == FieldDescriptor::TYPE_BYTES || opt.string_as_bytes())
{
vars["field_dv_ctype"] = "ProtobufCBinaryData";
}
else /* STRING type */
{
already_defined = true;
vars["maybe_static"] = "";
vars["field_dv_ctype"] = "char";
vars["field_dv_ctype_suffix"] = "[]";
}
break;
case FieldDescriptor::CPPTYPE_ENUM:
{
const EnumValueDescriptor *vd = fd->default_value_enum();
vars["field_dv_ctype"] = FullNameToC(vd->type()->full_name(), vd->type()->file());
break;
}
default:
GOOGLE_LOG(DFATAL) << "Unknown CPPTYPE";
break;
}
if (!already_defined)
printer->Print(vars, "$maybe_static$const $field_dv_ctype$ $lcclassname$__$lcname$__default_value$field_dv_ctype_suffix$ = $default_value$;\n");
}
}
if ( descriptor_->field_count() ) {
printer->Print(vars,
"static const ProtobufCFieldDescriptor $lcclassname$__field_descriptors[$n_fields$] =\n"
"{\n");
printer->Indent();
const FieldDescriptor **sorted_fields = new const FieldDescriptor *[descriptor_->field_count()];
for (int i = 0; i < descriptor_->field_count(); i++) {
sorted_fields[i] = descriptor_->field(i);
}
qsort (sorted_fields, descriptor_->field_count(),
sizeof (const FieldDescriptor *),
compare_pfields_by_number);
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor *field = sorted_fields[i];
field_generators_.get(field).GenerateDescriptorInitializer(printer);
}
printer->Outdent();
printer->Print(vars, "};\n");
if (!optimize_code_size) {
NameIndex *field_indices = new NameIndex [descriptor_->field_count()];
for (int i = 0; i < descriptor_->field_count(); i++) {
field_indices[i].name = sorted_fields[i]->name().c_str();
field_indices[i].index = i;
}
qsort (field_indices, descriptor_->field_count(), sizeof (NameIndex),
compare_name_indices_by_name);
printer->Print(vars, "static const unsigned $lcclassname$__field_indices_by_name[] = {\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
vars["index"] = SimpleItoa(field_indices[i].index);
vars["name"] = field_indices[i].name;
printer->Print(vars, " $index$, /* field[$index$] = $name$ */\n");
}
printer->Print("};\n");
delete[] field_indices;
}
// create range initializers
int *values = new int[descriptor_->field_count()];
for (int i = 0; i < descriptor_->field_count(); i++) {
values[i] = sorted_fields[i]->number();
}
int n_ranges = WriteIntRanges(printer,
descriptor_->field_count(), values,
vars["lcclassname"] + "__number_ranges");
delete [] values;
delete [] sorted_fields;
vars["n_ranges"] = SimpleItoa(n_ranges);
} else {
/* MS compiler can't handle arrays with zero size and empty
* initialization list. Furthermore it is an extension of GCC only but
* not a standard. */
vars["n_ranges"] = "0";
printer->Print(vars,
"#define $lcclassname$__field_descriptors NULL\n"
"#define $lcclassname$__field_indices_by_name NULL\n"
"#define $lcclassname$__number_ranges NULL\n");
}
printer->Print(vars,
"const ProtobufCMessageDescriptor $lcclassname$__descriptor =\n"
"{\n"
" PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC,\n");
if (optimize_code_size) {
printer->Print(" NULL,NULL,NULL,NULL, /* CODE_SIZE */\n");
} else {
printer->Print(vars,
" \"$fullname$\",\n"
" \"$shortname$\",\n"
" \"$classname$\",\n"
" \"$packagename$\",\n");
}
printer->Print(vars,
" sizeof($classname$),\n"
" $n_fields$,\n"
" $lcclassname$__field_descriptors,\n");
if (optimize_code_size) {
printer->Print(" NULL, /* CODE_SIZE */\n");
} else {
printer->Print(vars,
" $lcclassname$__field_indices_by_name,\n");
}
printer->Print(vars,
" $n_ranges$,"
" $lcclassname$__number_ranges,\n");
if (gen_init) {
printer->Print(vars,
" (ProtobufCMessageInit) $lcclassname$__init,\n");
} else {
printer->Print(vars,
" NULL, /* gen_init_helpers = false */\n");
}
printer->Print(vars,
" NULL,NULL,NULL /* reserved[123] */\n"
"};\n");
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,148 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_H__
#define GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_H__
#include <memory>
#include <string>
#include <google/protobuf/stubs/common.h>
#include <protoc-c/c_field.h>
namespace google {
namespace protobuf {
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace c {
class EnumGenerator; // enum.h
class ExtensionGenerator; // extension.h
class MessageGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
explicit MessageGenerator(const Descriptor* descriptor,
const std::string& dllexport_decl);
~MessageGenerator();
// Header stuff.
// Generate typedef.
void GenerateStructTypedef(io::Printer* printer);
// Generate descriptor prototype
void GenerateDescriptorDeclarations(io::Printer* printer);
// Generate descriptor prototype
void GenerateClosureTypedef(io::Printer* printer);
// Generate definitions of all nested enums (must come before class
// definitions because those classes use the enums definitions).
void GenerateEnumDefinitions(io::Printer* printer);
// Generate definitions for this class and all its nested types.
void GenerateStructDefinition(io::Printer* printer);
// Generate __INIT macro for populating this structure
void GenerateStructStaticInitMacro(io::Printer* printer);
// Generate standard helper functions declarations for this message.
void GenerateHelperFunctionDeclarations(io::Printer* printer,
bool is_pack_deep,
bool gen_pack,
bool gen_init);
// Source file stuff.
// Generate code that initializes the global variable storing the message's
// descriptor.
void GenerateMessageDescriptor(io::Printer* printer, bool gen_init);
void GenerateHelperFunctionDefinitions(io::Printer* printer,
bool is_pack_deep,
bool gen_pack,
bool gen_init);
private:
std::string GetDefaultValueC(const FieldDescriptor *fd);
const Descriptor* descriptor_;
std::string dllexport_decl_;
FieldGeneratorMap field_generators_;
std::unique_ptr<std::unique_ptr<MessageGenerator>[]> nested_generators_;
std::unique_ptr<std::unique_ptr<EnumGenerator>[]> enum_generators_;
std::unique_ptr<std::unique_ptr<ExtensionGenerator>[]> extension_generators_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_H__

View File

@@ -0,0 +1,129 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <protoc-c/c_message_field.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
using internal::WireFormat;
// ===================================================================
MessageFieldGenerator::
MessageFieldGenerator(const FieldDescriptor* descriptor)
: FieldGenerator(descriptor) {
}
MessageFieldGenerator::~MessageFieldGenerator() {}
void MessageFieldGenerator::GenerateStructMembers(io::Printer* printer) const
{
std::map<std::string, std::string> vars;
vars["name"] = FieldName(descriptor_);
vars["type"] = FullNameToC(descriptor_->message_type()->full_name(), descriptor_->message_type()->file());
vars["deprecated"] = FieldDeprecated(descriptor_);
switch (descriptor_->label()) {
case FieldDescriptor::LABEL_REQUIRED:
case FieldDescriptor::LABEL_OPTIONAL:
printer->Print(vars, "$type$ *$name$$deprecated$;\n");
break;
case FieldDescriptor::LABEL_REPEATED:
printer->Print(vars, "size_t n_$name$$deprecated$;\n");
printer->Print(vars, "$type$ **$name$$deprecated$;\n");
break;
}
}
std::string MessageFieldGenerator::GetDefaultValue(void) const
{
/* XXX: update when protobuf gets support
* for default-values of message fields.
*/
return "NULL";
}
void MessageFieldGenerator::GenerateStaticInit(io::Printer* printer) const
{
switch (descriptor_->label()) {
case FieldDescriptor::LABEL_REQUIRED:
case FieldDescriptor::LABEL_OPTIONAL:
printer->Print("NULL");
break;
case FieldDescriptor::LABEL_REPEATED:
printer->Print("0,NULL");
break;
}
}
void MessageFieldGenerator::GenerateDescriptorInitializer(io::Printer* printer) const
{
std::string addr = "&" + FullNameToLower(descriptor_->message_type()->full_name(), descriptor_->message_type()->file()) + "__descriptor";
GenerateDescriptorInitializerGeneric(printer, false, "MESSAGE", addr);
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,97 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_FIELD_H__
#include <map>
#include <string>
#include <protoc-c/c_field.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
class MessageFieldGenerator : public FieldGenerator {
public:
explicit MessageFieldGenerator(const FieldDescriptor* descriptor);
~MessageFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateStructMembers(io::Printer* printer) const;
void GenerateDescriptorInitializer(io::Printer* printer) const;
std::string GetDefaultValue(void) const;
void GenerateStaticInit(io::Printer* printer) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_FIELD_H__

View File

@@ -0,0 +1,211 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <protoc-c/c_primitive_field.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
PrimitiveFieldGenerator::
PrimitiveFieldGenerator(const FieldDescriptor* descriptor)
: FieldGenerator(descriptor) {
}
PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {}
void PrimitiveFieldGenerator::GenerateStructMembers(io::Printer* printer) const
{
std::string c_type;
std::map<std::string, std::string> vars;
switch (descriptor_->type()) {
case FieldDescriptor::TYPE_SINT32 :
case FieldDescriptor::TYPE_SFIXED32:
case FieldDescriptor::TYPE_INT32 : c_type = "int32_t"; break;
case FieldDescriptor::TYPE_SINT64 :
case FieldDescriptor::TYPE_SFIXED64:
case FieldDescriptor::TYPE_INT64 : c_type = "int64_t"; break;
case FieldDescriptor::TYPE_UINT32 :
case FieldDescriptor::TYPE_FIXED32 : c_type = "uint32_t"; break;
case FieldDescriptor::TYPE_UINT64 :
case FieldDescriptor::TYPE_FIXED64 : c_type = "uint64_t"; break;
case FieldDescriptor::TYPE_FLOAT : c_type = "float"; break;
case FieldDescriptor::TYPE_DOUBLE : c_type = "double"; break;
case FieldDescriptor::TYPE_BOOL : c_type = "protobuf_c_boolean"; break;
case FieldDescriptor::TYPE_ENUM :
case FieldDescriptor::TYPE_STRING :
case FieldDescriptor::TYPE_BYTES :
case FieldDescriptor::TYPE_GROUP :
case FieldDescriptor::TYPE_MESSAGE : GOOGLE_LOG(FATAL) << "not a primitive type"; break;
// No default because we want the compiler to complain if any new
// types are added.
}
vars["c_type"] = c_type;
vars["name"] = FieldName(descriptor_);
vars["deprecated"] = FieldDeprecated(descriptor_);
switch (descriptor_->label()) {
case FieldDescriptor::LABEL_REQUIRED:
printer->Print(vars, "$c_type$ $name$$deprecated$;\n");
break;
case FieldDescriptor::LABEL_OPTIONAL:
if (descriptor_->containing_oneof() == NULL && FieldSyntax(descriptor_) == 2)
printer->Print(vars, "protobuf_c_boolean has_$name$$deprecated$;\n");
printer->Print(vars, "$c_type$ $name$$deprecated$;\n");
break;
case FieldDescriptor::LABEL_REPEATED:
printer->Print(vars, "size_t n_$name$$deprecated$;\n");
printer->Print(vars, "$c_type$ *$name$$deprecated$;\n");
break;
}
}
std::string PrimitiveFieldGenerator::GetDefaultValue() const
{
/* XXX: SimpleItoa seems woefully inadequate for anything but int32,
* but that's what protobuf uses. */
switch (descriptor_->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return SimpleItoa(descriptor_->default_value_int32());
case FieldDescriptor::CPPTYPE_INT64:
return SimpleItoa(descriptor_->default_value_int64()) + "ll";
case FieldDescriptor::CPPTYPE_UINT32:
return SimpleItoa(descriptor_->default_value_uint32()) + "u";
case FieldDescriptor::CPPTYPE_UINT64:
return SimpleItoa(descriptor_->default_value_uint64()) + "ull";
case FieldDescriptor::CPPTYPE_FLOAT:
return SimpleFtoa(descriptor_->default_value_float());
case FieldDescriptor::CPPTYPE_DOUBLE:
return SimpleDtoa(descriptor_->default_value_double());
case FieldDescriptor::CPPTYPE_BOOL:
return descriptor_->default_value_bool() ? "1" : "0";
default:
GOOGLE_LOG(DFATAL) << "unexpected CPPTYPE in c_primitive_field";
return "UNEXPECTED_CPPTYPE";
}
}
void PrimitiveFieldGenerator::GenerateStaticInit(io::Printer* printer) const
{
std::map<std::string, std::string> vars;
if (descriptor_->has_default_value()) {
vars["default_value"] = GetDefaultValue();
} else {
vars["default_value"] = "0";
}
switch (descriptor_->label()) {
case FieldDescriptor::LABEL_REQUIRED:
printer->Print(vars, "$default_value$");
break;
case FieldDescriptor::LABEL_OPTIONAL:
if (FieldSyntax(descriptor_) == 2)
printer->Print(vars, "0, ");
printer->Print(vars, "$default_value$");
break;
case FieldDescriptor::LABEL_REPEATED:
printer->Print("0,NULL");
break;
}
}
void PrimitiveFieldGenerator::GenerateDescriptorInitializer(io::Printer* printer) const
{
std::string c_type_macro;
switch (descriptor_->type()) {
#define WRITE_CASE(shortname) case FieldDescriptor::TYPE_##shortname: c_type_macro = #shortname; break;
WRITE_CASE(INT32)
WRITE_CASE(SINT32)
WRITE_CASE(UINT32)
WRITE_CASE(SFIXED32)
WRITE_CASE(FIXED32)
WRITE_CASE(INT64)
WRITE_CASE(SINT64)
WRITE_CASE(UINT64)
WRITE_CASE(FIXED64)
WRITE_CASE(SFIXED64)
WRITE_CASE(FLOAT)
WRITE_CASE(DOUBLE)
WRITE_CASE(BOOL)
#undef WRITE_CASE
case FieldDescriptor::TYPE_ENUM :
case FieldDescriptor::TYPE_STRING :
case FieldDescriptor::TYPE_BYTES :
case FieldDescriptor::TYPE_GROUP :
case FieldDescriptor::TYPE_MESSAGE : GOOGLE_LOG(FATAL) << "not a primitive type"; break;
// No default because we want the compiler to complain if any new
// types are added.
}
GenerateDescriptorInitializerGeneric(printer, true, c_type_macro, "NULL");
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,96 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_PRIMITIVE_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_C_PRIMITIVE_FIELD_H__
#include <map>
#include <string>
#include <protoc-c/c_field.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
class PrimitiveFieldGenerator : public FieldGenerator {
public:
explicit PrimitiveFieldGenerator(const FieldDescriptor* descriptor);
~PrimitiveFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateStructMembers(io::Printer* printer) const;
void GenerateDescriptorInitializer(io::Printer* printer) const;
std::string GetDefaultValue(void) const;
void GenerateStaticInit(io::Printer* printer) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_PRIMITIVE_FIELD_H__

View File

@@ -0,0 +1,294 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <protoc-c/c_service.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor,
const std::string& dllexport_decl)
: descriptor_(descriptor) {
vars_["name"] = descriptor_->name();
vars_["fullname"] = descriptor_->full_name();
vars_["cname"] = FullNameToC(descriptor_->full_name(), descriptor_->file());
vars_["lcfullname"] = FullNameToLower(descriptor_->full_name(), descriptor_->file());
vars_["ucfullname"] = FullNameToUpper(descriptor_->full_name(), descriptor_->file());
vars_["lcfullpadd"] = ConvertToSpaces(vars_["lcfullname"]);
vars_["package"] = descriptor_->file()->package();
if (dllexport_decl.empty()) {
vars_["dllexport"] = "";
} else {
vars_["dllexport"] = dllexport_decl + " ";
}
}
ServiceGenerator::~ServiceGenerator() {}
// Header stuff.
void ServiceGenerator::GenerateMainHFile(io::Printer* printer)
{
GenerateVfuncs(printer);
GenerateInitMacros(printer);
GenerateCallersDeclarations(printer);
}
void ServiceGenerator::GenerateVfuncs(io::Printer* printer)
{
printer->Print(vars_,
"typedef struct $cname$_Service $cname$_Service;\n"
"struct $cname$_Service\n"
"{\n"
" ProtobufCService base;\n");
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor *method = descriptor_->method(i);
std::string lcname = CamelToLower(method->name());
vars_["method"] = lcname;
vars_["metpad"] = ConvertToSpaces(lcname);
vars_["input_typename"] = FullNameToC(method->input_type()->full_name(), method->input_type()->file());
vars_["output_typename"] = FullNameToC(method->output_type()->full_name(), method->output_type()->file());
printer->Print(vars_,
" void (*$method$)($cname$_Service *service,\n"
" $metpad$ const $input_typename$ *input,\n"
" $metpad$ $output_typename$_Closure closure,\n"
" $metpad$ void *closure_data);\n");
}
printer->Print(vars_,
"};\n");
printer->Print(vars_,
"typedef void (*$cname$_ServiceDestroy)($cname$_Service *);\n"
"void $lcfullname$__init ($cname$_Service *service,\n"
" $lcfullpadd$ $cname$_ServiceDestroy destroy);\n");
}
void ServiceGenerator::GenerateInitMacros(io::Printer* printer)
{
printer->Print(vars_,
"#define $ucfullname$__BASE_INIT \\\n"
" { &$lcfullname$__descriptor, protobuf_c_service_invoke_internal, NULL }\n"
"#define $ucfullname$__INIT(function_prefix__) \\\n"
" { $ucfullname$__BASE_INIT");
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor *method = descriptor_->method(i);
std::string lcname = CamelToLower(method->name());
vars_["method"] = lcname;
vars_["metpad"] = ConvertToSpaces(lcname);
printer->Print(vars_,
",\\\n function_prefix__ ## $method$");
}
printer->Print(vars_,
" }\n");
}
void ServiceGenerator::GenerateCallersDeclarations(io::Printer* printer)
{
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor *method = descriptor_->method(i);
std::string lcname = CamelToLower(method->name());
std::string lcfullname = FullNameToLower(descriptor_->full_name(), descriptor_->file());
vars_["method"] = lcname;
vars_["metpad"] = ConvertToSpaces(lcname);
vars_["input_typename"] = FullNameToC(method->input_type()->full_name(), method->input_type()->file());
vars_["output_typename"] = FullNameToC(method->output_type()->full_name(), method->output_type()->file());
vars_["padddddddddddddddddd"] = ConvertToSpaces(lcfullname + "__" + lcname);
printer->Print(vars_,
"void $lcfullname$__$method$(ProtobufCService *service,\n"
" $padddddddddddddddddd$ const $input_typename$ *input,\n"
" $padddddddddddddddddd$ $output_typename$_Closure closure,\n"
" $padddddddddddddddddd$ void *closure_data);\n");
}
}
void ServiceGenerator::GenerateDescriptorDeclarations(io::Printer* printer)
{
printer->Print(vars_, "extern const ProtobufCServiceDescriptor $lcfullname$__descriptor;\n");
}
// Source file stuff.
void ServiceGenerator::GenerateCFile(io::Printer* printer)
{
GenerateServiceDescriptor(printer);
GenerateCallersImplementations(printer);
GenerateInit(printer);
}
void ServiceGenerator::GenerateInit(io::Printer* printer)
{
printer->Print(vars_,
"void $lcfullname$__init ($cname$_Service *service,\n"
" $lcfullpadd$ $cname$_ServiceDestroy destroy)\n"
"{\n"
" protobuf_c_service_generated_init (&service->base,\n"
" &$lcfullname$__descriptor,\n"
" (ProtobufCServiceDestroy) destroy);\n"
"}\n");
}
struct MethodIndexAndName { unsigned i; const char *name; };
static int
compare_method_index_and_name_by_name (const void *a, const void *b)
{
const MethodIndexAndName *ma = (const MethodIndexAndName *) a;
const MethodIndexAndName *mb = (const MethodIndexAndName *) b;
return strcmp (ma->name, mb->name);
}
void ServiceGenerator::GenerateServiceDescriptor(io::Printer* printer)
{
int n_methods = descriptor_->method_count();
MethodIndexAndName *mi_array = new MethodIndexAndName[n_methods];
bool optimize_code_size = descriptor_->file()->options().has_optimize_for() &&
descriptor_->file()->options().optimize_for() ==
FileOptions_OptimizeMode_CODE_SIZE;
vars_["n_methods"] = SimpleItoa(n_methods);
printer->Print(vars_, "static const ProtobufCMethodDescriptor $lcfullname$__method_descriptors[$n_methods$] =\n"
"{\n");
for (int i = 0; i < n_methods; i++) {
const MethodDescriptor *method = descriptor_->method(i);
vars_["method"] = method->name();
vars_["input_descriptor"] = "&" + FullNameToLower(method->input_type()->full_name(), method->input_type()->file()) + "__descriptor";
vars_["output_descriptor"] = "&" + FullNameToLower(method->output_type()->full_name(), method->output_type()->file()) + "__descriptor";
if (optimize_code_size) {
printer->Print(vars_,
" { NULL, $input_descriptor$, $output_descriptor$ }, /* CODE_SIZE */\n");
} else {
printer->Print(vars_,
" { \"$method$\", $input_descriptor$, $output_descriptor$ },\n");
}
mi_array[i].i = i;
mi_array[i].name = method->name().c_str();
}
printer->Print(vars_, "};\n");
if (!optimize_code_size) {
qsort ((void*)mi_array, n_methods, sizeof (MethodIndexAndName),
compare_method_index_and_name_by_name);
printer->Print(vars_, "const unsigned $lcfullname$__method_indices_by_name[] = {\n");
for (int i = 0; i < n_methods; i++) {
vars_["i"] = SimpleItoa(mi_array[i].i);
vars_["name"] = mi_array[i].name;
vars_["comma"] = (i + 1 < n_methods) ? "," : " ";
printer->Print(vars_, " $i$$comma$ /* $name$ */\n");
}
printer->Print(vars_, "};\n");
vars_["name"] = descriptor_->name();
}
if (optimize_code_size) {
printer->Print(vars_, "const ProtobufCServiceDescriptor $lcfullname$__descriptor =\n"
"{\n"
" PROTOBUF_C__SERVICE_DESCRIPTOR_MAGIC,\n"
" NULL,NULL,NULL,NULL, /* CODE_SIZE */\n"
" $n_methods$,\n"
" $lcfullname$__method_descriptors,\n"
" NULL /* CODE_SIZE */\n"
"};\n");
} else {
printer->Print(vars_, "const ProtobufCServiceDescriptor $lcfullname$__descriptor =\n"
"{\n"
" PROTOBUF_C__SERVICE_DESCRIPTOR_MAGIC,\n"
" \"$fullname$\",\n"
" \"$name$\",\n"
" \"$cname$\",\n"
" \"$package$\",\n"
" $n_methods$,\n"
" $lcfullname$__method_descriptors,\n"
" $lcfullname$__method_indices_by_name\n"
"};\n");
}
delete[] mi_array;
}
void ServiceGenerator::GenerateCallersImplementations(io::Printer* printer)
{
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor *method = descriptor_->method(i);
std::string lcname = CamelToLower(method->name());
std::string lcfullname = FullNameToLower(descriptor_->full_name(), descriptor_->file());
vars_["method"] = lcname;
vars_["metpad"] = ConvertToSpaces(lcname);
vars_["input_typename"] = FullNameToC(method->input_type()->full_name(), method->input_type()->file());
vars_["output_typename"] = FullNameToC(method->output_type()->full_name(), method->output_type()->file());
vars_["padddddddddddddddddd"] = ConvertToSpaces(lcfullname + "__" + lcname);
vars_["index"] = SimpleItoa(i);
printer->Print(vars_,
"void $lcfullname$__$method$(ProtobufCService *service,\n"
" $padddddddddddddddddd$ const $input_typename$ *input,\n"
" $padddddddddddddddddd$ $output_typename$_Closure closure,\n"
" $padddddddddddddddddd$ void *closure_data)\n"
"{\n"
" assert(service->descriptor == &$lcfullname$__descriptor);\n"
" service->invoke(service, $index$, (const ProtobufCMessage *) input, (ProtobufCClosure) closure, closure_data);\n"
"}\n");
}
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,112 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_SERVICE_H__
#define GOOGLE_PROTOBUF_COMPILER_C_SERVICE_H__
#include <map>
#include <string>
#include <google/protobuf/descriptor.h>
namespace google {
namespace protobuf {
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace c {
class ServiceGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
explicit ServiceGenerator(const ServiceDescriptor* descriptor,
const std::string& dllexport_decl);
~ServiceGenerator();
// Header stuff.
void GenerateMainHFile(io::Printer* printer);
void GenerateVfuncs(io::Printer* printer);
void GenerateInitMacros(io::Printer* printer);
void GenerateDescriptorDeclarations(io::Printer* printer);
void GenerateCallersDeclarations(io::Printer* printer);
// Source file stuff.
void GenerateCFile(io::Printer* printer);
void GenerateServiceDescriptor(io::Printer* printer);
void GenerateInit(io::Printer* printer);
void GenerateCallersImplementations(io::Printer* printer);
const ServiceDescriptor* descriptor_;
std::map<std::string, std::string> vars_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ServiceGenerator);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_SERVICE_H__

View File

@@ -0,0 +1,160 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#include <protoc-c/c_string_field.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
#include <protobuf-c/protobuf-c.pb.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
using internal::WireFormat;
void SetStringVariables(const FieldDescriptor* descriptor,
std::map<std::string, std::string>* variables) {
(*variables)["name"] = FieldName(descriptor);
(*variables)["default"] = FullNameToLower(descriptor->full_name(), descriptor->file())
+ "__default_value";
(*variables)["deprecated"] = FieldDeprecated(descriptor);
}
// ===================================================================
StringFieldGenerator::
StringFieldGenerator(const FieldDescriptor* descriptor)
: FieldGenerator(descriptor) {
SetStringVariables(descriptor, &variables_);
}
StringFieldGenerator::~StringFieldGenerator() {}
void StringFieldGenerator::GenerateStructMembers(io::Printer* printer) const
{
const ProtobufCFileOptions opt = descriptor_->file()->options().GetExtension(pb_c_file);
switch (descriptor_->label()) {
case FieldDescriptor::LABEL_REQUIRED:
case FieldDescriptor::LABEL_OPTIONAL:
if (opt.const_strings())
printer->Print(variables_, "const ");
printer->Print(variables_, "char *$name$$deprecated$;\n");
break;
case FieldDescriptor::LABEL_REPEATED:
printer->Print(variables_, "size_t n_$name$$deprecated$;\n");
if (opt.const_strings())
printer->Print(variables_, "const ");
printer->Print(variables_, "char **$name$$deprecated$;\n");
break;
}
}
void StringFieldGenerator::GenerateDefaultValueDeclarations(io::Printer* printer) const
{
printer->Print(variables_, "extern char $default$[];\n");
}
void StringFieldGenerator::GenerateDefaultValueImplementations(io::Printer* printer) const
{
std::map<std::string, std::string> vars;
vars["default"] = variables_.find("default")->second;
vars["escaped"] = CEscape(descriptor_->default_value_string());
printer->Print(vars, "char $default$[] = \"$escaped$\";\n");
}
std::string StringFieldGenerator::GetDefaultValue(void) const
{
return variables_.find("default")->second;
}
void StringFieldGenerator::GenerateStaticInit(io::Printer* printer) const
{
std::map<std::string, std::string> vars;
const ProtobufCFileOptions opt = descriptor_->file()->options().GetExtension(pb_c_file);
if (descriptor_->has_default_value()) {
vars["default"] = GetDefaultValue();
} else if (FieldSyntax(descriptor_) == 2) {
vars["default"] = "NULL";
} else if (opt.const_strings()) {
vars["default"] = "(const char *)protobuf_c_empty_string";
} else {
vars["default"] = "(char *)protobuf_c_empty_string";
}
switch (descriptor_->label()) {
case FieldDescriptor::LABEL_REQUIRED:
case FieldDescriptor::LABEL_OPTIONAL:
printer->Print(vars, "$default$");
break;
case FieldDescriptor::LABEL_REPEATED:
printer->Print(vars, "0,NULL");
break;
}
}
void StringFieldGenerator::GenerateDescriptorInitializer(io::Printer* printer) const
{
GenerateDescriptorInitializerGeneric(printer, false, "STRING", "NULL");
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google

View File

@@ -0,0 +1,100 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Modified to implement C code by Dave Benson.
#ifndef GOOGLE_PROTOBUF_COMPILER_C_STRING_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_C_STRING_FIELD_H__
#include <map>
#include <string>
#include <protoc-c/c_field.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
class StringFieldGenerator : public FieldGenerator {
public:
explicit StringFieldGenerator(const FieldDescriptor* descriptor);
~StringFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateStructMembers(io::Printer* printer) const;
void GenerateDescriptorInitializer(io::Printer* printer) const;
void GenerateDefaultValueDeclarations(io::Printer* printer) const;
void GenerateDefaultValueImplementations(io::Printer* printer) const;
std::string GetDefaultValue(void) const;
void GenerateStaticInit(io::Printer* printer) const;
private:
std::map<std::string, std::string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator);
};
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_C_STRING_FIELD_H__

View File

@@ -0,0 +1,22 @@
#include <string>
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/compiler/command_line_interface.h>
#include <protoc-c/c_generator.h>
int main(int argc, char* argv[]) {
google::protobuf::compiler::c::CGenerator c_generator;
std::string invocation_name = argv[0];
std::string invocation_basename = invocation_name.substr(invocation_name.find_last_of("/") + 1);
const std::string legacy_name = "protoc-c";
if (invocation_basename == legacy_name) {
google::protobuf::compiler::CommandLineInterface cli;
cli.RegisterGenerator("--c_out", &c_generator, "Generate C/H files.");
cli.SetVersionInfo(PACKAGE_STRING);
return cli.Run(argc, argv);
}
return google::protobuf::compiler::PluginMain(argc, argv, &c_generator);
}