// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Google.ProtocolBuffers.DescriptorProtos; namespace Google.ProtocolBuffers.Descriptors { /// /// Describes a .proto file, including everything defined within. /// IDescriptor is implemented such that the File property returns this descriptor, /// and the FullName is the same as the Name. /// public sealed class FileDescriptor : IDescriptor { private readonly FileDescriptorProto proto; private readonly IList messageTypes; private readonly IList enumTypes; private readonly IList services; private readonly IList extensions; private readonly IList dependencies; private readonly DescriptorPool pool; private CSharpFileOptions csharpFileOptions; private readonly object optionsLock = new object(); private FileDescriptor(FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool) { this.pool = pool; this.proto = proto; this.dependencies = new ReadOnlyCollection((FileDescriptor[]) dependencies.Clone()); pool.AddPackage(Package, this); messageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageTypeList, (message, index) => new MessageDescriptor(message, this, null, index)); enumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumTypeList, (enumType, index) => new EnumDescriptor(enumType, this, null, index)); services = DescriptorUtil.ConvertAndMakeReadOnly(proto.ServiceList, (service, index) => new ServiceDescriptor(service, this, index)); extensions = DescriptorUtil.ConvertAndMakeReadOnly(proto.ExtensionList, (field, index) => new FieldDescriptor(field, this, null, index, true)); } private CSharpFileOptions BuildOrFakeCSharpOptions() { // TODO(jonskeet): Check if we could use FileDescriptorProto.Descriptor.Name - interesting bootstrap issues if (proto.Name == "google/protobuf/descriptor.proto") { return new CSharpFileOptions.Builder { Namespace = "Google.ProtocolBuffers.DescriptorProtos", UmbrellaClassname = "DescriptorProtoFile", NestClasses = false, MultipleFiles = false, PublicClasses = true }.Build(); } if (proto.Name == "google/protobuf/csharp_options.proto") { return new CSharpFileOptions.Builder { Namespace = "Google.ProtocolBuffers.DescriptorProtos", UmbrellaClassname = "CSharpOptions", NestClasses = false, MultipleFiles = false, PublicClasses = true }.Build(); } CSharpFileOptions.Builder builder = CSharpFileOptions.CreateBuilder(); if (proto.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)) { builder.MergeFrom(proto.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)); } if (!builder.HasNamespace) { builder.Namespace = Package; } if (!builder.HasMultipleFiles) { builder.MultipleFiles = false; } if (!builder.HasNestClasses) { builder.NestClasses = false; } if (!builder.HasPublicClasses) { builder.PublicClasses = true; } if (!builder.HasUmbrellaClassname) { int lastSlash = Name.LastIndexOf('/'); string baseName = Name.Substring(lastSlash + 1); builder.UmbrellaClassname = NameHelpers.UnderscoresToPascalCase(NameHelpers.StripProto(baseName)); } return builder.Build(); } /// /// The descriptor in its protocol message representation. /// public FileDescriptorProto Proto { get { return proto; } } /// /// The defined in descriptor.proto. /// public FileOptions Options { get { return proto.Options; } } /// /// Returns the C#-specific options for this file descriptor. This will always be /// completely filled in. /// public CSharpFileOptions CSharpOptions { get { lock (optionsLock) { if (csharpFileOptions == null) { csharpFileOptions = BuildOrFakeCSharpOptions(); } } return csharpFileOptions; } } /// /// The file name. /// public string Name { get { return proto.Name; } } /// /// The package as declared in the .proto file. This may or may not /// be equivalent to the .NET namespace of the generated classes. /// public string Package { get { return proto.Package; } } /// /// Unmodifiable list of top-level message types declared in this file. /// public IList MessageTypes { get { return messageTypes; } } /// /// Unmodifiable list of top-level enum types declared in this file. /// public IList EnumTypes { get { return enumTypes; } } /// /// Unmodifiable list of top-level services declared in this file. /// public IList Services { get { return services; } } /// /// Unmodifiable list of top-level extensions declared in this file. /// public IList Extensions { get { return extensions; } } /// /// Unmodifiable list of this file's dependencies (imports). /// public IList Dependencies { get { return dependencies; } } /// /// Implementation of IDescriptor.FullName - just returns the same as Name. /// string IDescriptor.FullName { get { return Name; } } /// /// Implementation of IDescriptor.File - just returns this descriptor. /// FileDescriptor IDescriptor.File { get { return this; } } /// /// Protocol buffer describing this descriptor. /// IMessage IDescriptor.Proto { get { return Proto; } } /// /// Pool containing symbol descriptors. /// internal DescriptorPool DescriptorPool { get { return pool; } } /// /// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types. /// /// The unqualified type name to look for. /// The type of descriptor to look for (or ITypeDescriptor for any) /// The type's descriptor, or null if not found. public T FindTypeByName(String name) where T : class, IDescriptor { // Don't allow looking up nested types. This will make optimization // easier later. if (name.IndexOf('.') != -1) { return null; } if (Package.Length > 0) { name = Package + "." + name; } T result = pool.FindSymbol(name); if (result != null && result.File == this) { return result; } return null; } /// /// Builds a FileDescriptor from its protocol buffer representation. /// /// The protocol message form of the FileDescriptor. /// FileDescriptors corresponding to all of the /// file's dependencies, in the exact order listed in the .proto file. May be null, /// in which case it is treated as an empty array. /// If is not /// a valid descriptor. This can occur for a number of reasons, such as a field /// having an undefined type or because two messages were defined with the same name. public static FileDescriptor BuildFrom(FileDescriptorProto proto, FileDescriptor[] dependencies) { // Building descriptors involves two steps: translating and linking. // In the translation step (implemented by FileDescriptor's // constructor), we build an object tree mirroring the // FileDescriptorProto's tree and put all of the descriptors into the // DescriptorPool's lookup tables. In the linking step, we look up all // type references in the DescriptorPool, so that, for example, a // FieldDescriptor for an embedded message contains a pointer directly // to the Descriptor for that message's type. We also detect undefined // types in the linking step. if (dependencies == null) { dependencies = new FileDescriptor[0]; } DescriptorPool pool = new DescriptorPool(dependencies); FileDescriptor result = new FileDescriptor(proto, dependencies, pool); if (dependencies.Length != proto.DependencyCount) { throw new DescriptorValidationException(result, "Dependencies passed to FileDescriptor.BuildFrom() don't match " + "those listed in the FileDescriptorProto."); } for (int i = 0; i < proto.DependencyCount; i++) { if (dependencies[i].Name != proto.DependencyList[i]) { /*throw new DescriptorValidationException(result, "Dependencies passed to FileDescriptor.BuildFrom() don't match " + "those listed in the FileDescriptorProto.");*/ } } result.CrossLink(); return result; } private void CrossLink() { foreach (MessageDescriptor message in messageTypes) { message.CrossLink(); } foreach (ServiceDescriptor service in services) { service.CrossLink(); } foreach (FieldDescriptor extension in extensions) { extension.CrossLink(); } foreach (MessageDescriptor message in messageTypes) { message.CheckRequiredFields(); } } /// /// This method is to be called by generated code only. It is equivalent /// to BuildFrom except that the FileDescriptorProto is encoded in /// protocol buffer wire format. /// public static FileDescriptor InternalBuildGeneratedFileFrom(byte[] descriptorData, FileDescriptor[] dependencies) { FileDescriptorProto proto = FileDescriptorProto.ParseFrom(descriptorData); return BuildFrom(proto, dependencies); } } }