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