Commit 71f662c3 authored by csharptest's avatar csharptest Committed by rogerk

reformatted all code to .NET standard formatting

parent d965c666
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,18 +31,21 @@
// 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.
#endregion
using System;
using System.IO;
namespace Google.ProtocolBuffers.Examples.AddressBook
{
class AddPerson {
internal class AddPerson
{
/// <summary>
/// Builds a person based on user input
/// </summary>
static Person PromptForAddress(TextReader input, TextWriter output) {
private static Person PromptForAddress(TextReader input, TextWriter output)
{
Person.Builder person = Person.CreateBuilder();
output.Write("Enter person ID: ");
......@@ -52,14 +56,17 @@ namespace Google.ProtocolBuffers.Examples.AddressBook
output.Write("Enter email address (blank for none): ");
string email = input.ReadLine();
if (email.Length > 0) {
if (email.Length > 0)
{
person.Email = email;
}
while (true) {
while (true)
{
output.Write("Enter a phone number (or leave blank to finish): ");
string number = input.ReadLine();
if (number.Length == 0) {
if (number.Length == 0)
{
break;
}
......@@ -68,7 +75,8 @@ namespace Google.ProtocolBuffers.Examples.AddressBook
output.Write("Is this a mobile, home, or work phone? ");
String type = input.ReadLine();
switch (type) {
switch (type)
{
case "mobile":
phoneNumber.Type = Person.Types.PhoneType.MOBILE;
break;
......@@ -92,19 +100,25 @@ namespace Google.ProtocolBuffers.Examples.AddressBook
/// Entry point - loads an existing addressbook or creates a new one,
/// then writes it back to the file.
/// </summary>
public static int Main(string[] args) {
if (args.Length != 1) {
public static int Main(string[] args)
{
if (args.Length != 1)
{
Console.Error.WriteLine("Usage: AddPerson ADDRESS_BOOK_FILE");
return -1;
}
AddressBook.Builder addressBook = AddressBook.CreateBuilder();
if (File.Exists(args[0])) {
using (Stream file = File.OpenRead(args[0])) {
if (File.Exists(args[0]))
{
using (Stream file = File.OpenRead(args[0]))
{
addressBook.MergeFrom(file);
}
} else {
}
else
{
Console.WriteLine("{0}: File not found. Creating a new file.", args[0]);
}
......@@ -112,7 +126,8 @@ namespace Google.ProtocolBuffers.Examples.AddressBook
addressBook.AddPerson(PromptForAddress(Console.In, Console.Out));
// Write the new address book back to disk.
using (Stream output = File.OpenWrite(args[0])) {
using (Stream output = File.OpenWrite(args[0]))
{
addressBook.Build().WriteTo(output);
}
return 0;
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,26 +31,34 @@
// 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.
#endregion
using System;
using System.IO;
namespace Google.ProtocolBuffers.Examples.AddressBook {
class ListPeople {
namespace Google.ProtocolBuffers.Examples.AddressBook
{
internal class ListPeople
{
/// <summary>
/// Iterates though all people in the AddressBook and prints info about them.
/// </summary>
static void Print(AddressBook addressBook) {
foreach (Person person in addressBook.PersonList) {
private static void Print(AddressBook addressBook)
{
foreach (Person person in addressBook.PersonList)
{
Console.WriteLine("Person ID: {0}", person.Id);
Console.WriteLine(" Name: {0}", person.Name);
if (person.HasEmail) {
if (person.HasEmail)
{
Console.WriteLine(" E-mail address: {0}", person.Email);
}
foreach (Person.Types.PhoneNumber phoneNumber in person.PhoneList) {
switch (phoneNumber.Type) {
foreach (Person.Types.PhoneNumber phoneNumber in person.PhoneList)
{
switch (phoneNumber.Type)
{
case Person.Types.PhoneType.MOBILE:
Console.Write(" Mobile phone #: ");
break;
......@@ -68,19 +77,23 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
/// <summary>
/// Entry point - loads the addressbook and then displays it.
/// </summary>
public static int Main(string[] args) {
if (args.Length != 1) {
public static int Main(string[] args)
{
if (args.Length != 1)
{
Console.Error.WriteLine("Usage: ListPeople ADDRESS_BOOK_FILE");
return 1;
}
if (!File.Exists(args[0])) {
if (!File.Exists(args[0]))
{
Console.WriteLine("{0} doesn't exist. Add a person to create the file first.", args[0]);
return 0;
}
// Read the existing address book.
using (Stream stream = File.OpenRead(args[0])) {
using (Stream stream = File.OpenRead(args[0]))
{
AddressBook addressBook = AddressBook.ParseFrom(stream);
Print(addressBook);
}
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,6 +31,7 @@
// 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.
#endregion
using System;
......@@ -41,9 +43,12 @@ namespace Google.ProtocolBuffers.Examples.AddressBook
/// to individual actions. Each action has its own Main method, so that it can be used as an
/// invidual complete program.
/// </summary>
class Program {
static int Main(string[] args) {
if (args.Length > 1) {
internal class Program
{
private static int Main(string[] args)
{
if (args.Length > 1)
{
Console.Error.WriteLine("Usage: AddressBook [file]");
Console.Error.WriteLine("If the filename isn't specified, \"addressbook.data\" is used instead.");
return 1;
......@@ -51,7 +56,8 @@ namespace Google.ProtocolBuffers.Examples.AddressBook
string addressBookFile = args.Length > 0 ? args[0] : "addressbook.data";
bool stopping = false;
while (!stopping) {
while (!stopping)
{
Console.WriteLine("Options:");
Console.WriteLine(" L: List contents");
Console.WriteLine(" A: Add new person");
......@@ -60,15 +66,17 @@ namespace Google.ProtocolBuffers.Examples.AddressBook
Console.Out.Flush();
char choice = Console.ReadKey().KeyChar;
Console.WriteLine();
try {
switch (choice) {
try
{
switch (choice)
{
case 'A':
case 'a':
AddPerson.Main(new string[] { addressBookFile });
AddPerson.Main(new string[] {addressBookFile});
break;
case 'L':
case 'l':
ListPeople.Main(new string[] { addressBookFile });
ListPeople.Main(new string[] {addressBookFile});
break;
case 'Q':
case 'q':
......@@ -78,7 +86,9 @@ namespace Google.ProtocolBuffers.Examples.AddressBook
Console.WriteLine("Unknown option: {0}", choice);
break;
}
} catch (Exception e) {
}
catch (Exception e)
{
Console.WriteLine("Exception executing action: {0}", e);
}
Console.WriteLine();
......
......@@ -4,6 +4,7 @@ using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AddressBook")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
......@@ -16,9 +17,11 @@ using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("57123e6e-28d1-4b9e-80a5-5e720df8035a")]
// Version information for an assembly consists of the following four values:
......@@ -31,5 +34,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyFileVersion("2.3.0.277")]
\ No newline at end of file
......@@ -3,9 +3,9 @@ using System.IO;
namespace Google.ProtocolBuffers.Examples.AddressBook
{
class SampleUsage
{
static void Main()
internal class SampleUsage
{
private static void Main()
{
byte[] bytes;
//Create a builder to start building a message
......@@ -23,7 +23,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook
Person person = newContact.Build();
//The builder is no longer valid (at least not now, scheduled for 2.4):
newContact = null;
using(MemoryStream stream = new MemoryStream())
using (MemoryStream stream = new MemoryStream())
{
//Save the person to a stream
person.WriteTo(stream);
......@@ -37,8 +37,8 @@ namespace Google.ProtocolBuffers.Examples.AddressBook
//And read the address book back again
AddressBook restored = AddressBook.CreateBuilder().MergeFrom(bytes).Build();
//The message performs a deep-comparison on equality:
if(restored.PersonCount != 1 || !person.Equals(restored.PersonList[0]))
if (restored.PersonCount != 1 || !person.Equals(restored.PersonList[0]))
throw new ApplicationException("There is a bad person in here!");
}
}
}
}
\ No newline at end of file
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,6 +31,7 @@
// 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.
#endregion
using System;
......@@ -41,24 +43,28 @@ namespace Google.ProtocolBuffers.ProtoBench
/// <summary>
/// Simple benchmarking of arbitrary messages.
/// </summary>
public sealed class Program {
public sealed class Program
{
private static readonly TimeSpan MinSampleTime = TimeSpan.FromSeconds(2);
private static readonly TimeSpan TargetTime = TimeSpan.FromSeconds(30);
// Avoid a .NET 3.5 dependency
delegate void Action();
private delegate void Action();
public static int Main(string[] args) {
if (args.Length < 2 || (args.Length % 2) != 0) {
public static int Main(string[] args)
{
if (args.Length < 2 || (args.Length%2) != 0)
{
Console.Error.WriteLine("Usage: ProtoBench <descriptor type name> <input data>");
Console.Error.WriteLine("The descriptor type name is the fully-qualified message name,");
Console.Error.WriteLine("including assembly - e.g. Google.ProtocolBuffers.BenchmarkProtos.Message1,ProtoBench");
Console.Error.WriteLine(
"including assembly - e.g. Google.ProtocolBuffers.BenchmarkProtos.Message1,ProtoBench");
Console.Error.WriteLine("(You can specify multiple pairs of descriptor type name and input data.)");
return 1;
}
bool success = true;
for (int i = 0; i < args.Length; i += 2) {
for (int i = 0; i < args.Length; i += 2)
{
success &= RunTest(args[i], args[i + 1]);
}
return success ? 0 : 1;
......@@ -68,23 +74,30 @@ namespace Google.ProtocolBuffers.ProtoBench
/// Runs a single test. Error messages are displayed to Console.Error, and the return value indicates
/// general success/failure.
/// </summary>
public static bool RunTest(string typeName, string file) {
public static bool RunTest(string typeName, string file)
{
Console.WriteLine("Benchmarking {0} with file {1}", typeName, file);
IMessage defaultMessage;
try {
try
{
defaultMessage = MessageUtil.GetDefaultMessage(typeName);
} catch (ArgumentException e) {
}
catch (ArgumentException e)
{
Console.Error.WriteLine(e.Message);
return false;
}
try {
try
{
byte[] inputData = File.ReadAllBytes(file);
MemoryStream inputStream = new MemoryStream(inputData);
ByteString inputString = ByteString.CopyFrom(inputData);
IMessage sampleMessage = defaultMessage.WeakCreateBuilderForType().WeakMergeFrom(inputString).WeakBuild();
IMessage sampleMessage =
defaultMessage.WeakCreateBuilderForType().WeakMergeFrom(inputString).WeakBuild();
Benchmark("Serialize to byte string", inputData.Length, () => sampleMessage.ToByteString());
Benchmark("Serialize to byte array", inputData.Length, () => sampleMessage.ToByteArray());
Benchmark("Serialize to memory stream", inputData.Length, () => sampleMessage.WriteTo(new MemoryStream()));
Benchmark("Serialize to memory stream", inputData.Length,
() => sampleMessage.WriteTo(new MemoryStream()));
Benchmark("Deserialize from byte string", inputData.Length,
() => defaultMessage.WeakCreateBuilderForType()
.WeakMergeFrom(inputString)
......@@ -95,15 +108,22 @@ namespace Google.ProtocolBuffers.ProtoBench
.WeakMergeFrom(CodedInputStream.CreateInstance(inputData))
.WeakBuild()
);
Benchmark("Deserialize from memory stream", inputData.Length, () => {
Benchmark("Deserialize from memory stream", inputData.Length, () =>
{
inputStream.Position = 0;
defaultMessage.WeakCreateBuilderForType()
.WeakMergeFrom(CodedInputStream.CreateInstance(inputStream))
defaultMessage.
WeakCreateBuilderForType()
.WeakMergeFrom(
CodedInputStream.
CreateInstance(
inputStream))
.WeakBuild();
});
Console.WriteLine();
return true;
} catch (Exception e) {
}
catch (Exception e)
{
Console.Error.WriteLine("Error: {0}", e.Message);
Console.Error.WriteLine();
Console.Error.WriteLine("Detailed exception information: {0}", e);
......@@ -111,31 +131,35 @@ namespace Google.ProtocolBuffers.ProtoBench
}
}
private static void Benchmark(string name, long dataSize, Action action) {
private static void Benchmark(string name, long dataSize, Action action)
{
// Make sure it's JITted
action();
// Run it progressively more times until we've got a reasonable sample
int iterations = 1;
TimeSpan elapsed = TimeAction(action, iterations);
while (elapsed < MinSampleTime) {
while (elapsed < MinSampleTime)
{
iterations *= 2;
elapsed = TimeAction(action, iterations);
}
// Upscale the sample to the target time. Do this in floating point arithmetic
// to avoid overflow issues.
iterations = (int) ((TargetTime.Ticks / (double)elapsed.Ticks) * iterations);
iterations = (int) ((TargetTime.Ticks/(double) elapsed.Ticks)*iterations);
elapsed = TimeAction(action, iterations);
Console.WriteLine("{0}: {1} iterations in {2:f3}s; {3:f3}MB/s",
name, iterations, elapsed.TotalSeconds,
(iterations * dataSize) / (elapsed.TotalSeconds * 1024 * 1024));
(iterations*dataSize)/(elapsed.TotalSeconds*1024*1024));
}
private static TimeSpan TimeAction(Action action, int iterations) {
private static TimeSpan TimeAction(Action action, int iterations)
{
GC.Collect();
GC.WaitForPendingFinalizers();
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++) {
for (int i = 0; i < iterations; i++)
{
action();
}
sw.Stop();
......
......@@ -6,6 +6,7 @@ using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ProtoBench")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
......@@ -18,11 +19,12 @@ using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0f515d09-9a6c-49ec-8500-14a5303ebadf")]
// Version information for an assembly consists of the following four values:
......@@ -35,5 +37,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyFileVersion("2.3.0.277")]
\ No newline at end of file
#region Copyright notice and license
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,6 +31,7 @@
// 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.
#endregion
using System;
......@@ -40,24 +42,32 @@ namespace Google.ProtocolBuffers.ProtoDump
/// <summary>
/// Small utility to load a binary message and dump it in text form
/// </summary>
class Program {
static int Main(string[] args) {
if (args.Length != 2) {
internal class Program
{
private static int Main(string[] args)
{
if (args.Length != 2)
{
Console.Error.WriteLine("Usage: ProtoDump <descriptor type name> <input data>");
Console.Error.WriteLine("The descriptor type name is the fully-qualified message name,");
Console.Error.WriteLine("including assembly e.g. ProjectNamespace.Message,Company.Project");
return 1;
}
IMessage defaultMessage;
try {
try
{
defaultMessage = MessageUtil.GetDefaultMessage(args[0]);
} catch (ArgumentException e) {
}
catch (ArgumentException e)
{
Console.Error.WriteLine(e.Message);
return 1;
}
try {
try
{
IBuilder builder = defaultMessage.WeakCreateBuilderForType();
if (builder == null) {
if (builder == null)
{
Console.Error.WriteLine("Unable to create builder");
return 1;
}
......@@ -65,7 +75,9 @@ namespace Google.ProtocolBuffers.ProtoDump
builder.WeakMergeFrom(ByteString.CopyFrom(inputData));
Console.WriteLine(TextFormat.PrintToString(builder.WeakBuild()));
return 0;
} catch (Exception e) {
}
catch (Exception e)
{
Console.Error.WriteLine("Error: {0}", e.Message);
Console.Error.WriteLine();
Console.Error.WriteLine("Detailed exception information: {0}", e);
......
......@@ -5,6 +5,7 @@ using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ProtoDump")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
......@@ -17,9 +18,11 @@ using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fed7572b-d747-4704-a6da-6c3c61088346")]
// Version information for an assembly consists of the following four values:
......@@ -32,5 +35,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyFileVersion("2.3.0.277")]
\ No newline at end of file
<?xml version="1.0"?>
<configuration>
<startup/></configuration>
<startup />
</configuration>
\ No newline at end of file
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,6 +31,7 @@
// 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.
#endregion
using System.Collections.Generic;
......@@ -37,18 +39,20 @@ using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors;
using NUnit.Framework;
namespace Google.ProtocolBuffers.ProtoGen {
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Tests for the dependency resolution in Generator.
/// </summary>
[TestFixture]
public class DependencyResolutionTest {
public class DependencyResolutionTest
{
[Test]
public void TwoDistinctFiles() {
FileDescriptorProto first = new FileDescriptorProto.Builder { Name="First" }.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder { Name="Second" }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } };
public void TwoDistinctFiles()
{
FileDescriptorProto first = new FileDescriptorProto.Builder {Name = "First"}.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder {Name = "Second"}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first, second}};
IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count);
......@@ -59,10 +63,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
}
[Test]
public void FirstDependsOnSecond() {
FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First", DependencyList = {"Second"} }.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder { Name = "Second" }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } };
public void FirstDependsOnSecond()
{
FileDescriptorProto first =
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"Second"}}.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder {Name = "Second"}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first, second}};
IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count);
Assert.AreEqual("First", converted[0].Name);
......@@ -73,10 +79,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
}
[Test]
public void SecondDependsOnFirst() {
FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First" }.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder { Name = "Second", DependencyList = {"First"} }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } };
public void SecondDependsOnFirst()
{
FileDescriptorProto first = new FileDescriptorProto.Builder {Name = "First"}.Build();
FileDescriptorProto second =
new FileDescriptorProto.Builder {Name = "Second", DependencyList = {"First"}}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first, second}};
IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count);
Assert.AreEqual("First", converted[0].Name);
......@@ -87,38 +95,54 @@ namespace Google.ProtocolBuffers.ProtoGen {
}
[Test]
public void CircularDependency() {
FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First", DependencyList = { "Second" } }.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder { Name = "Second", DependencyList = { "First" } }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first, second } };
try {
public void CircularDependency()
{
FileDescriptorProto first =
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"Second"}}.Build();
FileDescriptorProto second =
new FileDescriptorProto.Builder {Name = "Second", DependencyList = {"First"}}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first, second}};
try
{
Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.Fail("Expected exception");
} catch (DependencyResolutionException) {
}
catch (DependencyResolutionException)
{
// Expected
}
}
[Test]
public void MissingDependency() {
FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First", DependencyList = { "Second" } }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first } };
try {
public void MissingDependency()
{
FileDescriptorProto first =
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"Second"}}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first}};
try
{
Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.Fail("Expected exception");
} catch (DependencyResolutionException) {
}
catch (DependencyResolutionException)
{
// Expected
}
}
[Test]
public void SelfDependency() {
FileDescriptorProto first = new FileDescriptorProto.Builder { Name = "First", DependencyList = { "First" } }.Build();
FileDescriptorSet set = new FileDescriptorSet { FileList = { first } };
try {
public void SelfDependency()
{
FileDescriptorProto first =
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"First"}}.Build();
FileDescriptorSet set = new FileDescriptorSet {FileList = {first}};
try
{
Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.Fail("Expected exception");
} catch (DependencyResolutionException) {
}
catch (DependencyResolutionException)
{
// Expected
}
}
......
......@@ -5,6 +5,7 @@ using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ProtoGen.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
......@@ -17,9 +18,11 @@ using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("40720ee3-2d15-4271-8c42-8f9cfd01b52f")]
// Version information for an assembly consists of the following four values:
......@@ -32,5 +35,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyFileVersion("2.3.0.277")]
\ No newline at end of file
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Google.ProtocolBuffers.ProtoGen
{
class ProtoFile : TempFile
internal class ProtoFile : TempFile
{
public ProtoFile(string filename, string contents)
: base(filename, contents)
{
}
}
class TempFile : IDisposable
internal class TempFile : IDisposable
{
private string tempFile;
......@@ -21,7 +22,8 @@ namespace Google.ProtocolBuffers.ProtoGen
return new TempFile(path, null);
}
protected TempFile(string filename, string contents) {
protected TempFile(string filename, string contents)
{
tempFile = filename;
if (contents != null)
{
......@@ -34,7 +36,10 @@ namespace Google.ProtocolBuffers.ProtoGen
{
}
public string TempPath { get { return tempFile; } }
public string TempPath
{
get { return tempFile; }
}
public void ChangeExtension(string ext)
{
......
This diff is collapsed.
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,20 +31,25 @@
// 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.
#endregion
using System;
namespace Google.ProtocolBuffers.ProtoGen {
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Exception thrown when dependencies within a descriptor set can't be resolved.
/// </summary>
public sealed class DependencyResolutionException : Exception {
public DependencyResolutionException(string message) : base(message) {
public sealed class DependencyResolutionException : Exception
{
public DependencyResolutionException(string message) : base(message)
{
}
public DependencyResolutionException(string format, params object[] args)
: base(string.Format(format, args)) {
: base(string.Format(format, args))
{
}
}
}
\ No newline at end of file
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,22 +31,26 @@
// 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.
#endregion
using System;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Utility class for determining namespaces etc.
/// </summary>
internal static class DescriptorUtil {
internal static string GetFullUmbrellaClassName(IDescriptor descriptor) {
internal static class DescriptorUtil
{
internal static string GetFullUmbrellaClassName(IDescriptor descriptor)
{
CSharpFileOptions options = descriptor.File.CSharpOptions;
string result = options.Namespace;
if (result != "") {
if (result != "")
{
result += '.';
}
result += GetQualifiedUmbrellaClassName(options);
......@@ -57,27 +62,42 @@ namespace Google.ProtocolBuffers.ProtoGen {
/// relative to the descriptor type's namespace. Basically concatenates the
/// UmbrellaNamespace + UmbrellaClassname fields.
/// </summary>
internal static string GetQualifiedUmbrellaClassName(CSharpFileOptions options) {
internal static string GetQualifiedUmbrellaClassName(CSharpFileOptions options)
{
string fullName = options.UmbrellaClassname;
if (!options.NestClasses && options.UmbrellaNamespace != "") {
if (!options.NestClasses && options.UmbrellaNamespace != "")
{
fullName = String.Format("{0}.{1}", options.UmbrellaNamespace, options.UmbrellaClassname);
}
return fullName;
}
internal static string GetMappedTypeName(MappedType type) {
switch(type) {
case MappedType.Int32: return "int";
case MappedType.Int64: return "long";
case MappedType.UInt32: return "uint";
case MappedType.UInt64: return "ulong";
case MappedType.Single: return "float";
case MappedType.Double: return "double";
case MappedType.Boolean: return "bool";
case MappedType.String: return "string";
case MappedType.ByteString: return "pb::ByteString";
case MappedType.Enum: return null;
case MappedType.Message: return null;
internal static string GetMappedTypeName(MappedType type)
{
switch (type)
{
case MappedType.Int32:
return "int";
case MappedType.Int64:
return "long";
case MappedType.UInt32:
return "uint";
case MappedType.UInt64:
return "ulong";
case MappedType.Single:
return "float";
case MappedType.Double:
return "double";
case MappedType.Boolean:
return "bool";
case MappedType.String:
return "string";
case MappedType.ByteString:
return "pb::ByteString";
case MappedType.Enum:
return null;
case MappedType.Message:
return null;
default:
throw new ArgumentOutOfRangeException("Unknown mapped type " + type);
}
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,17 +31,22 @@
// 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.
#endregion
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
internal class EnumFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator {
namespace Google.ProtocolBuffers.ProtoGen
{
internal class EnumFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator
{
internal EnumFieldGenerator(FieldDescriptor descriptor)
: base(descriptor) {
: base(descriptor)
{
}
public void GenerateMembers(TextGenerator writer) {
public void GenerateMembers(TextGenerator writer)
{
writer.WriteLine("private bool has{0};", PropertyName);
writer.WriteLine("private {0} {1}_ = {2};", TypeName, Name, DefaultValue);
writer.WriteLine("public bool Has{0} {{", PropertyName);
......@@ -52,7 +58,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateBuilderMembers(TextGenerator writer) {
public void GenerateBuilderMembers(TextGenerator writer)
{
writer.WriteLine("public bool Has{0} {{", PropertyName);
writer.WriteLine(" get {{ return result.Has{0}; }}", PropertyName);
writer.WriteLine("}");
......@@ -74,21 +81,25 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateMergingCode(TextGenerator writer) {
public void GenerateMergingCode(TextGenerator writer)
{
writer.WriteLine("if (other.Has{0}) {{", PropertyName);
writer.WriteLine(" {0} = other.{0};", PropertyName);
writer.WriteLine("}");
}
public void GenerateBuildingCode(TextGenerator writer) {
public void GenerateBuildingCode(TextGenerator writer)
{
// Nothing to do here for enum types
}
public void GenerateParsingCode(TextGenerator writer) {
public void GenerateParsingCode(TextGenerator writer)
{
// TODO(jonskeet): Make a more efficient way of doing this
writer.WriteLine("int rawValue = input.ReadEnum();");
writer.WriteLine("if (!global::System.Enum.IsDefined(typeof({0}), rawValue)) {{", TypeName);
if (!UseLiteRuntime) {
if (!UseLiteRuntime)
{
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }");
......@@ -99,27 +110,33 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateSerializationCode(TextGenerator writer) {
public void GenerateSerializationCode(TextGenerator writer)
{
writer.WriteLine("if (Has{0}) {{", PropertyName);
writer.WriteLine(" output.WriteEnum({0}, (int) {1});", Number, PropertyName);
writer.WriteLine("}");
}
public void GenerateSerializedSizeCode(TextGenerator writer) {
public void GenerateSerializedSizeCode(TextGenerator writer)
{
writer.WriteLine("if (Has{0}) {{", PropertyName);
writer.WriteLine(" size += pb::CodedOutputStream.ComputeEnumSize({0}, (int) {1});", Number, PropertyName);
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
public override void WriteHash(TextGenerator writer)
{
writer.WriteLine("if (has{0}) hash ^= {1}_.GetHashCode();", PropertyName, Name);
}
public override void WriteEquals(TextGenerator writer) {
writer.WriteLine("if (has{0} != other.has{0} || (has{0} && !{1}_.Equals(other.{1}_))) return false;", PropertyName, Name);
public override void WriteEquals(TextGenerator writer)
{
writer.WriteLine("if (has{0} != other.has{0} || (has{0} && !{1}_.Equals(other.{1}_))) return false;",
PropertyName, Name);
}
public override void WriteToString(TextGenerator writer) {
public override void WriteToString(TextGenerator writer)
{
writer.WriteLine("PrintField(\"{0}\", has{1}, {2}_, writer);", Descriptor.Name, PropertyName, Name);
}
}
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,20 +31,26 @@
// 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.
#endregion
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
internal class EnumGenerator : SourceGeneratorBase<EnumDescriptor>, ISourceGenerator {
internal EnumGenerator(EnumDescriptor descriptor) : base(descriptor) {
namespace Google.ProtocolBuffers.ProtoGen
{
internal class EnumGenerator : SourceGeneratorBase<EnumDescriptor>, ISourceGenerator
{
internal EnumGenerator(EnumDescriptor descriptor) : base(descriptor)
{
}
// TODO(jonskeet): Write out enum descriptors? Can be retrieved from file...
public void Generate(TextGenerator writer) {
public void Generate(TextGenerator writer)
{
writer.WriteLine("{0} enum {1} {{", ClassAccessLevel, Descriptor.Name);
writer.Indent();
foreach (EnumValueDescriptor value in Descriptor.Values) {
foreach (EnumValueDescriptor value in Descriptor.Values)
{
writer.WriteLine("{0} = {1},", value.Name, value.Number);
}
writer.Outdent();
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,28 +31,35 @@
// 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.
#endregion
using System;
using System.Globalization;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
internal class ExtensionGenerator : FieldGeneratorBase, ISourceGenerator {
namespace Google.ProtocolBuffers.ProtoGen
{
internal class ExtensionGenerator : FieldGeneratorBase, ISourceGenerator
{
private readonly string extends;
private readonly string scope;
private readonly string type;
private readonly string name;
internal ExtensionGenerator(FieldDescriptor descriptor)
: base(descriptor) {
if (Descriptor.ExtensionScope != null) {
: base(descriptor)
{
if (Descriptor.ExtensionScope != null)
{
scope = GetClassName(Descriptor.ExtensionScope);
} else {
}
else
{
scope = DescriptorUtil.GetFullUmbrellaClassName(Descriptor.File);
}
switch (Descriptor.MappedType) {
switch (Descriptor.MappedType)
{
case MappedType.Message:
type = GetClassName(Descriptor.MessageType);
break;
......@@ -66,70 +74,104 @@ namespace Google.ProtocolBuffers.ProtoGen {
name = Descriptor.CSharpOptions.PropertyName;
}
public void Generate(TextGenerator writer) {
public void Generate(TextGenerator writer)
{
writer.WriteLine("public const int {0} = {1};", GetFieldConstantName(Descriptor), Descriptor.FieldNumber);
if (UseLiteRuntime) {
if (Descriptor.MappedType == MappedType.Message && Descriptor.MessageType.Options.MessageSetWireFormat) {
throw new ArgumentException("option message_set_wire_format = true; is not supported in Lite runtime extensions.");
}
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance) {
if (UseLiteRuntime)
{
if (Descriptor.MappedType == MappedType.Message && Descriptor.MessageType.Options.MessageSetWireFormat)
{
throw new ArgumentException(
"option message_set_wire_format = true; is not supported in Lite runtime extensions.");
}
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("{0} static pb::{4}<{1}, {2}> {3};", ClassAccessLevel, extends, type, name,
Descriptor.IsRepeated ? "GeneratedRepeatExtensionLite" : "GeneratedExtensionLite");
} else if (Descriptor.IsRepeated) {
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance) {
}
else if (Descriptor.IsRepeated)
{
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("{0} static pb::GeneratedExtensionBase<scg::IList<{1}>> {2};", ClassAccessLevel, type, name);
} else {
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance) {
writer.WriteLine("{0} static pb::GeneratedExtensionBase<scg::IList<{1}>> {2};", ClassAccessLevel, type,
name);
}
else
{
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("{0} static pb::GeneratedExtensionBase<{1}> {2};", ClassAccessLevel, type, name);
}
}
internal void GenerateStaticVariableInitializers(TextGenerator writer) {
if (UseLiteRuntime) {
internal void GenerateStaticVariableInitializers(TextGenerator writer)
{
if (UseLiteRuntime)
{
writer.WriteLine("{0}.{1} = ", scope, name);
writer.Indent();
writer.WriteLine("new pb::{0}<{1}, {2}>(", Descriptor.IsRepeated ? "GeneratedRepeatExtensionLite" : "GeneratedExtensionLite", extends, type);
writer.WriteLine("new pb::{0}<{1}, {2}>(",
Descriptor.IsRepeated ? "GeneratedRepeatExtensionLite" : "GeneratedExtensionLite",
extends, type);
writer.Indent();
writer.WriteLine("\"{0}\",", Descriptor.FullName);
writer.WriteLine("{0}.DefaultInstance,", extends);
if(!Descriptor.IsRepeated)
writer.WriteLine("{0},", Descriptor.HasDefaultValue ? DefaultValue : IsNullableType ? "null" : "default(" + type + ")");
writer.WriteLine("{0},", (Descriptor.MappedType == MappedType.Message) ? type + ".DefaultInstance" : "null");
writer.WriteLine("{0},", (Descriptor.MappedType == MappedType.Enum) ? "new EnumLiteMap<" + type + ">()" : "null");
if (!Descriptor.IsRepeated)
writer.WriteLine("{0},",
Descriptor.HasDefaultValue
? DefaultValue
: IsNullableType ? "null" : "default(" + type + ")");
writer.WriteLine("{0},",
(Descriptor.MappedType == MappedType.Message) ? type + ".DefaultInstance" : "null");
writer.WriteLine("{0},",
(Descriptor.MappedType == MappedType.Enum) ? "new EnumLiteMap<" + type + ">()" : "null");
writer.WriteLine("{0}.{1}FieldNumber,", scope, name);
writer.Write("pbd::FieldType.{0}", Descriptor.FieldType);
if (Descriptor.IsRepeated) {
if (Descriptor.IsRepeated)
{
writer.WriteLine(",");
writer.Write(Descriptor.IsPacked ? "true" : "false");
}
writer.Outdent();
writer.WriteLine(");");
writer.Outdent();
} else if (Descriptor.IsRepeated) {
writer.WriteLine("{0}.{1} = pb::GeneratedRepeatExtension<{2}>.CreateInstance({0}.Descriptor.Extensions[{3}]);", scope, name, type, Descriptor.Index);
} else {
writer.WriteLine("{0}.{1} = pb::GeneratedSingleExtension<{2}>.CreateInstance({0}.Descriptor.Extensions[{3}]);", scope, name, type, Descriptor.Index);
}
else if (Descriptor.IsRepeated)
{
writer.WriteLine(
"{0}.{1} = pb::GeneratedRepeatExtension<{2}>.CreateInstance({0}.Descriptor.Extensions[{3}]);", scope,
name, type, Descriptor.Index);
}
else
{
writer.WriteLine(
"{0}.{1} = pb::GeneratedSingleExtension<{2}>.CreateInstance({0}.Descriptor.Extensions[{3}]);", scope,
name, type, Descriptor.Index);
}
}
internal void GenerateExtensionRegistrationCode(TextGenerator writer) {
internal void GenerateExtensionRegistrationCode(TextGenerator writer)
{
writer.WriteLine("registry.Add({0}.{1});", scope, name);
}
public override void WriteHash(TextGenerator writer) {
public override void WriteHash(TextGenerator writer)
{
}
public override void WriteEquals(TextGenerator writer) {
public override void WriteEquals(TextGenerator writer)
{
}
public override void WriteToString(TextGenerator writer) {
public override void WriteToString(TextGenerator writer)
{
}
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,13 +31,15 @@
// 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.
#endregion
namespace Google.ProtocolBuffers.ProtoGen {
#endregion
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Helpers to resolve class names etc.
/// </summary>
internal static class Helpers {
internal static class Helpers
{
}
}
\ No newline at end of file
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,10 +31,13 @@
// 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.
#endregion
namespace Google.ProtocolBuffers.ProtoGen {
internal interface IFieldSourceGenerator {
namespace Google.ProtocolBuffers.ProtoGen
{
internal interface IFieldSourceGenerator
{
void GenerateMembers(TextGenerator writer);
void GenerateBuilderMembers(TextGenerator writer);
void GenerateMergingCode(TextGenerator writer);
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,10 +31,13 @@
// 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.
#endregion
namespace Google.ProtocolBuffers.ProtoGen {
internal interface ISourceGenerator {
namespace Google.ProtocolBuffers.ProtoGen
{
internal interface ISourceGenerator
{
void Generate(TextGenerator writer);
}
}
\ No newline at end of file
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,6 +31,7 @@
// 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.
#endregion
using System;
......@@ -37,30 +39,35 @@ using System.Collections.Generic;
using System.Text;
using Google.ProtocolBuffers.Collections;
namespace Google.ProtocolBuffers.ProtoGen {
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Exception thrown to indicate that the options passed were invalid.
/// </summary>
public sealed class InvalidOptionsException : Exception {
public sealed class InvalidOptionsException : Exception
{
private readonly IList<string> reasons;
/// <summary>
/// An immutable list of reasons why the options were invalid.
/// </summary>
public IList<string> Reasons {
public IList<string> Reasons
{
get { return reasons; }
}
public InvalidOptionsException(IList<string> reasons)
: base(BuildMessage(reasons)) {
: base(BuildMessage(reasons))
{
this.reasons = Lists.AsReadOnly(reasons);
}
private static string BuildMessage(IEnumerable<string> reasons) {
private static string BuildMessage(IEnumerable<string> reasons)
{
StringBuilder builder = new StringBuilder("Invalid options:");
builder.AppendLine();
foreach (string reason in reasons) {
foreach (string reason in reasons)
{
builder.Append(" ");
builder.AppendLine(reason);
}
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,18 +31,22 @@
// 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.
#endregion
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
internal class MessageFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator {
namespace Google.ProtocolBuffers.ProtoGen
{
internal class MessageFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator
{
internal MessageFieldGenerator(FieldDescriptor descriptor)
: base(descriptor) {
: base(descriptor)
{
}
public void GenerateMembers(TextGenerator writer) {
public void GenerateMembers(TextGenerator writer)
{
writer.WriteLine("private bool has{0};", PropertyName);
writer.WriteLine("private {0} {1}_ = {2};", TypeName, Name, DefaultValue);
writer.WriteLine("public bool Has{0} {{", PropertyName);
......@@ -52,7 +57,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateBuilderMembers(TextGenerator writer) {
public void GenerateBuilderMembers(TextGenerator writer)
{
writer.WriteLine("public bool Has{0} {{", PropertyName);
writer.WriteLine(" get {{ return result.Has{0}; }}", PropertyName);
writer.WriteLine("}");
......@@ -76,7 +82,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
AddNullCheck(writer);
writer.WriteLine(" if (result.Has{0} &&", PropertyName);
writer.WriteLine(" result.{0}_ != {1}) {{", Name, DefaultValue);
writer.WriteLine(" result.{0}_ = {1}.CreateBuilder(result.{0}_).MergeFrom(value).BuildPartial();", Name, TypeName);
writer.WriteLine(" result.{0}_ = {1}.CreateBuilder(result.{0}_).MergeFrom(value).BuildPartial();", Name,
TypeName);
writer.WriteLine(" } else {");
writer.WriteLine(" result.{0}_ = value;", Name);
writer.WriteLine(" }");
......@@ -90,51 +97,63 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateMergingCode(TextGenerator writer) {
public void GenerateMergingCode(TextGenerator writer)
{
writer.WriteLine("if (other.Has{0}) {{", PropertyName);
writer.WriteLine(" Merge{0}(other.{0});", PropertyName);
writer.WriteLine("}");
}
public void GenerateBuildingCode(TextGenerator writer) {
public void GenerateBuildingCode(TextGenerator writer)
{
// Nothing to do for singular fields
}
public void GenerateParsingCode(TextGenerator writer) {
public void GenerateParsingCode(TextGenerator writer)
{
writer.WriteLine("{0}.Builder subBuilder = {0}.CreateBuilder();", TypeName);
writer.WriteLine("if (Has{0}) {{", PropertyName);
writer.WriteLine(" subBuilder.MergeFrom({0});", PropertyName);
writer.WriteLine("}");
if (Descriptor.FieldType == FieldType.Group) {
if (Descriptor.FieldType == FieldType.Group)
{
writer.WriteLine("input.ReadGroup({0}, subBuilder, extensionRegistry);", Number);
} else {
}
else
{
writer.WriteLine("input.ReadMessage(subBuilder, extensionRegistry);");
}
writer.WriteLine("{0} = subBuilder.BuildPartial();", PropertyName);
}
public void GenerateSerializationCode(TextGenerator writer) {
public void GenerateSerializationCode(TextGenerator writer)
{
writer.WriteLine("if (Has{0}) {{", PropertyName);
writer.WriteLine(" output.Write{0}({1}, {2});", MessageOrGroup, Number, PropertyName);
writer.WriteLine("}");
}
public void GenerateSerializedSizeCode(TextGenerator writer) {
public void GenerateSerializedSizeCode(TextGenerator writer)
{
writer.WriteLine("if (Has{0}) {{", PropertyName);
writer.WriteLine(" size += pb::CodedOutputStream.Compute{0}Size({1}, {2});",
MessageOrGroup, Number, PropertyName);
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
public override void WriteHash(TextGenerator writer)
{
writer.WriteLine("if (has{0}) hash ^= {1}_.GetHashCode();", PropertyName, Name);
}
public override void WriteEquals(TextGenerator writer) {
writer.WriteLine("if (has{0} != other.has{0} || (has{0} && !{1}_.Equals(other.{1}_))) return false;", PropertyName, Name);
public override void WriteEquals(TextGenerator writer)
{
writer.WriteLine("if (has{0} != other.has{0} || (has{0} && !{1}_.Equals(other.{1}_))) return false;",
PropertyName, Name);
}
public override void WriteToString(TextGenerator writer) {
public override void WriteToString(TextGenerator writer)
{
writer.WriteLine("PrintField(\"{2}\", has{0}, {1}_, writer);", PropertyName, Name,
Descriptor.FieldType == FieldType.Group ? Descriptor.MessageType.Name : Descriptor.Name);
}
......
This diff is collapsed.
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,19 +31,23 @@
// 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.
#endregion
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
namespace Google.ProtocolBuffers.ProtoGen
{
// TODO(jonskeet): Refactor this. There's loads of common code here.
internal class PrimitiveFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator {
internal class PrimitiveFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator
{
internal PrimitiveFieldGenerator(FieldDescriptor descriptor)
: base(descriptor) {
: base(descriptor)
{
}
public void GenerateMembers(TextGenerator writer) {
public void GenerateMembers(TextGenerator writer)
{
writer.WriteLine("private bool has{0};", PropertyName);
writer.WriteLine("private {0} {1}_ = {2};", TypeName, Name, DefaultValue);
writer.WriteLine("public bool Has{0} {{", PropertyName);
......@@ -54,7 +59,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateBuilderMembers(TextGenerator writer) {
public void GenerateBuilderMembers(TextGenerator writer)
{
writer.WriteLine("public bool Has{0} {{", PropertyName);
writer.WriteLine(" get {{ return result.Has{0}; }}", PropertyName);
writer.WriteLine("}");
......@@ -77,42 +83,51 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateMergingCode(TextGenerator writer) {
public void GenerateMergingCode(TextGenerator writer)
{
writer.WriteLine("if (other.Has{0}) {{", PropertyName);
writer.WriteLine(" {0} = other.{0};", PropertyName);
writer.WriteLine("}");
}
public void GenerateBuildingCode(TextGenerator writer) {
public void GenerateBuildingCode(TextGenerator writer)
{
// Nothing to do here for primitive types
}
public void GenerateParsingCode(TextGenerator writer) {
public void GenerateParsingCode(TextGenerator writer)
{
writer.WriteLine("{0} = input.Read{1}();", PropertyName, CapitalizedTypeName);
}
public void GenerateSerializationCode(TextGenerator writer) {
public void GenerateSerializationCode(TextGenerator writer)
{
writer.WriteLine("if (Has{0}) {{", PropertyName);
writer.WriteLine(" output.Write{0}({1}, {2});", CapitalizedTypeName, Number, PropertyName);
writer.WriteLine("}");
}
public void GenerateSerializedSizeCode(TextGenerator writer) {
public void GenerateSerializedSizeCode(TextGenerator writer)
{
writer.WriteLine("if (Has{0}) {{", PropertyName);
writer.WriteLine(" size += pb::CodedOutputStream.Compute{0}Size({1}, {2});",
CapitalizedTypeName, Number, PropertyName);
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
public override void WriteHash(TextGenerator writer)
{
writer.WriteLine("if (has{0}) hash ^= {1}_.GetHashCode();", PropertyName, Name);
}
public override void WriteEquals(TextGenerator writer) {
writer.WriteLine("if (has{0} != other.has{0} || (has{0} && !{1}_.Equals(other.{1}_))) return false;", PropertyName, Name);
public override void WriteEquals(TextGenerator writer)
{
writer.WriteLine("if (has{0} != other.has{0} || (has{0} && !{1}_.Equals(other.{1}_))) return false;",
PropertyName, Name);
}
public override void WriteToString(TextGenerator writer) {
public override void WriteToString(TextGenerator writer)
{
writer.WriteLine("PrintField(\"{0}\", has{1}, {2}_, writer);", Descriptor.Name, PropertyName, Name);
}
}
......
......@@ -38,19 +38,24 @@ using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.DescriptorProtos;
namespace Google.ProtocolBuffers.ProtoGen {
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Entry point for the Protocol Buffers generator.
/// </summary>
internal class Program {
internal static int Main(string[] args) {
try {
internal class Program
{
internal static int Main(string[] args)
{
try
{
// Hack to make sure everything's initialized
DescriptorProtoFile.Descriptor.ToString();
GeneratorOptions options = new GeneratorOptions {Arguments = args};
IList<string> validationFailures;
if (!options.TryValidate(out validationFailures)) {
if (!options.TryValidate(out validationFailures))
{
// We've already got the message-building logic in the exception...
InvalidOptionsException exception = new InvalidOptionsException(validationFailures);
Console.WriteLine(exception.Message);
......@@ -61,7 +66,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
generator.Generate();
return 0;
}
catch (Exception e) {
catch (Exception e)
{
Console.Error.WriteLine("Error: {0}", e.Message);
Console.Error.WriteLine();
Console.Error.WriteLine("Detailed exception information: {0}", e);
......
using System;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Google.ProtocolBuffers.ProtoGen {
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Preprocesses any input files with an extension of '.proto' by running protoc.exe. If arguments
/// are supplied with '--' prefix they are provided to protoc.exe, otherwise they are assumed to
......@@ -11,62 +12,79 @@ namespace Google.ProtocolBuffers.ProtoGen {
/// --descriptor_set_out= is specified the proto buffer file is kept, otherwise it will be removed
/// after code generation.
/// </summary>
public class ProgramPreprocess {
private static int Main(string[] args) {
try {
public class ProgramPreprocess
{
private static int Main(string[] args)
{
try
{
return Environment.ExitCode = Run(args);
}
catch (Exception ex) {
catch (Exception ex)
{
Console.Error.WriteLine(ex);
return Environment.ExitCode = 2;
}
}
public static int Run(params string[] args) {
public static int Run(params string[] args)
{
bool deleteFile = false;
string tempFile = null;
int result;
bool doHelp = args.Length == 0;
try {
try
{
List<string> protocArgs = new List<string>();
List<string> protoGenArgs = new List<string>();
foreach (string arg in args) {
foreach (string arg in args)
{
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "/?");
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "/help");
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "-?");
doHelp |= StringComparer.OrdinalIgnoreCase.Equals(arg, "-help");
if (arg.StartsWith("--descriptor_set_out=")) {
if (arg.StartsWith("--descriptor_set_out="))
{
tempFile = arg.Substring("--descriptor_set_out=".Length);
protoGenArgs.Add(tempFile);
}
}
if (doHelp) {
if (doHelp)
{
Console.WriteLine();
Console.WriteLine("PROTOC.exe: Use any of the following options that begin with '--':");
Console.WriteLine();
try {
try
{
RunProtoc("--help");
}
catch (Exception ex) {
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("PROTOGEN.exe: The following options are used to specify defaults for code generation.");
Console.WriteLine(
"PROTOGEN.exe: The following options are used to specify defaults for code generation.");
Console.WriteLine();
Program.Main(new string[0]);
return 0;
}
foreach (string arg in args) {
if (arg.StartsWith("--")) {
foreach (string arg in args)
{
if (arg.StartsWith("--"))
{
protocArgs.Add(arg);
}
else if (File.Exists(arg) && StringComparer.OrdinalIgnoreCase.Equals(".proto", Path.GetExtension(arg))) {
if (tempFile == null) {
else if (File.Exists(arg) &&
StringComparer.OrdinalIgnoreCase.Equals(".proto", Path.GetExtension(arg)))
{
if (tempFile == null)
{
deleteFile = true;
tempFile = Path.GetTempFileName();
protocArgs.Add(String.Format("--descriptor_set_out={0}", tempFile));
......@@ -74,29 +92,35 @@ namespace Google.ProtocolBuffers.ProtoGen {
}
protocArgs.Add(arg);
}
else {
else
{
protoGenArgs.Add(arg);
}
}
if (tempFile != null) {
if (tempFile != null)
{
result = RunProtoc(protocArgs.ToArray());
if (result != 0) {
if (result != 0)
{
return result;
}
}
result = Program.Main(protoGenArgs.ToArray());
}
finally {
if (deleteFile && tempFile != null && File.Exists(tempFile)) {
finally
{
if (deleteFile && tempFile != null && File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
return result;
}
private static int RunProtoc(params string[] args) {
private static int RunProtoc(params string[] args)
{
const string protoc = "protoc.exe";
string exePath = protoc;
......@@ -106,18 +130,24 @@ namespace Google.ProtocolBuffers.ProtoGen {
searchPath.Add(AppDomain.CurrentDomain.BaseDirectory);
searchPath.AddRange((Environment.GetEnvironmentVariable("PATH") ?? String.Empty).Split(Path.PathSeparator));
foreach (string path in searchPath) {
if (File.Exists(exePath = Path.Combine(path, protoc))) {
foreach (string path in searchPath)
{
if (File.Exists(exePath = Path.Combine(path, protoc)))
{
break;
}
}
if (!File.Exists(exePath)) {
throw new FileNotFoundException("Unable to locate " + protoc + " make sure it is in the PATH, cwd, or exe dir.");
if (!File.Exists(exePath))
{
throw new FileNotFoundException("Unable to locate " + protoc +
" make sure it is in the PATH, cwd, or exe dir.");
}
for (int i = 0; i < args.Length; i++) {
if (args[i].IndexOf(' ') > 0 && args[i][0] != '"') {
for (int i = 0; i < args.Length; i++)
{
if (args[i].IndexOf(' ') > 0 && args[i][0] != '"')
{
args[i] = '"' + args[i] + '"';
}
}
......@@ -133,18 +163,21 @@ namespace Google.ProtocolBuffers.ProtoGen {
psi.WorkingDirectory = Environment.CurrentDirectory;
Process process = Process.Start(psi);
if (process == null) {
if (process == null)
{
return 1;
}
process.WaitForExit();
string tmp = process.StandardOutput.ReadToEnd();
if (tmp.Trim().Length > 0) {
if (tmp.Trim().Length > 0)
{
Console.Out.WriteLine(tmp);
}
tmp = process.StandardError.ReadToEnd();
if (tmp.Trim().Length > 0) {
if (tmp.Trim().Length > 0)
{
Console.Error.WriteLine(tmp);
}
return process.ExitCode;
......
......@@ -5,6 +5,7 @@ using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ProtoGen")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
......@@ -17,9 +18,11 @@ using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7101763b-7a38-41be-87f5-7ede4c554509")]
// Version information for an assembly consists of the following four values:
......@@ -32,6 +35,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyFileVersion("2.3.0.277")]
\ No newline at end of file
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,20 +31,25 @@
// 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.
#endregion
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
internal class RepeatedEnumFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator {
namespace Google.ProtocolBuffers.ProtoGen
{
internal class RepeatedEnumFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator
{
internal RepeatedEnumFieldGenerator(FieldDescriptor descriptor)
: base(descriptor) {
: base(descriptor)
{
}
public void GenerateMembers(TextGenerator writer) {
if (Descriptor.IsPacked && OptimizeSpeed) {
public void GenerateMembers(TextGenerator writer)
{
if (Descriptor.IsPacked && OptimizeSpeed)
{
writer.WriteLine("private int {0}MemoizedSerializedSize;", Name);
}
writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name);
......@@ -61,7 +67,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateBuilderMembers(TextGenerator writer) {
public void GenerateBuilderMembers(TextGenerator writer)
{
// Note: We can return the original list here, because we make it unmodifiable when we build
// We return it via IPopsicleList so that collection initializers work more pleasantly.
writer.WriteLine("public pbc::IPopsicleList<{0}> {1}List {{", TypeName, PropertyName);
......@@ -91,19 +98,23 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateMergingCode(TextGenerator writer) {
public void GenerateMergingCode(TextGenerator writer)
{
writer.WriteLine("if (other.{0}_.Count != 0) {{", Name);
writer.WriteLine(" base.AddRange(other.{0}_, result.{0}_);", Name);
writer.WriteLine("}");
}
public void GenerateBuildingCode(TextGenerator writer) {
public void GenerateBuildingCode(TextGenerator writer)
{
writer.WriteLine("result.{0}_.MakeReadOnly();", Name);
}
public void GenerateParsingCode(TextGenerator writer) {
public void GenerateParsingCode(TextGenerator writer)
{
// If packed, set up the while loop
if (Descriptor.IsPacked) {
if (Descriptor.IsPacked)
{
writer.WriteLine("int length = input.ReadInt32();");
writer.WriteLine("int oldLimit = input.PushLimit(length);");
writer.WriteLine("while (!input.ReachedLimit) {");
......@@ -114,7 +125,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
// TODO(jonskeet): Make a more efficient way of doing this
writer.WriteLine("int rawValue = input.ReadEnum();");
writer.WriteLine("if (!global::System.Enum.IsDefined(typeof({0}), rawValue)) {{", TypeName);
if (!UseLiteRuntime) {
if (!UseLiteRuntime)
{
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }");
......@@ -124,23 +136,28 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine(" Add{0}(({1}) rawValue);", PropertyName, TypeName);
writer.WriteLine("}");
if (Descriptor.IsPacked) {
if (Descriptor.IsPacked)
{
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine("input.PopLimit(oldLimit);");
}
}
public void GenerateSerializationCode(TextGenerator writer) {
public void GenerateSerializationCode(TextGenerator writer)
{
writer.WriteLine("if ({0}_.Count > 0) {{", Name);
writer.Indent();
if (Descriptor.IsPacked) {
if (Descriptor.IsPacked)
{
writer.WriteLine("output.WriteRawVarint32({0});", WireFormat.MakeTag(Descriptor));
writer.WriteLine("output.WriteRawVarint32((uint) {0}MemoizedSerializedSize);", Name);
writer.WriteLine("foreach (int element in {0}_) {{", Name);
writer.WriteLine(" output.WriteEnumNoTag(element);");
writer.WriteLine("}");
} else {
}
else
{
writer.WriteLine("foreach (int element in {0}_) {{", Name);
writer.WriteLine(" output.WriteEnum({0}, element);", Number);
writer.WriteLine("}");
......@@ -149,7 +166,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateSerializedSizeCode(TextGenerator writer) {
public void GenerateSerializedSizeCode(TextGenerator writer)
{
writer.WriteLine("{");
writer.Indent();
writer.WriteLine("int dataSize = 0;");
......@@ -160,34 +178,41 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
writer.WriteLine("size += dataSize;");
int tagSize = CodedOutputStream.ComputeTagSize(Descriptor.FieldNumber);
if (Descriptor.IsPacked) {
if (Descriptor.IsPacked)
{
writer.WriteLine("size += {0};", tagSize);
writer.WriteLine("size += pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize);");
} else {
}
else
{
writer.WriteLine("size += {0} * {1}_.Count;", tagSize, Name);
}
writer.Outdent();
writer.WriteLine("}");
// cache the data size for packed fields.
if (Descriptor.IsPacked) {
if (Descriptor.IsPacked)
{
writer.WriteLine("{0}MemoizedSerializedSize = dataSize;", Name);
}
writer.Outdent();
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
public override void WriteHash(TextGenerator writer)
{
writer.WriteLine("foreach({0} i in {1}_)", TypeName, Name);
writer.WriteLine(" hash ^= i.GetHashCode();");
}
public override void WriteEquals(TextGenerator writer) {
public override void WriteEquals(TextGenerator writer)
{
writer.WriteLine("if({0}_.Count != other.{0}_.Count) return false;", Name);
writer.WriteLine("for(int ix=0; ix < {0}_.Count; ix++)", Name);
writer.WriteLine(" if(!{0}_[ix].Equals(other.{0}_[ix])) return false;", Name);
}
public override void WriteToString(TextGenerator writer) {
public override void WriteToString(TextGenerator writer)
{
writer.WriteLine("PrintField(\"{0}\", {1}_, writer);", Descriptor.Name, Name);
}
}
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,18 +31,22 @@
// 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.
#endregion
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
internal class RepeatedMessageFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator {
namespace Google.ProtocolBuffers.ProtoGen
{
internal class RepeatedMessageFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator
{
internal RepeatedMessageFieldGenerator(FieldDescriptor descriptor)
: base(descriptor) {
: base(descriptor)
{
}
public void GenerateMembers(TextGenerator writer) {
public void GenerateMembers(TextGenerator writer)
{
writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name);
writer.WriteLine("public scg::IList<{0}> {1}List {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return {0}_; }}", Name);
......@@ -57,7 +62,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateBuilderMembers(TextGenerator writer) {
public void GenerateBuilderMembers(TextGenerator writer)
{
// Note: We can return the original list here, because we make it unmodifiable when we build
// We return it via IPopsicleList so that collection initializers work more pleasantly.
writer.WriteLine("public pbc::IPopsicleList<{0}> {1}List {{", TypeName, PropertyName);
......@@ -101,53 +107,64 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateMergingCode(TextGenerator writer) {
public void GenerateMergingCode(TextGenerator writer)
{
writer.WriteLine("if (other.{0}_.Count != 0) {{", Name);
writer.WriteLine(" base.AddRange(other.{0}_, result.{0}_);", Name);
writer.WriteLine("}");
}
public void GenerateBuildingCode(TextGenerator writer) {
public void GenerateBuildingCode(TextGenerator writer)
{
writer.WriteLine("result.{0}_.MakeReadOnly();", Name);
}
public void GenerateParsingCode(TextGenerator writer) {
public void GenerateParsingCode(TextGenerator writer)
{
writer.WriteLine("{0}.Builder subBuilder = {0}.CreateBuilder();", TypeName);
if (Descriptor.FieldType == FieldType.Group) {
if (Descriptor.FieldType == FieldType.Group)
{
writer.WriteLine("input.ReadGroup({0}, subBuilder, extensionRegistry);", Number);
} else {
}
else
{
writer.WriteLine("input.ReadMessage(subBuilder, extensionRegistry);");
}
writer.WriteLine("Add{0}(subBuilder.BuildPartial());", PropertyName);
}
public void GenerateSerializationCode(TextGenerator writer) {
public void GenerateSerializationCode(TextGenerator writer)
{
writer.WriteLine("foreach ({0} element in {1}List) {{", TypeName, PropertyName);
writer.WriteLine(" output.Write{0}({1}, element);", MessageOrGroup, Number);
writer.WriteLine("}");
}
public void GenerateSerializedSizeCode(TextGenerator writer) {
public void GenerateSerializedSizeCode(TextGenerator writer)
{
writer.WriteLine("foreach ({0} element in {1}List) {{", TypeName, PropertyName);
writer.WriteLine(" size += pb::CodedOutputStream.Compute{0}Size({1}, element);", MessageOrGroup, Number);
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
public override void WriteHash(TextGenerator writer)
{
writer.WriteLine("foreach({0} i in {1}_)", TypeName, Name);
writer.WriteLine(" hash ^= i.GetHashCode();");
}
public override void WriteEquals(TextGenerator writer) {
public override void WriteEquals(TextGenerator writer)
{
writer.WriteLine("if({0}_.Count != other.{0}_.Count) return false;", Name);
writer.WriteLine("for(int ix=0; ix < {0}_.Count; ix++)", Name);
writer.WriteLine(" if(!{0}_[ix].Equals(other.{0}_[ix])) return false;", Name);
}
public override void WriteToString(TextGenerator writer) {
public override void WriteToString(TextGenerator writer)
{
writer.WriteLine("PrintField(\"{0}\", {1}_, writer);",
Descriptor.FieldType == FieldType.Group ? Descriptor.MessageType.Name : Descriptor.Name, Name);
Descriptor.FieldType == FieldType.Group ? Descriptor.MessageType.Name : Descriptor.Name,
Name);
}
}
}
\ No newline at end of file
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,20 +31,25 @@
// 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.
#endregion
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
internal class RepeatedPrimitiveFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator {
namespace Google.ProtocolBuffers.ProtoGen
{
internal class RepeatedPrimitiveFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator
{
internal RepeatedPrimitiveFieldGenerator(FieldDescriptor descriptor)
: base(descriptor) {
: base(descriptor)
{
}
public void GenerateMembers(TextGenerator writer) {
if (Descriptor.IsPacked && OptimizeSpeed) {
public void GenerateMembers(TextGenerator writer)
{
if (Descriptor.IsPacked && OptimizeSpeed)
{
writer.WriteLine("private int {0}MemoizedSerializedSize;", Name);
}
writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name);
......@@ -63,7 +69,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateBuilderMembers(TextGenerator writer) {
public void GenerateBuilderMembers(TextGenerator writer)
{
// Note: We can return the original list here, because we make it unmodifiable when we build
// We return it via IPopsicleList so that collection initializers work more pleasantly.
AddClsComplianceCheck(writer);
......@@ -100,39 +107,49 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateMergingCode(TextGenerator writer) {
public void GenerateMergingCode(TextGenerator writer)
{
writer.WriteLine("if (other.{0}_.Count != 0) {{", Name);
writer.WriteLine(" base.AddRange(other.{0}_, result.{0}_);", Name);
writer.WriteLine("}");
}
public void GenerateBuildingCode(TextGenerator writer) {
public void GenerateBuildingCode(TextGenerator writer)
{
writer.WriteLine("result.{0}_.MakeReadOnly();", Name);
}
public void GenerateParsingCode(TextGenerator writer) {
if (Descriptor.IsPacked) {
public void GenerateParsingCode(TextGenerator writer)
{
if (Descriptor.IsPacked)
{
writer.WriteLine("int length = input.ReadInt32();");
writer.WriteLine("int limit = input.PushLimit(length);");
writer.WriteLine("while (!input.ReachedLimit) {");
writer.WriteLine(" Add{0}(input.Read{1}());", PropertyName, CapitalizedTypeName);
writer.WriteLine("}");
writer.WriteLine("input.PopLimit(limit);");
} else {
}
else
{
writer.WriteLine("Add{0}(input.Read{1}());", PropertyName, CapitalizedTypeName);
}
}
public void GenerateSerializationCode(TextGenerator writer) {
public void GenerateSerializationCode(TextGenerator writer)
{
writer.WriteLine("if ({0}_.Count > 0) {{", Name);
writer.Indent();
if (Descriptor.IsPacked) {
if (Descriptor.IsPacked)
{
writer.WriteLine("output.WriteRawVarint32({0});", WireFormat.MakeTag(Descriptor));
writer.WriteLine("output.WriteRawVarint32((uint) {0}MemoizedSerializedSize);", Name);
writer.WriteLine("foreach ({0} element in {1}_) {{", TypeName, Name);
writer.WriteLine(" output.Write{0}NoTag(element);", CapitalizedTypeName);
writer.WriteLine("}");
} else {
}
else
{
writer.WriteLine("foreach ({0} element in {1}_) {{", TypeName, Name);
writer.WriteLine(" output.Write{0}({1}, element);", CapitalizedTypeName, Number);
writer.WriteLine("}");
......@@ -141,46 +158,58 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
public void GenerateSerializedSizeCode(TextGenerator writer) {
public void GenerateSerializedSizeCode(TextGenerator writer)
{
writer.WriteLine("{");
writer.Indent();
writer.WriteLine("int dataSize = 0;");
if (FixedSize == -1) {
if (FixedSize == -1)
{
writer.WriteLine("foreach ({0} element in {1}List) {{", TypeName, PropertyName);
writer.WriteLine(" dataSize += pb::CodedOutputStream.Compute{0}SizeNoTag(element);", CapitalizedTypeName, Number);
writer.WriteLine(" dataSize += pb::CodedOutputStream.Compute{0}SizeNoTag(element);",
CapitalizedTypeName, Number);
writer.WriteLine("}");
} else {
}
else
{
writer.WriteLine("dataSize = {0} * {1}_.Count;", FixedSize, Name);
}
writer.WriteLine("size += dataSize;");
int tagSize = CodedOutputStream.ComputeTagSize(Descriptor.FieldNumber);
if (Descriptor.IsPacked) {
if (Descriptor.IsPacked)
{
writer.WriteLine("if ({0}_.Count != 0) {{", Name);
writer.WriteLine(" size += {0} + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize);", tagSize);
writer.WriteLine("}");
} else {
}
else
{
writer.WriteLine("size += {0} * {1}_.Count;", tagSize, Name);
}
// cache the data size for packed fields.
if (Descriptor.IsPacked) {
if (Descriptor.IsPacked)
{
writer.WriteLine("{0}MemoizedSerializedSize = dataSize;", Name);
}
writer.Outdent();
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
public override void WriteHash(TextGenerator writer)
{
writer.WriteLine("foreach({0} i in {1}_)", TypeName, Name);
writer.WriteLine(" hash ^= i.GetHashCode();");
}
public override void WriteEquals(TextGenerator writer) {
public override void WriteEquals(TextGenerator writer)
{
writer.WriteLine("if({0}_.Count != other.{0}_.Count) return false;", Name);
writer.WriteLine("for(int ix=0; ix < {0}_.Count; ix++)", Name);
writer.WriteLine(" if(!{0}_[ix].Equals(other.{0}_[ix])) return false;", Name);
}
public override void WriteToString(TextGenerator writer) {
public override void WriteToString(TextGenerator writer)
{
writer.WriteLine("PrintField(\"{0}\", {1}_, writer);", Descriptor.Name, Name);
}
}
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,28 +31,35 @@
// 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.
#endregion
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
internal class GenericServiceGenerator : SourceGeneratorBase<ServiceDescriptor>, ISourceGenerator {
private enum RequestOrResponse {
namespace Google.ProtocolBuffers.ProtoGen
{
internal class GenericServiceGenerator : SourceGeneratorBase<ServiceDescriptor>, ISourceGenerator
{
private enum RequestOrResponse
{
Request,
Response
}
internal GenericServiceGenerator(ServiceDescriptor descriptor)
: base(descriptor) {
: base(descriptor)
{
}
public void Generate(TextGenerator writer) {
public void Generate(TextGenerator writer)
{
writer.WriteLine("{0} abstract class {1} : pb::IService {{", ClassAccessLevel, Descriptor.Name);
writer.Indent();
foreach (MethodDescriptor method in Descriptor.Methods) {
writer.WriteLine("{0} abstract void {1}(", ClassAccessLevel, NameHelpers.UnderscoresToPascalCase(method.Name));
foreach (MethodDescriptor method in Descriptor.Methods)
{
writer.WriteLine("{0} abstract void {1}(", ClassAccessLevel,
NameHelpers.UnderscoresToPascalCase(method.Name));
writer.WriteLine(" pb::IRpcController controller,");
writer.WriteLine(" {0} request,", GetClassName(method.InputType));
writer.WriteLine(" global::System.Action<{0}> done);", GetClassName(method.OutputType));
......@@ -61,7 +69,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine();
writer.WriteLine("{0} static pbd::ServiceDescriptor Descriptor {{", ClassAccessLevel);
writer.WriteLine(" get {{ return {0}.Descriptor.Services[{1}]; }}",
DescriptorUtil.GetQualifiedUmbrellaClassName(Descriptor.File.CSharpOptions), Descriptor.Index);
DescriptorUtil.GetQualifiedUmbrellaClassName(Descriptor.File.CSharpOptions),
Descriptor.Index);
writer.WriteLine("}");
writer.WriteLine("{0} pbd::ServiceDescriptor DescriptorForType {{", ClassAccessLevel);
writer.WriteLine(" get { return Descriptor; }");
......@@ -76,7 +85,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
}
private void GenerateCallMethod(TextGenerator writer) {
private void GenerateCallMethod(TextGenerator writer)
{
writer.WriteLine();
writer.WriteLine("public void CallMethod(", ClassAccessLevel);
writer.WriteLine(" pbd::MethodDescriptor method,");
......@@ -90,7 +100,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
writer.WriteLine("switch(method.Index) {");
writer.Indent();
foreach (MethodDescriptor method in Descriptor.Methods) {
foreach (MethodDescriptor method in Descriptor.Methods)
{
writer.WriteLine("case {0}:", method.Index);
writer.WriteLine(" this.{0}(controller, ({1}) request,",
NameHelpers.UnderscoresToPascalCase(method.Name), GetClassName(method.InputType));
......@@ -107,17 +118,20 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine();
}
private void GenerateGetPrototype(RequestOrResponse which, TextGenerator writer) {
private void GenerateGetPrototype(RequestOrResponse which, TextGenerator writer)
{
writer.WriteLine("public pb::IMessage Get{0}Prototype(pbd::MethodDescriptor method) {{", which);
writer.Indent();
writer.WriteLine("if (method.Service != Descriptor) {");
writer.WriteLine(" throw new global::System.ArgumentException(");
writer.WriteLine(" \"Service.Get{0}Prototype() given method descriptor for wrong service type.\");", which);
writer.WriteLine(" \"Service.Get{0}Prototype() given method descriptor for wrong service type.\");",
which);
writer.WriteLine("}");
writer.WriteLine("switch(method.Index) {");
writer.Indent();
foreach (MethodDescriptor method in Descriptor.Methods) {
foreach (MethodDescriptor method in Descriptor.Methods)
{
writer.WriteLine("case {0}:", method.Index);
writer.WriteLine(" return {0}.DefaultInstance;",
GetClassName(which == RequestOrResponse.Request ? method.InputType : method.OutputType));
......@@ -131,7 +145,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine();
}
private void GenerateStub(TextGenerator writer) {
private void GenerateStub(TextGenerator writer)
{
writer.WriteLine("public static Stub CreateStub(pb::IRpcChannel channel) {");
writer.WriteLine(" return new Stub(channel);");
writer.WriteLine("}");
......@@ -148,7 +163,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine(" get { return channel; }");
writer.WriteLine("}");
foreach (MethodDescriptor method in Descriptor.Methods) {
foreach (MethodDescriptor method in Descriptor.Methods)
{
writer.WriteLine();
writer.WriteLine("public override void {0}(", NameHelpers.UnderscoresToPascalCase(method.Name));
writer.WriteLine(" pb::IRpcController controller,");
......
This diff is collapsed.
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,14 +31,16 @@
// 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.
#endregion
using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
internal abstract class SourceGeneratorBase<T> where T : IDescriptor {
namespace Google.ProtocolBuffers.ProtoGen
{
internal abstract class SourceGeneratorBase<T> where T : IDescriptor
{
private readonly T descriptor;
protected readonly bool OptimizeSpeed;
......@@ -45,55 +48,73 @@ namespace Google.ProtocolBuffers.ProtoGen {
protected readonly bool UseLiteRuntime;
protected readonly string RuntimeSuffix;
protected SourceGeneratorBase(T descriptor) {
protected SourceGeneratorBase(T descriptor)
{
this.descriptor = descriptor;
OptimizeSize = descriptor.File.Options.OptimizeFor == Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.CODE_SIZE;
OptimizeSpeed = descriptor.File.Options.OptimizeFor == Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.SPEED;
UseLiteRuntime = descriptor.File.Options.OptimizeFor == Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.LITE_RUNTIME;
OptimizeSize = descriptor.File.Options.OptimizeFor ==
Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.CODE_SIZE;
OptimizeSpeed = descriptor.File.Options.OptimizeFor ==
Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.SPEED;
UseLiteRuntime = descriptor.File.Options.OptimizeFor ==
Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.LITE_RUNTIME;
//Lite runtime uses OptimizeSpeed code branches
OptimizeSpeed |= UseLiteRuntime;
RuntimeSuffix = UseLiteRuntime ? "Lite" : "";
}
protected T Descriptor {
protected T Descriptor
{
get { return descriptor; }
}
internal static string GetClassName(IDescriptor descriptor) {
internal static string GetClassName(IDescriptor descriptor)
{
return ToCSharpName(descriptor.FullName, descriptor.File);
}
// Groups are hacky: The name of the field is just the lower-cased name
// of the group type. In C#, though, we would like to retain the original
// capitalization of the type name.
internal static string GetFieldName(FieldDescriptor descriptor) {
if (descriptor.FieldType == FieldType.Group) {
internal static string GetFieldName(FieldDescriptor descriptor)
{
if (descriptor.FieldType == FieldType.Group)
{
return descriptor.MessageType.Name;
} else {
}
else
{
return descriptor.Name;
}
}
internal static string GetFieldConstantName(FieldDescriptor field) {
internal static string GetFieldConstantName(FieldDescriptor field)
{
return field.CSharpOptions.PropertyName + "FieldNumber";
}
private static string ToCSharpName(string name, FileDescriptor file) {
private static string ToCSharpName(string name, FileDescriptor file)
{
string result = file.CSharpOptions.Namespace;
if (file.CSharpOptions.NestClasses) {
if (result != "") {
if (file.CSharpOptions.NestClasses)
{
if (result != "")
{
result += ".";
}
result += file.CSharpOptions.UmbrellaClassname;
}
if (result != "") {
if (result != "")
{
result += '.';
}
string classname;
if (file.Package == "") {
if (file.Package == "")
{
classname = name;
} else {
}
else
{
// Strip the proto package from full_name since we've replaced it with
// the C# namespace.
classname = name.Substring(file.Package.Length + 1);
......@@ -102,27 +123,31 @@ namespace Google.ProtocolBuffers.ProtoGen {
return "global::" + result;
}
protected string ClassAccessLevel {
get {
return descriptor.File.CSharpOptions.PublicClasses ? "public" : "internal";
}
protected string ClassAccessLevel
{
get { return descriptor.File.CSharpOptions.PublicClasses ? "public" : "internal"; }
}
protected void WriteChildren<TChild>(TextGenerator writer, string region, IEnumerable<TChild> children)
where TChild : IDescriptor {
where TChild : IDescriptor
{
// Copy the set of children; makes access easier
List<TChild> copy = new List<TChild>(children);
if (copy.Count == 0) {
if (copy.Count == 0)
{
return;
}
if (region != null) {
if (region != null)
{
writer.WriteLine("#region {0}", region);
}
foreach (TChild child in children) {
foreach (TChild child in children)
{
SourceGenerators.CreateGenerator(child).Generate(writer);
}
if (region != null) {
if (region != null)
{
writer.WriteLine("#endregion");
writer.WriteLine();
}
......
This diff is collapsed.
This diff is collapsed.
<?xml version="1.0"?>
<configuration>
<startup/></configuration>
<startup />
</configuration>
\ No newline at end of file
This diff is collapsed.
......@@ -5,6 +5,7 @@ using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ProtoMunge")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
......@@ -17,9 +18,11 @@ using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4d26ed0e-a6ca-4df9-bb87-59429d49b676")]
// Version information for an assembly consists of the following four values:
......@@ -32,5 +35,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyVersion("2.3.0.277")]
[assembly: AssemblyFileVersion("2.3.0.277")]
\ No newline at end of file
<?xml version="1.0"?>
<configuration>
<startup/></configuration>
<startup />
</configuration>
\ No newline at end of file
This diff is collapsed.
#region Copyright notice and license
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
......@@ -30,35 +31,41 @@
// 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.
#endregion
using NUnit.Framework;
using Google.ProtocolBuffers.TestProtos;
namespace Google.ProtocolBuffers.Descriptors {
namespace Google.ProtocolBuffers.Descriptors
{
[TestFixture]
public class MessageDescriptorTest {
public class MessageDescriptorTest
{
[Test]
public void FindPropertyWithDefaultName() {
public void FindPropertyWithDefaultName()
{
Assert.AreSame(OptionsMessage.Descriptor.FindFieldByNumber(OptionsMessage.NormalFieldNumber),
OptionsMessage.Descriptor.FindFieldByPropertyName("Normal"));
}
[Test]
public void FindPropertyWithAutoModifiedName() {
public void FindPropertyWithAutoModifiedName()
{
Assert.AreSame(OptionsMessage.Descriptor.FindFieldByNumber(OptionsMessage.OptionsMessage_FieldNumber),
OptionsMessage.Descriptor.FindFieldByPropertyName("OptionsMessage_"));
}
[Test]
public void FindPropertyWithCustomizedName() {
public void FindPropertyWithCustomizedName()
{
Assert.AreSame(OptionsMessage.Descriptor.FindFieldByNumber(OptionsMessage.CustomNameFieldNumber),
OptionsMessage.Descriptor.FindFieldByPropertyName("CustomName"));
}
[Test]
public void FindPropertyWithInvalidName() {
public void FindPropertyWithInvalidName()
{
Assert.IsNull(OptionsMessage.Descriptor.FindFieldByPropertyName("Bogus"));
}
}
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -30,12 +30,14 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Google.ProtocolBuffers.Descriptors {
namespace Google.ProtocolBuffers.Descriptors
{
/// <summary>
/// Enumeration of all the possible field types. The odd formatting is to make it very clear
/// which attribute applies to which value, while maintaining a compact format.
/// </summary>
public enum FieldType {
public enum FieldType
{
[FieldMapping(MappedType.Double, WireFormat.WireType.Fixed64)] Double,
[FieldMapping(MappedType.Single, WireFormat.WireType.Fixed32)] Float,
[FieldMapping(MappedType.Int64, WireFormat.WireType.Varint)] Int64,
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment